Compare commits
131
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9041afda80 | ||
|
|
1691bd3871 | ||
|
|
1270e2e948 | ||
|
|
18ee22f37e | ||
|
|
edca8e864c | ||
|
|
580b27451c | ||
|
|
561c64fa16 | ||
|
|
3aed45a2fe | ||
|
|
e72c9ddb8d | ||
|
|
9f9370dbf8 | ||
|
|
b942b5331a | ||
|
|
58b68b768c | ||
|
|
765b8e779e | ||
|
|
81037b9868 | ||
|
|
8a44c5886b | ||
|
|
3e2fd872c2 | ||
|
|
c57a506f85 | ||
|
|
219962daff | ||
|
|
390d61feaa | ||
|
|
90c74ac03d | ||
|
|
b714dc8219 | ||
|
|
b7502ef696 | ||
|
|
45ea56b52d | ||
|
|
09889da099 | ||
|
|
3c7a71532f | ||
|
|
ad581cb545 | ||
|
|
99122ddfee | ||
|
|
9fbd933e1e | ||
|
|
be24f3bf64 | ||
|
|
4584dcd013 | ||
|
|
cf8189623c | ||
|
|
9140e731f9 | ||
|
|
bb08b9b3fa | ||
|
|
e5b3eea7de | ||
|
|
b901b02cce | ||
|
|
79998f6347 | ||
|
|
26ca79cd22 | ||
|
|
bcda189267 | ||
|
|
bc140a0e83 | ||
|
|
ad03eee41f | ||
|
|
881703ba0e | ||
|
|
bbee288e69 | ||
|
|
d1f97a351a | ||
|
|
ef56befc0e | ||
|
|
0022fd50cb | ||
|
|
1d1f0ebb1f | ||
|
|
da02e0bbda | ||
|
|
3f9e463dfa | ||
|
|
03737a5fc7 | ||
|
|
b453a8be10 | ||
|
|
a3c159a729 | ||
|
|
b3fb619bda | ||
|
|
78c8870e4e | ||
|
|
dd3cc83057 | ||
|
|
32272e8e40 | ||
|
|
9db3a98440 | ||
|
|
f87e67ce02 | ||
|
|
fe39e1efb6 | ||
|
|
6518d1b80f | ||
|
|
69a22deb1f | ||
|
|
f0287eec2f | ||
|
|
42e0a6bb93 | ||
|
|
76fab81386 | ||
|
|
1ce2e1e51f | ||
|
|
0154182f3b | ||
|
|
cb80835c92 | ||
|
|
e7efb073da | ||
|
|
433f9aee61 | ||
|
|
bb0949dcd9 | ||
|
|
2d54d39c24 | ||
|
|
cf50d341f5 | ||
|
|
8b644292a7 | ||
|
|
0c4ef4c4ed | ||
|
|
2e6260acca | ||
|
|
8ecc1ecdaa | ||
|
|
9f070fbab2 | ||
|
|
ca0f68e8f6 | ||
|
|
aa1e6eb6ac | ||
|
|
05d487dd0b | ||
|
|
67614158e4 | ||
|
|
e0a3fdbb70 | ||
|
|
b8c5c68887 | ||
|
|
acb88e4a1d | ||
|
|
2a54347d50 | ||
|
|
992171bb7a | ||
|
|
8b59946bb1 | ||
|
|
061181f30d | ||
|
|
f54acd55e6 | ||
|
|
2ca7a8b268 | ||
|
|
cc890d9fc7 | ||
|
|
37056761a3 | ||
|
|
1413e0640f | ||
|
|
631502c064 | ||
|
|
4bc2e5871b | ||
|
|
1bc5356e84 | ||
|
|
2094961b6e | ||
|
|
7ef58e0e6e | ||
|
|
94eda30298 | ||
|
|
bff17a9e8e | ||
|
|
73126fec0c | ||
|
|
437bb394b2 | ||
|
|
5e28538551 | ||
|
|
be932c113a | ||
|
|
ef3af0e036 | ||
|
|
936c85ef5e | ||
|
|
c61869f8aa | ||
|
|
9f7c645baf | ||
|
|
08d03d0f56 | ||
|
|
ea4244487f | ||
|
|
fc40aba26c | ||
|
|
32837639e6 | ||
|
|
3825f53a9b | ||
|
|
604e1791c5 | ||
|
|
cd66561ca9 | ||
|
|
886715af96 | ||
|
|
05bd36509c | ||
|
|
96bb661239 | ||
|
|
340b898b7b | ||
|
|
9701777011 | ||
|
|
4520dba2f0 | ||
|
|
d49b178ebd | ||
|
|
da7ebca999 | ||
|
|
f72b79fd8c | ||
|
|
4e0760db1e | ||
|
|
6c8bbee363 | ||
|
|
7ad5929588 | ||
|
|
ed1f706d46 | ||
|
|
7c48a6480c | ||
|
|
d5c2b34b9d | ||
|
|
eb6192b067 | ||
|
|
061bc00564 |
No files matched your search
@@ -70,3 +70,8 @@ PAYMENT_DRIVER=test
|
||||
MEDIA_PUBLIC_PATH=
|
||||
MEDIA_DERIVED_PATH=
|
||||
MEDIA_ORIGINALS_PATH=
|
||||
|
||||
# Übernahme von Übungen aus Shinkan. Die Adresse ist je Umgebung vorgegeben. Der Zugangsschlüssel kann hier stehen (hat
|
||||
# Vorrang) oder in der Verwaltung hinterlegt werden (Inhalte -> Übungen aus Shinkan). Werte nie ins Repository.
|
||||
SHINKAN_DISTRIBUTION_URL=
|
||||
SHINKAN_DISTRIBUTION_KEY=
|
||||
@@ -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.
|
||||
@@ -63,6 +64,9 @@ ## Entwicklung
|
||||
## Verwaltungsoberfläche
|
||||
|
||||
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- 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,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Domain\Catalog\LegacyPillarAdoption;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
class AdoptLegacyPillars extends Command
|
||||
{
|
||||
protected $signature = 'luf:saeulen-uebernehmen {--dry-run : Nur berichten, nichts schreiben}';
|
||||
|
||||
protected $description = 'Übernimmt die alte Dimension „Fachliche Säule“ in die zentrale Säulenverwaltung und berichtet ungeklärte Fälle';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$report = (new LegacyPillarAdoption)->run($dryRun);
|
||||
|
||||
foreach (LegacyPillarAdoption::lines($report, $dryRun) as $line) {
|
||||
$this->line($line);
|
||||
}
|
||||
|
||||
return $report['unresolved'] === [] ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@ public function publishRelease(
|
||||
'content_element_version_id' => $row['version_id'],
|
||||
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
|
||||
'path' => $row['path'],
|
||||
'requirement' => $row['requirement'] ?? null,
|
||||
'variant_key' => $row['variant'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -141,6 +143,10 @@ private function checkedRows(ContentElementVersion|CompositionVersion $root): ar
|
||||
{
|
||||
$root->refresh();
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($root)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Er wird hier nicht veröffentlicht, damit nichts fehlt oder zu viel ausgegeben wird.');
|
||||
}
|
||||
|
||||
if ($root->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.');
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model
|
||||
protected $fillable = [
|
||||
'composition_version_id',
|
||||
'resolved_hash',
|
||||
'structure_hash',
|
||||
'confirmed_by',
|
||||
'confirmed_at',
|
||||
'note',
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Composition extends Model
|
||||
@@ -24,6 +25,7 @@ class Composition extends Model
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'working_draft',
|
||||
'pdf_template_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -35,13 +37,33 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::addGlobalScope(new SupportedKindScope);
|
||||
}
|
||||
|
||||
public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
/** Die PDF-Vorlage eines Dokuments; leer = bisheriges Layout (ADR-51). */
|
||||
public function pdfTemplate(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(PdfTemplate::class);
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersion::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). Die Säulen der enthaltenen Medien sind davon
|
||||
* getrennt und werden zur Laufzeit abgeleitet (CatalogReading::memberPillars).
|
||||
*/
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -7,13 +7,27 @@ enum CompositionKind: string
|
||||
case Kombination = 'kombination';
|
||||
case Uebung = 'uebung';
|
||||
case Kurs = 'kurs';
|
||||
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
|
||||
case Exercise = 'exercise';
|
||||
/** Ein zusammenhängendes Dokument aus Kapiteln, zum Beispiel ein Trainerhandbuch (ADR-51). */
|
||||
case Document = 'document';
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function values(): array
|
||||
{
|
||||
return array_map(fn (self $case): string => $case->value, self::cases());
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Übung',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Kurs',
|
||||
self::Exercise => 'Übung',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -21,8 +35,10 @@ public function plural(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Fachliche Kombinationen',
|
||||
self::Uebung => 'Übungen',
|
||||
self::Uebung => 'Module',
|
||||
self::Kurs => 'Kurse',
|
||||
self::Exercise => 'Übungen',
|
||||
self::Document => 'Dokumente',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -30,8 +46,10 @@ public function createLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Kombination => 'Kombination anlegen',
|
||||
self::Uebung => 'Übung anlegen',
|
||||
self::Uebung => 'Modul anlegen',
|
||||
self::Kurs => 'Kurs anlegen',
|
||||
self::Exercise => 'Übung anlegen',
|
||||
self::Document => 'Dokument anlegen',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,6 +59,8 @@ public function explanation(): string
|
||||
self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.',
|
||||
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
|
||||
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
|
||||
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
|
||||
self::Document => 'Ein zusammenhängendes Dokument, zum Beispiel ein Trainerhandbuch, aus Kapiteln und Unterkapiteln. Eine Fassung schreibt Reihenfolge und Texte fest; sie wird in Module und Programme aufgenommen und erscheint für Mitglieder mit Inhaltsverzeichnis und als PDF.',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -50,6 +70,8 @@ public function deskLabel(): string
|
||||
self::Kombination => 'Fachliche Kombination',
|
||||
self::Uebung => 'Modul',
|
||||
self::Kurs => 'Programm',
|
||||
self::Exercise => 'Übung',
|
||||
self::Document => 'Dokument',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -59,6 +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, self::Document => $this->explanation(),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,21 @@ class CompositionMember extends Model
|
||||
'placement_note',
|
||||
'content_element_version_id',
|
||||
'nested_composition_version_id',
|
||||
'variant_id',
|
||||
'requirement',
|
||||
'variant_selection',
|
||||
'origin',
|
||||
];
|
||||
|
||||
public const REQUIRED = 'erforderlich';
|
||||
|
||||
public const SUPPLEMENTARY = 'ergaenzend';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['variant_selection' => 'array'];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionMember $member): void {
|
||||
@@ -41,6 +54,11 @@ public function contentElementVersion(): BelongsTo
|
||||
return $this->belongsTo(ContentElementVersion::class);
|
||||
}
|
||||
|
||||
public function variant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
|
||||
}
|
||||
|
||||
public function nestedCompositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
|
||||
|
||||
@@ -54,6 +54,7 @@ public function publish(
|
||||
?string $note,
|
||||
array $didactic,
|
||||
bool $consent,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
$review = $this->review($host, $members);
|
||||
|
||||
@@ -67,8 +68,8 @@ public function publish(
|
||||
|
||||
$this->publishedDrafts = [];
|
||||
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, []);
|
||||
return DB::transaction(function () use ($host, $members, $actor, $note, $didactic, $variants): CompositionVersion {
|
||||
return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -220,6 +221,12 @@ private function inspectReleasedComposition(
|
||||
): void {
|
||||
$version = CompositionVersion::query()->with('composition', 'members')->find($id);
|
||||
|
||||
if ($version instanceof CompositionVersion && $version->composition === null && app(ForeignCompositions::class)->isForeignVersion($version->id)) {
|
||||
$blocked[] = $this->block('Bestandteil', 'Dieser Bestandteil stammt aus einer neueren Programmversion und kann hier nicht freigegeben werden.', $depth, null);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $version instanceof CompositionVersion || $version->composition === null) {
|
||||
$blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null);
|
||||
|
||||
@@ -324,6 +331,7 @@ private function materialize(
|
||||
?User $actor,
|
||||
?string $note,
|
||||
array $stack,
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if (isset($this->publishedDrafts[$composition->id])) {
|
||||
return $this->publishedDrafts[$composition->id];
|
||||
@@ -341,6 +349,10 @@ private function materialize(
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack),
|
||||
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||
'requirement' => $member['requirement'] ?? 'erforderlich',
|
||||
'selection' => is_array($member['selection'] ?? null) && $member['selection'] !== [] ? array_values($member['selection']) : null,
|
||||
'origin' => $member['origin'] ?? 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -352,8 +364,12 @@ private function materialize(
|
||||
[
|
||||
'learning_goal' => $didactic['learning_goal'] ?? null,
|
||||
'duration_minutes' => $didactic['duration_minutes'] ?? null,
|
||||
'duration_max' => $didactic['duration_max'] ?? null,
|
||||
'material_note' => $didactic['material_note'] ?? null,
|
||||
'prerequisites' => $didactic['prerequisites'] ?? null,
|
||||
'document_meta' => $didactic['document_meta'] ?? null,
|
||||
],
|
||||
$variants,
|
||||
);
|
||||
$this->publishedDrafts[$composition->id] = $version;
|
||||
|
||||
@@ -414,11 +430,15 @@ private function resolveTarget(string $target, ?User $actor, array $stack): Cont
|
||||
[
|
||||
'learning_goal' => $draft['learning_goal'] ?? null,
|
||||
'duration_minutes' => $draft['duration_minutes'] ?? null,
|
||||
'duration_max' => $draft['duration_max'] ?? null,
|
||||
'material_note' => $draft['material_note'] ?? null,
|
||||
'prerequisites' => $draft['prerequisites'] ?? null,
|
||||
'document_meta' => $draft['document_meta'] ?? null,
|
||||
],
|
||||
$actor,
|
||||
is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null,
|
||||
$stack,
|
||||
is_array($draft['variants'] ?? null) ? $draft['variants'] : [],
|
||||
);
|
||||
app(EditorialWorkingDraft::class)->clear($composition);
|
||||
|
||||
|
||||
@@ -60,6 +60,11 @@ private function members(CompositionVersion $version, array $stack = []): array
|
||||
$nested->loadMissing('composition.editorialContentKind', 'composition');
|
||||
$composition = $nested->composition;
|
||||
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz).
|
||||
if ($composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$nodes[] = new StructureNode(
|
||||
role: $member->role,
|
||||
position: $member->position,
|
||||
|
||||
@@ -17,12 +17,18 @@ class CompositionVersion extends Model
|
||||
'learning_goal',
|
||||
'duration_minutes',
|
||||
'material_note',
|
||||
'duration_max',
|
||||
'prerequisites',
|
||||
'structure_hash',
|
||||
'source_snapshot_id',
|
||||
'document_meta',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'status' => ContentVersionStatus::class,
|
||||
'document_meta' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -60,6 +66,11 @@ public function members(): HasMany
|
||||
return $this->hasMany(CompositionMember::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function variants(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompositionVersionVariant::class)->orderBy('position');
|
||||
}
|
||||
|
||||
public function attestations(): HasMany
|
||||
{
|
||||
return $this->hasMany(CompatibilityAttestation::class);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Durchführungsvariante einer Übungsfassung. Der Schlüssel ist je Fassung eindeutig und bleibt über Fassungen hinweg
|
||||
* gleich, damit eine Auswahl im Modul oder Programm und der Abgleich mit einer Quelle dieselbe Variante meinen.
|
||||
* Wie die Mitglieder ist sie nur im Entwurf der Fassung schreibbar.
|
||||
*/
|
||||
class CompositionVersionVariant extends Model
|
||||
{
|
||||
protected $fillable = ['composition_version_id', 'key', 'position', 'name', 'description', 'origin'];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (CompositionVersionVariant $variant): void {
|
||||
$status = CompositionVersion::query()->whereKey($variant->composition_version_id)->value('status');
|
||||
|
||||
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
|
||||
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.');
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function (): void {
|
||||
throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
|
||||
});
|
||||
}
|
||||
|
||||
public function compositionVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class);
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ class ContentElement extends Model
|
||||
'preview_path',
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'source_ref',
|
||||
'origin_composition_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -46,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);
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
class ContentResolver
|
||||
{
|
||||
/**
|
||||
* @return list<array{version_id: int, role: string, path: string}>
|
||||
* Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und
|
||||
* den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl
|
||||
* (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten).
|
||||
*
|
||||
* @param list<string>|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array
|
||||
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array
|
||||
{
|
||||
if ($node instanceof ContentElementVersion) {
|
||||
$node->loadMissing('element');
|
||||
@@ -16,7 +21,9 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $node->id,
|
||||
'role' => $path,
|
||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
||||
]];
|
||||
'requirement' => CompositionMember::REQUIRED,
|
||||
'variant' => null,
|
||||
], ...$this->embeddedImages($node, $path !== '' ? $path : $node->element->working_title, null)];
|
||||
}
|
||||
|
||||
if (in_array($node->composition_id, $stack, true)) {
|
||||
@@ -26,7 +33,13 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
$stack[] = $node->composition_id;
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->members()->orderBy('position')->get() as $member) {
|
||||
foreach ($node->members()->with('variant')->orderBy('position')->get() as $member) {
|
||||
$variantKey = $member->variant?->key;
|
||||
|
||||
if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
|
||||
|
||||
if ($member->content_element_version_id !== null) {
|
||||
@@ -34,8 +47,14 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'version_id' => $member->content_element_version_id,
|
||||
'role' => $member->role,
|
||||
'path' => $segment,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) {
|
||||
$rows[] = $image;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -45,7 +64,48 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.');
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand($nested, $segment, $stack));
|
||||
// Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht auflösen (Rückfallschutz).
|
||||
// Veröffentlichen verweigern die aufrufenden Stellen über ForeignCompositions.
|
||||
$nested->loadMissing('composition');
|
||||
|
||||
if ($nested->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows = array_merge($rows, $this->expand(
|
||||
$nested,
|
||||
$segment,
|
||||
$stack,
|
||||
is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null,
|
||||
));
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilder, auf die ein Text verweist, gehören zum Inhalt des Stands: Nur was im Stand steht, darf ein Mitglied sehen
|
||||
* (`DecideAccess`), und eine Sperre des Bildes wirkt über denselben Weg. Ein fehlendes Bild macht den Text nicht
|
||||
* unbrauchbar, daher „ergänzend“.
|
||||
*
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
private function embeddedImages(?ContentElementVersion $text, string $path, ?string $variantKey): array
|
||||
{
|
||||
if ($text === null || trim((string) $text->body) === '' || ! str_contains((string) $text->body, 'img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
|
||||
foreach (FormattedText::imageIds($text->body) as $id) {
|
||||
$rows[] = [
|
||||
'version_id' => $id,
|
||||
'role' => 'Bild',
|
||||
'path' => $path.' / Bild',
|
||||
'requirement' => CompositionMember::SUPPLEMENTARY,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -225,7 +299,9 @@ public function releaseElementVersion(ContentElementVersion $version): ContentEl
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
|
||||
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion, note?: string|null, variant?: string|null, requirement?: string|null, selection?: list<string>|null}> $members
|
||||
* @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic
|
||||
* @param list<array{key: string, name: string, description?: string|null, origin?: string}> $variants Durchführungsvarianten einer Übung
|
||||
*/
|
||||
public function publishComposition(
|
||||
Composition $composition,
|
||||
@@ -233,18 +309,21 @@ public function publishComposition(
|
||||
?User $confirmedBy = null,
|
||||
?string $note = null,
|
||||
array $didactic = [],
|
||||
array $variants = [],
|
||||
): CompositionVersion {
|
||||
if ($members === []) {
|
||||
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
|
||||
}
|
||||
|
||||
$variants = $this->checkedVariants($variants);
|
||||
$this->assertAcyclic($composition->id, $members);
|
||||
|
||||
foreach ($members as $member) {
|
||||
$this->assertReadyMember($member['target']);
|
||||
$this->assertMemberPlacement($member, $variants);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
|
||||
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): CompositionVersion {
|
||||
$number = ((int) $composition->versions()->max('number')) + 1;
|
||||
$version = $composition->versions()->create([
|
||||
'number' => $number,
|
||||
@@ -253,28 +332,53 @@ public function publishComposition(
|
||||
'resolved_hash' => 'pending',
|
||||
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
|
||||
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
|
||||
'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null,
|
||||
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
|
||||
'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null),
|
||||
'document_meta' => DocumentMeta::normalize($didactic['document_meta'] ?? null),
|
||||
'source_snapshot_id' => isset($didactic['source_snapshot_id']) ? (int) $didactic['source_snapshot_id'] : null,
|
||||
]);
|
||||
|
||||
$variantIds = [];
|
||||
|
||||
foreach ($variants as $index => $variant) {
|
||||
$variantIds[$variant['key']] = $version->variants()->create([
|
||||
'key' => $variant['key'],
|
||||
'position' => $index + 1,
|
||||
'name' => $variant['name'],
|
||||
'description' => $variant['description'],
|
||||
'origin' => $variant['origin'],
|
||||
])->id;
|
||||
}
|
||||
|
||||
foreach (array_values($members) as $index => $member) {
|
||||
$target = $member['target'];
|
||||
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
|
||||
$version->members()->create([
|
||||
'position' => $index + 1,
|
||||
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
|
||||
'placement_note' => $this->optionalText($member['note'] ?? null),
|
||||
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'variant_selection' => $selection === null ? null : array_values($selection),
|
||||
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
]);
|
||||
}
|
||||
|
||||
$version->load('members.variant', 'variants');
|
||||
$resolvedHash = $this->resolver->resolvedHash($version);
|
||||
$structureHash = $this->structureHash($version);
|
||||
$version->attestations()->create([
|
||||
'resolved_hash' => $resolvedHash,
|
||||
'structure_hash' => $structureHash,
|
||||
'confirmed_by' => $confirmedBy?->id,
|
||||
'confirmed_at' => now(),
|
||||
'note' => $note,
|
||||
]);
|
||||
$version->resolved_hash = $resolvedHash;
|
||||
$version->structure_hash = $structureHash;
|
||||
$version->status = ContentVersionStatus::Bereit;
|
||||
$version->save();
|
||||
|
||||
@@ -282,6 +386,107 @@ public function publishComposition(
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der
|
||||
* `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante,
|
||||
* Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben.
|
||||
*/
|
||||
public function structureHash(CompositionVersion $version): string
|
||||
{
|
||||
$version->loadMissing('members.variant', 'variants');
|
||||
|
||||
$meta = DocumentMeta::normalize($version->document_meta);
|
||||
|
||||
return hash('sha256', json_encode([
|
||||
'fields' => [
|
||||
$version->learning_goal,
|
||||
$version->duration_minutes,
|
||||
$version->duration_max,
|
||||
$version->material_note,
|
||||
$version->prerequisites,
|
||||
],
|
||||
// Nur wenn gesetzt: Der Nachweis älterer Fassungen ohne Dokumentangaben bleibt unverändert.
|
||||
...($meta === null ? [] : ['document' => $meta]),
|
||||
'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [
|
||||
$variant->key, $variant->position, $variant->name, $variant->description, $variant->origin,
|
||||
])->all(),
|
||||
'members' => $version->members->map(fn (CompositionMember $member): array => [
|
||||
$member->position,
|
||||
$member->role,
|
||||
$member->placement_note,
|
||||
$member->content_element_version_id,
|
||||
$member->nested_composition_version_id,
|
||||
$member->variant?->key,
|
||||
$member->requirement,
|
||||
$member->variant_selection,
|
||||
$member->origin,
|
||||
])->all(),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{key?: string, name?: string, description?: string|null}> $variants
|
||||
* @return list<array{key: string, name: string, description: string|null}>
|
||||
*/
|
||||
private function checkedVariants(array $variants): array
|
||||
{
|
||||
$checked = [];
|
||||
$keys = [];
|
||||
|
||||
foreach (array_values($variants) as $variant) {
|
||||
$key = trim((string) ($variant['key'] ?? ''));
|
||||
|
||||
if ($key === '' || in_array($key, $keys, true)) {
|
||||
throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.');
|
||||
}
|
||||
|
||||
$keys[] = $key;
|
||||
$checked[] = [
|
||||
'key' => $key,
|
||||
'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'),
|
||||
'description' => $this->optionalText($variant['description'] ?? null),
|
||||
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return $checked;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list<string>|null} $member
|
||||
* @param list<array{key: string, name: string, description: string|null}> $variants
|
||||
*/
|
||||
private function assertMemberPlacement(array $member, array $variants): void
|
||||
{
|
||||
$variant = $member['variant'] ?? null;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) {
|
||||
throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.');
|
||||
}
|
||||
|
||||
$requirement = $member['requirement'] ?? CompositionMember::REQUIRED;
|
||||
|
||||
if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) {
|
||||
throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.');
|
||||
}
|
||||
|
||||
$selection = $member['selection'] ?? null;
|
||||
|
||||
if ($selection === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $member['target'] instanceof CompositionVersion) {
|
||||
throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.');
|
||||
}
|
||||
|
||||
$offered = $member['target']->variants()->pluck('key')->all();
|
||||
|
||||
if ($selection === [] || array_diff($selection, $offered) !== []) {
|
||||
throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.');
|
||||
}
|
||||
}
|
||||
|
||||
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
|
||||
{
|
||||
return Composition::query()->create([
|
||||
@@ -345,6 +550,10 @@ private function assertAcyclic(int $compositionId, array $members, array $stack
|
||||
|
||||
private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void
|
||||
{
|
||||
if (app(ForeignCompositions::class)->reaches($target)) {
|
||||
throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.');
|
||||
}
|
||||
|
||||
if ($target->status !== ContentVersionStatus::Bereit) {
|
||||
throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.');
|
||||
}
|
||||
@@ -365,6 +574,9 @@ private function membersHash(array $members): string
|
||||
'note' => $this->optionalText($member['note'] ?? null),
|
||||
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
|
||||
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
|
||||
'variant' => $member['variant'] ?? null,
|
||||
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
|
||||
'selection' => $member['selection'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ class EditorialContentKind extends Model
|
||||
public const CONTEXTS = [
|
||||
'medium' => 'Medium',
|
||||
'modul' => 'Modul',
|
||||
'uebung' => 'Übung',
|
||||
'dokument' => 'Dokument',
|
||||
'programm' => 'Programm',
|
||||
'lizenzartikel' => 'Lizenzartikel',
|
||||
];
|
||||
@@ -26,7 +28,16 @@ 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', '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',
|
||||
@@ -73,6 +84,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);
|
||||
|
||||
@@ -20,20 +20,15 @@ public function values(): HasMany
|
||||
}
|
||||
|
||||
/**
|
||||
* Inhaltselemente pflegen Themen über die Säulen, nicht noch einmal über die Dimension.
|
||||
* Module, Programme und Lizenzartikel haben keine Säulenauswahl und behalten die Dimension.
|
||||
* Fachliche Säulen werden für alle Objektarten über die zentrale Säulenverwaltung gewählt (`pillars`), nie über
|
||||
* eine Dimension. Die alte Dimension „Fachliche Säule“ bleibt nur als Verlauf in der Datenbank und wird nirgends
|
||||
* mehr angeboten, geändert oder gefiltert.
|
||||
*
|
||||
* @return Collection<int, self>
|
||||
*/
|
||||
public static function forSubject(Model $subject): Collection
|
||||
{
|
||||
$query = static::query()->with('values')->orderBy('label');
|
||||
|
||||
if ($subject instanceof ContentElement) {
|
||||
$query->where('slug', '!=', self::PILLAR_SLUG);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
return static::query()->with('values')->where('slug', '!=', self::PILLAR_SLUG)->orderBy('label')->get();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
class EditorialDimensionValue extends Model
|
||||
{
|
||||
protected $fillable = ['editorial_dimension_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
protected $fillable = ['editorial_dimension_id', 'pillar_id', 'slug', 'label', 'sort_order', 'is_active'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -46,6 +46,8 @@ public static function compositionContext(?CompositionKind $kind): ?string
|
||||
return match ($kind) {
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
CompositionKind::Document => 'dokument',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
@@ -123,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>
|
||||
*/
|
||||
@@ -137,6 +181,8 @@ private function usedKindIds(string $context): array
|
||||
'lizenzartikel' => DB::table('license_articles'),
|
||||
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
|
||||
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
|
||||
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value),
|
||||
'dokument' => DB::table('compositions')->where('kind', CompositionKind::Document->value),
|
||||
default => null,
|
||||
};
|
||||
|
||||
@@ -181,13 +227,13 @@ public function dimensionGroups(Model $subject, array $assignedIds): array
|
||||
* @param list<int> $selectedIds
|
||||
* @return list<array{label: string, values: list<array{id: int, label: string}>}>
|
||||
*/
|
||||
public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars = true): array
|
||||
public function dimensionFilterGroups(array $selectedIds = []): array
|
||||
{
|
||||
$used = DB::table('identity_dimension_values')->distinct()->pluck('editorial_dimension_value_id')->map(fn ($id): int => (int) $id)->all();
|
||||
$groups = [];
|
||||
|
||||
foreach (EditorialDimension::query()->with('values')->orderBy('label')->get() as $dimension) {
|
||||
if (! $withPillars && $dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
if ($dimension->slug === EditorialDimension::PILLAR_SLUG) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -217,7 +263,7 @@ public function dimensionFilterGroups(array $selectedIds = [], bool $withPillars
|
||||
*/
|
||||
public function memberFilterDimensions(array $selectedIds = []): Collection
|
||||
{
|
||||
$dimensions = EditorialDimension::query()->with('values')->orderBy('label')->get();
|
||||
$dimensions = EditorialDimension::query()->with('values')->where('slug', '!=', EditorialDimension::PILLAR_SLUG)->orderBy('label')->get();
|
||||
|
||||
foreach ($dimensions as $dimension) {
|
||||
$dimension->setRelation('values', $dimension->values
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Media\PdfImage;
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Bilder in formatierten Texten (ADR-51). Ein Text verweist auf eine Bildfassung; ob und wie sie erscheint, entscheidet
|
||||
* hier für den Stand des Mitglieds:
|
||||
*
|
||||
* - Ein Bild im Text gehört zum Text. Wer den Text ansehen (PDF: laden) darf, darf die Bilder darin sehen. Es braucht kein
|
||||
* eigenes Recht für Bilder; bestehende Berechtigungen, die nur Texte nennen, zeigen die Bilder der Texte mit. Die Rechte
|
||||
* des Texts entscheidet wie überall `DecideAccess`.
|
||||
* - Das Bild muss zum festgeschriebenen Inhalt des Stands gehören ({@see ContentResolver}: ein Bild im Text steht als
|
||||
* ergänzende Zeile im Stand) und im Text tatsächlich vorkommen. So gibt die Adresse kein anderes Bild frei.
|
||||
* - Eine Sperre der Bildfassung wirkt: Das Bild entfällt, der Text bleibt lesbar.
|
||||
*
|
||||
* Ansicht: eine Adresse ohne Ablauf, die bei jedem Abruf neu entscheidet und die Datei ausliefert (`member.stand.image`);
|
||||
* eine lange Lektüre darf nicht an einer kurzlebigen Signatur scheitern. PDF: das Bild wird aus dem abgeleiteten Bestand
|
||||
* gelesen und für das PDF aufbereitet.
|
||||
*/
|
||||
final class EmbeddedImages
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Auflösung für die Vorschau der Redaktion: Bilder zeigt die Verwaltung über ihre eigene Dateiausgabe.
|
||||
*
|
||||
* @return Closure(int): ?array{src: string}
|
||||
*/
|
||||
public static function staff(): Closure
|
||||
{
|
||||
return fn (int $id): array => ['src' => self::staffSource($id)];
|
||||
}
|
||||
|
||||
/** Adresse einer Bildfassung für den Editor und die Vorschau der Verwaltung. */
|
||||
public static function staffSource(int $id): string
|
||||
{
|
||||
return route('content.file', ['version' => $id], false);
|
||||
}
|
||||
|
||||
/** Text für einen Editor der Verwaltung: Bilder tragen ihre Adresse, damit der Editor sie zeigt. */
|
||||
public static function forEditor(?string $value): string
|
||||
{
|
||||
return FormattedText::forEditor(FormattedText::canonical($value), fn (int $id): string => self::staffSource($id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für {@see FormattedText::html()} eines Textes im Stand.
|
||||
*
|
||||
* @return Closure(int): ?array{src?: string, alt?: string, note?: string}
|
||||
*/
|
||||
public function forView(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text): Closure
|
||||
{
|
||||
return function (int $id) use ($user, $article, $release, $text): ?array {
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'ansehen');
|
||||
|
||||
if ($found === null) {
|
||||
return ['note' => 'Dieses Bild gibt es nicht mehr.'];
|
||||
}
|
||||
|
||||
if (! $found['allowed']) {
|
||||
return ['note' => 'Dieses Bild ist derzeit nicht verfügbar.'];
|
||||
}
|
||||
|
||||
return ['src' => route('member.stand.image', ['article' => $article->id, 'release' => $release->id, 'text' => $text->id, 'version' => $id])];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bildfassung für die Auslieferung: nur wenn sie im Text vorkommt, zum Stand gehört, nicht gesperrt ist und der Text
|
||||
* für `ansehen` zulässig ist.
|
||||
*
|
||||
* @return array{version: ContentElementVersion, grant: Grant}|null
|
||||
*/
|
||||
public function serve(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text, int $id): ?array
|
||||
{
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'ansehen');
|
||||
|
||||
return $found !== null && $found['allowed'] && $found['grant'] instanceof Grant ? ['version' => $found['version'], 'grant' => $found['grant']] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für das PDF. Ein Bild darf ins PDF, wenn ein Text, der es enthält, für `laden` zulässig ist. Die Bilder, die
|
||||
* tatsächlich im PDF stehen, sammelt {@see PdfImages::used()} für den Ausgabenachweis.
|
||||
*
|
||||
* @param list<ContentElementVersion> $texts die Texte des PDF
|
||||
*/
|
||||
public function forPdf(User $user, LicenseArticle $article, ArticleRelease $release, array $texts): PdfImages
|
||||
{
|
||||
return new PdfImages(function (int $id) use ($user, $article, $release, $texts): ?array {
|
||||
$decision = null;
|
||||
$exists = false;
|
||||
|
||||
foreach ($texts as $text) {
|
||||
if (! in_array($id, FormattedText::imageIds($text->body), true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$found = $this->decide($user, $article, $release, $text, $id, 'laden');
|
||||
$exists = $exists || $found !== null;
|
||||
|
||||
if ($found !== null && $found['allowed']) {
|
||||
$decision = $found;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($decision === null) {
|
||||
return ['note' => $exists ? 'Bild nicht verfügbar' : 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
$prepared = self::prepared($decision['version']);
|
||||
|
||||
if ($prepared === null) {
|
||||
return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
return $prepared + ['grant' => $decision['grant'], 'version' => $decision['version']];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für die PDF-Vorschau der Redaktion: ohne Rechteprüfung, ohne Ausgabenachweis.
|
||||
*/
|
||||
public static function forStaffPdf(): PdfImages
|
||||
{
|
||||
return new PdfImages(function (int $id): ?array {
|
||||
$version = ContentElementVersion::query()->with('element')->find($id);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return ['note' => 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
$prepared = self::prepared($version);
|
||||
|
||||
return $prepared === null ? ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null] : $prepared + ['grant' => null, 'version' => null];
|
||||
});
|
||||
}
|
||||
|
||||
/** Pfad der Bilddatei im abgeleiteten Bestand, wenn sie vorliegt. */
|
||||
public static function file(ContentElementVersion $version): ?string
|
||||
{
|
||||
$file = $version->metadata['file'] ?? null;
|
||||
|
||||
return is_string($file) && $file !== '' && ! str_contains($file, '..') && Storage::disk('media_derived')->exists($file) ? $file : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bilddatei aus dem abgeleiteten Bestand (der Web-Prozess liest nur dort), für das PDF aufbereitet.
|
||||
*
|
||||
* @return array{jpeg: string, width: int, height: int}|null
|
||||
*/
|
||||
private static function prepared(ContentElementVersion $version): ?array
|
||||
{
|
||||
$file = self::file($version);
|
||||
|
||||
return $file === null ? null : PdfImage::fromBytes((string) Storage::disk('media_derived')->get($file));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null null = es gibt kein solches Bild im Text
|
||||
*/
|
||||
private function decide(User $user, LicenseArticle $article, ArticleRelease $release, ContentElementVersion $text, int $id, string $action): ?array
|
||||
{
|
||||
if (! in_array($id, FormattedText::imageIds($text->body), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = ContentElementVersion::query()->with('element')->find($id);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$inStand = $release->contents()->where('content_element_version_id', $id)->exists();
|
||||
$decision = ($this->access)($user, $article, $release, $text, $action);
|
||||
|
||||
return [
|
||||
'allowed' => $inStand && $decision->allowed && $version->status === ContentVersionStatus::Bereit,
|
||||
'version' => $version,
|
||||
'grant' => $decision->grant,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Die Anleitung einer Übung, wie ein Stand sie festschreibt: die im Stand gebundene Übungsfassung, die angebotenen
|
||||
* Varianten und je Abschnitt oder Medium die Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und
|
||||
* PDF lesen dieses Ergebnis und zeigen damit dieselbe Fassung.
|
||||
*
|
||||
* Eine Sperre oder fehlende Berechtigung betrifft nur den betroffenen Abschnitt oder das Medium. Anleitung und übrige
|
||||
* Inhalte bleiben im selben Stand erreichbar. Fehlt in einer Variante ein erforderlicher Bestandteil, gilt die Variante
|
||||
* als derzeit nicht vollständig durchführbar; ein ergänzender Bestandteil entfällt mit einem Hinweis.
|
||||
*/
|
||||
class ExerciseGuide
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Darf dieses Konto den Stand überhaupt sehen? Aktive, nutzbare Berechtigung auf den Artikel und ein auslieferbarer
|
||||
* Stand. Über die einzelnen Inhalte entscheidet danach `DecideAccess`.
|
||||
*/
|
||||
public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $release): bool
|
||||
{
|
||||
if ($release->license_article_id !== $article->id
|
||||
|| ! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Grant::query()
|
||||
->where('license_article_id', $article->id)
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->usableBy($user)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Übungsfassung an einer Stelle des Stands. Der Pfad nennt die Positionen der Mitglieder von der Wurzel des
|
||||
* Stands abwärts („2“ oder „1-3“). So ist auch dieselbe Übung an zwei Stellen eines Produkts unterscheidbar.
|
||||
*
|
||||
* @return array{version: CompositionVersion, selection: list<string>|null}|null
|
||||
*/
|
||||
public function locate(ArticleRelease $release, string $path, CompositionKind $kind = CompositionKind::Exercise): ?array
|
||||
{
|
||||
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$version = $release->rootCompositionVersion;
|
||||
$selection = null;
|
||||
|
||||
foreach (array_map('intval', explode('-', $path)) as $position) {
|
||||
if ($version === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$member = $version->members()->where('position', $position)->first();
|
||||
|
||||
if ($member === null || $member->nested_composition_version_id === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$selection = is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null;
|
||||
$version = $member->nestedCompositionVersion;
|
||||
}
|
||||
|
||||
$version?->loadMissing('composition');
|
||||
|
||||
if ($version === null || $version->composition === null || $version->composition->kind !== $kind) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['version' => $version, 'selection' => $selection];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pfad zur ersten Stelle, an der die Wurzel die Übungsfassung einbindet.
|
||||
*/
|
||||
public function pathTo(CompositionVersion $root, int $versionId, array $stack = []): ?string
|
||||
{
|
||||
if (in_array($root->id, $stack, true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($root->members()->orderBy('position')->get() as $member) {
|
||||
if ($member->nested_composition_version_id === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($member->nested_composition_version_id === $versionId) {
|
||||
return (string) $member->position;
|
||||
}
|
||||
|
||||
$below = $this->pathTo($member->nestedCompositionVersion, $versionId, [...$stack, $root->id]);
|
||||
|
||||
if ($below !== null) {
|
||||
return $member->position.'-'.$below;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $selection angebotene Variantenschlüssel; null = alle
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $exercise, ?array $selection, ?string $variantKey = null): array
|
||||
{
|
||||
$exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']);
|
||||
$library = app(LibraryCatalog::class);
|
||||
$embedded = app(EmbeddedImages::class);
|
||||
$offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values();
|
||||
$chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first();
|
||||
$entries = [];
|
||||
|
||||
foreach ($exercise->members as $member) {
|
||||
$version = $member->contentElementVersion;
|
||||
|
||||
if ($version === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = $member->variant?->key;
|
||||
$class = (string) $version->element->output_class;
|
||||
$action = in_array($class, ['film', 'audio'], true) ? 'streamen' : 'ansehen';
|
||||
$decision = ($this->access)($user, $article, $release, $version, $action);
|
||||
$download = $action === 'ansehen' ? ($this->access)($user, $article, $release, $version, 'laden') : null;
|
||||
|
||||
$entries[] = [
|
||||
'variant' => $key,
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'title' => $library->text($version->element)['title'] ?: $version->element->working_title,
|
||||
'class' => $class,
|
||||
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
|
||||
'action' => $action,
|
||||
'version' => $version,
|
||||
'allowed' => $decision->allowed,
|
||||
'may_download' => $download?->allowed ?? false,
|
||||
'grant' => $decision->grant,
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? FormattedText::blocks($version->body) : null,
|
||||
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version)) : null,
|
||||
];
|
||||
}
|
||||
|
||||
$variants = $offered->map(function (CompositionVersionVariant $variant) use ($entries): array {
|
||||
$missing = array_values(array_filter($entries, fn (array $entry): bool => ($entry['variant'] === null || $entry['variant'] === $variant->key)
|
||||
&& $entry['requirement'] === CompositionMember::REQUIRED
|
||||
&& ! $entry['allowed']));
|
||||
|
||||
return [
|
||||
'key' => $variant->key,
|
||||
'name' => $variant->name,
|
||||
'description' => $variant->description,
|
||||
'complete' => $missing === [],
|
||||
'missing' => array_map(fn (array $entry): string => $entry['title'], $missing),
|
||||
];
|
||||
})->all();
|
||||
|
||||
$shown = array_values(array_filter($entries, fn (array $entry): bool => $entry['variant'] === null || $entry['variant'] === $chosen?->key));
|
||||
|
||||
return [
|
||||
'exercise' => $exercise,
|
||||
'title' => $library->text($exercise->composition)['title'],
|
||||
'summary' => $library->text($exercise->composition)['summary'],
|
||||
'summary_html' => $library->text($exercise->composition)['summary_html'],
|
||||
'learning_goal' => $exercise->learning_goal,
|
||||
'duration_minutes' => $exercise->duration_minutes,
|
||||
'duration_max' => $exercise->duration_max,
|
||||
'prerequisites' => $exercise->prerequisites,
|
||||
'material_note' => $exercise->material_note,
|
||||
'variants' => $variants,
|
||||
'chosen' => $chosen?->key,
|
||||
'entries' => $shown,
|
||||
'entry_total' => count($entries),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ExerciseImportRun extends Model
|
||||
{
|
||||
protected $fillable = ['source_system', 'status', 'cursor', 'added', 'updated', 'removed', 'error', 'started_at', 'finished_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['started_at' => 'datetime', 'finished_at' => 'datetime'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Druckbare Ausgabe einer Übung (DIN A4, mehrere Seiten) aus demselben Ergebnis wie die Ansicht ({@see ExerciseGuide}).
|
||||
* Kennzeichnung: Fußzeile mit Lizenznehmer und Lizenzkopie auf jeder Seite (K2) und die Kennung in den Metadaten (K1).
|
||||
* Das Dokument wird bei jedem Abruf neu erzeugt und nie abgelegt, damit eine spätere Sperre keine ältere Kopie
|
||||
* ausliefern kann.
|
||||
*/
|
||||
class ExercisePdf
|
||||
{
|
||||
private const LEFT = 56.0;
|
||||
|
||||
private const RIGHT = 539.0;
|
||||
|
||||
private const TOP = 790.0;
|
||||
|
||||
private const BOTTOM = 72.0;
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private PdfFlow $flow;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
private string $footer = '';
|
||||
|
||||
/**
|
||||
* Welche Abschnitte gehören ins PDF? Erforderliche Textabschnitte der Auswahl müssen für `laden` zulässig sein, sonst
|
||||
* ist das PDF nicht erlaubt (null). Ergänzende ohne Berechtigung entfallen. Videos und Dokumente erscheinen nur als
|
||||
* Hinweis.
|
||||
*
|
||||
* @param array<string, mixed> $guide Ergebnis von {@see ExerciseGuide::build}
|
||||
* @return list<array<string, mixed>>|null
|
||||
*/
|
||||
public function sections(array $guide): ?array
|
||||
{
|
||||
$included = [];
|
||||
|
||||
foreach ($guide['entries'] as $entry) {
|
||||
if ($entry['class'] === 'text') {
|
||||
if ($entry['may_download'] && $entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
} elseif ($entry['requirement'] === CompositionMember::REQUIRED) {
|
||||
return null;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($entry['allowed']) {
|
||||
$included[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return array_filter($included, fn (array $entry): bool => $entry['class'] === 'text') === [] ? null : $included;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $guide
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl, ?PdfImages $images = null): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}, $images === null ? null : Closure::fromCallable($images));
|
||||
$this->newPage();
|
||||
|
||||
$this->flow->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$this->fact('Lernziel', $guide['learning_goal']);
|
||||
|
||||
if ($guide['duration_minutes'] !== null) {
|
||||
$this->flow->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4);
|
||||
}
|
||||
|
||||
if (filled($guide['prerequisites'])) {
|
||||
$this->flow->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->fact('Ausstattung', $guide['material_note']);
|
||||
|
||||
$this->flow->y -= 6;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$this->section($section, $guideUrl);
|
||||
}
|
||||
|
||||
$this->closePage();
|
||||
|
||||
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
|
||||
return $this->pdf->output($ascii?->transliterate((string) $guide['title']) ?: 'Uebung', 'Lizenzkopie '.$copyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
|
||||
* lateinische Buchstaben); sonst bleibt „?“.
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
return PdfFlow::printable($text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $section
|
||||
*/
|
||||
private function section(array $section, string $guideUrl): void
|
||||
{
|
||||
$title = self::printable((string) $section['title']);
|
||||
|
||||
if ($section['class'] !== 'text') {
|
||||
$label = in_array($section['class'], ['film', 'audio'], true)
|
||||
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
|
||||
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
|
||||
$this->flow->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->flow->write($title, 12.5, true, 5, keep: 40);
|
||||
|
||||
$this->flow->formatted($section['blocks'] ?? []);
|
||||
|
||||
$this->flow->y -= 4;
|
||||
}
|
||||
|
||||
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
|
||||
private function fact(string $label, ?string $value): void
|
||||
{
|
||||
$blocks = FormattedText::blocks($value);
|
||||
|
||||
if ($blocks === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (count($blocks) === 1 && $blocks[0]['type'] === 'paragraph') {
|
||||
$this->flow->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->flow->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->flow->formatted($blocks);
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->flow->restart();
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
{
|
||||
$this->pdf->line(self::LEFT, 54, self::RIGHT, 54, 0.4);
|
||||
$this->pdf->text(self::LEFT, 40, $this->footer, 8);
|
||||
$this->pdf->textRight(self::RIGHT, 40, 'Seite '.$this->page, 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übungsabschnitte: Textabschnitte, die für eine bestimmte Übung angelegt wurden, im Übungseditor oder bei der
|
||||
* Übernahme aus Shinkan. Sie liegen im gemeinsamen Medienbestand und tragen dort die Materialart „Übungsabschnitt“
|
||||
* und einen Verweis auf ihre Übung (`origin_composition_id`). Die Texte nutzen die gemeinsame Inhalts- und
|
||||
* Fassungsverwaltung; bearbeitet werden sie im Übungseditor.
|
||||
*/
|
||||
final class ExerciseSections
|
||||
{
|
||||
public const KIND_SLUG = EditorialContentKind::EXERCISE_SECTION_SLUG;
|
||||
|
||||
public function kindId(): ?int
|
||||
{
|
||||
$id = EditorialContentKind::query()->where('slug', self::KIND_SLUG)->value('id');
|
||||
|
||||
return $id === null ? null : (int) $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einen Abschnitt seiner Übung zu und gibt ihm die Materialart. Eine bereits gesetzte Materialart bleibt:
|
||||
* Sie ist eine bewusste Einordnung der Redaktion.
|
||||
*/
|
||||
public function mark(ContentElement $element, Composition $exercise): void
|
||||
{
|
||||
$element->origin_composition_id = $exercise->getKey();
|
||||
|
||||
if ($element->editorial_content_kind_id === null) {
|
||||
$element->editorial_content_kind_id = $this->kindId();
|
||||
}
|
||||
|
||||
$element->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet vorhandene Texte nur dann zu, wenn ihre Herkunft belegt ist:
|
||||
*
|
||||
* - Ein Abschnitt aus der Übernahme aus Shinkan (`source_ref` = `shinkan:<Quell-ID>:<Feld>`) gehört zur lokalen
|
||||
* Übung dieser Quelle.
|
||||
* - Ein anderer Text gilt als Abschnitt, wenn er ohne Materialart ist, ausschließlich in genau einer Übung
|
||||
* vorkommt und nirgends in einem Modul oder Programm direkt verwendet wird.
|
||||
*
|
||||
* Ein bereits gesetzter Materialtyp bleibt in jedem Fall erhalten, ebenso unklare Fälle.
|
||||
*
|
||||
* @return int Anzahl der Texte, die jetzt einer Übung zugeordnet sind
|
||||
*/
|
||||
public function backfill(): int
|
||||
{
|
||||
$kindId = $this->kindId();
|
||||
|
||||
if ($kindId === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$assigned = 0;
|
||||
|
||||
foreach ($this->fromSource() + $this->fromUse() as $elementId => $compositionId) {
|
||||
DB::table('content_elements')->where('id', $elementId)->whereNull('origin_composition_id')->update(['origin_composition_id' => $compositionId]);
|
||||
DB::table('content_elements')->where('id', $elementId)->whereNull('editorial_content_kind_id')->update(['editorial_content_kind_id' => $kindId]);
|
||||
$assigned++;
|
||||
}
|
||||
|
||||
return $assigned;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int> Element-ID => Übung
|
||||
*/
|
||||
private function fromSource(): array
|
||||
{
|
||||
$byRef = [];
|
||||
|
||||
foreach (DB::table('exercise_sources')->whereNotNull('composition_id')->get(['source_id', 'composition_id']) as $source) {
|
||||
$byRef[(string) $source->source_id] = (int) $source->composition_id;
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach (DB::table('content_elements')->where('output_class', 'text')->where('source_ref', 'like', 'shinkan:%')->get(['id', 'source_ref']) as $element) {
|
||||
$parts = explode(':', (string) $element->source_ref);
|
||||
|
||||
if (count($parts) === 3 && isset($byRef[$parts[1]])) {
|
||||
$found[(int) $element->id] = $byRef[$parts[1]];
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int> Element-ID => Übung
|
||||
*/
|
||||
private function fromUse(): array
|
||||
{
|
||||
$exerciseKind = CompositionKind::Exercise->value;
|
||||
$uses = DB::table('composition_members as m')
|
||||
->join('content_element_versions as v', 'v.id', '=', 'm.content_element_version_id')
|
||||
->join('content_elements as e', 'e.id', '=', 'v.content_element_id')
|
||||
->join('composition_versions as cv', 'cv.id', '=', 'm.composition_version_id')
|
||||
->join('compositions as c', 'c.id', '=', 'cv.composition_id')
|
||||
->where('e.output_class', 'text')
|
||||
->whereNull('e.editorial_content_kind_id')
|
||||
->whereNull('e.origin_composition_id')
|
||||
->select('e.id as element_id', 'c.id as composition_id', 'c.kind as composition_kind')
|
||||
->get();
|
||||
|
||||
$exercises = [];
|
||||
$elsewhere = [];
|
||||
|
||||
foreach ($uses as $use) {
|
||||
if ($use->composition_kind === $exerciseKind) {
|
||||
$exercises[(int) $use->element_id][(int) $use->composition_id] = true;
|
||||
} else {
|
||||
$elsewhere[(int) $use->element_id] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$found = [];
|
||||
|
||||
foreach ($exercises as $elementId => $compositions) {
|
||||
if (count($compositions) === 1 && ! isset($elsewhere[$elementId])) {
|
||||
$found[$elementId] = array_key_first($compositions);
|
||||
}
|
||||
}
|
||||
|
||||
return $found;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Eine Übung der Quelle, gebunden an ihre stabile Kennung. `availability` hält nur fest, ob die Quelle sie noch
|
||||
* bereitstellt. Das ist kein Rechtsvorgang: Eine rechtliche Sperre ist der lokale `block`.
|
||||
*/
|
||||
class ExerciseSource extends Model
|
||||
{
|
||||
public const PROVIDED = 'bereitgestellt';
|
||||
|
||||
public const WITHDRAWN = 'nicht_mehr_bereitgestellt';
|
||||
|
||||
protected $fillable = ['source_system', 'source_id', 'composition_id', 'title', 'availability', 'last_hash', 'last_seen_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['last_seen_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
public function snapshots(): HasMany
|
||||
{
|
||||
return $this->hasMany(ExerciseSourceSnapshot::class)->orderBy('id');
|
||||
}
|
||||
|
||||
public function latestSnapshot(): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $this->snapshots()->reorder()->orderByDesc('id')->first();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ein abgerufener Inhaltsstand einer Quellübung (Prüfsumme der Quelle und ihre Nutzlast). Er ist unveränderlich;
|
||||
* nur die Übernahme trägt die daraus entstandene lokale Fassung ein.
|
||||
*/
|
||||
class ExerciseSourceSnapshot extends Model
|
||||
{
|
||||
protected $fillable = ['exercise_source_id', 'content_hash', 'payload', 'adopted_version_id', 'fetched_at'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['payload' => 'array', 'fetched_at' => 'datetime'];
|
||||
}
|
||||
|
||||
public function source(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ExerciseSource::class, 'exercise_source_id');
|
||||
}
|
||||
|
||||
public function adoptedVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(CompositionVersion::class, 'adopted_version_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Verwendungsnachweis: Wo wird eine Übungsfassung tatsächlich verwendet, und was trifft eine Sperre? Der Nachweis steigt
|
||||
* über die Verschachtelung bis zu den Wurzeln der Artikel-Stände auf und erfasst damit auch ältere, abgelöste und
|
||||
* gesperrte Stände. Er liest nur und ändert keinen Stand.
|
||||
*/
|
||||
class ExerciseUsage
|
||||
{
|
||||
/**
|
||||
* Je Fassung der Komposition: die einbindenden Fassungen (mit Rolle, Position und Variantenauswahl) und die
|
||||
* Artikel-Stände, deren Wurzel die Fassung selbst oder eine einbindende Fassung ist.
|
||||
*
|
||||
* @return list<array{version: CompositionVersion, hosts: list<array<string, mixed>>, releases: list<array<string, mixed>>}>
|
||||
*/
|
||||
public function forComposition(Composition $composition): array
|
||||
{
|
||||
$guide = app(ExerciseGuide::class);
|
||||
$result = [];
|
||||
|
||||
foreach ($composition->versions()->orderBy('number')->get() as $version) {
|
||||
$hosts = [];
|
||||
$roots = [$version->id => $version];
|
||||
$queue = [$version->id];
|
||||
$seen = [$version->id];
|
||||
|
||||
while ($queue !== []) {
|
||||
$current = array_shift($queue);
|
||||
|
||||
foreach (CompositionMember::query()->where('nested_composition_version_id', $current)->with('compositionVersion.composition')->orderBy('id')->get() as $member) {
|
||||
$host = $member->compositionVersion;
|
||||
|
||||
if ($host === null || $host->composition === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts[] = [
|
||||
'composition' => $host->composition,
|
||||
'version' => $host,
|
||||
'role' => $member->role,
|
||||
'position' => $member->position,
|
||||
'selection' => $member->variant_selection,
|
||||
'direct' => $current === $version->id,
|
||||
];
|
||||
|
||||
if (! in_array($host->id, $seen, true)) {
|
||||
$seen[] = $host->id;
|
||||
$roots[$host->id] = $host;
|
||||
$queue[] = $host->id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$releases = [];
|
||||
|
||||
foreach (ArticleRelease::query()->whereIn('root_composition_version_id', array_keys($roots))->with('article')->orderBy('license_article_id')->orderBy('number')->get() as $release) {
|
||||
$root = $roots[$release->root_composition_version_id];
|
||||
$releases[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'path' => $root->id === $version->id ? null : $guide->pathTo($root, $version->id),
|
||||
'root' => $root,
|
||||
];
|
||||
}
|
||||
|
||||
$result[] = ['version' => $version, 'hosts' => $hosts, 'releases' => $releases];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folgen einer Sperre dieser Medienfassung je Artikel-Stand. Die Festschreibung bleibt unverändert; gesperrt wird
|
||||
* nur die Ausgabe des Mediums.
|
||||
*
|
||||
* @return list<array{article: LicenseArticle, release: ArticleRelease, status: ReleaseStatus, variant: string|null, requirement: string|null, path: string, effect: string}>
|
||||
*/
|
||||
public function blockImpact(ContentElementVersion $version): array
|
||||
{
|
||||
$impact = [];
|
||||
|
||||
foreach (ReleaseContent::query()->where('content_element_version_id', $version->id)->with('release.article')->orderBy('id')->get() as $content) {
|
||||
$release = $content->release;
|
||||
$required = ($content->requirement ?? CompositionMember::REQUIRED) === CompositionMember::REQUIRED;
|
||||
$effect = match (true) {
|
||||
! $required => 'Nur dieses ergänzende Medium entfällt. Die Übung bleibt vollständig durchführbar.',
|
||||
$content->variant_key !== null => 'Die Variante „'.$content->variant_key.'“ ist nicht mehr vollständig durchführbar. Andere Varianten bleiben nutzbar.',
|
||||
default => 'Ein erforderlicher Bestandteil entfällt. Die Anleitung bleibt lesbar.',
|
||||
};
|
||||
$impact[] = [
|
||||
'article' => $release->article,
|
||||
'release' => $release,
|
||||
'status' => $release->status,
|
||||
'variant' => $content->variant_key,
|
||||
'requirement' => $content->requirement,
|
||||
'path' => $content->path,
|
||||
'effect' => $effect,
|
||||
];
|
||||
}
|
||||
|
||||
return $impact;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Erkennt Kompositionen, deren Art dieser Programmstand nicht kennt (siehe {@see SupportedKindScope}), und Aufbauten, die
|
||||
* solche Bestandteile enthalten. Gelesen wird am Modell vorbei, weil der Bereichsfilter diese Zeilen ausblendet.
|
||||
*
|
||||
* Wozu: Eine ältere Programmversion darf eine Fassung mit unbekanntem Bestandteil weder neu veröffentlichen noch
|
||||
* überarbeiten. Sie würde den Bestandteil auslassen oder ohne seine Variantenwahl auflösen und damit Inhalt verlieren
|
||||
* oder zu viel ausgeben.
|
||||
*/
|
||||
class ForeignCompositions
|
||||
{
|
||||
public function isForeignVersion(int $compositionVersionId): bool
|
||||
{
|
||||
return DB::table('composition_versions as v')
|
||||
->join('compositions as c', 'c.id', '=', 'v.composition_id')
|
||||
->where('v.id', $compositionVersionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $target „composition:ID“ (Fassung) oder „composition-draft:ID“ (Komposition)
|
||||
*/
|
||||
public function isForeignTarget(string $target): bool
|
||||
{
|
||||
if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) {
|
||||
return $this->isForeignVersion((int) $match[1]);
|
||||
}
|
||||
|
||||
if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) {
|
||||
return DB::table('compositions')
|
||||
->where('id', (int) $match[1])
|
||||
->whereNotIn('kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ist die Fassung selbst unbekannt oder erreicht sie, auch verschachtelt, einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function reaches(ContentElementVersion|CompositionVersion $node): bool
|
||||
{
|
||||
return $node instanceof CompositionVersion && $this->reachesVersion($node->id, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enthält irgendeine Fassung dieser Komposition einen unbekannten Bestandteil?
|
||||
*/
|
||||
public function compositionHasForeignMembers(int $compositionId): bool
|
||||
{
|
||||
return DB::table('composition_members as m')
|
||||
->join('composition_versions as host', 'host.id', '=', 'm.composition_version_id')
|
||||
->join('composition_versions as nested', 'nested.id', '=', 'm.nested_composition_version_id')
|
||||
->join('compositions as c', 'c.id', '=', 'nested.composition_id')
|
||||
->where('host.composition_id', $compositionId)
|
||||
->whereNotIn('c.kind', CompositionKind::values())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $seen
|
||||
*/
|
||||
private function reachesVersion(int $versionId, array $seen): bool
|
||||
{
|
||||
if (in_array($versionId, $seen, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->isForeignVersion($versionId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$seen[] = $versionId;
|
||||
|
||||
foreach (DB::table('composition_members')
|
||||
->where('composition_version_id', $versionId)
|
||||
->whereNotNull('nested_composition_version_id')
|
||||
->pluck('nested_composition_version_id') as $nestedId) {
|
||||
if ($this->reachesVersion((int) $nestedId, $seen)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,728 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Dom\HTMLDocument;
|
||||
use Dom\Node;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
|
||||
|
||||
/**
|
||||
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51).
|
||||
*
|
||||
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschriften (h3 bis h6), fett, kursiv, Aufzählung,
|
||||
* nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte,
|
||||
* Ereignisattribute und Links auf andere Schemata als http, https und mailto.
|
||||
*
|
||||
* Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`<img data-id="…" alt="…">`).
|
||||
* Die Adresse entsteht erst bei der Ausgabe, je nach Leser (Verwaltung, Mitglied mit Berechtigung, PDF). Ohne Auflösung
|
||||
* zeigt die Ausgabe kein Bild.
|
||||
*
|
||||
* Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe
|
||||
* Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der
|
||||
* Text beginnt (nach Leerraum) mit einem der Blockelemente dieser Auswahl. Gespeichertes HTML ist kanonisch und beginnt
|
||||
* deshalb immer so; Klartext beginnt nie mit einem solchen Tag, wenn er nicht von Hand so geschrieben wurde.
|
||||
*
|
||||
* Verglichen und gehasht wird immer nur die kanonische Form ({@see self::canonical()}), damit das Öffnen im Editor oder
|
||||
* eine andere Schreibweise desselben Inhalts keine neue Fassung und keinen Scheinkonflikt erzeugt.
|
||||
*/
|
||||
final class FormattedText
|
||||
{
|
||||
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
|
||||
private const BLOCKS = ['p', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||||
|
||||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||||
public const FIELDS = ['summary', 'description'];
|
||||
|
||||
private static ?HtmlSanitizer $sanitizer = null;
|
||||
|
||||
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
|
||||
public const TOOLBAR = [
|
||||
['bold', 'italic', 'link'],
|
||||
['h3', 'h4', 'h5', 'h6'],
|
||||
['bulletList', 'orderedList', 'blockquote'],
|
||||
['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'],
|
||||
['undo', 'redo'],
|
||||
];
|
||||
|
||||
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
|
||||
public static function isHtml(?string $value): bool
|
||||
{
|
||||
return preg_match('/^\s*<(?:'.implode('|', self::BLOCKS).')[\s>\/]/i', (string) $value) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
|
||||
*/
|
||||
public static function canonical(?string $value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
|
||||
* einem Blockelement beginnt.
|
||||
*/
|
||||
public static function canonicalHtml(?string $html): string
|
||||
{
|
||||
$html = trim((string) $html);
|
||||
|
||||
return $html === '' ? '' : self::normalize($html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt.
|
||||
*
|
||||
* Bilder erscheinen nur, wenn `$images` sie auflöst: Die Funktion bekommt die Kennung der Bildfassung und liefert
|
||||
* `['src' => Adresse, 'alt' => Text]` (Bild), `['note' => Text]` (Hinweis an der Stelle des Bilds) oder null (Bild
|
||||
* entfällt). Ohne Funktion entfallen alle Bilder; so zeigt keine Ausgabe versehentlich ein Bild ohne Rechteprüfung.
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function html(?string $value, ?callable $images = null): string
|
||||
{
|
||||
return self::renderImages(self::canonical($value), $images);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe an Stellen, die Klartext des Altbestands bisher mit Zeilenumbrüchen zeigten: HTML wird
|
||||
* bereinigt ausgegeben, Klartext bleibt, wie er war (maskiert, Zeilenumbrüche erhalten).
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function display(?string $value, ?callable $images = null): string
|
||||
{
|
||||
$value = (string) $value;
|
||||
|
||||
return self::isHtml($value) ? self::renderImages(self::canonical($value), $images) : nl2br(e($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bildfassungen, auf die ein Text verweist, in der Reihenfolge ihres Auftretens (ohne Wiederholung).
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public static function imageIds(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = [];
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$id = (int) $image->getAttribute('data-id');
|
||||
|
||||
if ($id > 0 && ! in_array($id, $ids, true)) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Versieht die Zwischenüberschriften (h3 bis h6, auf oberster Ebene des Texts) mit Sprungmarken `<Präfix>-u<n>` und
|
||||
* verschiebt ihre Stufe um `$shift` (höchstens h6). Die Marken zählen die nicht leeren Überschriften in ihrer Reihenfolge;
|
||||
* {@see self::blocks()} zählt dieselben.
|
||||
*
|
||||
* @return array{html: string, headings: list<array{level: int, text: string, anchor: string}>}
|
||||
*/
|
||||
public static function anchorHeadings(string $html, string $prefix, int $shift = 0): array
|
||||
{
|
||||
if (preg_match('/<h[3-6][\s>]/i', $html) !== 1) {
|
||||
return ['html' => $html, 'headings' => []];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$headings = [];
|
||||
|
||||
foreach (iterator_to_array($document->body->childNodes) as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE || preg_match('/^h([3-6])$/', strtolower($node->nodeName), $match) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', (string) $node->textContent));
|
||||
|
||||
if ($text === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = min(6, (int) $match[1] + $shift);
|
||||
$anchor = $prefix.'-u'.(count($headings) + 1);
|
||||
$replacement = $document->createElement('h'.$level);
|
||||
$replacement->setAttribute('id', $anchor);
|
||||
|
||||
while ($node->firstChild !== null) {
|
||||
$replacement->appendChild($node->firstChild);
|
||||
}
|
||||
|
||||
$node->replaceWith($replacement);
|
||||
$headings[] = ['level' => $level, 'text' => $text, 'anchor' => $anchor];
|
||||
}
|
||||
|
||||
return ['html' => trim($document->body->innerHTML), 'headings' => $headings];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fügt die Adresse an jedes Bild, damit der Editor es zeigt. Die Adresse gehört nicht zum gespeicherten Wert: Die
|
||||
* Bereinigung entfernt sie beim Übernehmen aus dem Editor wieder.
|
||||
*
|
||||
* @param callable(int): ?string $source
|
||||
*/
|
||||
public static function forEditor(string $html, callable $source): string
|
||||
{
|
||||
if (! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$src = $source((int) $image->getAttribute('data-id'));
|
||||
|
||||
if ($src !== null) {
|
||||
$image->setAttribute('src', $src);
|
||||
}
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
private static function renderImages(string $html, ?callable $images): string
|
||||
{
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
$found = $images === null ? null : $images((int) $image->getAttribute('data-id'));
|
||||
|
||||
if (isset($found['src'])) {
|
||||
$image->removeAttribute('data-id');
|
||||
$image->setAttribute('src', (string) $found['src']);
|
||||
$image->setAttribute('alt', (string) ($found['alt'] ?? $image->getAttribute('alt')));
|
||||
$image->setAttribute('loading', 'lazy');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($found['note'])) {
|
||||
$note = $document->createElement('p');
|
||||
$note->setAttribute('class', 'mb-bildhinweis');
|
||||
$note->textContent = (string) $found['note'];
|
||||
$image->replaceWith($note);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$image->remove();
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
public static function isBlank(?string $value): bool
|
||||
{
|
||||
return self::canonical($value) === '';
|
||||
}
|
||||
|
||||
/** Sind beide Werte inhaltlich gleich (unabhängig von Klartext oder Schreibweise des HTML)? */
|
||||
public static function same(?string $a, ?string $b): bool
|
||||
{
|
||||
return self::canonical($a) === self::canonical($b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text ohne Auszeichnung für Orte, die kein HTML vertragen (Zahlungsdienst, Meta-Beschreibung, Listen). Absätze sind
|
||||
* durch Leerzeilen getrennt, Listenpunkte beginnen mit „- “ beziehungsweise „1. “.
|
||||
*/
|
||||
public static function plain(?string $value): string
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach (self::blocks($value) as $block) {
|
||||
$text = self::plainBlock($block);
|
||||
|
||||
if ($text !== '') {
|
||||
$out[] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
return trim(implode("\n\n", $out));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private static function plainBlock(array $block): string
|
||||
{
|
||||
return match ($block['type']) {
|
||||
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
|
||||
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
|
||||
'table' => implode("\n", array_map(
|
||||
fn (array $row): string => implode(' | ', array_map(
|
||||
fn (array $cell): string => trim((string) preg_replace('/\s+/u', ' ', implode(' ', array_filter(array_map(fn (array $inner): string => self::plainBlock($inner), $cell['blocks']))))),
|
||||
$row,
|
||||
)),
|
||||
$block['rows'],
|
||||
)),
|
||||
// Ein Bild hat im Klartext keinen Platz (Listen, Auszüge, Meta-Beschreibung).
|
||||
'image' => '',
|
||||
default => self::runsText($block['runs']),
|
||||
};
|
||||
}
|
||||
|
||||
/** Kurzer Text für Listen und Karten. */
|
||||
public static function excerpt(?string $value, int $length = 120): string
|
||||
{
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', self::plain($value)));
|
||||
|
||||
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
|
||||
* `href`. Eine Tabelle besteht aus Zeilen mit Zellen (`header`, `colspan`, `rowspan`, `blocks`); ein Bild trägt die
|
||||
* Kennung seiner Bildfassung (`id`) und den Alternativtext.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function blocks(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
return self::extractBlocks($document->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private static function extractBlocks(Node $parent): array
|
||||
{
|
||||
$blocks = [];
|
||||
|
||||
foreach ($parent->childNodes as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = [];
|
||||
|
||||
foreach ($node->childNodes as $item) {
|
||||
if ($item->nodeType === XML_ELEMENT_NODE && strtolower($item->nodeName) === 'li') {
|
||||
$items[] = self::runs($item);
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => $name === 'ul' ? 'bullets' : 'numbered', 'items' => $items];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'img') {
|
||||
$blocks[] = ['type' => 'image', 'id' => (int) $node->getAttribute('data-id'), 'alt' => (string) $node->getAttribute('alt')];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->querySelectorAll('tr') as $row) {
|
||||
$cells = [];
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cells[] = [
|
||||
'header' => strtolower($cell->nodeName) === 'th',
|
||||
'colspan' => max(1, (int) $cell->getAttribute('colspan')),
|
||||
'rowspan' => max(1, (int) $cell->getAttribute('rowspan')),
|
||||
'blocks' => self::extractBlocks($cell),
|
||||
];
|
||||
}
|
||||
|
||||
if ($cells !== []) {
|
||||
$rows[] = $cells;
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => 'table', 'rows' => $rows];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = preg_match('/^h([3-6])$/', $name, $heading) === 1 ? (int) $heading[1] : 0;
|
||||
$type = match (true) {
|
||||
$level > 0 => 'heading',
|
||||
$name === 'blockquote' => 'quote',
|
||||
default => 'paragraph',
|
||||
};
|
||||
|
||||
// Ein Bild mitten im Absatz (so setzt der Editor es) teilt den Absatz: Text davor, Bild, Text danach.
|
||||
$images = $node->querySelectorAll('img');
|
||||
|
||||
if (count($images) === 0) {
|
||||
$blocks[] = self::textBlock($type, $level, self::runs($node));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$pending = [];
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'img') {
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
|
||||
$pending = [];
|
||||
$blocks[] = ['type' => 'image', 'id' => (int) $child->getAttribute('data-id'), 'alt' => (string) $child->getAttribute('alt')];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$holder = $node->ownerDocument->createElement('span');
|
||||
$holder->appendChild($child->cloneNode(true));
|
||||
$pending = [...$pending, ...self::runs($holder)];
|
||||
}
|
||||
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Textblock; eine Überschrift trägt zusätzlich ihre Stufe (3 bis 6) und ihren Text ohne Auszeichnung.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function textBlock(string $type, int $level, array $runs): array
|
||||
{
|
||||
return $type === 'heading'
|
||||
? ['type' => $type, 'level' => $level, 'text' => self::runsText($runs), 'runs' => $runs]
|
||||
: ['type' => $type, 'runs' => $runs];
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
|
||||
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
|
||||
*/
|
||||
public static function legacyToHtml(?string $text): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach (GuideText::blocks($text) as $block) {
|
||||
$html .= match ($block['type']) {
|
||||
'heading' => '<h3>'.e($block['text']).'</h3>',
|
||||
'bullets' => '<ul>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ul>',
|
||||
'numbered' => '<ol>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ol>',
|
||||
default => '<p>'.e($block['text']).'</p>',
|
||||
};
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
private static function normalize(string $html): string
|
||||
{
|
||||
$html = self::mapLegacyTags($html);
|
||||
$html = trim(self::sanitizer()->sanitize($html));
|
||||
|
||||
if ($html === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$body = $document->body;
|
||||
|
||||
// Ein Bild steht zwischen den Absätzen, in einem Absatz (so setzt der Editor es) oder in einer Tabellenzelle und braucht
|
||||
// seine Bildfassung. Anderswo (Liste, Zitat, Überschrift) entfällt es.
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
if (! self::mayHoldImage($image->parentNode, $body) || (int) $image->getAttribute('data-id') < 1) {
|
||||
$image->remove();
|
||||
}
|
||||
}
|
||||
|
||||
$out = '';
|
||||
$loose = '';
|
||||
|
||||
$flush = function () use (&$out, &$loose): void {
|
||||
$loose = trim($loose);
|
||||
|
||||
if ($loose !== '' && trim(strip_tags(str_replace(['<br>', '<br/>', '<br />'], '', $loose))) !== '') {
|
||||
$out .= '<p>'.$loose.'</p>';
|
||||
}
|
||||
|
||||
$loose = '';
|
||||
};
|
||||
|
||||
foreach ($body->childNodes as $node) {
|
||||
if ($node->nodeType === XML_ELEMENT_NODE && in_array(strtolower($node->nodeName), self::BLOCKS, true)) {
|
||||
$flush();
|
||||
$out .= self::block($node);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$loose .= $document->saveHtml($node);
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
return self::hasText($out) || str_contains($out, '<img') ? $out : '';
|
||||
}
|
||||
|
||||
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
|
||||
private static function block(Node $node): string
|
||||
{
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if ($name === 'img') {
|
||||
$id = (int) $node->getAttribute('data-id');
|
||||
|
||||
return $id > 0 ? '<img data-id="'.$id.'" alt="'.e(trim((string) $node->getAttribute('alt'))).'">' : '';
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
return self::table($node);
|
||||
}
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$inner = self::inner($child);
|
||||
|
||||
if (! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
if (self::hasText($inner)) {
|
||||
$items .= '<li>'.$inner.'</li>';
|
||||
}
|
||||
}
|
||||
|
||||
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
|
||||
}
|
||||
|
||||
$inner = self::inner($node);
|
||||
|
||||
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Tabelle in der festen Form des Editors: Zeilen mit Kopf- (`th`) und Datenzellen (`td`), Zellen mit Absätzen,
|
||||
* Verbindungen nur als `colspan` und `rowspan` über 1. Breiten, Gestaltung und Zwischenebenen entfallen.
|
||||
*/
|
||||
private static function table(Node $table): string
|
||||
{
|
||||
$rows = '';
|
||||
|
||||
foreach ($table->querySelectorAll('tr') as $row) {
|
||||
$cells = '';
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($cell->nodeName);
|
||||
$attributes = '';
|
||||
|
||||
foreach (['colspan', 'rowspan'] as $span) {
|
||||
$value = (int) $cell->getAttribute($span);
|
||||
|
||||
if ($value > 1) {
|
||||
$attributes .= ' '.$span.'="'.min($value, 50).'"';
|
||||
}
|
||||
}
|
||||
|
||||
$inner = self::inner($cell);
|
||||
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h[3-6]|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||||
}
|
||||
|
||||
if ($cells !== '') {
|
||||
$rows .= '<tr>'.$cells.'</tr>';
|
||||
}
|
||||
}
|
||||
|
||||
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
|
||||
}
|
||||
|
||||
private static function inner(Node $node): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote', 'img'], true)) {
|
||||
$html .= self::block($child);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$html .= $node->ownerDocument->saveHtml($child);
|
||||
}
|
||||
|
||||
return trim($html);
|
||||
}
|
||||
|
||||
/** Wo darf ein Bild stehen: im Text, in einer Tabellenzelle oder in einem Absatz dort. */
|
||||
private static function mayHoldImage(?Node $parent, Node $body): bool
|
||||
{
|
||||
if ($parent === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$name = strtolower($parent->nodeName);
|
||||
|
||||
if ($parent === $body || in_array($name, ['td', 'th'], true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $name === 'p' && $parent->parentNode !== null && ($parent->parentNode === $body || in_array(strtolower($parent->parentNode->nodeName), ['td', 'th'], true));
|
||||
}
|
||||
|
||||
/** Hat der Ausschnitt einen Inhalt: Text oder ein Bild? */
|
||||
private static function hasContent(string $html): bool
|
||||
{
|
||||
return self::hasText($html) || str_contains($html, '<img');
|
||||
}
|
||||
|
||||
private static function hasText(string $html): bool
|
||||
{
|
||||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
|
||||
}
|
||||
|
||||
/** b, i und die Überschriftsstufen 1 und 2 der Quelle werden auf die feste Auswahl abgebildet (h1 und h2 gehören dem Dokument und dem Kapitel); der Rest fällt in der Bereinigung weg. */
|
||||
private static function mapLegacyTags(string $html): string
|
||||
{
|
||||
$html = (string) preg_replace('/<(\/?)b(?=[\s>\/])/i', '<$1strong', $html);
|
||||
$html = (string) preg_replace('/<(\/?)i(?=[\s>\/])/i', '<$1em', $html);
|
||||
$html = (string) preg_replace('/<(\/?)h[12](?=[\s>\/])/i', '<$1h3', $html);
|
||||
|
||||
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{text: string, bold: bool, italic: bool, href: ?string}>
|
||||
*/
|
||||
private static function runs(Node $node, bool $bold = false, bool $italic = false, ?string $href = null): array
|
||||
{
|
||||
$runs = [];
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_TEXT_NODE) {
|
||||
$runs[] = ['text' => (string) $child->textContent, 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($child->nodeName);
|
||||
|
||||
if ($name === 'br') {
|
||||
$runs[] = ['text' => "\n", 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($name, ['p', 'ul', 'ol', 'blockquote'], true)) {
|
||||
// Verschachtelte Blöcke (Absatz im Listenpunkt) werden zu Fließtext.
|
||||
$runs = [...$runs, ...self::runs($child, $bold, $italic, $href)];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$runs = [...$runs, ...self::runs(
|
||||
$child,
|
||||
$bold || $name === 'strong',
|
||||
$italic || $name === 'em',
|
||||
$name === 'a' ? ((string) $child->getAttribute('href') ?: $href) : $href,
|
||||
)];
|
||||
}
|
||||
|
||||
return $runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
private static function runsText(array $runs): string
|
||||
{
|
||||
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
|
||||
}
|
||||
|
||||
private static function sanitizer(): HtmlSanitizer
|
||||
{
|
||||
return self::$sanitizer ??= new HtmlSanitizer(
|
||||
(new HtmlSanitizerConfig)
|
||||
->allowElement('p')
|
||||
->allowElement('br')
|
||||
->allowElement('h3')
|
||||
->allowElement('h4')
|
||||
->allowElement('h5')
|
||||
->allowElement('h6')
|
||||
->allowElement('strong')
|
||||
->allowElement('em')
|
||||
->allowElement('ul')
|
||||
->allowElement('ol')
|
||||
->allowElement('li')
|
||||
->allowElement('blockquote')
|
||||
->allowElement('table')
|
||||
->allowElement('thead')
|
||||
->allowElement('tbody')
|
||||
->allowElement('tfoot')
|
||||
->allowElement('tr')
|
||||
->allowElement('th', ['colspan', 'rowspan'])
|
||||
->allowElement('td', ['colspan', 'rowspan'])
|
||||
->allowElement('img', ['data-id', 'alt'])
|
||||
->allowElement('a', ['href'])
|
||||
->allowLinkSchemes(['http', 'https', 'mailto'])
|
||||
->allowRelativeLinks(false)
|
||||
->forceAttribute('a', 'rel', 'noopener noreferrer')
|
||||
->withMaxInputLength(100000),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Anleitungstext als Klartext mit wenigen Konventionen: Absätze an Leerzeilen, Listen mit „- “ oder „• “ und
|
||||
* nummerierte Listen mit „1. “, Zwischenüberschriften mit „## “. Ansicht und PDF lesen dieselben Blöcke und zeigen damit
|
||||
* dieselbe Fassung. Es gibt kein freies HTML.
|
||||
*/
|
||||
final class GuideText
|
||||
{
|
||||
/**
|
||||
* @return list<array{type: 'paragraph'|'bullets'|'numbered'|'heading', text?: string, items?: list<string>}>
|
||||
*/
|
||||
public static function blocks(?string $body): array
|
||||
{
|
||||
$blocks = [];
|
||||
$paragraph = [];
|
||||
$list = null;
|
||||
|
||||
$flushParagraph = function () use (&$blocks, &$paragraph): void {
|
||||
if ($paragraph !== []) {
|
||||
$blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)];
|
||||
$paragraph = [];
|
||||
}
|
||||
};
|
||||
$flushList = function () use (&$blocks, &$list): void {
|
||||
if ($list !== null) {
|
||||
$blocks[] = ['type' => $list['type'], 'items' => $list['items']];
|
||||
$list = null;
|
||||
}
|
||||
};
|
||||
|
||||
foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) {
|
||||
$line = rtrim($line);
|
||||
|
||||
if (trim($line) === '') {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
$blocks[] = ['type' => 'heading', 'text' => trim($match[1])];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'bullets') {
|
||||
$flushList();
|
||||
$list = ['type' => 'bullets', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) {
|
||||
$flushParagraph();
|
||||
if ($list === null || $list['type'] !== 'numbered') {
|
||||
$flushList();
|
||||
$list = ['type' => 'numbered', 'items' => []];
|
||||
}
|
||||
|
||||
$list['items'][] = trim($match[1]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$flushList();
|
||||
$paragraph[] = trim($line);
|
||||
}
|
||||
|
||||
$flushParagraph();
|
||||
$flushList();
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Übernimmt die frühere Kopie „Fachliche Säule“ (Dimension `saeule`) in die zentrale Säulenverwaltung (Tabelle
|
||||
* `pillars`). Verlustfrei, wiederholbar und ohne Raten:
|
||||
*
|
||||
* - **Zuordnung Wert → Säule** nur über die gespeicherte Kennung `pfeiler-{Säulenkennung}`, die die Migration
|
||||
* vom 16.11.2026 beim Spiegeln geschrieben hat, und nur, wenn die Säule existiert und nicht jünger als der Wert ist
|
||||
* (sonst kann die Kennung nicht aus ihr entstanden sein). Eine abweichende Bezeichnung ist nach einem Umbenennen
|
||||
* erwartet und wird nur berichtet. Die Verknüpfung steht in `editorial_dimension_values.pillar_id`.
|
||||
* - **Übernommen** werden nur direkte Zuordnungen von Modulen, Programmen und Lizenzartikeln in `composition_pillar`
|
||||
* und `license_article_pillar` (insert-or-ignore, daher beliebig oft ausführbar).
|
||||
* - **Nicht übernommen, sondern gemeldet:** Werte ohne belastbare Kennung, Zuordnungen zu fehlenden Objekten,
|
||||
* abgeleitete Zuordnungen und unbekannte Objektarten. Abgeleitete Säulen eines Programms oder Moduls entstehen zur
|
||||
* Laufzeit aus den enthaltenen Medien und werden nie als direkte Zuordnung gespeichert.
|
||||
* - **Medien:** Die gespiegelten Zeilen sind eine veraltete Kopie; maßgeblich ist `content_element_pillar`. Sie werden
|
||||
* nicht zurückgemischt, nur gezählt.
|
||||
* - Alte Zeilen werden weder geändert noch gelöscht.
|
||||
*
|
||||
* Nur die Datenbankfassade, damit spätere Änderungen an Modellen die Migration nicht berühren.
|
||||
*/
|
||||
final class LegacyPillarAdoption
|
||||
{
|
||||
/** @var array<string, array{table: string, column: string, subjects: string}> */
|
||||
private const TARGETS = [
|
||||
'composition' => ['table' => 'composition_pillar', 'column' => 'composition_id', 'subjects' => 'compositions'],
|
||||
'license_article' => ['table' => 'license_article_pillar', 'column' => 'license_article_id', 'subjects' => 'license_articles'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* mapping: list<array<string, mixed>>,
|
||||
* unresolved: list<array<string, mixed>>,
|
||||
* copied: array<string, int>,
|
||||
* already: array<string, int>,
|
||||
* before: array<string, int>,
|
||||
* after: array<string, int>,
|
||||
* mirror: array<string, int>
|
||||
* }
|
||||
*/
|
||||
public function run(bool $dryRun = false): array
|
||||
{
|
||||
$report = [
|
||||
'mapping' => [],
|
||||
'unresolved' => [],
|
||||
'copied' => ['composition' => 0, 'license_article' => 0],
|
||||
'already' => ['composition' => 0, 'license_article' => 0],
|
||||
'before' => $this->counts(),
|
||||
'after' => [],
|
||||
'mirror' => ['element_rows' => 0, 'missing_in_pivot' => 0, 'only_in_pivot' => 0],
|
||||
];
|
||||
|
||||
$dimension = DB::table('editorial_dimensions')->where('slug', 'saeule')->first();
|
||||
|
||||
if ($dimension === null) {
|
||||
$report['after'] = $report['before'];
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
$resolved = [];
|
||||
|
||||
foreach (DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->orderBy('id')->get() as $value) {
|
||||
$pillar = $this->pillarFor($value);
|
||||
|
||||
if (is_string($pillar)) {
|
||||
$report['unresolved'][] = ['art' => 'Wert', 'wert_id' => (int) $value->id, 'wert' => $value->label, 'kennung' => $value->slug, 'grund' => $pillar];
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => null, 'status' => 'offen'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$resolved[(int) $value->id] = (int) $pillar->id;
|
||||
$status = $value->pillar_id === null ? 'zugeordnet' : 'bereits zugeordnet';
|
||||
$hint = $value->label !== $pillar->name ? 'über Kennung zugeordnet, Bezeichnung weicht ab („'.$pillar->name.'“)' : null;
|
||||
$report['mapping'][] = ['wert_id' => (int) $value->id, 'wert' => $value->label, 'saeule_id' => (int) $pillar->id, 'saeule' => $pillar->name, 'status' => $status, 'hinweis' => $hint];
|
||||
|
||||
if ($value->pillar_id === null && ! $dryRun) {
|
||||
DB::table('editorial_dimension_values')->where('id', $value->id)->update(['pillar_id' => $pillar->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$subjectTypes = $this->subjectTypes();
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('editorial_dimension_value_id', DB::table('editorial_dimension_values')->where('editorial_dimension_id', $dimension->id)->select('id'))
|
||||
->orderBy('id')->get() as $row) {
|
||||
$valueId = (int) $row->editorial_dimension_value_id;
|
||||
$label = DB::table('editorial_dimension_values')->where('id', $valueId)->value('label');
|
||||
$target = $subjectTypes[$row->subject_type] ?? null;
|
||||
|
||||
if ($target === 'content_element') {
|
||||
$report['mirror']['element_rows']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$where = ['art' => 'Zuordnung', 'zuordnung_id' => (int) $row->id, 'wert_id' => $valueId, 'wert' => $label, 'objektart' => $row->subject_type, 'objekt_id' => (int) $row->subject_id, 'herkunft' => $row->origin];
|
||||
|
||||
if ($target === null) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'unbekannte Objektart'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($row->origin !== 'direkt') {
|
||||
$report['unresolved'][] = $where + ['grund' => 'abgeleitete Zuordnung (wird nicht als direkte übernommen)'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($resolved[$valueId])) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Wert ohne belastbare Säule'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$config = self::TARGETS[$target];
|
||||
|
||||
if (! DB::table($config['subjects'])->where('id', $row->subject_id)->exists()) {
|
||||
$report['unresolved'][] = $where + ['grund' => 'Objekt nicht mehr vorhanden'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = DB::table($config['table'])->where($config['column'], $row->subject_id)->where('pillar_id', $resolved[$valueId])->exists();
|
||||
|
||||
if ($present) {
|
||||
$report['already'][$target]++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $dryRun) {
|
||||
DB::table($config['table'])->insertOrIgnore([$config['column'] => $row->subject_id, 'pillar_id' => $resolved[$valueId]]);
|
||||
}
|
||||
|
||||
$report['copied'][$target]++;
|
||||
}
|
||||
|
||||
$report['mirror'] = array_merge($report['mirror'], $this->mirrorDivergence($dimension->id, $resolved));
|
||||
$report['after'] = $dryRun ? $report['before'] : $this->counts();
|
||||
|
||||
return $report;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $report
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function lines(array $report, bool $dryRun = false): array
|
||||
{
|
||||
$names = ['composition' => 'Module und Programme', 'license_article' => 'Lizenzartikel'];
|
||||
$lines = [$dryRun ? 'Probelauf, es wird nichts geschrieben.' : 'Übernahme abgeschlossen.', ''];
|
||||
|
||||
foreach ($report['mapping'] as $row) {
|
||||
$lines[] = sprintf('Wert %d „%s“ → %s%s', $row['wert_id'], $row['wert'], $row['saeule_id'] === null ? 'keine Säule (offen)' : 'Säule '.$row['saeule_id'].' „'.($row['saeule'] ?? '').'“ ('.$row['status'].')', ! empty($row['hinweis']) ? ' – '.$row['hinweis'] : '');
|
||||
}
|
||||
|
||||
$lines[] = '';
|
||||
|
||||
foreach ($names as $key => $label) {
|
||||
$lines[] = sprintf('%s: %d übernommen, %d bereits vorhanden, Zuordnungen vorher %d, nachher %d', $label, $report['copied'][$key], $report['already'][$key], $report['before'][$key], $report['after'][$key]);
|
||||
}
|
||||
|
||||
$lines[] = sprintf('Medien (nur Information): %d gespiegelte Zeilen, %d nicht mehr in der Medienzuordnung, %d nur dort. Maßgeblich bleibt die Medienzuordnung.', $report['mirror']['element_rows'], $report['mirror']['missing_in_pivot'], $report['mirror']['only_in_pivot']);
|
||||
|
||||
if ($report['unresolved'] === []) {
|
||||
$lines[] = 'Keine ungeklärten Fälle.';
|
||||
} else {
|
||||
$lines[] = '';
|
||||
$lines[] = 'Ungeklärt, bitte entscheiden (nichts wurde geändert):';
|
||||
|
||||
foreach ($report['unresolved'] as $row) {
|
||||
$lines[] = '- '.json_encode($row, JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Säule zu einem alten Wert, oder der Grund, warum es keine belastbare gibt.
|
||||
*/
|
||||
private function pillarFor(object $value): object|string
|
||||
{
|
||||
if (preg_match('/^pfeiler-(\d+)$/', (string) $value->slug, $match) !== 1) {
|
||||
return 'Kennung ist nicht „pfeiler-<Nummer>“, keine belastbare Verknüpfung';
|
||||
}
|
||||
|
||||
$pillar = DB::table('pillars')->where('id', (int) $match[1])->first();
|
||||
|
||||
if ($pillar === null) {
|
||||
return 'Die Säule zur Kennung existiert nicht mehr';
|
||||
}
|
||||
|
||||
if ($value->pillar_id !== null && (int) $value->pillar_id !== (int) $pillar->id) {
|
||||
return 'Gespeicherte Verknüpfung (Säule '.$value->pillar_id.') und Kennung (Säule '.$pillar->id.') widersprechen sich';
|
||||
}
|
||||
|
||||
if ($pillar->created_at !== null && $value->created_at !== null && $pillar->created_at > $value->created_at) {
|
||||
return 'Die Säule ist jünger als der Wert; die Kennung kann nicht aus ihr entstanden sein';
|
||||
}
|
||||
|
||||
return $pillar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> Objektart wie gespeichert => Ziel
|
||||
*/
|
||||
private function subjectTypes(): array
|
||||
{
|
||||
$types = [];
|
||||
|
||||
foreach ([
|
||||
'composition' => [Composition::class],
|
||||
'license_article' => [LicenseArticle::class],
|
||||
'content_element' => [ContentElement::class],
|
||||
] as $target => $classes) {
|
||||
foreach ($classes as $class) {
|
||||
$types[$class] = $target;
|
||||
$types[(new $class)->getMorphClass()] = $target;
|
||||
}
|
||||
}
|
||||
|
||||
return $types;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function counts(): array
|
||||
{
|
||||
return [
|
||||
'composition' => DB::table('composition_pillar')->count(),
|
||||
'license_article' => DB::table('license_article_pillar')->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $resolved
|
||||
* @return array{missing_in_pivot: int, only_in_pivot: int}
|
||||
*/
|
||||
private function mirrorDivergence(int $dimensionId, array $resolved): array
|
||||
{
|
||||
$mirrored = [];
|
||||
|
||||
foreach (DB::table('identity_dimension_values')
|
||||
->whereIn('subject_type', array_unique([ContentElement::class, (new ContentElement)->getMorphClass()]))
|
||||
->whereIn('editorial_dimension_value_id', array_keys($resolved) ?: [0])
|
||||
->get() as $row) {
|
||||
$mirrored[$row->subject_id.':'.$resolved[(int) $row->editorial_dimension_value_id]] = true;
|
||||
}
|
||||
|
||||
$pivot = [];
|
||||
|
||||
foreach (DB::table('content_element_pillar')->get() as $row) {
|
||||
$pivot[$row->content_element_id.':'.$row->pillar_id] = true;
|
||||
}
|
||||
|
||||
return [
|
||||
'missing_in_pivot' => count(array_diff_key($mirrored, $pivot)),
|
||||
'only_in_pivot' => count(array_diff_key($pivot, $mirrored)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > self::MAX_TRAINERS) {
|
||||
throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.');
|
||||
}
|
||||
|
||||
return [self::MULTI, $count];
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.');
|
||||
}
|
||||
|
||||
/** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */
|
||||
public static function label(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Einzellizenz · 1 Trainer',
|
||||
self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer',
|
||||
default => 'Nutzerkreis nicht festgelegt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */
|
||||
public static function explanation(?string $scope, ?int $trainers): ?string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.',
|
||||
self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */
|
||||
public static function key(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return ($scope ?? '-').'|'.($trainers ?? 0);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class LicenseArticle extends Model
|
||||
@@ -49,4 +50,10 @@ public function editorialContentKind(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EditorialContentKind::class);
|
||||
}
|
||||
|
||||
/** Direkt zugeordnete fachliche Säulen (zentrale Säulenverwaltung). */
|
||||
public function pillars(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Pillar::class)->orderBy('pillars.sort_order')->orderBy('pillars.name');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Material-Tags des Brand-Kits (Film, Übung, PDF, Paket, Film + Übungen, Film + Merkblatt).
|
||||
*
|
||||
* Die Zuordnung hängt an Schlüsseln (Ausgabeklasse des Mediums, Kennung der redaktionellen Art), nie an Beschriftungen.
|
||||
* Was nicht eindeutig zuzuordnen ist, bekommt kein Tag und bleibt Text:
|
||||
* - „Paket“ und die beiden Kombinationen werden nicht automatisch vergeben (offen: Paket als Angebot oder als Programm;
|
||||
* Kombinationen aus dem Modulaufbau berechnen oder redaktionell wählen). Die Komponente kann sie darstellen.
|
||||
* - „Dokument“ ist nicht automatisch PDF; das Tag PDF gibt es nur für die Ausgabeklasse „pdf“.
|
||||
*/
|
||||
enum MaterialTag: string
|
||||
{
|
||||
case Film = 'film';
|
||||
case Uebung = 'uebung';
|
||||
case Pdf = 'pdf';
|
||||
case Paket = 'paket';
|
||||
case FilmUebungen = 'film-uebungen';
|
||||
case FilmMerkblatt = 'film-merkblatt';
|
||||
|
||||
private const FILM_KINDS = ['unterrichtsfilm', 'kurzfilm', 'trailer', 'interview'];
|
||||
|
||||
private const EXERCISE_KINDS = ['arbeitsblatt', 'uebungsbeschreibung'];
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'Film',
|
||||
self::Uebung => 'Übung',
|
||||
self::Pdf => 'PDF',
|
||||
self::Paket => 'Paket',
|
||||
self::FilmUebungen => 'Film + Übungen',
|
||||
self::FilmMerkblatt => 'Film + Merkblatt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Name des Zeichens im Satz „glyphen“ (resources/svg/brand/glyphen). */
|
||||
public function glyph(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'film',
|
||||
self::Uebung => 'uebung',
|
||||
self::Pdf, self::FilmMerkblatt => 'dokument',
|
||||
self::Paket => 'paket',
|
||||
self::FilmUebungen => 'filmstreifen',
|
||||
};
|
||||
}
|
||||
|
||||
public static function fromContent(?string $outputClass, ?string $editorialKindSlug = null): ?self
|
||||
{
|
||||
return match (true) {
|
||||
$outputClass === 'film' => self::Film,
|
||||
$outputClass === 'pdf' => self::Pdf,
|
||||
in_array($editorialKindSlug, self::FILM_KINDS, true) => self::Film,
|
||||
in_array($editorialKindSlug, self::EXERCISE_KINDS, true) => self::Uebung,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,37 @@
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class Offer extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'standalone_bundle' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Composition::class);
|
||||
}
|
||||
|
||||
/** Bezeichnung der Option auf der Produktseite. */
|
||||
public function optionName(): string
|
||||
{
|
||||
return filled($this->option_label) ? (string) $this->option_label : (string) $this->name;
|
||||
}
|
||||
|
||||
public function versions(): HasMany
|
||||
{
|
||||
return $this->hasMany(OfferVersion::class);
|
||||
|
||||
@@ -6,6 +6,27 @@ class OfferCoverage
|
||||
{
|
||||
public function __construct(private readonly ContentResolver $resolver) {}
|
||||
|
||||
/**
|
||||
* Bestandteile der Fassung, deren Medienfassung gesperrt ist. Ein Angebot soll nicht aktiviert werden, solange sein
|
||||
* Umfang gesperrte Bestandteile enthält; die Prüfung nennt sie vorab.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function blockedLeaves(CompositionVersion $version): array
|
||||
{
|
||||
$rows = $this->resolver->expand($version);
|
||||
$blocked = ContentElementVersion::query()
|
||||
->whereIn('id', array_column($rows, 'version_id'))
|
||||
->where('status', ContentVersionStatus::Gesperrt->value)
|
||||
->pluck('id')
|
||||
->all();
|
||||
|
||||
return array_values(array_map(
|
||||
fn (array $row): string => $row['path'],
|
||||
array_filter($rows, fn (array $row): bool => in_array($row['version_id'], $blocked, true)),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<LicenseArticle> $articles
|
||||
* @return list<string>
|
||||
|
||||
@@ -22,6 +22,23 @@ public function currentActiveVersion(Offer $offer): OfferVersion
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung mit Preis; sonst null (nicht kaufbar, zurückgezogen oder kostenlos).
|
||||
*/
|
||||
public function purchasableVersion(Offer $offer): ?OfferVersion
|
||||
{
|
||||
$version = $offer->versions()
|
||||
->where('status', OfferStatus::Aktiv)
|
||||
->orderByDesc('number')
|
||||
->first();
|
||||
|
||||
if ($version === null || $version->grant_kind !== 'kauf' || $version->price_cents === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $capabilities
|
||||
* @param array<string, mixed> $options
|
||||
@@ -85,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => false,
|
||||
'grant_kind' => 'kauf',
|
||||
'holder_kind' => 'person',
|
||||
'licence_scope' => null,
|
||||
'trainer_count' => null,
|
||||
], $attributes);
|
||||
|
||||
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
|
||||
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
|
||||
}
|
||||
|
||||
$this->assertAttributes($attributes);
|
||||
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||
$scope = $this->scopeFor($lines);
|
||||
$this->assertSellableContent($scope);
|
||||
$this->assertCoverage($lines, $attributes);
|
||||
|
||||
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
||||
@@ -109,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => $attributes['dynamic'],
|
||||
'grant_kind' => $attributes['grant_kind'],
|
||||
'holder_kind' => $attributes['holder_kind'],
|
||||
'licence_scope' => $attributes['licence_scope'],
|
||||
'trainer_count' => $attributes['trainer_count'],
|
||||
]);
|
||||
|
||||
foreach (array_values($lines) as $index => $line) {
|
||||
@@ -138,6 +165,45 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zieht die Option aus dem Verkauf zurück: Die aktive Fassung wird beendet und bleibt gespeichert. Bereits
|
||||
* begründete Berechtigungen und Bestellungen ändern sich nicht; offene Warenkörbe zeigen die Position als
|
||||
* zurückgezogen und blockieren den Abschluss, bis der Käufer sie entfernt.
|
||||
*/
|
||||
public function end(Offer $offer): OfferVersion
|
||||
{
|
||||
return DB::transaction(function () use ($offer): OfferVersion {
|
||||
$offer = Offer::query()->lockForUpdate()->findOrFail($offer->id);
|
||||
$version = $this->currentActiveVersion($offer);
|
||||
$version->status = OfferStatus::Beendet;
|
||||
$version->save();
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
||||
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
{
|
||||
if ($compositionId !== null) {
|
||||
Composition::query()->findOrFail($compositionId);
|
||||
}
|
||||
|
||||
if ($ownBundlePage && $compositionId !== null) {
|
||||
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
|
||||
}
|
||||
|
||||
$offer->composition_id = $compositionId;
|
||||
$offer->standalone_bundle = $ownBundlePage;
|
||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||
$offer->save();
|
||||
|
||||
return $offer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<int>
|
||||
*/
|
||||
@@ -168,6 +234,32 @@ private function assertAttributes(array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
|
||||
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
|
||||
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
|
||||
*
|
||||
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
|
||||
*/
|
||||
private function assertSellableContent(array $scope): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
|
||||
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
|
||||
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
|
||||
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
|
||||
|
||||
if ($missing->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
|
||||
|
||||
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
|
||||
.($missing->count() === 1 ? ' hat' : ' haben')
|
||||
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
|
||||
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
||||
@@ -185,6 +277,10 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
|
||||
$version = CompositionVersion::query()->findOrFail($versionId);
|
||||
|
||||
if (app(ForeignCompositions::class)->reaches($version)) {
|
||||
throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Das Angebot wird hier nicht aktiviert.');
|
||||
}
|
||||
$articles = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
@@ -193,6 +289,12 @@ private function assertCoverage(array $lines, array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
$blocked = app(OfferCoverage::class)->blockedLeaves($version);
|
||||
|
||||
if ($blocked !== []) {
|
||||
throw new DomainRuleException('Das Angebot enthält gesperrte Bestandteile: '.implode(', ', $blocked));
|
||||
}
|
||||
|
||||
$missing = app(OfferCoverage::class)->missingLeaves($version, $articles);
|
||||
|
||||
if ($missing !== []) {
|
||||
|
||||
@@ -19,6 +19,8 @@ class OfferVersion extends Model
|
||||
'dynamic',
|
||||
'grant_kind',
|
||||
'holder_kind',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'activated_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,16 @@ public function pages(): BelongsToMany
|
||||
return $this->belongsToMany(Page::class);
|
||||
}
|
||||
|
||||
public function compositions(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Composition::class);
|
||||
}
|
||||
|
||||
public function licenseArticles(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(LicenseArticle::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Pillar> $query
|
||||
* @return Builder<Pillar>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Alte Filteradressen: Vor der Vereinheitlichung war „Fachliche Säule“ ein Wert der redaktionellen Einordnung
|
||||
* (`?einordnung=…`, `?pillar=…`, `dimension[]=…`). Verweist ein solcher Wert über `pillar_id` auf eine zentrale Säule,
|
||||
* gilt der Filter jetzt für diese Säule, statt stillschweigend zu entfallen.
|
||||
*/
|
||||
final class PillarFilterCompat
|
||||
{
|
||||
/**
|
||||
* @return int|null|false Kennung der Säule; null: alter Säulenwert ohne belastbare Verknüpfung; false: kein Säulenwert
|
||||
*/
|
||||
public static function pillarOfLegacyValue(int $valueId): int|false|null
|
||||
{
|
||||
$row = DB::table('editorial_dimension_values')
|
||||
->join('editorial_dimensions', 'editorial_dimensions.id', '=', 'editorial_dimension_values.editorial_dimension_id')
|
||||
->where('editorial_dimension_values.id', $valueId)
|
||||
->where('editorial_dimensions.slug', EditorialDimension::PILLAR_SLUG)
|
||||
->first(['editorial_dimension_values.pillar_id']);
|
||||
|
||||
if ($row === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $row->pillar_id === null ? null : (int) $row->pillar_id;
|
||||
}
|
||||
}
|
||||
@@ -40,19 +40,55 @@ public function present(Pillar $pillar, string $name, string $slug, ?string $sum
|
||||
|
||||
public function delete(Pillar $pillar): void
|
||||
{
|
||||
if ($pillar->elements()->exists() || $pillar->pages()->exists()) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Medien oder Seiten wird nicht gelöscht.');
|
||||
$usage = $this->usage($pillar);
|
||||
|
||||
if (array_sum($usage) > 0) {
|
||||
throw new DomainRuleException('Eine Säule mit zugeordneten Objekten wird nicht gelöscht ('.$this->usageText($usage).'). Ordnen Sie sie zuerst anders zu.');
|
||||
}
|
||||
|
||||
$pillar->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $pillarIds
|
||||
* Zuordnungen je Objektart: Medien, Module und Programme, Lizenzartikel, Seiten.
|
||||
*
|
||||
* @return array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int}
|
||||
*/
|
||||
public function assign(ContentElement $element, array $pillarIds): void
|
||||
public function usage(Pillar $pillar): array
|
||||
{
|
||||
$element->pillars()->sync($this->ids($pillarIds));
|
||||
return [
|
||||
'medien' => $pillar->elements()->count(),
|
||||
'zusammenstellungen' => $pillar->compositions()->count(),
|
||||
'lizenzartikel' => $pillar->licenseArticles()->count(),
|
||||
'seiten' => $pillar->pages()->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{medien: int, zusammenstellungen: int, lizenzartikel: int, seiten: int} $usage
|
||||
*/
|
||||
public function usageText(array $usage): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach (['medien' => ['Medium', 'Medien'], 'zusammenstellungen' => ['Modul oder Programm', 'Module und Programme'], 'lizenzartikel' => ['Lizenzartikel', 'Lizenzartikel'], 'seiten' => ['Seite', 'Seiten']] as $key => [$one, $many]) {
|
||||
if ($usage[$key] > 0) {
|
||||
$parts[] = $usage[$key].' '.($usage[$key] === 1 ? $one : $many);
|
||||
}
|
||||
}
|
||||
|
||||
return $parts === [] ? 'nirgends zugeordnet' : implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordnet einem Medium, Modul, Programm, Lizenzartikel oder einer Seite Säulen zu. Alle Objektarten verwenden
|
||||
* dieselbe zentrale Säule und dieselbe Speicherregel; die Zuordnung ersetzt die bisherige vollständig.
|
||||
*
|
||||
* @param list<int|string> $pillarIds
|
||||
*/
|
||||
public function assign(ContentElement|Composition|LicenseArticle|Page $subject, array $pillarIds): void
|
||||
{
|
||||
$subject->pillars()->sync($this->ids($pillarIds));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -60,7 +96,7 @@ public function assign(ContentElement $element, array $pillarIds): void
|
||||
*/
|
||||
public function assignPages(Page $page, array $pillarIds): void
|
||||
{
|
||||
$page->pillars()->sync($this->ids($pillarIds));
|
||||
$this->assign($page, $pillarIds);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -13,6 +13,8 @@ class ReleaseContent extends Model
|
||||
'content_element_version_id',
|
||||
'role',
|
||||
'path',
|
||||
'requirement',
|
||||
'variant_key',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Design\SiteSetting;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
/**
|
||||
* Zugang zum Shinkan-Katalog. Die Adresse ist je Umgebung vorgegeben (`SHINKAN_DISTRIBUTION_URL`). Der Zugangsschlüssel
|
||||
* kommt aus der Umgebung des Servers (`SHINKAN_DISTRIBUTION_KEY`, hat Vorrang und bleibt die bestehende Anbindung) oder
|
||||
* ist in der Verwaltung hinterlegt. So lässt sich der Schlüssel ersetzen, ohne die Umgebung des Servers anzufassen.
|
||||
*
|
||||
* Der in der Verwaltung hinterlegte Schlüssel liegt je Umgebung getrennt und mit dem Anwendungsschlüssel verschlüsselt in
|
||||
* den Einstellungen. Er wird nie zurückgegeben, nie angezeigt und nie protokolliert und steht in keiner Fehlermeldung.
|
||||
*/
|
||||
final class ShinkanConnection
|
||||
{
|
||||
public const SETTING = 'shinkan.anbindung';
|
||||
|
||||
public const SERVER = 'server';
|
||||
|
||||
public const ADMIN = 'verwaltung';
|
||||
|
||||
public function url(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.url');
|
||||
|
||||
if (! is_string($value) || trim($value) === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Die Adresse ist die der Shinkan-Installation. Der Pfad `/api/distribution/v1` hängt der Abruf selbst an; wer ihn
|
||||
// (oder nur `/api`) mit einträgt, bekommt trotzdem die richtige Adresse und keinen doppelten Pfad.
|
||||
$base = rtrim(trim($value), '/');
|
||||
$base = (string) preg_replace('#/api(/distribution(/v1)?)?$#', '', $base);
|
||||
|
||||
return $base === '' ? null : $base;
|
||||
}
|
||||
|
||||
public function apiKey(): ?string
|
||||
{
|
||||
$server = $this->serverKey();
|
||||
|
||||
if ($server !== null) {
|
||||
return $server;
|
||||
}
|
||||
|
||||
$encrypted = $this->stored()['key'] ?? null;
|
||||
|
||||
if (! is_string($encrypted) || $encrypted === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return Crypt::decryptString($encrypted);
|
||||
} catch (DecryptException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Woher kommt der Schlüssel? `server`, `verwaltung` oder null.
|
||||
*/
|
||||
public function keySource(): ?string
|
||||
{
|
||||
if ($this->serverKey() !== null) {
|
||||
return self::SERVER;
|
||||
}
|
||||
|
||||
return $this->apiKey() !== null ? self::ADMIN : null;
|
||||
}
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return $this->url() !== null && $this->apiKey() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hinterlegt oder ersetzt den Schlüssel. Der Schlüssel aus der Umgebung des Servers behält den Vorrang.
|
||||
*/
|
||||
public function saveKey(string $key, ?User $by = null): void
|
||||
{
|
||||
$key = trim($key);
|
||||
|
||||
if ($key === '') {
|
||||
throw new DomainRuleException('Der Zugangsschlüssel fehlt.');
|
||||
}
|
||||
|
||||
$this->write(['key' => Crypt::encryptString($key)], $by);
|
||||
}
|
||||
|
||||
public function forgetKey(?User $by = null): void
|
||||
{
|
||||
$this->write([], $by);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function stored(): array
|
||||
{
|
||||
$value = SiteSetting::query()->find(self::SETTING)?->value;
|
||||
|
||||
return is_array($value) ? $value : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $stored
|
||||
*/
|
||||
private function write(array $stored, ?User $by): void
|
||||
{
|
||||
SiteSetting::query()->updateOrCreate(['key' => self::SETTING], ['value' => $stored, 'updated_by' => $by?->id]);
|
||||
}
|
||||
|
||||
private function serverKey(): ?string
|
||||
{
|
||||
$value = config('services.shinkan.key');
|
||||
|
||||
return is_string($value) && trim($value) !== '' ? trim($value) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,884 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Übernahme von Übungen aus dem Shinkan-Katalog (`GET /api/distribution/v1/catalog` und Detailroute) in denselben
|
||||
* Übungsbestand wie die lokalen Übungen.
|
||||
*
|
||||
* Grundsätze:
|
||||
* - Die Quellübung ist an ihre stabile Kennung gebunden. Jeder Inhaltsstand (Prüfsumme der Quelle) wird genau einmal
|
||||
* festgehalten; ein wiederholter Abruf erzeugt nichts Neues.
|
||||
* - Eine lokale Fassung entsteht nur durch die bewusste Übernahme ({@see adoptPreviewed}) und ist danach unveränderlich.
|
||||
* Lokale Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten. Entfällt die Quellvariante einer
|
||||
* lokalen Ergänzung, legt die Redaktion die neue Zuordnung fest.
|
||||
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
|
||||
* rechtliche Sperre ist der lokale `block`. Ausgeblendete Quellen sind von der Übernahme ausgeschlossen.
|
||||
* - Medien des Katalogs sind Metadaten ohne Datei. Sie begründen weder eine Ausgabe noch eine Nutzungsberechtigung und
|
||||
* stehen nie in einem Artikel-Stand.
|
||||
* - Ein fehlgeschlagener Abruf verändert den gespeicherten Stand nicht und rückt den Cursor nicht vor.
|
||||
*/
|
||||
class ShinkanImport
|
||||
{
|
||||
/** Abschnitte der Quelle in Lesereihenfolge: Feld => Bezeichnung. */
|
||||
public const SECTIONS = [
|
||||
'preparation' => 'Vorbereitung',
|
||||
'execution' => 'Durchführung',
|
||||
'trainer_notes' => 'Trainerhinweise',
|
||||
];
|
||||
|
||||
/** Felder, die Shinkan bei `text_format: html` als HTML liefert (ADR-50). Ohne diese Angabe sind alle Texte Klartext. */
|
||||
private const HTML_FIELDS = ['summary', 'goal', 'execution', 'preparation', 'trainer_notes'];
|
||||
|
||||
/** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */
|
||||
private const IMPORT_NOTE = 'Übernahme aus Shinkan';
|
||||
|
||||
/** Fassungsfelder der Quelle: Katalogfeld => [Feld der lokalen Fassung, Bezeichnung]. */
|
||||
private const FIELDS = [
|
||||
'goal' => ['learning_goal', 'Lernziel'],
|
||||
'duration_min' => ['duration_minutes', 'Dauer (von)'],
|
||||
'duration_max' => ['duration_max', 'Dauer (bis)'],
|
||||
'equipment' => ['material_note', 'Ausstattung'],
|
||||
];
|
||||
|
||||
public function configured(): bool
|
||||
{
|
||||
return app(ShinkanConnection::class)->configured();
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt.
|
||||
*
|
||||
* @return array{url: bool, key: bool, host: string|null, key_source: string|null}
|
||||
*/
|
||||
public function status(): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$url = $connection->url();
|
||||
|
||||
return [
|
||||
'url' => $url !== null,
|
||||
'key' => $connection->apiKey() !== null,
|
||||
'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null,
|
||||
'key_source' => $connection->keySource(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel
|
||||
* geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt.
|
||||
*
|
||||
* @return array{ok: bool, message: string}
|
||||
*/
|
||||
public function check(?string $candidateKey = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey();
|
||||
|
||||
if ($connection->url() === null || $key === null) {
|
||||
return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'];
|
||||
}
|
||||
|
||||
try {
|
||||
$catalog = $this->get('/catalog', [], $key);
|
||||
} catch (Throwable $exception) {
|
||||
return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)];
|
||||
}
|
||||
|
||||
$count = count((array) ($catalog['exercises'] ?? []));
|
||||
|
||||
return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.'];
|
||||
}
|
||||
|
||||
public function fetch(): ExerciseImportRun
|
||||
{
|
||||
$run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]);
|
||||
|
||||
if (! $this->configured()) {
|
||||
return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.');
|
||||
}
|
||||
|
||||
$previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor');
|
||||
$counts = ['added' => 0, 'updated' => 0, 'removed' => 0];
|
||||
|
||||
try {
|
||||
try {
|
||||
$catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]);
|
||||
} catch (RequestException $exception) {
|
||||
// Ein ungültiger Cursor heißt nur: ganz neu abgleichen.
|
||||
if ($previous === null || $exception->response->status() !== 400) {
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$catalog = $this->get('/catalog');
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['changes'] ?? []) as $change) {
|
||||
$id = (string) ($change['source_id'] ?? '');
|
||||
$kind = (string) ($change['change'] ?? '');
|
||||
|
||||
if ($id === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($kind === 'removed') {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id)
|
||||
->update(['availability' => ExerciseSource::WITHDRAWN]);
|
||||
$counts['removed']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$document = $this->get('/catalog/'.$id);
|
||||
$this->record($document);
|
||||
$counts[$kind === 'added' ? 'added' : 'updated']++;
|
||||
}
|
||||
|
||||
foreach ((array) ($catalog['exercises'] ?? []) as $listed) {
|
||||
ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? ''))
|
||||
->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]);
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.');
|
||||
}
|
||||
|
||||
return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert.
|
||||
*
|
||||
* @param array<string, mixed> $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern
|
||||
*/
|
||||
public function record(array $document): ExerciseSourceSnapshot
|
||||
{
|
||||
$id = (string) ($document['source_id'] ?? '');
|
||||
$hash = (string) ($document['content_hash'] ?? '');
|
||||
|
||||
if ($id === '' || $hash === '') {
|
||||
throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot {
|
||||
$source = ExerciseSource::query()->firstOrCreate(
|
||||
['source_system' => 'shinkan', 'source_id' => $id],
|
||||
['title' => (string) ($document['title'] ?? '')],
|
||||
);
|
||||
$source->update([
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'availability' => ExerciseSource::PROVIDED,
|
||||
'last_hash' => $hash,
|
||||
'last_seen_at' => now(),
|
||||
]);
|
||||
|
||||
return $source->snapshots()->firstOrCreate(
|
||||
['content_hash' => $hash],
|
||||
['payload' => $document, 'fetched_at' => now()],
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand einer Quellübung für die Redaktion.
|
||||
*/
|
||||
public function state(ExerciseSource $source): string
|
||||
{
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
return match (true) {
|
||||
$source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt',
|
||||
$latest === null => 'neu',
|
||||
$latest->adopted_version_id !== null => 'uebernommen',
|
||||
$source->composition_id !== null => 'geaendert',
|
||||
default => 'neu',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die
|
||||
* fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function preview(ExerciseSource $source): array
|
||||
{
|
||||
$snapshot = $source->latestSnapshot();
|
||||
$state = $this->state($source);
|
||||
$document = $snapshot?->payload ?? [];
|
||||
$previous = $this->lastAdopted($source);
|
||||
$sections = [];
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
if ($this->value($document, $field) !== '') {
|
||||
$sections[] = ['label' => $label, 'text' => FormattedText::excerpt($this->value($document, $field), 280)];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'source' => $source->id,
|
||||
'snapshot' => $snapshot?->id,
|
||||
'hash' => $snapshot?->content_hash,
|
||||
'state' => $state,
|
||||
'title' => (string) ($document['title'] ?? $source->title),
|
||||
'summary' => FormattedText::plain($this->value($document, 'summary')),
|
||||
'goal' => FormattedText::plain($this->value($document, 'goal')),
|
||||
'duration' => $this->duration($document),
|
||||
'equipment' => FormattedText::plain($this->value($document, 'equipment')),
|
||||
'sections' => $sections,
|
||||
'variants' => array_map(fn (array $variant): array => [
|
||||
'key' => (string) ($variant['id'] ?? ''),
|
||||
'name' => (string) ($variant['name'] ?? ''),
|
||||
'description' => (string) ($variant['description'] ?? ''),
|
||||
'changes' => $this->variantChanges($document, $variant) !== '',
|
||||
], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))),
|
||||
'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))),
|
||||
'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source),
|
||||
'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document),
|
||||
'text_conflicts' => $snapshot === null ? [] : $this->textDecisions($source, $document, 'conflict'),
|
||||
'kept_local' => $snapshot === null ? [] : array_column($this->textDecisions($source, $document, 'keep_local'), 'label'),
|
||||
'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null,
|
||||
'excluded' => $source->availability === ExerciseSource::WITHDRAWN,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
* @return list<string>
|
||||
*/
|
||||
public function changes(array $before, array $after, ?ExerciseSource $source = null): array
|
||||
{
|
||||
$lines = [];
|
||||
$labels = [
|
||||
'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung',
|
||||
'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)',
|
||||
] + self::SECTIONS;
|
||||
|
||||
foreach ($labels as $field => $label) {
|
||||
if (! $this->sameValue($field, $before, $after)) {
|
||||
$lines[] = $label.' geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
$new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
||||
|
||||
foreach ($new->diffKeys($old) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu';
|
||||
}
|
||||
|
||||
foreach ($old->diffKeys($new) as $variant) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt';
|
||||
}
|
||||
|
||||
foreach ($new->intersectByKeys($old) as $key => $variant) {
|
||||
if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) {
|
||||
$lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“';
|
||||
}
|
||||
|
||||
if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? ''))
|
||||
|| ! FormattedText::same($this->variantChanges($after, $variant), $this->variantChanges($before, (array) $old[$key]))) {
|
||||
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert';
|
||||
}
|
||||
}
|
||||
|
||||
$common = $old->keys()->intersect($new->keys())->values()->all();
|
||||
|
||||
if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) {
|
||||
$lines[] = 'Reihenfolge der Varianten geändert';
|
||||
}
|
||||
|
||||
if ($source?->composition !== null) {
|
||||
if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) {
|
||||
$lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
|
||||
if (! $this->sameValue('summary', $before, $after) && filled($source->composition->summary) && ! FormattedText::same($source->composition->summary, $this->value($before, 'summary'))) {
|
||||
$lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert';
|
||||
}
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt.
|
||||
* Die Redaktion legt deren neue Zuordnung fest.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, name: string, members: list<string>}>
|
||||
*/
|
||||
public function conflicts(ExerciseSource $source, array $document): array
|
||||
{
|
||||
$latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
|
||||
if ($latest === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$keep = array_merge(
|
||||
array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')),
|
||||
$latest->variants->where('origin', 'lokal')->pluck('key')->all(),
|
||||
);
|
||||
$open = [];
|
||||
|
||||
foreach ($latest->members->where('origin', 'lokal') as $member) {
|
||||
$key = $member->variant?->key;
|
||||
|
||||
if ($key !== null && ! in_array($key, $keep, true)) {
|
||||
$open[$key]['key'] = $key;
|
||||
$open[$key]['name'] = $member->variant->name;
|
||||
$open[$key]['members'][] = $member->role;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($open);
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte und Felder, die lokal bearbeitet wurden: `keep_local` bleiben erhalten, bei `conflict` hat auch die Quelle
|
||||
* geändert und die Redaktion entscheidet.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @return list<array{key: string, label: string}>
|
||||
*/
|
||||
public function textDecisions(ExerciseSource $source, array $document, string $wanted): array
|
||||
{
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
|
||||
if ($previousSnapshot === null || $source->composition === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$previousSource = $previousSnapshot->payload;
|
||||
$result = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'text' && $item['decision'] === $wanted) {
|
||||
$result[] = ['key' => $item['key'], 'label' => $item['label']];
|
||||
}
|
||||
}
|
||||
|
||||
$latest = $source->composition->versions()->orderByDesc('number')->first();
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
$isText = in_array($field, ['goal', 'equipment'], true);
|
||||
$old = $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null);
|
||||
$new = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null);
|
||||
|
||||
if ($latest !== null && $this->classifyField($latest->{$column}, $old, $new, $isText) === $wanted) {
|
||||
$result[] = ['key' => $field, 'label' => $label];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder
|
||||
* wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung.
|
||||
*
|
||||
* @param array<string, string> $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder ''
|
||||
* @param array<string, string> $choices bei lokal und in der Quelle geänderten Angaben: Schlüssel => `lokal` oder `quelle`
|
||||
* @return array{status: string, message: string, version?: CompositionVersion}
|
||||
*/
|
||||
public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null, array $choices = []): array
|
||||
{
|
||||
$source->refresh();
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
if ($source->availability === ExerciseSource::WITHDRAWN) {
|
||||
return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.'];
|
||||
}
|
||||
|
||||
if ($latest === null || $latest->id !== $previewedSnapshot) {
|
||||
return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.'];
|
||||
}
|
||||
|
||||
if ($latest->adopted_version_id !== null) {
|
||||
return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion];
|
||||
}
|
||||
|
||||
try {
|
||||
$version = $this->adopt($latest, $actor, $reassign, $choices);
|
||||
} catch (DomainRuleException $exception) {
|
||||
return ['status' => 'fehler', 'message' => $exception->getMessage()];
|
||||
}
|
||||
|
||||
return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
||||
* entsteht keine zweite Fassung.
|
||||
*
|
||||
* Eine importierte Übung ist eine Übung wie jede andere und lässt sich bearbeiten. Lokal bearbeitete Texte und Felder
|
||||
* bleiben deshalb erhalten, solange die Quelle sie nicht ebenfalls geändert hat. Haben beide Seiten geändert, legt die
|
||||
* Redaktion fest, welcher Stand gilt (`$choices`). Lokale Ergänzungen bleiben erhalten; entfällt ihre Quellvariante,
|
||||
* legt die Redaktion die neue Zuordnung fest (`$reassign`).
|
||||
*
|
||||
* @param array<string, string> $reassign
|
||||
* @param array<string, string> $choices Schlüssel => `lokal` oder `quelle`
|
||||
*/
|
||||
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = [], array $choices = []): CompositionVersion
|
||||
{
|
||||
$snapshot->refresh();
|
||||
|
||||
if ($snapshot->adopted_version_id !== null) {
|
||||
return $snapshot->adoptedVersion;
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($snapshot, $actor, $reassign, $choices): CompositionVersion {
|
||||
$source = $snapshot->source;
|
||||
$document = $snapshot->payload;
|
||||
$content = app(ContentService::class);
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
$previousSnapshot = $this->lastAdopted($source);
|
||||
$previousSource = $previousSnapshot?->payload ?? [];
|
||||
$composition = $source->composition ?? $this->createComposition($title, $this->value($document, 'summary'));
|
||||
|
||||
if ($source->composition !== null && $previousSnapshot !== null) {
|
||||
$this->carryOverTexts($composition, $previousSource, $document);
|
||||
}
|
||||
|
||||
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
||||
$variants = [];
|
||||
$members = [];
|
||||
|
||||
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
||||
if ($item['kind'] === 'variant') {
|
||||
$variants[] = $item['variant'];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$latest = $item['latest'];
|
||||
$decision = $item['decision'];
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$item['key']] ?? null) === 'lokal' ? 'keep_local'
|
||||
: (($choices[$item['key']] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$item['label'].'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$keepLocal = $decision === 'keep_local' && $latest !== null;
|
||||
$target = $keepLocal ? $latest : $this->sectionVersion($source, $composition, $item['field'], $item['title'], $item['text'], $latest);
|
||||
$members[] = array_filter([
|
||||
'role' => $item['role'],
|
||||
'target' => $target,
|
||||
'variant' => $item['variant_key'],
|
||||
'origin' => $keepLocal || ($latest !== null && $latest->id === $target->id && $latest->change_note !== self::IMPORT_NOTE) ? 'lokal' : 'quelle',
|
||||
], fn ($value): bool => $value !== null);
|
||||
}
|
||||
|
||||
// Fassungsfelder: lokal geändert bleibt erhalten, solange die Quelle den Wert nicht ebenfalls geändert hat.
|
||||
$fields = [];
|
||||
|
||||
foreach (self::FIELDS as $field => [$column, $label]) {
|
||||
$isText = in_array($field, ['goal', 'equipment'], true);
|
||||
$value = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null);
|
||||
|
||||
if ($previous !== null && $previousSnapshot !== null) {
|
||||
$decision = $this->classifyField($previous->{$column}, $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null), $value, $isText);
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
$decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict');
|
||||
}
|
||||
|
||||
if ($decision === 'conflict') {
|
||||
throw new DomainRuleException('„'.$label.'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
||||
}
|
||||
|
||||
$value = $decision === 'keep_local' ? $previous->{$column} : $value;
|
||||
}
|
||||
|
||||
$fields[$column] = $value;
|
||||
}
|
||||
|
||||
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign);
|
||||
$version = $content->publishComposition(
|
||||
$composition,
|
||||
[...$members, ...$localMembers],
|
||||
$actor,
|
||||
self::IMPORT_NOTE,
|
||||
[
|
||||
'learning_goal' => $fields['learning_goal'],
|
||||
'duration_minutes' => $fields['duration_minutes'],
|
||||
'duration_max' => $fields['duration_max'],
|
||||
'material_note' => $fields['material_note'],
|
||||
'source_snapshot_id' => $snapshot->id,
|
||||
],
|
||||
[...$variants, ...$localVariants],
|
||||
);
|
||||
|
||||
$snapshot->update(['adopted_version_id' => $version->id]);
|
||||
$source->update(['composition_id' => $composition->id]);
|
||||
|
||||
return $version;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Übernahme aus dem Quellstand anlegen würde, mit der Entscheidung je Text: `source` (Quelltext gilt),
|
||||
* `keep_local` (lokal bearbeitet, die Quelle hat sich nicht geändert) oder `conflict` (beide haben geändert).
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @param array<string, mixed> $previousSource
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function plan(ExerciseSource $source, array $document, array $previousSource): array
|
||||
{
|
||||
$plan = [];
|
||||
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
||||
|
||||
foreach (self::SECTIONS as $field => $label) {
|
||||
$text = $this->value($document, $field);
|
||||
|
||||
if ($text !== '') {
|
||||
$plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $this->value($previousSource, $field) ?: null);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
||||
$key = (string) ($variant['id'] ?? '');
|
||||
|
||||
if ($key === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) ($variant['name'] ?? '') ?: 'Variante';
|
||||
$plan[] = [
|
||||
'kind' => 'variant',
|
||||
'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'],
|
||||
];
|
||||
$changes = $this->variantChanges($document, $variant);
|
||||
|
||||
if ($changes !== '') {
|
||||
$before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key);
|
||||
$plan[] = $this->textItem(
|
||||
$source,
|
||||
'variant:'.$key,
|
||||
'Abweichung der Durchführung ('.$name.')',
|
||||
$title.' · '.$name.' · Abweichung',
|
||||
'Abweichung der Durchführung',
|
||||
$changes,
|
||||
$key,
|
||||
is_array($before) ? ($this->variantChanges($previousSource, $before) ?: null) : null,
|
||||
'variant_'.$key,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $plan;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function textItem(ExerciseSource $source, string $field, string $label, string $title, string $role, string $text, ?string $variantKey, ?string $previousText, ?string $key = null): array
|
||||
{
|
||||
$element = ContentElement::query()->where('source_ref', 'shinkan:'.$source->source_id.':'.$field)->first();
|
||||
$latest = $element?->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
||||
|
||||
return [
|
||||
'kind' => 'text',
|
||||
'key' => $key ?? $field,
|
||||
'field' => $field,
|
||||
'label' => $label,
|
||||
'title' => $title,
|
||||
'role' => $role,
|
||||
'text' => $text,
|
||||
'variant_key' => $variantKey,
|
||||
'latest' => $latest,
|
||||
'decision' => $this->classifyText($latest, $text, $previousText),
|
||||
];
|
||||
}
|
||||
|
||||
private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string
|
||||
{
|
||||
if ($latest === null || FormattedText::same($latest->body, $text) || $latest->change_note === self::IMPORT_NOTE) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return $previousText === null || ! FormattedText::same($previousText, $text) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
private function classifyField(mixed $local, mixed $previousSource, mixed $new, bool $text = false): string
|
||||
{
|
||||
$same = $text
|
||||
? fn (mixed $a, mixed $b): bool => FormattedText::same($a === null ? null : (string) $a, $b === null ? null : (string) $b)
|
||||
: fn (mixed $a, mixed $b): bool => ($a === null ? '' : trim((string) $a)) === ($b === null ? '' : trim((string) $b));
|
||||
|
||||
if ($same($local, $new) || $same($local, $previousSource)) {
|
||||
return 'source';
|
||||
}
|
||||
|
||||
return ! $same($previousSource, $new) ? 'conflict' : 'keep_local';
|
||||
}
|
||||
|
||||
/**
|
||||
* Text eines Felds der Quelle in der Form, in der er übernommen wird: Bei `text_format: html` wird das HTML bereinigt
|
||||
* und kanonisch, sonst bleibt der Klartext, wie er geliefert wird.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
*/
|
||||
private function value(array $document, string $field): string
|
||||
{
|
||||
$raw = trim((string) ($document[$field] ?? ''));
|
||||
|
||||
return ($document['text_format'] ?? null) === 'html' && in_array($field, self::HTML_FIELDS, true)
|
||||
? FormattedText::canonicalHtml($raw)
|
||||
: $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Abweichung der Durchführung einer Variante, im Format des Dokuments.
|
||||
*
|
||||
* @param array<string, mixed> $document
|
||||
* @param array<string, mixed> $variant
|
||||
*/
|
||||
private function variantChanges(array $document, array $variant): string
|
||||
{
|
||||
$raw = trim((string) ($variant['execution_changes'] ?? ''));
|
||||
|
||||
return ($document['text_format'] ?? null) === 'html' ? FormattedText::canonicalHtml($raw) : $raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ist das Feld in beiden Quellständen inhaltlich gleich? Texte werden als kanonischer Text verglichen, alles andere
|
||||
* ohne führenden und folgenden Leerraum.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function sameValue(string $field, array $before, array $after): bool
|
||||
{
|
||||
if (in_array($field, [...self::HTML_FIELDS, 'equipment'], true)) {
|
||||
return FormattedText::same($this->value($before, $field), $this->value($after, $field));
|
||||
}
|
||||
|
||||
return trim((string) ($before[$field] ?? '')) === trim((string) ($after[$field] ?? ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie
|
||||
* nicht lokal geändert hat; ein lokal geänderter Wert bleibt.
|
||||
*
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
private function carryOverTexts(Composition $composition, array $before, array $after): void
|
||||
{
|
||||
if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) {
|
||||
$composition->designation = trim((string) $after['title']);
|
||||
}
|
||||
|
||||
if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || FormattedText::same($composition->summary, $this->value($before, 'summary')))) {
|
||||
$composition->summary = $this->value($after, 'summary') ?: null;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
}
|
||||
|
||||
private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot
|
||||
{
|
||||
return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
|
||||
* Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung.
|
||||
*
|
||||
* @param list<string> $sourceVariantKeys
|
||||
* @param array<string, string> $reassign
|
||||
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
|
||||
*/
|
||||
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): array
|
||||
{
|
||||
if ($previous === null) {
|
||||
return [[], []];
|
||||
}
|
||||
|
||||
$localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal',
|
||||
])->values()->all();
|
||||
$known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')];
|
||||
$members = [];
|
||||
|
||||
foreach ($previous->members->where('origin', 'lokal') as $member) {
|
||||
$variant = $member->variant?->key;
|
||||
|
||||
if ($variant !== null && ! in_array($variant, $known, true)) {
|
||||
if (! array_key_exists($variant, $reassign)) {
|
||||
throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.');
|
||||
}
|
||||
|
||||
$target = (string) $reassign[$variant];
|
||||
|
||||
if ($target !== '' && ! in_array($target, $known, true)) {
|
||||
throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.');
|
||||
}
|
||||
|
||||
$variant = $target === '' ? null : $target;
|
||||
}
|
||||
|
||||
$members[] = [
|
||||
'role' => $member->role,
|
||||
'note' => $member->placement_note,
|
||||
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
|
||||
'variant' => $variant,
|
||||
'requirement' => $member->requirement,
|
||||
'selection' => $member->variant_selection,
|
||||
'origin' => 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
return [$members, $localVariants];
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung.
|
||||
*/
|
||||
private function sectionVersion(ExerciseSource $source, Composition $composition, string $field, string $title, string $text, ?ContentElementVersion $latest): ContentElementVersion
|
||||
{
|
||||
$content = app(ContentService::class);
|
||||
$ref = 'shinkan:'.$source->source_id.':'.$field;
|
||||
$element = ContentElement::query()->where('source_ref', $ref)->first();
|
||||
|
||||
if ($element === null) {
|
||||
$element = $content->createElement('text', 'text', $title);
|
||||
$element->source_ref = $ref;
|
||||
$element->save();
|
||||
}
|
||||
|
||||
// Der Abschnitt gehört zu dieser Übung und liegt als „Übungsabschnitt“ im gemeinsamen Medienbestand.
|
||||
app(ExerciseSections::class)->mark($element, $composition);
|
||||
|
||||
return $latest !== null && FormattedText::same($latest->body, $text)
|
||||
? $latest
|
||||
: $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE);
|
||||
}
|
||||
|
||||
private function createComposition(string $title, string $summary): Composition
|
||||
{
|
||||
$composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise);
|
||||
$composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id');
|
||||
|
||||
if ($summary !== '') {
|
||||
$composition->summary = $summary;
|
||||
}
|
||||
|
||||
$composition->save();
|
||||
|
||||
return $composition;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $document
|
||||
*/
|
||||
private function duration(array $document): string
|
||||
{
|
||||
$min = $document['duration_min'] ?? null;
|
||||
$max = $document['duration_max'] ?? null;
|
||||
|
||||
return match (true) {
|
||||
$min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten',
|
||||
$min !== null => $min.' Minuten',
|
||||
$max !== null => $max.' Minuten',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function get(string $path, array $query = [], ?string $key = null): array
|
||||
{
|
||||
$connection = app(ShinkanConnection::class);
|
||||
$response = Http::withToken((string) ($key ?? $connection->apiKey()))
|
||||
->acceptJson()
|
||||
->timeout(20)
|
||||
->get((string) $connection->url().'/api/distribution/v1'.$path, $query)
|
||||
->throw();
|
||||
|
||||
$json = $response->json();
|
||||
|
||||
if (! is_array($json)) {
|
||||
throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.');
|
||||
}
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{added?: int, updated?: int, removed?: int} $counts
|
||||
*/
|
||||
private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun
|
||||
{
|
||||
$run->update([
|
||||
'status' => $status,
|
||||
'cursor' => $cursor,
|
||||
'added' => $counts['added'] ?? 0,
|
||||
'updated' => $counts['updated'] ?? 0,
|
||||
'removed' => $counts['removed'] ?? 0,
|
||||
'error' => $error,
|
||||
'finished_at' => now(),
|
||||
]);
|
||||
|
||||
return $run;
|
||||
}
|
||||
|
||||
/** Fehlertext ohne Adresse und Schlüssel. */
|
||||
private function plain(Throwable $exception): string
|
||||
{
|
||||
if ($exception instanceof RequestException) {
|
||||
return match ($exception->response->status()) {
|
||||
401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').',
|
||||
404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).',
|
||||
default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.',
|
||||
};
|
||||
}
|
||||
|
||||
if ($exception instanceof DomainRuleException) {
|
||||
return $exception->getMessage();
|
||||
}
|
||||
|
||||
return $this->networkCause($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
|
||||
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
|
||||
*/
|
||||
private function networkCause(Throwable $exception): string
|
||||
{
|
||||
$host = app(ShinkanConnection::class)->url();
|
||||
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
|
||||
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
|
||||
$code = isset($match[1]) ? (int) $match[1] : null;
|
||||
|
||||
$cause = match (true) {
|
||||
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
|
||||
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
|
||||
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
|
||||
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
|
||||
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
|
||||
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
|
||||
default => 'Netzwerkfehler.',
|
||||
};
|
||||
|
||||
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
|
||||
/**
|
||||
* Rückfallschutz: Dieser Code kennt nur die Kompositionsarten aus {@see CompositionKind}. Eine Komposition mit einem
|
||||
* Wert, den erst eine neuere Programmversion einführt, gilt hier als nicht vorhanden. Sie wird weder geladen (der
|
||||
* Enum-Zugriff würde sonst abstürzen) noch angezeigt, bearbeitet oder veröffentlicht. Eine neuere Programmversion
|
||||
* kennt den Wert und sieht die Zeile wieder.
|
||||
*/
|
||||
class SupportedKindScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model): void
|
||||
{
|
||||
$builder->whereIn($model->qualifyColumn('kind'), CompositionKind::values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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,10 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
final readonly class CardSubject
|
||||
{
|
||||
@@ -36,24 +40,40 @@ public function __construct(
|
||||
public ?string $previewImage = null,
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
{
|
||||
return new self(
|
||||
title: $title ?? $this->title,
|
||||
summary: $summary ?? $this->summary,
|
||||
kind: $this->kind,
|
||||
badge: $this->badge,
|
||||
meta: $this->meta,
|
||||
url: $this->url,
|
||||
public: $this->public,
|
||||
notice: $this->notice,
|
||||
visual: $this->visual,
|
||||
visualLabel: $this->visualLabel,
|
||||
previewImage: $this->previewImage,
|
||||
missing: $this->missing,
|
||||
style: $this->style,
|
||||
);
|
||||
return $this->copy(['title' => $title ?? $this->title, 'summary' => $summary ?? $this->summary]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text der Karte aus einem zentralen Text des Fachobjekts. Ist er nicht gepflegt, bleibt die Karte ohne Text
|
||||
* (kein stiller Ersatz aus einem anderen Feld); in der Redaktionsvorschau steht dann ein Hinweis.
|
||||
*/
|
||||
public function withTextChoice(string $field, string $missingHint): self
|
||||
{
|
||||
if (! array_key_exists($field, $this->texts)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$text = $this->texts[$field];
|
||||
$missing = array_values(array_filter($this->missing, fn (string $hint): bool => ! str_contains($hint, 'Kurzbeschreibung')));
|
||||
|
||||
if ($text === null) {
|
||||
$missing[] = $missingHint;
|
||||
}
|
||||
|
||||
return $this->copy(['summary' => $text, 'missing' => $missing]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $changes
|
||||
*/
|
||||
private function copy(array $changes): self
|
||||
{
|
||||
return new self(...array_merge(get_object_vars($this), $changes));
|
||||
}
|
||||
}
|
||||
@@ -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,14 @@ 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'),
|
||||
'summary' => $profile->value('summary'),
|
||||
'description' => $profile->value('description'),
|
||||
'goal' => $goal,
|
||||
];
|
||||
$missing = [];
|
||||
|
||||
if ($summary === null) {
|
||||
@@ -313,6 +321,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
visualLabel: $kind,
|
||||
previewImage: $includeNonPublic ? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path) : null,
|
||||
missing: $missing,
|
||||
texts: $texts,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,13 +6,17 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* Lesesicht „Medien und Materialien“ für Premium-Karten (Website-CMS-Zielarchitektur 6.2).
|
||||
*
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung.
|
||||
* Auswahl in der Redaktion: jedes nicht archivierte Inhaltselement mit mindestens einer nicht gesperrten Fassung, dazu
|
||||
* jeder Film, der nur aus einer Website-Datei besteht (Medium ohne Inhaltsfassung, z. B. ein Teaser).
|
||||
*
|
||||
* Öffentliche Sichtbarkeit (Übergangsregel, solange öffentliche Fachobjektprofile nach ADR-29 fehlen):
|
||||
* Ein Medium hat keine eigene öffentliche Seite. Öffentlich genannt wird es heute nur als Bestandteil der gezeigten
|
||||
@@ -20,15 +24,22 @@
|
||||
* öffentlich, mit Verweis auf diese Programmseite, und nur mit bereitgestellter Fassung. Traineranleitungen erscheinen
|
||||
* nie öffentlich (vertraulich für Trainerinnen und Trainer).
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Kurzbeschreibung, Inhaltsart und Ausgabeart. Nie:
|
||||
* Beschreibung, Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte, Ausgabeadressen. Das Vorschaubild (Filmstandbild)
|
||||
* der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der Redaktionsvorschau.
|
||||
* Eine Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
* Ein Film nur mit Website-Datei hat weder Fassung noch Programm. Er erscheint öffentlich, sobald seine Website-Datei
|
||||
* für die Website freigegeben ist (die Freigabe ist die ausdrückliche Entscheidung der Redaktion), ohne Verweis auf
|
||||
* eine Programmseite und damit ohne Aktion. Ohne Freigabe bleibt er auf die Redaktionsvorschau beschränkt.
|
||||
*
|
||||
* Öffentlich gelesen werden Anzeigetitel (sonst Arbeitstitel), Inhaltsart und Ausgabeart sowie einer der Texte
|
||||
* Teaser, Kurzbeschreibung oder ausführliche Beschreibung. Welcher Text erscheint, entscheidet die Redaktion je Karte
|
||||
* (Einstellung „Text der Karte“); ohne Wahl gilt die Kurzbeschreibung, sonst der Teaser. Die ausführliche Beschreibung
|
||||
* erscheint nur, wenn die Redaktion sie ausdrücklich wählt. Nie: Einsatzhinweis, Lizenzvermerk, Dateien, Lehrtexte,
|
||||
* Ausgabeadressen. Das Vorschaubild der Bibliothek ist nicht für die Website freigegeben; es erscheint nur in der
|
||||
* Redaktionsvorschau und kann in der Karte ausdrücklich als Website-Bild übernommen werden (FilmStill).
|
||||
* Eine Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class PublicMaterialReader
|
||||
{
|
||||
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen. */
|
||||
public const CONFIDENTIAL_KINDS = ['traineranleitung'];
|
||||
/** 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;
|
||||
@@ -41,14 +52,36 @@ public function __construct(
|
||||
public function isSelectable(ContentElement $element): bool
|
||||
{
|
||||
return $element->archived_at === null
|
||||
&& $element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists();
|
||||
&& ($element->versions()->where('status', '!=', ContentVersionStatus::Gesperrt->value)->exists()
|
||||
|| $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Film ohne jede Inhaltsfassung, der nur die Website-Datei (`teaser/…`) hat, zum Beispiel ein Teaser. Er kann
|
||||
* auf der Medienkarte gewählt werden; was daraus öffentlich wird, bestimmt allein die Freigabe der Datei.
|
||||
*/
|
||||
public function isWebsiteOnlyFilm(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& filled($element->preview_path)
|
||||
&& ! $element->versions()->exists();
|
||||
}
|
||||
|
||||
public function isReady(ContentElement $element): bool
|
||||
{
|
||||
if ($this->isWebsiteOnlyFilm($element)) {
|
||||
return $this->isWebsiteReleased($element);
|
||||
}
|
||||
|
||||
return $element->versions()->where('status', ContentVersionStatus::Bereit->value)->exists();
|
||||
}
|
||||
|
||||
/** Die Website-Datei des Films ist freigegeben und wird tatsächlich ausgeliefert (WebsiteMedia). */
|
||||
private function isWebsiteReleased(ContentElement $element): bool
|
||||
{
|
||||
return app(WebsiteMedia::class)->present($element)?->kind === 'film';
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffentliches Programm, in dessen gezeigter Fassung das Element vorkommt, sonst null.
|
||||
*
|
||||
@@ -64,7 +97,7 @@ public function isPublic(ContentElement $element): bool
|
||||
return $this->isSelectable($element)
|
||||
&& $this->isReady($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true)
|
||||
&& $this->publicProgramFor($element) !== null;
|
||||
&& ($this->publicProgramFor($element) !== null || $this->isWebsiteOnlyFilm($element));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +110,13 @@ public function search(?string $term, int $limit = 25): array
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->whereNull('archived_at')
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->where(fn ($selectable) => $selectable
|
||||
->whereHas('versions', fn ($query) => $query->where('status', '!=', ContentVersionStatus::Gesperrt->value))
|
||||
->orWhere(fn ($websiteOnly) => $websiteOnly
|
||||
->where('output_class', 'film')
|
||||
->whereNotNull('preview_path')
|
||||
->where('preview_path', '!=', '')
|
||||
->whereDoesntHave('versions')))
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
@@ -124,7 +163,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
|
||||
$shown = clone $element;
|
||||
|
||||
foreach (['working_title', 'display_title', 'summary', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
foreach (['working_title', 'display_title', 'teaser', 'summary', 'description', 'thumbnail_path', 'thumbnail_alt'] as $field) {
|
||||
if (! array_key_exists($field, $draft)) {
|
||||
continue;
|
||||
}
|
||||
@@ -137,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') {
|
||||
@@ -146,17 +185,31 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$summary = trim((string) $shown->teaser);
|
||||
}
|
||||
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$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);
|
||||
}
|
||||
|
||||
$texts[$field] = $own;
|
||||
}
|
||||
|
||||
$title = (string) ($shown->display_title ?: $shown->working_title);
|
||||
|
||||
if (! array_key_exists('display_title', $draft) && $profile->origin('display_title') === 'variante') {
|
||||
$title = (string) $profile->value('display_title');
|
||||
}
|
||||
|
||||
$websiteOnly = $this->isWebsiteOnlyFilm($element);
|
||||
$meta = [$output];
|
||||
if ($program !== null) {
|
||||
$meta[] = 'Im Programm „'.$program['title'].'“';
|
||||
}
|
||||
if ($film) {
|
||||
if ($film && ! $websiteOnly) {
|
||||
$meta[] = 'Vollständiger Film nur mit Lizenz im Mitgliederbereich';
|
||||
}
|
||||
|
||||
@@ -184,6 +237,8 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
previewImage: $previewImage,
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -204,7 +259,11 @@ public function visibilityNote(ContentElement $element): string
|
||||
if ($this->isPublic($element)) {
|
||||
$program = $this->publicProgramFor($element);
|
||||
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.($program['title'] ?? '').'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
if ($program === null) {
|
||||
return 'Öffentlich mit der für die Website freigegebenen Datei, ohne Verweis auf eine Programmseite. Die Originaldatei wird nie ausgeliefert.';
|
||||
}
|
||||
|
||||
return 'Öffentlich nur als Teil der Programmseite „'.$program['title'].'“. Die Mediendatei wird dabei nicht ausgeliefert.';
|
||||
}
|
||||
|
||||
return $this->notice($element, $this->publicProgramFor($element));
|
||||
@@ -217,6 +276,7 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
{
|
||||
$reason = match (true) {
|
||||
in_array($element->editorialContentKind?->slug, self::CONFIDENTIAL_KINDS, true) => 'Traineranleitungen erscheinen nie öffentlich.',
|
||||
$this->isWebsiteOnlyFilm($element) => 'Die Website-Datei ist nicht für die Website freigegeben (Medium öffnen → Reiter „Website“ → freigeben).',
|
||||
! $this->isReady($element) => 'Das Medium hat noch keine bereitgestellte Fassung.',
|
||||
$program === null => 'Das Medium gehört zu keinem öffentlich gezeigten Programm. Medien haben noch keine eigene öffentliche Freigabe (öffentliches Profil, ADR-29).',
|
||||
default => 'Das Medium ist nicht öffentlich.',
|
||||
@@ -227,9 +287,14 @@ private function notice(ContentElement $element, ?array $program): string
|
||||
|
||||
private function optionLabel(ContentElement $element): string
|
||||
{
|
||||
$visibility = $this->isPublic($element)
|
||||
? 'öffentlich über Programmseite'
|
||||
: ($this->isReady($element) ? 'nur Redaktionsvorschau' : 'Entwurf, nur Redaktionsvorschau');
|
||||
$visibility = match (true) {
|
||||
$this->isWebsiteOnlyFilm($element) => $this->isPublic($element)
|
||||
? 'öffentlich mit Website-Datei'
|
||||
: 'Website-Datei nicht freigegeben, nur Redaktionsvorschau',
|
||||
$this->isPublic($element) => 'öffentlich über Programmseite',
|
||||
$this->isReady($element) => 'nur Redaktionsvorschau',
|
||||
default => 'Entwurf, nur Redaktionsvorschau',
|
||||
};
|
||||
$kind = $element->editorialContentKind?->label ?: self::outputLabel((string) $element->output_class);
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$kind.' · '.$visibility;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\PresentationAssignment;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Der kurze Clip, den eine Premium-Karte beim Überfahren oder Antippen abspielt.
|
||||
*
|
||||
* Gelesen wird nur, was die Redaktion ohnehin für die Website freigegeben hat (WebsiteMedia, Route website.media):
|
||||
* 1. der Trailer des Fachobjekts (Präsentationsrolle „Trailer“), sonst der Vorschauclip,
|
||||
* 2. bei einem Film ersatzweise dessen eigener freigegebener Teaser.
|
||||
* Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie über die Karte. Die Karte gibt
|
||||
* nichts frei; ohne freigegebenen Clip bleibt es beim Kartenbild.
|
||||
*
|
||||
* In der Redaktionsvorschau erklärt `notice`, warum kein Clip läuft (zugeordnet, aber nicht freigegeben).
|
||||
*/
|
||||
class CardClip
|
||||
{
|
||||
/** Rollen in der Reihenfolge, in der ein Clip gesucht wird. */
|
||||
public const ROLES = ['trailer', 'vorschauclip'];
|
||||
|
||||
public function __construct(private readonly WebsiteMedia $media) {}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
public function for(Model $subject, bool $preview): array
|
||||
{
|
||||
$assigned = PresentationAssignment::query()
|
||||
->with(['role', 'element'])
|
||||
->where('subject_type', $subject->getMorphClass())
|
||||
->where('subject_id', $subject->getKey())
|
||||
->whereHas('role', fn ($query) => $query->whereIn('slug', self::ROLES))
|
||||
->orderBy('position')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->sortBy(fn (PresentationAssignment $row): int => (int) array_search($row->role?->slug, self::ROLES, true))
|
||||
->values();
|
||||
|
||||
$unreleased = null;
|
||||
|
||||
foreach ($assigned as $assignment) {
|
||||
$element = $assignment->element;
|
||||
|
||||
if (! $element instanceof ContentElement || $element->archived_at !== null || $element->output_class !== 'film') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$present = $this->media->present($element);
|
||||
|
||||
if ($present !== null && $present->kind === 'film') {
|
||||
return $this->found($present->url, $present->title, $assignment->role?->slug === 'trailer' ? 'trailer' : 'vorschauclip');
|
||||
}
|
||||
|
||||
$unreleased ??= $element;
|
||||
}
|
||||
|
||||
if ($subject instanceof ContentElement && $subject->output_class === 'film') {
|
||||
$own = $this->media->present($subject);
|
||||
|
||||
if ($own !== null && $own->kind === 'film') {
|
||||
return $this->found($own->url, $own->title, 'teaser');
|
||||
}
|
||||
}
|
||||
|
||||
if (! $preview) {
|
||||
return $this->none();
|
||||
}
|
||||
|
||||
if ($unreleased instanceof ContentElement) {
|
||||
$title = (string) ($unreleased->display_title ?: $unreleased->working_title);
|
||||
|
||||
return $this->none('Der Trailer „'.$title.'“ ist nicht für die Website freigegeben; öffentlich bleibt es beim Kartenbild (Medium öffnen → Reiter „Website“ → freigeben).');
|
||||
}
|
||||
|
||||
return $this->none(null, 'Kein Trailer zugeordnet; die Karte zeigt nur das Bild (Rolle „Trailer“ in der Präsentation des Mediums).');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function found(string $url, string $title, string $source): array
|
||||
{
|
||||
return ['url' => $url, 'title' => $title, 'source' => $source, 'notice' => null, 'hint' => null];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, source: string, notice: string|null, hint: string|null}
|
||||
*/
|
||||
private function none(?string $notice = null, ?string $hint = null): array
|
||||
{
|
||||
return ['url' => null, 'title' => '', 'source' => 'none', 'notice' => $notice, 'hint' => $hint];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
<?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'];
|
||||
|
||||
/** @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';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Support;
|
||||
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
|
||||
/**
|
||||
* Das Video des Einstiegs (Hero): ein stummer Clip auf der Fläche des Fotos.
|
||||
*
|
||||
* Gewählt wird ein Film aus dem Medienmanager. Abgespielt wird nur, was die Redaktion für die Website freigegeben hat,
|
||||
* und zwar nach derselben Regel wie auf der Karte (CardClip): Trailer des Films, sonst sein Vorschauclip, sonst seine
|
||||
* eigene freigegebene Website-Datei. Der vollständige Film, die Originaldatei und nicht freigegebene Clips kommen nie
|
||||
* über den Einstieg. Ohne freigegebenen Clip bleibt es beim Foto; die Auswahl gibt nichts frei.
|
||||
*/
|
||||
final class HeroVideo
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CardClip $clips,
|
||||
private readonly PublicMaterialReader $materials,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Auswahlliste: Filme, die auf der Website gezeigt werden dürfen, mit dem Stand ihrer Freigabe.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function options(?string $term, int $limit = 25): array
|
||||
{
|
||||
$term = trim((string) $term);
|
||||
|
||||
$candidates = ContentElement::query()
|
||||
->with('editorialContentKind')
|
||||
->where('output_class', 'film')
|
||||
->whereNull('archived_at')
|
||||
->when($term !== '', function ($query) use ($term): void {
|
||||
$like = '%'.mb_strtolower($term).'%';
|
||||
$query->where(fn ($inner) => $inner
|
||||
->whereRaw('LOWER(working_title) LIKE ?', [$like])
|
||||
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
|
||||
})
|
||||
->orderBy('working_title')
|
||||
->limit($limit * 2)
|
||||
->get();
|
||||
|
||||
$options = [];
|
||||
|
||||
foreach ($candidates as $element) {
|
||||
if (! $this->allowed($element)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$options[$element->id] = $this->label($element);
|
||||
|
||||
if (count($options) >= $limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
public function labelFor(mixed $id): ?string
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $this->label($element) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die gewählte Kennung. Gibt die Kennung zurück oder null, wenn keine gewählt ist oder die Wahl ungültig ist.
|
||||
*/
|
||||
public function clean(mixed $value, WidgetErrors $errors, string $key = 'refs.video'): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || $value === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$element = is_numeric($value) ? ContentElement::query()->with('editorialContentKind')->find((int) $value) : null;
|
||||
|
||||
if (! $element instanceof ContentElement || ! $this->allowed($element)) {
|
||||
$errors->add($key, 'Bitte einen Film aus dem Medienmanager wählen (nicht archiviert, nicht gesperrt, keine Traineranleitung).');
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $element->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{url: string|null, title: string, notice: string|null}
|
||||
*/
|
||||
public function resolve(mixed $id, bool $preview): array
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
if (! $element instanceof ContentElement) {
|
||||
return ['url' => null, 'title' => '', 'notice' => null];
|
||||
}
|
||||
|
||||
$title = (string) ($element->display_title ?: $element->working_title);
|
||||
|
||||
if (! $this->allowed($element)) {
|
||||
return ['url' => null, 'title' => $title, 'notice' => $preview ? 'Das gewählte Medium „'.$title.'“ ist archiviert oder gesperrt; es erscheint kein Video.' : null];
|
||||
}
|
||||
|
||||
$clip = $this->clips->for($element, $preview);
|
||||
|
||||
if ($clip['url'] !== null) {
|
||||
return ['url' => $clip['url'], 'title' => $clip['title'] !== '' ? $clip['title'] : $title, 'notice' => null];
|
||||
}
|
||||
|
||||
return [
|
||||
'url' => null,
|
||||
'title' => $title,
|
||||
'notice' => $preview
|
||||
? 'Für „'.$title.'“ gibt es kein für die Website freigegebenes Video (Trailer, Vorschauclip oder freigegebene Website-Datei des Mediums); öffentlich bleibt es beim Foto. Freigabe: Medium öffnen → Reiter „Website“.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
/** Ein Film, der nicht archiviert, nicht gesperrt und keine Traineranleitung ist. */
|
||||
private function allowed(ContentElement $element): bool
|
||||
{
|
||||
return $element->output_class === 'film'
|
||||
&& $this->materials->isSelectable($element)
|
||||
&& ! in_array($element->editorialContentKind?->slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true);
|
||||
}
|
||||
|
||||
private function label(ContentElement $element): string
|
||||
{
|
||||
$state = $this->clips->for($element, false)['url'] !== null ? 'Video freigegeben' : 'noch kein freigegebenes Video';
|
||||
|
||||
return (string) ($element->display_title ?: $element->working_title).' · '.$state;
|
||||
}
|
||||
}
|
||||
@@ -127,6 +127,10 @@ public function url(mixed $value, bool $preview = false): ?string
|
||||
|
||||
$legacy = self::normalize($value);
|
||||
|
||||
if (is_string($legacy) && WebsiteMediaAlias::isRetired($legacy)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return is_string($legacy) ? PublicMedia::url($legacy) : null;
|
||||
}
|
||||
|
||||
@@ -175,6 +179,10 @@ public function status(mixed $value): ?array
|
||||
|
||||
$id = $this->elementId($value);
|
||||
|
||||
if ($id === null && WebsiteMediaAlias::isRetired($value)) {
|
||||
return ['public' => false, 'state' => 'missing', 'title' => basename((string) $value), 'note' => 'Das Medium wurde gelöscht.', 'thumb' => null, 'manageUrl' => null];
|
||||
}
|
||||
|
||||
if ($id === null) {
|
||||
return [
|
||||
'public' => true,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
@@ -90,6 +91,31 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
if (! SafeUrl::isSafe($data['url'] ?? null)) {
|
||||
|
||||
@@ -3,15 +3,18 @@
|
||||
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\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\SafeUrl;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use 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.
|
||||
@@ -85,11 +88,33 @@ public function dataRules(): array
|
||||
'items.*.title' => ['required', 'string', 'max:120'],
|
||||
'items.*.text' => ['nullable', 'string', 'max:500'],
|
||||
'items.*.url' => ['nullable', 'string', 'max:500'],
|
||||
'items.*.symbol' => ['nullable', 'string', Rule::in(array_keys(HeadingAccent::symbols()))],
|
||||
'items.*.image' => ['nullable'],
|
||||
'items.*._upload' => ['nullable'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
'symbol_size' => HeadingAccent::STEPS,
|
||||
'align' => HeadingAccent::TEXT_ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['symbol_size', 'align']];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'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.'],
|
||||
'align' => ['Ausrichtung', 'Richtet Symbol, Titel und Text jeder Karte aus. Vorgabe: linksbündig.'],
|
||||
];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
{
|
||||
[$image, $upload, $status] = ImageRefFields::fields('Bild (optional)');
|
||||
@@ -99,6 +124,8 @@ public function dataFields(): array
|
||||
->label('Karten')
|
||||
->schema([
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(120),
|
||||
SymbolField::make('symbol', 'Symbol (optional)')
|
||||
->helperText('Kleine Grafik aus dem Brand-Kit über dem Titel. Größe und Ausrichtung im Reiter „Darstellung“.'),
|
||||
Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500),
|
||||
TextInput::make('url')
|
||||
->label('Linkziel')
|
||||
@@ -128,10 +155,12 @@ 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");
|
||||
|
||||
// Der Schlüssel symbol wird nur gespeichert, wenn ein Symbol gewählt ist: Karten ohne Symbol bleiben byteweise wie zuvor.
|
||||
$data['items'][$index] = [
|
||||
'title' => $item['title'],
|
||||
'text' => filled($item['text'] ?? null) ? $item['text'] : null,
|
||||
'url' => filled($item['url'] ?? null) ? $item['url'] : null,
|
||||
...(filled($item['symbol'] ?? null) ? ['symbol' => $item['symbol']] : []),
|
||||
'image' => $itemRefs['image'],
|
||||
];
|
||||
}
|
||||
@@ -154,6 +183,7 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
'title' => $item['title'],
|
||||
'text' => $item['text'] ?? null,
|
||||
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
|
||||
'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]),
|
||||
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
|
||||
];
|
||||
|
||||
@@ -162,7 +192,11 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
}
|
||||
}
|
||||
|
||||
return ['items' => $items, 'imageNotice' => $notices === [] ? null : implode(' ', $notices)];
|
||||
return [
|
||||
'items' => $items,
|
||||
'layout' => HeadingAccent::block($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,217 @@
|
||||
<?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\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;
|
||||
|
||||
/** @var array<string, string> */
|
||||
public const DIVIDER = ['line' => 'Feiner Strich zwischen den Merkmalen'];
|
||||
|
||||
/**
|
||||
* Gültige Layout-Einstellungen mit Vorgaben (links, mittel, ohne Strich); alles andere fällt auf die Vorgabe zurück.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array{align: string, size: string, divider: bool}
|
||||
*/
|
||||
public static function layout(array $settings): array
|
||||
{
|
||||
return HeadingAccent::block($settings) + ['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; 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,
|
||||
'divider' => self::DIVIDER,
|
||||
'link_style' => HeadingAccent::LINK_STYLE,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return ['Aussehen' => ['align', 'symbol_size', '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.'],
|
||||
'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),
|
||||
TextInput::make('url')
|
||||
->label('Linkziel (optional)')
|
||||
->maxLength(500)
|
||||
->rule(SafeUrl::rule())
|
||||
->helperText('Seitenpfad wie /materialien oder eine http(s)-Adresse. 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,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\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -71,6 +72,31 @@ public function dataFields(): array
|
||||
];
|
||||
}
|
||||
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
return (string) ($widget['data']['heading'] ?? '');
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
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;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
@@ -20,6 +23,10 @@
|
||||
* Containerbreite), Label, Überschriftenebene, Bildfokus in Prozent, Akzent, zwei Schaltflächen.
|
||||
* Die data-Schlüssel der Version 1 (heading, text, cta_*, alt) bleiben unverändert, damit ältere Revisionen und ein
|
||||
* Code-Rollback darstellbar bleiben.
|
||||
*
|
||||
* Optional ein Video (refs.video, ein Film aus dem Medienmanager): In der Variante „Foto mit Textfläche“ läuft ein
|
||||
* stummer, für die Website freigegebener Clip auf der Fläche des Fotos (HeroVideo, resources/js/hero-video.js). Neuer
|
||||
* Schlüssel ohne Versionssprung; ältere Revisionen ohne `video` bleiben unverändert darstellbar.
|
||||
*/
|
||||
class HeroWidget extends WidgetType
|
||||
{
|
||||
@@ -64,9 +71,9 @@ public function narrowBehavior(): string
|
||||
public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (mind. 400 px)',
|
||||
'normal' => 'Normal (mind. 512 px)',
|
||||
'large' => 'Groß (mind. 640 px)',
|
||||
'compact' => 'Kompakt (niedriger, 75 % der Standardhöhe)',
|
||||
'normal' => 'Standard',
|
||||
'large' => 'Großzügig (höher, 130 % der Standardhöhe)',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -106,14 +113,28 @@ 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', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'heading_level' => ['Überschriftenebene', 'Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'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,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -152,7 +173,7 @@ public function dataRules(): array
|
||||
|
||||
public function refRules(): array
|
||||
{
|
||||
return ImageRefFields::rules();
|
||||
return ImageRefFields::rules() + ['video' => ['nullable']];
|
||||
}
|
||||
|
||||
public function dataFields(): array
|
||||
@@ -169,7 +190,19 @@ public function dataFields(): array
|
||||
|
||||
public function refFields(): array
|
||||
{
|
||||
return ImageRefFields::fields(live: true);
|
||||
return [...ImageRefFields::fields(live: true), $this->videoField()];
|
||||
}
|
||||
|
||||
private function videoField(): Select
|
||||
{
|
||||
return Select::make('video')
|
||||
->label('Video (optional)')
|
||||
->helperText('Ein Film aus dem Medienmanager. Läuft stumm auf der Fläche des Fotos, nur in der Variante „Foto mit Textfläche“ und nur, wenn ein Trailer, Vorschauclip oder die Website-Datei des Films für die Website freigegeben ist. Das Foto bleibt als Rückfall, bei „reduzierte Bewegung“ und im Datensparmodus startet das Video nur auf Wunsch. Die Auswahl gibt nichts frei.')
|
||||
->live()
|
||||
->searchable()
|
||||
->getSearchResultsUsing(fn (?string $search): array => app(HeroVideo::class)->options($search))
|
||||
->getOptionLabelUsing(fn (mixed $value): ?string => app(HeroVideo::class)->labelFor($value))
|
||||
->options(fn (): array => app(HeroVideo::class)->options(null));
|
||||
}
|
||||
|
||||
public function editorSchema(): array
|
||||
@@ -192,6 +225,8 @@ public function mediaSchema(): array
|
||||
public function clean(array $data, array $refs, WidgetErrors $errors): array
|
||||
{
|
||||
$refs = ImageRefFields::clean($refs, $errors);
|
||||
$video = app(HeroVideo::class)->clean($refs['video'] ?? null, $errors);
|
||||
$video === null ? $refs = array_diff_key($refs, ['video' => true]) : $refs['video'] = $video;
|
||||
$data['heading'] = trim((string) ($data['heading'] ?? ''));
|
||||
$data['text'] = filled($data['text'] ?? null) ? trim((string) $data['text']) : null;
|
||||
$data = PremiumFields::clean($data, $errors, $refs['image'] !== null);
|
||||
@@ -205,8 +240,15 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
|
||||
$images = app(WebsiteImage::class);
|
||||
$image = $widget['refs']['image'] ?? null;
|
||||
$video = app(HeroVideo::class)->resolve($widget['refs']['video'] ?? null, $context->preview);
|
||||
$photoSplit = ($widget['variant'] ?? 'photo_split') !== 'editorial_solid';
|
||||
|
||||
if (! $photoSplit && $video['title'] !== '') {
|
||||
$video = ['url' => null, 'title' => $video['title'], 'notice' => $context->preview ? 'Das Video erscheint nur in der Variante „Foto mit Textfläche“; die Markenfläche zeigt kein Video.' : null];
|
||||
}
|
||||
|
||||
return [
|
||||
'video' => $video,
|
||||
'imageUrl' => $images->url($image, $context->preview),
|
||||
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
|
||||
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
|
||||
|
||||
@@ -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\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
@@ -73,7 +74,7 @@ public function heights(): array
|
||||
{
|
||||
return [
|
||||
'compact' => 'Kompakt (flacheres Bild, engere Abstände)',
|
||||
'normal' => 'Normal',
|
||||
'normal' => 'Standard',
|
||||
'spacious' => 'Großzügig (höheres Bild, mehr Abstand)',
|
||||
];
|
||||
}
|
||||
@@ -114,6 +115,17 @@ public function settings(): array
|
||||
return [
|
||||
'surface' => ['cream' => 'Creme (Markenfläche)', 'clear' => 'Ohne eigene Fläche', 'navy' => 'Navy (dunkel)'],
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -121,7 +133,10 @@ public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
'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.'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,17 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicMaterialReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\FilmStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Medien- und Materialkarte (Kit v1.7 „media“): ein Inhaltselement mit Anzeigetitel, Kurzbeschreibung, Inhaltsart und
|
||||
* Ausgabeart. Filme erscheinen als Medienkarte (grüne Aktion, Filmtafel ohne freigegebenes Bild), Dokumente und andere
|
||||
* Materialien als Materialkarte (Materialsymbol). Öffentlich nur nach den Regeln von PublicMaterialReader; die Aktion
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt nichts ab, bietet keinen Download und gibt kein Medium frei.
|
||||
* führt auf die öffentliche Programmseite. Die Karte spielt höchstens den für die Website freigegebenen Trailer ab (CardClip), bietet keinen Download und gibt kein Medium frei.
|
||||
*/
|
||||
class MediaCardWidget extends PremiumCardWidget
|
||||
{
|
||||
@@ -28,7 +33,7 @@ public function label(): string
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, kein Abspielen, kein Download.';
|
||||
return 'Karte zu einem Film oder Material aus der Bibliothek; Titel und Art kommen aus den Fachdaten, Trailer nur wenn freigegeben, kein Download.';
|
||||
}
|
||||
|
||||
public function icon(): string
|
||||
@@ -53,7 +58,7 @@ protected function refLabel(): string
|
||||
|
||||
protected function refHelp(): string
|
||||
{
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; Traineranleitungen nie. Titel und Kurzbeschreibung pflegen Sie im Medium.';
|
||||
return 'Wählbar sind alle nicht archivierten, nicht gesperrten Filme und Materialien. Öffentlich erscheint die Karte nur mit bereitgestellter Fassung und wenn der Inhalt zu einem öffentlich gezeigten Programm gehört; ein Film nur mit Website-Datei (zum Beispiel ein Teaser) erscheint, sobald diese Datei für die Website freigegeben ist. Traineranleitungen nie. Titel, Teaser, Kurzbeschreibung und Beschreibung pflegen Sie im Medium; welcher Text auf der Karte erscheint, wählen Sie unter „Darstellung“.';
|
||||
}
|
||||
|
||||
protected function searchSubjects(?string $term): array
|
||||
@@ -90,6 +95,80 @@ protected function cardStyle(): string
|
||||
return 'media';
|
||||
}
|
||||
|
||||
/**
|
||||
* Bei einem Film: das Vorschaubild des Films oder eine Stelle des Films als Kartenbild übernehmen. Das Bild wird
|
||||
* einmal als Bild-Medium abgelegt (FilmStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_filmbild')
|
||||
->label('Bild aus dem Film')
|
||||
->view('filament.cms.filmbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->filmFor($get('element')) !== null)
|
||||
->viewData(fn (Get $get): array => $this->filmFieldData($this->filmFor($get('element')))),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzeigedaten des Felds „Bild aus dem Film“. Die Stelle kommt aus der bereitgestellten Fassung, bei einem Film
|
||||
* nur mit Website-Datei aus dieser (Route content.website-frame).
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function filmFieldData(?ContentElement $film): array
|
||||
{
|
||||
$stills = app(FilmStill::class);
|
||||
$version = $film instanceof ContentElement ? $stills->version($film) : null;
|
||||
|
||||
return [
|
||||
'film' => $film,
|
||||
'filmTitle' => $film instanceof ContentElement ? (string) ($film->display_title ?: $film->working_title) : '',
|
||||
'filmVersionId' => $version?->id,
|
||||
'filmWebsiteFrameUrl' => $film instanceof ContentElement && $version === null && $stills->websiteFile($film) !== null
|
||||
? route('content.website-frame', ['element' => $film])
|
||||
: null,
|
||||
'filmHasThumbnail' => $film instanceof ContentElement && is_string($film->thumbnail_path) && $film->thumbnail_path !== '',
|
||||
'filmThumbnailUrl' => $film instanceof ContentElement ? ThumbnailRef::url('editorial.card', 'element', (int) $film->id, $film->thumbnail_path) : null,
|
||||
'filmStartSecond' => $film instanceof ContentElement ? ($stills->thumbnailSecond($film) ?? '0') : '0',
|
||||
];
|
||||
}
|
||||
|
||||
private function filmFor(mixed $id): ?ContentElement
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement && app(FilmStill::class)->refusal($element) === null ? $element : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Medium';
|
||||
}
|
||||
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Kurzbeschreibung, sonst Teaser)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
];
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
return $element instanceof ContentElement ? $element : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$element = is_numeric($id) ? ContentElement::query()->find((int) $id) : null;
|
||||
|
||||
@@ -4,16 +4,19 @@
|
||||
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\CardClip;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
use App\Domain\Cms\Widgets\Support\PublicMedia;
|
||||
use App\Domain\Cms\Widgets\Support\WebsiteImage;
|
||||
use App\Domain\Cms\Widgets\WidgetErrors;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Field;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
@@ -56,6 +59,56 @@ abstract protected function defaultActionLabel(): string;
|
||||
/** Gestaltungsvariante des Kits: editorial, media oder catalog. */
|
||||
abstract protected function cardStyle(): string;
|
||||
|
||||
/**
|
||||
* Weitere Wege zum Kartenbild im Reiter „Medien“, zum Beispiel ein Bild aus dem Film. Standard: keine.
|
||||
*
|
||||
* @return list<Field>
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fachobjekt, dessen Trailer die Karte beim Überfahren oder Antippen abspielt (Medium, Programm, Modul).
|
||||
* Null: diese Karte hat keinen Clip (Thema). Der Clip kommt aus der Präsentation des Objekts (CardClip).
|
||||
*/
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentrale Texte des Fachobjekts, aus denen die Redaktion den Kartentext wählen kann: Wert => Bezeichnung.
|
||||
* Leer: keine Wahl (die Karte nimmt den Text ihrer Vorgabe). Mit Wahl gilt „auto“ als Vorgabe.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** Was die Redaktion bearbeitet, um einen Text zu pflegen („Medium“, „Programm oder Modul“); für Hinweise. */
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Objekt';
|
||||
}
|
||||
|
||||
/** Hinweis der Redaktionsvorschau, wenn der gewählte zentrale Text nicht gepflegt ist. */
|
||||
private function missingTextHint(string $field): string
|
||||
{
|
||||
$noun = $this->subjectNoun();
|
||||
|
||||
return match ($field) {
|
||||
'teaser' => 'Kein Teaser gepflegt ('.$noun.' bearbeiten → Teaser).',
|
||||
'summary' => 'Keine Kurzbeschreibung gepflegt ('.$noun.' bearbeiten → Kurzbeschreibung).',
|
||||
'description' => 'Keine ausführliche Beschreibung gepflegt ('.$noun.' bearbeiten → Beschreibung).',
|
||||
'goal' => 'Kein Lernziel gepflegt ('.$noun.' bearbeiten → Lernziel der Fassung).',
|
||||
default => '',
|
||||
};
|
||||
}
|
||||
|
||||
public function view(): string
|
||||
{
|
||||
return 'widgets.premium_card';
|
||||
@@ -110,7 +163,9 @@ public function optionIcons(): array
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
return [
|
||||
$choices = $this->textChoices();
|
||||
|
||||
return ($choices === [] ? [] : ['text_source' => $choices]) + ($this->supportsClip() ? ['clip' => ['yes' => 'Abspielen', 'no' => 'Nicht abspielen'], 'show_body' => self::SHOW] : []) + [
|
||||
'format' => ['landscape' => 'Querformat 16:9', 'square' => 'Quadrat 1:1', 'portrait' => 'Hochformat 3:4'],
|
||||
'fit' => ['cover' => 'Ausschnitt füllt die Fläche', 'contain' => 'Ganzes Bild zeigen (Dokument, Poster)'],
|
||||
'heading_level' => ['h3' => 'H3', 'h2' => 'H2', 'h4' => 'H4'],
|
||||
@@ -121,16 +176,34 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Bild und Video' => ['format', 'fit', 'clip'],
|
||||
'Texte auf der Karte' => ['show_body', 'text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
// „Texte auf der Karte: Ausblenden“ macht die Einzelschalter wirkungslos; sie bleiben gespeichert, aber unsichtbar.
|
||||
return array_fill_keys(['text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'], ['show_body', 'no']);
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'format' => ['Bildformat', 'Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bilddarstellung', 'Vorgabe: Ausschnitt. „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
'show_summary' => ['Kurzbeschreibung', 'Aus den Fachdaten. Vorgabe: anzeigen.'],
|
||||
'show_kind' => ['Art oder Label', 'Zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: anzeigen.'],
|
||||
'show_action' => ['Aktion', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: anzeigen.'],
|
||||
'format' => ['Bildformat', 'Seitenverhältnis des Bildes oder Videos. Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bildausschnitt', 'Ausschnitt füllt die ganze Fläche; „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche. Vorgabe: Ausschnitt.'],
|
||||
'clip' => ['Trailer auf der Karte', 'Spielt den freigegebenen Trailer als stumme Vorschau, solange die Maus auf der Karte steht; ein Klick oder Tipp auf das Bild oder die kleine Schaltfläche (auch per Tastatur) spielt ihn mit Ton. Gewählt wird der Trailer (sonst der Vorschauclip) in der Präsentation des Objekts, bei einem Film ersatzweise sein freigegebener Teaser. Ohne freigegebenen Clip bleibt das Kartenbild. Vorgabe: Abspielen.'],
|
||||
'show_body' => ['Texte auf der Karte', 'Hauptschalter für alle Texte neben dem Bild. „Ausblenden“ zeigt nur Bild und Video, ohne Titel, Beschreibung, Art, Zusatzangaben und Schaltfläche; die Einzelschalter darunter verschwinden dann. Für Hilfstechnik bleibt der Titel unsichtbar erhalten. Sinnvoll, wenn das Video allein erklärt. Vorgabe: Anzeigen.'],
|
||||
'text_source' => ['Quelle der Beschreibung', 'Welche Angabe aus der Redaktion als Beschreibung erscheint. Vorgabe: Automatisch. Der Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Beschreibung.'],
|
||||
'show_summary' => ['Beschreibung', 'Der Beschreibungstext unter dem Titel, aus den Fachdaten. Vorgabe: Anzeigen.'],
|
||||
'show_kind' => ['Art-Label', 'Kleines Label über dem Titel, zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: Anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Angaben aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: Anzeigen.'],
|
||||
'show_action' => ['Schaltfläche', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: Anzeigen.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -195,13 +268,13 @@ public function editorSchema(): array
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt den Anzeigenamen des Fachobjekts. Eine Eintragung gilt nur für diese Karte und ändert die Quelle nicht.'),
|
||||
TextInput::make('summary')
|
||||
->label('Teaser nur für diese Karte')
|
||||
->label('Text nur für diese Karte')
|
||||
->maxLength(500)
|
||||
->live(onBlur: true)
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary') ?? 'Zentraler Teaser oder Kurzbeschreibung')
|
||||
->placeholder(fn (Get $get): string => $this->centralText($get('../refs.'.$this->refKey()), 'summary', $get('../settings.text_source')) ?? 'Zentraler Text aus der Redaktion')
|
||||
->hint(fn (?string $state): string => filled($state) ? 'Eigene Angabe für diese Karte' : 'Aus der Redaktion')
|
||||
->hintColor(fn (?string $state): string => filled($state) ? 'warning' : 'gray')
|
||||
->helperText('Leer übernimmt Teaser oder Kurzbeschreibung. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
->helperText('Leer übernimmt den Text, den „Text der Karte“ (Darstellung) wählt. Lehrinhalt, Rechte und Preise bleiben unberührt.'),
|
||||
])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -211,7 +284,7 @@ public function mediaSchema(): array
|
||||
[, , $alt, $focusX, $focusY] = $this->dataFields();
|
||||
|
||||
return [
|
||||
Group::make(ImageRefFields::fields('Kartenbild', live: true))->statePath('refs'),
|
||||
Group::make([...ImageRefFields::fields('Kartenbild', live: true), ...$this->imageSourceFields()])->statePath('refs'),
|
||||
Group::make([$alt, $focusX, $focusY])->statePath('data'),
|
||||
];
|
||||
}
|
||||
@@ -248,6 +321,12 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$data = $widget['data'];
|
||||
|
||||
$subject = $this->subject($widget['refs'][$this->refKey()] ?? null, $context);
|
||||
$textSource = $option('text_source', 'auto');
|
||||
|
||||
if ($subject instanceof CardSubject && $textSource !== 'auto' && isset($this->textChoices()[$textSource])) {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$heading = filled($data['heading'] ?? null) ? trim((string) $data['heading']) : null;
|
||||
$lead = filled($data['summary'] ?? null) ? trim((string) $data['summary']) : null;
|
||||
|
||||
@@ -258,8 +337,16 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
$storedImage = WebsiteImage::normalize($widget['refs']['image'] ?? null);
|
||||
$imageRef = $storedImage ?? $this->centralCoverId($widget['refs'][$this->refKey()] ?? null);
|
||||
|
||||
$clip = null;
|
||||
|
||||
if ($this->supportsClip() && $option('clip', 'yes') === 'yes' && $subject instanceof CardSubject) {
|
||||
$owner = $this->clipSubject($widget['refs'][$this->refKey()] ?? null);
|
||||
$clip = $owner instanceof Model ? app(CardClip::class)->for($owner, $context->preview) : null;
|
||||
}
|
||||
|
||||
return [
|
||||
'subject' => $subject,
|
||||
'clip' => $clip,
|
||||
'cardStyle' => $subject?->style ?? $this->cardStyle(),
|
||||
'imageUrl' => app(WebsiteImage::class)->url($imageRef, $context->preview),
|
||||
'alt' => app(WebsiteImage::class)->alt($imageRef, $data['alt'] ?? null),
|
||||
@@ -277,6 +364,7 @@ public function resolve(array $widget, RenderContext $context): array
|
||||
'actionLabel' => filled($data['action_label'] ?? null) ? (string) $data['action_label'] : $this->defaultActionLabel(),
|
||||
'note' => filled($data['note'] ?? null) ? (string) $data['note'] : null,
|
||||
'stacked' => $widget['variant'] === 'stacked',
|
||||
'bare' => $this->supportsClip() && $option('show_body', 'yes') === 'no',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -299,10 +387,15 @@ protected function centralCoverId(mixed $id): ?int
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zentraler Anzeigename oder Teaser des gewählten Objekts (Redaktionsstand) für Platzhalter im Editor.
|
||||
*/
|
||||
private function centralText(mixed $id, string $field): ?string
|
||||
private function centralText(mixed $id, string $field, mixed $textSource = null): ?string
|
||||
{
|
||||
if (blank($id)) {
|
||||
return null;
|
||||
@@ -314,6 +407,10 @@ private function centralText(mixed $id, string $field): ?string
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($subject instanceof CardSubject && is_string($textSource) && isset($this->textChoices()[$textSource]) && $textSource !== 'auto') {
|
||||
$subject = $subject->withTextChoice($textSource, $this->missingTextHint($textSource));
|
||||
}
|
||||
|
||||
$text = $subject?->{$field};
|
||||
|
||||
return is_string($text) && trim($text) !== '' ? Str::limit(trim($text), 120) : null;
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
use App\Domain\Cms\Catalog\CardSubject;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Media\CompositionStill;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Modul- und Programmkarte (Kit v1.7 „catalog“): ein Programm oder Modul über PublicCatalogReader, dieselbe
|
||||
@@ -41,6 +46,59 @@ public function schematic(): array
|
||||
return [[2, 2, 56, 32, 'line'], [5, 5, 22, 26, 'ink'], [8, 24, 10, 2, 'accent'], [31, 8, 10, 2, 'line'], [31, 13, 22, 4, 'ink'], [31, 25, 14, 5, 'ink']];
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Vorschaubild des Programms oder Moduls als Kartenbild übernehmen. Es wird einmal als Bild-Medium abgelegt
|
||||
* (CompositionStill) und wie jedes andere Bild ausgewählt; die Karte liest nur diese Datei.
|
||||
*/
|
||||
protected function imageSourceFields(): array
|
||||
{
|
||||
return [
|
||||
ViewField::make('_programmbild')
|
||||
->label('Bild aus dem Programm oder Modul')
|
||||
->view('filament.cms.kompositionsbild-feld')
|
||||
->dehydrated(false)
|
||||
->visible(fn (Get $get): bool => $this->compositionFor($get('composition')) !== null)
|
||||
->viewData(function (Get $get): array {
|
||||
$composition = $this->compositionFor($get('composition'));
|
||||
|
||||
return [
|
||||
'composition' => $composition,
|
||||
'compositionTitle' => $composition instanceof Composition ? (string) ($composition->display_title ?: $composition->designation) : '',
|
||||
'compositionThumbnailUrl' => $composition instanceof Composition && app(CompositionStill::class)->hasThumbnail($composition)
|
||||
? ThumbnailRef::url('editorial.card', 'komposition', (int) $composition->id, $composition->thumbnail_path)
|
||||
: null,
|
||||
];
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
private function compositionFor(mixed $id): ?Composition
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->with('editorialContentKind')->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition && app(PublicCatalogReader::class)->isCardSelectable($composition) ? $composition : null;
|
||||
}
|
||||
|
||||
protected function subjectNoun(): string
|
||||
{
|
||||
return 'Programm oder Modul';
|
||||
}
|
||||
|
||||
/**
|
||||
* Wählbare Texte: die zentralen Texte des Programms oder Moduls und das Lernziel der Fassung. „Automatisch“ bleibt
|
||||
* wie bisher: Teaser, sonst Kurzbeschreibung, sonst Lernziel. Die ausführliche Beschreibung erscheint nur auf Wahl.
|
||||
*/
|
||||
protected function textChoices(): array
|
||||
{
|
||||
return [
|
||||
'auto' => 'Automatisch (Teaser, sonst Kurzbeschreibung, sonst Lernziel)',
|
||||
'teaser' => 'Teaser',
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung (erscheint öffentlich)',
|
||||
'goal' => 'Lernziel der Fassung',
|
||||
];
|
||||
}
|
||||
|
||||
public function settings(): array
|
||||
{
|
||||
// Die Art (Programm oder Modul) bleibt immer sichtbar; sie lässt sich nicht ausblenden.
|
||||
@@ -99,6 +157,18 @@ protected function cardStyle(): string
|
||||
return 'catalog';
|
||||
}
|
||||
|
||||
protected function supportsClip(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function clipSubject(mixed $id): ?Model
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
return $composition instanceof Composition ? $composition : null;
|
||||
}
|
||||
|
||||
protected function centralCoverId(mixed $id): ?int
|
||||
{
|
||||
$composition = is_numeric($id) ? Composition::query()->find((int) $id) : null;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\RichText;
|
||||
use App\Domain\Cms\Widgets\WidgetType;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
@@ -69,6 +70,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 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,
|
||||
];
|
||||
}
|
||||
|
||||
public function summary(array $widget): string
|
||||
{
|
||||
return RichText::excerpt(e((string) ($widget['data']['body'] ?? '')));
|
||||
|
||||
@@ -41,7 +41,7 @@ public function version(): int
|
||||
public const HEIGHTS = [
|
||||
'auto' => 'Automatisch',
|
||||
'compact' => 'Kompakt',
|
||||
'normal' => 'Normal',
|
||||
'normal' => 'Standard',
|
||||
'large' => 'Groß',
|
||||
'spacious' => 'Großzügig',
|
||||
'fill' => 'Abschnittshöhe füllen',
|
||||
@@ -194,6 +194,29 @@ public function settingLabels(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung der Einstellungen im Reiter „Darstellung“: Gruppentitel => Schlüssel der Einstellungen in der
|
||||
* Reihenfolge der Anzeige. Variante und Höhe stehen immer in der ersten Gruppe „Aufbau“. Einstellungen ohne
|
||||
* Gruppe erscheinen unter „Weitere Einstellungen“, so geht keine verloren.
|
||||
*
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen, die im Editor ausgeblendet werden, solange eine andere Einstellung einen bestimmten Wert hat:
|
||||
* Schlüssel => [steuernde Einstellung, Wert, bei dem ausgeblendet wird]. Die Werte bleiben dabei erhalten.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle zulässigen Einstellungen einschließlich der gemeinsamen Höhe. Registry-Prüfung, Editor und Darstellung
|
||||
* verwenden ausschließlich diese Zusammenführung.
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
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\Discount\DiscountResult;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* Sitzungsgebundener Mehrangebotswarenkorb (Etappe 1). Er bleibt in derselben Browsersitzung über Anmeldung,
|
||||
* Registrierung und E-Mail-Bestätigung erhalten. Je Option gibt es genau eine Position. Optionen derselben Produktseite
|
||||
* (gleiche Komposition) sind Alternativen und werden nur nach ausdrücklichem Wechsel ersetzt.
|
||||
* Der Warenkorb reserviert weder Preis noch Konditionen; er merkt sich, was der Käufer gesehen hat.
|
||||
*/
|
||||
class Cart
|
||||
{
|
||||
public const KEY = 'shop.cart';
|
||||
|
||||
/** Eingelöster Rabattcode (Kennung); höchstens einer je Bestellung. */
|
||||
public const DISCOUNT_KEY = 'shop.discount';
|
||||
|
||||
public const ADDED = 'added';
|
||||
|
||||
public const PRESENT = 'present';
|
||||
|
||||
public const ALTERNATIVE = 'alternative';
|
||||
|
||||
public const UNAVAILABLE = 'unavailable';
|
||||
|
||||
public function __construct(
|
||||
private readonly OwnershipCheck $ownership,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly OfferService $offers,
|
||||
private readonly DiscountService $discounts,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return array<int, array{version_id: int, price_cents: int}>
|
||||
*/
|
||||
public function items(): array
|
||||
{
|
||||
return (array) session()->get(self::KEY, []);
|
||||
}
|
||||
|
||||
public function count(): int
|
||||
{
|
||||
return count($this->items());
|
||||
}
|
||||
|
||||
public function has(Offer $offer): bool
|
||||
{
|
||||
return isset($this->items()[$offer->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die bereits enthaltene Alternative derselben Produktseite, falls vorhanden.
|
||||
*/
|
||||
public function alternativeTo(Offer $offer): ?Offer
|
||||
{
|
||||
$products = app(ProductOptions::class);
|
||||
$group = $products->groupKey($offer);
|
||||
|
||||
if ($group === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ids = array_diff(array_keys($this->items()), [$offer->id]);
|
||||
|
||||
return $ids === [] ? null : Offer::query()
|
||||
->whereIn('id', $ids)
|
||||
->get()
|
||||
->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
|
||||
}
|
||||
|
||||
public function add(Offer $offer): string
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return self::UNAVAILABLE;
|
||||
}
|
||||
|
||||
if ($this->has($offer)) {
|
||||
return self::PRESENT;
|
||||
}
|
||||
|
||||
if ($this->alternativeTo($offer) !== null) {
|
||||
return self::ALTERNATIVE;
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return self::ADDED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ausdrücklicher Wechsel: die Alternative wird durch die gewählte Option ersetzt.
|
||||
*/
|
||||
public function switchTo(Offer $offer): bool
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$alternative = $this->alternativeTo($offer);
|
||||
|
||||
if ($alternative !== null) {
|
||||
$this->remove($alternative);
|
||||
}
|
||||
|
||||
$this->put($offer, $version);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function remove(Offer $offer): void
|
||||
{
|
||||
$items = $this->items();
|
||||
unset($items[$offer->id]);
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* Der Käufer übernimmt Preis und Fassung, die der Shop jetzt zeigt.
|
||||
*/
|
||||
public function acceptCurrent(Offer $offer): void
|
||||
{
|
||||
$version = $this->purchasable($offer);
|
||||
|
||||
if ($version !== null && $this->has($offer)) {
|
||||
$this->put($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
session()->forget([self::KEY, self::DISCOUNT_KEY]);
|
||||
}
|
||||
|
||||
/** Der im Warenkorb eingelöste Code, auch wenn er gerade nicht (mehr) gilt. */
|
||||
public function discountCode(): ?DiscountCode
|
||||
{
|
||||
$id = session()->get(self::DISCOUNT_KEY);
|
||||
|
||||
return is_numeric($id) ? DiscountCode::query()->with('targets')->find((int) $id) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Löst einen Code ein. Er wird nur vorgemerkt, wenn er für diesen Warenkorb und dieses Konto gilt; sonst bleibt
|
||||
* der bisherige Stand und das Ergebnis nennt den Grund. Ein zweiter Code ersetzt den ersten (höchstens ein Code).
|
||||
*/
|
||||
public function applyCode(string $input, ?User $user, ?int $holderPartyId = null): DiscountResult
|
||||
{
|
||||
$code = $this->discounts->find($input);
|
||||
|
||||
if ($code === null) {
|
||||
return new DiscountResult(null, DiscountResult::UNKNOWN, 'Diesen Code kennen wir nicht. Prüfe die Schreibweise.');
|
||||
}
|
||||
|
||||
$previous = session()->get(self::DISCOUNT_KEY);
|
||||
session()->put(self::DISCOUNT_KEY, $code->id);
|
||||
$result = $this->review($user, $holderPartyId)->discount;
|
||||
|
||||
if ($result === null || ! $result->applied()) {
|
||||
$previous === null ? session()->forget(self::DISCOUNT_KEY) : session()->put(self::DISCOUNT_KEY, $previous);
|
||||
|
||||
return $result ?? new DiscountResult($code, DiscountResult::NO_MATCH, 'Der Code kann auf diese Bestellung nicht angewendet werden.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function removeCode(): void
|
||||
{
|
||||
session()->forget(self::DISCOUNT_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
|
||||
*/
|
||||
public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview
|
||||
{
|
||||
$offers = Offer::query()
|
||||
->whereIn('id', array_keys($this->items()))
|
||||
->with('composition')
|
||||
->get()
|
||||
->keyBy('id');
|
||||
$versions = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer !== null) {
|
||||
$versions[$offerId] = $this->purchasable($offer);
|
||||
}
|
||||
}
|
||||
|
||||
$holder = $user === null ? null : $this->holderFor($user, $holderPartyId, $versions);
|
||||
$lines = [];
|
||||
|
||||
foreach ($this->items() as $offerId => $item) {
|
||||
$offer = $offers->get($offerId);
|
||||
|
||||
if ($offer === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$version = $versions[$offerId] ?? null;
|
||||
$seen = (int) $item['price_cents'];
|
||||
|
||||
if ($version === null) {
|
||||
$lines[] = new CartLine($offer, null, CartLine::WITHDRAWN, $seen, null,
|
||||
'Diese Option ist nicht mehr erhältlich. Entferne sie, um mit den übrigen Positionen fortzufahren.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = (int) $version->price_cents;
|
||||
|
||||
if ($holder !== null && ! $this->suitsHolder($version, $holder)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::WRONG_HOLDER, $seen, $current,
|
||||
$version->holder_kind === 'organisation'
|
||||
? 'Diese Option ist für Organisationen. Bestelle als Verein oder entferne sie.'
|
||||
: 'Diese Option ist für Privatpersonen. Bestelle als Privatperson oder entferne sie.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($holder !== null && $this->ownership->covers($holder, $version)) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OWNED, $seen, $current);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($current !== $seen) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::PRICE_CHANGED, $seen, $current);
|
||||
} elseif ((int) $item['version_id'] !== $version->id) {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::TERMS_CHANGED, $seen, $current,
|
||||
'Die Bedingungen dieser Option wurden aktualisiert. Bitte prüfe die Übersicht.');
|
||||
} else {
|
||||
$lines[] = new CartLine($offer, $version, CartLine::OK, $seen, $current);
|
||||
}
|
||||
}
|
||||
|
||||
$code = $this->discountCode();
|
||||
$discount = null;
|
||||
|
||||
if ($code !== null) {
|
||||
$orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
$discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount);
|
||||
}
|
||||
|
||||
return new CartReview($lines, $holder, $discount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktive, als Kauf angebotene Fassung der Option; sonst null (nicht kaufbar oder zurückgezogen).
|
||||
*/
|
||||
public function purchasable(Offer $offer): ?OfferVersion
|
||||
{
|
||||
return $this->offers->purchasableVersion($offer);
|
||||
}
|
||||
|
||||
private function put(Offer $offer, OfferVersion $version): void
|
||||
{
|
||||
$items = $this->items();
|
||||
$items[$offer->id] = ['version_id' => $version->id, 'price_cents' => (int) $version->price_cents];
|
||||
session()->put(self::KEY, $items);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, OfferVersion|null> $versions
|
||||
*/
|
||||
private function holderFor(User $user, ?int $partyId, array $versions): ?Party
|
||||
{
|
||||
$onlyOrganisations = $versions !== [] && collect($versions)
|
||||
->filter()
|
||||
->every(fn (OfferVersion $version): bool => $version->holder_kind === 'organisation');
|
||||
|
||||
try {
|
||||
return $this->holders->resolve($user, $partyId, $onlyOrganisations);
|
||||
} catch (DomainRuleException) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private function suitsHolder(OfferVersion $version, Party $holder): bool
|
||||
{
|
||||
return ($version->holder_kind === 'organisation') === ($holder->type === PartyType::Organisation);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
|
||||
/**
|
||||
* Eine Position des Warenkorbs mit dem Ergebnis der serverseitigen Prüfung.
|
||||
*/
|
||||
final class CartLine
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const PRICE_CHANGED = 'preis_geaendert';
|
||||
|
||||
public const TERMS_CHANGED = 'bedingungen_geaendert';
|
||||
|
||||
public const WITHDRAWN = 'zurueckgezogen';
|
||||
|
||||
public const OWNED = 'bereits_erworben';
|
||||
|
||||
public const WRONG_HOLDER = 'falscher_inhaber';
|
||||
|
||||
public function __construct(
|
||||
public readonly Offer $offer,
|
||||
public readonly ?OfferVersion $version,
|
||||
public readonly string $state,
|
||||
public readonly int $seenPriceCents,
|
||||
public readonly ?int $currentPriceCents,
|
||||
public readonly ?string $note = null,
|
||||
) {}
|
||||
|
||||
/** Geht in Summe und Bestellung ein. */
|
||||
public function orderable(): bool
|
||||
{
|
||||
return in_array($this->state, [self::OK, self::PRICE_CHANGED, self::TERMS_CHANGED], true);
|
||||
}
|
||||
|
||||
/** Verhindert den Abschluss, bis der Käufer die Position selbst entfernt oder den Inhaber wechselt. */
|
||||
public function blocks(): bool
|
||||
{
|
||||
return in_array($this->state, [self::WITHDRAWN, self::WRONG_HOLDER], true);
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
if ($this->offer->standalone_bundle && $this->version !== null) {
|
||||
$bundle = app(ProductOptions::class)->bundleOf($this->version);
|
||||
|
||||
if ($bundle !== null) {
|
||||
return (string) $bundle->name;
|
||||
}
|
||||
}
|
||||
|
||||
$composition = $this->offer->composition;
|
||||
|
||||
return $composition !== null
|
||||
? (string) ($composition->display_title ?: $composition->designation)
|
||||
: (string) $this->offer->name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* Prüfergebnis des Warenkorbs für einen vorgesehenen Lizenzinhaber. Die Prüfsumme bindet die Bestellung an genau
|
||||
* diese Übersicht: Inhaber, Fassung und Preis jeder Position samt Zustand, auch der ausgeschlossenen.
|
||||
*/
|
||||
final class CartReview
|
||||
{
|
||||
/**
|
||||
* @param list<CartLine> $lines
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $lines,
|
||||
public readonly ?Party $holder,
|
||||
public readonly ?DiscountResult $discount = null,
|
||||
) {}
|
||||
|
||||
/** @return list<CartLine> */
|
||||
public function orderable(): array
|
||||
{
|
||||
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
}
|
||||
|
||||
/** Summe der Listenpreise der Positionen, die in die Bestellung eingehen. */
|
||||
public function subtotalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable()));
|
||||
}
|
||||
|
||||
public function discountCents(): int
|
||||
{
|
||||
return $this->discount?->totalCents() ?? 0;
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag: Listenpreise abzüglich Rabatt. */
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->subtotalCents() - $this->discountCents();
|
||||
}
|
||||
|
||||
/** Rabatt einer Position in Cent. */
|
||||
public function discountFor(CartLine $line): int
|
||||
{
|
||||
return $this->discount?->forOffer($line->offer->id) ?? 0;
|
||||
}
|
||||
|
||||
/** Ein vorgemerkter Code, der jetzt nicht gilt, hält die Bestellung an, bis er entfernt wird. */
|
||||
public function discountBlocks(): bool
|
||||
{
|
||||
return $this->discount !== null && ! $this->discount->applied();
|
||||
}
|
||||
|
||||
public function blocked(): bool
|
||||
{
|
||||
foreach ($this->lines as $line) {
|
||||
if ($line->blocks()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function empty(): bool
|
||||
{
|
||||
return $this->orderable() === [];
|
||||
}
|
||||
|
||||
public function canOrder(): bool
|
||||
{
|
||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks();
|
||||
}
|
||||
|
||||
public function digest(): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
foreach ($this->lines as $line) {
|
||||
$parts[] = $line->offer->id.':'.($line->version?->id ?? 0).':'.$line->currentPriceCents.':'.$line->state;
|
||||
}
|
||||
|
||||
sort($parts);
|
||||
|
||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,19 @@
|
||||
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;
|
||||
use App\Domain\Entitlement\Acquisition;
|
||||
use App\Domain\Entitlement\AcquisitionType;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Mail\OrderConfirmed;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -20,12 +26,21 @@ 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
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
$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);
|
||||
@@ -38,20 +53,114 @@ public function place(User $user, Offer $offer): Order
|
||||
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($user, $offer, $version): Order {
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $user->party_id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => 'person',
|
||||
]);
|
||||
$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
|
||||
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
||||
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
||||
*/
|
||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
if ($consent === null && Shop::live()) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order {
|
||||
// Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug
|
||||
// der Freigabe die Prüfung nicht unterläuft.
|
||||
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
|
||||
$discountId = session()->get(Cart::DISCOUNT_KEY);
|
||||
|
||||
if (is_numeric($discountId)) {
|
||||
DiscountCode::query()->whereKey((int) $discountId)->lockForUpdate()->first();
|
||||
}
|
||||
|
||||
$review = $cart->review($user, $holderPartyId, lockDiscount: true);
|
||||
|
||||
if ($review->holder === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
if (! hash_equals($review->digest(), $digest)) {
|
||||
throw new StaleOverview('Die Übersicht hat sich geändert. Bitte prüfe die aktualisierte Bestellübersicht.');
|
||||
}
|
||||
|
||||
if ($review->blocked()) {
|
||||
throw new DomainRuleException('Entferne zuerst die Positionen, die nicht bestellt werden können.');
|
||||
}
|
||||
|
||||
if ($review->empty()) {
|
||||
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
|
||||
}
|
||||
|
||||
if ($review->discountBlocks()) {
|
||||
throw new DomainRuleException(($review->discount?->message ?? 'Der Rabattcode gilt nicht.').' Entferne den Code, um ohne Rabatt zu bestellen.');
|
||||
}
|
||||
|
||||
$method = $paymentMethod ?? (Shop::driver() === 'stripe' ? 'stripe' : 'test');
|
||||
|
||||
if ($method === 'rechnung' && ! ($review->holder->type === PartyType::Organisation && Shop::invoice())) {
|
||||
throw new DomainRuleException('Der Kauf auf Rechnung ist nur für Vereine und Organisationen auf Anfrage möglich.');
|
||||
}
|
||||
|
||||
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
|
||||
|
||||
return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
||||
});
|
||||
|
||||
$cart->clear();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
||||
* @param array<string, mixed>|null $terms Nachweis der Zustimmungen (SalesTerms::proof)
|
||||
*/
|
||||
private function createOrder(User $user, Party $holder, array $pairs, ?CartReview $review, ?array $terms, string $method): Order
|
||||
{
|
||||
$subtotal = array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs));
|
||||
$discount = $review?->discount;
|
||||
$discountCents = $review?->discountCents() ?? 0;
|
||||
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $holder->id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => $holder->type->value,
|
||||
'subtotal_cents' => $subtotal,
|
||||
'discount_cents' => $discountCents,
|
||||
'total_cents' => $subtotal - $discountCents,
|
||||
'currency' => 'EUR',
|
||||
'discount_code_id' => $discountCents > 0 ? $discount?->code?->id : null,
|
||||
'discount_snapshot' => $discountCents > 0 ? $discount?->snapshot() : null,
|
||||
'payment_method' => $method,
|
||||
'terms_accepted_at' => $terms === null ? null : now(),
|
||||
'terms_snapshot' => $terms,
|
||||
]);
|
||||
|
||||
foreach ($pairs as [$offer, $version]) {
|
||||
$line = $order->lines()->create([
|
||||
'offer_version_id' => $version->id,
|
||||
'offer_name' => $offer->name,
|
||||
'price_cents' => $version->price_cents,
|
||||
'currency' => 'EUR',
|
||||
'term_rule' => $version->term_rule,
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'tax_class' => $version->tax_class,
|
||||
'grant_kind' => $version->grant_kind,
|
||||
'holder_party_id' => $holder->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0,
|
||||
]);
|
||||
$version->load('resolvedScopes.rights');
|
||||
|
||||
@@ -66,14 +175,62 @@ public function place(User $user, Offer $offer): Order
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $order->load('lines.scopeItems');
|
||||
});
|
||||
return $order->load('lines.scopeItems');
|
||||
}
|
||||
|
||||
/**
|
||||
* Freischaltung nach bestätigter Testzahlung: alle Bestellpositionen aus ihrem festgehaltenen Umfang, in einer
|
||||
* Transaktion. Wiederholte Bestätigung ist wirkungslos; ein Fehler hinterlässt weder Zahlung noch Rechte.
|
||||
*/
|
||||
public function confirmTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return $this->settle($order, 'test', $reference, null, now(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet
|
||||
* es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung
|
||||
* laut Anbieter, sonst jetzt.
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
|
||||
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
|
||||
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf
|
||||
* dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in
|
||||
* welchen Zeitraum die Einnahme fällt.
|
||||
*/
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
if ($order->payment_method !== 'rechnung') {
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
$day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at);
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live());
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
if ($reference === '') {
|
||||
@@ -81,7 +238,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $reference, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -92,22 +249,24 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
$order->payments()->create([
|
||||
'provider' => 'test',
|
||||
'status' => 'bestaetigt',
|
||||
'provider_reference' => $reference,
|
||||
]);
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$payment = $order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
array_filter(
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
|
||||
fn (mixed $value): bool => $value !== null,
|
||||
),
|
||||
);
|
||||
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$this->grants->issue(
|
||||
$order->user,
|
||||
$line->offerVersion,
|
||||
AcquisitionType::Bestellposition,
|
||||
'order_line',
|
||||
$line->id,
|
||||
);
|
||||
$actor = User::query()->findOrFail($order->user_id);
|
||||
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$holder = Party::query()->findOrFail($line->holder_party_id ?? $order->party_id);
|
||||
$this->grants->issueFromOrderLine($line, $holder, $actor);
|
||||
}
|
||||
|
||||
return $order->load('lines', 'payments');
|
||||
});
|
||||
@@ -122,6 +281,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
public function failTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return DB::transaction(function () use ($order, $reference): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
@@ -142,7 +302,16 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
});
|
||||
}
|
||||
|
||||
public function refund(Order $order, string $reason): Order
|
||||
/**
|
||||
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
||||
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
||||
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
||||
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
|
||||
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
|
||||
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
|
||||
*/
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order
|
||||
{
|
||||
$reason = trim($reason);
|
||||
|
||||
@@ -150,22 +319,31 @@ public function refund(Order $order, string $reason): Order
|
||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason): Order {
|
||||
$current = Order::query()->findOrFail($order->id);
|
||||
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at);
|
||||
$booking = null;
|
||||
|
||||
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
||||
$result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()];
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
|
||||
}
|
||||
|
||||
$line = $order->lines()->firstOrFail();
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
||||
$acquisition = Acquisition::query()->where([
|
||||
'type' => AcquisitionType::Bestellposition,
|
||||
'reference_type' => 'order_line',
|
||||
'reference_id' => $line->id,
|
||||
])->first();
|
||||
|
||||
if ($acquisition !== null) {
|
||||
foreach ($acquisition->grants as $grant) {
|
||||
foreach ($acquisition?->grants ?? [] as $grant) {
|
||||
if ($grant->status === GrantStatus::Aktiv) {
|
||||
$grant->status = GrantStatus::Widerrufen;
|
||||
$grant->status_reason = $reason;
|
||||
@@ -174,6 +352,16 @@ public function refund(Order $order, string $reason): Order
|
||||
}
|
||||
}
|
||||
|
||||
$payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$this->journal->recordRefund(
|
||||
$order,
|
||||
$payment,
|
||||
$booking['at'] ?? $manualAt,
|
||||
$actor,
|
||||
$reason,
|
||||
$booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id),
|
||||
$booking['status'] ?? null,
|
||||
);
|
||||
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
||||
$order->status = 'erstattet';
|
||||
$order->save();
|
||||
@@ -182,6 +370,43 @@ public function refund(Order $order, string $reason): Order
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und
|
||||
* erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit
|
||||
* ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung.
|
||||
*/
|
||||
public function requestWithdrawal(Order $order, string $note): Order
|
||||
{
|
||||
if (! in_array($order->status, ['bezahlt', 'offen'], true)) {
|
||||
throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.');
|
||||
}
|
||||
|
||||
if ($order->withdrawal_requested_at !== null) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$order->withdrawal_requested_at = now();
|
||||
$order->withdrawal_note = trim($note) !== '' ? trim($note) : null;
|
||||
$order->save();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
private function assertActive(User $user): void
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */
|
||||
private function assertTestOrder(Order $order): void
|
||||
{
|
||||
if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) {
|
||||
throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.');
|
||||
}
|
||||
}
|
||||
|
||||
private function assertTestDriver(): void
|
||||
{
|
||||
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
|
||||
*
|
||||
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
|
||||
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
|
||||
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
|
||||
*
|
||||
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
|
||||
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
|
||||
* frühere Position.
|
||||
*/
|
||||
final class DiscountCalculator
|
||||
{
|
||||
/**
|
||||
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
|
||||
* @return array<int|string, int> Schlüssel => Rabatt in Cent
|
||||
*/
|
||||
public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array
|
||||
{
|
||||
$discounts = array_fill_keys(array_keys($prices), 0);
|
||||
|
||||
if ($prices === []) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = max(0, min(100, (int) $percent));
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$discounts[$key] = min($price, intdiv($price * $percent + 50, 100));
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$sum = array_sum($prices);
|
||||
$total = min(max(0, (int) $amountCents), $sum);
|
||||
|
||||
if ($total === 0 || $sum === 0) {
|
||||
return $discounts;
|
||||
}
|
||||
|
||||
$remainders = [];
|
||||
$given = 0;
|
||||
|
||||
foreach ($prices as $key => $price) {
|
||||
$share = intdiv($total * $price, $sum);
|
||||
$discounts[$key] = $share;
|
||||
$remainders[$key] = ($total * $price) % $sum;
|
||||
$given += $share;
|
||||
}
|
||||
|
||||
$rest = $total - $given;
|
||||
$order = array_keys($prices);
|
||||
usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]);
|
||||
|
||||
foreach ($order as $key) {
|
||||
if ($rest === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
if ($discounts[$key] < $prices[$key]) {
|
||||
$discounts[$key]++;
|
||||
$rest--;
|
||||
}
|
||||
}
|
||||
|
||||
return $discounts;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
|
||||
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
|
||||
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
|
||||
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
|
||||
*/
|
||||
class DiscountCode extends Model
|
||||
{
|
||||
public const PERCENT = 'prozent';
|
||||
|
||||
public const AMOUNT = 'betrag';
|
||||
|
||||
public const SCOPE_CART = 'warenkorb';
|
||||
|
||||
public const SCOPE_SELECTED = 'auswahl';
|
||||
|
||||
public const OPEN = 'allgemein';
|
||||
|
||||
public const RESTRICTED = 'freigabe';
|
||||
|
||||
public const TARGET_OFFER = 'angebot';
|
||||
|
||||
public const TARGET_ARTICLE = 'lizenzartikel';
|
||||
|
||||
public const TARGET_BUNDLE = 'paket';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'label',
|
||||
'kind',
|
||||
'percent',
|
||||
'amount_cents',
|
||||
'scope',
|
||||
'eligibility',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
'active',
|
||||
'note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'valid_from' => 'datetime',
|
||||
'valid_until' => 'datetime',
|
||||
'active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */
|
||||
public static function normalise(string $input): string
|
||||
{
|
||||
return mb_strtoupper((string) preg_replace('/\s+/u', '', $input));
|
||||
}
|
||||
|
||||
public function targets(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountCodeTarget::class);
|
||||
}
|
||||
|
||||
public function releases(): HasMany
|
||||
{
|
||||
return $this->hasMany(DiscountRelease::class)->latest('id');
|
||||
}
|
||||
|
||||
public function restricted(): bool
|
||||
{
|
||||
return $this->eligibility === self::RESTRICTED;
|
||||
}
|
||||
|
||||
public function forSelection(): bool
|
||||
{
|
||||
return $this->scope === self::SCOPE_SELECTED;
|
||||
}
|
||||
|
||||
/** Lesbare Höhe: „10 %“ oder „5,00 €“. */
|
||||
public function valueLabel(): string
|
||||
{
|
||||
return $this->kind === self::PERCENT
|
||||
? (int) $this->percent.' %'
|
||||
: Money::format((int) $this->amount_cents);
|
||||
}
|
||||
|
||||
/** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */
|
||||
public function stateAt(CarbonInterface $now): string
|
||||
{
|
||||
return match (true) {
|
||||
! $this->active => 'deaktiviert',
|
||||
$this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht',
|
||||
$this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen',
|
||||
default => 'aktiv',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
|
||||
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
|
||||
*/
|
||||
class DiscountCodeTarget extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'target_type',
|
||||
'target_id',
|
||||
];
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
|
||||
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
|
||||
*/
|
||||
class DiscountRelease extends Model
|
||||
{
|
||||
protected $table = 'discount_code_releases';
|
||||
|
||||
protected $fillable = [
|
||||
'discount_code_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 code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
|
||||
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
|
||||
* den Grund erfährt.
|
||||
*/
|
||||
final class DiscountResult
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const UNKNOWN = 'unbekannt';
|
||||
|
||||
public const INACTIVE = 'deaktiviert';
|
||||
|
||||
public const NOT_YET = 'noch_nicht';
|
||||
|
||||
public const EXPIRED = 'abgelaufen';
|
||||
|
||||
public const LOGIN = 'anmeldung';
|
||||
|
||||
public const NO_RELEASE = 'keine_freigabe';
|
||||
|
||||
public const NO_MATCH = 'keine_position';
|
||||
|
||||
public const TOO_HIGH = 'zu_hoch';
|
||||
|
||||
/**
|
||||
* @param array<int, int> $perOffer Kennung der Option => Rabatt in Cent
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ?DiscountCode $code,
|
||||
public readonly string $state,
|
||||
public readonly ?string $message = null,
|
||||
public readonly array $perOffer = [],
|
||||
) {}
|
||||
|
||||
public function applied(): bool
|
||||
{
|
||||
return $this->state === self::OK && $this->totalCents() > 0;
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->state === self::OK ? array_sum($this->perOffer) : 0;
|
||||
}
|
||||
|
||||
public function forOffer(int $offerId): int
|
||||
{
|
||||
return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0;
|
||||
}
|
||||
|
||||
/** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */
|
||||
public function snapshot(): array
|
||||
{
|
||||
return [
|
||||
'code' => $this->code?->code,
|
||||
'label' => $this->code?->label,
|
||||
'kind' => $this->code?->kind,
|
||||
'percent' => $this->code?->percent,
|
||||
'amount_cents' => $this->code?->amount_cents,
|
||||
'scope' => $this->code?->scope,
|
||||
'eligibility' => $this->code?->eligibility,
|
||||
'discount_cents' => $this->totalCents(),
|
||||
];
|
||||
}
|
||||
|
||||
/** Teil der Prüfsumme der Bestellübersicht. */
|
||||
public function digestPart(): string
|
||||
{
|
||||
$parts = [];
|
||||
$perOffer = $this->perOffer;
|
||||
ksort($perOffer);
|
||||
|
||||
foreach ($perOffer as $offerId => $cents) {
|
||||
$parts[] = $offerId.'='.$cents;
|
||||
}
|
||||
|
||||
return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\CartLine;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
|
||||
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
|
||||
*/
|
||||
class DiscountService
|
||||
{
|
||||
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
|
||||
public const MIN_PAYABLE_CENTS = 50;
|
||||
|
||||
public function find(string $input): ?DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise($input);
|
||||
|
||||
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<CartLine> $lines nur Positionen, die in die Bestellung eingehen
|
||||
*/
|
||||
public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult
|
||||
{
|
||||
$now ??= now();
|
||||
|
||||
$timing = $code->stateAt($now);
|
||||
|
||||
if ($timing !== 'aktiv') {
|
||||
return new DiscountResult($code, $timing, match ($timing) {
|
||||
'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.',
|
||||
'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.',
|
||||
default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').',
|
||||
});
|
||||
}
|
||||
|
||||
if ($code->restricted()) {
|
||||
if ($user === null) {
|
||||
return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.');
|
||||
}
|
||||
|
||||
if ($this->activeRelease($code, $user, $now, $lock) === null) {
|
||||
return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.');
|
||||
}
|
||||
}
|
||||
|
||||
$matching = [];
|
||||
|
||||
foreach ($lines as $line) {
|
||||
if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) {
|
||||
$matching[$line->offer->id] = (int) $line->currentPriceCents;
|
||||
}
|
||||
}
|
||||
|
||||
if ($matching === []) {
|
||||
return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection()
|
||||
? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.'
|
||||
: 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.');
|
||||
}
|
||||
|
||||
$perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching);
|
||||
$payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer);
|
||||
|
||||
if ($payable < self::MIN_PAYABLE_CENTS) {
|
||||
return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.');
|
||||
}
|
||||
|
||||
return new DiscountResult($code, DiscountResult::OK, null, $perOffer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der
|
||||
* Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht
|
||||
* rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig.
|
||||
*/
|
||||
public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool
|
||||
{
|
||||
if (! $code->forSelection()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all());
|
||||
|
||||
if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$version->loadMissing('lines.bundleVersion');
|
||||
|
||||
foreach ($version->lines as $line) {
|
||||
if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease
|
||||
{
|
||||
$now ??= now();
|
||||
$query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at');
|
||||
|
||||
if ($lock) {
|
||||
$query->lockForUpdate();
|
||||
}
|
||||
|
||||
return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now));
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
*/
|
||||
public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise((string) ($data['code'] ?? ''));
|
||||
$label = trim((string) ($data['label'] ?? ''));
|
||||
|
||||
if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) {
|
||||
throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.');
|
||||
}
|
||||
|
||||
if ($label === '') {
|
||||
throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.');
|
||||
}
|
||||
|
||||
if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) {
|
||||
throw new DomainRuleException('Diesen Code gibt es schon.');
|
||||
}
|
||||
|
||||
$kind = (string) ($data['kind'] ?? '');
|
||||
$percent = null;
|
||||
$amount = null;
|
||||
|
||||
if ($kind === DiscountCode::PERCENT) {
|
||||
$percent = (int) ($data['percent'] ?? 0);
|
||||
|
||||
if ($percent < 1 || $percent > 100) {
|
||||
throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.');
|
||||
}
|
||||
} elseif ($kind === DiscountCode::AMOUNT) {
|
||||
$amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null));
|
||||
|
||||
if ($amount === null || $amount <= 0) {
|
||||
throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.');
|
||||
}
|
||||
} else {
|
||||
throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.');
|
||||
}
|
||||
|
||||
$scope = (string) ($data['scope'] ?? '');
|
||||
$eligibility = (string) ($data['eligibility'] ?? '');
|
||||
|
||||
if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) {
|
||||
throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.');
|
||||
}
|
||||
|
||||
if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) {
|
||||
throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.');
|
||||
}
|
||||
|
||||
$targets = $this->cleanTargets($targets);
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) {
|
||||
throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.');
|
||||
}
|
||||
|
||||
$from = $this->date($data['valid_from'] ?? null);
|
||||
$until = $this->date($data['valid_until'] ?? null, true);
|
||||
|
||||
if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) {
|
||||
throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode {
|
||||
$model = $existing ?? new DiscountCode;
|
||||
$model->fill([
|
||||
'code' => $code,
|
||||
'label' => $label,
|
||||
'kind' => $kind,
|
||||
'percent' => $percent,
|
||||
'amount_cents' => $amount,
|
||||
'scope' => $scope,
|
||||
'eligibility' => $eligibility,
|
||||
'valid_from' => $from,
|
||||
'valid_until' => $until,
|
||||
'active' => (bool) ($data['active'] ?? true),
|
||||
'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null,
|
||||
]);
|
||||
$model->save();
|
||||
|
||||
$model->targets()->delete();
|
||||
|
||||
if ($scope === DiscountCode::SCOPE_SELECTED) {
|
||||
foreach ($targets as $target) {
|
||||
$model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]);
|
||||
}
|
||||
}
|
||||
|
||||
return $model->load('targets');
|
||||
});
|
||||
}
|
||||
|
||||
public function setActive(DiscountCode $code, bool $active): DiscountCode
|
||||
{
|
||||
$code->active = $active;
|
||||
$code->save();
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht.
|
||||
*/
|
||||
public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
if (! $code->restricted()) {
|
||||
throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.');
|
||||
}
|
||||
|
||||
if ($member->party_id === null) {
|
||||
throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease {
|
||||
DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
if ($this->activeRelease($code, $member) !== null) {
|
||||
throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.');
|
||||
}
|
||||
|
||||
if ($until !== null && $until->lessThanOrEqualTo(now())) {
|
||||
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
|
||||
}
|
||||
|
||||
return DiscountRelease::query()->create([
|
||||
'discount_code_id' => $code->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.
|
||||
*/
|
||||
public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease
|
||||
{
|
||||
return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease {
|
||||
$release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id);
|
||||
|
||||
if ($release->revoked_at !== null) {
|
||||
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
|
||||
}
|
||||
|
||||
$release->revoked_at = now();
|
||||
$release->revoked_by = $actor?->id;
|
||||
$release->reason = filled($reason) ? trim((string) $reason) : $release->reason;
|
||||
$release->save();
|
||||
|
||||
return $release;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
* @return list<array{type: string, id: int}>
|
||||
*/
|
||||
private function cleanTargets(array $targets): array
|
||||
{
|
||||
$clean = [];
|
||||
|
||||
foreach ($targets as $target) {
|
||||
$type = (string) ($target['type'] ?? '');
|
||||
$id = (int) ($target['id'] ?? 0);
|
||||
$exists = match ($type) {
|
||||
DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(),
|
||||
DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(),
|
||||
default => false,
|
||||
};
|
||||
|
||||
if (! $exists) {
|
||||
throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).');
|
||||
}
|
||||
|
||||
$clean[$type.':'.$id] = ['type' => $type, 'id' => $id];
|
||||
}
|
||||
|
||||
return array_values($clean);
|
||||
}
|
||||
|
||||
/** Ein Datum ohne Uhrzeit gilt als Tag: ab Tagesbeginn, als Ende einschließlich des ganzen Tages. */
|
||||
private function date(mixed $value, bool $endOfDay = false): ?CarbonInterface
|
||||
{
|
||||
if (! filled($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = Carbon::parse((string) $value, config('app.timezone'));
|
||||
|
||||
return $endOfDay && strlen(trim((string) $value)) <= 10 ? $date->endOfDay() : $date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* Eine Geldbewegung im Zahlungsjournal (Zahlungseingang oder Erstattung). Unveränderlich: Eine Zeile wird nur
|
||||
* angelegt, nie geändert oder gelöscht. Eine Korrektur ist eine neue Gegenbuchung. Beträge sind vorzeichenbehaftet
|
||||
* (Eingang positiv, Erstattung negativ), sodass die Summe den Saldo ergibt.
|
||||
*/
|
||||
class LedgerEntry extends Model
|
||||
{
|
||||
public const KIND_PAYMENT = 'eingang';
|
||||
|
||||
public const KIND_REFUND = 'erstattung';
|
||||
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected $table = 'payment_ledger';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'occurred_at' => 'datetime',
|
||||
'amount_cents' => 'integer',
|
||||
'live' => 'boolean',
|
||||
'derived' => 'boolean',
|
||||
'payer' => 'array',
|
||||
'order_snapshot' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::updating(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.');
|
||||
});
|
||||
static::deleting(function (): never {
|
||||
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Einträge werden nie gelöscht.');
|
||||
});
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function isRefund(): bool
|
||||
{
|
||||
return $this->kind === self::KIND_REFUND;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Beträge werden als ganze Cent gespeichert und in Euro angezeigt und eingegeben (deutsches Format).
|
||||
*/
|
||||
final class Money
|
||||
{
|
||||
/** Obergrenze eines Preises (1.000.000 €), weit unter dem Wertebereich der Datenbank. */
|
||||
public const MAX_CENTS = 100_000_000;
|
||||
|
||||
public static function format(?int $cents): string
|
||||
{
|
||||
return $cents === null ? '–' : number_format($cents / 100, 2, ',', '.').' €';
|
||||
}
|
||||
|
||||
/**
|
||||
* Euro-Eingabe („12,50“, „1.299“, „5“) als Cent. Leere Eingabe ergibt null.
|
||||
*/
|
||||
public static function parse(string|int|float|null $input): ?int
|
||||
{
|
||||
if ($input === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = trim((string) $input);
|
||||
|
||||
if ($text === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = str_replace([' ', '€'], '', $text);
|
||||
|
||||
if (str_contains($text, ',')) {
|
||||
$text = str_replace('.', '', $text);
|
||||
$text = str_replace(',', '.', $text);
|
||||
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $text) === 1) {
|
||||
$text = str_replace('.', '', $text);
|
||||
}
|
||||
|
||||
if (preg_match('/^\d+(\.\d{1,2})?$/', $text) !== 1) {
|
||||
throw new DomainRuleException('Der Preis ist kein gültiger Eurobetrag, zum Beispiel 12,50.');
|
||||
}
|
||||
|
||||
$cents = (int) round(((float) $text) * 100);
|
||||
|
||||
if ($cents > self::MAX_CENTS) {
|
||||
throw new DomainRuleException('Der Preis ist zu hoch. Zulässig sind höchstens '.self::format(self::MAX_CENTS).'.');
|
||||
}
|
||||
|
||||
return $cents;
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,41 @@ class Order extends Model
|
||||
'party_id',
|
||||
'status',
|
||||
'holder_kind',
|
||||
'total_cents',
|
||||
'currency',
|
||||
'subtotal_cents',
|
||||
'discount_cents',
|
||||
'discount_code_id',
|
||||
'discount_snapshot',
|
||||
'payment_method',
|
||||
'terms_accepted_at',
|
||||
'terms_snapshot',
|
||||
'withdrawal_requested_at',
|
||||
'withdrawal_note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'discount_snapshot' => 'array',
|
||||
'terms_snapshot' => 'array',
|
||||
'terms_accepted_at' => 'datetime',
|
||||
'withdrawal_requested_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** Listenpreise vor Rabatt; bei älteren Bestellungen die Summe der Positionen. */
|
||||
public function subtotal(): int
|
||||
{
|
||||
return (int) ($this->subtotal_cents ?? $this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) ($this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Identity\Membership;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Für wen ein Konto bestellen darf: für sich selbst (Person) und für Organisationen, bei denen es eine aktive
|
||||
* Mitgliedschaft mit Bestellberechtigung hat. Eine Bestellung hat genau einen Lizenzinhaber.
|
||||
*/
|
||||
class OrderHolders
|
||||
{
|
||||
/**
|
||||
* @return Collection<int, Party>
|
||||
*/
|
||||
public function for(User $user): Collection
|
||||
{
|
||||
$holders = collect();
|
||||
|
||||
if ($user->party_id !== null) {
|
||||
$person = Party::query()->find($user->party_id);
|
||||
|
||||
if ($person !== null) {
|
||||
$holders->push($person);
|
||||
}
|
||||
}
|
||||
|
||||
$organisations = Membership::query()
|
||||
->active()
|
||||
->where('user_id', $user->id)
|
||||
->where('may_order', true)
|
||||
->with('organisation')
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->map(fn (Membership $membership): ?Party => $membership->organisation)
|
||||
->filter(fn (?Party $party): bool => $party !== null && $party->type === PartyType::Organisation);
|
||||
|
||||
return $holders->concat($organisations)->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Der gewählte Inhaber; ohne Wahl die Person, bei Angeboten nur für Organisationen die erste Organisation.
|
||||
*/
|
||||
public function resolve(User $user, ?int $partyId, bool $preferOrganisation = false): Party
|
||||
{
|
||||
$holders = $this->for($user);
|
||||
|
||||
if ($partyId !== null) {
|
||||
$chosen = $holders->first(fn (Party $party): bool => $party->id === $partyId);
|
||||
|
||||
if ($chosen === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
}
|
||||
|
||||
return $chosen;
|
||||
}
|
||||
|
||||
if ($preferOrganisation) {
|
||||
$organisation = $holders->first(fn (Party $party): bool => $party->type === PartyType::Organisation);
|
||||
|
||||
if ($organisation !== null) {
|
||||
return $organisation;
|
||||
}
|
||||
}
|
||||
|
||||
$person = $holders->first(fn (Party $party): bool => $party->type === PartyType::Person);
|
||||
|
||||
return $person ?? throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Identity\Party;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
@@ -17,13 +18,31 @@ class OrderLine extends Model
|
||||
'term_rule',
|
||||
'update_promise',
|
||||
'holder_kind',
|
||||
'currency',
|
||||
'tax_class',
|
||||
'grant_kind',
|
||||
'holder_party_id',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'discount_cents',
|
||||
];
|
||||
|
||||
/** Preis dieser Position nach Rabatt. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) $this->price_cents - (int) $this->discount_cents;
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function holder(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class, 'holder_party_id');
|
||||
}
|
||||
|
||||
public function offerVersion(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(OfferVersion::class);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
* „Bereits erworben“ (FACH-59): Der vorgesehene Lizenzinhaber hat bereits eine gültige Lizenz mit demselben Umfang
|
||||
* und denselben Nutzungsrechten. Maßgeblich ist genau ein Erwerb, der jeden Umfangsposten der Angebotsfassung mit
|
||||
* gleichem Zweck, gleichen Fähigkeiten und gleichen Optionen trägt. Rechte mehrerer Erwerbe werden nicht zu einer
|
||||
* neuen Lizenz kombiniert. Alle Erwerbsarten zählen (Kauf, freier Abruf, manuelle Vergabe), sofern aktiv und gültig.
|
||||
*/
|
||||
class OwnershipCheck
|
||||
{
|
||||
public function covers(Party $holder, OfferVersion $version): bool
|
||||
{
|
||||
$needed = $this->needed($version);
|
||||
|
||||
if ($needed === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$now = now();
|
||||
$byAcquisition = Grant::query()
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
||||
->with('acquisition')
|
||||
->get()
|
||||
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
||||
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
||||
->groupBy('acquisition_id');
|
||||
|
||||
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
|
||||
|
||||
foreach ($byAcquisition as $grants) {
|
||||
$conditions = (array) ($grants->first()->acquisition?->conditions ?? []);
|
||||
|
||||
// Gleicher Umfang heißt auch gleicher Nutzerkreis: Eine Einzellizenz deckt keine Mehrfachlizenz ab und
|
||||
// umgekehrt (der Nutzerkreis wird nicht aus Zweck oder Preis abgeleitet).
|
||||
if (LicenceScope::key($conditions['licence_scope'] ?? null, isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null) !== $wanted) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$have = [];
|
||||
|
||||
foreach ($grants as $grant) {
|
||||
$have[$grant->license_article_id.'|'.$this->fingerprint($grant->rights_snapshot ?? [])] = true;
|
||||
}
|
||||
|
||||
if (array_diff_key($needed, $have) === []) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, true>
|
||||
*/
|
||||
private function needed(OfferVersion $version): array
|
||||
{
|
||||
$needed = [];
|
||||
$version->loadMissing('resolvedScopes.rights');
|
||||
|
||||
foreach ($version->resolvedScopes as $scope) {
|
||||
$needed[$scope->license_article_id.'|'.$this->fingerprint([
|
||||
'purpose' => $scope->rights->purpose,
|
||||
'capabilities' => $scope->rights->capabilities,
|
||||
'options' => $scope->rights->options ?? [],
|
||||
])] = true;
|
||||
}
|
||||
|
||||
return $needed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reihenfolge von Schlüsseln und Aktionen spielt keine Rolle.
|
||||
*
|
||||
* @param array<string, mixed> $rights
|
||||
*/
|
||||
private function fingerprint(array $rights): string
|
||||
{
|
||||
$capabilities = [];
|
||||
|
||||
foreach ((array) ($rights['capabilities'] ?? []) as $class => $actions) {
|
||||
$actions = array_values(array_unique((array) $actions));
|
||||
sort($actions);
|
||||
$capabilities[(string) $class] = $actions;
|
||||
}
|
||||
|
||||
ksort($capabilities);
|
||||
$options = (array) ($rights['options'] ?? []);
|
||||
ksort($options);
|
||||
|
||||
return md5(json_encode([
|
||||
'purpose' => (string) ($rights['purpose'] ?? ''),
|
||||
'capabilities' => $capabilities,
|
||||
'options' => $options,
|
||||
], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,9 @@ class Payment extends Model
|
||||
'provider',
|
||||
'status',
|
||||
'provider_reference',
|
||||
'provider_payment_ref',
|
||||
'amount_cents',
|
||||
'confirmed_by',
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Zahlungsjournal: schreibt und liest die unveränderlichen Geldbewegungen (LedgerEntry). Geschrieben wird nur aus
|
||||
* derselben Transaktion, die die Bestellung auf „bezahlt“ oder „erstattet“ setzt, sodass beides nie auseinanderläuft.
|
||||
* Zeiträume und Datumsangaben gelten in deutscher Zeit (Geschäftsjahr, Monats- und Quartalsgrenzen); gespeichert wird
|
||||
* in UTC. Der Nachweis ist an die Grundsätze der ordnungsmäßigen Buchführung angelehnt (unveränderbar, nachvollziehbar);
|
||||
* ob er den Anforderungen der Steuerberatung genügt, ist dort zu bestätigen.
|
||||
*/
|
||||
final class PaymentJournal
|
||||
{
|
||||
public const TIMEZONE = 'Europe/Berlin';
|
||||
|
||||
/** Höchstzahl der in der Verwaltung gezeigten Zeilen; der Export enthält immer alle des Zeitraums. */
|
||||
public const DISPLAY_LIMIT = 500;
|
||||
|
||||
/**
|
||||
* Zahlungseingang. Wiederholte Meldung derselben Zahlung legt keine zweite Zeile an (Schlüssel: Art, Anbieter,
|
||||
* Referenz).
|
||||
*/
|
||||
public function recordPayment(Order $order, Payment $payment, CarbonInterface $occurredAt, ?User $actor, bool $live): LedgerEntry
|
||||
{
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_PAYMENT, 'provider' => $payment->provider, 'provider_reference' => $payment->provider_reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => $order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment->provider_payment_ref,
|
||||
'live' => $live,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'payer' => $this->payer($order),
|
||||
'order_snapshot' => $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erstattung: eine Gegenbuchung in Höhe des Zahlbetrags. Das Echt-Kennzeichen folgt dem Zahlungseingang der
|
||||
* Bestellung. `$reference` ist bei Stripe die Rückzahlungs-ID (re_...), sonst eine Referenz der Rückzahlung.
|
||||
*/
|
||||
public function recordRefund(Order $order, ?Payment $payment, CarbonInterface $occurredAt, ?User $actor, string $reason, string $reference, ?string $providerStatus = null): LedgerEntry
|
||||
{
|
||||
$original = LedgerEntry::query()->where('order_id', $order->id)->where('kind', LedgerEntry::KIND_PAYMENT)->orderBy('id')->first();
|
||||
|
||||
return LedgerEntry::query()->firstOrCreate(
|
||||
['kind' => LedgerEntry::KIND_REFUND, 'provider' => $payment?->provider ?? $original?->provider ?? 'unbekannt', 'provider_reference' => $reference],
|
||||
[
|
||||
'order_id' => $order->id,
|
||||
'payment_id' => $payment?->id,
|
||||
'occurred_at' => $this->utc($occurredAt),
|
||||
'amount_cents' => -$order->payable(),
|
||||
'currency' => (string) ($order->currency ?? 'EUR'),
|
||||
'provider_payment_ref' => $payment?->provider_payment_ref,
|
||||
'provider_status' => $providerStatus,
|
||||
'live' => $original?->live ?? false,
|
||||
'actor_id' => $actor?->id,
|
||||
'actor_name' => $actor?->name,
|
||||
'reason' => $reason,
|
||||
'payer' => $original?->payer ?? $this->payer($order),
|
||||
'order_snapshot' => $original?->order_snapshot ?? $this->orderSnapshot($order),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Datum ohne Uhrzeit (Zahlungseingang auf dem Konto): Beginn dieses Tages in deutscher Zeit. Nicht in der
|
||||
* Zukunft; `$notBefore` ist der früheste zulässige Tag (Bestelldatum).
|
||||
*/
|
||||
public static function dayOf(string|CarbonInterface $date, ?CarbonInterface $notBefore = null): CarbonImmutable
|
||||
{
|
||||
$day = CarbonImmutable::parse($date instanceof CarbonInterface ? $date->format('Y-m-d') : $date, self::TIMEZONE)->startOfDay();
|
||||
|
||||
if ($day->greaterThan(CarbonImmutable::now(self::TIMEZONE)->endOfDay())) {
|
||||
throw new DomainRuleException('Das Datum darf nicht in der Zukunft liegen.');
|
||||
}
|
||||
|
||||
if ($notBefore !== null && $day->lessThan(CarbonImmutable::instance($notBefore)->setTimezone(self::TIMEZONE)->startOfDay())) {
|
||||
throw new DomainRuleException('Das Datum liegt vor dem Bestelldatum.');
|
||||
}
|
||||
|
||||
return $day;
|
||||
}
|
||||
|
||||
/**
|
||||
* Von und bis (einschließlich) eines Zeitraums in UTC.
|
||||
*
|
||||
* @param 'monat'|'quartal'|'jahr' $mode
|
||||
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
|
||||
*/
|
||||
public static function range(string $mode, int $year, int $index): array
|
||||
{
|
||||
$from = CarbonImmutable::create($year, 1, 1, 0, 0, 0, self::TIMEZONE);
|
||||
|
||||
$from = match ($mode) {
|
||||
'monat' => $from->setMonth(max(1, min(12, $index)))->startOfMonth(),
|
||||
'quartal' => $from->setMonth((max(1, min(4, $index)) - 1) * 3 + 1)->startOfMonth(),
|
||||
default => $from->startOfYear(),
|
||||
};
|
||||
$to = match ($mode) {
|
||||
'monat' => $from->endOfMonth(),
|
||||
'quartal' => $from->addMonths(2)->endOfMonth(),
|
||||
default => $from->endOfYear(),
|
||||
};
|
||||
|
||||
return [$from->setTimezone('UTC'), $to->setTimezone('UTC')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param 'alle'|'eingang'|'erstattung' $kind
|
||||
* @param 'alle'|'stripe'|'ueberweisung'|'test' $provider
|
||||
* @param 'echt'|'test'|'alle' $operation
|
||||
* @return Collection<int, LedgerEntry>
|
||||
*/
|
||||
public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection
|
||||
{
|
||||
return LedgerEntry::query()
|
||||
->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])
|
||||
->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)))
|
||||
->when($kind !== 'alle', fn ($query) => $query->where('kind', $kind))
|
||||
->when($provider !== 'alle', fn ($query) => $query->where('provider', $provider))
|
||||
->when($operation === 'echt', fn ($query) => $query->where('live', true))
|
||||
->when($operation === 'test', fn ($query) => $query->where('live', false))
|
||||
->orderBy('occurred_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt,
|
||||
* wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen
|
||||
* Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen
|
||||
* Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @return array<int, int> Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung)
|
||||
*/
|
||||
public function shares(Collection $entries, int $offerId): array
|
||||
{
|
||||
$perOrder = OrderLine::query()
|
||||
->whereIn('order_id', $entries->pluck('order_id')->unique()->all())
|
||||
->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))
|
||||
->get()
|
||||
->groupBy('order_id')
|
||||
->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable()));
|
||||
$shares = [];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$share = (int) ($perOrder[$entry->order_id] ?? 0);
|
||||
$shares[$entry->id] = $entry->isRefund() ? -$share : $share;
|
||||
}
|
||||
|
||||
return $shares;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt.
|
||||
*/
|
||||
public function countByOperation(CarbonInterface $from, CarbonInterface $to): array
|
||||
{
|
||||
$rows = LedgerEntry::query()->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])->get(['live']);
|
||||
|
||||
return ['echt' => $rows->where('live', true)->count(), 'test' => $rows->where('live', false)->count()];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen
|
||||
* @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int}
|
||||
*/
|
||||
public static function totals(Collection $entries, ?array $shares = null): array
|
||||
{
|
||||
$in = $entries->where('kind', LedgerEntry::KIND_PAYMENT);
|
||||
$out = $entries->where('kind', LedgerEntry::KIND_REFUND);
|
||||
$amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0);
|
||||
|
||||
return [
|
||||
'eingang' => (int) $in->sum($amount),
|
||||
'erstattung' => (int) abs($out->sum($amount)),
|
||||
'saldo' => (int) $entries->sum($amount),
|
||||
'anzahl_eingang' => $in->count(),
|
||||
'anzahl_erstattung' => $out->count(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function providerLabel(string $provider): string
|
||||
{
|
||||
return match ($provider) {
|
||||
'stripe' => 'Stripe',
|
||||
'ueberweisung' => 'Überweisung',
|
||||
'test' => 'Testzahlung',
|
||||
default => $provider,
|
||||
};
|
||||
}
|
||||
|
||||
public static function local(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone(self::TIMEZONE);
|
||||
}
|
||||
|
||||
/** Hat die Bewegung eine belegte Uhrzeit? Datumsbuchungen (Überweisung) beginnen um 00:00 deutscher Zeit. */
|
||||
public static function hasTime(LedgerEntry $entry): bool
|
||||
{
|
||||
return self::local($entry->occurred_at)->format('H:i:s') !== '00:00:00';
|
||||
}
|
||||
|
||||
/**
|
||||
* Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg.
|
||||
*
|
||||
* @param Collection<int, LedgerEntry> $entries
|
||||
* @param array<int, int>|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“
|
||||
*/
|
||||
public static function csv(Collection $entries, ?array $shares = null): string
|
||||
{
|
||||
$header = [
|
||||
'Buchungsnummer', 'Datum', 'Uhrzeit', 'Art', 'Betrag EUR', 'Währung', 'Bestellung', 'Zahlungsweg', 'Betrieb', 'Herkunft',
|
||||
'Referenz', 'Zahlungsvorgang', 'Status beim Anbieter', 'Lizenzinhaber', 'Rechnungsempfänger', 'Zusatz', 'Straße', 'PLZ', 'Ort', 'Land',
|
||||
'Besteller', 'Zwischensumme EUR', 'Rabatt EUR', 'Rabattcode', 'Positionen', 'Begründung', 'Gebucht von', 'Gebucht am',
|
||||
...($shares === null ? [] : ['Anteil des Angebots EUR']),
|
||||
];
|
||||
$rows = [$header];
|
||||
|
||||
foreach ($entries as $entry) {
|
||||
$local = self::local($entry->occurred_at);
|
||||
$payer = (array) $entry->payer;
|
||||
$billing = (array) ($payer['billing'] ?? []);
|
||||
$snapshot = (array) $entry->order_snapshot;
|
||||
$lines = collect($snapshot['lines'] ?? [])->map(fn (array $line): string => ($line['name'] ?? '').' '.self::decimal((int) ($line['price_cents'] ?? 0) - (int) ($line['discount_cents'] ?? 0)))->implode(' | ');
|
||||
|
||||
$rows[] = [
|
||||
$entry->id,
|
||||
$local->format('d.m.Y'),
|
||||
self::hasTime($entry) ? $local->format('H:i:s') : '',
|
||||
$entry->isRefund() ? 'Erstattung' : 'Zahlungseingang',
|
||||
self::decimal($entry->amount_cents),
|
||||
$entry->currency,
|
||||
$entry->order_id,
|
||||
self::providerLabel($entry->provider),
|
||||
$entry->live ? 'echt' : 'Test',
|
||||
$entry->derived ? 'nachgetragen (Datum abgeleitet)' : 'belegt',
|
||||
$entry->provider_reference,
|
||||
$entry->provider_payment_ref,
|
||||
$entry->provider_status,
|
||||
$payer['holder'] ?? null,
|
||||
$billing['recipient'] ?? null,
|
||||
$billing['line2'] ?? null,
|
||||
$billing['street'] ?? null,
|
||||
$billing['postal_code'] ?? null,
|
||||
$billing['city'] ?? null,
|
||||
$billing['country'] ?? null,
|
||||
$payer['buyer'] ?? null,
|
||||
self::decimal((int) ($snapshot['subtotal_cents'] ?? 0)),
|
||||
self::decimal((int) ($snapshot['discount_cents'] ?? 0)),
|
||||
$snapshot['discount_code'] ?? null,
|
||||
$lines,
|
||||
$entry->reason,
|
||||
$entry->actor_name,
|
||||
self::local($entry->created_at)->format('d.m.Y H:i:s'),
|
||||
...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]),
|
||||
];
|
||||
}
|
||||
|
||||
$handle = fopen('php://temp', 'r+');
|
||||
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($handle, array_map(self::cell(...), $row), ';', '"', '\\', "\r\n");
|
||||
}
|
||||
|
||||
rewind($handle);
|
||||
$csv = (string) stream_get_contents($handle);
|
||||
fclose($handle);
|
||||
|
||||
return "\xEF\xBB\xBF".$csv;
|
||||
}
|
||||
|
||||
public static function decimal(int $cents): string
|
||||
{
|
||||
return number_format($cents / 100, 2, ',', '');
|
||||
}
|
||||
|
||||
/** Verhindert, dass ein Zellinhalt in der Tabellenkalkulation als Formel ausgeführt wird. */
|
||||
private static function cell(mixed $value): string
|
||||
{
|
||||
$text = (string) $value;
|
||||
|
||||
if ($text !== '' && preg_match('/^[=+\-@\t\r]/', $text) === 1 && preg_match('/^-?\d+(,\d+)?$/', $text) !== 1) {
|
||||
return "'".$text;
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
private function utc(CarbonInterface $moment): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::instance($moment)->setTimezone('UTC');
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahler zum Zeitpunkt der Bewegung. Spätere Änderungen an Profil oder Rechnungsadresse ändern sie nicht.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function payer(Order $order): array
|
||||
{
|
||||
$order->loadMissing('user', 'party.billingAddress');
|
||||
$address = $order->party?->billingAddress;
|
||||
|
||||
return [
|
||||
'holder' => $order->party?->display_name,
|
||||
'holder_kind' => $order->holder_kind,
|
||||
'buyer' => $order->user?->name,
|
||||
'buyer_email' => $order->user?->email,
|
||||
'billing' => $address === null ? null : [
|
||||
'recipient' => $address->recipient,
|
||||
'line2' => $address->line2,
|
||||
'street' => $address->street,
|
||||
'postal_code' => $address->postal_code,
|
||||
'city' => $address->city,
|
||||
'country' => $address->country,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function orderSnapshot(Order $order): array
|
||||
{
|
||||
$order->loadMissing('lines');
|
||||
|
||||
return [
|
||||
'subtotal_cents' => $order->subtotal(),
|
||||
'discount_cents' => (int) $order->discount_cents,
|
||||
'discount_code' => $order->discount_snapshot['code'] ?? null,
|
||||
'lines' => $order->lines->map(fn (OrderLine $line): array => [
|
||||
'name' => $line->offer_name,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
])->values()->all(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
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\Filament\Support\CatalogLabels;
|
||||
|
||||
/**
|
||||
* Kaufbare Lizenzoptionen einer Produktseite aus dem veröffentlichten Katalog: aktive Angebotsfassungen mit Preis,
|
||||
* Eignung, Laufzeit, Umfang und Nutzungsrechten. Die Seite selbst (Titel, Beschreibung, Struktur) kommt aus der
|
||||
* zur Anzeige freigegebenen Komposition; hier entsteht kein zweiter Text.
|
||||
*/
|
||||
class ProductOptions
|
||||
{
|
||||
public function __construct(private readonly OfferService $offers) {}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forComposition(Composition $composition): 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
|
||||
* dieses Paket verkauft.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null.
|
||||
*/
|
||||
public function bundleOf(OfferVersion $version): ?Bundle
|
||||
{
|
||||
$version->loadMissing('lines.bundleVersion.bundle');
|
||||
|
||||
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
|
||||
}
|
||||
|
||||
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
|
||||
public function groupKey(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return 'c:'.$offer->composition_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;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function bundleSummaries(): 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) {
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
|
||||
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
|
||||
*
|
||||
* @param list<array<string, mixed>> $options
|
||||
* @return list<array{title: string, teaser: string}>
|
||||
*/
|
||||
public function bundleContents(array $options): array
|
||||
{
|
||||
$contents = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$option['version']->loadMissing('resolvedScopes.article');
|
||||
|
||||
foreach ($option['version']->resolvedScopes as $item) {
|
||||
$article = $item->article;
|
||||
|
||||
if ($article === null || isset($contents[$article->id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$contents[$article->id] = [
|
||||
'title' => $this->articleTitle($article),
|
||||
'teaser' => trim((string) ($profile->value('teaser') ?? '')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
*/
|
||||
public function describe(Offer $offer, OfferVersion $version): array
|
||||
{
|
||||
$version->loadMissing('resolvedScopes.article', 'resolvedScopes.rights');
|
||||
$scope = [];
|
||||
|
||||
foreach ($version->resolvedScopes as $item) {
|
||||
$faehigkeiten = CatalogLabels::faehigkeiten($item->rights?->capabilities);
|
||||
$scope[] = [
|
||||
'article' => $this->articleTitle($item->article),
|
||||
'purpose' => CatalogLabels::zweck($item->rights?->purpose),
|
||||
'rights' => $faehigkeiten,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'offer' => $offer,
|
||||
'version' => $version,
|
||||
'name' => $offer->optionName(),
|
||||
'price_cents' => (int) $version->price_cents,
|
||||
'price' => Money::format((int) $version->price_cents),
|
||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'term' => self::termLabel($version),
|
||||
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count),
|
||||
'scope' => $scope,
|
||||
];
|
||||
}
|
||||
|
||||
public static function termLabel(OfferVersion $version): string
|
||||
{
|
||||
return self::termRuleLabel($version->term_rule);
|
||||
}
|
||||
|
||||
/** Laufzeitregel aus der Angebotsfassung oder aus den Bedingungen eines Erwerbs (gleiche Schlüssel). */
|
||||
public static function termRuleLabel(?string $rule): string
|
||||
{
|
||||
return match ((string) $rule) {
|
||||
'dauerhaft' => 'Dauerhaft nutzbar',
|
||||
'befristet' => 'Befristet',
|
||||
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
||||
'periodisch' => 'Laufend, periodisch',
|
||||
default => (string) $rule,
|
||||
};
|
||||
}
|
||||
|
||||
public function articleTitle(?LicenseArticle $article): string
|
||||
{
|
||||
if ($article === null) {
|
||||
return '–';
|
||||
}
|
||||
|
||||
return $this->articleName($article) ?: (string) $article->code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Name wie in der Redaktion: eigener Name, sonst der Name des Inhalts (Anzeigename, Arbeitstitel oder
|
||||
* Bezeichnung), sonst der eigene Arbeitstitel; leer, wenn nichts davon vorhanden ist.
|
||||
*/
|
||||
public function articleName(LicenseArticle $article): string
|
||||
{
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$source = $profile->source;
|
||||
$candidates = [
|
||||
$profile->value('display_title'),
|
||||
$article->working_title,
|
||||
$source?->getAttribute('working_title'),
|
||||
$source?->getAttribute('designation'),
|
||||
];
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if (filled($candidate)) {
|
||||
return trim((string) $candidate);
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Receipt;
|
||||
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\PaymentJournal;
|
||||
use App\Domain\Identity\BillingAddress;
|
||||
|
||||
/**
|
||||
* Zahlungs- oder Erstattungsbeleg zu einer Buchung des Zahlungsjournals als PDF. Gebaut wird ausschließlich aus den
|
||||
* bei der Buchung festgehaltenen Angaben (Zahler, Positionen, Beträge, Zeitpunkt, Beleg beim Anbieter), nie aus dem
|
||||
* heutigen Profil oder der heutigen Bestellung: Spätere Änderungen der Adresse ändern den Beleg nicht, und jeder Abruf
|
||||
* liefert dieselben Bytes. Der Beleg bestätigt die Zahlung. Er enthält weder Rechnungsnummer noch Steuerangaben; ob eine
|
||||
* Rechnung zu stellen ist, ist rechtlich noch nicht geklärt (OPEN-06). Aussteller und Zusatzhinweis kommen aus
|
||||
* `config('shop.receipt')` und werden nur gedruckt, wenn sie gepflegt sind. Zu nachgetragenen Buchungen (abgeleitetes
|
||||
* Datum) gibt es keinen Beleg.
|
||||
*/
|
||||
final class PaymentReceipt
|
||||
{
|
||||
private const LEFT = 50;
|
||||
|
||||
private const RIGHT = 545;
|
||||
|
||||
public static function available(LedgerEntry $entry): bool
|
||||
{
|
||||
return ! $entry->derived;
|
||||
}
|
||||
|
||||
public static function filename(LedgerEntry $entry): string
|
||||
{
|
||||
return ($entry->isRefund() ? 'Erstattungsbeleg' : 'Zahlungsbeleg').'-Bestellung-'.$entry->order_id.'-Buchung-'.$entry->id.'.pdf';
|
||||
}
|
||||
|
||||
public static function render(LedgerEntry $entry): string
|
||||
{
|
||||
$refund = $entry->isRefund();
|
||||
$payer = (array) $entry->payer;
|
||||
$billing = (array) ($payer['billing'] ?? []);
|
||||
$snapshot = (array) $entry->order_snapshot;
|
||||
$money = fn (int $cents): string => Money::format($cents);
|
||||
$when = PaymentJournal::local($entry->occurred_at);
|
||||
$title = $refund ? 'Erstattungsbeleg' : 'Zahlungsbeleg';
|
||||
$pdf = new PdfDocument;
|
||||
$pdf->addPage();
|
||||
$y = 790.0;
|
||||
|
||||
$pdf->text(self::LEFT, $y, $title, 22, true);
|
||||
$issuer = array_values(array_filter(array_map('trim', explode('|', (string) config('shop.receipt.issuer')))));
|
||||
$yIssuer = $y + 4;
|
||||
|
||||
foreach ($issuer as $i => $line) {
|
||||
$pdf->textRight(self::RIGHT, $yIssuer - $i * 12, $line, 9, $i === 0);
|
||||
}
|
||||
|
||||
$y = min($y - 26, $yIssuer - 12 * count($issuer) - 8);
|
||||
|
||||
if (! $entry->live) {
|
||||
$pdf->text(self::LEFT, $y, 'TESTZAHLUNG - kein Umsatz, kein Beleg für eine echte Zahlung', 10, true);
|
||||
$y -= 16;
|
||||
}
|
||||
|
||||
$y -= 6;
|
||||
$meta = [
|
||||
['Bestellung', (string) $entry->order_id],
|
||||
['Buchung', (string) $entry->id],
|
||||
[$refund ? 'Rückzahlung am' : 'Zahlung am', $when->format('d.m.Y').(PaymentJournal::hasTime($entry) ? ', '.$when->format('H:i').' Uhr' : '')],
|
||||
['Zahlungsweg', PaymentJournal::providerLabel($entry->provider)],
|
||||
['Referenz', (string) $entry->provider_reference],
|
||||
];
|
||||
|
||||
foreach ($meta as [$label, $value]) {
|
||||
$pdf->text(self::LEFT, $y, $label, 9);
|
||||
|
||||
foreach (PdfDocument::wrap($value, 330, 10) as $i => $part) {
|
||||
$pdf->text(160, $y - $i * 12, $part, 10);
|
||||
}
|
||||
|
||||
$y -= 14 * max(1, count(PdfDocument::wrap($value, 330, 10)));
|
||||
}
|
||||
|
||||
$y -= 10;
|
||||
$pdf->text(self::LEFT, $y, $refund ? 'Erstattung an' : 'Zahler', 9);
|
||||
$recipient = $billing !== [] ? array_values(array_filter([
|
||||
$billing['recipient'] ?? null,
|
||||
$billing['line2'] ?? null,
|
||||
$billing['street'] ?? null,
|
||||
trim(($billing['postal_code'] ?? '').' '.($billing['city'] ?? '')),
|
||||
($billing['country'] ?? 'DE') !== 'DE' ? (BillingAddress::COUNTRIES[$billing['country']] ?? $billing['country']) : null,
|
||||
])) : array_values(array_filter([$payer['holder'] ?? null, 'Keine Rechnungsadresse hinterlegt']));
|
||||
|
||||
foreach ($recipient as $i => $line) {
|
||||
$pdf->text(160, $y - $i * 13, (string) $line, 10, $i === 0);
|
||||
}
|
||||
|
||||
$y -= 13 * count($recipient);
|
||||
|
||||
if (filled($payer['buyer'] ?? null) && ($payer['buyer'] ?? '') !== ($billing['recipient'] ?? $payer['holder'] ?? '')) {
|
||||
$pdf->text(160, $y, 'Bestellt von '.$payer['buyer'], 9);
|
||||
$y -= 13;
|
||||
}
|
||||
|
||||
$y -= 16;
|
||||
$pdf->line(self::LEFT, $y + 12, self::RIGHT, $y + 12, 0.8);
|
||||
$pdf->text(self::LEFT, $y, 'Position', 9, true);
|
||||
$pdf->textRight(400, $y, 'Preis', 9, true);
|
||||
$pdf->textRight(472, $y, 'Rabatt', 9, true);
|
||||
$pdf->textRight(self::RIGHT, $y, 'Betrag', 9, true);
|
||||
$y -= 6;
|
||||
$pdf->line(self::LEFT, $y, self::RIGHT, $y, 0.4);
|
||||
$y -= 14;
|
||||
|
||||
foreach ((array) ($snapshot['lines'] ?? []) as $line) {
|
||||
$lines = PdfDocument::wrap((string) ($line['name'] ?? 'Angebot'), 270, 10);
|
||||
|
||||
if ($y - 13 * count($lines) < 140) {
|
||||
$pdf->addPage();
|
||||
$y = 790.0;
|
||||
}
|
||||
|
||||
$price = (int) ($line['price_cents'] ?? 0);
|
||||
$discount = (int) ($line['discount_cents'] ?? 0);
|
||||
|
||||
foreach ($lines as $i => $part) {
|
||||
$pdf->text(self::LEFT, $y - $i * 13, $part, 10);
|
||||
}
|
||||
|
||||
$pdf->textRight(400, $y, $money($price), 10);
|
||||
$pdf->textRight(472, $y, $discount > 0 ? '-'.$money($discount) : '', 10);
|
||||
$pdf->textRight(self::RIGHT, $y, $money($price - $discount), 10);
|
||||
$y -= 13 * count($lines) + 4;
|
||||
}
|
||||
|
||||
$y -= 6;
|
||||
$pdf->line(self::LEFT, $y + 10, self::RIGHT, $y + 10, 0.4);
|
||||
$y -= 6;
|
||||
|
||||
if ((int) ($snapshot['discount_cents'] ?? 0) > 0) {
|
||||
$pdf->text(300, $y, 'Zwischensumme', 10);
|
||||
$pdf->textRight(self::RIGHT, $y, $money((int) ($snapshot['subtotal_cents'] ?? 0)), 10);
|
||||
$y -= 14;
|
||||
$pdf->text(300, $y, 'Rabatt'.(filled($snapshot['discount_code'] ?? null) ? ' (Code '.$snapshot['discount_code'].')' : ''), 10);
|
||||
$pdf->textRight(self::RIGHT, $y, '-'.$money((int) $snapshot['discount_cents']), 10);
|
||||
$y -= 14;
|
||||
}
|
||||
|
||||
$pdf->text(300, $y, $refund ? 'Erstatteter Betrag' : 'Gezahlter Betrag', 11, true);
|
||||
$pdf->textRight(self::RIGHT, $y, $money(abs($entry->amount_cents)), 11, true);
|
||||
$y -= 26;
|
||||
|
||||
$notes = [
|
||||
$refund
|
||||
? 'Dieser Beleg bestätigt die Rückzahlung zur genannten Bestellung. Die Berechtigungen aus dieser Bestellung sind widerrufen.'
|
||||
: 'Dieser Beleg bestätigt die Zahlung zur genannten Bestellung.',
|
||||
'Er enthält keine Rechnungsnummer und keine steuerlichen Angaben und wurde aus den bei der Zahlung festgehaltenen Angaben erstellt.',
|
||||
];
|
||||
|
||||
if (filled(config('shop.receipt.note'))) {
|
||||
$notes[] = (string) config('shop.receipt.note');
|
||||
}
|
||||
|
||||
foreach ($notes as $note) {
|
||||
foreach (PdfDocument::wrap($note, self::RIGHT - self::LEFT, 9) as $part) {
|
||||
$pdf->text(self::LEFT, $y, $part, 9);
|
||||
$y -= 12;
|
||||
}
|
||||
|
||||
$y -= 3;
|
||||
}
|
||||
|
||||
return $pdf->output($title.' Bestellung '.$entry->order_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Receipt;
|
||||
|
||||
/**
|
||||
* Minimaler PDF-Schreiber für einseitige bis wenige Seiten Text (DIN A4, Standardschriften Helvetica, Kodierung
|
||||
* 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
|
||||
{
|
||||
public const WIDTH = 595;
|
||||
|
||||
public const HEIGHT = 842;
|
||||
|
||||
/** @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[] = '';
|
||||
}
|
||||
|
||||
/** Anzahl der bisher angelegten Seiten. */
|
||||
public function pageCount(): int
|
||||
{
|
||||
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
|
||||
{
|
||||
$this->text($xRight - self::width($text, $size, $bold), $y, $text, $size, $bold);
|
||||
}
|
||||
|
||||
public function line(float $x1, float $y1, float $x2, float $y2, float $width = 0.5): void
|
||||
{
|
||||
$this->append(sprintf("%s w %s %s m %s %s l S\n", $this->n($width), $this->n($x1), $this->n($y1), $this->n($x2), $this->n($y2)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilenumbruch nach Wörtern. Die Breite ist eine bewusst großzügige Schätzung der Helvetica-Breiten, damit nichts
|
||||
* über den Rand läuft; ein einzelnes zu langes Wort wird hart getrennt.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function wrap(string $text, float $maxWidth, float $size = 10, bool $bold = false): array
|
||||
{
|
||||
$lines = [];
|
||||
|
||||
foreach (preg_split('/\R/u', trim($text)) ?: [''] as $paragraph) {
|
||||
$current = '';
|
||||
|
||||
foreach (preg_split('/\s+/u', trim($paragraph)) ?: [] as $word) {
|
||||
while (mb_strlen($word) > 1 && self::width($word, $size, $bold) > $maxWidth) {
|
||||
$cut = mb_strlen($word) - 1;
|
||||
|
||||
while ($cut > 1 && self::width(mb_substr($word, 0, $cut), $size, $bold) > $maxWidth) {
|
||||
$cut--;
|
||||
}
|
||||
|
||||
if ($current !== '') {
|
||||
$lines[] = $current;
|
||||
$current = '';
|
||||
}
|
||||
|
||||
$lines[] = mb_substr($word, 0, $cut);
|
||||
$word = mb_substr($word, $cut);
|
||||
}
|
||||
|
||||
$candidate = $current === '' ? $word : $current.' '.$word;
|
||||
|
||||
if ($current !== '' && self::width($candidate, $size, $bold) > $maxWidth) {
|
||||
$lines[] = $current;
|
||||
$current = $word;
|
||||
} else {
|
||||
$current = $candidate;
|
||||
}
|
||||
}
|
||||
|
||||
$lines[] = $current;
|
||||
}
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Geschätzte Textbreite in Punkt (Helvetica; Ziffern und Währung exakt, Buchstaben großzügig). */
|
||||
public static function width(string $text, float $size = 10, bool $bold = false): float
|
||||
{
|
||||
$units = 0.0;
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$width = match (true) {
|
||||
$char === ' ', $char === ',', $char === '.', $char === ':', $char === ';', $char === "'", $char === '|', $char === 'i', $char === 'l', $char === 'I', $char === 'j', $char === 't', $char === 'f' => 0.3,
|
||||
$char === '-', $char === '(', $char === ')', $char === '/', $char === 'r' => 0.35,
|
||||
ctype_digit($char), $char === '€' => 0.556,
|
||||
mb_strtoupper($char) === $char && $char !== mb_strtolower($char) => 0.75,
|
||||
$char === 'm', $char === 'w', $char === 'M', $char === 'W' => 0.85,
|
||||
default => 0.57,
|
||||
};
|
||||
// Fette Ziffern, Währung und Satzzeichen sind in Helvetica so breit wie normale; nur Buchstaben werden breiter.
|
||||
$units += $bold && ctype_alpha($char) ? $width * 1.08 : $width;
|
||||
}
|
||||
|
||||
return $units * $size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $title Nur ASCII (Dokumenttitel)
|
||||
*/
|
||||
public function output(string $title, ?string $keywords = null): string
|
||||
{
|
||||
$pages = $this->pages === [] ? [''] : $this->pages;
|
||||
$objects = [];
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
|
||||
$kids = [];
|
||||
$next = 6;
|
||||
|
||||
// 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';
|
||||
$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 >>';
|
||||
$ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value));
|
||||
$objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>';
|
||||
ksort($objects);
|
||||
|
||||
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
|
||||
$offsets = [];
|
||||
|
||||
foreach ($objects as $number => $body) {
|
||||
$offsets[$number] = strlen($pdf);
|
||||
$pdf .= $number." 0 obj\n".$body."\nendobj\n";
|
||||
}
|
||||
|
||||
$xref = strlen($pdf);
|
||||
$pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n";
|
||||
|
||||
foreach ($offsets as $offset) {
|
||||
$pdf .= sprintf("%010d 00000 n \n", $offset);
|
||||
}
|
||||
|
||||
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 === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->pages[array_key_last($this->pages)] .= $operators;
|
||||
}
|
||||
|
||||
private function n(float $value): string
|
||||
{
|
||||
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.') ?: '0';
|
||||
}
|
||||
|
||||
/** Windows-1252, geklammert für PDF-Zeichenketten. */
|
||||
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\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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Page;
|
||||
|
||||
/**
|
||||
* Pflichtangaben und Zustimmungen im Bestellablauf (Verkaufsstart Deutschland, PAY-005, PAY-009).
|
||||
*
|
||||
* Die finalen Rechtstexte (AGB, Lizenzbedingungen, Widerrufsbelehrung, Impressum, Datenschutz) liegen als Seiten im
|
||||
* CMS und werden hier nur verlinkt. Der Wortlaut der Zustimmungen unten ist ein ENTWURF zur Prüfung durch die
|
||||
* Rechtsberatung. Er ist nicht rechtlich freigegeben; `VERSION` hält fest, welcher Wortlaut galt, damit die Zustimmung
|
||||
* je Bestellung nachvollziehbar bleibt.
|
||||
*/
|
||||
final class SalesTerms
|
||||
{
|
||||
public const VERSION = '2026-11-24-entwurf';
|
||||
|
||||
/** Schaltfläche zum verbindlichen Abschluss (Button-Lösung, § 312j Abs. 3 BGB). */
|
||||
public const ORDER_BUTTON = 'Zahlungspflichtig bestellen';
|
||||
|
||||
public const ORDER_BUTTON_INVOICE = 'Zahlungspflichtig auf Rechnung bestellen';
|
||||
|
||||
/**
|
||||
* Seiten der Rechtstexte: Schlüssel => Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt).
|
||||
*
|
||||
* @return array<string, array{label: string, paths: list<string>, required: bool}>
|
||||
*/
|
||||
public static function pages(): array
|
||||
{
|
||||
return [
|
||||
'agb' => ['label' => 'Allgemeine Geschäftsbedingungen', 'paths' => ['/agb'], 'required' => true],
|
||||
'lizenz' => ['label' => 'Lizenzbedingungen', 'paths' => ['/lizenzbedingungen', '/lizenz'], 'required' => true],
|
||||
'widerruf' => ['label' => 'Widerrufsbelehrung', 'paths' => ['/widerruf', '/widerrufsbelehrung'], 'required' => true],
|
||||
'impressum' => ['label' => 'Impressum', 'paths' => ['/impressum'], 'required' => true],
|
||||
'datenschutz' => ['label' => 'Datenschutzerklärung', 'paths' => ['/datenschutz'], 'required' => true],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Seite des Rechtstextes oder null.
|
||||
*/
|
||||
public static function page(string $key): ?Page
|
||||
{
|
||||
$definition = self::pages()[$key] ?? null;
|
||||
|
||||
if ($definition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Page::query()
|
||||
->whereIn('path', $definition['paths'])
|
||||
->whereNotNull('published_revision_id')
|
||||
->orderBy('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function url(string $key): ?string
|
||||
{
|
||||
return self::page($key)?->publicUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fehlende oder unveröffentlichte Rechtstexte (Schlüssel => Bezeichnung).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function missingPages(): array
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach (self::pages() as $key => $definition) {
|
||||
if ($definition['required'] && self::page($key) === null) {
|
||||
$missing[$key] = $definition['label'];
|
||||
}
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustimmungen im Checkout: Schlüssel => Wortlaut (ENTWURF).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function consents(): array
|
||||
{
|
||||
return [
|
||||
'agb' => 'Ich habe die Allgemeinen Geschäftsbedingungen und die Lizenzbedingungen gelesen und stimme ihnen zu.',
|
||||
'sofort' => 'Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird und die digitalen Inhalte sofort nach Zahlungseingang bereitgestellt werden. Mir ist bekannt, dass ich mein Widerrufsrecht verliere, sobald die Ausführung begonnen hat.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Zustimmungen und liefert den Nachweis für die Bestellung (Wortlaut, Fassung, Seiten, Zeit).
|
||||
*
|
||||
* @param array<string, mixed> $accepted Schlüssel => angekreuzt
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function proof(array $accepted): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach (self::consents() as $key => $wording) {
|
||||
if (empty($accepted[$key])) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$texts[$key] = $wording;
|
||||
}
|
||||
|
||||
$pages = [];
|
||||
|
||||
foreach (array_keys(self::pages()) as $key) {
|
||||
$page = self::page($key);
|
||||
$pages[$key] = $page === null ? null : ['path' => $page->path, 'revision_id' => $page->published_revision_id];
|
||||
}
|
||||
|
||||
return [
|
||||
'version' => self::VERSION,
|
||||
'consents' => $texts,
|
||||
'pages' => $pages,
|
||||
'recorded_at' => now()->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
/**
|
||||
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||
*
|
||||
* 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
|
||||
* Zahlungstreiber „stripe“ mit Live-Schlüssel und veröffentlichten Rechtstexten. Fehlt eines davon, bleibt der Shop in
|
||||
* Produktion abgeschaltet. Die Freigabe ist standardmäßig aus.
|
||||
*/
|
||||
final class Shop
|
||||
{
|
||||
public static function driver(): string
|
||||
{
|
||||
return (string) config('services.payment.driver');
|
||||
}
|
||||
|
||||
/** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */
|
||||
public static function live(): bool
|
||||
{
|
||||
return app()->isProduction()
|
||||
&& config('shop.live_release') === true
|
||||
&& self::driver() === 'stripe'
|
||||
&& self::liveKey()
|
||||
&& SalesTerms::missingPages() === [];
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return in_array(self::driver(), ['test', 'stripe'], true);
|
||||
}
|
||||
|
||||
/** Stripe-Kasse: im Test nur mit Testschlüsseln, in Produktion nur nach der Produktivfreigabe. */
|
||||
public static function stripe(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return self::driver() === 'stripe';
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
|
||||
private static function liveKey(): bool
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
return str_starts_with($secret, 'sk_live_') || str_starts_with($secret, 'rk_live_');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Preis oder bindende Bedingungen haben sich nach Anzeige der Bestellübersicht geändert. Es entsteht keine
|
||||
* Bestellung; der Käufer sieht zuerst die aktualisierte Übersicht (FACH-59).
|
||||
*/
|
||||
class StaleOverview extends DomainRuleException {}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
||||
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
||||
* Fall wird abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten berühren diese Anwendung
|
||||
* nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). Der Betrag je Position ist der
|
||||
* Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht.
|
||||
*/
|
||||
class StripeGateway
|
||||
{
|
||||
/**
|
||||
* Legt für die Bestellung eine Checkout Session an oder liefert die noch offene wieder.
|
||||
*
|
||||
* @return array{id: string, url: string}
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$order->loadMissing('lines', 'user');
|
||||
$taxRate = $this->taxRate();
|
||||
|
||||
if ($order->status !== 'offen') {
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
if ($order->payment_method === 'rechnung') {
|
||||
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
|
||||
}
|
||||
|
||||
$open = $this->reusableSession($order);
|
||||
|
||||
if ($open !== null) {
|
||||
return $open;
|
||||
}
|
||||
|
||||
$attempt = $order->payments()->where('provider', 'stripe')->count() + 1;
|
||||
$params = [
|
||||
'mode' => 'payment',
|
||||
'client_reference_id' => (string) $order->id,
|
||||
'customer_email' => $order->user->email,
|
||||
'locale' => 'de',
|
||||
'success_url' => route('member.order', $order).'?zahlung=zurueck',
|
||||
'cancel_url' => route('member.order', $order).'?zahlung=abbruch',
|
||||
'metadata' => ['order_id' => (string) $order->id],
|
||||
'payment_intent_data' => ['metadata' => ['order_id' => (string) $order->id]],
|
||||
];
|
||||
|
||||
foreach ($order->lines->values() as $index => $line) {
|
||||
$productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'];
|
||||
|
||||
if ((int) $line->discount_cents > 0) {
|
||||
$productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents);
|
||||
}
|
||||
|
||||
$params['line_items'][$index] = [
|
||||
'quantity' => 1,
|
||||
'price_data' => [
|
||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||
'unit_amount' => $line->payable(),
|
||||
'product_data' => $productData,
|
||||
],
|
||||
];
|
||||
|
||||
if ($taxRate !== null) {
|
||||
$params['line_items'][$index]['tax_rates'] = [$taxRate];
|
||||
}
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => $this->idempotencyKey($order, $attempt, $params)])
|
||||
->post('/v1/checkout/sessions', $params);
|
||||
|
||||
$this->assertOk($response, 'angelegt');
|
||||
$id = (string) $response->json('id');
|
||||
$url = (string) $response->json('url');
|
||||
|
||||
if ($id === '' || $url === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Kasse geliefert. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
|
||||
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => $id]);
|
||||
|
||||
return ['id' => $id, 'url' => $url];
|
||||
}
|
||||
|
||||
public function assertAllowed(): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||
}
|
||||
|
||||
if (app()->isProduction()) {
|
||||
if (! Shop::live()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
|
||||
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
|
||||
* entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen
|
||||
* „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal.
|
||||
*
|
||||
* @return array{id: string, status: string, created: ?CarbonImmutable}
|
||||
*/
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
|
||||
if ($intent === '') {
|
||||
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
$this->assertOk($session, 'abgefragt');
|
||||
$intent = (string) $session->json('payment_intent');
|
||||
}
|
||||
|
||||
if ($intent === '') {
|
||||
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
|
||||
->post('/v1/refunds', [
|
||||
'payment_intent' => $intent,
|
||||
'amount' => $order->payable(),
|
||||
'reason' => 'requested_by_customer',
|
||||
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
|
||||
]);
|
||||
|
||||
$this->assertOk($response, 'erstattet');
|
||||
$id = (string) $response->json('id');
|
||||
$status = (string) $response->json('status');
|
||||
|
||||
if ($id === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.');
|
||||
}
|
||||
|
||||
if (in_array($status, ['failed', 'canceled'], true)) {
|
||||
throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.');
|
||||
}
|
||||
|
||||
$payment->provider_payment_ref = $intent;
|
||||
$payment->save();
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'status' => $status !== '' ? $status : 'unbekannt',
|
||||
'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Stripe bindet einen Schlüssel an die Parameter der ersten Anfrage und lehnt dieselbe Kennung mit anderen
|
||||
* Parametern ab. Der Schlüssel enthält deshalb einen Fingerabdruck der Parameter und die Minute: Ein
|
||||
* doppelter Klick bleibt wirkungslos, eine geänderte Anfrage oder ein Neuversuch nach einer Korrektur nicht.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
private function idempotencyKey(Order $order, int $attempt, array $params): string
|
||||
{
|
||||
$fingerprint = substr(sha1(json_encode([$params, now()->format('YmdHi')], JSON_THROW_ON_ERROR)), 0, 12);
|
||||
|
||||
return 'luf-order-'.$order->id.'-'.$attempt.'-'.$fingerprint;
|
||||
}
|
||||
|
||||
/** Konfigurierter Steuersatz oder null; eine ungültige ID wird abgewiesen, statt geraten zu werden. */
|
||||
private function taxRate(): ?string
|
||||
{
|
||||
$id = trim((string) config('services.stripe.tax_rate'));
|
||||
|
||||
if ($id === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! preg_match('/^txr_[A-Za-z0-9]+$/', $id)) {
|
||||
throw new DomainRuleException('Die Steuersatz-ID für Stripe ist ungültig (erwartet txr_...).');
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: string, url: string}|null
|
||||
*/
|
||||
private function reusableSession(Order $order): ?array
|
||||
{
|
||||
$payment = $order->payments()->where('provider', 'stripe')->where('status', 'offen')->latest('id')->first();
|
||||
|
||||
if ($payment === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
} catch (ConnectionException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($response->successful() && $response->json('status') === 'open' && filled($response->json('url'))) {
|
||||
return ['id' => (string) $payment->provider_reference, 'url' => (string) $response->json('url')];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function request(): PendingRequest
|
||||
{
|
||||
return Http::baseUrl(rtrim((string) config('services.stripe.api_base'), '/'))
|
||||
->withToken((string) config('services.stripe.secret'))
|
||||
->asForm()
|
||||
->acceptJson()
|
||||
->timeout(15);
|
||||
}
|
||||
|
||||
private function assertOk(Response $response, string $what): void
|
||||
{
|
||||
if ($response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Statuscode, Fehlertyp, Code, betroffener Parameter und Begründung von Stripe, damit die Ursache lesbar ist.
|
||||
// Nie Schlüssel oder Kundendaten; die Begründung wird gekürzt.
|
||||
Log::warning('Stripe-Anfrage fehlgeschlagen', [
|
||||
'status' => $response->status(),
|
||||
'type' => $response->json('error.type'),
|
||||
'code' => $response->json('error.code'),
|
||||
'param' => $response->json('error.param'),
|
||||
'message' => mb_substr((string) $response->json('error.message'), 0, 300),
|
||||
]);
|
||||
|
||||
throw new DomainRuleException('Die Zahlung konnte bei Stripe nicht '.$what.' werden. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user