Compare commits
251
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4584dcd013 | ||
|
|
cf8189623c | ||
|
|
9140e731f9 | ||
|
|
bb08b9b3fa | ||
|
|
e5b3eea7de | ||
|
|
b901b02cce | ||
|
|
79998f6347 | ||
|
|
26ca79cd22 | ||
|
|
bcda189267 | ||
|
|
bc140a0e83 | ||
|
|
ad03eee41f | ||
|
|
881703ba0e | ||
|
|
bbee288e69 | ||
|
|
d1f97a351a | ||
|
|
ef56befc0e | ||
|
|
0022fd50cb | ||
|
|
1d1f0ebb1f | ||
|
|
da02e0bbda | ||
|
|
3f9e463dfa | ||
|
|
03737a5fc7 | ||
|
|
b453a8be10 | ||
|
|
a3c159a729 | ||
|
|
b3fb619bda | ||
|
|
78c8870e4e | ||
|
|
dd3cc83057 | ||
|
|
32272e8e40 | ||
|
|
9db3a98440 | ||
|
|
f87e67ce02 | ||
|
|
fe39e1efb6 | ||
|
|
6518d1b80f | ||
|
|
69a22deb1f | ||
|
|
f0287eec2f | ||
|
|
42e0a6bb93 | ||
|
|
76fab81386 | ||
|
|
1ce2e1e51f | ||
|
|
0154182f3b | ||
|
|
cb80835c92 | ||
|
|
e7efb073da | ||
|
|
433f9aee61 | ||
|
|
bb0949dcd9 | ||
|
|
2d54d39c24 | ||
|
|
cf50d341f5 | ||
|
|
8b644292a7 | ||
|
|
0c4ef4c4ed | ||
|
|
2e6260acca | ||
|
|
8ecc1ecdaa | ||
|
|
9f070fbab2 | ||
|
|
ca0f68e8f6 | ||
|
|
aa1e6eb6ac | ||
|
|
05d487dd0b | ||
|
|
67614158e4 | ||
|
|
e0a3fdbb70 | ||
|
|
b8c5c68887 | ||
|
|
acb88e4a1d | ||
|
|
2a54347d50 | ||
|
|
992171bb7a | ||
|
|
8b59946bb1 | ||
|
|
061181f30d | ||
|
|
f54acd55e6 | ||
|
|
2ca7a8b268 | ||
|
|
cc890d9fc7 | ||
|
|
37056761a3 | ||
|
|
1413e0640f | ||
|
|
631502c064 | ||
|
|
4bc2e5871b | ||
|
|
1bc5356e84 | ||
|
|
2094961b6e | ||
|
|
7ef58e0e6e | ||
|
|
94eda30298 | ||
|
|
bff17a9e8e | ||
|
|
73126fec0c | ||
|
|
437bb394b2 | ||
|
|
5e28538551 | ||
|
|
be932c113a | ||
|
|
ef3af0e036 | ||
|
|
936c85ef5e | ||
|
|
c61869f8aa | ||
|
|
9f7c645baf | ||
|
|
08d03d0f56 | ||
|
|
ea4244487f | ||
|
|
fc40aba26c | ||
|
|
32837639e6 | ||
|
|
3825f53a9b | ||
|
|
604e1791c5 | ||
|
|
cd66561ca9 | ||
|
|
886715af96 | ||
|
|
05bd36509c | ||
|
|
96bb661239 | ||
|
|
340b898b7b | ||
|
|
9701777011 | ||
|
|
4520dba2f0 | ||
|
|
d49b178ebd | ||
|
|
da7ebca999 | ||
|
|
f72b79fd8c | ||
|
|
4e0760db1e | ||
|
|
6c8bbee363 | ||
|
|
7ad5929588 | ||
|
|
ed1f706d46 | ||
|
|
7c48a6480c | ||
|
|
d5c2b34b9d | ||
|
|
eb6192b067 | ||
|
|
061bc00564 | ||
|
|
8a97d9c334 | ||
|
|
e20f428a57 | ||
|
|
70695db290 | ||
|
|
f774d43647 | ||
|
|
c84ae10809 | ||
|
|
f3eda56021 | ||
|
|
4f3b7c351e | ||
|
|
75596bdaec | ||
|
|
5548106c31 | ||
|
|
dd3ee39f69 | ||
|
|
a7d369bab1 | ||
|
|
d4110b1d51 | ||
|
|
0c6519be28 | ||
|
|
30dd0f9eb8 | ||
|
|
07592f57bd | ||
|
|
bc6e4ec7ad | ||
|
|
77ebb0c1d5 | ||
|
|
4e00c4254b | ||
|
|
aaad2fa19b | ||
|
|
b23b30e897 | ||
|
|
afe35fc11f | ||
|
|
514eb46217 | ||
|
|
71e71b4ef2 | ||
|
|
0a0e4edbc2 | ||
|
|
b60029431f | ||
|
|
f4376ae819 | ||
|
|
51d58ac55c | ||
|
|
3aa1bad859 | ||
|
|
660b50f418 | ||
|
|
532979aa86 | ||
|
|
f846c0b2ee | ||
|
|
335b09f40e | ||
|
|
7b712e0c45 | ||
|
|
4847303a6f | ||
|
|
608550b620 | ||
|
|
0a8ff0761a | ||
|
|
a994c875ee | ||
|
|
d33ce86ae3 | ||
|
|
d1b10ef11d | ||
|
|
60f5b8e6c0 | ||
|
|
105d27f9c9 | ||
|
|
7eb3cd6230 | ||
|
|
156cdd6976 | ||
|
|
baa7691ab5 | ||
|
|
494e9fa0fb | ||
|
|
e7b0932e54 | ||
|
|
872f156d7d | ||
|
|
2d63109553 | ||
|
|
9dc4b4e64d | ||
|
|
1b271e0ce7 | ||
|
|
e1fd59491c | ||
|
|
41658d98dd | ||
|
|
b9fe0e3791 | ||
|
|
4c29ab2593 | ||
|
|
a359a5fb69 | ||
|
|
7b325f0d66 | ||
|
|
5590225f4f | ||
|
|
f29ea58fd5 | ||
|
|
c4be6ed8dc | ||
|
|
053a8d4648 | ||
|
|
7c63424ea6 | ||
|
|
13530b8171 | ||
|
|
72130d66c5 | ||
|
|
d37a7093dd | ||
|
|
3e56314cf9 | ||
|
|
8a6678aad7 | ||
|
|
b178939852 | ||
|
|
a08067c078 | ||
|
|
bc1f84ac89 | ||
|
|
39ab25d8c6 | ||
|
|
127ea86817 | ||
|
|
cca069be48 | ||
|
|
f511ad10de | ||
|
|
f4d225d0b2 | ||
|
|
89fd95b243 | ||
|
|
87a7ffc45f | ||
|
|
0bfb53463a | ||
|
|
3cdb36e7a3 | ||
|
|
5dccbbce80 | ||
|
|
8a3f6df770 | ||
|
|
656f999d2c | ||
|
|
8387cc90df | ||
|
|
d89d4bdc70 | ||
|
|
7c1caec546 | ||
|
|
8390dcdb41 | ||
|
|
33aaf64024 | ||
|
|
3a5e5290f1 | ||
|
|
c6186fba6e | ||
|
|
dc33f0ee37 | ||
|
|
6152451e2e | ||
|
|
4cad60259a | ||
|
|
2ac2923852 | ||
|
|
480d55989b | ||
|
|
db4bd30319 | ||
|
|
2dc479a8a4 | ||
|
|
9d936bfa4a | ||
|
|
cfdd6de0c7 | ||
|
|
dee8c05eb0 | ||
|
|
dd67741f35 | ||
|
|
d12ba67b45 | ||
|
|
1168c04228 | ||
|
|
b71ee8023b | ||
|
|
89c574106f | ||
|
|
c73207f2c3 | ||
|
|
1fb48783bf | ||
|
|
8e77defaca | ||
|
|
f86032cb5f | ||
|
|
c47c3b9b32 | ||
|
|
9195cdcd15 | ||
|
|
053a361801 | ||
|
|
6955830579 | ||
|
|
7eb50c8a8d | ||
|
|
42415dff51 | ||
|
|
a7feef2cd2 | ||
|
|
30833f62a1 | ||
|
|
57802dfe48 | ||
|
|
295f784703 | ||
|
|
c997eb500c | ||
|
|
d6ff881e4e | ||
|
|
9b52181be1 | ||
|
|
8d0a0b8cc6 | ||
|
|
1d8315c9a4 | ||
|
|
abcdc6908e | ||
|
|
c99a957e6f | ||
|
|
5e763d15ec | ||
|
|
7b54c38623 | ||
|
|
fc08e6d0f2 | ||
|
|
338739a882 | ||
|
|
5ed01b9d04 | ||
|
|
1a2b1298b5 | ||
|
|
7820bececb | ||
|
|
8cd382c357 | ||
|
|
af85a94cd5 | ||
|
|
12f12117dd | ||
|
|
9866b3184a | ||
|
|
3ee9f529ca | ||
|
|
4f2e5a5f3b | ||
|
|
b374335b3a | ||
|
|
cd79fb99d7 | ||
|
|
fa706e5080 | ||
|
|
63f2be565f | ||
|
|
2113378e81 | ||
|
|
fe03b0804c | ||
|
|
fef0ea2ac2 | ||
|
|
fd6860efda | ||
|
|
463851d402 | ||
|
|
2ded4b7fad | ||
|
|
2035c46edd | ||
|
|
89b35ac480 |
No files matched your search
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,77 @@
|
||||
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=
|
||||
|
||||
# Übernahme von Übungen aus Shinkan. Die Adresse ist je Umgebung vorgegeben. Der Zugangsschlüssel kann hier stehen (hat
|
||||
# Vorrang) oder in der Verwaltung hinterlegt werden (Inhalte -> Übungen aus Shinkan). Werte nie ins Repository.
|
||||
SHINKAN_DISTRIBUTION_URL=
|
||||
SHINKAN_DISTRIBUTION_KEY=
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -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
@@ -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
|
||||
@@ -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.
|
||||
@@ -0,0 +1,69 @@
|
||||
# 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.**
|
||||
- **Ausnahme Shinkan-Zugangsschlüssel (ADR-49, Nachtrag vom 23.11.2026):** Dieser eine Schlüssel darf zusätzlich von Katalog- und Systemverwaltern in der Verwaltung hinterlegt werden (Inhalte → Übungen aus Shinkan). Er liegt je Umgebung getrennt mit dem Anwendungsschlüssel verschlüsselt in der Datenbank, wird nie angezeigt, zurückgegeben oder protokolliert. Ein Wert in `SHINKAN_DISTRIBUTION_KEY` (Serverdatei) hat Vorrang. Die Adresse (`SHINKAN_DISTRIBUTION_URL`) bleibt je Umgebung in der Serverdatei. Für alle anderen Schlüssel gilt die Regel unverändert.
|
||||
- **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“. Fachliche Säulen gibt es nur in der Säulenverwaltung (`pillars`); Zuordnung über `PillarService::assign`, nie über eine Dimension. 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
@@ -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
|
||||
@@ -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`.
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
class StaffAuthenticatorName
|
||||
{
|
||||
public static function current(): string
|
||||
{
|
||||
return app()->isProduction() ? 'Lara&Felix' : 'Lara&Felix (dev)';
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Catalog\LegacyPillarAdoption;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AdoptLegacyPillars extends Command
|
||||
{
|
||||
protected $signature = 'luf:saeulen-uebernehmen {--dry-run : Nur berichten, nichts schreiben}';
|
||||
|
||||
protected $description = 'Übernimmt die alte Dimension „Fachliche Säule“ in die zentrale Säulenverwaltung und berichtet ungeklärte Fälle';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$report = (new LegacyPillarAdoption)->run($dryRun);
|
||||
|
||||
foreach (LegacyPillarAdoption::lines($report, $dryRun) as $line) {
|
||||
$this->line($line);
|
||||
}
|
||||
|
||||
return $report['unresolved'] === [] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
<?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'],
|
||||
'requirement' => $row['requirement'] ?? null,
|
||||
'variant_key' => $row['variant'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
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 (app(ForeignCompositions::class)->reaches($root)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Er wird hier nicht veröffentlicht, damit nichts fehlt oder zu viel ausgegeben wird.');
|
||||
}
|
||||
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
enum BundleStatus: string
|
||||
{
|
||||
case Entwurf = 'entwurf';
|
||||
case Veroeffentlicht = 'veroeffentlicht';
|
||||
}
|
||||
@@ -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,38 @@
|
||||
<?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',
|
||||
'structure_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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?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 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',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::addGlobalScope(new SupportedKindScope);
|
||||
}
|
||||
|
||||
public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersion::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). Die Säulen der enthaltenen Medien sind davon
|
||||
* getrennt und werden zur Laufzeit abgeleitet (CatalogReading::memberPillars).
|
||||
*/
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
enum CompositionKind: string
|
||||
{
|
||||
case Kombination = 'kombination';
|
||||
case Uebung = 'uebung';
|
||||
case Kurs = 'kurs';
|
||||
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
|
||||
case Exercise = 'exercise';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_map(fn (self $case): string => $case->value, self::cases());
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Kurs',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
public function plural(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombinationen',
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
};
|
||||
}
|
||||
|
||||
public function createLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Kombination anlegen',
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung 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.',
|
||||
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
|
||||
};
|
||||
}
|
||||
|
||||
public function deskLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
};
|
||||
}
|
||||
|
||||
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.',
|
||||
self::Exercise => $this->explanation(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?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',
|
||||
'variant_id',
|
||||
'requirement',
|
||||
'variant_selection',
|
||||
'origin',
|
||||
];
|
||||
|
||||
public const REQUIRED = 'erforderlich';
|
||||
|
||||
public const SUPPLEMENTARY = 'ergaenzend';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['variant_selection' => 'array'];
|
||||
}
|
||||
|
||||
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 variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
|
||||
}
|
||||
|
||||
public function nestedCompositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
<?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,
|
||||
array $variants = [],
|
||||
): 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, $variants): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 && app(ForeignCompositions::class)->isForeignVersion($version->id)) {
|
||||
$blocked[] = $this->block('Bestandteil', 'Dieser Bestandteil stammt aus einer neueren Programmversion und kann hier nicht freigegeben werden.', $depth, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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,
|
||||
array $variants = [],
|
||||
): 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),
|
||||
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||
'requirement' => $member['requirement'] ?? 'erforderlich',
|
||||
'selection' => is_array($member['selection'] ?? null) && $member['selection'] !== [] ? array_values($member['selection']) : null,
|
||||
'origin' => $member['origin'] ?? 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
$version = app(ContentService::class)->publishComposition(
|
||||
$composition,
|
||||
$payload,
|
||||
$actor,
|
||||
$note,
|
||||
[
|
||||
'learning_goal' => $didactic['learning_goal'] ?? null,
|
||||
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
||||
'duration_max' => $didactic['duration_max'] ?? null,
|
||||
'material_note' => $didactic['material_note'] ?? null,
|
||||
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||
],
|
||||
$variants,
|
||||
);
|
||||
$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,
|
||||
'duration_max' => $draft['duration_max'] ?? null,
|
||||
'material_note' => $draft['material_note'] ?? null,
|
||||
'prerequisites' => $draft['prerequisites'] ?? null,
|
||||
],
|
||||
$actor,
|
||||
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
||||
$stack,
|
||||
is_array($draft['variants'] ?? null) ? $draft['variants'] : [],
|
||||
);
|
||||
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,87 @@
|
||||
<?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;
|
||||
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz).
|
||||
if ($composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?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',
|
||||
'duration_max',
|
||||
'prerequisites',
|
||||
'structure_hash',
|
||||
'source_snapshot_id',
|
||||
];
|
||||
|
||||
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 variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersionVariant::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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Durchführungsvariante einer Übungsfassung. Der Schlüssel ist je Fassung eindeutig und bleibt über Fassungen hinweg
|
||||
* gleich, damit eine Auswahl im Modul oder Programm und der Abgleich mit einer Quelle dieselbe Variante meinen.
|
||||
* Wie die Mitglieder ist sie nur im Entwurf der Fassung schreibbar.
|
||||
*/
|
||||
class CompositionVersionVariant extends Model
|
||||
{
|
||||
protected $fillable = ['composition_version_id', 'key', 'position', 'name', 'description', 'origin'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionVersionVariant $variant): void {
|
||||
$status = CompositionVersion::query()->whereKey($variant->composition_version_id)->value('status');
|
||||
|
||||
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
|
||||
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.');
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function (): void {
|
||||
throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
|
||||
});
|
||||
}
|
||||
|
||||
public function compositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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',
|
||||
'source_ref',
|
||||
];
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
class ContentResolver
|
||||
{
|
||||
/**
|
||||
* Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und
|
||||
* den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl
|
||||
* (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten).
|
||||
*
|
||||
* @param list<string>|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array
|
||||
{
|
||||
if ($node instanceof ContentElementVersion) {
|
||||
$node->loadMissing('element');
|
||||
|
||||
return [[
|
||||
'version_id' => $node->id,
|
||||
'role' => $path,
|
||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
||||
'requirement' => CompositionMember::REQUIRED,
|
||||
'variant' => null,
|
||||
]];
|
||||
}
|
||||
|
||||
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()->with('variant')->orderBy('position')->get() as $member) {
|
||||
$variantKey = $member->variant?->key;
|
||||
|
||||
if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$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,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$nested = $member->nestedCompositionVersion;
|
||||
|
||||
if ($nested === null) {
|
||||
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
|
||||
}
|
||||
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht auflösen (Rückfallschutz).
|
||||
// Veröffentlichen verweigern die aufrufenden Stellen über ForeignCompositions.
|
||||
$nested->loadMissing('composition');
|
||||
|
||||
if ($nested->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand(
|
||||
$nested,
|
||||
$segment,
|
||||
$stack,
|
||||
is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null,
|
||||
));
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
<?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, note?: string|null, variant?: string|null, requirement?: string|null, selection?: list<string>|null}> $members
|
||||
* @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic
|
||||
* @param list<array{key: string, name: string, description?: string|null, origin?: string}> $variants Durchführungsvarianten einer Übung
|
||||
*/
|
||||
public function publishComposition(
|
||||
Composition $composition,
|
||||
array $members,
|
||||
?User $confirmedBy = null,
|
||||
?string $note = null,
|
||||
array $didactic = [],
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if ($members === []) {
|
||||
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
||||
}
|
||||
|
||||
$variants = $this->checkedVariants($variants);
|
||||
$this->assertAcyclic($composition->id, $members);
|
||||
|
||||
foreach ($members as $member) {
|
||||
$this->assertReadyMember($member['target']);
|
||||
$this->assertMemberPlacement($member, $variants);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): 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,
|
||||
'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null,
|
||||
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
|
||||
'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null),
|
||||
'source_snapshot_id' => isset($didactic['source_snapshot_id']) ? (int) $didactic['source_snapshot_id'] : null,
|
||||
]);
|
||||
|
||||
$variantIds = [];
|
||||
|
||||
foreach ($variants as $index => $variant) {
|
||||
$variantIds[$variant['key']] = $version->variants()->create([
|
||||
'key' => $variant['key'],
|
||||
'position' => $index + 1,
|
||||
'name' => $variant['name'],
|
||||
'description' => $variant['description'],
|
||||
'origin' => $variant['origin'],
|
||||
])->id;
|
||||
}
|
||||
|
||||
foreach (array_values($members) as $index => $member) {
|
||||
$target = $member['target'];
|
||||
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
|
||||
$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,
|
||||
'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'variant_selection' => $selection === null ? null : array_values($selection),
|
||||
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
]);
|
||||
}
|
||||
|
||||
$version->load('members.variant', 'variants');
|
||||
$resolvedHash = $this->resolver->resolvedHash($version);
|
||||
$structureHash = $this->structureHash($version);
|
||||
$version->attestations()->create([
|
||||
'resolved_hash' => $resolvedHash,
|
||||
'structure_hash' => $structureHash,
|
||||
'confirmed_by' => $confirmedBy?->id,
|
||||
'confirmed_at' => now(),
|
||||
'note' => $note,
|
||||
]);
|
||||
$version->resolved_hash = $resolvedHash;
|
||||
$version->structure_hash = $structureHash;
|
||||
$version->status = ContentVersionStatus::Bereit;
|
||||
$version->save();
|
||||
|
||||
return $version->load('members');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der
|
||||
* `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante,
|
||||
* Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben.
|
||||
*/
|
||||
public function structureHash(CompositionVersion $version): string
|
||||
{
|
||||
$version->loadMissing('members.variant', 'variants');
|
||||
|
||||
return hash('sha256', json_encode([
|
||||
'fields' => [
|
||||
$version->learning_goal,
|
||||
$version->duration_minutes,
|
||||
$version->duration_max,
|
||||
$version->material_note,
|
||||
$version->prerequisites,
|
||||
],
|
||||
'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [
|
||||
$variant->key, $variant->position, $variant->name, $variant->description, $variant->origin,
|
||||
])->all(),
|
||||
'members' => $version->members->map(fn (CompositionMember $member): array => [
|
||||
$member->position,
|
||||
$member->role,
|
||||
$member->placement_note,
|
||||
$member->content_element_version_id,
|
||||
$member->nested_composition_version_id,
|
||||
$member->variant?->key,
|
||||
$member->requirement,
|
||||
$member->variant_selection,
|
||||
$member->origin,
|
||||
])->all(),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{key?: string, name?: string, description?: string|null}> $variants
|
||||
* @return list<array{key: string, name: string, description: string|null}>
|
||||
*/
|
||||
private function checkedVariants(array $variants): array
|
||||
{
|
||||
$checked = [];
|
||||
$keys = [];
|
||||
|
||||
foreach (array_values($variants) as $variant) {
|
||||
$key = trim((string) ($variant['key'] ?? ''));
|
||||
|
||||
if ($key === '' || in_array($key, $keys, true)) {
|
||||
throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.');
|
||||
}
|
||||
|
||||
$keys[] = $key;
|
||||
$checked[] = [
|
||||
'key' => $key,
|
||||
'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'),
|
||||
'description' => $this->optionalText($variant['description'] ?? null),
|
||||
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return $checked;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list<string>|null} $member
|
||||
* @param list<array{key: string, name: string, description: string|null}> $variants
|
||||
*/
|
||||
private function assertMemberPlacement(array $member, array $variants): void
|
||||
{
|
||||
$variant = $member['variant'] ?? null;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) {
|
||||
throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.');
|
||||
}
|
||||
|
||||
$requirement = $member['requirement'] ?? CompositionMember::REQUIRED;
|
||||
|
||||
if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) {
|
||||
throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.');
|
||||
}
|
||||
|
||||
$selection = $member['selection'] ?? null;
|
||||
|
||||
if ($selection === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $member['target'] instanceof CompositionVersion) {
|
||||
throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.');
|
||||
}
|
||||
|
||||
$offered = $member['target']->variants()->pluck('key')->all();
|
||||
|
||||
if ($selection === [] || array_diff($selection, $offered) !== []) {
|
||||
throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.');
|
||||
}
|
||||
}
|
||||
|
||||
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 (app(ForeignCompositions::class)->reaches($target)) {
|
||||
throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.');
|
||||
}
|
||||
|
||||
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,
|
||||
'variant' => $member['variant'] ?? null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'selection' => $member['selection'] ?? 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,92 @@
|
||||
<?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',
|
||||
'uebung' => 'Übung',
|
||||
'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', 'uebung', '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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?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');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachliche Säulen werden für alle Objektarten über die zentrale Säulenverwaltung gewählt (`pillars`), nie über
|
||||
* eine Dimension. Die alte Dimension „Fachliche Säule“ bleibt nur als Verlauf in der Datenbank und wird nirgends
|
||||
* mehr angeboten, geändert oder gefiltert.
|
||||
*
|
||||
* @return Collection<int, self>
|
||||
*/
|
||||
public static function forSubject(Model $subject): Collection
|
||||
{
|
||||
return static::query()->with('values')->where('slug', '!=', self::PILLAR_SLUG)->orderBy('label')->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', 'pillar_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');
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?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',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
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),
|
||||
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->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 = []): 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 ($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')->where('slug', '!=', EditorialDimension::PILLAR_SLUG)->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Die Anleitung einer Übung, wie ein Stand sie festschreibt: die im Stand gebundene Übungsfassung, die angebotenen
|
||||
* Varianten und je Abschnitt oder Medium die Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und
|
||||
* PDF lesen dieses Ergebnis und zeigen damit dieselbe Fassung.
|
||||
*
|
||||
* Eine Sperre oder fehlende Berechtigung betrifft nur den betroffenen Abschnitt oder das Medium. Anleitung und übrige
|
||||
* Inhalte bleiben im selben Stand erreichbar. Fehlt in einer Variante ein erforderlicher Bestandteil, gilt die Variante
|
||||
* als derzeit nicht vollständig durchführbar; ein ergänzender Bestandteil entfällt mit einem Hinweis.
|
||||
*/
|
||||
class ExerciseGuide
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Darf dieses Konto den Stand überhaupt sehen? Aktive, nutzbare Berechtigung auf den Artikel und ein auslieferbarer
|
||||
* Stand. Über die einzelnen Inhalte entscheidet danach `DecideAccess`.
|
||||
*/
|
||||
public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $release): bool
|
||||
{
|
||||
if ($release->license_article_id !== $article->id
|
||||
|| ! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Grant::query()
|
||||
->where('license_article_id', $article->id)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->usableBy($user)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Übungsfassung an einer Stelle des Stands. Der Pfad nennt die Positionen der Mitglieder von der Wurzel des
|
||||
* Stands abwärts („2“ oder „1-3“). So ist auch dieselbe Übung an zwei Stellen eines Produkts unterscheidbar.
|
||||
*
|
||||
* @return array{version: CompositionVersion, selection: list<string>|null}|null
|
||||
*/
|
||||
public function locate(ArticleRelease $release, string $path): ?array
|
||||
{
|
||||
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = $release->rootCompositionVersion;
|
||||
$selection = null;
|
||||
|
||||
foreach (array_map('intval', explode('-', $path)) as $position) {
|
||||
if ($version === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$member = $version->members()->where('position', $position)->first();
|
||||
|
||||
if ($member === null || $member->nested_composition_version_id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$selection = is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null;
|
||||
$version = $member->nestedCompositionVersion;
|
||||
}
|
||||
|
||||
$version?->loadMissing('composition');
|
||||
|
||||
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['version' => $version, 'selection' => $selection];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad zur ersten Stelle, an der die Wurzel die Übungsfassung einbindet.
|
||||
*/
|
||||
public function pathTo(CompositionVersion $root, int $versionId, array $stack = []): ?string
|
||||
{
|
||||
if (in_array($root->id, $stack, true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($root->members()->orderBy('position')->get() as $member) {
|
||||
if ($member->nested_composition_version_id === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($member->nested_composition_version_id === $versionId) {
|
||||
return (string) $member->position;
|
||||
}
|
||||
|
||||
$below = $this->pathTo($member->nestedCompositionVersion, $versionId, [...$stack, $root->id]);
|
||||
|
||||
if ($below !== null) {
|
||||
return $member->position.'-'.$below;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $selection angebotene Variantenschlüssel; null = alle
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $exercise, ?array $selection, ?string $variantKey = null): array
|
||||
{
|
||||
$exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']);
|
||||
$library = app(LibraryCatalog::class);
|
||||
$offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values();
|
||||
$chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first();
|
||||
$entries = [];
|
||||
|
||||
foreach ($exercise->members as $member) {
|
||||
$version = $member->contentElementVersion;
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = $member->variant?->key;
|
||||
$class = (string) $version->element->output_class;
|
||||
$action = in_array($class, ['film', 'audio'], true) ? 'streamen' : 'ansehen';
|
||||
$decision = ($this->access)($user, $article, $release, $version, $action);
|
||||
$download = $action === 'ansehen' ? ($this->access)($user, $article, $release, $version, 'laden') : null;
|
||||
|
||||
$entries[] = [
|
||||
'variant' => $key,
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'title' => $library->text($version->element)['title'] ?: $version->element->working_title,
|
||||
'class' => $class,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'action' => $action,
|
||||
'version' => $version,
|
||||
'allowed' => $decision->allowed,
|
||||
'may_download' => $download?->allowed ?? false,
|
||||
'grant' => $decision->grant,
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
|
||||
];
|
||||
}
|
||||
|
||||
$variants = $offered->map(function (CompositionVersionVariant $variant) use ($entries): array {
|
||||
$missing = array_values(array_filter($entries, fn (array $entry): bool => ($entry['variant'] === null || $entry['variant'] === $variant->key)
|
||||
&& $entry['requirement'] === CompositionMember::REQUIRED
|
||||
&& ! $entry['allowed']));
|
||||
|
||||
return [
|
||||
'key' => $variant->key,
|
||||
'name' => $variant->name,
|
||||
'description' => $variant->description,
|
||||
'complete' => $missing === [],
|
||||
'missing' => array_map(fn (array $entry): string => $entry['title'], $missing),
|
||||
];
|
||||
})->all();
|
||||
|
||||
$shown = array_values(array_filter($entries, fn (array $entry): bool => $entry['variant'] === null || $entry['variant'] === $chosen?->key));
|
||||
|
||||
return [
|
||||
'exercise' => $exercise,
|
||||
'title' => $library->text($exercise->composition)['title'],
|
||||
'summary' => $library->text($exercise->composition)['summary'],
|
||||
'learning_goal' => $exercise->learning_goal,
|
||||
'duration_minutes' => $exercise->duration_minutes,
|
||||
'duration_max' => $exercise->duration_max,
|
||||
'prerequisites' => $exercise->prerequisites,
|
||||
'material_note' => $exercise->material_note,
|
||||
'variants' => $variants,
|
||||
'chosen' => $chosen?->key,
|
||||
'entries' => $shown,
|
||||
'entry_total' => count($entries),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExerciseImportRun extends Model
|
||||
{
|
||||
protected $fillable = ['source_system', 'status', 'cursor', 'added', 'updated', 'removed', 'error', 'started_at', 'finished_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['started_at' => 'datetime', 'finished_at' => 'datetime'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Druckbare Ausgabe einer Übung (DIN A4, mehrere Seiten) aus demselben Ergebnis wie die Ansicht ({@see ExerciseGuide}).
|
||||
* Kennzeichnung: Fußzeile mit Lizenznehmer und Lizenzkopie auf jeder Seite (K2) und die Kennung in den Metadaten (K1).
|
||||
* Das Dokument wird bei jedem Abruf neu erzeugt und nie abgelegt, damit eine spätere Sperre keine ältere Kopie
|
||||
* ausliefern kann.
|
||||
*/
|
||||
class ExercisePdf
|
||||
{
|
||||
private const LEFT = 56.0;
|
||||
|
||||
private const RIGHT = 539.0;
|
||||
|
||||
private const TOP = 790.0;
|
||||
|
||||
private const BOTTOM = 72.0;
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private float $y = self::TOP;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
private string $footer = '';
|
||||
|
||||
/**
|
||||
* Welche Abschnitte gehören ins PDF? Erforderliche Textabschnitte der Auswahl müssen für `laden` zulässig sein, sonst
|
||||
* ist das PDF nicht erlaubt (null). Ergänzende ohne Berechtigung entfallen. Videos und Dokumente erscheinen nur als
|
||||
* Hinweis.
|
||||
*
|
||||
* @param array<string, mixed> $guide Ergebnis von {@see ExerciseGuide::build}
|
||||
* @return list<array<string, mixed>>|null
|
||||
*/
|
||||
public function sections(array $guide): ?array
|
||||
{
|
||||
$included = [];
|
||||
|
||||
foreach ($guide['entries'] as $entry) {
|
||||
if ($entry['class'] === 'text') {
|
||||
if ($entry['may_download'] && $entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
} elseif ($entry['requirement'] === CompositionMember::REQUIRED) {
|
||||
return null;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return array_filter($included, fn (array $entry): bool => $entry['class'] === 'text') === [] ? null : $included;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $guide
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->newPage();
|
||||
|
||||
$this->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$facts = array_filter([
|
||||
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
|
||||
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
|
||||
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
|
||||
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
|
||||
]);
|
||||
|
||||
foreach ($facts as $fact) {
|
||||
$this->write(self::printable($fact), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->y -= 6;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$this->section($section, $guideUrl);
|
||||
}
|
||||
|
||||
$this->closePage();
|
||||
|
||||
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
|
||||
return $this->pdf->output($ascii?->transliterate((string) $guide['title']) ?: 'Uebung', 'Lizenzkopie '.$copyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
|
||||
* lateinische Buchstaben); sonst bleibt „?“.
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
|
||||
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
$out = '';
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
|
||||
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
*/
|
||||
private function section(array $section, string $guideUrl): void
|
||||
{
|
||||
$title = self::printable((string) $section['title']);
|
||||
|
||||
if ($section['class'] !== 'text') {
|
||||
$label = in_array($section['class'], ['film', 'audio'], true)
|
||||
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
|
||||
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
|
||||
$this->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write($title, 12.5, true, 5);
|
||||
|
||||
foreach ($section['blocks'] ?? [] as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
|
||||
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
|
||||
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
|
||||
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
|
||||
};
|
||||
}
|
||||
|
||||
$this->y -= 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
*/
|
||||
private function items(array $items, callable $marker): void
|
||||
{
|
||||
foreach ($items as $index => $item) {
|
||||
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
|
||||
|
||||
foreach ($lines as $line => $text) {
|
||||
$this->room(14);
|
||||
|
||||
if ($line === 0) {
|
||||
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
|
||||
}
|
||||
|
||||
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
|
||||
$this->y -= 14;
|
||||
}
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
|
||||
private function write(string $text, float $size, bool $bold, float $after): void
|
||||
{
|
||||
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text(self::LEFT, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
private function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < self::BOTTOM) {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->y = self::TOP;
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
{
|
||||
$this->pdf->line(self::LEFT, 54, self::RIGHT, 54, 0.4);
|
||||
$this->pdf->text(self::LEFT, 40, $this->footer, 8);
|
||||
$this->pdf->textRight(self::RIGHT, 40, 'Seite '.$this->page, 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Eine Übung der Quelle, gebunden an ihre stabile Kennung. `availability` hält nur fest, ob die Quelle sie noch
|
||||
* bereitstellt. Das ist kein Rechtsvorgang: Eine rechtliche Sperre ist der lokale `block`.
|
||||
*/
|
||||
class ExerciseSource extends Model
|
||||
{
|
||||
public const PROVIDED = 'bereitgestellt';
|
||||
|
||||
public const WITHDRAWN = 'nicht_mehr_bereitgestellt';
|
||||
|
||||
protected $fillable = ['source_system', 'source_id', 'composition_id', 'title', 'availability', 'last_hash', 'last_seen_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['last_seen_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
public function snapshots(): HasMany
|
||||
{
|
||||
return $this->hasMany(ExerciseSourceSnapshot::class)->orderBy('id');
|
||||
}
|
||||
|
||||
public function latestSnapshot(): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $this->snapshots()->reorder()->orderByDesc('id')->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ein abgerufener Inhaltsstand einer Quellübung (Prüfsumme der Quelle und ihre Nutzlast). Er ist unveränderlich;
|
||||
* nur die Übernahme trägt die daraus entstandene lokale Fassung ein.
|
||||
*/
|
||||
class ExerciseSourceSnapshot extends Model
|
||||
{
|
||||
protected $fillable = ['exercise_source_id', 'content_hash', 'payload', 'adopted_version_id', 'fetched_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['payload' => 'array', 'fetched_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function source(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ExerciseSource::class, 'exercise_source_id');
|
||||
}
|
||||
|
||||
public function adoptedVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'adopted_version_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Verwendungsnachweis: Wo wird eine Übungsfassung tatsächlich verwendet, und was trifft eine Sperre? Der Nachweis steigt
|
||||
* über die Verschachtelung bis zu den Wurzeln der Artikel-Stände auf und erfasst damit auch ältere, abgelöste und
|
||||
* gesperrte Stände. Er liest nur und ändert keinen Stand.
|
||||
*/
|
||||
class ExerciseUsage
|
||||
{
|
||||
/**
|
||||
* Je Fassung der Komposition: die einbindenden Fassungen (mit Rolle, Position und Variantenauswahl) und die
|
||||
* Artikel-Stände, deren Wurzel die Fassung selbst oder eine einbindende Fassung ist.
|
||||
*
|
||||
* @return list<array{version: CompositionVersion, hosts: list<array<string, mixed>>, releases: list<array<string, mixed>>}>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
$guide = app(ExerciseGuide::class);
|
||||
$result = [];
|
||||
|
||||
foreach ($composition->versions()->orderBy('number')->get() as $version) {
|
||||
$hosts = [];
|
||||
$roots = [$version->id => $version];
|
||||
$queue = [$version->id];
|
||||
$seen = [$version->id];
|
||||
|
||||
while ($queue !== []) {
|
||||
$current = array_shift($queue);
|
||||
|
||||
foreach (CompositionMember::query()->where('nested_composition_version_id', $current)->with('compositionVersion.composition')->orderBy('id')->get() as $member) {
|
||||
$host = $member->compositionVersion;
|
||||
|
||||
if ($host === null || $host->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts[] = [
|
||||
'composition' => $host->composition,
|
||||
'version' => $host,
|
||||
'role' => $member->role,
|
||||
'position' => $member->position,
|
||||
'selection' => $member->variant_selection,
|
||||
'direct' => $current === $version->id,
|
||||
];
|
||||
|
||||
if (! in_array($host->id, $seen, true)) {
|
||||
$seen[] = $host->id;
|
||||
$roots[$host->id] = $host;
|
||||
$queue[] = $host->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$releases = [];
|
||||
|
||||
foreach (ArticleRelease::query()->whereIn('root_composition_version_id', array_keys($roots))->with('article')->orderBy('license_article_id')->orderBy('number')->get() as $release) {
|
||||
$root = $roots[$release->root_composition_version_id];
|
||||
$releases[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'path' => $root->id === $version->id ? null : $guide->pathTo($root, $version->id),
|
||||
'root' => $root,
|
||||
];
|
||||
}
|
||||
|
||||
$result[] = ['version' => $version, 'hosts' => $hosts, 'releases' => $releases];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folgen einer Sperre dieser Medienfassung je Artikel-Stand. Die Festschreibung bleibt unverändert; gesperrt wird
|
||||
* nur die Ausgabe des Mediums.
|
||||
*
|
||||
* @return list<array{article: LicenseArticle, release: ArticleRelease, status: ReleaseStatus, variant: string|null, requirement: string|null, path: string, effect: string}>
|
||||
*/
|
||||
public function blockImpact(ContentElementVersion $version): array
|
||||
{
|
||||
$impact = [];
|
||||
|
||||
foreach (ReleaseContent::query()->where('content_element_version_id', $version->id)->with('release.article')->orderBy('id')->get() as $content) {
|
||||
$release = $content->release;
|
||||
$required = ($content->requirement ?? CompositionMember::REQUIRED) === CompositionMember::REQUIRED;
|
||||
$effect = match (true) {
|
||||
! $required => 'Nur dieses ergänzende Medium entfällt. Die Übung bleibt vollständig durchführbar.',
|
||||
$content->variant_key !== null => 'Die Variante „'.$content->variant_key.'“ ist nicht mehr vollständig durchführbar. Andere Varianten bleiben nutzbar.',
|
||||
default => 'Ein erforderlicher Bestandteil entfällt. Die Anleitung bleibt lesbar.',
|
||||
};
|
||||
$impact[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'variant' => $content->variant_key,
|
||||
'requirement' => $content->requirement,
|
||||
'path' => $content->path,
|
||||
'effect' => $effect,
|
||||
];
|
||||
}
|
||||
|
||||
return $impact;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Erkennt Kompositionen, deren Art dieser Programmstand nicht kennt (siehe {@see SupportedKindScope}), und Aufbauten, die
|
||||
* solche Bestandteile enthalten. Gelesen wird am Modell vorbei, weil der Bereichsfilter diese Zeilen ausblendet.
|
||||
*
|
||||
* Wozu: Eine ältere Programmversion darf eine Fassung mit unbekanntem Bestandteil weder neu veröffentlichen noch
|
||||
* überarbeiten. Sie würde den Bestandteil auslassen oder ohne seine Variantenwahl auflösen und damit Inhalt verlieren
|
||||
* oder zu viel ausgeben.
|
||||
*/
|
||||
class ForeignCompositions
|
||||
{
|
||||
public function isForeignVersion(int $compositionVersionId): bool
|
||||
{
|
||||
return DB::table('composition_versions as v')
|
||||
->join('compositions as c', 'c.id', '=', 'v.composition_id')
|
||||
->where('v.id', $compositionVersionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $target „composition:ID“ (Fassung) oder „composition-draft:ID“ (Komposition)
|
||||
*/
|
||||
public function isForeignTarget(string $target): bool
|
||||
{
|
||||
if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) {
|
||||
return $this->isForeignVersion((int) $match[1]);
|
||||
}
|
||||
|
||||
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
|
||||
return DB::table('compositions')
|
||||
->where('id', (int) $match[1])
|
||||
->whereNotIn('kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ist die Fassung selbst unbekannt oder erreicht sie, auch verschachtelt, einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function reaches(ContentElementVersion|CompositionVersion $node): bool
|
||||
{
|
||||
return $node instanceof CompositionVersion && $this->reachesVersion($node->id, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enthält irgendeine Fassung dieser Komposition einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function compositionHasForeignMembers(int $compositionId): bool
|
||||
{
|
||||
return DB::table('composition_members as m')
|
||||
->join('composition_versions as host', 'host.id', '=', 'm.composition_version_id')
|
||||
->join('composition_versions as nested', 'nested.id', '=', 'm.nested_composition_version_id')
|
||||
->join('compositions as c', 'c.id', '=', 'nested.composition_id')
|
||||
->where('host.composition_id', $compositionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $seen
|
||||
*/
|
||||
private function reachesVersion(int $versionId, array $seen): bool
|
||||
{
|
||||
if (in_array($versionId, $seen, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->isForeignVersion($versionId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$seen[] = $versionId;
|
||||
|
||||
foreach (DB::table('composition_members')
|
||||
->where('composition_version_id', $versionId)
|
||||
->whereNotNull('nested_composition_version_id')
|
||||
->pluck('nested_composition_version_id') as $nestedId) {
|
||||
if ($this->reachesVersion((int) $nestedId, $seen)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Anleitungstext als Klartext mit wenigen Konventionen: Absätze an Leerzeilen, Listen mit „- “ oder „• “ und
|
||||
* nummerierte Listen mit „1. “, Zwischenüberschriften mit „## “. Ansicht und PDF lesen dieselben Blöcke und zeigen damit
|
||||
* dieselbe Fassung. Es gibt kein freies HTML.
|
||||
*/
|
||||
final class GuideText
|
||||
{
|
||||
/**
|
||||
* @return list<array{type: 'paragraph'|'bullets'|'numbered'|'heading', text?: string, items?: list<string>}>
|
||||
*/
|
||||
public static function blocks(?string $body): array
|
||||
{
|
||||
$blocks = [];
|
||||
$paragraph = [];
|
||||
$list = null;
|
||||
|
||||
$flushParagraph = function () use (&$blocks, &$paragraph): void {
|
||||
if ($paragraph !== []) {
|
||||
$blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)];
|
||||
$paragraph = [];
|
||||
}
|
||||
};
|
||||
$flushList = function () use (&$blocks, &$list): void {
|
||||
if ($list !== null) {
|
||||
$blocks[] = ['type' => $list['type'], 'items' => $list['items']];
|
||||
$list = null;
|
||||
}
|
||||
};
|
||||
|
||||
foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) {
|
||||
$line = rtrim($line);
|
||||
|
||||
if (trim($line) === '') {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
$blocks[] = ['type' => 'heading', 'text' => trim($match[1])];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'bullets') {
|
||||
$flushList();
|
||||
$list = ['type' => 'bullets', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'numbered') {
|
||||
$flushList();
|
||||
$list = ['type' => 'numbered', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$flushList();
|
||||
$paragraph[] = trim($line);
|
||||
}
|
||||
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übernimmt die frühere Kopie „Fachliche Säule“ (Dimension `saeule`) in die zentrale Säulenverwaltung (Tabelle
|
||||
* `pillars`). Verlustfrei, wiederholbar und ohne Raten:
|
||||
*
|
||||
* - **Zuordnung Wert → Säule** nur über die gespeicherte Kennung `pfeiler-{Säulenkennung}`, die die Migration
|
||||
* vom 16.11.2026 beim Spiegeln geschrieben hat, und nur, wenn die Säule existiert und nicht jünger als der Wert ist
|
||||
* (sonst kann die Kennung nicht aus ihr entstanden sein). Eine abweichende Bezeichnung ist nach einem Umbenennen
|
||||
* erwartet und wird nur berichtet. Die Verknüpfung steht in `editorial_dimension_values.pillar_id`.
|
||||
* - **Übernommen** werden nur direkte Zuordnungen von Modulen, Programmen und Lizenzartikeln in `composition_pillar`
|
||||
* und `license_article_pillar` (insert-or-ignore, daher beliebig oft ausführbar).
|
||||
* - **Nicht übernommen, sondern gemeldet:** Werte ohne belastbare Kennung, Zuordnungen zu fehlenden Objekten,
|
||||
* abgeleitete Zuordnungen und unbekannte Objektarten. Abgeleitete Säulen eines Programms oder Moduls entstehen zur
|
||||
* Laufzeit aus den enthaltenen Medien und werden nie als direkte Zuordnung gespeichert.
|
||||
* - **Medien:** Die gespiegelten Zeilen sind eine veraltete Kopie; maßgeblich ist `content_element_pillar`. Sie werden
|
||||
* nicht zurückgemischt, nur gezählt.
|
||||
* - Alte Zeilen werden weder geändert noch gelöscht.
|
||||
*
|
||||
* Nur die Datenbankfassade, damit spätere Änderungen an Modellen die Migration nicht berühren.
|
||||
*/
|
||||
final class LegacyPillarAdoption
|
||||
{
|
||||
/** @var array<string, array{table: string, column: string, subjects: string}> */
|
||||
private const TARGETS = [
|
||||
'composition' => ['table' => 'composition_pillar', 'column' => 'composition_id', 'subjects' => 'compositions'],
|
||||
'license_article' => ['table' => 'license_article_pillar', 'column' => 'license_article_id', 'subjects' => 'license_articles'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* mapping: list<array<string, mixed>>,
|
||||
* unresolved: list<array<string, mixed>>,
|
||||
* copied: array<string, int>,
|
||||
* already: array<string, int>,
|
||||
* before: array<string, int>,
|
||||
* after: array<string, int>,
|
||||
* mirror: array<string, int>
|
||||
* }
|
||||
*/
|
||||
public function run(bool $dryRun = false): array
|
||||
{
|
||||
$report = [
|
||||
'mapping' => [],
|
||||
'unresolved' => [],
|
||||
'copied' => ['composition' => 0, 'license_article' => 0],
|
||||
'already' => ['composition' => 0, 'license_article' => 0],
|
||||
'before' => $this->counts(),
|
||||
'after' => [],
|
||||
'mirror' => ['element_rows' => 0, 'missing_in_pivot' => 0, 'only_in_pivot' => 0],
|
||||
];
|
||||
|
||||
$dimension = DB::table('editorial_dimensions')->where('slug', 'saeule')->first();
|
||||
|
||||
if ($dimension === null) {
|
||||
$report['after'] = $report['before'];
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach (DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->orderBy('id')->get() as $value) {
|
||||
$pillar = $this->pillarFor($value);
|
||||
|
||||
if (is_string($pillar)) {
|
||||
$report['unresolved'][] = ['art' => 'Wert', 'wert_id' => (int) $value->id, 'wert' => $value->label, 'kennung' => $value->slug, 'grund' => $pillar];
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => null, 'status' => 'offen'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$resolved[(int) $value->id] = (int) $pillar->id;
|
||||
$status = $value->pillar_id === null ? 'zugeordnet' : 'bereits zugeordnet';
|
||||
$hint = $value->label !== $pillar->name ? 'über Kennung zugeordnet, Bezeichnung weicht ab („'.$pillar->name.'“)' : null;
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => (int) $pillar->id, 'saeule' => $pillar->name, 'status' => $status, 'hinweis' => $hint];
|
||||
|
||||
if ($value->pillar_id === null && ! $dryRun) {
|
||||
DB::table('editorial_dimension_values')->where('id', $value->id)->update(['pillar_id' => $pillar->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$subjectTypes = $this->subjectTypes();
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('editorial_dimension_value_id', DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->select('id'))
|
||||
->orderBy('id')->get() as $row) {
|
||||
$valueId = (int) $row->editorial_dimension_value_id;
|
||||
$label = DB::table('editorial_dimension_values')->where('id', $valueId)->value('label');
|
||||
$target = $subjectTypes[$row->subject_type] ?? null;
|
||||
|
||||
if ($target === 'content_element') {
|
||||
$report['mirror']['element_rows']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$where = ['art' => 'Zuordnung', 'zuordnung_id' => (int) $row->id, 'wert_id' => $valueId, 'wert' => $label, 'objektart' => $row->subject_type, 'objekt_id' => (int) $row->subject_id, 'herkunft' => $row->origin];
|
||||
|
||||
if ($target === null) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'unbekannte Objektart'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($row->origin !== 'direkt') {
|
||||
$report['unresolved'][] = $where + ['grund' => 'abgeleitete Zuordnung (wird nicht als direkte übernommen)'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($resolved[$valueId])) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Wert ohne belastbare Säule'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = self::TARGETS[$target];
|
||||
|
||||
if (! DB::table($config['subjects'])->where('id', $row->subject_id)->exists()) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Objekt nicht mehr vorhanden'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = DB::table($config['table'])->where($config['column'], $row->subject_id)->where('pillar_id', $resolved[$valueId])->exists();
|
||||
|
||||
if ($present) {
|
||||
$report['already'][$target]++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
DB::table($config['table'])->insertOrIgnore([$config['column'] => $row->subject_id, 'pillar_id' => $resolved[$valueId]]);
|
||||
}
|
||||
|
||||
$report['copied'][$target]++;
|
||||
}
|
||||
|
||||
$report['mirror'] = array_merge($report['mirror'], $this->mirrorDivergence($dimension->id, $resolved));
|
||||
$report['after'] = $dryRun ? $report['before'] : $this->counts();
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $report
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function lines(array $report, bool $dryRun = false): array
|
||||
{
|
||||
$names = ['composition' => 'Module und Programme', 'license_article' => 'Lizenzartikel'];
|
||||
$lines = [$dryRun ? 'Probelauf, es wird nichts geschrieben.' : 'Übernahme abgeschlossen.', ''];
|
||||
|
||||
foreach ($report['mapping'] as $row) {
|
||||
$lines[] = sprintf('Wert %d „%s“ → %s%s', $row['wert_id'], $row['wert'], $row['saeule_id'] === null ? 'keine Säule (offen)' : 'Säule '.$row['saeule_id'].' „'.($row['saeule'] ?? '').'“ ('.$row['status'].')', ! empty($row['hinweis']) ? ' – '.$row['hinweis'] : '');
|
||||
}
|
||||
|
||||
$lines[] = '';
|
||||
|
||||
foreach ($names as $key => $label) {
|
||||
$lines[] = sprintf('%s: %d übernommen, %d bereits vorhanden, Zuordnungen vorher %d, nachher %d', $label, $report['copied'][$key], $report['already'][$key], $report['before'][$key], $report['after'][$key]);
|
||||
}
|
||||
|
||||
$lines[] = sprintf('Medien (nur Information): %d gespiegelte Zeilen, %d nicht mehr in der Medienzuordnung, %d nur dort. Maßgeblich bleibt die Medienzuordnung.', $report['mirror']['element_rows'], $report['mirror']['missing_in_pivot'], $report['mirror']['only_in_pivot']);
|
||||
|
||||
if ($report['unresolved'] === []) {
|
||||
$lines[] = 'Keine ungeklärten Fälle.';
|
||||
} else {
|
||||
$lines[] = '';
|
||||
$lines[] = 'Ungeklärt, bitte entscheiden (nichts wurde geändert):';
|
||||
|
||||
foreach ($report['unresolved'] as $row) {
|
||||
$lines[] = '- '.json_encode($row, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Säule zu einem alten Wert, oder der Grund, warum es keine belastbare gibt.
|
||||
*/
|
||||
private function pillarFor(object $value): object|string
|
||||
{
|
||||
if (preg_match('/^pfeiler-(\d+)$/', (string) $value->slug, $match) !== 1) {
|
||||
return 'Kennung ist nicht „pfeiler-<Nummer>“, keine belastbare Verknüpfung';
|
||||
}
|
||||
|
||||
$pillar = DB::table('pillars')->where('id', (int) $match[1])->first();
|
||||
|
||||
if ($pillar === null) {
|
||||
return 'Die Säule zur Kennung existiert nicht mehr';
|
||||
}
|
||||
|
||||
if ($value->pillar_id !== null && (int) $value->pillar_id !== (int) $pillar->id) {
|
||||
return 'Gespeicherte Verknüpfung (Säule '.$value->pillar_id.') und Kennung (Säule '.$pillar->id.') widersprechen sich';
|
||||
}
|
||||
|
||||
if ($pillar->created_at !== null && $value->created_at !== null && $pillar->created_at > $value->created_at) {
|
||||
return 'Die Säule ist jünger als der Wert; die Kennung kann nicht aus ihr entstanden sein';
|
||||
}
|
||||
|
||||
return $pillar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Objektart wie gespeichert => Ziel
|
||||
*/
|
||||
private function subjectTypes(): array
|
||||
{
|
||||
$types = [];
|
||||
|
||||
foreach ([
|
||||
'composition' => [Composition::class],
|
||||
'license_article' => [LicenseArticle::class],
|
||||
'content_element' => [ContentElement::class],
|
||||
] as $target => $classes) {
|
||||
foreach ($classes as $class) {
|
||||
$types[$class] = $target;
|
||||
$types[(new $class)->getMorphClass()] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
return $types;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function counts(): array
|
||||
{
|
||||
return [
|
||||
'composition' => DB::table('composition_pillar')->count(),
|
||||
'license_article' => DB::table('license_article_pillar')->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $resolved
|
||||
* @return array{missing_in_pivot: int, only_in_pivot: int}
|
||||
*/
|
||||
private function mirrorDivergence(int $dimensionId, array $resolved): array
|
||||
{
|
||||
$mirrored = [];
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('subject_type', array_unique([ContentElement::class, (new ContentElement)->getMorphClass()]))
|
||||
->whereIn('editorial_dimension_value_id', array_keys($resolved) ?: [0])
|
||||
->get() as $row) {
|
||||
$mirrored[$row->subject_id.':'.$resolved[(int) $row->editorial_dimension_value_id]] = true;
|
||||
}
|
||||
|
||||
$pivot = [];
|
||||
|
||||
foreach (DB::table('content_element_pillar')->get() as $row) {
|
||||
$pivot[$row->content_element_id.':'.$row->pillar_id] = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'missing_in_pivot' => count(array_diff_key($mirrored, $pivot)),
|
||||
'only_in_pivot' => count(array_diff_key($pivot, $mirrored)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > self::MAX_TRAINERS) {
|
||||
throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.');
|
||||
}
|
||||
|
||||
return [self::MULTI, $count];
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.');
|
||||
}
|
||||
|
||||
/** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */
|
||||
public static function label(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Einzellizenz · 1 Trainer',
|
||||
self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer',
|
||||
default => 'Nutzerkreis nicht festgelegt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */
|
||||
public static function explanation(?string $scope, ?int $trainers): ?string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.',
|
||||
self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */
|
||||
public static function key(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return ($scope ?? '-').'|'.($trainers ?? 0);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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 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);
|
||||
}
|
||||
|
||||
/** Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). */
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Material-Tags des Brand-Kits (Film, Übung, PDF, Paket, Film + Übungen, Film + Merkblatt).
|
||||
*
|
||||
* Die Zuordnung hängt an Schlüsseln (Ausgabeklasse des Mediums, Kennung der redaktionellen Art), nie an Beschriftungen.
|
||||
* Was nicht eindeutig zuzuordnen ist, bekommt kein Tag und bleibt Text:
|
||||
* - „Paket“ und die beiden Kombinationen werden nicht automatisch vergeben (offen: Paket als Angebot oder als Programm;
|
||||
* Kombinationen aus dem Modulaufbau berechnen oder redaktionell wählen). Die Komponente kann sie darstellen.
|
||||
* - „Dokument“ ist nicht automatisch PDF; das Tag PDF gibt es nur für die Ausgabeklasse „pdf“.
|
||||
*/
|
||||
enum MaterialTag: string
|
||||
{
|
||||
case Film = 'film';
|
||||
case Uebung = 'uebung';
|
||||
case Pdf = 'pdf';
|
||||
case Paket = 'paket';
|
||||
case FilmUebungen = 'film-uebungen';
|
||||
case FilmMerkblatt = 'film-merkblatt';
|
||||
|
||||
private const FILM_KINDS = ['unterrichtsfilm', 'kurzfilm', 'trailer', 'interview'];
|
||||
|
||||
private const EXERCISE_KINDS = ['arbeitsblatt', 'uebungsbeschreibung'];
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'Film',
|
||||
self::Uebung => 'Übung',
|
||||
self::Pdf => 'PDF',
|
||||
self::Paket => 'Paket',
|
||||
self::FilmUebungen => 'Film + Übungen',
|
||||
self::FilmMerkblatt => 'Film + Merkblatt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Name des Zeichens im Satz „glyphen“ (resources/svg/brand/glyphen). */
|
||||
public function glyph(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'film',
|
||||
self::Uebung => 'uebung',
|
||||
self::Pdf, self::FilmMerkblatt => 'dokument',
|
||||
self::Paket => 'paket',
|
||||
self::FilmUebungen => 'filmstreifen',
|
||||
};
|
||||
}
|
||||
|
||||
public static function fromContent(?string $outputClass, ?string $editorialKindSlug = null): ?self
|
||||
{
|
||||
return match (true) {
|
||||
$outputClass === 'film' => self::Film,
|
||||
$outputClass === 'pdf' => self::Pdf,
|
||||
in_array($editorialKindSlug, self::FILM_KINDS, true) => self::Film,
|
||||
in_array($editorialKindSlug, self::EXERCISE_KINDS, true) => self::Uebung,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Offer extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'standalone_bundle' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
/** Bezeichnung der Option auf der Produktseite. */
|
||||
public function optionName(): string
|
||||
{
|
||||
return filled($this->option_label) ? (string) $this->option_label : (string) $this->name;
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(OfferVersion::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
class OfferCoverage
|
||||
{
|
||||
public function __construct(private readonly ContentResolver $resolver) {}
|
||||
|
||||
/**
|
||||
* Bestandteile der Fassung, deren Medienfassung gesperrt ist. Ein Angebot soll nicht aktiviert werden, solange sein
|
||||
* Umfang gesperrte Bestandteile enthält; die Prüfung nennt sie vorab.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function blockedLeaves(CompositionVersion $version): array
|
||||
{
|
||||
$rows = $this->resolver->expand($version);
|
||||
$blocked = ContentElementVersion::query()
|
||||
->whereIn('id', array_column($rows, 'version_id'))
|
||||
->where('status', ContentVersionStatus::Gesperrt->value)
|
||||
->pluck('id')
|
||||
->all();
|
||||
|
||||
return array_values(array_map(
|
||||
fn (array $row): string => $row['path'],
|
||||
array_filter($rows, fn (array $row): bool => in_array($row['version_id'], $blocked, true)),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
<?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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung mit Preis; sonst null (nicht kaufbar, zurückgezogen oder kostenlos).
|
||||
*/
|
||||
public function purchasableVersion(Offer $offer): ?OfferVersion
|
||||
{
|
||||
$version = $offer->versions()
|
||||
->where('status', OfferStatus::Aktiv)
|
||||
->orderByDesc('number')
|
||||
->first();
|
||||
|
||||
if ($version === null || $version->grant_kind !== 'kauf' || $version->price_cents === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
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',
|
||||
'licence_scope' => null,
|
||||
'trainer_count' => null,
|
||||
], $attributes);
|
||||
|
||||
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
|
||||
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
|
||||
}
|
||||
|
||||
$this->assertAttributes($attributes);
|
||||
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||
$scope = $this->scopeFor($lines);
|
||||
$this->assertSellableContent($scope);
|
||||
$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'],
|
||||
'licence_scope' => $attributes['licence_scope'],
|
||||
'trainer_count' => $attributes['trainer_count'],
|
||||
]);
|
||||
|
||||
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');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zieht die Option aus dem Verkauf zurück: Die aktive Fassung wird beendet und bleibt gespeichert. Bereits
|
||||
* begründete Berechtigungen und Bestellungen ändern sich nicht; offene Warenkörbe zeigen die Position als
|
||||
* zurückgezogen und blockieren den Abschluss, bis der Käufer sie entfernt.
|
||||
*/
|
||||
public function end(Offer $offer): OfferVersion
|
||||
{
|
||||
return DB::transaction(function () use ($offer): OfferVersion {
|
||||
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
|
||||
$version = $this->currentActiveVersion($offer);
|
||||
$version->status = OfferStatus::Beendet;
|
||||
$version->save();
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
||||
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
{
|
||||
if ($compositionId !== null) {
|
||||
Composition::query()->findOrFail($compositionId);
|
||||
}
|
||||
|
||||
if ($ownBundlePage && $compositionId !== null) {
|
||||
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
|
||||
}
|
||||
|
||||
$offer->composition_id = $compositionId;
|
||||
$offer->standalone_bundle = $ownBundlePage;
|
||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||
$offer->save();
|
||||
|
||||
return $offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
|
||||
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
|
||||
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
|
||||
*
|
||||
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
|
||||
*/
|
||||
private function assertSellableContent(array $scope): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
|
||||
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
|
||||
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
|
||||
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
|
||||
|
||||
if ($missing->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
|
||||
|
||||
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
|
||||
.($missing->count() === 1 ? ' hat' : ' haben')
|
||||
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
|
||||
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($version)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Das Angebot wird hier nicht aktiviert.');
|
||||
}
|
||||
$articles = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if ($line['target'] instanceof LicenseArticle) {
|
||||
$articles[] = $line['target'];
|
||||
}
|
||||
}
|
||||
|
||||
$blocked = app(OfferCoverage::class)->blockedLeaves($version);
|
||||
|
||||
if ($blocked !== []) {
|
||||
throw new DomainRuleException('Das Angebot enthält gesperrte Bestandteile: '.implode(', ', $blocked));
|
||||
}
|
||||
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
enum OfferStatus: string
|
||||
{
|
||||
case Entwurf = 'entwurf';
|
||||
case Aktiv = 'aktiv';
|
||||
case Beendet = 'beendet';
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?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',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?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);
|
||||
}
|
||||
|
||||
public function compositions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Composition::class);
|
||||
}
|
||||
|
||||
public function licenseArticles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(LicenseArticle::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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Alte Filteradressen: Vor der Vereinheitlichung war „Fachliche Säule“ ein Wert der redaktionellen Einordnung
|
||||
* (`?einordnung=…`, `?pillar=…`, `dimension[]=…`). Verweist ein solcher Wert über `pillar_id` auf eine zentrale Säule,
|
||||
* gilt der Filter jetzt für diese Säule, statt stillschweigend zu entfallen.
|
||||
*/
|
||||
final class PillarFilterCompat
|
||||
{
|
||||
/**
|
||||
* @return int|null|false Kennung der Säule; null: alter Säulenwert ohne belastbare Verknüpfung; false: kein Säulenwert
|
||||
*/
|
||||
public static function pillarOfLegacyValue(int $valueId): int|false|null
|
||||
{
|
||||
$row = DB::table('editorial_dimension_values')
|
||||
->join('editorial_dimensions', 'editorial_dimensions.id', '=', 'editorial_dimension_values.editorial_dimension_id')
|
||||
->where('editorial_dimension_values.id', $valueId)
|
||||
->where('editorial_dimensions.slug', EditorialDimension::PILLAR_SLUG)
|
||||
->first(['editorial_dimension_values.pillar_id']);
|
||||
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $row->pillar_id === null ? null : (int) $row->pillar_id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?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
|
||||
{
|
||||
$usage = $this->usage($pillar);
|
||||
|
||||
if (array_sum($usage) > 0) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Objekten wird nicht gelöscht ('.$this->usageText($usage).'). Ordnen Sie sie zuerst anders zu.');
|
||||
}
|
||||
|
||||
$pillar->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zuordnungen je Objektart: Medien, Module und Programme, Lizenzartikel, Seiten.
|
||||
*
|
||||
* @return array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int}
|
||||
*/
|
||||
public function usage(Pillar $pillar): array
|
||||
{
|
||||
return [
|
||||
'medien' => $pillar->elements()->count(),
|
||||
'zusammenstellungen' => $pillar->compositions()->count(),
|
||||
'lizenzartikel' => $pillar->licenseArticles()->count(),
|
||||
'seiten' => $pillar->pages()->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int} $usage
|
||||
*/
|
||||
public function usageText(array $usage): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach (['medien' => ['Medium', 'Medien'], 'zusammenstellungen' => ['Modul oder Programm', 'Module und Programme'], 'lizenzartikel' => ['Lizenzartikel', 'Lizenzartikel'], 'seiten' => ['Seite', 'Seiten']] as $key => [$one, $many]) {
|
||||
if ($usage[$key] > 0) {
|
||||
$parts[] = $usage[$key].' '.($usage[$key] === 1 ? $one : $many);
|
||||
}
|
||||
}
|
||||
|
||||
return $parts === [] ? 'nirgends zugeordnet' : implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einem Medium, Modul, Programm, Lizenzartikel oder einer Seite Säulen zu. Alle Objektarten verwenden
|
||||
* dieselbe zentrale Säule und dieselbe Speicherregel; die Zuordnung ersetzt die bisherige vollständig.
|
||||
*
|
||||
* @param list<int|string> $pillarIds
|
||||
*/
|
||||
public function assign(ContentElement|Composition|LicenseArticle|Page $subject, array $pillarIds): void
|
||||
{
|
||||
$subject->pillars()->sync($this->ids($pillarIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $pillarIds
|
||||
*/
|
||||
public function assignPages(Page $page, array $pillarIds): void
|
||||
{
|
||||
$this->assign($page, $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');
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?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',
|
||||
'requirement',
|
||||
'variant_key',
|
||||
];
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
) {}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Design\SiteSetting;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
/**
|
||||
* Zugang zum Shinkan-Katalog. Die Adresse ist je Umgebung vorgegeben (`SHINKAN_DISTRIBUTION_URL`). Der Zugangsschlüssel
|
||||
* kommt aus der Umgebung des Servers (`SHINKAN_DISTRIBUTION_KEY`, hat Vorrang und bleibt die bestehende Anbindung) oder
|
||||
* ist in der Verwaltung hinterlegt. So lässt sich der Schlüssel ersetzen, ohne die Umgebung des Servers anzufassen.
|
||||
*
|
||||
* Der in der Verwaltung hinterlegte Schlüssel liegt je Umgebung getrennt und mit dem Anwendungsschlüssel verschlüsselt in
|
||||
* den Einstellungen. Er wird nie zurückgegeben, nie angezeigt und nie protokolliert und steht in keiner Fehlermeldung.
|
||||
*/
|
||||
final class ShinkanConnection
|
||||
{
|
||||
public const SETTING = 'shinkan.anbindung';
|
||||
|
||||
public const SERVER = 'server';
|
||||
|
||||
public const ADMIN = 'verwaltung';
|
||||
|
||||
public function url(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.url');
|
||||
|
||||
if (! is_string($value) || trim($value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Die Adresse ist die der Shinkan-Installation. Der Pfad `/api/distribution/v1` hängt der Abruf selbst an; wer ihn
|
||||
// (oder nur `/api`) mit einträgt, bekommt trotzdem die richtige Adresse und keinen doppelten Pfad.
|
||||
$base = rtrim(trim($value), '/');
|
||||
$base = (string) preg_replace('#/api(/distribution(/v1)?)?$#', '', $base);
|
||||
|
||||
return $base === '' ? null : $base;
|
||||
}
|
||||
|
||||
public function apiKey(): ?string
|
||||
{
|
||||
$server = $this->serverKey();
|
||||
|
||||
if ($server !== null) {
|
||||
return $server;
|
||||
}
|
||||
|
||||
$encrypted = $this->stored()['key'] ?? null;
|
||||
|
||||
if (! is_string($encrypted) || $encrypted === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($encrypted);
|
||||
} catch (DecryptException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Woher kommt der Schlüssel? `server`, `verwaltung` oder null.
|
||||
*/
|
||||
public function keySource(): ?string
|
||||
{
|
||||
if ($this->serverKey() !== null) {
|
||||
return self::SERVER;
|
||||
}
|
||||
|
||||
return $this->apiKey() !== null ? self::ADMIN : null;
|
||||
}
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return $this->url() !== null && $this->apiKey() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinterlegt oder ersetzt den Schlüssel. Der Schlüssel aus der Umgebung des Servers behält den Vorrang.
|
||||
*/
|
||||
public function saveKey(string $key, ?User $by = null): void
|
||||
{
|
||||
$key = trim($key);
|
||||
|
||||
if ($key === '') {
|
||||
throw new DomainRuleException('Der Zugangsschlüssel fehlt.');
|
||||
}
|
||||
|
||||
$this->write(['key' => Crypt::encryptString($key)], $by);
|
||||
}
|
||||
|
||||
public function forgetKey(?User $by = null): void
|
||||
{
|
||||
$this->write([], $by);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function stored(): array
|
||||
{
|
||||
$value = SiteSetting::query()->find(self::SETTING)?->value;
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $stored
|
||||
*/
|
||||
private function write(array $stored, ?User $by): void
|
||||
{
|
||||
SiteSetting::query()->updateOrCreate(['key' => self::SETTING], ['value' => $stored, 'updated_by' => $by?->id]);
|
||||
}
|
||||
|
||||
private function serverKey(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.key');
|
||||
|
||||
return is_string($value) && trim($value) !== '' ? trim($value) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Übernahme von Übungen aus dem Shinkan-Katalog (`GET /api/distribution/v1/catalog` und Detailroute) in denselben
|
||||
* Übungsbestand wie die lokalen Übungen.
|
||||
*
|
||||
* Grundsätze:
|
||||
* - Die Quellübung ist an ihre stabile Kennung gebunden. Jeder Inhaltsstand (Prüfsumme der Quelle) wird genau einmal
|
||||
* festgehalten; ein wiederholter Abruf erzeugt nichts Neues.
|
||||
* - Eine lokale Fassung entsteht nur durch die bewusste Übernahme ({@see adoptPreviewed}) und ist danach unveränderlich.
|
||||
* Lokale Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten. Entfällt die Quellvariante einer
|
||||
* lokalen Ergänzung, legt die Redaktion die neue Zuordnung fest.
|
||||
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
|
||||
* rechtliche Sperre ist der lokale `block`. Ausgeblendete Quellen sind von der Übernahme ausgeschlossen.
|
||||
* - Medien des Katalogs sind Metadaten ohne Datei. Sie begründen weder eine Ausgabe noch eine Nutzungsberechtigung und
|
||||
* stehen nie in einem Artikel-Stand.
|
||||
* - Ein fehlgeschlagener Abruf verändert den gespeicherten Stand nicht und rückt den Cursor nicht vor.
|
||||
*/
|
||||
class ShinkanImport
|
||||
{
|
||||
/** Abschnitte der Quelle in Lesereihenfolge: Feld => Bezeichnung. */
|
||||
public const SECTIONS = [
|
||||
'preparation' => 'Vorbereitung',
|
||||
'execution' => 'Durchführung',
|
||||
'trainer_notes' => 'Trainerhinweise',
|
||||
];
|
||||
|
||||
/** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */
|
||||
private const IMPORT_NOTE = 'Übernahme aus Shinkan';
|
||||
|
||||
/** Fassungsfelder der Quelle: Katalogfeld => [Feld der lokalen Fassung, Bezeichnung]. */
|
||||
private const FIELDS = [
|
||||
'goal' => ['learning_goal', 'Lernziel'],
|
||||
'duration_min' => ['duration_minutes', 'Dauer (von)'],
|
||||
'duration_max' => ['duration_max', 'Dauer (bis)'],
|
||||
'equipment' => ['material_note', 'Ausstattung'],
|
||||
];
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return app(ShinkanConnection::class)->configured();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt.
|
||||
*
|
||||
* @return array{url: bool, key: bool, host: string|null, key_source: string|null}
|
||||
*/
|
||||
public function status(): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$url = $connection->url();
|
||||
|
||||
return [
|
||||
'url' => $url !== null,
|
||||
'key' => $connection->apiKey() !== null,
|
||||
'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null,
|
||||
'key_source' => $connection->keySource(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel
|
||||
* geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt.
|
||||
*
|
||||
* @return array{ok: bool, message: string}
|
||||
*/
|
||||
public function check(?string $candidateKey = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey();
|
||||
|
||||
if ($connection->url() === null || $key === null) {
|
||||
return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'];
|
||||
}
|
||||
|
||||
try {
|
||||
$catalog = $this->get('/catalog', [], $key);
|
||||
} catch (Throwable $exception) {
|
||||
return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)];
|
||||
}
|
||||
|
||||
$count = count((array) ($catalog['exercises'] ?? []));
|
||||
|
||||
return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.'];
|
||||
}
|
||||
|
||||
public function fetch(): ExerciseImportRun
|
||||
{
|
||||
$run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]);
|
||||
|
||||
if (! $this->configured()) {
|
||||
return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.');
|
||||
}
|
||||
|
||||
$previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor');
|
||||
$counts = ['added' => 0, 'updated' => 0, 'removed' => 0];
|
||||
|
||||
try {
|
||||
try {
|
||||
$catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]);
|
||||
} catch (RequestException $exception) {
|
||||
// Ein ungültiger Cursor heißt nur: ganz neu abgleichen.
|
||||
if ($previous === null || $exception->response->status() !== 400) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$catalog = $this->get('/catalog');
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['changes'] ?? []) as $change) {
|
||||
$id = (string) ($change['source_id'] ?? '');
|
||||
$kind = (string) ($change['change'] ?? '');
|
||||
|
||||
if ($id === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($kind === 'removed') {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id)
|
||||
->update(['availability' => ExerciseSource::WITHDRAWN]);
|
||||
$counts['removed']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$document = $this->get('/catalog/'.$id);
|
||||
$this->record($document);
|
||||
$counts[$kind === 'added' ? 'added' : 'updated']++;
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['exercises'] ?? []) as $listed) {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? ''))
|
||||
->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.');
|
||||
}
|
||||
|
||||
return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert.
|
||||
*
|
||||
* @param array<string, mixed> $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern
|
||||
*/
|
||||
public function record(array $document): ExerciseSourceSnapshot
|
||||
{
|
||||
$id = (string) ($document['source_id'] ?? '');
|
||||
$hash = (string) ($document['content_hash'] ?? '');
|
||||
|
||||
if ($id === '' || $hash === '') {
|
||||
throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot {
|
||||
$source = ExerciseSource::query()->firstOrCreate(
|
||||
['source_system' => 'shinkan', 'source_id' => $id],
|
||||
['title' => (string) ($document['title'] ?? '')],
|
||||
);
|
||||
$source->update([
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'availability' => ExerciseSource::PROVIDED,
|
||||
'last_hash' => $hash,
|
||||
'last_seen_at' => now(),
|
||||
]);
|
||||
|
||||
return $source->snapshots()->firstOrCreate(
|
||||
['content_hash' => $hash],
|
||||
['payload' => $document, 'fetched_at' => now()],
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand einer Quellübung für die Redaktion.
|
||||
*/
|
||||
public function state(ExerciseSource $source): string
|
||||
{
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
return match (true) {
|
||||
$source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt',
|
||||
$latest === null => 'neu',
|
||||
$latest->adopted_version_id !== null => 'uebernommen',
|
||||
$source->composition_id !== null => 'geaendert',
|
||||
default => 'neu',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die
|
||||
* fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function preview(ExerciseSource $source): array
|
||||
{
|
||||
$snapshot = $source->latestSnapshot();
|
||||
$state = $this->state($source);
|
||||
$document = $snapshot?->payload ?? [];
|
||||
$previous = $this->lastAdopted($source);
|
||||
$sections = [];
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
if (trim((string) ($document[$field] ?? '')) !== '') {
|
||||
$sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'source' => $source->id,
|
||||
'snapshot' => $snapshot?->id,
|
||||
'hash' => $snapshot?->content_hash,
|
||||
'state' => $state,
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'summary' => (string) ($document['summary'] ?? ''),
|
||||
'goal' => (string) ($document['goal'] ?? ''),
|
||||
'duration' => $this->duration($document),
|
||||
'equipment' => (string) ($document['equipment'] ?? ''),
|
||||
'sections' => $sections,
|
||||
'variants' => array_map(fn (array $variant): array => [
|
||||
'key' => (string) ($variant['id'] ?? ''),
|
||||
'name' => (string) ($variant['name'] ?? ''),
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '',
|
||||
], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))),
|
||||
'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))),
|
||||
'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source),
|
||||
'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document),
|
||||
'text_conflicts' => $snapshot === null ? [] : $this->textDecisions($source, $document, 'conflict'),
|
||||
'kept_local' => $snapshot === null ? [] : array_column($this->textDecisions($source, $document, 'keep_local'), 'label'),
|
||||
'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null,
|
||||
'excluded' => $source->availability === ExerciseSource::WITHDRAWN,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
* @return list<string>
|
||||
*/
|
||||
public function changes(array $before, array $after, ?ExerciseSource $source = null): array
|
||||
{
|
||||
$lines = [];
|
||||
$labels = [
|
||||
'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung',
|
||||
'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)',
|
||||
] + self::SECTIONS;
|
||||
|
||||
foreach ($labels as $field => $label) {
|
||||
if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) {
|
||||
$lines[] = $label.' geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
$new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
|
||||
foreach ($new->diffKeys($old) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu';
|
||||
}
|
||||
|
||||
foreach ($old->diffKeys($new) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt';
|
||||
}
|
||||
|
||||
foreach ($new->intersectByKeys($old) as $key => $variant) {
|
||||
if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) {
|
||||
$lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“';
|
||||
}
|
||||
|
||||
if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? ''))
|
||||
|| trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$common = $old->keys()->intersect($new->keys())->values()->all();
|
||||
|
||||
if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) {
|
||||
$lines[] = 'Reihenfolge der Varianten geändert';
|
||||
}
|
||||
|
||||
if ($source?->composition !== null) {
|
||||
if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) {
|
||||
$lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
|
||||
if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) {
|
||||
$lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt.
|
||||
* Die Redaktion legt deren neue Zuordnung fest.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, name: string, members: list<string>}>
|
||||
*/
|
||||
public function conflicts(ExerciseSource $source, array $document): array
|
||||
{
|
||||
$latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
|
||||
if ($latest === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keep = array_merge(
|
||||
array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')),
|
||||
$latest->variants->where('origin', 'lokal')->pluck('key')->all(),
|
||||
);
|
||||
$open = [];
|
||||
|
||||
foreach ($latest->members->where('origin', 'lokal') as $member) {
|
||||
$key = $member->variant?->key;
|
||||
|
||||
if ($key !== null && ! in_array($key, $keep, true)) {
|
||||
$open[$key]['key'] = $key;
|
||||
$open[$key]['name'] = $member->variant->name;
|
||||
$open[$key]['members'][] = $member->role;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($open);
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte und Felder, die lokal bearbeitet wurden: `keep_local` bleiben erhalten, bei `conflict` hat auch die Quelle
|
||||
* geändert und die Redaktion entscheidet.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public function textDecisions(ExerciseSource $source, array $document, string $wanted): array
|
||||
{
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
|
||||
if ($previousSnapshot === null || $source->composition === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$previousSource = $previousSnapshot->payload;
|
||||
$result = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'text' && $item['decision'] === $wanted) {
|
||||
$result[] = ['key' => $item['key'], 'label' => $item['label']];
|
||||
}
|
||||
}
|
||||
|
||||
$latest = $source->composition->versions()->orderByDesc('number')->first();
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
if ($latest !== null && $this->classifyField($latest->{$column}, $previousSource[$field] ?? null, $document[$field] ?? null) === $wanted) {
|
||||
$result[] = ['key' => $field, 'label' => $label];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder
|
||||
* wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung.
|
||||
*
|
||||
* @param array<string, string> $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder ''
|
||||
* @param array<string, string> $choices bei lokal und in der Quelle geänderten Angaben: Schlüssel => `lokal` oder `quelle`
|
||||
* @return array{status: string, message: string, version?: CompositionVersion}
|
||||
*/
|
||||
public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null, array $choices = []): array
|
||||
{
|
||||
$source->refresh();
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
if ($source->availability === ExerciseSource::WITHDRAWN) {
|
||||
return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.'];
|
||||
}
|
||||
|
||||
if ($latest === null || $latest->id !== $previewedSnapshot) {
|
||||
return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.'];
|
||||
}
|
||||
|
||||
if ($latest->adopted_version_id !== null) {
|
||||
return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion];
|
||||
}
|
||||
|
||||
try {
|
||||
$version = $this->adopt($latest, $actor, $reassign, $choices);
|
||||
} catch (DomainRuleException $exception) {
|
||||
return ['status' => 'fehler', 'message' => $exception->getMessage()];
|
||||
}
|
||||
|
||||
return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
||||
* entsteht keine zweite Fassung.
|
||||
*
|
||||
* Eine importierte Übung ist eine Übung wie jede andere und lässt sich bearbeiten. Lokal bearbeitete Texte und Felder
|
||||
* bleiben deshalb erhalten, solange die Quelle sie nicht ebenfalls geändert hat. Haben beide Seiten geändert, legt die
|
||||
* Redaktion fest, welcher Stand gilt (`$choices`). Lokale Ergänzungen bleiben erhalten; entfällt ihre Quellvariante,
|
||||
* legt die Redaktion die neue Zuordnung fest (`$reassign`).
|
||||
*
|
||||
* @param array<string, string> $reassign
|
||||
* @param array<string, string> $choices Schlüssel => `lokal` oder `quelle`
|
||||
*/
|
||||
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = [], array $choices = []): CompositionVersion
|
||||
{
|
||||
$snapshot->refresh();
|
||||
|
||||
if ($snapshot->adopted_version_id !== null) {
|
||||
return $snapshot->adoptedVersion;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($snapshot, $actor, $reassign, $choices): CompositionVersion {
|
||||
$source = $snapshot->source;
|
||||
$document = $snapshot->payload;
|
||||
$content = app(ContentService::class);
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
$previousSource = $previousSnapshot?->payload ?? [];
|
||||
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
|
||||
|
||||
if ($source->composition !== null && $previousSnapshot !== null) {
|
||||
$this->carryOverTexts($composition, $previousSource, $document);
|
||||
}
|
||||
|
||||
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
$variants = [];
|
||||
$members = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'variant') {
|
||||
$variants[] = $item['variant'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$latest = $item['latest'];
|
||||
$decision = $item['decision'];
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$item['key']] ?? null) === 'lokal' ? 'keep_local'
|
||||
: (($choices[$item['key']] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$item['label'].'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$keepLocal = $decision === 'keep_local' && $latest !== null;
|
||||
$target = $keepLocal ? $latest : $this->sectionVersion($source, $item['field'], $item['title'], $item['text'], $latest);
|
||||
$members[] = array_filter([
|
||||
'role' => $item['role'],
|
||||
'target' => $target,
|
||||
'variant' => $item['variant_key'],
|
||||
'origin' => $keepLocal || ($latest !== null && $latest->id === $target->id && $latest->change_note !== self::IMPORT_NOTE) ? 'lokal' : 'quelle',
|
||||
], fn ($value): bool => $value !== null);
|
||||
}
|
||||
|
||||
// Fassungsfelder: lokal geändert bleibt erhalten, solange die Quelle den Wert nicht ebenfalls geändert hat.
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
$value = $document[$field] ?? null;
|
||||
|
||||
if ($previous !== null && $previousSnapshot !== null) {
|
||||
$decision = $this->classifyField($previous->{$column}, $previousSource[$field] ?? null, $value);
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$label.'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$value = $decision === 'keep_local' ? $previous->{$column} : $value;
|
||||
}
|
||||
|
||||
$fields[$column] = $value;
|
||||
}
|
||||
|
||||
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign);
|
||||
$version = $content->publishComposition(
|
||||
$composition,
|
||||
[...$members, ...$localMembers],
|
||||
$actor,
|
||||
self::IMPORT_NOTE,
|
||||
[
|
||||
'learning_goal' => $fields['learning_goal'],
|
||||
'duration_minutes' => $fields['duration_minutes'],
|
||||
'duration_max' => $fields['duration_max'],
|
||||
'material_note' => $fields['material_note'],
|
||||
'source_snapshot_id' => $snapshot->id,
|
||||
],
|
||||
[...$variants, ...$localVariants],
|
||||
);
|
||||
|
||||
$snapshot->update(['adopted_version_id' => $version->id]);
|
||||
$source->update(['composition_id' => $composition->id]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Übernahme aus dem Quellstand anlegen würde, mit der Entscheidung je Text: `source` (Quelltext gilt),
|
||||
* `keep_local` (lokal bearbeitet, die Quelle hat sich nicht geändert) oder `conflict` (beide haben geändert).
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @param array<string, mixed> $previousSource
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function plan(ExerciseSource $source, array $document, array $previousSource): array
|
||||
{
|
||||
$plan = [];
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
$text = trim((string) ($document[$field] ?? ''));
|
||||
|
||||
if ($text !== '') {
|
||||
$plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $previousSource[$field] ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
||||
$key = (string) ($variant['id'] ?? '');
|
||||
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) ($variant['name'] ?? '') ?: 'Variante';
|
||||
$plan[] = [
|
||||
'kind' => 'variant',
|
||||
'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'],
|
||||
];
|
||||
$changes = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
|
||||
if ($changes !== '') {
|
||||
$before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key);
|
||||
$plan[] = $this->textItem(
|
||||
$source,
|
||||
'variant:'.$key,
|
||||
'Abweichung der Durchführung ('.$name.')',
|
||||
$title.' · '.$name.' · Abweichung',
|
||||
'Abweichung der Durchführung',
|
||||
$changes,
|
||||
$key,
|
||||
is_array($before) ? ($before['execution_changes'] ?? null) : null,
|
||||
'variant_'.$key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function textItem(ExerciseSource $source, string $field, string $label, string $title, string $role, string $text, ?string $variantKey, ?string $previousText, ?string $key = null): array
|
||||
{
|
||||
$element = ContentElement::query()->where('source_ref', 'shinkan:'.$source->source_id.':'.$field)->first();
|
||||
$latest = $element?->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
|
||||
return [
|
||||
'kind' => 'text',
|
||||
'key' => $key ?? $field,
|
||||
'field' => $field,
|
||||
'label' => $label,
|
||||
'title' => $title,
|
||||
'role' => $role,
|
||||
'text' => $text,
|
||||
'variant_key' => $variantKey,
|
||||
'latest' => $latest,
|
||||
'decision' => $this->classifyText($latest, $text, $previousText),
|
||||
];
|
||||
}
|
||||
|
||||
private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string
|
||||
{
|
||||
if ($latest === null || trim((string) $latest->body) === $text || $latest->change_note === self::IMPORT_NOTE) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $previousText === null || trim($previousText) !== $text ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
private function classifyField(mixed $local, mixed $previousSource, mixed $new): string
|
||||
{
|
||||
$plain = fn (mixed $value): string => $value === null ? '' : trim((string) $value);
|
||||
|
||||
if ($plain($local) === $plain($new) || $plain($local) === $plain($previousSource)) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $plain($previousSource) !== $plain($new) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
/**
|
||||
* Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie
|
||||
* nicht lokal geändert hat; ein lokal geänderter Wert bleibt.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function carryOverTexts(Composition $composition, array $before, array $after): void
|
||||
{
|
||||
if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) {
|
||||
$composition->designation = trim((string) $after['title']);
|
||||
}
|
||||
|
||||
if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) {
|
||||
$composition->summary = trim((string) $after['summary']) ?: null;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
}
|
||||
|
||||
private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
|
||||
* Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung.
|
||||
*
|
||||
* @param list<string> $sourceVariantKeys
|
||||
* @param array<string, string> $reassign
|
||||
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
|
||||
*/
|
||||
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): array
|
||||
{
|
||||
if ($previous === null) {
|
||||
return [[], []];
|
||||
}
|
||||
|
||||
$localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal',
|
||||
])->values()->all();
|
||||
$known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')];
|
||||
$members = [];
|
||||
|
||||
foreach ($previous->members->where('origin', 'lokal') as $member) {
|
||||
$variant = $member->variant?->key;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, $known, true)) {
|
||||
if (! array_key_exists($variant, $reassign)) {
|
||||
throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.');
|
||||
}
|
||||
|
||||
$target = (string) $reassign[$variant];
|
||||
|
||||
if ($target !== '' && ! in_array($target, $known, true)) {
|
||||
throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.');
|
||||
}
|
||||
|
||||
$variant = $target === '' ? null : $target;
|
||||
}
|
||||
|
||||
$members[] = [
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
|
||||
'variant' => $variant,
|
||||
'requirement' => $member->requirement,
|
||||
'selection' => $member->variant_selection,
|
||||
'origin' => 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return [$members, $localVariants];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung.
|
||||
*/
|
||||
private function sectionVersion(ExerciseSource $source, string $field, string $title, string $text, ?ContentElementVersion $latest): ContentElementVersion
|
||||
{
|
||||
$content = app(ContentService::class);
|
||||
$ref = 'shinkan:'.$source->source_id.':'.$field;
|
||||
$element = ContentElement::query()->where('source_ref', $ref)->first();
|
||||
|
||||
if ($element === null) {
|
||||
$element = $content->createElement('text', 'text', $title);
|
||||
$element->source_ref = $ref;
|
||||
$element->save();
|
||||
}
|
||||
|
||||
return $latest !== null && trim((string) $latest->body) === $text
|
||||
? $latest
|
||||
: $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE);
|
||||
}
|
||||
|
||||
private function createComposition(string $title, string $summary): Composition
|
||||
{
|
||||
$composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise);
|
||||
$composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id');
|
||||
|
||||
if ($summary !== '') {
|
||||
$composition->summary = $summary;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
|
||||
return $composition;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $document
|
||||
*/
|
||||
private function duration(array $document): string
|
||||
{
|
||||
$min = $document['duration_min'] ?? null;
|
||||
$max = $document['duration_max'] ?? null;
|
||||
|
||||
return match (true) {
|
||||
$min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten',
|
||||
$min !== null => $min.' Minuten',
|
||||
$max !== null => $max.' Minuten',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function get(string $path, array $query = [], ?string $key = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$response = Http::withToken((string) ($key ?? $connection->apiKey()))
|
||||
->acceptJson()
|
||||
->timeout(20)
|
||||
->get((string) $connection->url().'/api/distribution/v1'.$path, $query)
|
||||
->throw();
|
||||
|
||||
$json = $response->json();
|
||||
|
||||
if (! is_array($json)) {
|
||||
throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.');
|
||||
}
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{added?: int, updated?: int, removed?: int} $counts
|
||||
*/
|
||||
private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun
|
||||
{
|
||||
$run->update([
|
||||
'status' => $status,
|
||||
'cursor' => $cursor,
|
||||
'added' => $counts['added'] ?? 0,
|
||||
'updated' => $counts['updated'] ?? 0,
|
||||
'removed' => $counts['removed'] ?? 0,
|
||||
'error' => $error,
|
||||
'finished_at' => now(),
|
||||
]);
|
||||
|
||||
return $run;
|
||||
}
|
||||
|
||||
/** Fehlertext ohne Adresse und Schlüssel. */
|
||||
private function plain(Throwable $exception): string
|
||||
{
|
||||
if ($exception instanceof RequestException) {
|
||||
return match ($exception->response->status()) {
|
||||
401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').',
|
||||
404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).',
|
||||
default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.',
|
||||
};
|
||||
}
|
||||
|
||||
if ($exception instanceof DomainRuleException) {
|
||||
return $exception->getMessage();
|
||||
}
|
||||
|
||||
return $this->networkCause($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
|
||||
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
|
||||
*/
|
||||
private function networkCause(Throwable $exception): string
|
||||
{
|
||||
$host = app(ShinkanConnection::class)->url();
|
||||
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
|
||||
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
|
||||
$code = isset($match[1]) ? (int) $match[1] : null;
|
||||
|
||||
$cause = match (true) {
|
||||
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
|
||||
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
|
||||
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
|
||||
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
|
||||
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
|
||||
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
|
||||
default => 'Netzwerkfehler.',
|
||||
};
|
||||
|
||||
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
|
||||
/**
|
||||
* Rückfallschutz: Dieser Code kennt nur die Kompositionsarten aus {@see CompositionKind}. Eine Komposition mit einem
|
||||
* Wert, den erst eine neuere Programmversion einführt, gilt hier als nicht vorhanden. Sie wird weder geladen (der
|
||||
* Enum-Zugriff würde sonst abstürzen) noch angezeigt, bearbeitet oder veröffentlicht. Eine neuere Programmversion
|
||||
* kennt den Wert und sieht die Zeile wieder.
|
||||
*/
|
||||
class SupportedKindScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->whereIn($model->qualifyColumn('kind'), CompositionKind::values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?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.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
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 array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
{
|
||||
return $this->copy(['title' => $title ?? $this->title, 'summary' => $summary ?? $this->summary]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text der Karte aus einem zentralen Text des Fachobjekts. Ist er nicht gepflegt, bleibt die Karte ohne Text
|
||||
* (kein stiller Ersatz aus einem anderen Feld); in der Redaktionsvorschau steht dann ein Hinweis.
|
||||
*/
|
||||
public function withTextChoice(string $field, string $missingHint): self
|
||||
{
|
||||
if (! array_key_exists($field, $this->texts)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$text = $this->texts[$field];
|
||||
$missing = array_values(array_filter($this->missing, fn (string $hint): bool => ! str_contains($hint, 'Kurzbeschreibung')));
|
||||
|
||||
if ($text === null) {
|
||||
$missing[] = $missingHint;
|
||||
}
|
||||
|
||||
return $this->copy(['summary' => $text, 'missing' => $missing]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes
|
||||
*/
|
||||
private function copy(array $changes): self
|
||||
{
|
||||
return new self(...array_merge(get_object_vars($this), $changes));
|
||||
}
|
||||
}
|
||||
@@ -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,357 @@
|
||||
<?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;
|
||||
// Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“).
|
||||
$texts = [
|
||||
'teaser' => $profile->value('teaser'),
|
||||
'summary' => $profile->value('summary'),
|
||||
'description' => $profile->value('description'),
|
||||
'goal' => $goal,
|
||||
];
|
||||
$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,
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
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,349 @@
|
||||
<?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\MaterialTag;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
|
||||
/**
|
||||
* 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, dazu
|
||||
* jeder Film, der nur aus einer Website-Datei besteht (Medium ohne Inhaltsfassung, z. B. ein Teaser).
|
||||
*
|
||||
* Ö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).
|
||||
*
|
||||
* Ein Film nur mit Website-Datei hat weder Fassung noch Programm. Er erscheint öffentlich, sobald seine Website-Datei
|
||||
* für die Website freigegeben ist (die Freigabe ist die ausdrückliche Entscheidung der Redaktion), ohne Verweis auf
|
||||
* eine Programmseite und damit ohne Aktion. Ohne Freigabe bleibt er auf die Redaktionsvorschau beschränkt.
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Inhaltsart und Ausgabeart sowie einer der Texte
|
||||
* Teaser, Kurzbeschreibung oder ausführliche Beschreibung. Welcher Text erscheint, entscheidet die Redaktion je Karte
|
||||
* (Einstellung „Text der Karte“); ohne Wahl gilt die Kurzbeschreibung, sonst der Teaser. Die ausführliche Beschreibung
|
||||
* erscheint nur, wenn die Redaktion sie ausdrücklich wählt. Nie: Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte,
|
||||
* Ausgabeadressen. Das Vorschaubild der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der
|
||||
* Redaktionsvorschau und kann in der Karte ausdrücklich als Website-Bild übernommen werden (FilmStill).
|
||||
* Eine Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), 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()
|
||||
|| $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Film ohne jede Inhaltsfassung, der nur die Website-Datei (`teaser/…`) hat, zum Beispiel ein Teaser. Er kann
|
||||
* auf der Medienkarte gewählt werden; was daraus öffentlich wird, bestimmt allein die Freigabe der Datei.
|
||||
*/
|
||||
public function isWebsiteOnlyFilm(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& filled($element->preview_path)
|
||||
&& ! $element->versions()->exists();
|
||||
}
|
||||
|
||||
public function isReady(ContentElement $element): bool
|
||||
{
|
||||
if ($this->isWebsiteOnlyFilm($element)) {
|
||||
return $this->isWebsiteReleased($element);
|
||||
}
|
||||
|
||||
return $element->versions()->where('status', ContentVersionStatus::Bereit->value)->exists();
|
||||
}
|
||||
|
||||
/** Die Website-Datei des Films ist freigegeben und wird tatsächlich ausgeliefert (WebsiteMedia). */
|
||||
private function isWebsiteReleased(ContentElement $element): bool
|
||||
{
|
||||
return app(WebsiteMedia::class)->present($element)?->kind === 'film';
|
||||
}
|
||||
|
||||
/**
|
||||
* Ö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 || $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* @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')
|
||||
->where(fn ($selectable) => $selectable
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->orWhere(fn ($websiteOnly) => $websiteOnly
|
||||
->where('output_class', 'film')
|
||||
->whereNotNull('preview_path')
|
||||
->where('preview_path', '!=', '')
|
||||
->whereDoesntHave('versions')))
|
||||
->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', 'teaser', 'summary', 'description', '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);
|
||||
}
|
||||
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null;
|
||||
|
||||
if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') {
|
||||
$own = $profile->value($field);
|
||||
}
|
||||
|
||||
$texts[$field] = $own;
|
||||
}
|
||||
|
||||
$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');
|
||||
}
|
||||
|
||||
$websiteOnly = $this->isWebsiteOnlyFilm($element);
|
||||
$meta = [$output];
|
||||
if ($program !== null) {
|
||||
$meta[] = 'Im Programm „'.$program['title'].'“';
|
||||
}
|
||||
if ($film && ! $websiteOnly) {
|
||||
$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',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
/** 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);
|
||||
|
||||
if ($program === null) {
|
||||
return 'Öffentlich mit der für die Website freigegebenen Datei, ohne Verweis auf eine Programmseite. Die Originaldatei wird nie ausgeliefert.';
|
||||
}
|
||||
|
||||
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->isWebsiteOnlyFilm($element) => 'Die Website-Datei ist nicht für die Website freigegeben (Medium öffnen → Reiter „Website“ → freigeben).',
|
||||
! $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 = match (true) {
|
||||
$this->isWebsiteOnlyFilm($element) => $this->isPublic($element)
|
||||
? 'öffentlich mit Website-Datei'
|
||||
: 'Website-Datei nicht freigegeben, nur Redaktionsvorschau',
|
||||
$this->isPublic($element) => 'öffentlich über Programmseite',
|
||||
$this->isReady($element) => 'nur Redaktionsvorschau',
|
||||
default => '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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1439 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user