Merge pull request 'MVP 1.0 (ohne Shop)' (#1) from develop into main
Deploy Production / test (push) Successful in 1m18s
Deploy Production / deploy (push) Failing after 3m7s

Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
Lars committed 2026-11-20 21:58:41 +01:00
commit 57b2131632
800 files changed
+83679 -53

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
---
description: Verbindliche Betriebs- und Entwicklungsregeln für Lara & Felix. Die Quelle ist CLAUDE.md.
alwaysApply: true
---
# Lara & Felix – Betrieb
Lies und befolge `CLAUDE.md` im Repository-Root. Diese Regel wiederholt die dortigen Vorgaben nicht.
- Gearbeitet wird auf `develop` oder auf `feature/*`, die nach `develop` münden. Nie auf `main` committen, pushen oder mergen.
- Ein Push auf `develop` deployt auf Test. Ein Push auf `main` deployt auf Produktion und bleibt Lars vorbehalten.
- Kein Deploy von Hand (`docker compose`, `deploy.sh`, `systemctl` auf den Servern).
- Keine Secrets ins Repo, in Commits, Logs oder Chat.
- Tests vor dem Push auf `develop`. Fehlgeschlagene Tests werden behoben, nicht umgangen.
- Medien- und Prozessgrenzen aus `CLAUDE.md` nicht aufweichen: der Web-Prozess schreibt nicht nach `originals/` und liest `derived/` und `public/` nur.
+19
View File
@@ -0,0 +1,19 @@
---
description: Gemeinsame verbindliche UX-Vorgaben für Verwaltungsänderungen bei Lara & Felix. Ergänzt die Betriebsregeln, ersetzt sie nicht.
alwaysApply: true
---
# Verwaltung – gemeinsame Designgrundlage
Betriebsregeln in `CLAUDE.md` und `.cursor/rules/luf-betrieb.mdc` bleiben verbindlich. Diese Datei ergänzt sie für die Verwaltungsoberfläche.
1. `CLAUDE.md`, vorhandene aktive Repository-Regeln und `docs/ux/verwaltung/README.md` lesen.
2. `docs/ux/verwaltung/14-verwaltungsstandard.md` ist die maßgebliche UX-Grundlage. `15-umbauauftrag.md` beschreibt Umsetzung und Nachweise. Keine erneute allgemeine Designfreigabe oder neue Mockups je Screen verlangen.
3. Gemeinsame Komponenten statt kopierter Masken: Rahmen, Listen, Picker, Redaktion, geordnete Zuordnung, Status/Aktionen und Vorschau. Fachlich zulässige Typen und Referenzen sind Kontext derselben Komponente. Vorhanden in `resources/views/filament/verwaltung/`: `kopf` (Objektkopf, Status, Aktionen, Weitere Aktionen), `redaktion` (Manager), `texte`/`textfeld`, `praesentation`/`zuordnung-menue`, `einordnung`, `varianten`, `picker` (auch Aufbau, Vorschaubild und CMS-Bilder; Logik im Trait `ChoosesMedia`), `bestand` (gemeinsame Bestandsliste mit Suche, Filtern, aktiven Filterchips, Zeilen/Kacheln, „Weitere anzeigen“ und Dialogbereich; Trait `ShowsBestand`), Komponente `<x-vw.eintrag>` (Vorschau, Titel, Typzeile; Picker und Listen), `aufbau` (Struktur links, Detail rechts; auch Fassungen eines Mediums), `catalog/objekt` (Angebot, Paket, Rechteprofil), `cms/seite-kopf` (Seiteneditor mit Registern und Kontexten), Webpräsenz `cms/menues` mit `menue-zeile`, `menue-detail`, `ziel-auswahl` (Menüs als Arbeitsstand, breit Liste mit Detail, schmal ein aufgeklappter Eintrag), `bestaetigung` (statt `wire:confirm`), `abgang` (Warnung bei ungespeicherten Änderungen), `styles` (Tokens, einmal je Seite über den Panel-Hook). Logik im Trait `App\Filament\Support\ManagesEditorialSurface`; neue Objektarten liefern nur Feldliste, Einordnungsgruppen und Kopfangaben.
4. Eindeutigen Speicherumfang, Zustand und Vorschau-Datenstand anzeigen. Keine pauschale neue Genehmigungskette. Produktbeschreibung, Lehrinhalt, kommerzielle Daten und technische Verwaltung gezielt gliedern.
5. Redaktion für Medien einschließlich Filmen, Module, Programme und Lizenzartikel gemeinsam nutzen. Zentrale Medien referenzieren, mehrere Medien je Rolle und reine Präsentationsmedien ohne Lehrfassung erhalten.
6. Rückkehr mit offenen Eingaben sicherstellen; kein Pflichtspeichern vor dem Redaktionswechsel, kein heimliches Mitspeichern und kein veraltetes Zurückschreiben.
7. Bestehende Erwerbe, Rechte, Historie und fachliche Fassungsregeln erhalten. Offene Fragen in Dokument 04 nicht selbst durch neue Geschäftsregeln entscheiden; nur tatsächlich abhängige Teile gezielt klären.
8. Bestehende Tokens und freigegebene Assets nutzen. Verwaltungsmaße: `docs/ux/verwaltung/tokens.md`. Bilder sind räumliche Referenzen, keine autoritative Farbquelle oder auszuliefernde UI-Grafik.
9. Betroffene Abläufe funktional und visuell prüfen: Rückkehr, relevante Fehler-/Leer-/Ladezustände, Tastatur, breite/schmalere Fenster und fachliche Regressionen. Bestehende Betriebs- und Testregeln erfüllen.
10. Tatsächliche Komponentenwiederverwendung, Prüfergebnisse, gerenderte Screenshots und konkrete Abweichungen liefern; `docs/ux/verwaltung/regeln/ux-abnahme-vorlage.md` verwenden. Keine unbewiesene Abnahme behaupten.
+15
View File
@@ -0,0 +1,15 @@
.git
.gitea
.env
.env.*
!.env.example
node_modules
vendor
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
public/build
public/hot
docs
*.md
+18
View File
@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[{compose,docker-compose}.{yml,yaml}]
indent_size = 4
+72
View File
@@ -0,0 +1,72 @@
APP_NAME="Lara und Felix"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost:8000
APP_LOCALE=de
APP_FALLBACK_LOCALE=de
APP_FAKER_LOCALE=de_DE
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
PAYMENT_DRIVER=test
# Leer lassen. Lokal gilt dann storage/. Im Container setzt Compose den Host-Mount (/srv/luf/<env>/media/...).
MEDIA_PUBLIC_PATH=
MEDIA_DERIVED_PATH=
MEDIA_ORIGINALS_PATH=
+11
View File
@@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
+28
View File
@@ -0,0 +1,28 @@
name: CI Feature
# Tests auf Feature-Branches, ohne Deployment. Läuft auf dem llm-node-Runner (Label linux_host).
on:
push:
branches: ['feature/**']
jobs:
test:
runs-on: linux_host
env:
REPO_URL: http://192.168.2.144:3000/Lars/laraundfelix.git
steps:
- name: Runner prüfen
shell: bash
run: |
set -euo pipefail
[ "$(hostname)" = "llm-node" ] && [ "$(uname -m)" = "x86_64" ] || { echo "✗ Falscher Runner: $(hostname)/$(uname -m)"; exit 1; }
- name: Commit auschecken und testen
shell: bash
run: |
set -euo pipefail
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
git clone --quiet "$REPO_URL" "$WORK"
cd "$WORK"
git checkout --quiet "${{ github.sha }}"
bash scripts/ci-test.sh
+65
View File
@@ -0,0 +1,65 @@
name: Deploy Production
# main -> Tests auf genau diesem Commit -> Build -> Deploy (Prod) -> Health, bei Fehler Rollback.
# Deploy läuft nur, wenn der Testjob grün ist. Merge auf main nur per freigegebenem Pull Request aus develop
# (Branch-Schutz in Gitea, siehe docs/betrieb/DEPLOYMENT.md).
on:
push:
branches: [main]
jobs:
test:
runs-on: linux_host
env:
REPO_URL: http://192.168.2.144:3000/Lars/laraundfelix.git
steps:
- name: Runner prüfen
shell: bash
run: |
set -euo pipefail
[ "$(hostname)" = "llm-node" ] && [ "$(uname -m)" = "x86_64" ] || { echo "✗ Falscher Runner: $(hostname)/$(uname -m)"; exit 1; }
- name: Commit auschecken und testen
shell: bash
run: |
set -euo pipefail
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
git clone --quiet "$REPO_URL" "$WORK"
cd "$WORK"
git checkout --quiet "${{ github.sha }}"
bash scripts/ci-test.sh
deploy:
needs: test
runs-on: linux_host
env:
LUF_ENV: prod
REPO_URL: http://192.168.2.144:3000/Lars/laraundfelix.git
APP_DIR: /home/llmadmin/docker/luf-prod
ENV_FILE: /etc/luf/prod.env
COMPOSE_PROJECT: luf-prod
WEB_PORT: '3010'
steps:
- name: Runner prüfen
shell: bash
run: |
set -euo pipefail
[ "$(hostname)" = "llm-node" ] && [ "$(uname -m)" = "x86_64" ] || { echo "✗ Falscher Runner: $(hostname)/$(uname -m)"; exit 1; }
- name: Code aktualisieren (getesteter Commit)
shell: bash
run: |
set -euo pipefail
mkdir -p "$APP_DIR"
cd "$APP_DIR"
if [ ! -d .git ]; then
git init -q
git remote add origin "$REPO_URL"
fi
git fetch origin main
git reset --hard "${{ github.sha }}"
git log -1 --oneline
- name: Deploy
shell: bash
run: bash "$APP_DIR/scripts/deploy.sh"
+65
View File
@@ -0,0 +1,65 @@
name: Deploy Test
# develop -> Tests -> Build -> Deploy (Test) -> Health. Deploy läuft nur, wenn die Tests grün sind.
# Aktuell auf llm-node (Runner-Label linux_host). Ein Umzug auf den Raspberry Pi braucht nur geänderte
# Werte in env: (Label runs-on, Hostname/Architektur-Guard, APP_DIR, ENV_FILE, WEB_PORT).
on:
push:
branches: [develop]
jobs:
test:
runs-on: linux_host
env:
REPO_URL: http://192.168.2.144:3000/Lars/laraundfelix.git
steps:
- name: Runner prüfen
shell: bash
run: |
set -euo pipefail
[ "$(hostname)" = "llm-node" ] && [ "$(uname -m)" = "x86_64" ] || { echo "✗ Falscher Runner: $(hostname)/$(uname -m)"; exit 1; }
- name: Commit auschecken und testen
shell: bash
run: |
set -euo pipefail
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
git clone --quiet "$REPO_URL" "$WORK"
cd "$WORK"
git checkout --quiet "${{ github.sha }}"
bash scripts/ci-test.sh
deploy:
needs: test
runs-on: linux_host
env:
LUF_ENV: test
REPO_URL: http://192.168.2.144:3000/Lars/laraundfelix.git
APP_DIR: /home/llmadmin/docker/luf-test
ENV_FILE: /etc/luf/test.env
COMPOSE_PROJECT: luf-test
WEB_PORT: '3011'
steps:
- name: Runner prüfen
shell: bash
run: |
set -euo pipefail
[ "$(hostname)" = "llm-node" ] && [ "$(uname -m)" = "x86_64" ] || { echo "✗ Falscher Runner: $(hostname)/$(uname -m)"; exit 1; }
- name: Code aktualisieren (getesteter Commit)
shell: bash
run: |
set -euo pipefail
mkdir -p "$APP_DIR"
cd "$APP_DIR"
if [ ! -d .git ]; then
git init -q
git remote add origin "$REPO_URL"
fi
git fetch origin develop
git reset --hard "${{ github.sha }}"
git log -1 --oneline
- name: Deploy
shell: bash
run: bash "$APP_DIR/scripts/deploy.sh"
+32 -3
View File
@@ -1,6 +1,35 @@
node_modules/
*.log
.DS_Store
.env
.env.*
dist/
.DS_Store
!.env.example
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.codex
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/css/filament
/public/fonts-manifest.dev.json
/public/fonts/filament
/public/hot
/public/js/filament
/public/storage
/storage/*.key
/storage/pail
/storage/logs/
/vendor
/database/*.sqlite*
/tmp-laravel/
/composer.phar
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
+2
View File
@@ -0,0 +1,2 @@
ignore-scripts=true
audit=true
+13
View File
@@ -0,0 +1,13 @@
# Einstieg für Coding-Agenten
Betriebs-, Test-, Deployment- und Medienschutzregeln stehen in `CLAUDE.md` und in `.cursor/rules/luf-betrieb.mdc`. Sie gelten unverändert.
Für die Verwaltung zusätzlich:
- `docs/ux/verwaltung/14-verwaltungsstandard.md` ist die maßgebliche Designgrundlage, `docs/ux/verwaltung/15-umbauauftrag.md` der konkrete Auftrag. Keine neue allgemeine Designfreigabe oder Screenserie verlangen.
- `docs/ux/verwaltung/README.md` und Dokument 04 für Herkunft und offene Geschäftsfragen. Historische Entwürfe nach der Rangfolge in Dokument 14 lesen.
- Gleichartige Aufgaben mit den gemeinsamen Komponenten unter `resources/views/filament/verwaltung/` und `resources/views/filament/editorial/` lösen. Fachfunktionen, Datenbeziehungen, Rechte und Fassungsbindungen erhalten.
- Offene Eingaben beim Wechsel zur Redaktion und zurück erhalten. Speicherwirkung benennen. Maße in `docs/ux/verwaltung/tokens.md`.
- Hauptabläufe prüfen, bestehende Testpflichten erfüllen, Abweichungen konkret benennen. Keine ungeprüfte Abnahme behaupten.
Diese Datei ergänzt die Betriebsregeln und löst kein Deployment aus.
+68
View File
@@ -0,0 +1,68 @@
# Lara & Felix (LUF) – Arbeitsregeln für Claude
Stack: Laravel 13, PHP 8.4, Filament 5, PostgreSQL, Docker Compose. Repository: Gitea `Lars/laraundfelix` (`git@192.168.2.144:Lars/laraundfelix.git`).
Dokumentation: `docs/` (Architektur, Spezifikation), Betrieb: `docs/betrieb/DEPLOYMENT.md` und `docs/betrieb/Bestandsaufnahme_Deployment_2026-11-15.md`.
## Branches und Deployment (verbindlich)
| Branch | Zweck | Wirkung eines Pushs |
|---|---|---|
| `feature/**` | Einzelne Änderungen | Nur Tests (`ci-feature.yml`) |
| `develop` | **Arbeits- und Integrationsbranch** | Tests, dann Deploy auf **Test** (`deploy-test.yml`, Port 3011) |
| `main` | **Produktion** | Tests, dann Deploy auf **Prod** (`deploy-prod.yml`, Port 3010) |
1. **Gearbeitet wird auf `develop` oder auf `feature/*`-Branches, die in `develop` münden.** Nie direkt auf `main`.
2. **Nie auf `main` pushen, nie nach `main` mergen und keinen Pull Request nach `main` freigeben.** Ein Push auf `main` löst sofort ein Produktiv-Deployment aus. Der Merge `develop` → `main` ist ein **manueller Schritt von Lars** (Pull Request in Gitea, nach Prüfung des Teststands). Claude bereitet höchstens vor: Zusammenfassung der Änderungen seit dem letzten Merge, Stand der Tests, offene Migrationen.
3. Nie `--force`/`--force-with-lease` auf `develop` oder `main`. Kein `git reset --hard` auf geteilten Branches.
4. Vor einem Push auf `develop` prüfen, dass die Tests lokal bzw. im Feature-Branch grün waren. Fehlgeschlagene Tests blockieren das Deployment (`needs: test`); sie nicht umgehen oder deaktivieren.
5. **Claude deployt nie von Hand.** Keine `docker compose`-, `deploy.sh`- oder `systemctl`-Aufrufe auf den Servern. Deployments entstehen ausschließlich durch die Gitea-Workflows.
6. Ein roter Workflow wird behoben, nicht überbrückt. Der Rollback im Deploy-Skript setzt nur den Code zurück, nicht die Datenbank.
## Tests
- **Jede Änderung am Verhalten bringt Tests mit** (Feature-Tests für Abläufe, Berechtigungen und Lizenzlogik, Unit-Tests für reine Logik). Fehler werden erst durch einen fehlschlagenden Test reproduziert, dann behoben.
- Es gibt zwei Stufen, beide als eigene Gitea-Jobs:
1. **Gate vor dem Deploy** (`scripts/ci-test.sh`, Wegwerf-Container, Pint und `php artisan test`). Gilt für `feature/**`, `develop` und `main` und blockiert jedes Deployment.
2. **Suite auf der Test-Instanz** (wie bei Shinkan, eigener Workflow nach dem Deploy auf `develop`): Integrations- und Browser-Tests gegen die laufende Test-Instanz (`luf-test`). Eigener Workflow, nicht Teil von `deploy-test.yml`. Wird mit U0 angelegt.
- **Tests laufen nie gegen Prod** (`luf-prod`): nicht gegen deren Datenbank, Volumes oder Medien-Mounts, nicht in deren Containern, nicht gegen deren URL. Prod prüfen allein das Gate und die Health-Checks des Deploys. (Bei Shinkan hätten Integrationstests nach einem Prod-Deploy in die Prod-Datenbank geschrieben.)
- **Auf der Test-Instanz** dürfen Tests Daten in der Test-Datenbank anlegen, aber nie die Schemas zurücksetzen: kein `RefreshDatabase`, `migrate:fresh` oder `DatabaseTruncation` gegen `luf-test`, solange die Instanz nicht ausdrücklich dafür vorgesehen ist. Laravel-Env-Werte aus dem Container (`DB_CONNECTION=pgsql`) überschreiben die SQLite-Vorgabe der `phpunit.xml`. Ein Lauf von `php artisan test` im Test-Container würde sonst die Test-Datenbank leeren. Deshalb die Instanz-Suite über HTTP (Pest-Browser/Playwright) oder in einem eigenen Container mit eigener Wegwerf-Datenbank laufen lassen.
- Tests dürfen keine Netzwerkaufrufe an echte Dienste machen (Mail, Zahlung, externe APIs). Dafür Fakes verwenden (`Mail::fake()`, `Http::fake()`, `Storage::fake()`).
- **Ein roter Test wird behoben, nicht umgangen.** Kein `skip`, `markTestSkipped`, Löschen oder Abschwächen von Assertions und kein Deaktivieren von Pint, nur um grün zu werden. Ist ein Test fachlich überholt, wird er bewusst geändert und im Commit begründet.
- Tests sind deterministisch: keine Abhängigkeit von Reihenfolge, Uhrzeit oder Zufall ohne feste Werte (`Carbon::setTestNow`, Seeds).
- **Datenbank in der Suite:** Standard ist die SQLite-In-Memory-Konfiguration aus `phpunit.xml`. Tests, die PostgreSQL-spezifisches Verhalten brauchen (JSONB, Constraints, Migrationen), laufen gegen eine eigene Wegwerf-PostgreSQL-Instanz, nicht gegen `luf-test` oder `luf-prod`. Diese Instanz ist in `scripts/ci-test.sh` noch nicht eingebaut und wird mit U0 ergänzt.
- Ein Commit auf `develop` ohne grüne Suite ist nicht zulässig. Wer die Suite nicht lokal oder auf einem Feature-Branch laufen lassen kann, sagt das, statt trotzdem auf `develop` zu pushen.
## Migrationen
- Migrationen müssen **abwärtskompatibel** sein (erst ergänzen, später entfernen), weil der Rollback nur den Code zurücksetzt.
- Keine Migration, die Daten löscht oder umbenennt, ohne vorherige Freigabe von Lars und ein bestätigtes Backup.
## Server und Umgebungen
- Test und Prod laufen vorerst **beide auf `llm-node` (192.168.2.144)**, getrennt durch Compose-Projekt (`luf-test`, `luf-prod`), Verzeichnis, Env-Datei, Volumes und Zugangsdaten. Der Raspberry Pi ist als späteres Testsystem vorgesehen (Umzug über die Variablen in `deploy-test.yml`).
- Secrets liegen nur in `/etc/luf/test.env` und `/etc/luf/prod.env` auf dem Server. **Keine Secrets, Passwörter, Keys oder `.env`-Dateien ins Repo, in Commits, Logs oder Chat-Ausgaben.**
- **Auf Servern wird nur nach ausdrücklicher Freigabe geschrieben.** Rein lesende Abfragen über vorhandene SSH-Zugänge sind erlaubt. Keine SSH-Schlüssel, Benutzer, Firewall-, Proxy- oder Runner-Änderungen. Andere Anwendungen auf den Servern (Shinkan, Gitea, mindnet, qdrant, …) dürfen nicht verändert werden.
- Ports werden nicht geraten: Vor jedem neuen Host-Port die tatsächliche Belegung prüfen (`ss`, `docker ps`). Aktuell vorgesehen: Test 3011, Prod 3010 (Stand 2026-11-15). Datenbank und PHP-FPM veröffentlichen keine Host-Ports.
- Der Reverse Proxy (Synology NAS) wird von Lars verwaltet.
- Shell-Zugriff auf llm-node: `ssh -T llmadmin@192.168.2.144 '<befehl>' </dev/null`, nur lesend und nur mit vorhandenem Key.
## Medien
- Medien liegen auf dem NAS (NFS), je Umgebung eigener Bestand: Test `luf_media_dev`, Prod `luf_media`. Mountpunkte `/srv/luf/test/media` und `/srv/luf/prod/media`. Die Umgebungen dürfen nie auf den Bestand der anderen zeigen.
- Im Container gilt derselbe Pfad wie auf dem Host (`/srv/luf/test/media` bzw. `/srv/luf/prod/media`, Unterordner `originals/`, `derived/`, `public/`). **Der Web-Prozess hat keinen Zugriff auf `originals/`** und liest `derived/` und `public/` nur. Nur die Hintergrundverarbeitung (`queue`) schreibt. Diese Trennung (Architektur 03 und 08) nicht aufweichen, auch nicht „vorübergehend“.
- Private Medien werden nie über einen statischen öffentlichen Pfad ausgeliefert, sondern nur nach Berechtigungsentscheidung über kurzlebige Signaturen.
- Mounts am Server (fstab) und NFS-Freigaben auf dem NAS ändert Lars. Claude liefert die Zeilen, schreibt sie aber nicht.
## Entwicklung
- Zeilenenden: `.gitattributes` erzwingt LF (lokal ist `core.autocrlf=true` gesetzt). Shell-Skripte nie mit CRLF committen.
- Commits: kurze, deutsche oder englische Betreffzeile im Imperativ, ein logischer Schritt pro Commit.
- Änderungen an `.gitea/workflows/`, `Dockerfile`, `docker-compose.yml` und `scripts/deploy.sh` wirken direkt auf Test und Prod. Sie werden nur gezielt und mit Begründung geändert und in `docs/betrieb/DEPLOYMENT.md` nachgeführt.
- Nicht verifizierte Aussagen zu Servern oder Kapazitäten werden als solche gekennzeichnet. Nichts erfinden (Ports, Hostnamen, Pfade, Zugangsdaten).
## Verwaltungsoberfläche
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
- Die Redaktion ist ein Arbeitsstand: nur „Redaktion speichern“ schreibt Texte, Einordnung, Präsentationsmedien und Abweichungen. Kein verdecktes Mitspeichern aus anderen Dialogen, offene Eingaben bleiben beim Wechsel erhalten.
- Jede UI-Änderung in der echten Anwendung prüfen (luf-test, breite und schmale Fenster, Tastatur) und mit Screenshots in `docs/ux/verwaltung/abnahme/` belegen. Stand der Abnahme: `abnahme/teil-a.md`, `abnahme/teil-b.md`, `abnahme/teil-c.md`, `abnahme/stammdaten.md`.
+55
View File
@@ -0,0 +1,55 @@
# syntax=docker/dockerfile:1
# LUF – Laravel 13 / PHP 8.4 / Filament 5
# Targets: app (php-fpm, auch Queue und Scheduler), web (nginx mit statischen Assets), test (CI)
# Setzt eine Laravel-Anwendung im Repo-Root voraus (composer.json, composer.lock, package.json). Kommt mit U0.
ARG PHP_VERSION=8.4
# ---- Basis: PHP mit den Erweiterungen für Laravel und Filament -------------------------------
FROM php:${PHP_VERSION}-fpm-alpine AS base
RUN apk add --no-cache icu-libs libzip libpng libjpeg-turbo freetype libpq oniguruma su-exec ffmpeg \
&& apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev postgresql-dev oniguruma-dev \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j"$(nproc)" pdo_pgsql intl zip gd bcmath opcache pcntl exif \
&& apk del .build-deps
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
WORKDIR /var/www/html
# ---- Produktions-Abhängigkeiten --------------------------------------------------------------
FROM base AS vendor
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --no-autoloader --prefer-dist --no-interaction
COPY . .
RUN composer dump-autoload --no-dev --optimize --no-interaction \
&& APP_KEY=base64:MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= php artisan filament:assets --ansi --no-interaction
# ---- Frontend-Assets (Filament-Theme braucht vendor/) ----------------------------------------
FROM node:22-alpine AS assets
WORKDIR /app
COPY --from=vendor /var/www/html /app
RUN npm ci && npm run build
# ---- Test-Image (CI): inkl. Dev-Abhängigkeiten, führt Pint und Tests aus ---------------------
FROM base AS test
COPY composer.json composer.lock ./
RUN composer install --prefer-dist --no-scripts --no-autoloader --no-interaction
COPY . .
RUN composer dump-autoload --optimize --no-interaction
ENV APP_ENV=testing
CMD ["sh", "-ec", "if [ -x vendor/bin/pint ]; then vendor/bin/pint --test; fi; php artisan test --compact"]
# ---- App (php-fpm; derselbe Tag dient für Queue und Scheduler) -------------------------------
FROM base AS app
COPY --from=vendor /var/www/html /var/www/html
COPY --from=assets /app/public/build /var/www/html/public/build
COPY docker/entrypoint.sh /usr/local/bin/entrypoint
COPY docker/php.ini /usr/local/etc/php/conf.d/zz-luf.ini
RUN chmod +x /usr/local/bin/entrypoint
ENTRYPOINT ["entrypoint"]
CMD ["php-fpm"]
# ---- Web (nginx, nur öffentliche Dateien) ----------------------------------------------------
FROM nginx:1.27-alpine AS web
COPY docker/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=vendor /var/www/html/public /var/www/html/public
COPY --from=assets /app/public/build /var/www/html/public/build
+7
View File
@@ -0,0 +1,7 @@
# Lara & Felix – Stark im Alltag
Laravel-13-Anwendung mit Filament 5 und PostgreSQL.
Gearbeitet wird auf `develop`. Ein Push auf `develop` testet und deployt auf die Testumgebung. `main` ist Produktion und wird nicht direkt beschrieben. Die Betriebsregeln stehen in `CLAUDE.md`.
Lokal: `composer install`, `.env` aus `.env.example`, `php artisan key:generate`, `php artisan migrate`, `npm install`, `npm run build`, `php artisan test`.
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Auth;
class StaffAuthenticatorName
{
public static function current(): string
{
return app()->isProduction() ? 'Lara&Felix' : 'Lara&Felix (dev)';
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
class TrustedStaffDevice
{
public const COOKIE = 'luf_staff_mfa';
public const DAYS = 30;
public function remember(User $user): void
{
Cookie::queue(cookie(
self::COOKIE,
$this->token($user),
self::DAYS * 24 * 60,
'/',
null,
request()->isSecure(),
true,
false,
'lax',
));
}
public function token(User $user): string
{
return Crypt::encryptString(json_encode([
'user' => $user->getKey(),
'until' => now()->addDays(self::DAYS)->getTimestamp(),
'secret' => $this->fingerprint($user),
], JSON_THROW_ON_ERROR));
}
public function isTrusted(User $user, ?Request $request = null): bool
{
$request ??= request();
$token = $request->cookies->get(self::COOKIE);
if (! is_string($token) || $token === '') {
return false;
}
try {
$payload = json_decode(Crypt::decryptString($token), true, 8, JSON_THROW_ON_ERROR);
} catch (\Throwable) {
return false;
}
if (! is_array($payload)) {
return false;
}
$until = $payload['until'] ?? null;
$fingerprint = $payload['secret'] ?? null;
return (int) ($payload['user'] ?? 0) === (int) $user->getKey()
&& is_int($until)
&& $until >= now()->getTimestamp()
&& is_string($fingerprint)
&& hash_equals($this->fingerprint($user), $fingerprint);
}
private function fingerprint(User $user): string
{
return hash('sha256', (string) $user->getAppAuthenticationSecret());
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Domain\Identity\AssignStaffRoles;
use App\Domain\Identity\RegisterAccount;
use App\Domain\Identity\StaffRole;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class CreateStaffUser extends Command
{
protected $signature = 'luf:personal {email} {--role=systemverwalter} {--name=Personal}';
protected $description = 'Legt ein bestätigtes Personalkonto an und gibt das Passwort einmal aus';
public function handle(RegisterAccount $register, AssignStaffRoles $assign): int
{
$role = StaffRole::tryFrom((string) $this->option('role'));
if ($role === null) {
$this->error('Unbekannte Rolle.');
return self::FAILURE;
}
$password = Str::password(20);
$user = $register->register((string) $this->option('name'), (string) $this->argument('email'), $password, true);
$user->markEmailAsVerified();
$assign->sync($user, [$role->value], $user);
$this->info('Konto angelegt. Passwort (nur diese Ausgabe):');
$this->line($password);
return self::SUCCESS;
}
}
@@ -0,0 +1,87 @@
<?php
namespace App\Console\Commands;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageRevision;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Throwable;
/**
* Wiederherstellungsweg vor einem Code-Rollback (docs/architektur/cms-widget-registry.md, Abschnitt Rollback).
*
* Setzt die veröffentlichte Revision jeder Seite auf die letzte Revision, die vor dem angegebenen Zeitpunkt
* gespeichert wurde. Revisionen werden weder geändert noch gelöscht; nur der Veröffentlichungszeiger wechselt.
* Ohne --apply wird nur angezeigt, was geschähe.
*/
class RevertPublishedPages extends Command
{
protected $signature = 'cms:revert-published
{--before= : Zeitpunkt des Deployments, zum Beispiel "2026-11-17 18:00" (Zeitzone der Anwendung)}
{--apply : Änderung tatsächlich ausführen}';
protected $description = 'Setzt veröffentlichte Seiten auf ihren Stand vor einem Zeitpunkt zurück (nur Veröffentlichungszeiger).';
public function handle(): int
{
try {
$before = blank($this->option('before')) ? null : CarbonImmutable::parse((string) $this->option('before'));
} catch (Throwable) {
$before = null;
}
if ($before === null) {
$this->error('Bitte --before mit einem gültigen Zeitpunkt angeben.');
return self::FAILURE;
}
$apply = (bool) $this->option('apply');
$rows = [];
foreach (Page::query()->whereNotNull('published_revision_id')->with('publishedRevision')->orderBy('path')->get() as $page) {
$current = $page->publishedRevision;
if ($current === null || $current->created_at < $before) {
continue;
}
$previous = PageRevision::query()
->where('page_id', $page->id)
->where('created_at', '<', $before)
->latest('id')
->first();
if ($previous === null) {
$rows[] = [$page->path, $current->id, '–', 'keine ältere Revision: Seite wird zurückgezogen'];
if ($apply) {
$page->published_revision_id = null;
$page->save();
}
continue;
}
$rows[] = [$page->path, $current->id, $previous->id, $apply ? 'zurückgesetzt' : 'würde zurückgesetzt'];
if ($apply) {
$page->published_revision_id = $previous->id;
$page->save();
}
}
if ($rows === []) {
$this->info('Keine veröffentlichte Seite stammt aus der Zeit ab '.$before->format('d.m.Y H:i').'.');
return self::SUCCESS;
}
$this->table(['Pfad', 'veröffentlicht', 'neu veröffentlicht', 'Ergebnis'], $rows);
if (! $apply) {
$this->warn('Probelauf. Mit --apply ausführen.');
}
return self::SUCCESS;
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
namespace App\Console\Commands;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Identity\AccountStatus;
use App\Domain\Identity\Party;
use App\Domain\Identity\PartyType;
use App\Domain\Identity\Profile;
use App\Models\User;
use Illuminate\Console\Command;
class SeedLibraryReview extends Command
{
protected $signature = 'library:review-fixture {--actor=}';
protected $description = 'Legt einmalig einen gekennzeichneten Prüfbestand für die Bibliothek an';
public function handle(
ContentService $content,
ArticleService $articles,
OfferService $offers,
CompositionDisplayRelease $display,
): int {
$existing = Composition::query()->where('designation', 'Prüfprogramm Abstand')->first();
if ($existing === null) {
$created = $this->createFixture($content, $articles, $offers, $display);
if ($created !== self::SUCCESS) {
return $created;
}
} else {
$existing->display_title = 'Prüfprogramm Abstand und ein bewusst langer Titel für die Kursraumansicht';
$existing->summary = 'Gekennzeichneter Prüfbestand für die Testinstanz. Der Titel ist lang, damit die Karte im Kursraum prüfbar bleibt.';
$existing->save();
}
$this->ensureTrainer();
$this->info('Prüfbestand und Trainingskonto sind bereit.');
return self::SUCCESS;
}
private function createFixture(
ContentService $content,
ArticleService $articles,
OfferService $offers,
CompositionDisplayRelease $display,
): int {
$actor = User::query()->find($this->option('actor')) ?? User::query()->orderBy('id')->first();
if ($actor === null) {
$this->error('Es gibt kein Konto, das die Anzeigefreigabe zeichnen kann.');
return self::FAILURE;
}
$kind = EditorialContentKind::query()->where('slug', 'programm')->first();
if ($kind === null) {
$this->error('Die fachliche Materialart Programm fehlt.');
return self::FAILURE;
}
$sheet = $content->publishElementVersion(
$content->createElement('text', 'document', 'Prüfblatt Abstand'),
'Gekennzeichneter Prüftext. Kein Veröffentlichungstext.',
);
$composition = $content->createComposition('Prüfprogramm Abstand');
$composition->editorial_content_kind_id = $kind->id;
$composition->display_title = 'Prüfprogramm Abstand und ein bewusst langer Titel für die Kursraumansicht';
$composition->summary = 'Gekennzeichneter Prüfbestand für die Testinstanz. Der Titel ist lang, damit die Karte im Kursraum prüfbar bleibt.';
$composition->thumbnail_error = 'Prüfhinweis: kein Vorschaubild.';
$composition->save();
$version = $content->publishComposition($composition, [
['role' => 'Blatt', 'target' => $sheet],
], $actor, 'Prüfbestand', [
'learning_goal' => 'Den Prüfaufbau in der Bibliothek sehen.',
'duration_minutes' => 5,
'material_note' => 'Nur der Prüftext.',
]);
$article = $articles->create('pruef-abstand');
$articles->publishRelease($article, $version, 'Prüffassung.');
$rights = $offers->createRightsProfile('Prüfblatt ansehen', 'ehrenamtlich', [
'document' => ['ansehen', 'laden'],
]);
$offer = $offers->create('Prüfprogramm Abstand');
$offers->activate($offer, [
['target' => $article->fresh(), 'rights' => $rights],
], ['grant_kind' => 'auf_abruf', 'composition_version_id' => $version->id]);
$display->release($version, $actor, 'Prüffreigabe');
return self::SUCCESS;
}
private function ensureTrainer(): void
{
$trainer = User::query()->where('email', 'trainer-pruefung@example.test')->first();
if ($trainer === null) {
$party = Party::query()->create([
'type' => PartyType::Person,
'display_name' => 'Trainer Prüfung',
]);
Profile::query()->create([
'party_id' => $party->id,
'display_name' => 'Trainer Prüfung',
'visibility' => ['display_name' => 'private'],
]);
$trainer = new User;
$trainer->forceFill([
'party_id' => $party->id,
'name' => 'Trainer Prüfung',
'email' => 'trainer-pruefung@example.test',
'password' => 'Kursraum-Pruefung',
'status' => AccountStatus::Aktiv,
'confirmed_adult_at' => now(),
'email_verified_at' => now(),
]);
$trainer->save();
}
$offer = Offer::query()->where('name', 'Prüfprogramm Abstand')->first();
if ($offer !== null) {
app(GrantIssuer::class)->claim($trainer, $offer);
}
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ArticleRelease extends Model
{
protected $fillable = [
'license_article_id',
'number',
'change_kind',
'important',
'classification_note',
'status',
'block_reason',
'fallback_release_id',
'change_note',
'impact_report',
'root_element_version_id',
'root_composition_version_id',
];
protected function casts(): array
{
return [
'important' => 'boolean',
'status' => ReleaseStatus::class,
'impact_report' => 'array',
];
}
protected static function booted(): void
{
static::updating(function (ArticleRelease $release): void {
$original = StatusValue::of($release->getOriginal('status'));
$next = StatusValue::of($release->status);
$locked = [
ReleaseStatus::Veroeffentlicht->value,
ReleaseStatus::AbgeloestVerfuegbar->value,
ReleaseStatus::Gesperrt->value,
];
if (! in_array($original, $locked, true)) {
return;
}
$allowedFields = ['status', 'updated_at'];
if ($original === ReleaseStatus::Veroeffentlicht->value && $next === ReleaseStatus::Gesperrt->value) {
$allowedFields = ['status', 'updated_at', 'block_reason', 'fallback_release_id'];
}
if (array_diff(array_keys($release->getDirty()), $allowedFields) !== []) {
throw new DomainRuleException('Ein veröffentlichter Artikel-Stand ist unveränderlich.');
}
$allowed = match ($original) {
ReleaseStatus::Veroeffentlicht->value => [
ReleaseStatus::AbgeloestVerfuegbar->value,
ReleaseStatus::Gesperrt->value,
],
ReleaseStatus::AbgeloestVerfuegbar->value => [
ReleaseStatus::Veroeffentlicht->value,
],
default => [],
};
if (! in_array($next, $allowed, true)) {
throw new DomainRuleException('Dieser Statuswechsel eines Artikel-Stands ist nicht zulässig.');
}
});
}
public function article(): BelongsTo
{
return $this->belongsTo(LicenseArticle::class, 'license_article_id');
}
public function contents(): HasMany
{
return $this->hasMany(ReleaseContent::class)->orderBy('position');
}
public function rootElementVersion(): BelongsTo
{
return $this->belongsTo(ContentElementVersion::class, 'root_element_version_id');
}
public function rootCompositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class, 'root_composition_version_id');
}
}
+191
View File
@@ -0,0 +1,191 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Entitlement\Acquisition;
use App\Domain\Entitlement\GrantStatus;
use Illuminate\Support\Facades\DB;
class ArticleService
{
public function __construct(private readonly ContentResolver $resolver) {}
public function create(string $code, ?string $productLine = null): LicenseArticle
{
$code = trim($code);
if ($code === '') {
throw new DomainRuleException('Die Kennung des Lizenzartikels fehlt.');
}
return LicenseArticle::query()->create([
'code' => $code,
'product_line' => $productLine !== null && trim($productLine) !== '' ? trim($productLine) : null,
]);
}
public function publishRelease(
LicenseArticle $article,
ContentElementVersion|CompositionVersion $root,
string $classification,
?string $changeNote = null,
): ArticleRelease {
$classification = trim($classification);
if ($classification === '') {
throw new DomainRuleException('Ein neuer Stand braucht eine Einordnung, warum er zum selben Artikel gehört.');
}
$this->checkedRows($root);
return DB::transaction(function () use ($article, $root, $classification, $changeNote): ArticleRelease {
$rows = $this->checkedRows($root);
$impact = $this->impact($article, count($rows));
$release = $article->releases()->create([
'number' => ((int) $article->releases()->max('number')) + 1,
'classification_note' => $classification,
'status' => ReleaseStatus::Entwurf,
'change_note' => $changeNote,
'impact_report' => $impact,
'root_element_version_id' => $root instanceof ContentElementVersion ? $root->id : null,
'root_composition_version_id' => $root instanceof CompositionVersion ? $root->id : null,
]);
foreach ($rows as $index => $row) {
$release->contents()->create([
'position' => $index + 1,
'content_element_version_id' => $row['version_id'],
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
'path' => $row['path'],
]);
}
ArticleRelease::query()
->where('license_article_id', $article->id)
->where('status', ReleaseStatus::Veroeffentlicht)
->whereKeyNot($release->id)
->each(function (ArticleRelease $previous): void {
$previous->status = ReleaseStatus::AbgeloestVerfuegbar;
$previous->save();
});
$release->status = ReleaseStatus::Veroeffentlicht;
$release->save();
$article->current_release_id = $release->id;
$article->save();
return $release->load('contents');
});
}
/**
* @return array{fallback_number: int|null, holders: list<string>}
*/
public function withdraw(LicenseArticle $article, string $reason): array
{
$reason = trim($reason);
if ($reason === '') {
throw new DomainRuleException('Ein Rückzug braucht eine Begründung.');
}
return DB::transaction(function () use ($article, $reason): array {
$article->refresh();
$current = $article->currentRelease;
if ($current === null || $current->status !== ReleaseStatus::Veroeffentlicht) {
throw new DomainRuleException('Zurückziehen lässt sich nur der aktuell veröffentlichte Stand.');
}
$fallback = ArticleRelease::query()
->where('license_article_id', $article->id)
->where('status', ReleaseStatus::AbgeloestVerfuegbar)
->orderByDesc('number')
->first();
$current->status = ReleaseStatus::Gesperrt;
$current->block_reason = $reason;
$current->fallback_release_id = $fallback?->id;
$current->save();
if ($fallback instanceof ArticleRelease) {
$fallback->status = ReleaseStatus::Veroeffentlicht;
$fallback->save();
$article->current_release_id = $fallback->id;
} else {
$article->current_release_id = null;
}
$article->save();
return [
'fallback_number' => $fallback?->number,
'holders' => Acquisition::query()
->whereHas('grants', fn ($query) => $query
->where('license_article_id', $article->id)
->where('status', GrantStatus::Aktiv))
->with('party')
->get()
->map(fn (Acquisition $acquisition): string => $acquisition->party->display_name)
->unique()
->values()
->all(),
];
});
}
/**
* @return list<array{version_id: int, role: string, path: string}>
*/
private function checkedRows(ContentElementVersion|CompositionVersion $root): array
{
$root->refresh();
if ($root->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
}
$rows = $this->resolver->expand($root);
if ($rows === []) {
throw new DomainRuleException('Ein Artikel-Stand braucht mindestens eine Inhaltsfassung.');
}
$blocked = ContentElementVersion::query()
->whereIn('id', array_column($rows, 'version_id'))
->where('status', '!=', ContentVersionStatus::Bereit->value)
->exists();
if ($blocked) {
throw new DomainRuleException('Eine gesperrte Inhaltsfassung kann nicht veröffentlicht werden.');
}
return $rows;
}
/**
* @return array{holders: int, offers: list<string>, contents: int, replaces_number: int|null}
*/
private function impact(LicenseArticle $article, int $contents): array
{
$article->loadMissing('currentRelease');
return [
'holders' => Acquisition::query()
->whereHas('grants', fn ($query) => $query
->where('license_article_id', $article->id)
->where('status', GrantStatus::Aktiv))
->distinct()
->count('party_id'),
'offers' => Offer::query()
->whereHas('versions', fn ($query) => $query
->where('status', OfferStatus::Aktiv)
->whereHas('resolvedScopes', fn ($scope) => $scope->where('license_article_id', $article->id)))
->orderBy('name')
->pluck('name')
->all(),
'contents' => $contents,
'replaces_number' => $article->currentRelease?->number,
];
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Bundle extends Model
{
protected $fillable = [
'name',
'archived_at',
];
protected function casts(): array
{
return [
'archived_at' => 'datetime',
];
}
public function versions(): HasMany
{
return $this->hasMany(BundleVersion::class);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BundleItem extends Model
{
protected $fillable = [
'bundle_version_id',
'position',
'license_article_id',
'nested_bundle_id',
];
protected static function booted(): void
{
static::creating(function (BundleItem $item): void {
$status = BundleVersion::query()->whereKey($item->bundle_version_id)->value('status');
if (StatusValue::of($status) === BundleStatus::Veroeffentlicht->value) {
throw new DomainRuleException('Eine veröffentlichte Paketfassung nimmt keine weiteren Bestandteile auf.');
}
});
static::updating(function (): void {
throw new DomainRuleException('Bestandteile einer Paketfassung sind unveränderlich.');
});
}
public function bundleVersion(): BelongsTo
{
return $this->belongsTo(BundleVersion::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(LicenseArticle::class, 'license_article_id');
}
public function nestedBundle(): BelongsTo
{
return $this->belongsTo(Bundle::class, 'nested_bundle_id');
}
}
+137
View File
@@ -0,0 +1,137 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Support\Facades\DB;
class BundleService
{
public function create(string $name): Bundle
{
$name = trim($name);
if ($name === '') {
throw new DomainRuleException('Der Name des Pakets fehlt.');
}
return Bundle::query()->create([
'name' => $name,
]);
}
/**
* @param list<LicenseArticle|Bundle> $items
*/
public function publish(Bundle $bundle, array $items): BundleVersion
{
if ($items === []) {
throw new DomainRuleException('Ein Paket braucht mindestens einen Bestandteil.');
}
$this->assertItems($items);
$this->collectArticleIds($bundle->id, $items);
return DB::transaction(function () use ($bundle, $items): BundleVersion {
$version = $bundle->versions()->create([
'number' => ((int) $bundle->versions()->max('number')) + 1,
'status' => BundleStatus::Entwurf,
]);
foreach (array_values($items) as $index => $item) {
$version->items()->create([
'position' => $index + 1,
'license_article_id' => $item instanceof LicenseArticle ? $item->id : null,
'nested_bundle_id' => $item instanceof Bundle ? $item->id : null,
]);
}
$version->status = BundleStatus::Veroeffentlicht;
$version->save();
return $version->load('items');
});
}
/**
* @return list<int>
*/
public function articleIds(BundleVersion $version): array
{
return $this->collectArticleIds($version->bundle_id, $this->targetsOf($version));
}
/**
* @param list<LicenseArticle|Bundle> $items
*/
private function assertItems(array $items): void
{
foreach ($items as $item) {
if (! $item instanceof LicenseArticle && ! $item instanceof Bundle) {
throw new DomainRuleException('Ein Paket enthält nur Lizenzartikel oder andere Pakete.');
}
}
}
/**
* @param list<LicenseArticle|Bundle> $items
* @param list<int> $stack
* @return list<int>
*/
private function collectArticleIds(int $bundleId, array $items, array $stack = []): array
{
if (in_array($bundleId, $stack, true)) {
throw new DomainRuleException('Pakete dürfen keinen Zyklus bilden.');
}
$stack[] = $bundleId;
$articleIds = [];
foreach ($items as $item) {
if ($item instanceof LicenseArticle) {
$articleIds[$item->id] = $item->id;
continue;
}
$published = $this->publishedVersion($item);
if ($published === null) {
throw new DomainRuleException('Ein eingebettetes Paket braucht eine veröffentlichte Fassung.');
}
foreach ($this->collectArticleIds($item->id, $this->targetsOf($published), $stack) as $articleId) {
$articleIds[$articleId] = $articleId;
}
}
return array_values($articleIds);
}
private function publishedVersion(Bundle $bundle): ?BundleVersion
{
return $bundle->versions()
->where('status', BundleStatus::Veroeffentlicht)
->orderByDesc('number')
->first();
}
/**
* @return list<LicenseArticle|Bundle>
*/
private function targetsOf(BundleVersion $version): array
{
$targets = [];
foreach ($version->items()->orderBy('position')->get() as $item) {
$target = $item->article ?? $item->nestedBundle;
if ($target === null) {
throw new DomainRuleException('Ein Paketbestandteil braucht genau ein Ziel.');
}
$targets[] = $target;
}
return $targets;
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace App\Domain\Catalog;
enum BundleStatus: string
{
case Entwurf = 'entwurf';
case Veroeffentlicht = 'veroeffentlicht';
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class BundleVersion extends Model
{
protected $fillable = [
'bundle_id',
'number',
'status',
];
protected function casts(): array
{
return [
'status' => BundleStatus::class,
];
}
protected static function booted(): void
{
static::updating(function (BundleVersion $version): void {
if (StatusValue::of($version->getOriginal('status')) === BundleStatus::Veroeffentlicht->value) {
throw new DomainRuleException('Eine veröffentlichte Paketfassung ist unveränderlich.');
}
});
}
public function bundle(): BelongsTo
{
return $this->belongsTo(Bundle::class);
}
public function items(): HasMany
{
return $this->hasMany(BundleItem::class)->orderBy('position');
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CompatibilityAttestation extends Model
{
public $timestamps = false;
protected $fillable = [
'composition_version_id',
'resolved_hash',
'confirmed_by',
'confirmed_at',
'note',
];
protected function casts(): array
{
return [
'confirmed_at' => 'datetime',
];
}
public function compositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class);
}
public function confirmer(): BelongsTo
{
return $this->belongsTo(User::class, 'confirmed_by');
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Composition extends Model
{
protected $fillable = [
'designation',
'display_title',
'teaser',
'summary',
'description',
'search_terms',
'thumbnail_path',
'thumbnail_alt',
'thumbnail_source',
'thumbnail_error',
'public_slug',
'kind',
'editorial_content_kind_id',
'archived_at',
'working_draft',
];
protected function casts(): array
{
return [
'kind' => CompositionKind::class,
'archived_at' => 'datetime',
'working_draft' => 'array',
];
}
public function editorialContentKind(): BelongsTo
{
return $this->belongsTo(EditorialContentKind::class);
}
public function versions(): HasMany
{
return $this->hasMany(CompositionVersion::class);
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class CompositionDisplayRelease
{
public function isReleased(CompositionVersion $version): bool
{
return $this->latestEvent($version)?->event === CompositionVersionDisplayEvent::RELEASED;
}
public function highestReleasedVersion(Composition $composition): ?CompositionVersion
{
return $composition->versions()
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->get()
->first(fn (CompositionVersion $version): bool => $this->isReleased($version));
}
public function release(CompositionVersion $version, User $actor, ?string $note = null): CompositionVersionDisplayEvent
{
$this->assertBereit($version);
return DB::transaction(function () use ($version, $actor, $note): CompositionVersionDisplayEvent {
return $version->displayEvents()->create([
'event' => CompositionVersionDisplayEvent::RELEASED,
'actor_id' => $actor->id,
'occurred_at' => now(),
'note' => $note !== null && trim($note) !== '' ? trim($note) : null,
]);
});
}
public function revoke(CompositionVersion $version, User $actor, ?string $note = null): CompositionVersionDisplayEvent
{
$this->assertBereit($version);
if (! $this->isReleased($version)) {
throw new DomainRuleException('Diese Fassung ist nicht zur Anzeige freigegeben.');
}
return DB::transaction(function () use ($version, $actor, $note): CompositionVersionDisplayEvent {
return $version->displayEvents()->create([
'event' => CompositionVersionDisplayEvent::REVOKED,
'actor_id' => $actor->id,
'occurred_at' => now(),
'note' => $note !== null && trim($note) !== '' ? trim($note) : null,
]);
});
}
public function latestEvent(CompositionVersion $version): ?CompositionVersionDisplayEvent
{
return $version->displayEvents()->reorder()->orderByDesc('occurred_at')->orderByDesc('id')->first();
}
private function assertBereit(CompositionVersion $version): void
{
if ($version->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Nur eine bereitgestellte Kompositionsfassung kann freigegeben werden.');
}
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace App\Domain\Catalog;
enum CompositionKind: string
{
case Kombination = 'kombination';
case Uebung = 'uebung';
case Kurs = 'kurs';
public function label(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombination',
self::Uebung => 'Übung',
self::Kurs => 'Kurs',
};
}
public function plural(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombinationen',
self::Uebung => 'Übungen',
self::Kurs => 'Kurse',
};
}
public function createLabel(): string
{
return match ($this) {
self::Kombination => 'Kombination anlegen',
self::Uebung => 'Übung anlegen',
self::Kurs => 'Kurs anlegen',
};
}
public function explanation(): string
{
return match ($this) {
self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.',
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
};
}
public function deskLabel(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombination',
self::Uebung => 'Modul',
self::Kurs => 'Programm',
};
}
public function deskExplanation(): string
{
return match ($this) {
self::Kombination => $this->explanation(),
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
};
}
/**
* @return array<string, string>
*/
public static function deskOptions(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->deskLabel();
}
return $options;
}
/**
* @return array<string, string>
*/
public static function options(): array
{
$options = [];
foreach (self::cases() as $case) {
$options[$case->value] = $case->label();
}
return $options;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CompositionMember extends Model
{
protected $fillable = [
'composition_version_id',
'position',
'role',
'placement_note',
'content_element_version_id',
'nested_composition_version_id',
];
protected static function booted(): void
{
static::creating(function (CompositionMember $member): void {
$status = CompositionVersion::query()->whereKey($member->composition_version_id)->value('status');
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Mitglieder auf.');
}
});
static::updating(function (): void {
throw new DomainRuleException('Mitglieder einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
});
}
public function compositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class);
}
public function contentElementVersion(): BelongsTo
{
return $this->belongsTo(ContentElementVersion::class);
}
public function nestedCompositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
}
}
+478
View File
@@ -0,0 +1,478 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class CompositionRelease
{
/** @var array<int, CompositionVersion> */
private array $publishedDrafts = [];
/**
* @param list<array<string, mixed>> $members
* @return array{
* host_label: string,
* title: string,
* next_label: string,
* ready: list<array{title: string, detail: string, depth: int}>,
* pending: list<array{title: string, detail: string, depth: int}>,
* blocked: list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}>,
* needs_consent: bool,
* nested_draft: bool
* }
*/
public function review(Composition $host, array $members): array
{
$ready = [];
$pending = [];
$blocked = [];
$nestedDraft = false;
$this->inspectMembers($members, 0, [$host->id], false, $ready, $pending, $blocked, $nestedDraft);
return [
'host_label' => $this->label($host),
'title' => $this->title($host),
'next_label' => 'Fassung '.(((int) $host->versions()->max('number')) + 1),
'ready' => $ready,
'pending' => $pending,
'blocked' => $blocked,
'needs_consent' => $pending !== [],
'nested_draft' => $nestedDraft,
];
}
/**
* @param list<array<string, mixed>> $members
* @param array{learning_goal?: mixed, duration_minutes?: mixed, material_note?: mixed} $didactic
*/
public function publish(
Composition $host,
array $members,
?User $actor,
?string $note,
array $didactic,
bool $consent,
): CompositionVersion {
$review = $this->review($host, $members);
if ($review['blocked'] !== []) {
throw new DomainRuleException($review['blocked'][0]['detail']);
}
if ($review['needs_consent'] && ! $consent) {
throw new DomainRuleException('Noch nicht freigegebene Bestandteile werden nur mit ausdrücklicher Zustimmung freigegeben.');
}
$this->publishedDrafts = [];
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion {
return $this->materialize($host, $members, $didactic, $actor, $note, []);
});
}
/**
* @param list<array<string, mixed>> $members
* @param list<int> $stack
* @param list<array{title: string, detail: string, depth: int}> $ready
* @param list<array{title: string, detail: string, depth: int}> $pending
* @param list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}> $blocked
*/
private function inspectMembers(
array $members,
int $depth,
array $stack,
bool $frozen,
array &$ready,
array &$pending,
array &$blocked,
bool &$nestedDraft,
): void {
foreach ($members as $member) {
if (! is_array($member)) {
continue;
}
$role = trim((string) ($member['role'] ?? ''));
$target = (string) ($member['target'] ?? '');
if ($role === '' || $target === '') {
$blocked[] = $this->block('Bestandteil', 'Jeder Bestandteil braucht eine Rolle und eine vorhandene Fassung.', $depth, null);
continue;
}
$this->inspectTarget($target, $role, $depth, $stack, $frozen, $ready, $pending, $blocked, $nestedDraft);
}
}
/**
* @param list<int> $stack
* @param list<array{title: string, detail: string, depth: int}> $ready
* @param list<array{title: string, detail: string, depth: int}> $pending
* @param list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}> $blocked
*/
private function inspectTarget(
string $target,
string $role,
int $depth,
array $stack,
bool $frozen,
array &$ready,
array &$pending,
array &$blocked,
bool &$nestedDraft,
): void {
if (preg_match('/^element:(\d+)$/', $target, $match) === 1) {
$this->inspectElement((int) $match[1], $role, $depth, $frozen, $ready, $pending, $blocked);
return;
}
if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) {
$this->inspectReleasedComposition((int) $match[1], $role, $depth, $stack, $ready, $pending, $blocked, $nestedDraft);
return;
}
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
$this->inspectDraftComposition((int) $match[1], $role, $depth, $stack, $frozen, $ready, $pending, $blocked, $nestedDraft);
return;
}
$blocked[] = $this->block('Bestandteil', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
}
/**
* @param list<array{title: string, detail: string, depth: int}> $ready
* @param list<array{title: string, detail: string, depth: int}> $pending
* @param list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}> $blocked
*/
private function inspectElement(
int $id,
string $role,
int $depth,
bool $frozen,
array &$ready,
array &$pending,
array &$blocked,
): void {
$version = ContentElementVersion::query()->with('element')->find($id);
$title = $version?->element === null
? 'Medium'
: (filled($version->element->display_title) ? $version->element->display_title : $version->element->working_title);
$edit = $version?->element === null ? null : ['type' => 'element', 'id' => $version->element->id];
if (! $version instanceof ContentElementVersion || $version->element === null) {
$blocked[] = $this->block($title, 'Ein Medium ist nicht mehr vorhanden.', $depth, null);
return;
}
$kind = $this->outputLabel((string) $version->element->output_class);
if ($version->status === ContentVersionStatus::Bereit) {
$ready[] = $this->line($title, $this->kindAndRole($kind, $role).' · Fassung '.$version->number.', bleibt unverändert', $depth);
return;
}
if ($version->status === ContentVersionStatus::Gesperrt) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Diese Fassung ist deaktiviert und kann nicht freigegeben werden.', $depth, $edit);
return;
}
$problem = app(ContentService::class)->elementReleaseProblem($version);
if ($frozen) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Eine bereits freigegebene Fassung verweist auf diesen Entwurf. Sie bleibt unverändert.', $depth, $edit);
return;
}
if ($problem !== null) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. '.$problem, $depth, $edit);
return;
}
$pending[] = $this->line($title, $this->kindAndRole($kind, $role).'. Der Entwurf wird freigegeben. Es entsteht keine weitere Fassung.', $depth);
}
/**
* @param list<int> $stack
* @param list<array{title: string, detail: string, depth: int}> $ready
* @param list<array{title: string, detail: string, depth: int}> $pending
* @param list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}> $blocked
*/
private function inspectReleasedComposition(
int $id,
string $role,
int $depth,
array $stack,
array &$ready,
array &$pending,
array &$blocked,
bool &$nestedDraft,
): void {
$version = CompositionVersion::query()->with('composition', 'members')->find($id);
if (! $version instanceof CompositionVersion || $version->composition === null) {
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
return;
}
$title = $this->title($version->composition);
$kind = $this->label($version->composition);
if (in_array($version->composition_id, $stack, true)) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Der Aufbau verweist auf sich selbst. So kann nichts freigegeben werden.', $depth, ['type' => 'composition', 'id' => $version->composition_id]);
return;
}
if ($version->status !== ContentVersionStatus::Bereit) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Diese Fassung ist nicht freigegeben.', $depth, ['type' => 'composition', 'id' => $version->composition_id]);
return;
}
$ready[] = $this->line($title, $this->kindAndRole($kind, $role).' · Fassung '.$version->number.', bleibt unverändert', $depth);
$nested = [];
foreach ($version->members()->orderBy('position')->get() as $member) {
$target = $member->content_element_version_id
? 'element:'.$member->content_element_version_id
: 'composition:'.$member->nested_composition_version_id;
$nested[] = ['role' => (string) $member->role, 'target' => $target, 'note' => (string) ($member->placement_note ?? '')];
}
$this->inspectMembers($nested, $depth + 1, [...$stack, $version->composition_id], true, $ready, $pending, $blocked, $nestedDraft);
}
/**
* @param list<int> $stack
* @param list<array{title: string, detail: string, depth: int}> $ready
* @param list<array{title: string, detail: string, depth: int}> $pending
* @param list<array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}> $blocked
*/
private function inspectDraftComposition(
int $id,
string $role,
int $depth,
array $stack,
bool $frozen,
array &$ready,
array &$pending,
array &$blocked,
bool &$nestedDraft,
): void {
$composition = Composition::query()->find($id);
$edit = ['type' => 'composition', 'id' => $id];
if (! $composition instanceof Composition) {
$blocked[] = $this->block('Modul', 'Ein Modul ist nicht mehr vorhanden.', $depth, null);
return;
}
$title = $this->title($composition);
$kind = $this->label($composition);
if ($frozen || in_array($id, $stack, true)) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Der Aufbau verweist auf sich selbst. So kann nichts freigegeben werden.', $depth, $edit);
return;
}
$draft = is_array($composition->working_draft) ? $composition->working_draft : [];
$members = is_array($draft['members'] ?? null) ? $draft['members'] : [];
if ($members === []) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Der gespeicherte Entwurf hat keinen Bestandteil.', $depth, $edit);
return;
}
$minutes = $draft['duration_minutes'] ?? null;
if ($minutes !== null && $minutes !== '' && ! is_int($minutes)) {
$blocked[] = $this->block($title, $this->kindAndRole($kind, $role).'. Der Zeitbedarf ist keine Zahl von Minuten.', $depth, $edit);
return;
}
$nestedDraft = true;
$number = ((int) $composition->versions()->max('number')) + 1;
$pending[] = $this->line($title, $this->kindAndRole($kind, $role).'. Es entsteht Fassung '.$number.'.', $depth);
$this->inspectMembers($members, $depth + 1, [...$stack, $id], false, $ready, $pending, $blocked, $nestedDraft);
}
/**
* @param list<array<string, mixed>> $members
* @param array{learning_goal?: mixed, duration_minutes?: mixed, material_note?: mixed} $didactic
* @param list<int> $stack
*/
private function materialize(
Composition $composition,
array $members,
array $didactic,
?User $actor,
?string $note,
array $stack,
): CompositionVersion {
if (isset($this->publishedDrafts[$composition->id])) {
return $this->publishedDrafts[$composition->id];
}
if (in_array($composition->id, $stack, true)) {
throw new DomainRuleException('Der Aufbau verweist auf sich selbst. So kann nichts freigegeben werden.');
}
$stack[] = $composition->id;
$payload = [];
foreach (array_values($members) as $member) {
$payload[] = [
'role' => trim((string) ($member['role'] ?? '')),
'note' => trim((string) ($member['note'] ?? '')),
'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack),
];
}
$version = app(ContentService::class)->publishComposition(
$composition,
$payload,
$actor,
$note,
[
'learning_goal' => $didactic['learning_goal'] ?? null,
'duration_minutes' => $didactic['duration_minutes'] ?? null,
'material_note' => $didactic['material_note'] ?? null,
],
);
$this->publishedDrafts[$composition->id] = $version;
return $version;
}
/**
* @param list<int> $stack
*/
private function resolveTarget(string $target, ?User $actor, array $stack): ContentElementVersion|CompositionVersion
{
if (preg_match('/^element:(\d+)$/', $target, $match) === 1) {
$version = ContentElementVersion::query()->find($match[1]);
if (! $version instanceof ContentElementVersion) {
throw new DomainRuleException('Ein Medium ist nicht mehr vorhanden.');
}
if ($version->status === ContentVersionStatus::Entwurf) {
$version = app(ContentService::class)->releaseElementVersion($version);
}
if ($version->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht freigeben.');
}
return $version;
}
if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) {
$version = CompositionVersion::query()->find($match[1]);
if (! $version instanceof CompositionVersion || $version->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Eine bereits erwartete Fassung ist nicht mehr freigegeben.');
}
return $version;
}
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) !== 1) {
throw new DomainRuleException('Ein Bestandteil ist nicht mehr vorhanden.');
}
$composition = Composition::query()->find($match[1]);
if (! $composition instanceof Composition) {
throw new DomainRuleException('Ein Modul ist nicht mehr vorhanden.');
}
if (isset($this->publishedDrafts[$composition->id])) {
return $this->publishedDrafts[$composition->id];
}
$draft = is_array($composition->working_draft) ? $composition->working_draft : [];
$version = $this->materialize(
$composition,
is_array($draft['members'] ?? null) ? $draft['members'] : [],
[
'learning_goal' => $draft['learning_goal'] ?? null,
'duration_minutes' => $draft['duration_minutes'] ?? null,
'material_note' => $draft['material_note'] ?? null,
],
$actor,
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
$stack,
);
app(EditorialWorkingDraft::class)->clear($composition);
return $version;
}
/**
* @return array{title: string, detail: string, depth: int}
*/
private function line(string $title, string $detail, int $depth): array
{
return ['title' => $title, 'detail' => $detail, 'depth' => $depth];
}
/**
* @param array{type: string, id: int}|null $edit
* @return array{title: string, detail: string, depth: int, edit: array{type: string, id: int}|null}
*/
private function block(string $title, string $detail, int $depth, ?array $edit): array
{
return ['title' => $title, 'detail' => $detail, 'depth' => $depth, 'edit' => $edit];
}
private function kindAndRole(string $kind, string $role): string
{
$role = trim($role);
if ($role === '' || mb_strtolower($role) === mb_strtolower($kind)) {
return $kind;
}
return $kind.' · '.$role;
}
private function title(Composition $composition): string
{
return filled($composition->display_title) ? (string) $composition->display_title : (string) $composition->designation;
}
private function outputLabel(string $outputClass): string
{
return match ($outputClass) {
'film' => 'Film',
'audio' => 'Hörstück',
'bild' => 'Bild',
'document', 'pdf' => 'Dokument',
default => 'Text',
};
}
private function label(Composition $composition): string
{
$kind = $composition->kind;
return ($kind instanceof CompositionKind ? $kind : CompositionKind::from((string) $kind))->deskLabel();
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Domain\Catalog;
class CompositionStructureReader
{
/**
* @return list<StructureNode>
*/
public function tree(CompositionVersion $version): array
{
$version->loadMissing([
'members.contentElementVersion.element.editorialContentKind',
'members.nestedCompositionVersion.composition.editorialContentKind',
]);
return $this->members($version);
}
/**
* @return list<StructureNode>
*/
private function members(CompositionVersion $version, array $stack = []): array
{
if (in_array($version->composition_id, $stack, true)) {
throw new DomainRuleException('Kompositionen dürfen keinen Zyklus bilden.');
}
$stack[] = $version->composition_id;
$nodes = [];
foreach ($version->members as $member) {
if ($member->content_element_version_id !== null) {
$elementVersion = $member->contentElementVersion;
$elementVersion?->loadMissing('element.editorialContentKind');
$element = $elementVersion?->element;
$nodes[] = new StructureNode(
role: $member->role,
position: $member->position,
compositionVersionId: null,
compositionId: null,
contentElementVersionId: $elementVersion?->id,
contentElementId: $element?->id,
editorialKindLabel: $element?->editorialContentKind?->label,
technicalKindLabel: $element?->output_class,
outputClass: $element?->output_class,
title: $element?->working_title ?? $member->role,
);
continue;
}
$nested = $member->nestedCompositionVersion;
if ($nested === null) {
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
}
$nested->loadMissing('composition.editorialContentKind', 'composition');
$composition = $nested->composition;
$nodes[] = new StructureNode(
role: $member->role,
position: $member->position,
compositionVersionId: $nested->id,
compositionId: $composition->id,
contentElementVersionId: null,
contentElementId: null,
editorialKindLabel: $composition->editorialContentKind?->label,
technicalKindLabel: $composition->kind instanceof CompositionKind
? $composition->kind->label()
: null,
outputClass: null,
title: $composition->designation,
children: $this->members($nested, $stack),
);
}
return $nodes;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class CompositionVersion extends Model
{
protected $fillable = [
'composition_id',
'number',
'status',
'members_hash',
'resolved_hash',
'learning_goal',
'duration_minutes',
'material_note',
];
protected function casts(): array
{
return [
'status' => ContentVersionStatus::class,
];
}
protected static function booted(): void
{
static::updating(function (CompositionVersion $version): void {
$original = StatusValue::of($version->getOriginal('status'));
if (! in_array($original, [
ContentVersionStatus::Bereit->value,
ContentVersionStatus::Gesperrt->value,
], true)) {
return;
}
$dirty = array_diff(array_keys($version->getDirty()), ['status', 'updated_at']);
if ($dirty !== [] || $original === ContentVersionStatus::Gesperrt->value) {
throw new DomainRuleException('Eine bestätigte Kompositionsfassung ist unveränderlich.');
}
if (StatusValue::of($version->status) !== ContentVersionStatus::Gesperrt->value) {
throw new DomainRuleException('Eine bestätigte Kompositionsfassung kann nur gesperrt werden.');
}
});
}
public function composition(): BelongsTo
{
return $this->belongsTo(Composition::class);
}
public function members(): HasMany
{
return $this->hasMany(CompositionMember::class)->orderBy('position');
}
public function attestations(): HasMany
{
return $this->hasMany(CompatibilityAttestation::class);
}
public function displayEvents(): HasMany
{
return $this->hasMany(CompositionVersionDisplayEvent::class)->orderBy('occurred_at');
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class CompositionVersionDisplayEvent extends Model
{
public const RELEASED = 'freigegeben';
public const REVOKED = 'zurueckgenommen';
protected $fillable = [
'composition_version_id',
'event',
'actor_id',
'occurred_at',
'note',
];
protected function casts(): array
{
return [
'occurred_at' => 'datetime',
];
}
public function version(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class, 'composition_version_id');
}
public function actor(): BelongsTo
{
return $this->belongsTo(User::class, 'actor_id');
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ContentElement extends Model
{
protected $fillable = [
'kind',
'output_class',
'working_title',
'display_title',
'teaser',
'description',
'usage_note',
'license_note',
'website_credit',
'website_alt',
'website_released_at',
'website_public_path',
'summary',
'search_terms',
'thumbnail_path',
'thumbnail_alt',
'thumbnail_source',
'thumbnail_error',
'preview_path',
'editorial_content_kind_id',
'archived_at',
];
protected function casts(): array
{
return [
'archived_at' => 'datetime',
'website_released_at' => 'datetime',
];
}
public function editorialContentKind(): BelongsTo
{
return $this->belongsTo(EditorialContentKind::class);
}
public function versions(): HasMany
{
return $this->hasMany(ContentElementVersion::class);
}
public function pillars(): BelongsToMany
{
return $this->belongsToMany(Pillar::class)->orderBy('pillars.name');
}
}
@@ -0,0 +1,78 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ContentElementVersion extends Model
{
protected $fillable = [
'content_element_id',
'number',
'status',
'content_hash',
'body',
'metadata',
'change_note',
'block_reason',
];
protected function casts(): array
{
return [
'status' => ContentVersionStatus::class,
'metadata' => 'array',
];
}
protected static function booted(): void
{
static::updating(function (ContentElementVersion $version): void {
$original = StatusValue::of($version->getOriginal('status'));
if (! in_array($original, [
ContentVersionStatus::Bereit->value,
ContentVersionStatus::Gesperrt->value,
], true)) {
return;
}
if (
$original === ContentVersionStatus::Bereit->value
&& StatusValue::of($version->status) === ContentVersionStatus::Bereit->value
&& ! app(ContentService::class)->isCommitted($version)
) {
$contentFields = ['body', 'metadata', 'content_hash', 'change_note', 'updated_at'];
if (array_diff(array_keys($version->getDirty()), $contentFields) === []) {
return;
}
}
$allowed = ['status', 'updated_at'];
if (
$original === ContentVersionStatus::Bereit->value
&& StatusValue::of($version->status) === ContentVersionStatus::Gesperrt->value
) {
$allowed[] = 'block_reason';
}
$dirty = array_diff(array_keys($version->getDirty()), $allowed);
if ($dirty !== [] || $original === ContentVersionStatus::Gesperrt->value) {
throw new DomainRuleException('Eine bereitgestellte Inhaltsfassung ist unveränderlich.');
}
if (StatusValue::of($version->status) !== ContentVersionStatus::Gesperrt->value) {
throw new DomainRuleException('Eine bereitgestellte Inhaltsfassung kann nur gesperrt werden.');
}
});
}
public function element(): BelongsTo
{
return $this->belongsTo(ContentElement::class, 'content_element_id');
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace App\Domain\Catalog;
class ContentResolver
{
/**
* @return list<array{version_id: int, role: string, path: string}>
*/
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array
{
if ($node instanceof ContentElementVersion) {
$node->loadMissing('element');
return [[
'version_id' => $node->id,
'role' => $path,
'path' => $path !== '' ? $path : $node->element->working_title,
]];
}
if (in_array($node->composition_id, $stack, true)) {
throw new DomainRuleException('Kompositionen dürfen keinen Zyklus bilden.');
}
$stack[] = $node->composition_id;
$rows = [];
foreach ($node->members()->orderBy('position')->get() as $member) {
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
if ($member->content_element_version_id !== null) {
$rows[] = [
'version_id' => $member->content_element_version_id,
'role' => $member->role,
'path' => $segment,
];
continue;
}
$nested = $member->nestedCompositionVersion;
if ($nested === null) {
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
}
$rows = array_merge($rows, $this->expand($nested, $segment, $stack));
}
return $rows;
}
public function resolvedHash(ContentElementVersion|CompositionVersion $node): string
{
$ids = array_values(array_unique(array_column($this->expand($node), 'version_id')));
sort($ids);
return hash('sha256', json_encode($ids, JSON_THROW_ON_ERROR));
}
}
+395
View File
@@ -0,0 +1,395 @@
<?php
namespace App\Domain\Catalog;
use App\Jobs\StoreContentFile;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class ContentService
{
public function __construct(private readonly ContentResolver $resolver) {}
public function createElement(string $kind, string $outputClass, string $workingTitle): ContentElement
{
return ContentElement::query()->create([
'kind' => $this->required($kind, 'Die Art des Inhaltselements fehlt.'),
'output_class' => $this->required($outputClass, 'Die Ausgabeklasse fehlt.'),
'working_title' => $this->required($workingTitle, 'Der Arbeitstitel fehlt.'),
]);
}
public function block(ContentElementVersion|CompositionVersion $version, string $reason): void
{
if (trim($reason) === '') {
throw new DomainRuleException('Eine Sperre braucht eine Begründung.');
}
if ($version->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Nur eine bereitgestellte Fassung kann gesperrt werden.');
}
$version->status = ContentVersionStatus::Gesperrt;
if ($version instanceof ContentElementVersion) {
$version->block_reason = trim($reason);
}
$version->save();
}
public function describe(ContentElement $element, string $workingTitle, ?string $description): void
{
$element->working_title = $this->required($workingTitle, 'Der Arbeitstitel fehlt.');
$description = trim((string) $description);
$element->description = $description === '' ? null : $description;
$element->save();
}
public function publishElementVersion(
ContentElement $element,
?string $body = null,
array $metadata = [],
?string $changeNote = null,
): ContentElementVersion {
if (($body === null || $body === '') && $metadata === []) {
throw new DomainRuleException('Eine Inhaltsfassung braucht einen Inhalt.');
}
$number = ((int) $element->versions()->max('number')) + 1;
$incoming = $metadata['incoming'] ?? null;
$version = $element->versions()->create([
'number' => $number,
'status' => is_string($incoming) && $incoming !== '' ? ContentVersionStatus::Entwurf : ContentVersionStatus::Bereit,
'content_hash' => hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)),
'body' => $body,
'metadata' => $metadata === [] ? null : $metadata,
'change_note' => $changeNote,
]);
if (is_string($incoming) && $incoming !== '') {
StoreContentFile::dispatch($version->id, $incoming);
$version->refresh();
}
return $version;
}
public function draftElementVersion(
ContentElement $element,
?string $body = null,
array $metadata = [],
): ContentElementVersion {
if (($body === null || $body === '') && $metadata === []) {
throw new DomainRuleException('Eine Inhaltsfassung braucht einen Inhalt.');
}
$number = ((int) $element->versions()->max('number')) + 1;
$version = $element->versions()->create([
'number' => $number,
'status' => ContentVersionStatus::Entwurf,
'content_hash' => hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)),
'body' => $body,
'metadata' => $metadata === [] ? null : $metadata,
'change_note' => null,
]);
$incoming = $metadata['incoming'] ?? null;
if (is_string($incoming) && $incoming !== '') {
StoreContentFile::dispatch($version->id, $incoming);
$version->refresh();
}
return $version;
}
public function isCommitted(ContentElementVersion $version): bool
{
if ($version->status !== ContentVersionStatus::Bereit) {
return false;
}
$usedByComposition = CompositionMember::query()
->where('content_element_version_id', $version->id)
->whereHas('compositionVersion', function ($query): void {
$query->where('status', ContentVersionStatus::Bereit);
})
->exists();
if ($usedByComposition) {
return true;
}
return ReleaseContent::query()
->where('content_element_version_id', $version->id)
->exists();
}
public function reviseElementContent(ContentElementVersion $version, string $body): ContentElementVersion
{
$body = trim($body);
if ($body === '') {
throw new DomainRuleException('Der Text braucht einen Inhalt.');
}
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Gesperrt) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht ändern.');
}
if (trim((string) $version->body) === $body) {
return $version;
}
if ($this->isCommitted($version)) {
return $this->publishElementVersion($version->element, $body);
}
$metadata = $version->metadata ?? [];
$version->body = $body;
$version->content_hash = hash('sha256', json_encode([
'body' => $body,
'metadata' => $metadata,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->save();
return $version->refresh();
}
public function elementReleaseProblem(ContentElementVersion $version): ?string
{
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Gesperrt) {
return 'Diese Fassung ist deaktiviert und kann nicht freigegeben werden.';
}
if ($version->status === ContentVersionStatus::Bereit) {
return null;
}
$meta = is_array($version->metadata) ? $version->metadata : [];
if (isset($meta['incoming']) && ! isset($meta['file'])) {
return 'Die Datei ist noch nicht übernommen. Die Freigabe wartet, bis die Datei bereitsteht.';
}
if (isset($meta['error']) && is_string($meta['error']) && trim($meta['error']) !== '') {
return trim($meta['error']);
}
if ($version->element?->output_class === 'text' && trim((string) $version->body) === '') {
return 'Der Text braucht einen Inhalt.';
}
return null;
}
public function releaseElementVersion(ContentElementVersion $version): ContentElementVersion
{
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Bereit) {
return $version;
}
if ($version->status !== ContentVersionStatus::Entwurf) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht freigeben.');
}
$problem = $this->elementReleaseProblem($version);
if ($problem !== null) {
throw new DomainRuleException($problem);
}
$meta = is_array($version->metadata) ? $version->metadata : [];
unset($meta['held']);
$version->metadata = $meta === [] ? null : $meta;
$version->content_hash = hash('sha256', json_encode([
'body' => $version->body,
'metadata' => $meta,
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
$version->status = ContentVersionStatus::Bereit;
$version->save();
return $version->refresh();
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
*/
public function publishComposition(
Composition $composition,
array $members,
?User $confirmedBy = null,
?string $note = null,
array $didactic = [],
): CompositionVersion {
if ($members === []) {
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
}
$this->assertAcyclic($composition->id, $members);
foreach ($members as $member) {
$this->assertReadyMember($member['target']);
}
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
$number = ((int) $composition->versions()->max('number')) + 1;
$version = $composition->versions()->create([
'number' => $number,
'status' => ContentVersionStatus::Entwurf,
'members_hash' => $this->membersHash($members),
'resolved_hash' => 'pending',
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
]);
foreach (array_values($members) as $index => $member) {
$target = $member['target'];
$version->members()->create([
'position' => $index + 1,
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
'placement_note' => $this->optionalText($member['note'] ?? null),
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
]);
}
$resolvedHash = $this->resolver->resolvedHash($version);
$version->attestations()->create([
'resolved_hash' => $resolvedHash,
'confirmed_by' => $confirmedBy?->id,
'confirmed_at' => now(),
'note' => $note,
]);
$version->resolved_hash = $resolvedHash;
$version->status = ContentVersionStatus::Bereit;
$version->save();
return $version->load('members');
});
}
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
{
return Composition::query()->create([
'designation' => $this->required($designation, 'Die Bezeichnung fehlt.'),
'kind' => $kind,
]);
}
/**
* @return list<int>
*/
public function containingCompositionIds(ContentElementVersion $version): array
{
$ids = [];
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->get() as $compositionVersion) {
$contained = array_column($this->resolver->expand($compositionVersion), 'version_id');
if (in_array($version->id, $contained, true)) {
$ids[] = $compositionVersion->id;
}
}
return $ids;
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
* @param list<int> $stack
*/
private function assertAcyclic(int $compositionId, array $members, array $stack = []): void
{
if (in_array($compositionId, $stack, true)) {
throw new DomainRuleException('Kompositionen dürfen keinen Zyklus bilden.');
}
$stack[] = $compositionId;
foreach ($members as $member) {
$target = $member['target'];
if (! $target instanceof CompositionVersion) {
continue;
}
$nested = [];
foreach ($target->members()->orderBy('position')->get() as $row) {
$child = $row->contentElementVersion ?? $row->nestedCompositionVersion;
if ($child === null) {
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
}
$nested[] = ['role' => $row->role, 'target' => $child];
}
$this->assertAcyclic($target->composition_id, $nested, $stack);
}
}
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
{
if ($target->status !== ContentVersionStatus::Bereit) {
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
}
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
*/
private function membersHash(array $members): string
{
$list = [];
foreach (array_values($members) as $index => $member) {
$target = $member['target'];
$list[] = [
'position' => $index + 1,
'role' => $member['role'],
'note' => $this->optionalText($member['note'] ?? null),
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
];
}
return hash('sha256', json_encode($list, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
private function optionalText(mixed $value): ?string
{
if (! is_string($value)) {
return null;
}
$value = trim($value);
return $value === '' ? null : $value;
}
private function required(string $value, string $message): string
{
$value = trim($value);
if ($value === '') {
throw new DomainRuleException($message);
}
return $value;
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Domain\Catalog;
enum ContentVersionStatus: string
{
case Entwurf = 'entwurf';
case Bereit = 'bereit';
case Gesperrt = 'gesperrt';
}
@@ -0,0 +1,7 @@
<?php
namespace App\Domain\Catalog;
use RuntimeException;
class DomainRuleException extends RuntimeException {}
@@ -0,0 +1,91 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Fachliche Materialart (FACH-56 bis FACH-58). Die Bezeichnung ist pflegbar, die Kennung (slug) bleibt nach dem Anlegen
* fest. Zulässige Objektkontexte bestimmen, wo eine Materialart neu gewählt werden kann; vorhandene Zuordnungen bleiben
* immer erhalten (siehe EditorialVocabulary).
*/
class EditorialContentKind extends Model
{
/** Objektkontexte aus dem Fachmodell: Medium (ContentElement), Modul und Programm (Composition), Lizenzartikel. */
public const CONTEXTS = [
'medium' => 'Medium',
'modul' => 'Modul',
'programm' => 'Programm',
'lizenzartikel' => 'Lizenzartikel',
];
/**
* Kennungen, auf die der Code fachlich verweist: öffentliche Programmseiten und das Anlegen von Programmen und
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
*/
public const SYSTEM_SLUGS = ['programm', 'modul', 'traineranleitung'];
protected $fillable = [
'slug',
'label',
'sort_order',
'is_active',
'contexts',
];
protected function casts(): array
{
return [
'is_active' => 'boolean',
'contexts' => 'array',
'sort_order' => 'integer',
];
}
public function compositions(): HasMany
{
return $this->hasMany(Composition::class);
}
public function contentElements(): HasMany
{
return $this->hasMany(ContentElement::class);
}
public function licenseArticles(): HasMany
{
return $this->hasMany(LicenseArticle::class);
}
/**
* @param Builder<EditorialContentKind> $query
*/
public function scopeActive(Builder $query): void
{
$query->where('is_active', true);
}
public function allows(string $context): bool
{
return in_array($context, (array) ($this->contexts ?? []), true);
}
public function isSystem(): bool
{
return in_array($this->slug, self::SYSTEM_SLUGS, true);
}
/**
* Alle Materialarten in Pflegereihenfolge (ohne Kontext- oder Aktivfilter). Für Auswahlstellen gilt
* EditorialVocabulary.
*
* @return array<int, string>
*/
public static function selectOptions(): array
{
return static::query()->orderBy('sort_order')->orderBy('id')->pluck('label', 'id')->all();
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class EditorialDimension extends Model
{
/** Gespiegelte Säulen; gepflegt werden Säulen über die Säulenverwaltung, nicht als Stammdaten. */
public const PILLAR_SLUG = 'saeule';
protected $fillable = ['slug', 'label'];
/** Werte in Pflegereihenfolge. */
public function values(): HasMany
{
return $this->hasMany(EditorialDimensionValue::class)->orderBy('sort_order')->orderBy('id');
}
/**
* Inhaltselemente pflegen Themen über die Säulen, nicht noch einmal über die Dimension.
* Module, Programme und Lizenzartikel haben keine Säulenauswahl und behalten die Dimension.
*
* @return Collection<int, self>
*/
public static function forSubject(Model $subject): Collection
{
$query = static::query()->with('values')->orderBy('label');
if ($subject instanceof ContentElement) {
$query->where('slug', '!=', self::PILLAR_SLUG);
}
return $query->get();
}
/**
* @return list<int>
*/
public static function offeredValueIds(Model $subject): array
{
return static::forSubject($subject)
->flatMap(fn (self $dimension) => $dimension->values->pluck('id'))
->map(fn ($id): int => (int) $id)
->all();
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class EditorialDimensionValue extends Model
{
protected $fillable = ['editorial_dimension_id', 'slug', 'label', 'sort_order', 'is_active'];
protected function casts(): array
{
return [
'is_active' => 'boolean',
'sort_order' => 'integer',
];
}
public function dimension(): BelongsTo
{
return $this->belongsTo(EditorialDimension::class, 'editorial_dimension_id');
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
/**
* Aufgelöste Klasse-A-Angaben eines Fachobjekts.
* Fehlende Felder bleiben leer. Es wird nichts materialisiert.
*/
final readonly class EditorialProfile
{
/**
* @param array<string, ResolvedText> $texts
*/
public function __construct(
public ?string $workingTitle,
public array $texts,
public ?string $searchTerms,
public string $searchOrigin,
public ?string $kindLabel,
public ?Model $source,
) {}
public function text(string $field): ResolvedText
{
return $this->texts[$field] ?? new ResolvedText(null, 'leer', null);
}
public function value(string $field): ?string
{
return $this->text($field)->value;
}
public function origin(string $field): string
{
return $this->text($field)->origin;
}
public function originLabel(string $field): string
{
$text = $this->text($field);
return match ($text->origin) {
'eigen' => 'Eigene Angabe',
'variante' => 'Abweichung für '.($text->label ?? 'diesen Kontext'),
'quelle' => 'Übernommen von '.($text->label ?? 'der fachlichen Quelle'),
default => 'Keine Angabe',
};
}
}
@@ -0,0 +1,225 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
/**
* Löst die Klasse-A-Texte eines Fachobjekts auf.
*
* Reihenfolge: abweichende Formulierung für den Kontext, eigene Angabe am Objekt,
* bei einem Lizenzartikel die Angabe der eindeutigen fachlichen Quelle.
* Eine Quelle gibt es nur, wenn der aktuelle Artikelstand genau eine Wurzel hat.
* Preise, Rechte und Fassungen werden nicht gelesen und nicht geschrieben.
*/
class EditorialProfileReader
{
public const AUDIENCES = [
'kachel' => 'Öffentliche Kachel',
'detail' => 'Öffentliche Detailvorstellung',
'bibliothek' => 'Mitgliederbibliothek',
'trainer' => 'Fachliche Traineransicht',
'artikel' => 'Lizenzartikelpräsentation',
'cms' => 'CMS-Teaser',
'suche' => 'Suchergebnis',
];
public const TEXT_FIELDS = ['display_title', 'teaser', 'summary', 'description'];
public function read(Model $subject, ?string $audience = null): EditorialProfile
{
if ($audience !== null && ! array_key_exists($audience, self::AUDIENCES)) {
throw new DomainRuleException('Diese Zielgruppe ist nicht vorgesehen.');
}
$source = $subject instanceof LicenseArticle ? $this->sourceOf($subject) : null;
$texts = [];
foreach (self::TEXT_FIELDS as $field) {
$texts[$field] = $this->resolve($subject, $field, $audience, $source);
}
$search = $this->own($subject, 'search_terms');
$searchOrigin = 'eigen';
if ($search === null && $source instanceof Model) {
$search = $this->own($source, 'search_terms');
$searchOrigin = $search === null ? 'leer' : 'quelle';
}
if ($search === null) {
$searchOrigin = 'leer';
}
return new EditorialProfile(
workingTitle: $this->workingTitle($subject),
texts: $texts,
searchTerms: $search,
searchOrigin: $searchOrigin,
kindLabel: $subject->editorialContentKind?->label
?? ($source?->editorialContentKind?->label),
source: $source,
);
}
public function sourceOf(LicenseArticle $article): ?Model
{
$release = $article->relationLoaded('currentRelease')
? $article->currentRelease
: $article->currentRelease()->first();
if (! $release instanceof ArticleRelease) {
return null;
}
$elementId = $release->root_element_version_id;
$compositionId = $release->root_composition_version_id;
if (($elementId === null) === ($compositionId === null)) {
return null;
}
if ($elementId !== null) {
return ContentElementVersion::query()->with('element.editorialContentKind')->find($elementId)?->element;
}
return CompositionVersion::query()->with('composition.editorialContentKind')->find($compositionId)?->composition;
}
public function putVariant(Model $subject, string $field, string $audience, ?string $body, ?User $actor = null): string
{
if (! in_array($field, self::TEXT_FIELDS, true) || ! array_key_exists($audience, self::AUDIENCES)) {
throw new DomainRuleException('Diese Abweichung ist nicht vorgesehen.');
}
$body = is_string($body) ? trim($body) : '';
$existing = $this->variant($subject, $field, $audience);
if ($body === '') {
if ($existing instanceof EditorialTextVariant) {
$this->record($subject, $audience, $field, $existing->body, null, $actor);
$existing->delete();
}
return 'Die abweichende Formulierung ist entfernt. Es gilt wieder die zentrale Angabe.';
}
if ($existing instanceof EditorialTextVariant && $existing->body === $body) {
return 'Die abweichende Formulierung ist unverändert.';
}
$this->record($subject, $audience, $field, $existing?->body, $body, $actor);
EditorialTextVariant::query()->updateOrCreate(
[
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'field' => $field,
'audience' => $audience,
],
['body' => $body],
);
return 'Die abweichende Formulierung gilt nur für '.self::AUDIENCES[$audience].'. Die zentrale Angabe bleibt.';
}
public function forgetVariant(Model $subject, EditorialTextVariant $variant, ?User $actor = null): void
{
if ($variant->subject_type !== $subject->getMorphClass() || (int) $variant->subject_id !== (int) $subject->getKey()) {
throw new DomainRuleException('Diese Abweichung gehört zu einem anderen Objekt.');
}
$this->record($subject, $variant->audience, $variant->field, $variant->body, null, $actor);
$variant->delete();
}
private function resolve(Model $subject, string $field, ?string $audience, ?Model $source): ResolvedText
{
if ($audience !== null) {
$variant = $this->variant($subject, $field, $audience);
if ($variant instanceof EditorialTextVariant && trim($variant->body) !== '') {
return new ResolvedText(trim($variant->body), 'variante', self::AUDIENCES[$audience]);
}
}
$own = $this->own($subject, $field);
if ($own !== null) {
return new ResolvedText($own, 'eigen', null);
}
if ($source instanceof Model) {
$fromSource = $this->resolve($source, $field, $audience, null);
if ($fromSource->value !== null) {
return new ResolvedText($fromSource->value, 'quelle', $this->sourceLabel($source));
}
}
return new ResolvedText(null, 'leer', null);
}
private function variant(Model $subject, string $field, string $audience): ?EditorialTextVariant
{
return EditorialTextVariant::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('field', $field)
->where('audience', $audience)
->first();
}
private function own(Model $subject, string $field): ?string
{
$value = $subject->getAttribute($field);
if (! is_string($value)) {
return null;
}
$value = trim($value);
return $value === '' ? null : $value;
}
private function workingTitle(Model $subject): ?string
{
if ($subject instanceof Composition) {
return $this->own($subject, 'designation');
}
if ($subject instanceof LicenseArticle) {
return $this->own($subject, 'working_title') ?? $this->own($subject, 'code');
}
return $this->own($subject, 'working_title');
}
private function sourceLabel(Model $source): string
{
if ($source instanceof Composition) {
return (string) ($source->display_title ?: $source->designation);
}
if ($source instanceof ContentElement) {
return (string) ($source->display_title ?: $source->working_title);
}
return 'der fachlichen Quelle';
}
private function record(Model $subject, string $audience, string $field, ?string $before, ?string $after, ?User $actor): void
{
IdentityChange::query()->create([
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'field' => 'variante:'.$audience.':'.$field,
'before' => $before,
'after' => $after,
'actor_id' => $actor?->id,
'occurred_at' => now(),
]);
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
class EditorialTextVariant extends Model
{
protected $fillable = [
'subject_type',
'subject_id',
'field',
'audience',
'body',
];
}
+252
View File
@@ -0,0 +1,252 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
/**
* Eine Regelquelle für redaktionelle Stammdaten (FACH-56 bis FACH-58): Welche fachlichen Materialarten und welche
* Einordnungswerte Editor, Filter und Picker anbieten.
*
* - Neu wählbar sind nur aktive Werte; Materialarten zusätzlich nur im zulässigen Objektkontext.
* - Vorhandene Zuordnungen bleiben sichtbar und erhalten, auch wenn der Wert inaktiv ist oder sein Kontext geändert
* wurde; sie sind gekennzeichnet.
* - Filter finden auch Objekte mit inaktiven Werten; ein gewählter Filter bleibt erhalten.
*/
final class EditorialVocabulary
{
public const INACTIVE_SUFFIX = ' (inaktiv)';
public const OUT_OF_CONTEXT_SUFFIX = ' (hier nicht vorgesehen)';
/**
* Objektkontext eines Fachobjekts nach dem Fachmodell, null wenn es keine Materialart trägt.
*/
public function contextOf(Model $subject): ?string
{
if ($subject instanceof ContentElement) {
return 'medium';
}
if ($subject instanceof LicenseArticle) {
return 'lizenzartikel';
}
if ($subject instanceof Composition) {
return self::compositionContext($subject->kind instanceof CompositionKind ? $subject->kind : CompositionKind::tryFrom((string) $subject->kind));
}
return null;
}
public static function compositionContext(?CompositionKind $kind): ?string
{
return match ($kind) {
CompositionKind::Kurs => 'programm',
CompositionKind::Uebung => 'modul',
default => null,
};
}
/**
* Auswahl der Materialart in einem Editor: aktive, im Kontext zulässige Arten in Pflegereihenfolge, dazu die
* bereits zugeordnete Art mit Kennzeichnung, falls sie inaktiv oder hier nicht vorgesehen ist.
*
* @return array<int, string>
*/
public function kindOptions(string $context, ?int $currentId = null): array
{
$options = [];
foreach (EditorialContentKind::query()->orderBy('sort_order')->orderBy('id')->get() as $kind) {
$offered = $kind->is_active && $kind->allows($context);
if ($offered) {
$options[$kind->id] = (string) $kind->label;
} elseif ($currentId !== null && $kind->id === $currentId) {
$options[$kind->id] = $this->kindLabel($kind, $context);
}
}
return $options;
}
/**
* Prüft eine neue Materialart serverseitig. Die bereits gespeicherte Art bleibt immer zulässig.
*/
public function kindError(string $context, ?int $newId, ?int $storedId): ?string
{
if ($newId === null || $newId === $storedId) {
return null;
}
$kind = EditorialContentKind::query()->find($newId);
if (! $kind instanceof EditorialContentKind) {
return 'Diese fachliche Materialart gibt es nicht mehr.';
}
if (! $kind->is_active) {
return 'Die fachliche Materialart „'.$kind->label.'“ ist deaktiviert und kann nicht neu gewählt werden.';
}
if (! $kind->allows($context)) {
return 'Die fachliche Materialart „'.$kind->label.'“ ist für '.(EditorialContentKind::CONTEXTS[$context] ?? $context).' nicht vorgesehen.';
}
return null;
}
/**
* Filteroptionen der Materialart für einen Bestand: im Kontext zulässige Arten und Arten, die dort tatsächlich
* vorkommen (gekennzeichnet), dazu ein bereits gewählter Filter.
*
* @return array<string, string>
*/
public function kindFilterOptions(string $context, string $selected = ''): array
{
$used = $this->usedKindIds($context);
$options = [];
foreach (EditorialContentKind::query()->orderBy('sort_order')->orderBy('id')->get() as $kind) {
$show = ($kind->allows($context) && $kind->is_active) || in_array($kind->id, $used, true) || (string) $kind->id === $selected;
if ($show) {
$options[(string) $kind->id] = $this->kindLabel($kind, $context);
}
}
return $options;
}
public function kindLabel(EditorialContentKind $kind, string $context): string
{
return (string) $kind->label
.(! $kind->is_active ? self::INACTIVE_SUFFIX : (! $kind->allows($context) ? self::OUT_OF_CONTEXT_SUFFIX : ''));
}
/**
* @return list<int>
*/
private function usedKindIds(string $context): array
{
$query = match ($context) {
'medium' => DB::table('content_elements'),
'lizenzartikel' => DB::table('license_articles'),
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
default => null,
};
return $query === null ? [] : $query->whereNotNull('editorial_content_kind_id')->distinct()
->pluck('editorial_content_kind_id')->map(fn ($id): int => (int) $id)->all();
}
/**
* Einordnung im Editor: je angebotener Dimension aktive Werte und bereits zugeordnete inaktive Werte (gekennzeichnet).
*
* @param list<int> $assignedIds
* @return list<array{label: string, values: list<array{id: int, label: string, inactive: bool}>}>
*/
public function dimensionGroups(Model $subject, array $assignedIds): array
{
$groups = [];
foreach (EditorialDimension::forSubject($subject) as $dimension) {
$values = [];
foreach ($dimension->values as $value) {
if ($value->is_active || in_array((int) $value->id, $assignedIds, true)) {
$values[] = [
'id' => (int) $value->id,
'label' => (string) $value->label.($value->is_active ? '' : self::INACTIVE_SUFFIX),
'inactive' => ! $value->is_active,
];
}
}
if ($values !== []) {
$groups[] = ['label' => (string) $dimension->label, 'values' => $values];
}
}
return $groups;
}
/**
* Filtergruppen der Einordnung: aktive Werte, verwendete inaktive Werte (gekennzeichnet) und gewählte Filter.
*
* @param list<int> $selectedIds
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
*/
public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars = true): array
{
$used = DB::table('identity_dimension_values')->distinct()->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all();
$groups = [];
foreach (EditorialDimension::query()->with('values')->orderBy('label')->get() as $dimension) {
if (! $withPillars && $dimension->slug === EditorialDimension::PILLAR_SLUG) {
continue;
}
$values = [];
foreach ($dimension->values as $value) {
$id = (int) $value->id;
if ($value->is_active || in_array($id, $used, true) || in_array($id, $selectedIds, true)) {
$values[] = ['id' => $id, 'label' => (string) $value->label.($value->is_active ? '' : self::INACTIVE_SUFFIX)];
}
}
if ($values !== []) {
$groups[] = ['label' => (string) $dimension->label, 'values' => $values];
}
}
return $groups;
}
/**
* Öffentliche Filter der Mitgliederbibliothek: nur aktive Werte, ein bereits gewählter Wert bleibt sichtbar.
*
* @param list<int> $selectedIds
* @return Collection<int, EditorialDimension>
*/
public function memberFilterDimensions(array $selectedIds = []): Collection
{
$dimensions = EditorialDimension::query()->with('values')->orderBy('label')->get();
foreach ($dimensions as $dimension) {
$dimension->setRelation('values', $dimension->values
->filter(fn (EditorialDimensionValue $value): bool => $value->is_active || in_array((int) $value->id, $selectedIds, true))
->values());
}
return $dimensions->filter(fn (EditorialDimension $dimension): bool => $dimension->values->isNotEmpty())->values();
}
/**
* Für replaceOffered: Werte, die bei diesem Fachobjekt gesetzt oder entfernt werden dürfen. Aktive Werte der
* angebotenen Dimensionen und die bereits zugeordneten inaktiven (der Editor zeigt sie gekennzeichnet an).
*
* @param list<int> $assignedIds
* @return list<int>
*/
public function editableValueIds(Model $subject, array $assignedIds): array
{
$ids = [];
foreach (EditorialDimension::forSubject($subject) as $dimension) {
foreach ($dimension->values as $value) {
if ($value->is_active || in_array((int) $value->id, $assignedIds, true)) {
$ids[] = (int) $value->id;
}
}
}
return $ids;
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Domain\Catalog;
class EditorialWorkingDraft
{
/**
* @return array<string, mixed>|null
*/
public function read(Composition $composition): ?array
{
$draft = $composition->working_draft;
return is_array($draft) && $draft !== [] ? $draft : null;
}
/**
* @param array<string, mixed> $payload
*/
public function write(Composition $composition, array $payload): void
{
$composition->working_draft = $payload;
$composition->save();
}
public function clear(Composition $composition): void
{
if ($composition->working_draft === null) {
return;
}
$composition->working_draft = null;
$composition->save();
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class IdentityChange extends Model
{
protected $fillable = [
'subject_type',
'subject_id',
'field',
'before',
'after',
'actor_id',
'occurred_at',
];
protected function casts(): array
{
return [
'occurred_at' => 'datetime',
];
}
public function actor(): BelongsTo
{
return $this->belongsTo(User::class, 'actor_id');
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
class IdentityDimension
{
public function assign(Model $subject, EditorialDimensionValue $value, string $origin = 'direkt'): void
{
if (! in_array($origin, ['direkt', 'abgeleitet'], true)) {
throw new DomainRuleException('Die Herkunft einer Zuordnung ist direkt oder abgeleitet.');
}
IdentityDimensionValue::query()->updateOrCreate(
[
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'editorial_dimension_value_id' => $value->id,
],
['origin' => $origin],
);
}
/**
* @param list<int> $valueIds
*/
public function matches(Model $subject, array $valueIds): bool
{
if ($valueIds === []) {
return true;
}
$assigned = IdentityDimensionValue::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->pluck('editorial_dimension_value_id')
->all();
$wanted = EditorialDimensionValue::query()->whereIn('id', $valueIds)->get()->groupBy('editorial_dimension_id');
if ($wanted->isEmpty()) {
return false;
}
foreach ($wanted as $group) {
$ids = $group->pluck('id')->all();
if (array_intersect($ids, $assigned) === []) {
return false;
}
}
return true;
}
/**
* Ersetzt nur die Werte der Dimensionen, die dieses Fachobjekt anbietet.
* Nicht angebotene Zuordnungen, etwa gespiegelte Säulen am Inhaltselement, bleiben.
*
* Inaktive Werte (Stammdatenpflege) sind nicht neu wählbar. Bereits zugeordnete inaktive Werte zeigt der Editor
* gekennzeichnet an; sie bleiben, solange sie mitgeschickt werden, und werden nur bei ausdrücklicher Abwahl entfernt.
*
* @param list<int> $valueIds
*/
public function replaceOffered(Model $subject, array $valueIds): void
{
$assigned = IdentityDimensionValue::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->pluck('editorial_dimension_value_id')
->map(fn ($id): int => (int) $id)
->all();
$offeredIds = app(EditorialVocabulary::class)->editableValueIds($subject, $assigned);
$ids = array_values(array_intersect(
array_values(array_unique(array_map(intval(...), $valueIds))),
$offeredIds,
));
$query = IdentityDimensionValue::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('origin', 'direkt')
->whereIn('editorial_dimension_value_id', $offeredIds === [] ? [0] : $offeredIds);
if ($ids !== []) {
$query->whereNotIn('editorial_dimension_value_id', $ids);
}
$query->delete();
foreach (EditorialDimensionValue::query()->whereIn('id', $ids)->get() as $value) {
$this->assign($subject, $value, 'direkt');
}
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
class IdentityDimensionValue extends Model
{
protected $fillable = [
'subject_type',
'subject_id',
'editorial_dimension_value_id',
'origin',
];
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
class IdentityProfile
{
/**
* @param array<string, mixed> $fields
*/
public function fill(Model $subject, array $fields, ?User $actor = null): void
{
foreach ($fields as $field => $value) {
$next = is_string($value) ? trim($value) : $value;
$next = $next === '' ? null : $next;
$before = $subject->getAttribute($field);
$before = $before === '' ? null : $before;
if ($before === $next) {
continue;
}
$subject->setAttribute($field, $next);
IdentityChange::query()->create([
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'field' => $field,
'before' => $before,
'after' => $next,
'actor_id' => $actor?->id,
'occurred_at' => now(),
]);
}
$subject->save();
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class LicenseArticle extends Model
{
protected $fillable = [
'code',
'working_title',
'display_title',
'teaser',
'summary',
'description',
'search_terms',
'editorial_content_kind_id',
'product_line',
'successor_of_id',
'current_release_id',
'archived_at',
];
protected function casts(): array
{
return [
'archived_at' => 'datetime',
];
}
public function releases(): HasMany
{
return $this->hasMany(ArticleRelease::class);
}
public function currentRelease(): BelongsTo
{
return $this->belongsTo(ArticleRelease::class, 'current_release_id');
}
public function successorOf(): BelongsTo
{
return $this->belongsTo(self::class, 'successor_of_id');
}
public function editorialContentKind(): BelongsTo
{
return $this->belongsTo(EditorialContentKind::class);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Offer extends Model
{
protected $fillable = [
'name',
];
public function versions(): HasMany
{
return $this->hasMany(OfferVersion::class);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Domain\Catalog;
class OfferCoverage
{
public function __construct(private readonly ContentResolver $resolver) {}
/**
* @param list<LicenseArticle> $articles
* @return list<string>
*/
public function missingLeaves(CompositionVersion $version, array $articles): array
{
$covered = [];
foreach ($articles as $article) {
$release = $article->currentRelease;
if ($release === null) {
continue;
}
foreach ($release->contents()->pluck('content_element_version_id') as $id) {
$covered[(int) $id] = true;
}
}
$missing = [];
foreach ($this->resolver->expand($version) as $row) {
if (! isset($covered[$row['version_id']])) {
$missing[] = $row['path'];
}
}
return $missing;
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OfferLine extends Model
{
protected $fillable = [
'offer_version_id',
'position',
'license_article_id',
'bundle_version_id',
'rights_profile_version_id',
];
protected static function booted(): void
{
static::creating(function (OfferLine $line): void {
$status = OfferVersion::query()->whereKey($line->offer_version_id)->value('status');
if (in_array(StatusValue::of($status), [
OfferStatus::Aktiv->value,
OfferStatus::Beendet->value,
], true)) {
throw new DomainRuleException('Eine aktivierte Angebotsfassung nimmt keine weiteren Positionen auf.');
}
});
static::updating(function (): void {
throw new DomainRuleException('Positionen einer Angebotsfassung sind unveränderlich.');
});
}
public function offerVersion(): BelongsTo
{
return $this->belongsTo(OfferVersion::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(LicenseArticle::class, 'license_article_id');
}
public function bundleVersion(): BelongsTo
{
return $this->belongsTo(BundleVersion::class);
}
public function rights(): BelongsTo
{
return $this->belongsTo(RightsProfileVersion::class, 'rights_profile_version_id');
}
}
+232
View File
@@ -0,0 +1,232 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Support\Facades\DB;
class OfferService
{
public function __construct(private readonly BundleService $bundles) {}
public function currentActiveVersion(Offer $offer): OfferVersion
{
$version = $offer->versions()
->where('status', OfferStatus::Aktiv)
->orderByDesc('number')
->first();
if ($version === null) {
throw new DomainRuleException('Das Angebot hat keine aktive Fassung.');
}
return $version;
}
/**
* @param array<string, mixed> $capabilities
* @param array<string, mixed> $options
*/
public function createRightsProfile(
string $name,
string $purpose,
array $capabilities,
array $options = [],
): RightsProfileVersion {
$purpose = trim($purpose);
if (! in_array($purpose, ['ehrenamtlich', 'kommerziell', 'institutionell'], true)) {
throw new DomainRuleException('Der Nutzungszweck eines Rechteprofils ist ehrenamtlich, kommerziell oder institutionell.');
}
if ($capabilities === []) {
throw new DomainRuleException('Ein Rechteprofil braucht mindestens eine Fähigkeit.');
}
$profile = RightsProfile::query()->create([
'name' => trim($name) !== '' ? trim($name) : throw new DomainRuleException('Der Name des Rechteprofils fehlt.'),
]);
return $profile->versions()->create([
'number' => 1,
'purpose' => $purpose,
'capabilities' => $capabilities,
'options' => $options,
]);
}
public function create(string $name): Offer
{
$name = trim($name);
if ($name === '') {
throw new DomainRuleException('Der Name des Angebots fehlt.');
}
return Offer::query()->create([
'name' => $name,
]);
}
/**
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
* @param array<string, mixed> $attributes
*/
public function activate(Offer $offer, array $lines, array $attributes = []): OfferVersion
{
if ($lines === []) {
throw new DomainRuleException('Eine Angebotsfassung braucht mindestens eine Position.');
}
$attributes = array_merge([
'price_cents' => null,
'tax_class' => null,
'term_rule' => 'dauerhaft',
'update_promise' => 'alle_freigegebenen_fassungen',
'dynamic' => false,
'grant_kind' => 'kauf',
'holder_kind' => 'person',
], $attributes);
$this->assertAttributes($attributes);
$scope = $this->scopeFor($lines);
$this->assertCoverage($lines, $attributes);
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
OfferVersion::query()
->where('offer_id', $offer->id)
->where('status', OfferStatus::Aktiv)
->update(['status' => OfferStatus::Beendet->value]);
$version = $offer->versions()->create([
'number' => ((int) $offer->versions()->max('number')) + 1,
'status' => OfferStatus::Entwurf,
'price_cents' => $attributes['price_cents'],
'tax_class' => $attributes['tax_class'],
'term_rule' => $attributes['term_rule'],
'update_promise' => $attributes['update_promise'],
'dynamic' => $attributes['dynamic'],
'grant_kind' => $attributes['grant_kind'],
'holder_kind' => $attributes['holder_kind'],
]);
foreach (array_values($lines) as $index => $line) {
$target = $line['target'];
$version->lines()->create([
'position' => $index + 1,
'license_article_id' => $target instanceof LicenseArticle ? $target->id : null,
'bundle_version_id' => $target instanceof BundleVersion ? $target->id : null,
'rights_profile_version_id' => $line['rights']->id,
]);
}
foreach ($scope as $entry) {
$version->resolvedScopes()->create($entry);
}
RightsProfileVersion::query()
->whereIn('id', array_column($scope, 'rights_profile_version_id'))
->whereNull('locked_at')
->update(['locked_at' => now()]);
$version->status = OfferStatus::Aktiv;
$version->activated_at = now();
$version->save();
return $version->load('resolvedScopes');
});
}
/**
* @return list<int>
*/
public function scopeArticleIds(OfferVersion $version): array
{
return $version->resolvedScopes()->orderBy('id')->pluck('license_article_id')->all();
}
/**
* @param array<string, mixed> $attributes
*/
private function assertAttributes(array $attributes): void
{
if (! in_array($attributes['term_rule'], ['dauerhaft', 'befristet', 'solange_angebot_aktiv', 'periodisch'], true)) {
throw new DomainRuleException('Die Laufzeitregel der Angebotsfassung ist unbekannt.');
}
if (! in_array($attributes['grant_kind'], ['kauf', 'bei_registrierung', 'auf_abruf'], true)) {
throw new DomainRuleException('Die Vergabeart der Angebotsfassung ist unbekannt.');
}
if (! in_array($attributes['holder_kind'], ['person', 'organisation'], true)) {
throw new DomainRuleException('Die Inhaberart der Angebotsfassung ist Person oder Organisation.');
}
if ($attributes['update_promise'] !== 'alle_freigegebenen_fassungen') {
throw new DomainRuleException('Die Updatezusage umfasst alle später freigegebenen Fassungen des Artikels.');
}
}
/**
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
*/
/**
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
* @param array<string, mixed> $attributes
*/
private function assertCoverage(array $lines, array $attributes): void
{
$versionId = $attributes['composition_version_id'] ?? null;
if ($versionId === null) {
return;
}
$version = CompositionVersion::query()->findOrFail($versionId);
$articles = [];
foreach ($lines as $line) {
if ($line['target'] instanceof LicenseArticle) {
$articles[] = $line['target'];
}
}
$missing = app(OfferCoverage::class)->missingLeaves($version, $articles);
if ($missing !== []) {
throw new DomainRuleException('Das Angebot deckt nicht alle Blätter: '.implode(', ', $missing));
}
}
private function scopeFor(array $lines): array
{
$scope = [];
foreach ($lines as $line) {
$target = $line['target'];
$rights = $line['rights'];
if ($target instanceof BundleVersion && $target->status !== BundleStatus::Veroeffentlicht) {
throw new DomainRuleException('Eine Angebotsfassung enthält nur veröffentlichte Paketfassungen.');
}
$articleIds = match (true) {
$target instanceof LicenseArticle => [$target->id],
$target instanceof BundleVersion => $this->bundles->articleIds($target),
default => throw new DomainRuleException('Eine Angebotsposition zeigt auf einen Lizenzartikel oder eine Paketfassung.'),
};
foreach ($articleIds as $articleId) {
$key = $articleId.'-'.$rights->id;
$scope[$key] = [
'license_article_id' => $articleId,
'rights_profile_version_id' => $rights->id,
];
}
}
return array_values($scope);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace App\Domain\Catalog;
enum OfferStatus: string
{
case Entwurf = 'entwurf';
case Aktiv = 'aktiv';
case Beendet = 'beendet';
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class OfferVersion extends Model
{
protected $fillable = [
'offer_id',
'number',
'status',
'price_cents',
'tax_class',
'term_rule',
'update_promise',
'dynamic',
'grant_kind',
'holder_kind',
'activated_at',
];
protected function casts(): array
{
return [
'status' => OfferStatus::class,
'dynamic' => 'boolean',
'activated_at' => 'datetime',
];
}
protected static function booted(): void
{
static::updating(function (OfferVersion $version): void {
$original = StatusValue::of($version->getOriginal('status'));
$next = StatusValue::of($version->status);
if ($original === OfferStatus::Beendet->value) {
throw new DomainRuleException('Eine beendete Angebotsfassung ist unveränderlich.');
}
if ($original === OfferStatus::Aktiv->value) {
if ($next !== OfferStatus::Beendet->value) {
throw new DomainRuleException('Eine aktive Angebotsfassung lässt sich nur durch Beendigung schließen.');
}
$dirty = $version->getDirty();
unset($dirty['status'], $dirty['updated_at']);
if ($dirty !== []) {
throw new DomainRuleException('Eine aktive Angebotsfassung lässt sich nur durch Beendigung schließen.');
}
}
});
}
public function offer(): BelongsTo
{
return $this->belongsTo(Offer::class);
}
public function lines(): HasMany
{
return $this->hasMany(OfferLine::class)->orderBy('position');
}
public function resolvedScopes(): HasMany
{
return $this->hasMany(ResolvedScope::class);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Cms\Page;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Pillar extends Model
{
protected $fillable = [
'name',
'slug',
'public_summary',
'sort_order',
'published_at',
];
protected function casts(): array
{
return [
'published_at' => 'datetime',
];
}
public function elements(): BelongsToMany
{
return $this->belongsToMany(ContentElement::class);
}
public function pages(): BelongsToMany
{
return $this->belongsToMany(Page::class);
}
/**
* @param Builder<Pillar> $query
* @return Builder<Pillar>
*/
public function scopePublished(Builder $query): Builder
{
return $query->whereNotNull('published_at')->orderBy('sort_order')->orderBy('name');
}
public function publicUrl(): string
{
return route('theme', ['slug' => $this->slug]);
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Cms\Page;
use Illuminate\Support\Str;
class PillarService
{
public function create(string $name): Pillar
{
$name = $this->name($name);
if (Pillar::query()->where('name', $name)->exists()) {
throw new DomainRuleException('Diese fachliche Säule gibt es schon.');
}
return Pillar::query()->create([
'name' => $name,
'slug' => $this->uniqueSlug(Str::slug($name, '-', 'de')),
]);
}
public function present(Pillar $pillar, string $name, string $slug, ?string $summary, bool $published, int $sortOrder): void
{
$name = $this->name($name);
if (Pillar::query()->where('name', $name)->whereKeyNot($pillar->id)->exists()) {
throw new DomainRuleException('Diese fachliche Säule gibt es schon.');
}
$summary = trim((string) $summary);
$pillar->name = $name;
$pillar->slug = $this->slug($slug, $pillar->id);
$pillar->public_summary = $summary === '' ? null : $summary;
$pillar->sort_order = max(0, $sortOrder);
$pillar->published_at = $published ? ($pillar->published_at ?? now()) : null;
$pillar->save();
}
public function delete(Pillar $pillar): void
{
if ($pillar->elements()->exists() || $pillar->pages()->exists()) {
throw new DomainRuleException('Eine Säule mit zugeordneten Medien oder Seiten wird nicht gelöscht.');
}
$pillar->delete();
}
/**
* @param list<int> $pillarIds
*/
public function assign(ContentElement $element, array $pillarIds): void
{
$element->pillars()->sync($this->ids($pillarIds));
}
/**
* @param list<int> $pillarIds
*/
public function assignPages(Page $page, array $pillarIds): void
{
$page->pillars()->sync($this->ids($pillarIds));
}
/**
* @param list<int> $pillarIds
* @return list<int>
*/
private function ids(array $pillarIds): array
{
$ids = array_values(array_unique(array_map(intval(...), $pillarIds)));
if (Pillar::query()->whereIn('id', $ids)->count() !== count($ids)) {
throw new DomainRuleException('Eine fachliche Säule fehlt.');
}
return $ids;
}
private function slug(string $slug, ?int $ignoreId = null): string
{
$slug = Str::slug($slug, '-', 'de');
if ($slug === '') {
throw new DomainRuleException('Die öffentliche Adresse der Säule fehlt.');
}
$existing = Pillar::query()->where('slug', $slug);
if ($ignoreId !== null) {
$existing->whereKeyNot($ignoreId);
}
if ($existing->exists()) {
throw new DomainRuleException('Diese öffentliche Adresse ist schon vergeben.');
}
return $slug;
}
private function uniqueSlug(string $base): string
{
$base = $base !== '' ? $base : 'saeule';
$slug = $base;
$suffix = 2;
while (Pillar::query()->where('slug', $slug)->exists()) {
$slug = $base.'-'.$suffix;
$suffix++;
}
return $slug;
}
private function name(string $name): string
{
$name = trim($name);
if ($name === '') {
throw new DomainRuleException('Der Name der fachlichen Säule fehlt.');
}
return $name;
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PresentationAssignment extends Model
{
protected $fillable = [
'subject_type',
'subject_id',
'content_element_id',
'presentation_role_id',
'position',
'source_version_id',
];
public function role(): BelongsTo
{
return $this->belongsTo(PresentationRole::class, 'presentation_role_id');
}
public function element(): BelongsTo
{
return $this->belongsTo(ContentElement::class, 'content_element_id');
}
public function sourceVersion(): BelongsTo
{
return $this->belongsTo(ContentElementVersion::class, 'source_version_id');
}
}
+515
View File
@@ -0,0 +1,515 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Media\ThumbnailRef;
use App\Domain\Media\WebsiteMedia;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
/**
* Präsentationsmedien sind Referenzen auf Inhaltselemente.
* Die Rolle gehört zur Zuordnung. Eine Zuordnung gibt nichts frei und ändert keine Fassung.
*/
class PresentationMedia
{
public function __construct(private readonly WebsiteMedia $website) {}
/**
* @return list<array<string, mixed>>
*/
public function rows(Model $subject): array
{
$assignments = PresentationAssignment::query()
->with(['role', 'element.editorialContentKind', 'sourceVersion'])
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->orderBy('position')
->orderBy('id')
->get();
$rows = [];
foreach ($assignments as $assignment) {
$element = $assignment->element;
$released = $element instanceof ContentElement && $this->website->present($element) !== null;
$binding = $this->binding($assignment);
$rows[] = [
'id' => $assignment->id,
'role' => (string) $assignment->role?->slug,
'role_label' => (string) ($assignment->role?->label ?? ''),
'ordered' => (bool) $assignment->role?->ordered,
'position' => (int) $assignment->position,
'standard' => $assignment->role?->slug === 'titelbild',
'element_id' => (int) $assignment->content_element_id,
'title' => $element instanceof ContentElement
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
'released' => $released,
'release_label' => $released ? 'Für die Website freigegeben' : 'Nicht für die Website freigegeben',
'binding' => $binding,
];
}
return $rows;
}
/**
* Gespeicherte Zuordnungen als bearbeitbarer Arbeitsstand, nach Rolle und Position geordnet.
*
* @return list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}>
*/
public function staged(Model $subject): array
{
$assignments = PresentationAssignment::query()
->with('role')
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->get()
->sortBy(fn (PresentationAssignment $row): string => sprintf('%05d-%05d-%08d', (int) $row->role?->sort_order, (int) $row->position, (int) $row->id))
->values();
$rows = [];
foreach ($assignments as $assignment) {
$rows[] = [
'key' => 'a'.$assignment->id,
'id' => (int) $assignment->id,
'role' => (string) $assignment->role?->slug,
'element_id' => (int) $assignment->content_element_id,
'source' => $assignment->source_version_id !== null ? (int) $assignment->source_version_id : null,
];
}
return $rows;
}
/**
* Anzeigezeilen für einen Arbeitsstand, gruppiert nach Rolle. Liest nur, schreibt nichts.
*
* @param list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}> $staged
* @return list<array{role: string, label: string, multiple: bool, ordered: bool, rows: list<array<string, mixed>>}>
*/
public function describe(array $staged): array
{
$roles = PresentationRole::query()->orderBy('sort_order')->get()->keyBy('slug');
$elements = ContentElement::query()
->with('editorialContentKind')
->whereIn('id', array_values(array_unique(array_map(fn (array $row): int => (int) $row['element_id'], $staged))))
->get()
->keyBy('id');
$sources = ContentElementVersion::query()
->whereIn('id', array_values(array_filter(array_map(fn (array $row): ?int => $row['source'] ?? null, $staged))))
->get()
->keyBy('id');
$groups = [];
foreach ($roles as $slug => $role) {
$rows = array_values(array_filter($staged, fn (array $row): bool => $row['role'] === $slug));
if ($rows === []) {
continue;
}
$described = [];
foreach ($rows as $row) {
$element = $elements->get((int) $row['element_id']);
$released = $element instanceof ContentElement && $this->website->present($element) !== null;
$source = $row['source'] !== null ? $sources->get((int) $row['source']) : null;
$described[] = [
'key' => $row['key'],
'id' => $row['id'],
'element_id' => (int) $row['element_id'],
'title' => $element instanceof ContentElement
? (string) ($element->display_title ?: $element->working_title)
: 'Medium fehlt',
'image' => $element instanceof ContentElement
? ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path)
: null,
'kind' => $element?->editorialContentKind?->label,
'output' => $element instanceof ContentElement ? (string) $element->output_class : '',
'released' => $released,
'release_label' => $released ? 'Für die Website freigegeben' : 'Nicht für die Website freigegeben',
'binding' => $source instanceof ContentElementVersion ? $this->bindingFor($source) : null,
'new' => $row['id'] === null,
];
}
$groups[] = [
'role' => (string) $slug,
'label' => PresentationRole::displayLabel((string) $slug, (string) $role->label),
'multiple' => (bool) $role->multiple,
'ordered' => (bool) $role->ordered,
'rows' => $described,
];
}
return $groups;
}
/**
* Prüft, ob ein Medium im Arbeitsstand einer Rolle zugeordnet werden darf. Liefert den Ablehnungsgrund oder null.
*/
public function refusal(Model $subject, string $roleSlug, int $elementId): ?string
{
$role = PresentationRole::query()->where('slug', $roleSlug)->first();
$element = ContentElement::query()->find($elementId);
if (! $role instanceof PresentationRole || ! $element instanceof ContentElement) {
return 'Rolle oder Medium fehlt.';
}
if ($element->archived_at !== null) {
return 'Ein archiviertes Medium wird nicht zugeordnet.';
}
if ($subject instanceof ContentElement && (int) $subject->getKey() === (int) $element->id) {
return 'Ein Medium kann nicht seine eigene Präsentation sein.';
}
return null;
}
/**
* Schreibt einen Arbeitsstand: entfernte Zuordnungen lösen, neue anlegen, Bindung und Reihenfolge je Rolle setzen.
* Medien, Fassungen und Website-Freigaben bleiben unberührt.
*
* Mit $baseline (dem beim Laden gelesenen Stand) werden nur Zuordnungen gelöst, die dort standen und im
* Arbeitsstand fehlen. Was inzwischen an anderer Stelle hinzugekommen ist, bleibt erhalten.
*
* @param list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}> $staged
* @param list<array{key: string, id: int|null, role: string, element_id: int, source: int|null}>|null $baseline
*/
public function commit(Model $subject, array $staged, ?User $actor = null, ?array $baseline = null): void
{
$roles = PresentationRole::query()->get()->keyBy('slug');
$seen = [];
foreach ($staged as $row) {
$role = $roles->get($row['role']);
if (! $role instanceof PresentationRole) {
throw new DomainRuleException('Diese Rolle gibt es nicht.');
}
$refusal = $this->refusal($subject, $row['role'], (int) $row['element_id']);
if ($refusal !== null) {
throw new DomainRuleException($refusal);
}
$pair = $row['role'].':'.$row['element_id'];
if (isset($seen[$pair])) {
throw new DomainRuleException('Ein Medium steht in derselben Rolle nur einmal.');
}
$seen[$pair] = true;
$count = count(array_filter($staged, fn (array $other): bool => $other['role'] === $row['role']));
if (! $role->multiple && $count > 1) {
throw new DomainRuleException($role->label.' hat nur eine Zuordnung.');
}
$element = ContentElement::query()->findOrFail((int) $row['element_id']);
$this->checkedSource($subject, $element, $row['source']);
}
DB::transaction(function () use ($subject, $staged, $roles, $actor, $baseline): void {
$existing = PresentationAssignment::query()
->with(['role', 'element'])
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->get()
->keyBy('id');
$kept = array_filter(array_map(fn (array $row): ?int => $row['id'], $staged));
$known = $baseline === null ? null : array_filter(array_map(fn (array $row): ?int => $row['id'], $baseline));
foreach ($existing as $id => $assignment) {
$wasLoaded = $known === null || in_array((int) $id, $known, true);
$replacedSingle = ! (bool) $assignment->role?->multiple
&& ! in_array((int) $id, $kept, true)
&& array_filter($staged, fn (array $row): bool => $row['role'] === $assignment->role?->slug) !== [];
if (! in_array((int) $id, $kept, true) && ($wasLoaded || $replacedSingle)) {
$this->record($subject, ($assignment->role?->label ?? 'Präsentation').': '.($assignment->element?->working_title ?? ''), null, $actor);
$assignment->delete();
}
}
$positions = [];
foreach ($staged as $row) {
$role = $roles->get($row['role']);
$position = $positions[$row['role']] = ($positions[$row['role']] ?? 0) + 1;
$assignment = $row['id'] !== null ? $existing->get($row['id']) : null;
if ($assignment instanceof PresentationAssignment) {
$changed = (int) $assignment->position !== $position
|| (int) ($assignment->source_version_id ?? 0) !== (int) ($row['source'] ?? 0);
$assignment->position = $position;
$assignment->source_version_id = $row['source'];
if ($changed) {
$assignment->save();
}
continue;
}
$element = ContentElement::query()->findOrFail((int) $row['element_id']);
$same = PresentationAssignment::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('presentation_role_id', $role->id)
->where('content_element_id', $element->id)
->first();
if ($same instanceof PresentationAssignment) {
$same->position = $position;
$same->source_version_id = $row['source'];
$same->save();
continue;
}
PresentationAssignment::query()->create([
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'content_element_id' => $element->id,
'presentation_role_id' => $role->id,
'position' => $position,
'source_version_id' => $row['source'],
]);
$this->record($subject, null, $role->label.': '.$element->working_title, $actor);
}
});
}
public function assign(Model $subject, string $roleSlug, int $elementId, ?int $sourceVersionId, ?User $actor = null): string
{
$role = PresentationRole::query()->where('slug', $roleSlug)->first();
$element = ContentElement::query()->find($elementId);
if (! $role instanceof PresentationRole || ! $element instanceof ContentElement) {
throw new DomainRuleException('Rolle oder Medium fehlt.');
}
if ($element->archived_at !== null) {
throw new DomainRuleException('Ein archiviertes Medium wird nicht zugeordnet.');
}
if ($subject instanceof ContentElement && (int) $subject->getKey() === (int) $element->id) {
throw new DomainRuleException('Ein Medium kann nicht seine eigene Präsentation sein.');
}
$source = $this->checkedSource($subject, $element, $sourceVersionId);
$existing = PresentationAssignment::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('presentation_role_id', $role->id)
->where('content_element_id', $element->id)
->first();
if ($existing instanceof PresentationAssignment) {
if ((int) $existing->source_version_id !== (int) ($source?->id ?? 0) && ($source !== null || $existing->source_version_id !== null)) {
$existing->source_version_id = $source?->id;
$existing->save();
$this->record($subject, null, $role->label.': '.$element->working_title, $actor);
}
return $element->working_title.' ist in dieser Rolle bereits zugeordnet.';
}
if (! $role->multiple) {
PresentationAssignment::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('presentation_role_id', $role->id)
->delete();
}
$position = (int) PresentationAssignment::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('presentation_role_id', $role->id)
->max('position') + 1;
PresentationAssignment::query()->create([
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'content_element_id' => $element->id,
'presentation_role_id' => $role->id,
'position' => max(1, $position),
'source_version_id' => $source?->id,
]);
$this->record($subject, null, $role->label.': '.$element->working_title, $actor);
return $element->working_title.' ist als '.$role->label.' zugeordnet. Es entsteht keine Fassung und keine Freigabe.';
}
public function detach(Model $subject, int $assignmentId, ?User $actor = null): string
{
$assignment = $this->owned($subject, $assignmentId);
$label = ($assignment->role?->label ?? 'Präsentation').': '.($assignment->element?->working_title ?? '');
$assignment->delete();
$this->record($subject, $label, null, $actor);
return 'Die Zuordnung ist entfernt. Das Medium bleibt im Bestand.';
}
public function move(Model $subject, int $assignmentId, int $direction, ?User $actor = null): void
{
$assignment = $this->owned($subject, $assignmentId);
if (! $assignment->role?->ordered || $direction === 0) {
return;
}
$neighbors = PresentationAssignment::query()
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->where('presentation_role_id', $assignment->presentation_role_id)
->orderBy('position')
->orderBy('id')
->get()
->values();
$index = $neighbors->search(fn (PresentationAssignment $row): bool => $row->id === $assignment->id);
if ($index === false) {
return;
}
$swap = $index + ($direction < 0 ? -1 : 1);
$other = $neighbors->get($swap);
if (! $other instanceof PresentationAssignment) {
return;
}
$position = $assignment->position;
$assignment->position = $other->position === $position ? $position + ($direction < 0 ? -1 : 1) : $other->position;
$other->position = $position;
$assignment->save();
$other->save();
$this->record($subject, null, 'Reihenfolge '.$assignment->role?->label, $actor);
}
/**
* Kennung des ersten Titel- oder Galeriebildes. Ob es öffentlich erscheint, entscheidet WebsiteMedia.
*/
public function coverElementId(Model $subject): ?int
{
$assignments = PresentationAssignment::query()
->with('role')
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->orderBy('position')
->get();
foreach (PresentationRole::COVER_ROLES as $slug) {
$match = $assignments->first(fn (PresentationAssignment $row): bool => $row->role?->slug === $slug);
if ($match instanceof PresentationAssignment) {
return (int) $match->content_element_id;
}
}
return null;
}
private function owned(Model $subject, int $assignmentId): PresentationAssignment
{
$assignment = PresentationAssignment::query()
->with(['role', 'element'])
->where('subject_type', $subject->getMorphClass())
->where('subject_id', $subject->getKey())
->whereKey($assignmentId)
->first();
if (! $assignment instanceof PresentationAssignment) {
throw new DomainRuleException('Diese Zuordnung gehört zu einem anderen Objekt.');
}
return $assignment;
}
private function checkedSource(Model $subject, ContentElement $element, ?int $sourceVersionId): ?ContentElementVersion
{
if ($sourceVersionId === null) {
return null;
}
$version = ContentElementVersion::query()->find($sourceVersionId);
if (! $version instanceof ContentElementVersion) {
throw new DomainRuleException('Die gebundene Fassung fehlt.');
}
$ownsFilm = $subject instanceof ContentElement && (int) $version->content_element_id === (int) $subject->getKey();
$ownsClip = (int) $version->content_element_id === (int) $element->id;
if (! $ownsFilm && ! $ownsClip) {
throw new DomainRuleException('Die gebundene Fassung gehört weder zum Fachobjekt noch zum zugeordneten Medium.');
}
return $version;
}
/**
* @return array{label: string, stale: bool}|null
*/
private function binding(PresentationAssignment $assignment): ?array
{
if ($assignment->source_version_id === null || ! $assignment->sourceVersion instanceof ContentElementVersion) {
return null;
}
return $this->bindingFor($assignment->sourceVersion);
}
/**
* @return array{label: string, stale: bool}
*/
private function bindingFor(ContentElementVersion $version): array
{
$latestId = ContentElementVersion::query()
->where('content_element_id', $version->content_element_id)
->where('status', ContentVersionStatus::Bereit)
->orderByDesc('number')
->value('id');
$stale = $latestId !== null && (int) $latestId !== (int) $version->id;
return [
'label' => $stale
? 'Gebunden an Fassung '.$version->number.'. Die aktuelle Fassung ist eine andere. Der Clip wurde nicht neu erzeugt.'
: 'Gebunden an Fassung '.$version->number.'.',
'stale' => $stale,
];
}
private function record(Model $subject, ?string $before, ?string $after, ?User $actor): void
{
IdentityChange::query()->create([
'subject_type' => $subject->getMorphClass(),
'subject_id' => $subject->getKey(),
'field' => 'praesentation',
'before' => $before,
'after' => $after,
'actor_id' => $actor?->id,
'occurred_at' => now(),
]);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class PresentationRole extends Model
{
/** Rollen, deren Herkunft an einer Film- oder Audiofassung festgehalten werden kann. */
public const BOUND_ROLES = ['trailer', 'vorschauclip', 'audiovorschau'];
/** Reihenfolge, in der ein öffentliches Titelbild gesucht wird. */
public const COVER_ROLES = ['titelbild', 'hero', 'hover', 'titelbild_alternativ', 'galerie'];
protected $fillable = [
'slug',
'label',
'multiple',
'ordered',
'sort_order',
];
protected function casts(): array
{
return [
'multiple' => 'boolean',
'ordered' => 'boolean',
];
}
public function assignments(): HasMany
{
return $this->hasMany(PresentationAssignment::class);
}
/**
* @return array<string, string>
*/
public static function selectOptions(): array
{
return static::query()->orderBy('sort_order')->pluck('label', 'slug')->all();
}
/**
* Kurze Bezeichnung für Überschriften und Auswahl in der Verwaltung.
*/
public static function displayLabel(string $slug, string $label): string
{
return match ($slug) {
'titelbild' => 'Titelbild',
'titelbild_alternativ' => 'Alternative Titelbilder',
'trailer' => 'Trailer',
'vorschauclip' => 'Vorschauclips',
'interview' => 'Interviews',
'galerie' => 'Galerie',
default => $label,
};
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ReleaseContent extends Model
{
protected $fillable = [
'article_release_id',
'position',
'content_element_version_id',
'role',
'path',
];
protected static function booted(): void
{
static::creating(function (ReleaseContent $content): void {
$status = StatusValue::of(ArticleRelease::query()->whereKey($content->article_release_id)->value('status'));
if ($status !== ReleaseStatus::Entwurf->value) {
throw new DomainRuleException('Der Inhalt eines Artikel-Stands wird nur im Entwurf festgeschrieben.');
}
});
static::updating(function (): void {
throw new DomainRuleException('Der festgeschriebene Inhalt eines Artikel-Stands ist unveränderlich.');
});
}
public function release(): BelongsTo
{
return $this->belongsTo(ArticleRelease::class, 'article_release_id');
}
public function elementVersion(): BelongsTo
{
return $this->belongsTo(ContentElementVersion::class, 'content_element_version_id');
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Domain\Catalog;
enum ReleaseStatus: string
{
case Entwurf = 'entwurf';
case Veroeffentlicht = 'veroeffentlicht';
case AbgeloestVerfuegbar = 'abgeloest_verfuegbar';
case Gesperrt = 'gesperrt';
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ResolvedScope extends Model
{
protected $fillable = [
'offer_version_id',
'license_article_id',
'rights_profile_version_id',
];
protected static function booted(): void
{
static::updating(function (): void {
throw new DomainRuleException('Der aufgelöste Leistungsumfang einer Angebotsfassung ist unveränderlich.');
});
}
public function offerVersion(): BelongsTo
{
return $this->belongsTo(OfferVersion::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(LicenseArticle::class, 'license_article_id');
}
public function rights(): BelongsTo
{
return $this->belongsTo(RightsProfileVersion::class, 'rights_profile_version_id');
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Domain\Catalog;
/**
* Ein aufgelöster redaktioneller Text. Der Wert wird nicht kopiert:
* eigen steht am Fachobjekt, variante ist eine Abweichung für einen Kontext,
* quelle verweist auf das eindeutig zugeordnete Fachobjekt eines Lizenzartikels.
*/
final readonly class ResolvedText
{
public function __construct(
public ?string $value,
public string $origin,
public ?string $label,
) {}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class RightsProfile extends Model
{
protected $fillable = [
'name',
];
public function versions(): HasMany
{
return $this->hasMany(RightsProfileVersion::class);
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class RightsProfileVersion extends Model
{
protected $fillable = [
'rights_profile_id',
'number',
'purpose',
'capabilities',
'options',
'locked_at',
];
protected function casts(): array
{
return [
'capabilities' => 'array',
'options' => 'array',
'locked_at' => 'datetime',
];
}
protected static function booted(): void
{
static::updating(function (RightsProfileVersion $version): void {
if ($version->getOriginal('locked_at') !== null) {
throw new DomainRuleException('Eine verwendete Rechteprofil-Fassung ist unveränderlich.');
}
});
}
public function profile(): BelongsTo
{
return $this->belongsTo(RightsProfile::class, 'rights_profile_id');
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Domain\Catalog;
use BackedEnum;
class StatusValue
{
public static function of(mixed $status): ?string
{
return $status instanceof BackedEnum ? $status->value : $status;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Domain\Catalog;
/**
* @phpstan-type StructureNodeData array{
* role: string,
* position: int,
* composition_version_id: int|null,
* composition_id: int|null,
* content_element_version_id: int|null,
* content_element_id: int|null,
* editorial_kind: string|null,
* technical_kind: string|null,
* title: string,
* output_class: string|null,
* children: list<StructureNodeData>
* }
*/
readonly class StructureNode
{
/**
* @param list<StructureNode> $children
*/
public function __construct(
public string $role,
public int $position,
public ?int $compositionVersionId,
public ?int $compositionId,
public ?int $contentElementVersionId,
public ?int $contentElementId,
public ?string $editorialKindLabel,
public ?string $technicalKindLabel,
public ?string $outputClass,
public string $title,
public array $children = [],
) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'role' => $this->role,
'position' => $this->position,
'composition_version_id' => $this->compositionVersionId,
'composition_id' => $this->compositionId,
'content_element_version_id' => $this->contentElementVersionId,
'content_element_id' => $this->contentElementId,
'editorial_kind' => $this->editorialKindLabel,
'technical_kind' => $this->technicalKindLabel,
'output_class' => $this->outputClass,
'title' => $this->title,
'children' => array_map(fn (StructureNode $child): array => $child->toArray(), $this->children),
];
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Domain\Cms\Catalog;
/**
* Anzeigedaten des Fachobjekts hinter einer Premium-Karte (Thema, Medium/Material, Programm/Modul).
* Wird zur Laufzeit aus den maßgeblichen Fachdaten gelesen und nie im CMS gespeichert.
*
* - url: nur ein öffentlich freigegebenes Ziel aus dem Fachobjekt (Themenseite, Programmseite), sonst null.
* - public: false heißt „nur in der Redaktionsvorschau“; öffentlich entfällt die Karte dann.
* - notice: redaktioneller Hinweis für die Vorschau, warum die Karte öffentlich nicht erscheint.
* - visual: Darstellung ohne Kartenbild: 'film' (Medientafel Film), 'material' (Materialsymbol),
* 'catalog' (Navy-Tafel Programm/Modul) oder null (Karte ohne Bildbereich).
* - previewImage: geschütztes Vorschaubild der Bibliothek (Filmstandbild, Vorschau des Moduls). Nur für die
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
* keine Freigabe für die Website hat.
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
*/
final readonly class CardSubject
{
/**
* @param list<string> $meta reine Anzeigetexte aus Fachdaten
* @param list<string> $missing Hinweise für die Redaktion
*/
public function __construct(
public string $title,
public ?string $summary,
public string $kind,
public ?string $badge,
public array $meta,
public ?string $url,
public bool $public,
public ?string $notice = null,
public ?string $visual = null,
public ?string $visualLabel = null,
public ?string $previewImage = null,
public array $missing = [],
public ?string $style = null,
) {}
public function withText(?string $title, ?string $summary): self
{
return new self(
title: $title ?? $this->title,
summary: $summary ?? $this->summary,
kind: $this->kind,
badge: $this->badge,
meta: $this->meta,
url: $this->url,
public: $this->public,
notice: $this->notice,
visual: $this->visual,
visualLabel: $this->visualLabel,
previewImage: $this->previewImage,
missing: $this->missing,
style: $this->style,
);
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Domain\Cms\Catalog;
/**
* Anzeigedaten eines Fachobjekts, zur Laufzeit aus den maßgeblichen Fachdaten gelesen. Wird nie gespeichert.
*/
final readonly class CatalogEntry
{
public function __construct(
public int $id,
public string $title,
public ?string $summary,
public string $kindLabel,
public ?string $url,
public bool $public,
) {}
}
@@ -0,0 +1,349 @@
<?php
namespace App\Domain\Cms\Catalog;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Media\ThumbnailRef;
use Illuminate\Support\Collection;
/**
* Lesesicht „Öffentlicher Katalog“ für Website und CMS (Website-CMS-Zielarchitektur 5.1, 6.2).
*
* Übergangsregel, solange öffentliche Fachobjektprofile (ADR-29) fehlen:
* Öffentlich gezeigt wird nur, was die Website bereits heute öffentlich zeigt, nämlich Kompositionen
* der Inhaltsart „programm“ mit einer zur Anzeige freigegebenen Fassung (Route /programme).
* Module haben noch keine öffentliche Seitenart; sie sind im Editor wählbar und erscheinen nur in
* der geschützten Redaktionsvorschau, nie auf der öffentlichen Seite.
*
* Gelesen werden nur Anzeigetitel, Kurzbeschreibung und Inhaltsart, nie Dateien, Lehrtexte oder
* Vorschaubilder der Bibliothek (diese sind geschützt, Paket 6).
*/
class PublicCatalogReader
{
/** Inhaltsarten mit öffentlicher Seitenart. */
public const PUBLIC_KINDS = ['programm'];
/** Inhaltsarten, die ein Katalog-Widget referenzieren darf. */
public const SELECTABLE_KINDS = ['programm', 'modul'];
public function __construct(private readonly CompositionDisplayRelease $releases) {}
/**
* @return Collection<int, Composition>
*/
public function publicPrograms(): Collection
{
$kind = EditorialContentKind::query()->where('slug', 'programm')->first();
if ($kind === null) {
return collect();
}
return Composition::query()
->where('editorial_content_kind_id', $kind->id)
->orderBy('designation')
->get()
->filter(fn (Composition $composition): bool => $this->shownVersion($composition) !== null)
->values();
}
/**
* Gezeigte Fassung einer öffentlich gezeigten Komposition, sonst null.
*/
public function shownVersion(Composition $composition): ?CompositionVersion
{
if (! in_array($composition->editorialContentKind?->slug, self::PUBLIC_KINDS, true)) {
return null;
}
return $this->releases->highestReleasedVersion($composition);
}
public function isPublic(Composition $composition): bool
{
return $this->shownVersion($composition) !== null;
}
/**
* Wählbar sind Programme und Module mit zur Anzeige freigegebener Fassung, die nicht archiviert sind.
*/
public function isSelectable(Composition $composition): bool
{
return $composition->archived_at === null
&& in_array($composition->editorialContentKind?->slug, self::SELECTABLE_KINDS, true)
&& $this->releases->highestReleasedVersion($composition) !== null;
}
/**
* Suchtreffer für die Auswahl im Editor: Kennung => Bezeichnung mit Sichtbarkeitshinweis.
*
* @return array<int, string>
*/
public function search(?string $term, int $limit = 25): array
{
$term = trim((string) $term);
$candidates = Composition::query()
->with('editorialContentKind')
->whereNull('archived_at')
->whereHas('editorialContentKind', fn ($query) => $query->whereIn('slug', self::SELECTABLE_KINDS))
->when($term !== '', function ($query) use ($term): void {
$like = '%'.mb_strtolower($term).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(designation) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(teaser, \'\')) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(search_terms, \'\')) LIKE ?', [$like]));
})
->orderBy('designation')
->limit($limit * 3)
->get();
$options = [];
foreach ($candidates as $composition) {
if (! $this->isSelectable($composition)) {
continue;
}
$options[$composition->id] = $this->optionLabel($composition);
if (count($options) >= $limit) {
break;
}
}
return $options;
}
public function labelFor(mixed $id): ?string
{
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
return $composition === null ? null : $this->optionLabel($composition);
}
/**
* Löst Verweise in Anzeigeeinträge auf. Öffentlich entfallen nicht öffentliche Objekte stillschweigend.
*
* @param list<array{type?: mixed, id?: mixed}> $refs
* @return list<CatalogEntry>
*/
public function entries(array $refs, bool $includeNonPublic): array
{
$ids = [];
foreach ($refs as $ref) {
if (is_array($ref) && ($ref['type'] ?? null) === 'composition' && is_numeric($ref['id'] ?? null)) {
$ids[] = (int) $ref['id'];
}
}
if ($ids === []) {
return [];
}
$compositions = Composition::query()->with('editorialContentKind')->whereIn('id', $ids)->get()->keyBy('id');
$entries = [];
foreach (array_unique($ids) as $id) {
$composition = $compositions->get($id);
if ($composition === null || ! $this->isSelectable($composition)) {
continue;
}
$public = $this->isPublic($composition);
if (! $public && ! $includeNonPublic) {
continue;
}
$entries[] = new CatalogEntry(
id: $composition->id,
title: $this->title($composition),
summary: filled($composition->summary) ? (string) $composition->summary : null,
kindLabel: (string) ($composition->editorialContentKind?->label ?? ''),
url: $public ? route('public.program', $composition) : null,
public: $public,
);
}
return $entries;
}
/**
* Für die Programm- oder Modulkarte wählbar: Programm oder Modul, nicht archiviert, mit mindestens einer
* bereitgestellten Fassung. Anders als bei den Katalogkarten ist keine Anzeigefreigabe nötig, damit die Redaktion
* eine Karte vorbereiten kann; öffentlich gilt unverändert isPublic().
*/
public function isCardSelectable(Composition $composition): bool
{
return $composition->archived_at === null
&& in_array($composition->editorialContentKind?->slug, self::SELECTABLE_KINDS, true)
&& $this->latestReadyVersion($composition) !== null;
}
/**
* @return array<int, string>
*/
public function cardSearch(?string $term, int $limit = 25): array
{
$term = trim((string) $term);
$candidates = Composition::query()
->with('editorialContentKind')
->whereNull('archived_at')
->whereHas('editorialContentKind', fn ($query) => $query->whereIn('slug', self::SELECTABLE_KINDS))
->when($term !== '', function ($query) use ($term): void {
$like = '%'.mb_strtolower($term).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(designation) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(teaser, \'\')) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(search_terms, \'\')) LIKE ?', [$like]));
})
->orderBy('designation')
->limit($limit * 3)
->get();
$options = [];
foreach ($candidates as $composition) {
if (! $this->isCardSelectable($composition)) {
continue;
}
$options[$composition->id] = $this->cardOptionLabel($composition);
if (count($options) >= $limit) {
break;
}
}
return $options;
}
public function cardLabelFor(mixed $id): ?string
{
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
return $composition === null ? null : $this->cardOptionLabel($composition);
}
/**
* Anzeigedaten für eine Programm- oder Modulkarte (Premium-Karte).
*
* - Öffentlich nur Programme mit Anzeigefreigabe (dieselbe Regel wie /programme), mit Programmseite als Ziel.
* Module haben keine öffentliche Seitenart (ADR-29) und erscheinen nur in der Redaktionsvorschau, ohne Link.
* - Text: Kurzbeschreibung, sonst das Lernziel der gezeigten (öffentlich) bzw. neuesten bereitgestellten Fassung;
* das Lernziel steht auf der öffentlichen Programmseite bereits öffentlich.
* - Zusatzangaben: Zahl der Module, Dauer. Kein Preis, kein Angebot, keine Kaufaktion; eine Karte ist kein
* Lizenzartikel. Das Vorschaubild der Bibliothek erscheint nur in der Redaktionsvorschau.
*/
public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
{
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
if ($composition === null || ! $this->isCardSelectable($composition)) {
return null;
}
$shown = $this->shownVersion($composition);
$public = $shown !== null && $composition->archived_at === null;
if (! $public && ! $includeNonPublic) {
return null;
}
$version = $shown ?? $this->latestReadyVersion($composition);
$program = $composition->editorialContentKind?->slug === 'programm';
$kind = (string) ($composition->editorialContentKind?->label ?? ($program ? 'Programm' : 'Modul'));
$profile = app(EditorialProfileReader::class)->read($composition, 'kachel');
$summary = $profile->value('teaser') ?: $profile->value('summary');
$goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null;
$missing = [];
if ($summary === null) {
$missing[] = $goal !== null
? 'Keine Kurzbeschreibung gepflegt; die Karte zeigt das Lernziel.'
: 'Weder Kurzbeschreibung noch Lernziel gepflegt.';
}
$meta = [];
if ($version !== null) {
$modules = $version->members()
->whereNotNull('nested_composition_version_id')
->with('nestedCompositionVersion.composition.editorialContentKind')
->get()
->filter(fn ($member): bool => $member->nestedCompositionVersion?->composition?->editorialContentKind?->slug === 'modul')
->count();
if ($program && $modules > 0) {
$meta[] = $modules === 1 ? '1 Modul' : $modules.' Module';
}
if (is_numeric($version->duration_minutes) && (int) $version->duration_minutes > 0) {
$meta[] = 'Dauer '.(int) $version->duration_minutes.' Min.';
} else {
$missing[] = 'Keine Dauer gepflegt.';
}
}
$notice = null;
if (! $public) {
$notice = 'Nur in der Redaktionsvorschau sichtbar: '.($program
? 'Das Programm hat keine Anzeigefreigabe.'
: 'Für Module gibt es noch keine öffentliche Seitenart (öffentliches Profil, ADR-29); die Karte erhält deshalb keinen Link.');
}
return new CardSubject(
title: $profile->value('display_title') ?: $this->title($composition),
summary: $summary ?? $goal,
kind: $kind,
badge: null,
meta: $meta,
url: $public ? route('public.program', $composition) : null,
public: $public,
notice: $notice,
visual: 'catalog',
visualLabel: $kind,
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
missing: $missing,
);
}
private function latestReadyVersion(Composition $composition): ?CompositionVersion
{
return $composition->versions()
->where('status', ContentVersionStatus::Bereit->value)
->orderByDesc('number')
->first();
}
private function cardOptionLabel(Composition $composition): string
{
$visibility = match (true) {
$this->isPublic($composition) => 'öffentlich sichtbar',
$composition->editorialContentKind?->slug === 'modul' => 'Modul, nur Redaktionsvorschau',
default => 'ohne Anzeigefreigabe, nur Redaktionsvorschau',
};
return $this->title($composition).' · '.($composition->editorialContentKind?->label ?? '').' · '.$visibility;
}
private function title(Composition $composition): string
{
return (string) ($composition->display_title ?: $composition->designation);
}
private function optionLabel(Composition $composition): string
{
$visibility = $this->isPublic($composition) ? 'öffentlich sichtbar' : 'nur Redaktionsvorschau';
return $this->title($composition).' · '.($composition->editorialContentKind?->label ?? '').' · '.$visibility;
}
}
@@ -0,0 +1,286 @@
<?php
namespace App\Domain\Cms\Catalog;
use App\Domain\Catalog\CompositionStructureReader;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\StructureNode;
use App\Domain\Media\ThumbnailRef;
/**
* Lesesicht „Medien und Materialien“ für Premium-Karten (Website-CMS-Zielarchitektur 6.2).
*
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung.
*
* Öffentliche Sichtbarkeit (Übergangsregel, solange öffentliche Fachobjektprofile nach ADR-29 fehlen):
* Ein Medium hat keine eigene öffentliche Seite. Öffentlich genannt wird es heute nur als Bestandteil der gezeigten
* Fassung eines öffentlichen Programms (Programmseite /programme/{id}). Genau dann erscheint auch die Karte
* öffentlich, mit Verweis auf diese Programmseite, und nur mit bereitgestellter Fassung. Traineranleitungen erscheinen
* nie öffentlich (vertraulich für Trainerinnen und Trainer).
*
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Kurzbeschreibung, Inhaltsart und Ausgabeart. Nie:
* Beschreibung, Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte, Ausgabeadressen. Das Vorschaubild (Filmstandbild)
* der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der Redaktionsvorschau.
* Eine Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
*/
class PublicMaterialReader
{
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen. */
public const CONFIDENTIAL_KINDS = ['traineranleitung'];
/** @var array<int, array{id: int, title: string}>|null Element-ID => erstes öffentliches Programm */
private ?array $publicIndex = null;
public function __construct(
private readonly PublicCatalogReader $catalog,
private readonly CompositionStructureReader $structure,
) {}
public function isSelectable(ContentElement $element): bool
{
return $element->archived_at === null
&& $element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists();
}
public function isReady(ContentElement $element): bool
{
return $element->versions()->where('status', ContentVersionStatus::Bereit->value)->exists();
}
/**
* Öffentliches Programm, in dessen gezeigter Fassung das Element vorkommt, sonst null.
*
* @return array{id: int, title: string}|null
*/
public function publicProgramFor(ContentElement $element): ?array
{
return $this->publicIndex()[$element->id] ?? null;
}
public function isPublic(ContentElement $element): bool
{
return $this->isSelectable($element)
&& $this->isReady($element)
&& ! in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true)
&& $this->publicProgramFor($element) !== null;
}
/**
* @return array<int, string>
*/
public function search(?string $term, int $limit = 25): array
{
$term = trim((string) $term);
$candidates = ContentElement::query()
->with('editorialContentKind')
->whereNull('archived_at')
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
->when($term !== '', function ($query) use ($term): void {
$like = '%'.mb_strtolower($term).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(working_title) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
})
->orderBy('working_title')
->limit($limit)
->get();
$options = [];
foreach ($candidates as $element) {
$options[$element->id] = $this->optionLabel($element);
}
return $options;
}
public function labelFor(mixed $id): ?string
{
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
return $element === null ? null : $this->optionLabel($element);
}
/**
* Anzeigedaten für eine Karte. Öffentlich null, wenn das Element nicht öffentlich genannt wird.
*
* @param array<string, mixed> $draft ungespeicherte Anzeigedaten, nur für die Redaktionsvorschau
*/
public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?CardSubject
{
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
if ($element === null || ! $this->isSelectable($element)) {
return null;
}
$public = $this->isPublic($element);
if (! $public && ! $includeNonPublic) {
return null;
}
$shown = clone $element;
foreach (['working_title', 'display_title', 'summary', 'thumbnail_path', 'thumbnail_alt'] as $field) {
if (! array_key_exists($field, $draft)) {
continue;
}
$value = $draft[$field];
$shown->setAttribute($field, is_string($value) && trim($value) === '' ? null : $value);
}
$program = $this->publicProgramFor($element);
$output = self::outputLabel((string) $shown->output_class);
$film = $shown->output_class === 'film';
$editorialKind = $element->editorialContentKind?->label;
$summary = filled($shown->summary) ? trim((string) $shown->summary) : null;
$profile = app(EditorialProfileReader::class)->read($shown, 'bibliothek');
if (! array_key_exists('summary', $draft) && $profile->origin('summary') === 'variante') {
$summary = $profile->value('summary');
} elseif ($summary === null && filled($shown->teaser)) {
$summary = trim((string) $shown->teaser);
}
$title = (string) ($shown->display_title ?: $shown->working_title);
if (! array_key_exists('display_title', $draft) && $profile->origin('display_title') === 'variante') {
$title = (string) $profile->value('display_title');
}
$meta = [$output];
if ($program !== null) {
$meta[] = 'Im Programm „'.$program['title'].'“';
}
if ($film) {
$meta[] = 'Vollständiger Film nur mit Lizenz im Mitgliederbereich';
}
$missing = [];
if ($summary === null) {
$missing[] = 'Keine Kurzbeschreibung gepflegt (Medium bearbeiten → Kurzbeschreibung).';
}
if (! filled($shown->display_title)) {
$missing[] = 'Kein Anzeigetitel gepflegt; die Karte zeigt den Arbeitstitel.';
}
$previewImage = $includeNonPublic ? ThumbnailRef::url('editorial.card', 'element', (int) $element->id, $shown->thumbnail_path) : null;
return new CardSubject(
title: $title,
summary: $summary,
kind: filled($editorialKind) ? (string) $editorialKind : $output,
badge: $output,
meta: $meta,
url: $public && $program !== null ? route('public.program', $program['id']) : null,
public: $public,
notice: $public ? null : $this->notice($element, $program),
visual: $film ? 'film' : 'material',
visualLabel: $output,
previewImage: $previewImage,
missing: $missing,
style: $film ? 'media' : 'material',
);
}
/** Bezeichnung der Ausgabeart, wie in der Redaktionsstruktur (CompositionRelease::outputLabel). */
public static function outputLabel(string $outputClass): string
{
return match ($outputClass) {
'film' => 'Film',
'audio' => 'Hörstück',
'bild' => 'Bild',
'document', 'pdf' => 'Dokument',
default => 'Text',
};
}
public function visibilityNote(ContentElement $element): string
{
if ($this->isPublic($element)) {
$program = $this->publicProgramFor($element);
return 'Öffentlich nur als Teil der Programmseite „'.($program['title'] ?? '').'“. Die Mediendatei wird dabei nicht ausgeliefert.';
}
return $this->notice($element, $this->publicProgramFor($element));
}
/**
* @param array{id: int, title: string}|null $program
*/
private function notice(ContentElement $element, ?array $program): string
{
$reason = match (true) {
in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true) => 'Traineranleitungen erscheinen nie öffentlich.',
! $this->isReady($element) => 'Das Medium hat noch keine bereitgestellte Fassung.',
$program === null => 'Das Medium gehört zu keinem öffentlich gezeigten Programm. Medien haben noch keine eigene öffentliche Freigabe (öffentliches Profil, ADR-29).',
default => 'Das Medium ist nicht öffentlich.',
};
return 'Nur in der Redaktionsvorschau sichtbar: '.$reason;
}
private function optionLabel(ContentElement $element): string
{
$visibility = $this->isPublic($element)
? 'öffentlich über Programmseite'
: ($this->isReady($element) ? 'nur Redaktionsvorschau' : 'Entwurf, nur Redaktionsvorschau');
$kind = $element->editorialContentKind?->label ?: self::outputLabel((string) $element->output_class);
return (string) ($element->display_title ?: $element->working_title).' · '.$kind.' · '.$visibility;
}
/**
* Index aller Elemente, die in der gezeigten Fassung eines öffentlichen Programms vorkommen (auch verschachtelt).
*
* @return array<int, array{id: int, title: string}>
*/
private function publicIndex(): array
{
if ($this->publicIndex !== null) {
return $this->publicIndex;
}
$index = [];
foreach ($this->catalog->publicPrograms() as $program) {
$version = $this->catalog->shownVersion($program);
if ($version === null) {
continue;
}
$entry = ['id' => (int) $program->id, 'title' => (string) ($program->display_title ?: $program->designation)];
foreach ($this->elementIds($this->structure->tree($version)) as $elementId) {
$index[$elementId] ??= $entry;
}
}
return $this->publicIndex = $index;
}
/**
* @param list<StructureNode> $nodes
* @return list<int>
*/
private function elementIds(array $nodes): array
{
$ids = [];
foreach ($nodes as $node) {
if ($node->contentElementId !== null) {
$ids[] = (int) $node->contentElementId;
}
array_push($ids, ...$this->elementIds($node->children));
}
return $ids;
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class NavigationItem extends Model
{
/**
* Plätze im globalen Website-Gerüst. Die drei Fußbereichsgruppen ersetzen eine eigene Footer-Verwaltung.
*/
public const PLACEMENTS = [
'header' => 'Kopfzeile (Hauptnavigation)',
'footer' => 'Fußbereich: Service',
'footer_contact' => 'Fußbereich: Kontakt',
'footer_legal' => 'Fußbereich: Rechtliches',
];
/** Spaltenüberschriften im Fußbereich. */
public const FOOTER_GROUPS = [
'footer' => 'Service',
'footer_contact' => 'Kontakt',
'footer_legal' => 'Rechtliches',
];
protected $fillable = [
'label',
'page_id',
'url',
'placement',
'sort_order',
'is_visible',
'parent_id',
];
protected static function booted(): void
{
// Untermenüs gibt es nur in der Hauptnavigation.
static::saving(function (NavigationItem $item): void {
if ($item->placement !== 'header' && $item->getAttribute('parent_id') !== null) {
$item->parent_id = null;
}
});
}
protected function casts(): array
{
return [
'is_visible' => 'boolean',
];
}
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_id');
}
public function children(): HasMany
{
return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id');
}
/**
* @param Builder<NavigationItem> $query
*/
public function scopeVisible(Builder $query): void
{
$query->where('is_visible', true);
}
public function href(): ?string
{
if ($this->page !== null) {
return $this->page->path === '/' ? url('/') : url($this->page->path);
}
if ($this->url === null || $this->url === '' || ! SafeUrl::isSafe($this->url)) {
return null;
}
if (str_starts_with($this->url, '/')) {
return url($this->url);
}
return $this->url;
}
/**
* Pfad des Ziels innerhalb der Website (für die Kennzeichnung des aktiven Eintrags); null bei externen Zielen.
*/
public function targetPath(): ?string
{
if ($this->page !== null) {
return $this->page->path;
}
if (is_string($this->url) && str_starts_with($this->url, '/') && ! str_starts_with($this->url, '//')) {
$path = parse_url($this->url, PHP_URL_PATH);
return is_string($path) ? '/'.trim($path, '/') : null;
}
return null;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Identity\StaffRole;
use App\Models\User;
class NavigationItemPolicy
{
public function viewAny(User $user): bool
{
return $user->hasStaffRole(StaffRole::Redakteur);
}
public function view(User $user, NavigationItem $item): bool
{
return $this->viewAny($user);
}
public function create(User $user): bool
{
return $this->viewAny($user);
}
public function update(User $user, NavigationItem $item): bool
{
return $this->viewAny($user);
}
public function delete(User $user, NavigationItem $item): bool
{
return $this->viewAny($user);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Catalog\Pillar;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
class Page extends Model
{
protected $fillable = [
'path',
];
public function revisions(): HasMany
{
return $this->hasMany(PageRevision::class)->latest('id');
}
public function publishedRevision(): BelongsTo
{
return $this->belongsTo(PageRevision::class, 'published_revision_id');
}
public function latestRevision(): HasOne
{
return $this->hasOne(PageRevision::class)->latestOfMany();
}
public function navigationItems(): HasMany
{
return $this->hasMany(NavigationItem::class);
}
public function isPublished(): bool
{
return $this->published_revision_id !== null;
}
public function publicUrl(): string
{
return $this->path === '/' ? url('/') : url($this->path);
}
public function publicTitle(): string
{
$revision = $this->publishedRevision;
if (is_string($revision?->seo_title) && $revision->seo_title !== '') {
return $revision->seo_title;
}
return $revision?->contentTitle() ?? $this->path;
}
public function pillars(): BelongsToMany
{
return $this->belongsToMany(Pillar::class)->orderBy('pillars.name');
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Identity\StaffRole;
use App\Models\User;
class PagePolicy
{
public function viewAny(User $user): bool
{
return $user->hasStaffRole(StaffRole::Redakteur);
}
public function view(User $user, Page $page): bool
{
return $this->viewAny($user);
}
public function create(User $user): bool
{
return $this->viewAny($user);
}
public function update(User $user, Page $page): bool
{
return $this->viewAny($user);
}
public function publish(User $user, Page $page): bool
{
return $this->viewAny($user);
}
public function delete(User $user, Page $page): bool
{
return false;
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Cms\Sections\PageSections;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PageRevision extends Model
{
public const UPDATED_AT = null;
protected $fillable = [
'page_id',
'blocks',
'sections',
'seo_title',
'seo_description',
'created_by',
];
protected function casts(): array
{
return [
'blocks' => 'array',
'sections' => 'array',
'created_at' => 'datetime',
];
}
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
/**
* Abschnitte als aktuelle Hüllen. Revisionen ohne Abschnitte (vor Einführung des Rasters) werden als
* einspaltige Abschnitte gelesen. Die gespeicherten Daten bleiben unverändert.
*
* @return list<array<string, mixed>>
*/
public function sections(): array
{
return app(PageSections::class)->read($this->sections, $this->blocks);
}
/**
* Widgets in Lesereihenfolge als aktuelle Hüllen.
*
* @return list<array<string, mixed>>
*/
public function widgets(): array
{
return app(PageSections::class)->flatten($this->sections());
}
/**
* Titel aus dem ersten Überschriften- oder Einstiegs-Widget.
*/
public function contentTitle(): ?string
{
return app(PageSections::class)->pageTitle($this->sections());
}
}
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Cms\Sections\PageSections;
use App\Jobs\PublishPublicMedia;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
class PageService
{
public function __construct(private readonly PageSections $sections) {}
/**
* Speichert einen Entwurf als neue Revision. Veröffentlicht nichts.
*
* @param array<int|string, mixed> $content Abschnitte mit Slots; flache Widgets (Altformat oder Hülle)
* werden als einspaltige Abschnitte übernommen
*/
public function saveRevision(Page $page, array $content, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
{
$sections = $this->sections->normalize($content);
$seoTitle = $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null;
$seoDescription = $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null;
// Unveränderter Stand: keine weitere Revision (zum Beispiel „Veröffentlichen“ direkt nach dem Speichern).
$latest = $page->revisions()->first();
if ($latest !== null && $latest->sections === $sections && $latest->seo_title === $seoTitle && $latest->seo_description === $seoDescription) {
return $latest;
}
return $this->storeRevision($page, $this->sections->flatten($sections), $sections, $seoTitle, $seoDescription, $author);
}
public function publish(Page $page, PageRevision $revision): void
{
if ($revision->page_id !== $page->id) {
throw ValidationException::withMessages([
'revision' => 'Die Revision gehört zu einer anderen Seite.',
]);
}
$page->published_revision_id = $revision->id;
$page->save();
}
/**
* Legt den Stand einer früheren Revision unverändert als neue Revision an. Abschnitte und Bausteine
* werden nicht umgeschrieben; ältere Formate werden erst beim Lesen angehoben.
*/
public function restore(Page $page, PageRevision $source, ?User $author): PageRevision
{
if ($source->page_id !== $page->id) {
throw ValidationException::withMessages([
'revision' => 'Die Revision gehört zu einer anderen Seite.',
]);
}
return $this->storeRevision(
$page,
$source->blocks ?? [],
$source->sections,
$source->seo_title,
$source->seo_description,
$author,
);
}
/**
* Legt eine neue, unveröffentlichte Seite mit dem zuletzt gespeicherten Stand einer vorhandenen Seite an.
* Die Vorlage bleibt unverändert; spätere Änderungen wirken nicht auf die Kopie.
*/
public function duplicate(Page $source, string $path, ?User $author): Page
{
$revision = $source->latestRevision ?? $source->publishedRevision;
$page = Page::query()->create(['path' => $this->availablePath($path)]);
$this->saveRevision(
$page,
$revision?->sections() ?? [],
$revision?->seo_title,
$revision?->seo_description,
$author,
);
return $page;
}
/**
* Normalisiert den Pfad und prüft, dass keine andere Seite ihn verwendet.
*/
public function availablePath(string $path, ?Page $except = null): string
{
$path = $this->normalizePath($path);
$taken = Page::query()
->where('path', $path)
->when($except !== null, fn ($query) => $query->whereKeyNot($except->getKey()))
->exists();
if ($taken) {
throw ValidationException::withMessages([
'path' => 'Diesen Pfad verwendet bereits eine andere Seite.',
]);
}
return $path;
}
public function normalizePath(string $path): string
{
$path = '/'.trim($path, '/');
if ($path === '/') {
return '/';
}
$path = mb_strtolower($path);
if (preg_match('#^/[a-z0-9]+(?:-[a-z0-9]+)*$#', $path) !== 1) {
throw ValidationException::withMessages([
'path' => 'Der Pfad darf nur Kleinbuchstaben, Ziffern und Bindestriche enthalten.',
]);
}
return $path;
}
/**
* @param array<int|string, mixed> $blocks flache Widget-Liste (Rollback-Fassung)
* @param array<int|string, mixed>|null $sections Abschnitte; null bei Revisionen aus der Zeit vor dem Raster
*/
private function storeRevision(Page $page, array $blocks, ?array $sections, ?string $seoTitle, ?string $seoDescription, ?User $author): PageRevision
{
$attributes = [
'blocks' => array_values($blocks),
'seo_title' => $seoTitle !== null && $seoTitle !== '' ? $seoTitle : null,
'seo_description' => $seoDescription !== null && $seoDescription !== '' ? $seoDescription : null,
'created_by' => $author?->id,
];
// Die Erstbefüllung der Website läuft innerhalb einer frühen Migration, bevor die Spalte existiert.
// Solche Revisionen haben keine Abschnitte und werden beim Lesen als einspaltige Abschnitte gelesen.
if ($sections !== null && Schema::hasColumn('page_revisions', 'sections')) {
$attributes['sections'] = array_values($sections);
}
$revision = $page->revisions()->create($attributes);
// „Geändert“ in der Seitenliste zeigt die letzte Bearbeitung, nicht das Anlagedatum.
$page->touch();
foreach ($this->sections->mediaPaths($revision->sections()) as $path) {
PublishPublicMedia::dispatch($path);
}
return $revision;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Domain\Cms;
/**
* Seitenvorlagen der öffentlichen Website. Eine Vorlage ordnet die gerenderten Widgets im Inhaltsbereich
* des gemeinsamen Layouts an. Derzeit gibt es nur „standard“; weitere Vorlagen (zum Beispiel für
* Themen- oder Landingpages) werden in config/cms.php ergänzt und später über einen Seitentyp gewählt.
*/
class PageTemplates
{
public const DEFAULT = 'standard';
/**
* @return array<string, string>
*/
public function all(): array
{
return config('cms.templates', [self::DEFAULT => 'site.templates.standard']);
}
public function viewFor(Page $page): string
{
$templates = $this->all();
return $templates[self::DEFAULT];
}
}
+360
View File
@@ -0,0 +1,360 @@
<?php
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetRegistry;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/**
* Abschnitts- und Slotmodell einer Seite: Seite → Abschnitte → Slots → Widget-Instanzen.
*
* Gespeicherte Hülle eines Abschnitts (Version 1):
* {id, v, layout, style: {background, image, focus, overlay, width, spacing_top, spacing_bottom, gap, divider}, slots: [Widget-Hülle|null, …]}
*
* Version 2 (Abstände): oben, unten und Widget-Abstand sind drei unabhängige Werte. Hüllen der Version 1 werden beim
* Lesen übersetzt (SectionStyle::migrateSpacing), ohne die Darstellung zu ändern; gespeicherte Revisionen bleiben.
*
* Jeder Slot enthält höchstens ein Widget aus dem zentralen Widget-Register. Abschnitte sind nicht verschachtelbar.
* Revisionen ohne Abschnitte (Bestand vor dieser Fassung) werden beim Lesen als einspaltige Abschnitte gelesen.
*/
class PageSections
{
public const VERSION = 2;
public const MAX_SECTIONS = 30;
public const MAX_WIDGETS = 60;
public function __construct(private readonly WidgetRegistry $widgets) {}
/**
* Lesepfad. Unbekannte Werte fallen auf Vorgaben zurück, unbekannte Widget-Arten entfallen.
*
* @param array<int|string, mixed>|null $sections gespeicherte Abschnitte (Spalte sections)
* @param array<int|string, mixed>|null $blocks flache Bausteinliste (Spalte blocks), nur ohne Abschnitte verwendet
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
public function read(?array $sections, ?array $blocks = null): array
{
if ($sections === null) {
return $this->wrapWidgets($blocks ?? []);
}
$result = [];
foreach (SectionStyle::migrateSpacing(array_values(array_filter($sections, 'is_array')), byVersion: true) as $section) {
$result[] = $this->upcastSection($section);
}
return $result;
}
/**
* Schreibpfad: prüft und bereinigt Abschnitte für eine neue Revision. Flache Widgets (ohne „slots“) werden
* als einspaltige Abschnitte übernommen. Alle Fehler der Seite werden gesammelt gemeldet; Schlüssel:
* „sections.N.layout“, „sections.N.style.image“, „sections.N.slots“, „sections.N.slots.M.data.feld“.
*
* @param array<int|string, mixed> $content
* @return list<array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
public function normalize(array $content): array
{
$items = array_values($content);
if (count($items) > self::MAX_SECTIONS) {
throw ValidationException::withMessages([
'sections' => 'Eine Seite hat höchstens '.self::MAX_SECTIONS.' Abschnitte.',
]);
}
$errors = [];
$sections = [];
$seenSectionIds = [];
$seenWidgetIds = [];
$widgetCount = 0;
// Eingaben mit Abständen der Version 1 (zum Beispiel ältere Aufrufer) werden wie beim Lesen übersetzt.
$migrated = SectionStyle::migrateSpacing(array_map(
fn ($item) => is_array($item) && array_key_exists('slots', $item) ? $item : ['style' => [], 'slots' => [$item]],
$items,
));
foreach ($items as $index => $item) {
if (! is_array($item)) {
$errors["sections.$index"] = ['Ein Abschnitt ist unvollständig.'];
continue;
}
if (! array_key_exists('slots', $item)) {
$item = ['id' => null, 'layout' => SectionLayouts::DEFAULT, 'style' => [], 'slots' => [$item]];
} else {
$item['style'] = $migrated[$index]['style'] ?? ($item['style'] ?? []);
}
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount);
}
if ($widgetCount > self::MAX_WIDGETS) {
$errors['sections'] = ['Eine Seite enthält höchstens '.self::MAX_WIDGETS.' Widgets.'];
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
return $sections;
}
/**
* Widgets in Lesereihenfolge (Abschnitt für Abschnitt, Slot für Slot). Wird zusätzlich als flache
* Bausteinliste gespeichert, damit ein Code-Rollback auf die Fassung vor den Abschnitten die Inhalte
* weiterhin untereinander darstellt.
*
* @param list<array<string, mixed>> $sections
* @return list<array<string, mixed>>
*/
public function flatten(array $sections): array
{
$widgets = [];
foreach ($sections as $section) {
$count = SectionLayouts::slotCount($section['layout']);
foreach (array_slice($section['slots'], 0, $count) as $widget) {
if (is_array($widget)) {
$widgets[] = $widget;
}
}
}
return $widgets;
}
/**
* Öffentliche Medien der Seite: Widget-Bilder und Hintergrundbilder der Abschnitte.
*
* @param list<array<string, mixed>> $sections
* @return list<string>
*/
public function mediaPaths(array $sections): array
{
$paths = [];
foreach ($sections as $section) {
$style = SectionStyle::fromStored($section['style'] ?? []);
if (is_string($style['image']) && PublicMedia::isPublicPath($style['image'])) {
$paths[] = $style['image'];
}
}
foreach ($this->widgets->mediaPaths($this->flatten($sections)) as $path) {
$paths[] = $path;
}
return array_values(array_unique($paths));
}
/**
* @param list<array<string, mixed>> $sections
*/
public function pageTitle(array $sections): ?string
{
return $this->widgets->pageTitle($this->flatten($sections));
}
/**
* @param array<int|string, mixed> $blocks
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
*/
private function wrapWidgets(array $blocks): array
{
$sections = [];
foreach ($this->widgets->read($blocks) as $position => $widget) {
$sections[] = [
'id' => null,
'v' => self::VERSION,
'layout' => SectionLayouts::DEFAULT,
// Bestand vor dem Raster stand in einem durchgehenden Blatt: kompakte Abstände, zwischen den Widgets
// nur einmal (oben kein Abstand ab dem zweiten), wie bisher.
'style' => ['spacing_top' => $position === 0 ? 'compact' : 'none', 'spacing_bottom' => 'compact', 'gap' => 'normal'] + SectionStyle::DEFAULTS,
'slots' => [$widget],
];
}
return $sections;
}
/**
* @param array<string, mixed> $section
* @return array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
*/
private function upcastSection(array $section): array
{
$layout = SectionLayouts::has($section['layout'] ?? null) ? $section['layout'] : SectionLayouts::DEFAULT;
$slots = [];
foreach (array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []) as $slot) {
$slots[] = is_array($slot) ? $this->widgets->upcast($slot) : null;
}
while (count($slots) < SectionLayouts::slotCount($layout)) {
$slots[] = null;
}
return [
'id' => is_string($section['id'] ?? null) ? $section['id'] : null,
'v' => self::VERSION,
'layout' => $layout,
'style' => SectionStyle::fromStored($section['style'] ?? []),
'slots' => $slots,
];
}
/**
* @param array<string, mixed> $section
* @param array<string, list<string>> $errors
* @param array<string, true> $seenSectionIds
* @param array<string, true> $seenWidgetIds
* @return array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
*/
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount): array
{
$prefix = "sections.$index";
$layout = $section['layout'] ?? SectionLayouts::DEFAULT;
if (! SectionLayouts::has($layout)) {
$errors["$prefix.layout"] = ['Dieses Abschnittsraster ist nicht freigegeben.'];
$layout = SectionLayouts::DEFAULT;
}
$style = $this->normalizeStyle(is_array($section['style'] ?? null) ? $section['style'] : [], $prefix, $errors);
$units = SectionLayouts::units($layout);
$rawSlots = array_values(is_array($section['slots'] ?? null) ? $section['slots'] : []);
$filled = count(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
if ($filled > count($units)) {
$errors["$prefix.slots"] = [sprintf(
'Das Raster „%s“ hat %d %s, der Abschnitt enthält aber %d Widgets. Entfernen Sie ein Widget oder wählen Sie ein Raster mit mehr Plätzen.',
SectionLayouts::short($layout),
count($units),
count($units) === 1 ? 'Platz' : 'Plätze',
$filled,
)];
} elseif (count($rawSlots) > count($units)) {
// Überzählige Plätze sind leer: Widgets rücken in Reihenfolge nach vorn, leere Plätze entfallen.
$rawSlots = array_values(array_filter($rawSlots, fn ($slot): bool => is_array($slot)));
}
$slots = [];
foreach ($units as $position => $slotUnits) {
$block = $rawSlots[$position] ?? null;
if (! is_array($block)) {
$slots[] = null;
continue;
}
$widgetCount++;
try {
$widget = $this->widgets->normalizeWidget($block, "$prefix.slots.$position", $seenWidgetIds);
} catch (ValidationException $exception) {
foreach ($exception->errors() as $key => $messages) {
$errors[$key] = $messages;
}
$slots[] = null;
continue;
}
$type = $this->widgets->get($widget['type']);
if (! $type->supportsUnits($slotUnits)) {
$errors["$prefix.slots.$position.units"] = [sprintf(
'„%s“ ist für Plätze mit %s Rastereinheiten vorgesehen; dieser Platz hat %d. Wählen Sie ein passendes Raster oder einen passenden Platz.',
$type->label(),
$type->unitsLabel(),
$slotUnits,
)];
}
$slots[] = $widget;
}
$id = $section['id'] ?? null;
if (! is_string($id) || preg_match('/^[A-Za-z0-9-]{1,64}$/', $id) !== 1 || isset($seenSectionIds[$id])) {
$id = (string) Str::uuid();
}
$seenSectionIds[$id] = true;
return [
'id' => $id,
'v' => self::VERSION,
'layout' => $layout,
'style' => $style,
'slots' => $slots,
];
}
/**
* @param array<string, mixed> $style
* @param array<string, list<string>> $errors
* @return array<string, mixed>
*/
private function normalizeStyle(array $style, string $prefix, array &$errors): array
{
$result = SectionStyle::DEFAULTS;
$enums = SectionStyle::enums();
foreach ($style as $key => $value) {
if ($key === 'image' || str_starts_with((string) $key, '_')) {
continue;
}
if (! isset($enums[$key])) {
$errors["$prefix.style.$key"] = ['Diese Gestaltungsoption ist nicht freigegeben.'];
continue;
}
if ($value === null || $value === '') {
continue;
}
if (! is_string($value) || ! array_key_exists($value, $enums[$key])) {
$errors["$prefix.style.$key"] = ['Dieser Gestaltungswert ist nicht freigegeben.'];
continue;
}
$result[$key] = $value;
}
if ($result['background'] === 'image') {
$widgetErrors = new WidgetErrors;
$refs = ImageRefFields::clean(['image' => $style['image'] ?? null, '_upload' => $style['_upload'] ?? null], $widgetErrors, errorKey: 'image');
$image = $refs['image'];
foreach ($widgetErrors->all() as $messages) {
$errors["$prefix.style.image"] = $messages;
}
if ($image === null && ! isset($errors["$prefix.style.image"])) {
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild aus dem Medienmanager wählen oder hochladen.'];
}
$result['image'] = $image;
} else {
$result['image'] = null;
}
return $result;
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
namespace App\Domain\Cms\Sections;
/**
* Freigegebene Abschnittsraster. Ein Raster teilt die Abschnittsbreite in höchstens vier logische Einheiten.
* Die Kennungen sind gespeichert und ändern sich nie; neue Raster werden ergänzt, nicht umbenannt.
*
* Die Einheiten werden nicht als eigenes CSS-Grundraster umgesetzt, sondern als Spaltenverhältnis (fr)
* des Abschnittsrasters. Leere Slots entfallen auf der veröffentlichten Seite; die übrigen Slots teilen
* sich die Breite im Verhältnis ihrer Einheiten.
*/
final class SectionLayouts
{
public const DEFAULT = 'u4';
/** @var array<string, list<int>> */
public const UNITS = [
'u4' => [4],
'u2_2' => [2, 2],
'u1_3' => [1, 3],
'u3_1' => [3, 1],
'u1_2_1' => [1, 2, 1],
'u1_1_1_1' => [1, 1, 1, 1],
'u1_1_2' => [1, 1, 2],
'u2_1_1' => [2, 1, 1],
];
/** @var array<string, string> */
public const LABELS = [
'u4' => 'Volle Breite',
'u2_2' => 'Zwei gleich breit',
'u1_3' => 'Schmal und breit',
'u3_1' => 'Breit und schmal',
'u1_2_1' => 'Mitte betont',
'u1_1_1_1' => 'Vier gleich breit',
'u1_1_2' => 'Zwei schmal, eins breit',
'u2_1_1' => 'Eins breit, zwei schmal',
];
public static function has(mixed $key): bool
{
return is_string($key) && isset(self::UNITS[$key]);
}
/**
* @return list<int>
*/
public static function units(string $key): array
{
return self::UNITS[$key] ?? self::UNITS[self::DEFAULT];
}
public static function slotCount(string $key): int
{
return count(self::units($key));
}
/** Kurzform wie „1 + 3“. */
public static function short(string $key): string
{
return implode(' + ', self::units($key));
}
public static function label(string $key): string
{
return (self::LABELS[$key] ?? self::LABELS[self::DEFAULT]).' ('.self::short($key).')';
}
/**
* @return array<string, string>
*/
public static function options(): array
{
$options = [];
foreach (array_keys(self::UNITS) as $key) {
$options[$key] = self::label($key);
}
return $options;
}
/**
* Spaltenvorlagen für die Slots, die tatsächlich etwas darstellen.
*
* - Desktop (Abschnitt ab 60rem): Verhältnis der Einheiten.
* - Tablet (ab 40rem): gleich breite Slots bleiben nebeneinander (zwei oder drei Spalten, vier Slots als 2 × 2);
* ungleiche Raster stapeln, damit kein Slot unter etwa 13rem fällt.
* - Smartphone: immer eine Spalte. Die Lese- und Fokusreihenfolge bleibt die Reihenfolge der Slots.
*
* @param list<int> $units
* @return array{lg: string, md: string}
*/
public static function columns(array $units): array
{
$units = array_values(array_filter($units, fn ($unit): bool => is_int($unit) && $unit > 0));
$count = count($units);
if ($count <= 1) {
return ['lg' => 'minmax(0, 1fr)', 'md' => 'minmax(0, 1fr)'];
}
$lg = implode(' ', array_map(fn (int $unit): string => "minmax(0, {$unit}fr)", $units));
$equal = count(array_unique($units)) === 1;
$md = match (true) {
! $equal => 'minmax(0, 1fr)',
$count === 3 => 'repeat(3, minmax(0, 1fr))',
default => 'repeat(2, minmax(0, 1fr))',
};
return ['lg' => $lg, 'md' => $md];
}
/**
* Symbolbild des Rasters für die grafische Auswahl im Editor (rein dekorativ).
*/
public static function schematicSvg(string $key): string
{
$units = self::units($key);
$gap = 2;
$width = 56 - $gap * (count($units) - 1);
$x = 2;
$rects = '';
foreach ($units as $unit) {
$w = (int) round($width * $unit / 4);
$rects .= sprintf('<rect x="%d" y="4" width="%d" height="20" rx="1.5"/>', $x, $w);
$x += $w + $gap;
}
return '<svg class="luf-layout-schematic" viewBox="0 0 60 28" width="60" height="28" aria-hidden="true" focusable="false">'.$rects.'</svg>';
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetRenderer;
use Illuminate\Support\HtmlString;
/**
* Einziger Darstellungsweg für Abschnitte: öffentliche Seite und Seitenvorschau rufen denselben Renderer auf.
*
* Regeln:
* - Leere Slots erzeugen keine Leerfläche; die übrigen Slots teilen sich die Breite im Verhältnis ihrer Einheiten.
* - Ein Abschnitt ohne darstellbares Widget entfällt samt Hintergrund und Trenner.
* - Das erste dargestellte Widget der Seite ist der Seiteneinstieg (Überschrift erster Ordnung).
* - Trenner stehen zwischen Abschnitten, nie nach dem letzten.
*/
class SectionRenderer
{
public function __construct(private readonly WidgetRenderer $widgets) {}
/**
* @param list<array<string, mixed>> $sections gelesene Abschnitte (PageSections::read)
*/
public function renderAll(array $sections, RenderContext $context): HtmlString
{
$rendered = [];
$first = true;
foreach ($sections as $section) {
$cells = [];
$units = SectionLayouts::units($section['layout']);
foreach ($units as $position => $slotUnits) {
$widget = $section['slots'][$position] ?? null;
if (! is_array($widget)) {
continue;
}
$html = $this->widgets->renderWidget($widget, $context, $first);
if ($html !== '') {
$first = false;
$cells[] = ['units' => $slotUnits, 'html' => $html];
}
}
if ($cells !== []) {
$rendered[] = ['section' => $section, 'cells' => $cells];
}
}
$html = '';
$last = count($rendered) - 1;
foreach ($rendered as $index => $item) {
$html .= $this->renderSection($item['section'], $item['cells'], $index, $context);
$divider = $item['section']['style']['divider'] ?? 'none';
if ($index < $last && in_array($divider, ['line', 'accent'], true)) {
$html .= '<div class="section-divider section-divider-'.$divider.'" aria-hidden="true"><span></span></div>';
}
}
return new HtmlString($html);
}
/**
* @param array<string, mixed> $section
* @param list<array{units: int, html: string}> $cells
*/
private function renderSection(array $section, array $cells, int $index, RenderContext $context): string
{
$style = SectionStyle::fromStored($section['style'] ?? []);
$columns = SectionLayouts::columns(array_column($cells, 'units'));
// Hintergrundbild aus dem Medienmanager: öffentlich nur mit Website-Freigabe (WebsiteImage → WebsiteMedia).
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview) : null;
$hasImage = $imageUrl !== null;
$classes = [
'page-section',
'section-bg-'.($hasImage ? 'image' : ($style['background'] === 'image' ? 'default' : $style['background'])),
'section-width-'.$style['width'],
'section-space-top-'.$style['spacing_top'],
'section-space-bottom-'.$style['spacing_bottom'],
'section-gap-'.$style['gap'],
'section-layout-'.str_replace('_', '-', $section['layout']),
];
if ($hasImage) {
$classes[] = 'section-overlay-'.$style['overlay'];
}
// Bedeutungswerte der Fläche (tokens.css): helle Schrift auf dunklen Flächen, gelber Fokus.
$scope = match (true) {
$hasImage && $style['overlay'] === 'dark' => 'scope-dark',
$hasImage => 'scope-light',
$style['background'] === 'dark' => 'scope-dark',
$style['background'] === 'accent' => 'scope-accent',
default => null,
};
if ($scope !== null) {
$classes[] = $scope;
}
$id = is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '';
$html = '<div class="'.e(implode(' ', $classes)).'"'.$id.'>';
if ($hasImage) {
// Das Bild des ersten Abschnitts ist meist das größte sichtbare Element und wird nicht verzögert geladen.
$loading = $index === 0 ? 'loading="eager" fetchpriority="high"' : 'loading="lazy"';
$html .= '<img class="page-section-image" src="'.e($imageUrl).'" alt="" '.$loading.' decoding="async"'
.' style="object-position: '.e(SectionStyle::FOCUS_POSITIONS[$style['focus']]).'">';
}
$html .= '<div class="page-section-inner"><div class="section-grid" data-slots="'.count($cells).'"'
.' style="--section-cols-lg: '.e($columns['lg']).'; --section-cols-md: '.e($columns['md']).'">';
foreach ($cells as $cell) {
$html .= '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
}
return $html.'</div></div></div>';
}
}
+244
View File
@@ -0,0 +1,244 @@
<?php
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
/**
* Semantische Abschnittsgestaltung. Jeder Wert ist eine Aufzählung, die auf zentrale Design-Tokens
* abgebildet wird (resources/css/app.css, Abschnitt „Abschnitte“). Keine freie CSS- oder Farbangabe.
*/
final class SectionStyle
{
/** @var array<string, string> */
public const BACKGROUNDS = [
'default' => 'Standard (ohne eigene Fläche)',
'light' => 'Helle Markenfläche',
'dark' => 'Dunkle Markenfläche',
'accent' => 'Markenakzent',
'image' => 'Hintergrundbild',
];
/** @var array<string, string> */
public const WIDTHS = [
'narrow' => 'Lesebereich',
'standard' => 'Standard',
'wide' => 'Breit',
'full' => 'Vollbreite',
];
/**
* Gemeinsame Stufen der drei Abstände eines Abschnitts (Hülle Version 2):
* - spacing_top: Abstand vor dem Inhalt (oben),
* - spacing_bottom: Abstand nach dem Inhalt (unten),
* - gap: Abstand zwischen den Plätzen im Abschnittsraster, nebeneinander und gestapelt.
* Zwischen zwei Abschnitten addieren sich „unten“ des ersten und „oben“ des zweiten; es gibt keine weitere
* versteckte Vorgabe. Liegt eine eigene Fläche (Hintergrund) vor, liegen oben und unten innerhalb dieser Fläche.
* Werte: resources/css/tokens.css (--section-space-*, --section-gap-*).
*
* @var array<string, string>
*/
public const SPACINGS = [
'none' => 'Kein Abstand',
'compact' => 'Kompakt',
'normal' => 'Normal',
'large' => 'Großzügig',
];
/** @var array<string, string> */
public const DIVIDERS = [
'none' => 'Kein Trenner',
'line' => 'Dezente Linie',
'accent' => 'Markenakzent',
];
/** @var array<string, string> */
public const OVERLAYS = [
'light' => 'Helle Überlagerung (dunkle Schrift)',
'dark' => 'Dunkle Überlagerung (helle Schrift)',
'none' => 'Keine Überlagerung',
];
/** @var array<string, string> */
public const FOCUS = [
'center' => 'Mitte',
'top' => 'Oben',
'bottom' => 'Unten',
'left' => 'Links',
'right' => 'Rechts',
'top_left' => 'Oben links',
'top_right' => 'Oben rechts',
'bottom_left' => 'Unten links',
'bottom_right' => 'Unten rechts',
];
/** Fokuspunkt als Objektposition des Bildes; bestimmt den Zuschnitt auf schmalen Bildschirmen. */
public const FOCUS_POSITIONS = [
'center' => '50% 50%',
'top' => '50% 0%',
'bottom' => '50% 100%',
'left' => '0% 50%',
'right' => '100% 50%',
'top_left' => '0% 0%',
'top_right' => '100% 0%',
'bottom_left' => '0% 100%',
'bottom_right' => '100% 100%',
];
public const DEFAULTS = [
'background' => 'default',
'image' => null,
'focus' => 'center',
'overlay' => 'light',
'width' => 'standard',
'spacing_top' => 'compact',
'spacing_bottom' => 'compact',
'gap' => 'normal',
'divider' => 'none',
];
/**
* Aufzählungsfelder und ihre zulässigen Werte.
*
* @return array<string, array<string, string>>
*/
public static function enums(): array
{
return [
'background' => self::BACKGROUNDS,
'focus' => self::FOCUS,
'overlay' => self::OVERLAYS,
'width' => self::WIDTHS,
'spacing_top' => self::SPACINGS,
'spacing_bottom' => self::SPACINGS,
'gap' => self::SPACINGS,
'divider' => self::DIVIDERS,
];
}
/**
* Lesepfad: gespeicherte Werte; Unbekanntes fällt auf die Vorgabe zurück, damit alte oder fremde Daten
* nie eine Seite brechen.
*
* @return array{background: string, image: ?string, focus: string, overlay: string, width: string, spacing_top: string, spacing_bottom: string, gap: string, divider: string}
*/
public static function fromStored(mixed $style): array
{
$style = is_array($style) ? $style : [];
$result = self::DEFAULTS;
foreach (self::enums() as $key => $options) {
$value = $style[$key] ?? null;
if (is_string($value) && array_key_exists($value, $options)) {
$result[$key] = $value;
}
}
$result['image'] = $result['background'] === 'image' ? WebsiteImage::normalize($style['image'] ?? null) : null;
return $result;
}
/**
* Kurzbeschreibung für die Abschnittsliste im Editor.
*
* @param array<string, mixed> $style
*/
public static function summary(array $style): string
{
$style = self::fromStored($style);
$parts = [self::BACKGROUNDS[$style['background']]];
if ($style['width'] !== 'standard') {
$parts[] = self::WIDTHS[$style['width']];
}
if ($style['spacing_top'] !== self::DEFAULTS['spacing_top'] || $style['spacing_bottom'] !== self::DEFAULTS['spacing_bottom']) {
$parts[] = 'Abstand oben '.mb_strtolower(self::SPACINGS[$style['spacing_top']])
.', unten '.mb_strtolower(self::SPACINGS[$style['spacing_bottom']]);
}
if ($style['gap'] !== 'normal') {
$parts[] = 'Widget-Abstand '.mb_strtolower(self::SPACINGS[$style['gap']]);
}
if ($style['divider'] !== 'none') {
$parts[] = 'Trenner: '.self::DIVIDERS[$style['divider']];
}
return implode(' · ', $parts);
}
/**
* Ob eine gespeicherte Gestaltung noch die Abstände der Hülle Version 1 trägt
* („Abstand oben und unten“ spacing, Abweichung „Abstand oben“ same/small/none).
*
* @param array<string, mixed> $style
*/
public static function hasLegacySpacing(array $style): bool
{
return array_key_exists('spacing', $style)
|| in_array($style['spacing_top'] ?? null, ['same', 'small'], true);
}
/**
* Übersetzt die Abstände der Hülle Version 1 in die drei Werte der Version 2, ohne die Darstellung zu ändern.
*
* Version 1 rechnete so: jeder Abschnitt oben und unten „spacing“ (Vorgabe normal); die Abweichung
* „Abstand oben“ ersetzte nur oben (small/none); und eine versteckte Regel setzte oben auf null, wenn ein Abschnitt
* ohne eigene Fläche direkt auf einen Abschnitt ohne eigene Fläche folgte (ohne Linien- oder Akzenttrenner dazwischen).
* Diese Regel wird hier als „oben: kein Abstand“ ausgeschrieben. „Gering“ hat keine eigene Stufe mehr und wird
* „Kompakt“ (dokumentierte Abweichung). Der Widget-Abstand entspricht dem bisherigen festen Rasterabstand („normal“).
*
* @param list<array<string, mixed>> $sections Abschnitte in Lesereihenfolge (mit style und slots)
* @param bool $byVersion true: jede Hülle mit v < 2 gilt als Version 1 (Lesepfad gespeicherter Revisionen);
* false: nur Gestaltungen mit alten Schlüsseln (Eingaben ohne Versionsangabe)
* @return list<array<string, mixed>> dieselben Abschnitte mit übersetzter Gestaltung
*/
public static function migrateSpacing(array $sections, bool $byVersion = false): array
{
$previous = null;
foreach ($sections as $index => $section) {
$style = is_array($section['style'] ?? null) ? $section['style'] : [];
$rendered = is_array($section['slots'] ?? null) && array_filter($section['slots'], 'is_array') !== [];
$background = is_string($style['background'] ?? null) && isset(self::BACKGROUNDS[$style['background']]) ? $style['background'] : 'default';
if ($background === 'image' && WebsiteImage::normalize($style['image'] ?? null) === null) {
$background = 'default';
}
$divider = in_array($style['divider'] ?? null, ['line', 'accent'], true) ? $style['divider'] : 'none';
$legacy = $byVersion ? (int) ($section['v'] ?? 1) < 2 : self::hasLegacySpacing($style);
if ($legacy) {
$level = in_array($style['spacing'] ?? null, ['compact', 'normal', 'large'], true) ? $style['spacing'] : 'normal';
$override = $style['spacing_top'] ?? 'same';
$collapsed = $background === 'default' && $previous !== null && $previous['background'] === 'default' && ! in_array($previous['divider'], ['line', 'accent'], true);
$style['spacing_top'] = match (true) {
$override === 'none' => 'none',
$override === 'small' => 'compact',
$collapsed => 'none',
default => $level,
};
$style['spacing_bottom'] = $level;
$style['gap'] = 'normal';
// Trenner „Zusätzlicher Abstand“ (Version 1) fügte unten noch einmal den Abschnittsabstand an.
if (($style['divider'] ?? null) === 'space') {
$style['spacing_bottom'] = ['compact' => 'normal', 'normal' => 'large', 'large' => 'large'][$level];
$style['divider'] = 'none';
}
unset($style['spacing']);
$sections[$index]['style'] = $style;
}
if ($rendered) {
$previous = ['background' => $background, 'divider' => $divider];
}
}
return $sections;
}
}
+104
View File
@@ -0,0 +1,104 @@
<?php
namespace App\Domain\Cms;
use Illuminate\Support\Collection;
/**
* Baut Kopf- und Fußnavigation aus dem CMS-Navigationsmodell. Keine fest codierten Menüpunkte.
*
* Die Ausgabe hängt nur von der Navigation und dem angefragten Pfad ab, nie vom Anmeldestatus,
* damit öffentliche Seiten für alle Besucher gleich ausgeliefert werden können (ADR-32).
*/
final class SiteNavigation
{
/**
* @param Collection<int, NavigationItem> $items sichtbare Einträge, sortiert
*/
public function __construct(private readonly Collection $items, private readonly string $currentPath) {}
/**
* @param Collection<int, NavigationItem> $items
*/
public static function forPath(Collection $items, string $path): self
{
return new self($items, '/'.trim($path, '/'));
}
/**
* Hauptnavigation mit einer Ebene Untermenü. Untereinträge eines ausgeblendeten Eintrags sind ebenfalls verborgen.
*
* @return list<array{id: int, label: string, href: ?string, current: bool, activeTrail: bool, children: list<array{id: int, label: string, href: string, current: bool}>}>
*/
public function header(): array
{
$topLevel = $this->items->where('placement', 'header')->whereNull('parent_id');
$entries = [];
foreach ($topLevel as $item) {
$children = [];
foreach ($this->items->where('parent_id', $item->id) as $child) {
$href = $child->href();
if ($href !== null) {
$children[] = [
'id' => $child->id,
'label' => $child->label,
'href' => $href,
'current' => $this->isCurrent($child),
];
}
}
$href = $item->href();
if ($href === null && $children === []) {
continue;
}
$current = $href !== null && $this->isCurrent($item);
$entries[] = [
'id' => $item->id,
'label' => $item->label,
'href' => $href,
'current' => $current,
'activeTrail' => $current || in_array(true, array_column($children, 'current'), true),
'children' => $children,
];
}
return $entries;
}
/**
* Spalten des Fußbereichs in fester Reihenfolge; Gruppen ohne Einträge entfallen.
*
* @return list<array{key: string, heading: string, links: list<array{label: string, href: string, current: bool}>}>
*/
public function footerGroups(): array
{
$groups = [];
foreach (NavigationItem::FOOTER_GROUPS as $placement => $heading) {
$links = [];
foreach ($this->items->where('placement', $placement) as $item) {
$href = $item->href();
if ($href !== null) {
$links[] = ['label' => $item->label, 'href' => $href, 'current' => $this->isCurrent($item)];
}
}
if ($links !== []) {
$groups[] = ['key' => $placement, 'heading' => $heading, 'links' => $links];
}
}
return $groups;
}
private function isCurrent(NavigationItem $item): bool
{
return $item->targetPath() === $this->currentPath;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\WebsiteMediaAlias;
/**
* Wo ein Medium auf Website-Seiten als Bild verwendet wird (veröffentlichte Fassung und neuester Entwurf).
* Für den Medienmanager: Vor dem Zurücknehmen einer Website-Freigabe ist sichtbar, welche Seiten das Bild verlieren.
*/
class WebsiteImageUsage
{
/**
* @return list<array{path: string, published: bool, draft: bool}>
*/
public function pages(ContentElement $element): array
{
$legacy = WebsiteMediaAlias::query()->where('content_element_id', $element->id)->pluck('legacy_path')->all();
$usages = [];
foreach (Page::query()->with(['publishedRevision', 'latestRevision'])->orderBy('path')->get() as $page) {
$published = $page->publishedRevision !== null && $this->uses($page->publishedRevision->sections ?? [], $element->id, $legacy);
$draft = $page->latestRevision !== null && $page->latestRevision->id !== $page->published_revision_id
&& $this->uses($page->latestRevision->sections ?? [], $element->id, $legacy);
if ($published || $draft) {
$usages[] = ['path' => (string) $page->path, 'published' => $published, 'draft' => $draft];
}
}
return $usages;
}
/**
* @param list<string> $legacy
*/
private function uses(mixed $value, int $id, array $legacy): bool
{
if (! is_array($value)) {
return false;
}
foreach ($value as $key => $item) {
if ($key === 'image' && (($item === $id || (is_string($item) && ($item === (string) $id || in_array($item, $legacy, true)))))) {
return true;
}
if (is_array($item) && $this->uses($item, $id, $legacy)) {
return true;
}
}
return false;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Domain\Cms\Widgets;
/**
* Darstellungsrahmen. In der Vorschau zeigen Widgets zusätzlich redaktionelle Hinweise,
* zum Beispiel auf Verweise, die öffentlich nicht erscheinen.
*/
final readonly class RenderContext
{
public function __construct(public bool $preview = false) {}
public static function publicPage(): self
{
return new self(preview: false);
}
public static function preview(): self
{
return new self(preview: true);
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use App\Domain\Cms\Widgets\WidgetErrors;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\ViewField;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\HtmlString;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
/**
* Gemeinsame Bildauswahl aller Widgets und des Abschnittshintergrunds: Bilder aus dem zentralen Medienmanager
* (siehe WebsiteImage, docs/architektur/medienzugriff-fuer-komponenten.md). Keine eigene CMS-Medienverwaltung.
*
* - Auswahl: durchsuchbare Liste mit Vorschaubild, Titel und Website-Status.
* - Neu hochladen: Das Bild wird sofort als Medium im Medienmanager angelegt (WebsiteIntake) und ausgewählt.
* - Anzeige des gewählten Mediums mit Status und Verweis auf die Freigabe im Medienmanager.
*
* Das Bedienmuster folgt der Bildauswahl im Modul- und Programmeditor (Suche, Vorschaubild, Auswählen); jene ist an
* die Livewire-Seite des Editors gebunden und lässt sich nicht als Formularfeld im Widget-Dialog einhängen.
*/
final class ImageRefFields
{
/**
* @param bool $live Änderungen sofort an die Vorschau im Bearbeitungsdialog geben.
* @param string|null $altField Name des Alternativtext-Felds im selben Formular (für neue Medien), falls vorhanden.
* @return list<Field|Placeholder>
*/
public static function fields(string $label = 'Bild', bool $live = false, string $key = 'image', ?string $altField = null): array
{
return [
// Auswahl über den gemeinsamen visuellen Picker (Suche, Vorschau, Website-Freigabe im Detail).
ViewField::make($key)
->live()
->label($label.' aus dem Medienmanager')
->view('filament.cms.bild-feld')
->helperText('Öffentlich erscheint ein Bild nur mit Website-Freigabe; die Auswahl gibt es nicht frei.'),
FileUpload::make('_upload')
->live()
->label($label.': neues Bild hochladen')
->image()
->maxSize(8192)
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->storeFiles(false)
->afterStateUpdated(function (mixed $state, Set $set, Get $get) use ($key, $altField): void {
$file = is_array($state) ? (array_values($state)[0] ?? null) : $state;
if (! $file instanceof TemporaryUploadedFile) {
return;
}
$element = app(WebsiteImage::class)->accept($file, $altField !== null ? $get($altField) : null);
$set('_upload', null);
if ($element === null) {
Notification::make()->danger()->title('Das Bild konnte nicht übernommen werden.')->send();
return;
}
$set($key, $element->id);
Notification::make()
->success()
->title('Im Medienmanager angelegt: „'.($element->display_title ?: $element->working_title).'“')
->body('Das Bild ist ausgewählt. Nach der Verarbeitung wird es automatisch für die Website freigegeben.')
->send();
})
->helperText('Das Bild wird im Medienmanager angelegt und hier ausgewählt. Nur Bilder mit geklärten Rechten hochladen.'),
Placeholder::make('_media_status')
->label('Gewähltes Bild')
->visible(fn (Get $get): bool => WebsiteImage::normalize($get($key)) !== null)
->content(fn (Get $get): HtmlString => self::statusHtml($get($key))),
];
}
/**
* @return array<string, mixed>
*/
public static function rules(): array
{
return [
'image' => ['nullable'],
'_upload' => ['nullable'],
];
}
/**
* Prüft das gewählte Bild. Ein früherer CMS-Pfad mit wirksamer Zuordnung wird zur Kennung des Mediums.
* Ein noch als Datei übergebener Upload (frühere Formulare) wird über den Medienmanager aufgenommen.
*
* @param array<string, mixed> $refs
* @return array<string, mixed>
*/
public static function clean(array $refs, WidgetErrors $errors, string $key = 'image', ?string $errorKey = null): array
{
$images = app(WebsiteImage::class);
$upload = $refs['_upload'] ?? null;
$upload = is_array($upload) ? (array_values($upload)[0] ?? null) : $upload;
if ($upload instanceof TemporaryUploadedFile) {
$element = $images->accept($upload);
$refs[$key] = $element?->id ?? $refs[$key] ?? null;
}
$refs[$key] = $images->clean($refs[$key] ?? null, $errors, $errorKey ?? "refs.$key");
unset($refs['_upload']);
return $refs;
}
public static function statusHtml(mixed $value): HtmlString
{
$status = app(WebsiteImage::class)->status($value);
if ($status === null) {
return new HtmlString('');
}
$thumb = $status['thumb'] !== null ? '<img src="'.e($status['thumb']).'" alt="">' : '';
$link = $status['manageUrl'] !== null
? '<a href="'.e($status['manageUrl']).'" target="_blank" rel="noopener">Im Medienmanager öffnen</a>'
: '';
return new HtmlString('<div class="luf-media-status luf-media-status-'.e($status['state']).'">'.$thumb
.'<div><strong>'.e($status['title']).'</strong><p>'.e($status['note']).'</p>'.$link.'</div></div>');
}
}
@@ -0,0 +1,196 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use App\Domain\Cms\Sections\SectionStyle;
use App\Domain\Cms\Widgets\WidgetErrors;
use Filament\Forms\Components\Slider;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Grid;
/**
* Gemeinsame Bausteine der Premium-Widgets (Einstieg, Bild und Text; Brand-UI-Kit v1.6): Label, Überschriftenebene,
* Bildfokus in Prozent und zwei Schaltflächen. Alle Werte bleiben in data bzw. settings der bestehenden Hülle.
*
* Abweichungen vom Kit (bewusst, dokumentiert in cms-widget-registry.md):
* - Bildfokus als data.focus_x / data.focus_y (ganze Zahlen 0–100), weil settings nur Aufzählungswerte trägt.
* - Überschriftenebene „Automatisch“ statt freier H1: Die Seite hat genau eine H1 (erstes Widget der Seite).
* - Linkziele über SafeUrl des Repositorys (Seitenpfad, #Anker, http und https), nicht nur https.
*/
final class PremiumFields
{
public const HEADING_LEVELS = [
'auto' => 'Automatisch (Seiteneinstieg H1, sonst H2)',
'h2' => 'H2',
'h3' => 'H3',
];
/**
* @return array<string, mixed>
*/
public static function rules(): array
{
return [
'eyebrow' => ['nullable', 'string', 'max:80'],
'cta_label' => ['nullable', 'string', 'max:80', 'required_with:data.cta_url'],
'cta_url' => ['nullable', 'string', 'max:500', 'required_with:data.cta_label'],
'cta2_label' => ['nullable', 'string', 'max:80', 'required_with:data.cta2_url'],
'cta2_url' => ['nullable', 'string', 'max:500', 'required_with:data.cta2_label'],
'alt' => ['nullable', 'string', 'max:300'],
'focus_x' => ['nullable', 'numeric', 'between:0,100'],
'focus_y' => ['nullable', 'numeric', 'between:0,100'],
];
}
public static function eyebrowField(): TextInput
{
return TextInput::make('eyebrow')
->label('Label über der Überschrift (optional)')
->maxLength(80)
->live(onBlur: true)
->helperText('Kurzer Hinweis, zum Beispiel ein Themenbereich. Kein Pflichtfeld.');
}
public static function ctaFields(): Grid
{
$url = fn (string $name, string $label, string $pair) => TextInput::make($name)
->label($label)
->maxLength(500)
->rule(SafeUrl::rule())
->requiredWith($pair)
->live(onBlur: true)
->placeholder('/programme');
return Grid::make(['default' => 1, 'md' => 2])->schema([
TextInput::make('cta_label')->label('Hauptschaltfläche: Beschriftung')->maxLength(80)->live(onBlur: true),
$url('cta_url', 'Hauptschaltfläche: Linkziel', 'cta_label'),
TextInput::make('cta2_label')->label('Zweite Schaltfläche: Beschriftung')->maxLength(80)->live(onBlur: true),
$url('cta2_url', 'Zweite Schaltfläche: Linkziel', 'cta2_label'),
]);
}
/**
* @return list<Slider>
*/
public static function focusFields(int $defaultX = 50, int $defaultY = 50): array
{
// Ohne gespeicherten Wert zeigt der Regler die Vorgabe der Widget-Art, die auch die Darstellung verwendet.
$slider = fn (string $name, string $label, int $default) => Slider::make($name)
->label($label)
->range(0, 100)
->step(1)
->required(false)
->tooltips()
->default($default)
->afterStateHydrated(function (Slider $component, mixed $state) use ($default): void {
if (! is_numeric($state)) {
$component->state($default);
}
})
->live();
return [
$slider('focus_x', 'Bildausschnitt waagerecht (0 = links, 100 = rechts)', $defaultX),
$slider('focus_y', 'Bildausschnitt senkrecht (0 = oben, 100 = unten)', $defaultY),
];
}
public static function altField(): TextInput
{
return TextInput::make('alt')
->label('Alternativtext (optional)')
->maxLength(300)
->live(onBlur: true)
->helperText('Leer lassen, dann gilt der Alternativtext des Mediums aus dem Medienmanager. Nur ausfüllen, wenn das Bild hier etwas anderes aussagen soll.');
}
/**
* Bereinigt Label, Schaltflächen, Alternativtext und Fokus; meldet unsichere Linkziele.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
public static function clean(array $data, WidgetErrors $errors, bool $hasImage): array
{
foreach (['eyebrow', 'cta_label', 'cta_url', 'cta2_label', 'cta2_url', 'alt'] as $key) {
$data[$key] = filled($data[$key] ?? null) ? trim((string) $data[$key]) : null;
}
foreach (['cta_url', 'cta2_url'] as $key) {
if ($data[$key] !== null && ! SafeUrl::isSafe($data[$key])) {
$errors->add("data.$key", SafeUrl::message());
}
}
foreach (['focus_x', 'focus_y'] as $key) {
$value = $data[$key] ?? null;
$data[$key] = is_numeric($value) ? (int) round(max(0, min(100, (float) $value))) : null;
}
return $data;
}
/**
* Schaltflächen mit sicherem Linkziel in Anzeigereihenfolge.
*
* @param array<string, mixed> $data
* @return list<array{label: string, url: string}>
*/
public static function actions(array $data): array
{
$actions = [];
foreach ([['cta_label', 'cta_url'], ['cta2_label', 'cta2_url']] as [$label, $url]) {
if (filled($data[$label] ?? null) && SafeUrl::isSafe($data[$url] ?? null)) {
$actions[] = ['label' => (string) $data[$label], 'url' => (string) $data[$url]];
}
}
return $actions;
}
/**
* Bildfokus in Prozent; ohne Angabe die Vorgabe der Widget-Art.
*
* @param array<string, mixed> $data
* @return array{x: int, y: int}
*/
public static function focus(array $data, int $defaultX = 50, int $defaultY = 50): array
{
$clamp = fn (mixed $value, int $default): int => is_numeric($value) ? (int) round(max(0, min(100, (float) $value))) : $default;
return ['x' => $clamp($data['focus_x'] ?? null, $defaultX), 'y' => $clamp($data['focus_y'] ?? null, $defaultY)];
}
/**
* Übersetzt den früheren Fokuspunkt (Aufzählung wie beim Abschnittshintergrund) in Prozentwerte.
*
* @return array{focus_x: int|null, focus_y: int|null}
*/
public static function focusFromEnum(mixed $focus): array
{
if (! is_string($focus) || ! isset(SectionStyle::FOCUS_POSITIONS[$focus])) {
return ['focus_x' => null, 'focus_y' => null];
}
[$x, $y] = array_map(fn (string $part): int => (int) rtrim($part, '%'), explode(' ', SectionStyle::FOCUS_POSITIONS[$focus]));
return ['focus_x' => $x, 'focus_y' => $y];
}
/**
* Überschriftenebene: „auto“ ergibt H1 für das erste Widget der Seite, sonst H2. Eine weitere H1 gibt es nicht.
*
* @param array<string, mixed> $settings
*/
public static function headingTag(array $settings, bool $first): string
{
$level = $settings['heading_level'] ?? 'auto';
return match (true) {
$first => 'h1',
$level === 'h3' => 'h3',
default => 'h2',
};
}
}
@@ -0,0 +1,37 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
/**
* Frühere öffentliche CMS-Bilder („cms/“, Route media.public). Neue Bilder kommen aus dem Medienmanager (WebsiteImage);
* dieser Bereich bleibt nur für gespeicherte Revisionen mit früheren Pfaden, die (noch) keinem Medium zugeordnet sind.
*/
final class PublicMedia
{
public const PREFIX = 'cms/';
public static function isPublicPath(mixed $path): bool
{
return is_string($path)
&& str_starts_with($path, self::PREFIX)
&& ! str_contains($path, '..')
&& preg_match('#^cms/[A-Za-z0-9._\-/]+$#', $path) === 1;
}
public static function url(string $path): string
{
return route('media.public', ['path' => $path]);
}
/**
* Pfad aus dem Zustand eines Upload-Felds (Zeichenkette oder Liste).
*/
public static function fromUploadState(mixed $state): ?string
{
if (is_array($state)) {
$state = array_values($state)[0] ?? null;
}
return is_string($state) && $state !== '' ? $state : null;
}
}
@@ -0,0 +1,79 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
/**
* Formatierter Text in Widgets: feste Auswahl an Auszeichnungen, kein freies HTML, keine Skripte.
* Bereinigt wird beim Speichern und erneut bei der Darstellung.
*/
final class RichText
{
/** Werkzeugleiste des Editors; muss zur Erlaubnisliste unten passen. */
public const TOOLBAR = [['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']];
private static ?HtmlSanitizer $sanitizer = null;
public static function sanitize(?string $html): string
{
if ($html === null || trim($html) === '') {
return '';
}
return trim(self::sanitizer()->sanitize($html));
}
/**
* Übernimmt Klartext aus dem Altbestand: Absätze an Leerzeilen, Zeichen maskiert.
*/
public static function fromPlainText(?string $text): string
{
$text = trim((string) $text);
if ($text === '') {
return '';
}
$paragraphs = preg_split("/\n\s*\n/", $text) ?: [];
return implode('', array_map(
fn (string $paragraph): string => '<p>'.e(trim($paragraph)).'</p>',
$paragraphs,
));
}
public static function isBlank(?string $html): bool
{
return trim(html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === '';
}
public static function excerpt(?string $html, int $length = 80): string
{
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')) ?? '');
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
}
private static function sanitizer(): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p')
->allowElement('br')
->allowElement('strong')
->allowElement('b')
->allowElement('em')
->allowElement('i')
->allowElement('ul')
->allowElement('ol')
->allowElement('li')
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks()
->forceAttribute('a', 'rel', 'noopener')
->withMaxInputLength(40000),
);
}
}
@@ -0,0 +1,44 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
/**
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...") oder http(s)-Adressen.
*/
final class SafeUrl implements ValidationRule
{
public static function isSafe(mixed $url): bool
{
if (! is_string($url) || $url === '' || preg_match('/[\s\x00-\x1F\x7F]/', $url) === 1) {
return false;
}
$isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//') && ! str_starts_with($url, '/\\');
$isAbsolute = preg_match('#^https?://[^/\s]+#i', $url) === 1;
return $isRelative || $isAbsolute;
}
public static function message(): string
{
return 'Erlaubt sind Seitenpfade (beginnend mit /) oder http(s)-Adressen.';
}
/**
* Prüfregel für Formularfelder.
*/
public static function rule(): self
{
return new self;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value !== null && $value !== '' && ! self::isSafe($value)) {
$fail(self::message());
}
}
}
@@ -0,0 +1,349 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Media\ThumbnailRef;
use App\Domain\Media\WebsiteIntake;
use App\Domain\Media\WebsiteMedia;
use App\Domain\Media\WebsiteMediaAlias;
use App\Domain\Media\WebsitePresentation;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Models\User;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Throwable;
/**
* Bilder in CMS-Widgets und Abschnittshintergründen aus dem zentralen Medienbestand
* (docs/architektur/medienzugriff-fuer-komponenten.md).
*
* Gespeichert wird im jeweiligen Bildschlüssel (refs.image, style.image, data.items[].image) die Kennung des
* Inhaltselements (int). Frühere Werte sind Pfade unter cms/ (string):
* - mit wirksamer Zuordnung (WebsiteMediaAlias) gelten sie als das zugeordnete Medium,
* - ohne Zuordnung gelten sie weiter als öffentliches CMS-Bild (PublicMedia), bis das Widget umgestellt ist.
*
* Öffentlich erscheint ein Medium nur über WebsiteMedia (Website-Freigabe, Route website.media). In der
* Redaktionsvorschau erscheint ein nicht freigegebenes Bild als Vorschaubild der Bibliothek (Route editorial.card)
* mit Hinweis. Eine CMS-Verwendung gibt nichts frei.
*
* Je Anfrage gebunden (scoped): Ergebnisse werden innerhalb einer Anfrage zwischengespeichert.
*/
class WebsiteImage
{
/** @var array<string, int|string|null> */
private array $resolved = [];
/** @var array<int, WebsitePresentation|false> */
private array $presentations = [];
public function __construct(private readonly WebsiteMedia $media) {}
/**
* Gespeicherter oder eingegebener Wert → Kennung (int), früherer Pfad (string) oder null.
*/
public static function normalize(mixed $value): int|string|null
{
if (is_array($value)) {
$value = array_values($value)[0] ?? null;
}
if (is_int($value) && $value > 0) {
return $value;
}
if (is_string($value) && preg_match('/^[1-9][0-9]*$/', $value) === 1) {
return (int) $value;
}
return PublicMedia::isPublicPath($value) ? $value : null;
}
/**
* Kennung des Mediums: gespeicherte Kennung oder wirksam zugeordneter früherer Pfad; sonst null.
*/
public function elementId(mixed $value): ?int
{
$value = self::normalize($value);
if (is_int($value)) {
return $value;
}
if ($value === null) {
return null;
}
if (! array_key_exists($value, $this->resolved)) {
$this->resolved[$value] = WebsiteMediaAlias::effectiveFor($value)?->content_element_id;
}
$id = $this->resolved[$value];
return is_int($id) ? $id : null;
}
public function presentation(mixed $value): ?WebsitePresentation
{
$id = $this->elementId($value);
if ($id === null) {
return null;
}
if (! array_key_exists($id, $this->presentations)) {
$this->presentations[$id] = $this->media->present($id) ?? false;
}
return $this->presentations[$id] ?: null;
}
/**
* Bildadresse für die Darstellung. Öffentlich nur freigegebene Medien (oder frühere CMS-Bilder ohne Zuordnung);
* in der Redaktionsvorschau zusätzlich das Vorschaubild eines nicht freigegebenen Mediums.
*/
public function url(mixed $value, bool $preview = false): ?string
{
$presentation = $this->presentation($value);
if ($presentation !== null) {
return $presentation->kind === 'bild' ? $presentation->url : null;
}
$id = $this->elementId($value);
if ($id !== null) {
if (! $preview) {
return null;
}
$element = ContentElement::query()->find($id);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
}
$legacy = self::normalize($value);
return is_string($legacy) ? PublicMedia::url($legacy) : null;
}
/** Alternativtext: Angabe im Widget, sonst der Alternativtext des Mediums. */
public function alt(mixed $value, mixed $override = null): string
{
if (is_string($override) && trim($override) !== '') {
return trim($override);
}
return $this->presentation($value)?->alt ?? '';
}
/** Öffentliche Quellenzeile des Mediums (nur solange es freigegeben ist). */
public function credit(mixed $value): ?string
{
return $this->presentation($value)?->credit;
}
/**
* Hinweis für die Redaktionsvorschau, wenn das gewählte Bild öffentlich nicht erscheint; sonst null.
*/
public function previewNotice(mixed $value, string $label = 'Das gewählte Bild'): ?string
{
$status = $this->status($value);
if ($status === null || $status['public']) {
return null;
}
return $label.' „'.$status['title'].'“ erscheint öffentlich nicht: '.$status['note'];
}
/**
* Zustand für Editor und Vorschau.
*
* @return array{public: bool, state: string, title: string, note: string, thumb: ?string, manageUrl: ?string}|null
*/
public function status(mixed $value): ?array
{
$value = self::normalize($value);
if ($value === null) {
return null;
}
$id = $this->elementId($value);
if ($id === null) {
return [
'public' => true,
'state' => 'legacy',
'title' => basename((string) $value),
'note' => 'Früheres CMS-Bild, noch nicht in den Medienmanager übernommen.',
'thumb' => PublicMedia::url((string) $value),
'manageUrl' => null,
];
}
$element = ContentElement::query()->with('editorialContentKind')->find($id);
if ($element === null) {
return ['public' => false, 'state' => 'missing', 'title' => 'Medium '.$id, 'note' => 'Das Medium gibt es nicht mehr.', 'thumb' => null, 'manageUrl' => null];
}
$title = (string) ($element->display_title ?: $element->working_title);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$manageUrl = ContentElementResource::getUrl('view', ['record' => $element]);
$public = $this->presentation($id) !== null;
$note = match (true) {
$public => 'Für die Website freigegeben.',
$element->archived_at !== null => 'Das Medium ist archiviert.',
filled($element->thumbnail_error) => 'Die Datei ließ sich nicht verarbeiten: '.Str::limit((string) $element->thumbnail_error, 120),
$element->thumbnail_path === null => 'Wird gerade verarbeitet. Danach wird es automatisch für die Website freigegeben.',
default => 'Nicht für die Website freigegeben. Die Freigabe steht im Medienmanager beim Medium unter „Beschreibung“ (Website-Freigabe).',
};
return [
'public' => $public,
'state' => $public ? 'released' : ($element->thumbnail_path === null && ! filled($element->thumbnail_error) ? 'pending' : 'unreleased'),
'title' => $title,
'note' => $note,
'thumb' => $thumb,
'manageUrl' => $manageUrl,
];
}
/**
* Prüft einen Wert beim Speichern. Ein früherer Pfad mit wirksamer Zuordnung wird zur Kennung des Mediums.
*/
public function clean(mixed $value, WidgetErrors $errors, string $errorKey): int|string|null
{
$raw = is_array($value) ? (array_values($value)[0] ?? null) : $value;
$value = self::normalize($raw);
if ($value === null) {
if ($raw !== null && $raw !== '') {
$errors->add($errorKey, 'Bitte ein Bild aus dem Medienmanager wählen.');
}
return null;
}
if (is_string($value)) {
return $this->elementId($value) ?? $value;
}
$element = ContentElement::query()->find($value);
if ($element === null || ! self::isSelectable($element)) {
$errors->add($errorKey, 'Dieses Medium ist kein Bild für die Website (nur Bilder aus dem Medienmanager, keine Traineranleitungen).');
return null;
}
return $element->id;
}
public static function isSelectable(ContentElement $element): bool
{
if ($element->output_class !== 'bild' || $element->archived_at !== null) {
return false;
}
$slug = $element->editorialContentKind?->slug
?? ($element->editorial_content_kind_id !== null ? EditorialContentKind::query()->whereKey($element->editorial_content_kind_id)->value('slug') : null);
return ! in_array($slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true);
}
/**
* Auswahl für den Medienpicker: Bilder aus dem Medienmanager mit Vorschaubild, Titel und Freigabestatus (HTML).
*
* @return array<int, string>
*/
public function options(?string $search = null, int $limit = 60): array
{
$search = trim((string) $search);
$elements = ContentElement::query()
->with('editorialContentKind')
->where('output_class', 'bild')
->whereNull('archived_at')
->when($search !== '', function ($query) use ($search): void {
$like = '%'.mb_strtolower($search).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(working_title) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
})
->orderByDesc('id')
->limit($limit)
->get();
$options = [];
foreach ($elements as $element) {
if (self::isSelectable($element)) {
$options[$element->id] = $this->optionHtml($element->id);
}
}
return $options;
}
/** HTML-Bezeichnung einer Option oder des gewählten Werts (auch für frühere Pfade). */
public function optionHtml(mixed $value): ?string
{
$status = $this->status($value);
if ($status === null) {
return null;
}
$badge = match ($status['state']) {
'released' => ['ok', 'Website: freigegeben'],
'pending' => ['wait', 'Wird verarbeitet'],
'legacy' => ['quiet', 'Früheres CMS-Bild'],
default => ['warn', 'Website: nicht freigegeben'],
};
$thumb = $status['thumb'] !== null
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy">'
: '<span class="luf-media-option-empty" aria-hidden="true"></span>';
return '<span class="luf-media-option">'.$thumb
.'<span class="luf-media-option-text"><strong>'.e($status['title']).'</strong>'
.'<span class="luf-media-badge luf-media-badge-'.$badge[0].'">'.e($badge[1]).'</span></span></span>';
}
/**
* Neues Bild direkt aus dem CMS: Datei in den Eingang legen und über WebsiteIntake als Medium anlegen.
* Die Warteschlange leitet das Bild ab und gibt die Ableitung für die Website frei.
*/
public function accept(TemporaryUploadedFile $file, ?string $alt = null): ?ContentElement
{
$base = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) ?: 'bild';
$name = $base.'-'.Str::lower(Str::random(6)).'.'.($file->guessExtension() ?: 'jpg');
try {
$path = $file->storeAs('cms', $name, 'cms_incoming');
} catch (Throwable $exception) {
report($exception);
return null;
}
if (! is_string($path) || $path === '') {
return null;
}
$actor = auth('staff')->user();
return app(WebsiteIntake::class)->acceptImage(
$path,
Str::title(str_replace(['-', '_'], ' ', $base)),
null,
filled($alt) ? trim((string) $alt) : null,
$actor instanceof User ? $actor : null,
);
}
}
@@ -0,0 +1,106 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
class CallToActionWidget extends WidgetType
{
public function key(): string
{
return 'call_to_action';
}
public function label(): string
{
return 'Handlungsaufruf';
}
public function description(): string
{
return 'Hervorgehobene Fläche mit Überschrift, Text und einer Schaltfläche.';
}
public function supportedUnits(): array
{
return [1, 2, 3, 4];
}
public function narrowBehavior(): string
{
return 'Unter 20 rem Slotbreite steht die Schaltfläche in voller Breite; Überschrift, Text und Beschriftung brechen um.';
}
public function heights(): array
{
return [
'auto' => 'Automatisch (nach Inhalt)',
'fill' => 'Abschnittshöhe füllen (gleich hoch wie Nachbarplätze)',
];
}
public function preferredUnits(): int
{
return 2;
}
public function stages(): array
{
return [
'fluid' => 'Text und Schaltfläche untereinander, Schaltfläche volle Breite unter 20rem',
];
}
public function icon(): string
{
return 'heroicon-o-megaphone';
}
public function schematic(): array
{
return [[2, 4, 56, 28, 'ink'], [8, 9, 30, 4, 'line'], [8, 16, 40, 3, 'line'], [8, 23, 16, 5, 'accent']];
}
public function dataRules(): array
{
return [
'heading' => ['required', 'string', 'max:200'],
'text' => ['nullable', 'string', 'max:1000'],
'label' => ['required', 'string', 'max:80'],
'url' => ['required', 'string', 'max:500'],
];
}
public function dataFields(): array
{
return [
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
Textarea::make('text')->label('Text')->rows(3)->maxLength(1000),
TextInput::make('label')->label('Beschriftung der Schaltfläche')->required()->maxLength(80),
TextInput::make('url')
->label('Linkziel')
->required()
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /angebote oder eine vollständige http(s)-Adresse.'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
if (! SafeUrl::isSafe($data['url'] ?? null)) {
$errors->add('data.url', SafeUrl::message());
}
return [$data, $refs];
}
public function summary(array $widget): string
{
return trim(($widget['data']['heading'] ?? '').' → '.($widget['data']['label'] ?? ''));
}
}
@@ -0,0 +1,187 @@
<?php
namespace App\Domain\Cms\Widgets\Types;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
/**
* Redaktionelle Karten. Die Einträge sind freie redaktionelle Verweise, keine Produkte oder Lizenzartikel.
*
* Version 1 umfasst den Bestand (Titel, Text, Adresse). Das optionale Bild je Karte ist eine
* abwärtskompatible Ergänzung derselben Version: ältere Karten haben schlicht kein Bild.
*/
class CardsWidget extends WidgetType
{
public function key(): string
{
return 'cards';
}
public function label(): string
{
return 'Redaktionelle Karten';
}
public function description(): string
{
return 'Mehrere Karten mit Titel, Text, Linkziel und optionalem Bild. Als Raster, kompakte Liste oder mit hervorgehobener erster Karte.';
}
public function supportedUnits(): array
{
return [1, 2, 3, 4];
}
public function narrowBehavior(): string
{
return 'Karten stehen untereinander, sobald keine zwei 15 rem breiten Karten nebeneinander passen; die hervorgehobene Karte stapelt Bild und Text.';
}
public function preferredUnits(): int
{
return 4;
}
public function stages(): array
{
return [
'narrow' => 'eine Karte je Zeile',
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 15rem Kartenbreite passen; hervorgehobene Karte ab 44rem mit Bild neben dem Text',
];
}
public function icon(): string
{
return 'heroicon-o-squares-2x2';
}
public function schematic(): array
{
return [[2, 6, 17, 24, 'line'], [21, 6, 17, 24, 'line'], [40, 6, 17, 24, 'line'], [2, 6, 17, 2, 'accent'], [21, 6, 17, 2, 'accent'], [40, 6, 17, 2, 'accent']];
}
public function variants(): array
{
return [
'standard' => 'Raster',
'compact' => 'Kompakte Liste',
'featured' => 'Erste Karte hervorgehoben',
];
}
public function dataRules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:12'],
'items.*.title' => ['required', 'string', 'max:120'],
'items.*.text' => ['nullable', 'string', 'max:500'],
'items.*.url' => ['nullable', 'string', 'max:500'],
'items.*.image' => ['nullable'],
'items.*._upload' => ['nullable'],
];
}
public function dataFields(): array
{
[$image, $upload, $status] = ImageRefFields::fields('Bild (optional)');
return [
Repeater::make('items')
->label('Karten')
->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(120),
Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500),
TextInput::make('url')
->label('Linkziel')
->maxLength(500)
->rule(SafeUrl::rule())
->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'),
$image,
$upload,
$status,
])
->minItems(1)
->maxItems(12)
->reorderableWithButtons()
->collapsible()
->cloneable()
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
->addActionLabel('Karte hinzufügen'),
];
}
public function clean(array $data, array $refs, WidgetErrors $errors): array
{
foreach ($data['items'] as $index => $item) {
if (filled($item['url'] ?? null) && ! SafeUrl::isSafe($item['url'])) {
$errors->add("data.items.$index.url", SafeUrl::message());
}
$itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image");
$data['items'][$index] = [
'title' => $item['title'],
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
'url' => filled($item['url'] ?? null) ? $item['url'] : null,
'image' => $itemRefs['image'],
];
}
return [$data, $refs];
}
public function resolve(array $widget, RenderContext $context): array
{
$images = app(WebsiteImage::class);
$items = [];
$notices = [];
foreach ($widget['data']['items'] ?? [] as $item) {
if (! is_array($item) || ! filled($item['title'] ?? null)) {
continue;
}
$items[] = [
'title' => $item['title'],
'text' => $item['text'] ?? null,
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
];
if ($context->preview && ($notice = $images->previewNotice($item['image'] ?? null, 'Das Bild der Karte „'.$item['title'].'“')) !== null) {
$notices[] = $notice;
}
}
return ['items' => $items, 'imageNotice' => $notices === [] ? null : implode(' ', $notices)];
}
public function mediaPaths(array $widget): array
{
$paths = [];
foreach ($widget['data']['items'] ?? [] as $item) {
if (is_array($item) && PublicMedia::isPublicPath($item['image'] ?? null)) {
$paths[] = $item['image'];
}
}
return $paths;
}
public function summary(array $widget): string
{
$titles = array_filter(array_map(fn ($item) => is_array($item) ? ($item['title'] ?? null) : null, $widget['data']['items'] ?? []));
return count($titles).' Karten: '.implode(', ', $titles);
}
}
Loaded 100 of 800 files, more files were not shown because too many files have changed in this diff. Show more