Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
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.
|
||||
@@ -64,5 +65,8 @@ ## Verwaltungsoberfläche
|
||||
|
||||
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
|
||||
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Fachliche Säulen gibt es nur in der Säulenverwaltung (`pillars`); Zuordnung über `PillarService::assign`, nie über eine Dimension. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
|
||||
- Formatierte Texte (ADR-50): gespeichert wird bereinigtes HTML aus fester Auswahl, bearbeitet mit dem einen Editor `App\Filament\Support\RichField`, in den Arbeitsplätzen über `ManagesRichFields` (`richFelder()`, `kind => 'rich'`). Ausgabe nur über `App\Domain\Catalog\FormattedText` (`html()`, `display()`, `plain()`, `blocks()` fürs PDF), nie ungeprüft; verglichen wird nur `FormattedText::same()`/`canonical()`. Klartext des Altbestands bleibt in der Datenbank, bis jemand ihn ändert. Keine eigenen Textfelder mit `textarea` für Texte, die formatiert sein sollen.
|
||||
- Filter mit Mehrfachauswahl in Bestandslisten (z. B. Medienmanager): Baustein `verwaltung/bestand-filterdialog` über den Eintrag `filterdialog` in `bestand()` (Filterknopf neben der Suche, Pillen je wirksamem Feld, Dialog mit Entwurf der Auswahl: „Anwenden“ übernimmt, „Abbrechen“ verwirft). Mehrere Werte eines Felds gelten als ODER, verschiedene Felder als UND. Die Häkchen sind per `wire:model` an eine Liste im Entwurf gebunden (nie `wire:click` mit `@checked`: nach einer Serverantwort stimmt sonst die Anzeige nicht). Persönliche Standardfilter je Konto liegen in `user_view_defaults` (`UserViewDefault`). Texte, die für eine Übung angelegt werden, erhalten über `ExerciseSections::mark` die Materialart „Übungsabschnitt“ und den Verweis auf ihre Übung.
|
||||
- Die Redaktion ist ein Arbeitsstand: nur „Redaktion speichern“ schreibt Texte, Einordnung, Präsentationsmedien und Abweichungen. Kein verdecktes Mitspeichern aus anderen Dialogen, offene Eingaben bleiben beim Wechsel erhalten.
|
||||
- Dokumente (ADR-51): Kapitel sind Texte, die Dokumentfassung ist eine Komposition (`CompositionKind::Document`); bearbeitet wird im Aufbaueditor über den Kapitelarbeitsplatz (`ManagesDocumentChapters`, `verwaltung/dokument`), ausgegeben über `DocumentGuide` (Seite) und `DocumentPdf`. Formatierte Texte mit Tabellen und Bildern laufen nur über `FormattedText`, `RichField` und `EmbeddedImages` (ein Bild ist ein Verweis auf eine Bildfassung, nie eine Adresse); PDF-Satz nur über `PdfFlow`. Änderungen an `PdfDocument` müssen die Prüfsummen in `tests/Unit/PdfDocumentTest.php` einhalten (Belege byte-gleich). Das Aussehen des Dokument-PDF (Titelseite, Kopf, Fuß) kommt aus der `PdfTemplate` (Seite `PdfVorlagen`); Inhalt wie Ausgabe, Datum und Vermerk gehört in `document_meta` der Dokumentfassung, nicht in die Vorlage.
|
||||
- Jede UI-Änderung in der echten Anwendung prüfen (luf-test, breite und schmale Fenster, Tastatur) und mit Screenshots in `docs/ux/verwaltung/abnahme/` belegen. Stand der Abnahme: `abnahme/teil-a.md`, `abnahme/teil-b.md`, `abnahme/teil-c.md`, `abnahme/stammdaten.md`.
|
||||
@@ -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',
|
||||
|
||||
@@ -25,6 +25,7 @@ class Composition extends Model
|
||||
'editorial_content_kind_id',
|
||||
'archived_at',
|
||||
'working_draft',
|
||||
'pdf_template_id',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -36,11 +37,22 @@ 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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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,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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -277,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) {
|
||||
@@ -285,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 !== []) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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,8 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
@@ -39,6 +41,7 @@ public function __construct(
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
@@ -166,7 +167,7 @@ public function entries(array $refs, bool $includeNonPublic): array
|
||||
$entries[] = new CatalogEntry(
|
||||
id: $composition->id,
|
||||
title: $this->title($composition),
|
||||
summary: filled($composition->summary) ? (string) $composition->summary : null,
|
||||
summary: FormattedText::plain($composition->summary) ?: null,
|
||||
kindLabel: (string) ($composition->editorialContentKind?->label ?? ''),
|
||||
url: $public ? route('public.program', $composition) : null,
|
||||
public: $public,
|
||||
@@ -264,7 +265,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject
|
||||
$kind = (string) ($composition->editorialContentKind?->label ?? ($program ? 'Programm' : 'Modul'));
|
||||
$profile = app(EditorialProfileReader::class)->read($composition, 'kachel');
|
||||
$summary = $profile->value('teaser') ?: $profile->value('summary');
|
||||
$goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null;
|
||||
$goal = FormattedText::plain($version?->learning_goal) ?: null;
|
||||
// Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“).
|
||||
$texts = [
|
||||
'teaser' => $profile->value('teaser'),
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\MaterialTag;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
@@ -36,8 +38,8 @@
|
||||
*/
|
||||
class PublicMaterialReader
|
||||
{
|
||||
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen. */
|
||||
public const CONFIDENTIAL_KINDS = ['traineranleitung'];
|
||||
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen: Anleitungen für Trainer und die Textabschnitte der Übungen. */
|
||||
public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt', 'dokumentkapitel'];
|
||||
|
||||
/** @var array<int, array{id: int, title: string}>|null Element-ID => erstes öffentliches Programm */
|
||||
private ?array $publicIndex = null;
|
||||
@@ -174,7 +176,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$output = self::outputLabel((string) $shown->output_class);
|
||||
$film = $shown->output_class === 'film';
|
||||
$editorialKind = $element->editorialContentKind?->label;
|
||||
$summary = filled($shown->summary) ? trim((string) $shown->summary) : null;
|
||||
$summary = FormattedText::plain($shown->summary) ?: null;
|
||||
$profile = app(EditorialProfileReader::class)->read($shown, 'bibliothek');
|
||||
|
||||
if (! array_key_exists('summary', $draft) && $profile->origin('summary') === 'variante') {
|
||||
@@ -186,7 +188,8 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
$texts = [];
|
||||
|
||||
foreach (['teaser', 'summary', 'description'] as $field) {
|
||||
$own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null;
|
||||
$own = filled($shown->getAttribute($field)) ? trim(in_array($field, FormattedText::FIELDS, true) ? FormattedText::plain((string) $shown->getAttribute($field)) : (string) $shown->getAttribute($field)) : null;
|
||||
$own = $own === '' ? null : $own;
|
||||
|
||||
if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') {
|
||||
$own = $profile->value($field);
|
||||
@@ -235,6 +238,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,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';
|
||||
}
|
||||
}
|
||||
@@ -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,6 +3,7 @@
|
||||
namespace App\Domain\Cms\Widgets\Types;
|
||||
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Domain\Cms\Widgets\Support\HeadingAccent;
|
||||
use App\Domain\Cms\Widgets\Support\HeroVideo;
|
||||
use App\Domain\Cms\Widgets\Support\ImageRefFields;
|
||||
use App\Domain\Cms\Widgets\Support\PremiumFields;
|
||||
@@ -112,13 +113,16 @@ public function settings(): array
|
||||
return [
|
||||
'heading_level' => PremiumFields::HEADING_LEVELS,
|
||||
'accent' => ['underline' => 'Gelbe Unterstreichung', 'rays' => 'Unterstreichung und Signalstrahlen', 'none' => 'Ohne Akzent'],
|
||||
'symbol' => HeadingAccent::symbols(),
|
||||
'symbol_size' => HeadingAccent::SIZE,
|
||||
'symbol_align' => HeadingAccent::ALIGN,
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Aussehen' => ['accent', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -128,6 +132,9 @@ public function settingLabels(): array
|
||||
return [
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||
'symbol' => HeadingAccent::SYMBOL_LABEL,
|
||||
'symbol_size' => HeadingAccent::SIZE_LABEL,
|
||||
'symbol_align' => HeadingAccent::ALIGN_LABEL,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,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;
|
||||
@@ -114,13 +115,16 @@ 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'],
|
||||
'Aussehen' => ['surface', 'symbol', 'symbol_size', 'symbol_align'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
@@ -129,6 +133,9 @@ public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'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.'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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'] ?? '')));
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
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;
|
||||
|
||||
@@ -26,6 +27,7 @@ public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -187,14 +189,16 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return $this->settle($order, 'test', $reference);
|
||||
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.
|
||||
* 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): Order
|
||||
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'));
|
||||
|
||||
@@ -202,15 +206,17 @@ public function confirmProviderPayment(Order $order, string $provider, string $r
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference);
|
||||
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.
|
||||
* (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): Order
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
@@ -218,10 +224,12 @@ public function confirmInvoicePayment(Order $order, string $reference, User $act
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor);
|
||||
$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 = null): Order
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
@@ -230,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, &$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') {
|
||||
@@ -242,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$order->payments()->updateOrCreate(
|
||||
$payment = $order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id],
|
||||
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;
|
||||
@@ -295,8 +307,11 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
* (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): Order
|
||||
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);
|
||||
|
||||
@@ -306,12 +321,15 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
|
||||
$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) {
|
||||
($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$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): Order {
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
@@ -334,6 +352,16 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
}
|
||||
}
|
||||
|
||||
$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();
|
||||
|
||||
@@ -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,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,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);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
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;
|
||||
@@ -121,9 +122,12 @@ public function assertAllowed(): void
|
||||
/**
|
||||
* 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).
|
||||
* 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): void
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
@@ -148,8 +152,25 @@ public function refund(Order $order, Payment $payment, string $reason): void
|
||||
]);
|
||||
|
||||
$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,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,6 +16,7 @@ class MediaDelivery extends Model
|
||||
'copy_id',
|
||||
'checksum',
|
||||
'marking',
|
||||
'composition_version_id',
|
||||
'delivered_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ public function write(
|
||||
string $format,
|
||||
?string $checksum,
|
||||
string $marking,
|
||||
?string $copyId = null,
|
||||
?int $compositionVersionId = null,
|
||||
): MediaDelivery {
|
||||
return MediaDelivery::query()->create([
|
||||
'grant_id' => $grant->id,
|
||||
@@ -27,10 +29,16 @@ public function write(
|
||||
'content_element_version_id' => $version->id,
|
||||
'action' => $action,
|
||||
'format' => $format,
|
||||
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
|
||||
'copy_id' => $copyId ?? self::newCopyId(),
|
||||
'composition_version_id' => $compositionVersionId,
|
||||
'checksum' => $checksum,
|
||||
'marking' => $marking,
|
||||
'delivered_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function newCopyId(): string
|
||||
{
|
||||
return 'LK-'.strtoupper(bin2hex(random_bytes(6)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
/**
|
||||
* Bereitet ein Bild für das PDF auf: Es wird mit GD gelesen, auf eine druckbare Größe verkleinert, auf Weiß gesetzt
|
||||
* (Transparenz gibt es im PDF-Schreiber nicht) und als JPEG neu kodiert. So braucht das PDF keine Bildbibliothek und
|
||||
* keine Rücksicht auf das Ausgangsformat. Was GD nicht lesen kann (zum Beispiel WebP in einem Image ohne WebP-Unterstützung),
|
||||
* liefert null; die Ausgabe zeigt dann einen Hinweis statt des Bildes.
|
||||
*/
|
||||
final class PdfImage
|
||||
{
|
||||
/** Längste Kante in Pixel; 1400 Pixel genügen für die Spaltenbreite einer A4-Seite bei guter Druckqualität. */
|
||||
public const MAX_EDGE = 1400;
|
||||
|
||||
/**
|
||||
* @return array{jpeg: string, width: int, height: int}|null
|
||||
*/
|
||||
public static function fromBytes(string $raw): ?array
|
||||
{
|
||||
if ($raw === '' || ! function_exists('imagecreatefromstring')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$source = @imagecreatefromstring($raw);
|
||||
|
||||
if ($source === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
|
||||
if ($width < 1 || $height < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scale = min(1.0, self::MAX_EDGE / max($width, $height));
|
||||
$targetWidth = max(1, (int) round($width * $scale));
|
||||
$targetHeight = max(1, (int) round($height * $scale));
|
||||
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
|
||||
|
||||
if ($canvas === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
imagefill($canvas, 0, 0, (int) imagecolorallocate($canvas, 255, 255, 255));
|
||||
imagecopyresampled($canvas, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
|
||||
|
||||
ob_start();
|
||||
$written = imagejpeg($canvas, null, 82);
|
||||
$jpeg = (string) ob_get_clean();
|
||||
|
||||
return $written && $jpeg !== '' ? ['jpeg' => $jpeg, 'width' => $targetWidth, 'height' => $targetHeight] : null;
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* Arbeitsplatz: Programme und Module in der gemeinsamen Bestandsliste. Die Listen „Module“ und „Programme“ zeigen
|
||||
* Gemeinsame Übersicht „Programme und Module“ (kein Menüpunkt; Einstieg über die Stammdaten). Die Listen „Module“ und „Programme“ zeigen
|
||||
* dieselben Zeilen mit festem Typ (ListsCompositions).
|
||||
*/
|
||||
class EditorialDesk extends Page
|
||||
@@ -23,6 +23,9 @@ class EditorialDesk extends Page
|
||||
|
||||
protected static ?int $navigationSort = 0;
|
||||
|
||||
/** Kein Menüpunkt mehr; die gemeinsame Übersicht bleibt über den Filterlink der Stammdaten erreichbar. */
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static ?string $slug = 'arbeitsplatz';
|
||||
|
||||
protected static ?string $title = 'Arbeitsplatz';
|
||||
|
||||
@@ -0,0 +1,387 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Catalog\PdfTemplate;
|
||||
use App\Domain\Catalog\TemplateImage;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\ChoosesMedia;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* PDF-Vorlagen für Dokumente (ADR-51, Nachtrag): Titelseite, grafische Kopf- und Fußzeile und Standardvermerke. Die Bilder
|
||||
* wählt der gemeinsame Picker aus dem Medienbestand (freigegebene Bildfassungen); eine Vorlage ist reines Layout und ändert
|
||||
* keinen Inhalt. Gespeichert wird erst mit „Vorlage speichern“; offene Eingaben bleiben beim Wechsel der Vorlage nicht stehen,
|
||||
* der Wechsel fragt bei offenen Änderungen nach.
|
||||
*/
|
||||
class PdfVorlagen extends Page
|
||||
{
|
||||
use ChoosesMedia;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?string $navigationLabel = 'PDF-Vorlagen';
|
||||
|
||||
protected static ?int $navigationSort = 60;
|
||||
|
||||
protected static ?string $slug = 'pdf-vorlagen';
|
||||
|
||||
protected static ?string $title = 'PDF-Vorlagen';
|
||||
|
||||
protected string $view = 'filament.pdf.vorlagen';
|
||||
|
||||
/** Gewählte Vorlage; 0 = neue, noch nicht gespeicherte. */
|
||||
public int $templateId = 0;
|
||||
|
||||
public string $name = '';
|
||||
|
||||
public string $publisher = '';
|
||||
|
||||
public string $copyright = '';
|
||||
|
||||
public bool $showCover = true;
|
||||
|
||||
/** Inhaltsverzeichnis im PDF: `auto` (nur bei mehr als einem Eintrag), `always`, `never`. */
|
||||
public string $tocModus = 'auto';
|
||||
|
||||
/** Tiefe des Verzeichnisses: 2 = nur Kapitel, 3 bis 6 = bis zu dieser Überschriftenstufe. */
|
||||
public int $tocTiefe = PdfTemplate::TOC_DEPTH_MAX;
|
||||
|
||||
/**
|
||||
* Anordnung von Kopf und Fuß: `full` (Band in voller Seitenbreite), `left` oder `right` (Logo).
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
public array $anordnung = ['header' => 'full', 'footer' => 'full'];
|
||||
|
||||
/**
|
||||
* Höhe des Logos in Punkt, wenn Kopf oder Fuß ein Logo tragen.
|
||||
*
|
||||
* @var array<string, int|string>
|
||||
*/
|
||||
public array $logohoehe = ['header' => PdfTemplate::LOGO_DEFAULT, 'footer' => PdfTemplate::LOGO_DEFAULT];
|
||||
|
||||
/**
|
||||
* Die Bilder je Bildfeld (header, footer, cover) als Ziel des Pickers: `element:<Fassung>` oder `medium:<Medium>`.
|
||||
*
|
||||
* @var array<string, string|null>
|
||||
*/
|
||||
public array $bilder = ['header' => null, 'footer' => null, 'cover' => null];
|
||||
|
||||
/** Das Bildfeld, in das die Auswahl übernommen wird: header, footer oder cover. */
|
||||
public ?string $bildFeld = null;
|
||||
|
||||
/** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */
|
||||
public ?array $bestaetigung = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ContentElementResource::editor();
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$first = PdfTemplate::query()->where('kind', PdfTemplate::KIND_DOCUMENT)->orderBy('name')->first();
|
||||
$first instanceof PdfTemplate ? $this->loadTemplate($first) : $this->clearForm();
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{id: int, name: string, documents: int}>
|
||||
*/
|
||||
public function templates(): array
|
||||
{
|
||||
return PdfTemplate::query()->where('kind', PdfTemplate::KIND_DOCUMENT)->withCount('compositions')->orderBy('name')->get()
|
||||
->map(fn (PdfTemplate $template): array => ['id' => $template->id, 'name' => $template->name, 'documents' => (int) $template->compositions_count])->all();
|
||||
}
|
||||
|
||||
public function select(int $id): void
|
||||
{
|
||||
$template = PdfTemplate::query()->where('kind', PdfTemplate::KIND_DOCUMENT)->find($id);
|
||||
|
||||
if ($template instanceof PdfTemplate) {
|
||||
$this->loadTemplate($template);
|
||||
}
|
||||
}
|
||||
|
||||
public function newTemplate(): void
|
||||
{
|
||||
$this->clearForm();
|
||||
}
|
||||
|
||||
/** Ob die Eingaben vom gespeicherten Stand abweichen. */
|
||||
public function changed(): bool
|
||||
{
|
||||
$template = $this->templateId > 0 ? PdfTemplate::query()->find($this->templateId) : null;
|
||||
|
||||
if (! $template instanceof PdfTemplate) {
|
||||
return $this->name !== '' || $this->publisher !== '' || $this->copyright !== '' || array_filter($this->bilder) !== [] || $this->layouts() !== [PdfTemplate::normalizeLayout(null, null), PdfTemplate::normalizeLayout(null, null)] || $this->tocSetting() !== PdfTemplate::normalizeToc(null, null);
|
||||
}
|
||||
|
||||
return $this->name !== $template->name
|
||||
|| $this->publisher !== (string) $template->publisher
|
||||
|| $this->copyright !== (string) $template->copyright
|
||||
|| $this->showCover !== (bool) $template->show_cover
|
||||
|| $this->bilder !== $this->templateSlots($template)
|
||||
|| $this->layouts() !== [$template->layout('header'), $template->layout('footer')]
|
||||
|| $this->tocSetting() !== $template->toc();
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
|
||||
if (trim($this->name) === '') {
|
||||
Notification::make()->danger()->title('Der Name fehlt.')->body('Er bezeichnet die Vorlage bei der Auswahl am Dokument.')->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (PdfTemplate::SLOTS as $slot) {
|
||||
$problem = $this->bilder[$slot] === null ? null : TemplateImage::problem($this->bilder[$slot]);
|
||||
|
||||
if ($problem !== null) {
|
||||
Notification::make()->danger()->title('Das Bild für '.$this->slotLabel($slot).' lässt sich nicht verwenden.')->body($problem)->send();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$values = [
|
||||
'name' => trim($this->name),
|
||||
'kind' => PdfTemplate::KIND_DOCUMENT,
|
||||
'show_cover' => $this->showCover,
|
||||
...PdfTemplate::columns('header', $this->bilder['header']),
|
||||
...PdfTemplate::columns('footer', $this->bilder['footer']),
|
||||
...PdfTemplate::columns('cover', $this->bilder['cover']),
|
||||
'header_align' => $this->layouts()[0]['align'],
|
||||
'header_logo_height' => $this->layouts()[0]['height'],
|
||||
'footer_align' => $this->layouts()[1]['align'],
|
||||
'footer_logo_height' => $this->layouts()[1]['height'],
|
||||
'toc_mode' => $this->tocSetting()['mode'],
|
||||
'toc_depth' => $this->tocSetting()['depth'],
|
||||
'publisher' => trim($this->publisher) === '' ? null : trim($this->publisher),
|
||||
'copyright' => trim($this->copyright) === '' ? null : trim($this->copyright),
|
||||
];
|
||||
$template = $this->templateId > 0 ? PdfTemplate::query()->find($this->templateId) : null;
|
||||
$template instanceof PdfTemplate ? $template->update($values) : $template = PdfTemplate::query()->create($values);
|
||||
$this->loadTemplate($template);
|
||||
Notification::make()->success()->title('Vorlage gespeichert')->body('Sie gilt sofort für jedes Dokument, das sie verwendet, auch für ältere Fassungen.')->send();
|
||||
}
|
||||
|
||||
public function askConfirmation(string $aktion): void
|
||||
{
|
||||
if ($aktion === 'delete' && $this->templateId > 0) {
|
||||
$uses = PdfTemplate::query()->withCount('compositions')->find($this->templateId)?->compositions_count ?? 0;
|
||||
$this->bestaetigung = [
|
||||
'aktion' => 'delete',
|
||||
'argument' => null,
|
||||
'titel' => '„'.$this->name.'“ löschen?',
|
||||
'text' => $uses > 0
|
||||
? $uses.' '.($uses === 1 ? 'Dokument verwendet' : 'Dokumente verwenden').' diese Vorlage und '.($uses === 1 ? 'erzeugt' : 'erzeugen').' danach wieder das einfache PDF ohne Titelseite. Die Bilder bleiben im Medienbestand.'
|
||||
: 'Die Vorlage wird entfernt. Die Bilder bleiben im Medienbestand.',
|
||||
'label' => 'Vorlage löschen',
|
||||
'gefahr' => true,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function confirmConfirmation(): void
|
||||
{
|
||||
$frage = $this->bestaetigung;
|
||||
$this->bestaetigung = null;
|
||||
|
||||
if (($frage['aktion'] ?? null) === 'delete' && $this->templateId > 0) {
|
||||
abort_unless(ContentElementResource::editor(), 403);
|
||||
PdfTemplate::query()->whereKey($this->templateId)->delete();
|
||||
$this->mount();
|
||||
Notification::make()->success()->title('Vorlage gelöscht')->send();
|
||||
}
|
||||
}
|
||||
|
||||
public function cancelConfirmation(): void
|
||||
{
|
||||
$this->bestaetigung = null;
|
||||
}
|
||||
|
||||
public function openImagePicker(string $slot): void
|
||||
{
|
||||
if (! in_array($slot, ['header', 'footer', 'cover'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->bildFeld = $slot;
|
||||
$this->resetPicker('vorlagenbild');
|
||||
$this->pickerKind = 'bild';
|
||||
}
|
||||
|
||||
public function clearImage(string $slot): void
|
||||
{
|
||||
if (in_array($slot, PdfTemplate::SLOTS, true)) {
|
||||
$this->bilder[$slot] = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function pickerAllowsMany(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function closePicker(): void
|
||||
{
|
||||
$this->pickerOpen = false;
|
||||
$this->pickerSelected = '';
|
||||
$this->pickerInspected = '';
|
||||
$this->pickerMarked = [];
|
||||
$this->bildFeld = null;
|
||||
}
|
||||
|
||||
public function confirmPicker(): void
|
||||
{
|
||||
$target = array_key_first($this->pickerMarked);
|
||||
$slot = $this->bildFeld;
|
||||
|
||||
if ($target === null || $slot === null || ! in_array($slot, PdfTemplate::SLOTS, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$problem = TemplateImage::problem((string) $target);
|
||||
|
||||
if ($problem !== null) {
|
||||
Notification::make()->danger()->title('Dieses Bild lässt sich nicht verwenden.')->body($problem)->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->bilder[$slot] = (string) $target;
|
||||
$this->closePicker();
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function pickerKinds(): array
|
||||
{
|
||||
return ['bild' => 'Bilder'];
|
||||
}
|
||||
|
||||
public function pickerTitle(): string
|
||||
{
|
||||
return 'Bild für '.$this->slotLabel((string) $this->bildFeld);
|
||||
}
|
||||
|
||||
public function pickerConfirmLabel(): string
|
||||
{
|
||||
return 'Bild übernehmen';
|
||||
}
|
||||
|
||||
/** @return array{art: string, titel: string} */
|
||||
public function pickerKontext(): array
|
||||
{
|
||||
return ['art' => 'die PDF-Vorlage', 'titel' => trim($this->name) !== '' ? $this->name : 'neue Vorlage'];
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function presentationRoleOptions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function pickerReplacing(): ?array
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function imageUrl(?string $target): ?string
|
||||
{
|
||||
return TemplateImage::previewUrl($target);
|
||||
}
|
||||
|
||||
public function imageTitle(?string $target): string
|
||||
{
|
||||
return TemplateImage::title($target);
|
||||
}
|
||||
|
||||
public function slotLabel(string $slot): string
|
||||
{
|
||||
return match ($slot) {
|
||||
'header' => 'den Kopf der Seiten',
|
||||
'footer' => 'den Fuß der Seiten',
|
||||
'cover' => 'die Titelseite',
|
||||
default => 'die Vorlage',
|
||||
};
|
||||
}
|
||||
|
||||
private function loadTemplate(PdfTemplate $template): void
|
||||
{
|
||||
$this->templateId = $template->id;
|
||||
$this->name = $template->name;
|
||||
$this->publisher = (string) $template->publisher;
|
||||
$this->copyright = (string) $template->copyright;
|
||||
$this->showCover = (bool) $template->show_cover;
|
||||
$this->bilder = $this->templateSlots($template);
|
||||
$this->anordnung = ['header' => $template->layout('header')['align'], 'footer' => $template->layout('footer')['align']];
|
||||
$this->logohoehe = ['header' => $template->layout('header')['height'], 'footer' => $template->layout('footer')['height']];
|
||||
$this->tocModus = $template->toc()['mode'];
|
||||
$this->tocTiefe = $template->toc()['depth'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{mode: string, depth: int}
|
||||
*/
|
||||
private function tocSetting(): array
|
||||
{
|
||||
return PdfTemplate::normalizeToc($this->tocModus, $this->tocTiefe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Anordnung und Logohöhe von Kopf und Fuß, ungültige Eingaben auf gültige Werte gebracht.
|
||||
*
|
||||
* @return list<array{align: string, height: int}>
|
||||
*/
|
||||
private function layouts(): array
|
||||
{
|
||||
return [
|
||||
PdfTemplate::normalizeLayout($this->anordnung['header'] ?? null, $this->logohoehe['header'] ?? null),
|
||||
PdfTemplate::normalizeLayout($this->anordnung['footer'] ?? null, $this->logohoehe['footer'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string|null>
|
||||
*/
|
||||
private function templateSlots(PdfTemplate $template): array
|
||||
{
|
||||
return ['header' => $template->target('header'), 'footer' => $template->target('footer'), 'cover' => $template->target('cover')];
|
||||
}
|
||||
|
||||
private function clearForm(): void
|
||||
{
|
||||
$this->templateId = 0;
|
||||
$this->name = '';
|
||||
$this->publisher = '';
|
||||
$this->copyright = '';
|
||||
$this->showCover = true;
|
||||
$this->bilder = ['header' => null, 'footer' => null, 'cover' => null];
|
||||
$this->anordnung = ['header' => 'full', 'footer' => 'full'];
|
||||
$this->logohoehe = ['header' => PdfTemplate::LOGO_DEFAULT, 'footer' => PdfTemplate::LOGO_DEFAULT];
|
||||
$this->tocModus = 'auto';
|
||||
$this->tocTiefe = PdfTemplate::TOC_DEPTH_MAX;
|
||||
}
|
||||
|
||||
protected function pickerExceptId(): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -52,11 +52,11 @@ class RedaktionelleStammdaten extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Redaktionelle Stammdaten';
|
||||
|
||||
protected static ?int $navigationSort = 6;
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected static ?string $slug = 'stammdaten';
|
||||
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\ExerciseImportRun;
|
||||
use App\Domain\Catalog\ExerciseSource;
|
||||
use App\Domain\Catalog\ShinkanConnection;
|
||||
use App\Domain\Catalog\ShinkanImport;
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
/**
|
||||
* Übungen aus Shinkan übernehmen: abrufen, suchen und nach Zustand filtern, markieren, vor der Übernahme prüfen und
|
||||
* ausdrücklich bestätigen. Abrufen verändert nur den Quellenstand; erst die Bestätigung legt lokale Fassungen an, und
|
||||
* erst eine Produktveröffentlichung setzt sie ein.
|
||||
*
|
||||
* Den Zugangsschlüssel hinterlegen und ersetzen nur Katalog- und Systemverwalter. Die Redaktion sieht den Zustand der
|
||||
* Anbindung und arbeitet mit ihr; der Schlüssel wird nie an den Browser zurückgegeben.
|
||||
*/
|
||||
class Uebernahme extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?string $navigationLabel = 'Übungen aus Shinkan';
|
||||
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
protected static ?string $slug = 'uebernahme';
|
||||
|
||||
protected static ?string $title = 'Übungen aus Shinkan übernehmen';
|
||||
|
||||
protected string $view = 'filament.pages.uebernahme';
|
||||
|
||||
public string $apiKey = '';
|
||||
|
||||
public string $search = '';
|
||||
|
||||
public string $statusFilter = 'alle';
|
||||
|
||||
/** @var list<int|string> Markierte Quellübungen (Kennung in der Datenbank) */
|
||||
public array $selected = [];
|
||||
|
||||
/** auswahl | vorschau | ergebnis */
|
||||
public string $step = 'auswahl';
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $preview = [];
|
||||
|
||||
/** @var array<int|string, array<string, string>> Quellübung => (entfallene Quellvariante => neue Zuordnung) */
|
||||
public array $reassign = [];
|
||||
|
||||
/** @var array<int|string, array<string, string>> Quellübung => (Text oder Feld => `lokal` oder `quelle`) */
|
||||
public array $textChoice = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $results = [];
|
||||
|
||||
public string $feedback = '';
|
||||
|
||||
public bool $feedbackError = false;
|
||||
|
||||
/**
|
||||
* Die Übernahme ist ein Weg im Übungsbestand („Aus Shinkan übernehmen“) und kein eigener Einstieg. Nur wer die
|
||||
* Anbindung pflegen darf, aber den Übungsbestand nicht sieht, bekommt den Eintrag in der Navigation.
|
||||
*/
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
return static::canConfigure() && ! ContentElementResource::editor();
|
||||
}
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ContentElementResource::editor() || static::canConfigure();
|
||||
}
|
||||
|
||||
/** Den Schlüssel ändern dürfen nur Katalogverwalter und Systemverwalter. */
|
||||
public static function canConfigure(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Systemverwalter));
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
public function saveKey(): void
|
||||
{
|
||||
abort_unless(static::canConfigure(), 403);
|
||||
|
||||
try {
|
||||
app(ShinkanConnection::class)->saveKey($this->apiKey, $this->actor());
|
||||
$this->say('Der Zugangsschlüssel ist gespeichert. Prüfe jetzt die Verbindung. Der Schlüssel wird nie wieder angezeigt.');
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->say($exception->getMessage(), true);
|
||||
}
|
||||
|
||||
$this->apiKey = '';
|
||||
}
|
||||
|
||||
public function removeKey(): void
|
||||
{
|
||||
abort_unless(static::canConfigure(), 403);
|
||||
|
||||
app(ShinkanConnection::class)->forgetKey($this->actor());
|
||||
$this->say('Der in der Verwaltung hinterlegte Zugangsschlüssel ist entfernt. Ein Schlüssel aus der Umgebung des Servers bleibt davon unberührt.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Verbindung. Ein eingetragener, noch nicht gespeicherter Schlüssel wird mitgeprüft (nur Verwalter).
|
||||
*/
|
||||
public function check(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$candidate = static::canConfigure() ? $this->apiKey : '';
|
||||
$result = app(ShinkanImport::class)->check($candidate);
|
||||
$this->apiKey = '';
|
||||
$this->say($result['message'], ! $result['ok']);
|
||||
}
|
||||
|
||||
public function fetch(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$run = app(ShinkanImport::class)->fetch();
|
||||
$this->say(
|
||||
$run->status === 'ok'
|
||||
? 'Abruf abgeschlossen: '.$run->added.' neu, '.$run->updated.' geändert, '.$run->removed.' nicht mehr bereitgestellt. Es wurde noch keine lokale Fassung angelegt.'
|
||||
: (string) $run->error,
|
||||
$run->status !== 'ok',
|
||||
);
|
||||
}
|
||||
|
||||
public function review(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$ids = array_values(array_unique(array_map('intval', $this->selected)));
|
||||
|
||||
if ($ids === []) {
|
||||
$this->say('Markiere mindestens eine Übung.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->buildPreview($ids);
|
||||
$this->step = 'vorschau';
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function backToSelection(): void
|
||||
{
|
||||
$this->step = 'auswahl';
|
||||
$this->preview = [];
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function confirm(): void
|
||||
{
|
||||
abort_unless(static::canAccess(), 403);
|
||||
|
||||
$import = app(ShinkanImport::class);
|
||||
$changed = [];
|
||||
$open = [];
|
||||
|
||||
foreach ($this->preview as $entry) {
|
||||
$source = ExerciseSource::query()->find($entry['source']);
|
||||
|
||||
if ($source === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$latest = $source->latestSnapshot();
|
||||
|
||||
if (($source->availability === ExerciseSource::WITHDRAWN) !== (bool) $entry['excluded'] || $latest?->id !== $entry['snapshot']) {
|
||||
$changed[] = $entry['title'];
|
||||
}
|
||||
|
||||
foreach ($entry['text_conflicts'] as $conflict) {
|
||||
if (! in_array($this->textChoice[$entry['source']][$conflict['key']] ?? 'offen', ['lokal', 'quelle'], true)) {
|
||||
$open[] = $entry['title'].': '.$conflict['label'];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($entry['conflicts'] as $conflict) {
|
||||
if (! isset($this->reassign[$entry['source']][$conflict['key']]) || $this->reassign[$entry['source']][$conflict['key']] === 'offen') {
|
||||
$open[] = $entry['title'].': '.implode(', ', $conflict['members']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($changed !== []) {
|
||||
$this->buildPreview(array_map(fn (array $entry): int => (int) $entry['source'], $this->preview));
|
||||
$this->say('Der Quellstand hat sich seit der Vorschau geändert ('.implode(', ', $changed).'). Die Vorschau ist aktualisiert. Prüfe sie und bestätige den neuen Stand bewusst. Es wurde nichts übernommen.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($open !== []) {
|
||||
$this->say('Lege zuerst fest, was gilt: '.implode('; ', $open).'.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->results = [];
|
||||
|
||||
foreach ($this->preview as $entry) {
|
||||
$source = ExerciseSource::query()->findOrFail($entry['source']);
|
||||
$reassign = array_map(fn (string $value): string => $value === 'gemeinsam' ? '' : $value, $this->reassign[$entry['source']] ?? []);
|
||||
$result = $import->adoptPreviewed($source, (int) $entry['snapshot'], $reassign, $this->actor(), $this->textChoice[$entry['source']] ?? []);
|
||||
$source->refresh();
|
||||
$this->results[] = [
|
||||
'title' => $entry['title'],
|
||||
'status' => $result['status'],
|
||||
'message' => $result['message'],
|
||||
'url' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]),
|
||||
];
|
||||
}
|
||||
|
||||
$this->selected = [];
|
||||
$this->preview = [];
|
||||
$this->step = 'ergebnis';
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
public function done(): void
|
||||
{
|
||||
$this->step = 'auswahl';
|
||||
$this->results = [];
|
||||
$this->say('');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function daten(): array
|
||||
{
|
||||
$import = app(ShinkanImport::class);
|
||||
$labels = [
|
||||
'neu' => ['Neu', 'is-neu'],
|
||||
'geaendert' => ['Geänderter Quellstand', 'is-geaendert'],
|
||||
'uebernommen' => ['Übernommen', 'is-eigen'],
|
||||
'nicht_mehr_bereitgestellt' => ['Nicht mehr bereitgestellt', ''],
|
||||
];
|
||||
$needle = mb_strtolower(trim($this->search));
|
||||
$rows = [];
|
||||
$total = 0;
|
||||
|
||||
foreach (ExerciseSource::query()->with('composition')->orderBy('title')->get() as $source) {
|
||||
$total++;
|
||||
$state = $import->state($source);
|
||||
|
||||
if (($this->statusFilter !== 'alle' && $this->statusFilter !== $state)
|
||||
|| ($needle !== '' && ! str_contains(mb_strtolower(($source->title ?? '').' '.$source->source_id), $needle))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$rows[] = [
|
||||
'id' => $source->id,
|
||||
'titel' => $source->title ?: $source->source_id,
|
||||
'zustand' => $labels[$state][0],
|
||||
'ton' => $labels[$state][1],
|
||||
'state' => $state,
|
||||
'markierbar' => $state !== 'nicht_mehr_bereitgestellt',
|
||||
'lokal' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]),
|
||||
'hinweis' => $state === 'nicht_mehr_bereitgestellt'
|
||||
? 'Lokale Fassungen und Verwendungen bleiben unverändert. Eine rechtliche Sperre ist ein eigener Vorgang am Medium.'
|
||||
: null,
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'zeilen' => $rows,
|
||||
'gesamt' => $total,
|
||||
'optionen' => ['alle' => 'Alle Zustände', 'neu' => 'Neu', 'geaendert' => 'Geänderter Quellstand', 'uebernommen' => 'Übernommen', 'nicht_mehr_bereitgestellt' => 'Nicht mehr bereitgestellt'],
|
||||
'eingerichtet' => $import->configured(),
|
||||
'anbindung' => $import->status(),
|
||||
'darfAendern' => static::canConfigure(),
|
||||
'letzterLauf' => ExerciseImportRun::query()->orderByDesc('id')->first(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $ids
|
||||
*/
|
||||
private function buildPreview(array $ids): void
|
||||
{
|
||||
$import = app(ShinkanImport::class);
|
||||
$this->preview = [];
|
||||
|
||||
foreach (ExerciseSource::query()->whereIn('id', $ids)->orderBy('title')->get() as $source) {
|
||||
$this->preview[] = $import->preview($source);
|
||||
}
|
||||
}
|
||||
|
||||
private function actor(): ?User
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User ? $user : null;
|
||||
}
|
||||
|
||||
private function say(string $message, bool $error = false): void
|
||||
{
|
||||
$this->feedback = $message;
|
||||
$this->feedbackError = $error;
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,11 @@ public function daten(): array
|
||||
['text' => 'Stripe-Schlüssel: '.$mode, 'neben' => 'Der Schlüssel steht nur in der Umgebungsdatei des Servers und wird hier nie angezeigt.', 'zustand' => $mode === 'nicht eingerichtet' ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => $mode, 'ton' => 'neutral']],
|
||||
['text' => 'Signaturschlüssel für Stripe-Meldungen: '.(filled(config('services.stripe.webhook_secret')) ? 'gesetzt' : 'fehlt'), 'neben' => 'Ohne ihn weist die Anwendung jede Meldung von Stripe ab; Zahlungen schalten dann nichts frei.', 'zustand' => filled(config('services.stripe.webhook_secret')) ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Fehlt', 'ton' => 'offen']],
|
||||
['text' => 'Steuersatz bei Stripe: '.(filled(config('services.stripe.tax_rate')) ? 'hinterlegt' : 'nicht hinterlegt'), 'neben' => 'Steuerstatus und Belegangaben sind noch nicht entschieden (OPEN-06). Ohne sie gibt es keinen Steuerausweis auf der Stripe-Kasse und keine Rechnungsvorlage.', 'zustand' => filled(config('services.stripe.tax_rate')) ? ['label' => 'Hinterlegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||
['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung.', 'zustand' => ['label' => Shop::invoice() ? 'Bereit' : 'Aus', 'ton' => 'neutral']],
|
||||
['text' => 'Aussteller auf dem Zahlungsbeleg: '.(filled(config('shop.receipt.issuer')) ? 'gepflegt' : 'nicht gepflegt'), 'neben' => 'Mitglieder laden zu jeder Zahlung einen Beleg (PDF) herunter. Er nennt den Aussteller nur, wenn er mit SHOP_RECEIPT_ISSUER gepflegt ist (Zeilen durch „|“ getrennt). Name und Anschrift des Verkäufers, Steuerangaben und eine Rechnungsnummer hängen an der rechtlichen Klärung (OPEN-06); bis dahin trägt der Beleg keine steuerlichen Angaben.', 'zustand' => filled(config('shop.receipt.issuer')) ? ['label' => 'Gepflegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
|
||||
['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => Shop::invoice()
|
||||
? 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung. Vereine sehen die Möglichkeit im Checkout.'
|
||||
: 'Mitglieder sehen die Möglichkeit nicht. Sie wird erst angeboten, wenn der Prozess vollständig ist: Rechnungserstellung mit Nummernkreis, Benachrichtigung des Betreibers bei neuer Rechnungsbestellung und die rechtliche Klärung (OPEN-06). Die Umsetzung ist vorbereitet; schaltest du sie mit SHOP_INVOICE=true in der Umgebungsdatei ein, erscheint sie im Checkout. Bereits angelegte Rechnungsbestellungen bleiben in der Bestellverwaltung bearbeitbar.',
|
||||
'zustand' => Shop::invoice() ? ['label' => 'Angeboten', 'ton' => 'neutral'] : ['label' => 'Aus', 'ton' => 'neutral']],
|
||||
];
|
||||
|
||||
$freigabe = [
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\PaymentJournal;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Livewire\Attributes\Url;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* Einnahmen und Erstattungen (Zahlungsjournal): Jede Geldbewegung steht unveränderlich mit Datum, Betrag, Beleg beim
|
||||
* Anbieter, handelnder Person, Begründung und Zahler da. Die Seite liest nur; es gibt nichts zu bearbeiten oder zu
|
||||
* löschen. Standardmäßig zählen nur echte Zahlungen; Testzahlungen sind ein eigener Filter und fließen nie in die
|
||||
* Summen echter Einnahmen. Der Export (CSV) enthält alle Zeilen des gewählten Zeitraums und Filters.
|
||||
*/
|
||||
class Zahlungsjournal extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Einnahmen und Erstattungen';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected static ?string $slug = 'zahlungsjournal';
|
||||
|
||||
protected static ?string $title = 'Einnahmen und Erstattungen';
|
||||
|
||||
protected string $view = 'filament.pages.zahlungsjournal';
|
||||
|
||||
#[Url(as: 'zeitraum')]
|
||||
public string $modus = 'monat';
|
||||
|
||||
#[Url(as: 'jahr')]
|
||||
public ?int $jahr = null;
|
||||
|
||||
#[Url(as: 'nr')]
|
||||
public ?int $nr = null;
|
||||
|
||||
#[Url(as: 'art')]
|
||||
public string $art = 'alle';
|
||||
|
||||
#[Url(as: 'weg')]
|
||||
public string $weg = 'alle';
|
||||
|
||||
/** Ohne Angabe: auf Prod die echten Zahlungen, auf jeder anderen Instanz (Test, lokal) die Testzahlungen. */
|
||||
#[Url(as: 'betrieb')]
|
||||
public ?string $betrieb = null;
|
||||
|
||||
/** Kennung eines Angebots oder leer für alle (Zeichenkette, damit die Auswahl „Alle“ leer sein kann). */
|
||||
#[Url(as: 'angebot')]
|
||||
public string $angebot = '';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$now = CarbonImmutable::now(PaymentJournal::TIMEZONE);
|
||||
$this->jahr ??= $now->year;
|
||||
$this->nr ??= $this->modus === 'quartal' ? $now->quarter : $now->month;
|
||||
$this->betrieb ??= self::defaultBetrieb();
|
||||
$this->normalize();
|
||||
}
|
||||
|
||||
/** Nur Prod zeigt standardmäßig echte Zahlungen; auf anderen Instanzen entstehen Buchungen nur aus der Sandbox. */
|
||||
public static function defaultBetrieb(): string
|
||||
{
|
||||
return app()->isProduction() ? 'echt' : 'test';
|
||||
}
|
||||
|
||||
/** Beim Wechsel zwischen Monat und Quartal bleibt der gewählte Zeitraum erhalten. */
|
||||
public function updatingModus(string $value): void
|
||||
{
|
||||
if ($this->modus === 'monat' && $value === 'quartal') {
|
||||
$this->nr = (int) ceil(((int) $this->nr) / 3);
|
||||
} elseif ($this->modus === 'quartal' && $value === 'monat') {
|
||||
$this->nr = (((int) $this->nr) - 1) * 3 + 1;
|
||||
}
|
||||
}
|
||||
|
||||
public function updated(): void
|
||||
{
|
||||
$this->normalize();
|
||||
}
|
||||
|
||||
/** Ungültige Eingaben aus der Adresszeile fallen auf zulässige Werte zurück. */
|
||||
private function normalize(): void
|
||||
{
|
||||
$this->modus = in_array($this->modus, ['monat', 'quartal', 'jahr'], true) ? $this->modus : 'monat';
|
||||
$this->art = in_array($this->art, ['alle', LedgerEntry::KIND_PAYMENT, LedgerEntry::KIND_REFUND], true) ? $this->art : 'alle';
|
||||
$this->weg = in_array($this->weg, ['alle', 'stripe', 'ueberweisung', 'test'], true) ? $this->weg : 'alle';
|
||||
$this->betrieb = in_array($this->betrieb, ['echt', 'test', 'alle'], true) ? $this->betrieb : self::defaultBetrieb();
|
||||
$this->angebot = ctype_digit($this->angebot) && Offer::query()->whereKey((int) $this->angebot)->exists() ? $this->angebot : '';
|
||||
$this->jahr = max(2020, min((int) CarbonImmutable::now(PaymentJournal::TIMEZONE)->year + 1, (int) ($this->jahr ?? 2026)));
|
||||
$max = $this->modus === 'quartal' ? 4 : 12;
|
||||
$this->nr = max(1, min($max, (int) ($this->nr ?? 1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
|
||||
*/
|
||||
private function range(): array
|
||||
{
|
||||
return PaymentJournal::range($this->modus, (int) $this->jahr, (int) $this->nr);
|
||||
}
|
||||
|
||||
public function zeitraumName(): string
|
||||
{
|
||||
$months = [1 => 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
|
||||
|
||||
return match ($this->modus) {
|
||||
'monat' => $months[(int) $this->nr].' '.$this->jahr,
|
||||
'quartal' => $this->nr.'. Quartal '.$this->jahr,
|
||||
default => 'Jahr '.$this->jahr,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function daten(): array
|
||||
{
|
||||
[$from, $to] = $this->range();
|
||||
$journal = app(PaymentJournal::class);
|
||||
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
|
||||
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
|
||||
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
|
||||
|
||||
return [
|
||||
'zeitraum' => $this->zeitraumName(),
|
||||
'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT),
|
||||
'anzahl' => $entries->count(),
|
||||
'angebote' => Offer::query()->orderBy('name')->pluck('name', 'id')->all(),
|
||||
'angebotName' => $offerId === null ? null : Offer::query()->find($offerId)?->name,
|
||||
'anteile' => $shares,
|
||||
'summen' => PaymentJournal::totals($entries, $shares),
|
||||
'nachBetrieb' => $journal->countByOperation($from, $to),
|
||||
'ohneAdresse' => $entries->filter(fn (LedgerEntry $entry): bool => $entry->kind === LedgerEntry::KIND_PAYMENT && empty(($entry->payer ?? [])['billing']))->count(),
|
||||
'nachgetragen' => $entries->where('derived', true)->count(),
|
||||
];
|
||||
}
|
||||
|
||||
public function exportieren(): StreamedResponse
|
||||
{
|
||||
abort_unless(ShopAccess::allowed(), 403);
|
||||
|
||||
[$from, $to] = $this->range();
|
||||
$journal = app(PaymentJournal::class);
|
||||
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
|
||||
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
|
||||
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
|
||||
$name = 'zahlungsjournal-'.match ($this->modus) {
|
||||
'monat' => $this->jahr.'-'.str_pad((string) $this->nr, 2, '0', STR_PAD_LEFT),
|
||||
'quartal' => $this->jahr.'-Q'.$this->nr,
|
||||
default => (string) $this->jahr,
|
||||
}.'-'.match ($this->betrieb) {
|
||||
'echt' => 'echt', 'test' => 'test', default => 'alle'
|
||||
}.($offerId === null ? '' : '-angebot-'.$offerId).'.csv';
|
||||
|
||||
return response()->streamDownload(function () use ($entries, $shares): void {
|
||||
echo PaymentJournal::csv($entries, $shares);
|
||||
}, $name, ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ class CombinationResource extends CompositionKindResource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Fachliche Kombinationen';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
|
||||
@@ -12,19 +12,26 @@
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\DocumentMeta;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EditorialWorkingDraft;
|
||||
use App\Domain\Catalog\ExerciseSections;
|
||||
use App\Domain\Catalog\ForeignCompositions;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\IdentityProfile;
|
||||
use App\Domain\Catalog\PdfTemplate;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Cms\Widgets\RenderContext;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\AssignsPillars;
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Filament\Support\ManagesDocumentChapters;
|
||||
use App\Filament\Support\ManagesEditorialSurface;
|
||||
use App\Filament\Support\ManagesRichFields;
|
||||
use App\Filament\Support\MediumForm;
|
||||
use App\Filament\Support\WidgetEditor;
|
||||
use App\Http\Controllers\ContentPreviewController;
|
||||
@@ -39,13 +46,16 @@
|
||||
use Filament\Support\Exceptions\Halt;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
abstract class EditComposition extends EditRecord
|
||||
{
|
||||
use AssignsPillars;
|
||||
use ManagesDocumentChapters;
|
||||
use ManagesEditorialSurface;
|
||||
use ManagesRichFields;
|
||||
use WithFileUploads;
|
||||
|
||||
protected string $view = 'filament.editorial.edit';
|
||||
@@ -68,6 +78,27 @@ abstract class EditComposition extends EditRecord
|
||||
|
||||
public string $materialNote = '';
|
||||
|
||||
/** @var list<array{key: string, name: string, description: string}> Durchführungsvarianten einer Übung */
|
||||
public array $variants = [];
|
||||
|
||||
public string $durationMax = '';
|
||||
|
||||
/** Dokumentfassung (ADR-51): Angaben für Titelseite und Impressum des PDF. Sie gehören zur Fassung. */
|
||||
public string $docSubtitle = '';
|
||||
|
||||
public string $docEdition = '';
|
||||
|
||||
public string $docPublished = '';
|
||||
|
||||
public string $docCopyright = '';
|
||||
|
||||
/** Die PDF-Vorlage des Dokuments („“ = bisheriges Layout). Wirkt sofort, ohne Fassung. */
|
||||
public string $pdfTemplateId = '';
|
||||
|
||||
public string $prerequisites = '';
|
||||
|
||||
public string $newVariantName = '';
|
||||
|
||||
public string $revisionNote = '';
|
||||
|
||||
public string $search = '';
|
||||
@@ -263,6 +294,10 @@ public function previewUrl(): ?string
|
||||
/** @var Composition $composition */
|
||||
$composition = $this->getRecord();
|
||||
|
||||
if ($this->isDocument()) {
|
||||
return $this->currentReadyVersion() === null && ! is_array($composition->working_draft) ? null : route('editorial.document-preview', ['composition' => $composition]);
|
||||
}
|
||||
|
||||
if (is_array($composition->working_draft) && $composition->working_draft !== []) {
|
||||
return route('editorial.draft-preview', ['composition' => $composition]);
|
||||
}
|
||||
@@ -356,8 +391,18 @@ public function redaktionKopf(): array
|
||||
|
||||
return [
|
||||
'art' => $this->hostLabel(),
|
||||
'fuer' => $program ? 'das Programm' : 'das Modul',
|
||||
'liste' => $program ? 'Programme' : 'Module',
|
||||
'fuer' => match (true) {
|
||||
$program => 'das Programm',
|
||||
$this->isDocument() => 'das Dokument',
|
||||
$this->isExercise() => 'die Übung',
|
||||
default => 'das Modul',
|
||||
},
|
||||
'liste' => match (true) {
|
||||
$program => 'Programme',
|
||||
$this->isDocument() => 'Dokumente',
|
||||
$this->isExercise() => 'Übungen',
|
||||
default => 'Module',
|
||||
},
|
||||
'zurueck' => 'Zurück zum Aufbau',
|
||||
'typ' => null,
|
||||
'umfang' => '„Redaktion speichern“ sichert Name, Texte, Präsentationsmedien und Einordnung. Aufbau, Lernziel, Zeit und Fassungen bleiben unverändert; offene Änderungen am Aufbau bleiben offen.',
|
||||
@@ -371,6 +416,31 @@ public function redaktionTitel(): string
|
||||
return $title !== '' ? $title : $this->hostLabel();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function richFelder(): array
|
||||
{
|
||||
return [
|
||||
'summary' => 'Kurzbeschreibung',
|
||||
'description' => 'Ausführliche Beschreibung',
|
||||
'learningGoal' => 'Lernziel',
|
||||
'materialNote' => $this->isExercise() ? 'Ausstattung' : 'Materialbedarf',
|
||||
'partBody' => 'Inhalt des Textes',
|
||||
'newTextBody' => 'Inhalt des neuen Textes',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte dürfen Bilder aus dem Medienbestand enthalten (gemeinsamer Picker); Kurzangaben nicht.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function richBilder(): array
|
||||
{
|
||||
return ['partBody', 'newTextBody'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
@@ -384,8 +454,8 @@ public function redaktionFelder(): array
|
||||
['id' => 'name', 'label' => 'Name in der Verwaltung', 'model' => 'designation', 'kind' => 'text', 'stored' => $stored('designation'), 'required' => true, 'hilfe' => 'Pflichtangabe. Erscheint in Listen der Verwaltung.'],
|
||||
['id' => 'titel', 'label' => 'Titel', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Namen.'],
|
||||
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser')],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 3, 'stored' => $stored('summary')],
|
||||
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'description', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Beschreibt das Angebot. Kein Lehrtext und kein Lernziel.'],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary')],
|
||||
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'description', 'kind' => 'rich', 'stored' => $stored('description'), 'hilfe' => 'Beschreibt das Angebot. Kein Lehrtext und kein Lernziel.'],
|
||||
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
|
||||
];
|
||||
}
|
||||
@@ -489,8 +559,173 @@ public function cancelText(): void
|
||||
$this->newTextBody = '';
|
||||
}
|
||||
|
||||
public function isExercise(): bool
|
||||
{
|
||||
return $this->hostKind() === CompositionKind::Exercise;
|
||||
}
|
||||
|
||||
public function addVariant(): void
|
||||
{
|
||||
$name = trim($this->newVariantName);
|
||||
|
||||
if ($name === '') {
|
||||
$this->feedback = 'Eine Variante braucht einen Namen.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$base = Str::slug($name) ?: 'variante';
|
||||
$key = $base;
|
||||
$n = 2;
|
||||
|
||||
while (in_array($key, array_column($this->variants, 'key'), true)) {
|
||||
$key = $base.'-'.$n++;
|
||||
}
|
||||
|
||||
$this->variants[] = ['key' => $key, 'name' => $name, 'description' => '', 'origin' => 'lokal'];
|
||||
$this->newVariantName = '';
|
||||
$this->feedback = 'Variante „'.$name.'“ ist angelegt. Ordne ihr Bestandteile zu. Gespeichert wird mit „Entwurf speichern“.';
|
||||
}
|
||||
|
||||
public function removeVariant(string $key): void
|
||||
{
|
||||
foreach ($this->members as $member) {
|
||||
if (($member['variant'] ?? null) === $key) {
|
||||
$this->feedback = 'Diese Variante hat noch Bestandteile. Ordne sie zuerst einer anderen Variante oder dem gemeinsamen Teil zu.';
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$this->variants = array_values(array_filter($this->variants, fn (array $variant): bool => $variant['key'] !== $key));
|
||||
$this->feedback = 'Die Variante ist aus diesem Entwurf genommen. Eine freigegebene Fassung bleibt unverändert.';
|
||||
}
|
||||
|
||||
public function setMemberVariant(int $index, string $key): void
|
||||
{
|
||||
if (! isset($this->members[$index])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->members[$index]['variant'] = $key === '' ? null : $key;
|
||||
}
|
||||
|
||||
public function setMemberRequirement(int $index, string $requirement): void
|
||||
{
|
||||
if (! isset($this->members[$index]) || ! in_array($requirement, ['erforderlich', 'ergaenzend'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->members[$index]['requirement'] = $requirement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Angebotene Varianten der eingebundenen Übungsfassung. Ohne Auswahl werden alle angeboten.
|
||||
*/
|
||||
public function toggleVariantSelection(int $index, string $key): void
|
||||
{
|
||||
if (! isset($this->members[$index])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$all = array_column($this->offeredVariants((string) ($this->members[$index]['target'] ?? '')), 'key');
|
||||
$current = $this->members[$index]['selection'] ?? null;
|
||||
$current = is_array($current) ? $current : $all;
|
||||
$current = in_array($key, $current, true) ? array_values(array_diff($current, [$key])) : [...$current, $key];
|
||||
|
||||
if ($current === []) {
|
||||
$this->feedback = 'Mindestens eine Variante muss angeboten werden.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->members[$index]['selection'] = count($current) === count($all) ? null : array_values($current);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, name: string}>
|
||||
*/
|
||||
public function offeredVariants(string $target): array
|
||||
{
|
||||
if (preg_match('/^composition:(\d+)$/', $target, $match) !== 1) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return CompositionVersion::query()->find((int) $match[1])?->variants
|
||||
->map(fn ($variant): array => ['key' => $variant->key, 'name' => $variant->name])
|
||||
->all() ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $member
|
||||
* @return array{variant: string|null, requirement: string, selection: list<string>|null, origin: string}
|
||||
*/
|
||||
private function memberExtras(array $member): array
|
||||
{
|
||||
$selection = $member['selection'] ?? null;
|
||||
|
||||
return [
|
||||
'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null,
|
||||
'requirement' => ($member['requirement'] ?? 'erforderlich') === 'ergaenzend' ? 'ergaenzend' : 'erforderlich',
|
||||
'selection' => is_array($selection) && $selection !== [] ? array_values(array_map('strval', $selection)) : null,
|
||||
'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, name: string, description: string}>
|
||||
*/
|
||||
private function normalizeVariants(mixed $variants): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (is_array($variants) ? $variants : [] as $variant) {
|
||||
if (is_array($variant) && trim((string) ($variant['key'] ?? '')) !== '') {
|
||||
$result[] = [
|
||||
'key' => trim((string) $variant['key']),
|
||||
'name' => trim((string) ($variant['name'] ?? '')),
|
||||
'description' => trim((string) ($variant['description'] ?? '')),
|
||||
'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rückfallschutz: Enthält dieser Aufbau (in einer Fassung oder im Entwurf) einen Bestandteil, den dieser Programmstand
|
||||
* nicht kennt, bleibt er schreibgeschützt. Der Editor könnte den Bestandteil sonst nicht laden und würde ihn beim
|
||||
* Speichern oder Freigeben still weglassen.
|
||||
*/
|
||||
public function schreibschutz(): ?string
|
||||
{
|
||||
$foreign = app(ForeignCompositions::class);
|
||||
$reason = 'Dieser Aufbau enthält einen Bestandteil aus einer neueren Programmversion. Er kann hier nur angesehen werden, damit nichts verloren geht.';
|
||||
|
||||
if ($foreign->compositionHasForeignMembers((int) $this->getRecord()->getKey())) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
$draft = app(EditorialWorkingDraft::class)->read($this->getRecord());
|
||||
|
||||
foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) {
|
||||
if (is_array($member) && $foreign->isForeignTarget((string) ($member['target'] ?? ''))) {
|
||||
return $reason;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function saveDraft(): void
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$minutes = $this->minutes($this->durationMinutes);
|
||||
|
||||
@@ -500,16 +735,35 @@ public function saveDraft(): void
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $this->persistChapterEdits()) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Composition $record */
|
||||
$record = $this->getRecord();
|
||||
app(EditorialWorkingDraft::class)->write($record, $this->payload());
|
||||
$this->feedback = 'Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
|
||||
$this->feedback = $this->isDocument()
|
||||
? 'Der Entwurf ist gespeichert, auch die Texte der Kapitel. Es entsteht keine neue Dokumentfassung.'
|
||||
: 'Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
|
||||
}
|
||||
|
||||
public function armRelease(): void
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->releaseArmed = false;
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if (! $this->persistChapterEdits()) {
|
||||
$this->releaseArmed = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->members === []) {
|
||||
$this->releaseArmed = false;
|
||||
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Entwurf kannst du schon speichern.';
|
||||
@@ -559,6 +813,11 @@ public function releaseFollowUp(): string
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($this->isDocument()) {
|
||||
return 'Module und Programme binden eine Dokumentfassung über „Hinzufügen“ ein; ein Stand schreibt sie dann fest. Frühere Fassungen bleiben dort, wo sie eingebunden sind, unverändert.'
|
||||
.(is_array($this->getRecord()->working_draft) && $this->getRecord()->working_draft !== [] ? ' Es gibt einen gespeicherten Entwurf neben der bereitgestellten Fassung.' : ' Es gibt keinen offenen Entwurf.');
|
||||
}
|
||||
|
||||
/** @var Composition $composition */
|
||||
$composition = $this->getRecord();
|
||||
$releases = app(CompositionDisplayRelease::class);
|
||||
@@ -585,10 +844,17 @@ protected function selectFirstPart(): void
|
||||
|
||||
public function discardDraft(): void
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Composition $record */
|
||||
$record = $this->getRecord();
|
||||
app(EditorialWorkingDraft::class)->clear($record);
|
||||
$this->releaseArmed = false;
|
||||
$this->chapterEdits = [];
|
||||
$this->loadAufbau();
|
||||
$this->selected = null;
|
||||
$this->selectFirstPart();
|
||||
@@ -634,6 +900,12 @@ public function includeNeedsRelease(): bool
|
||||
|
||||
public function moveTo(int $from, int $to): void
|
||||
{
|
||||
if ($this->isDocument()) {
|
||||
$this->moveChapterTo($from, $to);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$count = count($this->members);
|
||||
|
||||
@@ -924,7 +1196,7 @@ private function includePart(string $target, bool $allowDraft): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($this->members as $index => $member) {
|
||||
foreach ($this->isExercise() ? [] : $this->members as $index => $member) {
|
||||
if (($member['target'] ?? '') === $target) {
|
||||
$this->selected = $index;
|
||||
$this->panel = 'bestandteil';
|
||||
@@ -944,6 +1216,7 @@ private function includePart(string $target, bool $allowDraft): bool
|
||||
|
||||
$row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']);
|
||||
$row['note'] = '';
|
||||
$row = [...$row, ...$this->memberExtras([])];
|
||||
$this->members[] = $row;
|
||||
$this->members = array_values($this->members);
|
||||
$this->selected = array_key_last($this->members);
|
||||
@@ -965,6 +1238,11 @@ public function removePart(int $index): void
|
||||
}
|
||||
|
||||
$title = (string) ($this->members[$index]['title'] ?? 'Der Bestandteil');
|
||||
|
||||
if ($this->isDocument()) {
|
||||
$this->forgetChapter($index);
|
||||
}
|
||||
|
||||
unset($this->members[$index]);
|
||||
$this->members = array_values($this->members);
|
||||
$this->selected = $this->members === [] ? null : min($index, count($this->members) - 1);
|
||||
@@ -987,7 +1265,9 @@ protected function extraConfirmation(string $aktion, int|string|null $argument):
|
||||
'aktion' => $aktion,
|
||||
'argument' => (int) $argument,
|
||||
'titel' => '„'.$title.'“ aus diesem Aufbau entfernen?',
|
||||
'text' => 'Nur diese Verwendung wird entfernt. Das Medium oder Modul bleibt im Bestand und in anderen Aufbauten. Gespeichert wird das mit „Entwurf speichern“.',
|
||||
'text' => $this->isDocument()
|
||||
? 'Nur dieses Kapitel wird aus dem Dokument genommen; seine Unterkapitel bleiben und gehören dann zum Kapitel davor. Der Text bleibt im Medienbestand, ungespeicherte Eingaben zu diesem Kapitel entfallen. Gespeichert wird das mit „Entwurf speichern“.'
|
||||
: 'Nur diese Verwendung wird entfernt. Das Medium oder Modul bleibt im Bestand und in anderen Aufbauten. Gespeichert wird das mit „Entwurf speichern“.',
|
||||
'label' => 'Aus dem Aufbau entfernen',
|
||||
'gefahr' => true,
|
||||
];
|
||||
@@ -1002,6 +1282,12 @@ protected function runExtraConfirmation(string $aktion, int|string|null $argumen
|
||||
|
||||
public function movePart(int $index, int $direction): void
|
||||
{
|
||||
if ($this->isDocument()) {
|
||||
$this->moveChapter($index, $direction);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$target = $index + $direction;
|
||||
|
||||
@@ -1034,6 +1320,7 @@ public function useVersion(int $index, string $target): void
|
||||
$this->commitRoleDraft();
|
||||
$row['role'] = $this->members[$index]['role'] ?? $row['kind'];
|
||||
$row['note'] = $this->members[$index]['note'] ?? '';
|
||||
$row = [...$row, ...$this->memberExtras($this->members[$index])];
|
||||
$this->members[$index] = $row;
|
||||
$this->syncRoleDraft();
|
||||
$this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Der Entwurf speichert das. Eine freigegebene Fassung bleibt unverändert.';
|
||||
@@ -1057,7 +1344,7 @@ public function loadTemplate(int $versionId): void
|
||||
public function addText(): void
|
||||
{
|
||||
$title = trim($this->newTextTitle);
|
||||
$body = trim($this->newTextBody);
|
||||
$body = FormattedText::canonical($this->newTextBody);
|
||||
|
||||
if ($title === '' || $body === '') {
|
||||
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
|
||||
@@ -1069,6 +1356,11 @@ public function addText(): void
|
||||
$service = app(ContentService::class);
|
||||
$element = $service->createElement('text', 'text', $title);
|
||||
$version = $service->draftElementVersion($element, $body);
|
||||
|
||||
// Ein Abschnitt, der im Übungseditor entsteht, gehört zu dieser Übung (Materialart „Übungsabschnitt“).
|
||||
if ($this->isExercise()) {
|
||||
app(ExerciseSections::class)->mark($element, $this->getRecord());
|
||||
}
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedback = $exception->getMessage();
|
||||
|
||||
@@ -1387,7 +1679,7 @@ private function writePartText(): string|false
|
||||
}
|
||||
|
||||
$title = trim($this->partTitle);
|
||||
$body = trim($this->partBody);
|
||||
$body = FormattedText::canonical($this->partBody);
|
||||
|
||||
if ($title === '' || $body === '') {
|
||||
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
|
||||
@@ -1407,7 +1699,7 @@ private function writePartText(): string|false
|
||||
return false;
|
||||
}
|
||||
|
||||
$changed = $title !== (string) ($member['title'] ?? '') || $body !== trim((string) $version->body);
|
||||
$changed = $title !== (string) ($member['title'] ?? '') || ! FormattedText::same($body, $version->body);
|
||||
|
||||
if (! $changed) {
|
||||
return '';
|
||||
@@ -1514,6 +1806,11 @@ public function presentationChips(): array
|
||||
{
|
||||
/** @var Composition $composition */
|
||||
$composition = $this->getRecord();
|
||||
|
||||
// Ein Dokument erscheint nie als eigene Karte in der Bibliothek; es wird in Module und Programme eingebunden.
|
||||
if ($this->isDocument()) {
|
||||
return [];
|
||||
}
|
||||
$offered = in_array($composition->id, app(EditorialCatalog::class)->offeredCompositionIds(), true);
|
||||
|
||||
return app(EditorialCatalog::class)->statusChips($composition, $offered);
|
||||
@@ -1521,8 +1818,18 @@ public function presentationChips(): array
|
||||
|
||||
public function publishRevision(): bool
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if (! $this->persistChapterEdits()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->members === []) {
|
||||
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Kurzbeschreibung kannst du schon speichern.';
|
||||
|
||||
@@ -1558,11 +1865,15 @@ public function publishRevision(): bool
|
||||
$this->actor(),
|
||||
$note !== '' ? $note : null,
|
||||
[
|
||||
'learning_goal' => $this->blank($this->learningGoal),
|
||||
'learning_goal' => $this->richBlank('learningGoal'),
|
||||
'duration_minutes' => $minutes,
|
||||
'material_note' => $this->blank($this->materialNote),
|
||||
'duration_max' => $this->blank($this->durationMax),
|
||||
'material_note' => $this->richBlank('materialNote'),
|
||||
'prerequisites' => $this->blank($this->prerequisites),
|
||||
'document_meta' => $this->documentMetaNow(),
|
||||
],
|
||||
$this->releaseConsent,
|
||||
$this->normalizeVariants($this->variants),
|
||||
);
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedback = $exception->getMessage();
|
||||
@@ -1579,7 +1890,9 @@ public function publishRevision(): bool
|
||||
$this->loadEditor();
|
||||
$released = $this->currentReadyVersion();
|
||||
$number = $released instanceof CompositionVersion ? $released->number : '';
|
||||
$this->feedback = 'Fassung '.$number.' ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.';
|
||||
$this->feedback = $this->isDocument()
|
||||
? 'Dokumentfassung '.$number.' ist bereitgestellt. Der Entwurf ist geschlossen, frühere Fassungen bleiben erhalten. Ein Modul oder Programm bindet sie über „Hinzufügen“ ein; bestehende Stände ändern sich dadurch nicht.'
|
||||
: 'Fassung '.$number.' ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.';
|
||||
|
||||
if ($this->returnAfterRelease) {
|
||||
$this->returnAfterRelease = false;
|
||||
@@ -1677,9 +1990,11 @@ protected function loadAufbau(): void
|
||||
$this->thumbnailError = $composition->thumbnail_error;
|
||||
$this->thumbnailSource = $composition->thumbnail_source;
|
||||
$this->imageCaptionText = $this->captionFor($composition->thumbnail_source);
|
||||
$this->pdfTemplateId = $composition->pdf_template_id === null ? '' : (string) $composition->pdf_template_id;
|
||||
$this->catalogScope = match ($this->hostKind()) {
|
||||
CompositionKind::Kurs => 'module',
|
||||
CompositionKind::Uebung => 'medien',
|
||||
CompositionKind::Uebung => 'uebungen',
|
||||
CompositionKind::Exercise => 'medien',
|
||||
default => 'alles',
|
||||
};
|
||||
|
||||
@@ -1693,9 +2008,13 @@ protected function loadAufbau(): void
|
||||
|
||||
if ($version === null) {
|
||||
$this->members = [];
|
||||
$this->variants = [];
|
||||
$this->durationMax = '';
|
||||
$this->prerequisites = '';
|
||||
$this->learningGoal = '';
|
||||
$this->durationMinutes = '';
|
||||
$this->materialNote = '';
|
||||
$this->fillDocumentMeta(null);
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -1726,13 +2045,19 @@ protected function applyDraft(array $draft): void
|
||||
|
||||
$row['role'] = (string) ($member['role'] ?? $row['kind']);
|
||||
$row['note'] = trim((string) ($member['note'] ?? ''));
|
||||
$row = [...$row, ...$this->memberExtras($member)];
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
$this->members = $rows;
|
||||
$this->slimChapterMembers();
|
||||
$this->variants = $this->normalizeVariants($draft['variants'] ?? []);
|
||||
$this->durationMax = ($draft['duration_max'] ?? null) === null ? '' : (string) $draft['duration_max'];
|
||||
$this->prerequisites = (string) ($draft['prerequisites'] ?? '');
|
||||
$this->learningGoal = (string) ($draft['learning_goal'] ?? '');
|
||||
$this->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes'];
|
||||
$this->materialNote = (string) ($draft['material_note'] ?? '');
|
||||
$this->fillDocumentMeta($draft['document_meta'] ?? null);
|
||||
$this->revisionNote = (string) ($draft['revision_note'] ?? '');
|
||||
$this->selected = null;
|
||||
$this->roleDraft = '';
|
||||
@@ -1747,9 +2072,16 @@ protected function applyDraft(array $draft): void
|
||||
protected function applyVersion(CompositionVersion $version): void
|
||||
{
|
||||
$this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
|
||||
$this->slimChapterMembers();
|
||||
$this->variants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
|
||||
])->all());
|
||||
$this->durationMax = $version->duration_max === null ? '' : (string) $version->duration_max;
|
||||
$this->prerequisites = (string) ($version->prerequisites ?? '');
|
||||
$this->learningGoal = (string) ($version->learning_goal ?? '');
|
||||
$this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes;
|
||||
$this->materialNote = (string) ($version->material_note ?? '');
|
||||
$this->fillDocumentMeta($version->document_meta);
|
||||
$this->selected = null;
|
||||
$this->roleDraft = '';
|
||||
$this->noteDraft = '';
|
||||
@@ -1767,6 +2099,13 @@ protected function commitRoleDraft(?string $value = null): void
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->isDocument()) {
|
||||
// Ein Kapitel hat keine freie Rolle: Die Ebene steht fest; offene Eingaben des Kapitels bleiben erhalten.
|
||||
$this->stashChapter();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->members[$this->selected]['role'] = trim($value ?? $this->roleDraft);
|
||||
$this->members[$this->selected]['note'] = trim($this->noteDraft);
|
||||
}
|
||||
@@ -1776,6 +2115,13 @@ protected function syncRoleDraft(): void
|
||||
$member = $this->selected !== null ? ($this->members[$this->selected] ?? null) : null;
|
||||
$this->roleDraft = is_array($member) ? (string) ($member['role'] ?? '') : '';
|
||||
$this->noteDraft = is_array($member) ? (string) ($member['note'] ?? '') : '';
|
||||
|
||||
if ($this->isDocument()) {
|
||||
$this->loadChapterFields();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->partTitle = is_array($member) ? (string) ($member['title'] ?? '') : '';
|
||||
$this->partBody = is_array($member) ? (string) ($member['body'] ?? '') : '';
|
||||
}
|
||||
@@ -1833,22 +2179,85 @@ protected function needsRevision(): bool
|
||||
|
||||
protected function sameMembers(CompositionVersion $version): bool
|
||||
{
|
||||
$version->loadMissing('members');
|
||||
$version->loadMissing('members.variant');
|
||||
$current = $version->members->map(function ($member): string {
|
||||
$target = $member->content_element_version_id
|
||||
? 'element:'.$member->content_element_version_id
|
||||
: 'composition:'.$member->nested_composition_version_id;
|
||||
|
||||
return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? ''));
|
||||
return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? ''))
|
||||
.'|'.($member->variant?->key ?? '').'|'.($member->requirement ?: 'erforderlich').'|'.json_encode($member->variant_selection);
|
||||
})->all();
|
||||
$next = array_values(array_map(
|
||||
fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')),
|
||||
$this->members,
|
||||
));
|
||||
$next = array_values(array_map(function (array $member): string {
|
||||
$extras = $this->memberExtras($member);
|
||||
|
||||
return trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? ''))
|
||||
.'|'.($extras['variant'] ?? '').'|'.$extras['requirement'].'|'.json_encode($extras['selection']);
|
||||
}, $this->members));
|
||||
|
||||
return $current === $next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Angaben der Dokumentfassung im Arbeitsstand; nur bei einem Dokument, sonst null.
|
||||
*
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
protected function documentMetaNow(): ?array
|
||||
{
|
||||
if (! $this->isDocument()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return DocumentMeta::normalize([
|
||||
'subtitle' => $this->docSubtitle,
|
||||
'edition' => $this->docEdition,
|
||||
'published_on' => $this->docPublished,
|
||||
'copyright' => $this->docCopyright,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function fillDocumentMeta(mixed $meta): void
|
||||
{
|
||||
$meta = DocumentMeta::normalize($meta) ?? [];
|
||||
$this->docSubtitle = $meta['subtitle'] ?? '';
|
||||
$this->docEdition = $meta['edition'] ?? '';
|
||||
$this->docPublished = $meta['published_on'] ?? '';
|
||||
$this->docCopyright = $meta['copyright'] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Die wählbaren PDF-Vorlagen für Dokumente.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function pdfTemplateOptions(): array
|
||||
{
|
||||
return PdfTemplate::query()->where('kind', PdfTemplate::KIND_DOCUMENT)->orderBy('name')->pluck('name', 'id')
|
||||
->mapWithKeys(fn (string $name, int|string $id): array => [(string) $id => $name])->all();
|
||||
}
|
||||
|
||||
/** Ordnet dem Dokument eine PDF-Vorlage zu. Das gilt sofort für jedes PDF dieses Dokuments, auch für ältere Fassungen. */
|
||||
public function savePdfTemplate(): void
|
||||
{
|
||||
$this->guardEditorial();
|
||||
$id = ctype_digit($this->pdfTemplateId) ? (int) $this->pdfTemplateId : null;
|
||||
|
||||
if ($id !== null && ! PdfTemplate::query()->where('kind', PdfTemplate::KIND_DOCUMENT)->whereKey($id)->exists()) {
|
||||
$this->feedback = 'Diese PDF-Vorlage gibt es nicht mehr.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var Composition $composition */
|
||||
$composition = $this->getRecord();
|
||||
$composition->pdf_template_id = $id;
|
||||
$composition->save();
|
||||
$this->feedback = $id === null
|
||||
? 'Das Dokument verwendet wieder das einfache PDF-Layout ohne Titelseite.'
|
||||
: 'Die PDF-Vorlage ist zugeordnet. Sie gilt sofort für jedes PDF dieses Dokuments, auch für ältere Fassungen; Ausgabe, Datum und Vermerk bleiben je Fassung.';
|
||||
}
|
||||
|
||||
protected function didacticChanged(CompositionVersion $version): bool
|
||||
{
|
||||
$minutes = $this->minutes($this->durationMinutes);
|
||||
@@ -1859,8 +2268,16 @@ protected function didacticChanged(CompositionVersion $version): bool
|
||||
|
||||
$storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes;
|
||||
|
||||
return $version->learning_goal !== $this->blank($this->learningGoal)
|
||||
|| $version->material_note !== $this->blank($this->materialNote)
|
||||
$storedVariants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
|
||||
])->all());
|
||||
|
||||
return ! FormattedText::same($version->learning_goal, $this->learningGoal)
|
||||
|| ! FormattedText::same($version->material_note, $this->materialNote)
|
||||
|| $version->prerequisites !== $this->blank($this->prerequisites)
|
||||
|| ($version->duration_max === null ? null : (string) $version->duration_max) !== $this->blank($this->durationMax)
|
||||
|| $storedVariants !== $this->normalizeVariants($this->variants)
|
||||
|| DocumentMeta::normalize($version->document_meta) !== $this->documentMetaNow()
|
||||
|| $storedMinutes !== $minutes;
|
||||
}
|
||||
|
||||
@@ -1881,6 +2298,14 @@ protected function minutes(string $value): int|false|null
|
||||
return $minutes > 0 ? $minutes : false;
|
||||
}
|
||||
|
||||
/** Formatierte Eigenschaft in kanonischer Form für das Speichern; leer wird null. */
|
||||
protected function richBlank(string $name): ?string
|
||||
{
|
||||
$value = $this->richWert($name);
|
||||
|
||||
return $value === '' ? null : $value;
|
||||
}
|
||||
|
||||
protected function blank(string $value): ?string
|
||||
{
|
||||
$value = trim($value);
|
||||
@@ -1915,9 +2340,9 @@ protected function persistRedaktion(): bool
|
||||
app(IdentityProfile::class)->fill($record, [
|
||||
'display_title' => $this->displayTitle,
|
||||
'teaser' => $this->teaser,
|
||||
'summary' => $this->summary,
|
||||
'summary' => $this->richStore('summary', $record->summary),
|
||||
'search_terms' => $this->searchTerms,
|
||||
'description' => $this->description,
|
||||
'description' => $this->richStore('description', $record->description),
|
||||
], $this->actor());
|
||||
$this->syncDimensions($record, array_map(intval(...), $this->dimensionIds));
|
||||
$this->persistPillarIds($record);
|
||||
@@ -1929,6 +2354,12 @@ protected function persistRedaktion(): bool
|
||||
|
||||
protected function persistDraft(): bool
|
||||
{
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->minutes($this->durationMinutes) === false) {
|
||||
$this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.';
|
||||
|
||||
@@ -2062,15 +2493,22 @@ protected function payload(): array
|
||||
$minutes = $this->minutes($this->durationMinutes);
|
||||
|
||||
return [
|
||||
'learning_goal' => $this->blank($this->learningGoal),
|
||||
'learning_goal' => $this->richBlank('learningGoal'),
|
||||
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
|
||||
'material_note' => $this->blank($this->materialNote),
|
||||
'material_note' => $this->richBlank('materialNote'),
|
||||
'duration_max' => $this->blank($this->durationMax),
|
||||
'prerequisites' => $this->blank($this->prerequisites),
|
||||
'variants' => $this->normalizeVariants($this->variants),
|
||||
'revision_note' => $this->blank($this->revisionNote),
|
||||
'document_meta' => $this->documentMetaNow(),
|
||||
// Ungespeicherte Texte der Kapitel gelten als Änderung des Entwurfs; nach dem Speichern sind sie leer.
|
||||
'chapters' => $this->chapterEditsNow(),
|
||||
'members' => array_values(array_map(
|
||||
fn (array $member): array => [
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'target' => (string) ($member['target'] ?? ''),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
...$this->memberExtras($member),
|
||||
],
|
||||
$members,
|
||||
)),
|
||||
@@ -2105,7 +2543,11 @@ protected function readyPayload(): array
|
||||
'learning_goal' => null,
|
||||
'duration_minutes' => null,
|
||||
'material_note' => null,
|
||||
'duration_max' => null,
|
||||
'prerequisites' => null,
|
||||
'variants' => [],
|
||||
'revision_note' => null,
|
||||
'document_meta' => null,
|
||||
'members' => [],
|
||||
];
|
||||
}
|
||||
@@ -2116,12 +2558,19 @@ protected function readyPayload(): array
|
||||
'learning_goal' => $version->learning_goal,
|
||||
'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes,
|
||||
'material_note' => $version->material_note,
|
||||
'duration_max' => $version->duration_max === null ? null : (string) $version->duration_max,
|
||||
'prerequisites' => $version->prerequisites,
|
||||
'variants' => $this->normalizeVariants($version->variants->map(fn ($variant): array => [
|
||||
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
|
||||
])->all()),
|
||||
'revision_note' => null,
|
||||
'document_meta' => DocumentMeta::normalize($version->document_meta),
|
||||
'members' => array_values(array_map(
|
||||
fn (array $row): array => [
|
||||
'role' => trim((string) ($row['role'] ?? '')),
|
||||
'target' => (string) ($row['target'] ?? ''),
|
||||
'note' => trim((string) ($row['note'] ?? '')),
|
||||
...$this->memberExtras($row),
|
||||
],
|
||||
$rows,
|
||||
)),
|
||||
@@ -2145,14 +2594,21 @@ protected function normalizePayload(array $payload): array
|
||||
'role' => trim((string) ($member['role'] ?? '')),
|
||||
'target' => (string) ($member['target'] ?? ''),
|
||||
'note' => trim((string) ($member['note'] ?? '')),
|
||||
...$this->memberExtras($member),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'learning_goal' => $payload['learning_goal'] ?? null,
|
||||
// Formatierte Angaben nur in kanonischer Form vergleichen: Klartext des Altbestands und dasselbe als HTML sind gleich.
|
||||
'learning_goal' => FormattedText::canonical($payload['learning_goal'] ?? null) ?: null,
|
||||
'duration_minutes' => $payload['duration_minutes'] ?? null,
|
||||
'material_note' => $payload['material_note'] ?? null,
|
||||
'material_note' => FormattedText::canonical($payload['material_note'] ?? null) ?: null,
|
||||
'duration_max' => isset($payload['duration_max']) && $payload['duration_max'] !== '' ? (string) $payload['duration_max'] : null,
|
||||
'prerequisites' => $payload['prerequisites'] ?? null,
|
||||
'variants' => $this->normalizeVariants($payload['variants'] ?? []),
|
||||
'revision_note' => $payload['revision_note'] ?? null,
|
||||
'document_meta' => DocumentMeta::normalize($payload['document_meta'] ?? null),
|
||||
'chapters' => is_array($payload['chapters'] ?? null) ? $payload['chapters'] : [],
|
||||
'members' => $members,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Filament\Pages\Uebernahme;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\ListsCompositions;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
@@ -33,14 +34,12 @@ protected function fixedKind(): ?CompositionKind
|
||||
|
||||
private function onDesk(): bool
|
||||
{
|
||||
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung], true);
|
||||
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise, CompositionKind::Document], true);
|
||||
}
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
$desk = $this->onDesk() ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : '';
|
||||
|
||||
return $this->kind()->deskExplanation().$desk;
|
||||
return $this->kind()->deskExplanation();
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
@@ -55,6 +54,18 @@ public function content(Schema $schema): Schema
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
if ($this->kind() === CompositionKind::Exercise) {
|
||||
return [
|
||||
$this->createCompositionAction($this->kind()),
|
||||
Action::make('shinkan')
|
||||
->label('Aus Shinkan übernehmen')
|
||||
->icon('heroicon-o-arrow-down-tray')
|
||||
->color('gray')
|
||||
->visible(fn (): bool => ContentElementResource::editor())
|
||||
->url(fn (): string => Uebernahme::getUrl()),
|
||||
];
|
||||
}
|
||||
|
||||
if ($this->onDesk()) {
|
||||
return [$this->createCompositionAction($this->kind())];
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ class ContentElementResource extends Resource
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?string $navigationLabel = 'Medien';
|
||||
protected static ?string $navigationLabel = 'Contentmanager';
|
||||
|
||||
protected static ?string $slug = 'contentmanager';
|
||||
|
||||
protected static ?string $modelLabel = 'Medium';
|
||||
|
||||
@@ -32,7 +34,7 @@ class ContentElementResource extends Resource
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'working_title';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\IdentityProfile;
|
||||
@@ -19,13 +21,13 @@
|
||||
use App\Filament\Support\ElementRevision;
|
||||
use App\Filament\Support\MediumForm;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Filament\Support\RichField;
|
||||
use App\Jobs\DeriveThumbnail;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\Placeholder;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
@@ -71,7 +73,7 @@ public function form(Schema $schema): Schema
|
||||
...MediumForm::fields(creating: false, element: $element),
|
||||
TextInput::make('display_title')->label('Anzeigetitel')
|
||||
->helperText('Erscheint in der Bibliothek. Leer lässt den Arbeitstitel stehen. Speichern legt keine Fassung an.'),
|
||||
Textarea::make('summary')->label('Kurzbeschreibung')->rows(3),
|
||||
RichField::make('summary', 'Kurzbeschreibung', live: false),
|
||||
Select::make('editorial_content_kind_id')
|
||||
->label('Fachliche Materialart')
|
||||
->options(fn (): array => app(EditorialVocabulary::class)->kindOptions('medium', $this->getRecord()->editorial_content_kind_id !== null ? (int) $this->getRecord()->editorial_content_kind_id : null))
|
||||
@@ -194,12 +196,12 @@ protected function mutateFormDataBeforeFill(array $data): array
|
||||
return [
|
||||
'working_title' => $this->getRecord()->working_title,
|
||||
'thumbnail_alt' => $this->getRecord()->thumbnail_alt,
|
||||
'body' => $this->getRecord()->versions()->orderByDesc('number')->first()?->body,
|
||||
'body' => EmbeddedImages::forEditor($this->getRecord()->versions()->orderByDesc('number')->first()?->body),
|
||||
'display_title' => $this->getRecord()->display_title,
|
||||
'description' => $this->getRecord()->description,
|
||||
'description' => FormattedText::html($this->getRecord()->description),
|
||||
'usage_note' => $this->getRecord()->usage_note,
|
||||
'license_note' => $this->getRecord()->license_note,
|
||||
'summary' => $this->getRecord()->summary,
|
||||
'summary' => FormattedText::html($this->getRecord()->summary),
|
||||
'editorial_content_kind_id' => $this->getRecord()->editorial_content_kind_id,
|
||||
'dimension_ids' => IdentityDimensionValue::query()
|
||||
->where('subject_type', $this->getRecord()->getMorphClass())
|
||||
@@ -218,10 +220,15 @@ protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
/** @var ContentElement $record */
|
||||
try {
|
||||
app(ContentService::class)->describe($record, (string) $data['working_title'], $data['description'] ?? null);
|
||||
$description = FormattedText::same((string) ($data['description'] ?? ''), $record->description)
|
||||
? $record->description
|
||||
: (FormattedText::canonical((string) ($data['description'] ?? '')) ?: null);
|
||||
app(ContentService::class)->describe($record, (string) $data['working_title'], $description);
|
||||
app(IdentityProfile::class)->fill($record, [
|
||||
'display_title' => $data['display_title'] ?? null,
|
||||
'summary' => $data['summary'] ?? null,
|
||||
'summary' => FormattedText::same((string) ($data['summary'] ?? ''), $record->summary)
|
||||
? $record->summary
|
||||
: (FormattedText::canonical((string) ($data['summary'] ?? '')) ?: null),
|
||||
'usage_note' => $data['usage_note'] ?? null,
|
||||
'license_note' => $data['license_note'] ?? null,
|
||||
'thumbnail_alt' => $data['thumbnail_alt'] ?? null,
|
||||
@@ -229,8 +236,8 @@ protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
if ($record->output_class === 'text' && is_string($data['body'] ?? null)) {
|
||||
$latest = $record->versions()->orderByDesc('number')->first();
|
||||
|
||||
if ($latest instanceof ContentElementVersion) {
|
||||
app(ContentService::class)->reviseElementContent($latest, $data['body']);
|
||||
if ($latest instanceof ContentElementVersion && ! FormattedText::same($data['body'], $latest->body)) {
|
||||
app(ContentService::class)->reviseElementContent($latest, FormattedText::canonical($data['body']));
|
||||
}
|
||||
}
|
||||
if (array_key_exists('editorial_content_kind_id', $data)) {
|
||||
|
||||
@@ -6,11 +6,15 @@
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Support\Bestand;
|
||||
use App\Filament\Support\MaterialKindSelection;
|
||||
use App\Filament\Support\MediaLibrary;
|
||||
use App\Filament\Support\MediumForm;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Filament\Support\ShowsBestand;
|
||||
use App\Models\UserViewDefault;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Schemas\Components\RenderHook;
|
||||
use Filament\Schemas\Components\View;
|
||||
@@ -55,9 +59,34 @@ class ListContentElements extends ListRecords
|
||||
#[Url(as: 'saeule', except: '')]
|
||||
public string $saeule = '';
|
||||
|
||||
/** Frühere Adresse mit einer einzelnen Materialart (zum Beispiel aus den Stammdaten); wird zu `arten`. */
|
||||
#[Url(as: 'inhaltsart', except: '')]
|
||||
public string $inhaltsart = '';
|
||||
|
||||
/**
|
||||
* Mehrfachauswahl der fachlichen Materialarten (MaterialKindSelection). Leer heißt: allgemeine Startansicht, also
|
||||
* alle Materialarten und Medien ohne Materialart, aber ohne Übungsabschnitte.
|
||||
*/
|
||||
#[Url(as: 'arten', except: '')]
|
||||
public string $arten = '';
|
||||
|
||||
/** Der Filterdialog ist offen. */
|
||||
public bool $filterOffen = false;
|
||||
|
||||
/** Das Filterfeld, bei dem der Dialog beginnt (leer: beim ersten Feld). */
|
||||
public string $filterFokus = '';
|
||||
|
||||
/**
|
||||
* Arbeitsstand des Dialogs: die Auswahl seit dem Öffnen. Erst „Anwenden“ übernimmt sie in die Filter der Liste,
|
||||
* „Abbrechen“ verwirft sie.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
public array $filterDraft = [];
|
||||
|
||||
/** Filterfelder mit mehreren Werten (ODER); verschiedene Felder gelten zusammen (UND). */
|
||||
private const MULTI_FIELDS = ['art', 'freigabe', 'nutzung'];
|
||||
|
||||
#[Url(as: 'einordnung', except: '')]
|
||||
public string $einordnung = '';
|
||||
|
||||
@@ -67,6 +96,27 @@ class ListContentElements extends ListRecords
|
||||
#[Url(as: 'archiv', except: 'aktiv')]
|
||||
public string $archiv = 'aktiv';
|
||||
|
||||
/** Eigenschaften, die der persönliche Standard festhält. Die Suche gehört nicht dazu: Sie ist Teil der Arbeit, kein Zustand der Ansicht. */
|
||||
private const DEFAULT_FILTERS = ['arten', 'art', 'freigabe', 'schutz', 'entwurf', 'fassung', 'nutzung', 'saeule', 'einordnung', 'verarbeitung', 'archiv', 'ansicht'];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
parent::mount();
|
||||
|
||||
if ($this->inhaltsart !== '' && $this->arten === '') {
|
||||
$this->arten = ctype_digit($this->inhaltsart) ? MaterialKindSelection::encode([MaterialKindSelection::key((int) $this->inhaltsart)]) : '';
|
||||
}
|
||||
|
||||
$this->inhaltsart = '';
|
||||
|
||||
// Ohne eigene Vorgaben in der Adresse startet der Medienmanager mit dem persönlichen Standard.
|
||||
$given = array_intersect(array_keys(request()->query()), ['suche', 'ansicht', 'art', 'arten', 'inhaltsart', 'freigabe', 'schutz', 'entwurf', 'fassung', 'nutzung', 'saeule', 'einordnung', 'verarbeitung', 'archiv']);
|
||||
|
||||
if ($given === [] && ($saved = $this->savedDefault()) !== null) {
|
||||
$this->applyFilters($saved);
|
||||
}
|
||||
}
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Die Dateien und Texte. Ein Modul oder ein Programm verweist auf eine Fassung; die Datei wird nicht für jede Verwendung neu hochgeladen.';
|
||||
@@ -88,7 +138,7 @@ public function content(Schema $schema): Schema
|
||||
|
||||
protected function bestandFilterEigenschaften(): array
|
||||
{
|
||||
return ['suche', 'art', 'schutz', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv'];
|
||||
return ['suche', 'art', 'arten', 'schutz', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv'];
|
||||
}
|
||||
|
||||
public function showingList(): bool
|
||||
@@ -128,14 +178,6 @@ public function classificationOptions(): array
|
||||
return app(MediaLibrary::class)->classifications(ctype_digit($this->einordnung) ? [(int) $this->einordnung] : []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function contentKindOptions(): array
|
||||
{
|
||||
return app(EditorialVocabulary::class)->kindFilterOptions('medium', $this->inhaltsart);
|
||||
}
|
||||
|
||||
public function filtersActive(): bool
|
||||
{
|
||||
return trim($this->suche) !== ''
|
||||
@@ -147,7 +189,7 @@ public function filtersActive(): bool
|
||||
|| $this->nutzung !== ''
|
||||
|| $this->saeule !== ''
|
||||
|| $this->einordnung !== ''
|
||||
|| $this->inhaltsart !== ''
|
||||
|| $this->arten !== ''
|
||||
|| $this->verarbeitung !== ''
|
||||
|| $this->archiv !== 'aktiv';
|
||||
}
|
||||
@@ -164,13 +206,346 @@ public function resetFilters(): void
|
||||
$this->saeule = '';
|
||||
$this->einordnung = '';
|
||||
$this->inhaltsart = '';
|
||||
$this->arten = '';
|
||||
$this->verarbeitung = '';
|
||||
$this->archiv = 'aktiv';
|
||||
$this->bestandGrenze = Bestand::SCHRITT;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Materialarten und persönlicher Standard
|
||||
|
||||
/**
|
||||
* Gemeinsame Bestandsliste: Suche und häufige Filter sichtbar, die übrigen unter „Weitere Filter“.
|
||||
* Die wählbaren Materialarten mit Schlüssel: die Arten der redaktionellen Stammdaten, „Übungsabschnitt“ und „Ohne
|
||||
* Materialart“.
|
||||
*
|
||||
* @return array<string, array{label: string, automatic: bool}>
|
||||
*/
|
||||
public function artChoices(): array
|
||||
{
|
||||
$chosen = array_map(
|
||||
fn (string $key): int => (int) substr($key, 1),
|
||||
array_filter(MaterialKindSelection::decode($this->arten) ?? [], fn (string $key): bool => $key !== MaterialKindSelection::WITHOUT),
|
||||
);
|
||||
$choices = [];
|
||||
|
||||
foreach (app(EditorialVocabulary::class)->mediumKindChoices(array_values($chosen)) as $kind) {
|
||||
$choices[MaterialKindSelection::key($kind['id'])] = ['label' => $kind['label'], 'automatic' => $kind['automatic']];
|
||||
}
|
||||
|
||||
$choices[MaterialKindSelection::WITHOUT] = ['label' => 'Ohne Materialart', 'automatic' => false];
|
||||
|
||||
return $choices;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allgemeine Startansicht: alle Materialarten und Medien ohne Materialart, ohne Übungsabschnitte.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function defaultArten(): array
|
||||
{
|
||||
return array_keys(array_filter($this->artChoices(), fn (array $choice): bool => ! $choice['automatic']));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string> die gerade gewählten Schlüssel
|
||||
*/
|
||||
public function selectedArten(): array
|
||||
{
|
||||
return MaterialKindSelection::decode($this->arten) ?? $this->defaultArten();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $keys
|
||||
*/
|
||||
private function storeArten(array $keys): void
|
||||
{
|
||||
$default = $this->defaultArten();
|
||||
sort($keys);
|
||||
sort($default);
|
||||
|
||||
// Die allgemeine Startansicht bleibt ohne Eintrag in der Adresse.
|
||||
$this->arten = $keys === $default ? '' : MaterialKindSelection::encode($keys);
|
||||
$this->bestandGrenze = Bestand::SCHRITT;
|
||||
}
|
||||
|
||||
private function userId(): ?int
|
||||
{
|
||||
$id = Filament::auth()->id();
|
||||
|
||||
return $id === null ? null : (int) $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
private function savedDefault(): ?array
|
||||
{
|
||||
return UserViewDefault::filtersFor($this->userId(), UserViewDefault::MEDIA);
|
||||
}
|
||||
|
||||
public function hasSavedDefault(): bool
|
||||
{
|
||||
return $this->savedDefault() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die aktuellen Filter (ohne Suche) als persönlicher Standard dieses Kontos.
|
||||
*/
|
||||
public function saveDefault(): void
|
||||
{
|
||||
$userId = $this->userId();
|
||||
|
||||
if ($userId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$filters = [];
|
||||
|
||||
foreach (self::DEFAULT_FILTERS as $name) {
|
||||
$filters[$name] = (string) $this->{$name};
|
||||
}
|
||||
|
||||
UserViewDefault::remember($userId, UserViewDefault::MEDIA, $filters);
|
||||
$this->filterOffen = false;
|
||||
Notification::make()->title('Standard gespeichert')->body('Der Medienmanager startet für dich mit diesen Filtern.')->success()->send();
|
||||
}
|
||||
|
||||
public function restoreDefault(): void
|
||||
{
|
||||
$saved = $this->savedDefault();
|
||||
|
||||
if ($saved === null) {
|
||||
Notification::make()->title('Kein persönlicher Standard gespeichert')->warning()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->suche = '';
|
||||
$this->applyFilters($saved);
|
||||
$this->filterOffen = false;
|
||||
Notification::make()->title('Dein Standard ist geladen')->success()->send();
|
||||
}
|
||||
|
||||
public function deleteDefault(): void
|
||||
{
|
||||
$userId = $this->userId();
|
||||
|
||||
if ($userId !== null) {
|
||||
UserViewDefault::forget($userId, UserViewDefault::MEDIA);
|
||||
}
|
||||
|
||||
$this->resetFilters();
|
||||
$this->ansicht = 'liste';
|
||||
$this->filterOffen = false;
|
||||
Notification::make()->title('Persönlicher Standard gelöscht')->body('Der Medienmanager startet wieder mit der allgemeinen Auswahl.')->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $filters
|
||||
*/
|
||||
private function applyFilters(array $filters): void
|
||||
{
|
||||
foreach (self::DEFAULT_FILTERS as $name) {
|
||||
if (array_key_exists($name, $filters)) {
|
||||
$this->{$name} = (string) $filters[$name];
|
||||
}
|
||||
}
|
||||
|
||||
$this->ansicht = $this->ansicht === 'kacheln' ? 'kacheln' : 'liste';
|
||||
$this->archiv = in_array($this->archiv, ['aktiv', 'archiviert', 'alle'], true) ? $this->archiv : 'aktiv';
|
||||
$this->bestandGrenze = Bestand::SCHRITT;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Filterdialog
|
||||
|
||||
/**
|
||||
* Filterfelder mit Checkboxen (Mehrfachauswahl). Mehrere Werte eines Felds gelten als ODER.
|
||||
*
|
||||
* @return array<string, array{label: string, kurz: string, optionen: array<string, string>}>
|
||||
*/
|
||||
private function multiFields(): array
|
||||
{
|
||||
$arten = array_map(fn (array $choice): string => $choice['label'], $this->artChoices());
|
||||
|
||||
return [
|
||||
'arten' => ['label' => 'Fachliche Materialart', 'kurz' => 'Materialart', 'optionen' => $arten],
|
||||
'art' => ['label' => 'Technische Art', 'kurz' => 'Technische Art', 'optionen' => collect($this->typeOptions())->mapWithKeys(fn (array $type): array => [$type['value'] => $type['label']])->all()],
|
||||
'freigabe' => ['label' => 'Freigabe', 'kurz' => 'Freigabe', 'optionen' => ['freigegeben' => 'Freigegebene Fassung', 'entwurf' => 'Nur offener Entwurf', 'ohne' => 'Keine freigegebene Fassung']],
|
||||
'nutzung' => ['label' => 'Verwendung', 'kurz' => 'Verwendung', 'optionen' => ['verwendet' => 'Verwendet', 'unbenutzt' => 'Nicht verwendet']],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Weitere Kriterien mit einem Wert je Feld, unter „Weitere Filter“ im Dialog.
|
||||
*
|
||||
* @return array<string, array{label: string, vorgabe: string, alle: string|null, optionen: array<string, string>}>
|
||||
*/
|
||||
private function singleFields(): array
|
||||
{
|
||||
$optionen = fn (array $liste, string $wert, string $label): array => collect($liste)
|
||||
->mapWithKeys(fn (array $eintrag): array => [(string) $eintrag[$wert] => $eintrag[$label]])
|
||||
->all();
|
||||
$fields = [
|
||||
'schutz' => ['label' => 'Schutz', 'vorgabe' => '', 'alle' => 'Alle Medien', 'optionen' => ['geschuetzt' => 'Geschützte Medien', 'oeffentlich' => 'Öffentliche Medien', 'website' => 'Auf der Website frei']],
|
||||
'entwurf' => ['label' => 'Entwurf', 'vorgabe' => '', 'alle' => 'Entwurf egal', 'optionen' => ['offen' => 'Offener Entwurf', 'keiner' => 'Kein offener Entwurf']],
|
||||
'fassung' => ['label' => 'Deaktivierte Fassungen', 'vorgabe' => '', 'alle' => 'Regulärer Bestand', 'optionen' => ['mit' => 'Mit deaktivierter Fassung', 'nur' => 'Nur deaktivierte Fassungen']],
|
||||
];
|
||||
|
||||
if (($pillars = $this->pillarOptions()) !== []) {
|
||||
$fields['saeule'] = ['label' => 'Fachliche Säule', 'vorgabe' => '', 'alle' => 'Alle Säulen', 'optionen' => $optionen($pillars, 'id', 'name')];
|
||||
}
|
||||
|
||||
if (($classes = $this->classificationOptions()) !== []) {
|
||||
$fields['einordnung'] = ['label' => 'Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'optionen' => $optionen($classes, 'id', 'label')];
|
||||
}
|
||||
|
||||
$fields['verarbeitung'] = ['label' => 'Verarbeitung', 'vorgabe' => '', 'alle' => 'Verarbeitung egal', 'optionen' => ['fehler' => 'Verarbeitungsfehler', 'uebernahme' => 'Datei wird übernommen']];
|
||||
$fields['archiv'] = ['label' => 'Archiv', 'vorgabe' => 'aktiv', 'alle' => null, 'optionen' => ['aktiv' => 'Aktive Medien', 'archiviert' => 'Archivierte Medien', 'alle' => 'Auch archivierte']];
|
||||
|
||||
return $fields;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function appliedList(string $field): array
|
||||
{
|
||||
$value = trim((string) $this->{$field});
|
||||
|
||||
return $value === '' ? [] : array_values(array_filter(array_map('trim', explode(',', $value)), fn (string $part): bool => $part !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Auswahl der Liste als Arbeitsstand des Dialogs.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function draftFromApplied(): array
|
||||
{
|
||||
$draft = ['arten' => $this->selectedArten()];
|
||||
|
||||
foreach (self::MULTI_FIELDS as $field) {
|
||||
$draft[$field] = $this->appliedList($field);
|
||||
}
|
||||
|
||||
foreach (array_keys($this->singleFields()) as $field) {
|
||||
$draft[$field] = (string) $this->{$field};
|
||||
}
|
||||
|
||||
return $draft;
|
||||
}
|
||||
|
||||
public function openFilter(string $field = ''): void
|
||||
{
|
||||
$this->filterDraft = $this->draftFromApplied();
|
||||
$this->filterFokus = $field;
|
||||
$this->filterOffen = true;
|
||||
}
|
||||
|
||||
/** Verwirft die Auswahl seit dem Öffnen. */
|
||||
public function cancelFilter(): void
|
||||
{
|
||||
$this->filterOffen = false;
|
||||
$this->filterDraft = [];
|
||||
$this->filterFokus = '';
|
||||
}
|
||||
|
||||
/** Alle Materialarten im Dialog ankreuzen, auch Übungsabschnitte und „Ohne Materialart“. */
|
||||
public function draftAlleArten(): void
|
||||
{
|
||||
$this->filterDraft['arten'] = array_keys($this->artChoices());
|
||||
}
|
||||
|
||||
/** Übernimmt die Auswahl des Dialogs in die Liste. */
|
||||
public function applyFilter(): void
|
||||
{
|
||||
$this->applyDraft();
|
||||
$this->filterOffen = false;
|
||||
$this->filterDraft = [];
|
||||
$this->filterFokus = '';
|
||||
}
|
||||
|
||||
/** Übernimmt die Auswahl des Dialogs und merkt sie als persönlichen Standard. */
|
||||
public function saveDefaultFromDialog(): void
|
||||
{
|
||||
$this->applyDraft();
|
||||
$this->filterDraft = [];
|
||||
$this->filterFokus = '';
|
||||
$this->saveDefault();
|
||||
}
|
||||
|
||||
private function applyDraft(): void
|
||||
{
|
||||
$draft = $this->filterDraft;
|
||||
$known = array_keys($this->artChoices());
|
||||
$this->storeArten(array_values(array_intersect($known, array_map('strval', (array) ($draft['arten'] ?? [])))));
|
||||
$options = $this->multiFields();
|
||||
|
||||
foreach (self::MULTI_FIELDS as $field) {
|
||||
$allowed = array_keys($options[$field]['optionen']);
|
||||
$chosen = array_values(array_intersect($allowed, array_map('strval', (array) ($draft[$field] ?? []))));
|
||||
// Alle Werte angekreuzt heißt: keine Einschränkung.
|
||||
$this->{$field} = count($chosen) === count($allowed) ? '' : implode(',', $chosen);
|
||||
}
|
||||
|
||||
foreach ($this->singleFields() as $field => $definition) {
|
||||
$value = (string) ($draft[$field] ?? $definition['vorgabe']);
|
||||
$this->{$field} = array_key_exists($value, $definition['optionen']) ? $value : $definition['vorgabe'];
|
||||
}
|
||||
|
||||
$this->bestandGrenze = Bestand::SCHRITT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die wirksamen Filter als Pillen unter der Suche. Ein Klick öffnet den Dialog beim Filterfeld. In der allgemeinen
|
||||
* Startansicht erklärt eine Pille, warum Übungsabschnitte fehlen.
|
||||
*
|
||||
* @return list<array{feld: string, label: string, info: bool}>
|
||||
*/
|
||||
private function filterPills(): array
|
||||
{
|
||||
$pills = [];
|
||||
$short = function (array $labels): string {
|
||||
$joined = implode(', ', $labels);
|
||||
|
||||
return count($labels) <= 3 && mb_strlen($joined) <= 40 ? $joined : count($labels).' gewählt';
|
||||
};
|
||||
$multi = $this->multiFields();
|
||||
|
||||
if ($this->arten === '') {
|
||||
$pills[] = ['feld' => 'arten', 'label' => 'Übungsabschnitte und Dokumentkapitel ausgeblendet', 'info' => true];
|
||||
} else {
|
||||
$selected = $this->selectedArten();
|
||||
|
||||
if ($selected === []) {
|
||||
$pills[] = ['feld' => 'arten', 'label' => 'Materialart · keine gewählt', 'info' => false];
|
||||
} elseif (count($selected) < count($multi['arten']['optionen'])) {
|
||||
$pills[] = ['feld' => 'arten', 'label' => 'Materialart · '.$short(array_map(fn (string $key): string => $multi['arten']['optionen'][$key] ?? $key, $selected)), 'info' => false];
|
||||
}
|
||||
}
|
||||
|
||||
foreach (self::MULTI_FIELDS as $field) {
|
||||
$values = $this->appliedList($field);
|
||||
|
||||
if ($values !== []) {
|
||||
$pills[] = ['feld' => $field, 'label' => $multi[$field]['kurz'].' · '.$short(array_map(fn (string $value): string => $multi[$field]['optionen'][$value] ?? $value, $values)), 'info' => false];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->singleFields() as $field => $definition) {
|
||||
$value = (string) $this->{$field};
|
||||
|
||||
if ($value !== $definition['vorgabe']) {
|
||||
$pills[] = ['feld' => $field, 'label' => $definition['label'].' · '.($definition['optionen'][$value] ?? $value), 'info' => false];
|
||||
}
|
||||
}
|
||||
|
||||
return $pills;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gemeinsame Bestandsliste: Suche mit Filterknopf, wirksame Filter als Pillen, alle Kriterien im Filterdialog.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
@@ -181,38 +556,27 @@ public function bestand(): array
|
||||
[$this->saeule, $this->einordnung] = [(string) $pillar, ''];
|
||||
}
|
||||
|
||||
$optionen = fn (array $liste, string $wert, string $label): array => collect($liste)
|
||||
->mapWithKeys(fn (array $eintrag): array => [(string) $eintrag[$wert] => $eintrag[$label]])
|
||||
->all();
|
||||
$weitere = [
|
||||
['eigenschaft' => 'inhaltsart', 'label' => 'Fachliche Materialart', 'vorgabe' => '', 'alle' => 'Alle Materialarten', 'optionen' => $this->contentKindOptions()],
|
||||
['eigenschaft' => 'entwurf', 'label' => 'Entwurf', 'vorgabe' => '', 'alle' => 'Entwurf egal', 'optionen' => ['offen' => 'Offener Entwurf', 'keiner' => 'Kein offener Entwurf']],
|
||||
['eigenschaft' => 'fassung', 'label' => 'Deaktivierte Fassungen', 'vorgabe' => '', 'alle' => 'Regulärer Bestand', 'optionen' => ['mit' => 'Mit deaktivierter Fassung', 'nur' => 'Nur deaktivierte Fassungen']],
|
||||
$pills = $this->filterPills();
|
||||
$keine = $this->selectedArten() === [];
|
||||
$gespeichert = $this->hasSavedDefault();
|
||||
$dialog = [
|
||||
'offen' => $this->filterOffen,
|
||||
'fokus' => $this->filterFokus,
|
||||
'pillen' => $pills,
|
||||
'anzahl' => count(array_filter($pills, fn (array $pill): bool => ! $pill['info'])),
|
||||
'felder' => $this->multiFields(),
|
||||
'weitere' => $this->singleFields(),
|
||||
'entwurf' => 'filterDraft',
|
||||
'gespeichert' => $gespeichert,
|
||||
'hinweis' => 'Mehrere Werte eines Felds zeigen Medien, auf die einer davon zutrifft. Verschiedene Felder gelten zusammen. Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Geschützte Medien haben eine Inhaltsfassung und laufen über Lizenzen. Öffentliche Medien sind eigenständige Präsentationsmedien ohne Fassung für die Website. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Übungsabschnitte und Dokumentkapitel, die Texte der Übungen und Dokumente, erscheinen erst, wenn du sie unter Materialart ankreuzt. „Als Standard speichern“ merkt die Filter für dein Konto, ohne die Suche.',
|
||||
];
|
||||
|
||||
if (($pillars = $this->pillarOptions()) !== []) {
|
||||
$weitere[] = ['eigenschaft' => 'saeule', 'label' => 'Fachliche Säule', 'vorgabe' => '', 'alle' => 'Alle Säulen', 'optionen' => $optionen($pillars, 'id', 'name')];
|
||||
}
|
||||
|
||||
if (($classes = $this->classificationOptions()) !== []) {
|
||||
$weitere[] = ['eigenschaft' => 'einordnung', 'label' => 'Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'optionen' => $optionen($classes, 'id', 'label')];
|
||||
}
|
||||
|
||||
$weitere[] = ['eigenschaft' => 'verarbeitung', 'label' => 'Verarbeitung', 'vorgabe' => '', 'alle' => 'Verarbeitung egal', 'optionen' => ['fehler' => 'Verarbeitungsfehler', 'uebernahme' => 'Datei wird übernommen']];
|
||||
$weitere[] = ['eigenschaft' => 'archiv', 'label' => 'Archiv', 'vorgabe' => 'aktiv', 'optionen' => ['aktiv' => 'Aktive Medien', 'archiviert' => 'Archivierte Medien', 'alle' => 'Auch archivierte']];
|
||||
|
||||
return [
|
||||
'suche' => ['eigenschaft' => 'suche', 'label' => 'Suche', 'platzhalter' => 'Titel, Beschreibung oder Suchbegriff'],
|
||||
'filter' => [
|
||||
['eigenschaft' => 'art', 'label' => 'Technische Art', 'vorgabe' => '', 'alle' => 'Alle Arten', 'optionen' => $optionen($this->typeOptions(), 'value', 'label')],
|
||||
['eigenschaft' => 'schutz', 'label' => 'Schutz', 'vorgabe' => '', 'alle' => 'Alle Medien', 'optionen' => ['geschuetzt' => 'Geschützte Medien', 'oeffentlich' => 'Öffentliche Medien', 'website' => 'Auf der Website frei']],
|
||||
['eigenschaft' => 'freigabe', 'label' => 'Freigabe', 'vorgabe' => '', 'alle' => 'Alle Freigaben', 'optionen' => ['freigegeben' => 'Freigegebene Fassung', 'entwurf' => 'Nur offener Entwurf', 'ohne' => 'Keine freigegebene Fassung']],
|
||||
['eigenschaft' => 'nutzung', 'label' => 'Verwendung', 'vorgabe' => '', 'alle' => 'Verwendung egal', 'optionen' => ['verwendet' => 'Verwendet', 'unbenutzt' => 'Nicht verwendet']],
|
||||
],
|
||||
'weitere' => $weitere,
|
||||
'hinweis' => 'Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Geschützte Medien haben eine Inhaltsfassung und laufen über Lizenzen. Öffentliche Medien sind eigenständige Präsentationsmedien ohne Fassung für die Website; ob sie freigegeben sind, zeigt die Kennzeichnung an der Zeile. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Deaktivierte und archivierte Medien bleiben über „Weitere Filter“ auffindbar.',
|
||||
'filterdialog' => $dialog,
|
||||
'zeilen' => array_map($this->zeile(...), $this->cards()),
|
||||
'einheit' => ['Medium', 'Medien'],
|
||||
'leerHinweis' => $keine ? 'Öffne den Filter und wähle mindestens eine Materialart aus, um Medien zu sehen. „Alle auswählen“ zeigt alles, auch Übungsabschnitte und Dokumentkapitel.' : null,
|
||||
'leer' => ['titel' => 'Noch keine Medien', 'text' => 'Mit „Medium anlegen“ oben lädst du eine Datei hoch oder schreibst einen Text.'],
|
||||
'ansicht' => 'ansicht',
|
||||
];
|
||||
@@ -250,7 +614,7 @@ private function zeile(array $card): array
|
||||
return [
|
||||
'schluessel' => 'm'.$card['id'],
|
||||
'titel' => $card['title'],
|
||||
'meta' => $card['type'].(filled($card['editorialKind'] ?? null) ? ' · '.$card['editorialKind'] : ''),
|
||||
'meta' => $card['type'].(filled($card['editorialKind'] ?? null) ? ' · '.$card['editorialKind'] : '').($card['exercise'] !== null ? ' · Übung: '.$card['exercise']['title'] : ''),
|
||||
'text' => $card['description'],
|
||||
'bild' => $card['image'],
|
||||
'bildAlt' => $card['imageAlt'],
|
||||
@@ -271,6 +635,7 @@ private function zeile(array $card): array
|
||||
'aktionen' => array_values(array_filter([
|
||||
['label' => 'Ansehen', 'href' => $card['url'], 'icon' => 'auge'],
|
||||
$card['editUrl'] ? ['label' => 'Redaktion', 'href' => $card['editUrl'], 'icon' => 'stift'] : null,
|
||||
($card['exercise']['url'] ?? null) ? ['label' => 'Zur Übung', 'href' => $card['exercise']['url'], 'icon' => 'stift'] : null,
|
||||
])),
|
||||
];
|
||||
}
|
||||
@@ -291,6 +656,7 @@ private function libraryFilters(): array
|
||||
'saeule' => $this->saeule,
|
||||
'einordnung' => $this->einordnung,
|
||||
'inhaltsart' => $this->inhaltsart,
|
||||
'arten' => $this->arten === '' ? MaterialKindSelection::encode($this->defaultArten()) : $this->arten,
|
||||
'verarbeitung' => $this->verarbeitung,
|
||||
'archiv' => $this->archiv,
|
||||
];
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityChange;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
@@ -26,6 +27,7 @@
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Filament\Support\ElementRevision;
|
||||
use App\Filament\Support\ManagesEditorialSurface;
|
||||
use App\Filament\Support\ManagesRichFields;
|
||||
use App\Filament\Support\MediaLibrary;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Http\Controllers\ContentPreviewController;
|
||||
@@ -45,6 +47,7 @@
|
||||
class ViewContentElement extends ViewRecord
|
||||
{
|
||||
use ManagesEditorialSurface;
|
||||
use ManagesRichFields;
|
||||
use ReportsDomainRules;
|
||||
use WithFileUploads;
|
||||
|
||||
@@ -211,7 +214,7 @@ public function textUnsaved(): bool
|
||||
return $shown instanceof ContentElementVersion
|
||||
&& $this->getRecord()->output_class === 'text'
|
||||
&& $shown->status !== ContentVersionStatus::Gesperrt
|
||||
&& trim($this->bodyDraft) !== trim((string) $shown->body);
|
||||
&& ! FormattedText::same($this->bodyDraft, $shown->body);
|
||||
}
|
||||
|
||||
public function discardShownText(): void
|
||||
@@ -243,7 +246,7 @@ public function saveShownText(): void
|
||||
}
|
||||
|
||||
try {
|
||||
$saved = app(ContentService::class)->reviseElementContent($shown, $this->bodyDraft);
|
||||
$saved = app(ContentService::class)->reviseElementContent($shown, FormattedText::canonical($this->bodyDraft));
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->fassungFeedback = $exception->getMessage();
|
||||
$this->fassungFeedbackError = true;
|
||||
@@ -687,9 +690,9 @@ protected function saveRedaktionTexte(): bool
|
||||
'working_title' => $title,
|
||||
'display_title' => $this->displayTitle,
|
||||
'teaser' => $this->teaser,
|
||||
'summary' => $this->summary,
|
||||
'summary' => $this->richStore('summary', $element->summary),
|
||||
'search_terms' => $this->searchTerms,
|
||||
'description' => $this->descriptionText,
|
||||
'description' => $this->richStore('descriptionText', $element->description),
|
||||
'usage_note' => $this->usageNote,
|
||||
'license_note' => $this->licenseNote,
|
||||
'website_credit' => $this->websiteCredit,
|
||||
@@ -780,6 +783,22 @@ public function redaktionTitel(): string
|
||||
return $title !== '' ? $title : (string) $this->getRecord()->working_title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function richFelder(): array
|
||||
{
|
||||
return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Ausführliche Beschreibung', 'bodyDraft' => 'Text der Fassung'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function richBilder(): array
|
||||
{
|
||||
return ['bodyDraft'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
@@ -793,8 +812,8 @@ public function redaktionFelder(): array
|
||||
['id' => 'arbeitstitel', 'label' => 'Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'required' => true, 'hilfe' => 'Bezeichnung in der Verwaltung. Pflichtangabe.'],
|
||||
['id' => 'anzeigename', 'label' => 'Anzeigename', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Arbeitstitel.'],
|
||||
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser')],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 3, 'stored' => $stored('summary'), 'hilfe' => 'Erscheint auf Website- und Bibliothekskarten.'],
|
||||
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'descriptionText', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Bleibt in der Verwaltung und in Detailansichten. Kein Lehrtext.'],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary'), 'hilfe' => 'Erscheint auf Website- und Bibliothekskarten.'],
|
||||
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'descriptionText', 'kind' => 'rich', 'stored' => $stored('description'), 'hilfe' => 'Bleibt in der Verwaltung und in Detailansichten. Kein Lehrtext.'],
|
||||
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
|
||||
['id' => 'einsatz', 'label' => 'Hinweise für den Einsatz', 'model' => 'usageNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('usage_note')],
|
||||
['id' => 'lizenz', 'label' => 'Interner Lizenzvermerk', 'model' => 'licenseNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('license_note'), 'hilfe' => 'Nur intern sichtbar.'],
|
||||
@@ -1040,7 +1059,7 @@ public function previewHtml(): string
|
||||
$draft = [
|
||||
'working_title' => $this->workingTitle,
|
||||
'display_title' => $this->displayTitle,
|
||||
'summary' => $this->summary,
|
||||
'summary' => FormattedText::plain($this->summary),
|
||||
'thumbnail_alt' => $this->thumbnailAlt,
|
||||
];
|
||||
|
||||
@@ -1053,7 +1072,7 @@ public function previewHtml(): string
|
||||
'type' => $element->output_class === 'film' ? 'film' : 'material',
|
||||
'url' => '#vorschau',
|
||||
'title' => $title !== '' ? $title : $element->working_title,
|
||||
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
|
||||
'summary' => FormattedText::plain($this->summary) !== '' ? FormattedText::plain($this->summary) : null,
|
||||
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
|
||||
'hide_status' => true,
|
||||
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
class CourseResource extends CompositionKindResource
|
||||
{
|
||||
protected static ?string $slug = 'kurse';
|
||||
protected static ?string $slug = 'programme';
|
||||
|
||||
protected static ?string $navigationLabel = 'Programme';
|
||||
|
||||
@@ -17,7 +17,7 @@ class CourseResource extends CompositionKindResource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Programme';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Documents;
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Filament\Resources\Compositions\CompositionKindResource;
|
||||
use App\Filament\Resources\Documents\Pages\EditDocument;
|
||||
use App\Filament\Resources\Documents\Pages\ListDocuments;
|
||||
|
||||
/**
|
||||
* Dokumente unter „Inhalte“: zusammenhängende Texte aus Kapiteln, der erste Fall ist das Trainerhandbuch (ADR-51).
|
||||
* Wie Übungen sind es Kompositionen mit eigener Art; Fassung, Einbindung und Stand arbeiten mit denselben Bausteinen.
|
||||
*/
|
||||
class DocumentResource extends CompositionKindResource
|
||||
{
|
||||
protected static ?string $slug = 'dokumente';
|
||||
|
||||
protected static ?string $navigationLabel = 'Dokumente';
|
||||
|
||||
protected static ?string $modelLabel = 'Dokument';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Dokumente';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
return CompositionKind::Document;
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListDocuments::route('/'),
|
||||
'edit' => EditDocument::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Documents\Pages;
|
||||
|
||||
use App\Filament\Resources\Compositions\Pages\EditComposition;
|
||||
use App\Filament\Resources\Documents\DocumentResource;
|
||||
|
||||
class EditDocument extends EditComposition
|
||||
{
|
||||
protected static string $resource = DocumentResource::class;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Documents\Pages;
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Filament\Resources\Compositions\Pages\ListCompositionKind;
|
||||
use App\Filament\Resources\Documents\DocumentResource;
|
||||
|
||||
class ListDocuments extends ListCompositionKind
|
||||
{
|
||||
protected static string $resource = DocumentResource::class;
|
||||
|
||||
protected function kind(): CompositionKind
|
||||
{
|
||||
return CompositionKind::Document;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
class ExerciseResource extends CompositionKindResource
|
||||
{
|
||||
protected static ?string $slug = 'uebungen';
|
||||
protected static ?string $slug = 'module';
|
||||
|
||||
protected static ?string $navigationLabel = 'Module';
|
||||
|
||||
@@ -17,7 +17,7 @@ class ExerciseResource extends CompositionKindResource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Module';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Filament\Support\ManagesEditorialSurface;
|
||||
use App\Filament\Support\ManagesRichFields;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
@@ -33,6 +34,7 @@ class ViewLicenseArticle extends ViewRecord
|
||||
{
|
||||
use AssignsPillars;
|
||||
use ManagesEditorialSurface;
|
||||
use ManagesRichFields;
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = LicenseArticleResource::class;
|
||||
@@ -110,8 +112,8 @@ protected function saveRedaktionTexte(): bool
|
||||
'working_title' => $this->workingTitle,
|
||||
'display_title' => $this->displayTitle,
|
||||
'teaser' => $this->teaser,
|
||||
'summary' => $this->summary,
|
||||
'description' => $this->descriptionText,
|
||||
'summary' => $this->richStore('summary', $article->summary),
|
||||
'description' => $this->richStore('descriptionText', $article->description),
|
||||
'search_terms' => $this->searchTerms,
|
||||
'editorial_content_kind_id' => filled($this->kindId) ? (int) $this->kindId : null,
|
||||
], auth()->user());
|
||||
@@ -199,6 +201,14 @@ public function redaktionTitel(): string
|
||||
return $source !== null ? $this->sourceTitle($source) : (string) $this->getRecord()->code;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function richFelder(): array
|
||||
{
|
||||
return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Beschreibung'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
@@ -218,8 +228,8 @@ public function redaktionFelder(): array
|
||||
['id' => 'arbeitstitel', 'label' => 'Interner Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'hilfe' => 'Nur in der Verwaltung sichtbar.'],
|
||||
['id' => 'anzeigename', 'label' => 'Name', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'quelle' => $quelle('display_title')],
|
||||
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser'), 'quelle' => $quelle('teaser')],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 4, 'stored' => $stored('summary'), 'quelle' => $quelle('summary')],
|
||||
['id' => 'beschreibung', 'label' => 'Beschreibung', 'model' => 'descriptionText', 'kind' => 'textarea', 'rows' => 6, 'stored' => $stored('description'), 'quelle' => $quelle('description')],
|
||||
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary'), 'quelle' => $quelle('summary')],
|
||||
['id' => 'beschreibung', 'label' => 'Beschreibung', 'model' => 'descriptionText', 'kind' => 'rich', 'stored' => $stored('description'), 'quelle' => $quelle('description')],
|
||||
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'quelle' => $quelle('search_terms')],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -18,11 +18,13 @@
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Filament\Pages\Zahlungsjournal;
|
||||
use App\Filament\Resources\Offers\OfferResource;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\PublicationReadiness;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
@@ -366,6 +368,11 @@ private function angebotDaten(): array
|
||||
'wire' => "mountAction('end')",
|
||||
'art' => 'line',
|
||||
]] : []),
|
||||
...(ShopAccess::allowed() ? [[
|
||||
'label' => 'Zahlungen zu diesem Angebot',
|
||||
'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']),
|
||||
'art' => 'quiet',
|
||||
]] : []),
|
||||
],
|
||||
],
|
||||
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
|
||||
|
||||
@@ -4,14 +4,17 @@
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\PaymentJournal;
|
||||
use App\Filament\Resources\Orders\OrderResource;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
@@ -66,6 +69,11 @@ public function infolist(Schema $schema): Schema
|
||||
])->columns(1);
|
||||
}
|
||||
|
||||
private function hasStripePayment(): bool
|
||||
{
|
||||
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
|
||||
}
|
||||
|
||||
private function order(): Order
|
||||
{
|
||||
/** @var Order $order */
|
||||
@@ -84,11 +92,15 @@ public function confirmInvoiceAction(): Action
|
||||
->schema([
|
||||
TextInput::make('reference')->label('Rechnungsnummer oder Buchungsreferenz')->required()->maxLength(120)
|
||||
->helperText('Bleibt an der Zahlung gespeichert, zum Beispiel „RE-2026-014“.'),
|
||||
DatePicker::make('received_on')->label('Zahlungseingang am')->required()->native(false)->displayFormat('d.m.Y')
|
||||
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->helperText('Der Tag, an dem das Geld auf dem Konto einging. Er bestimmt, in welchen Zeitraum die Einnahme im Zahlungsjournal fällt.'),
|
||||
])
|
||||
->visible(fn (): bool => $this->order()->payment_method === 'rechnung' && $this->order()->status === 'offen')
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user());
|
||||
app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user(), (string) $data['received_on']);
|
||||
|
||||
return 'Der Zahlungseingang ist bestätigt. Die Inhalte sind freigeschaltet.';
|
||||
}, 'Bestätigt.');
|
||||
@@ -111,12 +123,27 @@ public function refundAction(): Action
|
||||
->modalSubmitActionLabel('Vollständig erstatten')
|
||||
->schema([
|
||||
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
|
||||
->helperText('Bleibt am Widerruf der Berechtigungen stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||
->helperText('Bleibt am Widerruf der Berechtigungen und im Zahlungsjournal stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||
DatePicker::make('refunded_on')->label('Rückzahlung am')->native(false)->displayFormat('d.m.Y')
|
||||
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
|
||||
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||
->helperText('Der Tag, an dem du das Geld zurücküberwiesen hast. Bei Stripe gilt der Zeitpunkt von Stripe.'),
|
||||
TextInput::make('refund_reference')->label('Referenz der Rückzahlung')->maxLength(120)
|
||||
->visible(fn (): bool => ! $this->hasStripePayment())
|
||||
->helperText('Optional, zum Beispiel Buchungstext oder Gutschriftnummer.'),
|
||||
])
|
||||
->visible(fn (): bool => $this->order()->status === 'bezahlt')
|
||||
->action(function (array $data): void {
|
||||
$this->report(function () use ($data): string {
|
||||
app(Checkout::class)->refund($this->order(), (string) $data['reason']);
|
||||
app(Checkout::class)->refund(
|
||||
$this->order(),
|
||||
(string) $data['reason'],
|
||||
null,
|
||||
Filament::auth()->user(),
|
||||
$this->hasStripePayment() ? null : ($data['refunded_on'] ?? null),
|
||||
$this->hasStripePayment() ? null : ($data['refund_reference'] ?? null),
|
||||
);
|
||||
|
||||
return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.';
|
||||
}, 'Erstattet.');
|
||||
@@ -188,6 +215,15 @@ private function bestellDaten(): array
|
||||
])->values()->all(),
|
||||
'leer' => ['titel' => 'Noch keine Zahlung', 'text' => 'Es gibt noch keinen Zahlungsvorgang zu dieser Bestellung.'],
|
||||
],
|
||||
[
|
||||
'titel' => 'Buchungen im Zahlungsjournal',
|
||||
'hilfe' => 'Unveränderlich festgehalten, mit Datum, Beleg beim Anbieter und Rechnungsempfänger zum Zeitpunkt der Buchung. Alle Buchungen eines Zeitraums und den Export findest du unter „Einnahmen und Erstattungen“.',
|
||||
'zeilen' => LedgerEntry::query()->where('order_id', $order->id)->orderBy('occurred_at')->orderBy('id')->get()->map(fn (LedgerEntry $entry): array => [
|
||||
'text' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y').' · '.($entry->isRefund() ? 'Erstattung −' : 'Zahlungseingang ').Money::format(abs($entry->amount_cents)).($entry->live ? '' : ' (Test, kein Umsatz)').($entry->derived ? ' (nachgetragen)' : ''),
|
||||
'neben' => PaymentJournal::providerLabel($entry->provider).' · '.$entry->provider_reference.(filled($entry->actor_name) ? ' · gebucht von '.$entry->actor_name : ''),
|
||||
])->values()->all(),
|
||||
'leer' => ['titel' => 'Noch keine Buchung', 'text' => 'Zahlungseingang und Erstattung dieser Bestellung erscheinen hier.'],
|
||||
],
|
||||
],
|
||||
'seite' => [
|
||||
[
|
||||
|
||||
@@ -20,7 +20,7 @@ class PillarResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Pillar::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Fachliche Säulen';
|
||||
|
||||
@@ -32,7 +32,7 @@ class PillarResource extends Resource
|
||||
|
||||
protected static ?string $slug = 'saeulen';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Practices\Pages;
|
||||
|
||||
use App\Filament\Resources\Compositions\Pages\EditComposition;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
|
||||
class EditPractice extends EditComposition
|
||||
{
|
||||
protected static string $resource = PracticeResource::class;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Practices\Pages;
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Filament\Resources\Compositions\Pages\ListCompositionKind;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
|
||||
class ListPractices extends ListCompositionKind
|
||||
{
|
||||
protected static string $resource = PracticeResource::class;
|
||||
|
||||
protected function kind(): CompositionKind
|
||||
{
|
||||
return CompositionKind::Exercise;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Practices;
|
||||
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Filament\Resources\Compositions\CompositionKindResource;
|
||||
use App\Filament\Resources\Practices\Pages\EditPractice;
|
||||
use App\Filament\Resources\Practices\Pages\ListPractices;
|
||||
|
||||
/**
|
||||
* Die fachliche Übung. Der Eintrag „Module“ (`ExerciseResource`, Adresse `module`) zeigt die Zusammenstellungen der Art `uebung`;
|
||||
* hier stehen die Übungen mit Varianten.
|
||||
*/
|
||||
class PracticeResource extends CompositionKindResource
|
||||
{
|
||||
protected static ?string $slug = 'fachuebungen';
|
||||
|
||||
protected static ?string $navigationLabel = 'Übungen';
|
||||
|
||||
protected static ?string $modelLabel = 'Übung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Übungen';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
public static function kind(): CompositionKind
|
||||
{
|
||||
return CompositionKind::Exercise;
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListPractices::route('/'),
|
||||
'edit' => EditPractice::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ final class CatalogLabels
|
||||
'pdf:ansehen' => 'PDF ansehen',
|
||||
'pdf:laden' => 'PDF herunterladen',
|
||||
'text:ansehen' => 'Text ansehen',
|
||||
'text:laden' => 'Text als PDF herunterladen (Übung, Dokument)',
|
||||
'bild:ansehen' => 'Bild ansehen',
|
||||
];
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ public static function assignmentTargets(?int $exceptCompositionId = null): arra
|
||||
$media['element:'.$version->id] = self::elementLabel($version);
|
||||
}
|
||||
|
||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||
if ($exceptCompositionId !== null && (int) $version->composition_id === $exceptCompositionId) {
|
||||
continue;
|
||||
}
|
||||
@@ -94,7 +94,7 @@ public static function readyTargets(): array
|
||||
$options['element:'.$version->id] = self::elementLabel($version);
|
||||
}
|
||||
|
||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||
foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) {
|
||||
$options['composition:'.$version->id] = self::compositionLabel($version);
|
||||
}
|
||||
|
||||
|
||||
@@ -266,7 +266,7 @@ public function elementUsage(ContentElement $element): array
|
||||
->get();
|
||||
|
||||
foreach ($members as $member) {
|
||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
||||
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||
.' · Fassung '.$member->compositionVersion->number
|
||||
.' · Rolle '.$member->role;
|
||||
}
|
||||
@@ -280,7 +280,9 @@ public function elementUsage(ContentElement $element): array
|
||||
foreach ($contents as $content) {
|
||||
$lines[] = 'Lizenzartikel '.$content->release->article->code
|
||||
.' · Stand '.$content->release->number
|
||||
.' · '.$content->path;
|
||||
.' · '.$content->path
|
||||
.($content->variant_key !== null ? ' · Variante '.$content->variant_key : '')
|
||||
.($content->requirement === CompositionMember::SUPPLEMENTARY ? ' · ergänzend' : '');
|
||||
}
|
||||
|
||||
return $lines === []
|
||||
@@ -313,7 +315,7 @@ public function compositionMembers(Composition $composition): array
|
||||
}
|
||||
|
||||
$nested = $member->nestedCompositionVersion;
|
||||
$lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabel($nested->composition));
|
||||
$lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabelOf($nested->composition));
|
||||
}
|
||||
|
||||
return $lines;
|
||||
@@ -365,7 +367,7 @@ public function compositionUsage(Composition $composition): array
|
||||
->get();
|
||||
|
||||
foreach ($parents as $member) {
|
||||
$lines[] = self::compositionLabel($member->compositionVersion->composition)
|
||||
$lines[] = self::compositionLabelOf($member->compositionVersion->composition)
|
||||
.' · Fassung '.$member->compositionVersion->number
|
||||
.' · Rolle '.$member->role;
|
||||
}
|
||||
@@ -448,6 +450,16 @@ private function purpose(string $purpose): string
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Zusammenstellung, die dieser Programmstand nicht kennt, erscheint nur als Hinweis ohne Namen und Inhalt.
|
||||
*/
|
||||
private static function compositionLabelOf(?Composition $composition): string
|
||||
{
|
||||
return $composition === null
|
||||
? 'Zusammenstellung einer neueren Programmversion'
|
||||
: self::compositionLabel($composition);
|
||||
}
|
||||
|
||||
private static function compositionLabel(Composition $composition): string
|
||||
{
|
||||
$kind = $composition->kind;
|
||||
|
||||
@@ -106,13 +106,20 @@ public function pickerResult(): array
|
||||
return ['items' => [], 'more' => false];
|
||||
}
|
||||
|
||||
if ($this->pickerPurpose === 'aufbau') {
|
||||
// Eine PDF-Vorlage nimmt auch Bilder ohne Inhaltsfassung (Präsentationsmedien, Website-Bilder) auf.
|
||||
if ($this->pickerPurpose === 'vorlagenbild') {
|
||||
return $this->filterByMaterialart(app(EditorialCatalog::class)->presentationBrowse($this->pickerQuery, 'bild'));
|
||||
}
|
||||
|
||||
if (in_array($this->pickerPurpose, ['aufbau', 'textbild'], true)) {
|
||||
$image = $this->pickerPurpose === 'textbild';
|
||||
|
||||
return $this->filterByMaterialart(app(EditorialCatalog::class)->browse(
|
||||
$this->pickerQuery,
|
||||
$this->pickerKind,
|
||||
$image ? 'bild' : $this->pickerKind,
|
||||
$this->pickerDimension,
|
||||
$this->pickerExceptId(),
|
||||
false,
|
||||
$image,
|
||||
ctype_digit($this->pickerSaeule) ? (int) $this->pickerSaeule : 0,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
@@ -20,7 +21,9 @@
|
||||
use App\Filament\Resources\Combinations\CombinationResource;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Filament\Resources\Courses\CourseResource;
|
||||
use App\Filament\Resources\Documents\DocumentResource;
|
||||
use App\Filament\Resources\Exercises\ExerciseResource;
|
||||
use App\Filament\Resources\Practices\PracticeResource;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -33,6 +36,7 @@ class EditorialCatalog
|
||||
public function rows(CompositionVersion $version, int $exceptCompositionId): array
|
||||
{
|
||||
$version->loadMissing([
|
||||
'members.variant',
|
||||
'members.contentElementVersion.element.editorialContentKind',
|
||||
'members.nestedCompositionVersion.composition.editorialContentKind',
|
||||
]);
|
||||
@@ -50,6 +54,10 @@ public function rows(CompositionVersion $version, int $exceptCompositionId): arr
|
||||
|
||||
$row['role'] = $member->role;
|
||||
$row['note'] = trim((string) ($member->placement_note ?? ''));
|
||||
$row['variant'] = $member->variant?->key;
|
||||
$row['requirement'] = $member->requirement ?: 'erforderlich';
|
||||
$row['selection'] = is_array($member->variant_selection) ? $member->variant_selection : null;
|
||||
$row['origin'] = $member->origin ?: 'lokal';
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
@@ -102,8 +110,8 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
|
||||
'kind' => $kind,
|
||||
'output' => (string) $element->output_class,
|
||||
'body' => (string) ($version->body ?? ''),
|
||||
'summary' => (string) ($element->summary ?: $element->description ?: ''),
|
||||
'medium_description' => (string) ($element->description ?? ''),
|
||||
'summary' => FormattedText::plain((string) ($element->summary ?: $element->description ?: '')),
|
||||
'medium_description' => FormattedText::plain((string) ($element->description ?? '')),
|
||||
'usage_note' => (string) ($element->usage_note ?? ''),
|
||||
'license_note' => (string) ($element->license_note ?? ''),
|
||||
'tone' => $this->tone((string) $element->output_class, $kind),
|
||||
@@ -140,6 +148,12 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
|
||||
}
|
||||
|
||||
$composition = $version->composition;
|
||||
|
||||
// Art, die dieser Programmstand nicht kennt: nicht anbieten und nicht laden (Rückfallschutz).
|
||||
if ($composition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$kind = $composition->editorialContentKind?->label
|
||||
?: ($composition->kind instanceof CompositionKind ? $composition->kind->deskLabel() : 'Zusammenstellung');
|
||||
|
||||
@@ -147,7 +161,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
|
||||
'target' => 'composition:'.$version->id,
|
||||
'title' => $this->compositionTitle($composition),
|
||||
'kind' => $kind,
|
||||
'summary' => (string) ($composition->summary ?? ''),
|
||||
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
|
||||
'tone' => $this->tone('', $kind),
|
||||
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
|
||||
'version_label' => $version->status === ContentVersionStatus::Gesperrt
|
||||
@@ -182,7 +196,7 @@ private function draftCompositionRow(int $compositionId, int $exceptCompositionI
|
||||
'target' => 'composition-draft:'.$composition->id,
|
||||
'title' => $this->compositionTitle($composition),
|
||||
'kind' => $kind,
|
||||
'summary' => (string) ($composition->summary ?? ''),
|
||||
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
|
||||
'tone' => $this->tone('', $kind),
|
||||
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
|
||||
'version_label' => 'Entwurf',
|
||||
@@ -238,7 +252,11 @@ public function search(string $query, string $scope, int $exceptCompositionId):
|
||||
->with('composition.editorialContentKind')
|
||||
->whereHas('composition', function ($builder) use ($scope, $query, $like): void {
|
||||
if ($scope === 'module') {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||
}
|
||||
|
||||
if ($scope === 'uebungen') {
|
||||
$builder->where('kind', CompositionKind::Exercise);
|
||||
}
|
||||
|
||||
if ($query === '') {
|
||||
@@ -280,7 +298,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
$rows = [];
|
||||
$dimensionId = ctype_digit($dimension) ? (int) $dimension : 0;
|
||||
|
||||
if ($kind !== 'modul') {
|
||||
if (! in_array($kind, ['modul', 'dokumentfassung'], true)) {
|
||||
$latestElements = ContentElementVersion::query()
|
||||
->selectRaw('MAX(id)')
|
||||
->whereIn('status', [ContentVersionStatus::Bereit, ContentVersionStatus::Entwurf])
|
||||
@@ -304,14 +322,18 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
}
|
||||
}
|
||||
|
||||
if (! $elementsOnly && in_array($kind, ['alle', 'modul'], true)) {
|
||||
if (! $elementsOnly && in_array($kind, ['alle', 'modul', 'dokumentfassung'], true)) {
|
||||
$latestCompositions = CompositionVersion::query()
|
||||
->selectRaw('MAX(id)')
|
||||
->where('status', ContentVersionStatus::Bereit)
|
||||
->where('composition_id', '!=', $exceptCompositionId)
|
||||
->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void {
|
||||
if ($kind === 'modul') {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||
}
|
||||
|
||||
if ($kind === 'dokumentfassung') {
|
||||
$builder->where('kind', CompositionKind::Document);
|
||||
}
|
||||
|
||||
if ($dimensionId > 0) {
|
||||
@@ -353,11 +375,13 @@ public function browse(string $query, string $kind, string $dimension, int $exce
|
||||
$unreleased = Composition::query()
|
||||
->where('id', '!=', $exceptCompositionId)
|
||||
->whereNotNull('working_draft')
|
||||
// Ein Dokument bindet man nur als bereitgestellte Fassung ein, nie als Entwurf.
|
||||
->where('kind', '!=', CompositionKind::Document->value)
|
||||
->whereDoesntHave('versions', function ($builder): void {
|
||||
$builder->where('status', ContentVersionStatus::Bereit);
|
||||
})
|
||||
->when($kind === 'modul', function ($builder): void {
|
||||
$builder->where('kind', CompositionKind::Uebung);
|
||||
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
|
||||
})
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
@@ -494,8 +518,8 @@ private function rowForPresentationMedium(int $id): ?array
|
||||
'kind' => $kind,
|
||||
'output' => (string) $element->output_class,
|
||||
'body' => '',
|
||||
'summary' => (string) ($element->summary ?: $element->description ?: ''),
|
||||
'medium_description' => (string) ($element->description ?? ''),
|
||||
'summary' => FormattedText::plain((string) ($element->summary ?: $element->description ?: '')),
|
||||
'medium_description' => FormattedText::plain((string) ($element->description ?? '')),
|
||||
'usage_note' => (string) ($element->usage_note ?? ''),
|
||||
'license_note' => (string) ($element->license_note ?? ''),
|
||||
'tone' => $this->tone((string) $element->output_class, $kind),
|
||||
@@ -1028,6 +1052,10 @@ private function suggestPicture(array $members, array $seen = []): ?array
|
||||
|
||||
$nested = $version->composition;
|
||||
|
||||
if ($nested === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->cardUrl('komposition', $nested->id, $nested->thumbnail_path) !== null) {
|
||||
return [
|
||||
'kind' => 'komposition',
|
||||
@@ -1063,6 +1091,8 @@ public function create(string $designation, CompositionKind $kind): Composition
|
||||
$slug = match ($kind) {
|
||||
CompositionKind::Kurs => 'programm',
|
||||
CompositionKind::Uebung => 'modul',
|
||||
CompositionKind::Exercise => 'uebung',
|
||||
CompositionKind::Document => 'dokument',
|
||||
default => null,
|
||||
};
|
||||
$editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first();
|
||||
@@ -1084,6 +1114,8 @@ public static function editUrl(Composition $composition): string
|
||||
CompositionKind::Kurs => CourseResource::class,
|
||||
CompositionKind::Kombination => CombinationResource::class,
|
||||
CompositionKind::Uebung => ExerciseResource::class,
|
||||
CompositionKind::Exercise => PracticeResource::class,
|
||||
CompositionKind::Document => DocumentResource::class,
|
||||
};
|
||||
|
||||
return $resource::getUrl('edit', ['record' => $composition]);
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Filament\Resources\ContentElements\Pages\EditContentElement;
|
||||
use Filament\Forms\Components\Component;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
|
||||
@@ -37,14 +38,14 @@ public static function publish(ContentElement $record, array $data): string
|
||||
$metadata['decision_seconds'] = $decision;
|
||||
}
|
||||
|
||||
$body = is_string($data['body'] ?? null) ? $data['body'] : null;
|
||||
$body = is_string($data['body'] ?? null) ? (FormattedText::canonical($data['body']) ?: null) : null;
|
||||
$note = is_string($data['change_note'] ?? null) ? $data['change_note'] : null;
|
||||
$previousDecision = is_array($latest?->metadata) && is_numeric($latest->metadata['decision_seconds'] ?? null)
|
||||
? (int) $latest->metadata['decision_seconds']
|
||||
: null;
|
||||
$changed = $incoming !== null
|
||||
|| $dropFile
|
||||
|| trim((string) $body) !== trim((string) $latest?->body)
|
||||
|| ! FormattedText::same($body, $latest?->body)
|
||||
|| $decision !== $previousDecision
|
||||
|| (is_string($note) && trim($note) !== '');
|
||||
|
||||
@@ -71,7 +72,7 @@ public static function fields(ContentElement $element): array
|
||||
$latest = $element->versions()->orderByDesc('number')->first();
|
||||
|
||||
return [
|
||||
Textarea::make('body')->label('Text')->rows(8)->default($latest?->body),
|
||||
RichField::make('body', 'Text', live: false)->default(EmbeddedImages::forEditor($latest?->body)),
|
||||
EditContentElement::uploadField(),
|
||||
Toggle::make('drop_file')
|
||||
->label('Datei in der neuen Fassung nicht mehr verwenden')
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
/**
|
||||
* Frühere Adressen der Verwaltung. Die Bestände heißen seit der Neuordnung „Inhalte“ anders: Programme
|
||||
* (früher `kurse`), Module (früher `uebungen`) und Contentmanager (früher `content-elements`). Gespeicherte Links
|
||||
* führen mit Objektnummer, Unterseite und Filtern zum neuen Ziel.
|
||||
*
|
||||
* Die Weiterleitung steht hinter der Anmeldung des Panels und trägt selbst keine Daten. Die Rechte prüft erst das
|
||||
* Ziel; wer die Seite nicht sehen darf, bekommt über eine alte Adresse dieselbe Absage wie über die neue. Die
|
||||
* Antwort ist bewusst keine dauerhafte (302): Ein Rückfall des Codes setzt die neuen Adressen zurück, ein im Browser
|
||||
* gemerktes 301 würde dann ins Leere führen.
|
||||
*/
|
||||
final class LegacyAddresses
|
||||
{
|
||||
/** @var array<string, string> alte Adresse => neue Adresse (jeweils unter dem Panelpfad) */
|
||||
public const MOVED = [
|
||||
'kurse' => 'programme',
|
||||
'uebungen' => 'module',
|
||||
'content-elements' => 'contentmanager',
|
||||
];
|
||||
|
||||
public static function routes(): void
|
||||
{
|
||||
foreach (self::MOVED as $old => $new) {
|
||||
Route::get($old.'/{rest?}', fn (Request $request, ?string $rest = null): RedirectResponse => self::redirect($request, $new, $rest))
|
||||
->where('rest', '.*')
|
||||
->name('legacy.'.$old);
|
||||
}
|
||||
}
|
||||
|
||||
private static function redirect(Request $request, string $new, ?string $rest): RedirectResponse
|
||||
{
|
||||
$path = '/'.trim(Filament::getPanel('verwaltung')->getPath(), '/').'/'.$new;
|
||||
$rest = trim((string) $rest, '/');
|
||||
|
||||
if ($rest !== '') {
|
||||
$path .= '/'.$rest;
|
||||
}
|
||||
|
||||
$query = (string) $request->server->get('QUERY_STRING', '');
|
||||
|
||||
return redirect()->to(url($path).($query !== '' ? '?'.$query : ''));
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,11 @@
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\CompositionMember;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\ExerciseSource;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
use App\Domain\Catalog\PillarFilterCompat;
|
||||
@@ -74,6 +77,8 @@ public function bestand(): array
|
||||
$einheit = match ($fixed) {
|
||||
CompositionKind::Kurs => ['Programm', 'Programme'],
|
||||
CompositionKind::Uebung => ['Modul', 'Module'],
|
||||
CompositionKind::Exercise => ['Übung', 'Übungen'],
|
||||
CompositionKind::Document => ['Dokument', 'Dokumente'],
|
||||
CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'],
|
||||
default => ['Programm oder Modul', 'Programme und Module'],
|
||||
};
|
||||
@@ -114,6 +119,8 @@ public function bestand(): array
|
||||
'text' => 'Mit „'.match ($fixed) {
|
||||
CompositionKind::Kurs => 'Programm anlegen',
|
||||
CompositionKind::Kombination => CompositionKind::Kombination->createLabel(),
|
||||
CompositionKind::Exercise => 'Übung anlegen',
|
||||
CompositionKind::Document => 'Dokument anlegen',
|
||||
default => 'Modul anlegen',
|
||||
}.'“ oben entsteht der erste Eintrag. Der Name genügt.',
|
||||
],
|
||||
@@ -150,6 +157,10 @@ public function entries(): array
|
||||
$canEdit = ContentElementResource::editor();
|
||||
$rows = [];
|
||||
|
||||
$shinkan = $kinds === [CompositionKind::Exercise] || in_array(CompositionKind::Exercise, $kinds, true)
|
||||
? ExerciseSource::query()->whereNotNull('composition_id')->pluck('composition_id')->all()
|
||||
: [];
|
||||
|
||||
$compositions = Composition::query()
|
||||
->whereIn('kind', $kinds)
|
||||
->with(['editorialContentKind', 'versions.members.contentElementVersion.element'])
|
||||
@@ -176,8 +187,8 @@ public function entries(): array
|
||||
}
|
||||
|
||||
$title = $catalog->compositionTitle($composition);
|
||||
$summary = trim((string) ($composition->summary ?? ''));
|
||||
$haystack = mb_strtolower($title.' '.$composition->designation.' '.$summary.' '.(string) $composition->description);
|
||||
$summary = FormattedText::plain((string) ($composition->summary ?? ''));
|
||||
$haystack = mb_strtolower($title.' '.$composition->designation.' '.$summary.' '.FormattedText::plain((string) $composition->description));
|
||||
|
||||
if ($needle !== '' && ! str_contains($haystack, $needle)) {
|
||||
continue;
|
||||
@@ -188,7 +199,7 @@ public function entries(): array
|
||||
$rows[] = [
|
||||
'schluessel' => 'c'.$composition->id,
|
||||
'titel' => $title,
|
||||
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : ''),
|
||||
'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : '').($kind === CompositionKind::Exercise ? ' · Herkunft: '.$this->exerciseOrigin($composition, $shinkan) : ''),
|
||||
'text' => $summary,
|
||||
'bild' => $cover['url'],
|
||||
'bildFehlt' => 'Kein Titelbild',
|
||||
@@ -214,16 +225,43 @@ public function entries(): array
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Herkunft einer Übung: lokal angelegt, aus Shinkan übernommen oder aus Shinkan übernommen und lokal ergänzt.
|
||||
*
|
||||
* @param list<int> $shinkan Übungen mit Quellbindung
|
||||
*/
|
||||
private function exerciseOrigin(Composition $composition, array $shinkan): string
|
||||
{
|
||||
if (! in_array($composition->id, $shinkan, true)) {
|
||||
return 'lokal';
|
||||
}
|
||||
|
||||
$latest = $composition->versions->sortByDesc('number')->first();
|
||||
$local = $latest !== null && CompositionMember::query()->where('composition_version_id', $latest->id)->where('origin', 'lokal')->exists();
|
||||
|
||||
return $local ? 'Shinkan, lokal bearbeitet' : 'Shinkan';
|
||||
}
|
||||
|
||||
/**
|
||||
* Anlegedialog für Module und Programme; derselbe auf dem Arbeitsplatz und in den Listen.
|
||||
*/
|
||||
protected function createCompositionAction(CompositionKind $kind): Action
|
||||
{
|
||||
$label = $kind === CompositionKind::Kurs ? 'Programm' : 'Modul';
|
||||
$label = match ($kind) {
|
||||
CompositionKind::Kurs => 'Programm',
|
||||
CompositionKind::Exercise => 'Übung',
|
||||
CompositionKind::Document => 'Dokument',
|
||||
default => 'Modul',
|
||||
};
|
||||
|
||||
return Action::make($kind === CompositionKind::Kurs ? 'createProgram' : 'createModule')
|
||||
return Action::make(match ($kind) {
|
||||
CompositionKind::Kurs => 'createProgram',
|
||||
CompositionKind::Exercise => 'createExercise',
|
||||
CompositionKind::Document => 'createDocument',
|
||||
default => 'createModule',
|
||||
})
|
||||
->label($label.' anlegen')
|
||||
->modalHeading('Neues '.$label)
|
||||
->modalHeading(($kind === CompositionKind::Exercise ? 'Neue ' : 'Neues ').$label)
|
||||
->modalDescription('Der Name genügt. Danach öffnet sich der Aufbau; Texte, Bilder und Einordnung folgen dort und in der Redaktion.')
|
||||
->modalSubmitActionLabel($label.' anlegen')
|
||||
->modalWidth('lg')
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionKind;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DocumentChapters;
|
||||
use App\Domain\Catalog\DocumentOutline;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Filament\Resources\Compositions\Pages\EditComposition;
|
||||
|
||||
/**
|
||||
* Kapitelarbeitsplatz eines Dokuments im Aufbaueditor (ADR-51). Der Arbeitsplatz hält die Kapitel wie jeden Aufbau als
|
||||
* Mitglieder in `$members`; die Ebene steht in der Rolle („Kapitel“, „Unterkapitel“). Das Kapitel, das gerade offen ist,
|
||||
* liegt in `$partTitle` und `$partBody` (derselbe Editor wie bei jedem Text).
|
||||
*
|
||||
* Offene Eingaben bleiben beim Wechsel des Kapitels erhalten: Der Wechsel legt Titel und Text des verlassenen Kapitels in
|
||||
* `$chapterEdits` ab, und das Öffnen eines Kapitels liest zuerst dort. Geschrieben wird erst mit „Entwurf speichern“
|
||||
* ({@see self::persistChapterEdits()}), und zwar als Entwurfsfassung des Kapitels; bereitgestellt wird erst mit der
|
||||
* Dokumentfassung. Die Reihenfolge ändert immer den ganzen Block aus Kapitel und seinen Unterkapiteln.
|
||||
*
|
||||
* Die Seite stellt `members`, `selected`, `partTitle`, `partBody`, `feedback` und `memberExtras()` bereit
|
||||
* ({@see EditComposition}).
|
||||
*/
|
||||
trait ManagesDocumentChapters
|
||||
{
|
||||
/** @var array<string, array{title: string, body: string}> Ungespeicherte Änderungen je Kapitel (Ziel => Titel und Text) */
|
||||
public array $chapterEdits = [];
|
||||
|
||||
/** @var array<string, string> Gespeicherter Text je Ziel, nur für den Vergleich innerhalb einer Anfrage */
|
||||
private array $chapterBase = [];
|
||||
|
||||
public function isDocument(): bool
|
||||
{
|
||||
return $this->hostKind() === CompositionKind::Document;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Kapitelübersicht: Nummer, Ebene, Titel (auch ein noch nicht gespeicherter) und Stand je Kapitel.
|
||||
*
|
||||
* @return list<array{index: int, number: string, level: int, anchor: string, title: string, changed: bool, draft: bool, selected: bool, first: bool, last: bool}>
|
||||
*/
|
||||
public function chapterRows(): array
|
||||
{
|
||||
$numbering = DocumentOutline::numbering(array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members));
|
||||
$open = $this->openChapterEdit();
|
||||
$rows = [];
|
||||
|
||||
foreach ($this->members as $index => $member) {
|
||||
$target = (string) ($member['target'] ?? '');
|
||||
$edit = $this->chapterEdits[$target] ?? null;
|
||||
$title = $this->selected === $index && $open !== null ? $open['title'] : ($edit['title'] ?? (string) ($member['title'] ?? ''));
|
||||
$rows[] = $numbering[$index] + [
|
||||
'index' => $index,
|
||||
'title' => trim($title) === '' ? 'Ohne Titel' : $title,
|
||||
'changed' => $edit !== null || ($this->selected === $index && $open !== null),
|
||||
'draft' => ($member['version_label'] ?? '') === 'Entwurf',
|
||||
'selected' => $this->selected === $index,
|
||||
'first' => $index === 0,
|
||||
'last' => $index === count($this->members) - 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public function chapterCount(): int
|
||||
{
|
||||
return count($this->members);
|
||||
}
|
||||
|
||||
/** Anzahl der Kapitel mit offenen Änderungen (gespeichert wird mit „Entwurf speichern“). */
|
||||
public function chapterEditCount(): int
|
||||
{
|
||||
return count($this->chapterEditsNow());
|
||||
}
|
||||
|
||||
/**
|
||||
* Wechselt das Kapitel. Das verlassene bleibt mit seinen offenen Eingaben erhalten.
|
||||
*/
|
||||
public function selectChapter(int $index): void
|
||||
{
|
||||
if (! isset($this->members[$index])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$this->selected = $index;
|
||||
$this->panel = 'bestandteil';
|
||||
$this->aufbauTab = 'aufbau';
|
||||
$this->syncRoleDraft();
|
||||
}
|
||||
|
||||
/** Legt das offene Kapitel in den Arbeitsstand, wenn es vom gespeicherten abweicht. */
|
||||
protected function stashChapter(): void
|
||||
{
|
||||
$open = $this->openChapterEdit();
|
||||
$target = $this->selectedChapterTarget();
|
||||
|
||||
if ($target === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($open === null) {
|
||||
unset($this->chapterEdits[$target]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->chapterEdits[$target] = $open;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das offene Kapitel, falls Titel oder Text vom gespeicherten Stand abweichen.
|
||||
*
|
||||
* @return array{title: string, body: string}|null
|
||||
*/
|
||||
protected function openChapterEdit(): ?array
|
||||
{
|
||||
$target = $this->selectedChapterTarget();
|
||||
|
||||
if ($target === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$title = trim($this->partTitle);
|
||||
$body = FormattedText::canonical($this->partBody);
|
||||
$storedTitle = trim((string) ($this->members[$this->selected]['title'] ?? ''));
|
||||
|
||||
if ($title === $storedTitle && FormattedText::same($body, $this->storedChapterBody($target))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['title' => $title, 'body' => $body];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Änderungen, auch die des gerade offenen Kapitels.
|
||||
*
|
||||
* @return array<string, array{title: string, body: string}>
|
||||
*/
|
||||
public function chapterEditsNow(): array
|
||||
{
|
||||
$edits = $this->chapterEdits;
|
||||
$target = $this->selectedChapterTarget();
|
||||
|
||||
if ($target !== null) {
|
||||
$open = $this->openChapterEdit();
|
||||
|
||||
if ($open === null) {
|
||||
unset($edits[$target]);
|
||||
} else {
|
||||
$edits[$target] = $open;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($edits);
|
||||
|
||||
return $edits;
|
||||
}
|
||||
|
||||
private function selectedChapterTarget(): ?string
|
||||
{
|
||||
if (! $this->isDocument() || $this->selected === null || ! isset($this->members[$this->selected])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$target = (string) ($this->members[$this->selected]['target'] ?? '');
|
||||
|
||||
return preg_match('/^element:\d+$/', $target) === 1 ? $target : null;
|
||||
}
|
||||
|
||||
private function storedChapterBody(string $target): string
|
||||
{
|
||||
if (! array_key_exists($target, $this->chapterBase)) {
|
||||
$version = ContentElementVersion::query()->find((int) substr($target, 8));
|
||||
$this->chapterBase[$target] = $version instanceof ContentElementVersion ? (string) $version->body : '';
|
||||
}
|
||||
|
||||
return $this->chapterBase[$target];
|
||||
}
|
||||
|
||||
/**
|
||||
* Titel und Text des gewählten Kapitels in die Eingabefelder laden: zuerst die offenen Eingaben, sonst den gespeicherten Stand.
|
||||
*/
|
||||
protected function loadChapterFields(): void
|
||||
{
|
||||
$target = $this->selectedChapterTarget();
|
||||
|
||||
if ($target === null) {
|
||||
$this->partTitle = '';
|
||||
$this->partBody = '';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$edit = $this->chapterEdits[$target] ?? null;
|
||||
$this->partTitle = $edit['title'] ?? (string) ($this->members[$this->selected]['title'] ?? '');
|
||||
$this->partBody = $edit['body'] ?? FormattedText::canonical($this->storedChapterBody($target));
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibt die offenen Kapitel als Entwurfsfassungen und übernimmt sie in den Aufbau. Eine festgeschriebene Fassung
|
||||
* bleibt unverändert; es entsteht eine neue Entwurfsfassung, die erst mit der Dokumentfassung bereitgestellt wird.
|
||||
*/
|
||||
protected function persistChapterEdits(): bool
|
||||
{
|
||||
if (! $this->isDocument()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->stashChapter();
|
||||
|
||||
foreach ($this->chapterEdits as $target => $edit) {
|
||||
if (trim($edit['title']) === '') {
|
||||
$this->feedback = 'Jedes Kapitel braucht einen Titel.';
|
||||
$this->selectTarget($target);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$service = app(ContentService::class);
|
||||
|
||||
foreach ($this->chapterEdits as $target => $edit) {
|
||||
$index = $this->memberIndex($target);
|
||||
$version = $index === null ? null : ContentElementVersion::query()->with('element')->find((int) substr($target, 8));
|
||||
|
||||
if ($index === null || ! $version instanceof ContentElementVersion || $version->element === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$service->describe($version->element, trim($edit['title']), $version->element->description);
|
||||
$updated = $service->reviseElementDraft($version, $edit['body'] === '' ? '<p></p>' : $edit['body']);
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedback = $exception->getMessage();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($updated->id !== $version->id) {
|
||||
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$updated->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
|
||||
|
||||
if ($row === null) {
|
||||
$this->feedback = 'Die neue Fassung des Kapitels ließ sich nicht übernehmen.';
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->members[$index] = [...$row, 'role' => (string) $this->members[$index]['role'], 'note' => (string) ($this->members[$index]['note'] ?? ''), ...$this->memberExtras($this->members[$index])];
|
||||
} else {
|
||||
$this->members[$index]['title'] = trim($edit['title']);
|
||||
}
|
||||
}
|
||||
|
||||
$this->chapterEdits = [];
|
||||
$this->chapterBase = [];
|
||||
$this->slimChapterMembers();
|
||||
$this->syncRoleDraft();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Kapitelmitglied trägt nur, was die Übersicht braucht. Der Text eines Kapitels liegt in der Datenbank und wird beim
|
||||
* Öffnen gelesen; so bleibt der Zustand der Seite klein, auch bei einem Handbuch mit vielen Kapiteln (jede Anfrage sendet ihn).
|
||||
*/
|
||||
protected function slimChapterMembers(): void
|
||||
{
|
||||
if (! $this->isDocument()) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($this->members as $index => $member) {
|
||||
unset($this->members[$index]['body'], $this->members[$index]['summary'], $this->members[$index]['medium_description'], $this->members[$index]['usage_note'], $this->members[$index]['license_note']);
|
||||
}
|
||||
}
|
||||
|
||||
private function memberIndex(string $target): ?int
|
||||
{
|
||||
foreach ($this->members as $index => $member) {
|
||||
if (($member['target'] ?? '') === $target) {
|
||||
return $index;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function selectTarget(string $target): void
|
||||
{
|
||||
$index = $this->memberIndex($target);
|
||||
|
||||
if ($index !== null) {
|
||||
$this->selected = $index;
|
||||
$this->syncRoleDraft();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt ein neues Kapitel (Ebene 1) oder Unterkapitel (Ebene 2) an. Es steht hinter dem gewählten Kapitel samt dessen
|
||||
* Unterkapiteln beziehungsweise hinter dem gewählten Unterkapitel und ist sofort zum Schreiben geöffnet.
|
||||
*/
|
||||
public function addChapter(int $level = 1): void
|
||||
{
|
||||
abort_unless($this->canEditEditorial(), 403);
|
||||
|
||||
if (($reason = $this->schreibschutz()) !== null) {
|
||||
$this->feedback = $reason;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
$level = $level >= 2 && $this->members !== [] ? 2 : 1;
|
||||
$title = $level === 2 ? 'Neues Unterkapitel' : 'Neues Kapitel';
|
||||
|
||||
try {
|
||||
$service = app(ContentService::class);
|
||||
$element = $service->createElement('text', 'text', $title);
|
||||
$version = $service->draftElementVersion($element, '<p></p>');
|
||||
/** @var Composition $document */
|
||||
$document = $this->getRecord();
|
||||
app(DocumentChapters::class)->mark($element, $document);
|
||||
} catch (DomainRuleException $exception) {
|
||||
$this->feedback = $exception->getMessage();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$version->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
|
||||
|
||||
if ($row === null) {
|
||||
$this->feedback = 'Das Kapitel ließ sich nicht anlegen.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$row['role'] = DocumentOutline::role($level);
|
||||
$row['note'] = '';
|
||||
$row = [...$row, ...$this->memberExtras([])];
|
||||
unset($row['body'], $row['summary'], $row['medium_description'], $row['usage_note'], $row['license_note']);
|
||||
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
|
||||
$at = count($this->members);
|
||||
|
||||
if ($this->selected !== null && isset($this->members[$this->selected])) {
|
||||
$base = $this->selected;
|
||||
$levels = array_column(DocumentOutline::numbering($roles), 'level');
|
||||
|
||||
// Ein neues Kapitel steht hinter dem ganzen gewählten Kapitel, ein Unterkapitel hinter dem gewählten Eintrag.
|
||||
while ($level === 1 && $levels[$base] === 2 && $base > 0) {
|
||||
$base--;
|
||||
}
|
||||
|
||||
$at = DocumentOutline::blockEnd($roles, $base) + 1;
|
||||
}
|
||||
|
||||
array_splice($this->members, $at, 0, [$row]);
|
||||
$this->members = array_values($this->members);
|
||||
$this->selected = $at;
|
||||
$this->panel = 'bestandteil';
|
||||
$this->syncRoleDraft();
|
||||
$this->feedback = '„'.$title.'“ steht jetzt an Stelle '.($at + 1).'. Gib dem Kapitel einen Titel und schreibe den Text; gespeichert wird mit „Entwurf speichern“.';
|
||||
}
|
||||
|
||||
/** Ändert die Ebene: Kapitel oder Unterkapitel. Das erste Kapitel bleibt immer ein Kapitel. */
|
||||
public function setChapterLevel(int $index, int $level): void
|
||||
{
|
||||
if (! isset($this->members[$index])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if ($index === 0 && $level >= 2) {
|
||||
$this->feedback = 'Das erste Kapitel bleibt ein Kapitel: Ein Unterkapitel braucht ein Kapitel davor.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->members[$index]['role'] = DocumentOutline::role($level);
|
||||
$this->syncRoleDraft();
|
||||
$this->feedback = '„'.$this->members[$index]['title'].'“ ist jetzt ein '.DocumentOutline::role($level).'. Die Nummern folgen der Reihenfolge. Gespeichert ist das erst mit „Entwurf speichern“.';
|
||||
}
|
||||
|
||||
/** Verschiebt ein Kapitel mit seinen Unterkapiteln um eine Stelle; ein Unterkapitel wandert auch in das Nachbarkapitel. */
|
||||
public function moveChapter(int $index, int $direction): void
|
||||
{
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if (! isset($this->members[$index]) || ! in_array($direction, [-1, 1], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
|
||||
$levels = array_column(DocumentOutline::numbering($roles), 'level');
|
||||
$end = DocumentOutline::blockEnd($roles, $index);
|
||||
$after = null;
|
||||
|
||||
if ($levels[$index] === 1) {
|
||||
if ($direction < 0) {
|
||||
$previous = null;
|
||||
|
||||
for ($i = $index - 1; $i >= 0; $i--) {
|
||||
if ($levels[$i] === 1) {
|
||||
$previous = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$after = $previous === null ? null : $previous - 1;
|
||||
} elseif (isset($this->members[$end + 1])) {
|
||||
$after = DocumentOutline::blockEnd($roles, $end + 1);
|
||||
}
|
||||
} elseif ($direction < 0) {
|
||||
if ($index > 0 && $levels[$index - 1] === 2) {
|
||||
$after = $index - 2;
|
||||
} elseif ($index - 1 > 0) {
|
||||
// Das erste Unterkapitel wandert ans Ende des vorigen Kapitels.
|
||||
$after = $index - 2;
|
||||
}
|
||||
} elseif (isset($levels[$index + 1])) {
|
||||
// Hinter das nächste Unterkapitel, beziehungsweise als erstes Unterkapitel in das nächste Kapitel.
|
||||
$after = $index + 1;
|
||||
}
|
||||
|
||||
if ($after === null) {
|
||||
$this->feedback = 'Weiter lässt sich dieses Kapitel nicht verschieben.';
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->relocate($index, $end, $after);
|
||||
}
|
||||
|
||||
/** Ablegen per Ziehen: Der Block des gezogenen Kapitels wandert an die Stelle des Ziels. */
|
||||
protected function moveChapterTo(int $from, int $to): void
|
||||
{
|
||||
$this->commitRoleDraft();
|
||||
|
||||
if (! isset($this->members[$from], $this->members[$to]) || $from === $to) {
|
||||
return;
|
||||
}
|
||||
|
||||
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
|
||||
$levels = array_column(DocumentOutline::numbering($roles), 'level');
|
||||
$end = DocumentOutline::blockEnd($roles, $from);
|
||||
|
||||
if ($to >= $from && $to <= $end) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($levels[$from] === 1) {
|
||||
// Ein Kapitel zieht man auf ein Kapitel; ein Unterkapitel als Ziel zählt als sein Kapitel.
|
||||
while ($levels[$to] === 2 && $to > 0) {
|
||||
$to--;
|
||||
}
|
||||
|
||||
$after = $to < $from ? $to - 1 : DocumentOutline::blockEnd($roles, $to);
|
||||
} else {
|
||||
$after = $to < $from ? $to - 1 : $to;
|
||||
}
|
||||
|
||||
$this->relocate($from, $end, $after);
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt den Block `$start..$end` hinter den Eintrag mit dem ursprünglichen Index `$after` (−1 = an den Anfang).
|
||||
*/
|
||||
private function relocate(int $start, int $end, int $after): void
|
||||
{
|
||||
$selectedTarget = $this->selected !== null ? ($this->members[$this->selected]['target'] ?? null) : null;
|
||||
$block = array_slice($this->members, $start, $end - $start + 1);
|
||||
$position = 0;
|
||||
|
||||
foreach (array_keys($this->members) as $i) {
|
||||
if ($i <= $after && ($i < $start || $i > $end)) {
|
||||
$position++;
|
||||
}
|
||||
}
|
||||
|
||||
$rest = array_values(array_filter($this->members, fn (int $i): bool => $i < $start || $i > $end, ARRAY_FILTER_USE_KEY));
|
||||
array_splice($rest, $position, 0, $block);
|
||||
$this->members = $rest;
|
||||
|
||||
// Ein Unterkapitel am Anfang hätte kein Kapitel davor.
|
||||
if (DocumentOutline::level((string) ($this->members[0]['role'] ?? '')) === 2) {
|
||||
$this->members[0]['role'] = DocumentOutline::CHAPTER;
|
||||
}
|
||||
|
||||
$this->selected = $this->memberIndex((string) $selectedTarget) ?? $this->selected;
|
||||
$this->syncRoleDraft();
|
||||
$this->feedback = 'Die Reihenfolge ist geändert. Die Nummern folgen ihr. Gespeichert ist das erst mit „Entwurf speichern“.';
|
||||
}
|
||||
|
||||
/** Entfernt ein Kapitel aus dem Dokument; seine offenen Eingaben entfallen, der Text bleibt im Medienbestand. */
|
||||
protected function forgetChapter(int $index): void
|
||||
{
|
||||
$target = (string) ($this->members[$index]['target'] ?? '');
|
||||
unset($this->chapterEdits[$target]);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 703 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user