Merge #7: Formulare, WordPress-Import, Geburtstage, anpassbare Startseite
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m21s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m23s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m42s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m48s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 3m22s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m27s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 3m20s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 3m3s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m15s
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m21s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m23s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m42s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m48s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 3m22s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 3m27s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 3m20s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 3m3s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m15s
This commit is contained in:
commit
57a4b813ca
388 changed files with 10529 additions and 734 deletions
29
CHANGELOG.md
29
CHANGELOG.md
|
|
@ -4,6 +4,35 @@ Neueste Version oben. Jeder Abschnitt beginnt mit `## MAJOR.MINOR.PATCH` und
|
|||
enthält kurze Stichpunkte für Anwenderinnen und Anwender – keine Commit-Texte.
|
||||
Der Self-Updater zeigt diese Abschnitte bei neuen Versionen an.
|
||||
|
||||
## 0.7.0
|
||||
|
||||
- Erscheinungsbild vollständig anpassbar: Portalname, Logos für helle und dunkle Flächen, Signet für Smartphones, App-Symbol für Favicon und Homescreen
|
||||
- Markenfarbe wird exakt übernommen, optional eine zweite Akzentfarbe; Kopfleiste hell, in der Markenfarbe oder dunkel
|
||||
- Kontrastprüfung nach WCAG AA: zu helle Markenfarben bekommen automatisch gut lesbare Linkfarben
|
||||
- Schriften zur Auswahl oder als eigene Datei, auch getrennt für Überschriften – immer vom eigenen Server, nie von Google
|
||||
- Ecken, Abstände und Dunkelmodus (frei wählbar, immer hell oder immer dunkel) einstellbar
|
||||
- Anmeldeseite mit Hintergrundbild, eigenem Begrüßungstext und zwei Aufteilungen
|
||||
- Fußzeile mit Links (z. B. Impressum, Datenschutz); E-Mails im gleichen Design mit eigener Fußzeile
|
||||
- Entwurf, Live-Vorschau (Startseite, Anmeldung, Beispielseite – hell und dunkel) und Veröffentlichen; Export, Import und Zurücksetzen
|
||||
- Eigenes CSS für Fortgeschrittene
|
||||
- Der Admin-Bereich übernimmt Logo, Farbe und Favicon; „Inhaus“ erscheint nirgends mehr zwingend
|
||||
- Hochgeladene SVG-Logos werden von Skripten bereinigt
|
||||
|
||||
## 0.6.0
|
||||
|
||||
- Formulare: Anträge, Anmeldungen, Umfragen und Meldungen im visuellen Baukasten zusammenstellen – so, wie das Formular später aussieht: Bezeichnungen und Auswahlmöglichkeiten direkt bearbeiten, Felder per Ziehen und Ablegen anordnen, Vorschau mit Bedingungen
|
||||
- Felder lassen sich abhängig von anderen Antworten ein- und ausblenden und aus dem Profil vorbelegen
|
||||
- Einsendungen landen im Backend und per E-Mail bei festen Empfängern; auf Wunsch eine Kopie an die ausfüllende Person
|
||||
- Zugriff auf die Ergebnisse je Formular und Rolle – ansehen und exportieren (CSV für Excel) bzw. löschen getrennt vergebbar
|
||||
- Anonyme Formulare, „nur einmal ausfüllen“, Einsendeschluss, Sichtbarkeit und automatische Löschfrist
|
||||
- Formularfelder lassen sich fest mit Profilangaben füllen (z. B. Vorname, Personalnummer, Abteilung) – nicht änderbar, beim Absenden gilt immer der Profilwert
|
||||
- Formulare lassen sich mit dem Pagebuilder in Seiten und unter Neuigkeiten-Beiträgen einbinden
|
||||
- Ergebnisse als CSV herunterladen – alle oder nur ausgewählte Einsendungen
|
||||
- WordPress-Import: Beiträge mit Kategorien, Autorinnen und Autoren, Beitragsbildern und Bildern im Text übernehmen, auf Wunsch auch Seiten – wiederholbar, ohne Doppelungen
|
||||
- E-Mail-Versand im Admin einrichten (SMTP), mit Test-Mail
|
||||
- Startseite anpassen: Kacheln je Bereich sortieren und ausblenden, eigene Kacheln anlegen – Bild mit Link, Text oder Hinweis, mit Zeitraum und Zielgruppe
|
||||
- Geburtstage (optional, unter „Plugins“ zu aktivieren): Mitarbeitende tragen freiwillig Tag und Monat im Profil ein; Kachel und Liste der anstehenden Geburtstage, Glückwunsch auf der Startseite am eigenen Geburtstag
|
||||
|
||||
## 0.5.0
|
||||
|
||||
- Seiten: eigener Seitenbaum für Bereiche, Abteilungen und Gremien – mit Seitennavigation, Brotkrumen und optional in der Hauptnavigation
|
||||
|
|
|
|||
|
|
@ -66,3 +66,10 @@ und danach `bin/build` ausführen, damit `vendor/` nachzieht.
|
|||
`text-muted-foreground` …), nie fest verdrahtet – sonst greift das Branding nicht
|
||||
- N+1-Abfragen vermeiden: `Model::preventLazyLoading()` ist außerhalb der
|
||||
Produktion aktiv
|
||||
|
||||
## Schriften
|
||||
|
||||
Die mitgelieferten Schriften kommen aus `@fontsource`-Paketen, eingebunden nur
|
||||
mit den Zeichensätzen Latein und Latein-Erweitert. Nach dem Hinzufügen einer
|
||||
Schrift `python3 scripts/generate-fonts-css.py` ausführen und die Schrift in
|
||||
`App\Support\Theme\Fonts` eintragen.
|
||||
|
|
|
|||
|
|
@ -20,11 +20,11 @@ class CoreWidgets
|
|||
'location' => $user->location,
|
||||
'avatar_url' => $user->avatarUrl(256),
|
||||
],
|
||||
], mobileSort: 0);
|
||||
], label: 'Begrüßung mit Profil', mobileSort: 0);
|
||||
|
||||
$widgets->add('core.quick-links', 'core::QuickLinks', 'main', sort: 10, props: fn () => [
|
||||
'links' => app(QuickLinks::class)->all(),
|
||||
], mobileSort: 40);
|
||||
], label: 'Schnellzugriffe', mobileSort: 40);
|
||||
|
||||
$widgets->add('core.new-colleagues', 'core::NewColleagues', 'main', sort: 90, props: function (User $user) {
|
||||
$people = User::query()
|
||||
|
|
@ -36,12 +36,12 @@ class CoreWidgets
|
|||
->get();
|
||||
|
||||
return $people->isEmpty() ? null : ['people' => PersonResource::collection($people)->resolve()];
|
||||
}, mobileSort: 60);
|
||||
}, label: 'Neue Kolleginnen und Kollegen', mobileSort: 60);
|
||||
|
||||
$widgets->add('core.profile-incomplete', 'core::ProfileIncomplete', 'aside', sort: 50, props: fn (User $user) => $user->avatar_path && $user->job_title ? null : [], mobileSort: 70);
|
||||
$widgets->add('core.profile-incomplete', 'core::ProfileIncomplete', 'aside', sort: 50, props: fn (User $user) => $user->avatar_path && $user->job_title ? null : [], label: 'Hinweis „Profil vervollständigen“', mobileSort: 70);
|
||||
|
||||
$widgets->add('core.people-search', 'core::PeopleSearch', 'aside', sort: 60, props: fn () => [
|
||||
'count' => User::query()->active()->count(),
|
||||
], mobileSort: 80);
|
||||
], label: 'Personen finden', mobileSort: 80);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,11 @@
|
|||
|
||||
namespace App\Dashboard;
|
||||
|
||||
use App\Models\DashboardTile;
|
||||
use App\Models\User;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
|
|
@ -11,6 +14,7 @@ use Throwable;
|
|||
* Kacheln der Startseite als Registry.
|
||||
*
|
||||
* Bereiche (siehe resources/js/pages/Dashboard.vue):
|
||||
* top – volle Breite über allem (Hinweise, z. B. Geburtstagsgruß)
|
||||
* hero – groß links oben (z. B. Slider) feed – neben hero
|
||||
* main – volle Breite der linken Spalte aside – rechte Spalte
|
||||
*
|
||||
|
|
@ -19,25 +23,27 @@ use Throwable;
|
|||
*/
|
||||
class Widgets
|
||||
{
|
||||
public const AREAS = ['hero', 'feed', 'main', 'aside'];
|
||||
public const AREAS = ['top', 'hero', 'feed', 'main', 'aside'];
|
||||
|
||||
/** @var array<string, array{component: string, area: string, sort: int, mobileSort: int, props: callable}> */
|
||||
/** @var array<string, array{component: string, area: string, sort: int, mobileSort: int, props: callable, label: string}> */
|
||||
private array $widgets = [];
|
||||
|
||||
/**
|
||||
* @param string $component Vue-Komponente, z. B. „core::QuickLinks“ oder „news::Hero“
|
||||
* @param callable(User, Request): (array<string, mixed>|null) $props
|
||||
* @param int|null $mobileSort Reihenfolge in der einspaltigen Mobilansicht (Standard: nach Bereich)
|
||||
* @param string|null $label Name im Admin unter „Startseite“
|
||||
*/
|
||||
public function add(string $key, string $component, string $area, int $sort, callable $props, ?int $mobileSort = null): void
|
||||
public function add(string $key, string $component, string $area, int $sort, callable $props, ?int $mobileSort = null, ?string $label = null): void
|
||||
{
|
||||
if (! in_array($area, self::AREAS, true)) {
|
||||
throw new \InvalidArgumentException("Unbekannter Bereich „{$area}“ für Kachel {$key}.");
|
||||
}
|
||||
|
||||
$mobileSort ??= ['hero' => 10, 'feed' => 20, 'aside' => 30, 'main' => 50][$area] + $sort;
|
||||
$mobileSort ??= ['top' => -100, 'hero' => 10, 'feed' => 20, 'aside' => 30, 'main' => 50][$area] + $sort;
|
||||
|
||||
$this->widgets[$key] = compact('component', 'area', 'sort', 'mobileSort', 'props');
|
||||
$label ??= $key;
|
||||
$this->widgets[$key] = compact('component', 'area', 'sort', 'mobileSort', 'props', 'label');
|
||||
}
|
||||
|
||||
public function remove(string $key): void
|
||||
|
|
@ -45,6 +51,71 @@ class Widgets
|
|||
unset($this->widgets[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Kacheln eines Bereichs für den Admin: mitgelieferte und eigene,
|
||||
* in gespeicherter Reihenfolge, mit Sichtbarkeit.
|
||||
*
|
||||
* @return list<array{key: string, label: string, area: string, visible: bool, custom: bool}>
|
||||
*/
|
||||
public function forAdmin(string $area): array
|
||||
{
|
||||
$layout = $this->layout();
|
||||
|
||||
return $this->candidates()
|
||||
->filter(fn (array $w) => $w['area'] === $area)
|
||||
->map(fn (array $w, string $key) => [
|
||||
'key' => $key,
|
||||
'label' => $w['label'],
|
||||
'area' => $w['area'],
|
||||
'visible' => $layout[$key]['visible'] ?? true,
|
||||
'custom' => $w['custom'] ?? false,
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mitgelieferte Kacheln plus eigene Kacheln, sortiert nach gespeicherter Anordnung.
|
||||
*
|
||||
* @return Collection<string, array<string, mixed>>
|
||||
*/
|
||||
private function candidates(?User $user = null)
|
||||
{
|
||||
$widgets = collect($this->widgets);
|
||||
|
||||
try {
|
||||
$tiles = DashboardTile::query()->when($user, fn ($q) => $q->visibleTo($user))->get();
|
||||
} catch (Throwable) {
|
||||
$tiles = collect(); // Tabelle noch nicht angelegt (Aktualisierung läuft)
|
||||
}
|
||||
|
||||
foreach ($tiles as $tile) {
|
||||
$widgets[$tile->widgetKey()] = [
|
||||
'component' => 'core::CustomTile',
|
||||
'area' => array_key_exists($tile->area, DashboardTile::AREAS) ? $tile->area : 'aside',
|
||||
'sort' => 1000 + $tile->id,
|
||||
'mobileSort' => ['top' => -50, 'main' => 45, 'aside' => 32][$tile->area] ?? 32,
|
||||
'props' => fn () => $tile->toWidgetProps(),
|
||||
'label' => 'Eigene Kachel: '.$tile->name,
|
||||
'custom' => true,
|
||||
];
|
||||
}
|
||||
|
||||
$layout = $this->layout();
|
||||
|
||||
return $widgets->sortBy(fn (array $w, string $key) => $layout[$key]['sort'] ?? $w['sort']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gespeicherte Anordnung: Schlüssel => [sort, visible].
|
||||
*
|
||||
* @return array<string, array{sort?: int, visible?: bool}>
|
||||
*/
|
||||
private function layout(): array
|
||||
{
|
||||
return (array) app(Settings::class)->get('dashboard.layout', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, component: string, area: string, mobileSort: int, props: array<string, mixed>}>
|
||||
*/
|
||||
|
|
@ -52,7 +123,13 @@ class Widgets
|
|||
{
|
||||
$result = [];
|
||||
|
||||
foreach (collect($this->widgets)->sortBy('sort') as $key => $widget) {
|
||||
$layout = $this->layout();
|
||||
|
||||
foreach ($this->candidates($user) as $key => $widget) {
|
||||
if (($layout[$key]['visible'] ?? true) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$props = ($widget['props'])($user, $request);
|
||||
} catch (Throwable $e) {
|
||||
|
|
|
|||
|
|
@ -2,27 +2,46 @@
|
|||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Theme\Contrast;
|
||||
use App\Support\Theme\Fonts;
|
||||
use App\Support\Theme\Icons;
|
||||
use App\Support\Theme\Theme;
|
||||
use App\Support\Theme\ThemeCompiler;
|
||||
use App\Support\Theme\ThemeTransfer;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\HtmlString;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Basis-Branding (Phase 0). Die vollständige Seite „Erscheinungsbild“ mit
|
||||
* Logo-Varianten, Schriften, Vorschau usw. folgt in Phase 5.
|
||||
* „Erscheinungsbild“ (docs/PLAN.md, Abschnitt 12): Entwurf bearbeiten, in der
|
||||
* Vorschau ansehen, dann für alle veröffentlichen.
|
||||
*/
|
||||
class Appearance extends Page
|
||||
{
|
||||
protected string $view = 'filament.pages.settings-form';
|
||||
protected string $view = 'filament.pages.appearance';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPaintBrush;
|
||||
|
||||
|
|
@ -32,75 +51,194 @@ class Appearance extends Page
|
|||
|
||||
protected static ?string $title = 'Erscheinungsbild';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('appearance.manage') ?? false;
|
||||
}
|
||||
|
||||
protected static ?string $slug = 'erscheinungsbild';
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
public ?array $data = [];
|
||||
|
||||
public function mount(Branding $branding): void
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
$this->form->fill([
|
||||
'portal_name' => $branding->portalName(),
|
||||
'primary_color' => $branding->primaryColor(),
|
||||
'logo_path' => $branding->logoPath(),
|
||||
]);
|
||||
return auth()->user()?->can('appearance.manage') ?? false;
|
||||
}
|
||||
|
||||
public function mount(Theme $theme): void
|
||||
{
|
||||
$this->form->fill($theme->working());
|
||||
}
|
||||
|
||||
public function hasDraft(): bool
|
||||
{
|
||||
return app(Theme::class)->hasDraft();
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Portal')
|
||||
->description('Name und Logo erscheinen im Kopfbereich, auf der Anmeldeseite und im Browser-Tab.')
|
||||
->schema([
|
||||
TextInput::make('portal_name')
|
||||
->label('Name des Portals')
|
||||
->placeholder(Branding::DEFAULT_NAME)
|
||||
->maxLength(60),
|
||||
FileUpload::make('logo_path')
|
||||
->label('Logo')
|
||||
->helperText('SVG, PNG oder WebP, am besten mit transparentem Hintergrund.')
|
||||
->disk('uploads')
|
||||
->directory('branding')
|
||||
->visibility('public')
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp'])
|
||||
->maxSize(2048),
|
||||
$image = fn (string $name, string $label, string $help) => FileUpload::make($name)->label($label)->helperText($help)
|
||||
->disk('uploads')->directory('theme')->visibility('public')->maxSize(4096);
|
||||
|
||||
return $schema->statePath('data')->components([
|
||||
Tabs::make()->persistTabInQueryString()->tabs([
|
||||
Tab::make('Identität')->icon(Heroicon::OutlinedIdentification)->columns(2)->schema([
|
||||
TextInput::make('portal_name')->label('Name des Portals')->required()->maxLength(60)
|
||||
->helperText('Erscheint im Kopfbereich, im Browser-Tab, in E-Mails und auf dem Homescreen.')->columnSpanFull(),
|
||||
$image('logo_light', 'Logo für helle Flächen', 'SVG, PNG oder WebP mit transparentem Hintergrund.')
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']),
|
||||
$image('logo_dark', 'Logo für dunkle Flächen', 'Für den Dunkelmodus und farbige Kopfleisten, z. B. in Weiß. Leer = wie hell.')
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']),
|
||||
$image('logo_mark', 'Signet (quadratisch)', 'Kurzform für Smartphones, z. B. nur das Bildzeichen.')
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']),
|
||||
$image('app_icon', 'App-Symbol', 'Quadratisch, mindestens 512 × 512 Pixel (PNG oder JPG). Daraus entstehen Favicon und Homescreen-Symbole.')
|
||||
->image()->acceptedFileTypes(['image/png', 'image/jpeg', 'image/webp']),
|
||||
]),
|
||||
|
||||
Tab::make('Farben')->icon(Heroicon::OutlinedSwatch)->columns(2)->schema([
|
||||
ColorPicker::make('primary_color')->label('Markenfarbe')->required()->regex('/^#[0-9a-fA-F]{6}$/')->live(onBlur: true)
|
||||
->helperText('Wird exakt übernommen: Schaltflächen, aktive Navigation, Begrüßungskarte. Die Abstufungen werden berechnet.'),
|
||||
ColorPicker::make('secondary_color')->label('Zweite Akzentfarbe (optional)')->regex('/^#[0-9a-fA-F]{6}$/')->live(onBlur: true)
|
||||
->helperText('Für Kategorien und Datumsangaben. Leer = Markenfarbe.'),
|
||||
Radio::make('header_style')->label('Kopfleiste')->options(Theme::HEADER_STYLES)->inline()->required()->columnSpanFull(),
|
||||
Section::make('Kontrastprüfung (WCAG AA)')->columnSpanFull()->compact()->schema([
|
||||
Text::make(fn (Get $get) => $this->contrastReport((string) $get('primary_color'), $get('secondary_color'))),
|
||||
]),
|
||||
Section::make('Farben')
|
||||
->description('Aus der Primärfarbe wird die komplette Farbpalette für den hellen und den dunklen Modus berechnet.')
|
||||
->schema([
|
||||
ColorPicker::make('primary_color')
|
||||
->label('Primärfarbe')
|
||||
->regex('/^#[0-9a-fA-F]{6}$/')
|
||||
->required(),
|
||||
]),
|
||||
])
|
||||
->statePath('data');
|
||||
]),
|
||||
|
||||
Tab::make('Schrift & Form')->icon(Heroicon::OutlinedLanguage)->columns(2)->schema([
|
||||
Select::make('font_body')->label('Schrift')->options(fn (Get $get) => Fonts::options((bool) $get('custom_font')))->required()->native(false),
|
||||
Select::make('font_heading')->label('Schrift für Überschriften')->options(fn (Get $get) => ['same' => 'Wie die Schrift'] + Fonts::options((bool) $get('custom_font')))->required()->native(false),
|
||||
FileUpload::make('custom_font')->label('Eigene Schrift (WOFF2)')
|
||||
->helperText('Z. B. die Hausschrift aus dem Corporate Design. Wird lokal ausgeliefert – keine Verbindung zu Google oder anderen Diensten. Bitte die Lizenz für die Nutzung im Web beachten.')
|
||||
->disk('uploads')->directory('theme/fonts')->visibility('public')->maxSize(2048)
|
||||
->acceptedFileTypes(['font/woff2', 'application/font-woff2', 'application/octet-stream'])
|
||||
->rule('extensions:woff2')->live()->columnSpanFull(),
|
||||
Radio::make('radius')->label('Ecken')->options(collect(Theme::RADII)->map(fn ($r) => $r[0])->all())->inline()->required(),
|
||||
Radio::make('density')->label('Abstände')->options(collect(Theme::DENSITIES)->map(fn ($d) => $d[0])->all())->inline()->required(),
|
||||
Radio::make('dark_mode')->label('Dunkelmodus')->options(Theme::DARK_MODES)->required()->columnSpanFull(),
|
||||
]),
|
||||
|
||||
Tab::make('Anmeldeseite')->icon(Heroicon::OutlinedArrowRightOnRectangle)->columns(2)->schema([
|
||||
Radio::make('login_layout')->label('Aufteilung')->options(Theme::LOGIN_LAYOUTS)->required()->columnSpanFull(),
|
||||
TextInput::make('login_title')->label('Begrüßung')->maxLength(200)->columnSpanFull(),
|
||||
Textarea::make('login_text')->label('Text darunter')->rows(2)->maxLength(500)->columnSpanFull(),
|
||||
$image('login_image', 'Hintergrundbild', 'Querformat, mindestens 1600 Pixel breit. Leer = Fläche in der Markenfarbe.')
|
||||
->image()->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])->maxSize(8192)->columnSpanFull(),
|
||||
]),
|
||||
|
||||
Tab::make('Fußzeile & E-Mails')->icon(Heroicon::OutlinedEnvelope)->schema([
|
||||
TextInput::make('footer_text')->label('Text in der Fußzeile')->placeholder('© 2027 Musterstift gGmbH')->maxLength(200),
|
||||
Repeater::make('footer_links')->label('Links in der Fußzeile')->columns(2)->defaultItems(0)->reorderable()
|
||||
->addActionLabel('Link hinzufügen')->maxItems(8)
|
||||
->schema([
|
||||
TextInput::make('label')->label('Bezeichnung')->required()->maxLength(60)->placeholder('Impressum'),
|
||||
TextInput::make('url')->label('Adresse')->required()->maxLength(500)->placeholder('https://… oder /seiten/impressum'),
|
||||
]),
|
||||
Textarea::make('email_footer')->label('Fußzeile in E-Mails')->rows(3)->maxLength(500)
|
||||
->helperText('Z. B. Anschrift und Hinweis. Logo und Markenfarbe übernehmen die E-Mails automatisch.'),
|
||||
]),
|
||||
|
||||
Tab::make('Erweitert')->icon(Heroicon::OutlinedCodeBracket)->schema([
|
||||
Textarea::make('custom_css')->label('Eigenes CSS')->rows(12)->maxLength(50000)
|
||||
->extraInputAttributes(['class' => 'font-mono text-xs', 'spellcheck' => 'false'])
|
||||
->helperText('Für Fortgeschrittene. Wird nach dem Portal-CSS geladen und bei Aktualisierungen unverändert übernommen. Klassennamen können sich mit neuen Versionen ändern – bitte nach jedem Update prüfen. Verfügbare Variablen: --brand, --brand-50 … --brand-950, --radius, --font-body, --font-heading.'),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(Settings $settings, Branding $branding): void
|
||||
private function contrastReport(string $primary, ?string $secondary): HtmlString
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
$previousLogo = $branding->logoPath();
|
||||
|
||||
$settings->setMany([
|
||||
'branding.portal_name' => filled($data['portal_name']) ? trim($data['portal_name']) : null,
|
||||
'branding.primary_color' => strtoupper($data['primary_color']),
|
||||
'branding.logo_path' => $data['logo_path'] ?: null,
|
||||
]);
|
||||
|
||||
if ($previousLogo && $previousLogo !== $data['logo_path']) {
|
||||
Storage::disk('uploads')->delete($previousLogo);
|
||||
if (! preg_match('/^#[0-9a-fA-F]{6}$/', $primary)) {
|
||||
return new HtmlString('');
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->success()
|
||||
->title('Erscheinungsbild gespeichert')
|
||||
->send();
|
||||
$colors = ['ok' => '#15803d', 'info' => '#0369a1', 'warning' => '#b45309'];
|
||||
$icons = ['ok' => '✓', 'info' => 'i', 'warning' => '!'];
|
||||
|
||||
return new HtmlString(collect(Contrast::report(strtoupper($primary), $secondary && preg_match('/^#[0-9a-fA-F]{6}$/', $secondary) ? strtoupper($secondary) : null))
|
||||
->map(fn ($note) => '<p style="display:flex;gap:.5rem;margin:.25rem 0"><span style="font-weight:700;color:'.$colors[$note['level']].';width:1rem;text-align:center">'.$icons[$note['level']].'</span><span>'.e($note['text']).'</span></p>')
|
||||
->implode(''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Entwurf speichern und die Vorschau aktualisieren.
|
||||
*/
|
||||
public function save(Theme $theme, Branding $branding): void
|
||||
{
|
||||
$theme->saveDraft($this->form->getState());
|
||||
session()->put(Branding::PREVIEW_SESSION_KEY, true);
|
||||
$branding->refresh();
|
||||
|
||||
$this->dispatch('theme-preview-reload');
|
||||
Notification::make()->success()->title('Entwurf gespeichert')->body('Die Vorschau zeigt jetzt den Entwurf. Für alle sichtbar wird er erst mit „Veröffentlichen“.')->send();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('publish')->label('Veröffentlichen')->icon(Heroicon::OutlinedRocketLaunch)
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Erscheinungsbild veröffentlichen?')
|
||||
->modalDescription('Der gespeicherte Entwurf wird für alle sichtbar. Ungespeicherte Änderungen im Formular werden vorher als Entwurf gespeichert.')
|
||||
->action(function (Theme $theme, ThemeCompiler $compiler, Icons $icons, Branding $branding) {
|
||||
$theme->saveDraft($this->form->getState());
|
||||
$theme->publish($compiler, $icons);
|
||||
session()->forget(Branding::PREVIEW_SESSION_KEY);
|
||||
$branding->refresh();
|
||||
Audit::log('appearance.published');
|
||||
|
||||
$this->form->fill($theme->working());
|
||||
$this->dispatch('theme-preview-reload');
|
||||
Notification::make()->success()->title('Erscheinungsbild veröffentlicht')->send();
|
||||
}),
|
||||
Action::make('discard')->label('Entwurf verwerfen')->icon(Heroicon::OutlinedArrowUturnLeft)->color('gray')
|
||||
->visible(fn () => $this->hasDraft())
|
||||
->requiresConfirmation()
|
||||
->action(function (Theme $theme, Branding $branding) {
|
||||
$theme->discardDraft();
|
||||
session()->forget(Branding::PREVIEW_SESSION_KEY);
|
||||
$branding->refresh();
|
||||
$this->form->fill($theme->working());
|
||||
$this->dispatch('theme-preview-reload');
|
||||
}),
|
||||
ActionGroup::make([
|
||||
Action::make('export')->label('Exportieren')->icon(Heroicon::OutlinedArrowDownTray)
|
||||
->action(fn (ThemeTransfer $transfer): StreamedResponse => response()->streamDownload(
|
||||
fn () => print (json_encode($transfer->export(app(Theme::class)->working()), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)),
|
||||
'erscheinungsbild-'.now()->format('Y-m-d').'.json',
|
||||
['Content-Type' => 'application/json'],
|
||||
)),
|
||||
Action::make('import')->label('Importieren')->icon(Heroicon::OutlinedArrowUpTray)
|
||||
->modalDescription('Erscheinungsbild aus einer exportierten Datei übernehmen – als Entwurf, damit Sie es erst ansehen können.')
|
||||
->schema([
|
||||
FileUpload::make('file')->label('Datei (.json)')->disk('local')->directory('theme-import')
|
||||
->acceptedFileTypes(['application/json', 'text/plain'])->maxSize(20 * 1024)->required(),
|
||||
])
|
||||
->action(function (array $data, ThemeTransfer $transfer, Theme $theme) {
|
||||
try {
|
||||
$values = $transfer->import((string) Storage::disk('local')->get($data['file']));
|
||||
} catch (Throwable $e) {
|
||||
Notification::make()->danger()->title('Import nicht möglich')->body($e->getMessage())->send();
|
||||
|
||||
return;
|
||||
} finally {
|
||||
Storage::disk('local')->delete($data['file']);
|
||||
}
|
||||
|
||||
$theme->saveDraft($values);
|
||||
session()->put(Branding::PREVIEW_SESSION_KEY, true);
|
||||
$this->form->fill($theme->working());
|
||||
$this->dispatch('theme-preview-reload');
|
||||
Notification::make()->success()->title('Als Entwurf importiert')->send();
|
||||
}),
|
||||
Action::make('reset')->label('Auf Standard zurücksetzen')->icon(Heroicon::OutlinedArrowPath)->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Setzt Farben, Schriften, Logos und Texte auf die Standardwerte zurück – als Entwurf. Der Portalname bleibt.')
|
||||
->action(function (Theme $theme) {
|
||||
$theme->resetToDefaults();
|
||||
session()->put(Branding::PREVIEW_SESSION_KEY, true);
|
||||
$this->form->fill($theme->working());
|
||||
$this->dispatch('theme-preview-reload');
|
||||
}),
|
||||
])->label('Mehr')->icon(Heroicon::OutlinedEllipsisVertical)->button()->color('gray'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
108
app/Filament/Pages/DashboardSettings.php
Normal file
108
app/Filament/Pages/DashboardSettings.php
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Filament\Resources\DashboardTiles\DashboardTileResource;
|
||||
use App\Support\Settings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Anordnung der Startseite: Kacheln je Bereich sortieren und ausblenden –
|
||||
* mitgelieferte wie eigene.
|
||||
*/
|
||||
class DashboardSettings extends Page
|
||||
{
|
||||
protected string $view = 'filament.pages.settings-form';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHome;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Portal';
|
||||
|
||||
protected static ?int $navigationSort = 10;
|
||||
|
||||
protected static ?string $navigationLabel = 'Startseite';
|
||||
|
||||
protected static ?string $title = 'Startseite';
|
||||
|
||||
protected static ?string $slug = 'startseite';
|
||||
|
||||
private const AREAS = [
|
||||
'top' => ['Ganz oben (volle Breite)', 'Hinweise und Banner über allem.'],
|
||||
'hero' => ['Groß links oben', 'Nur die erste sichtbare Kachel wird gezeigt.'],
|
||||
'feed' => ['Neben dem großen Bereich', ''],
|
||||
'main' => ['Hauptspalte', ''],
|
||||
'aside' => ['Seitenleiste (rechts)', ''],
|
||||
];
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
public ?array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('appearance.manage') ?? false;
|
||||
}
|
||||
|
||||
public function mount(Widgets $widgets): void
|
||||
{
|
||||
$this->form->fill(collect(self::AREAS)->mapWithKeys(fn ($info, $area) => [$area => $widgets->forAdmin($area)])->all());
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->statePath('data')->components(
|
||||
collect(self::AREAS)->map(fn ($info, $area) => Section::make($info[0])
|
||||
->description($info[1] ?: null)
|
||||
->visible(fn () => app(Widgets::class)->forAdmin($area) !== [])
|
||||
->schema([
|
||||
Repeater::make($area)
|
||||
->hiddenLabel()
|
||||
->reorderable()
|
||||
->reorderableWithDragAndDrop()
|
||||
->addable(false)
|
||||
->deletable(false)
|
||||
->itemLabel(fn (array $state) => $state['label'] ?? $state['key'])
|
||||
->schema([
|
||||
Hidden::make('key'),
|
||||
Hidden::make('label'),
|
||||
Toggle::make('visible')->label('Anzeigen'),
|
||||
]),
|
||||
]))->values()->all()
|
||||
);
|
||||
}
|
||||
|
||||
public function save(Settings $settings): void
|
||||
{
|
||||
$layout = [];
|
||||
|
||||
foreach (array_keys(self::AREAS) as $area) {
|
||||
foreach (array_values($this->data[$area] ?? []) as $index => $item) {
|
||||
$layout[$item['key']] = ['sort' => $index * 10, 'visible' => (bool) ($item['visible'] ?? true)];
|
||||
}
|
||||
}
|
||||
|
||||
$settings->set('dashboard.layout', $layout);
|
||||
|
||||
Notification::make()->success()->title('Startseite gespeichert')->send();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('tiles')->label('Eigene Kacheln')->icon(Heroicon::OutlinedRectangleGroup)->color('gray')
|
||||
->url(fn () => DashboardTileResource::getUrl()),
|
||||
Action::make('preview')->label('Startseite ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
|
||||
->url('/')->openUrlInNewTab(),
|
||||
];
|
||||
}
|
||||
}
|
||||
109
app/Filament/Pages/MailSettingsPage.php
Normal file
109
app/Filament/Pages/MailSettingsPage.php
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\MailSettings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* SMTP-Zugang für Benachrichtigungen, Formulare und „Passwort vergessen“.
|
||||
*/
|
||||
class MailSettingsPage extends Page
|
||||
{
|
||||
protected string $view = 'filament.pages.settings-form';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelope;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
protected static ?string $navigationLabel = 'E-Mail-Versand';
|
||||
|
||||
protected static ?string $title = 'E-Mail-Versand';
|
||||
|
||||
protected static ?string $slug = 'e-mail';
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
public ?array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('mail.manage') ?? false;
|
||||
}
|
||||
|
||||
public function mount(MailSettings $mail): void
|
||||
{
|
||||
$this->form->fill([...$mail->values(), 'password' => null]);
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$smtp = fn (Get $get) => $get('mailer') === 'smtp';
|
||||
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Versand')
|
||||
->description('Die Zugangsdaten erhalten Sie von Ihrem Hoster oder Ihrer IT (z. B. Microsoft 365: smtp.office365.com, Port 587, TLS).')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('mailer')->label('Versandart')->options(MailSettings::MAILERS)->required()->live()->native(false)->columnSpanFull(),
|
||||
TextInput::make('host')->label('SMTP-Server')->required($smtp)->visible($smtp)->maxLength(255),
|
||||
TextInput::make('port')->label('Port')->numeric()->required($smtp)->visible($smtp)->minValue(1)->maxValue(65535),
|
||||
Select::make('encryption')->label('Verschlüsselung')->visible($smtp)->native(false)
|
||||
->options(['tls' => 'STARTTLS (meist Port 587)', 'ssl' => 'SSL/TLS (meist Port 465)', 'none' => 'Keine']),
|
||||
TextInput::make('username')->label('Benutzername')->visible($smtp)->maxLength(255)->autocomplete('off'),
|
||||
TextInput::make('password')->label('Passwort')->password()->revealable()->visible($smtp)->maxLength(255)
|
||||
->helperText('Leer lassen, um das gespeicherte Passwort zu behalten.')->autocomplete('new-password'),
|
||||
]),
|
||||
Section::make('Absender')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('from_address')->label('Absenderadresse')->email()->required()->maxLength(255)->placeholder('intranet@firma.de'),
|
||||
TextInput::make('from_name')->label('Absendername')->maxLength(100)->placeholder('Name des Portals'),
|
||||
]),
|
||||
])
|
||||
->statePath('data');
|
||||
}
|
||||
|
||||
public function save(MailSettings $mail): void
|
||||
{
|
||||
$mail->save($this->form->getState());
|
||||
Audit::log('mail.settings_updated');
|
||||
|
||||
Notification::make()->success()->title('E-Mail-Versand gespeichert')->send();
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('test')
|
||||
->label('Test-Mail senden')
|
||||
->icon(Heroicon::OutlinedPaperAirplane)
|
||||
->color('gray')
|
||||
->action(function () {
|
||||
$to = auth()->user()->email;
|
||||
|
||||
try {
|
||||
Mail::raw('Diese Test-Mail bestätigt, dass der E-Mail-Versand des Portals funktioniert.', fn ($m) => $m->to($to)->subject('Test-Mail aus dem Portal'));
|
||||
Notification::make()->success()->title('Test-Mail an '.$to.' gesendet')->send();
|
||||
} catch (Throwable $e) {
|
||||
Notification::make()->danger()->title('Versand fehlgeschlagen')->body($e->getMessage())->persistent()->send();
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
104
app/Filament/Resources/DashboardTiles/DashboardTileResource.php
Normal file
104
app/Filament/Resources/DashboardTiles/DashboardTileResource.php
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DashboardTiles;
|
||||
|
||||
use App\Filament\Components\AudienceSection;
|
||||
use App\Filament\Resources\DashboardTiles\Pages\ManageDashboardTiles;
|
||||
use App\Models\DashboardTile;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\ImageColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Eigene Kacheln der Startseite. Reihenfolge und Ein-/Ausblenden unter „Startseite“.
|
||||
*/
|
||||
class DashboardTileResource extends Resource
|
||||
{
|
||||
protected static ?string $model = DashboardTile::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedRectangleGroup;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Portal';
|
||||
|
||||
protected static ?int $navigationSort = 11;
|
||||
|
||||
protected static ?string $modelLabel = 'Eigene Kachel';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Eigene Kacheln';
|
||||
|
||||
protected static ?string $slug = 'kacheln';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('appearance.manage') ?? false;
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
$type = fn (string ...$types) => fn (Get $get) => in_array($get('type'), $types, true);
|
||||
|
||||
return $schema->columns(2)->components([
|
||||
TextInput::make('name')->label('Name (nur im Admin)')->required()->maxLength(100),
|
||||
Select::make('type')->label('Art')->options(DashboardTile::TYPES)->default('image')->required()->live()->native(false),
|
||||
Select::make('area')->label('Bereich')->options(DashboardTile::AREAS)->default('aside')->required()->native(false)
|
||||
->helperText('Die Reihenfolge innerhalb des Bereichs legen Sie unter „Startseite“ fest.'),
|
||||
TextInput::make('title')->label(fn (Get $get) => $get('type') === 'image' ? 'Bildunterschrift (optional)' : 'Überschrift')->maxLength(150),
|
||||
|
||||
FileUpload::make('image_path')->label('Bild')->image()->disk('uploads')->directory('dashboard')->visibility('public')
|
||||
->maxSize(8 * 1024)->required($type('image'))->visible($type('image'))->columnSpanFull()
|
||||
->helperText('Für die Seitenleiste z. B. 800 × 600 Pixel, für „ganz oben“ ein breites Banner (z. B. 2400 × 500).'),
|
||||
TextInput::make('alt')->label('Alternativtext')->maxLength(200)->visible($type('image'))->helperText('Beschreibt das Bild für Screenreader.'),
|
||||
|
||||
RichEditor::make('body')->label('Text')->toolbarButtons([['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']])
|
||||
->required($type('text', 'notice'))->visible($type('text', 'notice'))->columnSpanFull(),
|
||||
Select::make('variant')->label('Farbe')->options(DashboardTile::VARIANTS)->default('brand')->visible($type('notice'))->native(false),
|
||||
|
||||
TextInput::make('url')->label('Link')->placeholder('https://… oder /seiten/…')->maxLength(2000),
|
||||
Toggle::make('new_tab')->label('In neuem Tab öffnen')->inline(false),
|
||||
|
||||
Section::make('Anzeige')->columnSpanFull()->columns(3)->schema([
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
|
||||
DateTimePicker::make('starts_at')->label('Ab')->native(false)->seconds(false)->displayFormat('d.m.Y H:i'),
|
||||
DateTimePicker::make('ends_at')->label('Bis')->native(false)->seconds(false)->displayFormat('d.m.Y H:i')->after('starts_at'),
|
||||
]),
|
||||
AudienceSection::make('dashboard_tile', 'Wer die Kachel sieht. Leer lassen = alle.')->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
ImageColumn::make('image_path')->label('')->disk('uploads')->width(64)->height(40),
|
||||
TextColumn::make('name')->label('Name')->weight('medium')->searchable(),
|
||||
TextColumn::make('type')->label('Art')->formatStateUsing(fn (string $state) => DashboardTile::TYPES[$state] ?? $state),
|
||||
TextColumn::make('area')->label('Bereich')->formatStateUsing(fn (string $state) => DashboardTile::AREAS[$state] ?? $state),
|
||||
IconColumn::make('is_active')->label('Aktiv')->boolean(),
|
||||
TextColumn::make('ends_at')->label('Bis')->dateTime('d.m.Y H:i')->placeholder('–'),
|
||||
])
|
||||
->recordActions([EditAction::make(), DeleteAction::make()])
|
||||
->emptyStateHeading('Noch keine eigenen Kacheln')
|
||||
->emptyStateDescription('Zum Beispiel ein verlinktes Bild in der Seitenleiste oder ein Hinweis ganz oben.');
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return ['index' => ManageDashboardTiles::route('/')];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DashboardTiles\Pages;
|
||||
|
||||
use App\Filament\Pages\DashboardSettings;
|
||||
use App\Filament\Resources\DashboardTiles\DashboardTileResource;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
class ManageDashboardTiles extends ManageRecords
|
||||
{
|
||||
protected static string $resource = DashboardTileResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('layout')->label('Anordnung der Startseite')->icon(Heroicon::OutlinedSquares2x2)->color('gray')
|
||||
->url(fn () => DashboardSettings::getUrl()),
|
||||
CreateAction::make()->label('Kachel anlegen'),
|
||||
];
|
||||
}
|
||||
}
|
||||
86
app/Http/Controllers/AppearanceController.php
Normal file
86
app/Http/Controllers/AppearanceController.php
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\IdentityProvider;
|
||||
use App\Pagebuilder\Content;
|
||||
use App\Support\Branding;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
/**
|
||||
* Web-App-Manifest und die Vorschauseiten für „Erscheinungsbild“.
|
||||
*/
|
||||
class AppearanceController extends Controller
|
||||
{
|
||||
public function manifest(Branding $branding): JsonResponse
|
||||
{
|
||||
$icons = collect($branding->get('icons') ?? [])
|
||||
->reject(fn ($path, $size) => (int) $size < 192)
|
||||
->map(fn ($path, $size) => ['src' => $branding->url($path), 'sizes' => "{$size}x{$size}", 'type' => 'image/png', 'purpose' => 'any'])
|
||||
->values();
|
||||
|
||||
if ($icons->isEmpty()) {
|
||||
$icons = collect([['src' => $branding->faviconUrl(), 'sizes' => 'any', 'type' => 'image/svg+xml']]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'name' => $branding->portalName(),
|
||||
'short_name' => mb_substr($branding->portalName(), 0, 12),
|
||||
'start_url' => '/',
|
||||
'scope' => '/',
|
||||
'display' => 'standalone',
|
||||
'lang' => 'de',
|
||||
'theme_color' => $branding->primaryColor(),
|
||||
'background_color' => '#F4F5F7',
|
||||
'icons' => $icons->all(),
|
||||
], 200, ['Content-Type' => 'application/manifest+json', 'Cache-Control' => 'public, max-age=3600']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anmeldeseite im aktuellen Entwurf – für die Vorschau (Formular ohne Funktion).
|
||||
*/
|
||||
public function loginPreview(Request $request): Response
|
||||
{
|
||||
return Inertia::render('Auth/Login', [
|
||||
'canResetPassword' => true,
|
||||
'providers' => IdentityProvider::query()->where('enabled', true)->get()
|
||||
->map(fn (IdentityProvider $p) => ['slug' => $p->slug, 'type' => $p->type, 'label' => $p->buttonLabel()])->values(),
|
||||
'preview' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Beispielseite mit Boxen, Tabs, Akkordeon, Tabelle und Schaltflächen.
|
||||
*/
|
||||
public function sample(Request $request, Content $content): Response
|
||||
{
|
||||
$text = fn (string $html) => ['type' => 'text', 'data' => ['html' => $html]];
|
||||
$box = fn (string $variant, string $title, string $html) => ['type' => 'box', 'data' => ['variant' => $variant, 'title' => $title, 'show_icon' => true], 'items' => [['blocks' => [$text($html)]]]];
|
||||
|
||||
$blocks = [
|
||||
['type' => 'heading', 'data' => ['text' => 'Überschrift der Seite', 'level' => '2']],
|
||||
$text('<p>Fließtext mit einem <a href="#">Link in der Akzentfarbe</a>, <strong>Hervorhebungen</strong> und einer Liste:</p><ul><li>erster Punkt</li><li>zweiter Punkt</li></ul>'),
|
||||
['type' => 'columns', 'data' => ['layout' => '1-1'], 'items' => [
|
||||
['blocks' => [$box('info', 'Info', '<p>Sprechstunde dienstags 14–16 Uhr.</p>'), $box('warning', 'Warnung', '<p>Bitte bis Freitag einreichen.</p>')]],
|
||||
['blocks' => [$box('success', 'Erfolg', '<p>Das neue Verfahren gilt ab sofort.</p>'), $box('highlight', 'Hervorgehoben', '<p>In der Markenfarbe.</p>')]],
|
||||
]],
|
||||
['type' => 'tabs', 'items' => [
|
||||
['title' => 'Erster Tab', 'blocks' => [$text('<p>Inhalt des ersten Tabs.</p>')]],
|
||||
['title' => 'Zweiter Tab', 'blocks' => [$text('<p>Inhalt des zweiten Tabs.</p>')]],
|
||||
]],
|
||||
['type' => 'accordion', 'data' => ['first_open' => true], 'items' => [
|
||||
['title' => 'Häufige Frage', 'blocks' => [$text('<p>Die Antwort steht hier.</p>')]],
|
||||
['title' => 'Noch eine Frage', 'blocks' => [$text('<p>Noch eine Antwort.</p>')]],
|
||||
]],
|
||||
['type' => 'table', 'data' => ['header' => true, 'rows' => [['Bereich', 'Ansprechpartner', 'Durchwahl'], ['Personal', 'A. Beispiel', '123'], ['IT', 'B. Muster', '456']]]],
|
||||
['type' => 'buttons', 'data' => ['buttons' => [['label' => 'Primäre Schaltfläche', 'url' => '#', 'variant' => 'primary'], ['label' => 'Umrandet', 'url' => '#', 'variant' => 'outline']]]],
|
||||
];
|
||||
|
||||
return Inertia::render('Appearance/Sample', [
|
||||
'content' => $content->render($content->sanitize(['blocks' => $blocks]), $request->user()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
|||
|
||||
use App\Http\Requests\UpdateProfileRequest;
|
||||
use App\Models\User;
|
||||
use App\Profile\ProfileSections;
|
||||
use App\Support\Avatars;
|
||||
use App\Support\ProfileFields;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
|
@ -39,6 +40,7 @@ class ProfileController extends Controller
|
|||
// Felder, die Microsoft Entra ID pflegt – im Portal nur lesbar.
|
||||
'managed' => $managed,
|
||||
'customFields' => $profileFields->formFor($user, $managed),
|
||||
'sections' => app(ProfileSections::class)->resolve($user),
|
||||
]);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ class HandleInertiaRequests extends Middleware
|
|||
'notifications' => fn () => $user ? ['unread' => $user->unreadNotifications()->count()] : null,
|
||||
'flash' => [
|
||||
'status' => fn () => $request->session()->get('status'),
|
||||
'form_submitted' => fn () => $request->session()->get('form_submitted'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
|
|
|||
32
app/Http/Middleware/ThemePreview.php
Normal file
32
app/Http/Middleware/ThemePreview.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\Branding;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Vorschau des Entwurfs im Portal: ?vorschau=entwurf schaltet sie für die
|
||||
* Sitzung ein, ?vorschau=aus wieder aus. Nur mit „Erscheinungsbild“-Recht.
|
||||
*/
|
||||
class ThemePreview
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$value = $request->query('vorschau');
|
||||
|
||||
if ($value !== null && $request->hasSession()) {
|
||||
if ($value === 'entwurf' && $request->user()?->can('appearance.manage')) {
|
||||
$request->session()->put(Branding::PREVIEW_SESSION_KEY, true);
|
||||
} elseif ($value === 'aus') {
|
||||
$request->session()->forget(Branding::PREVIEW_SESSION_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
app(Branding::class)->refresh();
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
94
app/Models/DashboardTile.php
Normal file
94
app/Models/DashboardTile.php
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Support\Permissions\Audiences;
|
||||
use App\Support\RichText;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Eigene Kachel auf der Startseite („Administration → Portal → Startseite“).
|
||||
*/
|
||||
#[Fillable(['name', 'type', 'area', 'title', 'image_path', 'url', 'new_tab', 'alt', 'body', 'variant', 'is_active', 'starts_at', 'ends_at'])]
|
||||
class DashboardTile extends Model
|
||||
{
|
||||
public const TYPES = [
|
||||
'image' => 'Bild mit Link',
|
||||
'text' => 'Text',
|
||||
'notice' => 'Hinweis',
|
||||
];
|
||||
|
||||
public const AREAS = [
|
||||
'aside' => 'Seitenleiste (rechts)',
|
||||
'main' => 'Hauptspalte (breit)',
|
||||
'top' => 'Ganz oben (volle Breite)',
|
||||
];
|
||||
|
||||
public const VARIANTS = [
|
||||
'brand' => 'Markenfarbe',
|
||||
'info' => 'Info (blau)',
|
||||
'success' => 'Erfolg (grün)',
|
||||
'warning' => 'Warnung (rot)',
|
||||
'neutral' => 'Neutral (grau)',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (DashboardTile $tile) {
|
||||
$tile->url = filled($tile->url) ? (Field::safeUrl($tile->url) ?: null) : null;
|
||||
|
||||
if ($tile->isDirty('body')) {
|
||||
$tile->body_html = app(RichText::class)->toSafeHtml($tile->body);
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (DashboardTile $tile) => $tile->image_path && Storage::disk('uploads')->delete($tile->image_path));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['new_tab' => 'boolean', 'is_active' => 'boolean', 'starts_at' => 'datetime', 'ends_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function widgetKey(): string
|
||||
{
|
||||
return 'tile.'.$this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aktiv, im Zeitraum und für die Person sichtbar.
|
||||
*
|
||||
* @param Builder<DashboardTile> $query
|
||||
*/
|
||||
public function scopeVisibleTo(Builder $query, User $user): void
|
||||
{
|
||||
$query->where('is_active', true)
|
||||
->where(fn ($q) => $q->whereNull('starts_at')->orWhere('starts_at', '<=', now()))
|
||||
->where(fn ($q) => $q->whereNull('ends_at')->orWhere('ends_at', '>', now()));
|
||||
|
||||
Audiences::constrain($query, 'dashboard_tile', 'dashboard_tiles.id', $user);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toWidgetProps(): array
|
||||
{
|
||||
return [
|
||||
'tile' => [
|
||||
'type' => $this->type,
|
||||
'title' => $this->title,
|
||||
'image_url' => $this->image_path ? Storage::disk('uploads')->url($this->image_path) : null,
|
||||
'url' => $this->url,
|
||||
'new_tab' => $this->new_tab,
|
||||
'alt' => $this->alt ?: '',
|
||||
'html' => $this->body_html,
|
||||
'variant' => $this->variant ?: 'brand',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -39,6 +39,7 @@ final class PluginManifest
|
|||
public readonly bool $core,
|
||||
public readonly array $requires,
|
||||
public readonly ?string $updateUrl,
|
||||
public readonly bool $enabledByDefault = true,
|
||||
) {}
|
||||
|
||||
public static function fromDirectory(string $path, bool $core): self
|
||||
|
|
@ -90,6 +91,7 @@ final class PluginManifest
|
|||
core: $core,
|
||||
requires: is_array($data['requires'] ?? null) ? $data['requires'] : [],
|
||||
updateUrl: is_string($data['update_url'] ?? null) ? $data['update_url'] : null,
|
||||
enabledByDefault: (bool) ($data['enabled_by_default'] ?? true),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,10 +7,17 @@ use App\Support\Update\AtomicFile;
|
|||
/**
|
||||
* Aktivierungszustand der Plugins in storage/app/plugins.json – als Datei, damit
|
||||
* das Laden der Plugins keine Datenbankabfrage kostet und auch ohne DB klappt.
|
||||
* Mitgelieferte Plugins sind aktiv, solange nichts anderes vermerkt ist.
|
||||
* Mitgelieferte Plugins sind aktiv, solange nichts anderes vermerkt ist – außer sie
|
||||
* sind als optional markiert („enabled_by_default“: false in plugin.json).
|
||||
*/
|
||||
class PluginState
|
||||
{
|
||||
/**
|
||||
* Test-Suite: optionale mitgelieferte Plugins ebenfalls laden, damit ihre
|
||||
* Tabellen und Tests dabei sind (gesetzt in tests/TestCase.php).
|
||||
*/
|
||||
public static bool $enableOptionalCorePlugins = false;
|
||||
|
||||
/** @var array<string, array<string, mixed>>|null */
|
||||
private ?array $data = null;
|
||||
|
||||
|
|
@ -20,7 +27,7 @@ class PluginState
|
|||
{
|
||||
$entry = $this->all()[$manifest->slug] ?? null;
|
||||
|
||||
return is_array($entry) ? (bool) ($entry['enabled'] ?? false) : $manifest->core;
|
||||
return is_array($entry) ? (bool) ($entry['enabled'] ?? false) : $manifest->core && ($manifest->enabledByDefault || self::$enableOptionalCorePlugins);
|
||||
}
|
||||
|
||||
public function setEnabled(string $slug, bool $enabled, ?string $reason = null): void
|
||||
|
|
|
|||
52
app/Profile/ProfileSections.php
Normal file
52
app/Profile/ProfileSections.php
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<?php
|
||||
|
||||
namespace App\Profile;
|
||||
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Zusätzliche Abschnitte in „Profil bearbeiten“, beigesteuert von Plugins
|
||||
* (z. B. „Geburtstag“). Die Vue-Komponente liegt unter
|
||||
* plugins-core/<plugin>/resources/js/profile/<Name>.vue („<plugin>::Name“)
|
||||
* und speichert über eigene Routen des Plugins.
|
||||
*/
|
||||
class ProfileSections
|
||||
{
|
||||
/** @var array<string, array{component: string, sort: int, props: Closure}> */
|
||||
private array $sections = [];
|
||||
|
||||
/**
|
||||
* @param Closure(User): (array<string, mixed>|null) $props null = Abschnitt nicht zeigen
|
||||
*/
|
||||
public function add(string $key, string $component, int $sort, Closure $props): void
|
||||
{
|
||||
$this->sections[$key] = compact('component', 'sort', 'props');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, component: string, props: array<string, mixed>}>
|
||||
*/
|
||||
public function resolve(User $user): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (collect($this->sections)->sortBy('sort') as $key => $section) {
|
||||
try {
|
||||
$props = ($section['props'])($user);
|
||||
} catch (Throwable $e) {
|
||||
Log::error("Profilabschnitt {$key} fehlgeschlagen: ".$e->getMessage());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($props !== null) {
|
||||
$result[] = ['key' => $key, 'component' => $section['component'], 'props' => $props];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
|
@ -13,12 +13,15 @@ use App\Support\BackgroundTasks;
|
|||
use App\Support\Branding;
|
||||
use App\Support\Installation;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\MailSettings;
|
||||
use App\Support\Navigation;
|
||||
use App\Support\Permissions\PermissionResource;
|
||||
use App\Support\Permissions\Permissions;
|
||||
use App\Support\ProfileFields;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Theme\Theme;
|
||||
use App\Support\Theme\ThemeCompiler;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
use App\Support\Update\MaintenanceFlag;
|
||||
use App\Support\Update\UpdateProgress;
|
||||
|
|
@ -42,7 +45,10 @@ class AppServiceProvider extends ServiceProvider
|
|||
}
|
||||
|
||||
$this->app->singleton(Settings::class);
|
||||
$this->app->singleton(MailSettings::class);
|
||||
$this->app->singleton(Branding::class);
|
||||
$this->app->singleton(Theme::class);
|
||||
$this->app->singleton(ThemeCompiler::class);
|
||||
$this->app->singleton(Avatars::class);
|
||||
$this->app->singleton(QuickLinks::class);
|
||||
$this->app->singleton(LicenseStore::class);
|
||||
|
|
@ -60,7 +66,7 @@ class AppServiceProvider extends ServiceProvider
|
|||
{
|
||||
CoreWidgets::register($this->app->make(Widgets::class));
|
||||
|
||||
$this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*'], sort: 85,
|
||||
$this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder'], sort: 85,
|
||||
visible: fn (User $user) => $this->app->make(Editorial::class)->visibleFor($user));
|
||||
|
||||
// N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance).
|
||||
|
|
@ -84,5 +90,16 @@ class AppServiceProvider extends ServiceProvider
|
|||
});
|
||||
|
||||
Password::defaults(fn () => Password::min(10)->letters()->numbers());
|
||||
|
||||
if (Installation::isInstalled()) {
|
||||
$this->app->make(MailSettings::class)->apply();
|
||||
|
||||
// Whitelabel: Laravel nutzt app.name z. B. in Benachrichtigungs-Mails („Viele Grüße …“).
|
||||
try {
|
||||
config(['app.name' => $this->app->make(Branding::class)->portalName()]);
|
||||
} catch (\Throwable) {
|
||||
// Datenbank noch nicht bereit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ namespace App\Providers\Filament;
|
|||
|
||||
use App\Filament\AvatarProviders\InitialsAvatarProvider;
|
||||
use App\Filament\Pages\Feedback;
|
||||
use App\Filament\Resources\DashboardTiles\DashboardTileResource;
|
||||
use App\Filament\Resources\IdentityProviders\IdentityProviderResource;
|
||||
use App\Filament\Resources\ProfileFields\ProfileFieldResource;
|
||||
use App\Filament\Resources\Roles\RoleResource;
|
||||
|
|
@ -41,6 +42,9 @@ class AdminPanelProvider extends PanelProvider
|
|||
->defaultAvatarProvider(InitialsAvatarProvider::class)
|
||||
->brandName(fn () => app(Branding::class)->portalName())
|
||||
->brandLogo(fn () => app(Branding::class)->logoUrl())
|
||||
->darkModeBrandLogo(fn () => app(Branding::class)->logoDarkUrl())
|
||||
->brandLogoHeight('2rem')
|
||||
->favicon(fn () => app(Branding::class)->faviconUrl())
|
||||
->colors(fn () => [
|
||||
'primary' => app(Branding::class)->palette(),
|
||||
])
|
||||
|
|
@ -65,6 +69,7 @@ class AdminPanelProvider extends PanelProvider
|
|||
UserResource::class,
|
||||
RoleResource::class,
|
||||
ProfileFieldResource::class,
|
||||
DashboardTileResource::class,
|
||||
IdentityProviderResource::class,
|
||||
])
|
||||
->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages')
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use App\Dashboard\Widgets;
|
|||
use App\Plugins\Hooks;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Plugins\PluginState;
|
||||
use App\Profile\ProfileSections;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
|
@ -24,6 +25,7 @@ class PluginServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Navigation::class);
|
||||
$this->app->singleton(Widgets::class);
|
||||
$this->app->singleton(Abilities::class);
|
||||
$this->app->singleton(ProfileSections::class);
|
||||
|
||||
$this->app->make(PluginManager::class)->registerAll();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ class Abilities
|
|||
$this->define('plugins.manage', 'Plugins verwalten und installieren', 'System');
|
||||
$this->define('appearance.manage', 'Erscheinungsbild und Schnellzugriffe', 'System');
|
||||
$this->define('updates.manage', 'Aktualisierungen, Lizenz und Systemzustand', 'System');
|
||||
$this->define('mail.manage', 'E-Mail-Versand einrichten', 'System');
|
||||
$this->define('feedback.send', 'Rückmeldungen an den Hersteller senden', 'System');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,11 +2,15 @@
|
|||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Support\Theme\Icons;
|
||||
use App\Support\Theme\Theme;
|
||||
use App\Support\Theme\ThemeCompiler;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Basis-Branding der Installation (Phase 0): Portalname, Logo, Primärfarbe.
|
||||
* Das vollständige Erscheinungsbild folgt in Phase 5 (docs/PLAN.md, Abschnitt 12).
|
||||
* Das aktive Erscheinungsbild (docs/PLAN.md, Abschnitt 12): der veröffentlichte
|
||||
* Stand – oder der Entwurf, wenn eine berechtigte Person gerade die Vorschau nutzt.
|
||||
*/
|
||||
class Branding
|
||||
{
|
||||
|
|
@ -14,31 +18,84 @@ class Branding
|
|||
|
||||
public const DEFAULT_PRIMARY_COLOR = '#0F4C5C';
|
||||
|
||||
public function __construct(private readonly Settings $settings) {}
|
||||
public const PREVIEW_SESSION_KEY = 'theme_preview';
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
private ?array $active = null;
|
||||
|
||||
private ?bool $previewing = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly Settings $settings,
|
||||
private readonly Theme $theme,
|
||||
private readonly ThemeCompiler $compiler,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function active(): array
|
||||
{
|
||||
return $this->active ??= $this->isPreviewing() ? ($this->theme->draft() ?? $this->theme->published()) : $this->theme->published();
|
||||
}
|
||||
|
||||
public function isPreviewing(): bool
|
||||
{
|
||||
if ($this->previewing !== null) {
|
||||
return $this->previewing;
|
||||
}
|
||||
|
||||
try {
|
||||
$request = request();
|
||||
|
||||
return $this->previewing = $request->hasSession()
|
||||
&& $request->session()->get(self::PREVIEW_SESSION_KEY) === true
|
||||
&& (bool) $request->user()?->can('appearance.manage')
|
||||
&& $this->theme->hasDraft();
|
||||
} catch (Throwable) {
|
||||
return $this->previewing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Nach dem Speichern eines Entwurfs oder Veröffentlichen neu lesen. */
|
||||
public function refresh(): void
|
||||
{
|
||||
$this->active = null;
|
||||
$this->previewing = null;
|
||||
}
|
||||
|
||||
public function get(string $key): mixed
|
||||
{
|
||||
return $this->active()[$key] ?? null;
|
||||
}
|
||||
|
||||
public function portalName(): string
|
||||
{
|
||||
return $this->settings->get('branding.portal_name') ?: self::DEFAULT_NAME;
|
||||
return $this->get('portal_name') ?: self::DEFAULT_NAME;
|
||||
}
|
||||
|
||||
public function primaryColor(): string
|
||||
{
|
||||
$color = $this->settings->get('branding.primary_color');
|
||||
|
||||
return is_string($color) && preg_match('/^#[0-9a-fA-F]{6}$/', $color)
|
||||
? strtoupper($color)
|
||||
: self::DEFAULT_PRIMARY_COLOR;
|
||||
return $this->get('primary_color') ?: self::DEFAULT_PRIMARY_COLOR;
|
||||
}
|
||||
|
||||
public function logoPath(): ?string
|
||||
{
|
||||
return $this->settings->get('branding.logo_path') ?: null;
|
||||
return $this->get('logo_light');
|
||||
}
|
||||
|
||||
public function logoUrl(): ?string
|
||||
{
|
||||
$path = $this->logoPath();
|
||||
return $this->url($this->get('logo_light'));
|
||||
}
|
||||
|
||||
public function logoDarkUrl(): ?string
|
||||
{
|
||||
return $this->url($this->get('logo_dark')) ?? $this->logoUrl();
|
||||
}
|
||||
|
||||
public function url(?string $path): ?string
|
||||
{
|
||||
return $path ? Storage::disk('uploads')->url($path) : null;
|
||||
}
|
||||
|
||||
|
|
@ -51,33 +108,80 @@ class Branding
|
|||
}
|
||||
|
||||
/**
|
||||
* CSS-Variablen für das Portal. Werden serverseitig in die Seite geschrieben –
|
||||
* ohne Build und ohne Farbberechnung im Browser.
|
||||
* Stylesheet des veröffentlichten Stands; null = inline ausgeben (Vorschau, noch nie veröffentlicht).
|
||||
*/
|
||||
public function cssVariables(): string
|
||||
public function stylesheetUrl(): ?string
|
||||
{
|
||||
$color = $this->primaryColor();
|
||||
$variables = [
|
||||
'--brand' => $color,
|
||||
'--brand-foreground' => ColorPalette::foregroundFor($color),
|
||||
];
|
||||
$path = $this->isPreviewing() ? null : $this->get('stylesheet');
|
||||
|
||||
foreach ($this->palette() as $shade => $hex) {
|
||||
$variables["--brand-{$shade}"] = $hex;
|
||||
}
|
||||
return $path && Storage::disk('uploads')->exists($path) ? $this->url($path) : null;
|
||||
}
|
||||
|
||||
return collect($variables)->map(fn (string $value, string $name) => "{$name}:{$value}")->implode(';');
|
||||
public function inlineCss(): string
|
||||
{
|
||||
return $this->compiler->css($this->active());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{portal_name: string, primary_color: string, logo_url: string|null}
|
||||
* @deprecated Nur noch für Übergänge – das Theme liefert alle Variablen.
|
||||
*/
|
||||
public function cssVariables(): string
|
||||
{
|
||||
return '--brand:'.$this->primaryColor();
|
||||
}
|
||||
|
||||
public function faviconUrl(): string
|
||||
{
|
||||
$icons = $this->get('icons') ?? [];
|
||||
|
||||
return isset($icons[32]) ? $this->url($icons[32]) : Icons::monogram($this->portalName(), $this->primaryColor(), ColorPalette::foregroundFor($this->primaryColor()));
|
||||
}
|
||||
|
||||
public function appleTouchIconUrl(): ?string
|
||||
{
|
||||
return isset(($this->get('icons') ?? [])[180]) ? $this->url($this->get('icons')[180]) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Welche Darstellung gilt für eine Person? null = selbst gewählt/Systemeinstellung.
|
||||
*/
|
||||
public function forcedColorMode(): ?string
|
||||
{
|
||||
return match ($this->get('dark_mode')) {
|
||||
'light' => 'light',
|
||||
'dark' => 'dark',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Für das Portal (Inertia).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
$theme = $this->active();
|
||||
|
||||
return [
|
||||
'portal_name' => $this->portalName(),
|
||||
'primary_color' => $this->primaryColor(),
|
||||
'logo_url' => $this->logoUrl(),
|
||||
'logo_dark_url' => $this->logoDarkUrl(),
|
||||
'logo_mark_url' => $this->url($theme['logo_mark']),
|
||||
'header_style' => $theme['header_style'],
|
||||
'color_mode' => $this->forcedColorMode(),
|
||||
'login' => [
|
||||
'layout' => $theme['login_layout'],
|
||||
'title' => $theme['login_title'],
|
||||
'text' => $theme['login_text'],
|
||||
'image_url' => $this->url($theme['login_image']),
|
||||
],
|
||||
'footer' => [
|
||||
'text' => $theme['footer_text'],
|
||||
'links' => $theme['footer_links'],
|
||||
],
|
||||
'preview' => $this->isPreviewing(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
100
app/Support/MailSettings.php
Normal file
100
app/Support/MailSettings.php
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* E-Mail-Versand aus den Einstellungen („Administration → E-Mail-Versand“).
|
||||
* Auf Shared Hosting gibt es meist nur SMTP-Zugangsdaten des Hosters – ohne
|
||||
* Zugriff auf die .env. Die Werte hier haben Vorrang vor der .env.
|
||||
*/
|
||||
class MailSettings
|
||||
{
|
||||
public const MAILERS = [
|
||||
'smtp' => 'SMTP-Server',
|
||||
'sendmail' => 'Sendmail des Servers',
|
||||
'log' => 'Nicht senden (nur ins Protokoll schreiben)',
|
||||
];
|
||||
|
||||
public function __construct(private readonly Settings $settings) {}
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return $this->settings->get('mail.mailer') !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function values(): array
|
||||
{
|
||||
return [
|
||||
'mailer' => $this->settings->get('mail.mailer', 'log'),
|
||||
'host' => $this->settings->get('mail.host'),
|
||||
'port' => $this->settings->get('mail.port', 587),
|
||||
'encryption' => $this->settings->get('mail.encryption', 'tls'),
|
||||
'username' => $this->settings->get('mail.username'),
|
||||
'from_address' => $this->settings->get('mail.from_address'),
|
||||
'from_name' => $this->settings->get('mail.from_name'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
*/
|
||||
public function save(array $values): void
|
||||
{
|
||||
$data = [
|
||||
'mail.mailer' => $values['mailer'],
|
||||
'mail.host' => $values['host'] ?? null,
|
||||
'mail.port' => isset($values['port']) ? (int) $values['port'] : null,
|
||||
'mail.encryption' => $values['encryption'] ?? 'tls',
|
||||
'mail.username' => $values['username'] ?? null,
|
||||
'mail.from_address' => $values['from_address'] ?? null,
|
||||
'mail.from_name' => $values['from_name'] ?? null,
|
||||
];
|
||||
|
||||
// Leeres Passwortfeld = gespeichertes behalten.
|
||||
if (filled($values['password'] ?? null)) {
|
||||
$data['mail.password'] = Crypt::encryptString($values['password']);
|
||||
}
|
||||
|
||||
$this->settings->setMany($data);
|
||||
$this->apply();
|
||||
}
|
||||
|
||||
public function apply(): void
|
||||
{
|
||||
if (! $this->configured()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$values = $this->values();
|
||||
|
||||
try {
|
||||
$password = $this->settings->get('mail.password') ? Crypt::decryptString($this->settings->get('mail.password')) : null;
|
||||
} catch (Throwable) {
|
||||
$password = null; // APP_KEY geändert – Passwort muss neu eingegeben werden
|
||||
}
|
||||
|
||||
config([
|
||||
'mail.default' => $values['mailer'],
|
||||
'mail.mailers.smtp.host' => $values['host'],
|
||||
'mail.mailers.smtp.port' => (int) $values['port'],
|
||||
'mail.mailers.smtp.scheme' => $values['encryption'] === 'ssl' ? 'smtps' : 'smtp',
|
||||
'mail.mailers.smtp.username' => $values['username'],
|
||||
'mail.mailers.smtp.password' => $password,
|
||||
'mail.mailers.smtp.timeout' => 15,
|
||||
'mail.from.address' => $values['from_address'] ?: config('mail.from.address'),
|
||||
'mail.from.name' => $values['from_name'] ?: app(Branding::class)->portalName(),
|
||||
]);
|
||||
|
||||
// Bereits erzeugte Mailer mit alter Konfiguration verwerfen.
|
||||
app()->forgetInstance('mail.manager');
|
||||
app()->forgetInstance('mailer');
|
||||
Mail::clearResolvedInstance('mail.manager');
|
||||
}
|
||||
}
|
||||
91
app/Support/Theme/Contrast.php
Normal file
91
app/Support/Theme/Contrast.php
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use App\Support\ColorPalette;
|
||||
|
||||
/**
|
||||
* Kontrastprüfung nach WCAG 2.1 (AA: 4,5:1 für Text, 3:1 für große Schrift und Bedienelemente).
|
||||
* Warnt und schlägt vor – blockiert nichts.
|
||||
*/
|
||||
final class Contrast
|
||||
{
|
||||
public const LIGHT_BACKGROUND = '#FFFFFF';
|
||||
|
||||
public const DARK_BACKGROUND = '#171A1E';
|
||||
|
||||
public const AA = 4.5;
|
||||
|
||||
/**
|
||||
* Farbe für Links und Akzenttext auf hellem Grund: die Markenfarbe selbst,
|
||||
* sonst die erste dunklere Abstufung mit ausreichendem Kontrast.
|
||||
*/
|
||||
public static function textShadeOnLight(string $hex): int
|
||||
{
|
||||
$palette = ColorPalette::fromHex($hex);
|
||||
|
||||
foreach ([600, 700, 800, 900, 950] as $shade) {
|
||||
if (ColorPalette::contrast($palette[$shade], self::LIGHT_BACKGROUND) >= self::AA) {
|
||||
return $shade;
|
||||
}
|
||||
}
|
||||
|
||||
return 950;
|
||||
}
|
||||
|
||||
/**
|
||||
* Farbe für Links und Akzenttext auf dunklem Grund.
|
||||
*/
|
||||
public static function textShadeOnDark(string $hex): int
|
||||
{
|
||||
$palette = ColorPalette::fromHex($hex);
|
||||
|
||||
foreach ([300, 200, 100, 50] as $shade) {
|
||||
if (ColorPalette::contrast($palette[$shade], self::DARK_BACKGROUND) >= self::AA) {
|
||||
return $shade;
|
||||
}
|
||||
}
|
||||
|
||||
return 50;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinweise für die Seite „Erscheinungsbild“.
|
||||
*
|
||||
* @return list<array{level: string, text: string}>
|
||||
*/
|
||||
public static function report(string $primary, ?string $secondary = null): array
|
||||
{
|
||||
$notes = [];
|
||||
$foreground = ColorPalette::foregroundFor($primary);
|
||||
$onButton = ColorPalette::contrast($primary, $foreground);
|
||||
$onWhite = ColorPalette::contrast($primary, self::LIGHT_BACKGROUND);
|
||||
$palette = ColorPalette::fromHex($primary);
|
||||
|
||||
$notes[] = $onButton >= self::AA
|
||||
? ['level' => 'ok', 'text' => sprintf('Schrift auf Schaltflächen (%s): Kontrast %s:1 – gut lesbar.', $foreground === '#FFFFFF' ? 'weiß' : 'schwarz', self::format($onButton))]
|
||||
: ['level' => 'warning', 'text' => sprintf('Schrift auf Schaltflächen erreicht nur %s:1 (empfohlen mindestens 4,5:1). Eine etwas dunklere oder hellere Markenfarbe wäre besser lesbar, z. B. %s.', self::format($onButton), $palette[700])];
|
||||
|
||||
if ($onWhite >= self::AA) {
|
||||
$notes[] = ['level' => 'ok', 'text' => sprintf('Links auf hellem Grund: Kontrast %s:1 – die Markenfarbe wird unverändert verwendet.', self::format($onWhite))];
|
||||
} else {
|
||||
$shade = self::textShadeOnLight($primary);
|
||||
$notes[] = ['level' => 'info', 'text' => sprintf('Die Markenfarbe ist auf Weiß als Textfarbe zu hell (%s:1). Für Links und Akzenttexte wird automatisch die dunklere Abstufung %s verwendet. Schaltflächen und Flächen behalten die Markenfarbe.', self::format($onWhite), $palette[$shade])];
|
||||
}
|
||||
|
||||
if ($secondary !== null) {
|
||||
$onWhite2 = ColorPalette::contrast($secondary, self::LIGHT_BACKGROUND);
|
||||
|
||||
if ($onWhite2 < 3) {
|
||||
$notes[] = ['level' => 'info', 'text' => sprintf('Die zweite Akzentfarbe ist auf Weiß sehr hell (%s:1). Für Beschriftungen wird automatisch eine dunklere Abstufung verwendet.', self::format($onWhite2))];
|
||||
}
|
||||
}
|
||||
|
||||
return $notes;
|
||||
}
|
||||
|
||||
private static function format(float $ratio): string
|
||||
{
|
||||
return number_format($ratio, 1, ',', '');
|
||||
}
|
||||
}
|
||||
55
app/Support/Theme/Fonts.php
Normal file
55
app/Support/Theme/Fonts.php
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
/**
|
||||
* Mitgelieferte Schriften – lokal ausgeliefert (resources/css/fonts.css,
|
||||
* erzeugt von scripts/generate-fonts-css.py), nie von Google Fonts.
|
||||
*/
|
||||
final class Fonts
|
||||
{
|
||||
public const FALLBACK_SANS = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
|
||||
|
||||
public const FALLBACK_SERIF = 'ui-serif, Georgia, Cambria, "Times New Roman", serif';
|
||||
|
||||
/** Schlüssel => [Bezeichnung, CSS-Familie, serif?] */
|
||||
public const FONTS = [
|
||||
'inter' => ['Inter', 'Inter Variable', false],
|
||||
'source-sans-3' => ['Source Sans 3', 'Source Sans 3 Variable', false],
|
||||
'open-sans' => ['Open Sans', 'Open Sans Variable', false],
|
||||
'nunito-sans' => ['Nunito Sans', 'Nunito Sans Variable', false],
|
||||
'roboto' => ['Roboto', 'Roboto Variable', false],
|
||||
'ibm-plex-sans' => ['IBM Plex Sans', 'IBM Plex Sans Variable', false],
|
||||
'figtree' => ['Figtree', 'Figtree Variable', false],
|
||||
'atkinson' => ['Atkinson Hyperlegible (besonders gut lesbar)', 'Atkinson Hyperlegible', false],
|
||||
'source-serif-4' => ['Source Serif 4 (Serifen)', 'Source Serif 4 Variable', true],
|
||||
'merriweather' => ['Merriweather (Serifen)', 'Merriweather Variable', true],
|
||||
'lora' => ['Lora (Serifen)', 'Lora Variable', true],
|
||||
'system' => ['Systemschrift des Geräts', null, false],
|
||||
];
|
||||
|
||||
/** Familienname einer hochgeladenen Schrift. */
|
||||
public const CUSTOM_FAMILY = 'Portal Eigene Schrift';
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function options(bool $withCustom = false): array
|
||||
{
|
||||
$options = array_map(fn (array $font) => $font[0], self::FONTS);
|
||||
|
||||
return $withCustom ? $options + ['custom' => 'Eigene Schrift (hochgeladen)'] : $options;
|
||||
}
|
||||
|
||||
public static function stack(string $key): string
|
||||
{
|
||||
if ($key === 'custom') {
|
||||
return '"'.self::CUSTOM_FAMILY.'", '.self::FALLBACK_SANS;
|
||||
}
|
||||
|
||||
[, $family, $serif] = self::FONTS[$key] ?? self::FONTS['inter'];
|
||||
$fallback = $serif ? self::FALLBACK_SERIF : self::FALLBACK_SANS;
|
||||
|
||||
return $family ? '"'.$family.'", '.$fallback : $fallback;
|
||||
}
|
||||
}
|
||||
66
app/Support/Theme/Icons.php
Normal file
66
app/Support/Theme/Icons.php
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use App\Support\Images;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Intervention\Image\Drivers\Gd\Driver;
|
||||
use Intervention\Image\Encoders\PngEncoder;
|
||||
use Intervention\Image\ImageManager;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Favicon und App-Symbole (Homescreen, Web-App) aus einem quadratischen Bild –
|
||||
* in allen üblichen Größen. Ohne Bild: Monogramm in der Markenfarbe (SVG).
|
||||
*/
|
||||
class Icons
|
||||
{
|
||||
public const SIZES = [32, 180, 192, 512];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $theme
|
||||
* @return array<int, string> Größe => Pfad im Speicher „uploads“
|
||||
*/
|
||||
public function generate(array $theme): array
|
||||
{
|
||||
$source = $theme['app_icon'] ?? null;
|
||||
$disk = Storage::disk('uploads');
|
||||
|
||||
if (! $source || ! $disk->exists($source)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
Images::raiseMemoryLimitFor($disk->path($source));
|
||||
$manager = ImageManager::usingDriver(Driver::class);
|
||||
$hash = substr(sha1((string) $disk->get($source)), 0, 10);
|
||||
$result = [];
|
||||
|
||||
foreach (self::SIZES as $size) {
|
||||
$image = $manager->decodePath($disk->path($source));
|
||||
$image->cover($size, $size);
|
||||
$path = "theme/icons/icon-{$hash}-{$size}.png";
|
||||
$disk->put($path, $image->encode(new PngEncoder)->toString());
|
||||
$result[$size] = $path;
|
||||
}
|
||||
|
||||
return $result;
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Monogramm als SVG-Favicon (Daten-URL), wenn kein Symbol hochgeladen ist.
|
||||
*/
|
||||
public static function monogram(string $name, string $color, string $foreground): string
|
||||
{
|
||||
$letter = htmlspecialchars(mb_strtoupper(mb_substr(trim($name), 0, 1)) ?: 'P', ENT_XML1);
|
||||
$svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="'.$color.'"/>'
|
||||
.'<text x="32" y="44" font-family="Arial,Helvetica,sans-serif" font-size="34" font-weight="700" text-anchor="middle" fill="'.$foreground.'">'.$letter.'</text></svg>';
|
||||
|
||||
return 'data:image/svg+xml;base64,'.base64_encode($svg);
|
||||
}
|
||||
}
|
||||
62
app/Support/Theme/SvgSanitizer.php
Normal file
62
app/Support/Theme/SvgSanitizer.php
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMXPath;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Entfernt aus hochgeladenen SVG-Dateien alles Ausführbare (Skripte,
|
||||
* Ereignis-Attribute, javascript:-Links, eingebettetes HTML). Logos werden
|
||||
* öffentlich ausgeliefert und dürfen niemals Code enthalten.
|
||||
*/
|
||||
final class SvgSanitizer
|
||||
{
|
||||
public static function sanitizeFile(?string $path): void
|
||||
{
|
||||
if (! $path || ! str_ends_with(strtolower($path), '.svg')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$disk = Storage::disk('uploads');
|
||||
|
||||
if (! $disk->exists($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$clean = self::sanitize((string) $disk->get($path));
|
||||
$clean === null ? $disk->delete($path) : $disk->put($path, $clean);
|
||||
}
|
||||
|
||||
public static function sanitize(string $svg): ?string
|
||||
{
|
||||
$dom = new DOMDocument;
|
||||
|
||||
// Keine externen Entitäten, kein Netzwerkzugriff.
|
||||
if (str_contains($svg, '<!ENTITY') || ! @$dom->loadXML($svg, LIBXML_NONET) || $dom->documentElement?->localName !== 'svg') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$xpath = new DOMXPath($dom);
|
||||
|
||||
foreach (iterator_to_array($xpath->query('//*[local-name()="script" or local-name()="foreignObject" or local-name()="iframe" or local-name()="object" or local-name()="embed"]')) as $node) {
|
||||
$node->parentNode->removeChild($node);
|
||||
}
|
||||
|
||||
foreach (iterator_to_array($xpath->query('//*')) as $element) {
|
||||
/** @var DOMElement $element */
|
||||
foreach (iterator_to_array($element->attributes) as $attribute) {
|
||||
$name = strtolower($attribute->nodeName);
|
||||
$value = strtolower(preg_replace('/\s+/', '', $attribute->nodeValue));
|
||||
|
||||
if (str_starts_with($name, 'on') || (in_array($name, ['href', 'xlink:href', 'src'], true) && ! str_starts_with($value, '#') && ! str_starts_with($value, 'data:image/'))) {
|
||||
$element->removeAttributeNode($attribute);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $dom->saveXML($dom->documentElement);
|
||||
}
|
||||
}
|
||||
191
app/Support/Theme/Theme.php
Normal file
191
app/Support/Theme/Theme.php
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/**
|
||||
* Erscheinungsbild der Installation: veröffentlichter Stand und Entwurf.
|
||||
* Gespeichert in den Einstellungen (Datenbank) – überlebt jedes Update.
|
||||
* Bilder und Schriften liegen im Speicher „uploads“ unter theme/.
|
||||
*/
|
||||
class Theme
|
||||
{
|
||||
public const DEFAULTS = [
|
||||
'portal_name' => 'Inhaus',
|
||||
'logo_light' => null,
|
||||
'logo_dark' => null,
|
||||
'logo_mark' => null,
|
||||
'app_icon' => null,
|
||||
'icons' => [],
|
||||
'primary_color' => '#0F4C5C',
|
||||
'secondary_color' => null,
|
||||
'header_style' => 'light',
|
||||
'font_body' => 'inter',
|
||||
'font_heading' => 'same',
|
||||
'custom_font' => null,
|
||||
'radius' => 'medium',
|
||||
'density' => 'normal',
|
||||
'dark_mode' => 'user',
|
||||
'login_layout' => 'split',
|
||||
'login_title' => 'Alles Wichtige für Ihren Arbeitsalltag – an einem Ort.',
|
||||
'login_text' => null,
|
||||
'login_image' => null,
|
||||
'footer_text' => null,
|
||||
'footer_links' => [],
|
||||
'email_footer' => null,
|
||||
'custom_css' => null,
|
||||
'stylesheet' => null,
|
||||
];
|
||||
|
||||
public const HEADER_STYLES = ['light' => 'Hell', 'brand' => 'In der Markenfarbe', 'dark' => 'Dunkel'];
|
||||
|
||||
public const RADII = ['none' => ['Eckig', '0rem'], 'small' => ['Leicht gerundet', '0.25rem'], 'medium' => ['Gerundet', '0.5rem'], 'large' => ['Stark gerundet', '0.75rem'], 'round' => ['Rund', '1rem']];
|
||||
|
||||
public const DENSITIES = ['compact' => ['Kompakt', '0.225rem'], 'normal' => ['Normal', '0.25rem'], 'comfortable' => ['Luftig', '0.275rem']];
|
||||
|
||||
public const DARK_MODES = [
|
||||
'user' => 'Jede Person wählt selbst (Standard: wie im System)',
|
||||
'light' => 'Immer hell',
|
||||
'dark' => 'Immer dunkel',
|
||||
];
|
||||
|
||||
public const LOGIN_LAYOUTS = ['split' => 'Geteilt: Bild bzw. Markenfarbe links, Anmeldung rechts', 'centered' => 'Zentriert: Anmeldung vor dem Hintergrundbild'];
|
||||
|
||||
private const PUBLISHED = 'theme.published';
|
||||
|
||||
private const DRAFT = 'theme.draft';
|
||||
|
||||
public function __construct(private readonly Settings $settings) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function published(): array
|
||||
{
|
||||
$stored = $this->settings->get(self::PUBLISHED);
|
||||
|
||||
return self::normalize(is_array($stored) ? $stored : $this->legacy());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function draft(): ?array
|
||||
{
|
||||
$stored = $this->settings->get(self::DRAFT);
|
||||
|
||||
return is_array($stored) ? self::normalize($stored) : null;
|
||||
}
|
||||
|
||||
public function hasDraft(): bool
|
||||
{
|
||||
return $this->draft() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Entwurf, sonst der veröffentlichte Stand – Ausgangspunkt für das Formular.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function working(): array
|
||||
{
|
||||
return $this->draft() ?? $this->published();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
*/
|
||||
public function saveDraft(array $values): void
|
||||
{
|
||||
$theme = self::normalize([...$this->working(), ...$values]);
|
||||
|
||||
foreach (['logo_light', 'logo_dark', 'logo_mark'] as $logo) {
|
||||
SvgSanitizer::sanitizeFile($theme[$logo]);
|
||||
}
|
||||
|
||||
$this->settings->set(self::DRAFT, $theme);
|
||||
}
|
||||
|
||||
public function discardDraft(): void
|
||||
{
|
||||
$this->settings->set(self::DRAFT, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Entwurf veröffentlichen: statische CSS-Datei erzeugen, Symbole berechnen.
|
||||
*/
|
||||
public function publish(ThemeCompiler $compiler, Icons $icons): void
|
||||
{
|
||||
$theme = $this->working();
|
||||
$theme['icons'] = $icons->generate($theme);
|
||||
$theme['stylesheet'] = $compiler->write($theme);
|
||||
|
||||
$this->settings->setMany([self::PUBLISHED => $theme, self::DRAFT => null]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Auf die Standardwerte zurücksetzen – als Entwurf, damit man es erst ansehen kann.
|
||||
*/
|
||||
public function resetToDefaults(): void
|
||||
{
|
||||
$this->settings->set(self::DRAFT, self::normalize([...self::DEFAULTS, 'portal_name' => $this->published()['portal_name']]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Nur bekannte Schlüssel, gültige Werte.
|
||||
*
|
||||
* @param array<string, mixed> $theme
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function normalize(array $theme): array
|
||||
{
|
||||
$theme = [...self::DEFAULTS, ...Arr::only($theme, array_keys(self::DEFAULTS))];
|
||||
$hex = fn ($value) => is_string($value) && preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? strtoupper($value) : null;
|
||||
|
||||
$theme['portal_name'] = mb_substr(trim((string) $theme['portal_name']), 0, 60) ?: self::DEFAULTS['portal_name'];
|
||||
$theme['primary_color'] = $hex($theme['primary_color']) ?? self::DEFAULTS['primary_color'];
|
||||
$theme['secondary_color'] = $hex($theme['secondary_color']);
|
||||
$theme['header_style'] = array_key_exists($theme['header_style'], self::HEADER_STYLES) ? $theme['header_style'] : 'light';
|
||||
$theme['font_body'] = array_key_exists($theme['font_body'], Fonts::FONTS) || ($theme['font_body'] === 'custom' && $theme['custom_font']) ? $theme['font_body'] : 'inter';
|
||||
$theme['font_heading'] = $theme['font_heading'] === 'same' || array_key_exists($theme['font_heading'], Fonts::FONTS) || ($theme['font_heading'] === 'custom' && $theme['custom_font']) ? $theme['font_heading'] : 'same';
|
||||
$theme['radius'] = array_key_exists($theme['radius'], self::RADII) ? $theme['radius'] : 'medium';
|
||||
$theme['density'] = array_key_exists($theme['density'], self::DENSITIES) ? $theme['density'] : 'normal';
|
||||
$theme['dark_mode'] = array_key_exists($theme['dark_mode'], self::DARK_MODES) ? $theme['dark_mode'] : 'user';
|
||||
$theme['login_layout'] = array_key_exists($theme['login_layout'], self::LOGIN_LAYOUTS) ? $theme['login_layout'] : 'split';
|
||||
$theme['footer_links'] = array_values(array_filter(array_map(
|
||||
fn ($link) => is_array($link) && filled($link['label'] ?? null) && filled($link['url'] ?? null)
|
||||
? ['label' => mb_substr(trim($link['label']), 0, 60), 'url' => mb_substr(trim($link['url']), 0, 500)]
|
||||
: null,
|
||||
(array) $theme['footer_links'],
|
||||
)));
|
||||
$theme['icons'] = is_array($theme['icons']) ? $theme['icons'] : [];
|
||||
|
||||
foreach (['login_title', 'login_text', 'footer_text', 'email_footer'] as $text) {
|
||||
$theme[$text] = filled($theme[$text]) ? mb_substr(trim((string) $theme[$text]), 0, 500) : null;
|
||||
}
|
||||
|
||||
foreach (['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'custom_font'] as $file) {
|
||||
$theme[$file] = is_string($theme[$file]) && preg_match('#^(theme|branding)/[A-Za-z0-9/_.-]+$#', $theme[$file]) && ! str_contains($theme[$file], '..') ? $theme[$file] : null;
|
||||
}
|
||||
|
||||
$theme['custom_css'] = filled($theme['custom_css']) ? mb_substr((string) $theme['custom_css'], 0, 50000) : null;
|
||||
|
||||
return $theme;
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen aus Phase 0 (Portalname, Logo, Markenfarbe) übernehmen.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function legacy(): array
|
||||
{
|
||||
return array_filter([
|
||||
'portal_name' => $this->settings->get('branding.portal_name'),
|
||||
'primary_color' => $this->settings->get('branding.primary_color'),
|
||||
'logo_light' => $this->settings->get('branding.logo_path'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
98
app/Support/Theme/ThemeCompiler.php
Normal file
98
app/Support/Theme/ThemeCompiler.php
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use App\Support\ColorPalette;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Baut aus dem Theme eine CSS-Datei mit Variablen (Farben, Schriften, Form)
|
||||
* und dem eigenen CSS. Beim Veröffentlichen wird sie mit Hash im Namen
|
||||
* gespeichert – kein Build, keine Rechenarbeit pro Seitenaufruf.
|
||||
*/
|
||||
class ThemeCompiler
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $theme
|
||||
*/
|
||||
public function css(array $theme): string
|
||||
{
|
||||
$primary = $theme['primary_color'];
|
||||
$palette = ColorPalette::fromHex($primary);
|
||||
$secondary = $theme['secondary_color'] ?? $primary;
|
||||
$palette2 = ColorPalette::fromHex($secondary);
|
||||
|
||||
$light = [
|
||||
'--brand' => $primary,
|
||||
'--brand-foreground' => ColorPalette::foregroundFor($primary),
|
||||
'--brand-text' => $palette[Contrast::textShadeOnLight($primary)],
|
||||
'--accent2' => $secondary,
|
||||
'--accent2-foreground' => ColorPalette::foregroundFor($secondary),
|
||||
'--accent2-text' => $palette2[Contrast::textShadeOnLight($secondary)],
|
||||
'--radius' => Theme::RADII[$theme['radius']][1],
|
||||
'--spacing' => Theme::DENSITIES[$theme['density']][1],
|
||||
'--font-body' => Fonts::stack($theme['font_body']),
|
||||
'--font-heading' => Fonts::stack($theme['font_heading'] === 'same' ? $theme['font_body'] : $theme['font_heading']),
|
||||
];
|
||||
|
||||
foreach ($palette as $shade => $hex) {
|
||||
$light["--brand-{$shade}"] = $hex;
|
||||
}
|
||||
|
||||
foreach ($palette2 as $shade => $hex) {
|
||||
$light["--accent2-{$shade}"] = $hex;
|
||||
}
|
||||
|
||||
$dark = [
|
||||
'--brand-text' => $palette[Contrast::textShadeOnDark($primary)],
|
||||
'--accent2-text' => $palette2[Contrast::textShadeOnDark($secondary)],
|
||||
];
|
||||
|
||||
$css = ':root{'.$this->declarations($light).'}'."\n"
|
||||
.'.dark{'.$this->declarations($dark).'}'."\n";
|
||||
|
||||
if ($theme['custom_font']) {
|
||||
$url = Storage::disk('uploads')->url($theme['custom_font']);
|
||||
$css .= '@font-face{font-family:"'.Fonts::CUSTOM_FAMILY.'";src:url("'.$url.'") format("woff2");font-weight:100 900;font-display:swap}'."\n";
|
||||
}
|
||||
|
||||
if ($theme['custom_css']) {
|
||||
// Eigenes CSS steht in einer eigenen CSS-Datei; ein schließendes </style> ist dort bedeutungslos,
|
||||
// wird aber für die Vorschau (inline) trotzdem entschärft.
|
||||
$css .= "/* Eigenes CSS */\n".str_ireplace('</style', '<\/style', $theme['custom_css'])."\n";
|
||||
}
|
||||
|
||||
return $css;
|
||||
}
|
||||
|
||||
/**
|
||||
* CSS-Datei schreiben und ihren Pfad im Speicher „uploads“ liefern.
|
||||
*
|
||||
* @param array<string, mixed> $theme
|
||||
*/
|
||||
public function write(array $theme): string
|
||||
{
|
||||
$css = $this->css($theme);
|
||||
$path = 'theme/theme-'.substr(sha1($css), 0, 12).'.css';
|
||||
$disk = Storage::disk('uploads');
|
||||
|
||||
if (! $disk->exists($path)) {
|
||||
$disk->put($path, $css);
|
||||
}
|
||||
|
||||
// Ältere Fassungen aufräumen (die aktuelle und die vorherige bleiben für offene Seiten).
|
||||
$old = collect($disk->files('theme'))->filter(fn ($f) => preg_match('#^theme/theme-[0-9a-f]{12}\.css$#', $f) && $f !== $path)
|
||||
->sortByDesc(fn ($f) => $disk->lastModified($f))->slice(1);
|
||||
$disk->delete($old->all());
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $values
|
||||
*/
|
||||
private function declarations(array $values): string
|
||||
{
|
||||
return collect($values)->map(fn ($value, $name) => $name.':'.$value)->implode(';');
|
||||
}
|
||||
}
|
||||
92
app/Support/Theme/ThemeTransfer.php
Normal file
92
app/Support/Theme/ThemeTransfer.php
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support\Theme;
|
||||
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Erscheinungsbild als Datei – z. B. vom Test- auf das Produktivsystem.
|
||||
* Bilder und Schrift reisen als Daten-URLs mit.
|
||||
*/
|
||||
class ThemeTransfer
|
||||
{
|
||||
public const FORMAT = 'inhaus-theme';
|
||||
|
||||
private const FILES = ['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'custom_font'];
|
||||
|
||||
private const MIME = [
|
||||
'image/svg+xml' => 'svg', 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp', 'font/woff2' => 'woff2',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $theme
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function export(array $theme): array
|
||||
{
|
||||
$disk = Storage::disk('uploads');
|
||||
$files = [];
|
||||
|
||||
foreach (self::FILES as $key) {
|
||||
if ($theme[$key] && $disk->exists($theme[$key])) {
|
||||
$mime = $key === 'custom_font' ? 'font/woff2' : ($disk->mimeType($theme[$key]) ?: 'application/octet-stream');
|
||||
$files[$key] = 'data:'.$mime.';base64,'.base64_encode((string) $disk->get($theme[$key]));
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'format' => self::FORMAT,
|
||||
'version' => 1,
|
||||
'exported_at' => now()->toIso8601String(),
|
||||
'theme' => collect($theme)->except([...self::FILES, 'icons', 'stylesheet'])->all(),
|
||||
'files' => $files,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed> Werte für den Entwurf
|
||||
*/
|
||||
public function import(string $json): array
|
||||
{
|
||||
$data = json_decode($json, true);
|
||||
|
||||
if (! is_array($data) || ($data['format'] ?? null) !== self::FORMAT || ! is_array($data['theme'] ?? null)) {
|
||||
throw new RuntimeException('Die Datei ist kein exportiertes Erscheinungsbild.');
|
||||
}
|
||||
|
||||
$values = collect($data['theme'])->except([...self::FILES, 'icons', 'stylesheet'])->all();
|
||||
|
||||
foreach (self::FILES as $key) {
|
||||
$values[$key] = null;
|
||||
$uri = $data['files'][$key] ?? null;
|
||||
|
||||
if (! is_string($uri) || ! preg_match('#^data:([a-z0-9.+/-]+);base64,(.+)$#i', $uri, $m)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$extension = self::MIME[strtolower($m[1])] ?? null;
|
||||
$binary = base64_decode($m[2], true);
|
||||
|
||||
if (! $extension || $binary === false || strlen($binary) > 8 * 1024 * 1024) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Inhalt prüfen: Bilder müssen sich lesen lassen, SVG wird von allem Ausführbaren befreit.
|
||||
if ($extension === 'svg' && ($binary = SvgSanitizer::sanitize($binary)) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($extension, ['png', 'jpg', 'webp'], true) && @getimagesizefromstring($binary) === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$path = ($key === 'custom_font' ? 'theme/fonts/' : 'theme/').'import-'.Str::random(20).'.'.$extension;
|
||||
Storage::disk('uploads')->put($path, $binary);
|
||||
$values[$key] = $path;
|
||||
}
|
||||
|
||||
return Theme::normalize([...Theme::DEFAULTS, ...$values]);
|
||||
}
|
||||
}
|
||||
|
|
@ -9,5 +9,5 @@ namespace App;
|
|||
*/
|
||||
final class Version
|
||||
{
|
||||
public const VERSION = '0.5.0';
|
||||
public const VERSION = '0.7.0';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ use App\Http\Middleware\HandleInertiaRequests;
|
|||
use App\Http\Middleware\RedirectToInstaller;
|
||||
use App\Http\Middleware\RunPendingMigrations;
|
||||
use App\Http\Middleware\RunPseudoCron;
|
||||
use App\Http\Middleware\ThemePreview;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
|
|
@ -22,6 +23,7 @@ return Application::configure(basePath: dirname(__DIR__))
|
|||
RedirectToInstaller::class,
|
||||
], append: [
|
||||
RunPendingMigrations::class,
|
||||
ThemePreview::class,
|
||||
HandleInertiaRequests::class,
|
||||
RunPseudoCron::class,
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Eigene Kacheln der Startseite: Bild mit Link, Text oder Hinweis.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('dashboard_tiles', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
$table->string('type', 20);
|
||||
$table->string('area', 20)->default('aside');
|
||||
$table->string('title')->nullable();
|
||||
$table->string('image_path')->nullable();
|
||||
$table->string('url', 2000)->nullable();
|
||||
$table->boolean('new_tab')->default(false);
|
||||
$table->string('alt')->nullable();
|
||||
$table->longText('body')->nullable();
|
||||
$table->longText('body_html')->nullable();
|
||||
$table->string('variant', 20)->nullable();
|
||||
$table->boolean('is_active')->default(true);
|
||||
$table->timestamp('starts_at')->nullable();
|
||||
$table->timestamp('ends_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('dashboard_tiles');
|
||||
}
|
||||
};
|
||||
|
|
@ -81,6 +81,44 @@ Die Anmeldung mit Passwort bleibt für Notfälle erhalten (z. B. wenn Entra ID
|
|||
nicht erreichbar ist). Den geheimen Clientschlüssel vor Ablauf erneuern – er
|
||||
ist bei Microsoft befristet.
|
||||
|
||||
## Erscheinungsbild
|
||||
|
||||
Unter **Administration → Portal → Erscheinungsbild** lassen sich Name, Logos,
|
||||
Farben, Schriften, Anmeldeseite, Fußzeile und E-Mails anpassen. Änderungen
|
||||
werden zuerst als **Entwurf** gespeichert und sind nur in der Vorschau
|
||||
sichtbar; für alle gelten sie erst nach **Veröffentlichen**. Über „Mehr“ lässt
|
||||
sich das Erscheinungsbild als Datei exportieren und auf einem anderen System
|
||||
(z. B. vom Test- auf das Produktivsystem) importieren.
|
||||
|
||||
Schriften werden immer vom eigenen Server ausgeliefert. Eine eigene Schrift
|
||||
(WOFF2) darf nur hochgeladen werden, wenn ihre Lizenz die Nutzung im Web erlaubt.
|
||||
|
||||
## E-Mail-Versand
|
||||
|
||||
Unter **Administration → E-Mail-Versand** den SMTP-Zugang eintragen (vom
|
||||
Hoster oder der IT, z. B. Microsoft 365: `smtp.office365.com`, Port 587,
|
||||
STARTTLS) und mit **Test-Mail senden** prüfen. Das Passwort wird verschlüsselt
|
||||
gespeichert. Gebraucht wird der Versand für „Passwort vergessen“ und
|
||||
Formular-Benachrichtigungen. Mails werden über die Hintergrundaufgaben
|
||||
verschickt – ohne Cron oder Web-Cron also mit etwas Verzögerung.
|
||||
|
||||
## Umstieg von WordPress
|
||||
|
||||
1. In WordPress unter **Werkzeuge → Daten exportieren** „Alle Inhalte“ wählen
|
||||
und die XML-Datei herunterladen.
|
||||
2. Im Portal unter **Administration → Inhalte → WordPress-Import** hochladen
|
||||
und **Datei prüfen**.
|
||||
3. Kategorien zuordnen (neu anlegen, vorhandene nutzen oder weglassen),
|
||||
Autorinnen und Autoren prüfen (Zuordnung über die E-Mail-Adresse) und
|
||||
entscheiden, ob Entwürfe und WordPress-Seiten mitkommen.
|
||||
4. **Import starten** – die Seite geöffnet lassen, der Import läuft in Portionen.
|
||||
|
||||
Bilder werden von der alten Website geladen, sie muss dafür noch erreichbar
|
||||
sein. Ein erneuter Import legt nichts doppelt an; auf Wunsch aktualisiert er
|
||||
bereits übernommene Einträge. Kommentare, Schlagwörter und Inhalte anderer
|
||||
WordPress-Plugins werden nicht übernommen. Nach dem Umstieg kann das Plugin
|
||||
„WordPress-Import“ deaktiviert werden.
|
||||
|
||||
## Hintergrundaufgaben
|
||||
|
||||
Rückmeldungen, geplante Inhalte und Aufräumarbeiten laufen im Hintergrund. Die
|
||||
|
|
|
|||
|
|
@ -452,8 +452,8 @@ Entwickler, ohne Build, direkt im Admin unter „Erscheinungsbild“.
|
|||
|
||||
## 13. Mitgelieferte Plugins
|
||||
|
||||
**Start:** Dashboard, News/Feed mit Kategorien, CMS-Seiten, Verzeichnis &
|
||||
Organigramm, Dokumente, App-Launcher.
|
||||
**Start:** Dashboard, News/Feed mit Kategorien, CMS-Seiten, Formulare,
|
||||
WordPress-Import, Verzeichnis & Organigramm, Dokumente, App-Launcher.
|
||||
|
||||
**Später:** Events, Umfragen, Geburtstage/Jubiläen, Onboarding, Raumbuchung,
|
||||
Kantinenplan, Ideenbox, Urlaubsanträge.
|
||||
|
|
@ -482,7 +482,8 @@ Kantinenplan, Ideenbox, Urlaubsanträge.
|
|||
| **2 – Plugin-System & Rechte** ✅ | Plugin-Loader, Hooks/Filter, Registries, Recovery-Modus, Import-Map-Frontend; Rollen, Grants, Zielgruppen, Rechte-Cache, Rechte-Prüfer |
|
||||
| **3 – Entra ID** ✅ | OIDC-Login, JIT, Gruppen-/App-Rollen-Mapping (additiv), Graph-Profil- & Foto-Sync mit frei zuordenbaren Attributen (inkl. Erweiterungsattributen) und eigenen Profilfeldern, Delta-Sync |
|
||||
| **4 – CMS** ✅ | Seitenbaum, Pagebuilder (Layout-, Inhalts-, Medien- und dynamische Blöcke, Sichtbarkeit je Block), Entwürfe, Versionen, Zeitsteuerung, Bearbeitungssperre, Freigaben; News-Freigabe-Workflow und Redaktion im Portal; Benachrichtigungen. Offen: Vorlagen und wiederverwendbare Blöcke |
|
||||
| **5 – Branding & Theming** | Vollständige Seite „Erscheinungsbild“: Logo-Varianten, Farben inkl. Farbtreue & Kontrastprüfung, Schriften, Form, Login-Seite, E-Mails, Live-Vorschau, Entwurf/Veröffentlichen, Export/Import |
|
||||
| **4b – Formulare & Umstieg** ✅ | Formular-Plugin (visueller Baukasten im Portal, Bedingungen, Uploads, anonyme Formulare, Mail + Backend, Ergebnis-Rechte je Formular und Rolle, CSV, Löschfristen; eingebunden per Pagebuilder-Block und unter Beiträgen, kein eigener Menüpunkt); WordPress-Import (Beiträge, Kategorien, Bilder, Seiten); E-Mail-Versand im Admin; anpassbare Startseite mit eigenen Kacheln; Geburtstage (optionales Plugin) |
|
||||
| **5 – Branding & Theming** ✅ | Vollständige Seite „Erscheinungsbild“: Logo-Varianten, Farben inkl. Farbtreue & Kontrastprüfung, Schriften, Form, Login-Seite, E-Mails, Live-Vorschau, Entwurf/Veröffentlichen, Export/Import |
|
||||
| **6 – Weitere Plugins & IdPs** | Verzeichnis/Organigramm, Dokumente, Events …; OIDC generisch, LDAP, SAML; Lasttests 5.000 User |
|
||||
| **7 – Plugin-SDK öffentlich** | Doku, Generator, Beispiel-Plugins (kein Plugin-Verzeichnis) |
|
||||
| **8 – Mobil** | REST-API (Sanctum), Web-Push, native App |
|
||||
|
|
|
|||
|
|
@ -116,6 +116,14 @@ $this->app->make(Blocks::class)->add(BlockType::make('mein-plugin.liste', 'Meine
|
|||
- Die Vue-Komponente erhält `block` (`data`, `items`, `props`) – Kinder werden mit
|
||||
`inject('pagebuilder:list')` gerendert. `inject('pagebuilder:editing')` ist im Editor wahr.
|
||||
|
||||
## Startseite und Profil
|
||||
|
||||
- Kacheln: `app(App\Dashboard\Widgets::class)->add($key, 'mein-plugin::Kachel', 'aside', sort: 20, props: fn (User $user) => [...], label: 'Name im Admin')`.
|
||||
Bereiche: `top`, `hero`, `feed`, `main`, `aside`. Admins sortieren und blenden Kacheln unter „Startseite“ aus.
|
||||
- Abschnitt in „Profil bearbeiten“: `app(App\Profile\ProfileSections::class)->add($key, 'mein-plugin::Abschnitt', $sort, fn (User $user) => [...])`
|
||||
(Komponente unter `resources/js/profile/`, speichert über eigene Routen).
|
||||
- Optionale mitgelieferte Plugins: `"enabled_by_default": false` in `plugin.json`.
|
||||
|
||||
## Redaktion, Navigation und Benachrichtigungen
|
||||
|
||||
- Arbeitslisten im Bereich „Redaktion“: `app(App\Editorial\Editorial::class)->add($key, $label, 'mein-plugin::Liste', $sort, $sichtbar, $props)`.
|
||||
|
|
|
|||
110
package-lock.json
generated
110
package-lock.json
generated
|
|
@ -5,7 +5,17 @@
|
|||
"packages": {
|
||||
"": {
|
||||
"devDependencies": {
|
||||
"@fontsource-variable/figtree": "^5.3.0",
|
||||
"@fontsource-variable/ibm-plex-sans": "^5.3.0",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/lora": "^5.3.0",
|
||||
"@fontsource-variable/merriweather": "^5.3.0",
|
||||
"@fontsource-variable/nunito-sans": "^5.3.0",
|
||||
"@fontsource-variable/open-sans": "^5.3.0",
|
||||
"@fontsource-variable/roboto": "^5.3.0",
|
||||
"@fontsource-variable/source-sans-3": "^5.3.0",
|
||||
"@fontsource-variable/source-serif-4": "^5.3.0",
|
||||
"@fontsource/atkinson-hyperlegible": "^5.3.0",
|
||||
"@inertiajs/vue3": "^3.7.1",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@tailwindcss/typography": "^0.5.20",
|
||||
|
|
@ -148,6 +158,26 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/figtree": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/figtree/-/figtree-5.3.0.tgz",
|
||||
"integrity": "sha512-VRVodD7OiG7apQwE8/2fMjaqpY/a0qRJqL5HtYj8CKIVps+9amaFcdfKmDIf7iqYQx6iPLlArVXAfKeIZmVcNQ==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/ibm-plex-sans": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/ibm-plex-sans/-/ibm-plex-sans-5.3.0.tgz",
|
||||
"integrity": "sha512-agG8tXFEo0hD9+J7npa4vbbWult52eMLVaQ6WQRlhs/iCAojrMAoejru85W9HTVXHfyUj96KM7gp/KGAS87XaQ==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/inter": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
|
||||
|
|
@ -158,6 +188,86 @@
|
|||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/lora": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/lora/-/lora-5.3.0.tgz",
|
||||
"integrity": "sha512-2ph8KiZ8Bn141hWuC3ErtpJ+Ui8p2MJQn8TJNRSRmLmnCIOCtHfiBM9R7WLRPeUG/q6hXyHOxWQ8DvRSX+ixvQ==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/merriweather": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/merriweather/-/merriweather-5.3.0.tgz",
|
||||
"integrity": "sha512-wK7S4NtPXWUWll/sZCdub93pqSCnFkpKFbnoOE8fh+9Ut6JFjgkc9UlBxHJ0RVMkDpoWwGwMwYYTMvd3G9aAXA==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/nunito-sans": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/nunito-sans/-/nunito-sans-5.3.0.tgz",
|
||||
"integrity": "sha512-Vk1PSfckNDwgw2yGcsvJP3o/0zEW8Rp6KzbD8Ql/6iRHQshnhhAjt+cSIfAUyp5vQuSlleGHFW2LfYaaex0diw==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/open-sans": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/open-sans/-/open-sans-5.3.0.tgz",
|
||||
"integrity": "sha512-VOfhZfLIOBVa6K/dTEu7scqQXYdGa4jBX8quFpQ0S6574B+W2EOBJf9PkqyVtMEI7WWIWNEbpvPc3vY1mN2mmQ==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/roboto": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/roboto/-/roboto-5.3.0.tgz",
|
||||
"integrity": "sha512-BoaaZiQf8fgtxv07KXkTwx1bKz/EoqIlTXq2OOKKXINxp6qXWdnlChqV+hSaDANS49yyUASFl3OVBMMDTCIHFA==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/source-sans-3": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/source-sans-3/-/source-sans-3-5.3.0.tgz",
|
||||
"integrity": "sha512-dpi0GZk7EQe2tYpg6Q0Fx0OmUgnuGu+0rHPgtXqtKhglYmJuP7jZ12Mu1uN+NfRaJRY1Emn8AQJEWzmoZ4wa9g==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource-variable/source-serif-4": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource-variable/source-serif-4/-/source-serif-4-5.3.0.tgz",
|
||||
"integrity": "sha512-9vch9WqxjaaA+1o9Ur8pOgIGbCYLjRReOUel23A6lOpD1syptgjtkORevvNmldJ5kGXQL29onQUqI5Ltz0s3bQ==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@fontsource/atkinson-hyperlegible": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fontsource/atkinson-hyperlegible/-/atkinson-hyperlegible-5.3.0.tgz",
|
||||
"integrity": "sha512-Sp8Ve8+rQmENY2Lv02VH7sLpntzTTvnncnJMTbRE7DX6TLxGraN4ykZfzaUWIoCFmaomwkvNiqmlPkrKBuDoSA==",
|
||||
"dev": true,
|
||||
"license": "OFL-1.1",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ayuhito"
|
||||
}
|
||||
},
|
||||
"node_modules/@inertiajs/core": {
|
||||
"version": "3.7.1",
|
||||
"resolved": "https://registry.npmjs.org/@inertiajs/core/-/core-3.7.1.tgz",
|
||||
|
|
|
|||
10
package.json
10
package.json
|
|
@ -7,7 +7,17 @@
|
|||
"dev": "vite"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@fontsource-variable/figtree": "^5.3.0",
|
||||
"@fontsource-variable/ibm-plex-sans": "^5.3.0",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/lora": "^5.3.0",
|
||||
"@fontsource-variable/merriweather": "^5.3.0",
|
||||
"@fontsource-variable/nunito-sans": "^5.3.0",
|
||||
"@fontsource-variable/open-sans": "^5.3.0",
|
||||
"@fontsource-variable/roboto": "^5.3.0",
|
||||
"@fontsource-variable/source-sans-3": "^5.3.0",
|
||||
"@fontsource-variable/source-serif-4": "^5.3.0",
|
||||
"@fontsource/atkinson-hyperlegible": "^5.3.0",
|
||||
"@inertiajs/vue3": "^3.7.1",
|
||||
"@lucide/vue": "^1.48.0",
|
||||
"@tailwindcss/typography": "^0.5.20",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Freiwillige Geburtstagsliste: nur Tag und Monat – kein Geburtsjahr, kein Alter.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('birthdays', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->unique()->constrained('users')->cascadeOnDelete();
|
||||
$table->unsignedTinyInteger('month');
|
||||
$table->unsignedTinyInteger('day');
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['month', 'day']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('birthdays');
|
||||
}
|
||||
};
|
||||
14
plugins-core/birthdays/plugin.json
Normal file
14
plugins-core/birthdays/plugin.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"slug": "birthdays",
|
||||
"name": "Geburtstage",
|
||||
"version": "1.0.0",
|
||||
"description": "Geburtstagsliste zum Mitmachen: Wer möchte, trägt Tag und Monat im Profil ein. Mit Kachel auf der Startseite und Glückwunsch am eigenen Geburtstag.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\Birthdays\\",
|
||||
"class": "Inhaus\\Plugins\\Birthdays\\BirthdaysPlugin",
|
||||
"enabled_by_default": false,
|
||||
"requires": {
|
||||
"core": ">=0.6.0",
|
||||
"php": ">=8.3"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
<script setup>
|
||||
import BirthdayItem from '../components/BirthdayItem.vue';
|
||||
|
||||
defineProps({ block: { type: Object, required: true } });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h3 v-if="block.data.title" class="mb-3 text-lg font-semibold">{{ block.data.title }}</h3>
|
||||
<div class="divide-y rounded-lg border bg-card px-4">
|
||||
<BirthdayItem v-for="item in block.props?.birthdays ?? []" :key="`${item.person.id}-${item.date}`" :item="item" />
|
||||
<p v-if="!(block.props?.birthdays ?? []).length" class="py-3 text-sm text-muted-foreground">Keine anstehenden Geburtstage.</p>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Cake } from '@lucide/vue';
|
||||
import PersonAvatar from '@/components/PersonAvatar.vue';
|
||||
|
||||
defineProps({
|
||||
item: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const day = (iso) => new Intl.DateTimeFormat('de-DE', { day: 'numeric', month: 'long' }).format(new Date(`${iso}T12:00:00`));
|
||||
const weekday = (iso) => new Intl.DateTimeFormat('de-DE', { weekday: 'short' }).format(new Date(`${iso}T12:00:00`));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Link :href="`/personen/${item.person.id}`" class="group flex items-center gap-3 py-2.5">
|
||||
<span class="relative shrink-0">
|
||||
<PersonAvatar :person="item.person" class="size-10" />
|
||||
<span v-if="item.today" class="absolute -right-1 -bottom-1 grid size-5 place-items-center rounded-full bg-brand text-brand-foreground ring-2 ring-card"><Cake class="size-3" /></span>
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-sm font-medium group-hover:underline">{{ item.person.name }}</span>
|
||||
<span class="block truncate text-xs text-muted-foreground">{{ item.person.job_title || item.person.department }}</span>
|
||||
</span>
|
||||
<span class="shrink-0 text-right text-xs" :class="item.today ? 'font-semibold text-brand-text' : 'text-muted-foreground'">
|
||||
{{ item.today ? 'Heute' : `${weekday(item.date)}, ${day(item.date)}` }}
|
||||
</span>
|
||||
</Link>
|
||||
</template>
|
||||
52
plugins-core/birthdays/resources/js/pages/Index.vue
Normal file
52
plugins-core/birthdays/resources/js/pages/Index.vue
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Cake } from '@lucide/vue';
|
||||
import EmptyState from '@/components/EmptyState.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import BirthdayItem from '../components/BirthdayItem.vue';
|
||||
|
||||
const props = defineProps({
|
||||
birthdays: { type: Array, required: true },
|
||||
scope: { type: String, required: true },
|
||||
registered: { type: Boolean, default: false },
|
||||
});
|
||||
|
||||
// Nach Tagen gruppiert: „Heute“, dann die folgenden Tage
|
||||
const groups = computed(() => {
|
||||
const result = [];
|
||||
|
||||
for (const item of props.birthdays) {
|
||||
const last = result.at(-1);
|
||||
last && last.date === item.date ? last.items.push(item) : result.push({ date: item.date, today: item.today, items: [item] });
|
||||
}
|
||||
|
||||
return result;
|
||||
});
|
||||
|
||||
const label = (group) => group.today ? 'Heute' : new Intl.DateTimeFormat('de-DE', { weekday: 'long', day: 'numeric', month: 'long' }).format(new Date(`${group.date}T12:00:00`));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AppLayout title="Geburtstage">
|
||||
<div class="mx-auto max-w-3xl">
|
||||
<h1 class="text-2xl font-semibold tracking-tight">Geburtstage</h1>
|
||||
<p class="mt-1 text-sm text-muted-foreground">Die nächsten 30 Tage · {{ scope }}</p>
|
||||
|
||||
<p v-if="!registered" class="mt-5 rounded-lg border bg-card px-4 py-3 text-sm">
|
||||
Sie möchten auch in der Liste stehen? Tragen Sie Tag und Monat unter
|
||||
<Link href="/profil/bearbeiten" class="font-medium text-brand-text hover:underline">Profil bearbeiten</Link> ein.
|
||||
</p>
|
||||
|
||||
<div v-if="groups.length" class="mt-6 grid gap-5">
|
||||
<section v-for="group in groups" :key="group.date" class="rounded-lg border bg-card">
|
||||
<h2 class="border-b px-5 py-3 text-sm font-semibold" :class="group.today ? 'text-brand-text' : ''">{{ label(group) }}</h2>
|
||||
<div class="divide-y px-5">
|
||||
<BirthdayItem v-for="item in group.items" :key="item.person.id" :item="item" />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div v-else class="mt-6 rounded-lg border bg-card"><EmptyState :icon="Cake" title="Keine Geburtstage in den nächsten 30 Tagen" /></div>
|
||||
</div>
|
||||
</AppLayout>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { router, useForm } from '@inertiajs/vue3';
|
||||
import { Cake, LoaderCircle } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import FormField from '@/components/FormField.vue';
|
||||
import NativeSelect from '@/components/NativeSelect.vue';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
|
||||
const props = defineProps({
|
||||
birthday: { type: Object, default: null },
|
||||
months: { type: Array, required: true },
|
||||
scope: { type: String, default: 'all' },
|
||||
});
|
||||
|
||||
const form = useForm({ day: props.birthday?.day ?? null, month: props.birthday?.month ?? null });
|
||||
const days = computed(() => Array.from({ length: 31 }, (_, i) => ({ value: i + 1, label: String(i + 1) })));
|
||||
|
||||
const audience = { all: 'allen Mitarbeitenden', department: 'Ihrer Abteilung', location: 'Ihrem Standort' };
|
||||
|
||||
function save() {
|
||||
form.put('/profil/geburtstag', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.defaults();
|
||||
toast.success('Geburtstag gespeichert');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function remove() {
|
||||
router.delete('/profil/geburtstag', {
|
||||
preserveScroll: true,
|
||||
onSuccess: () => {
|
||||
form.day = null;
|
||||
form.month = null;
|
||||
form.defaults();
|
||||
toast.success('Aus der Geburtstagsliste entfernt');
|
||||
},
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Geburtstag">
|
||||
<form class="grid gap-4" @submit.prevent="save">
|
||||
<p class="flex gap-2 text-sm text-muted-foreground">
|
||||
<Cake class="mt-0.5 size-4 shrink-0 text-brand-text" />
|
||||
<span>Freiwillig: Wenn Sie Tag und Monat eintragen, erscheint Ihr Geburtstag in der Geburtstagsliste und ist {{ audience[scope] }} sichtbar. Das Geburtsjahr wird nicht erfasst. Austragen ist jederzeit möglich.</span>
|
||||
</p>
|
||||
<div class="grid grid-cols-2 gap-4 sm:max-w-sm">
|
||||
<FormField id="birthday-day" label="Tag" :error="form.errors.day">
|
||||
<NativeSelect id="birthday-day" v-model="form.day" :options="days" placeholder="–" />
|
||||
</FormField>
|
||||
<FormField id="birthday-month" label="Monat" :error="form.errors.month">
|
||||
<NativeSelect id="birthday-month" v-model="form.month" :options="months" placeholder="–" />
|
||||
</FormField>
|
||||
</div>
|
||||
<div class="flex justify-end gap-2 border-t pt-4">
|
||||
<Button v-if="birthday" type="button" variant="ghost" class="text-destructive hover:text-destructive" @click="remove">Austragen</Button>
|
||||
<Button type="submit" :disabled="form.processing || !form.day || !form.month || !form.isDirty">
|
||||
<LoaderCircle v-if="form.processing" class="animate-spin" />
|
||||
{{ birthday ? 'Speichern' : 'Eintragen' }}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Panel>
|
||||
</template>
|
||||
55
plugins-core/birthdays/resources/js/widgets/Greeting.vue
Normal file
55
plugins-core/birthdays/resources/js/widgets/Greeting.vue
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { Cake, X } from '@lucide/vue';
|
||||
|
||||
/**
|
||||
* Glückwunsch am eigenen Geburtstag – lässt sich für heute ausblenden.
|
||||
*/
|
||||
const props = defineProps({
|
||||
name: { type: String, required: true },
|
||||
});
|
||||
|
||||
const key = `inhaus.birthday-greeting.${new Date().toISOString().slice(0, 10)}`;
|
||||
const hidden = ref(false);
|
||||
|
||||
try {
|
||||
hidden.value = localStorage.getItem(key) === '1';
|
||||
} catch {
|
||||
// Speicher nicht verfügbar – dann eben immer zeigen.
|
||||
}
|
||||
|
||||
function dismiss() {
|
||||
hidden.value = true;
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, '1');
|
||||
} catch {
|
||||
// ignorieren
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="!hidden" class="relative overflow-hidden rounded-lg bg-brand text-brand-foreground" role="status">
|
||||
<!-- dezente Konfetti-Punkte -->
|
||||
<svg class="pointer-events-none absolute inset-0 size-full opacity-25" aria-hidden="true">
|
||||
<circle cx="8%" cy="30%" r="4" fill="currentColor" />
|
||||
<circle cx="15%" cy="75%" r="3" fill="currentColor" />
|
||||
<rect x="24%" y="18%" width="7" height="7" transform="rotate(20)" fill="currentColor" />
|
||||
<circle cx="62%" cy="20%" r="3" fill="currentColor" />
|
||||
<circle cx="78%" cy="70%" r="5" fill="currentColor" />
|
||||
<rect x="88%" y="30%" width="8" height="8" fill="currentColor" />
|
||||
<circle cx="94%" cy="80%" r="3" fill="currentColor" />
|
||||
</svg>
|
||||
<div class="relative flex items-center gap-4 px-5 py-5 sm:px-8">
|
||||
<span class="grid size-12 shrink-0 place-items-center rounded-full bg-white/15"><Cake class="size-6" /></span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-xl font-semibold tracking-tight">Alles Gute zum Geburtstag, {{ props.name }}!</p>
|
||||
<p class="mt-0.5 text-sm opacity-90">Wir wünschen Ihnen einen schönen Tag.</p>
|
||||
</div>
|
||||
<button type="button" class="grid size-9 shrink-0 place-items-center rounded-md hover:bg-white/15" aria-label="Glückwunsch ausblenden" @click="dismiss">
|
||||
<X class="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
17
plugins-core/birthdays/resources/js/widgets/Upcoming.vue
Normal file
17
plugins-core/birthdays/resources/js/widgets/Upcoming.vue
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<script setup>
|
||||
import Panel from '@/components/Panel.vue';
|
||||
import BirthdayItem from '../components/BirthdayItem.vue';
|
||||
|
||||
defineProps({
|
||||
birthdays: { type: Array, required: true },
|
||||
days: { type: Number, default: 7 },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Geburtstage" action-label="Alle" action-href="/geburtstage">
|
||||
<div class="-my-2 divide-y">
|
||||
<BirthdayItem v-for="item in birthdays" :key="`${item.person.id}-${item.date}`" :item="item" />
|
||||
</div>
|
||||
</Panel>
|
||||
</template>
|
||||
10
plugins-core/birthdays/routes/web.php
Normal file
10
plugins-core/birthdays/routes/web.php
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Birthdays\Http\Controllers\BirthdayController;
|
||||
|
||||
Route::middleware('auth')->group(function () {
|
||||
Route::get('/geburtstage', [BirthdayController::class, 'index'])->name('birthdays.index');
|
||||
Route::put('/profil/geburtstag', [BirthdayController::class, 'update'])->name('birthdays.update');
|
||||
Route::delete('/profil/geburtstag', [BirthdayController::class, 'destroy'])->name('birthdays.destroy');
|
||||
});
|
||||
95
plugins-core/birthdays/src/BirthdayList.php
Normal file
95
plugins-core/birthdays/src/BirthdayList.php
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Birthdays;
|
||||
|
||||
use App\Http\Resources\PersonResource;
|
||||
use App\Models\User;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Inhaus\Plugins\Birthdays\Models\Birthday;
|
||||
|
||||
/**
|
||||
* Anstehende Geburtstage für eine Person – je nach Einstellung aus dem ganzen
|
||||
* Haus, der eigenen Abteilung oder dem eigenen Standort.
|
||||
*/
|
||||
class BirthdayList
|
||||
{
|
||||
public const SCOPES = [
|
||||
'all' => 'Alle Mitarbeitenden',
|
||||
'department' => 'Nur die eigene Abteilung',
|
||||
'location' => 'Nur der eigene Standort',
|
||||
];
|
||||
|
||||
public function __construct(private readonly Settings $settings) {}
|
||||
|
||||
public function scope(): string
|
||||
{
|
||||
return array_key_exists($s = (string) $this->settings->get('birthdays.scope', 'all'), self::SCOPES) ? $s : 'all';
|
||||
}
|
||||
|
||||
public function daysAhead(): int
|
||||
{
|
||||
return max(0, min(60, (int) $this->settings->get('birthdays.days', 7)));
|
||||
}
|
||||
|
||||
public function greetingEnabled(): bool
|
||||
{
|
||||
return (bool) $this->settings->get('birthdays.greeting', true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{date: string, today: bool, person: array<string, mixed>}>
|
||||
*/
|
||||
public function upcoming(User $viewer, ?int $days = null, ?string $scope = null, int $limit = 200): array
|
||||
{
|
||||
$days ??= $this->daysAhead();
|
||||
$scope ??= $this->scope();
|
||||
$today = Carbon::today();
|
||||
$end = $today->copy()->addDays($days);
|
||||
|
||||
// Nur die betroffenen Monate laden (höchstens drei), dann genau filtern.
|
||||
$months = collect(range(0, (int) $today->copy()->startOfMonth()->diffInMonths($end->copy()->startOfMonth())))
|
||||
->map(fn ($i) => $today->copy()->startOfMonth()->addMonths($i)->month)->unique()->values()->all();
|
||||
|
||||
$birthdays = Birthday::query()
|
||||
->whereIn('month', $months)
|
||||
->whereHas('user', function ($q) use ($viewer, $scope) {
|
||||
$q->where('is_active', true);
|
||||
|
||||
if ($scope === 'department') {
|
||||
$viewer->department ? $q->where('department', $viewer->department) : $q->whereKey($viewer->id);
|
||||
} elseif ($scope === 'location') {
|
||||
$viewer->location ? $q->where('location', $viewer->location) : $q->whereKey($viewer->id);
|
||||
}
|
||||
})
|
||||
->with('user')
|
||||
->get();
|
||||
|
||||
return $birthdays
|
||||
->map(fn (Birthday $b) => ['birthday' => $b, 'date' => $b->nextOccurrence($today)])
|
||||
->filter(fn ($row) => $row['date']->lte($end))
|
||||
->sortBy(fn ($row) => $row['date']->format('Ymd').mb_strtolower($row['birthday']->user->last_name.' '.$row['birthday']->user->first_name))
|
||||
->take($limit)
|
||||
->map(fn ($row) => [
|
||||
'date' => $row['date']->toDateString(),
|
||||
'today' => $row['date']->isSameDay($today),
|
||||
'person' => (new PersonResource($row['birthday']->user))->resolve(),
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
public function isBirthdayToday(User $user): bool
|
||||
{
|
||||
return (bool) Birthday::query()->where('user_id', $user->id)->first()?->isOn(Carbon::today());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, string>
|
||||
*/
|
||||
public static function months(): Collection
|
||||
{
|
||||
return collect(range(1, 12))->mapWithKeys(fn ($m) => [$m => Carbon::create(2000, $m, 1)->locale('de')->translatedFormat('F')]);
|
||||
}
|
||||
}
|
||||
60
plugins-core/birthdays/src/BirthdaysPlugin.php
Normal file
60
plugins-core/birthdays/src/BirthdaysPlugin.php
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Birthdays;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\BlockType;
|
||||
use App\Pagebuilder\Field;
|
||||
use App\Plugins\Plugin;
|
||||
use App\Profile\ProfileSections;
|
||||
use Inhaus\Plugins\Birthdays\Models\Birthday;
|
||||
|
||||
/**
|
||||
* Freiwillige Geburtstagsliste. Standardmäßig aus – im Admin unter „Plugins“ aktivierbar.
|
||||
*/
|
||||
class BirthdaysPlugin extends Plugin
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(BirthdayList::class);
|
||||
|
||||
$this->app->make(ProfileSections::class)->add('birthday', 'birthdays::ProfileBirthday', 10, function (User $user) {
|
||||
$birthday = Birthday::query()->where('user_id', $user->id)->first();
|
||||
|
||||
return [
|
||||
'birthday' => $birthday ? ['day' => $birthday->day, 'month' => $birthday->month] : null,
|
||||
'months' => BirthdayList::months()->map(fn ($label, $value) => ['value' => $value, 'label' => $label])->values(),
|
||||
'scope' => app(BirthdayList::class)->scope(),
|
||||
];
|
||||
});
|
||||
|
||||
$widgets = $this->app->make(Widgets::class);
|
||||
|
||||
// Glückwunsch oben auf der Startseite – nur am eigenen Geburtstag.
|
||||
$widgets->add('birthdays.greeting', 'birthdays::Greeting', 'top', sort: 0, props: function (User $user) {
|
||||
$list = app(BirthdayList::class);
|
||||
|
||||
return $list->greetingEnabled() && $list->isBirthdayToday($user) ? ['name' => $user->first_name ?: $user->name] : null;
|
||||
}, label: 'Geburtstagsgruß (am eigenen Geburtstag)', mobileSort: -100);
|
||||
|
||||
$widgets->add('birthdays.upcoming', 'birthdays::Upcoming', 'aside', sort: 30, props: function (User $user) {
|
||||
$list = app(BirthdayList::class);
|
||||
$upcoming = $list->upcoming($user, limit: 8);
|
||||
|
||||
return $upcoming === [] ? null : ['birthdays' => $upcoming, 'days' => $list->daysAhead()];
|
||||
}, label: 'Geburtstage', mobileSort: 35);
|
||||
|
||||
$this->app->make(Blocks::class)->add(BlockType::make('birthdays.list', 'Geburtstage', 'cake', 'dynamic', 'birthdays::BirthdaysBlock')
|
||||
->description('Anstehende Geburtstage – z. B. auf der Seite einer Abteilung.')
|
||||
->fields([
|
||||
Field::text('title', 'Überschrift', 150, 'Geburtstage'),
|
||||
Field::select('scope', 'Wessen Geburtstage', ['' => 'Wie in den Einstellungen'] + BirthdayList::SCOPES, ''),
|
||||
Field::number('days', 'Tage im Voraus', 0, 60, 14),
|
||||
])
|
||||
->resolveUsing(fn (array $data, ?User $user) => $user ? [
|
||||
'birthdays' => app(BirthdayList::class)->upcoming($user, $data['days'], $data['scope'] ?: null, 30),
|
||||
] : null));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Birthdays\Filament\Pages;
|
||||
|
||||
use App\Support\Settings;
|
||||
use BackedEnum;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Inhaus\Plugins\Birthdays\BirthdayList;
|
||||
use Inhaus\Plugins\Birthdays\Models\Birthday;
|
||||
use UnitEnum;
|
||||
|
||||
class BirthdaySettings extends Page
|
||||
{
|
||||
protected string $view = 'filament.pages.settings-form';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCake;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Portal';
|
||||
|
||||
protected static ?int $navigationSort = 30;
|
||||
|
||||
protected static ?string $navigationLabel = 'Geburtstage';
|
||||
|
||||
protected static ?string $title = 'Geburtstage';
|
||||
|
||||
protected static ?string $slug = 'geburtstage';
|
||||
|
||||
/** @var array<string, mixed>|null */
|
||||
public ?array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->user()?->can('appearance.manage') ?? false;
|
||||
}
|
||||
|
||||
public function mount(BirthdayList $list): void
|
||||
{
|
||||
$this->form->fill(['scope' => $list->scope(), 'days' => $list->daysAhead(), 'greeting' => $list->greetingEnabled()]);
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->statePath('data')->components([
|
||||
Section::make('Geburtstagsliste')
|
||||
->description(fn () => 'Mitarbeitende tragen sich freiwillig im Profil ein (nur Tag und Monat). Derzeit eingetragen: '.Birthday::query()->count().'.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('scope')->label('Wer sieht wessen Geburtstag')->options(BirthdayList::SCOPES)->required()->native(false),
|
||||
TextInput::make('days')->label('Tage im Voraus auf der Startseite')->numeric()->minValue(0)->maxValue(60)->required(),
|
||||
Toggle::make('greeting')->label('Am eigenen Geburtstag auf der Startseite gratulieren')->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(Settings $settings): void
|
||||
{
|
||||
$state = $this->form->getState();
|
||||
$settings->setMany(['birthdays.scope' => $state['scope'], 'birthdays.days' => (int) $state['days'], 'birthdays.greeting' => (bool) $state['greeting']]);
|
||||
|
||||
Notification::make()->success()->title('Gespeichert')->send();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Birthdays\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Birthdays\BirthdayList;
|
||||
use Inhaus\Plugins\Birthdays\Models\Birthday;
|
||||
|
||||
class BirthdayController extends Controller
|
||||
{
|
||||
public function index(Request $request, BirthdayList $list): Response
|
||||
{
|
||||
return Inertia::render('birthdays::Index', [
|
||||
'birthdays' => $list->upcoming($request->user(), 30),
|
||||
'scope' => BirthdayList::SCOPES[$list->scope()],
|
||||
'registered' => Birthday::query()->where('user_id', $request->user()->id)->exists(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'day' => ['required', 'integer', 'between:1,31'],
|
||||
'month' => ['required', 'integer', 'between:1,12'],
|
||||
], [], ['day' => 'Tag', 'month' => 'Monat']);
|
||||
|
||||
// Gültiger Tag im Monat (29. Februar erlaubt).
|
||||
if (! checkdate($data['month'], $data['day'], 2000)) {
|
||||
throw ValidationException::withMessages(['day' => 'Diesen Tag gibt es im gewählten Monat nicht.']);
|
||||
}
|
||||
|
||||
Birthday::query()->updateOrCreate(['user_id' => $request->user()->id], $data);
|
||||
|
||||
return back()->with('status', 'birthday-saved');
|
||||
}
|
||||
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Birthday::query()->where('user_id', $request->user()->id)->delete();
|
||||
|
||||
return back()->with('status', 'birthday-removed');
|
||||
}
|
||||
}
|
||||
46
plugins-core/birthdays/src/Models/Birthday.php
Normal file
46
plugins-core/birthdays/src/Models/Birthday.php
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Birthdays\Models;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
#[Fillable(['user_id', 'month', 'day'])]
|
||||
class Birthday extends Model
|
||||
{
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nächster Geburtstag ab $from (heute eingeschlossen). Der 29. Februar
|
||||
* wird in Nicht-Schaltjahren am 28. Februar gefeiert.
|
||||
*/
|
||||
public function nextOccurrence(Carbon $from): Carbon
|
||||
{
|
||||
$date = self::inYear($from->year, $this->month, $this->day);
|
||||
|
||||
return $date->lt($from->copy()->startOfDay()) ? self::inYear($from->year + 1, $this->month, $this->day) : $date;
|
||||
}
|
||||
|
||||
public function isOn(Carbon $date): bool
|
||||
{
|
||||
return self::inYear($date->year, $this->month, $this->day)->isSameDay($date);
|
||||
}
|
||||
|
||||
private static function inYear(int $year, int $month, int $day): Carbon
|
||||
{
|
||||
if ($month === 2 && $day === 29 && ! Carbon::create($year)->isLeapYear()) {
|
||||
$day = 28;
|
||||
}
|
||||
|
||||
return Carbon::create($year, $month, $day)->startOfDay();
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,6 @@ const block = computed(() => dateBlock(props.date));
|
|||
<template>
|
||||
<div class="grid w-12 shrink-0 place-items-center rounded-md bg-muted py-1.5 leading-none">
|
||||
<span class="text-xl font-semibold">{{ block.day }}</span>
|
||||
<span class="mt-1 text-[10px] font-semibold tracking-wide text-muted-foreground">{{ block.month }}</span>
|
||||
<span class="mt-1 text-[10px] font-semibold tracking-wide text-accent2-text">{{ block.month }}</span>
|
||||
</div>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class EventsPlugin extends Plugin
|
|||
|
||||
$this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [
|
||||
'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(),
|
||||
], mobileSort: 30);
|
||||
], label: 'Termine', mobileSort: 30);
|
||||
|
||||
$this->app->make(Blocks::class)->add(BlockType::make('events.upcoming', 'Termine', 'calendar-days', 'dynamic', 'events::UpcomingEvents')
|
||||
->description('Die nächsten Termine.')
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
}
|
||||
};
|
||||
13
plugins-core/forms/plugin.json
Normal file
13
plugins-core/forms/plugin.json
Normal 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"
|
||||
}
|
||||
}
|
||||
21
plugins-core/forms/resources/js/blocks/FormBlock.vue
Normal file
21
plugins-core/forms/resources/js/blocks/FormBlock.vue
Normal 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>
|
||||
218
plugins-core/forms/resources/js/components/FormRenderer.vue
Normal file
218
plugins-core/forms/resources/js/components/FormRenderer.vue
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
import { useForm, usePage } from '@inertiajs/vue3';
|
||||
import { CircleCheck, EyeOff, LoaderCircle, Lock, Paperclip, Send, X } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
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 },
|
||||
// Vorschau im Baukasten: nichts wird gesendet.
|
||||
preview: { 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() {
|
||||
if (props.preview) {
|
||||
toast.info('Vorschau – es wird nichts gesendet.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
<div v-else-if="field.locked" class="flex h-9 items-center gap-2 rounded-md border border-input bg-muted/60 px-3 text-sm" :aria-describedby="`${fieldId(field)}-locked`">
|
||||
<Lock class="size-3.5 shrink-0 text-muted-foreground" />
|
||||
<span v-if="data.answers[field.key]" :id="fieldId(field)" class="truncate">{{ data.answers[field.key] }}</span>
|
||||
<span v-else class="text-muted-foreground italic">{{ preview ? 'wird aus dem Profil übernommen' : 'nicht im Profil hinterlegt' }}</span>
|
||||
</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) }}
|
||||
<a v-if="field.locked" href="/profil/bearbeiten" class="font-medium underline">Profil öffnen</a>
|
||||
</p>
|
||||
<p v-else-if="field.locked" :id="`${fieldId(field)}-locked`" class="text-[13px] text-muted-foreground">Aus Ihrem Profil – nicht änderbar.</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>
|
||||
|
|
@ -0,0 +1,179 @@
|
|||
<script setup>
|
||||
import { computed, inject } from 'vue';
|
||||
import { Asterisk, Calendar, ChevronDown, Copy, GitBranch, GripVertical, Lock, Paperclip, Plus, Trash2, X } from '@lucide/vue';
|
||||
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
|
||||
|
||||
/**
|
||||
* Ein Feld im Baukasten – dargestellt wie im fertigen Formular.
|
||||
* Bezeichnung, Hinweis und Auswahlmöglichkeiten werden direkt hier bearbeitet.
|
||||
*/
|
||||
const props = defineProps({
|
||||
field: { type: Object, required: true },
|
||||
index: { type: Number, required: true },
|
||||
});
|
||||
|
||||
const builder = inject('forms:builder');
|
||||
|
||||
const selected = computed(() => builder.selectedId.value === props.field._id);
|
||||
const hasError = computed(() => builder.errorIndex.value === props.index);
|
||||
const isLayout = computed(() => layoutTypes.includes(props.field.type));
|
||||
const d = computed(() => props.field.data);
|
||||
|
||||
const conditionText = computed(() => {
|
||||
if (!d.value.condition_field) return null;
|
||||
|
||||
const other = builder.fields.find((f) => f.data.key === d.value.condition_field);
|
||||
const label = other?.data.label ?? d.value.condition_field;
|
||||
const op = operators[d.value.condition_operator ?? 'equals'];
|
||||
|
||||
return ['filled', 'empty'].includes(d.value.condition_operator) ? `${label} ${op}` : `${label} ${op} „${d.value.condition_value ?? ''}“`;
|
||||
});
|
||||
|
||||
function addOption() {
|
||||
d.value.options = [...(d.value.options ?? []), `Option ${(d.value.options?.length ?? 0) + 1}`];
|
||||
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${d.value.options.length - 1}"]`)?.select());
|
||||
}
|
||||
|
||||
function removeOption(i) {
|
||||
d.value.options = d.value.options.filter((_, index) => index !== i);
|
||||
}
|
||||
|
||||
function optionKeydown(event, i) {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
d.value.options.splice(i + 1, 0, '');
|
||||
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${i + 1}"]`)?.focus());
|
||||
} else if (event.key === 'Backspace' && d.value.options[i] === '' && d.value.options.length > 1) {
|
||||
event.preventDefault();
|
||||
removeOption(i);
|
||||
requestAnimationFrame(() => document.querySelector(`[data-option="${props.field._id}-${Math.max(0, i - 1)}"]`)?.focus());
|
||||
}
|
||||
}
|
||||
|
||||
// Unauffällige Eingabefelder, die wie normaler Text aussehen
|
||||
const inline = 'w-full min-w-0 rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
|
||||
// Bezeichnung nur so breit wie ihr Text – das Pflicht-Sternchen steht direkt dahinter.
|
||||
const labelInput = 'field-sizing-content min-w-6 max-w-full rounded-sm bg-transparent outline-none placeholder:text-muted-foreground/60 focus:bg-brand-soft/40';
|
||||
const fake = 'flex h-9 w-full items-center rounded-md border border-input bg-card px-3 text-sm text-muted-foreground shadow-xs';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="group relative rounded-md p-3 outline-offset-2 transition-[outline-color]"
|
||||
:class="[
|
||||
field.data.width === 'half' && !isLayout ? '' : '@xl:col-span-2',
|
||||
selected ? 'bg-brand-soft/30 outline-2 outline-brand-500' : hasError ? 'outline-2 outline-destructive' : 'outline-1 outline-transparent hover:outline-brand-300',
|
||||
]"
|
||||
:data-field-id="field._id"
|
||||
@click.stop="builder.select(field._id)"
|
||||
>
|
||||
<!-- Werkzeugleiste -->
|
||||
<div class="absolute -top-3.5 right-2 z-10 items-center gap-0.5 rounded-md border bg-card px-1 py-0.5 text-xs shadow-sm" :class="selected ? 'flex' : 'hidden group-hover:flex'" @click.stop>
|
||||
<span class="fb-handle flex cursor-grab items-center gap-1 px-1 py-0.5 font-medium text-muted-foreground active:cursor-grabbing" title="Ziehen zum Verschieben">
|
||||
<GripVertical class="size-3.5" />
|
||||
<component :is="fieldTypes[field.type].icon" class="size-3.5" />
|
||||
{{ builder.types[field.type] }}
|
||||
</span>
|
||||
<template v-if="!isLayout">
|
||||
<span class="mx-0.5 h-4 w-px bg-border" />
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-6 items-center gap-1 rounded px-1.5"
|
||||
:class="d.required ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
|
||||
:aria-pressed="!!d.required"
|
||||
title="Pflichtfeld"
|
||||
@click="d.required = !d.required"
|
||||
>
|
||||
<Asterisk class="size-3.5" /> Pflicht
|
||||
</button>
|
||||
<button type="button" class="h-6 rounded px-1.5 text-muted-foreground hover:bg-accent" :title="d.width === 'half' ? 'Volle Breite' : 'Halbe Breite'" @click="d.width = d.width === 'half' ? 'full' : 'half'">
|
||||
{{ d.width === 'half' ? '½' : '1/1' }}
|
||||
</button>
|
||||
</template>
|
||||
<span class="mx-0.5 h-4 w-px bg-border" />
|
||||
<button type="button" class="grid size-6 place-items-center rounded hover:bg-accent" title="Duplizieren" @click="builder.duplicate(field._id)"><Copy class="size-3.5" /></button>
|
||||
<button type="button" class="grid size-6 place-items-center rounded text-destructive hover:bg-destructive/10" title="Entfernen" @click="builder.remove(field._id)"><Trash2 class="size-3.5" /></button>
|
||||
</div>
|
||||
|
||||
<p v-if="d.prefill && !d.locked && !isLayout" class="mb-1.5 mr-1 inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground">
|
||||
Vorbelegt: {{ builder.prefillOptions.find((o) => o.value === d.prefill)?.label ?? d.prefill }}
|
||||
</p>
|
||||
<p v-if="conditionText" class="mb-1.5 inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-[11px] text-amber-800 dark:bg-amber-900/50 dark:text-amber-200">
|
||||
<GitBranch class="size-3" /> Nur wenn {{ conditionText }}
|
||||
</p>
|
||||
|
||||
<!-- Gestaltung -->
|
||||
<input v-if="field.type === 'heading'" v-model="d.text" :class="[inline, 'text-lg font-semibold']" placeholder="Zwischenüberschrift" aria-label="Zwischenüberschrift" />
|
||||
<textarea
|
||||
v-else-if="field.type === 'paragraph'"
|
||||
v-model="d.text"
|
||||
:class="[inline, 'field-sizing-content resize-none text-sm leading-relaxed text-muted-foreground']"
|
||||
rows="1"
|
||||
placeholder="Hinweistext"
|
||||
aria-label="Hinweistext"
|
||||
/>
|
||||
|
||||
<!-- Kontrollkästchen: Bezeichnung neben dem Kasten -->
|
||||
<div v-else-if="field.type === 'checkbox'" class="flex items-start gap-2.5">
|
||||
<span class="mt-0.5 size-4 shrink-0 rounded-[4px] border border-input bg-card" />
|
||||
<input v-model="d.label" :class="[labelInput, 'text-sm']" placeholder="Text neben dem Kästchen" aria-label="Bezeichnung" />
|
||||
<span v-if="d.required" class="text-destructive">*</span>
|
||||
</div>
|
||||
|
||||
<!-- Eingabefelder -->
|
||||
<div v-else class="grid gap-1.5">
|
||||
<div class="flex items-center gap-0.5 text-[13px] font-medium">
|
||||
<input v-model="d.label" :class="labelInput" placeholder="Bezeichnung" aria-label="Bezeichnung" />
|
||||
<span v-if="d.required" class="text-destructive">*</span>
|
||||
</div>
|
||||
|
||||
<div v-if="field.type === 'textarea'" class="rounded-md border border-input bg-card shadow-xs" :style="{ height: `${(d.rows ?? 4) * 1.5 + 1}rem` }">
|
||||
<input v-model="d.placeholder" class="w-full bg-transparent px-3 py-2 text-sm outline-none placeholder:text-muted-foreground/50" placeholder="Platzhalter (optional)" aria-label="Platzhalter" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="field.type === 'select'" class="grid gap-1.5">
|
||||
<div :class="[fake, 'justify-between']">Bitte wählen … <ChevronDown class="size-4" /></div>
|
||||
<div v-if="selected" class="grid gap-1 rounded-md border border-dashed p-2">
|
||||
<p class="text-xs text-muted-foreground">Auswahlmöglichkeiten</p>
|
||||
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2">
|
||||
<span class="w-5 text-right text-xs text-muted-foreground">{{ i + 1 }}.</span>
|
||||
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" />
|
||||
<button type="button" class="grid size-6 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
|
||||
</div>
|
||||
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="optionTypes.includes(field.type)" class="grid gap-1.5">
|
||||
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-2.5">
|
||||
<span class="size-4 shrink-0 border border-input bg-card" :class="field.type === 'radio' ? 'rounded-full' : 'rounded-[4px]'" />
|
||||
<input v-model="d.options[i]" :data-option="`${field._id}-${i}`" :class="[inline, 'text-sm']" placeholder="Auswahlmöglichkeit" @keydown="optionKeydown($event, i)" @focus="builder.select(field._id)" />
|
||||
<button v-if="selected" type="button" class="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent" title="Entfernen" @click.stop="removeOption(i)"><X class="size-3.5" /></button>
|
||||
</div>
|
||||
<button v-if="selected" type="button" class="ml-6.5 inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click.stop="addOption"><Plus class="size-3.5" /> Auswahlmöglichkeit</button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="field.type === 'file'" class="flex h-10 items-center justify-center gap-2 rounded-md border border-dashed text-sm text-muted-foreground">
|
||||
<Paperclip class="size-4" /> {{ d.multiple ? 'Dateien auswählen' : 'Datei auswählen' }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="field.type === 'date'" :class="[fake, 'justify-between']">TT.MM.JJJJ <Calendar class="size-4" /></div>
|
||||
|
||||
<div v-else-if="d.locked && d.prefill" class="flex h-9 items-center gap-2 rounded-md border border-input bg-muted/60 px-3 text-sm text-muted-foreground">
|
||||
<Lock class="size-3.5" /> Aus dem Profil: {{ builder.prefillOptions.find((o) => o.value === d.prefill)?.label ?? d.prefill }} – nicht änderbar
|
||||
</div>
|
||||
|
||||
<div v-else class="rounded-md border border-input bg-card shadow-xs">
|
||||
<input v-model="d.placeholder" class="h-9 w-full bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground/50" :placeholder="field.type === 'text' ? 'Platzhalter (optional)' : ''" :disabled="field.type !== 'text'" aria-label="Platzhalter" />
|
||||
</div>
|
||||
|
||||
<input
|
||||
v-if="selected || d.help"
|
||||
v-model="d.help"
|
||||
:class="[inline, 'text-[13px] text-muted-foreground']"
|
||||
placeholder="Hinweis unter dem Feld hinzufügen …"
|
||||
aria-label="Hinweis"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,204 @@
|
|||
<script setup>
|
||||
import { computed, inject } from 'vue';
|
||||
import { ArrowDown, ArrowUp, Plus, X } from '@lucide/vue';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import NativeSelect from '@/components/NativeSelect.vue';
|
||||
import { fieldTypes, layoutTypes, operators, optionTypes } from '../../lib/fields';
|
||||
|
||||
const props = defineProps({
|
||||
field: { type: Object, required: true },
|
||||
});
|
||||
|
||||
const builder = inject('forms:builder');
|
||||
const d = computed(() => props.field.data);
|
||||
const isLayout = computed(() => layoutTypes.includes(props.field.type));
|
||||
|
||||
// Bedingung: nur andere Eingabefelder, die davor stehen
|
||||
const conditionFields = computed(() => {
|
||||
const index = builder.fields.findIndex((f) => f._id === props.field._id);
|
||||
|
||||
return builder.fields.slice(0, index)
|
||||
.filter((f) => !layoutTypes.includes(f.type))
|
||||
.map((f) => ({ value: f.data.key, label: f.data.label || f.data.key }));
|
||||
});
|
||||
|
||||
const conditionTarget = computed(() => builder.fields.find((f) => f.data.key === d.value.condition_field));
|
||||
const valueOptions = computed(() => {
|
||||
const target = conditionTarget.value;
|
||||
|
||||
if (!target) return null;
|
||||
if (target.type === 'checkbox') return [{ value: '1', label: 'angehakt' }];
|
||||
if (optionTypes.includes(target.type)) return (target.data.options ?? []).filter(Boolean).map((o) => ({ value: o, label: o }));
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
function setCondition(key) {
|
||||
if (!key) {
|
||||
delete d.value.condition_field;
|
||||
delete d.value.condition_operator;
|
||||
delete d.value.condition_value;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
d.value.condition_field = key;
|
||||
d.value.condition_operator ??= 'equals';
|
||||
}
|
||||
|
||||
function moveOption(i, dir) {
|
||||
const options = [...d.value.options];
|
||||
const j = i + dir;
|
||||
|
||||
if (j < 0 || j >= options.length) return;
|
||||
|
||||
[options[i], options[j]] = [options[j], options[i]];
|
||||
d.value.options = options;
|
||||
}
|
||||
|
||||
const number = (key) => ({
|
||||
get: () => d.value[key] ?? '',
|
||||
set: (value) => (value === '' || value === null ? delete d.value[key] : (d.value[key] = Number(value))),
|
||||
});
|
||||
const min = computed(number('min'));
|
||||
const max = computed(number('max'));
|
||||
const rows = computed(number('rows'));
|
||||
const maxSize = computed(number('max_size'));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-5">
|
||||
<header class="flex items-center gap-3">
|
||||
<span class="grid size-9 shrink-0 place-items-center rounded-md bg-brand-soft text-brand-text"><component :is="fieldTypes[field.type].icon" class="size-4.5" /></span>
|
||||
<div class="min-w-0">
|
||||
<h2 class="font-semibold">{{ builder.types[field.type] }}</h2>
|
||||
<p class="text-xs text-muted-foreground">Bezeichnung und Auswahlmöglichkeiten bearbeiten Sie direkt im Formular.</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<template v-if="isLayout">
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Text</span>
|
||||
<Textarea v-if="field.type === 'paragraph'" v-model="d.text" rows="4" maxlength="3000" />
|
||||
<Input v-else v-model="d.text" maxlength="200" />
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Bezeichnung</span>
|
||||
<Input v-model="d.label" maxlength="200" />
|
||||
</label>
|
||||
|
||||
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
|
||||
Pflichtfeld
|
||||
<Switch :model-value="!!d.required" @update:model-value="(v) => (d.required = v)" />
|
||||
</label>
|
||||
|
||||
<div class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Breite</span>
|
||||
<div class="grid grid-cols-2 rounded-md border p-0.5 text-[13px]" role="group">
|
||||
<button
|
||||
v-for="option in [{ value: 'full', label: 'Volle Breite' }, { value: 'half', label: 'Halbe Breite' }]"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="rounded py-1.5"
|
||||
:class="(d.width ?? 'full') === option.value ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'"
|
||||
:aria-pressed="(d.width ?? 'full') === option.value"
|
||||
@click="d.width = option.value"
|
||||
>
|
||||
{{ option.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Hinweis unter dem Feld</span>
|
||||
<Input v-model="d.help" maxlength="300" />
|
||||
</label>
|
||||
|
||||
<label v-if="['text', 'email', 'phone'].includes(field.type)" class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Vorbelegen mit</span>
|
||||
<NativeSelect :model-value="d.prefill ?? null" :options="builder.prefillOptions" placeholder="– nicht vorbelegen –" @update:model-value="(v) => (v ? (d.prefill = v) : (delete d.prefill, delete d.locked))" />
|
||||
</label>
|
||||
<div v-if="['text', 'email', 'phone'].includes(field.type) && d.prefill" class="grid gap-1.5 rounded-md border p-3">
|
||||
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
|
||||
Nicht änderbar
|
||||
<Switch :model-value="!!d.locked" @update:model-value="(v) => (v ? (d.locked = true) : delete d.locked)" />
|
||||
</label>
|
||||
<span class="text-xs text-muted-foreground">
|
||||
{{ d.locked
|
||||
? 'Das Feld zeigt den Wert aus dem Profil und kann nicht geändert werden. Beim Absenden wird immer der Profilwert gespeichert.'
|
||||
: 'Das Feld ist mit dem Profilwert vorausgefüllt, kann aber geändert werden.' }}
|
||||
</span>
|
||||
<span v-if="d.locked && builder.anonymous" class="text-xs text-amber-700 dark:text-amber-300">Achtung: Das Formular ist anonym – diese Profilangabe wird trotzdem mit der Einsendung gespeichert.</span>
|
||||
</div>
|
||||
|
||||
<div v-if="['text', 'textarea', 'number', 'checkboxes'].includes(field.type)" class="grid grid-cols-2 gap-3">
|
||||
<label v-if="['number', 'checkboxes'].includes(field.type)" class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">{{ field.type === 'checkboxes' ? 'Mindestens wählen' : 'Mindestens' }}</span>
|
||||
<Input v-model="min" type="number" />
|
||||
</label>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">{{ { text: 'Höchstlänge', textarea: 'Höchstlänge', number: 'Höchstens', checkboxes: 'Höchstens wählen' }[field.type] }}</span>
|
||||
<Input v-model="max" type="number" min="1" />
|
||||
</label>
|
||||
<label v-if="field.type === 'textarea'" class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Zeilen</span>
|
||||
<Input v-model="rows" type="number" min="2" max="20" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<template v-if="field.type === 'file'">
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Erlaubte Dateien</span>
|
||||
<NativeSelect v-model="d.accept" :options="[{ value: 'documents', label: 'Dokumente (PDF, Office …)' }, { value: 'images', label: 'Bilder' }, { value: 'any', label: 'Dokumente und Bilder' }]" />
|
||||
</label>
|
||||
<label class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Höchstgröße in MB</span>
|
||||
<Input v-model="maxSize" type="number" min="1" max="50" />
|
||||
</label>
|
||||
<label class="flex items-center justify-between gap-3 text-[13px] font-medium">
|
||||
Mehrere Dateien (bis 10)
|
||||
<Switch :model-value="!!d.multiple" @update:model-value="(v) => (d.multiple = v)" />
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<div v-if="optionTypes.includes(field.type)" class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Auswahlmöglichkeiten</span>
|
||||
<div v-for="(option, i) in d.options" :key="i" class="flex items-center gap-1">
|
||||
<Input v-model="d.options[i]" class="h-8" maxlength="200" />
|
||||
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach oben" @click="moveOption(i, -1)"><ArrowUp class="size-3.5" /></button>
|
||||
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Nach unten" @click="moveOption(i, 1)"><ArrowDown class="size-3.5" /></button>
|
||||
<button type="button" class="grid size-7 shrink-0 place-items-center rounded hover:bg-accent" title="Entfernen" @click="d.options = d.options.filter((_, j) => j !== i)"><X class="size-3.5" /></button>
|
||||
</div>
|
||||
<button type="button" class="inline-flex items-center gap-1 justify-self-start text-[13px] font-medium text-brand-text hover:underline" @click="d.options = [...(d.options ?? []), '']"><Plus class="size-3.5" /> Hinzufügen</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<details class="rounded-md border" :open="!!d.condition_field">
|
||||
<summary class="cursor-pointer px-3 py-2 text-[13px] font-medium">Nur anzeigen, wenn …</summary>
|
||||
<div class="grid gap-3 border-t px-3 py-3">
|
||||
<p v-if="!conditionFields.length" class="text-xs text-muted-foreground">Bedingungen beziehen sich auf Felder weiter oben im Formular.</p>
|
||||
<template v-else>
|
||||
<NativeSelect :model-value="d.condition_field ?? null" :options="conditionFields" placeholder="– immer anzeigen –" aria-label="Feld" @update:model-value="setCondition" />
|
||||
<template v-if="d.condition_field">
|
||||
<NativeSelect v-model="d.condition_operator" :options="Object.entries(operators).map(([value, label]) => ({ value, label }))" aria-label="Bedingung" />
|
||||
<template v-if="!['filled', 'empty'].includes(d.condition_operator)">
|
||||
<NativeSelect v-if="valueOptions" v-model="d.condition_value" :options="valueOptions" placeholder="Wert wählen …" aria-label="Wert" />
|
||||
<Input v-else v-model="d.condition_value" placeholder="Wert" aria-label="Wert" />
|
||||
</template>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<label v-if="!isLayout" class="grid gap-1.5">
|
||||
<span class="text-[13px] font-medium">Technischer Schlüssel</span>
|
||||
<Input :model-value="d.key" disabled class="font-mono text-xs" />
|
||||
<span class="text-xs text-muted-foreground">Für Export und Bedingungen. Wird aus der Bezeichnung gebildet und bleibt danach gleich.</span>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
33
plugins-core/forms/resources/js/editorial/EditorialForms.vue
Normal file
33
plugins-core/forms/resources/js/editorial/EditorialForms.vue
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
<script setup>
|
||||
import { Link } from '@inertiajs/vue3';
|
||||
import { Download, PencilLine, Plus, TableProperties } from '@lucide/vue';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import Panel from '@/components/Panel.vue';
|
||||
|
||||
defineProps({
|
||||
forms: { type: Array, required: true },
|
||||
createUrl: { type: String, default: null },
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Panel title="Formulare">
|
||||
<template #actions>
|
||||
<Button v-if="createUrl" size="sm" variant="outline" as-child><a :href="createUrl"><Plus /> Neues Formular</a></Button>
|
||||
</template>
|
||||
<ul v-if="forms.length" class="-mx-5 divide-y border-t">
|
||||
<li v-for="form in forms" :key="form.id" class="flex items-center gap-3 px-5 py-2.5">
|
||||
<div class="min-w-0 flex-1">
|
||||
<Link :href="form.url" class="block truncate text-sm font-medium hover:underline">{{ form.title }}</Link>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
{{ form.open ? 'offen' : 'geschlossen' }} · {{ form.submissions }} Einsendungen<template v-if="form.unread">, <span class="font-medium text-brand-text">{{ form.unread }} neu</span></template>
|
||||
</p>
|
||||
</div>
|
||||
<Button v-if="form.builder_url" size="icon" variant="ghost" as-child title="Felder bearbeiten"><Link :href="form.builder_url"><PencilLine /></Link></Button>
|
||||
<Button v-if="form.results_url" size="icon" variant="ghost" as-child title="Ergebnisse"><a :href="form.results_url"><TableProperties /></a></Button>
|
||||
<Button v-if="form.csv_url" size="icon" variant="ghost" as-child title="Ergebnisse als CSV herunterladen"><a :href="form.csv_url"><Download /></a></Button>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="text-sm text-muted-foreground">Noch keine Formulare.</p>
|
||||
</Panel>
|
||||
</template>
|
||||
111
plugins-core/forms/resources/js/lib/fields.js
Normal file
111
plugins-core/forms/resources/js/lib/fields.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import {
|
||||
AtSign,
|
||||
Calendar,
|
||||
CheckSquare,
|
||||
ChevronsUpDown,
|
||||
CircleDot,
|
||||
Hash,
|
||||
Heading,
|
||||
Info,
|
||||
ListChecks,
|
||||
Paperclip,
|
||||
Phone,
|
||||
Text,
|
||||
TextCursorInput,
|
||||
} from '@lucide/vue';
|
||||
|
||||
/**
|
||||
* Feldtypen des Formularbaukastens – passend zu Inhaus\Plugins\Forms\FormFields.
|
||||
*/
|
||||
export const fieldTypes = {
|
||||
text: { icon: TextCursorInput, group: 'Eingabe', defaults: { label: 'Textzeile', width: 'full' } },
|
||||
textarea: { icon: Text, group: 'Eingabe', defaults: { label: 'Mehrzeiliger Text', rows: 4, width: 'full' } },
|
||||
email: { icon: AtSign, group: 'Eingabe', defaults: { label: 'E-Mail-Adresse', width: 'half' } },
|
||||
phone: { icon: Phone, group: 'Eingabe', defaults: { label: 'Telefonnummer', width: 'half' } },
|
||||
number: { icon: Hash, group: 'Eingabe', defaults: { label: 'Zahl', width: 'half' } },
|
||||
date: { icon: Calendar, group: 'Eingabe', defaults: { label: 'Datum', width: 'half' } },
|
||||
select: { icon: ChevronsUpDown, group: 'Auswahl', defaults: { label: 'Auswahlliste', options: ['Option 1', 'Option 2'], width: 'full' } },
|
||||
radio: { icon: CircleDot, group: 'Auswahl', defaults: { label: 'Einfachauswahl', options: ['Ja', 'Nein'], width: 'full' } },
|
||||
checkboxes: { icon: ListChecks, group: 'Auswahl', defaults: { label: 'Mehrfachauswahl', options: ['Option 1', 'Option 2', 'Option 3'], width: 'full' } },
|
||||
checkbox: { icon: CheckSquare, group: 'Auswahl', defaults: { label: 'Ich stimme zu.', width: 'full' } },
|
||||
file: { icon: Paperclip, group: 'Sonstiges', defaults: { label: 'Datei', accept: 'any', max_size: 10, width: 'full' } },
|
||||
heading: { icon: Heading, group: 'Gestaltung', defaults: { text: 'Zwischenüberschrift' } },
|
||||
paragraph: { icon: Info, group: 'Gestaltung', defaults: { text: 'Hinweistext' } },
|
||||
};
|
||||
|
||||
export const layoutTypes = ['heading', 'paragraph'];
|
||||
export const optionTypes = ['select', 'radio', 'checkboxes'];
|
||||
|
||||
/** Wie Str::slug($label, '_', 'de') auf dem Server. */
|
||||
export function slugify(text) {
|
||||
return String(text ?? '')
|
||||
.toLowerCase()
|
||||
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
|
||||
.normalize('NFKD').replace(/[̀-ͯ]/g, '')
|
||||
.replace(/@/g, '_at_')
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
.slice(0, 60);
|
||||
}
|
||||
|
||||
export function uid() {
|
||||
return Math.random().toString(36).slice(2, 10);
|
||||
}
|
||||
|
||||
/** Schlüssel für neue Felder aus der Bezeichnung ableiten, eindeutig im Formular. */
|
||||
export function assignKeys(fields) {
|
||||
const used = new Set(fields.filter((f) => !f._new && f.data.key).map((f) => f.data.key));
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field._new) continue;
|
||||
|
||||
const base = slugify(field.data.label || field.data.text || field.type) || field.type;
|
||||
let key = base;
|
||||
|
||||
for (let i = 2; used.has(key); i++) key = `${base}_${i}`;
|
||||
|
||||
field.data.key = key;
|
||||
used.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function createField(type) {
|
||||
return { _id: uid(), _new: true, type, data: structuredClone(fieldTypes[type].defaults) };
|
||||
}
|
||||
|
||||
/** Darstellung für die Vorschau – wie FormFields::forFrontend(). */
|
||||
export function toFrontend(fields) {
|
||||
const accept = {
|
||||
documents: '.pdf,.doc,.docx,.xls,.xlsx,.odt,.ods,.ppt,.pptx,.txt,.csv,.rtf',
|
||||
images: '.jpg,.jpeg,.png,.webp,.gif,.heic',
|
||||
any: '',
|
||||
};
|
||||
|
||||
return fields.map(({ type, data }) => ({
|
||||
type,
|
||||
key: data.key,
|
||||
label: data.label,
|
||||
text: data.text,
|
||||
help: data.help,
|
||||
placeholder: data.placeholder,
|
||||
required: !!data.required,
|
||||
options: (data.options ?? []).filter((o) => o !== ''),
|
||||
width: data.width ?? 'full',
|
||||
min: data.min,
|
||||
max: data.max,
|
||||
rows: data.rows,
|
||||
multiple: !!data.multiple,
|
||||
accept: accept[data.accept ?? 'any'] || undefined,
|
||||
max_size: data.max_size,
|
||||
locked: !!(data.locked && data.prefill && ['text', 'email', 'phone'].includes(type)),
|
||||
condition: data.condition_field ? { field: data.condition_field, operator: data.condition_operator ?? 'equals', value: String(data.condition_value ?? '') } : null,
|
||||
}));
|
||||
}
|
||||
|
||||
export const operators = {
|
||||
equals: 'ist gleich',
|
||||
not_equals: 'ist nicht',
|
||||
contains: 'enthält',
|
||||
filled: 'ist ausgefüllt',
|
||||
empty: 'ist leer',
|
||||
};
|
||||
326
plugins-core/forms/resources/js/pages/Builder.vue
Normal file
326
plugins-core/forms/resources/js/pages/Builder.vue
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
<script setup>
|
||||
import { computed, onBeforeUnmount, onMounted, provide, reactive, ref, watch } from 'vue';
|
||||
import { Head, Link, router } from '@inertiajs/vue3';
|
||||
import { VueDraggable } from 'vue-draggable-plus';
|
||||
import { ArrowLeft, CircleCheck, Eye, LoaderCircle, PencilLine, Plus, Save, Settings2, TableProperties } from '@lucide/vue';
|
||||
import { toast } from 'vue-sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { http } from '@/lib/http';
|
||||
import BuilderField from '../components/builder/BuilderField.vue';
|
||||
import FieldSettings from '../components/builder/FieldSettings.vue';
|
||||
import FormRenderer from '../components/FormRenderer.vue';
|
||||
import { assignKeys, createField, fieldTypes, toFrontend, uid } from '../lib/fields';
|
||||
|
||||
const props = defineProps({
|
||||
form: { type: Object, required: true },
|
||||
types: { type: Object, required: true },
|
||||
prefillOptions: { type: Array, required: true },
|
||||
settingsUrl: { type: String, required: true },
|
||||
resultsUrl: { type: String, default: null },
|
||||
});
|
||||
|
||||
const state = reactive({
|
||||
title: props.form.title,
|
||||
description: props.form.description ?? '',
|
||||
fields: props.form.fields.map((field) => ({ _id: uid(), type: field.type, data: { ...field.data } })),
|
||||
});
|
||||
|
||||
const selectedId = ref(null);
|
||||
const errorIndex = ref(null);
|
||||
const mode = ref('edit');
|
||||
const saving = ref(false);
|
||||
const saved = ref(JSON.stringify(state));
|
||||
const dirty = computed(() => JSON.stringify(state) !== saved.value);
|
||||
const selected = computed(() => state.fields.find((f) => f._id === selectedId.value) ?? null);
|
||||
|
||||
// Schlüssel neuer Felder folgen der Bezeichnung, bis gespeichert wurde.
|
||||
watch(() => state.fields.map((f) => [f._new, f.data.label, f.data.text]), () => assignKeys(state.fields), { deep: true, immediate: true });
|
||||
|
||||
function select(id) {
|
||||
selectedId.value = id;
|
||||
}
|
||||
|
||||
function add(type, index = null) {
|
||||
const field = createField(type);
|
||||
const selectedIndex = state.fields.findIndex((f) => f._id === selectedId.value);
|
||||
const at = index ?? (selectedIndex >= 0 ? selectedIndex + 1 : state.fields.length);
|
||||
|
||||
state.fields.splice(at, 0, field);
|
||||
select(field._id);
|
||||
requestAnimationFrame(() => {
|
||||
const el = document.querySelector(`[data-field-id="${field._id}"]`);
|
||||
el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
el?.querySelector('input, textarea')?.select();
|
||||
});
|
||||
}
|
||||
|
||||
function remove(id) {
|
||||
const field = state.fields.find((f) => f._id === id);
|
||||
const dependents = state.fields.filter((f) => f.data.condition_field && f.data.condition_field === field?.data.key);
|
||||
|
||||
if (dependents.length && !window.confirm(`${dependents.length} Feld(er) hängen von diesem Feld ab. Die Bedingung wird dort entfernt. Trotzdem löschen?`)) return;
|
||||
|
||||
dependents.forEach((f) => {
|
||||
delete f.data.condition_field;
|
||||
delete f.data.condition_operator;
|
||||
delete f.data.condition_value;
|
||||
});
|
||||
state.fields = state.fields.filter((f) => f._id !== id);
|
||||
|
||||
if (selectedId.value === id) select(null);
|
||||
}
|
||||
|
||||
function duplicate(id) {
|
||||
const index = state.fields.findIndex((f) => f._id === id);
|
||||
const copy = { _id: uid(), _new: true, type: state.fields[index].type, data: structuredClone({ ...state.fields[index].data, key: undefined }) };
|
||||
|
||||
state.fields.splice(index + 1, 0, copy);
|
||||
select(copy._id);
|
||||
}
|
||||
|
||||
// „fields“ wird beim Löschen und Verschieben neu zugewiesen – daher als Getter.
|
||||
provide('forms:builder', {
|
||||
get fields() {
|
||||
return state.fields;
|
||||
},
|
||||
types: props.types,
|
||||
prefillOptions: props.prefillOptions,
|
||||
anonymous: props.form.anonymous,
|
||||
selectedId,
|
||||
errorIndex,
|
||||
select,
|
||||
remove,
|
||||
duplicate,
|
||||
});
|
||||
|
||||
async function save() {
|
||||
if (saving.value) return;
|
||||
|
||||
saving.value = true;
|
||||
errorIndex.value = null;
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
title: state.title,
|
||||
description: state.description,
|
||||
fields: state.fields.map(({ type, data }) => ({ type, data })),
|
||||
};
|
||||
const result = await http.put(`/redaktion/formulare/${props.form.id}`, payload);
|
||||
|
||||
// Gespeicherte Schlüssel übernehmen; die Felder gelten nun als bestehend.
|
||||
result.fields.forEach((field, i) => {
|
||||
if (state.fields[i]) {
|
||||
state.fields[i].data.key = field.data.key;
|
||||
delete state.fields[i]._new;
|
||||
}
|
||||
});
|
||||
saved.value = JSON.stringify(state);
|
||||
toast.success('Formular gespeichert');
|
||||
} catch (error) {
|
||||
const [key, message] = Object.entries(error.fieldErrors ?? {})[0] ?? [];
|
||||
const match = key?.match(/^fields\.(\d+)/);
|
||||
|
||||
if (match) {
|
||||
errorIndex.value = Number(match[1]);
|
||||
select(state.fields[errorIndex.value]?._id);
|
||||
document.querySelector(`[data-field-id="${selectedId.value}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
}
|
||||
|
||||
toast.error(message ?? error.message);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function onKeydown(event) {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault();
|
||||
save();
|
||||
} else if (event.key === 'Escape') {
|
||||
select(null);
|
||||
}
|
||||
}
|
||||
|
||||
function beforeUnload(event) {
|
||||
if (dirty.value) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
}
|
||||
|
||||
let removeRouterGuard;
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('keydown', onKeydown);
|
||||
window.addEventListener('beforeunload', beforeUnload);
|
||||
removeRouterGuard = router.on('before', (event) => {
|
||||
if (dirty.value && event.detail.visit.method === 'get' && !window.confirm('Es gibt ungespeicherte Änderungen. Seite trotzdem verlassen?')) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('keydown', onKeydown);
|
||||
window.removeEventListener('beforeunload', beforeUnload);
|
||||
removeRouterGuard?.();
|
||||
});
|
||||
|
||||
// Vorschau: echtes Formular mit Bedingungen, ohne Absenden
|
||||
const previewForm = computed(() => ({
|
||||
id: -1,
|
||||
title: state.title,
|
||||
description: state.description,
|
||||
url: '#',
|
||||
fields: toFrontend(state.fields),
|
||||
prefill: {},
|
||||
submit_label: 'Absenden',
|
||||
confirmation: '',
|
||||
open: true,
|
||||
}));
|
||||
|
||||
const palette = computed(() => {
|
||||
const groups = {};
|
||||
|
||||
for (const [type, meta] of Object.entries(fieldTypes)) {
|
||||
(groups[meta.group] ??= []).push({ type, label: props.types[type], icon: meta.icon });
|
||||
}
|
||||
|
||||
return Object.entries(groups);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Head :title="`Formular: ${state.title}`" />
|
||||
|
||||
<div class="flex h-dvh flex-col bg-background">
|
||||
<header class="z-30 flex h-14 shrink-0 items-center gap-2 border-b bg-card px-2 sm:px-3">
|
||||
<Link href="/redaktion" class="grid size-9 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground" title="Zurück zur Redaktion">
|
||||
<ArrowLeft class="size-5" />
|
||||
</Link>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="truncate text-sm font-semibold">{{ state.title || 'Ohne Titel' }}</p>
|
||||
<p class="flex items-center gap-1 truncate text-xs text-muted-foreground" aria-live="polite">
|
||||
<template v-if="saving"><LoaderCircle class="size-3 animate-spin" /> Speichert …</template>
|
||||
<template v-else-if="dirty">Ungespeicherte Änderungen</template>
|
||||
<template v-else><CircleCheck class="size-3" /> Gespeichert · {{ form.submissions }} Einsendungen</template>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex rounded-md border p-0.5 text-sm" role="group" aria-label="Ansicht">
|
||||
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'edit' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'edit'">
|
||||
<PencilLine class="size-4" /> <span class="hidden sm:inline">Bearbeiten</span>
|
||||
</button>
|
||||
<button type="button" class="flex items-center gap-1.5 rounded px-2.5 py-1" :class="mode === 'preview' ? 'bg-brand-soft font-medium text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent'" @click="mode = 'preview'; select(null)">
|
||||
<Eye class="size-4" /> <span class="hidden sm:inline">Vorschau</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" size="icon" as-child title="Einstellungen, Benachrichtigung und Zugriff"><a :href="settingsUrl"><Settings2 /></a></Button>
|
||||
<Button v-if="resultsUrl" variant="ghost" size="icon" as-child title="Ergebnisse"><a :href="resultsUrl"><TableProperties /></a></Button>
|
||||
<Button :disabled="saving || !dirty" @click="save"><Save /> <span class="hidden sm:inline">Speichern</span></Button>
|
||||
</header>
|
||||
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<main class="min-w-0 flex-1 overflow-y-auto" @click="select(null)">
|
||||
<div class="mx-auto max-w-3xl px-4 py-8">
|
||||
<p v-if="form.submissions && mode === 'edit'" class="mb-4 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-[13px] text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100">
|
||||
Es gibt bereits {{ form.submissions }} Einsendungen. Umbenennen ist unproblematisch – gelöschte Felder fehlen nur in neuen Einsendungen.
|
||||
</p>
|
||||
|
||||
<template v-if="mode === 'edit'">
|
||||
<input v-model="state.title" class="w-full rounded-sm bg-transparent text-3xl font-semibold tracking-tight outline-none focus:bg-brand-soft/40" placeholder="Titel des Formulars" aria-label="Titel" maxlength="200" @click.stop />
|
||||
<textarea
|
||||
v-model="state.description"
|
||||
class="field-sizing-content mt-3 w-full resize-none rounded-sm bg-transparent leading-relaxed text-muted-foreground outline-none placeholder:text-muted-foreground/50 focus:bg-brand-soft/40"
|
||||
placeholder="Einleitung (optional) – z. B. wofür das Formular gedacht ist und wer es bearbeitet"
|
||||
aria-label="Einleitung"
|
||||
rows="1"
|
||||
maxlength="2000"
|
||||
@click.stop
|
||||
/>
|
||||
|
||||
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
|
||||
<VueDraggable
|
||||
v-model="state.fields"
|
||||
:group="{ name: 'form-fields' }"
|
||||
handle=".fb-handle"
|
||||
:animation="150"
|
||||
ghost-class="pb-ghost"
|
||||
class="grid min-h-24 gap-x-5 gap-y-3 @xl:grid-cols-2"
|
||||
@add="(event) => select(state.fields[event.newIndex]?._id)"
|
||||
>
|
||||
<BuilderField v-for="(field, index) in state.fields" :key="field._id" :field="field" :index="index" />
|
||||
</VueDraggable>
|
||||
|
||||
<p v-if="!state.fields.length" class="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
|
||||
Noch keine Felder. Felder aus der rechten Spalte hierher ziehen oder anklicken.
|
||||
</p>
|
||||
|
||||
<Popover>
|
||||
<PopoverTrigger class="mt-4 flex h-9 w-full items-center justify-center gap-1.5 rounded-md border border-dashed text-sm font-medium text-muted-foreground hover:border-brand-300 hover:bg-brand-soft hover:text-brand-soft-foreground" @click.stop>
|
||||
<Plus class="size-4" /> Feld hinzufügen
|
||||
</PopoverTrigger>
|
||||
<PopoverContent class="w-[22rem] p-3" @click.stop>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button v-for="(label, type) in types" :key="type" type="button" class="flex items-center gap-2 rounded-md border px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60" @click="add(type, state.fields.length)">
|
||||
<component :is="fieldTypes[type].icon" class="size-4 shrink-0 text-brand-text" /> <span class="truncate">{{ label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
<div class="mt-5 flex items-center gap-4 border-t pt-5">
|
||||
<span class="inline-flex h-9 items-center rounded-md bg-brand px-4 text-sm font-medium text-brand-foreground opacity-80">Absenden</span>
|
||||
<span class="text-xs text-muted-foreground">Beschriftung und Bestätigungstext unter „Einstellungen“</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<h1 class="text-3xl font-semibold tracking-tight">{{ state.title }}</h1>
|
||||
<p v-if="state.description" class="mt-3 leading-relaxed whitespace-pre-line text-muted-foreground">{{ state.description }}</p>
|
||||
<div class="@container mt-8 rounded-lg border bg-card p-5 sm:p-8">
|
||||
<FormRenderer :key="JSON.stringify(previewForm.fields)" :form="previewForm" preview />
|
||||
</div>
|
||||
<p class="mt-3 text-center text-xs text-muted-foreground">Vorschau: Bedingungen und Pflichtfelder funktionieren wie im Portal, gesendet wird nichts.</p>
|
||||
</template>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<aside v-if="mode === 'edit'" class="hidden w-[340px] shrink-0 flex-col border-l bg-card lg:flex">
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-4">
|
||||
<FieldSettings v-if="selected" :key="selected._id" :field="selected" />
|
||||
<template v-else>
|
||||
<p class="mb-4 text-xs text-muted-foreground">Klicken fügt das Feld unter dem ausgewählten ein. Felder lassen sich auch an jede Stelle ziehen.</p>
|
||||
<section v-for="[group, items] in palette" :key="group" class="mb-4">
|
||||
<h3 class="mb-2 text-xs font-semibold tracking-wide text-muted-foreground uppercase">{{ group }}</h3>
|
||||
<VueDraggable
|
||||
:model-value="items"
|
||||
:group="{ name: 'form-fields', pull: 'clone', put: false }"
|
||||
:clone="(item) => createField(item.type)"
|
||||
:sort="false"
|
||||
class="grid grid-cols-2 gap-2"
|
||||
>
|
||||
<button
|
||||
v-for="item in items"
|
||||
:key="item.type"
|
||||
type="button"
|
||||
class="flex cursor-grab items-center gap-2 rounded-md border bg-card px-2.5 py-2 text-left text-[13px] font-medium hover:border-brand-300 hover:bg-brand-soft/60 active:cursor-grabbing"
|
||||
@click="add(item.type)"
|
||||
>
|
||||
<component :is="item.icon" class="size-4 shrink-0 text-brand-text" />
|
||||
<span class="truncate">{{ item.label }}</span>
|
||||
</button>
|
||||
</VueDraggable>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Toaster position="bottom-left" />
|
||||
</template>
|
||||
33
plugins-core/forms/resources/js/pages/Index.vue
Normal file
33
plugins-core/forms/resources/js/pages/Index.vue
Normal 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>
|
||||
29
plugins-core/forms/resources/js/pages/Show.vue
Normal file
29
plugins-core/forms/resources/js/pages/Show.vue
Normal 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>
|
||||
|
|
@ -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>
|
||||
44
plugins-core/forms/resources/views/mail/submitted.blade.php
Normal file
44
plugins-core/forms/resources/views/mail/submitted.blade.php
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
<!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">
|
||||
@php($branding = app(\App\Support\Branding::class))
|
||||
@php($logo = $branding->logoUrl() && ! str_ends_with(strtolower($branding->logoUrl()), '.svg') ? $branding->logoUrl() : null)
|
||||
<p style="margin:0 0 16px;font-size:15px;font-weight:700;color:{{ $branding->primaryColor() }}">
|
||||
@if ($logo)<img src="{{ $logo }}" alt="{{ $portalName }}" style="max-height:40px;max-width:200px;border:0">@else{{ $portalName }}@endif
|
||||
</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:{{ $branding->primaryColor() }};color:{{ \App\Support\ColorPalette::foregroundFor($branding->primaryColor()) }};text-decoration:none;padding:10px 16px;border-radius:6px;font-size:14px">Ergebnisse im Portal öffnen</a></p>
|
||||
@endif
|
||||
</div>
|
||||
@if ($branding->get('email_footer'))
|
||||
<p style="margin:16px 0 0;font-size:12px;color:#5f6670;line-height:1.5">{!! nl2br(e($branding->get('email_footer'))) !!}</p>
|
||||
@endif
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
18
plugins-core/forms/routes/web.php
Normal file
18
plugins-core/forms/routes/web.php
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inhaus\Plugins\Forms\Http\Controllers\FormBuilderController;
|
||||
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('/redaktion/formulare/{form}', [FormBuilderController::class, 'edit'])->name('forms.builder');
|
||||
Route::put('/redaktion/formulare/{form}', [FormBuilderController::class, 'update'])->name('forms.builder.update');
|
||||
|
||||
Route::get('/formulare/dateien/{file}', [FormResultsController::class, 'file'])->name('forms.file');
|
||||
Route::get('/admin/formulare/{form}/export', [FormResultsController::class, 'export'])->name('forms.export');
|
||||
});
|
||||
51
plugins-core/forms/src/EditorialForms.php
Normal file
51
plugins-core/forms/src/EditorialForms.php
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Forms;
|
||||
|
||||
use App\Models\User;
|
||||
use Inhaus\Plugins\Forms\Models\Form;
|
||||
|
||||
/**
|
||||
* „Redaktion → Formulare“: Formulare, deren Felder oder Ergebnisse die Person bearbeiten bzw. sehen darf.
|
||||
*/
|
||||
final class EditorialForms
|
||||
{
|
||||
public static function visible(User $user): bool
|
||||
{
|
||||
return $user->can('forms.manage')
|
||||
|| $user->permissions()->ids('forms.edit', 'form') !== []
|
||||
|| $user->permissions()->ids('forms.results', 'form') !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function props(User $user): array
|
||||
{
|
||||
$all = $user->can('forms.manage');
|
||||
$edit = $all ? true : $user->permissions()->ids('forms.edit', 'form');
|
||||
$results = $all ? true : $user->permissions()->ids('forms.results', 'form');
|
||||
$ids = $edit === true || $results === true ? true : array_values(array_unique([...$edit, ...$results]));
|
||||
|
||||
$forms = Form::query()
|
||||
->when($ids !== true, fn ($q) => $q->whereIn('id', $ids))
|
||||
->withCount(['submissions', 'submissions as unread_count' => fn ($q) => $q->whereNull('read_at')])
|
||||
->orderBy('title')
|
||||
->get(['id', 'title', 'slug', 'is_open', 'closes_at']);
|
||||
|
||||
return [
|
||||
'forms' => $forms->map(fn (Form $form) => [
|
||||
'id' => $form->id,
|
||||
'title' => $form->title,
|
||||
'url' => $form->url(),
|
||||
'open' => $form->acceptsSubmissions(),
|
||||
'submissions' => $form->submissions_count,
|
||||
'unread' => $form->unread_count,
|
||||
'builder_url' => $edit === true || in_array($form->id, (array) $edit, true) ? route('forms.builder', $form) : null,
|
||||
'results_url' => $results === true || in_array($form->id, (array) $results, true) ? url('/admin/formulare/'.$form->id.'/ergebnisse') : null,
|
||||
'csv_url' => $results === true || in_array($form->id, (array) $results, true) ? route('forms.export', $form) : null,
|
||||
])->all(),
|
||||
'createUrl' => $all ? url('/admin/formulare/neu') : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
173
plugins-core/forms/src/Filament/Resources/Forms/FormResource.php
Normal file
173
plugins-core/forms/src/Filament/Resources/Forms/FormResource.php
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
<?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\DateTimePicker;
|
||||
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\Actions;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Schemas\Components\Text;
|
||||
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 Illuminate\Support\HtmlString;
|
||||
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),
|
||||
Text::make(fn (?Form $record) => new HtmlString($record
|
||||
? '<strong>'.count(FormFields::inputs($record)).' Felder.</strong> Die Felder bearbeiten Sie im visuellen Baukasten – so, wie das Formular später aussieht.'
|
||||
: 'Nach dem Anlegen öffnet sich der visuelle Baukasten für die Felder.')),
|
||||
Actions::make([
|
||||
Action::make('builder')->label('Felder im Baukasten bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
|
||||
->url(fn (?Form $record) => $record ? route('forms.builder', $record) : null),
|
||||
])->visibleOn('edit'),
|
||||
]),
|
||||
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.'),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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('builder')->label('Felder')->icon(Heroicon::OutlinedPencilSquare)->iconButton()->tooltip('Felder im Baukasten bearbeiten')
|
||||
->url(fn (Form $record) => route('forms.builder', $record))
|
||||
->visible(fn (Form $record) => auth()->user()->can('update', $record)),
|
||||
Action::make('csv')->label('CSV')->icon(Heroicon::OutlinedArrowDownTray)->iconButton()->tooltip('Ergebnisse als CSV herunterladen')
|
||||
->url(fn (Form $record) => route('forms.export', $record))
|
||||
->visible(fn (Form $record) => auth()->user()->can('viewResults', $record)),
|
||||
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'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?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, 'fields' => [], 'created_by' => auth()->id()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Nach dem Anlegen direkt in den visuellen Baukasten.
|
||||
*/
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return route('forms.builder', $this->record);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?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('builder')->label('Felder bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
|
||||
->url(fn () => route('forms.builder', $this->record)),
|
||||
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.'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
<?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('csv')->label('Auswahl als CSV')->icon(Heroicon::OutlinedArrowDownTray)
|
||||
->action(fn (Collection $records) => $this->redirect(route('forms.export', ['form' => $form, 'ids' => $records->modelKeys()])))
|
||||
->deselectRecordsAfterCompletion(),
|
||||
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('Alle als CSV herunterladen')->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>';
|
||||
}
|
||||
}
|
||||
|
|
@ -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')];
|
||||
}
|
||||
}
|
||||
334
plugins-core/forms/src/FormFields.php
Normal file
334
plugins-core/forms/src/FormFields.php
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
<?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,
|
||||
'locked' => self::isLocked($field),
|
||||
'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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feld fest aus dem Profil: nicht änderbar, beim Absenden setzt der Server den Profilwert ein.
|
||||
*
|
||||
* @param array{type: string, data: array<string, mixed>} $field
|
||||
*/
|
||||
public static function isLocked(array $field): bool
|
||||
{
|
||||
return in_array($field['type'], ['text', 'email', 'phone'], true)
|
||||
&& filled($field['data']['prefill'] ?? null)
|
||||
&& (bool) ($field['data']['locked'] ?? false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Eingaben für feste Profilfelder durch die Werte aus dem Profil ersetzen –
|
||||
* unabhängig davon, was der Browser schickt.
|
||||
*
|
||||
* @param array<string, mixed> $answers
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function applyLocked(Form $form, User $user, array $answers): array
|
||||
{
|
||||
$profile = self::prefill($form, $user);
|
||||
|
||||
foreach ($form->fields ?? [] as $field) {
|
||||
if (self::isLocked($field)) {
|
||||
$answers[$field['data']['key']] = $profile[$field['data']['key']] ?? '';
|
||||
}
|
||||
}
|
||||
|
||||
return $answers;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 (self::isLocked($field)) {
|
||||
$messages[$name.'.required'] = 'Diese Angabe fehlt in Ihrem Profil. Bitte ergänzen Sie sie dort (Profil bearbeiten) oder wenden Sie sich an die Personalverwaltung.';
|
||||
// Profilwerte werden nicht wie Eingaben geprüft (z. B. Telefonformat).
|
||||
$rules[$name] = [$required ? 'required' : 'nullable', 'string', 'max:500'];
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
36
plugins-core/forms/src/FormPresenter.php
Normal file
36
plugins-core/forms/src/FormPresenter.php
Normal 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),
|
||||
];
|
||||
}
|
||||
}
|
||||
55
plugins-core/forms/src/FormsPlugin.php
Normal file
55
plugins-core/forms/src/FormsPlugin.php
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Forms;
|
||||
|
||||
use App\Editorial\Editorial;
|
||||
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 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
|
||||
{
|
||||
// Kein eigener Menüpunkt im Portal: Formulare werden in Seiten und Beiträge eingebunden.
|
||||
// /formulare/{slug} bleibt als direkte Adresse (z. B. für Links in E-Mails).
|
||||
|
||||
$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(Editorial::class)->add('forms', 'Formulare', 'forms::EditorialForms', 30,
|
||||
fn (User $user) => EditorialForms::visible($user),
|
||||
fn (User $user) => EditorialForms::props($user));
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Forms\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Forms\FormFields;
|
||||
use Inhaus\Plugins\Forms\Models\Form;
|
||||
|
||||
/**
|
||||
* Visueller Formularbaukasten im Portal: Das Formular erscheint so, wie es
|
||||
* ausgefüllt wird; Bezeichnungen und Auswahlmöglichkeiten werden direkt darin
|
||||
* bearbeitet. Einstellungen und Zugriff pflegt man im Admin.
|
||||
*/
|
||||
class FormBuilderController extends Controller
|
||||
{
|
||||
public function edit(Form $form): Response
|
||||
{
|
||||
Gate::authorize('update', $form);
|
||||
|
||||
return Inertia::render('forms::Builder', [
|
||||
'form' => [
|
||||
'id' => $form->id,
|
||||
'title' => $form->title,
|
||||
'description' => $form->description,
|
||||
'fields' => $form->fields ?? [],
|
||||
'url' => $form->url(),
|
||||
'submissions' => $form->submissions()->count(),
|
||||
'anonymous' => $form->isAnonymous(),
|
||||
],
|
||||
'types' => FormFields::TYPES,
|
||||
'prefillOptions' => collect(FormFields::prefillOptions())->map(fn ($label, $value) => ['value' => $value, 'label' => $label])->values(),
|
||||
'settingsUrl' => url('/admin/formulare/'.$form->id.'/bearbeiten'),
|
||||
'resultsUrl' => auth()->user()->can('viewResults', $form) ? url('/admin/formulare/'.$form->id.'/ergebnisse') : null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, Form $form): JsonResponse
|
||||
{
|
||||
Gate::authorize('update', $form);
|
||||
|
||||
$data = $request->validate([
|
||||
'title' => ['required', 'string', 'max:200'],
|
||||
'description' => ['nullable', 'string', 'max:2000'],
|
||||
'fields' => ['present', 'array', 'max:150'],
|
||||
'fields.*.type' => ['required', Rule::in(array_keys(FormFields::TYPES))],
|
||||
'fields.*.data' => ['required', 'array'],
|
||||
'fields.*.data.label' => ['nullable', 'string', 'max:200'],
|
||||
'fields.*.data.text' => ['nullable', 'string', 'max:3000'],
|
||||
'fields.*.data.help' => ['nullable', 'string', 'max:300'],
|
||||
'fields.*.data.placeholder' => ['nullable', 'string', 'max:100'],
|
||||
'fields.*.data.key' => ['nullable', 'string', 'max:60', 'regex:/^[a-z0-9_]*$/'],
|
||||
'fields.*.data.options' => ['nullable', 'array', 'max:100'],
|
||||
'fields.*.data.options.*' => ['nullable', 'string', 'max:200'],
|
||||
], [], ['title' => 'Titel']);
|
||||
|
||||
// Nicht $data['fields']: validate() liefert nur die ausdrücklich geprüften Schlüssel.
|
||||
// Die übrigen Einstellungen filtert cleanData() je Feldtyp.
|
||||
$fields = array_map(fn (array $field) => ['type' => $field['type'], 'data' => self::cleanData($field['type'], (array) $field['data'])], array_values((array) $request->input('fields')));
|
||||
|
||||
foreach ($fields as $index => $field) {
|
||||
$needsLabel = ! in_array($field['type'], FormFields::LAYOUT_TYPES, true);
|
||||
|
||||
if ($needsLabel ? blank($field['data']['label'] ?? null) : blank($field['data']['text'] ?? null)) {
|
||||
throw ValidationException::withMessages(["fields.{$index}" => 'Feld '.($index + 1).': Bitte eine Bezeichnung eingeben.']);
|
||||
}
|
||||
|
||||
if (in_array($field['type'], ['select', 'radio', 'checkboxes'], true) && ($field['data']['options'] ?? []) === []) {
|
||||
throw ValidationException::withMessages(["fields.{$index}" => '„'.$field['data']['label'].'“: Bitte mindestens eine Auswahlmöglichkeit angeben.']);
|
||||
}
|
||||
}
|
||||
|
||||
$form->fill(['title' => $data['title'], 'description' => $data['description'] ?? null, 'fields' => $fields])->save();
|
||||
Audit::log('forms.fields_updated', ['form' => $form->id, 'fields' => count($fields)]);
|
||||
|
||||
return response()->json(['fields' => $form->fresh()->fields]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nur bekannte Einstellungen übernehmen.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function cleanData(string $type, array $data): array
|
||||
{
|
||||
$allowed = ['label', 'key', 'required', 'help', 'width', 'condition_field', 'condition_operator', 'condition_value'];
|
||||
$allowed = [...$allowed, ...match ($type) {
|
||||
'text' => ['placeholder', 'max', 'prefill', 'locked'],
|
||||
'textarea' => ['rows', 'max'],
|
||||
'email', 'phone' => ['prefill', 'locked'],
|
||||
'number' => ['min', 'max'],
|
||||
'select', 'radio' => ['options'],
|
||||
'checkboxes' => ['options', 'min', 'max'],
|
||||
'file' => ['accept', 'max_size', 'multiple'],
|
||||
'heading', 'paragraph' => ['text'],
|
||||
default => [],
|
||||
}];
|
||||
|
||||
$clean = array_intersect_key($data, array_flip($allowed));
|
||||
|
||||
if (isset($clean['options'])) {
|
||||
$clean['options'] = array_values(array_unique(array_filter(array_map(fn ($o) => trim((string) $o), $clean['options']), 'strlen')));
|
||||
}
|
||||
|
||||
foreach (['required', 'multiple', 'locked'] as $flag) {
|
||||
if (isset($clean[$flag])) {
|
||||
$clean[$flag] = (bool) $clean[$flag];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (['min', 'max', 'rows', 'max_size'] as $number) {
|
||||
if (isset($clean[$number])) {
|
||||
$clean[$number] = is_numeric($clean[$number]) ? (int) $clean[$number] : null;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($clean['width']) && ! in_array($clean['width'], ['full', 'half'], true)) {
|
||||
$clean['width'] = 'full';
|
||||
}
|
||||
|
||||
if (isset($clean['accept']) && ! array_key_exists($clean['accept'], FormFields::FILE_TYPES)) {
|
||||
$clean['accept'] = 'any';
|
||||
}
|
||||
|
||||
if (isset($clean['prefill']) && ! array_key_exists($clean['prefill'], FormFields::prefillOptions())) {
|
||||
unset($clean['prefill']);
|
||||
}
|
||||
|
||||
if (empty($clean['prefill']) || empty($clean['locked'])) {
|
||||
unset($clean['locked']);
|
||||
}
|
||||
|
||||
if (isset($clean['condition_operator']) && ! in_array($clean['condition_operator'], ['equals', 'not_equals', 'contains', 'filled', 'empty'], true)) {
|
||||
$clean['condition_operator'] = 'equals';
|
||||
}
|
||||
|
||||
return array_filter($clean, fn ($value) => $value !== null && $value !== '');
|
||||
}
|
||||
}
|
||||
74
plugins-core/forms/src/Http/Controllers/FormController.php
Normal file
74
plugins-core/forms/src/Http/Controllers/FormController.php
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
<?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];
|
||||
}
|
||||
|
||||
$answers = FormFields::applyLocked($form, $user, $answers);
|
||||
|
||||
[$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);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
<?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();
|
||||
|
||||
// Optional nur ausgewählte Einsendungen (aus der Ergebnisliste).
|
||||
$ids = array_values(array_filter(array_map('intval', (array) $request->query('ids', []))));
|
||||
$submissions = fn () => $form->submissions()->when($ids !== [], fn ($q) => $q->whereIn('id', $ids));
|
||||
|
||||
return response()->streamDownload(function () use ($submissions, $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.
|
||||
$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)], ';', '"', '');
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
54
plugins-core/forms/src/Mail/FormSubmitted.php
Normal file
54
plugins-core/forms/src/Mail/FormSubmitted.php
Normal 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'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
116
plugins-core/forms/src/Models/Form.php
Normal file
116
plugins-core/forms/src/Models/Form.php
Normal 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);
|
||||
}
|
||||
}
|
||||
36
plugins-core/forms/src/Models/FormFile.php
Normal file
36
plugins-core/forms/src/Models/FormFile.php
Normal 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);
|
||||
}
|
||||
}
|
||||
74
plugins-core/forms/src/Models/FormSubmission.php
Normal file
74
plugins-core/forms/src/Models/FormSubmission.php
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
53
plugins-core/forms/src/Policies/FormPolicy.php
Normal file
53
plugins-core/forms/src/Policies/FormPolicy.php
Normal 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);
|
||||
}
|
||||
}
|
||||
32
plugins-core/forms/src/Retention.php
Normal file
32
plugins-core/forms/src/Retention.php
Normal 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;
|
||||
}
|
||||
}
|
||||
118
plugins-core/forms/src/Submissions.php
Normal file
118
plugins-core/forms/src/Submissions.php
Normal 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Formular unter einem Beitrag (z. B. Anmeldung zum Sommerfest). Ohne
|
||||
* Fremdschlüssel: Das Formular-Plugin ist optional.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('news_posts', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('form_id')->nullable()->after('cover_path');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('news_posts', fn (Blueprint $table) => $table->dropColumn('form_id'));
|
||||
}
|
||||
};
|
||||
|
|
@ -5,5 +5,5 @@ defineProps({
|
|||
</script>
|
||||
|
||||
<template>
|
||||
<span v-if="category" class="text-[11px] font-semibold tracking-wide text-brand-text uppercase">{{ category.name }}</span>
|
||||
<span v-if="category" class="text-[11px] font-semibold tracking-wide text-accent2-text uppercase">{{ category.name }}</span>
|
||||
</template>
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const props = defineProps({
|
|||
categories: { type: Array, required: true },
|
||||
canPublishWithoutCategory: { type: Boolean, default: false },
|
||||
canDelete: { type: Boolean, default: false },
|
||||
forms: { type: Array, default: () => [] },
|
||||
});
|
||||
|
||||
const page = usePage();
|
||||
|
|
@ -41,6 +42,7 @@ const form = useForm({
|
|||
remove_cover: false,
|
||||
is_featured: props.post?.is_featured ?? false,
|
||||
published_at: localValue(props.post?.published_at),
|
||||
form_id: props.post?.form_id ?? null,
|
||||
action: 'draft',
|
||||
});
|
||||
|
||||
|
|
@ -88,6 +90,7 @@ function submit(action) {
|
|||
...data,
|
||||
published_at: data.published_at ? new Date(data.published_at).toISOString() : null,
|
||||
category_id: data.category_id ? Number(data.category_id) : null,
|
||||
form_id: data.form_id ? Number(data.form_id) : '',
|
||||
...(props.post ? { _method: 'put' } : {}),
|
||||
})).post(props.post ? `/redaktion/neuigkeiten/${props.post.id}` : '/redaktion/neuigkeiten', {
|
||||
forceFormData: true,
|
||||
|
|
@ -205,6 +208,12 @@ const scheduled = computed(() => form.published_at && new Date(form.published_at
|
|||
</div>
|
||||
</Panel>
|
||||
|
||||
<Panel v-if="forms.length" title="Formular">
|
||||
<FormField id="form_id" label="Formular unter dem Beitrag" :error="form.errors.form_id" hint="Z. B. Anmeldung zum Sommerfest oder Rückmeldung. Formulare legt die Redaktion unter „Formulare“ an.">
|
||||
<NativeSelect id="form_id" v-model="form.form_id" :options="forms" placeholder="– kein Formular –" />
|
||||
</FormField>
|
||||
</Panel>
|
||||
|
||||
<Panel title="Titelbild">
|
||||
<div class="grid gap-3">
|
||||
<div v-if="coverPreview" class="relative overflow-hidden rounded-md border">
|
||||
|
|
|
|||
|
|
@ -6,12 +6,14 @@ import CategoryLabel from '../components/CategoryLabel.vue';
|
|||
import NewsCard from '../components/NewsCard.vue';
|
||||
import PersonAvatar from '@/components/PersonAvatar.vue';
|
||||
import AppLayout from '@/layouts/AppLayout.vue';
|
||||
import PageContent from '@/pagebuilder/PageContent.vue';
|
||||
import { formatDate } from '@/lib/format';
|
||||
|
||||
defineProps({
|
||||
post: { type: Object, required: true },
|
||||
related: { type: Object, required: true },
|
||||
editUrl: { type: String, default: null },
|
||||
form: { type: Object, default: null },
|
||||
});
|
||||
</script>
|
||||
|
||||
|
|
@ -46,6 +48,9 @@ defineProps({
|
|||
<img v-if="post.cover_url" :src="post.cover_url" :alt="post.title" class="mt-8 aspect-video w-full rounded-lg object-cover" />
|
||||
|
||||
<div class="prose prose-neutral mt-8 max-w-none prose-headings:tracking-tight prose-img:rounded-lg" v-html="post.body_html" />
|
||||
|
||||
<!-- Eingebundenes Formular (Pagebuilder-Block des Formular-Plugins) -->
|
||||
<PageContent v-if="form" :content="form" class="mt-10" />
|
||||
</article>
|
||||
|
||||
<section v-if="related.data.length" class="mx-auto mt-16 max-w-5xl">
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ use Illuminate\Database\Eloquent\Builder;
|
|||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\CreateNewsPost;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\EditNewsPost;
|
||||
use Inhaus\Plugins\News\Filament\Resources\NewsPosts\Pages\ListNewsPosts;
|
||||
use Inhaus\Plugins\News\FormEmbed;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Inhaus\Plugins\News\Policies\NewsPostPolicy;
|
||||
|
|
@ -106,6 +107,12 @@ class NewsPostResource extends Resource
|
|||
->label('Auf der Startseite hervorheben')
|
||||
->disabled(fn (Get $get) => ! static::canPublishIn($get('category_id')))
|
||||
->helperText('Hervorgehobene Beiträge mit Titelbild erscheinen groß im Slider.'),
|
||||
Select::make('form_id')
|
||||
->label('Formular unter dem Beitrag')
|
||||
->helperText('Z. B. Anmeldung oder Rückmeldung zum Beitrag.')
|
||||
->options(fn () => FormEmbed::options())
|
||||
->visible(fn () => FormEmbed::available())
|
||||
->searchable(),
|
||||
FileUpload::make('cover_path')
|
||||
->label('Titelbild')
|
||||
->helperText('Querformat, mindestens 1600 × 900 Pixel.')
|
||||
|
|
|
|||
48
plugins-core/news/src/FormEmbed.php
Normal file
48
plugins-core/news/src/FormEmbed.php
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\News;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Pagebuilder\Blocks;
|
||||
use App\Pagebuilder\Content;
|
||||
|
||||
/**
|
||||
* Formular unter einem Beitrag – über den Pagebuilder-Block „forms.form“,
|
||||
* damit die Neuigkeiten nicht vom Formular-Plugin abhängen.
|
||||
*/
|
||||
final class FormEmbed
|
||||
{
|
||||
public const BLOCK = 'forms.form';
|
||||
|
||||
public static function available(): bool
|
||||
{
|
||||
return app(Blocks::class)->get(self::BLOCK) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> ID => Titel
|
||||
*/
|
||||
public static function options(): array
|
||||
{
|
||||
$field = collect(app(Blocks::class)->get(self::BLOCK)?->fields ?? [])->first(fn ($f) => $f->name === 'form');
|
||||
|
||||
return $field ? collect($field->toArray()['choices'] ?? [])->pluck('label', 'value')->all() : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzeigefertiger Inhalt (wie eine Pagebuilder-Seite mit einem Block) oder null.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public static function render(?int $formId, ?User $user): ?array
|
||||
{
|
||||
if (! $formId || ! self::available()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$content = app(Content::class);
|
||||
$rendered = $content->render($content->sanitize(['blocks' => [['type' => self::BLOCK, 'data' => ['form' => (string) $formId, 'show_title' => true]]]]), $user);
|
||||
|
||||
return $rendered['blocks'] === [] ? null : $rendered;
|
||||
}
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
|
|||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\News\FormEmbed;
|
||||
use Inhaus\Plugins\News\Http\Resources\NewsPostResource;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
|
|
@ -53,6 +54,7 @@ class NewsController extends Controller
|
|||
] : null,
|
||||
],
|
||||
'editUrl' => request()->user()->can('update', $post) ? route('news.editor.edit', $post) : null,
|
||||
'form' => FormEmbed::render($post->form_id, request()->user()),
|
||||
'related' => NewsPostResource::collection(
|
||||
NewsPost::query()
|
||||
->published()
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ use Illuminate\Validation\Rules\File;
|
|||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\News\FormEmbed;
|
||||
use Inhaus\Plugins\News\Models\NewsCategory;
|
||||
use Inhaus\Plugins\News\Models\NewsPost;
|
||||
use Inhaus\Plugins\News\NewsWorkflow;
|
||||
|
|
@ -125,6 +126,7 @@ class NewsEditorController extends Controller
|
|||
'remove_cover' => ['boolean'],
|
||||
'is_featured' => ['boolean'],
|
||||
'published_at' => ['nullable', 'date'],
|
||||
'form_id' => ['nullable', 'integer', Rule::in(array_map('intval', array_keys(FormEmbed::options())))],
|
||||
'action' => ['required', Rule::in(['draft', 'submit', 'publish'])],
|
||||
], ['category_id.in' => 'In dieser Kategorie dürfen Sie keine Beiträge schreiben.'], ['category_id' => 'Kategorie', 'title' => 'Titel']);
|
||||
|
||||
|
|
@ -139,6 +141,7 @@ class NewsEditorController extends Controller
|
|||
'teaser' => $data['teaser'] ?? null,
|
||||
'body' => $data['body'] ?? null,
|
||||
'category_id' => $data['category_id'] ?? null,
|
||||
'form_id' => FormEmbed::available() ? ($data['form_id'] ?? null) : $post->form_id,
|
||||
]);
|
||||
|
||||
if ($canPublish) {
|
||||
|
|
@ -209,6 +212,7 @@ class NewsEditorController extends Controller
|
|||
'is_published' => $post->isPublished(),
|
||||
'url' => $post->isPublished() ? route('news.show', $post) : null,
|
||||
'review_note' => $post->review_note,
|
||||
'form_id' => $post->form_id,
|
||||
'author' => $post->author?->name,
|
||||
] : null,
|
||||
'categories' => $categories->map(fn (NewsCategory $c) => [
|
||||
|
|
@ -217,6 +221,7 @@ class NewsEditorController extends Controller
|
|||
'can_publish' => $this->policy->publish($user, $c->id),
|
||||
]),
|
||||
'canPublishWithoutCategory' => $user->can('news.manage'),
|
||||
'forms' => collect(FormEmbed::options())->map(fn ($title, $id) => ['value' => (int) $id, 'label' => $title])->values(),
|
||||
'canDelete' => $post && $user->can('delete', $post) && ($post->status !== NewsPost::PUBLISHED || $this->policy->publish($user, $post->category_id)),
|
||||
]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ use Inhaus\Plugins\News\Database\Factories\NewsPostFactory;
|
|||
|
||||
#[Fillable([
|
||||
'category_id', 'author_id', 'title', 'slug', 'teaser', 'body',
|
||||
'cover_path', 'is_featured', 'published_at',
|
||||
'cover_path', 'is_featured', 'published_at', 'form_id',
|
||||
])]
|
||||
class NewsPost extends Model
|
||||
{
|
||||
|
|
@ -80,6 +80,7 @@ class NewsPost extends Model
|
|||
'is_featured' => 'boolean',
|
||||
'published_at' => 'datetime',
|
||||
'submitted_at' => 'datetime',
|
||||
'form_id' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ class NewsPlugin extends Plugin
|
|||
$featured = $this->featured($user);
|
||||
|
||||
return $featured->isEmpty() ? null : ['posts' => NewsPostResource::collection($featured)->resolve()];
|
||||
}, mobileSort: 10);
|
||||
}, label: 'Slider mit hervorgehobenen Beiträgen', mobileSort: 10);
|
||||
|
||||
$widgets->add('news.latest', 'news::Latest', 'feed', sort: 10, props: function (User $user, Request $request) {
|
||||
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
|
||||
|
|
@ -84,7 +84,7 @@ class NewsPlugin extends Plugin
|
|||
'posts' => NewsPostResource::collection($posts)->resolve(),
|
||||
'canWrite' => $user->can('news.manage'),
|
||||
];
|
||||
}, mobileSort: 20);
|
||||
}, label: 'Neuigkeiten', mobileSort: 20);
|
||||
|
||||
$widgets->add('news.areas', 'news::Areas', 'main', sort: 20, props: function (User $user) {
|
||||
$posts = NewsPost::query()->published()->visibleTo($user)->with('category')
|
||||
|
|
@ -92,7 +92,7 @@ class NewsPlugin extends Plugin
|
|||
->latest('published_at')->skip(4)->limit(4)->get();
|
||||
|
||||
return $posts->isEmpty() ? null : ['posts' => NewsPostResource::collection($posts)->resolve()];
|
||||
}, mobileSort: 50);
|
||||
}, label: 'Aktuelles aus den Bereichen', mobileSort: 50);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ class PageRevision extends Model
|
|||
'published' => 'Veröffentlicht',
|
||||
'scheduled' => 'Zeitgesteuert veröffentlicht',
|
||||
'restored' => 'Wiederhergestellt',
|
||||
'imported' => 'Importiert',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
|
|
|
|||
|
|
@ -0,0 +1,60 @@
|
|||
<?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('wp_imports', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->string('file');
|
||||
$table->string('site_title')->nullable();
|
||||
$table->string('site_url')->nullable();
|
||||
// analyzed → running → done (oder failed)
|
||||
$table->string('status', 20)->default('analyzed');
|
||||
$table->json('options')->nullable();
|
||||
$table->json('stats')->nullable();
|
||||
$table->longText('log')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
// Zwischenablage der Exportdatei: je Eintrag eine Zeile, abgearbeitet in Portionen.
|
||||
Schema::create('wp_import_items', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('import_id')->constrained('wp_imports')->cascadeOnDelete();
|
||||
$table->string('type', 20); // category, author, attachment, post, page
|
||||
$table->unsignedBigInteger('wp_id')->default(0);
|
||||
$table->unsignedBigInteger('wp_parent')->default(0);
|
||||
$table->string('status', 12)->default('pending'); // pending, done, skipped, failed
|
||||
$table->longText('data');
|
||||
$table->string('message', 500)->nullable();
|
||||
|
||||
$table->index(['import_id', 'type', 'status']);
|
||||
$table->index(['import_id', 'type', 'wp_id']);
|
||||
});
|
||||
|
||||
// Was schon übernommen wurde – ein erneuter Import legt nichts doppelt an.
|
||||
Schema::create('wp_import_refs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('source', 191);
|
||||
$table->string('type', 20); // post, page, category, media
|
||||
$table->string('wp_key', 191);
|
||||
$table->string('local_type', 60);
|
||||
$table->string('local_value', 500);
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['source', 'type', 'wp_key']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('wp_import_refs');
|
||||
Schema::dropIfExists('wp_import_items');
|
||||
Schema::dropIfExists('wp_imports');
|
||||
}
|
||||
};
|
||||
14
plugins-core/wordpress-import/plugin.json
Normal file
14
plugins-core/wordpress-import/plugin.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"slug": "wordpress-import",
|
||||
"name": "WordPress-Import",
|
||||
"version": "1.0.0",
|
||||
"description": "Übernimmt Beiträge, Kategorien, Bilder und Seiten aus einer WordPress-Exportdatei – für den Umstieg auf das Portal.",
|
||||
"author": "Inhaus",
|
||||
"namespace": "Inhaus\\Plugins\\WordpressImport\\",
|
||||
"class": "Inhaus\\Plugins\\WordpressImport\\WordpressImportPlugin",
|
||||
"requires": {
|
||||
"core": ">=0.6.0",
|
||||
"php": ">=8.3",
|
||||
"plugins": ["news"]
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue