Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9407c2f98 | ||
|
|
a495b0d740 | ||
|
|
22f8afdcd6 | ||
|
|
c6a8167601 | ||
|
|
2ee1fc9866 | ||
|
|
9e2d64a4a9 | ||
|
|
a12818b752 | ||
|
|
2393000468 | ||
|
|
333e2975d5 | ||
|
|
ef876465f0 | ||
|
|
510ae7944c | ||
|
|
c8d44caa75 | ||
|
|
cbc6b30a6d | ||
|
|
bd6b62b4e3 | ||
|
|
010b4fedd4 | ||
|
|
c5d93737ec | ||
|
|
e29014a8a1 | ||
|
|
c33e47fadd | ||
|
|
04a9a4f83f | ||
|
|
6b43fbb7d1 | ||
|
|
6172364bf8 | ||
|
|
ed53bb1669 | ||
|
|
3a37e8a7a1 | ||
|
|
00b7ce9b3f | ||
|
|
bd91104970 | ||
|
|
57f3a18b82 | ||
|
|
28bd5590bc | ||
|
|
40f8a4afc2 | ||
|
|
79b58903ac | ||
|
|
5233b96c42 | ||
|
|
3cf3e822b8 | ||
|
|
6160e95d57 | ||
|
|
f0ffb47210 | ||
|
|
fbe4226347 | ||
|
|
27c1a52edf | ||
|
|
95a888d1ca | ||
|
|
61c65595e1 | ||
|
|
1af462e1d6 | ||
|
|
0ac70884cc | ||
|
|
db3a6ba779 | ||
|
|
3d76062097 | ||
|
|
28e3342b1f | ||
|
|
657578455f | ||
|
|
3b0b4c955e | ||
|
|
93ae01c986 | ||
|
|
cce22ebd81 | ||
|
|
08f7d0c63d | ||
|
|
1950dc377b | ||
|
|
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 | ||
|
|
0022fd50cb | ||
|
|
1d1f0ebb1f |
No files matched your search
+2
-1
@@ -71,6 +71,7 @@ MEDIA_PUBLIC_PATH=
|
||||
MEDIA_DERIVED_PATH=
|
||||
MEDIA_ORIGINALS_PATH=
|
||||
|
||||
# Übernahme von Übungen aus Shinkan (Test: erst nach Freigabe der Anbindung eintragen; Werte nie ins Repository)
|
||||
# Ü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=
|
||||
@@ -41,6 +41,7 @@ ## 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.
|
||||
@@ -64,5 +65,8 @@ ## 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`.
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Communication\CommunicationSettings;
|
||||
use App\Domain\Communication\Inquiry;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
/**
|
||||
* Löscht Anfragen, die älter sind als die in „Kommunikation → Einstellungen“ gewählte Aufbewahrungsdauer. Ohne
|
||||
* Aufbewahrungsdauer geschieht nichts. Mit --pretend wird nur gezählt.
|
||||
*/
|
||||
class PurgeInquiries extends Command
|
||||
{
|
||||
protected $signature = 'communication:purge {--pretend : Nur zählen, nichts löschen}';
|
||||
|
||||
protected $description = 'Löscht Anfragen nach Ablauf der Aufbewahrungsdauer (Einstellungen der Kommunikationsverwaltung)';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$months = CommunicationSettings::current()->retention_months;
|
||||
|
||||
if ($months === null || $months < 1) {
|
||||
$this->info('Keine Aufbewahrungsdauer eingestellt; es wird nichts gelöscht.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$query = Inquiry::query()->where('created_at', '<', now()->subMonths($months));
|
||||
$count = $query->count();
|
||||
|
||||
if ($this->option('pretend')) {
|
||||
$this->info("$count Anfragen wären älter als $months Monate.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$query->delete();
|
||||
$this->info("$count Anfragen gelöscht (älter als $months Monate).");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ class Composition extends Model
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'working_draft',
|
||||
'pdf_template_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -46,6 +47,12 @@ 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);
|
||||
|
||||
@@ -9,6 +9,8 @@ enum CompositionKind: string
|
||||
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>
|
||||
@@ -25,6 +27,7 @@ public function label(): string
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Kurs',
|
||||
self::Exercise => 'Übung',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -35,6 +38,7 @@ public function plural(): string
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
self::Document => 'Dokumente',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,6 +49,7 @@ public function createLabel(): string
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung anlegen',
|
||||
self::Document => 'Dokument anlegen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,6 +60,7 @@ public function explanation(): string
|
||||
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.',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -65,6 +71,7 @@ public function deskLabel(): string
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -74,7 +81,7 @@ public function deskExplanation(): string
|
||||
self::Kombination => $this->explanation(),
|
||||
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
|
||||
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
|
||||
self::Exercise => $this->explanation(),
|
||||
self::Exercise, self::Document => $this->explanation(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -367,6 +367,7 @@ private function materialize(
|
||||
'duration_max' => $didactic['duration_max'] ?? null,
|
||||
'material_note' => $didactic['material_note'] ?? null,
|
||||
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||
'document_meta' => $didactic['document_meta'] ?? null,
|
||||
],
|
||||
$variants,
|
||||
);
|
||||
@@ -432,6 +433,7 @@ private function resolveTarget(string $target, ?User $actor, array $stack): Cont
|
||||
'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,
|
||||
|
||||
@@ -21,12 +21,14 @@ class CompositionVersion extends Model
|
||||
'prerequisites',
|
||||
'structure_hash',
|
||||
'source_snapshot_id',
|
||||
'document_meta',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => ContentVersionStatus::class,
|
||||
'document_meta' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ class ContentElement extends Model
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'source_ref',
|
||||
'origin_composition_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -47,6 +48,12 @@ 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);
|
||||
|
||||
@@ -23,7 +23,7 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'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)) {
|
||||
@@ -51,6 +51,10 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) {
|
||||
$rows[] = $image;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -79,6 +83,34 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
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')));
|
||||
|
||||
@@ -164,6 +164,42 @@ public function reviseElementContent(ContentElementVersion $version, string $bod
|
||||
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');
|
||||
@@ -190,6 +226,44 @@ public function elementReleaseProblem(ContentElementVersion $version): ?string
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -261,6 +335,7 @@ public function publishComposition(
|
||||
'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,
|
||||
]);
|
||||
|
||||
@@ -320,6 +395,8 @@ 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,
|
||||
@@ -328,6 +405,8 @@ public function structureHash(CompositionVersion $version): string
|
||||
$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(),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ class EditorialContentKind extends Model
|
||||
'medium' => 'Medium',
|
||||
'modul' => 'Modul',
|
||||
'uebung' => 'Übung',
|
||||
'dokument' => 'Dokument',
|
||||
'programm' => 'Programm',
|
||||
'lizenzartikel' => 'Lizenzartikel',
|
||||
];
|
||||
@@ -27,11 +28,21 @@ class EditorialContentKind extends Model
|
||||
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
|
||||
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
|
||||
*/
|
||||
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung'];
|
||||
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',
|
||||
'symbol',
|
||||
'sort_order',
|
||||
'is_active',
|
||||
'contexts',
|
||||
@@ -74,6 +85,12 @@ 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);
|
||||
|
||||
@@ -27,11 +27,34 @@ 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;
|
||||
|
||||
@@ -47,6 +47,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
CompositionKind::Document => 'dokument',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -124,10 +125,52 @@ public function kindFilterOptions(string $context, string $selected = ''): array
|
||||
|
||||
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>
|
||||
*/
|
||||
@@ -139,6 +182,7 @@ private function usedKindIds(string $context): array
|
||||
'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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $rel
|
||||
*
|
||||
* @return array{version: CompositionVersion, selection: list<string>|null}|null
|
||||
*/
|
||||
public function locate(ArticleRelease $release, string $path): ?array
|
||||
public function locate(ArticleRelease $release, string $path, CompositionKind $kind = CompositionKind::Exercise): ?array
|
||||
{
|
||||
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
|
||||
return null;
|
||||
@@ -71,7 +71,7 @@ public function locate(ArticleRelease $release, string $path): ?array
|
||||
|
||||
$version?->loadMissing('composition');
|
||||
|
||||
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
|
||||
if ($version === null || $version->composition === null || $version->composition->kind !== $kind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
{
|
||||
$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 = [];
|
||||
@@ -145,7 +146,8 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'grant' => $decision->grant,
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
|
||||
'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,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -169,6 +171,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'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,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
@@ -23,7 +24,7 @@ class ExercisePdf
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private float $y = self::TOP;
|
||||
private PdfFlow $flow;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
@@ -64,31 +65,36 @@ public function sections(array $guide): ?array
|
||||
* @param array<string, mixed> $guide
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string
|
||||
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->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
$this->flow->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
$this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$facts = array_filter([
|
||||
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
|
||||
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
|
||||
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
|
||||
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
|
||||
]);
|
||||
$this->fact('Lernziel', $guide['learning_goal']);
|
||||
|
||||
foreach ($facts as $fact) {
|
||||
$this->write(self::printable($fact), 10.5, false, 4);
|
||||
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);
|
||||
}
|
||||
|
||||
$this->y -= 6;
|
||||
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);
|
||||
@@ -107,16 +113,7 @@ public function render(array $guide, array $sections, string $licensee, string $
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
|
||||
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
$out = '';
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
|
||||
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
|
||||
}
|
||||
|
||||
return $out;
|
||||
return PdfFlow::printable($text);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -130,72 +127,42 @@ private function section(array $section, string $guideUrl): void
|
||||
$label = in_array($section['class'], ['film', 'audio'], true)
|
||||
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
|
||||
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
|
||||
$this->write(self::printable($label), 10, false, 6);
|
||||
$this->flow->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write($title, 12.5, true, 5);
|
||||
$this->flow->write($title, 12.5, true, 5, keep: 40);
|
||||
|
||||
foreach ($section['blocks'] ?? [] as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
|
||||
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
|
||||
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
|
||||
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
|
||||
};
|
||||
}
|
||||
$this->flow->formatted($section['blocks'] ?? []);
|
||||
|
||||
$this->y -= 4;
|
||||
$this->flow->y -= 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
*/
|
||||
private function items(array $items, callable $marker): void
|
||||
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
|
||||
private function fact(string $label, ?string $value): void
|
||||
{
|
||||
foreach ($items as $index => $item) {
|
||||
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
|
||||
$blocks = FormattedText::blocks($value);
|
||||
|
||||
foreach ($lines as $line => $text) {
|
||||
$this->room(14);
|
||||
|
||||
if ($line === 0) {
|
||||
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
|
||||
}
|
||||
|
||||
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
|
||||
$this->y -= 14;
|
||||
}
|
||||
if ($blocks === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
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);
|
||||
|
||||
private function write(string $text, float $size, bool $bold, float $after): void
|
||||
{
|
||||
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text(self::LEFT, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
return;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
private function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < self::BOTTOM) {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}
|
||||
$this->flow->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->flow->formatted($blocks);
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->y = self::TOP;
|
||||
$this->flow->restart();
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
|
||||
@@ -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,817 @@
|
||||
<?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'];
|
||||
|
||||
/** Schriftgrößen der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Werte stehen in `widgets.css`. */
|
||||
public const SITE_SIZES = ['small' => 'Klein', 'large' => 'Groß', 'xlarge' => 'Sehr groß'];
|
||||
|
||||
/** Schriftfarben der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Farbwerte stehen in `widgets.css`. */
|
||||
public const SITE_COLORS = ['marine' => 'Marine', 'gruen' => 'Grün', 'rot' => 'Rot', 'grau' => 'Grau'];
|
||||
|
||||
/** Ausrichtungen der Website außer der Vorgabe „linksbündig“ (so schreibt der Editor sie: `end` heißt rechtsbündig). */
|
||||
private const SITE_ALIGNMENTS = ['center', 'end'];
|
||||
|
||||
/** @var array<string, HtmlSanitizer> je Profil eine Bereinigung (siehe sanitizer()) */
|
||||
private static array $sanitizers = [];
|
||||
|
||||
/** 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.
|
||||
*
|
||||
* `$site` ist das Profil der Website (CMS): Links auf Seiten der eigenen Website (`/materialien`, `#anker`) bleiben
|
||||
* erhalten, dazu Ausrichtung (zentriert, rechtsbündig), Schriftgröße und Schriftfarbe aus festen Werten
|
||||
* ({@see self::SITE_SIZES}, {@see self::SITE_COLORS}). Verwaltung und PDF kennen nur ausdrückliche Adressen
|
||||
* (http, https, mailto) und keine dieser Auszeichnungen; sie fallen dort beim Speichern weg. Das Profil gehört zum Text:
|
||||
* Wer mit `true` speichert, liest auch mit `true`.
|
||||
*/
|
||||
public static function canonical(?string $value, bool $site = false): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value), $site);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, bool $site = false): string
|
||||
{
|
||||
$html = trim((string) $html);
|
||||
|
||||
return $html === '' ? '' : self::normalize($html, $site);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, bool $site = false): string
|
||||
{
|
||||
return self::renderImages(self::canonical($value, $site), $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, bool $site = false): string
|
||||
{
|
||||
$html = self::mapLegacyTags($html);
|
||||
$html = trim(self::sanitizer($site)->sanitize($html));
|
||||
|
||||
if ($html === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$body = $document->body;
|
||||
|
||||
if ($site) {
|
||||
self::siteMarks($document);
|
||||
}
|
||||
|
||||
// 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 (preg_match('/<p[\s>]/', $inner) !== 1) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
if (self::hasText($inner)) {
|
||||
$items .= '<li>'.$inner.'</li>';
|
||||
}
|
||||
}
|
||||
|
||||
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
|
||||
}
|
||||
|
||||
$inner = self::inner($node);
|
||||
|
||||
if ($name === 'blockquote' && preg_match('/<p[\s>]/', $inner) !== 1) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
// Die Ausrichtung ist im Webprofil schon auf `text-align: center|end` zurückgeführt (siehe siteMarks()).
|
||||
$align = $name !== 'blockquote' && preg_match('/^text-align: (?:'.implode('|', self::SITE_ALIGNMENTS).')$/', (string) $node->getAttribute('style')) === 1
|
||||
? ' style="'.$node->getAttribute('style').'"'
|
||||
: '';
|
||||
|
||||
return self::hasContent($inner) ? '<'.$name.$align.'>'.$inner.'</'.$name.'>' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Webprofil: Ausrichtung, Größe und Farbe auf feste Werte zurückführen. Stil und Klassen aus dem Editor oder von Hand
|
||||
* sind nie maßgeblich: Ein Span trägt nur noch `class="color" data-color` (bekannter Schlüssel) und/oder `data-size`
|
||||
* (bekannter Schlüssel), sonst entfällt er; Absatz und Zwischenüberschrift nur `style="text-align: center|end"`. So
|
||||
* liest der Editor den Wert beim Öffnen wieder, und ein beliebiger Stil kommt nie auf die Seite.
|
||||
*/
|
||||
private static function siteMarks(HTMLDocument $document): void
|
||||
{
|
||||
foreach (iterator_to_array($document->querySelectorAll('span')) as $span) {
|
||||
$color = (string) $span->getAttribute('data-color');
|
||||
$size = (string) $span->getAttribute('data-size');
|
||||
$color = array_key_exists($color, self::SITE_COLORS) ? $color : '';
|
||||
$size = array_key_exists($size, self::SITE_SIZES) ? $size : '';
|
||||
|
||||
if ($color === '' && $size === '') {
|
||||
while ($span->firstChild !== null) {
|
||||
$span->parentNode->insertBefore($span->firstChild, $span);
|
||||
}
|
||||
|
||||
$span->remove();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (iterator_to_array($span->attributes) as $attribute) {
|
||||
$span->removeAttribute($attribute->name);
|
||||
}
|
||||
|
||||
if ($color !== '') {
|
||||
$span->setAttribute('class', 'color');
|
||||
$span->setAttribute('data-color', $color);
|
||||
}
|
||||
|
||||
if ($size !== '') {
|
||||
$span->setAttribute('data-size', $size);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($document->querySelectorAll('p, h3, h4, h5, h6') as $block) {
|
||||
$align = preg_match('/(?:^|;)\s*text-align\s*:\s*(center|end|right)\s*(?:;|$)/i', (string) $block->getAttribute('style'), $match) === 1
|
||||
? (strtolower($match[1]) === 'center' ? 'center' : 'end')
|
||||
: null;
|
||||
|
||||
$block->removeAttribute('style');
|
||||
|
||||
if ($align !== null) {
|
||||
$block->setAttribute('style', 'text-align: '.$align);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(bool $site = false): HtmlSanitizer
|
||||
{
|
||||
if (isset(self::$sanitizers[$site ? 'site' : 'catalog'])) {
|
||||
return self::$sanitizers[$site ? 'site' : 'catalog'];
|
||||
}
|
||||
|
||||
// Das Webprofil lässt zusätzlich Spans (Größe, Farbe) und den Stil an Absätzen und Überschriften zu; siteMarks()
|
||||
// führt beides danach auf feste Werte zurück. Verwaltung und PDF kennen weder Spans noch Stile.
|
||||
$text = $site ? ['style'] : [];
|
||||
$config = (new HtmlSanitizerConfig)
|
||||
->allowElement('p', $text)
|
||||
->allowElement('h3', $text)
|
||||
->allowElement('h4', $text)
|
||||
->allowElement('h5', $text)
|
||||
->allowElement('h6', $text);
|
||||
|
||||
if ($site) {
|
||||
$config = $config->allowElement('span', ['class', 'data-color', 'data-size']);
|
||||
}
|
||||
|
||||
return self::$sanitizers[$site ? 'site' : 'catalog'] = new HtmlSanitizer(
|
||||
$config
|
||||
->allowElement('br')
|
||||
->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($site)
|
||||
->forceAttribute('a', 'rel', 'noopener noreferrer')
|
||||
->withMaxInputLength(100000),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,14 @@ class LicenseArticle extends Model
|
||||
'successor_of_id',
|
||||
'current_release_id',
|
||||
'archived_at',
|
||||
'shop_markers',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'archived_at' => 'datetime',
|
||||
'shop_markers' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ class Offer extends Model
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
'claim_access',
|
||||
'claim_requires_article_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -22,12 +24,21 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
/**
|
||||
* Altbestand: Programmseite, der eine Option mit mehreren Positionen früher von Hand zugeordnet wurde. Neue Optionen
|
||||
* haben genau eine Position; ihre Produktseite ergibt sich aus ihr (Artikel- oder Paketseite) und wird nicht zugeordnet.
|
||||
*/
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
/** Freigaben einzelner Konten für den Abruf (nur bei Vergabe „auf Abruf“ mit der Regel „freigeschaltete Konten“). */
|
||||
public function releases(): HasMany
|
||||
{
|
||||
return $this->hasMany(OfferRelease::class);
|
||||
}
|
||||
|
||||
/** Bezeichnung der Option auf der Produktseite. */
|
||||
public function optionName(): string
|
||||
{
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Freigabe eines Kontos für ein Angebot „auf Abruf“ (ADR-56). Gilt je Angebot und Konto, wird nie gelöscht, nur entzogen.
|
||||
*/
|
||||
class OfferRelease extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'offer_id',
|
||||
'user_id',
|
||||
'granted_by',
|
||||
'granted_at',
|
||||
'valid_until',
|
||||
'revoked_by',
|
||||
'revoked_at',
|
||||
'reason',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'granted_at' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'revoked_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function offer(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Offer::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function grantor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'granted_by');
|
||||
}
|
||||
|
||||
public function isActiveAt(CarbonInterface $now): bool
|
||||
{
|
||||
return $this->revoked_at === null
|
||||
&& $this->granted_at->lessThanOrEqualTo($now)
|
||||
&& ($this->valid_until === null || $this->valid_until->greaterThan($now));
|
||||
}
|
||||
}
|
||||
@@ -106,9 +106,7 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'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->assertBuyable($lines, $attributes);
|
||||
|
||||
$this->assertAttributes($attributes);
|
||||
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||
@@ -165,6 +163,68 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Bietet einen Lizenzartikel als Kauf an: legt die Option (Angebot) an und aktiviert ihre erste Fassung in einem
|
||||
* Schritt. Besteht eine Prüfung nicht (Stand, Preis, Rechte), bleibt kein leeres Angebot zurück.
|
||||
*
|
||||
* @param array<string, mixed> $attributes holder_kind, licence_scope, trainer_count, price_cents
|
||||
*/
|
||||
public function offerArticle(LicenseArticle $article, RightsProfileVersion $rights, array $attributes, string $name, ?string $label = null): OfferVersion
|
||||
{
|
||||
return DB::transaction(function () use ($article, $rights, $attributes, $name, $label): OfferVersion {
|
||||
$offer = $this->create($name);
|
||||
$this->setOptionLabel($offer, $label);
|
||||
|
||||
return $this->activate($offer, [['target' => $article, 'rights' => $rights]], [...$attributes, 'grant_kind' => 'kauf']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ändert eine Option eines Artikels: Die nächste Fassung wird aktiv, die bisherige bleibt gespeichert. Bedingungen,
|
||||
* die die Maske nicht zeigt (Laufzeit, Steuerklasse), bleiben die der letzten Fassung. Die Option muss den Artikel
|
||||
* als einzige Position verkaufen.
|
||||
*
|
||||
* @param array<string, mixed> $attributes holder_kind, licence_scope, trainer_count, price_cents
|
||||
*/
|
||||
public function reviseArticleOption(Offer $offer, LicenseArticle $article, RightsProfileVersion $rights, array $attributes, ?string $label = null): OfferVersion
|
||||
{
|
||||
return DB::transaction(function () use ($offer, $article, $rights, $attributes, $label): OfferVersion {
|
||||
$latest = $offer->versions()->with('lines')->orderByDesc('number')->first();
|
||||
|
||||
if ($latest === null || $latest->lines->count() !== 1 || (int) $latest->lines->first()->license_article_id !== $article->id) {
|
||||
throw new DomainRuleException('Diese Option gehört nicht zu diesem Lizenzartikel.');
|
||||
}
|
||||
|
||||
if ($latest->grant_kind !== 'kauf') {
|
||||
throw new DomainRuleException('Nur eine Option, die als Kauf angeboten wird, lässt sich so ändern. Vergaben auf Abruf oder bei Registrierung bearbeitest du am Angebot.');
|
||||
}
|
||||
|
||||
$this->setOptionLabel($offer, $label);
|
||||
|
||||
return $this->activate($offer, [['target' => $article, 'rights' => $rights]], [
|
||||
'term_rule' => $latest->term_rule,
|
||||
'tax_class' => $latest->tax_class,
|
||||
'dynamic' => (bool) $latest->dynamic,
|
||||
...$attributes,
|
||||
'grant_kind' => 'kauf',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschlag für die Bezeichnung einer Option, wenn keine eingegeben wird: Nutzerkreis und Eignung.
|
||||
*/
|
||||
public static function defaultOptionLabel(?string $holderKind, ?string $licenceScope, mixed $trainers): string
|
||||
{
|
||||
$scope = match ($licenceScope) {
|
||||
LicenceScope::MULTI => 'Mehrfachlizenz ('.(int) $trainers.' Trainer)',
|
||||
LicenceScope::SINGLE => 'Einzellizenz',
|
||||
default => 'Lizenz',
|
||||
};
|
||||
|
||||
return $scope.' für '.($holderKind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -183,21 +243,11 @@ public function end(Offer $offer): OfferVersion
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Die Bezeichnung der Option auf der Produktseite. Die Seite selbst wird nicht zugeordnet: Sie ist die Seite des
|
||||
* Artikels bzw. des Pakets, das die einzige Position der Fassung verkauft. Die Bezeichnung ist keine bindende Kondition.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
public function setOptionLabel(Offer $offer, ?string $optionLabel): 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();
|
||||
|
||||
@@ -212,6 +262,29 @@ public function scopeArticleIds(OfferVersion $version): array
|
||||
return $version->resolvedScopes()->orderBy('id')->pluck('license_article_id')->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Kauf muss im Shop auffindbar und kaufbar sein, sonst lässt er sich nicht aktivieren: Er verkauft genau einen
|
||||
* Artikel oder ein Paket (das ist die Produktseite) und hat einen Preis. Mehrere Artikel gemeinsam verkauft ein
|
||||
* Paket. Vergaben bei Registrierung oder auf Abruf stehen nie im Shop und sind davon ausgenommen.
|
||||
*
|
||||
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
private function assertBuyable(array $lines, array $attributes): void
|
||||
{
|
||||
if (($attributes['grant_kind'] ?? null) !== 'kauf') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($lines) !== 1) {
|
||||
throw new DomainRuleException('Ein Kauf verkauft genau einen Artikel oder ein Paket. Mehrere Artikel gemeinsam verkaufst du als Paket (Katalog → Pakete).');
|
||||
}
|
||||
|
||||
if (! is_int($attributes['price_cents'] ?? null) || $attributes['price_cents'] <= 0) {
|
||||
throw new DomainRuleException('Ein Kauf braucht einen Preis über 0,00 €.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use App\Domain\Media\WebsitePresentation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -430,6 +431,32 @@ public function coverElementId(Model $subject): ?int
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das öffentlich zeigbare Titelbild: das erste Titel- oder Galeriebild in der Reihenfolge der Rollen, das für die
|
||||
* Website freigegeben ist (WebsiteMedia). Ein nicht freigegebenes Bild wird übersprungen, nie ausgeliefert.
|
||||
*/
|
||||
public function coverPresentation(Model $subject): ?WebsitePresentation
|
||||
{
|
||||
$assignments = PresentationAssignment::query()
|
||||
->with('role')
|
||||
->where('subject_type', $subject->getMorphClass())
|
||||
->where('subject_id', $subject->getKey())
|
||||
->orderBy('position')
|
||||
->get();
|
||||
|
||||
foreach (PresentationRole::COVER_ROLES as $slug) {
|
||||
foreach ($assignments->filter(fn (PresentationAssignment $row): bool => $row->role?->slug === $slug) as $row) {
|
||||
$presentation = $this->website->present((int) $row->content_element_id);
|
||||
|
||||
if ($presentation !== null && $presentation->kind === 'bild') {
|
||||
return $presentation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function owned(Model $subject, int $assignmentId): PresentationAssignment
|
||||
{
|
||||
$assignment = PresentationAssignment::query()
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -15,26 +15,85 @@
|
||||
* 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 adopt}) und ist danach unveränderlich. Lokale
|
||||
* Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten.
|
||||
* - 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`.
|
||||
* 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, Rolle]. */
|
||||
private const SECTIONS = [
|
||||
/** 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 filled(config('services.shinkan.url')) && filled(config('services.shinkan.key'));
|
||||
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
|
||||
@@ -42,7 +101,7 @@ 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 und Schlüssel fehlen in der Umgebung.');
|
||||
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');
|
||||
@@ -142,10 +201,234 @@ public function state(ExerciseSource $source): string
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
||||
* entsteht keine zweite Fassung. Lokale Ergänzungen der bisherigen Fassung werden übernommen.
|
||||
* 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 adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null): CompositionVersion
|
||||
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();
|
||||
|
||||
@@ -153,65 +436,87 @@ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null): Co
|
||||
return $snapshot->adoptedVersion;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($snapshot, $actor): CompositionVersion {
|
||||
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';
|
||||
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
|
||||
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
$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 (self::SECTIONS as $field => $label) {
|
||||
$text = trim((string) ($document[$field] ?? ''));
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'variant') {
|
||||
$variants[] = $item['variant'];
|
||||
|
||||
if ($text !== '') {
|
||||
$members[] = [
|
||||
'role' => $label,
|
||||
'target' => $this->section($source, $field, $title.' · '.$label, $text),
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
||||
$key = (string) ($variant['id'] ?? '');
|
||||
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$variants[] = [
|
||||
'key' => $key,
|
||||
'name' => (string) ($variant['name'] ?? '') ?: 'Variante',
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
$changes = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
$latest = $item['latest'];
|
||||
$decision = $item['decision'];
|
||||
|
||||
if ($changes !== '') {
|
||||
$members[] = [
|
||||
'role' => 'Abweichung der Durchführung',
|
||||
'target' => $this->section($source, 'variant:'.$key, $title.' · '.($variant['name'] ?? 'Variante').' · Abweichung', $changes),
|
||||
'variant' => $key,
|
||||
'origin' => 'quelle',
|
||||
];
|
||||
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);
|
||||
}
|
||||
|
||||
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'));
|
||||
// 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,
|
||||
'Übernahme aus Shinkan',
|
||||
self::IMPORT_NOTE,
|
||||
[
|
||||
'learning_goal' => $document['goal'] ?? null,
|
||||
'duration_minutes' => $document['duration_min'] ?? null,
|
||||
'duration_max' => $document['duration_max'] ?? null,
|
||||
'material_note' => $document['equipment'] ?? null,
|
||||
'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],
|
||||
@@ -224,14 +529,182 @@ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null): Co
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, wandert in den gemeinsamen Teil, damit nichts verloren geht.
|
||||
* 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
|
||||
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): array
|
||||
{
|
||||
if ($previous === null) {
|
||||
return [[], []];
|
||||
@@ -245,11 +718,26 @@ private function localAdditions(?CompositionVersion $previous, array $sourceVari
|
||||
|
||||
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 !== null && in_array($variant, $known, true) ? $variant : null,
|
||||
'variant' => $variant,
|
||||
'requirement' => $member->requirement,
|
||||
'selection' => $member->variant_selection,
|
||||
'origin' => 'lokal',
|
||||
@@ -262,7 +750,7 @@ private function localAdditions(?CompositionVersion $previous, array $sourceVari
|
||||
/**
|
||||
* Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung.
|
||||
*/
|
||||
private function section(ExerciseSource $source, string $field, string $title, string $text): ContentElementVersion
|
||||
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;
|
||||
@@ -274,11 +762,12 @@ private function section(ExerciseSource $source, string $field, string $title, s
|
||||
$element->save();
|
||||
}
|
||||
|
||||
$latest = $element->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
// Der Abschnitt gehört zu dieser Übung und liegt als „Übungsabschnitt“ im gemeinsamen Medienbestand.
|
||||
app(ExerciseSections::class)->mark($element, $composition);
|
||||
|
||||
return $latest !== null && trim((string) $latest->body) === $text
|
||||
return $latest !== null && FormattedText::same($latest->body, $text)
|
||||
? $latest
|
||||
: $content->publishElementVersion($element, $text, [], 'Übernahme aus Shinkan');
|
||||
: $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE);
|
||||
}
|
||||
|
||||
private function createComposition(string $title, string $summary): Composition
|
||||
@@ -295,16 +784,33 @@ private function createComposition(string $title, string $summary): Composition
|
||||
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 = []): array
|
||||
private function get(string $path, array $query = [], ?string $key = null): array
|
||||
{
|
||||
$response = Http::withToken((string) config('services.shinkan.key'))
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$response = Http::withToken((string) ($key ?? $connection->apiKey()))
|
||||
->acceptJson()
|
||||
->timeout(20)
|
||||
->get(rtrim((string) config('services.shinkan.url'), '/').'/api/distribution/v1'.$path, $query)
|
||||
->get((string) $connection->url().'/api/distribution/v1'.$path, $query)
|
||||
->throw();
|
||||
|
||||
$json = $response->json();
|
||||
@@ -338,9 +844,41 @@ private function finish(ExerciseImportRun $run, string $status, array $counts =
|
||||
private function plain(Throwable $exception): string
|
||||
{
|
||||
if ($exception instanceof RequestException) {
|
||||
return 'Die Quelle antwortete mit Status '.$exception->response->status().'.';
|
||||
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().'.',
|
||||
};
|
||||
}
|
||||
|
||||
return $exception instanceof DomainRuleException ? $exception->getMessage() : 'Die Quelle ist nicht erreichbar.';
|
||||
if ($exception instanceof DomainRuleException) {
|
||||
return $exception->getMessage();
|
||||
}
|
||||
|
||||
return $this->networkCause($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
|
||||
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
|
||||
*/
|
||||
private function networkCause(Throwable $exception): string
|
||||
{
|
||||
$host = app(ShinkanConnection::class)->url();
|
||||
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
|
||||
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
|
||||
$code = isset($match[1]) ? (int) $match[1] : null;
|
||||
|
||||
$cause = match (true) {
|
||||
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
|
||||
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
|
||||
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
|
||||
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
|
||||
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
|
||||
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
|
||||
default => 'Netzwerkfehler.',
|
||||
};
|
||||
|
||||
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Ein Bild einer PDF-Vorlage (ADR-51, Nachtrag). Es kommt aus dem Medienmanager in einer von zwei Formen, die der gemeinsame
|
||||
* Picker als Ziel liefert:
|
||||
*
|
||||
* - `element:<Fassung>`: ein Bild mit Inhaltsfassung (Datei im abgeleiteten Bestand), gleich in welchem Stand; nur ein gesperrtes Bild nicht,
|
||||
* - `medium:<Medium>`: ein Bild ohne Inhaltsfassung, also ein Präsentationsmedium oder ein für die Website freigegebenes Bild. Gedruckt wird
|
||||
* die für die Website freigegebene Datei, sonst die Präsentationsdatei.
|
||||
*
|
||||
* Jedes Bild mit vorhandener Datei lässt sich verwenden. Das Bild ist Gestaltung der Vorlage und kein lizenzierter Inhalt; es geht nicht über
|
||||
* die Rechteprüfung der Mitglieder und braucht keine Inhaltsfassung.
|
||||
*/
|
||||
final class TemplateImage
|
||||
{
|
||||
/**
|
||||
* @return array{type: 'version'|'medium', id: int}|null
|
||||
*/
|
||||
public static function parse(?string $target): ?array
|
||||
{
|
||||
if ($target !== null && preg_match('/^(element|medium):(\d+)$/', $target, $match) === 1) {
|
||||
return ['type' => $match[1] === 'element' ? 'version' : 'medium', 'id' => (int) $match[2]];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Die Bilddatei als Bytes, oder null, wenn sie nicht vorliegt. */
|
||||
public static function bytes(?string $target): ?string
|
||||
{
|
||||
$source = self::source($target);
|
||||
|
||||
return $source === null ? null : (string) Storage::disk($source['disk'])->get($source['path']);
|
||||
}
|
||||
|
||||
/** Warum sich das Bild nicht verwenden lässt; null, wenn es geht. */
|
||||
public static function problem(?string $target): ?string
|
||||
{
|
||||
$ref = self::parse($target);
|
||||
|
||||
if ($ref === null) {
|
||||
return 'Das ist kein Bild des Medienmanagers.';
|
||||
}
|
||||
|
||||
if ($ref['type'] === 'version') {
|
||||
$version = ContentElementVersion::query()->with('element')->find($ref['id']);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return 'Das ist kein Bild des Medienmanagers.';
|
||||
}
|
||||
|
||||
// Gestaltung braucht keine Freigabe der Fassung; nur ein bewusst gesperrtes Bild bleibt außen vor.
|
||||
if ($version->status === ContentVersionStatus::Gesperrt) {
|
||||
return 'Dieses Bild ist deaktiviert.';
|
||||
}
|
||||
} else {
|
||||
$element = ContentElement::query()->find($ref['id']);
|
||||
|
||||
if (! $element instanceof ContentElement || $element->output_class !== 'bild' || $element->archived_at !== null) {
|
||||
return 'Das ist kein Bild des Medienmanagers.';
|
||||
}
|
||||
}
|
||||
|
||||
return self::source($target) === null ? 'Die Bilddatei liegt nicht vor.' : null;
|
||||
}
|
||||
|
||||
public static function title(?string $target): string
|
||||
{
|
||||
$ref = self::parse($target);
|
||||
$element = match ($ref['type'] ?? null) {
|
||||
'version' => ContentElementVersion::query()->with('element')->find($ref['id'])?->element,
|
||||
'medium' => ContentElement::query()->find($ref['id']),
|
||||
default => null,
|
||||
};
|
||||
|
||||
return $element === null ? '' : (string) ($element->display_title ?: $element->working_title);
|
||||
}
|
||||
|
||||
/** Adresse zur Ansicht in der Verwaltung (Vorschau im Formular). */
|
||||
public static function previewUrl(?string $target): ?string
|
||||
{
|
||||
$ref = self::parse($target);
|
||||
|
||||
if ($ref === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($ref['type'] === 'version') {
|
||||
return EmbeddedImages::staffSource($ref['id']);
|
||||
}
|
||||
|
||||
$element = ContentElement::query()->find($ref['id']);
|
||||
|
||||
if (! $element instanceof ContentElement) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($element->website_released_at !== null && $element->website_public_path !== null) {
|
||||
return route('website.media', $element);
|
||||
}
|
||||
|
||||
return app(EditorialCatalog::class)->cardUrl('element', $element->id, $element->thumbnail_path);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{disk: string, path: string}|null
|
||||
*/
|
||||
private static function source(?string $target): ?array
|
||||
{
|
||||
$ref = self::parse($target);
|
||||
|
||||
if ($ref === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($ref['type'] === 'version') {
|
||||
$version = ContentElementVersion::query()->find($ref['id']);
|
||||
$file = $version instanceof ContentElementVersion ? EmbeddedImages::file($version) : null;
|
||||
|
||||
return $file === null ? null : ['disk' => 'media_derived', 'path' => $file];
|
||||
}
|
||||
|
||||
$element = ContentElement::query()->find($ref['id']);
|
||||
|
||||
if (! $element instanceof ContentElement) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$public = (string) $element->website_public_path;
|
||||
|
||||
if ($element->website_released_at !== null && preg_match('#^website/'.$element->id.'/datei\.[a-z0-9]+$#', $public) === 1 && Storage::disk('media_public')->exists($public)) {
|
||||
return ['disk' => 'media_public', 'path' => $public];
|
||||
}
|
||||
|
||||
$preview = (string) $element->thumbnail_path;
|
||||
|
||||
if (str_starts_with($preview, 'vorschau/') && ! str_contains($preview, '..') && Storage::disk('media_derived')->exists($preview)) {
|
||||
return ['disk' => 'media_derived', 'path' => $preview];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
@@ -39,6 +41,7 @@ public function __construct(
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
@@ -166,7 +167,7 @@ public function entries(array $refs, bool $includeNonPublic): array
|
||||
$entries[] = new CatalogEntry(
|
||||
id: $composition->id,
|
||||
title: $this->title($composition),
|
||||
summary: filled($composition->summary) ? (string) $composition->summary : null,
|
||||
summary: FormattedText::plain($composition->summary) ?: null,
|
||||
kindLabel: (string) ($composition->editorialContentKind?->label ?? ''),
|
||||
url: $public ? route('public.program', $composition) : null,
|
||||
public: $public,
|
||||
@@ -264,7 +265,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
$kind = (string) ($composition->editorialContentKind?->label ?? ($program ? 'Programm' : 'Modul'));
|
||||
$profile = app(EditorialProfileReader::class)->read($composition, 'kachel');
|
||||
$summary = $profile->value('teaser') ?: $profile->value('summary');
|
||||
$goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null;
|
||||
$goal = FormattedText::plain($version?->learning_goal) ?: null;
|
||||
// Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“).
|
||||
$texts = [
|
||||
'teaser' => $profile->value('teaser'),
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\MaterialTag;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
@@ -36,8 +38,8 @@
|
||||
*/
|
||||
class PublicMaterialReader
|
||||
{
|
||||
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen. */
|
||||
public const CONFIDENTIAL_KINDS = ['traineranleitung'];
|
||||
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen: Anleitungen für Trainer und die Textabschnitte der Übungen. */
|
||||
public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt', 'dokumentkapitel'];
|
||||
|
||||
/** @var array<int, array{id: int, title: string}>|null Element-ID => erstes öffentliches Programm */
|
||||
private ?array $publicIndex = null;
|
||||
@@ -174,7 +176,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$output = self::outputLabel((string) $shown->output_class);
|
||||
$film = $shown->output_class === 'film';
|
||||
$editorialKind = $element->editorialContentKind?->label;
|
||||
$summary = filled($shown->summary) ? trim((string) $shown->summary) : null;
|
||||
$summary = FormattedText::plain($shown->summary) ?: null;
|
||||
$profile = app(EditorialProfileReader::class)->read($shown, 'bibliothek');
|
||||
|
||||
if (! array_key_exists('summary', $draft) && $profile->origin('summary') === 'variante') {
|
||||
@@ -186,7 +188,8 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null;
|
||||
$own = filled($shown->getAttribute($field)) ? trim(in_array($field, FormattedText::FIELDS, true) ? FormattedText::plain((string) $shown->getAttribute($field)) : (string) $shown->getAttribute($field)) : null;
|
||||
$own = $own === '' ? null : $own;
|
||||
|
||||
if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') {
|
||||
$own = $profile->value($field);
|
||||
@@ -235,6 +238,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms;
|
||||
|
||||
use App\Domain\Cms\Sections\PageSections;
|
||||
|
||||
/**
|
||||
* Interne Linkziele für die Auswahl im CMS: Seiten mit ihrem Veröffentlichungszustand und die Sprungmarken ihrer
|
||||
* Abschnitte. Rein lesend; das Ergebnis ist eine Adresse, die in ein Linkfeld oder einen Menüeintrag geschrieben wird.
|
||||
*
|
||||
* Adressformen: „/pfad“, „/pfad#marke“ (andere Seite) und „#marke“ (dieselbe Seite). Sie bestehen SafeUrl.
|
||||
*/
|
||||
class LinkTargets
|
||||
{
|
||||
public function __construct(private readonly PageSections $sections) {}
|
||||
|
||||
/**
|
||||
* Seiten für die Auswahl, nach Adresse sortiert. Suche in Titel und Adresse.
|
||||
*
|
||||
* @return list<array{id: int, titel: string, pfad: string, zustand: array{label: string, ton: string}, marken: int}>
|
||||
*/
|
||||
public function pages(string $search = '', ?int $exceptId = null): array
|
||||
{
|
||||
$needle = mb_strtolower(trim($search));
|
||||
|
||||
return Page::query()->with(['latestRevision', 'publishedRevision'])->orderBy('path')->get()
|
||||
->reject(fn (Page $page): bool => $page->getKey() === $exceptId)
|
||||
->map(fn (Page $page): array => [
|
||||
'id' => (int) $page->getKey(),
|
||||
'titel' => $page->latestRevision?->contentTitle() ?: $page->path,
|
||||
'pfad' => $page->path,
|
||||
'zustand' => $this->state($page),
|
||||
'marken' => count($this->anchorsOf($page->latestRevision?->sections() ?? [])),
|
||||
])
|
||||
->filter(fn (array $page): bool => $needle === '' || str_contains(mb_strtolower($page['titel'].' '.$page['pfad']), $needle))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{label: string, ton: string}
|
||||
*/
|
||||
public function state(Page $page): array
|
||||
{
|
||||
if ($page->published_revision_id === null) {
|
||||
return ['label' => 'Nur Entwurf, öffentlich nicht erreichbar', 'ton' => 'offen'];
|
||||
}
|
||||
|
||||
return $page->latestRevision !== null && $page->latestRevision->id !== $page->published_revision_id
|
||||
? ['label' => 'Veröffentlicht · Entwurf neuer', 'ton' => 'gut']
|
||||
: ['label' => 'Veröffentlicht', 'ton' => 'gut'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sprungmarken einer gespeicherten Seite: die des neuesten Entwurfs, je mit dem Hinweis, ob sie schon
|
||||
* veröffentlicht sind und ob der Abschnitt ausgeblendet ist.
|
||||
*
|
||||
* @return list<array{anchor: string, label: string, hidden: bool, published: bool}>
|
||||
*/
|
||||
public function anchorsForPage(Page $page): array
|
||||
{
|
||||
$published = collect($this->anchorsOf($page->publishedRevision?->sections() ?? []))
|
||||
->filter(fn (array $anchor): bool => ! $anchor['hidden'])
|
||||
->pluck('anchor')
|
||||
->all();
|
||||
|
||||
return array_map(
|
||||
fn (array $anchor): array => $anchor + ['published' => in_array($anchor['anchor'], $published, true)],
|
||||
$this->anchorsOf($page->latestRevision?->sections() ?? $page->publishedRevision?->sections() ?? []),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sprungmarken der Abschnitte im Editor, auch ungespeicherte. Für „diese Seite“.
|
||||
*
|
||||
* @param list<array<string, mixed>> $sections Abschnitte im Modell (nach SectionEditor::fromEditorState)
|
||||
* @return list<array{anchor: string, label: string, hidden: bool, published: bool}>
|
||||
*/
|
||||
public function anchorsInEditor(array $sections): array
|
||||
{
|
||||
return array_map(fn (array $anchor): array => $anchor + ['published' => false], $this->anchorsOf($sections));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $sections
|
||||
* @return list<array{anchor: string, label: string, hidden: bool}>
|
||||
*/
|
||||
public function anchorsOf(array $sections): array
|
||||
{
|
||||
$anchors = [];
|
||||
|
||||
foreach (array_values($sections) as $position => $section) {
|
||||
$anchor = PageSections::cleanAnchor($section['anchor'] ?? null);
|
||||
|
||||
if ($anchor === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = PageSections::cleanName($section['name'] ?? null);
|
||||
$anchors[] = [
|
||||
'anchor' => $anchor,
|
||||
'label' => $name ?? 'Abschnitt '.($position + 1),
|
||||
'hidden' => PageSections::isHidden($section['hidden'] ?? false),
|
||||
];
|
||||
}
|
||||
|
||||
return $anchors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse für ein Linkfeld: „/pfad“, „/pfad#marke“ oder (dieselbe Seite) „#marke“.
|
||||
*/
|
||||
public function href(?string $path, ?string $anchor): ?string
|
||||
{
|
||||
$anchor = $anchor !== null && $anchor !== '' ? PageSections::cleanAnchor($anchor) : null;
|
||||
|
||||
if ($path === null) {
|
||||
return $anchor !== null ? '#'.$anchor : null;
|
||||
}
|
||||
|
||||
return $path.($anchor !== null ? '#'.$anchor : '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollständige öffentliche Adresse mit Sprungmarke, für Verweise von außen.
|
||||
*/
|
||||
public function publicUrl(Page $page, ?string $anchor = null): string
|
||||
{
|
||||
return $page->publicUrl().($anchor !== null && $anchor !== '' ? '#'.$anchor : '');
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Domain\Cms;
|
||||
|
||||
use App\Domain\Cms\Sections\PageSections;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
@@ -31,6 +33,7 @@ class NavigationItem extends Model
|
||||
'label',
|
||||
'page_id',
|
||||
'url',
|
||||
'anchor',
|
||||
'placement',
|
||||
'sort_order',
|
||||
'is_visible',
|
||||
@@ -79,8 +82,15 @@ public function scopeVisible(Builder $query): void
|
||||
|
||||
public function href(): ?string
|
||||
{
|
||||
// Ein Menüpunkt in den Shop erscheint nicht, solange der Shop nicht sichtbar ist: Er führte ins Leere (404).
|
||||
if ($this->pointsIntoShop() && ! Shop::visible()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->page !== null) {
|
||||
return $this->page->path === '/' ? url('/') : url($this->page->path);
|
||||
$anchor = PageSections::cleanAnchor($this->anchor);
|
||||
|
||||
return ($this->page->path === '/' ? url('/') : url($this->page->path)).($anchor !== null ? '#'.$anchor : '');
|
||||
}
|
||||
|
||||
if ($this->url === null || $this->url === '' || ! SafeUrl::isSafe($this->url)) {
|
||||
@@ -94,6 +104,24 @@ public function href(): ?string
|
||||
return $this->url;
|
||||
}
|
||||
|
||||
/** Ziel ist der Shop selbst oder eine seiner Seiten: Übersicht, Produktseiten, Hinweisseite, Warenkorb, Kasse. */
|
||||
private function pointsIntoShop(): bool
|
||||
{
|
||||
$path = $this->targetPath();
|
||||
|
||||
if ($path === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (['/shop', '/warenkorb', '/kasse', '/kauf-noch-nicht-moeglich'] as $prefix) {
|
||||
if ($path === $prefix || str_starts_with($path, $prefix.'/')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad des Ziels innerhalb der Website (für die Kennzeichnung des aktiven Eintrags); null bei externen Zielen.
|
||||
*/
|
||||
|
||||
@@ -18,6 +18,13 @@
|
||||
* Version 2 (Abstände): oben, unten und Widget-Abstand sind drei unabhängige Werte. Hüllen der Version 1 werden beim
|
||||
* Lesen übersetzt (SectionStyle::migrateSpacing), ohne die Darstellung zu ändern; gespeicherte Revisionen bleiben.
|
||||
*
|
||||
* Optionale Felder des Abschnitts (abwärtskompatibel, fehlen in älteren Revisionen):
|
||||
* - name: interner Name zur Orientierung im Seitenaufbau (nie öffentlich), höchstens 80 Zeichen;
|
||||
* - anchor: Sprungmarke, wird als Element-Kennung des Abschnitts ausgegeben (Link „#marke“ oder „/pfad#marke“),
|
||||
* je Seite eindeutig, nur Kleinbuchstaben, Ziffern und Bindestriche;
|
||||
* - hidden: true blendet den Abschnitt auf der Website aus; er bleibt im Entwurf und in den Revisionen erhalten.
|
||||
* Ältere Programmstände kennen „hidden“ nicht und würden einen ausgeblendeten Abschnitt zeigen (siehe Release-Vorbereitung).
|
||||
*
|
||||
* Jeder Slot enthält höchstens ein Widget aus dem zentralen Widget-Register. Abschnitte sind nicht verschachtelbar.
|
||||
* Revisionen ohne Abschnitte (Bestand vor dieser Fassung) werden beim Lesen als einspaltige Abschnitte gelesen.
|
||||
*/
|
||||
@@ -29,6 +36,20 @@ class PageSections
|
||||
|
||||
public const MAX_WIDGETS = 60;
|
||||
|
||||
public const MAX_NAME = 80;
|
||||
|
||||
public const MAX_ANCHOR = 60;
|
||||
|
||||
/**
|
||||
* Kennungen, die im Seitengerüst schon vergeben sind (Hauptbereich, Navigation, Fuß) oder als Vorgabe dienen.
|
||||
* Eine Sprungmarke darf sie nicht wiederholen.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
public const RESERVED_ANCHORS = ['inhalt', 'main', 'top', 'site-nav', 'fuss-themen', 'mb-account-menu'];
|
||||
|
||||
public const ANCHOR_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
|
||||
|
||||
public function __construct(private readonly WidgetRegistry $widgets) {}
|
||||
|
||||
/**
|
||||
@@ -36,7 +57,7 @@ public function __construct(private readonly WidgetRegistry $widgets) {}
|
||||
*
|
||||
* @param array<int|string, mixed>|null $sections gespeicherte Abschnitte (Spalte sections)
|
||||
* @param array<int|string, mixed>|null $blocks flache Bausteinliste (Spalte blocks), nur ohne Abschnitte verwendet
|
||||
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
public function read(?array $sections, ?array $blocks = null): array
|
||||
{
|
||||
@@ -59,7 +80,7 @@ public function read(?array $sections, ?array $blocks = null): array
|
||||
* „sections.N.layout“, „sections.N.style.image“, „sections.N.slots“, „sections.N.slots.M.data.feld“.
|
||||
*
|
||||
* @param array<int|string, mixed> $content
|
||||
* @return list<array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
* @return list<array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
public function normalize(array $content): array
|
||||
{
|
||||
@@ -75,6 +96,7 @@ public function normalize(array $content): array
|
||||
$sections = [];
|
||||
$seenSectionIds = [];
|
||||
$seenWidgetIds = [];
|
||||
$seenAnchors = [];
|
||||
$widgetCount = 0;
|
||||
|
||||
// Eingaben mit Abständen der Version 1 (zum Beispiel ältere Aufrufer) werden wie beim Lesen übersetzt.
|
||||
@@ -96,7 +118,7 @@ public function normalize(array $content): array
|
||||
$item['style'] = $migrated[$index]['style'] ?? ($item['style'] ?? []);
|
||||
}
|
||||
|
||||
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount);
|
||||
$sections[] = $this->normalizeSection($item, $index, $errors, $seenSectionIds, $seenWidgetIds, $widgetCount, $seenAnchors);
|
||||
}
|
||||
|
||||
if ($widgetCount > self::MAX_WIDGETS) {
|
||||
@@ -164,12 +186,14 @@ public function mediaPaths(array $sections): array
|
||||
*/
|
||||
public function pageTitle(array $sections): ?string
|
||||
{
|
||||
return $this->widgets->pageTitle($this->flatten($sections));
|
||||
// Ein ausgeblendeter Abschnitt liefert keinen Seitentitel; seine Medien bleiben dagegen erfasst (mediaPaths),
|
||||
// damit ihre Bilder nicht als ungenutzt gelten.
|
||||
return $this->widgets->pageTitle($this->flatten(array_values(array_filter($sections, fn (array $section): bool => ! ($section['hidden'] ?? false)))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int|string, mixed> $blocks
|
||||
* @return list<array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
* @return list<array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}>
|
||||
*/
|
||||
private function wrapWidgets(array $blocks): array
|
||||
{
|
||||
@@ -179,6 +203,9 @@ private function wrapWidgets(array $blocks): array
|
||||
$sections[] = [
|
||||
'id' => null,
|
||||
'v' => self::VERSION,
|
||||
'name' => null,
|
||||
'anchor' => null,
|
||||
'hidden' => false,
|
||||
'layout' => SectionLayouts::DEFAULT,
|
||||
// Bestand vor dem Raster stand in einem durchgehenden Blatt: kompakte Abstände, zwischen den Widgets
|
||||
// nur einmal (oben kein Abstand ab dem zweiten), wie bisher.
|
||||
@@ -192,7 +219,7 @@ private function wrapWidgets(array $blocks): array
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
* @return array{id: ?string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
* @return array{id: ?string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
*/
|
||||
private function upcastSection(array $section): array
|
||||
{
|
||||
@@ -210,6 +237,9 @@ private function upcastSection(array $section): array
|
||||
return [
|
||||
'id' => is_string($section['id'] ?? null) ? $section['id'] : null,
|
||||
'v' => self::VERSION,
|
||||
'name' => self::cleanName($section['name'] ?? null),
|
||||
'anchor' => self::cleanAnchor($section['anchor'] ?? null),
|
||||
'hidden' => self::isHidden($section['hidden'] ?? false),
|
||||
'layout' => $layout,
|
||||
'style' => SectionStyle::fromStored($section['style'] ?? []),
|
||||
'slots' => $slots,
|
||||
@@ -221,9 +251,9 @@ private function upcastSection(array $section): array
|
||||
* @param array<string, list<string>> $errors
|
||||
* @param array<string, true> $seenSectionIds
|
||||
* @param array<string, true> $seenWidgetIds
|
||||
* @return array{id: string, v: int, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
* @return array{id: string, v: int, name: ?string, anchor: ?string, hidden: bool, layout: string, style: array<string, mixed>, slots: list<array<string, mixed>|null>}
|
||||
*/
|
||||
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount): array
|
||||
private function normalizeSection(array $section, int $index, array &$errors, array &$seenSectionIds, array &$seenWidgetIds, int &$widgetCount, array &$seenAnchors): array
|
||||
{
|
||||
$prefix = "sections.$index";
|
||||
|
||||
@@ -294,15 +324,90 @@ private function normalizeSection(array $section, int $index, array &$errors, ar
|
||||
}
|
||||
$seenSectionIds[$id] = true;
|
||||
|
||||
[$name, $anchor] = $this->normalizeLabels($section, $prefix, $errors, $seenAnchors);
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'v' => self::VERSION,
|
||||
'name' => $name,
|
||||
'anchor' => $anchor,
|
||||
'hidden' => self::isHidden($section['hidden'] ?? false),
|
||||
'layout' => $layout,
|
||||
'style' => $style,
|
||||
'slots' => $slots,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Name und Sprungmarke eines Abschnitts. Fehler: „sections.N.name“ und „sections.N.anchor“.
|
||||
*
|
||||
* @param array<string, mixed> $section
|
||||
* @param array<string, list<string>> $errors
|
||||
* @param array<string, true> $seenAnchors
|
||||
* @return array{0: ?string, 1: ?string}
|
||||
*/
|
||||
private function normalizeLabels(array $section, string $prefix, array &$errors, array &$seenAnchors): array
|
||||
{
|
||||
$name = null;
|
||||
$rawName = $section['name'] ?? null;
|
||||
|
||||
if (is_string($rawName) && trim($rawName) !== '') {
|
||||
$name = self::cleanName($rawName);
|
||||
|
||||
if ($name === null) {
|
||||
$errors["$prefix.name"] = ['Der Name darf höchstens '.self::MAX_NAME.' Zeichen lang sein.'];
|
||||
}
|
||||
}
|
||||
|
||||
$anchor = null;
|
||||
$rawAnchor = $section['anchor'] ?? null;
|
||||
|
||||
if (is_string($rawAnchor) && trim($rawAnchor) !== '') {
|
||||
$candidate = mb_strtolower(trim($rawAnchor));
|
||||
|
||||
if (strlen($candidate) > self::MAX_ANCHOR || preg_match(self::ANCHOR_PATTERN, $candidate) !== 1) {
|
||||
$errors["$prefix.anchor"] = ['Eine Sprungmarke besteht aus Kleinbuchstaben, Ziffern und einzelnen Bindestrichen (höchstens '.self::MAX_ANCHOR.' Zeichen), zum Beispiel „anmeldung“.'];
|
||||
} elseif (in_array($candidate, self::RESERVED_ANCHORS, true) || str_starts_with($candidate, 'bereich-')) {
|
||||
$errors["$prefix.anchor"] = ['Diese Sprungmarke ist im Seitengerüst schon vergeben. Bitte eine andere wählen.'];
|
||||
} elseif (isset($seenAnchors[$candidate])) {
|
||||
$errors["$prefix.anchor"] = ['Diese Sprungmarke gibt es auf der Seite schon. Jede Sprungmarke darf nur einmal vorkommen.'];
|
||||
} else {
|
||||
$seenAnchors[$candidate] = true;
|
||||
$anchor = $candidate;
|
||||
}
|
||||
} elseif ($rawAnchor !== null && ! is_string($rawAnchor)) {
|
||||
$errors["$prefix.anchor"] = ['Die Sprungmarke ist ungültig.'];
|
||||
}
|
||||
|
||||
return [$name, $anchor];
|
||||
}
|
||||
|
||||
/** Interner Name: Leerraum vereinheitlicht, ohne Steuerzeichen; leer oder über 80 Zeichen ergibt null. */
|
||||
public static function cleanName(mixed $value): ?string
|
||||
{
|
||||
if (! is_string($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$name = trim((string) preg_replace('/\s+/u', ' ', (string) preg_replace('/[\x00-\x1F\x7F]/u', ' ', $value)));
|
||||
|
||||
return $name === '' || mb_strlen($name) > self::MAX_NAME ? null : $name;
|
||||
}
|
||||
|
||||
/** Lesepfad: eine gespeicherte Sprungmarke nur, wenn sie der Form entspricht. */
|
||||
public static function cleanAnchor(mixed $value): ?string
|
||||
{
|
||||
return is_string($value) && strlen($value) <= self::MAX_ANCHOR && preg_match(self::ANCHOR_PATTERN, $value) === 1
|
||||
&& ! in_array($value, self::RESERVED_ANCHORS, true) && ! str_starts_with($value, 'bereich-')
|
||||
? $value
|
||||
: null;
|
||||
}
|
||||
|
||||
public static function isHidden(mixed $value): bool
|
||||
{
|
||||
return $value === true || $value === 1 || $value === '1' || $value === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $style
|
||||
* @param array<string, list<string>> $errors
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
* Die Kennungen sind gespeichert und ändern sich nie; neue Raster werden ergänzt, nicht umbenannt.
|
||||
*
|
||||
* Die Einheiten werden nicht als eigenes CSS-Grundraster umgesetzt, sondern als Spaltenverhältnis (fr)
|
||||
* des Abschnittsrasters. Leere Slots entfallen auf der veröffentlichten Seite; die übrigen Slots teilen
|
||||
* sich die Breite im Verhältnis ihrer Einheiten.
|
||||
* des Abschnittsrasters. Jeder Platz behält seine Stelle und Breite, auch wenn er leer bleibt; die Widgets
|
||||
* daneben rücken nicht nach.
|
||||
*/
|
||||
final class SectionLayouts
|
||||
{
|
||||
@@ -81,7 +81,7 @@ public static function options(): array
|
||||
}
|
||||
|
||||
/**
|
||||
* Spaltenvorlagen für die Slots, die tatsächlich etwas darstellen.
|
||||
* Spaltenvorlagen für alle Plätze des Rasters (auch leere, damit die übrigen an ihrer Stelle bleiben).
|
||||
*
|
||||
* - Desktop (Abschnitt ab 60rem): Verhältnis der Einheiten.
|
||||
* - Tablet (ab 40rem): gleich breite Slots bleiben nebeneinander (zwei oder drei Spalten, vier Slots als 2 × 2);
|
||||
|
||||
@@ -11,10 +11,15 @@
|
||||
* Einziger Darstellungsweg für Abschnitte: öffentliche Seite und Seitenvorschau rufen denselben Renderer auf.
|
||||
*
|
||||
* Regeln:
|
||||
* - Leere Slots erzeugen keine Leerfläche; die übrigen Slots teilen sich die Breite im Verhältnis ihrer Einheiten.
|
||||
* - Jeder Platz des Rasters behält seine Stelle und seine Breite: Ein leerer Platz bleibt als leere Spalte stehen, die
|
||||
* Widgets daneben rücken nicht in ihn hinein. Gestapelt (Smartphone, schmaler Abschnitt) erzeugt ein leerer Platz keine
|
||||
* Lücke.
|
||||
* - Ein Abschnitt ohne darstellbares Widget entfällt samt Hintergrund und Trenner.
|
||||
* - Das erste dargestellte Widget der Seite ist der Seiteneinstieg (Überschrift erster Ordnung).
|
||||
* - Trenner stehen zwischen Abschnitten, nie nach dem letzten.
|
||||
* - Ein ausgeblendeter Abschnitt („hidden“) erscheint nie auf der Website und zählt weder für das erste Widget noch für
|
||||
* Trenner. Nur die Vorschau zeigt an seiner Stelle einen schmalen Hinweis (ohne Inhalt).
|
||||
* - Eine Sprungmarke („anchor“) ist die Element-Kennung des Abschnitts; ohne Sprungmarke gilt „bereich-<Kennung>“.
|
||||
*/
|
||||
class SectionRenderer
|
||||
{
|
||||
@@ -29,37 +34,59 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
|
||||
$first = true;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
if ($section['hidden'] ?? false) {
|
||||
if ($context->preview) {
|
||||
$rendered[] = ['note' => $this->hiddenNote($section)];
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$cells = [];
|
||||
$shown = false;
|
||||
$units = SectionLayouts::units($section['layout']);
|
||||
|
||||
foreach ($units as $position => $slotUnits) {
|
||||
$widget = $section['slots'][$position] ?? null;
|
||||
|
||||
if (! is_array($widget)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$html = $this->widgets->renderWidget($widget, $context, $first);
|
||||
$html = is_array($widget) ? $this->widgets->renderWidget($widget, $context, $first) : '';
|
||||
|
||||
if ($html !== '') {
|
||||
$first = false;
|
||||
$cells[] = ['units' => $slotUnits, 'html' => $html];
|
||||
$shown = true;
|
||||
}
|
||||
|
||||
// Auch ein leerer Platz (oder ein Widget, das nichts darstellt) bleibt eine Zelle, damit die Plätze daneben stehen bleiben.
|
||||
$cells[] = ['units' => $slotUnits, 'html' => $html];
|
||||
}
|
||||
|
||||
if ($cells !== []) {
|
||||
if ($shown) {
|
||||
$rendered[] = ['section' => $section, 'cells' => $cells];
|
||||
}
|
||||
}
|
||||
|
||||
$html = '';
|
||||
$last = count($rendered) - 1;
|
||||
$last = -1;
|
||||
|
||||
foreach ($rendered as $position => $item) {
|
||||
if (isset($item['section'])) {
|
||||
$last = $position;
|
||||
}
|
||||
}
|
||||
|
||||
$index = 0;
|
||||
|
||||
foreach ($rendered as $position => $item) {
|
||||
if (! isset($item['section'])) {
|
||||
$html .= $item['note'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($rendered as $index => $item) {
|
||||
$html .= $this->renderSection($item['section'], $item['cells'], $index, $context);
|
||||
$index++;
|
||||
|
||||
$divider = $item['section']['style']['divider'] ?? 'none';
|
||||
if ($index < $last && in_array($divider, ['line', 'accent'], true)) {
|
||||
if ($position < $last && in_array($divider, ['line', 'accent'], true)) {
|
||||
$html .= '<div class="section-divider section-divider-'.$divider.'" aria-hidden="true"><span></span></div>';
|
||||
}
|
||||
}
|
||||
@@ -68,8 +95,20 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinweis der Vorschau an der Stelle eines ausgeblendeten Abschnitts.
|
||||
*
|
||||
* @param array<string, mixed> $section
|
||||
* @param list<array{units: int, html: string}> $cells
|
||||
*/
|
||||
private function hiddenNote(array $section): string
|
||||
{
|
||||
$name = is_string($section['name'] ?? null) && $section['name'] !== '' ? '„'.$section['name'].'“ ' : '';
|
||||
|
||||
return '<div class="section-hidden-note" role="note">Abschnitt '.e($name).'ist für die Website ausgeblendet und erscheint hier nur als Hinweis.</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
* @param list<array{units: int, html: string}> $cells alle Plätze des Rasters in ihrer Reihenfolge; html '' = leer
|
||||
*/
|
||||
private function renderSection(array $section, array $cells, int $index, RenderContext $context): string
|
||||
{
|
||||
@@ -105,7 +144,11 @@ private function renderSection(array $section, array $cells, int $index, RenderC
|
||||
$classes[] = $scope;
|
||||
}
|
||||
|
||||
$id = is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '';
|
||||
// Die Sprungmarke ist die Kennung, die ein Link „#marke“ anspringt; ohne sie bleibt die bisherige Kennung.
|
||||
$anchor = PageSections::cleanAnchor($section['anchor'] ?? null);
|
||||
$id = $anchor !== null
|
||||
? ' id="'.e($anchor).'"'
|
||||
: (is_string($section['id'] ?? null) ? ' id="bereich-'.e($section['id']).'"' : '');
|
||||
$html = '<div class="'.e(implode(' ', $classes)).'"'.$id.'>';
|
||||
|
||||
if ($hasImage) {
|
||||
@@ -115,11 +158,26 @@ private function renderSection(array $section, array $cells, int $index, RenderC
|
||||
.' style="object-position: '.e(SectionStyle::FOCUS_POSITIONS[$style['focus']]).'">';
|
||||
}
|
||||
|
||||
$html .= '<div class="page-section-inner"><div class="section-grid" data-slots="'.count($cells).'"'
|
||||
// Auf dem Tablet stehen gleich breite Plätze nebeneinander (zwei oder drei je Zeile); nur dort behalten leere Plätze
|
||||
// ihre Stelle. Eine Zeile, in der alle Plätze leer sind, entfällt auf dem Tablet ganz (sonst bliebe ihr Abstand stehen).
|
||||
$perRow = preg_match('/^repeat\((\d+),/', $columns['md'], $match) === 1 ? (int) $match[1] : 1;
|
||||
$tabletColumns = $perRow > 1 ? ' section-grid-tablet-columns' : '';
|
||||
$emptyRows = [];
|
||||
|
||||
if ($perRow > 1) {
|
||||
foreach (array_chunk(array_keys($cells), $perRow) as $row) {
|
||||
if (array_filter($row, fn (int $position): bool => $cells[$position]['html'] !== '') === []) {
|
||||
$emptyRows = array_merge($emptyRows, $row);
|
||||
}
|
||||
}
|
||||
}
|
||||
$html .= '<div class="page-section-inner"><div class="section-grid'.$tabletColumns.'" data-slots="'.count($cells).'"'
|
||||
.' style="--section-cols-lg: '.e($columns['lg']).'; --section-cols-md: '.e($columns['md']).'">';
|
||||
|
||||
foreach ($cells as $cell) {
|
||||
$html .= '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
|
||||
foreach ($cells as $position => $cell) {
|
||||
$html .= $cell['html'] === ''
|
||||
? '<div class="section-slot section-slot-empty'.(in_array($position, $emptyRows, true) ? ' section-slot-empty-row' : '').'" data-units="'.$cell['units'].'" aria-hidden="true"></div>'
|
||||
: '<div class="section-slot" data-units="'.$cell['units'].'">'.$cell['html'].'</div>';
|
||||
}
|
||||
|
||||
return $html.'</div></div></div>';
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Support\Brand\SymbolCatalog;
|
||||
|
||||
/**
|
||||
* Zulässige Kleingrafiken des Brand-Kits als Auswahl im CMS (ADR-30: nur feste Werte, nie freie Dateinamen).
|
||||
*
|
||||
* Die Schlüssel sind Dateinamen aus resources/svg/brand/symbole/, Titel und Gruppen stehen im Katalog
|
||||
* (App\Support\Brand\SymbolCatalog, Datei _katalog.json). Nicht angeboten werden die gelbe Unterstreichung (eigene
|
||||
* Einstellung „Pinselstrich“) und die Signalstrahlen (Markenakzent des Einstiegs). Eine Prüfung im Test stellt sicher,
|
||||
* dass jeder Schlüssel eine vorhandene Datei und einen Katalogeintrag hat.
|
||||
*/
|
||||
final class HeadingAccent
|
||||
{
|
||||
/**
|
||||
* Angebotene Symbole: Schlüssel => Titel, geordnet nach Gruppe. Einzige Quelle für Prüfung und Auswahl.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function symbols(): array
|
||||
{
|
||||
return SymbolCatalog::options();
|
||||
}
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const BRUSH = ['brush' => 'Gelber Pinselstrich unter der Überschrift'];
|
||||
|
||||
public const SYMBOL_LABEL = ['Symbol vor der Überschrift', 'Kleine Grafik aus dem Brand-Kit vor dem Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'];
|
||||
|
||||
public const BRUSH_LABEL = ['Pinselstrich', 'Gelbe Unterstreichung unter der Überschrift (freigegebenes Motiv aus dem Brand-Kit). Vorgabe: ohne.'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const SIZE = [
|
||||
'small' => 'Klein (2,5 rem), links neben dem ganzen Absatz',
|
||||
'medium' => 'Mittel (3,5 rem), links neben dem ganzen Absatz',
|
||||
'large' => 'Groß (5 rem), links neben dem ganzen Absatz',
|
||||
'xlarge' => 'Sehr groß (7 rem), links neben dem ganzen Absatz',
|
||||
];
|
||||
|
||||
/**
|
||||
* Gemeinsame Größenstufen aller Widgets (Kantenlänge des Symbolquadrats): klein 2,5 rem, mittel 3,5 rem, groß 5 rem,
|
||||
* sehr groß 7 rem. Die Werte stehen als --lf-symbol-… in tokens.css; Merkmalszeile, Karten und alle Überschriften-
|
||||
* Widgets verwenden dieselben Schlüssel.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const STEPS = ['small' => 'Klein', 'medium' => 'Mittel', 'large' => 'Groß', 'xlarge' => 'Sehr groß'];
|
||||
|
||||
public const SIZE_LABEL = ['Größe des Symbols', 'Vorgabe: klein, vor der Überschrift in der Zeile. Klein bis Sehr groß stellen das Symbol links neben Überschrift und Text; bei wenig Platz steht es darüber. Wirkt nur, wenn ein Symbol gewählt ist.'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const ALIGN = ['top' => 'Oben', 'center' => 'Mitte', 'bottom' => 'Unten'];
|
||||
|
||||
public const ALIGN_LABEL = ['Ausrichtung des Symbols', 'Senkrechte Lage des Symbols neben dem Absatz. Vorgabe: oben. Wirkt nur bei Symbolen neben dem Absatz (Klein bis Sehr groß).'];
|
||||
|
||||
/**
|
||||
* Waagerechte Ausrichtung von Inhalten mit Symbol (Merkmalszeile, Karten): links ist die Vorgabe.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const TEXT_ALIGN = ['left' => 'Linksbündig', 'center' => 'Zentriert', 'right' => 'Rechtsbündig'];
|
||||
|
||||
/**
|
||||
* Breite des Texts in Überschrift und Fließtext: Vorgabe ist die volle Breite des Platzes (so viel, wie die Abschnitts-
|
||||
* einstellung dem Widget gibt); die Lesebreite begrenzt Zeilen auf etwa 70 Zeichen (Überschrift 22 Zeichen).
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const TEXT_WIDTH = ['full' => 'Volle Breite des Platzes', 'reading' => 'Lesebreite (etwa 70 Zeichen je Zeile)'];
|
||||
|
||||
public const TEXT_WIDTH_LABEL = ['Breite des Texts', 'Volle Breite nutzt den ganzen Platz, den der Abschnitt dem Widget gibt (bei vier von vier Einheiten die ganze Zeile). Lesebreite begrenzt die Zeilen auf etwa 70 Zeichen, das liest sich bei langen Texten leichter. Vorgabe: volle Breite.'];
|
||||
|
||||
/**
|
||||
* „reading“ nur bei ausdrücklicher, gültiger Wahl; alles andere ist die volle Breite.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function textWidth(array $settings): string
|
||||
{
|
||||
return ($settings['text_width'] ?? null) === 'reading' ? 'reading' : 'full';
|
||||
}
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const LINK_STYLE = ['text' => 'Kleiner Textlink', 'pill' => 'Pille (Schaltfläche)'];
|
||||
|
||||
public const LINK_STYLE_LABEL = ['Darstellung der Links', 'Wie die Links der Merkmale aussehen. Vorgabe: kleiner Textlink. Merkmale ohne Link zeigen nichts.'];
|
||||
|
||||
/**
|
||||
* Größenstufe eines Symbols links neben dem ganzen Absatz (small, medium, large, xlarge) oder null, wenn das Symbol
|
||||
* klein vor der Überschrift steht. Nur mit gültigem Symbol. Ohne gültige Stufe gilt $default (null = in der Zeile).
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function sideSize(array $settings, ?string $default = null): ?string
|
||||
{
|
||||
if (self::symbol($settings) === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = $settings['symbol_size'] ?? null;
|
||||
|
||||
return is_string($size) && array_key_exists($size, self::SIZE) ? $size : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Alles, was eine Ansicht für Symbol und Absatz braucht: das Symbol, die Stufe neben dem Absatz (oder null), die
|
||||
* senkrechte Lage und die Einstellungen für das kleine Symbol in der Überschrift (leer, wenn das Symbol daneben steht,
|
||||
* damit es nicht doppelt erscheint).
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{symbol: ?string, side: ?string, align: string, inline: array<string, mixed>}
|
||||
*/
|
||||
public static function lead(array $settings, ?string $defaultSide = null): array
|
||||
{
|
||||
$side = self::sideSize($settings, $defaultSide);
|
||||
|
||||
return [
|
||||
'symbol' => self::symbol($settings),
|
||||
'side' => $side,
|
||||
'align' => self::align($settings),
|
||||
'inline' => $side !== null ? [] : $settings,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Senkrechte Ausrichtung des Symbols neben dem Absatz; ungültig oder leer ergibt oben.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function align(array $settings): string
|
||||
{
|
||||
$align = $settings['symbol_align'] ?? null;
|
||||
|
||||
return is_string($align) && array_key_exists($align, self::ALIGN) ? $align : 'top';
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausrichtung und Symbolgröße für Inhalte mit Symbol über dem Text (Merkmalszeile, Karten). Ungültige oder fehlende
|
||||
* Werte fallen auf die Vorgaben zurück: linksbündig und mittlere Symbole.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{align: string, size: string}
|
||||
*/
|
||||
public static function block(array $settings): array
|
||||
{
|
||||
$align = $settings['align'] ?? null;
|
||||
$size = $settings['symbol_size'] ?? null;
|
||||
|
||||
return [
|
||||
'align' => is_string($align) && array_key_exists($align, self::TEXT_ALIGN) ? $align : 'left',
|
||||
'size' => is_string($size) && array_key_exists($size, self::STEPS) ? $size : 'medium',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function linkStyle(array $settings): string
|
||||
{
|
||||
return ($settings['link_style'] ?? null) === 'pill' ? 'pill' : 'text';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gültiger Symbolname aus den Einstellungen eines Widgets oder null.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function symbol(array $settings): ?string
|
||||
{
|
||||
$name = $settings['symbol'] ?? null;
|
||||
|
||||
return is_string($name) && array_key_exists($name, self::symbols()) ? $name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function hasBrush(array $settings): bool
|
||||
{
|
||||
return ($settings['accent'] ?? null) === 'brush';
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,12 @@ public function resolve(mixed $id, bool $preview): array
|
||||
];
|
||||
}
|
||||
|
||||
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist (auch für den Medienwähler). */
|
||||
public function isSelectable(ContentElement $element): bool
|
||||
{
|
||||
return $this->allowed($element);
|
||||
}
|
||||
|
||||
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist. */
|
||||
private function allowed(ContentElement $element): bool
|
||||
{
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Support\Js;
|
||||
|
||||
/**
|
||||
* Linkfeld für alle Widgets: Die Adresse lässt sich frei eintippen (Seitenpfad, #Sprungmarke oder http(s)-Adresse) oder
|
||||
* über den Dialog „Interne Seite oder Sprungmarke wählen“ aus den Seiten der Website übernehmen
|
||||
* (ChoosesLinkTargets). Der Knopf ruft den Dialog direkt auf; ein Aktionsdialog im Bausteindialog entsteht nicht. Wo die
|
||||
* Seite den Dialog nicht kennt, fehlt der Knopf und das Feld bleibt ein Textfeld.
|
||||
*/
|
||||
final class LinkField
|
||||
{
|
||||
public static function make(string $name, string $label = 'Linkziel'): TextInput
|
||||
{
|
||||
return TextInput::make($name)
|
||||
->label($label)
|
||||
->maxLength(500)
|
||||
->rule(SafeUrl::rule())
|
||||
->suffixAction(Action::make('linkWaehlen')
|
||||
->label('Interne Seite oder Sprungmarke wählen')
|
||||
->tooltip('Interne Seite oder Sprungmarke wählen')
|
||||
->icon('heroicon-o-link')
|
||||
->visible(fn ($livewire): bool => is_object($livewire) && method_exists($livewire, 'openLinkPicker'))
|
||||
->actionJs(fn ($component): string => '$wire.openLinkPicker('.Js::from($component->getStatePath()).')'));
|
||||
}
|
||||
}
|
||||
@@ -53,10 +53,7 @@ public static function eyebrowField(): TextInput
|
||||
|
||||
public static function ctaFields(): Grid
|
||||
{
|
||||
$url = fn (string $name, string $label, string $pair) => TextInput::make($name)
|
||||
->label($label)
|
||||
->maxLength(500)
|
||||
->rule(SafeUrl::rule())
|
||||
$url = fn (string $name, string $label, string $pair) => LinkField::make($name, $label)
|
||||
->requiredWith($pair)
|
||||
->live(onBlur: true)
|
||||
->placeholder('/programme');
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
final class RichText
|
||||
{
|
||||
/** Werkzeugleiste des Editors; muss zur Erlaubnisliste unten passen. */
|
||||
public const TOOLBAR = [['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']];
|
||||
public const TOOLBAR = [['bold', 'italic', 'link', 'interneSeite'], ['bulletList', 'orderedList'], ['undo', 'redo']];
|
||||
|
||||
private static ?HtmlSanitizer $sanitizer = null;
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
/**
|
||||
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...") oder http(s)-Adressen.
|
||||
* Zulässige Linkziele in redaktionellen Inhalten: Seitenpfade ("/...", auch mit "#marke"), Sprungmarken auf der
|
||||
* eigenen Seite ("#marke") oder http(s)-Adressen. Eine Sprungmarke besteht aus Buchstaben, Ziffern, Bindestrich und Unterstrich.
|
||||
*/
|
||||
final class SafeUrl implements ValidationRule
|
||||
{
|
||||
@@ -16,6 +17,10 @@ public static function isSafe(mixed $url): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
if (str_starts_with($url, '#')) {
|
||||
return preg_match('/^#[A-Za-z0-9_-]{1,80}$/', $url) === 1;
|
||||
}
|
||||
|
||||
$isRelative = str_starts_with($url, '/') && ! str_starts_with($url, '//') && ! str_starts_with($url, '/\\');
|
||||
$isAbsolute = preg_match('#^https?://[^/\s]+#i', $url) === 1;
|
||||
|
||||
@@ -24,7 +29,7 @@ public static function isSafe(mixed $url): bool
|
||||
|
||||
public static function message(): string
|
||||
{
|
||||
return 'Erlaubt sind Seitenpfade (beginnend mit /) oder http(s)-Adressen.';
|
||||
return 'Erlaubt sind Seitenpfade (beginnend mit /), Sprungmarken (#marke) oder http(s)-Adressen.';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\LinkField;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
@@ -81,12 +83,34 @@ public function dataFields(): array
|
||||
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
|
||||
Textarea::make('text')->label('Text')->rows(3)->maxLength(1000),
|
||||
TextInput::make('label')->label('Beschriftung der Schaltfläche')->required()->maxLength(80),
|
||||
TextInput::make('url')
|
||||
->label('Linkziel')
|
||||
LinkField::make('url')
|
||||
->required()
|
||||
->maxLength(500)
|
||||
->rule(SafeUrl::rule())
|
||||
->helperText('Seitenpfad wie /angebote oder eine vollständige http(s)-Adresse.'),
|
||||
->helperText('Seitenpfad wie /angebote, Sprungmarke wie #kurse oder eine vollständige http(s)-Adresse; oder über das Linksymbol eine Seite oder Sprungmarke wählen.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
'accent' => HeadingAccent::BRUSH,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align', 'accent']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'symbol_size' => HeadingAccent::SIZE_LABEL,
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
'accent' => HeadingAccent::BRUSH_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -2,25 +2,79 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\LinkField;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Filament\Support\RichField;
|
||||
use App\Filament\Support\SymbolField;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Redaktionelle Karten. Die Einträge sind freie redaktionelle Verweise, keine Produkte oder Lizenzartikel.
|
||||
*
|
||||
* Version 1 umfasst den Bestand (Titel, Text, Adresse). Das optionale Bild je Karte ist eine
|
||||
* abwärtskompatible Ergänzung derselben Version: ältere Karten haben schlicht kein Bild.
|
||||
* Version 1 (Bestand): Titel, Klartext, Adresse; Bild und Symbol je Karte sind abwärtskompatible Ergänzungen derselben
|
||||
* Version. Version 2: Die Beschreibung ist formatierter Text (HTML, Webprofil von FormattedText wie im Fließtext). Neu je
|
||||
* Karte ist die optionale Dachzeile über dem Titel (sie wird nur gespeichert, wenn sie ausgefüllt ist).
|
||||
*/
|
||||
class CardsWidget extends WidgetType
|
||||
{
|
||||
/** Größtes zulässiges Maß des gespeicherten HTML einer Beschreibung. */
|
||||
public const TEXT_MAX_LENGTH = 5000;
|
||||
|
||||
/**
|
||||
* Verteilung der Karten auf die Breite: die Karten wachsen und füllen jede Zeile (Vorgabe) oder behalten ihre Breite,
|
||||
* und die Abstände wachsen. In beiden Fällen sind alle Spalten gleich breit.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const DISTRIBUTION = ['grow' => 'Karten vergrößern sich', 'space' => 'Abstände gleichen aus'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const DIVIDER = ['line' => 'Feiner Strich zwischen den Karten'];
|
||||
|
||||
private const DEFAULT_LINK_LABEL = 'Mehr erfahren';
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const HOVER = ['lift' => 'Karte unter der Maus hervorheben'];
|
||||
|
||||
/**
|
||||
* Gültige Layout-Einstellungen mit Vorgaben; alles andere fällt auf die Vorgabe zurück (Karten wachsen, Symbol über
|
||||
* dem Text, oben, ohne Strich, ohne Pinselstrich, ohne Hervorhebung).
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{align: string, size: string, position: string, valign: string, distribution: string, divider: bool, brush: bool, hover: bool, link: ?string}
|
||||
*/
|
||||
public static function layout(array $settings): array
|
||||
{
|
||||
$position = $settings['symbol_position'] ?? null;
|
||||
$distribution = $settings['distribution'] ?? null;
|
||||
|
||||
return HeadingAccent::block($settings) + [
|
||||
'position' => is_string($position) && array_key_exists($position, FeaturesWidget::SYMBOL_POSITION) ? $position : 'top',
|
||||
'valign' => HeadingAccent::align($settings),
|
||||
'distribution' => is_string($distribution) && array_key_exists($distribution, self::DISTRIBUTION) ? $distribution : 'grow',
|
||||
'divider' => ($settings['divider'] ?? null) === 'line',
|
||||
'brush' => HeadingAccent::hasBrush($settings),
|
||||
'hover' => ($settings['hover'] ?? null) === 'lift',
|
||||
// Sichtbarer Link unter dem Text (Textlink oder Pille); ohne Einstellung ist der Titel der Link der Karte.
|
||||
'link' => in_array($settings['link_style'] ?? null, array_keys(HeadingAccent::LINK_STYLE), true) ? $settings['link_style'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return 'cards';
|
||||
@@ -33,7 +87,7 @@ public function label(): string
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Mehrere Karten mit Titel, Text, Linkziel und optionalem Bild. Als Raster, kompakte Liste oder mit hervorgehobener erster Karte.';
|
||||
return 'Mehrere Karten mit Dachzeile, Titel, formatiertem Text, Symbol, Linkziel und optionalem Bild. Als Raster, kompakte Liste oder mit hervorgehobener erster Karte.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
@@ -43,7 +97,7 @@ public function supportedUnits(): array
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Karten stehen untereinander, sobald keine zwei 15 rem breiten Karten nebeneinander passen; die hervorgehobene Karte stapelt Bild und Text.';
|
||||
return 'Die Karten sind mindestens 15 rem breit (mit Symbol neben dem Text 18 rem) und verteilen sich ausgewogen auf Zeilen (zehn Karten als 4, 3 und 3); passen keine zwei Karten nebeneinander, stehen sie untereinander. Bei „Abstände gleichen aus“ behalten sie ihre Breite (höchstens 20 rem). Die hervorgehobene Karte stapelt Bild und Text.';
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
@@ -55,7 +109,7 @@ public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'eine Karte je Zeile',
|
||||
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 15rem Kartenbreite passen; hervorgehobene Karte ab 44rem mit Bild neben dem Text',
|
||||
'wide' => 'so viele Karten nebeneinander, wie bei mindestens 15rem Kartenbreite passen, ausgewogen auf die Zeilen verteilt; hervorgehobene Karte ab 44rem mit Bild neben dem Text',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -82,14 +136,57 @@ public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'items' => ['required', 'array', 'min:1', 'max:12'],
|
||||
'items.*.eyebrow' => ['nullable', 'string', 'max:80'],
|
||||
'items.*.title' => ['required', 'string', 'max:120'],
|
||||
'items.*.text' => ['nullable', 'string', 'max:500'],
|
||||
'items.*.text' => ['nullable', 'string', 'max:'.self::TEXT_MAX_LENGTH],
|
||||
'items.*.url' => ['nullable', 'string', 'max:500'],
|
||||
'items.*.link_label' => ['nullable', 'string', 'max:60'],
|
||||
'items.*.symbol' => ['nullable', 'string', Rule::in(array_keys(HeadingAccent::symbols()))],
|
||||
'items.*.image' => ['nullable'],
|
||||
'items.*._upload' => ['nullable'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'distribution' => self::DISTRIBUTION,
|
||||
'align' => HeadingAccent::TEXT_ALIGN,
|
||||
'symbol_size' => HeadingAccent::STEPS,
|
||||
'symbol_position' => FeaturesWidget::SYMBOL_POSITION,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
'accent' => HeadingAccent::BRUSH,
|
||||
'divider' => self::DIVIDER,
|
||||
'hover' => self::HOVER,
|
||||
'link_style' => HeadingAccent::LINK_STYLE,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Verteilung' => ['distribution', 'align'],
|
||||
'Symbol' => ['symbol_size', 'symbol_position', 'symbol_align'],
|
||||
'Gestaltung' => ['accent', 'divider', 'hover'],
|
||||
'Link' => ['link_style'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'distribution' => ['Verteilung der Karten', 'Wie die Karten den verfügbaren Platz füllen. Die Zeilen sind in beiden Fällen ausgewogen (fünf Karten stehen als drei und zwei, zehn als vier, drei und drei) und jede Karte ist mindestens 15 rem breit (mit Symbol neben dem Text 18 rem); wird das unterschritten, wandert eine Karte in die nächste Zeile. „Karten vergrößern sich“ (Vorgabe): Jede Zeile wird ganz ausgefüllt. „Abstände gleichen aus“: Die Karten behalten eine feste Breite (höchstens 20 rem), und der übrige Platz verteilt sich gleichmäßig zwischen und neben den Karten. Möglich sind eine bis zwölf Karten.'],
|
||||
'align' => ['Ausrichtung', 'Richtet Symbol, Dachzeile, Titel, Pinselstrich und Text jeder Karte aus. Vorgabe: linksbündig.'],
|
||||
'symbol_size' => ['Größe der Symbole', 'Kantenlänge der Symbole auf den Karten, die eins haben: Klein 2,5 rem, Mittel 3,5 rem, Groß 5 rem, Sehr groß 7 rem. Vorgabe: Mittel.'],
|
||||
'symbol_position' => ['Lage des Symbols', 'Über dem Text (Vorgabe) oder links bzw. rechts neben Dachzeile, Titel und Text jeder Karte. Neben dem Text braucht jede Karte mindestens 18 rem Breite, sonst stehen die Karten untereinander. Vorgabe: über dem Text.'],
|
||||
'symbol_align' => ['Senkrechte Lage des Symbols', 'Wo das Symbol neben dem Text sitzt: oben (Vorgabe), mittig oder unten. Wirkt nur, wenn das Symbol links oder rechts neben dem Text steht.'],
|
||||
'accent' => ['Pinselstrich', 'Gelbe Unterstreichung unter dem Titel jeder Karte (freigegebenes Motiv aus dem Brand-Kit). Vorgabe: ohne.'],
|
||||
'divider' => ['Trennstrich', 'Ein feiner Strich zwischen den Karten: senkrecht zwischen Spalten, waagerecht zwischen Zeilen. Die Karten verlieren dabei ihre Fläche und stehen flach auf dem Abschnitt, wie in der Merkmalszeile. In der kompakten Liste wirkt die Einstellung nicht, sie hat schon Linien. Vorgabe: ohne.'],
|
||||
'link_style' => ['Link unter dem Text', 'Zeigt unter dem Text jeder Karte mit Linkziel einen sichtbaren Link: als kleiner Textlink oder als Pille (Schaltfläche). Die ganze Karte bleibt anklickbar, der Titel ist dann kein eigener Link. Der Linktext steht je Karte (leer: „'.self::DEFAULT_LINK_LABEL.'“). Vorgabe: kein sichtbarer Link, die Karte öffnet sich über den Titel.'],
|
||||
'hover' => ['Hervorhebung unter der Maus', 'Die Karte, über der die Maus steht (oder die per Tastatur erreicht wird), hebt sich leicht ab. Ohne Bewegung, wenn das Betriebssystem reduzierte Bewegung wünscht. Vorgabe: ohne.'],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
[$image, $upload, $status] = ImageRefFields::fields('Bild (optional)');
|
||||
@@ -98,13 +195,22 @@ public function dataFields(): array
|
||||
Repeater::make('items')
|
||||
->label('Karten')
|
||||
->schema([
|
||||
TextInput::make('eyebrow')
|
||||
->label('Dachzeile (optional)')
|
||||
->maxLength(80)
|
||||
->helperText('Kurzer Hinweis über dem Titel, zum Beispiel ein Themenbereich. Kein Pflichtfeld.'),
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(120),
|
||||
Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500),
|
||||
TextInput::make('url')
|
||||
->label('Linkziel')
|
||||
->maxLength(500)
|
||||
->rule(SafeUrl::rule())
|
||||
->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'),
|
||||
SymbolField::make('symbol', 'Symbol (optional)')
|
||||
->helperText('Kleine Grafik aus dem Brand-Kit. Größe, Lage und senkrechte Ausrichtung im Reiter „Darstellung“.'),
|
||||
RichField::make('text', 'Beschreibung', website: true)
|
||||
->helperText('Wie beim Fließtext: Absätze und Zeilenumbrüche (Umschalt + Eingabe), fett, kursiv, Links, Listen, Schriftgröße, Schriftfarbe und Ausrichtung. Die Karten bleiben auch auf dunklen und grünen Abschnitten hell; die Farben entsprechen dort denen auf hellen Flächen.'),
|
||||
LinkField::make('url')
|
||||
->helperText('Seitenpfad wie /praevention, Sprungmarke wie #kurse oder eine http(s)-Adresse; oder über das Linksymbol wählen. Leer lassen für eine Karte ohne Link.'),
|
||||
TextInput::make('link_label')
|
||||
->label('Linktext (optional)')
|
||||
->maxLength(60)
|
||||
->placeholder(self::DEFAULT_LINK_LABEL)
|
||||
->helperText('Nur sichtbar, wenn im Reiter „Darstellung“ ein Link unter dem Text gewählt ist, und nur mit Linkziel. Leer: „'.self::DEFAULT_LINK_LABEL.'“.'),
|
||||
$image,
|
||||
$upload,
|
||||
$status,
|
||||
@@ -119,6 +225,36 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function upgrade(array $widget, int $from): array
|
||||
{
|
||||
if ($from === 1) {
|
||||
foreach ($widget['data']['items'] ?? [] as $index => $item) {
|
||||
if (is_array($item) && filled($item['text'] ?? null)) {
|
||||
$widget['data']['items'][$index]['text'] = self::plainToHtml((string) $item['text']);
|
||||
}
|
||||
}
|
||||
|
||||
return $widget;
|
||||
}
|
||||
|
||||
return parent::upgrade($widget, $from);
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext der Version 1 als formatierter Text: Leerzeilen trennen Absätze, ein einfacher Zeilenumbruch bleibt ein
|
||||
* Zeilenumbruch (so wie in der Überschrift mit Einleitung).
|
||||
*/
|
||||
public static function plainToHtml(string $text): string
|
||||
{
|
||||
$paragraphs = preg_split('/\R\s*\R/u', trim($text)) ?: [];
|
||||
$html = implode('', array_map(
|
||||
fn (string $paragraph): string => trim($paragraph) === '' ? '' : '<p>'.preg_replace('/\R/u', '<br>', e(trim($paragraph))).'</p>',
|
||||
$paragraphs,
|
||||
));
|
||||
|
||||
return FormattedText::canonicalHtml($html, true);
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
foreach ($data['items'] as $index => $item) {
|
||||
@@ -128,10 +264,18 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
|
||||
$itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image");
|
||||
|
||||
$text = FormattedText::canonical(is_string($item['text'] ?? null) ? $item['text'] : '', true);
|
||||
|
||||
// Die Schlüssel eyebrow und symbol werden nur gespeichert, wenn sie ausgefüllt sind: Karten ohne sie bleiben
|
||||
// byteweise wie zuvor.
|
||||
$data['items'][$index] = [
|
||||
...(filled($item['eyebrow'] ?? null) ? ['eyebrow' => trim((string) $item['eyebrow'])] : []),
|
||||
'title' => $item['title'],
|
||||
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
|
||||
'text' => $text !== '' ? $text : null,
|
||||
'url' => filled($item['url'] ?? null) ? $item['url'] : null,
|
||||
// Ein Linktext ohne Linkziel wird verworfen; ohne Linktext bleibt der Schlüssel weg (Karten bleiben wie zuvor).
|
||||
...(filled($item['url'] ?? null) && filled($item['link_label'] ?? null) ? ['link_label' => trim((string) $item['link_label'])] : []),
|
||||
...(filled($item['symbol'] ?? null) ? ['symbol' => $item['symbol']] : []),
|
||||
'image' => $itemRefs['image'],
|
||||
];
|
||||
}
|
||||
@@ -151,9 +295,12 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'eyebrow' => filled($item['eyebrow'] ?? null) ? $item['eyebrow'] : null,
|
||||
'title' => $item['title'],
|
||||
'text' => $item['text'] ?? null,
|
||||
'textHtml' => filled($item['text'] ?? null) ? ProseWidget::render($item['text']) : '',
|
||||
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
|
||||
'linkLabel' => filled($item['link_label'] ?? null) ? $item['link_label'] : self::DEFAULT_LINK_LABEL,
|
||||
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
|
||||
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
|
||||
];
|
||||
|
||||
@@ -162,7 +309,11 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
}
|
||||
}
|
||||
|
||||
return ['items' => $items, 'imageNotice' => $notices === [] ? null : implode(' ', $notices)];
|
||||
return [
|
||||
'items' => $items,
|
||||
'layout' => self::layout($widget['settings'] ?? []),
|
||||
'imageNotice' => $notices === [] ? null : implode(' ', $notices),
|
||||
];
|
||||
}
|
||||
|
||||
public function mediaPaths(array $widget): array
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
@@ -83,6 +84,29 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => ['Symbol neben den Fragen', 'Kleine Grafik aus dem Brand-Kit links neben allen Fragen. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'],
|
||||
'symbol_size' => ['Größe des Symbols', 'Vorgabe: Mittel. Bei wenig Platz steht das Symbol über den Fragen. Wirkt nur, wenn ein Symbol gewählt ist.'],
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$count = count($widget['data']['items'] ?? []);
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\LinkField;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Filament\Support\SymbolField;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Merkmalszeile nach den Entwürfen des Brand-Kits (04_visuelle_entwuerfe): ein bis zwölf Merkmale nebeneinander,
|
||||
* je mit Symbol, Kurztitel und einem Satz. Die Spaltenzahl folgt der Anzahl der Einträge und der Breite; es gibt keine
|
||||
* zweite Einstellung dafür. Das Symbol stammt aus der festen Auswahl (HeadingAccent::symbols()), nie aus einem
|
||||
* freien Dateinamen.
|
||||
*/
|
||||
class FeaturesWidget extends WidgetType
|
||||
{
|
||||
private const DEFAULT_LINK_LABEL = 'Mehr erfahren';
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const ALIGN = HeadingAccent::TEXT_ALIGN;
|
||||
|
||||
/**
|
||||
* Größenstufen der Symbole, überall dieselben (HeadingAccent::STEPS): klein 2,5 rem, mittel 3,5 rem (Vorgabe), groß
|
||||
* 5 rem, sehr groß 7 rem.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const SYMBOL_SIZE = HeadingAccent::STEPS;
|
||||
|
||||
/**
|
||||
* Lage des Symbols zum Text jedes Merkmals: über dem Text (Vorgabe), links oder rechts daneben.
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const SYMBOL_POSITION = ['top' => 'Über dem Text', 'left' => 'Links neben dem Text', 'right' => 'Rechts neben dem Text'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const DIVIDER = ['line' => 'Feiner Strich zwischen den Merkmalen'];
|
||||
|
||||
/**
|
||||
* Gültige Layout-Einstellungen mit Vorgaben (links, mittel, Symbol oben, ohne Strich); alles andere fällt auf die
|
||||
* Vorgabe zurück.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{align: string, size: string, position: string, divider: bool}
|
||||
*/
|
||||
public static function layout(array $settings): array
|
||||
{
|
||||
$position = $settings['symbol_position'] ?? null;
|
||||
|
||||
return HeadingAccent::block($settings) + [
|
||||
'position' => is_string($position) && array_key_exists($position, self::SYMBOL_POSITION) ? $position : 'top',
|
||||
'divider' => ($settings['divider'] ?? null) === 'line',
|
||||
];
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return 'features';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Merkmalszeile';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Ein bis zwölf Merkmale nebeneinander (bei wenig Platz untereinander), je mit Symbol, Kurztitel, einem Satz und optionalem Link.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
{
|
||||
return [1, 2, 3, 4];
|
||||
}
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Die Merkmale stehen nebeneinander, solange jedes mindestens 12 rem breit bleibt (mit Symbol neben dem Text 18 rem); darunter stehen sie untereinander.';
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'ein Merkmal je Zeile',
|
||||
'wide' => 'so viele Merkmale nebeneinander, wie bei mindestens 12rem Breite passen',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-sparkles';
|
||||
}
|
||||
|
||||
public function schematic(): array
|
||||
{
|
||||
return [[3, 6, 14, 14, 'accent'], [23, 6, 14, 14, 'accent'], [43, 6, 14, 14, 'accent'], [3, 24, 14, 3, 'ink'], [23, 24, 14, 3, 'ink'], [43, 24, 14, 3, 'ink'], [3, 29, 14, 2, 'line'], [23, 29, 14, 2, 'line'], [43, 29, 14, 2, 'line']];
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'items' => ['required', 'array', 'min:1', 'max:12'],
|
||||
'items.*.symbol' => ['required', 'string', Rule::in(array_keys(HeadingAccent::symbols()))],
|
||||
'items.*.title' => ['required', 'string', 'max:60'],
|
||||
'items.*.text' => ['nullable', 'string', 'max:200'],
|
||||
'items.*.url' => ['nullable', 'string', 'max:500'],
|
||||
'items.*.link_label' => ['nullable', 'string', 'max:60'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'align' => self::ALIGN,
|
||||
'symbol_size' => self::SYMBOL_SIZE,
|
||||
'symbol_position' => self::SYMBOL_POSITION,
|
||||
'divider' => self::DIVIDER,
|
||||
'link_style' => HeadingAccent::LINK_STYLE,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['align', 'symbol_size', 'symbol_position', 'divider', 'link_style']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'align' => ['Ausrichtung', 'Richtet Symbol, Titel, Satz und Link jedes Merkmals aus. Vorgabe: linksbündig.'],
|
||||
'symbol_size' => ['Größe der Symbole', 'Kantenlänge der Symbole: Klein 2,5 rem, Mittel 3,5 rem, Groß 5 rem, Sehr groß 7 rem. Vorgabe: Mittel.'],
|
||||
'symbol_position' => ['Lage des Symbols', 'Über dem Text (Vorgabe) oder links bzw. rechts neben Titel, Satz und Link jedes Merkmals. Neben dem Text braucht jedes Merkmal mindestens 18 rem Breite, sonst stehen die Merkmale untereinander. Vorgabe: über dem Text.'],
|
||||
'divider' => ['Trennstrich', 'Ein feiner Strich zwischen den Merkmalen: senkrecht zwischen Spalten, waagerecht zwischen Zeilen und bei untereinander stehenden Merkmalen. Vorgabe: ohne.'],
|
||||
'link_style' => HeadingAccent::LINK_STYLE_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
Repeater::make('items')
|
||||
->label('Merkmale')
|
||||
->schema([
|
||||
SymbolField::make('symbol', 'Symbol', required: true),
|
||||
TextInput::make('title')->label('Kurztitel')->required()->maxLength(60),
|
||||
Textarea::make('text')->label('Satz')->rows(2)->maxLength(200),
|
||||
LinkField::make('url', 'Linkziel (optional)')
|
||||
->helperText('Seitenpfad wie /materialien, Sprungmarke wie #kurse oder eine http(s)-Adresse; oder über das Linksymbol wählen. Leer lassen für ein Merkmal ohne Link.'),
|
||||
TextInput::make('link_label')
|
||||
->label('Linktext')
|
||||
->maxLength(60)
|
||||
->placeholder(self::DEFAULT_LINK_LABEL)
|
||||
->helperText('Nur mit Linkziel. Leer: „'.self::DEFAULT_LINK_LABEL.'“.'),
|
||||
])
|
||||
->minItems(1)
|
||||
->maxItems(12)
|
||||
->reorderableWithButtons()
|
||||
->collapsible()
|
||||
->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
|
||||
->addActionLabel('Merkmal hinzufügen')
|
||||
->helperText('Ein bis zwölf Merkmale. Sie stehen nebeneinander, solange jedes mindestens 12 rem breit bleibt, und brechen sonst um.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
foreach ($data['items'] as $index => $item) {
|
||||
$hasUrl = filled($item['url'] ?? null);
|
||||
|
||||
if ($hasUrl && ! SafeUrl::isSafe($item['url'])) {
|
||||
$errors->add("data.items.$index.url", SafeUrl::message());
|
||||
}
|
||||
|
||||
$data['items'][$index] = [
|
||||
'symbol' => $item['symbol'],
|
||||
'title' => $item['title'],
|
||||
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
|
||||
'url' => $hasUrl ? $item['url'] : null,
|
||||
// Ein Linktext ohne Linkziel wird verworfen, damit nichts Verstecktes gespeichert bleibt.
|
||||
'link_label' => $hasUrl && filled($item['link_label'] ?? null) ? $item['link_label'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$items = [];
|
||||
|
||||
foreach ($widget['data']['items'] ?? [] as $item) {
|
||||
if (! is_array($item) || ! filled($item['title'] ?? null)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
|
||||
'title' => $item['title'],
|
||||
'text' => $item['text'] ?? null,
|
||||
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
|
||||
'linkLabel' => filled($item['link_label'] ?? null) ? $item['link_label'] : self::DEFAULT_LINK_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
$settings = $widget['settings'] ?? [];
|
||||
|
||||
return ['items' => $items, 'linkStyle' => HeadingAccent::linkStyle($settings), 'layout' => self::layout($settings)];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$titles = array_filter(array_map(fn ($item) => is_array($item) ? ($item['title'] ?? null) : null, $widget['data']['items'] ?? []));
|
||||
|
||||
return count($titles).' Merkmale: '.implode(', ', $titles);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,31 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use App\Filament\Support\RichField;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
|
||||
/**
|
||||
* Überschrift mit Einleitung. Die Einleitung wird im Editor des Fließtexts geschrieben (Absätze, Zeilenumbrüche, fett,
|
||||
* kursiv, Links, Listen, Schriftgröße, -farbe, Ausrichtung; Webprofil von FormattedText) und so dargestellt wie dort.
|
||||
*
|
||||
* Version 1 (Bestand): Einleitung als Klartext; eine Leerzeile beginnt einen Absatz, ein einfacher Zeilenumbruch bleibt
|
||||
* ein Zeilenumbruch. Version 2: formatierter Text (HTML).
|
||||
*/
|
||||
class HeadingWidget extends WidgetType
|
||||
{
|
||||
/** Größtes zulässiges Maß des gespeicherten HTML der Einleitung. */
|
||||
public const INTRO_MAX_LENGTH = 20000;
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return 'heading';
|
||||
@@ -59,15 +78,83 @@ public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'heading' => ['required', 'string', 'max:200'],
|
||||
'intro' => ['nullable', 'string', 'max:1000'],
|
||||
'intro' => ['nullable', 'string', 'max:'.self::INTRO_MAX_LENGTH],
|
||||
];
|
||||
}
|
||||
|
||||
public function upgrade(array $widget, int $from): array
|
||||
{
|
||||
if ($from === 1) {
|
||||
$intro = $widget['data']['intro'] ?? '';
|
||||
$paragraphs = preg_split("/
|
||||
\s*
|
||||
/", trim(is_string($intro) ? $intro : '')) ?: [];
|
||||
$html = implode('', array_map(
|
||||
fn (string $paragraph): string => trim($paragraph) === '' ? '' : '<p>'.preg_replace('/\R/u', '<br>', e(trim($paragraph))).'</p>',
|
||||
$paragraphs,
|
||||
));
|
||||
|
||||
$widget['data']['intro'] = FormattedText::canonicalHtml($html, true);
|
||||
|
||||
return $widget;
|
||||
}
|
||||
|
||||
return parent::upgrade($widget, $from);
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$intro = FormattedText::canonical(is_string($data['intro'] ?? null) ? $data['intro'] : '', true);
|
||||
|
||||
if ($intro === '') {
|
||||
unset($data['intro']);
|
||||
} else {
|
||||
$data['intro'] = $intro;
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$intro = $widget['data']['intro'] ?? null;
|
||||
|
||||
return ['introHtml' => is_string($intro) && trim($intro) !== '' ? ProseWidget::render($intro) : ''];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('heading')->label('Überschrift')->required()->maxLength(200),
|
||||
Textarea::make('intro')->label('Einleitung')->rows(3)->maxLength(1000),
|
||||
RichField::make('intro', 'Einleitung', website: true)
|
||||
->helperText('Wie beim Fließtext: Absätze und Zeilenumbrüche (Umschalt + Eingabe), fett, kursiv, Links, Listen, Zitate und Tabellen, dazu Schriftgröße, Schriftfarbe (Marine, Grün, Rot, Grau) und Ausrichtung. Auf dunklen und grünen Flächen werden die Farben aufgehellt, damit die Schrift lesbar bleibt.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
'accent' => HeadingAccent::BRUSH,
|
||||
'text_width' => HeadingAccent::TEXT_WIDTH,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['text_width', 'symbol', 'symbol_size', 'symbol_align', 'accent']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'symbol_size' => HeadingAccent::SIZE_LABEL,
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
'accent' => HeadingAccent::BRUSH_LABEL,
|
||||
'text_width' => HeadingAccent::TEXT_WIDTH_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
@@ -112,13 +113,16 @@ public function settings(): array
|
||||
return [
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'accent' => ['underline' => 'Gelbe Unterstreichung', 'rays' => 'Unterstreichung und Signalstrahlen', 'none' => 'Ohne Akzent'],
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Aussehen' => ['accent', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -128,6 +132,9 @@ public function settingLabels(): array
|
||||
return [
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'symbol_size' => HeadingAccent::SIZE_LABEL,
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
@@ -10,8 +12,10 @@
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Filament\Support\InternalLinkPlugin;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Group;
|
||||
|
||||
/**
|
||||
@@ -19,6 +23,11 @@
|
||||
*
|
||||
* Version 1 (Bestand): data {image, alt, body} mit Klartext.
|
||||
* Version 2: data {title, body (formatierter Text), alt}, refs {image}, Varianten Bild links/rechts.
|
||||
* Ohne Versionssprung ergänzt (ältere Revisionen bleiben unverändert darstellbar): Bildanteil (settings.image_share),
|
||||
* Bild ohne Text (Text ist nicht mehr Pflicht, wenn ein Bild gewählt ist) und ein Video (refs.video, ein Film aus dem
|
||||
* Medienmanager): Das freigegebene Video (Trailer, Vorschauclip oder Website-Datei, Regel CardClip) spielt auf dem Bild
|
||||
* beim Überfahren mit der Maus stumm und per Klick oder Schaltfläche mit Ton, wie auf der Medienkarte.
|
||||
*
|
||||
* Version 3: zusätzlich Label, zwei Schaltflächen, Bildfokus in Prozent; Einstellungen Oberfläche, Höhe und
|
||||
* Überschriftenebene. Die Bildseite bleibt die Variante (keine doppelte Einstellung). Die Einstellung
|
||||
* format der Designiteration 1 entfällt; die Bildproportion folgt jetzt der Höhe.
|
||||
@@ -109,18 +118,36 @@ public function optionIcons(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Bildanteil an der Breite im zweispaltigen Stand (ab 900 px Containerbreite): Bild- und Textspalte als Verhältnis.
|
||||
* Ohne Wert gilt die bisherige Verteilung (Text 1,1 : Bild 0,9, je nach Bildseite).
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const IMAGE_SHARE = [
|
||||
'third' => 'Schmales Bild (ein Drittel Bild, zwei Drittel Text)',
|
||||
'two_fifths' => 'Eher schmales Bild (40 % Bild, 60 % Text)',
|
||||
'half' => 'Gleich breit (je die Hälfte)',
|
||||
'three_fifths' => 'Eher breites Bild (60 % Bild, 40 % Text)',
|
||||
'two_thirds' => 'Breites Bild (zwei Drittel Bild, ein Drittel Text)',
|
||||
];
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['cream' => 'Creme (Markenfläche)', 'clear' => 'Ohne eigene Fläche', 'navy' => 'Navy (dunkel)'],
|
||||
'image_share' => self::IMAGE_SHARE,
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface'],
|
||||
'Aussehen' => ['surface', 'image_share', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -129,6 +156,10 @@ public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'image_share' => ['Bildanteil', 'Verhältnis von Bild und Text nebeneinander. Gilt erst ab 900 px Breite des Widgets; schmaler steht das Bild über dem Text. Ohne Auswahl bleibt es bei der bisherigen Verteilung (Text etwas breiter als das Bild). Ohne Text füllt das Bild die ganze Breite.'],
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'symbol_size' => HeadingAccent::SIZE_LABEL,
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
];
|
||||
}
|
||||
@@ -173,13 +204,14 @@ public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'title' => ['nullable', 'string', 'max:160'],
|
||||
'body' => ['required', 'string', 'max:40000'],
|
||||
// Der Text ist nur Pflicht, solange kein Bild gewählt ist (clean); ein Bild darf allein stehen.
|
||||
'body' => ['nullable', 'string', 'max:40000'],
|
||||
] + PremiumFields::rules();
|
||||
}
|
||||
|
||||
public function refRules(): array
|
||||
{
|
||||
return ImageRefFields::rules();
|
||||
return ImageRefFields::rules() + ['video' => ['nullable']];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
@@ -189,8 +221,9 @@ public function dataFields(): array
|
||||
TextInput::make('title')->label('Überschrift')->maxLength(160)->live(onBlur: true),
|
||||
RichEditor::make('body')
|
||||
->label('Text')
|
||||
->required()
|
||||
->helperText('Leer lassen, wenn nur das Bild gezeigt werden soll. Ohne Text, Überschrift, Label und Schaltflächen füllt das Bild die ganze Breite.')
|
||||
->live(onBlur: true)
|
||||
->plugins([new InternalLinkPlugin])
|
||||
->toolbarButtons(RichText::TOOLBAR),
|
||||
PremiumFields::ctaFields(),
|
||||
PremiumFields::altField(),
|
||||
@@ -200,7 +233,16 @@ public function dataFields(): array
|
||||
|
||||
public function refFields(): array
|
||||
{
|
||||
return ImageRefFields::fields(live: true);
|
||||
return [...ImageRefFields::fields(live: true), $this->videoField()];
|
||||
}
|
||||
|
||||
private function videoField(): ViewField
|
||||
{
|
||||
return ViewField::make('video')
|
||||
->live()
|
||||
->label('Video (optional)')
|
||||
->view('filament.cms.video-feld')
|
||||
->helperText('Ein Film aus dem Medienmanager, über denselben Wähler wie das Bild. Das Bild bleibt stehen; das Video spielt darauf beim Überfahren stumm und per Klick oder Schaltfläche mit Ton, nur wenn ein Trailer, Vorschauclip oder die Website-Datei des Films für die Website freigegeben ist. Die Auswahl gibt nichts frei.');
|
||||
}
|
||||
|
||||
public function editorSchema(): array
|
||||
@@ -227,13 +269,47 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
$data['title'] = filled($data['title'] ?? null) ? trim((string) $data['title']) : null;
|
||||
$data = PremiumFields::clean($data, $errors, $refs['image'] !== null);
|
||||
|
||||
if (RichText::isBlank($data['body'])) {
|
||||
$errors->add('data.body', 'Bitte einen Text eingeben.');
|
||||
$video = app(HeroVideo::class)->clean($refs['video'] ?? null, $errors);
|
||||
$video === null ? $refs = array_diff_key($refs, ['video' => true]) : $refs['video'] = $video;
|
||||
|
||||
if ($video !== null && $refs['image'] === null) {
|
||||
$errors->add('refs.image', 'Bitte auch ein Bild wählen: Es steht, bis das Video startet.');
|
||||
}
|
||||
|
||||
if ($refs['image'] === null && ! self::hasCopy($data)) {
|
||||
$errors->add('data.body', 'Bitte einen Text eingeben oder ein Bild wählen.');
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ob neben dem Bild etwas zu lesen ist: Text, Überschrift, Label oder Schaltfläche. Ohne bleibt das Bild allein.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function hasCopy(array $data): bool
|
||||
{
|
||||
$body = is_string($data['body'] ?? null) ? RichText::sanitize($data['body']) : '';
|
||||
|
||||
return ! RichText::isBlank($body)
|
||||
|| filled($data['title'] ?? null)
|
||||
|| filled($data['eyebrow'] ?? null)
|
||||
|| PremiumFields::actions($data) !== [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gültiger Bildanteil oder null (bisherige Verteilung).
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
public static function imageShare(array $settings): ?string
|
||||
{
|
||||
$share = $settings['image_share'] ?? null;
|
||||
|
||||
return is_string($share) && array_key_exists($share, self::IMAGE_SHARE) ? $share : null;
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$surface = $widget['settings']['surface'] ?? 'cream';
|
||||
@@ -241,10 +317,23 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$images = app(WebsiteImage::class);
|
||||
$image = $widget['refs']['image'] ?? null;
|
||||
|
||||
$imageUrl = $images->url($image, $context->preview);
|
||||
$imageAlt = $images->alt($image, $widget['data']['alt'] ?? null);
|
||||
$hasCopy = self::hasCopy($widget['data'] ?? []);
|
||||
$video = app(HeroVideo::class)->resolve($widget['refs']['video'] ?? null, $context->preview);
|
||||
|
||||
// Ohne Bild gibt es nichts, worauf das Video stehen könnte; die Redaktion erfährt es in der Vorschau.
|
||||
if ($imageUrl === null && $video['url'] !== null) {
|
||||
$video = ['url' => null, 'title' => $video['title'], 'notice' => $context->preview ? 'Das Video braucht ein Bild: Es steht, bis das Video startet. Bitte ein Bild wählen.' : null];
|
||||
}
|
||||
|
||||
return [
|
||||
'imageUrl' => $images->url($image, $context->preview),
|
||||
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
|
||||
'imageUrl' => $imageUrl,
|
||||
'imageAlt' => $imageAlt,
|
||||
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
|
||||
'video' => $video,
|
||||
'hasCopy' => $hasCopy,
|
||||
'imageShare' => self::imageShare($widget['settings'] ?? []),
|
||||
'body' => RichText::sanitize(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : ''),
|
||||
'actions' => PremiumFields::actions($widget['data']),
|
||||
'focus' => PremiumFields::focus($widget['data'], 64, 43),
|
||||
@@ -263,6 +352,16 @@ public function summary(array $widget): string
|
||||
{
|
||||
$title = $widget['data']['title'] ?? null;
|
||||
|
||||
return filled($title) ? (string) $title : RichText::excerpt($widget['data']['body'] ?? '');
|
||||
if (filled($title)) {
|
||||
return (string) $title;
|
||||
}
|
||||
|
||||
$excerpt = RichText::excerpt($widget['data']['body'] ?? '');
|
||||
|
||||
if ($excerpt !== '') {
|
||||
return $excerpt;
|
||||
}
|
||||
|
||||
return filled($widget['data']['alt'] ?? null) ? 'Bild: '.$widget['data']['alt'] : 'Bild';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Domain\Communication\InquiryEntry;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* Kontakt-Widget: bindet einen veröffentlichten Anfrage-Einstieg der Kommunikationsverwaltung ein (ADR-60). Das Widget
|
||||
* speichert ausschließlich die Kennung des Einstiegs. Felder, Auswahlwerte, Bedingungen, Schritte, Texte und
|
||||
* Empfänger gibt es im CMS nicht; sie werden in der Kommunikationsverwaltung gepflegt.
|
||||
*/
|
||||
class InquiryWidget extends WidgetType
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'inquiry';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Anfrage';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Bindet einen Anfrage-Einstieg aus der Kommunikationsverwaltung ein: Kontaktformular oder mehrstufiger Anfragedialog.';
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-envelope';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
{
|
||||
return [3, 4];
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Das Formular nutzt die Breite des Platzes; Felder stehen untereinander, der mehrstufige Dialog bleibt einspaltig.';
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return ['fluid' => 'einspaltig, in Lesebreite begrenzt; Felder gleicher Art stehen auf breiten Plätzen nebeneinander'];
|
||||
}
|
||||
|
||||
public function schematic(): array
|
||||
{
|
||||
return [[6, 4, 24, 3, 'ink'], [6, 10, 48, 5, 'line'], [6, 18, 48, 5, 'line'], [6, 26, 18, 5, 'accent']];
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function refRules(): array
|
||||
{
|
||||
return [
|
||||
// Nur die Existenz: Ein später zurückgezogener Einstieg darf eine Seite nicht unspeicherbar machen (Seiten bleiben
|
||||
// konsistent). Auswahl im Editor sind nur veröffentlichte Einstiege; öffentlich erscheint nichts, solange er es nicht ist.
|
||||
'entry' => ['required', 'integer', Rule::exists('inquiry_entries', 'id')],
|
||||
];
|
||||
}
|
||||
|
||||
public function refFields(): array
|
||||
{
|
||||
return [
|
||||
Select::make('entry')
|
||||
->label('Anfrage-Einstieg')
|
||||
->required()
|
||||
->searchable()
|
||||
->options(fn (): array => InquiryEntry::query()->live()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->helperText('Nur veröffentlichte Einstiege stehen zur Auswahl. Anliegen, Felder, Bedingungen, Texte und Empfänger pflegst du in der Kommunikationsverwaltung („Kommunikation → Anfrage-Einstiege“), nicht hier. Eine Änderung dort gilt sofort auf allen Seiten, die diesen Einstieg verwenden.'),
|
||||
Text::make('Ein Einstieg ist die konkrete Nutzungsvariante einer Anfragevorlage. Mehrere Seiten können denselben Einstieg einbinden.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function editorSchema(): array
|
||||
{
|
||||
return parent::editorSchema();
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$id = $widget['refs']['entry'] ?? null;
|
||||
$entry = is_numeric($id) ? InquiryEntry::query()->with('template')->find((int) $id) : null;
|
||||
|
||||
return ['entry' => $entry, 'entryLive' => $entry?->isLive() ?? false];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$id = $widget['refs']['entry'] ?? null;
|
||||
$name = is_numeric($id) ? InquiryEntry::query()->whereKey((int) $id)->value('name') : null;
|
||||
|
||||
return $name !== null ? 'Anfrage: '.$name : 'Kein Anfrage-Einstieg gewählt';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Filament\Support\RichField;
|
||||
|
||||
/**
|
||||
* Hinweiszeile: ein kompakter Hinweis (zum Beispiel „Dieses Bild wurde mit KI erzeugt“) mit formatiertem Text und
|
||||
* optionalem Symbol, wahlweise mit aufklappbarer Kurzdarstellung.
|
||||
*
|
||||
* Drei Darstellungsmodi (Einstellung `mode`), der Text steht immer in beiden Fassungen gespeichert, ein Wechsel des Modus
|
||||
* verliert also nichts:
|
||||
* - full (Vorgabe): der vollständige Hinweis, immer sichtbar, ohne Aufklappen.
|
||||
* - responsive: breit der volle Text; unter einer Widgetbreite (Einstellung `narrow`) die Kurzdarstellung, auf Wunsch erst
|
||||
* dann, wenn der Volltext mehr Zeilen braucht als die Zeilengrenze (`line_limit`). Beim Laden eingeklappt.
|
||||
* - collapsed: immer zuerst die Kurzdarstellung, auf jeder Breite; ein Klick zeigt den vollständigen Text. Breite und
|
||||
* Zeilengrenze bleiben unberücksichtigt.
|
||||
* Ohne Kurztext gibt es nichts einzuklappen: Der Hinweis erscheint dann wie im Modus „Volltext“.
|
||||
*/
|
||||
class NoticeWidget extends WidgetType
|
||||
{
|
||||
/** Größtes zulässiges Maß des gespeicherten HTML je Text. */
|
||||
public const TEXT_MAX_LENGTH = 10000;
|
||||
|
||||
public const SHORT_MAX_LENGTH = 2000;
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const MODE = [
|
||||
'full' => 'Volltext: immer vollständig sichtbar',
|
||||
'responsive' => 'Responsiv: auf schmalen Bildschirmen die Kurzdarstellung',
|
||||
'collapsed' => 'Immer mit Kurzdarstellung starten',
|
||||
];
|
||||
|
||||
/**
|
||||
* Auslösegrenze: Der Volltext braucht mehr Zeilen als die Grenze. Die Schlüssel sind keine Zahlen, damit sie als
|
||||
* Zeichenketten erhalten bleiben (ADR-30: nur feste Werte).
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public const LINE_LIMIT = [
|
||||
'l1' => 'Mehr als 1 Zeile',
|
||||
'l2' => 'Mehr als 2 Zeilen',
|
||||
'l3' => 'Mehr als 3 Zeilen',
|
||||
'l4' => 'Mehr als 4 Zeilen',
|
||||
'l5' => 'Mehr als 5 Zeilen',
|
||||
'l6' => 'Mehr als 6 Zeilen',
|
||||
];
|
||||
|
||||
/**
|
||||
* Breite des Widgets (nicht des Fensters), unter der „schmal“ gilt, in rem.
|
||||
*
|
||||
* @var array<string, float>
|
||||
*/
|
||||
public const NARROW_REM = ['narrow' => 30.0, 'medium' => 40.0, 'wide' => 56.0];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const NARROW = [
|
||||
'narrow' => 'Nur bei sehr wenig Platz (Widgetbreite unter 30 rem, etwa 480 px)',
|
||||
'medium' => 'Bei wenig Platz (unter 40 rem, etwa 640 px)',
|
||||
'wide' => 'Auch bei mittlerem Platz (unter 56 rem, etwa 900 px)',
|
||||
];
|
||||
|
||||
/** Schriftgrößen: S, M und L sind die Stufen „klein“, „Text“ und „Einleitung“ des Designsystems, XS ist kleiner als diese. */
|
||||
public const SIZE = ['xs' => 'XS (klein, 13 px)', 's' => 'S (Hinweistext des Designsystems)', 'm' => 'M (Fließtext)', 'l' => 'L (Einleitungstext)'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const SYMBOL_SIZE = ['xs' => 'Sehr klein (1 rem)', 's' => 'Klein (1,25 rem)', 'm' => 'Mittel (1,75 rem)', 'l' => 'Groß (2,5 rem)', 'xl' => 'Sehr groß (3,5 rem)'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const SURFACE = ['green' => 'Dezentes Grün', 'yellow' => 'Hinweisgelb', 'cream' => 'Creme'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const BORDER = ['line' => 'Feiner Rahmen'];
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const BAR = ['left' => 'Akzentlinie links', 'top' => 'Akzentlinie oben'];
|
||||
|
||||
/**
|
||||
* Gültige Darstellungswerte; alles andere fällt auf die Vorgabe zurück (Volltext, ohne Grenze, mittlere Schwelle, S,
|
||||
* linksbündig, Symbol klein und oben, ohne Fläche, Rahmen und Linie). Ohne Kurztext ist der Modus immer „full“.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{mode: string, limit: ?int, narrow: float, size: string, align: string, symbol: ?string, symbolSize: string, symbolAlign: string, surface: ?string, border: bool, bar: ?string}
|
||||
*/
|
||||
public static function layout(array $settings, bool $hasShort = true): array
|
||||
{
|
||||
$pick = fn (string $key, array $allowed, ?string $default): ?string => is_string($settings[$key] ?? null) && array_key_exists($settings[$key], $allowed) ? $settings[$key] : $default;
|
||||
|
||||
$mode = $pick('mode', self::MODE, 'full');
|
||||
$limit = $pick('line_limit', self::LINE_LIMIT, null);
|
||||
|
||||
return [
|
||||
'mode' => $hasShort ? $mode : 'full',
|
||||
'limit' => $limit === null ? null : (int) substr($limit, 1),
|
||||
'narrow' => self::NARROW_REM[$pick('narrow', self::NARROW, 'medium')],
|
||||
'size' => $pick('size', self::SIZE, 's'),
|
||||
'align' => $pick('align', HeadingAccent::TEXT_ALIGN, 'left'),
|
||||
'symbol' => HeadingAccent::symbol($settings),
|
||||
'symbolSize' => $pick('symbol_size', self::SYMBOL_SIZE, 's'),
|
||||
'symbolAlign' => $pick('symbol_align', HeadingAccent::ALIGN, 'top'),
|
||||
'surface' => $pick('surface', self::SURFACE, null),
|
||||
'border' => ($settings['border'] ?? null) === 'line',
|
||||
'bar' => $pick('bar', self::BAR, null),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Skript der Hinweiszeile (resources/js/notice.js) ohne Kommentare, zum Einbetten in die Seite. Es steht beim ersten
|
||||
* Hinweis einer Seite inline im Quelltext und entscheidet dort über die Darstellung, bevor der Browser die folgenden
|
||||
* Inhalte malt; sonst spränge ein Hinweis nach dem Laden vom vollen Text zur Kurzdarstellung. Dieselbe Datei läuft auch
|
||||
* als Modul (app.js) für dynamisch eingefügte Hinweise.
|
||||
*/
|
||||
public static function bootScript(): string
|
||||
{
|
||||
$file = resource_path('js/notice.js');
|
||||
|
||||
// Fehlt die Datei im Abbild, bleibt die Seite lesbar: Das Modul (app.js) übernimmt, nur ein Sprung beim Laden ist möglich.
|
||||
if (! is_readable($file)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$source = (string) file_get_contents($file);
|
||||
$source = (string) preg_replace('#/\*.*?\*/#s', '', $source);
|
||||
$source = (string) preg_replace('#^\s*//.*$#m', '', $source);
|
||||
|
||||
return trim((string) preg_replace('/\n\s*\n+/', "\n", $source));
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return 'notice';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Hinweiszeile';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Kompakter Hinweis mit formatiertem Text und Symbol, wahlweise mit aufklappbarer Kurzdarstellung.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
{
|
||||
return [1, 2, 3, 4];
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Der Text bricht um, nichts wird abgeschnitten. Je nach Modus wechselt der Hinweis bei geringer Widgetbreite zur aufklappbaren Kurzdarstellung; die Breite des Widgets entscheidet, nicht die des Fensters.';
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'Modus „Responsiv“: Kurzdarstellung (bei Zeilengrenze nur, wenn der Volltext mehr Zeilen braucht)',
|
||||
'wide' => 'vollständiger Text; im Modus „Immer mit Kurzdarstellung starten“ auch hier zuerst die Kurzdarstellung',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-information-circle';
|
||||
}
|
||||
|
||||
public function schematic(): array
|
||||
{
|
||||
return [[2, 11, 56, 14, 'line'], [2, 11, 2, 14, 'accent'], [8, 15, 30, 3, 'ink'], [8, 20, 44, 2, 'line']];
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'text' => ['required', 'string', 'max:'.self::TEXT_MAX_LENGTH],
|
||||
'short' => ['nullable', 'string', 'max:'.self::SHORT_MAX_LENGTH],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
RichField::make('text', 'Vollständiger Text', website: true)
|
||||
->required()
|
||||
->helperText('Der ganze Hinweis. Wie beim Fließtext: fett, kursiv, Farbmarkierungen (Marine, Grün, Rot, Grau), Links, Listen und Ausrichtung. Im Modus „Volltext“ ist das der einzige Text, der angezeigt wird.'),
|
||||
RichField::make('short', 'Kurztext (optional)', website: true)
|
||||
->helperText('Die Kurzdarstellung für die Modi „Responsiv“ und „Immer mit Kurzdarstellung starten“, am besten ein Satz. Er wird gespeichert, auch wenn der Modus „Volltext“ gewählt ist, und geht beim Wechsel des Modus nicht verloren. Ohne Kurztext erscheint immer der vollständige Text.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$text = FormattedText::canonical(is_string($data['text'] ?? null) ? $data['text'] : '', true);
|
||||
$short = FormattedText::canonical(is_string($data['short'] ?? null) ? $data['short'] : '', true);
|
||||
|
||||
if ($text === '') {
|
||||
$errors->add('data.text', 'Bitte den vollständigen Text eingeben.');
|
||||
}
|
||||
|
||||
// Die Schlüssel stehen nur, wenn sie ausgefüllt sind; ein leerer Kurztext bleibt byteweise ohne Spur.
|
||||
$data['text'] = $text;
|
||||
|
||||
if ($short === '') {
|
||||
unset($data['short']);
|
||||
} else {
|
||||
$data['short'] = $short;
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
$text = $widget['data']['text'] ?? null;
|
||||
$short = $widget['data']['short'] ?? null;
|
||||
$shortHtml = is_string($short) && trim($short) !== '' ? ProseWidget::render($short) : '';
|
||||
$layout = self::layout($widget['settings'] ?? [], $shortHtml !== '');
|
||||
|
||||
return [
|
||||
'textHtml' => is_string($text) && trim($text) !== '' ? ProseWidget::render($text) : '',
|
||||
'shortHtml' => $shortHtml,
|
||||
'layout' => $layout,
|
||||
// Nur die Vorschau weist darauf hin, dass ein gewählter Modus ohne Kurztext nichts einklappen kann.
|
||||
'notice' => $context->preview && $shortHtml === '' && self::layout($widget['settings'] ?? [])['mode'] !== 'full'
|
||||
? 'Der gewählte Modus braucht einen Kurztext. Ohne ihn erscheint der vollständige Text immer.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'mode' => self::MODE,
|
||||
'line_limit' => self::LINE_LIMIT,
|
||||
'narrow' => self::NARROW,
|
||||
'size' => self::SIZE,
|
||||
'align' => HeadingAccent::TEXT_ALIGN,
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => self::SYMBOL_SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
'surface' => self::SURFACE,
|
||||
'border' => self::BORDER,
|
||||
'bar' => self::BAR,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Darstellungsmodus' => ['mode', 'narrow', 'line_limit'],
|
||||
'Text' => ['size', 'align'],
|
||||
'Symbol' => ['symbol', 'symbol_size', 'symbol_align'],
|
||||
'Fläche' => ['surface', 'border', 'bar'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'mode' => ['Darstellungsmodus', 'Volltext (Vorgabe): Der ganze Hinweis ist immer sichtbar. Responsiv: Breit der ganze Text, bei wenig Platz die Kurzdarstellung mit Pfeil zum Aufklappen. Immer mit Kurzdarstellung starten: Auf jeder Breite zuerst der Kurztext, ein Klick zeigt den ganzen Text, ein weiterer Klick klappt wieder zu. Die Kurzdarstellung ist beim Laden immer eingeklappt. Beide Fassungen bleiben beim Wechsel erhalten; ohne Kurztext erscheint immer der vollständige Text.'],
|
||||
'narrow' => ['Wann gilt „wenig Platz“?', 'Gemessen wird die Breite des Widgets, nicht die des Fensters: Ein Hinweis in einer schmalen Spalte klappt früher ein als derselbe Hinweis über die ganze Seite. Wirkt nur im Modus „Responsiv“. Vorgabe: unter 40 rem (etwa 640 px).'],
|
||||
'line_limit' => ['Zeilengrenze', 'Nur bei wenig Platz und nur im Modus „Responsiv“: Die Kurzdarstellung erscheint, wenn der vollständige Text bei der tatsächlichen Breite mehr Zeilen braucht als gewählt (gezählt werden umgebrochene Textzeilen). Es werden nie Zeilen abgeschnitten. Ohne Grenze (Vorgabe) steht bei wenig Platz immer die Kurzdarstellung. Im Modus „Immer mit Kurzdarstellung starten“ wird die Grenze nicht berücksichtigt.'],
|
||||
'size' => ['Schriftgröße', 'XS, S (Vorgabe), M und L. S, M und L sind die Stufen „klein“, „Text“ und „Einleitung“ des Designsystems; XS ist etwas kleiner (13 px) und nur für Randbemerkungen gedacht.'],
|
||||
'align' => ['Ausrichtung', 'Richtet den Text aus. Vorgabe: linksbündig.'],
|
||||
'symbol' => ['Symbol', 'Kleine Grafik aus dem Brand-Kit vor dem Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'],
|
||||
'symbol_size' => ['Größe des Symbols', 'Unabhängig von der Schriftgröße: von sehr klein (1 rem) bis sehr groß (3,5 rem). Vorgabe: Klein. Wirkt nur, wenn ein Symbol gewählt ist.'],
|
||||
'symbol_align' => ['Senkrechte Lage des Symbols', 'Oben (Vorgabe, auf Höhe der ersten Zeile), Mitte oder Unten. Wirkt nur, wenn ein Symbol gewählt ist.'],
|
||||
'surface' => ['Hintergrundfläche', 'Eine dezente Fläche hinter dem Hinweis (Farben des Designsystems). Auf der Fläche ist die Schrift immer dunkel, auch auf dunklen Abschnitten. Vorgabe: ohne Fläche, der Hinweis steht auf dem Abschnitt.'],
|
||||
'border' => ['Rahmen', 'Ein feiner Rahmen um den Hinweis. Vorgabe: ohne.'],
|
||||
'bar' => ['Akzentlinie', 'Eine farbige Linie links oder oben am Hinweis. Vorgabe: ohne.'],
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$html = FormattedText::canonical(is_string($widget['data']['text'] ?? null) ? $widget['data']['text'] : '', true);
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags((string) preg_replace('#</(?:p|li|blockquote)>#', ' $0', $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
|
||||
|
||||
return mb_strlen($text) > 120 ? rtrim(mb_substr($text, 0, 119)).'…' : $text;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,32 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\RichText;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use App\Filament\Support\RichField;
|
||||
|
||||
/**
|
||||
* Fließtext mit dem Editor der Dokumente (ADR-50, ADR-51): Zwischenüberschriften, fett, kursiv, Links, Listen, Zitate und
|
||||
* Tabellen, dazu Schriftgröße, Schriftfarbe und Ausrichtung aus festen Werten (Webprofil von FormattedText). Gespeichert wird bereinigtes HTML (FormattedText, Regel „Links auf eigene Seiten erlaubt“); Skripte, Stile und
|
||||
* Ereignisattribute entfallen. Bilder gibt es im Text nicht: Die Bilder der Website stehen als eigene Bausteine (zum
|
||||
* Beispiel Bild und Text), nicht als Bildfassungen eines Dokuments.
|
||||
*
|
||||
* Version 1 (Bestand): Klartext, eine Leerzeile beginnt einen Absatz. Version 2: formatierter Text (HTML).
|
||||
*/
|
||||
class ProseWidget extends WidgetType
|
||||
{
|
||||
/** Größtes zulässiges Maß des gespeicherten HTML (entspricht der Bereinigung des Textbausteins). */
|
||||
public const MAX_LENGTH = 100000;
|
||||
|
||||
public function version(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return 'prose';
|
||||
@@ -20,7 +40,7 @@ public function label(): string
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Längerer Text in Absätzen. Eine Leerzeile beginnt einen neuen Absatz.';
|
||||
return 'Längerer Text mit Zwischenüberschriften, Hervorhebungen, Listen, Zitaten, Tabellen und Links, geschrieben im Editor wie bei den Dokumenten.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
@@ -30,12 +50,12 @@ public function supportedUnits(): array
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Fließtext bricht um; Zeilen höchstens etwa 70 Zeichen.';
|
||||
return 'Fließtext bricht um; Zeilen höchstens etwa 70 Zeichen. Eine Tabelle scrollt bei wenig Platz waagerecht.';
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 2;
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
@@ -50,27 +70,98 @@ public function icon(): string
|
||||
return 'heroicon-o-bars-3-bottom-left';
|
||||
}
|
||||
|
||||
public function upgrade(array $widget, int $from): array
|
||||
{
|
||||
if ($from === 1) {
|
||||
// Klartext wird zu Absätzen an den Leerzeilen (wie bisher dargestellt), nicht zu Listen oder Überschriften.
|
||||
$body = $widget['data']['body'] ?? '';
|
||||
$widget['data']['body'] = FormattedText::canonicalHtml(RichText::fromPlainText(is_string($body) ? $body : ''), true);
|
||||
|
||||
return $widget;
|
||||
}
|
||||
|
||||
return parent::upgrade($widget, $from);
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'body' => ['required', 'string', 'max:20000'],
|
||||
'body' => ['required', 'string', 'max:'.self::MAX_LENGTH],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
Textarea::make('body')
|
||||
->label('Text')
|
||||
->rows(10)
|
||||
RichField::make('body', 'Text', website: true)
|
||||
->required()
|
||||
->maxLength(20000)
|
||||
->helperText('Eine Leerzeile beginnt einen neuen Absatz.'),
|
||||
->helperText('Zwischenüberschriften (H3 bis H6), fett, kursiv, Links, Listen, Zitate und Tabellen. Dazu Schriftgröße, Schriftfarbe (Marine, Grün, Rot, Grau) und Ausrichtung (linksbündig, zentriert, rechtsbündig) des Absatzes. Auf dunklen und grünen Flächen werden die Farben aufgehellt, damit die Schrift lesbar bleibt. Links auf eigene Seiten wie /materialien oder #anker sind möglich. Eine Tabelle legen Sie über das Tabellensymbol an; die erste Zeile lässt sich als Kopfzeile kennzeichnen.'),
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$data['body'] = FormattedText::canonical(is_string($data['body'] ?? null) ? $data['body'] : '', true);
|
||||
|
||||
if ($data['body'] === '') {
|
||||
$errors->add('data.body', 'Bitte einen Text eingeben.');
|
||||
}
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
return ['html' => self::render($widget['data']['body'] ?? null)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe. Jede Tabelle steht in einem Rahmen, der bei wenig Platz waagerecht scrollt und mit der
|
||||
* Tastatur erreichbar ist.
|
||||
*/
|
||||
public static function render(mixed $body): string
|
||||
{
|
||||
$html = FormattedText::html(is_string($body) ? $body : '', null, true);
|
||||
|
||||
// Die Ausrichtung steht gespeichert als Stil (so liest der Editor sie); auf der Seite wird sie eine Klasse.
|
||||
return str_replace(
|
||||
['<table>', '</table>', ' style="text-align: center"', ' style="text-align: end"'],
|
||||
['<div class="prose-table" role="region" tabindex="0" aria-label="Tabelle"><table>', '</table></div>', ' class="ta-center"', ' class="ta-end"'],
|
||||
$html,
|
||||
);
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
'text_width' => HeadingAccent::TEXT_WIDTH,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['text_width', 'symbol', 'symbol_size', 'symbol_align']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'symbol' => ['Symbol neben dem Text', 'Kleine Grafik aus dem Brand-Kit links neben dem ganzen Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'],
|
||||
'symbol_size' => ['Größe des Symbols', 'Vorgabe: Mittel. Bei wenig Platz steht das Symbol über dem Text. Wirkt nur, wenn ein Symbol gewählt ist.'],
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
'text_width' => HeadingAccent::TEXT_WIDTH_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
return RichText::excerpt(e((string) ($widget['data']['body'] ?? '')));
|
||||
// Gelesen wird im Webprofil: Das Profil der Verwaltung kennt Spans (Größe, Farbe) nicht und ließe ihren Text weg.
|
||||
$html = FormattedText::canonical(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : '', true);
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags((string) preg_replace('#</(?:p|h[3-6]|li|td|th|blockquote)>#', ' $0', $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')));
|
||||
|
||||
return mb_strlen($text) > 120 ? rtrim(mb_substr($text, 0, 119)).'…' : $text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\ShopCatalog;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
|
||||
/**
|
||||
* Shop-Produkte (ADR-55): die kaufbaren Produkte als Kacheln, aus derselben Datenquelle wie die Shopseite (ShopCatalog).
|
||||
*
|
||||
* Gespeichert werden nur Darstellungswahl und Filter (Säule, Materialart); Titel, Bild, Preis und Marker kommen zur
|
||||
* Laufzeit aus den Fachdaten. Das Widget zeigt nichts, solange der Shop nicht sichtbar ist (Schalter „Shop sichtbar“).
|
||||
* Eine Kachel begründet keine Berechtigung. Anders als Programm- und Modulkarten trägt es Preise und führt zur Produktseite.
|
||||
*/
|
||||
class ShopProductsWidget extends WidgetType
|
||||
{
|
||||
public function key(): string
|
||||
{
|
||||
return 'shop_products';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'Shop-Produkte';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Die kaufbaren Produkte des Shops als Kacheln mit Bild, Marker und Preis; optional gefiltert und sortiert.';
|
||||
}
|
||||
|
||||
public function supportedUnits(): array
|
||||
{
|
||||
return [2, 3, 4];
|
||||
}
|
||||
|
||||
public function minUnits(): int
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
public function preferredUnits(): int
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
|
||||
public function narrowBehavior(): string
|
||||
{
|
||||
return 'Die Kacheln stehen untereinander; ab etwa 17 rem Kachelbreite mehrere nebeneinander.';
|
||||
}
|
||||
|
||||
public function stages(): array
|
||||
{
|
||||
return [
|
||||
'narrow' => 'eine Kachel je Zeile',
|
||||
'wide' => 'mehrere Kacheln nebeneinander ab 17 rem Kachelbreite',
|
||||
];
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
{
|
||||
return 'heroicon-o-shopping-bag';
|
||||
}
|
||||
|
||||
public function schematic(): array
|
||||
{
|
||||
return [[2, 4, 17, 28, 'line'], [21, 4, 17, 28, 'line'], [40, 4, 17, 28, 'line'], [4, 6, 13, 10, 'image'], [23, 6, 13, 10, 'image'], [42, 6, 13, 10, 'image'], [4, 19, 11, 3, 'ink'], [23, 19, 11, 3, 'ink'], [42, 19, 11, 3, 'ink'], [4, 26, 7, 3, 'accent'], [23, 26, 7, 3, 'accent'], [42, 26, 7, 3, 'accent']];
|
||||
}
|
||||
|
||||
public function variants(): array
|
||||
{
|
||||
return [
|
||||
'kacheln' => 'Kacheln mit Bild',
|
||||
'liste' => 'Liste mit kleinem Bild',
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'sort' => ['name' => 'Alphabetisch', 'neu' => 'Neueste zuerst', 'preis' => 'Preis aufsteigend'],
|
||||
'limit' => ['alle' => 'Alle Produkte', 'n3' => '3 Produkte', 'n6' => '6 Produkte', 'n9' => '9 Produkte', 'n12' => '12 Produkte', 'n24' => '24 Produkte'],
|
||||
'search' => ['aus' => 'Ohne Suchfeld', 'an' => 'Mit Suchfeld'],
|
||||
'filter' => ['aus' => 'Ohne Auswahl', 'an' => 'Mit Suche, Auswahl, Ansicht und Seiten'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'sort' => ['Reihenfolge', 'Ohne Wahl gilt die Reihenfolge der Shopseite: Altbestand, Artikel, Pakete.'],
|
||||
'limit' => ['Anzahl', 'Wie viele Produkte höchstens erscheinen. Ohne Wahl erscheinen alle.'],
|
||||
'search' => ['Suchfeld', 'Ein einfaches Suchfeld über den Kacheln. Es sendet an die Seite, auf der das Widget steht.'],
|
||||
'filter' => ['Auswahl für Besucher', 'Suche, Auswahl nach Thema, Materialart, Eignung und Nutzerkreis, Reihenfolge, Umschalter Kacheln und Liste und Seiten. Sinnvoll auf der Shopseite mit vielen Produkten. Ersetzt das einfache Suchfeld und die Einstellung „Anzahl“.'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Auswahl' => ['sort', 'limit', 'search', 'filter']];
|
||||
}
|
||||
|
||||
public function dataRules(): array
|
||||
{
|
||||
return [
|
||||
'heading' => ['nullable', 'string', 'max:160'],
|
||||
'intro' => ['nullable', 'string', 'max:400'],
|
||||
'pillar' => ['nullable', 'integer'],
|
||||
'kind' => ['nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('heading')->label('Abschnittsüberschrift (optional)')->maxLength(160),
|
||||
Textarea::make('intro')->label('Einleitung (optional)')->rows(2)->maxLength(400),
|
||||
Select::make('pillar')
|
||||
->label('Nur Produkte einer Säule (optional)')
|
||||
->helperText('Nur veröffentlichte Säulen sind wählbar. Ohne Wahl erscheinen alle Produkte.')
|
||||
->options(fn (): array => Pillar::query()->published()->pluck('name', 'id')->all())
|
||||
->placeholder('Alle Säulen')
|
||||
->native(false),
|
||||
Select::make('kind')
|
||||
->label('Nur eine Materialart (optional)')
|
||||
->options(fn (): array => EditorialContentKind::query()->where('is_active', true)->orderBy('sort_order')->get()
|
||||
->filter(fn (EditorialContentKind $kind): bool => in_array('lizenzartikel', (array) ($kind->contexts ?? []), true))
|
||||
->pluck('label', 'id')->all())
|
||||
->placeholder('Alle Materialarten')
|
||||
->native(false),
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
foreach (['heading', 'intro'] as $key) {
|
||||
$data[$key] = filled($data[$key] ?? null) ? trim((string) $data[$key]) : null;
|
||||
}
|
||||
|
||||
$pillar = filled($data['pillar'] ?? null) ? (int) $data['pillar'] : null;
|
||||
|
||||
if ($pillar !== null && ! Pillar::query()->published()->whereKey($pillar)->exists()) {
|
||||
$errors->add('data.pillar', 'Diese Säule gibt es nicht oder sie ist nicht veröffentlicht.');
|
||||
$pillar = null;
|
||||
}
|
||||
|
||||
$kind = filled($data['kind'] ?? null) ? (int) $data['kind'] : null;
|
||||
|
||||
if ($kind !== null && ! EditorialContentKind::query()->whereKey($kind)->exists()) {
|
||||
$errors->add('data.kind', 'Diese Materialart gibt es nicht.');
|
||||
$kind = null;
|
||||
}
|
||||
|
||||
$data['pillar'] = $pillar;
|
||||
$data['kind'] = $kind;
|
||||
|
||||
return [$data, $refs];
|
||||
}
|
||||
|
||||
public function resolve(array $widget, RenderContext $context): array
|
||||
{
|
||||
if (! Shop::visible()) {
|
||||
return ['listing' => null, 'cards' => [], 'term' => '', 'shopVisible' => false];
|
||||
}
|
||||
|
||||
$settings = is_array($widget['settings'] ?? null) ? $widget['settings'] : [];
|
||||
$filters = ($settings['filter'] ?? 'aus') === 'an';
|
||||
$search = ($settings['search'] ?? 'aus') === 'an';
|
||||
$limit = preg_match('/^n(\\d+)$/', (string) ($settings['limit'] ?? ''), $match) === 1 ? (int) $match[1] : null;
|
||||
$query = $context->preview ? [] : request()->query();
|
||||
$term = ($search || $filters) && isset($query['suche']) && is_string($query['suche']) ? mb_substr(trim($query['suche']), 0, 100) : '';
|
||||
$fixed = [
|
||||
'pillar' => $widget['data']['pillar'] ?? null,
|
||||
'kind' => $widget['data']['kind'] ?? null,
|
||||
'sort' => $settings['sort'] ?? null,
|
||||
'limit' => $filters ? null : $limit,
|
||||
'view' => ($widget['variant'] ?? 'kacheln') === 'liste' ? 'liste' : 'kacheln',
|
||||
'filters' => $filters,
|
||||
];
|
||||
$listing = app(ShopCatalog::class)->listing($filters ? $query : ['suche' => $term], $fixed);
|
||||
|
||||
return [
|
||||
'listing' => $listing,
|
||||
'cards' => $listing['cards'],
|
||||
'term' => $term,
|
||||
'shopVisible' => true,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
$heading = $widget['data']['heading'] ?? null;
|
||||
|
||||
return trim(($heading ? $heading.' · ' : '').'Shop-Produkte');
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,41 @@ public function add(Offer $offer): string
|
||||
return self::ADDED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Welche der Optionen das Konto schon besitzt (für einen Lizenzinhaber, für den es bestellen darf, mit denselben
|
||||
* Rechten). Ohne Konto ist es leer; die Kasse prüft den Besitz ohnehin noch einmal.
|
||||
*
|
||||
* @param list<Offer> $offers
|
||||
* @return array<int, true>
|
||||
*/
|
||||
public function ownedAmong(?User $user, array $offers): array
|
||||
{
|
||||
if ($user === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$holders = $this->holders->for($user);
|
||||
$owned = [];
|
||||
|
||||
foreach ($offers as $offer) {
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($holders as $holder) {
|
||||
if ($this->suitsHolder($version, $holder) && $this->ownership->covers($holder, $version)) {
|
||||
$owned[$offer->id] = true;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $owned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausdrücklicher Wechsel: die Alternative wird durch die gewählte Option ersetzt.
|
||||
*/
|
||||
|
||||
@@ -45,10 +45,18 @@ public function blocks(): bool
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
if ($this->offer->standalone_bundle && $this->version !== null) {
|
||||
$bundle = app(ProductOptions::class)->bundleOf($this->version);
|
||||
$products = app(ProductOptions::class);
|
||||
|
||||
if ($bundle !== null) {
|
||||
if ($this->version !== null) {
|
||||
$article = $products->articleOf($this->version);
|
||||
|
||||
if ($article !== null) {
|
||||
return $products->articleTitle($article);
|
||||
}
|
||||
|
||||
$bundle = $products->bundleOf($this->version);
|
||||
|
||||
if ($bundle !== null && $this->version->lines->count() === 1) {
|
||||
return (string) $bundle->name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
@@ -25,39 +24,10 @@ class Checkout
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Einzelkauf einer Option als Person (bestehender Weg, ohne Warenkorb).
|
||||
*/
|
||||
public function place(User $user, Offer $offer): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
// Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den
|
||||
// Weg über die Kasse mit Pflichtangaben.
|
||||
if (Shop::live()) {
|
||||
throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.');
|
||||
}
|
||||
|
||||
$version = $this->offers->currentActiveVersion($offer);
|
||||
|
||||
if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
|
||||
throw new DomainRuleException('Dieses Angebot kann nicht als persönlicher Kauf bestellt werden.');
|
||||
}
|
||||
|
||||
if ($version->price_cents === null) {
|
||||
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
|
||||
}
|
||||
|
||||
$holder = $this->holders->resolve($user, null);
|
||||
|
||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Bestellung aus dem Warenkorb, erst nach serverseitiger Prüfung. Die Prüfsumme bindet die Bestellung an die
|
||||
* Übersicht, die der Käufer gesehen hat: Hat sich Preis, Fassung oder Bedingung seither geändert, entsteht keine
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionStructureReader;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
|
||||
/**
|
||||
@@ -22,42 +24,99 @@ class ProductOptions
|
||||
public function __construct(private readonly OfferService $offers) {}
|
||||
|
||||
/**
|
||||
* Optionen der Produktseite eines Lizenzartikels: Angebote, deren einzige Position dieser Artikel ist.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
public function forArticle(LicenseArticle $article): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('composition_id', $composition->id)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
return $this->optionsFor('a:'.$article->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
|
||||
* dieses Paket verkauft.
|
||||
* Alle Optionen, die diesen Artikel als einzige Position verkaufen oder verkauften, auch beendete und solche ohne
|
||||
* Preis (Verwaltung). Die öffentliche Seite zeigt davon nur die kaufbaren (`forArticle`).
|
||||
*
|
||||
* @return list<Offer>
|
||||
*/
|
||||
public function offersOfArticle(LicenseArticle $article): array
|
||||
{
|
||||
return Offer::query()
|
||||
->whereHas('versions.lines', fn ($query) => $query->where('license_article_id', $article->id))
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->filter(fn (Offer $offer): bool => $this->groupKey($offer) === 'a:'.$article->id)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der Produktseite eines Pakets: Angebote, deren einzige Position eine Fassung dieses Pakets ist.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$options = [];
|
||||
return $this->optionsFor('b:'.$bundle->id);
|
||||
}
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
/**
|
||||
* Altbestand: Angebote mit mehreren Positionen, die einer Programmseite zugeordnet wurden. Neue Angebote
|
||||
* haben immer genau eine Position und damit eine Artikel- oder Paketseite.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
return $this->optionsFor('c:'.$composition->id);
|
||||
}
|
||||
|
||||
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Der Artikel, den die Fassung als einzige Position verkauft, sonst null.
|
||||
*/
|
||||
public function articleOf(OfferVersion $version): ?LicenseArticle
|
||||
{
|
||||
$version->loadMissing('lines.article');
|
||||
|
||||
return $options;
|
||||
return $version->lines->count() === 1 ? $version->lines->first()->article : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aufbau des Inhalts, den der aktuelle Stand des Artikels liefert (Rolle und Titel der Bestandteile). Ein Artikel
|
||||
* mit einem einzelnen Medium als Wurzel hat keine Struktur. Dateien und Lehrtexte kommen hier nie vor.
|
||||
*
|
||||
* @return list<StructureNode>
|
||||
*/
|
||||
public function articleStructure(LicenseArticle $article): array
|
||||
{
|
||||
$version = $article->currentRelease?->rootCompositionVersion;
|
||||
|
||||
return $version === null ? [] : app(CompositionStructureReader::class)->tree($version);
|
||||
}
|
||||
|
||||
/** Lernziel des Inhalts im aktuellen Stand des Artikels, wie es schon die öffentliche Programmseite zeigt. */
|
||||
public function articleGoal(LicenseArticle $article): ?string
|
||||
{
|
||||
$goal = $article->currentRelease?->rootCompositionVersion?->learning_goal;
|
||||
|
||||
return filled($goal) ? (string) $goal : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Artikel mit kaufbarer Option, deren Inhalt diese Komposition ist: Die Programmseite verweist auf sie.
|
||||
*
|
||||
* @return list<LicenseArticle>
|
||||
*/
|
||||
public function articlesOf(Composition $composition): array
|
||||
{
|
||||
return LicenseArticle::query()
|
||||
->whereNull('archived_at')
|
||||
->whereHas('currentRelease.rootCompositionVersion', fn ($query) => $query->where('composition_id', $composition->id))
|
||||
->orderBy('code')
|
||||
->get()
|
||||
->filter(fn (LicenseArticle $article): bool => $this->forArticle($article) !== [])
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -70,62 +129,139 @@ public function bundleOf(OfferVersion $version): ?Bundle
|
||||
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
|
||||
}
|
||||
|
||||
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
|
||||
/**
|
||||
* Schlüssel der Produktseite, auf der die Option angeboten wird: Artikelseite (`a:`), Paketseite (`b:`) oder, nur
|
||||
* im Altbestand mit mehreren Positionen, die Programmseite (`c:`). Die Seite ergibt sich aus der Angebotsfassung
|
||||
* und wird nirgends von Hand zugeordnet.
|
||||
*/
|
||||
public function groupKey(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return 'c:'.$offer->composition_id;
|
||||
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
|
||||
|
||||
return $this->keyFor($offer, $version);
|
||||
}
|
||||
|
||||
private function keyFor(Offer $offer, ?OfferVersion $version): ?string
|
||||
{
|
||||
if ($version !== null && $version->lines()->count() === 1) {
|
||||
$article = $this->articleOf($version);
|
||||
|
||||
if ($article !== null) {
|
||||
return 'a:'.$article->id;
|
||||
}
|
||||
|
||||
$bundle = $this->bundleOf($version);
|
||||
|
||||
if ($bundle !== null) {
|
||||
return 'b:'.$bundle->id;
|
||||
}
|
||||
}
|
||||
|
||||
if ($offer->standalone_bundle) {
|
||||
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
return $bundle === null ? null : 'b:'.$bundle->id;
|
||||
}
|
||||
|
||||
return null;
|
||||
return $offer->composition_id !== null ? 'c:'.$offer->composition_id : null;
|
||||
}
|
||||
|
||||
/** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */
|
||||
public function pageUrl(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return route('public.program', $offer->composition_id);
|
||||
}
|
||||
|
||||
$key = $this->groupKey($offer);
|
||||
|
||||
return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null;
|
||||
if ($key === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$id = (int) substr($key, 2);
|
||||
|
||||
return match ($key[0]) {
|
||||
'a' => route('shop.article', $id),
|
||||
'b' => route('public.package', $id),
|
||||
default => route('public.program', $id),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
* Kaufbare Optionen je Produktseite: Seitenschlüssel => Angebot und Fassung in der Reihenfolge der Angebote.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
* @return array<string, list<array{offer: Offer, version: OfferVersion}>>
|
||||
*/
|
||||
public function bundleSummaries(): array
|
||||
private function purchasable(): array
|
||||
{
|
||||
$pages = [];
|
||||
|
||||
foreach (Offer::query()->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
$key = $version === null ? null : $this->keyFor($offer, $version);
|
||||
|
||||
if ($key !== null) {
|
||||
$pages[$key][] = ['offer' => $offer, 'version' => $version];
|
||||
}
|
||||
}
|
||||
|
||||
return $pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function optionsFor(string $key): array
|
||||
{
|
||||
return array_map(fn (array $row): array => $this->describe($row['offer'], $row['version']), $this->purchasable()[$key] ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Günstigster Preis und Zahl der Optionen je Seite einer Art ('a', 'b' oder 'c'): Kennung => Zusammenfassung.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
|
||||
*/
|
||||
private function summariesOf(string $kind): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
if ($bundle === null) {
|
||||
foreach ($this->purchasable() as $key => $rows) {
|
||||
if ($key[0] !== $kind) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$bundle->id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
$summary[(int) substr($key, 2)] = [
|
||||
'from_cents' => min(array_map(fn (array $row): int => (int) $row['version']->price_cents, $rows)),
|
||||
'count' => count($rows),
|
||||
'holders' => array_values(array_unique(array_map(fn (array $row): string => (string) $row['version']->holder_kind, $rows))),
|
||||
'scopes' => array_values(array_unique(array_filter(array_map(fn (array $row): ?string => $row['version']->licence_scope, $rows)))),
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Artikel mit kaufbarer Option: Artikelkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
|
||||
*/
|
||||
public function articleSummaries(): array
|
||||
{
|
||||
return $this->summariesOf('a');
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
|
||||
*/
|
||||
public function bundleSummaries(): array
|
||||
{
|
||||
return $this->summariesOf('b');
|
||||
}
|
||||
|
||||
/**
|
||||
* Altbestand: Programmseiten mit kaufbaren Optionen (Angebote mit mehreren Positionen).
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int, holders: list<string>, scopes: list<string>}>
|
||||
*/
|
||||
public function summaries(): array
|
||||
{
|
||||
return $this->summariesOf('c');
|
||||
}
|
||||
|
||||
/**
|
||||
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
|
||||
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
|
||||
@@ -158,32 +294,6 @@ public function bundleContents(array $options): array
|
||||
return array_values($contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function summaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->whereNotNull('composition_id')->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$offer->composition_id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$offer->composition_id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
* WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und
|
||||
* enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können.
|
||||
* Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“).
|
||||
*
|
||||
* Für längere Dokumente (Handbuch) kann der Schreiber zusätzlich Flächen, JPEG-Bilder, Verweise innerhalb des Dokuments
|
||||
* (Inhaltsverzeichnis) und Lesezeichen setzen. Wer sie nicht nutzt, erhält dieselben Bytes wie zuvor: Die zusätzlichen
|
||||
* Objekte entstehen nur bei Bedarf und nach allen bisherigen.
|
||||
*/
|
||||
final class PdfDocument
|
||||
{
|
||||
@@ -17,14 +21,139 @@ final class PdfDocument
|
||||
/** @var list<string> */
|
||||
private array $pages = [];
|
||||
|
||||
/** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */
|
||||
private bool $usesItalic = false;
|
||||
|
||||
/** @var list<array{bytes: string, width: int, height: int}> */
|
||||
private array $images = [];
|
||||
|
||||
/** @var array<string, int> Prüfsumme der Bilddatei => Index in {@see self::$images} */
|
||||
private array $imageIndex = [];
|
||||
|
||||
/** @var array<int, array<int, true>> Seite => Bilder, die sie zeigt */
|
||||
private array $pageImages = [];
|
||||
|
||||
/** @var array<int, list<array{x: float, y: float, w: float, h: float, page?: int, top?: float, uri?: string}>> */
|
||||
private array $links = [];
|
||||
|
||||
/** @var list<array{title: string, page: int, top: float, level: int}> */
|
||||
private array $outline = [];
|
||||
|
||||
/** Breiten der Helvetica (Tausendstel der Schrifthöhe) für Zeichen 32 bis 126; schräg wie aufrecht. */
|
||||
private const REGULAR = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
|
||||
|
||||
/** Breiten der Helvetica-Bold für Zeichen 32 bis 126; schräg wie aufrecht. */
|
||||
private const BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
|
||||
|
||||
public function addPage(): void
|
||||
{
|
||||
$this->pages[] = '';
|
||||
}
|
||||
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
/** Anzahl der bisher angelegten Seiten. */
|
||||
public function pageCount(): int
|
||||
{
|
||||
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
|
||||
return count($this->pages);
|
||||
}
|
||||
|
||||
/** Gefüllte Fläche in einem Grauwert (0 schwarz, 1 weiß), zum Beispiel für Tabellenköpfe. */
|
||||
public function fillRect(float $x, float $y, float $w, float $h, float $gray): void
|
||||
{
|
||||
$this->append(sprintf("q %s g %s %s %s %s re f Q\n", $this->n($gray), $this->n($x), $this->n($y), $this->n($w), $this->n($h)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt ein JPEG (RGB, aus `imagejpeg`) mit seiner linken unteren Ecke bei `$x`/`$y`. Dasselbe Bild wird nur einmal
|
||||
* im Dokument abgelegt.
|
||||
*/
|
||||
public function image(float $x, float $y, float $w, float $h, string $jpeg, int $pixelWidth, int $pixelHeight): void
|
||||
{
|
||||
$key = md5($jpeg);
|
||||
|
||||
if (! isset($this->imageIndex[$key])) {
|
||||
$this->imageIndex[$key] = count($this->images);
|
||||
$this->images[] = ['bytes' => $jpeg, 'width' => $pixelWidth, 'height' => $pixelHeight];
|
||||
}
|
||||
|
||||
$index = $this->imageIndex[$key];
|
||||
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->pageImages[array_key_last($this->pages)][$index] = true;
|
||||
$this->append(sprintf("q %s 0 0 %s %s %s cm /Im%d Do Q\n", $this->n($w), $this->n($h), $this->n($x), $this->n($y), $index + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Anklickbarer Bereich auf der aktuellen Seite, der zu einer Stelle im Dokument springt (Seitenindex ab 0, `$top` ist
|
||||
* die Höhe des Ziels auf der Zielseite).
|
||||
*/
|
||||
public function link(float $x, float $y, float $w, float $h, int $page, float $top): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->links[array_key_last($this->pages)][] = ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'page' => $page, 'top' => $top];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anklickbarer Bereich auf der aktuellen Seite, der eine Internetadresse öffnet. Eine Adresse, die am Zeilenende umbricht,
|
||||
* bekommt für jede Zeile einen Bereich mit derselben vollständigen Adresse: Sie bleibt als Ganzes zusammen, gleich wie
|
||||
* der sichtbare Text umbricht.
|
||||
*/
|
||||
public function uriLink(float $x, float $y, float $w, float $h, string $uri): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->links[array_key_last($this->pages)][] = ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'uri' => $uri];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Adresse als 7-Bit-Zeichenkette für das PDF: Zeichen außerhalb von ASCII und Leerzeichen werden prozentkodiert,
|
||||
* unsichtbare Zeichen entfallen.
|
||||
*/
|
||||
private static function uriString(string $uri): string
|
||||
{
|
||||
$uri = (string) preg_replace('/[\x{00AD}\x{034F}\x{061C}\x{180E}\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{FEFF}]/u', '', $uri);
|
||||
$uri = (string) preg_replace_callback('/[^\x21-\x7E]/', fn (array $m): string => rawurlencode($m[0]), $uri);
|
||||
|
||||
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $uri);
|
||||
}
|
||||
|
||||
/** Lesezeichen (Ebene 1 bis 6) für die Gliederung in PDF-Betrachtern. */
|
||||
public function bookmark(string $title, int $page, float $top, int $level = 1): void
|
||||
{
|
||||
$this->outline[] = ['title' => $title, 'page' => $page, 'top' => $top, 'level' => max(1, min(6, $level))];
|
||||
}
|
||||
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void
|
||||
{
|
||||
$font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1');
|
||||
$this->usesItalic = $this->usesItalic || $italic;
|
||||
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $font, $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Genaue Breite in Punkt nach den Schriftbreiten der Helvetica, damit Textabschnitte mit verschiedenen Schnitten in
|
||||
* einer Zeile ohne Lücken aneinanderstoßen. Umlaute zählen wie ihr Grundbuchstabe, das ß wie ein kleines b, jedes
|
||||
* andere Zeichen außerhalb von ASCII wie eine Ziffer.
|
||||
*/
|
||||
public static function exactWidth(string $text, float $size = 10, bool $bold = false): float
|
||||
{
|
||||
$table = $bold ? self::BOLD : self::REGULAR;
|
||||
$units = 0;
|
||||
$text = strtr($text, ['ä' => 'a', 'ö' => 'o', 'ü' => 'u', 'Ä' => 'A', 'Ö' => 'O', 'Ü' => 'U', 'ß' => 'b', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ']);
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$code = strlen($char) === 1 ? ord($char) : 0;
|
||||
$units += $code >= 32 && $code <= 126 ? $table[$code - 32] : 556;
|
||||
}
|
||||
|
||||
return $units / 1000 * $size;
|
||||
}
|
||||
|
||||
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
@@ -115,13 +244,78 @@ public function output(string $title, ?string $keywords = null): string
|
||||
$kids = [];
|
||||
$next = 6;
|
||||
|
||||
foreach ($pages as $stream) {
|
||||
// Nummern der zusätzlichen Objekte: nach den Seiten und Schriften, in fester Reihenfolge (Verweise, Bilder, Gliederung).
|
||||
$cursor = 6 + 2 * count($pages) + ($this->usesItalic ? 2 : 0);
|
||||
$annotations = [];
|
||||
|
||||
foreach ($this->links as $pageIndex => $links) {
|
||||
foreach ($links as $link) {
|
||||
$annotations[$pageIndex][] = ['number' => $cursor++] + $link;
|
||||
}
|
||||
}
|
||||
|
||||
$imageNumbers = [];
|
||||
|
||||
foreach (array_keys($this->images) as $index) {
|
||||
$imageNumbers[$index] = $cursor++;
|
||||
}
|
||||
|
||||
$outlineRoot = $this->outline === [] ? null : $cursor++;
|
||||
$outlineNumbers = [];
|
||||
|
||||
foreach (array_keys($this->outline) as $index) {
|
||||
$outlineNumbers[$index] = $cursor++;
|
||||
}
|
||||
|
||||
foreach ($pages as $pageIndex => $stream) {
|
||||
$kids[] = $next.' 0 R';
|
||||
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.($next + 1).' 0 R >>';
|
||||
$xobjects = '';
|
||||
|
||||
foreach (array_keys($this->pageImages[$pageIndex] ?? []) as $index) {
|
||||
$xobjects .= ' /Im'.($index + 1).' '.$imageNumbers[$index].' 0 R';
|
||||
}
|
||||
|
||||
$annots = isset($annotations[$pageIndex]) ? ' /Annots ['.implode(' ', array_map(fn (array $link): string => $link['number'].' 0 R', $annotations[$pageIndex])).']' : '';
|
||||
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >>'.($xobjects === '' ? '' : ' /XObject <<'.$xobjects.' >>').' >> /Contents '.($next + 1).' 0 R'.$annots.' >>';
|
||||
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
|
||||
$next += 2;
|
||||
}
|
||||
|
||||
if ($this->usesItalic) {
|
||||
$objects[$next] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';
|
||||
$objects[$next + 1] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique /Encoding /WinAnsiEncoding >>';
|
||||
|
||||
foreach ($objects as $number => $body) {
|
||||
$objects[$number] = str_replace(['%ITALIC%', '%BOLDITALIC%'], [(string) $next, (string) ($next + 1)], $body);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($annotations as $links) {
|
||||
foreach ($links as $link) {
|
||||
$rect = sprintf('[%s %s %s %s]', $this->n($link['x']), $this->n($link['y']), $this->n($link['x'] + $link['w']), $this->n($link['y'] + $link['h']));
|
||||
$objects[$link['number']] = isset($link['uri'])
|
||||
? '<< /Type /Annot /Subtype /Link /Rect '.$rect.' /Border [0 0 0] /A << /S /URI /URI ('.self::uriString($link['uri']).') >> >>'
|
||||
: sprintf(
|
||||
'<< /Type /Annot /Subtype /Link /Rect %s /Border [0 0 0] /Dest [%d 0 R /XYZ 0 %s null] >>',
|
||||
$rect,
|
||||
6 + 2 * min($link['page'], count($pages) - 1),
|
||||
$this->n($link['top']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->images as $index => $image) {
|
||||
$objects[$imageNumbers[$index]] = '<< /Type /XObject /Subtype /Image /Width '.$image['width'].' /Height '.$image['height'].' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '.strlen($image['bytes'])." >>\nstream\n".$image['bytes']."\nendstream";
|
||||
}
|
||||
|
||||
if ($outlineRoot !== null) {
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R /Outlines '.$outlineRoot.' 0 R /PageMode /UseOutlines >>';
|
||||
|
||||
foreach ($this->outlineObjects($outlineRoot, $outlineNumbers, count($pages)) as $number => $body) {
|
||||
$objects[$number] = $body;
|
||||
}
|
||||
}
|
||||
|
||||
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
|
||||
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
|
||||
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
|
||||
@@ -147,6 +341,52 @@ public function output(string $title, ?string $keywords = null): string
|
||||
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung (Lesezeichen): Ebene 1 unter der Wurzel, Ebene 2 unter dem vorangehenden Eintrag der Ebene 1.
|
||||
*
|
||||
* @param array<int, int> $numbers Objektnummer je Eintrag
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function outlineObjects(int $root, array $numbers, int $pageCount): array
|
||||
{
|
||||
$parentOf = [];
|
||||
$childrenOf = [];
|
||||
$descendants = [];
|
||||
$path = [];
|
||||
|
||||
// Ein Eintrag gehört zum nächsten davor mit kleinerer Ebene; ohne einen solchen steht er oben.
|
||||
foreach ($this->outline as $index => $item) {
|
||||
while ($path !== [] && $this->outline[$path[array_key_last($path)]]['level'] >= $item['level']) {
|
||||
array_pop($path);
|
||||
}
|
||||
|
||||
$parentOf[$index] = $path === [] ? null : $path[array_key_last($path)];
|
||||
$childrenOf[$parentOf[$index] ?? -1][] = $index;
|
||||
|
||||
foreach ($path as $ancestor) {
|
||||
$descendants[$ancestor] = ($descendants[$ancestor] ?? 0) + 1;
|
||||
}
|
||||
|
||||
$path[] = $index;
|
||||
}
|
||||
|
||||
$top = $childrenOf[-1];
|
||||
$objects = [$root => '<< /Type /Outlines /First '.$numbers[$top[0]].' 0 R /Last '.$numbers[$top[array_key_last($top)]].' 0 R /Count '.count($this->outline).' >>'];
|
||||
|
||||
foreach ($this->outline as $index => $item) {
|
||||
$siblings = $childrenOf[$parentOf[$index] ?? -1];
|
||||
$position = (int) array_search($index, $siblings, true);
|
||||
$kids = $childrenOf[$index] ?? [];
|
||||
$objects[$numbers[$index]] = '<< /Title ('.self::escape($item['title']).') /Parent '.($parentOf[$index] === null ? $root : $numbers[$parentOf[$index]]).' 0 R'
|
||||
.($position > 0 ? ' /Prev '.$numbers[$siblings[$position - 1]].' 0 R' : '')
|
||||
.($position < count($siblings) - 1 ? ' /Next '.$numbers[$siblings[$position + 1]].' 0 R' : '')
|
||||
.($kids === [] ? '' : ' /First '.$numbers[$kids[0]].' 0 R /Last '.$numbers[$kids[array_key_last($kids)]].' 0 R /Count '.($descendants[$index] ?? 0))
|
||||
.' /Dest ['.(6 + 2 * min($item['page'], $pageCount - 1)).' 0 R /XYZ 0 '.$this->n($item['top']).' null] >>';
|
||||
}
|
||||
|
||||
return $objects;
|
||||
}
|
||||
|
||||
private function append(string $operators): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
@@ -165,7 +405,7 @@ private function n(float $value): string
|
||||
private static function escape(string $text): string
|
||||
{
|
||||
$text = strtr($text, ["\u{2212}" => '-', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ', "\u{202F}" => ' ']);
|
||||
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/u', '', $text);
|
||||
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F\x{00AD}\x{034F}\x{061C}\x{180E}\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2064}\x{FEFF}]/u', '', $text);
|
||||
$encoded = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
|
||||
|
||||
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $encoded);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
/**
|
||||
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||
* Wann der Shop zu sehen ist (visible) und wann gekauft werden kann (checkoutOpen).
|
||||
*
|
||||
* Test und Sandbox: nicht in Produktion, Zahlungstreiber „test“ oder „stripe“ (Testschlüssel).
|
||||
* Produktion: nur mit der ausdrücklichen Produktivfreigabe (`SHOP_LIVE_RELEASE`, Entscheidung von Lars), dem
|
||||
@@ -27,7 +27,24 @@ public static function live(): bool
|
||||
&& SalesTerms::missingPages() === [];
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
/**
|
||||
* Schalter 1: Der Shop ist zu sehen (Übersicht, Produktseiten, Pakete, Menüeinträge in den Shop).
|
||||
* In Produktion mit `SHOP_PUBLIC` oder mit der Produktivfreigabe, sonst wie der Checkout.
|
||||
*/
|
||||
public static function visible(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return config('shop.public') === true || self::live();
|
||||
}
|
||||
|
||||
return self::checkoutOpen();
|
||||
}
|
||||
|
||||
/**
|
||||
* Schalter 2: Der Kauf läuft (Warenkorb, Kasse, Zahlung). In Produktion nur mit der Produktivfreigabe, sonst mit
|
||||
* dem Testzahlungsweg oder der Stripe-Sandbox.
|
||||
*/
|
||||
public static function checkoutOpen(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
@@ -49,7 +66,7 @@ public static function stripe(): bool
|
||||
/** Kauf auf Rechnung für Organisationen (manuelle Rechnung, Zahlungseingang durch den Betreiber). */
|
||||
public static function invoice(): bool
|
||||
{
|
||||
return self::enabled() && (bool) config('shop.invoice', true);
|
||||
return self::checkoutOpen() && (bool) config('shop.invoice', true);
|
||||
}
|
||||
|
||||
private static function liveKey(): bool
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PresentationMedia;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Support\Brand\SymbolCatalog;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Die Produkte des Shops als Kacheln: eine Datenquelle für die Shopseite (und später das Widget).
|
||||
*
|
||||
* Gelistet wird, was mindestens eine kaufbare Option hat (Artikel, Pakete mit eigener Seite, Altbestand mit
|
||||
* Programmseite). Jede Kachel trägt nur öffentlich Zeigbares: Titel und Kurztext aus der Redaktion, das Titelbild nur mit
|
||||
* Website-Freigabe, Säulen nur, wenn sie veröffentlicht sind, die Materialart mit ihrem Symbol, die Marker und den
|
||||
* niedrigsten Preis. Nichts davon begründet eine Berechtigung (ADR-52, ADR-54).
|
||||
*
|
||||
* @phpstan-type Card array{key: string, kind: string, url: string, title: string, teaser: string, from: string, from_cents: int, count: int, image: ?array{url: string, alt: string}, kind_label: string, symbol: ?string, pillars: list<string>, markers: list<array{key: string, label: string}>}
|
||||
*/
|
||||
class ShopCatalog
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProductOptions $products,
|
||||
private readonly PublicCatalogReader $catalog,
|
||||
private readonly EditorialProfileReader $profiles,
|
||||
private readonly PresentationMedia $presentation,
|
||||
private readonly ShopMarkers $markers,
|
||||
) {}
|
||||
|
||||
public const SORTS = ['name' => 'Alphabetisch', 'neu' => 'Neueste zuerst', 'preis' => 'Preis aufsteigend'];
|
||||
|
||||
/**
|
||||
* @param array{pillar?: int|null, kind?: int|null, holder?: string|null, scope?: string|null, sort?: string|null, limit?: int|null} $options Filter
|
||||
* nach Säule, Materialart, Eignung und Nutzerkreis, Sortierung (name, neu, preis) und Höchstzahl
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function cards(string $term = '', array $options = []): array
|
||||
{
|
||||
return $this->arrange($this->all($term), $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Kacheln zu einem Suchbegriff, ungefiltert und in der Reihenfolge der Quellen.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function all(string $term = ''): array
|
||||
{
|
||||
$term = mb_strtolower(mb_substr(trim($term), 0, 100));
|
||||
$cards = [];
|
||||
|
||||
// Altbestand: Angebote mit mehreren Positionen auf einer freigegebenen Programmseite.
|
||||
$summaries = $this->products->summaries();
|
||||
|
||||
foreach (Composition::query()->with(['editorialContentKind', 'pillars'])->whereIn('id', array_keys($summaries))->orderBy('designation')->get() as $composition) {
|
||||
if ($this->catalog->shownVersion($composition) === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$title = (string) ($composition->display_title ?: $composition->designation);
|
||||
$teaser = (string) ($composition->teaser ?: FormattedText::plain($composition->summary));
|
||||
$pillarMap = $this->publishedPillars($composition->pillars);
|
||||
$pillars = array_values($pillarMap);
|
||||
$card = $this->card('c:'.$composition->id, 'programm', route('public.program', $composition), $title, $teaser, $summaries[$composition->id], 'Programm', null, $pillars, [], $this->image($composition));
|
||||
$card['pillar_ids'] = array_keys($pillarMap);
|
||||
$card['kind_id'] = $composition->editorial_content_kind_id !== null ? (int) $composition->editorial_content_kind_id : null;
|
||||
$card['holders'] = $summaries[$composition->id]['holders'] ?? [];
|
||||
$card['scopes'] = $summaries[$composition->id]['scopes'] ?? [];
|
||||
|
||||
if ($this->matches($term, $title.' '.$teaser.' '.FormattedText::plain($composition->summary).' '.$composition->search_terms.' '.implode(' ', $pillars))) {
|
||||
$cards[] = $card;
|
||||
}
|
||||
}
|
||||
|
||||
// Lizenzartikel mit kaufbarer Option.
|
||||
$articleSummaries = $this->products->articleSummaries();
|
||||
|
||||
foreach (LicenseArticle::query()->with(['editorialContentKind', 'pillars', 'currentRelease'])->whereIn('id', array_keys($articleSummaries))->whereNull('archived_at')->orderBy('code')->get() as $article) {
|
||||
$profile = $this->profiles->read($article, 'kachel');
|
||||
$title = $this->products->articleTitle($article);
|
||||
$teaser = (string) ($profile->value('teaser') ?: $profile->value('summary'));
|
||||
$kind = $article->editorialContentKind;
|
||||
$pillarMap = $this->publishedPillars($article->pillars);
|
||||
$pillars = array_values($pillarMap);
|
||||
$offerIds = array_map(fn ($offer): int => (int) $offer->id, $this->products->offersOfArticle($article));
|
||||
$card = $this->card(
|
||||
'a:'.$article->id, 'artikel', route('shop.article', $article), $title, $teaser, $articleSummaries[$article->id],
|
||||
(string) ($kind?->label ?? ''), $this->symbol($kind?->symbol), $pillars, $this->markers->visible($article, $offerIds), $this->image($article),
|
||||
);
|
||||
$card['pillar_ids'] = array_keys($pillarMap);
|
||||
$card['kind_id'] = $kind !== null ? (int) $kind->id : null;
|
||||
$card['since'] = $this->markers->firstOffered($offerIds)?->getTimestamp() ?? 0;
|
||||
$card['holders'] = $articleSummaries[$article->id]['holders'] ?? [];
|
||||
$card['scopes'] = $articleSummaries[$article->id]['scopes'] ?? [];
|
||||
|
||||
if ($this->matches($term, $title.' '.$teaser.' '.$profile->value('summary').' '.$profile->searchTerms.' '.($kind?->label ?? '').' '.implode(' ', $pillars))) {
|
||||
$cards[] = $card;
|
||||
}
|
||||
}
|
||||
|
||||
// Pakete mit eigener Produktseite.
|
||||
$bundleSummaries = $this->products->bundleSummaries();
|
||||
|
||||
foreach (Bundle::query()->whereIn('id', array_keys($bundleSummaries))->orderBy('name')->get() as $bundle) {
|
||||
$contents = $this->products->bundleContents($this->products->forBundle($bundle));
|
||||
$names = implode(', ', array_column($contents, 'title'));
|
||||
$teaser = 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : '');
|
||||
$card = $this->card('b:'.$bundle->id, 'paket', route('public.package', $bundle), (string) $bundle->name, $teaser, $bundleSummaries[$bundle->id], 'Paket', null, [], [], $this->image($bundle));
|
||||
$card['holders'] = $bundleSummaries[$bundle->id]['holders'] ?? [];
|
||||
$card['scopes'] = $bundleSummaries[$bundle->id]['scopes'] ?? [];
|
||||
|
||||
if ($this->matches($term, $bundle->name.' '.$names)) {
|
||||
$cards[] = $card;
|
||||
}
|
||||
}
|
||||
|
||||
return $cards;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter, Sortierung und Höchstzahl der Kacheln (Widget und Shopseite). Ohne Angabe bleibt die Reihenfolge der
|
||||
* Datenquelle.
|
||||
*
|
||||
* @param list<array<string, mixed>> $cards
|
||||
* @param array<string, mixed> $options
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function arrange(array $cards, array $options): array
|
||||
{
|
||||
$pillar = isset($options['pillar']) ? (int) $options['pillar'] : 0;
|
||||
$kind = isset($options['kind']) ? (int) $options['kind'] : 0;
|
||||
|
||||
if ($pillar > 0) {
|
||||
$cards = array_filter($cards, fn (array $card): bool => in_array($pillar, $card['pillar_ids'] ?? [], true));
|
||||
}
|
||||
|
||||
if ($kind > 0) {
|
||||
$cards = array_filter($cards, fn (array $card): bool => ($card['kind_id'] ?? null) === $kind);
|
||||
}
|
||||
|
||||
$holder = (string) ($options['holder'] ?? '');
|
||||
$scope = (string) ($options['scope'] ?? '');
|
||||
|
||||
if ($holder !== '') {
|
||||
$cards = array_filter($cards, fn (array $card): bool => in_array($holder, $card['holders'] ?? [], true));
|
||||
}
|
||||
|
||||
if ($scope !== '') {
|
||||
$cards = array_filter($cards, fn (array $card): bool => in_array($scope, $card['scopes'] ?? [], true));
|
||||
}
|
||||
|
||||
$cards = array_values($cards);
|
||||
|
||||
match ($options['sort'] ?? null) {
|
||||
'name' => usort($cards, fn (array $a, array $b): int => strcmp(mb_strtolower($a['title']), mb_strtolower($b['title']))),
|
||||
'neu' => usort($cards, fn (array $a, array $b): int => [$b['since'] ?? 0, mb_strtolower($a['title'])] <=> [$a['since'] ?? 0, mb_strtolower($b['title'])]),
|
||||
'preis' => usort($cards, fn (array $a, array $b): int => [$a['from_cents'], mb_strtolower($a['title'])] <=> [$b['from_cents'], mb_strtolower($b['title'])]),
|
||||
default => null,
|
||||
};
|
||||
|
||||
$limit = isset($options['limit']) ? (int) $options['limit'] : 0;
|
||||
|
||||
return $limit > 0 ? array_slice($cards, 0, $limit) : $cards;
|
||||
}
|
||||
|
||||
public const HOLDERS = ['person' => 'Privatpersonen', 'organisation' => 'Organisationen und Vereine'];
|
||||
|
||||
public const SCOPES = [LicenceScope::SINGLE => 'Einzellizenz', LicenceScope::MULTI => 'Mehrfachlizenz'];
|
||||
|
||||
/**
|
||||
* Die Auswahl, die ein Besucher bei diesen Kacheln hat: nur Werte, die es gibt, und nur Auswahlfelder mit mindestens
|
||||
* zwei Werten (sonst filtert nichts).
|
||||
*
|
||||
* @param list<array<string, mixed>> $cards
|
||||
* @return array{pillar: array<int, string>, kind: array<int, string>, holder: array<string, string>, scope: array<string, string>}
|
||||
*/
|
||||
public function facets(array $cards): array
|
||||
{
|
||||
$pillars = [];
|
||||
$kinds = [];
|
||||
$holders = [];
|
||||
$scopes = [];
|
||||
|
||||
foreach ($cards as $card) {
|
||||
foreach (array_values($card['pillar_ids'] ?? []) as $index => $id) {
|
||||
$pillars[(int) $id] = (string) ($card['pillars'][$index] ?? '');
|
||||
}
|
||||
|
||||
if (($card['kind_id'] ?? null) !== null && ($card['kind_label'] ?? '') !== '') {
|
||||
$kinds[(int) $card['kind_id']] = (string) $card['kind_label'];
|
||||
}
|
||||
|
||||
foreach ($card['holders'] ?? [] as $holder) {
|
||||
if (isset(self::HOLDERS[$holder])) {
|
||||
$holders[$holder] = self::HOLDERS[$holder];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($card['scopes'] ?? [] as $scope) {
|
||||
if (isset(self::SCOPES[$scope])) {
|
||||
$scopes[$scope] = self::SCOPES[$scope];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
asort($pillars);
|
||||
asort($kinds);
|
||||
|
||||
$facets = ['pillar' => $pillars, 'kind' => $kinds, 'holder' => $holders, 'scope' => $scopes];
|
||||
|
||||
return array_map(fn (array $values): array => count($values) >= 2 ? $values : [], $facets);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Produktliste für Shopseite und Widget: Suche, Auswahl des Besuchers (Säule, Materialart, Eignung,
|
||||
* Nutzerkreis), Reihenfolge, Ansicht und Seiten. Alles kommt aus dem Abfragetext und wird gegen feste Werte
|
||||
* geprüft; unbekannte Werte entfallen.
|
||||
*
|
||||
* @param array<string, mixed> $query Abfrage des Besuchers (suche, saeule, art, eignung, kreis, sort, ansicht, seite)
|
||||
* @param array<string, mixed> $fixed Vorgaben der Seite (pillar, kind, sort, limit, view, filters)
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function listing(array $query, array $fixed = []): array
|
||||
{
|
||||
$text = fn (string $key): string => isset($query[$key]) && (is_string($query[$key]) || is_int($query[$key])) ? trim((string) $query[$key]) : '';
|
||||
$filters = (bool) ($fixed['filters'] ?? true);
|
||||
$term = mb_substr($text('suche'), 0, 100);
|
||||
$base = $this->arrange($this->all($term), array_intersect_key($fixed, ['pillar' => 1, 'kind' => 1]));
|
||||
$facets = $filters ? $this->facets($base) : ['pillar' => [], 'kind' => [], 'holder' => [], 'scope' => []];
|
||||
$pick = function (string $key, string $facet) use ($text, $facets, $filters): int|string|null {
|
||||
$value = $text($key);
|
||||
|
||||
return $filters && $value !== '' && array_key_exists($value, $facets[$facet]) ? (ctype_digit($value) ? (int) $value : $value) : null;
|
||||
};
|
||||
$chosen = [
|
||||
'pillar' => $pick('saeule', 'pillar'),
|
||||
'kind' => $pick('art', 'kind'),
|
||||
'holder' => $pick('eignung', 'holder'),
|
||||
'scope' => $pick('kreis', 'scope'),
|
||||
];
|
||||
$sort = $filters && isset(self::SORTS[$text('sort')]) ? $text('sort') : ($fixed['sort'] ?? null);
|
||||
$view = $filters && in_array($text('ansicht'), ['kacheln', 'liste'], true) ? $text('ansicht') : (string) ($fixed['view'] ?? 'kacheln');
|
||||
$cards = $this->arrange($base, $chosen + ['sort' => $sort, 'limit' => $fixed['limit'] ?? null]);
|
||||
$perPage = max(1, (int) config('shop.per_page', 12));
|
||||
$pages = max(1, (int) ceil(count($cards) / $perPage));
|
||||
$page = $filters ? min($pages, max(1, (int) $text('seite'))) : 1;
|
||||
$shown = $filters ? array_slice($cards, ($page - 1) * $perPage, $perPage) : $cards;
|
||||
|
||||
return [
|
||||
'cards' => $shown,
|
||||
'total' => count($cards),
|
||||
'page' => $page,
|
||||
'pages' => $filters ? $pages : 1,
|
||||
'facets' => $facets,
|
||||
'chosen' => $chosen,
|
||||
'sort' => $sort,
|
||||
'view' => $view,
|
||||
'term' => $term,
|
||||
'filters' => $filters,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{from_cents: int, count: int} $summary
|
||||
* @param list<string> $pillars
|
||||
* @param list<array{key: string, label: string}> $markers
|
||||
* @param array{url: string, alt: string}|null $image
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function card(string $key, string $kind, string $url, string $title, string $teaser, array $summary, string $kindLabel, ?string $symbol, array $pillars, array $markers, ?array $image): array
|
||||
{
|
||||
return [
|
||||
'key' => $key,
|
||||
'kind' => $kind,
|
||||
'url' => $url,
|
||||
'title' => $title,
|
||||
'teaser' => $teaser,
|
||||
'from' => Money::format($summary['from_cents']),
|
||||
'from_cents' => (int) $summary['from_cents'],
|
||||
'count' => (int) $summary['count'],
|
||||
'image' => $image,
|
||||
'kind_label' => $kindLabel,
|
||||
'symbol' => $symbol,
|
||||
'pillars' => $pillars,
|
||||
'markers' => $markers,
|
||||
'pillar_ids' => [],
|
||||
'kind_id' => null,
|
||||
'since' => 0,
|
||||
'holders' => [],
|
||||
'scopes' => [],
|
||||
];
|
||||
}
|
||||
|
||||
private function matches(string $term, string $haystack): bool
|
||||
{
|
||||
return $term === '' || str_contains(mb_strtolower($haystack), $term);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nur veröffentlichte Säulen sind öffentlich (Säulenverwaltung).
|
||||
*
|
||||
* @param Collection<int, Pillar> $pillars
|
||||
* @return array<int, string> Kennung => Name
|
||||
*/
|
||||
private function publishedPillars(Collection $pillars): array
|
||||
{
|
||||
return $pillars->filter(fn (Pillar $pillar): bool => $pillar->published_at !== null)->mapWithKeys(fn (Pillar $pillar): array => [(int) $pillar->id => (string) $pillar->name])->all();
|
||||
}
|
||||
|
||||
/** Ein Symbol zeigt nur, was die Symbolbibliothek kennt (die Auswahl wird an der Materialart geprüft, hier noch einmal). */
|
||||
private function symbol(?string $key): ?string
|
||||
{
|
||||
return is_string($key) && $key !== '' && array_key_exists($key, SymbolCatalog::options()) ? $key : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string, alt: string}|null
|
||||
*/
|
||||
private function image(Model $subject): ?array
|
||||
{
|
||||
$presentation = $this->presentation->coverPresentation($subject);
|
||||
|
||||
return $presentation === null ? null : ['url' => $presentation->url, 'alt' => $presentation->alt];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Produktmarker „Neu“, „Aktualisiert“ und „Beliebt“ an einer Kachel (ADR-54).
|
||||
*
|
||||
* „Neu“ und „Aktualisiert“ folgen automatisch den Daten (erstes Angebot als Kauf, neuer Stand), jeweils für eine feste
|
||||
* Zahl Tage (`shop.marker_days`); die Redaktion kann sie auch fest an- oder abschalten. „Beliebt“ setzt die Redaktion
|
||||
* von Hand, solange es keine Verkaufszahlen gibt. Ein Marker trägt immer sein Wort, nie nur Farbe oder Symbol.
|
||||
*/
|
||||
class ShopMarkers
|
||||
{
|
||||
public const KEYS = ['neu' => 'Neu', 'aktualisiert' => 'Aktualisiert', 'beliebt' => 'Beliebt'];
|
||||
|
||||
/** Erlaubte Einstellungen je Marker; der erste Wert ist die Vorgabe. */
|
||||
public const CHOICES = [
|
||||
'neu' => ['auto' => 'Automatisch (zeitlich begrenzt nach dem ersten Angebot)', 'an' => 'Immer anzeigen', 'aus' => 'Nie anzeigen'],
|
||||
'aktualisiert' => ['auto' => 'Automatisch (zeitlich begrenzt nach einem neuen Stand)', 'an' => 'Immer anzeigen', 'aus' => 'Nie anzeigen'],
|
||||
'beliebt' => ['aus' => 'Nicht anzeigen', 'an' => 'Anzeigen'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Die Einstellungen des Artikels mit den Vorgaben für fehlende oder ungültige Werte.
|
||||
*
|
||||
* @return array{neu: string, aktualisiert: string, beliebt: string}
|
||||
*/
|
||||
public function settings(LicenseArticle $article): array
|
||||
{
|
||||
$stored = is_array($article->shop_markers) ? $article->shop_markers : [];
|
||||
$settings = [];
|
||||
|
||||
foreach (self::CHOICES as $key => $choices) {
|
||||
$value = $stored[$key] ?? null;
|
||||
$settings[$key] = is_string($value) && array_key_exists($value, $choices) ? $value : array_key_first($choices);
|
||||
}
|
||||
|
||||
return $settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $choices
|
||||
*/
|
||||
public function save(LicenseArticle $article, array $choices): void
|
||||
{
|
||||
$settings = [];
|
||||
|
||||
foreach (self::CHOICES as $key => $allowed) {
|
||||
$value = $choices[$key] ?? array_key_first($allowed);
|
||||
|
||||
if (! is_string($value) || ! array_key_exists($value, $allowed)) {
|
||||
throw new DomainRuleException('Der Marker „'.self::KEYS[$key].'“ hat eine unzulässige Einstellung.');
|
||||
}
|
||||
|
||||
$settings[$key] = $value;
|
||||
}
|
||||
|
||||
$article->shop_markers = $settings;
|
||||
$article->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die anzuzeigenden Marker in fester Reihenfolge.
|
||||
*
|
||||
* @param list<int> $offerIds Angebote dieses Artikels (Optionen)
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public function visible(LicenseArticle $article, array $offerIds, ?Carbon $now = null): array
|
||||
{
|
||||
$now ??= now();
|
||||
$settings = $this->settings($article);
|
||||
$days = max(1, (int) config('shop.marker_days', 30));
|
||||
$limit = $now->copy()->subDays($days);
|
||||
|
||||
$isNew = match ($settings['neu']) {
|
||||
'an' => true,
|
||||
'aus' => false,
|
||||
default => $this->firstOffered($offerIds)?->greaterThanOrEqualTo($limit) ?? false,
|
||||
};
|
||||
|
||||
$isUpdated = match ($settings['aktualisiert']) {
|
||||
'an' => true,
|
||||
'aus' => false,
|
||||
default => ! $isNew && $this->updatedAt($article)?->greaterThanOrEqualTo($limit) === true,
|
||||
};
|
||||
|
||||
$markers = [];
|
||||
|
||||
foreach (['neu' => $isNew, 'aktualisiert' => $isUpdated, 'beliebt' => $settings['beliebt'] === 'an'] as $key => $shown) {
|
||||
if ($shown) {
|
||||
$markers[] = ['key' => $key, 'label' => self::KEYS[$key]];
|
||||
}
|
||||
}
|
||||
|
||||
return $markers;
|
||||
}
|
||||
|
||||
/** Zeitpunkt der ersten Fassung eines Angebots als Kauf. */
|
||||
public function firstOffered(array $offerIds): ?Carbon
|
||||
{
|
||||
if ($offerIds === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$first = OfferVersion::query()->whereIn('offer_id', $offerIds)->where('grant_kind', 'kauf')->min('created_at');
|
||||
|
||||
return $first === null ? null : Carbon::parse($first);
|
||||
}
|
||||
|
||||
/** Zeitpunkt des neuesten Stands, sofern es nicht der erste ist. */
|
||||
private function updatedAt(LicenseArticle $article): ?Carbon
|
||||
{
|
||||
$release = $article->currentRelease;
|
||||
|
||||
return $release !== null && (int) $release->number > 1 && $release->created_at !== null ? Carbon::parse($release->created_at) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Wer die Kommunikationsverwaltung bedienen darf. Konfigurieren (Anliegen, Felder, Gruppen, Vorlagen, Einstiege):
|
||||
* Redaktion und Systemverwaltung. Anfragen lesen und bearbeiten sowie Einstellungen: Kundenbetreuung und
|
||||
* Systemverwaltung. Anfragen enthalten personenbezogene Daten und sind deshalb enger gefasst als die Konfiguration.
|
||||
*/
|
||||
final class CommunicationAccess
|
||||
{
|
||||
public static function user(): ?User
|
||||
{
|
||||
$user = Filament::auth()->user() ?? auth('staff')->user();
|
||||
|
||||
return $user instanceof User ? $user : null;
|
||||
}
|
||||
|
||||
public static function configure(?User $user = null): bool
|
||||
{
|
||||
$user ??= self::user();
|
||||
|
||||
return $user !== null && ($user->hasStaffRole(StaffRole::Redakteur) || $user->hasStaffRole(StaffRole::Systemverwalter));
|
||||
}
|
||||
|
||||
public static function inbox(?User $user = null): bool
|
||||
{
|
||||
$user ??= self::user();
|
||||
|
||||
return $user !== null && ($user->hasStaffRole(StaffRole::Kundenbetreuung) || $user->hasStaffRole(StaffRole::Systemverwalter));
|
||||
}
|
||||
|
||||
/** Anfragen endgültig löschen (Datenschutz): nur Systemverwaltung. */
|
||||
public static function erase(?User $user = null): bool
|
||||
{
|
||||
$user ??= self::user();
|
||||
|
||||
return $user !== null && $user->hasStaffRole(StaffRole::Systemverwalter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Allgemeine Kommunikationsvorgaben (eine Zeile): Empfänger der internen Benachrichtigung und Aufbewahrungsdauer.
|
||||
* Empfänger werden nur hier gepflegt; Besucher und das CMS können keine Empfänger angeben.
|
||||
*/
|
||||
class CommunicationSettings extends Model
|
||||
{
|
||||
protected $fillable = ['recipients', 'retention_months'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['recipients' => 'array', 'retention_months' => 'integer'];
|
||||
}
|
||||
|
||||
public static function current(): self
|
||||
{
|
||||
return self::query()->first() ?? self::query()->create(['recipients' => []]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function recipientList(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
(array) $this->recipients,
|
||||
fn (mixed $address): bool => is_string($address) && filter_var($address, FILTER_VALIDATE_EMAIL) !== false,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Beispielkonfiguration für die Kommunikationsverwaltung: Anliegen, Felder, Feldgruppen, drei Anfragevorlagen und
|
||||
* fünf Anfrage-Einstiege. Sie entsteht nur auf ausdrücklichen Wunsch („Beispielkonfiguration anlegen“) und nur in einer
|
||||
* noch leeren Verwaltung. Alles daraus lässt sich in der Verwaltung ändern; die Vorlagen sind gewöhnliche Entwürfe,
|
||||
* keine Sonderfälle im Code.
|
||||
*/
|
||||
final class ExampleConfiguration
|
||||
{
|
||||
public function __construct(private readonly Publisher $publisher) {}
|
||||
|
||||
public static function isEmpty(): bool
|
||||
{
|
||||
return ! InquiryIssue::query()->exists() && ! InquiryField::query()->exists() && ! InquiryTemplate::query()->exists();
|
||||
}
|
||||
|
||||
public function install(?User $by = null): void
|
||||
{
|
||||
if (! self::isEmpty()) {
|
||||
throw new RuntimeException('Die Kommunikationsverwaltung enthält bereits Konfiguration; die Beispiele werden nicht daneben angelegt.');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($by): void {
|
||||
$this->issues();
|
||||
$this->fields();
|
||||
$this->groups();
|
||||
$templates = $this->templates();
|
||||
$this->entries($templates, $by);
|
||||
});
|
||||
}
|
||||
|
||||
private function issues(): void
|
||||
{
|
||||
$tree = [
|
||||
['allgemein', 'Allgemeine Informationen', 'Allgemeine Fragen zu Lara & Felix, dem Trainingskonzept oder Sonstiges.', []],
|
||||
['kurse', 'Kurse & Workshops', 'Präsenzkurse und individuelle Kursvorhaben.', [
|
||||
['kursinfo', 'Allgemeine Kursinformation', 'Ich möchte mich zunächst informieren.'],
|
||||
['kursvorhaben', 'Konkretes Kursvorhaben', 'Ich plane ein konkretes Kursvorhaben.'],
|
||||
]],
|
||||
['materialien', 'Programme & Materialien', 'Trainingsprogramme, Module, Filmgeschichten, Übungen, Materialien und Nutzungsrechte.', []],
|
||||
['kooperation', 'Kooperationen', 'Anfragen möglicher Trainer, Institutionen und anderer Kooperationspartner.', []],
|
||||
];
|
||||
|
||||
foreach ($tree as $i => [$key, $label, $description, $children]) {
|
||||
$parent = InquiryIssue::query()->create(['key' => $key, 'label' => $label, 'description' => $description, 'sort_order' => ($i + 1) * 10]);
|
||||
|
||||
foreach ($children as $j => [$childKey, $childLabel, $childDescription]) {
|
||||
InquiryIssue::query()->create(['parent_id' => $parent->id, 'key' => $childKey, 'label' => $childLabel, 'description' => $childDescription, 'sort_order' => ($j + 1) * 10]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function fields(): void
|
||||
{
|
||||
$text = fn (string $key, string $name, string $label, ?string $purpose = null, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'text', 'purpose' => $purpose, 'help' => $help];
|
||||
$select = fn (string $key, string $name, string $label, array $options, ?string $help = null): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'select', 'help' => $help, 'options' => array_map(fn (string $k, string $l): array => ['key' => $k, 'label' => $l], array_keys($options), $options)];
|
||||
$yesNo = fn (string $key, string $name, string $label): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'boolean'];
|
||||
$number = fn (string $key, string $name, string $label, int $min = 1, int $max = 1000): array => ['key' => $key, 'name' => $name, 'label' => $label, 'type' => 'number', 'settings' => ['min' => $min, 'max' => $max]];
|
||||
|
||||
$fields = [
|
||||
$text('name', 'Name (ein Feld)', 'Ihr Name', 'name'),
|
||||
['key' => 'email', 'name' => 'E-Mail-Adresse', 'label' => 'Ihre E-Mail-Adresse', 'type' => 'email', 'purpose' => 'email'],
|
||||
['key' => 'nachricht', 'name' => 'Nachricht', 'label' => 'Ihre Nachricht', 'type' => 'textarea', 'purpose' => 'nachricht', 'help' => 'Bitte nennen Sie hier keine Namen oder persönlichen Daten einzelner Kinder.'],
|
||||
$text('vorname', 'Vorname', 'Vorname', 'vorname'),
|
||||
$text('nachname', 'Nachname', 'Nachname', 'nachname'),
|
||||
['key' => 'telefon', 'name' => 'Telefonnummer', 'label' => 'Telefonnummer (optional)', 'type' => 'phone', 'purpose' => 'telefon'],
|
||||
$text('funktion', 'Funktion / Rolle', 'Ihre Funktion oder Rolle', null, 'Zum Beispiel Schulleitung, Lehrkraft, Vereinsvorstand.'),
|
||||
$text('region', 'Region / Ort', 'Region oder Ort', null, 'Wo würde das Angebot stattfinden? Die Region genügt.'),
|
||||
$text('einrichtung_name', 'Name der Einrichtung', 'Name der Schule oder Einrichtung', 'organisation'),
|
||||
$select('einrichtungstyp', 'Einrichtungstyp', 'Einrichtungstyp', [
|
||||
'grundschule' => 'Grundschule', 'weiterfuehrend' => 'Weiterführende Schule', 'verein' => 'Verein',
|
||||
'jugendeinrichtung' => 'Kinder- oder Jugendeinrichtung', 'bildungstraeger' => 'Sonstiger Bildungsträger', 'sonstiges' => 'Sonstiges',
|
||||
]),
|
||||
$select('schulart', 'Schulart', 'Schulart', ['gs' => 'Grundschule', 'foerder' => 'Förderschule', 'gemeinschaft' => 'Gemeinschaftsschule', 'sek' => 'Sekundarschule', 'gym' => 'Gymnasium', 'andere' => 'Andere']),
|
||||
$text('einrichtung_strasse', 'Straße und Hausnummer (Einrichtung)', 'Straße und Hausnummer'),
|
||||
$text('einrichtung_plz', 'Postleitzahl (Einrichtung)', 'Postleitzahl'),
|
||||
$text('einrichtung_ort', 'Ort (Einrichtung)', 'Ort'),
|
||||
$yesNo('traeger_abweichend', 'Träger weicht von der Einrichtung ab', 'Weicht der Bildungsträger bzw. Auftraggeber von der Einrichtung ab?'),
|
||||
$text('traeger_name', 'Name des Trägers', 'Name des Trägers oder Auftraggebers'),
|
||||
$select('traeger_art', 'Art des Trägers', 'Art des Trägers', ['kommune' => 'Kommune oder Land', 'freier' => 'Freier Träger', 'verein' => 'Verein', 'sonstiges' => 'Sonstiges']),
|
||||
$text('traeger_ansprechpartner', 'Ansprechpartner beim Träger', 'Ansprechpartner beim Träger (optional)'),
|
||||
$yesNo('ort_abweichend', 'Abweichender Durchführungsort', 'Findet der Kurs an einem anderen Ort statt als in der Einrichtung?'),
|
||||
$text('ort_strasse', 'Straße und Hausnummer (Durchführungsort)', 'Straße und Hausnummer des Durchführungsorts'),
|
||||
$text('ort_plz', 'Postleitzahl (Durchführungsort)', 'Postleitzahl des Durchführungsorts'),
|
||||
$text('ort_ort', 'Ort (Durchführungsort)', 'Ort des Durchführungsorts'),
|
||||
['key' => 'ort_hinweise', 'name' => 'Hinweise zum Durchführungsort', 'label' => 'Organisatorische Hinweise zum Ort (optional)', 'type' => 'textarea'],
|
||||
$text('alter', 'Alter / Altersbereich', 'Alter oder Altersbereich der Kinder', null, 'Zum Beispiel 8 bis 10 Jahre.'),
|
||||
$text('klassenstufe', 'Klassenstufe', 'Klassenstufe (falls zutreffend)'),
|
||||
$number('anzahl_kinder', 'Anzahl der Kinder', 'Anzahl der Kinder insgesamt'),
|
||||
$number('anzahl_gruppen', 'Anzahl der Gruppen oder Klassen', 'Anzahl der Gruppen oder Klassen', 1, 100),
|
||||
['key' => 'besonderheiten', 'name' => 'Organisatorische Anforderungen', 'label' => 'Besondere organisatorische Anforderungen (optional)', 'type' => 'textarea', 'help' => 'Bitte keine Angaben zu einzelnen Kindern.'],
|
||||
$select('kursformat', 'Kursformat', 'Welches Format interessiert Sie?', [
|
||||
'kompakt' => 'Kompakttraining', 'vertiefung' => 'Vertiefungsprogramm', 'schul_ag' => 'Schul-AG', 'unentschieden' => 'Noch unentschieden',
|
||||
], 'Kompakttraining: kurzes, individuell abgestimmtes Schultraining mit wenigen Terminen. Vertiefungsprogramm: mehrere aufeinander aufbauende Einheiten über einen längeren Zeitraum. Schul-AG: regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Die Formate sind Arbeitsvorschläge; Termine, Preise und Umfang werden erst im Gespräch festgelegt.'),
|
||||
['key' => 'zeitraum', 'name' => 'Geplanter Zeitraum', 'label' => 'Geplanter Zeitraum', 'type' => 'period'],
|
||||
$text('zeitwuensche', 'Zeitwünsche', 'Zeitwünsche (optional)', null, 'Zum Beispiel Wochentage oder Tageszeiten.'),
|
||||
$number('einheiten', 'Anzahl geplanter Einheiten', 'Anzahl geplanter Einheiten (optional)', 1, 200),
|
||||
$select('haeufigkeit', 'Gewünschte Häufigkeit', 'Gewünschte Häufigkeit', ['woechentlich' => 'Einmal pro Woche', 'zweiwoechentlich' => 'Alle zwei Wochen', 'absprache' => 'Nach Absprache']),
|
||||
$select('laufzeit', 'Laufzeit der Schul-AG', 'Gewünschte Laufzeit', ['halbjahr' => 'Ein Schulhalbjahr', 'schuljahr' => 'Ein Schuljahr', 'absprache' => 'Nach Absprache']),
|
||||
['key' => 'kurs_hinweise', 'name' => 'Ergänzende Informationen (Kurs)', 'label' => 'Ergänzende Informationen (optional)', 'type' => 'textarea'],
|
||||
$select('material_interesse', 'Interesse an Materialien', 'Wofür interessieren Sie sich?', [
|
||||
'programme' => 'Trainingsprogramme', 'module' => 'Module', 'filmgeschichten' => 'Filmgeschichten', 'uebungen' => 'Übungen',
|
||||
'materialien' => 'Materialien', 'rechte' => 'Nutzungsrechte',
|
||||
]),
|
||||
$select('koop_art', 'Art der Kooperation', 'Wer sind Sie?', ['trainer' => 'Trainerin oder Trainer', 'institution' => 'Institution', 'sonstiges' => 'Sonstiges']),
|
||||
$text('koop_organisation', 'Organisation (Kooperation)', 'Organisation (optional)', 'organisation'),
|
||||
];
|
||||
|
||||
foreach ($fields as $i => $field) {
|
||||
InquiryField::query()->create([
|
||||
'key' => $field['key'],
|
||||
'name' => $field['name'],
|
||||
'label' => $field['label'],
|
||||
'help' => $field['help'] ?? null,
|
||||
'type' => $field['type'],
|
||||
'options' => $field['options'] ?? null,
|
||||
'settings' => $field['settings'] ?? null,
|
||||
'purpose' => $field['purpose'] ?? null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private function groups(): void
|
||||
{
|
||||
$groups = [
|
||||
['kontakt_einfach', 'Kontakt (einfach)', 'Ihre Kontaktdaten', [['name', true], ['email', true]]],
|
||||
['ansprechpartner', 'Ansprechpartner', 'Ihre Kontaktdaten', [['vorname', true], ['nachname', true], ['email', true], ['telefon', false], ['funktion', false]]],
|
||||
['einrichtung', 'Einrichtung', 'Ihre Einrichtung', [['einrichtung_name', true], ['einrichtungstyp', true], ['schulart', false], ['einrichtung_strasse', true], ['einrichtung_plz', true], ['einrichtung_ort', true]]],
|
||||
['traeger_frage', 'Träger', 'Bildungsträger oder Auftraggeber', [['traeger_abweichend', true]]],
|
||||
['traeger_angaben', 'Trägerangaben', 'Angaben zum Träger', [['traeger_name', true], ['traeger_art', false], ['traeger_ansprechpartner', false]]],
|
||||
['ort_frage', 'Durchführungsort', 'Wo soll der Kurs stattfinden?', [['ort_abweichend', true]]],
|
||||
['ort_angaben', 'Abweichender Durchführungsort', 'Adresse des Durchführungsorts', [['ort_strasse', true], ['ort_plz', true], ['ort_ort', true], ['ort_hinweise', false]]],
|
||||
['kindergruppe', 'Kindergruppe', 'Die Kindergruppe', [['alter', true], ['klassenstufe', false], ['anzahl_kinder', true], ['anzahl_gruppen', false], ['besonderheiten', false]]],
|
||||
['kursplanung', 'Kursplanung', 'Ihre Planung', [['zeitraum', false], ['zeitwuensche', false], ['einheiten', false], ['kurs_hinweise', false]]],
|
||||
['schul_ag', 'Schul-AG', 'Zur Schul-AG', [['laufzeit', true], ['haeufigkeit', true]]],
|
||||
['material', 'Programm- und Materialbezug', 'Ihr Interesse', [['material_interesse', true]]],
|
||||
['kooperation', 'Kooperation', 'Zu Ihrer Kooperationsanfrage', [['koop_art', true], ['koop_organisation', false]]],
|
||||
];
|
||||
|
||||
foreach ($groups as $i => [$key, $name, $label, $items]) {
|
||||
InquiryFieldGroup::query()->create([
|
||||
'key' => $key,
|
||||
'name' => $name,
|
||||
'label' => $label,
|
||||
'items' => array_map(fn (array $row): array => ['field' => $row[0], 'required' => $row[1]], $items),
|
||||
'sort_order' => ($i + 1) * 10,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, InquiryTemplate>
|
||||
*/
|
||||
private function templates(): array
|
||||
{
|
||||
$cond = fn (string $source, string $op, string ...$values): array => ['source' => $source, 'op' => $op, 'values' => $values];
|
||||
$rule = fn (string $effect, string $target, array $conditions, ?string $value = null): array => ['effect' => $effect, 'target' => $target, 'match' => 'all', 'conditions' => $conditions, 'value' => $value];
|
||||
$group = fn (string $key): array => ['kind' => 'group', 'group' => $key];
|
||||
|
||||
$general = [
|
||||
'texts' => ['heading' => 'Schreiben Sie uns', 'intro' => 'Wir freuen uns über Ihre Frage.', 'success_text' => 'Danke, wir melden uns in der Regel innerhalb weniger Werktage.'],
|
||||
'issues' => ['allgemein'],
|
||||
'steps' => [['key' => 'sallg1', 'title' => 'Ihre Nachricht', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
|
||||
'rules' => [],
|
||||
];
|
||||
|
||||
$courses = [
|
||||
'texts' => [
|
||||
'heading' => 'Kursanfrage',
|
||||
'intro' => 'Beschreiben Sie uns, was Sie planen. Alle Angaben sind unverbindlich; Termine, Preise und Umfang besprechen wir gemeinsam.',
|
||||
'privacy_note' => 'Wir verwenden Ihre Angaben ausschließlich, um Ihre Anfrage zu beantworten. Bitte nennen Sie keine Namen oder persönlichen Daten einzelner Kinder.',
|
||||
'success_text' => 'Wir haben Ihre Kursanfrage erhalten und melden uns bei Ihnen. Eine Buchung ist damit noch nicht verbunden.',
|
||||
],
|
||||
'issues' => ['kurse'],
|
||||
'steps' => [
|
||||
['key' => 'skurs1', 'title' => 'Ihr Anliegen', 'intro' => null, 'items' => [['kind' => 'issue'], ['kind' => 'field', 'field' => 'kursformat', 'required' => false]]],
|
||||
['key' => 'skurs2', 'title' => 'Ihr Vorhaben', 'intro' => 'Einrichtung, Träger, Standort, Zielgruppe und Planung.', 'items' => [
|
||||
$group('einrichtung'), $group('traeger_frage'), $group('traeger_angaben'), $group('ort_frage'), $group('ort_angaben'),
|
||||
$group('kindergruppe'), $group('schul_ag'), $group('kursplanung'),
|
||||
]],
|
||||
['key' => 'skurs3', 'title' => 'Kontakt und Zusammenfassung', 'intro' => null, 'items' => [
|
||||
['kind' => 'field', 'field' => 'region', 'required' => true], $group('ansprechpartner'), ['kind' => 'field', 'field' => 'nachricht', 'required' => false],
|
||||
]],
|
||||
],
|
||||
'rules' => [
|
||||
$rule('show', 'field:kursformat', [$cond('anliegen', 'eq', 'kurse')]),
|
||||
$rule('skip', 'step:skurs2', [$cond('unteranliegen', 'eq', 'kursinfo')]),
|
||||
$rule('show', 'group:traeger_angaben', [$cond('traeger_abweichend', 'eq', 'ja')]),
|
||||
$rule('show', 'group:ort_angaben', [$cond('ort_abweichend', 'eq', 'ja')]),
|
||||
$rule('show', 'group:schul_ag', [$cond('kursformat', 'eq', 'schul_ag')]),
|
||||
$rule('show', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]),
|
||||
$rule('require', 'field:schulart', [$cond('einrichtungstyp', 'in', 'grundschule', 'weiterfuehrend')]),
|
||||
$rule('show', 'field:region', [$cond('unteranliegen', 'eq', 'kursinfo')]),
|
||||
],
|
||||
];
|
||||
|
||||
$materials = [
|
||||
'texts' => ['heading' => 'Frage zu Programmen und Materialien', 'intro' => 'Zu Trainingsprogrammen, Modulen, Filmgeschichten, Übungen, Materialien und Nutzungsrechten.'],
|
||||
'issues' => ['materialien'],
|
||||
'steps' => [['key' => 'smat1', 'title' => 'Ihre Frage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('material'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
|
||||
'rules' => [],
|
||||
];
|
||||
|
||||
$cooperation = [
|
||||
'texts' => ['heading' => 'Kooperation anfragen', 'intro' => 'Für Trainerinnen, Trainer, Institutionen und weitere Partner.'],
|
||||
'issues' => ['kooperation'],
|
||||
'steps' => [['key' => 'skoop1', 'title' => 'Ihre Anfrage', 'intro' => null, 'items' => [['kind' => 'issue'], $group('kooperation'), $group('kontakt_einfach'), ['kind' => 'field', 'field' => 'nachricht', 'required' => true]]]],
|
||||
'rules' => [],
|
||||
];
|
||||
|
||||
$templates = [];
|
||||
|
||||
foreach ([
|
||||
['allgemein', 'Allgemeine Kontaktaufnahme', $general],
|
||||
['kursanfragen', 'Kursanfragen', $courses],
|
||||
['materialanfragen', 'Materialanfragen', $materials],
|
||||
['kooperationsanfragen', 'Kooperationsanfragen', $cooperation],
|
||||
] as [$key, $name, $draft]) {
|
||||
$templates[$key] = InquiryTemplate::query()->create(['key' => $key, 'name' => $name, 'draft' => $draft]);
|
||||
}
|
||||
|
||||
return $templates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, InquiryTemplate> $templates
|
||||
*/
|
||||
private function entries(array $templates, ?User $by): void
|
||||
{
|
||||
foreach ($templates as $template) {
|
||||
$result = $this->publisher->publishTemplate($template, $by, 'Beispielkonfiguration');
|
||||
$template->refresh();
|
||||
}
|
||||
|
||||
$entries = [
|
||||
['allgemeiner_kontakt', 'Allgemeiner Kontakt', 'allgemein', ['mode' => 'compact', 'allowed_issues' => ['allgemein']]],
|
||||
['kurse_workshops', 'Kurse & Workshops', 'kursanfragen', [
|
||||
'mode' => 'wizard', 'allowed_issues' => ['kurse'],
|
||||
'texts' => ['heading' => 'Kurse & Workshops anfragen'],
|
||||
]],
|
||||
['schul_ag', 'Schul-AG', 'kursanfragen', [
|
||||
'mode' => 'wizard', 'allowed_issues' => ['kurse'],
|
||||
'defaults' => ['anliegen' => 'kurse', 'unteranliegen' => 'kursvorhaben', 'kursformat' => 'schul_ag'],
|
||||
'texts' => ['heading' => 'Schul-AG anfragen', 'intro' => 'Regelmäßiges Training, zum Beispiel über ein Schulhalbjahr. Alle Angaben sind unverbindlich.'],
|
||||
]],
|
||||
['programme_materialien', 'Programme & Materialien', 'materialanfragen', ['mode' => 'compact', 'allowed_issues' => ['materialien']]],
|
||||
['kooperation', 'Kooperation', 'kooperationsanfragen', ['mode' => 'compact', 'allowed_issues' => ['kooperation']]],
|
||||
];
|
||||
|
||||
foreach ($entries as [$key, $name, $template, $config]) {
|
||||
$entry = InquiryEntry::query()->create([
|
||||
'key' => $key,
|
||||
'name' => $name,
|
||||
'template_id' => $templates[$template]->id,
|
||||
'config' => array_merge(InquiryEntry::emptyConfig(), $config),
|
||||
]);
|
||||
|
||||
$this->publisher->publishEntry($entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Fachliche Verwendung eines Feldes in der Anfrageübersicht. Ohne Verwendung erscheint die Antwort nur in der Liste
|
||||
* der Antworten.
|
||||
*/
|
||||
enum FieldPurpose: string
|
||||
{
|
||||
case FirstName = 'vorname';
|
||||
case LastName = 'nachname';
|
||||
case FullName = 'name';
|
||||
case Email = 'email';
|
||||
case Phone = 'telefon';
|
||||
case Organisation = 'organisation';
|
||||
case Message = 'nachricht';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::FirstName => 'Vorname des Ansprechpartners',
|
||||
self::LastName => 'Nachname des Ansprechpartners',
|
||||
self::FullName => 'Name des Ansprechpartners',
|
||||
self::Email => 'E-Mail-Adresse für Rückfragen',
|
||||
self::Phone => 'Telefonnummer',
|
||||
self::Organisation => 'Organisation oder Einrichtung',
|
||||
self::Message => 'Nachricht',
|
||||
};
|
||||
}
|
||||
|
||||
/** @return list<FieldType> */
|
||||
public function types(): array
|
||||
{
|
||||
return match ($this) {
|
||||
self::Email => [FieldType::Email],
|
||||
self::Phone => [FieldType::Phone],
|
||||
self::Message => [FieldType::Textarea, FieldType::Text],
|
||||
default => [FieldType::Text],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @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,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Unterstützte Feldtypen des Feldkatalogs (ADR-60). Ein neuer technischer Typ ist eine kontrollierte
|
||||
* Softwareerweiterung: hier ergänzen, in {@see FieldValue} prüfen und in resources/js/inquiry-form.js darstellen.
|
||||
*/
|
||||
enum FieldType: string
|
||||
{
|
||||
case Text = 'text';
|
||||
case Textarea = 'textarea';
|
||||
case Email = 'email';
|
||||
case Phone = 'phone';
|
||||
case Number = 'number';
|
||||
case Select = 'select';
|
||||
case Multiselect = 'multiselect';
|
||||
case Boolean = 'boolean';
|
||||
case Date = 'date';
|
||||
case Period = 'period';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Text => 'Text, einzeilig',
|
||||
self::Textarea => 'Text, mehrzeilig',
|
||||
self::Email => 'E-Mail-Adresse',
|
||||
self::Phone => 'Telefonnummer',
|
||||
self::Number => 'Zahl',
|
||||
self::Select => 'Einfachauswahl',
|
||||
self::Multiselect => 'Mehrfachauswahl',
|
||||
self::Boolean => 'Ja/Nein',
|
||||
self::Date => 'Datum',
|
||||
self::Period => 'Zeitraum (von – bis)',
|
||||
};
|
||||
}
|
||||
|
||||
public function hasOptions(): bool
|
||||
{
|
||||
return in_array($this, [self::Select, self::Multiselect], true);
|
||||
}
|
||||
|
||||
/** Ob Bedingungen auf den Wert dieses Feldes aufbauen dürfen. */
|
||||
public function canControl(): bool
|
||||
{
|
||||
return $this === self::Select || $this === self::Multiselect || $this === self::Boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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,286 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Prüft und bereinigt einen einzelnen Antwortwert nach dem Feldtyp. Die einzige Stelle, an der Werte eines Besuchers
|
||||
* in gespeicherte Werte übergehen. Eingabe ist die Feldbeschreibung aus der Fassung (siehe InquiryField::snapshot()).
|
||||
*/
|
||||
final class FieldValue
|
||||
{
|
||||
public const TEXT_MAX = 200;
|
||||
|
||||
public const TEXTAREA_MAX = 4000;
|
||||
|
||||
/**
|
||||
* Rohwert für Bedingungen: ungültige oder fehlende Werte zählen als nicht gesetzt (null).
|
||||
*
|
||||
* @param array<string, mixed> $field
|
||||
*/
|
||||
public static function forRules(array $field, mixed $raw): string|array|null
|
||||
{
|
||||
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
|
||||
|
||||
return match ($type) {
|
||||
FieldType::Select => self::option($field, $raw),
|
||||
FieldType::Multiselect => self::options($field, $raw) ?: null,
|
||||
FieldType::Boolean => self::yesNo($raw),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $field
|
||||
* @return array{0: mixed, 1: ?string} bereinigter Wert (null = nicht beantwortet) und Fehlermeldung
|
||||
*/
|
||||
public static function check(array $field, mixed $raw, bool $required): array
|
||||
{
|
||||
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
|
||||
$label = (string) ($field['label'] ?? 'Dieses Feld');
|
||||
$settings = (array) ($field['settings'] ?? []);
|
||||
$missing = 'Bitte füllen Sie dieses Feld aus.';
|
||||
|
||||
if ($type === null) {
|
||||
return [null, 'Dieses Feld ist nicht verfügbar.'];
|
||||
}
|
||||
|
||||
if (is_string($raw)) {
|
||||
$raw = str_replace(["\r\n", "\r"], "\n", $raw);
|
||||
$raw = preg_replace('/[^\P{C}\n\t]/u', '', $raw) ?? '';
|
||||
$raw = trim($raw);
|
||||
}
|
||||
|
||||
$empty = $raw === null || $raw === '' || $raw === [] || (is_array($raw) && $type === FieldType::Period && trim((string) ($raw['von'] ?? '')) === '' && trim((string) ($raw['bis'] ?? '')) === '');
|
||||
|
||||
if ($empty) {
|
||||
return [null, $required ? $missing : null];
|
||||
}
|
||||
|
||||
switch ($type) {
|
||||
case FieldType::Text:
|
||||
case FieldType::Textarea:
|
||||
if (! is_string($raw)) {
|
||||
return [null, 'Bitte geben Sie einen Text ein.'];
|
||||
}
|
||||
|
||||
$max = (int) ($settings['max_length'] ?? ($type === FieldType::Text ? self::TEXT_MAX : self::TEXTAREA_MAX));
|
||||
$max = max(1, min($max, $type === FieldType::Text ? 500 : 8000));
|
||||
|
||||
if ($type === FieldType::Text) {
|
||||
$raw = preg_replace('/\s*\n\s*/', ' ', $raw) ?? $raw;
|
||||
}
|
||||
|
||||
if (mb_strlen($raw) > $max) {
|
||||
return [null, "Bitte höchstens $max Zeichen."];
|
||||
}
|
||||
|
||||
return [$raw, null];
|
||||
|
||||
case FieldType::Email:
|
||||
if (! is_string($raw) || mb_strlen($raw) > 200 || filter_var($raw, FILTER_VALIDATE_EMAIL) === false) {
|
||||
return [null, 'Bitte geben Sie eine gültige E-Mail-Adresse ein.'];
|
||||
}
|
||||
|
||||
return [$raw, null];
|
||||
|
||||
case FieldType::Phone:
|
||||
if (! is_string($raw) || preg_match('/^\+?[0-9][0-9 ()\/.\-]{3,28}[0-9]$/', $raw) !== 1) {
|
||||
return [null, 'Bitte geben Sie eine gültige Telefonnummer ein.'];
|
||||
}
|
||||
|
||||
return [$raw, null];
|
||||
|
||||
case FieldType::Number:
|
||||
if (is_string($raw)) {
|
||||
$raw = str_replace(',', '.', $raw);
|
||||
}
|
||||
|
||||
if (! is_numeric($raw) || is_nan((float) $raw) || is_infinite((float) $raw)) {
|
||||
return [null, 'Bitte geben Sie eine Zahl ein.'];
|
||||
}
|
||||
|
||||
$number = $raw + 0;
|
||||
|
||||
if (isset($settings['min']) && $settings['min'] !== '' && $number < (float) $settings['min']) {
|
||||
return [null, 'Bitte mindestens '.self::plain($settings['min']).'.'];
|
||||
}
|
||||
|
||||
if (isset($settings['max']) && $settings['max'] !== '' && $number > (float) $settings['max']) {
|
||||
return [null, 'Bitte höchstens '.self::plain($settings['max']).'.'];
|
||||
}
|
||||
|
||||
return [$number, null];
|
||||
|
||||
case FieldType::Select:
|
||||
$option = self::option($field, $raw);
|
||||
|
||||
return $option === null ? [null, 'Bitte wählen Sie einen der angebotenen Werte.'] : [$option, null];
|
||||
|
||||
case FieldType::Multiselect:
|
||||
if (! is_array($raw)) {
|
||||
return [null, 'Bitte wählen Sie aus den angebotenen Werten.'];
|
||||
}
|
||||
|
||||
$values = self::options($field, $raw);
|
||||
|
||||
if ($values === [] || count($values) !== count(array_unique(array_filter($raw, 'is_string')))) {
|
||||
return [null, 'Bitte wählen Sie aus den angebotenen Werten.'];
|
||||
}
|
||||
|
||||
return [$values, null];
|
||||
|
||||
case FieldType::Boolean:
|
||||
$answer = self::yesNo($raw);
|
||||
|
||||
return $answer === null ? [null, 'Bitte antworten Sie mit Ja oder Nein.'] : [$answer, null];
|
||||
|
||||
case FieldType::Date:
|
||||
$date = self::date($raw);
|
||||
|
||||
return $date === null ? [null, 'Bitte geben Sie ein gültiges Datum ein.'] : [$date, null];
|
||||
|
||||
case FieldType::Period:
|
||||
if (! is_array($raw)) {
|
||||
return [null, 'Bitte geben Sie einen Zeitraum an.'];
|
||||
}
|
||||
|
||||
$from = trim((string) ($raw['von'] ?? '')) === '' ? null : self::date($raw['von']);
|
||||
$to = trim((string) ($raw['bis'] ?? '')) === '' ? null : self::date($raw['bis']);
|
||||
|
||||
if ((trim((string) ($raw['von'] ?? '')) !== '' && $from === null) || (trim((string) ($raw['bis'] ?? '')) !== '' && $to === null)) {
|
||||
return [null, 'Bitte geben Sie gültige Daten ein.'];
|
||||
}
|
||||
|
||||
if ($required && ($from === null || $to === null)) {
|
||||
return [null, 'Bitte geben Sie Beginn und Ende an.'];
|
||||
}
|
||||
|
||||
if ($from !== null && $to !== null && $to < $from) {
|
||||
return [null, 'Das Ende liegt vor dem Beginn.'];
|
||||
}
|
||||
|
||||
return [['von' => $from, 'bis' => $to], null];
|
||||
}
|
||||
|
||||
return [null, "$label ist nicht verfügbar."];
|
||||
}
|
||||
|
||||
/**
|
||||
* Lesbare Darstellung eines bereinigten Wertes, wie sie in der Anfrage gespeichert wird.
|
||||
*
|
||||
* @param array<string, mixed> $field
|
||||
*/
|
||||
public static function display(array $field, mixed $value): string
|
||||
{
|
||||
$type = FieldType::tryFrom((string) ($field['type'] ?? ''));
|
||||
$labels = [];
|
||||
|
||||
foreach ((array) ($field['options'] ?? []) as $option) {
|
||||
$labels[$option['key']] = $option['label'];
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
FieldType::Select => (string) ($labels[$value] ?? $value),
|
||||
FieldType::Multiselect => implode(', ', array_map(fn (string $key): string => (string) ($labels[$key] ?? $key), (array) $value)),
|
||||
FieldType::Boolean => $value === 'ja' ? 'Ja' : 'Nein',
|
||||
FieldType::Date => Carbon::parse((string) $value)->format('d.m.Y'),
|
||||
FieldType::Period => self::periodText((array) $value),
|
||||
default => (string) $value,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $field
|
||||
*/
|
||||
private static function option(array $field, mixed $raw): ?string
|
||||
{
|
||||
if (! is_string($raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ((array) ($field['options'] ?? []) as $option) {
|
||||
if (($option['key'] ?? null) === $raw) {
|
||||
return $raw;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $field
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function options(array $field, mixed $raw): array
|
||||
{
|
||||
if (! is_array($raw)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values = [];
|
||||
|
||||
foreach ($raw as $item) {
|
||||
$option = self::option($field, $item);
|
||||
|
||||
if ($option === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$values[$option] = $option;
|
||||
}
|
||||
|
||||
return array_values($values);
|
||||
}
|
||||
|
||||
private static function yesNo(mixed $raw): ?string
|
||||
{
|
||||
return match (true) {
|
||||
$raw === true, $raw === 'ja', $raw === '1', $raw === 'true', $raw === 1 => 'ja',
|
||||
$raw === false, $raw === 'nein', $raw === '0', $raw === 'false', $raw === 0 => 'nein',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static function date(mixed $raw): ?string
|
||||
{
|
||||
if (! is_string($raw) || preg_match('/^\d{4}-\d{2}-\d{2}$/', $raw) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$date = Carbon::createFromFormat('!Y-m-d', $raw);
|
||||
} catch (Throwable) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($date === false || $date->format('Y-m-d') !== $raw || $date->year < 1900 || $date->year > 2200) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $value
|
||||
*/
|
||||
private static function periodText(array $value): string
|
||||
{
|
||||
$from = isset($value['von']) ? Carbon::parse($value['von'])->format('d.m.Y') : null;
|
||||
$to = isset($value['bis']) ? Carbon::parse($value['bis'])->format('d.m.Y') : null;
|
||||
|
||||
return match (true) {
|
||||
$from !== null && $to !== null => "$from bis $to",
|
||||
$from !== null => "ab $from",
|
||||
$to !== null => "bis $to",
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
private static function plain(mixed $number): string
|
||||
{
|
||||
return rtrim(rtrim(number_format((float) $number, 4, ',', ''), '0'), ',');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Die einzige Auswertung der Bedingungen (ADR-60). Browser, Vorschau und Anfrageservice fragen dieselbe Funktion; der
|
||||
* Browser entscheidet nichts allein.
|
||||
*
|
||||
* Die Auswertung läuft einmal in Dokumentreihenfolge. Eine Bedingung sieht nur Werte von Feldern, die vor ihr stehen und
|
||||
* selbst sichtbar sind; Werte ausgeblendeter Felder zählen als nicht vorhanden. Daraus folgt: keine Zyklen, und
|
||||
* nicht mehr relevante Werte erreichen nie die Speicherung.
|
||||
*/
|
||||
final class FormEvaluator
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $form wirksames Formular (FormFactory::effective)
|
||||
* @param array<string, mixed> $values Eingaben des Besuchers, nach Feldkennung
|
||||
* @return array{steps: array<string, bool>, groups: array<string, bool>, fields: array<string, bool>, required: array<string, bool>, presets: array<string, string>, issue: ?string, subissue: ?string, issue_active: bool}
|
||||
*/
|
||||
public function evaluate(array $form, array $values): array
|
||||
{
|
||||
$state = ['steps' => [], 'groups' => [], 'fields' => [], 'required' => [], 'presets' => [], 'issue' => null, 'subissue' => null, 'issue_active' => false];
|
||||
$context = [];
|
||||
$byTarget = [];
|
||||
|
||||
foreach ((array) ($form['rules'] ?? []) as $rule) {
|
||||
$byTarget[$rule['target']][] = $rule;
|
||||
}
|
||||
|
||||
foreach ((array) $form['steps'] as $step) {
|
||||
$stepVisible = ! $this->any($byTarget['step:'.$step['key']] ?? [], 'skip', $context);
|
||||
$state['steps'][$step['key']] = $stepVisible;
|
||||
|
||||
foreach ($step['items'] as $item) {
|
||||
if ($item['kind'] === 'issue') {
|
||||
$this->issue($form, $values, $stepVisible, $state, $context);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$groupVisible = $stepVisible && ($item['key'] === null || $this->visible($byTarget['group:'.$item['key']] ?? [], $context));
|
||||
|
||||
if ($item['key'] !== null) {
|
||||
$state['groups'][$item['key']] = $groupVisible;
|
||||
}
|
||||
|
||||
foreach ($item['fields'] as $row) {
|
||||
$key = $row['field'];
|
||||
$rules = $byTarget["field:$key"] ?? [];
|
||||
$visible = $groupVisible && $this->visible($rules, $context);
|
||||
$state['fields'][$key] = $visible;
|
||||
$state['required'][$key] = $visible && ($row['required'] || $this->any($rules, 'require', $context));
|
||||
|
||||
if (! $visible) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$context[$key] = FieldValue::forRules($form['fields'][$key], $values[$key] ?? null);
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
if ($rule['effect'] === 'preset' && $this->matches($rule, $context)) {
|
||||
$state['presets'][$key] ??= (string) $rule['value'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $form
|
||||
* @param array<string, mixed> $values
|
||||
* @param array<string, mixed> $state
|
||||
* @param array<string, string|array<int, string>|null> $context
|
||||
*/
|
||||
private function issue(array $form, array $values, bool $stepVisible, array &$state, array &$context): void
|
||||
{
|
||||
$state['fields']['anliegen'] = false;
|
||||
$state['fields']['unteranliegen'] = false;
|
||||
$state['required']['anliegen'] = false;
|
||||
$state['required']['unteranliegen'] = false;
|
||||
|
||||
if (! $stepVisible) {
|
||||
return;
|
||||
}
|
||||
|
||||
$state['issue_active'] = true;
|
||||
$tops = (array) $form['issues'];
|
||||
$selected = null;
|
||||
|
||||
if (count($tops) === 1) {
|
||||
$selected = $tops[0];
|
||||
} else {
|
||||
$state['fields']['anliegen'] = $tops !== [];
|
||||
$state['required']['anliegen'] = $tops !== [];
|
||||
$wanted = $values['anliegen'] ?? null;
|
||||
|
||||
foreach ($tops as $top) {
|
||||
if ($top['key'] === $wanted) {
|
||||
$selected = $top;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$context['anliegen'] = $selected['key'] ?? null;
|
||||
$state['issue'] = $selected['key'] ?? null;
|
||||
|
||||
if ($selected === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$children = (array) $selected['children'];
|
||||
$child = null;
|
||||
|
||||
if (count($children) === 1) {
|
||||
$child = $children[0];
|
||||
} elseif (count($children) > 1) {
|
||||
$state['fields']['unteranliegen'] = true;
|
||||
$state['required']['unteranliegen'] = true;
|
||||
$wanted = $values['unteranliegen'] ?? null;
|
||||
|
||||
foreach ($children as $candidate) {
|
||||
if ($candidate['key'] === $wanted) {
|
||||
$child = $candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$context['unteranliegen'] = $child['key'] ?? null;
|
||||
$state['subissue'] = $child['key'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sichtbar, wenn keine „Anzeigen“-Regel besteht oder eine zutrifft, und keine „Ausblenden“-Regel zutrifft.
|
||||
*
|
||||
* @param list<array<string, mixed>> $rules
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function visible(array $rules, array $context): bool
|
||||
{
|
||||
$show = array_filter($rules, fn (array $rule): bool => $rule['effect'] === 'show');
|
||||
|
||||
if ($show !== [] && ! $this->any($show, 'show', $context)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! $this->any($rules, 'hide', $context);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $rules
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function any(array $rules, string $effect, array $context): bool
|
||||
{
|
||||
foreach ($rules as $rule) {
|
||||
if ($rule['effect'] === $effect && $this->matches($rule, $context)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $rule
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function matches(array $rule, array $context): bool
|
||||
{
|
||||
$results = [];
|
||||
|
||||
foreach ($rule['conditions'] as $condition) {
|
||||
$results[] = $this->condition($condition, $context);
|
||||
}
|
||||
|
||||
if ($results === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $rule['match'] === 'any' ? in_array(true, $results, true) : ! in_array(false, $results, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Bedingung auf einem nicht sichtbaren Feld ist nie erfüllt, auch nicht „ist nicht“.
|
||||
*
|
||||
* @param array<string, mixed> $condition
|
||||
* @param array<string, mixed> $context
|
||||
*/
|
||||
private function condition(array $condition, array $context): bool
|
||||
{
|
||||
if (! array_key_exists($condition['source'], $context)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$actual = $context[$condition['source']];
|
||||
$wanted = (array) $condition['values'];
|
||||
$hit = is_array($actual)
|
||||
? array_intersect($actual, $wanted) !== []
|
||||
: ($actual !== null && in_array($actual, $wanted, true));
|
||||
|
||||
return match ($condition['op']) {
|
||||
'eq', 'in' => $hit,
|
||||
'neq', 'not_in' => ! $hit,
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Baut aus einer veröffentlichten Fassung und der Konfiguration eines Anfrage-Einstiegs das wirksame Formular:
|
||||
* zugelassene Anliegen, Texte, Darstellung und Vorbelegung. Dieselbe Funktion bedient Besucher, Vorschau und
|
||||
* Anfrageservice, damit nirgends eine zweite Auslegung entsteht.
|
||||
*/
|
||||
final class FormFactory
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $definition aufgelöste Fassung (TemplateCompiler)
|
||||
* @param array<string, mixed> $config Konfiguration des Einstiegs (veröffentlichter Stand oder Entwurf)
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function effective(array $definition, array $config): array
|
||||
{
|
||||
$allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string'));
|
||||
$allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string'));
|
||||
$tree = [];
|
||||
|
||||
foreach ((array) ($definition['issues'] ?? []) as $issue) {
|
||||
if ($allowed !== [] && ! in_array($issue['key'], $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$children = (array) $issue['children'];
|
||||
$chosen = array_values(array_filter($children, fn (array $child): bool => in_array($child['key'], $allowedSub, true)));
|
||||
$issue['children'] = $chosen !== [] ? $chosen : $children;
|
||||
$tree[] = $issue;
|
||||
}
|
||||
|
||||
$form = $definition;
|
||||
$form['issues'] = $tree;
|
||||
$form['texts'] = FormTexts::merge((array) ($definition['texts'] ?? []), (array) ($config['texts'] ?? []));
|
||||
$form['mode'] = ($config['mode'] ?? 'compact') === 'wizard' ? 'wizard' : 'compact';
|
||||
$form['open'] = ($config['open'] ?? 'inline') === 'button' ? 'button' : 'inline';
|
||||
$form['defaults'] = $this->defaults($form, (array) ($config['defaults'] ?? []));
|
||||
$form['controls'] = $this->controls($form);
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $form
|
||||
* @param array<string, mixed> $wanted
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function defaults(array $form, array $wanted): array
|
||||
{
|
||||
$defaults = [];
|
||||
$tops = array_column((array) $form['issues'], 'key');
|
||||
|
||||
if (isset($wanted['anliegen']) && in_array($wanted['anliegen'], $tops, true)) {
|
||||
$defaults['anliegen'] = $wanted['anliegen'];
|
||||
|
||||
foreach ($form['issues'] as $issue) {
|
||||
if ($issue['key'] === $wanted['anliegen'] && isset($wanted['unteranliegen']) && in_array($wanted['unteranliegen'], array_column($issue['children'], 'key'), true)) {
|
||||
$defaults['unteranliegen'] = $wanted['unteranliegen'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) $form['fields'] as $key => $field) {
|
||||
$value = $wanted[$key] ?? null;
|
||||
|
||||
if (! is_string($value) || ! in_array($field['type'], ['select', 'boolean'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
|
||||
|
||||
if (in_array($value, $valid, true)) {
|
||||
$defaults[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $defaults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Felder, auf deren Änderung das Formular die Regeln neu auswerten lassen muss.
|
||||
*
|
||||
* @param array<string, mixed> $form
|
||||
* @return list<string>
|
||||
*/
|
||||
private function controls(array $form): array
|
||||
{
|
||||
$controls = [];
|
||||
|
||||
foreach ((array) $form['rules'] as $rule) {
|
||||
foreach ($rule['conditions'] as $condition) {
|
||||
$controls[$condition['source']] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return array_keys($controls);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Konfiguration eines Einstiegs gegen eine Fassung. Leere Liste: gültig.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
* @param array<string, mixed> $config
|
||||
* @return list<string>
|
||||
*/
|
||||
public function problems(array $definition, array $config): array
|
||||
{
|
||||
$problems = [];
|
||||
$tops = array_column((array) ($definition['issues'] ?? []), 'key');
|
||||
$subs = [];
|
||||
|
||||
foreach ((array) ($definition['issues'] ?? []) as $issue) {
|
||||
foreach ($issue['children'] as $child) {
|
||||
$subs[$child['key']] = $issue['key'];
|
||||
}
|
||||
}
|
||||
|
||||
$allowed = array_values(array_filter((array) ($config['allowed_issues'] ?? []), 'is_string'));
|
||||
$allowedSub = array_values(array_filter((array) ($config['allowed_subissues'] ?? []), 'is_string'));
|
||||
|
||||
foreach ($allowed as $key) {
|
||||
if (! in_array($key, $tops, true)) {
|
||||
$problems[] = "Das Anliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten.";
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($allowedSub as $key) {
|
||||
if (! isset($subs[$key])) {
|
||||
$problems[] = "Das Unteranliegen „{$key}“ ist in der veröffentlichten Vorlage nicht enthalten.";
|
||||
} elseif ($allowed !== [] && ! in_array($subs[$key], $allowed, true)) {
|
||||
$problems[] = "Das Unteranliegen „{$key}“ gehört zu einem Anliegen, das dieser Einstieg nicht zulässt.";
|
||||
}
|
||||
}
|
||||
|
||||
if (($definition['has_issue'] ?? false) && $allowed !== [] && array_diff($allowed, $tops) === $allowed) {
|
||||
$problems[] = 'Keines der zugelassenen Anliegen ist in der Vorlage vorhanden.';
|
||||
}
|
||||
|
||||
foreach ((array) ($config['defaults'] ?? []) as $key => $value) {
|
||||
if ($key === 'anliegen') {
|
||||
if (! in_array($value, $allowed !== [] ? $allowed : $tops, true)) {
|
||||
$problems[] = 'Das vorausgewählte Anliegen ist nicht zugelassen oder nicht in der Vorlage.';
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($key === 'unteranliegen') {
|
||||
if (! isset($subs[$value])) {
|
||||
$problems[] = 'Das vorausgewählte Unteranliegen ist nicht in der Vorlage.';
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$field = $definition['fields'][$key] ?? null;
|
||||
|
||||
if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) {
|
||||
$problems[] = "Die Vorbelegung für „{$key}“ ist in der veröffentlichten Vorlage nicht möglich.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
|
||||
|
||||
if (! in_array($value, $valid, true)) {
|
||||
$problems[] = "Der vorausgewählte Wert für „{$field['label']}“ gibt es nicht mehr.";
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($config['mode']) && ! in_array($config['mode'], ['compact', 'wizard'], true)) {
|
||||
$problems[] = 'Die Darstellung muss „kompakt“ oder „mehrstufig“ sein.';
|
||||
}
|
||||
|
||||
return $problems;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Vergleichbare Form für gespeicherte Konfigurationen: Schlüssel sortiert, Listen unverändert, Skalare als Text.
|
||||
*/
|
||||
final class FormJson
|
||||
{
|
||||
/**
|
||||
* @param array<mixed> $value
|
||||
* @return array<mixed>
|
||||
*/
|
||||
public static function normalize(array $value): array
|
||||
{
|
||||
$isList = array_is_list($value);
|
||||
|
||||
foreach ($value as $key => $item) {
|
||||
if (is_array($item)) {
|
||||
$value[$key] = self::normalize($item);
|
||||
} elseif (is_int($item) || is_float($item)) {
|
||||
$value[$key] = (string) $item;
|
||||
} elseif (is_bool($item)) {
|
||||
$value[$key] = $item ? '1' : '0';
|
||||
}
|
||||
}
|
||||
|
||||
if (! $isList) {
|
||||
ksort($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Die Beschreibung des Formulars für den Browser. Sie enthält, was zur Darstellung nötig ist (Texte, Schritte, Felder,
|
||||
* Auswahlwerte), und den ersten Zustand der Bedingungen, aber keine Regeln und keine Verwendungszwecke: Entscheidungen
|
||||
* über Sichtbarkeit und Pflicht trifft ausschließlich der Server (FormEvaluator).
|
||||
*/
|
||||
final class FormPayload
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $form wirksames Formular (FormFactory::effective)
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function definition(array $form, FormEvaluator $evaluator): array
|
||||
{
|
||||
$fields = [];
|
||||
|
||||
foreach ((array) $form['fields'] as $key => $field) {
|
||||
$settings = (array) ($field['settings'] ?? []);
|
||||
$fields[$key] = array_filter([
|
||||
'key' => $key,
|
||||
'label' => $field['label'],
|
||||
'help' => $field['help'],
|
||||
'type' => $field['type'],
|
||||
'options' => $field['options'] ?: null,
|
||||
'max_length' => $settings['max_length'] ?? null,
|
||||
'min' => $settings['min'] ?? null,
|
||||
'max' => $settings['max'] ?? null,
|
||||
], fn (mixed $value): bool => $value !== null);
|
||||
}
|
||||
|
||||
return [
|
||||
'mode' => $form['mode'] ?? 'compact',
|
||||
'open' => $form['open'] ?? 'inline',
|
||||
'texts' => $form['texts'],
|
||||
'issues' => $form['issues'],
|
||||
'defaults' => (object) ($form['defaults'] ?? []),
|
||||
'controls' => $form['controls'] ?? [],
|
||||
'steps' => $form['steps'],
|
||||
'fields' => $fields,
|
||||
'state' => self::state($form, (array) ($form['defaults'] ?? []), $evaluator),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $form
|
||||
* @param array<string, mixed> $values
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function state(array $form, array $values, FormEvaluator $evaluator): array
|
||||
{
|
||||
$state = $evaluator->evaluate($form, $values);
|
||||
|
||||
return [
|
||||
'steps' => (object) $state['steps'],
|
||||
'groups' => (object) $state['groups'],
|
||||
'fields' => (object) $state['fields'],
|
||||
'required' => (object) $state['required'],
|
||||
'presets' => (object) $state['presets'],
|
||||
'issue' => $state['issue'],
|
||||
'subissue' => $state['subissue'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Die Texte eines Anfrageformulars. Die Vorlage legt sie fest, ein Anfrage-Einstieg darf sie überschreiben.
|
||||
* Alle Texte werden ausschließlich in der Kommunikationsverwaltung gepflegt (ADR-60).
|
||||
*/
|
||||
final class FormTexts
|
||||
{
|
||||
/** Schlüssel => [Bezeichnung in der Verwaltung, Vorgabe, Hilfetext, mehrzeilig] */
|
||||
public const FIELDS = [
|
||||
'heading' => ['Überschrift', 'Ihre Anfrage', 'Steht über dem Formular.', false],
|
||||
'intro' => ['Beschreibung', '', 'Kurzer Text unter der Überschrift.', true],
|
||||
'open_label' => ['Beschriftung der Öffnen-Schaltfläche', 'Anfrage stellen', 'Nur wenn der Einstieg zunächst eine Schaltfläche zeigt.', false],
|
||||
'issue_question' => ['Frage nach dem Anliegen', 'Wie können wir Ihnen helfen?', 'Steht über der Auswahl des Anliegens.', false],
|
||||
'privacy_note' => ['Hinweis zum Datenschutz', '', 'Steht über der Schaltfläche zum Absenden. Der rechtlich geprüfte Wortlaut wird hier gepflegt; es gibt keine Pflicht-Einwilligungsbox.', true],
|
||||
'back_label' => ['Schaltfläche „Zurück“', 'Zurück', null, false],
|
||||
'next_label' => ['Schaltfläche „Weiter“', 'Weiter', null, false],
|
||||
'summary_title' => ['Überschrift der Zusammenfassung', 'Ihre Angaben im Überblick', 'Letzter Schritt vor dem Absenden im mehrstufigen Dialog.', false],
|
||||
'edit_label' => ['Schaltfläche „Ändern“', 'Ändern', 'Steht in der Zusammenfassung neben jedem Schritt.', false],
|
||||
'submit_label' => ['Schaltfläche zum Absenden', 'Anfrage senden', null, false],
|
||||
'success_title' => ['Bestätigung: Überschrift', 'Vielen Dank für Ihre Anfrage', null, false],
|
||||
'success_text' => ['Bestätigung: Text', 'Wir haben Ihre Anfrage erhalten und melden uns bei Ihnen.', null, true],
|
||||
'error_text' => ['Meldung bei einem Fehler', 'Ihre Anfrage konnte nicht gesendet werden. Ihre Eingaben bleiben erhalten; bitte versuchen Sie es noch einmal.', null, true],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function defaults(): array
|
||||
{
|
||||
$defaults = [];
|
||||
|
||||
foreach (self::FIELDS as $key => $field) {
|
||||
$defaults[$key] = $field[1];
|
||||
}
|
||||
|
||||
return $defaults;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt Vorgaben und eigene Texte zusammen; leere Eigenwerte fallen auf die Vorgabe zurück.
|
||||
*
|
||||
* @param array<string, mixed> ...$layers von der schwächsten zur stärksten Schicht
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function merge(array ...$layers): array
|
||||
{
|
||||
$texts = self::defaults();
|
||||
|
||||
foreach ($layers as $layer) {
|
||||
foreach (array_keys(self::FIELDS) as $key) {
|
||||
$value = $layer[$key] ?? null;
|
||||
|
||||
if (is_string($value) && trim($value) !== '') {
|
||||
$texts[$key] = trim($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $texts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bereinigt eigene Texte aus der Verwaltung: nur bekannte Schlüssel, Länge begrenzt.
|
||||
*
|
||||
* @param array<string, mixed> $texts
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function clean(array $texts): array
|
||||
{
|
||||
$clean = [];
|
||||
|
||||
foreach (self::FIELDS as $key => $field) {
|
||||
$value = $texts[$key] ?? null;
|
||||
|
||||
if (is_string($value) && trim($value) !== '') {
|
||||
$clean[$key] = mb_substr(trim($value), 0, $field[3] ? 1500 : 200);
|
||||
}
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Verschlüsseltes Formular-Token, das mit dem Formular ausgeliefert wird. Es trägt Einstieg, Fassung, Zeitpunkt und
|
||||
* eine einmalige Kennung. Daraus folgen:
|
||||
* - die Anfrage bezieht sich auf die Fassung, die der Besucher tatsächlich sah,
|
||||
* - eine zu schnelle Absendung und ein abgelaufenes Formular lassen sich erkennen,
|
||||
* - doppeltes Absenden ergibt dieselbe Anfrage (Einmalkennung).
|
||||
* Nichts davon steht in der gespeicherten Seite; die Seite enthält nur die Kennung des Einstiegs.
|
||||
*/
|
||||
final class FormToken
|
||||
{
|
||||
public static function issue(int $entryId, int $versionId): string
|
||||
{
|
||||
return Crypt::encryptString(json_encode([
|
||||
'e' => $entryId,
|
||||
'v' => $versionId,
|
||||
't' => now()->getTimestamp(),
|
||||
'n' => Str::random(32),
|
||||
], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{e: int, v: int, t: int, n: string}|null
|
||||
*/
|
||||
public static function read(mixed $token): ?array
|
||||
{
|
||||
if (! is_string($token) || $token === '' || strlen($token) > 2000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$data = json_decode(Crypt::decryptString($token), true, 4, JSON_THROW_ON_ERROR);
|
||||
} catch (DecryptException|\JsonException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! is_array($data) || ! isset($data['e'], $data['v'], $data['t'], $data['n']) || ! is_string($data['n'])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['e' => (int) $data['e'], 'v' => (int) $data['v'], 't' => (int) $data['t'], 'n' => $data['n']];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Eine eingegangene Anfrage. answers hält Bezeichnungen und Werte, wie sie der Besucher sah; sie bleiben auch nach
|
||||
* einer Änderung der zentralen Konfiguration lesbar.
|
||||
*/
|
||||
class Inquiry extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'reference', 'entry_id', 'template_version_id', 'submission_token', 'issue_key', 'issue_label', 'subissue_key',
|
||||
'subissue_label', 'contact_name', 'contact_email', 'contact_phone', 'organisation', 'message', 'answers',
|
||||
'source_path', 'status', 'notified_at', 'notification_error',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['answers' => 'array', 'status' => InquiryStatus::class, 'notified_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function entry(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InquiryEntry::class, 'entry_id');
|
||||
}
|
||||
|
||||
public function templateVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InquiryTemplateVersion::class, 'template_version_id');
|
||||
}
|
||||
|
||||
public function notes(): HasMany
|
||||
{
|
||||
return $this->hasMany(InquiryNote::class)->orderByDesc('created_at')->orderByDesc('id');
|
||||
}
|
||||
|
||||
/** Lesbare Bezeichnung des Anliegens, mit Unteranliegen. */
|
||||
public function issueTitle(): string
|
||||
{
|
||||
return trim(implode(' › ', array_filter([$this->issue_label, $this->subissue_label])));
|
||||
}
|
||||
|
||||
public function contactTitle(): string
|
||||
{
|
||||
return $this->contact_name ?: ($this->contact_email ?: 'Unbekannt');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anfrage-Einstieg: die veröffentlichbare Nutzungsvariante einer Anfragevorlage. config ist der Entwurf,
|
||||
* published_config der wirksame Stand.
|
||||
*/
|
||||
class InquiryEntry extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'template_id', 'config', 'published_config', 'published_at', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['config' => 'array', 'published_config' => 'array', 'published_at' => 'datetime', 'archived_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function template(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InquiryTemplate::class, 'template_id');
|
||||
}
|
||||
|
||||
public function inquiries(): HasMany
|
||||
{
|
||||
return $this->hasMany(Inquiry::class, 'entry_id');
|
||||
}
|
||||
|
||||
/** Einstiege, die Besuchern ausgeliefert werden können (Vorlage zusätzlich in isLive() prüfen). */
|
||||
public function scopeLive(Builder $query): Builder
|
||||
{
|
||||
return $query->whereNotNull('published_at')->whereNull('archived_at')->whereNotNull('published_config');
|
||||
}
|
||||
|
||||
public function isLive(): bool
|
||||
{
|
||||
return $this->published_at !== null && $this->archived_at === null && $this->published_config !== null
|
||||
&& $this->template?->published_version_id !== null && $this->template->archived_at === null;
|
||||
}
|
||||
|
||||
public function hasUnpublishedChanges(): bool
|
||||
{
|
||||
return $this->published_config === null || FormJson::normalize($this->published_config) !== FormJson::normalize((array) $this->config);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function emptyConfig(): array
|
||||
{
|
||||
return [
|
||||
'mode' => 'compact',
|
||||
'open' => 'inline',
|
||||
'allowed_issues' => [],
|
||||
'allowed_subissues' => [],
|
||||
'defaults' => [],
|
||||
'texts' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Eingabefeld des Feldkatalogs. Wiederverwendbar in beliebig vielen Feldgruppen und Vorlagen.
|
||||
*/
|
||||
class InquiryField extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'label', 'help', 'type', 'options', 'settings', 'purpose', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'type' => FieldType::class,
|
||||
'purpose' => FieldPurpose::class,
|
||||
'options' => 'array',
|
||||
'settings' => 'array',
|
||||
'active' => 'boolean',
|
||||
'archived_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function scopeOffered(Builder $query): Builder
|
||||
{
|
||||
return $query->where('active', true)->whereNull('archived_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* Auswahlwerte als Liste [{key, label}] in der gepflegten Reihenfolge.
|
||||
*
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public function optionList(): array
|
||||
{
|
||||
if ($this->type === FieldType::Boolean) {
|
||||
return [['key' => 'ja', 'label' => 'Ja'], ['key' => 'nein', 'label' => 'Nein']];
|
||||
}
|
||||
|
||||
if (! $this->type->hasOptions()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$list = [];
|
||||
|
||||
foreach ((array) $this->options as $option) {
|
||||
if (is_array($option) && Keys::valid($option['key'] ?? null) && filled($option['label'] ?? null)) {
|
||||
$list[] = ['key' => $option['key'], 'label' => (string) $option['label']];
|
||||
}
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Beschreibung des Feldes, wie sie in eine Fassung übernommen wird.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function snapshot(): array
|
||||
{
|
||||
return [
|
||||
'key' => $this->key,
|
||||
'label' => $this->label,
|
||||
'help' => $this->help,
|
||||
'type' => $this->type->value,
|
||||
'options' => $this->optionList(),
|
||||
'settings' => (array) $this->settings,
|
||||
'purpose' => $this->purpose?->value,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Fachliche Zusammenstellung von Feldern. items: geordnete Liste [{field: Kennung, required: bool}].
|
||||
*/
|
||||
class InquiryFieldGroup extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'label', 'description', 'items', 'sort_order', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['items' => 'array', 'active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer'];
|
||||
}
|
||||
|
||||
public function scopeOffered(Builder $query): Builder
|
||||
{
|
||||
return $query->where('active', true)->whereNull('archived_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{field: string, required: bool}>
|
||||
*/
|
||||
public function itemList(): array
|
||||
{
|
||||
$list = [];
|
||||
|
||||
foreach ((array) $this->items as $item) {
|
||||
if (is_array($item) && Keys::valid($item['field'] ?? null)) {
|
||||
$list[] = ['field' => $item['field'], 'required' => (bool) ($item['required'] ?? false)];
|
||||
}
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anliegen (oberste Ebene) oder Unteranliegen. Wird nie gelöscht, nur deaktiviert oder archiviert.
|
||||
*/
|
||||
class InquiryIssue extends Model
|
||||
{
|
||||
protected $fillable = ['parent_id', 'key', 'label', 'description', 'sort_order', 'active', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['active' => 'boolean', 'archived_at' => 'datetime', 'sort_order' => 'integer'];
|
||||
}
|
||||
|
||||
public function parent(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function children(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'parent_id')->orderBy('sort_order')->orderBy('id');
|
||||
}
|
||||
|
||||
/** Anliegen, die Besuchern angeboten werden können. */
|
||||
public function scopeOffered(Builder $query): Builder
|
||||
{
|
||||
return $query->where('active', true)->whereNull('archived_at');
|
||||
}
|
||||
|
||||
public function isOffered(): bool
|
||||
{
|
||||
return $this->active && $this->archived_at === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Baum aus angebotenen Anliegen mit ihren angebotenen Unteranliegen, wie er in eine Fassung übernommen wird.
|
||||
*
|
||||
* @return list<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
|
||||
*/
|
||||
public static function tree(): array
|
||||
{
|
||||
$all = self::query()->offered()->orderBy('sort_order')->orderBy('id')->get();
|
||||
$children = $all->whereNotNull('parent_id')->groupBy('parent_id');
|
||||
$tree = [];
|
||||
|
||||
foreach ($all->whereNull('parent_id') as $issue) {
|
||||
$tree[] = [
|
||||
'key' => $issue->key,
|
||||
'label' => $issue->label,
|
||||
'description' => $issue->description,
|
||||
'children' => ($children[$issue->id] ?? collect())->map(fn (self $child): array => [
|
||||
'key' => $child->key,
|
||||
'label' => $child->label,
|
||||
'description' => $child->description,
|
||||
])->values()->all(),
|
||||
];
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class InquiryNote extends Model
|
||||
{
|
||||
protected $fillable = ['inquiry_id', 'user_id', 'body'];
|
||||
|
||||
public function inquiry(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Inquiry::class);
|
||||
}
|
||||
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Jobs\SendInquiryNotification;
|
||||
use Illuminate\Database\UniqueConstraintViolationException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Zentraler Anfrageservice (ADR-60): jeder öffentliche Anfrage-Einstieg sendet hierher, unabhängig von der Seite.
|
||||
*
|
||||
* 1. gültige veröffentlichte Konfiguration ermitteln, 2. Token prüfen, 3. Bedingungen auswerten, 4. serverseitig
|
||||
* validieren, 5. speichern, 6. erst danach benachrichtigen, 7. Ergebnis melden.
|
||||
* Der Browser entscheidet nichts: Werte ausgeblendeter Felder werden verworfen, unbekannte Schlüssel und Auswahlwerte
|
||||
* zurückgewiesen.
|
||||
*/
|
||||
final class InquiryService
|
||||
{
|
||||
public function __construct(private readonly FormFactory $factory, private readonly FormEvaluator $evaluator) {}
|
||||
|
||||
/**
|
||||
* Die Fassung und das wirksame Formular für einen Besucher. Null, wenn der Einstieg nicht ausgeliefert wird.
|
||||
*
|
||||
* @return array{form: array<string, mixed>, version: InquiryTemplateVersion}|null
|
||||
*/
|
||||
public function deliver(InquiryEntry $entry, ?int $versionId = null): ?array
|
||||
{
|
||||
$entry->loadMissing('template.publishedVersion');
|
||||
|
||||
if (! $entry->isLive()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = $entry->template->publishedVersion;
|
||||
|
||||
if ($versionId !== null && $versionId !== $version->id) {
|
||||
$older = InquiryTemplateVersion::query()->where('template_id', $entry->template_id)->find($versionId);
|
||||
$version = $older ?? $version;
|
||||
}
|
||||
|
||||
return ['form' => $this->factory->effective($version->definition, (array) $entry->published_config), 'version' => $version];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $payload {values: {...}, token: string, website?: string, source?: string}
|
||||
* @return array{reference: string, created: bool}
|
||||
*
|
||||
* @throws SubmissionException
|
||||
*/
|
||||
public function submit(InquiryEntry $entry, array $payload): array
|
||||
{
|
||||
$token = FormToken::read($payload['token'] ?? null);
|
||||
|
||||
if ($token === null || $token['e'] !== $entry->id) {
|
||||
throw new SubmissionException('Das Formular ist abgelaufen. Bitte laden Sie die Seite neu; Ihre Eingaben bleiben dabei nicht erhalten.', [], 419);
|
||||
}
|
||||
|
||||
$age = now()->getTimestamp() - $token['t'];
|
||||
|
||||
if ($age > config('communication.token_ttl_hours', 24) * 3600) {
|
||||
throw new SubmissionException('Das Formular war zu lange geöffnet. Bitte laden Sie die Seite neu.', [], 419);
|
||||
}
|
||||
|
||||
$existing = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->first();
|
||||
|
||||
if ($existing !== null) {
|
||||
return ['reference' => $existing->reference, 'created' => false];
|
||||
}
|
||||
|
||||
$delivered = $this->deliver($entry, $token['v']);
|
||||
|
||||
if ($delivered === null) {
|
||||
throw new SubmissionException('Dieses Anfrageformular ist zurzeit nicht verfügbar.', [], 410);
|
||||
}
|
||||
|
||||
// Automaten: ausgefülltes Köderfeld oder zu schnelle Absendung. Keine Speicherung, keine Rückmeldung an das Programm.
|
||||
$website = $payload['website'] ?? null;
|
||||
|
||||
if ((is_string($website) && trim($website) !== '') || $age < (int) config('communication.min_fill_seconds', 3)) {
|
||||
if (! (is_string($website) && trim($website) !== '')) {
|
||||
throw new SubmissionException('Bitte nehmen Sie sich einen Moment Zeit und senden Sie noch einmal.', [], 429);
|
||||
}
|
||||
|
||||
return ['reference' => 'LF-'.now()->format('ymd').'-'.Str::upper(Str::random(5)), 'created' => false];
|
||||
}
|
||||
|
||||
$values = $payload['values'] ?? null;
|
||||
|
||||
if (! is_array($values) || strlen((string) json_encode($values)) > (int) config('communication.max_payload_chars', 40000)) {
|
||||
throw new SubmissionException('Die Eingaben sind ungültig.');
|
||||
}
|
||||
|
||||
$form = $delivered['form'];
|
||||
$result = $this->process($form, $values);
|
||||
|
||||
$source = $payload['source'] ?? null;
|
||||
$source = is_string($source) && preg_match('#^/[A-Za-z0-9\-_/.]{0,250}$#', $source) === 1 ? $source : null;
|
||||
|
||||
try {
|
||||
$inquiry = DB::transaction(fn (): Inquiry => Inquiry::query()->create([
|
||||
'reference' => $this->reference(),
|
||||
'entry_id' => $entry->id,
|
||||
'template_version_id' => $delivered['version']->id,
|
||||
'submission_token' => hash('sha256', $token['n']),
|
||||
'issue_key' => $result['issue']['key'] ?? null,
|
||||
'issue_label' => $result['issue']['label'] ?? null,
|
||||
'subissue_key' => $result['subissue']['key'] ?? null,
|
||||
'subissue_label' => $result['subissue']['label'] ?? null,
|
||||
'contact_name' => $result['contact']['name'] ?? null,
|
||||
'contact_email' => $result['contact']['email'] ?? null,
|
||||
'contact_phone' => $result['contact']['telefon'] ?? null,
|
||||
'organisation' => $result['contact']['organisation'] ?? null,
|
||||
'message' => $result['contact']['nachricht'] ?? null,
|
||||
'answers' => $result['answers'],
|
||||
'source_path' => $source,
|
||||
'status' => InquiryStatus::Neu->value,
|
||||
]));
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
// Doppelt abgesendet, zwischen Prüfung und Speicherung: dieselbe Anfrage melden.
|
||||
$again = Inquiry::query()->where('submission_token', hash('sha256', $token['n']))->firstOrFail();
|
||||
|
||||
return ['reference' => $again->reference, 'created' => false];
|
||||
}
|
||||
|
||||
// Erst nach der Speicherung benachrichtigen. Ein Fehler hier verliert die Anfrage nie.
|
||||
try {
|
||||
SendInquiryNotification::dispatch($inquiry->id, url('/verwaltung/anfragen/'.$inquiry->id))->afterCommit();
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
$inquiry->forceFill(['notification_error' => 'Die Benachrichtigung konnte nicht eingereiht werden: '.Str::limit($e->getMessage(), 300)])->save();
|
||||
}
|
||||
|
||||
return ['reference' => $inquiry->reference, 'created' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Wertet das Formular für Eingaben aus und prüft sie. Wird auch von der Vorschau verwendet.
|
||||
*
|
||||
* @param array<string, mixed> $form
|
||||
* @param array<string, mixed> $values
|
||||
* @return array{answers: list<array<string, mixed>>, contact: array<string, string>, issue: ?array<string, string>, subissue: ?array<string, string>}
|
||||
*
|
||||
* @throws SubmissionException
|
||||
*/
|
||||
public function process(array $form, array $values): array
|
||||
{
|
||||
$known = array_merge(array_keys((array) $form['fields']), ['anliegen', 'unteranliegen']);
|
||||
|
||||
foreach (array_keys($values) as $key) {
|
||||
if (! is_string($key) || ! in_array($key, $known, true)) {
|
||||
throw new SubmissionException('Die Eingaben sind ungültig.');
|
||||
}
|
||||
}
|
||||
|
||||
$state = $this->evaluator->evaluate($form, $values);
|
||||
$errors = [];
|
||||
|
||||
// Anliegen: Auswahl aus dem zugelassenen Rahmen. Ein abweichender Wert ist eine Manipulation, auch wenn das Feld
|
||||
// nicht sichtbar ist (zum Beispiel weil nur ein Anliegen zugelassen ist).
|
||||
if ($state['issue_active']) {
|
||||
foreach (['anliegen', 'unteranliegen'] as $key) {
|
||||
$raw = $values[$key] ?? null;
|
||||
$selected = $key === 'anliegen' ? $state['issue'] : $state['subissue'];
|
||||
$filled = $raw !== null && $raw !== '';
|
||||
|
||||
if (! $filled && ($state['required'][$key] ?? false)) {
|
||||
$errors[$key] = 'Bitte treffen Sie eine Auswahl.';
|
||||
} elseif ($filled && $raw !== $selected) {
|
||||
$errors[$key] = 'Bitte wählen Sie einen der angebotenen Werte.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$answers = [];
|
||||
$contact = [];
|
||||
$steps = [];
|
||||
|
||||
foreach ((array) $form['steps'] as $step) {
|
||||
foreach ($step['items'] as $item) {
|
||||
if ($item['kind'] !== 'group') {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($item['fields'] as $row) {
|
||||
$key = $row['field'];
|
||||
$steps[$key] = [$step['title'], $item['label']];
|
||||
|
||||
if (! ($state['fields'][$key] ?? false)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$field = $form['fields'][$key];
|
||||
[$value, $error] = FieldValue::check($field, $values[$key] ?? null, (bool) ($state['required'][$key] ?? false));
|
||||
|
||||
if ($error !== null) {
|
||||
$errors[$key] = $error;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$display = FieldValue::display($field, $value);
|
||||
$answers[] = [
|
||||
'key' => $key,
|
||||
'label' => $field['label'],
|
||||
'type' => $field['type'],
|
||||
'value' => $value,
|
||||
'display' => $display,
|
||||
'step' => $steps[$key][0],
|
||||
'group' => $steps[$key][1],
|
||||
];
|
||||
|
||||
if ($field['purpose'] !== null) {
|
||||
$contact[$field['purpose']] = $display;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($errors !== []) {
|
||||
throw new SubmissionException('Bitte prüfen Sie Ihre Angaben.', $errors);
|
||||
}
|
||||
|
||||
$issue = $this->issueEntry($form, $state['issue']);
|
||||
$subissue = $issue === null ? null : $this->subissueEntry($form, $state['issue'], $state['subissue']);
|
||||
|
||||
$name = $contact['name'] ?? trim(($contact['vorname'] ?? '').' '.($contact['nachname'] ?? ''));
|
||||
|
||||
return [
|
||||
'answers' => $answers,
|
||||
'contact' => array_filter([
|
||||
'name' => $name,
|
||||
'email' => $contact['email'] ?? null,
|
||||
'telefon' => $contact['telefon'] ?? null,
|
||||
'organisation' => $contact['organisation'] ?? null,
|
||||
'nachricht' => $contact['nachricht'] ?? null,
|
||||
], fn (?string $value): bool => $value !== null && $value !== ''),
|
||||
'issue' => $issue,
|
||||
'subissue' => $subissue,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $form
|
||||
* @return ?array{key: string, label: string}
|
||||
*/
|
||||
private function issueEntry(array $form, ?string $key): ?array
|
||||
{
|
||||
foreach ((array) $form['issues'] as $issue) {
|
||||
if ($issue['key'] === $key) {
|
||||
return ['key' => $issue['key'], 'label' => $issue['label']];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $form
|
||||
* @return ?array{key: string, label: string}
|
||||
*/
|
||||
private function subissueEntry(array $form, ?string $issue, ?string $key): ?array
|
||||
{
|
||||
foreach ((array) $form['issues'] as $top) {
|
||||
if ($top['key'] !== $issue) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($top['children'] as $child) {
|
||||
if ($child['key'] === $key) {
|
||||
return ['key' => $child['key'], 'label' => $child['label']];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function reference(): string
|
||||
{
|
||||
do {
|
||||
$reference = 'LF-'.now()->format('ymd').'-'.Str::upper(substr(str_replace(['0', 'O', '1', 'I', 'L'], '', Str::upper(Str::random(12))), 0, 5));
|
||||
} while (strlen($reference) < 12 || Inquiry::query()->where('reference', $reference)->exists());
|
||||
|
||||
return $reference;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
enum InquiryStatus: string
|
||||
{
|
||||
case Neu = 'neu';
|
||||
case InBearbeitung = 'in_bearbeitung';
|
||||
case RueckfrageOffen = 'rueckfrage_offen';
|
||||
case Erledigt = 'erledigt';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Neu => 'Neu',
|
||||
self::InBearbeitung => 'In Bearbeitung',
|
||||
self::RueckfrageOffen => 'Rückfrage offen',
|
||||
self::Erledigt => 'Erledigt',
|
||||
};
|
||||
}
|
||||
|
||||
public function color(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Neu => 'warning',
|
||||
self::InBearbeitung => 'info',
|
||||
self::RueckfrageOffen => 'danger',
|
||||
self::Erledigt => 'success',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @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,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Anfragevorlage: bearbeitbarer Entwurf (draft) und unveränderliche, veröffentlichte Fassungen.
|
||||
*/
|
||||
class InquiryTemplate extends Model
|
||||
{
|
||||
protected $fillable = ['key', 'name', 'description', 'draft', 'published_version_id', 'archived_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['draft' => 'array', 'archived_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(InquiryTemplateVersion::class, 'template_id')->orderByDesc('version');
|
||||
}
|
||||
|
||||
public function publishedVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InquiryTemplateVersion::class, 'published_version_id');
|
||||
}
|
||||
|
||||
public function entries(): HasMany
|
||||
{
|
||||
return $this->hasMany(InquiryEntry::class, 'template_id');
|
||||
}
|
||||
|
||||
public function isPublished(): bool
|
||||
{
|
||||
return $this->published_version_id !== null;
|
||||
}
|
||||
|
||||
/** Ob der Entwurf von der veröffentlichten Fassung abweicht. */
|
||||
public function hasUnpublishedChanges(): bool
|
||||
{
|
||||
$version = $this->publishedVersion;
|
||||
|
||||
return $version === null || FormJson::normalize($version->source) !== FormJson::normalize((array) $this->draft);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function emptyDraft(): array
|
||||
{
|
||||
return [
|
||||
'texts' => [],
|
||||
'issues' => [],
|
||||
'steps' => [],
|
||||
'rules' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Unveränderliche Fassung einer Anfragevorlage. definition ist vollständig aufgelöst (Bezeichnungen, Auswahlwerte,
|
||||
* Regeln); source ist der bearbeitbare Entwurf, aus dem sie entstand. Eine Fassung wird nie geändert.
|
||||
*/
|
||||
class InquiryTemplateVersion extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = ['template_id', 'version', 'definition', 'source', 'note', 'published_by', 'published_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['definition' => 'array', 'source' => 'array', 'published_at' => 'datetime', 'version' => 'integer'];
|
||||
}
|
||||
|
||||
public function template(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(InquiryTemplate::class, 'template_id');
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
// Nur die Bemerkung darf nachträglich ergänzt werden; Löschen ist ausgeschlossen.
|
||||
static::updating(fn (self $version): bool => array_diff(array_keys($version->getDirty()), ['note']) === []);
|
||||
static::deleting(fn (): bool => false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Stabile technische Kennungen für Anliegen, Felder, Gruppen und Auswahlwerte. Eine Kennung entsteht einmal aus der
|
||||
* Bezeichnung und ändert sich nie; die öffentliche Bezeichnung darf sich ändern (ADR-60).
|
||||
*/
|
||||
final class Keys
|
||||
{
|
||||
public const PATTERN = '/^[a-z][a-z0-9_]{1,59}$/';
|
||||
|
||||
/** Kennungen der eingebauten Anliegen-Felder; Felder des Katalogs dürfen sie nicht belegen. */
|
||||
public const RESERVED = ['anliegen', 'unteranliegen'];
|
||||
|
||||
public static function valid(mixed $key): bool
|
||||
{
|
||||
return is_string($key) && preg_match(self::PATTERN, $key) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt aus einer Bezeichnung eine freie Kennung. $taken enthält bereits vergebene Kennungen.
|
||||
*
|
||||
* @param list<string> $taken
|
||||
*/
|
||||
public static function from(string $label, array $taken = []): string
|
||||
{
|
||||
$base = Str::slug($label, '_', 'de');
|
||||
$base = preg_replace('/^[^a-z]+/', '', $base) ?? '';
|
||||
$base = substr($base, 0, 50);
|
||||
|
||||
if (strlen($base) < 2) {
|
||||
$base = 'eintrag';
|
||||
}
|
||||
|
||||
$taken = array_merge($taken, self::RESERVED);
|
||||
$key = $base;
|
||||
$n = 2;
|
||||
|
||||
while (in_array($key, $taken, true)) {
|
||||
$key = $base.'_'.$n++;
|
||||
}
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ergänzt fehlende oder doppelte Kennungen von Auswahlwerten. Bestehende, gültige Kennungen bleiben unverändert,
|
||||
* damit gespeicherte Antworten und Bedingungen gültig bleiben, auch wenn eine Bezeichnung umbenannt wird.
|
||||
*
|
||||
* @param array<int|string, mixed> $options
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public static function withKeys(array $options): array
|
||||
{
|
||||
$result = [];
|
||||
$taken = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$key = is_array($option) ? ($option['key'] ?? null) : null;
|
||||
|
||||
if (self::valid($key) && ! in_array($key, $taken, true)) {
|
||||
$taken[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($options as $option) {
|
||||
$option = is_array($option) ? $option : [];
|
||||
$label = trim((string) ($option['label'] ?? ''));
|
||||
|
||||
if ($label === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = $option['key'] ?? null;
|
||||
|
||||
if (! self::valid($key) || in_array($key, array_column($result, 'key'), true)) {
|
||||
$key = self::from($label, array_merge($taken, array_column($result, 'key')));
|
||||
$taken[] = $key;
|
||||
}
|
||||
|
||||
$result[] = ['key' => $key, 'label' => mb_substr($label, 0, 120)];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* Veröffentlichung von Anfragevorlagen und Anfrage-Einstiegen (ADR-60).
|
||||
*
|
||||
* Eine Vorlage wird als neue, unveränderliche Fassung veröffentlicht; bis dahin gilt die bisherige Fassung. Ein Einstieg
|
||||
* veröffentlicht seine Konfiguration gegen die aktuell gültige Fassung seiner Vorlage. Wirksam ist immer nur ein
|
||||
* bewusst veröffentlichter Stand, nie ein Entwurf.
|
||||
*/
|
||||
final class Publisher
|
||||
{
|
||||
public function __construct(private readonly TemplateCompiler $compiler, private readonly FormFactory $factory) {}
|
||||
|
||||
/**
|
||||
* Einstiege, die von einer neuen Fassung betroffen sind, samt Befund gegen die neue Fassung.
|
||||
*
|
||||
* @param array<string, mixed> $definition
|
||||
* @return list<array{entry: InquiryEntry, problems: list<string>}>
|
||||
*/
|
||||
public function affected(InquiryTemplate $template, ?array $definition = null): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($template->entries()->whereNull('archived_at')->orderBy('name')->get() as $entry) {
|
||||
$problems = $definition !== null && $entry->published_config !== null
|
||||
? $this->factory->problems($definition, (array) $entry->published_config)
|
||||
: [];
|
||||
|
||||
$result[] = ['entry' => $entry, 'problems' => $problems];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlicht den Entwurf der Vorlage als neue Fassung.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function publishTemplate(InquiryTemplate $template, ?User $by = null, ?string $note = null): InquiryTemplateVersion
|
||||
{
|
||||
$compiled = $this->compiler->compile((array) $template->draft);
|
||||
|
||||
if ($compiled['definition'] === null) {
|
||||
throw ValidationException::withMessages(['draft' => $compiled['errors']]);
|
||||
}
|
||||
|
||||
$blocking = [];
|
||||
foreach ($this->affected($template, $compiled['definition']) as $row) {
|
||||
if ($row['entry']->published_config !== null && $row['problems'] !== []) {
|
||||
$blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zur neuen Fassung: '.implode(' ', $row['problems']);
|
||||
}
|
||||
}
|
||||
|
||||
if ($blocking !== []) {
|
||||
throw ValidationException::withMessages(['draft' => $blocking]);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($template, $compiled, $by, $note): InquiryTemplateVersion {
|
||||
$template = InquiryTemplate::query()->lockForUpdate()->findOrFail($template->id);
|
||||
$next = (int) InquiryTemplateVersion::query()->where('template_id', $template->id)->max('version') + 1;
|
||||
|
||||
$version = InquiryTemplateVersion::query()->create([
|
||||
'template_id' => $template->id,
|
||||
'version' => $next,
|
||||
'definition' => $compiled['definition'],
|
||||
'source' => (array) $template->draft,
|
||||
'note' => $note !== null && trim($note) !== '' ? mb_substr(trim($note), 0, 300) : null,
|
||||
'published_by' => $by?->id,
|
||||
'published_at' => now(),
|
||||
]);
|
||||
|
||||
$template->forceFill(['published_version_id' => $version->id])->save();
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt eine frühere Fassung wieder in Kraft (Rückkehr zu einer gültigen Konfiguration). Betroffene Einstiege
|
||||
* müssen zur Fassung passen, sonst wird abgelehnt.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function restoreVersion(InquiryTemplate $template, InquiryTemplateVersion $version): void
|
||||
{
|
||||
abort_unless($version->template_id === $template->id, 404);
|
||||
|
||||
$blocking = [];
|
||||
foreach ($this->affected($template, (array) $version->definition) as $row) {
|
||||
if ($row['entry']->published_config !== null && $row['problems'] !== []) {
|
||||
$blocking[] = 'Der veröffentlichte Einstieg „'.$row['entry']->name.'“ passt nicht zu dieser Fassung: '.implode(' ', $row['problems']);
|
||||
}
|
||||
}
|
||||
|
||||
if ($blocking !== []) {
|
||||
throw ValidationException::withMessages(['draft' => $blocking]);
|
||||
}
|
||||
|
||||
$template->forceFill(['published_version_id' => $version->id])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlicht die Konfiguration eines Einstiegs.
|
||||
*
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public function publishEntry(InquiryEntry $entry): void
|
||||
{
|
||||
$template = $entry->template()->with('publishedVersion')->firstOrFail();
|
||||
|
||||
if ($template->publishedVersion === null) {
|
||||
throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist noch nicht veröffentlicht. Ein Einstieg kann nur eine veröffentlichte Vorlage verwenden.']]);
|
||||
}
|
||||
|
||||
if ($template->archived_at !== null) {
|
||||
throw ValidationException::withMessages(['config' => ['Die Anfragevorlage „'.$template->name.'“ ist archiviert.']]);
|
||||
}
|
||||
|
||||
$problems = $this->factory->problems((array) $template->publishedVersion->definition, (array) $entry->config);
|
||||
|
||||
if ($problems !== []) {
|
||||
throw ValidationException::withMessages(['config' => $problems]);
|
||||
}
|
||||
|
||||
$entry->forceFill([
|
||||
'published_config' => $entry->config,
|
||||
'published_at' => $entry->published_at ?? now(),
|
||||
'archived_at' => null,
|
||||
])->save();
|
||||
}
|
||||
|
||||
/** Nimmt einen Einstieg aus dem öffentlichen Angebot; die Konfiguration bleibt erhalten. */
|
||||
public function withdrawEntry(InquiryEntry $entry): void
|
||||
{
|
||||
$entry->forceFill(['published_config' => null, 'published_at' => null])->save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Eine Einsendung wurde zurückgewiesen. fields: Feldkennung => Meldung. Der Code entspricht dem HTTP-Status.
|
||||
*/
|
||||
final class SubmissionException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $fields
|
||||
*/
|
||||
public function __construct(string $message, public readonly array $fields = [], int $code = 422)
|
||||
{
|
||||
parent::__construct($message, $code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Übersetzt den bearbeitbaren Entwurf einer Anfragevorlage in eine vollständig aufgelöste Definition (Fassung) und prüft
|
||||
* dabei die Konfiguration: Verweise, doppelte Verwendung, Regeln und deren Reihenfolge. Kein Skript, keine freien
|
||||
* Ausdrücke: Regeln sind Daten aus einer festen Menge von Operatoren und Wirkungen (ADR-60).
|
||||
*
|
||||
* Entwurf: {texts, issues[Kennungen oberster Anliegen], steps[{key,title,intro,items[{kind,...}]}], rules[...]}
|
||||
* Reihenfolge ist Dokumentreihenfolge: Schritte, darin Bausteine, darin Felder. Eine Bedingung darf nur auf Felder
|
||||
* verweisen, die vor ihrem Ziel stehen; damit sind Zyklen ausgeschlossen.
|
||||
*/
|
||||
final class TemplateCompiler
|
||||
{
|
||||
public const EFFECTS = [
|
||||
'show' => 'Anzeigen, wenn …',
|
||||
'hide' => 'Ausblenden, wenn …',
|
||||
'require' => 'Pflichtfeld, wenn …',
|
||||
'skip' => 'Schritt überspringen, wenn …',
|
||||
'preset' => 'Vorbelegen, wenn …',
|
||||
];
|
||||
|
||||
public const OPERATORS = [
|
||||
'eq' => 'ist',
|
||||
'neq' => 'ist nicht',
|
||||
'in' => 'ist eines von',
|
||||
'not_in' => 'ist keines von',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $draft
|
||||
* @return array{definition: ?array<string, mixed>, errors: list<string>}
|
||||
*/
|
||||
public function compile(array $draft): array
|
||||
{
|
||||
$errors = [];
|
||||
|
||||
$fieldsByKey = InquiryField::query()->offered()->get()->keyBy('key');
|
||||
$groupsByKey = InquiryFieldGroup::query()->offered()->get()->keyBy('key');
|
||||
$tree = $this->issueTree((array) ($draft['issues'] ?? []));
|
||||
|
||||
$steps = [];
|
||||
$fields = [];
|
||||
$usedFields = [];
|
||||
$usedGroups = [];
|
||||
$hasIssue = false;
|
||||
$position = [];
|
||||
$order = 0;
|
||||
$stepKeys = [];
|
||||
|
||||
foreach (array_values((array) ($draft['steps'] ?? [])) as $index => $step) {
|
||||
$number = $index + 1;
|
||||
$step = is_array($step) ? $step : [];
|
||||
$key = (string) ($step['key'] ?? '');
|
||||
$title = trim((string) ($step['title'] ?? ''));
|
||||
|
||||
if (! Keys::valid($key) && ! preg_match('/^s[a-z0-9]{3,12}$/', $key)) {
|
||||
$key = 's'.substr(md5($number.'|'.$title), 0, 6);
|
||||
}
|
||||
|
||||
if (in_array($key, $stepKeys, true)) {
|
||||
$errors[] = "Schritt $number: Die Kennung des Schritts kommt doppelt vor.";
|
||||
}
|
||||
|
||||
$stepKeys[] = $key;
|
||||
|
||||
if ($title === '') {
|
||||
$title = "Schritt $number";
|
||||
}
|
||||
|
||||
$position["step:$key"] = $order++;
|
||||
$items = [];
|
||||
|
||||
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
|
||||
$item = is_array($item) ? $item : [];
|
||||
$kind = (string) ($item['kind'] ?? '');
|
||||
|
||||
if ($kind === 'issue') {
|
||||
if ($hasIssue) {
|
||||
$errors[] = "Schritt $number („{$title}“): Die Auswahl des Anliegens darf nur einmal vorkommen.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$hasIssue = true;
|
||||
$position['field:anliegen'] = $order++;
|
||||
$position['field:unteranliegen'] = $order++;
|
||||
$items[] = ['kind' => 'issue'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($kind === 'group') {
|
||||
$groupKey = (string) ($item['group'] ?? '');
|
||||
$group = $groupsByKey[$groupKey] ?? null;
|
||||
|
||||
if ($group === null) {
|
||||
$errors[] = "Schritt $number („{$title}“): Eine Feldgruppe ist nicht mehr verfügbar (gelöscht, deaktiviert oder archiviert).";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($usedGroups[$groupKey])) {
|
||||
$errors[] = "Die Feldgruppe „{$group->name}“ ist mehrfach eingebunden.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$usedGroups[$groupKey] = true;
|
||||
$position["group:$groupKey"] = $order++;
|
||||
$rows = [];
|
||||
|
||||
foreach ($group->itemList() as $row) {
|
||||
$field = $fieldsByKey[$row['field']] ?? null;
|
||||
|
||||
if ($field === null) {
|
||||
$errors[] = "Die Feldgruppe „{$group->name}“ verwendet ein Feld, das nicht mehr verfügbar ist.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($usedFields[$field->key])) {
|
||||
$errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$usedFields[$field->key] = true;
|
||||
$fields[$field->key] = $field->snapshot();
|
||||
$position['field:'.$field->key] = $order++;
|
||||
$rows[] = ['field' => $field->key, 'required' => $row['required']];
|
||||
}
|
||||
|
||||
$items[] = [
|
||||
'kind' => 'group',
|
||||
'key' => $group->key,
|
||||
'label' => $group->label ?: $group->name,
|
||||
'description' => $group->description,
|
||||
'fields' => $rows,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($kind === 'field') {
|
||||
$field = $fieldsByKey[(string) ($item['field'] ?? '')] ?? null;
|
||||
|
||||
if ($field === null) {
|
||||
$errors[] = "Schritt $number („{$title}“): Ein Einzelfeld ist nicht mehr verfügbar.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($usedFields[$field->key])) {
|
||||
$errors[] = "Das Feld „{$field->name}“ kommt mehrfach in der Vorlage vor.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$usedFields[$field->key] = true;
|
||||
$fields[$field->key] = $field->snapshot();
|
||||
$position['field:'.$field->key] = $order++;
|
||||
$items[] = [
|
||||
'kind' => 'group',
|
||||
'key' => null,
|
||||
'label' => null,
|
||||
'description' => null,
|
||||
'fields' => [['field' => $field->key, 'required' => (bool) ($item['required'] ?? false)]],
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$errors[] = "Schritt $number („{$title}“): Ein Baustein hat keinen gültigen Typ.";
|
||||
}
|
||||
|
||||
if ($items === []) {
|
||||
$errors[] = "Schritt $number („{$title}“) enthält nichts.";
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'key' => $key,
|
||||
'title' => mb_substr($title, 0, 120),
|
||||
'intro' => $this->text($step['intro'] ?? null, 600),
|
||||
'items' => $items,
|
||||
];
|
||||
}
|
||||
|
||||
if ($steps === []) {
|
||||
$errors[] = 'Die Vorlage hat noch keinen Schritt.';
|
||||
}
|
||||
|
||||
$purposes = [];
|
||||
foreach ($fields as $field) {
|
||||
if ($field['purpose'] !== null) {
|
||||
$purposes[$field['purpose']][] = $field['key'];
|
||||
}
|
||||
}
|
||||
|
||||
if (! isset($purposes[FieldPurpose::Email->value])) {
|
||||
$errors[] = 'Die Vorlage braucht ein Feld mit der Verwendung „E-Mail-Adresse für Rückfragen“, sonst lässt sich eine Anfrage nicht beantworten.';
|
||||
}
|
||||
|
||||
foreach ($purposes as $purpose => $keys) {
|
||||
if (count($keys) > 1) {
|
||||
$errors[] = 'Die Verwendung „'.FieldPurpose::from($purpose)->label().'“ ist mehreren Feldern zugeordnet.';
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasIssue && $tree === []) {
|
||||
$errors[] = 'Die Auswahl des Anliegens hat kein verfügbares Anliegen. Bitte Anliegen anlegen oder aktivieren.';
|
||||
}
|
||||
|
||||
$rules = $this->rules((array) ($draft['rules'] ?? []), $fields, $tree, $hasIssue, $position, $stepKeys, $usedGroups, $errors);
|
||||
|
||||
$definition = [
|
||||
'v' => 1,
|
||||
'texts' => FormTexts::merge(FormTexts::clean((array) ($draft['texts'] ?? []))),
|
||||
'has_issue' => $hasIssue,
|
||||
'issues' => $hasIssue ? $tree : [],
|
||||
'fields' => $fields,
|
||||
'steps' => $steps,
|
||||
'rules' => $rules,
|
||||
];
|
||||
|
||||
return ['definition' => $errors === [] ? $definition : null, 'errors' => array_values(array_unique($errors))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollständige Auflösung ohne Fehlerfreiheit: für die Vorschau eines unfertigen Entwurfs.
|
||||
*
|
||||
* @param array<string, mixed> $draft
|
||||
* @return array{definition: ?array<string, mixed>, errors: list<string>}
|
||||
*/
|
||||
public function preview(array $draft): array
|
||||
{
|
||||
return $this->compile($draft);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $only
|
||||
* @return list<array{key: string, label: string, description: ?string, children: list<array{key: string, label: string, description: ?string}>}>
|
||||
*/
|
||||
private function issueTree(array $only): array
|
||||
{
|
||||
$tree = InquiryIssue::tree();
|
||||
|
||||
if ($only === []) {
|
||||
return $tree;
|
||||
}
|
||||
|
||||
return array_values(array_filter($tree, fn (array $issue): bool => in_array($issue['key'], $only, true)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int|string, mixed> $rules
|
||||
* @param array<string, array<string, mixed>> $fields
|
||||
* @param list<array<string, mixed>> $tree
|
||||
* @param array<string, int> $position
|
||||
* @param list<string> $stepKeys
|
||||
* @param array<string, true> $usedGroups
|
||||
* @param list<string> $errors
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function rules(array $rules, array $fields, array $tree, bool $hasIssue, array $position, array $stepKeys, array $usedGroups, array &$errors): array
|
||||
{
|
||||
$normalized = [];
|
||||
$issueKeys = array_column($tree, 'key');
|
||||
$subKeys = [];
|
||||
foreach ($tree as $issue) {
|
||||
foreach ($issue['children'] as $child) {
|
||||
$subKeys[] = $child['key'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array_values($rules) as $index => $rule) {
|
||||
$number = $index + 1;
|
||||
$rule = is_array($rule) ? $rule : [];
|
||||
$effect = (string) ($rule['effect'] ?? '');
|
||||
$target = (string) ($rule['target'] ?? '');
|
||||
|
||||
if (! isset(self::EFFECTS[$effect])) {
|
||||
$errors[] = "Regel $number: Die Wirkung ist ungültig.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
[$targetKind] = array_pad(explode(':', $target, 2), 2, '');
|
||||
|
||||
if (! isset($position[$target])) {
|
||||
$errors[] = "Regel $number: Das Ziel „{$target}“ gibt es in dieser Vorlage nicht.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$kindOk = match ($effect) {
|
||||
'show', 'hide' => in_array($targetKind, ['group', 'field'], true),
|
||||
'require', 'preset' => $targetKind === 'field',
|
||||
'skip' => $targetKind === 'step',
|
||||
default => false,
|
||||
};
|
||||
|
||||
if (! $kindOk) {
|
||||
$errors[] = "Regel $number: Die Wirkung „".self::EFFECTS[$effect].'“ passt nicht zum Ziel.';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($target, ['field:anliegen', 'field:unteranliegen'], true)) {
|
||||
$errors[] = "Regel $number: Die Auswahl des Anliegens lässt sich nicht durch eine Regel steuern.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$presetValue = null;
|
||||
if ($effect === 'preset') {
|
||||
$field = $fields[substr($target, 6)] ?? null;
|
||||
$presetValue = $rule['value'] ?? null;
|
||||
|
||||
if ($field === null || ! in_array($field['type'], ['select', 'boolean'], true)) {
|
||||
$errors[] = "Regel $number: Vorbelegt werden können nur Einfachauswahl- und Ja/Nein-Felder.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$valid = array_column($field['options'] ?: [['key' => 'ja'], ['key' => 'nein']], 'key');
|
||||
if ($field['type'] === 'boolean') {
|
||||
$valid = ['ja', 'nein'];
|
||||
}
|
||||
|
||||
if (! is_string($presetValue) || ! in_array($presetValue, $valid, true)) {
|
||||
$errors[] = "Regel $number: Der Wert zum Vorbelegen ist kein Auswahlwert des Feldes.";
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
$match = ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all';
|
||||
$conditions = [];
|
||||
|
||||
foreach (array_values((array) ($rule['conditions'] ?? [])) as $c => $condition) {
|
||||
$condition = is_array($condition) ? $condition : [];
|
||||
$source = (string) ($condition['source'] ?? '');
|
||||
$op = (string) ($condition['op'] ?? 'eq');
|
||||
$values = array_values(array_filter((array) ($condition['values'] ?? []), fn (mixed $v): bool => is_string($v) && $v !== ''));
|
||||
|
||||
if (! isset(self::OPERATORS[$op])) {
|
||||
$errors[] = "Regel $number, Bedingung ".($c + 1).': Der Vergleich ist ungültig.';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($op, ['eq', 'neq'], true)) {
|
||||
$values = array_slice($values, 0, 1);
|
||||
}
|
||||
|
||||
if ($values === []) {
|
||||
$errors[] = "Regel $number, Bedingung ".($c + 1).': Es fehlt ein Vergleichswert.';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$sourceKey = "field:$source";
|
||||
|
||||
if ($source === 'anliegen' || $source === 'unteranliegen') {
|
||||
if (! $hasIssue) {
|
||||
$errors[] = "Regel $number: Die Vorlage hat keine Auswahl des Anliegens.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$valid = $source === 'anliegen' ? $issueKeys : $subKeys;
|
||||
} else {
|
||||
$field = $fields[$source] ?? null;
|
||||
|
||||
if ($field === null || ! isset($position[$sourceKey])) {
|
||||
$errors[] = "Regel $number: Die Bedingung bezieht sich auf ein Feld, das es in der Vorlage nicht gibt.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! FieldType::from($field['type'])->canControl()) {
|
||||
$errors[] = "Regel $number: Bedingungen sind nur für Auswahlfelder und Ja/Nein-Felder möglich („{$field['label']}“).";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$valid = $field['type'] === 'boolean' ? ['ja', 'nein'] : array_column($field['options'], 'key');
|
||||
}
|
||||
|
||||
if (array_diff($values, $valid) !== []) {
|
||||
$errors[] = "Regel $number: Ein Vergleichswert ist kein Auswahlwert von „{$source}“.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($position[$sourceKey] >= $position[$target]) {
|
||||
$errors[] = "Regel $number: Die Bedingung „{$source}“ muss in der Vorlage vor ihrem Ziel stehen, sonst kann sie noch nicht ausgewertet werden.";
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$conditions[] = ['source' => $source, 'op' => $op, 'values' => $values];
|
||||
}
|
||||
|
||||
if ($conditions === [] || count($conditions) !== count((array) ($rule['conditions'] ?? []))) {
|
||||
if ($conditions === []) {
|
||||
$errors[] = "Regel $number hat keine gültige Bedingung.";
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[] = [
|
||||
'effect' => $effect,
|
||||
'target' => $target,
|
||||
'match' => $match,
|
||||
'conditions' => $conditions,
|
||||
'value' => $presetValue,
|
||||
];
|
||||
}
|
||||
|
||||
// Widersprüche: gleiche Bedingung zeigt und blendet dasselbe Ziel aus.
|
||||
$seen = [];
|
||||
foreach ($normalized as $rule) {
|
||||
if (! in_array($rule['effect'], ['show', 'hide'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$signature = json_encode([$rule['target'], $rule['match'], $rule['conditions']]);
|
||||
$opposite = $rule['effect'] === 'show' ? 'hide' : 'show';
|
||||
|
||||
if (isset($seen[$opposite][$signature])) {
|
||||
$errors[] = 'Widerspruch: Das Ziel „'.$rule['target'].'“ wird unter derselben Bedingung angezeigt und ausgeblendet.';
|
||||
}
|
||||
|
||||
$seen[$rule['effect']][$signature] = true;
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
private function text(mixed $value, int $max): ?string
|
||||
{
|
||||
if (! is_string($value) || trim($value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return mb_substr(trim($value), 0, $max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Communication;
|
||||
|
||||
/**
|
||||
* Bereinigt den Entwurf einer Anfragevorlage aus dem Formular der Verwaltung: Listen mit fortlaufenden Schlüsseln
|
||||
* (Repeater liefern Zufallsschlüssel), nur bekannte Felder, Texte begrenzt. Eine inhaltliche Prüfung geschieht erst beim
|
||||
* Veröffentlichen (TemplateCompiler); ein unfertiger Entwurf darf gespeichert werden.
|
||||
*/
|
||||
final class TemplateDraft
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $draft
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function clean(array $draft): array
|
||||
{
|
||||
$steps = [];
|
||||
|
||||
foreach (array_values((array) ($draft['steps'] ?? [])) as $step) {
|
||||
$step = is_array($step) ? $step : [];
|
||||
$items = [];
|
||||
|
||||
foreach (array_values((array) ($step['items'] ?? [])) as $item) {
|
||||
$item = is_array($item) ? $item : [];
|
||||
$kind = (string) ($item['kind'] ?? '');
|
||||
|
||||
$items[] = match ($kind) {
|
||||
'issue' => ['kind' => 'issue'],
|
||||
'group' => ['kind' => 'group', 'group' => (string) ($item['group'] ?? '')],
|
||||
'field' => ['kind' => 'field', 'field' => (string) ($item['field'] ?? ''), 'required' => (bool) ($item['required'] ?? false)],
|
||||
default => ['kind' => $kind],
|
||||
};
|
||||
}
|
||||
|
||||
$steps[] = [
|
||||
'key' => (string) ($step['key'] ?? ''),
|
||||
'title' => mb_substr(trim((string) ($step['title'] ?? '')), 0, 120),
|
||||
'intro' => filled($step['intro'] ?? null) ? mb_substr(trim((string) $step['intro']), 0, 600) : null,
|
||||
'items' => $items,
|
||||
];
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
|
||||
foreach (array_values((array) ($draft['rules'] ?? [])) as $rule) {
|
||||
$rule = is_array($rule) ? $rule : [];
|
||||
$conditions = [];
|
||||
|
||||
foreach (array_values((array) ($rule['conditions'] ?? [])) as $condition) {
|
||||
$condition = is_array($condition) ? $condition : [];
|
||||
$conditions[] = [
|
||||
'source' => (string) ($condition['source'] ?? ''),
|
||||
'op' => (string) ($condition['op'] ?? 'eq'),
|
||||
'values' => array_values(array_filter((array) ($condition['values'] ?? []), 'is_string')),
|
||||
];
|
||||
}
|
||||
|
||||
$rules[] = [
|
||||
'effect' => (string) ($rule['effect'] ?? ''),
|
||||
'target' => (string) ($rule['target'] ?? ''),
|
||||
'match' => ($rule['match'] ?? 'all') === 'any' ? 'any' : 'all',
|
||||
'conditions' => $conditions,
|
||||
'value' => filled($rule['value'] ?? null) ? (string) $rule['value'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'texts' => FormTexts::clean((array) ($draft['texts'] ?? [])),
|
||||
'issues' => array_values(array_filter((array) ($draft['issues'] ?? []), 'is_string')),
|
||||
'steps' => $steps,
|
||||
'rules' => $rules,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,11 @@ public function claim(User $user, Offer $offer): Acquisition
|
||||
throw new DomainRuleException('Dieses Angebot richtet sich nicht an Personen.');
|
||||
}
|
||||
|
||||
// Wer ein Angebot auf Abruf übernehmen darf, bestimmt seine Regel (ADR-56); „bei Registrierung“ kennt keine.
|
||||
if ($version->grant_kind === 'auf_abruf') {
|
||||
app(OfferAccess::class)->assertMayClaim($user, $offer);
|
||||
}
|
||||
|
||||
return $this->issue($user, $version, AcquisitionType::FreierAbruf, 'offer', $offer->id);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Entitlement;
|
||||
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Neue Stände zu Artikeln, die das Konto bereits besitzt („Neu für dich“, ADR-56).
|
||||
*
|
||||
* Nach der Updatepolitik (ADR-09, OPEN-01) stehen alle später veröffentlichten Stände desselben Artikels dem Inhaber
|
||||
* ohne Aufpreis zu, solange die Lizenz gilt. Sie erscheinen von selbst in der Bibliothek; diese Liste macht sie nur
|
||||
* sichtbar. Es wird nichts vergeben und nichts übernommen.
|
||||
*/
|
||||
class NewStands
|
||||
{
|
||||
/** So lange (in Tagen) nach der Veröffentlichung erscheint ein neuer Stand in der Liste. */
|
||||
public const DAYS = 90;
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{grant: Grant, title: string, number: int, since: CarbonInterface}>
|
||||
*/
|
||||
public function forUser(User $user): Collection
|
||||
{
|
||||
if ($user->party_id === null) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$limit = now()->subDays(self::DAYS);
|
||||
$titles = app(ProductOptions::class);
|
||||
|
||||
return Grant::query()
|
||||
->with(['article.currentRelease', 'releaseAtGrant'])
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhere('valid_until', '>', now()))
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $user->party_id))
|
||||
->whereHas('article', fn ($query) => $query->whereNull('archived_at'))
|
||||
->orderByDesc('id')
|
||||
->get()
|
||||
->filter(function (Grant $grant) use ($limit): bool {
|
||||
$current = $grant->article?->currentRelease;
|
||||
$had = $grant->releaseAtGrant;
|
||||
|
||||
return $current instanceof ArticleRelease
|
||||
&& $had instanceof ArticleRelease
|
||||
&& (int) $current->number > (int) $had->number
|
||||
&& $current->created_at !== null
|
||||
&& $current->created_at->greaterThanOrEqualTo($limit);
|
||||
})
|
||||
->unique('license_article_id')
|
||||
->map(fn (Grant $grant): array => [
|
||||
'grant' => $grant,
|
||||
'title' => $titles->articleTitle($grant->article),
|
||||
'number' => (int) $grant->article->currentRelease->number,
|
||||
'since' => $grant->article->currentRelease->created_at,
|
||||
])
|
||||
->values();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Entitlement;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferRelease;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Wer ein Angebot „auf Abruf“ in die Bibliothek übernehmen darf (ADR-56). Drei Regeln, serverseitig beim Abruf geprüft:
|
||||
* alle angemeldeten Mitglieder, nur ausdrücklich freigeschaltete Konten (Freigabe je Angebot und Konto, wie bei
|
||||
* Rabattcodes, nie gelöscht, nur entzogen) oder Mitglieder, die einen bestimmten anderen Artikel besitzen.
|
||||
*
|
||||
* Die Regel gilt nur für Vergaben „auf Abruf“. „Bei Registrierung“ geht automatisch an neue Konten; Kauf ist Sache der
|
||||
* Kasse. Die Regel begründet keinen Zugang, sie begrenzt nur den freien Abruf.
|
||||
*/
|
||||
class OfferAccess
|
||||
{
|
||||
public const ALL = 'alle';
|
||||
|
||||
public const RELEASED = 'konten';
|
||||
|
||||
public const OWNERS = 'besitz';
|
||||
|
||||
public const OPTIONS = [
|
||||
self::ALL => 'Alle angemeldeten Mitglieder',
|
||||
self::RELEASED => 'Nur freigeschaltete Konten',
|
||||
self::OWNERS => 'Mitglieder, die einen bestimmten Artikel besitzen',
|
||||
];
|
||||
|
||||
public function __construct(private readonly OfferService $offers) {}
|
||||
|
||||
/**
|
||||
* Die Regel eines Angebots festlegen. Der Artikel ist nur bei „besitzt einen Artikel“ gesetzt.
|
||||
*/
|
||||
public function setRule(Offer $offer, string $access, ?int $articleId = null): void
|
||||
{
|
||||
if (! array_key_exists($access, self::OPTIONS)) {
|
||||
throw new DomainRuleException('Diese Regel für den Abruf gibt es nicht.');
|
||||
}
|
||||
|
||||
if ($access === self::OWNERS) {
|
||||
$article = $articleId === null ? null : LicenseArticle::query()->whereNull('archived_at')->find($articleId);
|
||||
|
||||
if ($article === null) {
|
||||
throw new DomainRuleException('Für diese Regel braucht es einen vorhandenen, nicht archivierten Lizenzartikel.');
|
||||
}
|
||||
} else {
|
||||
$articleId = null;
|
||||
}
|
||||
|
||||
$offer->claim_access = $access;
|
||||
$offer->claim_requires_article_id = $articleId;
|
||||
$offer->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Warum das Konto das Angebot nicht abrufen darf; null, wenn es das darf. Regeln gelten nur für Vergaben „auf Abruf“.
|
||||
*/
|
||||
public function refusal(User $user, Offer $offer, ?CarbonInterface $now = null): ?string
|
||||
{
|
||||
$now ??= now();
|
||||
$version = $this->activeVersion($offer);
|
||||
|
||||
if ($version === null || ! in_array($version->grant_kind, ['auf_abruf', 'bei_registrierung'], true) || $version->holder_kind !== 'person') {
|
||||
return 'Dieses Angebot wird nicht frei vergeben.';
|
||||
}
|
||||
|
||||
if ($user->party_id === null) {
|
||||
return 'Nur ein Mitgliedskonto kann ein Angebot abrufen.';
|
||||
}
|
||||
|
||||
// „Bei Registrierung“ geht automatisch an neue Konten und kennt keine Regel.
|
||||
if ($version->grant_kind !== 'auf_abruf') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return match ((string) $offer->claim_access) {
|
||||
self::RELEASED => $this->activeRelease($offer, $user, $now) === null ? 'Dieses Angebot ist für dein Konto nicht freigeschaltet.' : null,
|
||||
self::OWNERS => $offer->claim_requires_article_id !== null && $this->owns($user, (int) $offer->claim_requires_article_id, $now) ? null : 'Dieses Angebot steht für dein Konto nicht zur Verfügung.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function mayClaim(User $user, Offer $offer, ?CarbonInterface $now = null): bool
|
||||
{
|
||||
return $this->refusal($user, $offer, $now) === null;
|
||||
}
|
||||
|
||||
public function assertMayClaim(User $user, Offer $offer): void
|
||||
{
|
||||
$reason = $this->refusal($user, $offer);
|
||||
|
||||
if ($reason !== null) {
|
||||
throw new DomainRuleException($reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Angebote auf Abruf, die das Konto jetzt übernehmen darf und noch nicht übernommen hat.
|
||||
*
|
||||
* @return Collection<int, Offer>
|
||||
*/
|
||||
public function claimable(User $user): Collection
|
||||
{
|
||||
if ($user->party_id === null) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$taken = Acquisition::query()
|
||||
->where('party_id', $user->party_id)
|
||||
->where('type', AcquisitionType::FreierAbruf)
|
||||
->where('reference_type', 'offer')
|
||||
->pluck('reference_id')
|
||||
->all();
|
||||
|
||||
return Offer::query()
|
||||
->whereHas('versions', fn ($query) => $query->where('status', OfferStatus::Aktiv)->where('holder_kind', 'person')->whereIn('grant_kind', ['auf_abruf', 'bei_registrierung']))
|
||||
->whereNotIn('id', $taken)
|
||||
->orderBy('name')
|
||||
->get()
|
||||
->filter(fn (Offer $offer): bool => $this->mayClaim($user, $offer))
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Konto für ein Angebot freischalten (Regel „nur freigeschaltete Konten“).
|
||||
*/
|
||||
public function release(Offer $offer, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): OfferRelease
|
||||
{
|
||||
if ($offer->claim_access !== self::RELEASED) {
|
||||
throw new DomainRuleException('Freigaben gibt es nur bei der Regel „nur freigeschaltete Konten“.');
|
||||
}
|
||||
|
||||
if ($member->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein Mitgliedskonto kann für ein Angebot freigeschaltet werden.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($offer, $member, $actor, $until, $reason): OfferRelease {
|
||||
Offer::query()->whereKey($offer->id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
if ($this->activeRelease($offer, $member) !== null) {
|
||||
throw new DomainRuleException('Dieses Konto ist für das Angebot bereits freigeschaltet.');
|
||||
}
|
||||
|
||||
if ($until !== null && $until->lessThanOrEqualTo(now())) {
|
||||
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
|
||||
}
|
||||
|
||||
return OfferRelease::query()->create([
|
||||
'offer_id' => $offer->id,
|
||||
'user_id' => $member->id,
|
||||
'granted_by' => $actor?->id,
|
||||
'granted_at' => now(),
|
||||
'valid_until' => $until,
|
||||
'reason' => filled($reason) ? trim((string) $reason) : null,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert; bereits übernommene Angebote
|
||||
* bleiben in der Bibliothek.
|
||||
*/
|
||||
public function revoke(OfferRelease $release, ?User $actor, ?string $reason = null): OfferRelease
|
||||
{
|
||||
return DB::transaction(function () use ($release, $actor, $reason): OfferRelease {
|
||||
$release = OfferRelease::query()->lockForUpdate()->findOrFail($release->id);
|
||||
|
||||
if ($release->revoked_at !== null) {
|
||||
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
|
||||
}
|
||||
|
||||
$release->forceFill([
|
||||
'revoked_at' => now(),
|
||||
'revoked_by' => $actor?->id,
|
||||
'reason' => filled($reason) ? trim((string) $reason) : $release->reason,
|
||||
])->save();
|
||||
|
||||
return $release;
|
||||
});
|
||||
}
|
||||
|
||||
public function activeRelease(Offer $offer, User $member, ?CarbonInterface $now = null): ?OfferRelease
|
||||
{
|
||||
$now ??= now();
|
||||
|
||||
return OfferRelease::query()
|
||||
->where('offer_id', $offer->id)
|
||||
->where('user_id', $member->id)
|
||||
->whereNull('revoked_at')
|
||||
->where('granted_at', '<=', $now)
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhere('valid_until', '>', $now))
|
||||
->first();
|
||||
}
|
||||
|
||||
/** Das Konto besitzt den Artikel, wenn seine Person eine aktive, gültige Berechtigung darauf hat. */
|
||||
public function owns(User $user, int $articleId, ?CarbonInterface $now = null): bool
|
||||
{
|
||||
$now ??= now();
|
||||
|
||||
if ($user->party_id === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Grant::query()
|
||||
->where('license_article_id', $articleId)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->where(fn ($query) => $query->whereNull('valid_from')->orWhere('valid_from', '<=', $now))
|
||||
->where(fn ($query) => $query->whereNull('valid_until')->orWhere('valid_until', '>', $now))
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $user->party_id))
|
||||
->exists();
|
||||
}
|
||||
|
||||
private function activeVersion(Offer $offer): ?OfferVersion
|
||||
{
|
||||
return $offer->versions()->where('status', OfferStatus::Aktiv)->orderByDesc('number')->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
/**
|
||||
* Bereitet ein Bild für das PDF auf: Es wird mit GD gelesen, auf eine druckbare Größe verkleinert, auf Weiß gesetzt
|
||||
* (Transparenz gibt es im PDF-Schreiber nicht) und als JPEG neu kodiert. So braucht das PDF keine Bildbibliothek und
|
||||
* keine Rücksicht auf das Ausgangsformat. Was GD nicht lesen kann (zum Beispiel WebP in einem Image ohne WebP-Unterstützung),
|
||||
* liefert null; die Ausgabe zeigt dann einen Hinweis statt des Bildes.
|
||||
*/
|
||||
final class PdfImage
|
||||
{
|
||||
/** Längste Kante in Pixel; 1400 Pixel genügen für die Spaltenbreite einer A4-Seite bei guter Druckqualität. */
|
||||
public const MAX_EDGE = 1400;
|
||||
|
||||
/**
|
||||
* @return array{jpeg: string, width: int, height: int}|null
|
||||
*/
|
||||
public static function fromBytes(string $raw): ?array
|
||||
{
|
||||
if ($raw === '' || ! function_exists('imagecreatefromstring')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$source = @imagecreatefromstring($raw);
|
||||
|
||||
if ($source === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
|
||||
if ($width < 1 || $height < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scale = min(1.0, self::MAX_EDGE / max($width, $height));
|
||||
$targetWidth = max(1, (int) round($width * $scale));
|
||||
$targetHeight = max(1, (int) round($height * $scale));
|
||||
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
|
||||
|
||||
if ($canvas === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
imagefill($canvas, 0, 0, (int) imagecolorallocate($canvas, 255, 255, 255));
|
||||
imagecopyresampled($canvas, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
|
||||
|
||||
ob_start();
|
||||
$written = imagejpeg($canvas, null, 82);
|
||||
$jpeg = (string) ob_get_clean();
|
||||
|
||||
return $written && $jpeg !== '' ? ['jpeg' => $jpeg, 'width' => $targetWidth, 'height' => $targetHeight] : null;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 966 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user