Compare commits
280
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9041afda80 | ||
|
|
1691bd3871 | ||
|
|
1270e2e948 | ||
|
|
18ee22f37e | ||
|
|
edca8e864c | ||
|
|
580b27451c | ||
|
|
561c64fa16 | ||
|
|
3aed45a2fe | ||
|
|
e72c9ddb8d | ||
|
|
9f9370dbf8 | ||
|
|
b942b5331a | ||
|
|
58b68b768c | ||
|
|
765b8e779e | ||
|
|
81037b9868 | ||
|
|
8a44c5886b | ||
|
|
3e2fd872c2 | ||
|
|
c57a506f85 | ||
|
|
219962daff | ||
|
|
390d61feaa | ||
|
|
90c74ac03d | ||
|
|
b714dc8219 | ||
|
|
b7502ef696 | ||
|
|
45ea56b52d | ||
|
|
09889da099 | ||
|
|
3c7a71532f | ||
|
|
ad581cb545 | ||
|
|
99122ddfee | ||
|
|
9fbd933e1e | ||
|
|
be24f3bf64 | ||
|
|
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,72 @@
|
||||
# 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`).
|
||||
- Formatierte Texte (ADR-50): gespeichert wird bereinigtes HTML aus fester Auswahl, bearbeitet mit dem einen Editor `App\Filament\Support\RichField`, in den Arbeitsplätzen über `ManagesRichFields` (`richFelder()`, `kind => 'rich'`). Ausgabe nur über `App\Domain\Catalog\FormattedText` (`html()`, `display()`, `plain()`, `blocks()` fürs PDF), nie ungeprüft; verglichen wird nur `FormattedText::same()`/`canonical()`. Klartext des Altbestands bleibt in der Datenbank, bis jemand ihn ändert. Keine eigenen Textfelder mit `textarea` für Texte, die formatiert sein sollen.
|
||||
- Filter mit Mehrfachauswahl in Bestandslisten (z. B. Medienmanager): Baustein `verwaltung/bestand-filterdialog` über den Eintrag `filterdialog` in `bestand()` (Filterknopf neben der Suche, Pillen je wirksamem Feld, Dialog mit Entwurf der Auswahl: „Anwenden“ übernimmt, „Abbrechen“ verwirft). Mehrere Werte eines Felds gelten als ODER, verschiedene Felder als UND. Die Häkchen sind per `wire:model` an eine Liste im Entwurf gebunden (nie `wire:click` mit `@checked`: nach einer Serverantwort stimmt sonst die Anzeige nicht). Persönliche Standardfilter je Konto liegen in `user_view_defaults` (`UserViewDefault`). Texte, die für eine Übung angelegt werden, erhalten über `ExerciseSections::mark` die Materialart „Übungsabschnitt“ und den Verweis auf ihre Übung.
|
||||
- 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.
|
||||
- Dokumente (ADR-51): Kapitel sind Texte, die Dokumentfassung ist eine Komposition (`CompositionKind::Document`); bearbeitet wird im Aufbaueditor über den Kapitelarbeitsplatz (`ManagesDocumentChapters`, `verwaltung/dokument`), ausgegeben über `DocumentGuide` (Seite) und `DocumentPdf`. Formatierte Texte mit Tabellen und Bildern laufen nur über `FormattedText`, `RichField` und `EmbeddedImages` (ein Bild ist ein Verweis auf eine Bildfassung, nie eine Adresse); PDF-Satz nur über `PdfFlow`. Änderungen an `PdfDocument` müssen die Prüfsummen in `tests/Unit/PdfDocumentTest.php` einhalten (Belege byte-gleich). Das Aussehen des Dokument-PDF (Titelseite, Kopf, Fuß) kommt aus der `PdfTemplate` (Seite `PdfVorlagen`); Inhalt wie Ausgabe, Datum und Vermerk gehört in `document_meta` der Dokumentfassung, nicht in die Vorlage.
|
||||
- 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,69 @@
|
||||
<?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',
|
||||
'pdf_template_id',
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** Die PDF-Vorlage eines Dokuments; leer = bisheriges Layout (ADR-51). */
|
||||
public function pdfTemplate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PdfTemplate::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,115 @@
|
||||
<?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';
|
||||
/** Ein zusammenhängendes Dokument aus Kapiteln, zum Beispiel ein Trainerhandbuch (ADR-51). */
|
||||
case Document = 'document';
|
||||
|
||||
/**
|
||||
* @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',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
public function plural(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombinationen',
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
self::Document => 'Dokumente',
|
||||
};
|
||||
}
|
||||
|
||||
public function createLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Kombination anlegen',
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung anlegen',
|
||||
self::Document => 'Dokument 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.',
|
||||
self::Document => 'Ein zusammenhängendes Dokument, zum Beispiel ein Trainerhandbuch, aus Kapiteln und Unterkapiteln. Eine Fassung schreibt Reihenfolge und Texte fest; sie wird in Module und Programme aufgenommen und erscheint für Mitglieder mit Inhaltsverzeichnis und als PDF.',
|
||||
};
|
||||
}
|
||||
|
||||
public function deskLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
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, self::Document => $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,498 @@
|
||||
<?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,
|
||||
'document_meta' => $didactic['document_meta'] ?? 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,
|
||||
'document_meta' => $draft['document_meta'] ?? 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,83 @@
|
||||
<?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',
|
||||
'document_meta',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => ContentVersionStatus::class,
|
||||
'document_meta' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
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,66 @@
|
||||
<?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',
|
||||
'origin_composition_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'archived_at' => 'datetime',
|
||||
'website_released_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
/** Die Übung, für die dieser Textabschnitt angelegt wurde (nur bei Übungsabschnitten). */
|
||||
public function originComposition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class, 'origin_composition_id');
|
||||
}
|
||||
|
||||
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,121 @@
|
||||
<?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,
|
||||
], ...$this->embeddedImages($node, $path !== '' ? $path : $node->element->working_title, 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,
|
||||
];
|
||||
|
||||
foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) {
|
||||
$rows[] = $image;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilder, auf die ein Text verweist, gehören zum Inhalt des Stands: Nur was im Stand steht, darf ein Mitglied sehen
|
||||
* (`DecideAccess`), und eine Sperre des Bildes wirkt über denselben Weg. Ein fehlendes Bild macht den Text nicht
|
||||
* unbrauchbar, daher „ergänzend“.
|
||||
*
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
private function embeddedImages(?ContentElementVersion $text, string $path, ?string $variantKey): array
|
||||
{
|
||||
if ($text === null || trim((string) $text->body) === '' || ! str_contains((string) $text->body, 'img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
|
||||
foreach (FormattedText::imageIds($text->body) as $id) {
|
||||
$rows[] = [
|
||||
'version_id' => $id,
|
||||
'role' => 'Bild',
|
||||
'path' => $path.' / Bild',
|
||||
'requirement' => CompositionMember::SUPPLEMENTARY,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
}
|
||||
|
||||
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,607 @@
|
||||
<?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();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ändert den Text einer Fassung nur als Entwurf. Ist die Fassung schon festgeschrieben (in einer bereitgestellten
|
||||
* Komposition oder einem Stand), entsteht eine neue Entwurfsfassung und die festgeschriebene bleibt unverändert.
|
||||
* Anders als {@see self::reviseElementContent()} wird nichts bereitgestellt: Das geschieht erst mit der Fassung des
|
||||
* Dokuments.
|
||||
*/
|
||||
public function reviseElementDraft(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 ($version->status === ContentVersionStatus::Entwurf) {
|
||||
return $this->reviseElementContent($version, $body);
|
||||
}
|
||||
|
||||
// Eine bereitgestellte Fassung, die nirgends festgeschrieben ist, wird weiterhin an Ort und Stelle geändert.
|
||||
if (! $this->isCommitted($version)) {
|
||||
return $this->reviseElementContent($version, $body);
|
||||
}
|
||||
|
||||
return $this->draftElementVersion($version->element, $body);
|
||||
}
|
||||
|
||||
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.';
|
||||
}
|
||||
|
||||
if ($version->element?->output_class === 'text') {
|
||||
return $this->imageProblem((string) $version->body);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Text verweist auf Bildfassungen des Medienbestands. Festgeschrieben werden kann er nur, wenn jede davon
|
||||
* vorhanden, ein Bild und freigegeben ist; sonst wäre die Ausgabe der Fassung nicht festgelegt.
|
||||
*/
|
||||
public function imageProblem(?string $body): ?string
|
||||
{
|
||||
$ids = FormattedText::imageIds($body);
|
||||
|
||||
if ($ids === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$versions = ContentElementVersion::query()->with('element')->whereKey($ids)->get()->keyBy('id');
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$image = $versions->get($id);
|
||||
$title = $image?->element === null ? 'Bild' : (string) ($image->element->display_title ?: $image->element->working_title);
|
||||
|
||||
if ($image === null || $image->element === null || $image->element->output_class !== 'bild') {
|
||||
return 'Der Text verweist auf ein Bild, das es nicht mehr gibt.';
|
||||
}
|
||||
|
||||
if ($image->status === ContentVersionStatus::Gesperrt) {
|
||||
return 'Das Bild „'.$title.'“ ist deaktiviert und kann nicht festgeschrieben werden.';
|
||||
}
|
||||
|
||||
if ($image->status !== ContentVersionStatus::Bereit) {
|
||||
return 'Das Bild „'.$title.'“ ist noch nicht freigegeben.';
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
'document_meta' => DocumentMeta::normalize($didactic['document_meta'] ?? 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');
|
||||
|
||||
$meta = DocumentMeta::normalize($version->document_meta);
|
||||
|
||||
return hash('sha256', json_encode([
|
||||
'fields' => [
|
||||
$version->learning_goal,
|
||||
$version->duration_minutes,
|
||||
$version->duration_max,
|
||||
$version->material_note,
|
||||
$version->prerequisites,
|
||||
],
|
||||
// Nur wenn gesetzt: Der Nachweis älterer Fassungen ohne Dokumentangaben bleibt unverändert.
|
||||
...($meta === null ? [] : ['document' => $meta]),
|
||||
'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,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Kapitel eines Dokuments: Textabschnitte im gemeinsamen Medienbestand mit der automatischen Materialart „Dokumentkapitel“
|
||||
* und dem Verweis auf ihr Dokument (`origin_composition_id`), wie die Übungsabschnitte ({@see ExerciseSections}).
|
||||
*/
|
||||
final class DocumentChapters
|
||||
{
|
||||
public function kindId(): ?int
|
||||
{
|
||||
$id = EditorialContentKind::query()->where('slug', EditorialContentKind::DOCUMENT_CHAPTER_SLUG)->value('id');
|
||||
|
||||
return $id === null ? null : (int) $id;
|
||||
}
|
||||
|
||||
public function mark(ContentElement $element, Composition $document): void
|
||||
{
|
||||
$element->origin_composition_id = $document->getKey();
|
||||
|
||||
if ($element->editorial_content_kind_id === null) {
|
||||
$element->editorial_content_kind_id = $this->kindId();
|
||||
}
|
||||
|
||||
$element->save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Das Dokument, wie ein Stand es festschreibt: die im Stand gebundene Dokumentfassung mit ihren Kapiteln und je Kapitel die
|
||||
* Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und PDF lesen dieses Ergebnis; beide zeigen dieselbe
|
||||
* Kapitelreihenfolge und dieselben gebundenen Textfassungen. Eine spätere Bearbeitung des Dokuments ändert einen älteren Stand
|
||||
* nicht: Der Stand verweist auf die Fassung, die er festgeschrieben hat.
|
||||
*/
|
||||
class DocumentGuide
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DecideAccess $access,
|
||||
private readonly DocumentReader $reader,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $document): array
|
||||
{
|
||||
$document->loadMissing('composition');
|
||||
$library = app(LibraryCatalog::class);
|
||||
$embedded = app(EmbeddedImages::class);
|
||||
$chapters = [];
|
||||
|
||||
foreach ($this->reader->fromVersion($document) as $chapter) {
|
||||
$version = $chapter['version'];
|
||||
$view = ($this->access)($user, $article, $release, $version, 'ansehen');
|
||||
$download = ($this->access)($user, $article, $release, $version, 'laden');
|
||||
|
||||
$entry = [
|
||||
'number' => $chapter['number'],
|
||||
'level' => $chapter['level'],
|
||||
'anchor' => $chapter['anchor'],
|
||||
'title' => $chapter['title'],
|
||||
'version' => $version,
|
||||
'allowed' => $view->allowed,
|
||||
'grant' => $view->grant,
|
||||
'may_download' => $download->allowed,
|
||||
'download_grant' => $download->grant,
|
||||
'state' => $view->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'html' => null,
|
||||
'blocks' => $view->allowed ? FormattedText::blocks($version->body) : null,
|
||||
];
|
||||
$entry['html'] = $view->allowed ? self::anchoredHtml($entry, FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version))) : null;
|
||||
$chapters[] = self::withHeadings($entry);
|
||||
}
|
||||
|
||||
$text = $library->text($document->composition);
|
||||
|
||||
return [
|
||||
'document' => $document,
|
||||
'title' => $text['title'],
|
||||
'summary_html' => $text['summary_html'],
|
||||
'pdf_template' => $document->composition->pdfTemplate,
|
||||
'meta' => DocumentMeta::normalize($document->document_meta),
|
||||
'chapters' => $chapters,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Um wie viele Stufen die Zwischenüberschriften eines Kapitels nach unten rücken: Im Kapitel (h2) bleiben h3 bis h6 wie
|
||||
* geschrieben, unter einem Unterkapitel (h3) rücken sie eine Stufe tiefer (höchstens h6). So steht nie eine Überschrift
|
||||
* des Texts auf der Stufe des Kapitels oder Unterkapitels, zu dem sie gehört.
|
||||
*/
|
||||
public static function headingShift(int $chapterLevel): int
|
||||
{
|
||||
return $chapterLevel >= 2 ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das HTML eines Kapitels mit Sprungmarken an den Zwischenüberschriften und der Stufe, die zum Kapitel passt.
|
||||
*
|
||||
* @param array<string, mixed> $chapter
|
||||
*/
|
||||
public static function anchoredHtml(array $chapter, string $html): string
|
||||
{
|
||||
return FormattedText::anchorHeadings($html, (string) $chapter['anchor'], self::headingShift((int) $chapter['level']))['html'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ergänzt ein Kapitel um seine Zwischenüberschriften (`headings`: Stufe, Text, Sprungmarke) für das Inhaltsverzeichnis und
|
||||
* legt Stufe und Sprungmarke in die Überschriftenblöcke des PDF. Ansicht und PDF zählen gleich; sie lesen beide diese Liste.
|
||||
*
|
||||
* @param array<string, mixed> $chapter
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function withHeadings(array $chapter): array
|
||||
{
|
||||
$shift = self::headingShift((int) $chapter['level']);
|
||||
$headings = [];
|
||||
$blocks = $chapter['blocks'] ?? null;
|
||||
|
||||
foreach (is_array($blocks) ? $blocks : [] as $index => $block) {
|
||||
if ($block['type'] !== 'heading' || trim((string) ($block['text'] ?? '')) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = min(6, (int) $block['level'] + $shift);
|
||||
$anchor = $chapter['anchor'].'-u'.(count($headings) + 1);
|
||||
$blocks[$index]['level'] = $level;
|
||||
$blocks[$index]['anchor'] = $anchor;
|
||||
$headings[] = ['level' => $level, 'text' => (string) $block['text'], 'anchor' => $anchor];
|
||||
}
|
||||
|
||||
$chapter['blocks'] = is_array($blocks) ? $blocks : null;
|
||||
$chapter['headings'] = $headings;
|
||||
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Darf das PDF entstehen? Jedes Kapitel muss für `laden` zulässig sein; sonst fehlte ein Teil des Handbuchs.
|
||||
*
|
||||
* @param array<string, mixed> $guide
|
||||
*/
|
||||
public function pdfAllowed(array $guide): bool
|
||||
{
|
||||
if ($guide['chapters'] === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
if (! $chapter['allowed'] || ! $chapter['may_download']) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Angaben einer Dokumentfassung für Titelseite und Impressum des PDF: Untertitel, Ausgabe (Release), Veröffentlichungsdatum und
|
||||
* Copyright-Vermerk. Sie liegen als Teil der Fassung in `composition_versions.document_meta` und ändern sich nur mit einer neuen
|
||||
* Fassung. Alle Felder sind Klartext; ein leeres Feld entfällt.
|
||||
*/
|
||||
final class DocumentMeta
|
||||
{
|
||||
public const FIELDS = ['subtitle', 'edition', 'published_on', 'copyright'];
|
||||
|
||||
/**
|
||||
* Bereinigte Angaben: nur die bekannten Felder, getrimmt, ohne leere Werte; ein Datum nur als `YYYY-MM-DD`. Null, wenn nichts gesetzt ist.
|
||||
*
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
public static function normalize(mixed $value): ?array
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$clean = [];
|
||||
|
||||
foreach (self::FIELDS as $field) {
|
||||
$text = trim((string) ($value[$field] ?? ''));
|
||||
|
||||
if ($field === 'published_on') {
|
||||
$text = preg_match('/^\d{4}-\d{2}-\d{2}$/', $text) === 1 ? $text : '';
|
||||
}
|
||||
|
||||
if ($text !== '') {
|
||||
$clean[$field] = mb_substr($text, 0, $field === 'copyright' ? 600 : 200);
|
||||
}
|
||||
}
|
||||
|
||||
return $clean === [] ? null : $clean;
|
||||
}
|
||||
|
||||
/** Das Veröffentlichungsdatum in deutscher Schreibweise, oder leer. */
|
||||
public static function publishedLabel(?array $meta): string
|
||||
{
|
||||
$date = $meta['published_on'] ?? '';
|
||||
|
||||
return $date === '' ? '' : CarbonImmutable::parse($date)->format('d.m.Y');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Gliederung eines Dokuments (ADR-51). Ein Dokument ist eine flache Folge von Kapiteln; die Ebene steht in der Rolle des
|
||||
* Mitglieds: „Kapitel“ (Ebene 1) oder „Unterkapitel“ (Ebene 2). Ein Unterkapitel gehört zum Kapitel davor. Die Nummern
|
||||
* („3“, „3.2“) entstehen aus der Reihenfolge und werden nirgends gespeichert; Editor, Ansicht und PDF zählen gleich.
|
||||
*/
|
||||
final class DocumentOutline
|
||||
{
|
||||
public const CHAPTER = 'Kapitel';
|
||||
|
||||
public const SUBCHAPTER = 'Unterkapitel';
|
||||
|
||||
public static function level(?string $role): int
|
||||
{
|
||||
return trim((string) $role) === self::SUBCHAPTER ? 2 : 1;
|
||||
}
|
||||
|
||||
public static function role(int $level): string
|
||||
{
|
||||
return $level >= 2 ? self::SUBCHAPTER : self::CHAPTER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ebene und Nummer je Eintrag. Ein Unterkapitel ohne Kapitel davor zählt als Kapitel.
|
||||
*
|
||||
* @param list<string> $roles
|
||||
* @return list<array{level: int, number: string, anchor: string}>
|
||||
*/
|
||||
public static function numbering(array $roles): array
|
||||
{
|
||||
$chapter = 0;
|
||||
$sub = 0;
|
||||
$out = [];
|
||||
|
||||
foreach ($roles as $role) {
|
||||
$level = self::level($role);
|
||||
|
||||
if ($level === 2 && $chapter === 0) {
|
||||
$level = 1;
|
||||
}
|
||||
|
||||
if ($level === 1) {
|
||||
$chapter++;
|
||||
$sub = 0;
|
||||
$number = (string) $chapter;
|
||||
} else {
|
||||
$sub++;
|
||||
$number = $chapter.'.'.$sub;
|
||||
}
|
||||
|
||||
$out[] = ['level' => $level, 'number' => $number, 'anchor' => 'kapitel-'.str_replace('.', '-', $number)];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Letzter Index des Blocks, den der Eintrag bei `$index` mit seinen Unterkapiteln bildet.
|
||||
*
|
||||
* @param list<string> $roles
|
||||
*/
|
||||
public static function blockEnd(array $roles, int $index): int
|
||||
{
|
||||
if (self::numbering($roles)[$index]['level'] === 2) {
|
||||
return $index;
|
||||
}
|
||||
|
||||
$end = $index;
|
||||
|
||||
for ($i = $index + 1; $i < count($roles); $i++) {
|
||||
if (self::level($roles[$i]) !== 2) {
|
||||
break;
|
||||
}
|
||||
|
||||
$end = $i;
|
||||
}
|
||||
|
||||
return $end;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use App\Domain\Media\PdfImage;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Druckbare Ausgabe eines Dokuments (DIN A4) aus demselben Ergebnis wie die Ansicht ({@see DocumentGuide}): anklickbares
|
||||
* Inhaltsverzeichnis samt Seitenzahlen, jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite, Lesezeichen für die
|
||||
* Gliederung des PDF-Betrachters. Fußzeile mit Lizenznehmer, Lizenzkopie und „Seite n von m“ auf jeder Seite (K2), die Kennung
|
||||
* in den Metadaten (K1). Die Datei wird bei jedem Abruf neu erzeugt und nie abgelegt.
|
||||
*
|
||||
* Vorlage (ADR-51, Nachtrag): Ist dem Dokument eine {@see PdfTemplate} zugeordnet, steht der Titel allein auf einer eigenen
|
||||
* Titelseite (mit Untertitel, Ausgabe, Veröffentlichungsdatum, Herausgeber und Copyright-Vermerk), und Kopf und Fuß aller
|
||||
* weiteren Seiten tragen die gewählten Grafiken. Die Angaben kommen aus der Dokumentfassung ({@see DocumentMeta}). Ohne Vorlage
|
||||
* beginnt das Inhaltsverzeichnis wie bisher unter dem Titel auf der ersten Seite.
|
||||
*
|
||||
* Seitenzahlen stehen erst nach dem Satz fest. Der Satz läuft deshalb so oft, bis Inhaltsverzeichnis, Kapitelanfänge und
|
||||
* Seitenzahl sich nicht mehr ändern (in der Regel zweimal).
|
||||
*/
|
||||
class DocumentPdf
|
||||
{
|
||||
private const LEFT = 56.0;
|
||||
|
||||
private const RIGHT = 539.0;
|
||||
|
||||
private const PAGE_HEIGHT = 842.0;
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private PdfFlow $flow;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
private string $footer = '';
|
||||
|
||||
private int $total = 0;
|
||||
|
||||
private bool $onCover = false;
|
||||
|
||||
/** Das erste Kapitel setzt die Seite fort, statt eine neue zu beginnen (ohne Inhaltsverzeichnis). */
|
||||
private bool $continueFirst = false;
|
||||
|
||||
/** Obere und untere Grenze des Textes, abhängig von den Grafiken der Vorlage. */
|
||||
private float $top = 790.0;
|
||||
|
||||
private float $bottom = 72.0;
|
||||
|
||||
/** Höhe der Fußlinie über dem Seitenrand. */
|
||||
private float $footerLine = 54.0;
|
||||
|
||||
/** @var array{header: ?array<string, mixed>, footer: ?array<string, mixed>, cover: ?array<string, mixed>} Grafiken samt Maßen, siehe {@see self::band()} */
|
||||
private array $bands = ['header' => null, 'footer' => null, 'cover' => null];
|
||||
|
||||
/** @var array<string, array{page: int, top: float}> */
|
||||
private array $starts = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $guide Ergebnis von {@see DocumentGuide::build}; `pdf_template` und `meta` sind optional
|
||||
*/
|
||||
public function render(array $guide, string $licensee, string $copyId, ?PdfImages $images = null): string
|
||||
{
|
||||
$template = ($guide['pdf_template'] ?? null) instanceof PdfTemplate ? $guide['pdf_template'] : null;
|
||||
$this->prepareLayout($template);
|
||||
$starts = [];
|
||||
$total = 0;
|
||||
$bytes = '';
|
||||
|
||||
for ($pass = 0; $pass < 5; $pass++) {
|
||||
$bytes = $this->pass($guide, $template, $licensee, $copyId, $images, $starts, $total);
|
||||
|
||||
if ($this->starts === $starts && $this->total === $total) {
|
||||
break;
|
||||
}
|
||||
|
||||
$starts = $this->starts;
|
||||
$total = $this->total;
|
||||
}
|
||||
|
||||
return $bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bereitet die Grafiken der Vorlage auf und legt Ränder fest: Kopf und Fuß in voller Seitenbreite (höchstens 140 Punkt hoch),
|
||||
* der Text beginnt unter dem Kopf und endet über dem Fuß.
|
||||
*/
|
||||
private function prepareLayout(?PdfTemplate $template): void
|
||||
{
|
||||
$this->bands = [
|
||||
'header' => $this->band($template?->target('header'), 140.0, 'header', $template?->layout('header')),
|
||||
'footer' => $this->band($template?->target('footer'), 140.0, 'footer', $template?->layout('footer')),
|
||||
'cover' => $template !== null && $template->show_cover ? $this->band($template->target('cover'), self::PAGE_HEIGHT * 0.4, 'cover') : null,
|
||||
];
|
||||
$header = (float) ($this->bands['header']['occupied'] ?? 0);
|
||||
$footer = (float) ($this->bands['footer']['occupied'] ?? 0);
|
||||
$this->top = $header > 0 ? min(790.0, self::PAGE_HEIGHT - $header - 26.0) : 790.0;
|
||||
$this->footerLine = max(54.0, $footer + 24.0);
|
||||
$this->bottom = $this->footerLine + 18.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Grafik für Kopf, Fuß oder Titelseite. Als Band steht sie in Seitenbreite (bei zu großer Höhe verkleinert und zentriert),
|
||||
* als Logo hat sie die gewählte Höhe und steht am linken oder rechten Textrand, höchstens halb so breit wie der Text.
|
||||
* `occupied` ist die Höhe, die sie am Seitenrand belegt; `y` die Unterkante.
|
||||
*
|
||||
* @param array{align: string, height: int}|null $layout nur für Kopf und Fuß
|
||||
* @return array{jpeg: string, pixelWidth: int, pixelHeight: int, width: float, height: float, x: float, y: float, occupied: float}|null
|
||||
*/
|
||||
private function band(?string $target, float $maxHeight, string $edge, ?array $layout = null): ?array
|
||||
{
|
||||
$bytes = TemplateImage::bytes($target);
|
||||
$image = $bytes === null ? null : PdfImage::fromBytes($bytes);
|
||||
|
||||
if ($image === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ratio = $image['width'] / max(1, $image['height']);
|
||||
$align = $layout['align'] ?? 'full';
|
||||
$common = ['jpeg' => $image['jpeg'], 'pixelWidth' => $image['width'], 'pixelHeight' => $image['height']];
|
||||
|
||||
if ($edge !== 'cover' && $align !== 'full') {
|
||||
$height = (float) ($layout['height'] ?? PdfTemplate::LOGO_DEFAULT);
|
||||
$width = $height * $ratio;
|
||||
|
||||
if ($width > (self::RIGHT - self::LEFT) / 2) {
|
||||
$width = (self::RIGHT - self::LEFT) / 2;
|
||||
$height = $width / $ratio;
|
||||
}
|
||||
|
||||
$padding = $edge === 'header' ? 24.0 : 14.0;
|
||||
|
||||
return $common + [
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'x' => $align === 'left' ? self::LEFT : self::RIGHT - $width,
|
||||
'y' => $edge === 'header' ? self::PAGE_HEIGHT - $padding - $height : $padding,
|
||||
'occupied' => $height + $padding,
|
||||
];
|
||||
}
|
||||
|
||||
$width = (float) PdfDocument::WIDTH;
|
||||
$height = $width / $ratio;
|
||||
|
||||
if ($height > $maxHeight) {
|
||||
$height = $maxHeight;
|
||||
$width = $height * $ratio;
|
||||
}
|
||||
|
||||
return $common + [
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'x' => (PdfDocument::WIDTH - $width) / 2,
|
||||
'y' => $edge === 'header' ? self::PAGE_HEIGHT - $height : 0.0,
|
||||
'occupied' => $height,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $guide
|
||||
* @param array<string, array{page: int, top: float}> $known Kapitelanfänge aus dem vorigen Durchgang
|
||||
*/
|
||||
private function pass(array $guide, ?PdfTemplate $template, string $licensee, string $copyId, ?PdfImages $images, array $known, int $total): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->starts = [];
|
||||
$this->onCover = false;
|
||||
$this->footer = PdfFlow::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, $this->top, $this->bottom, function (): void {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}, $images === null ? null : Closure::fromCallable($images));
|
||||
$this->flow->onHeading = function (array $block, float $top): void {
|
||||
$this->starts[$block['anchor']] = ['page' => $this->page, 'top' => $top];
|
||||
$this->pdf->bookmark((string) $block['text'], $this->page - 1, $top, (int) $block['level'] - 1);
|
||||
};
|
||||
$this->total = $total;
|
||||
$withCover = $template !== null && $template->show_cover;
|
||||
|
||||
if ($withCover) {
|
||||
$this->onCover = true;
|
||||
$this->newPage();
|
||||
$this->cover($guide, $template);
|
||||
$this->closePage();
|
||||
$this->onCover = false;
|
||||
$this->newPage();
|
||||
} else {
|
||||
$this->newPage();
|
||||
$this->flow->write(PdfFlow::printable((string) $guide['title']), 24, true, 10);
|
||||
}
|
||||
|
||||
$setting = PdfTemplate::normalizeToc($template?->toc_mode, $template?->toc_depth);
|
||||
$entries = $this->contents($guide, $setting['depth']);
|
||||
$withContents = match ($setting['mode']) {
|
||||
'never' => false,
|
||||
'always' => true,
|
||||
default => count($entries) > 1,
|
||||
};
|
||||
$this->continueFirst = ! $withContents;
|
||||
|
||||
if ($withContents) {
|
||||
$this->flow->write('Inhaltsverzeichnis', 14, true, 8, keep: 40);
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$this->contentsLine($entry, $known[$entry['anchor']] ?? ['page' => 1, 'top' => $this->top]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
$this->chapter($chapter);
|
||||
}
|
||||
|
||||
$this->closePage();
|
||||
$total = $this->page;
|
||||
$starts = $this->starts;
|
||||
$bytes = $this->pdf->output($this->asciiTitle((string) $guide['title']), 'Lizenzkopie '.$copyId);
|
||||
$this->total = $total;
|
||||
$this->starts = $starts;
|
||||
|
||||
return $bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Titelseite: Bild (falls gewählt), Titel allein, Untertitel, dann Ausgabe, Veröffentlichung und Herausgeber, unten der
|
||||
* Copyright-Vermerk. Die Vermerke der Fassung gehen dem Standard der Vorlage vor.
|
||||
*
|
||||
* @param array<string, mixed> $guide
|
||||
*/
|
||||
private function cover(array $guide, PdfTemplate $template): void
|
||||
{
|
||||
$meta = is_array($guide['meta'] ?? null) ? $guide['meta'] : [];
|
||||
$y = self::PAGE_HEIGHT - 150.0;
|
||||
|
||||
if ($this->bands['cover'] !== null) {
|
||||
$cover = $this->bands['cover'];
|
||||
$this->pdf->image($cover['x'], self::PAGE_HEIGHT - $cover['height'], $cover['width'], $cover['height'], $cover['jpeg'], $cover['pixelWidth'], $cover['pixelHeight']);
|
||||
$y = self::PAGE_HEIGHT - $cover['height'] - 90.0;
|
||||
}
|
||||
|
||||
$this->coverText(PdfFlow::printable((string) $guide['title']), 30.0, true, $y, 12.0);
|
||||
|
||||
if (filled($meta['subtitle'] ?? null)) {
|
||||
$this->coverText(PdfFlow::printable((string) $meta['subtitle']), 15.0, false, $y, 8.0);
|
||||
}
|
||||
|
||||
$y -= 26.0;
|
||||
$facts = array_filter([
|
||||
filled($meta['edition'] ?? null) ? $meta['edition'] : null,
|
||||
DocumentMeta::publishedLabel($meta) !== '' ? 'Veröffentlicht am '.DocumentMeta::publishedLabel($meta) : null,
|
||||
filled($template->publisher) ? 'Herausgeber: '.$template->publisher : null,
|
||||
]);
|
||||
|
||||
foreach ($facts as $fact) {
|
||||
$this->coverText(PdfFlow::printable((string) $fact), 11.0, false, $y, 4.0);
|
||||
}
|
||||
|
||||
$copyright = trim((string) ($meta['copyright'] ?? '')) !== '' ? (string) $meta['copyright'] : (string) $template->copyright;
|
||||
|
||||
if (trim($copyright) !== '') {
|
||||
$lines = PdfDocument::wrap(PdfFlow::printable($copyright), self::RIGHT - self::LEFT, 8.5, false);
|
||||
$at = $this->footerLine + 24.0 + (count($lines) - 1) * 12.0;
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$this->pdf->text(self::LEFT, $at, $line, 8.5);
|
||||
$at -= 12.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function coverText(string $text, float $size, bool $bold, float &$y, float $after): void
|
||||
{
|
||||
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
|
||||
$this->pdf->text(self::LEFT, $y, $line, $size, $bold);
|
||||
$y -= $size + 6.0;
|
||||
}
|
||||
|
||||
$y -= $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Einträge des Inhaltsverzeichnisses in der Reihenfolge des Dokuments: Kapitel und Unterkapitel mit Nummer, darunter
|
||||
* ihre Zwischenüberschriften (h3 bis h6) bis zur gewählten Tiefe, eingerückt nach Stufe. Die Lesezeichen im PDF zeigen
|
||||
* unabhängig davon alle Ebenen.
|
||||
*
|
||||
* @param array<string, mixed> $guide
|
||||
* @param int $depth höchste Überschriftenstufe im Verzeichnis (2 = nur Kapitel)
|
||||
* @return list<array{anchor: string, label: string, size: float, indent: float, bold: bool}>
|
||||
*/
|
||||
private function contents(array $guide, int $depth = 6): array
|
||||
{
|
||||
$entries = [];
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
$entries[] = [
|
||||
'anchor' => $chapter['anchor'],
|
||||
'label' => $chapter['number'].' '.$chapter['title'],
|
||||
'size' => $chapter['level'] === 1 ? 11.0 : 10.0,
|
||||
'indent' => $chapter['level'] === 1 ? 0.0 : 18.0,
|
||||
'bold' => $chapter['level'] === 1,
|
||||
];
|
||||
|
||||
foreach ($chapter['headings'] ?? [] as $heading) {
|
||||
if ($heading['level'] > $depth) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$entries[] = ['anchor' => $heading['anchor'], 'label' => $heading['text'], 'size' => 9.5, 'indent' => 18.0 + ($heading['level'] - 3) * 12.0, 'bold' => false];
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Zeile des Inhaltsverzeichnisses: Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Eintrag.
|
||||
*
|
||||
* @param array{anchor: string, label: string, size: float, indent: float, bold: bool} $entry
|
||||
* @param array{page: int, top: float} $target
|
||||
*/
|
||||
private function contentsLine(array $entry, array $target): void
|
||||
{
|
||||
$size = $entry['size'];
|
||||
$indent = $entry['indent'];
|
||||
$bold = $entry['bold'];
|
||||
$label = PdfFlow::printable($entry['label']);
|
||||
$pageText = (string) $target['page'];
|
||||
$numberWidth = PdfDocument::exactWidth($pageText, $size, false);
|
||||
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $bold);
|
||||
$x = self::LEFT + $indent;
|
||||
$this->flow->room(count($lines) * ($size + 4) + 2);
|
||||
$top = $this->flow->y;
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
$this->pdf->text($x, $this->flow->y, $line, $size, $bold);
|
||||
|
||||
if ($index === count($lines) - 1) {
|
||||
$used = PdfDocument::exactWidth($line, $size, $bold) + 4;
|
||||
$room = self::RIGHT - $numberWidth - 4 - ($x + $used);
|
||||
$dots = (int) floor($room / PdfDocument::exactWidth('.', 8, false));
|
||||
|
||||
if ($dots > 2) {
|
||||
$this->pdf->text($x + $used, $this->flow->y, str_repeat('.', $dots), 8);
|
||||
}
|
||||
|
||||
$this->pdf->textRight(self::RIGHT, $this->flow->y, $pageText, $size);
|
||||
}
|
||||
|
||||
$this->flow->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->pdf->link(self::LEFT, $this->flow->y + 2, self::RIGHT - self::LEFT, $top - $this->flow->y, max(0, $target['page'] - 1), $target['top']);
|
||||
$this->flow->y -= 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $chapter
|
||||
*/
|
||||
private function chapter(array $chapter): void
|
||||
{
|
||||
$level = $chapter['level'];
|
||||
|
||||
if ($level === 1 && ! $this->continueFirst) {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}
|
||||
|
||||
$this->continueFirst = false;
|
||||
$size = $level === 1 ? 18.0 : 13.5;
|
||||
$title = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
|
||||
$this->flow->room(($size + 4) + 60);
|
||||
$top = $this->flow->y + $size;
|
||||
$this->starts[$chapter['anchor']] = ['page' => $this->page, 'top' => $top];
|
||||
$this->pdf->bookmark($chapter['number'].' '.$chapter['title'], $this->page - 1, $top, $level);
|
||||
$this->flow->y -= $level === 1 ? 0 : 6;
|
||||
$this->flow->write($title, $size, true, $level === 1 ? 10 : 5, keep: 40);
|
||||
|
||||
if (! $chapter['allowed']) {
|
||||
$this->flow->write('Dieses Kapitel ist derzeit nicht verfügbar.', 10.5, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->flow->formatted($chapter['blocks'] ?? []);
|
||||
$this->flow->y -= 4;
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->flow->restart();
|
||||
|
||||
if (! $this->onCover && $this->bands['header'] !== null) {
|
||||
$band = $this->bands['header'];
|
||||
$this->pdf->image($band['x'], $band['y'], $band['width'], $band['height'], $band['jpeg'], $band['pixelWidth'], $band['pixelHeight']);
|
||||
}
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
{
|
||||
if (! $this->onCover && $this->bands['footer'] !== null) {
|
||||
$band = $this->bands['footer'];
|
||||
$this->pdf->image($band['x'], $band['y'], $band['width'], $band['height'], $band['jpeg'], $band['pixelWidth'], $band['pixelHeight']);
|
||||
}
|
||||
|
||||
$this->pdf->line(self::LEFT, $this->footerLine, self::RIGHT, $this->footerLine, 0.4);
|
||||
$this->pdf->text(self::LEFT, $this->footerLine - 14.0, $this->footer, 8);
|
||||
$this->pdf->textRight(self::RIGHT, $this->footerLine - 14.0, 'Seite '.$this->page.($this->total > 0 ? ' von '.$this->total : ''), 8);
|
||||
}
|
||||
|
||||
private function asciiTitle(string $title): string
|
||||
{
|
||||
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
|
||||
return $ascii?->transliterate($title) ?: 'Dokument';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Liest die Kapitel eines Dokuments in ihrer Reihenfolge: aus einer Fassung (gebundene Textfassungen) oder aus dem
|
||||
* gespeicherten Entwurf (jeweils verwiesene Fassung). Ansicht, PDF und Vorschau zählen dadurch dieselben Kapitel und
|
||||
* Nummern ({@see DocumentOutline}).
|
||||
*/
|
||||
final class DocumentReader
|
||||
{
|
||||
/**
|
||||
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
|
||||
*/
|
||||
public function fromVersion(CompositionVersion $document): array
|
||||
{
|
||||
$document->loadMissing('members.contentElementVersion.element');
|
||||
$items = [];
|
||||
|
||||
foreach ($document->members as $member) {
|
||||
if ($member->contentElementVersion !== null) {
|
||||
$items[] = ['role' => (string) $member->role, 'version' => $member->contentElementVersion];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->number($items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Der gespeicherte Entwurf; ohne Entwurf die letzte bereitgestellte Fassung. Null, wenn beides fehlt.
|
||||
*
|
||||
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>|null
|
||||
*/
|
||||
public function forStaff(Composition $document): ?array
|
||||
{
|
||||
$draft = app(EditorialWorkingDraft::class)->read($document);
|
||||
|
||||
if ($draft === null) {
|
||||
$ready = $document->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
|
||||
return $ready instanceof CompositionVersion ? $this->fromVersion($ready) : null;
|
||||
}
|
||||
|
||||
$items = [];
|
||||
|
||||
foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) {
|
||||
if (! is_array($member) || preg_match('/^element:(\d+)$/', (string) ($member['target'] ?? ''), $match) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = ContentElementVersion::query()->with('element')->find($match[1]);
|
||||
|
||||
if ($version instanceof ContentElementVersion && $version->element !== null) {
|
||||
$items[] = ['role' => (string) ($member['role'] ?? ''), 'version' => $version];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->number($items);
|
||||
}
|
||||
|
||||
public static function title(ContentElementVersion $version): string
|
||||
{
|
||||
$element = $version->element;
|
||||
|
||||
return $element === null ? 'Kapitel' : (filled($element->display_title) ? (string) $element->display_title : (string) $element->working_title);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{role: string, version: ContentElementVersion}> $items
|
||||
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
|
||||
*/
|
||||
private function number(array $items): array
|
||||
{
|
||||
$numbering = DocumentOutline::numbering(array_column($items, 'role'));
|
||||
|
||||
return array_map(fn (array $item, array $number): array => $number + [
|
||||
'role' => DocumentOutline::role($number['level']),
|
||||
'title' => self::title($item['version']),
|
||||
'version' => $item['version'],
|
||||
], $items, $numbering);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class DomainRuleException extends RuntimeException {}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?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',
|
||||
'dokument' => 'Dokument',
|
||||
'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', 'dokument', 'traineranleitung', self::EXERCISE_SECTION_SLUG, self::DOCUMENT_CHAPTER_SLUG];
|
||||
|
||||
/**
|
||||
* Textabschnitte einer Übung. Die Materialart wird nur automatisch gesetzt (ExerciseSections) und hat deshalb
|
||||
* keinen wählbaren Kontext.
|
||||
*/
|
||||
public const EXERCISE_SECTION_SLUG = 'uebungsabschnitt';
|
||||
|
||||
/** Kapitel eines Dokuments: wie Übungsabschnitte nur automatisch gesetzt, nie öffentlich (ADR-51). */
|
||||
public const DOCUMENT_CHAPTER_SLUG = 'dokumentkapitel';
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** Wird nie von Hand gewählt, sondern von der Übungsverwaltung gesetzt. */
|
||||
public function isAutomatic(): bool
|
||||
{
|
||||
return in_array($this->slug, [self::EXERCISE_SECTION_SLUG, self::DOCUMENT_CHAPTER_SLUG], 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,74 @@
|
||||
<?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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text einer Angabe. Formatierte Angaben (Kurzbeschreibung, Beschreibung) kommen hier als Klartext, damit nirgends
|
||||
* Auszeichnung in Karten, Listen, Suchergebnisse oder Meta-Angaben gelangt; wer die Formatierung zeigt, nutzt
|
||||
* {@see self::html()}.
|
||||
*/
|
||||
public function value(string $field): ?string
|
||||
{
|
||||
$value = $this->text($field)->value;
|
||||
|
||||
if ($value !== null && in_array($field, FormattedText::FIELDS, true)) {
|
||||
return FormattedText::plain($value) ?: null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** Gespeicherter Wert unverändert (HTML oder Klartext des Altbestands), für Bearbeitung und Vergleich. */
|
||||
public function raw(string $field): ?string
|
||||
{
|
||||
return $this->text($field)->value;
|
||||
}
|
||||
|
||||
/** Sicheres HTML einer formatierten Angabe; leer, wenn nichts da ist. */
|
||||
public function html(string $field): string
|
||||
{
|
||||
return FormattedText::html($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,298 @@
|
||||
<?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',
|
||||
CompositionKind::Document => 'dokument',
|
||||
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
|
||||
{
|
||||
// Die automatische Art hat bewusst keinen wählbaren Kontext; das ist kein Mangel der Zuordnung.
|
||||
if ($kind->isAutomatic() && $kind->is_active) {
|
||||
return (string) $kind->label;
|
||||
}
|
||||
|
||||
return (string) $kind->label
|
||||
.(! $kind->is_active ? self::INACTIVE_SUFFIX : (! $kind->allows($context) ? self::OUT_OF_CONTEXT_SUFFIX : ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialarten für die Mehrfachauswahl im Medienmanager: im Kontext zulässige Arten, Arten, die bei Medien
|
||||
* tatsächlich vorkommen, und die automatische Art „Übungsabschnitt“. Die Reihenfolge folgt der Pflege, die
|
||||
* automatische Art steht zuletzt. „Ohne Materialart“ ergänzt der Medienmanager.
|
||||
*
|
||||
* @param list<int> $selectedIds bereits gewählte Arten bleiben sichtbar
|
||||
* @return list<array{id: int, label: string, automatic: bool}>
|
||||
*/
|
||||
public function mediumKindChoices(array $selectedIds = []): array
|
||||
{
|
||||
$used = $this->usedKindIds('medium');
|
||||
$regular = [];
|
||||
$automatic = [];
|
||||
|
||||
foreach (EditorialContentKind::query()->orderBy('sort_order')->orderBy('id')->get() as $kind) {
|
||||
$id = (int) $kind->id;
|
||||
$show = $kind->isAutomatic()
|
||||
|| ($kind->allows('medium') && $kind->is_active)
|
||||
|| in_array($id, $used, true)
|
||||
|| in_array($id, $selectedIds, true);
|
||||
|
||||
if (! $show) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$row = ['id' => $id, 'label' => $this->kindLabel($kind, 'medium'), 'automatic' => $kind->isAutomatic()];
|
||||
|
||||
if ($kind->isAutomatic()) {
|
||||
$automatic[] = $row;
|
||||
} else {
|
||||
$regular[] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return [...$regular, ...$automatic];
|
||||
}
|
||||
|
||||
/**
|
||||
* @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),
|
||||
'dokument' => DB::table('compositions')->where('kind', CompositionKind::Document->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,191 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Media\PdfImage;
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Bilder in formatierten Texten (ADR-51). Ein Text verweist auf eine Bildfassung; ob und wie sie erscheint, entscheidet
|
||||
* hier für den Stand des Mitglieds:
|
||||
*
|
||||
* - Ein Bild im Text gehört zum Text. Wer den Text ansehen (PDF: laden) darf, darf die Bilder darin sehen. Es braucht kein
|
||||
* eigenes Recht für Bilder; bestehende Berechtigungen, die nur Texte nennen, zeigen die Bilder der Texte mit. Die Rechte
|
||||
* des Texts entscheidet wie überall `DecideAccess`.
|
||||
* - Das Bild muss zum festgeschriebenen Inhalt des Stands gehören ({@see ContentResolver}: ein Bild im Text steht als
|
||||
* ergänzende Zeile im Stand) und im Text tatsächlich vorkommen. So gibt die Adresse kein anderes Bild frei.
|
||||
* - Eine Sperre der Bildfassung wirkt: Das Bild entfällt, der Text bleibt lesbar.
|
||||
*
|
||||
* Ansicht: eine Adresse ohne Ablauf, die bei jedem Abruf neu entscheidet und die Datei ausliefert (`member.stand.image`);
|
||||
* eine lange Lektüre darf nicht an einer kurzlebigen Signatur scheitern. PDF: das Bild wird aus dem abgeleiteten Bestand
|
||||
* gelesen und für das PDF aufbereitet.
|
||||
*/
|
||||
final class EmbeddedImages
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Auflösung für die Vorschau der Redaktion: Bilder zeigt die Verwaltung über ihre eigene Dateiausgabe.
|
||||
*
|
||||
* @return Closure(int): ?array{src: string}
|
||||
*/
|
||||
public static function staff(): Closure
|
||||
{
|
||||
return fn (int $id): array => ['src' => self::staffSource($id)];
|
||||
}
|
||||
|
||||
/** Adresse einer Bildfassung für den Editor und die Vorschau der Verwaltung. */
|
||||
public static function staffSource(int $id): string
|
||||
{
|
||||
return route('content.file', ['version' => $id], false);
|
||||
}
|
||||
|
||||
/** Text für einen Editor der Verwaltung: Bilder tragen ihre Adresse, damit der Editor sie zeigt. */
|
||||
public static function forEditor(?string $value): string
|
||||
{
|
||||
return FormattedText::forEditor(FormattedText::canonical($value), fn (int $id): string => self::staffSource($id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für {@see FormattedText::html()} eines Textes im Stand.
|
||||
*
|
||||
* @return Closure(int): ?array{src?: string, alt?: string, note?: string}
|
||||
*/
|
||||
public function forView(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text): Closure
|
||||
{
|
||||
return function (int $id) use ($user, $article, $release, $text): ?array {
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'ansehen');
|
||||
|
||||
if ($found === null) {
|
||||
return ['note' => 'Dieses Bild gibt es nicht mehr.'];
|
||||
}
|
||||
|
||||
if (! $found['allowed']) {
|
||||
return ['note' => 'Dieses Bild ist derzeit nicht verfügbar.'];
|
||||
}
|
||||
|
||||
return ['src' => route('member.stand.image', ['article' => $article->id, 'release' => $release->id, 'text' => $text->id, 'version' => $id])];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bildfassung für die Auslieferung: nur wenn sie im Text vorkommt, zum Stand gehört, nicht gesperrt ist und der Text
|
||||
* für `ansehen` zulässig ist.
|
||||
*
|
||||
* @return array{version: ContentElementVersion, grant: Grant}|null
|
||||
*/
|
||||
public function serve(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text, int $id): ?array
|
||||
{
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'ansehen');
|
||||
|
||||
return $found !== null && $found['allowed'] && $found['grant'] instanceof Grant ? ['version' => $found['version'], 'grant' => $found['grant']] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für das PDF. Ein Bild darf ins PDF, wenn ein Text, der es enthält, für `laden` zulässig ist. Die Bilder, die
|
||||
* tatsächlich im PDF stehen, sammelt {@see PdfImages::used()} für den Ausgabenachweis.
|
||||
*
|
||||
* @param list<ContentElementVersion> $texts die Texte des PDF
|
||||
*/
|
||||
public function forPdf(User $user, LicenseArticle $article, ArticleRelease $release, array $texts): PdfImages
|
||||
{
|
||||
return new PdfImages(function (int $id) use ($user, $article, $release, $texts): ?array {
|
||||
$decision = null;
|
||||
$exists = false;
|
||||
|
||||
foreach ($texts as $text) {
|
||||
if (! in_array($id, FormattedText::imageIds($text->body), true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'laden');
|
||||
$exists = $exists || $found !== null;
|
||||
|
||||
if ($found !== null && $found['allowed']) {
|
||||
$decision = $found;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($decision === null) {
|
||||
return ['note' => $exists ? 'Bild nicht verfügbar' : 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
$prepared = self::prepared($decision['version']);
|
||||
|
||||
if ($prepared === null) {
|
||||
return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
return $prepared + ['grant' => $decision['grant'], 'version' => $decision['version']];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für die PDF-Vorschau der Redaktion: ohne Rechteprüfung, ohne Ausgabenachweis.
|
||||
*/
|
||||
public static function forStaffPdf(): PdfImages
|
||||
{
|
||||
return new PdfImages(function (int $id): ?array {
|
||||
$version = ContentElementVersion::query()->with('element')->find($id);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return ['note' => 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
$prepared = self::prepared($version);
|
||||
|
||||
return $prepared === null ? ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null] : $prepared + ['grant' => null, 'version' => null];
|
||||
});
|
||||
}
|
||||
|
||||
/** Pfad der Bilddatei im abgeleiteten Bestand, wenn sie vorliegt. */
|
||||
public static function file(ContentElementVersion $version): ?string
|
||||
{
|
||||
$file = $version->metadata['file'] ?? null;
|
||||
|
||||
return is_string($file) && $file !== '' && ! str_contains($file, '..') && Storage::disk('media_derived')->exists($file) ? $file : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bilddatei aus dem abgeleiteten Bestand (der Web-Prozess liest nur dort), für das PDF aufbereitet.
|
||||
*
|
||||
* @return array{jpeg: string, width: int, height: int}|null
|
||||
*/
|
||||
private static function prepared(ContentElementVersion $version): ?array
|
||||
{
|
||||
$file = self::file($version);
|
||||
|
||||
return $file === null ? null : PdfImage::fromBytes((string) Storage::disk('media_derived')->get($file));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null null = es gibt kein solches Bild im Text
|
||||
*/
|
||||
private function decide(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text, int $id, string $action): ?array
|
||||
{
|
||||
if (! in_array($id, FormattedText::imageIds($text->body), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = ContentElementVersion::query()->with('element')->find($id);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$inStand = $release->contents()->where('content_element_version_id', $id)->exists();
|
||||
$decision = ($this->access)($user, $article, $release, $text, $action);
|
||||
|
||||
return [
|
||||
'allowed' => $inStand && $decision->allowed && $version->status === ContentVersionStatus::Bereit,
|
||||
'version' => $version,
|
||||
'grant' => $decision->grant,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?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, CompositionKind $kind = CompositionKind::Exercise): ?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 !== $kind) {
|
||||
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);
|
||||
$embedded = app(EmbeddedImages::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' ? FormattedText::blocks($version->body) : null,
|
||||
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version)) : 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'],
|
||||
'summary_html' => $library->text($exercise->composition)['summary_html'],
|
||||
'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,174 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
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 PdfFlow $flow;
|
||||
|
||||
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, ?PdfImages $images = null): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}, $images === null ? null : Closure::fromCallable($images));
|
||||
$this->newPage();
|
||||
|
||||
$this->flow->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$this->fact('Lernziel', $guide['learning_goal']);
|
||||
|
||||
if ($guide['duration_minutes'] !== null) {
|
||||
$this->flow->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4);
|
||||
}
|
||||
|
||||
if (filled($guide['prerequisites'])) {
|
||||
$this->flow->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->fact('Ausstattung', $guide['material_note']);
|
||||
|
||||
$this->flow->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
|
||||
{
|
||||
return PdfFlow::printable($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @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->flow->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->flow->write($title, 12.5, true, 5, keep: 40);
|
||||
|
||||
$this->flow->formatted($section['blocks'] ?? []);
|
||||
|
||||
$this->flow->y -= 4;
|
||||
}
|
||||
|
||||
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
|
||||
private function fact(string $label, ?string $value): void
|
||||
{
|
||||
$blocks = FormattedText::blocks($value);
|
||||
|
||||
if ($blocks === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($blocks) === 1 && $blocks[0]['type'] === 'paragraph') {
|
||||
$this->flow->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->flow->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->flow->formatted($blocks);
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->flow->restart();
|
||||
}
|
||||
|
||||
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,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übungsabschnitte: Textabschnitte, die für eine bestimmte Übung angelegt wurden, im Übungseditor oder bei der
|
||||
* Übernahme aus Shinkan. Sie liegen im gemeinsamen Medienbestand und tragen dort die Materialart „Übungsabschnitt“
|
||||
* und einen Verweis auf ihre Übung (`origin_composition_id`). Die Texte nutzen die gemeinsame Inhalts- und
|
||||
* Fassungsverwaltung; bearbeitet werden sie im Übungseditor.
|
||||
*/
|
||||
final class ExerciseSections
|
||||
{
|
||||
public const KIND_SLUG = EditorialContentKind::EXERCISE_SECTION_SLUG;
|
||||
|
||||
public function kindId(): ?int
|
||||
{
|
||||
$id = EditorialContentKind::query()->where('slug', self::KIND_SLUG)->value('id');
|
||||
|
||||
return $id === null ? null : (int) $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einen Abschnitt seiner Übung zu und gibt ihm die Materialart. Eine bereits gesetzte Materialart bleibt:
|
||||
* Sie ist eine bewusste Einordnung der Redaktion.
|
||||
*/
|
||||
public function mark(ContentElement $element, Composition $exercise): void
|
||||
{
|
||||
$element->origin_composition_id = $exercise->getKey();
|
||||
|
||||
if ($element->editorial_content_kind_id === null) {
|
||||
$element->editorial_content_kind_id = $this->kindId();
|
||||
}
|
||||
|
||||
$element->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet vorhandene Texte nur dann zu, wenn ihre Herkunft belegt ist:
|
||||
*
|
||||
* - Ein Abschnitt aus der Übernahme aus Shinkan (`source_ref` = `shinkan:<Quell-ID>:<Feld>`) gehört zur lokalen
|
||||
* Übung dieser Quelle.
|
||||
* - Ein anderer Text gilt als Abschnitt, wenn er ohne Materialart ist, ausschließlich in genau einer Übung
|
||||
* vorkommt und nirgends in einem Modul oder Programm direkt verwendet wird.
|
||||
*
|
||||
* Ein bereits gesetzter Materialtyp bleibt in jedem Fall erhalten, ebenso unklare Fälle.
|
||||
*
|
||||
* @return int Anzahl der Texte, die jetzt einer Übung zugeordnet sind
|
||||
*/
|
||||
public function backfill(): int
|
||||
{
|
||||
$kindId = $this->kindId();
|
||||
|
||||
if ($kindId === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$assigned = 0;
|
||||
|
||||
foreach ($this->fromSource() + $this->fromUse() as $elementId => $compositionId) {
|
||||
DB::table('content_elements')->where('id', $elementId)->whereNull('origin_composition_id')->update(['origin_composition_id' => $compositionId]);
|
||||
DB::table('content_elements')->where('id', $elementId)->whereNull('editorial_content_kind_id')->update(['editorial_content_kind_id' => $kindId]);
|
||||
$assigned++;
|
||||
}
|
||||
|
||||
return $assigned;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int> Element-ID => Übung
|
||||
*/
|
||||
private function fromSource(): array
|
||||
{
|
||||
$byRef = [];
|
||||
|
||||
foreach (DB::table('exercise_sources')->whereNotNull('composition_id')->get(['source_id', 'composition_id']) as $source) {
|
||||
$byRef[(string) $source->source_id] = (int) $source->composition_id;
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach (DB::table('content_elements')->where('output_class', 'text')->where('source_ref', 'like', 'shinkan:%')->get(['id', 'source_ref']) as $element) {
|
||||
$parts = explode(':', (string) $element->source_ref);
|
||||
|
||||
if (count($parts) === 3 && isset($byRef[$parts[1]])) {
|
||||
$found[(int) $element->id] = $byRef[$parts[1]];
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int> Element-ID => Übung
|
||||
*/
|
||||
private function fromUse(): array
|
||||
{
|
||||
$exerciseKind = CompositionKind::Exercise->value;
|
||||
$uses = DB::table('composition_members as m')
|
||||
->join('content_element_versions as v', 'v.id', '=', 'm.content_element_version_id')
|
||||
->join('content_elements as e', 'e.id', '=', 'v.content_element_id')
|
||||
->join('composition_versions as cv', 'cv.id', '=', 'm.composition_version_id')
|
||||
->join('compositions as c', 'c.id', '=', 'cv.composition_id')
|
||||
->where('e.output_class', 'text')
|
||||
->whereNull('e.editorial_content_kind_id')
|
||||
->whereNull('e.origin_composition_id')
|
||||
->select('e.id as element_id', 'c.id as composition_id', 'c.kind as composition_kind')
|
||||
->get();
|
||||
|
||||
$exercises = [];
|
||||
$elsewhere = [];
|
||||
|
||||
foreach ($uses as $use) {
|
||||
if ($use->composition_kind === $exerciseKind) {
|
||||
$exercises[(int) $use->element_id][(int) $use->composition_id] = true;
|
||||
} else {
|
||||
$elsewhere[(int) $use->element_id] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach ($exercises as $elementId => $compositions) {
|
||||
if (count($compositions) === 1 && ! isset($elsewhere[$elementId])) {
|
||||
$found[$elementId] = array_key_first($compositions);
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
}
|
||||
@@ -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,728 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Dom\HTMLDocument;
|
||||
use Dom\Node;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
|
||||
|
||||
/**
|
||||
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51).
|
||||
*
|
||||
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschriften (h3 bis h6), fett, kursiv, Aufzählung,
|
||||
* nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte,
|
||||
* Ereignisattribute und Links auf andere Schemata als http, https und mailto.
|
||||
*
|
||||
* Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`<img data-id="…" alt="…">`).
|
||||
* Die Adresse entsteht erst bei der Ausgabe, je nach Leser (Verwaltung, Mitglied mit Berechtigung, PDF). Ohne Auflösung
|
||||
* zeigt die Ausgabe kein Bild.
|
||||
*
|
||||
* Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe
|
||||
* Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der
|
||||
* Text beginnt (nach Leerraum) mit einem der Blockelemente dieser Auswahl. Gespeichertes HTML ist kanonisch und beginnt
|
||||
* deshalb immer so; Klartext beginnt nie mit einem solchen Tag, wenn er nicht von Hand so geschrieben wurde.
|
||||
*
|
||||
* Verglichen und gehasht wird immer nur die kanonische Form ({@see self::canonical()}), damit das Öffnen im Editor oder
|
||||
* eine andere Schreibweise desselben Inhalts keine neue Fassung und keinen Scheinkonflikt erzeugt.
|
||||
*/
|
||||
final class FormattedText
|
||||
{
|
||||
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
|
||||
private const BLOCKS = ['p', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||||
|
||||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||||
public const FIELDS = ['summary', 'description'];
|
||||
|
||||
private static ?HtmlSanitizer $sanitizer = null;
|
||||
|
||||
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
|
||||
public const TOOLBAR = [
|
||||
['bold', 'italic', 'link'],
|
||||
['h3', 'h4', 'h5', 'h6'],
|
||||
['bulletList', 'orderedList', 'blockquote'],
|
||||
['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'],
|
||||
['undo', 'redo'],
|
||||
];
|
||||
|
||||
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
|
||||
public static function isHtml(?string $value): bool
|
||||
{
|
||||
return preg_match('/^\s*<(?:'.implode('|', self::BLOCKS).')[\s>\/]/i', (string) $value) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
|
||||
*/
|
||||
public static function canonical(?string $value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
|
||||
* einem Blockelement beginnt.
|
||||
*/
|
||||
public static function canonicalHtml(?string $html): string
|
||||
{
|
||||
$html = trim((string) $html);
|
||||
|
||||
return $html === '' ? '' : self::normalize($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt.
|
||||
*
|
||||
* Bilder erscheinen nur, wenn `$images` sie auflöst: Die Funktion bekommt die Kennung der Bildfassung und liefert
|
||||
* `['src' => Adresse, 'alt' => Text]` (Bild), `['note' => Text]` (Hinweis an der Stelle des Bilds) oder null (Bild
|
||||
* entfällt). Ohne Funktion entfallen alle Bilder; so zeigt keine Ausgabe versehentlich ein Bild ohne Rechteprüfung.
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function html(?string $value, ?callable $images = null): string
|
||||
{
|
||||
return self::renderImages(self::canonical($value), $images);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe an Stellen, die Klartext des Altbestands bisher mit Zeilenumbrüchen zeigten: HTML wird
|
||||
* bereinigt ausgegeben, Klartext bleibt, wie er war (maskiert, Zeilenumbrüche erhalten).
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function display(?string $value, ?callable $images = null): string
|
||||
{
|
||||
$value = (string) $value;
|
||||
|
||||
return self::isHtml($value) ? self::renderImages(self::canonical($value), $images) : nl2br(e($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bildfassungen, auf die ein Text verweist, in der Reihenfolge ihres Auftretens (ohne Wiederholung).
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public static function imageIds(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = [];
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$id = (int) $image->getAttribute('data-id');
|
||||
|
||||
if ($id > 0 && ! in_array($id, $ids, true)) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Versieht die Zwischenüberschriften (h3 bis h6, auf oberster Ebene des Texts) mit Sprungmarken `<Präfix>-u<n>` und
|
||||
* verschiebt ihre Stufe um `$shift` (höchstens h6). Die Marken zählen die nicht leeren Überschriften in ihrer Reihenfolge;
|
||||
* {@see self::blocks()} zählt dieselben.
|
||||
*
|
||||
* @return array{html: string, headings: list<array{level: int, text: string, anchor: string}>}
|
||||
*/
|
||||
public static function anchorHeadings(string $html, string $prefix, int $shift = 0): array
|
||||
{
|
||||
if (preg_match('/<h[3-6][\s>]/i', $html) !== 1) {
|
||||
return ['html' => $html, 'headings' => []];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$headings = [];
|
||||
|
||||
foreach (iterator_to_array($document->body->childNodes) as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE || preg_match('/^h([3-6])$/', strtolower($node->nodeName), $match) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', (string) $node->textContent));
|
||||
|
||||
if ($text === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = min(6, (int) $match[1] + $shift);
|
||||
$anchor = $prefix.'-u'.(count($headings) + 1);
|
||||
$replacement = $document->createElement('h'.$level);
|
||||
$replacement->setAttribute('id', $anchor);
|
||||
|
||||
while ($node->firstChild !== null) {
|
||||
$replacement->appendChild($node->firstChild);
|
||||
}
|
||||
|
||||
$node->replaceWith($replacement);
|
||||
$headings[] = ['level' => $level, 'text' => $text, 'anchor' => $anchor];
|
||||
}
|
||||
|
||||
return ['html' => trim($document->body->innerHTML), 'headings' => $headings];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fügt die Adresse an jedes Bild, damit der Editor es zeigt. Die Adresse gehört nicht zum gespeicherten Wert: Die
|
||||
* Bereinigung entfernt sie beim Übernehmen aus dem Editor wieder.
|
||||
*
|
||||
* @param callable(int): ?string $source
|
||||
*/
|
||||
public static function forEditor(string $html, callable $source): string
|
||||
{
|
||||
if (! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$src = $source((int) $image->getAttribute('data-id'));
|
||||
|
||||
if ($src !== null) {
|
||||
$image->setAttribute('src', $src);
|
||||
}
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
private static function renderImages(string $html, ?callable $images): string
|
||||
{
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
$found = $images === null ? null : $images((int) $image->getAttribute('data-id'));
|
||||
|
||||
if (isset($found['src'])) {
|
||||
$image->removeAttribute('data-id');
|
||||
$image->setAttribute('src', (string) $found['src']);
|
||||
$image->setAttribute('alt', (string) ($found['alt'] ?? $image->getAttribute('alt')));
|
||||
$image->setAttribute('loading', 'lazy');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($found['note'])) {
|
||||
$note = $document->createElement('p');
|
||||
$note->setAttribute('class', 'mb-bildhinweis');
|
||||
$note->textContent = (string) $found['note'];
|
||||
$image->replaceWith($note);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$image->remove();
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
public static function isBlank(?string $value): bool
|
||||
{
|
||||
return self::canonical($value) === '';
|
||||
}
|
||||
|
||||
/** Sind beide Werte inhaltlich gleich (unabhängig von Klartext oder Schreibweise des HTML)? */
|
||||
public static function same(?string $a, ?string $b): bool
|
||||
{
|
||||
return self::canonical($a) === self::canonical($b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text ohne Auszeichnung für Orte, die kein HTML vertragen (Zahlungsdienst, Meta-Beschreibung, Listen). Absätze sind
|
||||
* durch Leerzeilen getrennt, Listenpunkte beginnen mit „- “ beziehungsweise „1. “.
|
||||
*/
|
||||
public static function plain(?string $value): string
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach (self::blocks($value) as $block) {
|
||||
$text = self::plainBlock($block);
|
||||
|
||||
if ($text !== '') {
|
||||
$out[] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
return trim(implode("\n\n", $out));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private static function plainBlock(array $block): string
|
||||
{
|
||||
return match ($block['type']) {
|
||||
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
|
||||
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
|
||||
'table' => implode("\n", array_map(
|
||||
fn (array $row): string => implode(' | ', array_map(
|
||||
fn (array $cell): string => trim((string) preg_replace('/\s+/u', ' ', implode(' ', array_filter(array_map(fn (array $inner): string => self::plainBlock($inner), $cell['blocks']))))),
|
||||
$row,
|
||||
)),
|
||||
$block['rows'],
|
||||
)),
|
||||
// Ein Bild hat im Klartext keinen Platz (Listen, Auszüge, Meta-Beschreibung).
|
||||
'image' => '',
|
||||
default => self::runsText($block['runs']),
|
||||
};
|
||||
}
|
||||
|
||||
/** Kurzer Text für Listen und Karten. */
|
||||
public static function excerpt(?string $value, int $length = 120): string
|
||||
{
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', self::plain($value)));
|
||||
|
||||
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
|
||||
* `href`. Eine Tabelle besteht aus Zeilen mit Zellen (`header`, `colspan`, `rowspan`, `blocks`); ein Bild trägt die
|
||||
* Kennung seiner Bildfassung (`id`) und den Alternativtext.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function blocks(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
return self::extractBlocks($document->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private static function extractBlocks(Node $parent): array
|
||||
{
|
||||
$blocks = [];
|
||||
|
||||
foreach ($parent->childNodes as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = [];
|
||||
|
||||
foreach ($node->childNodes as $item) {
|
||||
if ($item->nodeType === XML_ELEMENT_NODE && strtolower($item->nodeName) === 'li') {
|
||||
$items[] = self::runs($item);
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => $name === 'ul' ? 'bullets' : 'numbered', 'items' => $items];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'img') {
|
||||
$blocks[] = ['type' => 'image', 'id' => (int) $node->getAttribute('data-id'), 'alt' => (string) $node->getAttribute('alt')];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->querySelectorAll('tr') as $row) {
|
||||
$cells = [];
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cells[] = [
|
||||
'header' => strtolower($cell->nodeName) === 'th',
|
||||
'colspan' => max(1, (int) $cell->getAttribute('colspan')),
|
||||
'rowspan' => max(1, (int) $cell->getAttribute('rowspan')),
|
||||
'blocks' => self::extractBlocks($cell),
|
||||
];
|
||||
}
|
||||
|
||||
if ($cells !== []) {
|
||||
$rows[] = $cells;
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => 'table', 'rows' => $rows];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = preg_match('/^h([3-6])$/', $name, $heading) === 1 ? (int) $heading[1] : 0;
|
||||
$type = match (true) {
|
||||
$level > 0 => 'heading',
|
||||
$name === 'blockquote' => 'quote',
|
||||
default => 'paragraph',
|
||||
};
|
||||
|
||||
// Ein Bild mitten im Absatz (so setzt der Editor es) teilt den Absatz: Text davor, Bild, Text danach.
|
||||
$images = $node->querySelectorAll('img');
|
||||
|
||||
if (count($images) === 0) {
|
||||
$blocks[] = self::textBlock($type, $level, self::runs($node));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$pending = [];
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'img') {
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
|
||||
$pending = [];
|
||||
$blocks[] = ['type' => 'image', 'id' => (int) $child->getAttribute('data-id'), 'alt' => (string) $child->getAttribute('alt')];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$holder = $node->ownerDocument->createElement('span');
|
||||
$holder->appendChild($child->cloneNode(true));
|
||||
$pending = [...$pending, ...self::runs($holder)];
|
||||
}
|
||||
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Textblock; eine Überschrift trägt zusätzlich ihre Stufe (3 bis 6) und ihren Text ohne Auszeichnung.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function textBlock(string $type, int $level, array $runs): array
|
||||
{
|
||||
return $type === 'heading'
|
||||
? ['type' => $type, 'level' => $level, 'text' => self::runsText($runs), 'runs' => $runs]
|
||||
: ['type' => $type, 'runs' => $runs];
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
|
||||
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
|
||||
*/
|
||||
public static function legacyToHtml(?string $text): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach (GuideText::blocks($text) as $block) {
|
||||
$html .= match ($block['type']) {
|
||||
'heading' => '<h3>'.e($block['text']).'</h3>',
|
||||
'bullets' => '<ul>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ul>',
|
||||
'numbered' => '<ol>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ol>',
|
||||
default => '<p>'.e($block['text']).'</p>',
|
||||
};
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
private static function normalize(string $html): string
|
||||
{
|
||||
$html = self::mapLegacyTags($html);
|
||||
$html = trim(self::sanitizer()->sanitize($html));
|
||||
|
||||
if ($html === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$body = $document->body;
|
||||
|
||||
// Ein Bild steht zwischen den Absätzen, in einem Absatz (so setzt der Editor es) oder in einer Tabellenzelle und braucht
|
||||
// seine Bildfassung. Anderswo (Liste, Zitat, Überschrift) entfällt es.
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
if (! self::mayHoldImage($image->parentNode, $body) || (int) $image->getAttribute('data-id') < 1) {
|
||||
$image->remove();
|
||||
}
|
||||
}
|
||||
|
||||
$out = '';
|
||||
$loose = '';
|
||||
|
||||
$flush = function () use (&$out, &$loose): void {
|
||||
$loose = trim($loose);
|
||||
|
||||
if ($loose !== '' && trim(strip_tags(str_replace(['<br>', '<br/>', '<br />'], '', $loose))) !== '') {
|
||||
$out .= '<p>'.$loose.'</p>';
|
||||
}
|
||||
|
||||
$loose = '';
|
||||
};
|
||||
|
||||
foreach ($body->childNodes as $node) {
|
||||
if ($node->nodeType === XML_ELEMENT_NODE && in_array(strtolower($node->nodeName), self::BLOCKS, true)) {
|
||||
$flush();
|
||||
$out .= self::block($node);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$loose .= $document->saveHtml($node);
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
return self::hasText($out) || str_contains($out, '<img') ? $out : '';
|
||||
}
|
||||
|
||||
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
|
||||
private static function block(Node $node): string
|
||||
{
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if ($name === 'img') {
|
||||
$id = (int) $node->getAttribute('data-id');
|
||||
|
||||
return $id > 0 ? '<img data-id="'.$id.'" alt="'.e(trim((string) $node->getAttribute('alt'))).'">' : '';
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
return self::table($node);
|
||||
}
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$inner = self::inner($child);
|
||||
|
||||
if (! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
if (self::hasText($inner)) {
|
||||
$items .= '<li>'.$inner.'</li>';
|
||||
}
|
||||
}
|
||||
|
||||
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
|
||||
}
|
||||
|
||||
$inner = self::inner($node);
|
||||
|
||||
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Tabelle in der festen Form des Editors: Zeilen mit Kopf- (`th`) und Datenzellen (`td`), Zellen mit Absätzen,
|
||||
* Verbindungen nur als `colspan` und `rowspan` über 1. Breiten, Gestaltung und Zwischenebenen entfallen.
|
||||
*/
|
||||
private static function table(Node $table): string
|
||||
{
|
||||
$rows = '';
|
||||
|
||||
foreach ($table->querySelectorAll('tr') as $row) {
|
||||
$cells = '';
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($cell->nodeName);
|
||||
$attributes = '';
|
||||
|
||||
foreach (['colspan', 'rowspan'] as $span) {
|
||||
$value = (int) $cell->getAttribute($span);
|
||||
|
||||
if ($value > 1) {
|
||||
$attributes .= ' '.$span.'="'.min($value, 50).'"';
|
||||
}
|
||||
}
|
||||
|
||||
$inner = self::inner($cell);
|
||||
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h[3-6]|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||||
}
|
||||
|
||||
if ($cells !== '') {
|
||||
$rows .= '<tr>'.$cells.'</tr>';
|
||||
}
|
||||
}
|
||||
|
||||
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
|
||||
}
|
||||
|
||||
private static function inner(Node $node): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote', 'img'], true)) {
|
||||
$html .= self::block($child);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$html .= $node->ownerDocument->saveHtml($child);
|
||||
}
|
||||
|
||||
return trim($html);
|
||||
}
|
||||
|
||||
/** Wo darf ein Bild stehen: im Text, in einer Tabellenzelle oder in einem Absatz dort. */
|
||||
private static function mayHoldImage(?Node $parent, Node $body): bool
|
||||
{
|
||||
if ($parent === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$name = strtolower($parent->nodeName);
|
||||
|
||||
if ($parent === $body || in_array($name, ['td', 'th'], true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $name === 'p' && $parent->parentNode !== null && ($parent->parentNode === $body || in_array(strtolower($parent->parentNode->nodeName), ['td', 'th'], true));
|
||||
}
|
||||
|
||||
/** Hat der Ausschnitt einen Inhalt: Text oder ein Bild? */
|
||||
private static function hasContent(string $html): bool
|
||||
{
|
||||
return self::hasText($html) || str_contains($html, '<img');
|
||||
}
|
||||
|
||||
private static function hasText(string $html): bool
|
||||
{
|
||||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
|
||||
}
|
||||
|
||||
/** b, i und die Überschriftsstufen 1 und 2 der Quelle werden auf die feste Auswahl abgebildet (h1 und h2 gehören dem Dokument und dem Kapitel); der Rest fällt in der Bereinigung weg. */
|
||||
private static function mapLegacyTags(string $html): string
|
||||
{
|
||||
$html = (string) preg_replace('/<(\/?)b(?=[\s>\/])/i', '<$1strong', $html);
|
||||
$html = (string) preg_replace('/<(\/?)i(?=[\s>\/])/i', '<$1em', $html);
|
||||
$html = (string) preg_replace('/<(\/?)h[12](?=[\s>\/])/i', '<$1h3', $html);
|
||||
|
||||
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{text: string, bold: bool, italic: bool, href: ?string}>
|
||||
*/
|
||||
private static function runs(Node $node, bool $bold = false, bool $italic = false, ?string $href = null): array
|
||||
{
|
||||
$runs = [];
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_TEXT_NODE) {
|
||||
$runs[] = ['text' => (string) $child->textContent, 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($child->nodeName);
|
||||
|
||||
if ($name === 'br') {
|
||||
$runs[] = ['text' => "\n", 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($name, ['p', 'ul', 'ol', 'blockquote'], true)) {
|
||||
// Verschachtelte Blöcke (Absatz im Listenpunkt) werden zu Fließtext.
|
||||
$runs = [...$runs, ...self::runs($child, $bold, $italic, $href)];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$runs = [...$runs, ...self::runs(
|
||||
$child,
|
||||
$bold || $name === 'strong',
|
||||
$italic || $name === 'em',
|
||||
$name === 'a' ? ((string) $child->getAttribute('href') ?: $href) : $href,
|
||||
)];
|
||||
}
|
||||
|
||||
return $runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
private static function runsText(array $runs): string
|
||||
{
|
||||
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
|
||||
}
|
||||
|
||||
private static function sanitizer(): HtmlSanitizer
|
||||
{
|
||||
return self::$sanitizer ??= new HtmlSanitizer(
|
||||
(new HtmlSanitizerConfig)
|
||||
->allowElement('p')
|
||||
->allowElement('br')
|
||||
->allowElement('h3')
|
||||
->allowElement('h4')
|
||||
->allowElement('h5')
|
||||
->allowElement('h6')
|
||||
->allowElement('strong')
|
||||
->allowElement('em')
|
||||
->allowElement('ul')
|
||||
->allowElement('ol')
|
||||
->allowElement('li')
|
||||
->allowElement('blockquote')
|
||||
->allowElement('table')
|
||||
->allowElement('thead')
|
||||
->allowElement('tbody')
|
||||
->allowElement('tfoot')
|
||||
->allowElement('tr')
|
||||
->allowElement('th', ['colspan', 'rowspan'])
|
||||
->allowElement('td', ['colspan', 'rowspan'])
|
||||
->allowElement('img', ['data-id', 'alt'])
|
||||
->allowElement('a', ['href'])
|
||||
->allowLinkSchemes(['http', 'https', 'mailto'])
|
||||
->allowRelativeLinks(false)
|
||||
->forceAttribute('a', 'rel', 'noopener noreferrer')
|
||||
->withMaxInputLength(100000),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,692 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Satz für gedruckte Ausgaben (Übung, Dokument): Überschriften, Absätze mit fett und kursiv, Listen, Tabellen und Bilder
|
||||
* aus den Blöcken von {@see FormattedText::blocks()}. Übung und Dokument setzen mit demselben Baustein; so sehen
|
||||
* Tabellen und Bilder in beiden gleich aus.
|
||||
*
|
||||
* Der Satz kennt weder Seitenkopf noch Fußzeile: Passt etwas nicht mehr auf die Seite, ruft er `$breakPage` auf. Diese
|
||||
* Funktion schließt die Seite und öffnet die nächste; danach beginnt der Satz wieder am oberen Rand.
|
||||
*/
|
||||
final class PdfFlow
|
||||
{
|
||||
public float $y;
|
||||
|
||||
/**
|
||||
* Wird für jede Zwischenüberschrift mit Sprungmarke aufgerufen, bevor sie gesetzt wird: Block und obere Kante.
|
||||
*
|
||||
* @var (Closure(array<string, mixed>, float): void)|null
|
||||
*/
|
||||
public ?Closure $onHeading = null;
|
||||
|
||||
/** Schachtelungstiefe beim Setzen einer Tabelle (Zelleninhalt setzt nie wieder eine Tabelle). */
|
||||
private int $depth = 0;
|
||||
|
||||
/**
|
||||
* @param Closure(): void $breakPage
|
||||
* @param (Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string})|null $images Löst ein Bild auf: JPEG mit Maßen,
|
||||
* ein Hinweistext oder null (entfällt)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PdfDocument $pdf,
|
||||
private readonly float $left,
|
||||
private readonly float $right,
|
||||
private readonly float $top,
|
||||
private readonly float $bottom,
|
||||
private readonly Closure $breakPage,
|
||||
private readonly ?Closure $images = null,
|
||||
) {
|
||||
$this->y = $top;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsichtbare Zeichen, die im Browser nichts zeigen, im PDF aber stören: der weiche Trennstrich (erscheint dort als
|
||||
* Bindestrich), Nullbreiten- und Steuerzeichen für die Schreibrichtung sowie die Byte-Reihenfolge-Marke (erscheinen als „?“).
|
||||
* Mitten in einem Link machen sie die Adresse unbrauchbar. Das PDF trennt keine Wörter und braucht sie nicht.
|
||||
*/
|
||||
private const INVISIBLE = '/[\x{00AD}\x{034F}\x{061C}\x{180E}\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{FEFF}]/u';
|
||||
|
||||
/**
|
||||
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
|
||||
* lateinische Buchstaben); sonst bleibt „?“. Unsichtbare Zeichen entfallen.
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = (string) preg_replace(self::INVISIBLE, '', $text);
|
||||
$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;
|
||||
}
|
||||
|
||||
/** Beginn einer neuen Seite: der Satz steht wieder am oberen Rand. */
|
||||
public function restart(): void
|
||||
{
|
||||
$this->y = $this->top;
|
||||
}
|
||||
|
||||
public function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < $this->bottom) {
|
||||
($this->breakPage)();
|
||||
$this->y = $this->top;
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Überschrift oder ein kurzer Text in Zeilen nach {@see PdfDocument::wrap()}. `$keep` hält Platz für folgenden Text frei. */
|
||||
public function write(string $text, float $size, bool $bold, float $after, float $keep = 0, ?float $x = null): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
$lines = PdfDocument::wrap($text, $this->right - $x, $size, $bold);
|
||||
|
||||
if ($keep > 0 && $lines !== []) {
|
||||
$this->room(count($lines) * ($size + 4) + $keep);
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text($x, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat, Listen, Tabelle und Bild.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
public function formatted(array $blocks, ?float $x = null, float $size = 10.5): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->headingBlock($block, $x, $size),
|
||||
'quote' => $this->runs($block['runs'], $x + 14, $size, italic: true, after: 5),
|
||||
'bullets' => $this->listItems($block['items'], fn (int $n): string => '•', $x, $size),
|
||||
'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.', $x, $size),
|
||||
'table' => $this->table($block['rows'], $x),
|
||||
'image' => $this->image($block, $x),
|
||||
default => $this->runs($block['runs'] ?? [], $x, $size, after: 5),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private function headingBlock(array $block, float $x, float $size): void
|
||||
{
|
||||
// Stufe 3 ist die größte Zwischenüberschrift, Stufe 6 hat Textgröße (und steht kursiv).
|
||||
$level = max(3, min(6, (int) ($block['level'] ?? 3)));
|
||||
$heading = $size + [3 => 2.0, 4 => 1.0, 5 => 0.5, 6 => 0.0][$level];
|
||||
$gap = [3 => 6.0, 4 => 4.0, 5 => 3.0, 6 => 2.0][$level];
|
||||
|
||||
// Eine Zwischenüberschrift bleibt bei ihrem Text: mindestens zwei Zeilen müssen mit auf die Seite.
|
||||
$this->room($gap + $heading + 4 + 2 * ($size + 4));
|
||||
$this->y -= $gap;
|
||||
|
||||
if ($this->onHeading !== null && isset($block['anchor'])) {
|
||||
($this->onHeading)($block, $this->y + $heading);
|
||||
}
|
||||
|
||||
$this->runs($block['runs'], $x, $heading, bold: true, italic: $level === 6, after: 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<array{text: string, bold: bool, italic: bool, href: ?string}>> $items
|
||||
* @param callable(int): string $marker
|
||||
*/
|
||||
public function listItems(array $items, callable $marker, ?float $x = null, float $size = 10.5): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
$this->room(14);
|
||||
$this->pdf->text($x + 4, $this->y, $marker($index + 1), $size);
|
||||
$this->runs($item, $x + 18, $size, after: 1);
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt Textabschnitte mit fett und kursiv in Zeilen um und zeichnet sie. Ein Link ist unterstrichen und anklickbar; die
|
||||
* vollständige Adresse hängt am Link und bleibt auch über Zeilenumbrüche zusammen. Gedruckt steht die Adresse nur in
|
||||
* Kurzform ({@see self::shortAddress()}), damit der PDF-Betrachter keine umgebrochene Adresse im Text erraten muss.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
public function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void
|
||||
{
|
||||
foreach ($this->lines($runs, $this->right - $x, $size, $bold, $italic) as $row) {
|
||||
$this->room($size + 4);
|
||||
$this->drawSegments($row, $x, $this->y, $size);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichnet die Abschnitte einer Zeile; ein Abschnitt mit Adresse wird unterstrichen und anklickbar.
|
||||
*
|
||||
* @param list<array{0: string, 1: bool, 2: bool, 3?: ?string}> $segments
|
||||
*/
|
||||
private function drawSegments(array $segments, float $x, float $y, float $size, bool $forceBold = false): void
|
||||
{
|
||||
foreach ($segments as $segment) {
|
||||
[$text, $isBold, $isItalic] = $segment;
|
||||
$href = $segment[3] ?? null;
|
||||
$isBold = $isBold || $forceBold;
|
||||
$this->pdf->text($x, $y, $text, $size, $isBold, $isItalic);
|
||||
|
||||
if ($href !== null && trim($text) !== '') {
|
||||
$start = $x + PdfDocument::exactWidth(substr($text, 0, strlen($text) - strlen(ltrim($text))), $size, $isBold);
|
||||
$width = PdfDocument::exactWidth(trim($text), $size, $isBold);
|
||||
$this->pdf->uriLink($start, $y - 2, $width, $size + 3, $href);
|
||||
$this->pdf->line($start, $y - 1.5, $start + $width, $y - 1.5, 0.4);
|
||||
}
|
||||
|
||||
$x += PdfDocument::exactWidth($text, $size, $isBold);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kurzform einer Adresse für den Druck: ohne Schema und „www.“, ohne abschließenden Schrägstrich, höchstens
|
||||
* `$max` Zeichen (sonst mit „…“). Ohne „https://“ erkennt kein PDF-Betrachter sie selbst als Link.
|
||||
*/
|
||||
public static function shortAddress(string $address, int $max = 42): string
|
||||
{
|
||||
$short = (string) preg_replace('#^(?:https?://|mailto:)(?:www\.)?#i', '', trim(self::printable($address)));
|
||||
$short = rtrim($short, '/');
|
||||
|
||||
return mb_strlen($short) > $max ? rtrim(mb_substr($short, 0, $max - 1), '/.-?&=#').'…' : $short;
|
||||
}
|
||||
|
||||
/** Ist der Linktext selbst eine Adresse (mit Schema oder „www.“)? */
|
||||
private static function isAddress(string $text): bool
|
||||
{
|
||||
return preg_match('#^(?:https?://|mailto:|www\.)#i', trim($text)) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen aus Textabschnitten für eine Breite. Die Breite kommt aus den Schriftbreiten der Helvetica
|
||||
* ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
* @return list<list<array{0: string, 1: bool, 2: bool, 3: ?string}>>
|
||||
*/
|
||||
public function lines(array $runs, float $maxWidth, float $size, bool $bold = false, bool $italic = false): array
|
||||
{
|
||||
$lines = [];
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
$count = count($runs);
|
||||
|
||||
$flush = function () use (&$lines, &$line, &$width, &$pendingSpace): void {
|
||||
if ($line !== []) {
|
||||
$lines[] = $line;
|
||||
}
|
||||
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
$place = function (string $word, bool $isBold, bool $isItalic, ?string $href = null) use (&$line, &$width, &$pendingSpace, $maxWidth, $size, $flush): void {
|
||||
$space = $pendingSpace && $line !== [] ? ' ' : '';
|
||||
$need = PdfDocument::exactWidth($space.$word, $size, $isBold);
|
||||
|
||||
if ($line !== [] && $width + $need > $maxWidth) {
|
||||
$flush();
|
||||
$space = '';
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
while ($need > $maxWidth && mb_strlen($word) > 1) {
|
||||
$cut = mb_strlen($word) - 1;
|
||||
|
||||
while ($cut > 1 && PdfDocument::exactWidth(mb_substr($word, 0, $cut), $size, $isBold) > $maxWidth) {
|
||||
$cut--;
|
||||
}
|
||||
|
||||
$line[] = [mb_substr($word, 0, $cut), $isBold, $isItalic, $href];
|
||||
$flush();
|
||||
$word = mb_substr($word, $cut);
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
$last = $line === [] ? null : $line[array_key_last($line)];
|
||||
|
||||
if ($last !== null && $last[1] === $isBold && $last[2] === $isItalic && $last[3] === $href) {
|
||||
$line[array_key_last($line)][0] .= $space.$word;
|
||||
} else {
|
||||
$line[] = [$space.$word, $isBold, $isItalic, $href];
|
||||
}
|
||||
|
||||
$width += $need;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
foreach ($runs as $index => $run) {
|
||||
$isBold = $bold || $run['bold'];
|
||||
$isItalic = $italic || $run['italic'];
|
||||
|
||||
$href = $run['href'] !== null && trim($run['href']) !== '' ? self::printable($run['href']) : null;
|
||||
$text = self::printable($run['text']);
|
||||
$isAddress = $href !== null && self::isAddress($text);
|
||||
|
||||
// Ein Linktext, der selbst eine Adresse ist, steht in Kurzform; die ganze Adresse hängt am Link.
|
||||
if ($isAddress) {
|
||||
$text = (preg_match('#^\s#u', $text) === 1 ? ' ' : '').self::shortAddress($text).(preg_match('#\s$#u', $text) === 1 ? ' ' : '');
|
||||
}
|
||||
|
||||
foreach (preg_split('/(\s+)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) {
|
||||
if (trim($token) !== '') {
|
||||
$place($token, $isBold, $isItalic, $href);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($token, "\n")) {
|
||||
$flush();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$pendingSpace = true;
|
||||
}
|
||||
|
||||
$nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null;
|
||||
|
||||
// Zeigt der Linktext die Adresse schon, steht sie nicht noch einmal in Klammern (verglichen, wie sie gedruckt wird).
|
||||
if ($href !== null && $nextHref !== $run['href'] && ! $isAddress && ! str_contains(mb_strtolower($text), mb_strtolower(self::shortAddress($href)))) {
|
||||
$pendingSpace = true;
|
||||
$place('('.self::shortAddress($href).')', false, false, $href);
|
||||
}
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Bild in Breite der Spalte, höchstens 320 Punkt hoch. Ein Bild lässt sich nicht teilen: Es steht ganz auf einer
|
||||
* Seite. Kann das Bild nicht gezeigt werden, steht an seiner Stelle der Hinweis.
|
||||
*
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private function image(array $block, float $x): void
|
||||
{
|
||||
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
|
||||
|
||||
if ($found === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! isset($found['jpeg'])) {
|
||||
$this->runs([['text' => '['.($found['note'] ?? 'Bild nicht verfügbar').']', 'bold' => false, 'italic' => true, 'href' => null]], $x, 9.5, after: 5);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$available = $this->right - $x;
|
||||
$scale = min(1.0, $available / max(1, $found['width']), 320.0 / max(1, $found['height']));
|
||||
$width = max(1.0, $found['width'] * $scale);
|
||||
$height = max(1.0, $found['height'] * $scale);
|
||||
|
||||
$this->room($height + 16);
|
||||
$this->pdf->image($x, $this->y + 4 - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']);
|
||||
$this->y -= $height + 16;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Tabelle mit Rahmen. Die Spaltenbreiten folgen dem Inhalt (Spalten mit kurzem Text bleiben schmal), Verbindungen
|
||||
* über Spalten und Zeilen werden gesetzt. Eine Zeile bleibt zusammen; auf jeder Folgeseite stehen die Kopfzeilen
|
||||
* erneut. Ist eine einzelne Zeile höher als eine Seite, erscheint ihr Inhalt als Fließtext.
|
||||
*
|
||||
* @param list<list<array<string, mixed>>> $rows
|
||||
*/
|
||||
private function table(array $rows, float $x): void
|
||||
{
|
||||
if ($this->depth > 0 || $rows === []) {
|
||||
// Tabellen in Tabellen kennt der Editor nicht; sicherheitshalber als Fließtext.
|
||||
foreach ($rows as $row) {
|
||||
foreach ($row as $cell) {
|
||||
$this->formatted($cell['blocks'], $x);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$size = 9.5;
|
||||
$pad = 3.5;
|
||||
$lineHeight = $size + 3;
|
||||
$grid = $this->grid($rows);
|
||||
$columns = $grid['columns'];
|
||||
$widths = $this->columnWidths($grid['cells'], $columns, $this->right - $x, $size, $pad);
|
||||
$headRows = 0;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if ($row !== [] && count(array_filter($row, fn (array $cell): bool => $cell['header'])) === count($row)) {
|
||||
$headRows++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$headRows = $headRows === count($rows) ? 0 : $headRows;
|
||||
$prepared = [];
|
||||
|
||||
foreach ($grid['cells'] as $cell) {
|
||||
$inner = array_sum(array_slice($widths, $cell['column'], $cell['colspan'])) - 2 * $pad;
|
||||
$this->depth++;
|
||||
$cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']);
|
||||
$this->depth--;
|
||||
$cell['height'] = max($lineHeight, array_sum(array_column($cell['lines'], 'height'))) + 2 * $pad;
|
||||
$prepared[] = $cell;
|
||||
}
|
||||
|
||||
$rowCount = count($rows);
|
||||
$heights = array_fill(0, $rowCount, $lineHeight + 2 * $pad);
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['rowspan'] === 1) {
|
||||
$heights[$cell['row']] = max($heights[$cell['row']], $cell['height']);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['rowspan'] > 1) {
|
||||
$last = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
|
||||
$have = array_sum(array_slice($heights, $cell['row'], $last - $cell['row'] + 1));
|
||||
$heights[$last] += max(0.0, $cell['height'] - $have);
|
||||
}
|
||||
}
|
||||
|
||||
$pageHeight = $this->top - $this->bottom;
|
||||
|
||||
if (max($heights) > $pageHeight - 8) {
|
||||
foreach ($rows as $row) {
|
||||
foreach ($row as $cell) {
|
||||
$this->formatted($cell['blocks'], $x);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad): void {
|
||||
$y = $this->y;
|
||||
|
||||
for ($r = $from; $r <= $to; $r++) {
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['row'] !== $r) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cellLeft = $x + array_sum(array_slice($widths, 0, $cell['column']));
|
||||
$cellWidth = array_sum(array_slice($widths, $cell['column'], $cell['colspan']));
|
||||
$cellHeight = array_sum(array_slice($heights, $r, $cell['rowspan']));
|
||||
$this->frame($cellLeft, $y - $cellHeight, $cellWidth, $cellHeight, $cell['header']);
|
||||
$textY = $y - $pad - $size;
|
||||
|
||||
foreach ($cell['lines'] as $line) {
|
||||
if (isset($line['image'])) {
|
||||
$this->pdf->image($cellLeft + $pad, $textY + $size - $line['image']['height'], $line['image']['width'], $line['image']['height'], $line['image']['jpeg'], $line['image']['pixelWidth'], $line['image']['pixelHeight']);
|
||||
$textY -= $line['height'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line['marker'] !== null) {
|
||||
$this->pdf->text($cellLeft + $pad + $line['indent'] - 12, $textY, $line['marker'], $size, $cell['header']);
|
||||
}
|
||||
|
||||
$cursor = $cellLeft + $pad + $line['indent'];
|
||||
|
||||
$this->drawSegments($line['segments'], $cursor, $textY, $size, $cell['header']);
|
||||
|
||||
$textY -= $line['height'];
|
||||
}
|
||||
}
|
||||
|
||||
$y -= $heights[$r];
|
||||
}
|
||||
|
||||
$this->y = $y;
|
||||
};
|
||||
|
||||
$this->room($heights[0] + ($rowCount > 1 ? min($heights[1], 40.0) : 0));
|
||||
|
||||
for ($r = 0; $r < $rowCount; $r++) {
|
||||
// Zeilen, die eine Verbindung über Zeilen zusammenhält, werden gemeinsam gesetzt.
|
||||
$end = $r;
|
||||
|
||||
do {
|
||||
$before = $end;
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['row'] <= $end && $end < $cell['row'] + $cell['rowspan'] - 1) {
|
||||
$end = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
|
||||
}
|
||||
}
|
||||
} while ($end !== $before);
|
||||
|
||||
$span = $end - $r + 1;
|
||||
$need = array_sum(array_slice($heights, $r, $span));
|
||||
|
||||
if ($this->y - $need < $this->bottom) {
|
||||
($this->breakPage)();
|
||||
$this->y = $this->top;
|
||||
|
||||
if ($headRows > 0 && $r >= $headRows) {
|
||||
$drawRows(0, $headRows - 1);
|
||||
}
|
||||
}
|
||||
|
||||
$drawRows($r, $r + $span - 1);
|
||||
$r += $span - 1;
|
||||
}
|
||||
|
||||
$this->y -= 18;
|
||||
}
|
||||
|
||||
private function frame(float $x, float $y, float $w, float $h, bool $header): void
|
||||
{
|
||||
if ($header) {
|
||||
$this->pdf->fillRect($x, $y, $w, $h, 0.92);
|
||||
}
|
||||
|
||||
$this->pdf->line($x, $y, $x + $w, $y, 0.4);
|
||||
$this->pdf->line($x, $y + $h, $x + $w, $y + $h, 0.4);
|
||||
$this->pdf->line($x, $y, $x, $y + $h, 0.4);
|
||||
$this->pdf->line($x + $w, $y, $x + $w, $y + $h, 0.4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Weist jeder Zelle ihre Spalte zu; Verbindungen über Zeilen belegen die Spalte in den Folgezeilen mit.
|
||||
*
|
||||
* @param list<list<array<string, mixed>>> $rows
|
||||
* @return array{columns: int, cells: list<array<string, mixed>>}
|
||||
*/
|
||||
private function grid(array $rows): array
|
||||
{
|
||||
$occupied = [];
|
||||
$cells = [];
|
||||
$columns = 0;
|
||||
|
||||
foreach ($rows as $r => $row) {
|
||||
$column = 0;
|
||||
|
||||
foreach ($row as $cell) {
|
||||
while (isset($occupied[$r][$column])) {
|
||||
$column++;
|
||||
}
|
||||
|
||||
$colspan = max(1, (int) $cell['colspan']);
|
||||
$rowspan = max(1, (int) $cell['rowspan']);
|
||||
|
||||
for ($dr = 0; $dr < $rowspan; $dr++) {
|
||||
for ($dc = 0; $dc < $colspan; $dc++) {
|
||||
$occupied[$r + $dr][$column + $dc] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$cells[] = $cell + ['row' => $r, 'column' => $column] + ['colspan' => $colspan, 'rowspan' => $rowspan];
|
||||
$column += $colspan;
|
||||
$columns = max($columns, $column);
|
||||
}
|
||||
}
|
||||
|
||||
return ['columns' => max(1, $columns), 'cells' => $cells];
|
||||
}
|
||||
|
||||
/**
|
||||
* Spaltenbreiten nach Inhalt: Jede Spalte braucht mindestens ihr längstes Wort und wünscht sich die Breite ihres
|
||||
* längsten Zelltexts. Reicht der Platz, wird der Rest gleichmäßig verteilt; sonst teilt sich der Mangel nach Wunsch auf.
|
||||
*
|
||||
* @param list<array<string, mixed>> $cells
|
||||
* @return list<float>
|
||||
*/
|
||||
private function columnWidths(array $cells, int $columns, float $available, float $size, float $pad): array
|
||||
{
|
||||
$min = array_fill(0, $columns, 24.0);
|
||||
$want = array_fill(0, $columns, 24.0);
|
||||
|
||||
foreach ($cells as $cell) {
|
||||
if ($cell['colspan'] !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = self::printable($this->cellText($cell['blocks']));
|
||||
$widest = 0.0;
|
||||
|
||||
foreach (preg_split('/\s+/u', $text) ?: [] as $word) {
|
||||
$widest = max($widest, PdfDocument::exactWidth($word, $size, (bool) $cell['header']));
|
||||
}
|
||||
|
||||
$c = $cell['column'];
|
||||
$min[$c] = max($min[$c], $widest + 2 * $pad + 1);
|
||||
$want[$c] = max($want[$c], PdfDocument::exactWidth($text, $size, (bool) $cell['header']) + 2 * $pad + 1);
|
||||
}
|
||||
|
||||
$want = array_map(fn (float $w, float $m): float => max($w, $m), $want, $min);
|
||||
|
||||
if (array_sum($min) >= $available) {
|
||||
$scale = $available / array_sum($min);
|
||||
|
||||
return array_map(fn (float $w): float => $w * $scale, $min);
|
||||
}
|
||||
|
||||
if (array_sum($want) <= $available) {
|
||||
$extra = ($available - array_sum($want)) / $columns;
|
||||
|
||||
return array_map(fn (float $w): float => $w + $extra, $want);
|
||||
}
|
||||
|
||||
// Der Platz über dem Mindestmaß wird gleichmäßig verteilt, aber keine Spalte bekommt mehr, als sie sich wünscht:
|
||||
// Schmale Spalten behalten ihren Text in einer Zeile, die breite nimmt den Rest.
|
||||
$widths = $min;
|
||||
$room = $available - array_sum($min);
|
||||
$open = array_keys($min);
|
||||
usort($open, fn (int $a, int $b): int => ($want[$a] - $min[$a]) <=> ($want[$b] - $min[$b]));
|
||||
|
||||
foreach ($open as $position => $c) {
|
||||
$share = $room / (count($open) - $position);
|
||||
$give = min($want[$c] - $min[$c], $share);
|
||||
$widths[$c] += $give;
|
||||
$room -= $give;
|
||||
}
|
||||
|
||||
return $widths;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
private function cellText(array $blocks): string
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
$out[] = match ($block['type']) {
|
||||
'bullets', 'numbered' => implode(' ', array_map(fn (array $item): string => implode('', array_column($item, 'text')), $block['items'])),
|
||||
'table', 'image' => '',
|
||||
default => implode('', array_column($block['runs'] ?? [], 'text')),
|
||||
};
|
||||
}
|
||||
|
||||
return trim((string) preg_replace('/\s+/u', ' ', implode(' ', $out)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen einer Tabellenzelle: Absätze, Aufzählungen, Zwischenüberschriften und Bilder (höchstens 110 Punkt hoch, in
|
||||
* Breite der Zelle). Jeder Eintrag trägt seine Höhe.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function cellLines(array $blocks, float $width, float $size, bool $header): array
|
||||
{
|
||||
$out = [];
|
||||
$lineHeight = $size + 3;
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
if (in_array($block['type'], ['bullets', 'numbered'], true)) {
|
||||
foreach ($block['items'] as $index => $item) {
|
||||
foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) {
|
||||
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null, 'height' => $lineHeight];
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($block['type'] === 'image') {
|
||||
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
|
||||
|
||||
if ($found !== null && isset($found['jpeg'])) {
|
||||
$scale = min(1.0, $width / max(1, $found['width']), 110.0 / max(1, $found['height']));
|
||||
$w = max(1.0, $found['width'] * $scale);
|
||||
$h = max(1.0, $found['height'] * $scale);
|
||||
$out[] = ['image' => ['jpeg' => $found['jpeg'], 'width' => $w, 'height' => $h, 'pixelWidth' => $found['width'], 'pixelHeight' => $found['height']], 'height' => $h + 4];
|
||||
} elseif ($found !== null) {
|
||||
$out[] = ['segments' => [['['.($found['note'] ?? 'Bild nicht verfügbar').']', false, true]], 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($block['runs'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($this->lines($block['runs'], $width, $size, $header || $block['type'] === 'heading', $block['type'] === 'quote') as $segments) {
|
||||
$out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Die Bilder eines PDF: löst jedes Bild einmal auf und merkt sich, welche Bildfassungen tatsächlich gedruckt wurden,
|
||||
* damit der Ausgabenachweis sie wie jede andere Fassung des PDF führt.
|
||||
*/
|
||||
final class PdfImages
|
||||
{
|
||||
/** @var array<int, array{jpeg?: string, width?: int, height?: int, note?: string, grant: ?Grant, version: ?ContentElementVersion}|null> */
|
||||
private array $resolved = [];
|
||||
|
||||
/**
|
||||
* @param Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string, grant: ?Grant, version: ?ContentElementVersion} $resolve
|
||||
*/
|
||||
public function __construct(private readonly Closure $resolve) {}
|
||||
|
||||
/**
|
||||
* @return array{jpeg?: string, width?: int, height?: int, note?: string}|null
|
||||
*/
|
||||
public function __invoke(int $id): ?array
|
||||
{
|
||||
if (! array_key_exists($id, $this->resolved)) {
|
||||
$this->resolved[$id] = ($this->resolve)($id);
|
||||
}
|
||||
|
||||
return $this->resolved[$id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{version: ContentElementVersion, grant: Grant}>
|
||||
*/
|
||||
public function used(): array
|
||||
{
|
||||
$used = [];
|
||||
|
||||
foreach ($this->resolved as $found) {
|
||||
if ($found !== null && isset($found['jpeg']) && $found['version'] instanceof ContentElementVersion && $found['grant'] instanceof Grant) {
|
||||
$used[] = ['version' => $found['version'], 'grant' => $found['grant']];
|
||||
}
|
||||
}
|
||||
|
||||
return $used;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Vorlage für das PDF eines Dokuments (ADR-51, Nachtrag): Titelseite, grafische Kopf- und Fußzeile und Standardvermerke.
|
||||
* Die Vorlage bestimmt nur das Aussehen. Der Inhalt, auch Ausgabe, Datum und Copyright-Vermerk der Dokumentfassung, gehört
|
||||
* zur Fassung ({@see DocumentMeta}); die Vorlage liefert nur den Standard-Vermerk, wenn die Fassung keinen eigenen hat.
|
||||
*/
|
||||
class PdfTemplate extends Model
|
||||
{
|
||||
public const KIND_DOCUMENT = 'dokument';
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'kind',
|
||||
'show_cover',
|
||||
'header_version_id',
|
||||
'footer_version_id',
|
||||
'cover_version_id',
|
||||
'header_element_id',
|
||||
'footer_element_id',
|
||||
'cover_element_id',
|
||||
'header_align',
|
||||
'footer_align',
|
||||
'header_logo_height',
|
||||
'footer_logo_height',
|
||||
'toc_mode',
|
||||
'toc_depth',
|
||||
'publisher',
|
||||
'copyright',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['show_cover' => 'boolean'];
|
||||
}
|
||||
|
||||
public const SLOTS = ['header', 'footer', 'cover'];
|
||||
|
||||
/** Anordnung von Kopf- und Fußgrafik: Band in voller Seitenbreite oder Logo links oder rechts. */
|
||||
public const ALIGNMENTS = ['full', 'left', 'right'];
|
||||
|
||||
public const LOGO_MIN = 16;
|
||||
|
||||
public const LOGO_MAX = 100;
|
||||
|
||||
public const LOGO_DEFAULT = 40;
|
||||
|
||||
/** Inhaltsverzeichnis: nur bei mehr als einem Eintrag, immer oder nie. */
|
||||
public const TOC_MODES = ['auto', 'always', 'never'];
|
||||
|
||||
/** Tiefe des Verzeichnisses: 2 = nur Kapitel und Unterkapitel, 3 bis 6 = zusätzlich die Überschriften bis zu dieser Stufe. */
|
||||
public const TOC_DEPTH_MIN = 2;
|
||||
|
||||
public const TOC_DEPTH_MAX = 6;
|
||||
|
||||
/**
|
||||
* Darstellung des gedruckten Inhaltsverzeichnisses.
|
||||
*
|
||||
* @return array{mode: string, depth: int}
|
||||
*/
|
||||
public function toc(): array
|
||||
{
|
||||
return self::normalizeToc((string) $this->getAttribute('toc_mode'), (int) $this->getAttribute('toc_depth'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{mode: string, depth: int}
|
||||
*/
|
||||
public static function normalizeToc(?string $mode, int|string|null $depth): array
|
||||
{
|
||||
$depth = (int) $depth;
|
||||
|
||||
return [
|
||||
'mode' => in_array($mode, self::TOC_MODES, true) ? (string) $mode : 'auto',
|
||||
'depth' => $depth < 1 ? self::TOC_DEPTH_MAX : max(self::TOC_DEPTH_MIN, min(self::TOC_DEPTH_MAX, $depth)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anordnung und Logohöhe (Punkt) von Kopf oder Fuß; ungültige Werte fallen auf die Vorgabe zurück.
|
||||
*
|
||||
* @return array{align: string, height: int}
|
||||
*/
|
||||
public function layout(string $slot): array
|
||||
{
|
||||
return self::normalizeLayout((string) $this->getAttribute($slot.'_align'), (int) $this->getAttribute($slot.'_logo_height'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{align: string, height: int}
|
||||
*/
|
||||
public static function normalizeLayout(?string $align, int|string|null $height): array
|
||||
{
|
||||
$height = (int) $height;
|
||||
|
||||
return [
|
||||
'align' => in_array($align, self::ALIGNMENTS, true) ? (string) $align : 'full',
|
||||
'height' => $height < 1 ? self::LOGO_DEFAULT : max(self::LOGO_MIN, min(self::LOGO_MAX, $height)),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Bild eines Bildfelds als Ziel des Pickers: `element:<Fassung>`, `medium:<Medium>` oder null.
|
||||
*/
|
||||
public function target(string $slot): ?string
|
||||
{
|
||||
$version = $this->getAttribute($slot.'_version_id');
|
||||
$element = $this->getAttribute($slot.'_element_id');
|
||||
|
||||
return $version !== null ? 'element:'.$version : ($element !== null ? 'medium:'.$element : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Spaltenwerte eines Bildfelds für ein Ziel des Pickers.
|
||||
*
|
||||
* @return array<string, int|null>
|
||||
*/
|
||||
public static function columns(string $slot, ?string $target): array
|
||||
{
|
||||
$ref = TemplateImage::parse($target);
|
||||
|
||||
return [
|
||||
$slot.'_version_id' => ($ref['type'] ?? null) === 'version' ? $ref['id'] : null,
|
||||
$slot.'_element_id' => ($ref['type'] ?? null) === 'medium' ? $ref['id'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
public function headerVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElementVersion::class, 'header_version_id');
|
||||
}
|
||||
|
||||
public function footerVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElementVersion::class, 'footer_version_id');
|
||||
}
|
||||
|
||||
public function coverVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ContentElementVersion::class, 'cover_version_id');
|
||||
}
|
||||
|
||||
public function compositions(): HasMany
|
||||
{
|
||||
return $this->hasMany(Composition::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,884 @@
|
||||
<?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',
|
||||
];
|
||||
|
||||
/** Felder, die Shinkan bei `text_format: html` als HTML liefert (ADR-50). Ohne diese Angabe sind alle Texte Klartext. */
|
||||
private const HTML_FIELDS = ['summary', 'goal', 'execution', 'preparation', 'trainer_notes'];
|
||||
|
||||
/** Ä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 ($this->value($document, $field) !== '') {
|
||||
$sections[] = ['label' => $label, 'text' => FormattedText::excerpt($this->value($document, $field), 280)];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'source' => $source->id,
|
||||
'snapshot' => $snapshot?->id,
|
||||
'hash' => $snapshot?->content_hash,
|
||||
'state' => $state,
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'summary' => FormattedText::plain($this->value($document, 'summary')),
|
||||
'goal' => FormattedText::plain($this->value($document, 'goal')),
|
||||
'duration' => $this->duration($document),
|
||||
'equipment' => FormattedText::plain($this->value($document, 'equipment')),
|
||||
'sections' => $sections,
|
||||
'variants' => array_map(fn (array $variant): array => [
|
||||
'key' => (string) ($variant['id'] ?? ''),
|
||||
'name' => (string) ($variant['name'] ?? ''),
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'changes' => $this->variantChanges($document, $variant) !== '',
|
||||
], 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 (! $this->sameValue($field, $before, $after)) {
|
||||
$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'] ?? ''))
|
||||
|| ! FormattedText::same($this->variantChanges($after, $variant), $this->variantChanges($before, (array) $old[$key]))) {
|
||||
$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 (! $this->sameValue('summary', $before, $after) && filled($source->composition->summary) && ! FormattedText::same($source->composition->summary, $this->value($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]) {
|
||||
$isText = in_array($field, ['goal', 'equipment'], true);
|
||||
$old = $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null);
|
||||
$new = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null);
|
||||
|
||||
if ($latest !== null && $this->classifyField($latest->{$column}, $old, $new, $isText) === $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, $this->value($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, $composition, $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]) {
|
||||
$isText = in_array($field, ['goal', 'equipment'], true);
|
||||
$value = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null);
|
||||
|
||||
if ($previous !== null && $previousSnapshot !== null) {
|
||||
$decision = $this->classifyField($previous->{$column}, $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null), $value, $isText);
|
||||
|
||||
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 = $this->value($document, $field);
|
||||
|
||||
if ($text !== '') {
|
||||
$plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $this->value($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 = $this->variantChanges($document, $variant);
|
||||
|
||||
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) ? ($this->variantChanges($previousSource, $before) ?: 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 || FormattedText::same($latest->body, $text) || $latest->change_note === self::IMPORT_NOTE) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $previousText === null || ! FormattedText::same($previousText, $text) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
private function classifyField(mixed $local, mixed $previousSource, mixed $new, bool $text = false): string
|
||||
{
|
||||
$same = $text
|
||||
? fn (mixed $a, mixed $b): bool => FormattedText::same($a === null ? null : (string) $a, $b === null ? null : (string) $b)
|
||||
: fn (mixed $a, mixed $b): bool => ($a === null ? '' : trim((string) $a)) === ($b === null ? '' : trim((string) $b));
|
||||
|
||||
if ($same($local, $new) || $same($local, $previousSource)) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return ! $same($previousSource, $new) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
/**
|
||||
* Text eines Felds der Quelle in der Form, in der er übernommen wird: Bei `text_format: html` wird das HTML bereinigt
|
||||
* und kanonisch, sonst bleibt der Klartext, wie er geliefert wird.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
*/
|
||||
private function value(array $document, string $field): string
|
||||
{
|
||||
$raw = trim((string) ($document[$field] ?? ''));
|
||||
|
||||
return ($document['text_format'] ?? null) === 'html' && in_array($field, self::HTML_FIELDS, true)
|
||||
? FormattedText::canonicalHtml($raw)
|
||||
: $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abweichung der Durchführung einer Variante, im Format des Dokuments.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @param array<string, mixed> $variant
|
||||
*/
|
||||
private function variantChanges(array $document, array $variant): string
|
||||
{
|
||||
$raw = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
|
||||
return ($document['text_format'] ?? null) === 'html' ? FormattedText::canonicalHtml($raw) : $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ist das Feld in beiden Quellständen inhaltlich gleich? Texte werden als kanonischer Text verglichen, alles andere
|
||||
* ohne führenden und folgenden Leerraum.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function sameValue(string $field, array $before, array $after): bool
|
||||
{
|
||||
if (in_array($field, [...self::HTML_FIELDS, 'equipment'], true)) {
|
||||
return FormattedText::same($this->value($before, $field), $this->value($after, $field));
|
||||
}
|
||||
|
||||
return trim((string) ($before[$field] ?? '')) === trim((string) ($after[$field] ?? ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 === '' || FormattedText::same($composition->summary, $this->value($before, 'summary')))) {
|
||||
$composition->summary = $this->value($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, Composition $composition, 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();
|
||||
}
|
||||
|
||||
// Der Abschnitt gehört zu dieser Übung und liegt als „Übungsabschnitt“ im gemeinsamen Medienbestand.
|
||||
app(ExerciseSections::class)->mark($element, $composition);
|
||||
|
||||
return $latest !== null && FormattedText::same($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;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1794 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user