diff --git a/CLAUDE.md b/CLAUDE.md index b1d14cf..44e87f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -68,4 +68,5 @@ ## Verwaltungsoberfläche - 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). - 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`. diff --git a/app/Domain/Catalog/CompositionKind.php b/app/Domain/Catalog/CompositionKind.php index 3945b68..1e8d837 100644 --- a/app/Domain/Catalog/CompositionKind.php +++ b/app/Domain/Catalog/CompositionKind.php @@ -9,6 +9,8 @@ enum CompositionKind: string case Kurs = 'kurs'; /** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */ case Exercise = 'exercise'; + /** Ein zusammenhängendes Dokument aus Kapiteln, zum Beispiel ein Trainerhandbuch (ADR-51). */ + case Document = 'document'; /** * @return list @@ -25,6 +27,7 @@ public function label(): string self::Uebung => 'Modul', self::Kurs => 'Kurs', self::Exercise => 'Übung', + self::Document => 'Dokument', }; } @@ -35,6 +38,7 @@ public function plural(): string self::Uebung => 'Module', self::Kurs => 'Kurse', self::Exercise => 'Übungen', + self::Document => 'Dokumente', }; } @@ -45,6 +49,7 @@ public function createLabel(): string self::Uebung => 'Modul anlegen', self::Kurs => 'Kurs anlegen', self::Exercise => 'Übung anlegen', + self::Document => 'Dokument anlegen', }; } @@ -55,6 +60,7 @@ public function explanation(): string self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.', self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.', self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.', + self::Document => 'Ein zusammenhängendes Dokument, zum Beispiel ein Trainerhandbuch, aus Kapiteln und Unterkapiteln. Eine Fassung schreibt Reihenfolge und Texte fest; sie wird in Module und Programme aufgenommen und erscheint für Mitglieder mit Inhaltsverzeichnis und als PDF.', }; } @@ -65,6 +71,7 @@ public function deskLabel(): string self::Uebung => 'Modul', self::Kurs => 'Programm', self::Exercise => 'Übung', + self::Document => 'Dokument', }; } @@ -74,7 +81,7 @@ public function deskExplanation(): string self::Kombination => $this->explanation(), self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.', self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.', - self::Exercise => $this->explanation(), + self::Exercise, self::Document => $this->explanation(), }; } diff --git a/app/Domain/Catalog/ContentResolver.php b/app/Domain/Catalog/ContentResolver.php index 54098ba..6988819 100644 --- a/app/Domain/Catalog/ContentResolver.php +++ b/app/Domain/Catalog/ContentResolver.php @@ -23,7 +23,7 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'path' => $path !== '' ? $path : $node->element->working_title, 'requirement' => CompositionMember::REQUIRED, 'variant' => null, - ]]; + ], ...$this->embeddedImages($node, $path !== '' ? $path : $node->element->working_title, null)]; } if (in_array($node->composition_id, $stack, true)) { @@ -51,6 +51,10 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'variant' => $variantKey, ]; + foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) { + $rows[] = $image; + } + continue; } @@ -79,6 +83,34 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p return $rows; } + /** + * Bilder, auf die ein Text verweist, gehören zum Inhalt des Stands: Nur was im Stand steht, darf ein Mitglied sehen + * (`DecideAccess`), und eine Sperre des Bildes wirkt über denselben Weg. Ein fehlendes Bild macht den Text nicht + * unbrauchbar, daher „ergänzend“. + * + * @return list + */ + private function embeddedImages(?ContentElementVersion $text, string $path, ?string $variantKey): array + { + if ($text === null || trim((string) $text->body) === '' || ! str_contains((string) $text->body, 'img')) { + return []; + } + + $rows = []; + + foreach (FormattedText::imageIds($text->body) as $id) { + $rows[] = [ + 'version_id' => $id, + 'role' => 'Bild', + 'path' => $path.' / Bild', + 'requirement' => CompositionMember::SUPPLEMENTARY, + 'variant' => $variantKey, + ]; + } + + return $rows; + } + public function resolvedHash(ContentElementVersion|CompositionVersion $node): string { $ids = array_values(array_unique(array_column($this->expand($node), 'version_id'))); diff --git a/app/Domain/Catalog/ContentService.php b/app/Domain/Catalog/ContentService.php index fba9675..38545c5 100644 --- a/app/Domain/Catalog/ContentService.php +++ b/app/Domain/Catalog/ContentService.php @@ -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; } diff --git a/app/Domain/Catalog/DocumentChapters.php b/app/Domain/Catalog/DocumentChapters.php new file mode 100644 index 0000000..c4f9013 --- /dev/null +++ b/app/Domain/Catalog/DocumentChapters.php @@ -0,0 +1,28 @@ +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(); + } +} diff --git a/app/Domain/Catalog/DocumentGuide.php b/app/Domain/Catalog/DocumentGuide.php new file mode 100644 index 0000000..9eff4d0 --- /dev/null +++ b/app/Domain/Catalog/DocumentGuide.php @@ -0,0 +1,91 @@ + + */ + 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'); + + $chapters[] = [ + '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' => $view->allowed ? $this->shiftHeadings(FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version))) : null, + 'blocks' => $view->allowed ? FormattedText::blocks($version->body) : null, + ]; + } + + $text = $library->text($document->composition); + + return [ + 'document' => $document, + 'title' => $text['title'], + 'summary_html' => $text['summary_html'], + 'chapters' => $chapters, + ]; + } + + /** + * Zwischenüberschriften im Kapiteltext stehen eine Ebene unter dem Kapiteltitel (h3 wird h4), damit die + * Überschriftenfolge der Seite stimmt: Dokument h1, Kapitel h2, Unterkapitel h3, Zwischenüberschrift h4. + */ + public static function shiftHeadings(string $html): string + { + return (string) preg_replace('/<(\/?)h3(?=[\s>])/i', '<$1h4', $html); + } + + /** + * Darf das PDF entstehen? Jedes Kapitel muss für `laden` zulässig sein; sonst fehlte ein Teil des Handbuchs. + * + * @param array $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; + } +} diff --git a/app/Domain/Catalog/DocumentOutline.php b/app/Domain/Catalog/DocumentOutline.php new file mode 100644 index 0000000..35168a7 --- /dev/null +++ b/app/Domain/Catalog/DocumentOutline.php @@ -0,0 +1,83 @@ += 2 ? self::SUBCHAPTER : self::CHAPTER; + } + + /** + * Ebene und Nummer je Eintrag. Ein Unterkapitel ohne Kapitel davor zählt als Kapitel. + * + * @param list $roles + * @return list + */ + 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 $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; + } +} diff --git a/app/Domain/Catalog/DocumentPdf.php b/app/Domain/Catalog/DocumentPdf.php new file mode 100644 index 0000000..ddb3a5a --- /dev/null +++ b/app/Domain/Catalog/DocumentPdf.php @@ -0,0 +1,196 @@ + */ + private array $starts = []; + + /** + * @param array $guide Ergebnis von {@see DocumentGuide::build} + */ + public function render(array $guide, string $licensee, string $copyId, ?PdfImages $images = null): string + { + $starts = []; + $total = 0; + $bytes = ''; + + for ($pass = 0; $pass < 5; $pass++) { + $bytes = $this->pass($guide, $licensee, $copyId, $images, $starts, $total); + + if ($this->starts === $starts && $this->total === $total) { + break; + } + + $starts = $this->starts; + $total = $this->total; + } + + return $bytes; + } + + /** + * @param array $guide + * @param array $known Kapitelanfänge aus dem vorigen Durchgang + */ + private function pass(array $guide, string $licensee, string $copyId, ?PdfImages $images, array $known, int $total): string + { + $this->pdf = new PdfDocument; + $this->page = 0; + $this->total = 0; + $this->starts = []; + $this->footer = PdfFlow::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)); + $knownTotal = $total; + $this->total = $knownTotal; + $this->newPage(); + + $this->flow->write(PdfFlow::printable((string) $guide['title']), 24, true, 10); + $this->flow->write('Inhaltsverzeichnis', 14, true, 8, keep: 40); + + foreach ($guide['chapters'] as $chapter) { + $this->contentsLine($chapter, $known[$chapter['anchor']] ?? ['page' => 1, 'top' => self::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; + } + + /** + * Eine Zeile des Inhaltsverzeichnisses: Nummer und Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Kapitel. + * + * @param array $chapter + * @param array{page: int, top: float} $target + */ + private function contentsLine(array $chapter, array $target): void + { + $level = $chapter['level']; + $size = $level === 1 ? 11.0 : 10.0; + $indent = $level === 1 ? 0.0 : 18.0; + $label = PdfFlow::printable($chapter['number'].' '.$chapter['title']); + $pageText = (string) $target['page']; + $numberWidth = PdfDocument::exactWidth($pageText, $size, false); + $lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $level === 1); + $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, $level === 1); + + if ($index === count($lines) - 1) { + $used = PdfDocument::exactWidth($line, $size, $level === 1) + 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 $chapter + */ + private function chapter(array $chapter): void + { + $level = $chapter['level']; + + if ($level === 1) { + $this->closePage(); + $this->newPage(); + } + + $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(); + } + + 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.($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'; + } +} diff --git a/app/Domain/Catalog/DocumentReader.php b/app/Domain/Catalog/DocumentReader.php new file mode 100644 index 0000000..b625982 --- /dev/null +++ b/app/Domain/Catalog/DocumentReader.php @@ -0,0 +1,82 @@ + + */ + 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|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 $items + * @return list + */ + 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); + } +} diff --git a/app/Domain/Catalog/EditorialContentKind.php b/app/Domain/Catalog/EditorialContentKind.php index 1fa989a..4026cd2 100644 --- a/app/Domain/Catalog/EditorialContentKind.php +++ b/app/Domain/Catalog/EditorialContentKind.php @@ -18,6 +18,7 @@ class EditorialContentKind extends Model 'medium' => 'Medium', 'modul' => 'Modul', 'uebung' => 'Übung', + 'dokument' => 'Dokument', 'programm' => 'Programm', 'lizenzartikel' => 'Lizenzartikel', ]; @@ -27,7 +28,7 @@ class EditorialContentKind extends Model * Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt * pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt. */ - public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung', self::EXERCISE_SECTION_SLUG]; + 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 @@ -35,6 +36,9 @@ class EditorialContentKind extends Model */ public const EXERCISE_SECTION_SLUG = 'uebungsabschnitt'; + /** Kapitel eines Dokuments: wie Übungsabschnitte nur automatisch gesetzt, nie öffentlich (ADR-51). */ + public const DOCUMENT_CHAPTER_SLUG = 'dokumentkapitel'; + protected $fillable = [ 'slug', 'label', @@ -83,7 +87,7 @@ public function allows(string $context): bool /** Wird nie von Hand gewählt, sondern von der Übungsverwaltung gesetzt. */ public function isAutomatic(): bool { - return $this->slug === self::EXERCISE_SECTION_SLUG; + return in_array($this->slug, [self::EXERCISE_SECTION_SLUG, self::DOCUMENT_CHAPTER_SLUG], true); } public function isSystem(): bool diff --git a/app/Domain/Catalog/EditorialVocabulary.php b/app/Domain/Catalog/EditorialVocabulary.php index fea6138..9a8b9ed 100644 --- a/app/Domain/Catalog/EditorialVocabulary.php +++ b/app/Domain/Catalog/EditorialVocabulary.php @@ -47,6 +47,7 @@ public static function compositionContext(?CompositionKind $kind): ?string CompositionKind::Kurs => 'programm', CompositionKind::Uebung => 'modul', CompositionKind::Exercise => 'uebung', + CompositionKind::Document => 'dokument', default => null, }; } @@ -181,6 +182,7 @@ private function usedKindIds(string $context): array 'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value), 'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value), 'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value), + 'dokument' => DB::table('compositions')->where('kind', CompositionKind::Document->value), default => null, }; diff --git a/app/Domain/Catalog/EmbeddedImages.php b/app/Domain/Catalog/EmbeddedImages.php new file mode 100644 index 0000000..15be9c3 --- /dev/null +++ b/app/Domain/Catalog/EmbeddedImages.php @@ -0,0 +1,191 @@ + ['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 $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, + ]; + } +} diff --git a/app/Domain/Catalog/ExerciseGuide.php b/app/Domain/Catalog/ExerciseGuide.php index 27416d0..584c08f 100644 --- a/app/Domain/Catalog/ExerciseGuide.php +++ b/app/Domain/Catalog/ExerciseGuide.php @@ -45,7 +45,7 @@ public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $rel * * @return array{version: CompositionVersion, selection: list|null}|null */ - public function locate(ArticleRelease $release, string $path): ?array + public function locate(ArticleRelease $release, string $path, CompositionKind $kind = CompositionKind::Exercise): ?array { if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) { return null; @@ -71,7 +71,7 @@ public function locate(ArticleRelease $release, string $path): ?array $version?->loadMissing('composition'); - if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) { + if ($version === null || $version->composition === null || $version->composition->kind !== $kind) { return null; } @@ -114,6 +114,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea { $exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']); $library = app(LibraryCatalog::class); + $embedded = app(EmbeddedImages::class); $offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values(); $chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first(); $entries = []; @@ -146,7 +147,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea '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) : null, + 'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version)) : null, ]; } diff --git a/app/Domain/Catalog/ExercisePdf.php b/app/Domain/Catalog/ExercisePdf.php index f7c837b..00ac074 100644 --- a/app/Domain/Catalog/ExercisePdf.php +++ b/app/Domain/Catalog/ExercisePdf.php @@ -3,6 +3,7 @@ namespace App\Domain\Catalog; use App\Domain\Commerce\Receipt\PdfDocument; +use Closure; use Transliterator; /** @@ -23,7 +24,7 @@ class ExercisePdf private PdfDocument $pdf; - private float $y = self::TOP; + private PdfFlow $flow; private int $page = 0; @@ -64,32 +65,36 @@ public function sections(array $guide): ?array * @param array $guide * @param list> $sections */ - public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string + public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl, ?PdfImages $images = null): string { $this->pdf = new PdfDocument; $this->page = 0; $this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId); + $this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void { + $this->closePage(); + $this->newPage(); + }, $images === null ? null : Closure::fromCallable($images)); $this->newPage(); - $this->write(self::printable((string) $guide['title']), 18, true, 8); + $this->flow->write(self::printable((string) $guide['title']), 18, true, 8); if ($variantName !== '') { - $this->write(self::printable('Variante: '.$variantName), 11, true, 6); + $this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6); } $this->fact('Lernziel', $guide['learning_goal']); if ($guide['duration_minutes'] !== null) { - $this->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4); + $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->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4); + $this->flow->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4); } $this->fact('Ausstattung', $guide['material_note']); - $this->y -= 6; + $this->flow->y -= 6; foreach ($sections as $section) { $this->section($section, $guideUrl); @@ -108,16 +113,7 @@ public function render(array $guide, array $sections, string $licensee, string $ */ public static function printable(string $text): string { - $text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']); - $latin = Transliterator::create('Any-Latin; Latin-ASCII'); - $out = ''; - - foreach (mb_str_split($text) as $char) { - $encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8'); - $out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char; - } - - return $out; + return PdfFlow::printable($text); } /** @@ -131,16 +127,16 @@ private function section(array $section, string $guideUrl): void $label = in_array($section['class'], ['film', 'audio'], true) ? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl : 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl; - $this->write(self::printable($label), 10, false, 6); + $this->flow->write(self::printable($label), 10, false, 6); return; } - $this->write($title, 12.5, true, 5); + $this->flow->write($title, 12.5, true, 5, keep: 40); - $this->formatted($section['blocks'] ?? []); + $this->flow->formatted($section['blocks'] ?? []); - $this->y -= 4; + $this->flow->y -= 4; } /** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */ @@ -153,177 +149,20 @@ private function fact(string $label, ?string $value): void } if (count($blocks) === 1 && $blocks[0]['type'] === 'paragraph') { - $this->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4); + $this->flow->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4); return; } - $this->write(self::printable($label.':'), 10.5, true, 2); - $this->formatted($blocks); - } - - /** - * Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv. - * - * @param list> $blocks - */ - private function formatted(array $blocks): void - { - foreach ($blocks as $block) { - match ($block['type']) { - 'heading' => $this->runs($block['runs'], self::LEFT, 11, bold: true, after: 4), - 'quote' => $this->runs($block['runs'], self::LEFT + 14, 10.5, italic: true, after: 5), - 'bullets' => $this->listItems($block['items'], fn (int $n): string => '•'), - 'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.'), - default => $this->runs($block['runs'] ?? [], self::LEFT, 10.5, after: 5), - }; - } - } - - /** - * @param list> $items - */ - private function listItems(array $items, callable $marker): void - { - foreach ($items as $index => $item) { - $this->room(14); - $this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5); - $this->runs($item, self::LEFT + 18, 10.5, after: 1); - } - - $this->y -= 3; - } - - /** - * Setzt Textabschnitte mit fett und kursiv in Zeilen um. Die Breite kommt aus den Schriftbreiten der Helvetica - * ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen. - * Links erscheinen mit ausgeschriebener Adresse, weil sie auf Papier sonst verloren gehen. - * - * @param list $runs - */ - private function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void - { - $maxWidth = self::RIGHT - $x; - $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) 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]; - $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) { - $line[array_key_last($line)][0] .= $space.$word; - } else { - $line[] = [$space.$word, $isBold, $isItalic]; - } - - $width += $need; - $pendingSpace = false; - }; - - foreach ($runs as $index => $run) { - $isBold = $bold || $run['bold']; - $isItalic = $italic || $run['italic']; - - foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) { - if (trim($token) !== '') { - $place($token, $isBold, $isItalic); - - continue; - } - - if (str_contains($token, "\n")) { - $flush(); - - continue; - } - - $pendingSpace = true; - } - - $nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null; - - if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) { - $pendingSpace = true; - $place('('.self::printable($run['href']).')', false, false); - } - } - - $flush(); - - foreach ($lines as $row) { - $this->room($size + 4); - $cursor = $x; - - foreach ($row as [$text, $isBold, $isItalic]) { - $this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic); - $cursor += PdfDocument::exactWidth($text, $size, $isBold); - } - - $this->y -= $size + 4; - } - - $this->y -= $after; - } - - private function write(string $text, float $size, bool $bold, float $after): void - { - foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) { - $this->room($size + 4); - $this->pdf->text(self::LEFT, $this->y, $line, $size, $bold); - $this->y -= $size + 4; - } - - $this->y -= $after; - } - - private function room(float $needed): void - { - if ($this->y - $needed < self::BOTTOM) { - $this->closePage(); - $this->newPage(); - } + $this->flow->write(self::printable($label.':'), 10.5, true, 2); + $this->flow->formatted($blocks); } private function newPage(): void { $this->pdf->addPage(); $this->page++; - $this->y = self::TOP; + $this->flow->restart(); } private function closePage(): void diff --git a/app/Domain/Catalog/FormattedText.php b/app/Domain/Catalog/FormattedText.php index 1ff124e..11fb890 100644 --- a/app/Domain/Catalog/FormattedText.php +++ b/app/Domain/Catalog/FormattedText.php @@ -8,11 +8,15 @@ use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; /** - * Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50). + * Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51). * * Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschrift (h3), fett, kursiv, Aufzählung, - * nummerierte Liste, Zitat, Link und Zeilenumbruch. Alles andere fällt beim Speichern weg, auch Skripte, Ereignis­attribute - * und Links auf andere Schemata als http, https und mailto. + * nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte, + * Ereignis­attribute und Links auf andere Schemata als http, https und mailto. + * + * Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`…`). + * 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 @@ -25,7 +29,7 @@ final class FormattedText { /** Blockelemente, mit denen gespeichertes HTML beginnt. */ - private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote']; + private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote', 'table', 'img']; /** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */ public const FIELDS = ['summary', 'description']; @@ -33,7 +37,13 @@ final class FormattedText private static ?HtmlSanitizer $sanitizer = null; /** Symbolleiste der Editoren; muss zur Auswahl oben passen. */ - public const TOOLBAR = [['bold', 'italic', 'link'], ['h3'], ['bulletList', 'orderedList', 'blockquote'], ['undo', 'redo']]; + public const TOOLBAR = [ + ['bold', 'italic', 'link'], + ['h3'], + ['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 @@ -66,21 +76,121 @@ public static function canonicalHtml(?string $html): string return $html === '' ? '' : self::normalize($html); } - /** Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. */ - public static function html(?string $value): string + /** + * 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::canonical($value); + 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): string + public static function display(?string $value, ?callable $images = null): string { $value = (string) $value; - return self::isHtml($value) ? self::canonical($value) : nl2br(e($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 + */ + public static function imageIds(?string $value): array + { + $html = self::canonical($value); + + if ($html === '' || ! str_contains($html, ''.$html.'', 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; + } + + /** + * 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, ''.$html.'', 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, ''.$html.'', 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 @@ -103,16 +213,37 @@ public static function plain(?string $value): string $out = []; foreach (self::blocks($value) as $block) { - $out[] = 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']))), - default => self::runsText($block['runs']), - }; + $text = self::plainBlock($block); + + if ($text !== '') { + $out[] = $text; + } } return trim(implode("\n\n", $out)); } + /** + * @param array $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 { @@ -123,9 +254,10 @@ public static function excerpt(?string $value, int $length = 120): string /** * Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und - * `href`. + * `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, items?: list>}> + * @return list> */ public static function blocks(?string $value): array { @@ -136,9 +268,18 @@ public static function blocks(?string $value): array } $document = HTMLDocument::createFromString(''.$html.'', LIBXML_NOERROR); + + return self::extractBlocks($document->body); + } + + /** + * @return list> + */ + private static function extractBlocks(Node $parent): array + { $blocks = []; - foreach ($document->body->childNodes as $node) { + foreach ($parent->childNodes as $node) { if ($node->nodeType !== XML_ELEMENT_NODE) { continue; } @@ -159,14 +300,78 @@ public static function blocks(?string $value): array continue; } - $blocks[] = [ - 'type' => match ($name) { - 'h3' => 'heading', - 'blockquote' => 'quote', - default => 'paragraph', - }, - 'runs' => self::runs($node), - ]; + 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; + } + + $type = match ($name) { + 'h3' => 'heading', + '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[] = ['type' => $type, 'runs' => 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[] = ['type' => $type, 'runs' => $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[] = ['type' => $type, 'runs' => $pending]; + } } return $blocks; @@ -203,6 +408,15 @@ private static function normalize(string $html): string $document = HTMLDocument::createFromString(''.$html.'', 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 = ''; @@ -229,7 +443,7 @@ private static function normalize(string $html): string $flush(); - return self::hasText($out) ? $out : ''; + return self::hasText($out) || str_contains($out, 'nodeName); + if ($name === 'img') { + $id = (int) $node->getAttribute('data-id'); + + return $id > 0 ? ''.e(trim((string) $node->getAttribute('alt'))).'' : ''; + } + + if ($name === 'table') { + return self::table($node); + } + if (in_array($name, ['ul', 'ol'], true)) { $items = ''; @@ -265,7 +489,46 @@ private static function block(Node $node): string $inner = '

'.$inner.'

'; } - return self::hasText($inner) ? '<'.$name.'>'.$inner.'' : ''; + return self::hasContent($inner) ? '<'.$name.'>'.$inner.'' : ''; + } + + /** + * 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 === '' ? '

' : (preg_match('/^<(?:p|ul|ol|blockquote|h3|img)[\s>]/', $inner) === 1 ? $inner : '

'.$inner.'

')).''; + } + + if ($cells !== '') { + $rows .= ''.$cells.''; + } + } + + return $rows !== '' && (self::hasText($rows) || str_contains($rows, ''.$rows.'' : ''; } private static function inner(Node $node): string @@ -273,7 +536,7 @@ 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'], true)) { + if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote', 'img'], true)) { $html .= self::block($child); continue; @@ -285,6 +548,28 @@ private static function inner(Node $node): string 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, '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) diff --git a/app/Domain/Catalog/PdfFlow.php b/app/Domain/Catalog/PdfFlow.php new file mode 100644 index 0000000..7efaab3 --- /dev/null +++ b/app/Domain/Catalog/PdfFlow.php @@ -0,0 +1,622 @@ +y = $top; + } + + /** + * Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere + * lateinische Buchstaben); sonst bleibt „?“. + */ + public static function printable(string $text): string + { + $text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']); + $latin = Transliterator::create('Any-Latin; Latin-ASCII'); + $out = ''; + + foreach (mb_str_split($text) as $char) { + $encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8'); + $out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char; + } + + return $out; + } + + /** 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> $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 $block + */ + private function headingBlock(array $block, float $x, float $size): void + { + // Eine Zwischenüberschrift bleibt bei ihrem Text: mindestens zwei Zeilen müssen mit auf die Seite. + $this->room(($size + 0.5) + 4 + 2 * ($size + 4)); + $this->runs($block['runs'], $x, $size + 0.5, bold: true, after: 4); + } + + /** + * @param list> $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. Links erscheinen mit ausgeschriebener + * Adresse, weil sie auf Papier sonst verloren gehen. + * + * @param list $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); + $cursor = $x; + + foreach ($row as [$text, $isBold, $isItalic]) { + $this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic); + $cursor += PdfDocument::exactWidth($text, $size, $isBold); + } + + $this->y -= $size + 4; + } + + $this->y -= $after; + } + + /** + * 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 $runs + * @return list> + */ + 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) 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]; + $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) { + $line[array_key_last($line)][0] .= $space.$word; + } else { + $line[] = [$space.$word, $isBold, $isItalic]; + } + + $width += $need; + $pendingSpace = false; + }; + + foreach ($runs as $index => $run) { + $isBold = $bold || $run['bold']; + $isItalic = $italic || $run['italic']; + + foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) { + if (trim($token) !== '') { + $place($token, $isBold, $isItalic); + + continue; + } + + if (str_contains($token, "\n")) { + $flush(); + + continue; + } + + $pendingSpace = true; + } + + $nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null; + + if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) { + $pendingSpace = true; + $place('('.self::printable($run['href']).')', false, false); + } + } + + $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 $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>> $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']; + + foreach ($line['segments'] as [$text, $isBold, $isItalic]) { + $this->pdf->text($cursor, $textY, $text, $size, $isBold || $cell['header'], $isItalic); + $cursor += PdfDocument::exactWidth($text, $size, $isBold || $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>> $rows + * @return array{columns: int, cells: list>} + */ + 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> $cells + * @return list + */ + 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> $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> $blocks + * @return list> + */ + 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; + } +} diff --git a/app/Domain/Catalog/PdfImages.php b/app/Domain/Catalog/PdfImages.php new file mode 100644 index 0000000..536e2f6 --- /dev/null +++ b/app/Domain/Catalog/PdfImages.php @@ -0,0 +1,49 @@ + */ + 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 + */ + 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; + } +} diff --git a/app/Domain/Cms/Catalog/PublicMaterialReader.php b/app/Domain/Cms/Catalog/PublicMaterialReader.php index 66fa673..0fc5e96 100644 --- a/app/Domain/Cms/Catalog/PublicMaterialReader.php +++ b/app/Domain/Cms/Catalog/PublicMaterialReader.php @@ -39,7 +39,7 @@ class PublicMaterialReader { /** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen: Anleitungen für Trainer und die Textabschnitte der Übungen. */ - public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt']; + public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt', 'dokumentkapitel']; /** @var array|null Element-ID => erstes öffentliches Programm */ private ?array $publicIndex = null; diff --git a/app/Domain/Commerce/Receipt/PdfDocument.php b/app/Domain/Commerce/Receipt/PdfDocument.php index fb73e0e..ba4e4c4 100644 --- a/app/Domain/Commerce/Receipt/PdfDocument.php +++ b/app/Domain/Commerce/Receipt/PdfDocument.php @@ -7,6 +7,10 @@ * WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und * enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können. * Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“). + * + * Für längere Dokumente (Handbuch) kann der Schreiber zusätzlich Flächen, JPEG-Bilder, Verweise innerhalb des Dokuments + * (Inhaltsverzeichnis) und Lesezeichen setzen. Wer sie nicht nutzt, erhält dieselben Bytes wie zuvor: Die zusätzlichen + * Objekte entstehen nur bei Bedarf und nach allen bisherigen. */ final class PdfDocument { @@ -20,6 +24,21 @@ final class PdfDocument /** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */ private bool $usesItalic = false; + /** @var list */ + private array $images = []; + + /** @var array Prüfsumme der Bilddatei => Index in {@see self::$images} */ + private array $imageIndex = []; + + /** @var array> Seite => Bilder, die sie zeigt */ + private array $pageImages = []; + + /** @var array> */ + private array $links = []; + + /** @var list */ + 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]; @@ -31,6 +50,60 @@ 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]; + } + + /** Lesezeichen (Ebene 1 oder 2) 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' => $level >= 2 ? 2 : 1]; + } + 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'); @@ -145,9 +218,39 @@ public function output(string $title, ?string $keywords = null): string $kids = []; $next = 6; - foreach ($pages as $stream) { + // Nummern der zusätzlichen Objekte: nach den Seiten und Schriften, in fester Reihenfolge (Verweise, Bilder, Gliederung). + $cursor = 6 + 2 * count($pages) + ($this->usesItalic ? 2 : 0); + $annotations = []; + + foreach ($this->links as $pageIndex => $links) { + foreach ($links as $link) { + $annotations[$pageIndex][] = ['number' => $cursor++] + $link; + } + } + + $imageNumbers = []; + + foreach (array_keys($this->images) as $index) { + $imageNumbers[$index] = $cursor++; + } + + $outlineRoot = $this->outline === [] ? null : $cursor++; + $outlineNumbers = []; + + foreach (array_keys($this->outline) as $index) { + $outlineNumbers[$index] = $cursor++; + } + + foreach ($pages as $pageIndex => $stream) { $kids[] = $next.' 0 R'; - $objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >> >> /Contents '.($next + 1).' 0 R >>'; + $xobjects = ''; + + foreach (array_keys($this->pageImages[$pageIndex] ?? []) as $index) { + $xobjects .= ' /Im'.($index + 1).' '.$imageNumbers[$index].' 0 R'; + } + + $annots = isset($annotations[$pageIndex]) ? ' /Annots ['.implode(' ', array_map(fn (array $link): string => $link['number'].' 0 R', $annotations[$pageIndex])).']' : ''; + $objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >>'.($xobjects === '' ? '' : ' /XObject <<'.$xobjects.' >>').' >> /Contents '.($next + 1).' 0 R'.$annots.' >>'; $objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream'; $next += 2; } @@ -161,6 +264,32 @@ public function output(string $title, ?string $keywords = null): string } } + foreach ($annotations as $links) { + foreach ($links as $link) { + $objects[$link['number']] = sprintf( + '<< /Type /Annot /Subtype /Link /Rect [%s %s %s %s] /Border [0 0 0] /Dest [%d 0 R /XYZ 0 %s null] >>', + $this->n($link['x']), + $this->n($link['y']), + $this->n($link['x'] + $link['w']), + $this->n($link['y'] + $link['h']), + 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 >>'; @@ -186,6 +315,46 @@ public function output(string $title, ?string $keywords = null): string return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n"; } + /** + * Gliederung (Lesezeichen): Ebene 1 unter der Wurzel, Ebene 2 unter dem vorangehenden Eintrag der Ebene 1. + * + * @param array $numbers Objektnummer je Eintrag + * @return array + */ + private function outlineObjects(int $root, array $numbers, int $pageCount): array + { + $parentOf = []; + $childrenOf = []; + $lastTop = null; + + foreach ($this->outline as $index => $item) { + if ($item['level'] === 1 || $lastTop === null) { + $parentOf[$index] = null; + $lastTop = $index; + } else { + $parentOf[$index] = $lastTop; + } + + $childrenOf[$parentOf[$index] ?? -1][] = $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 '.count($kids)) + .' /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 === []) { diff --git a/app/Domain/Media/PdfImage.php b/app/Domain/Media/PdfImage.php new file mode 100644 index 0000000..61b8e4f --- /dev/null +++ b/app/Domain/Media/PdfImage.php @@ -0,0 +1,56 @@ + $jpeg, 'width' => $targetWidth, 'height' => $targetHeight] : null; + } +} diff --git a/app/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index 7934111..6b6d016 100644 --- a/app/Filament/Resources/Compositions/Pages/EditComposition.php +++ b/app/Filament/Resources/Compositions/Pages/EditComposition.php @@ -27,6 +27,7 @@ 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; @@ -50,6 +51,7 @@ abstract class EditComposition extends EditRecord { use AssignsPillars; + use ManagesDocumentChapters; use ManagesEditorialSurface; use ManagesRichFields; use WithFileUploads; @@ -278,6 +280,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]); } @@ -371,8 +377,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.', @@ -401,6 +417,16 @@ protected function richFelder(): array ]; } + /** + * Texte dürfen Bilder aus dem Medienbestand enthalten (gemeinsamer Picker); Kurzangaben nicht. + * + * @return list + */ + protected function richBilder(): array + { + return ['partBody', 'newTextBody']; + } + /** * @return list> */ @@ -695,10 +721,16 @@ 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 @@ -712,6 +744,12 @@ public function armRelease(): void $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.'; @@ -761,6 +799,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); @@ -797,6 +840,7 @@ public function discardDraft(): void $record = $this->getRecord(); app(EditorialWorkingDraft::class)->clear($record); $this->releaseArmed = false; + $this->chapterEdits = []; $this->loadAufbau(); $this->selected = null; $this->selectFirstPart(); @@ -842,6 +886,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); @@ -1174,6 +1224,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); @@ -1196,7 +1251,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, ]; @@ -1211,6 +1268,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; @@ -1729,6 +1792,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); @@ -1744,6 +1812,10 @@ public function publishRevision(): bool $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.'; @@ -1803,7 +1875,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; @@ -1959,6 +2033,7 @@ protected function applyDraft(array $draft): void } $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'] ?? ''); @@ -1979,6 +2054,7 @@ 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()); @@ -2004,6 +2080,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); } @@ -2013,6 +2096,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'] ?? '') : ''; } @@ -2330,6 +2420,8 @@ protected function payload(): array 'prerequisites' => $this->blank($this->prerequisites), 'variants' => $this->normalizeVariants($this->variants), 'revision_note' => $this->blank($this->revisionNote), + // 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'] ?? '')), @@ -2432,6 +2524,7 @@ protected function normalizePayload(array $payload): array 'prerequisites' => $payload['prerequisites'] ?? null, 'variants' => $this->normalizeVariants($payload['variants'] ?? []), 'revision_note' => $payload['revision_note'] ?? null, + 'chapters' => is_array($payload['chapters'] ?? null) ? $payload['chapters'] : [], 'members' => $members, ]; } diff --git a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php index bb89d40..3f96d74 100644 --- a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php +++ b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php @@ -34,12 +34,12 @@ protected function fixedKind(): ?CompositionKind private function onDesk(): bool { - return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise], true); + return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise, CompositionKind::Document], true); } public function getSubheading(): string|Htmlable|null { - $desk = $this->onDesk() && $this->kind() !== CompositionKind::Exercise ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : ''; + $desk = $this->onDesk() && ! in_array($this->kind(), [CompositionKind::Exercise, CompositionKind::Document], true) ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : ''; return $this->kind()->deskExplanation().$desk; } diff --git a/app/Filament/Resources/ContentElements/Pages/EditContentElement.php b/app/Filament/Resources/ContentElements/Pages/EditContentElement.php index 815f998..5f6e298 100644 --- a/app/Filament/Resources/ContentElements/Pages/EditContentElement.php +++ b/app/Filament/Resources/ContentElements/Pages/EditContentElement.php @@ -8,6 +8,7 @@ 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; @@ -195,7 +196,7 @@ protected function mutateFormDataBeforeFill(array $data): array return [ 'working_title' => $this->getRecord()->working_title, 'thumbnail_alt' => $this->getRecord()->thumbnail_alt, - 'body' => FormattedText::html($this->getRecord()->versions()->orderByDesc('number')->first()?->body), + 'body' => EmbeddedImages::forEditor($this->getRecord()->versions()->orderByDesc('number')->first()?->body), 'display_title' => $this->getRecord()->display_title, 'description' => FormattedText::html($this->getRecord()->description), 'usage_note' => $this->getRecord()->usage_note, diff --git a/app/Filament/Resources/ContentElements/Pages/ListContentElements.php b/app/Filament/Resources/ContentElements/Pages/ListContentElements.php index 071048c..79738d4 100644 --- a/app/Filament/Resources/ContentElements/Pages/ListContentElements.php +++ b/app/Filament/Resources/ContentElements/Pages/ListContentElements.php @@ -514,7 +514,7 @@ private function filterPills(): array $multi = $this->multiFields(); if ($this->arten === '') { - $pills[] = ['feld' => 'arten', 'label' => 'Übungsabschnitte ausgeblendet', 'info' => true]; + $pills[] = ['feld' => 'arten', 'label' => 'Übungsabschnitte und Dokumentkapitel ausgeblendet', 'info' => true]; } else { $selected = $this->selectedArten(); @@ -568,7 +568,7 @@ public function bestand(): array '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, die Texte der Übungen, erscheinen erst, wenn du sie unter Materialart ankreuzt. „Als Standard speichern“ merkt die Filter für dein Konto, ohne die Suche.', + '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.', ]; return [ @@ -576,7 +576,7 @@ public function bestand(): array '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 die Übungsabschnitte.' : null, + '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', ]; diff --git a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php index b41a36d..c733a5c 100644 --- a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php +++ b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php @@ -791,6 +791,14 @@ protected function richFelder(): array return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Ausführliche Beschreibung', 'bodyDraft' => 'Text der Fassung']; } + /** + * @return list + */ + protected function richBilder(): array + { + return ['bodyDraft']; + } + /** * @return list> */ diff --git a/app/Filament/Resources/Documents/DocumentResource.php b/app/Filament/Resources/Documents/DocumentResource.php new file mode 100644 index 0000000..9e9b3f9 --- /dev/null +++ b/app/Filament/Resources/Documents/DocumentResource.php @@ -0,0 +1,38 @@ + ListDocuments::route('/'), + 'edit' => EditDocument::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Documents/Pages/EditDocument.php b/app/Filament/Resources/Documents/Pages/EditDocument.php new file mode 100644 index 0000000..091ef43 --- /dev/null +++ b/app/Filament/Resources/Documents/Pages/EditDocument.php @@ -0,0 +1,11 @@ + 'PDF ansehen', 'pdf:laden' => 'PDF herunterladen', 'text:ansehen' => 'Text ansehen', + 'text:laden' => 'Text als PDF herunterladen (Übung, Dokument)', 'bild:ansehen' => 'Bild ansehen', ]; diff --git a/app/Filament/Support/ChoosesMedia.php b/app/Filament/Support/ChoosesMedia.php index 47bd4d2..f3f5daf 100644 --- a/app/Filament/Support/ChoosesMedia.php +++ b/app/Filament/Support/ChoosesMedia.php @@ -106,13 +106,15 @@ public function pickerResult(): array return ['items' => [], 'more' => false]; } - if ($this->pickerPurpose === 'aufbau') { + 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, )); } diff --git a/app/Filament/Support/EditorialCatalog.php b/app/Filament/Support/EditorialCatalog.php index 865cb22..2d5eef5 100644 --- a/app/Filament/Support/EditorialCatalog.php +++ b/app/Filament/Support/EditorialCatalog.php @@ -21,6 +21,7 @@ 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; @@ -297,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]) @@ -321,7 +322,7 @@ 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) @@ -331,6 +332,10 @@ public function browse(string $query, string $kind, string $dimension, int $exce $builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]); } + if ($kind === 'dokumentfassung') { + $builder->where('kind', CompositionKind::Document); + } + if ($dimensionId > 0) { $builder->whereIn('id', $this->dimensionSubjectIds(Composition::class, $dimensionId)); } @@ -370,6 +375,8 @@ 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); }) @@ -1085,6 +1092,7 @@ public function create(string $designation, CompositionKind $kind): Composition CompositionKind::Kurs => 'programm', CompositionKind::Uebung => 'modul', CompositionKind::Exercise => 'uebung', + CompositionKind::Document => 'dokument', default => null, }; $editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first(); @@ -1107,6 +1115,7 @@ public static function editUrl(Composition $composition): string CompositionKind::Kombination => CombinationResource::class, CompositionKind::Uebung => ExerciseResource::class, CompositionKind::Exercise => PracticeResource::class, + CompositionKind::Document => DocumentResource::class, }; return $resource::getUrl('edit', ['record' => $composition]); diff --git a/app/Filament/Support/ElementRevision.php b/app/Filament/Support/ElementRevision.php index fa3fcd1..2c255f7 100644 --- a/app/Filament/Support/ElementRevision.php +++ b/app/Filament/Support/ElementRevision.php @@ -6,6 +6,7 @@ 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; @@ -71,7 +72,7 @@ public static function fields(ContentElement $element): array $latest = $element->versions()->orderByDesc('number')->first(); return [ - RichField::make('body', 'Text', live: false)->default(FormattedText::html($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') diff --git a/app/Filament/Support/ListsCompositions.php b/app/Filament/Support/ListsCompositions.php index c22dc83..8820a76 100644 --- a/app/Filament/Support/ListsCompositions.php +++ b/app/Filament/Support/ListsCompositions.php @@ -78,6 +78,7 @@ public function bestand(): array 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'], }; @@ -118,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.', ], @@ -247,12 +250,14 @@ protected function createCompositionAction(CompositionKind $kind): Action $label = match ($kind) { CompositionKind::Kurs => 'Programm', CompositionKind::Exercise => 'Übung', + CompositionKind::Document => 'Dokument', default => 'Modul', }; return Action::make(match ($kind) { CompositionKind::Kurs => 'createProgram', CompositionKind::Exercise => 'createExercise', + CompositionKind::Document => 'createDocument', default => 'createModule', }) ->label($label.' anlegen') diff --git a/app/Filament/Support/ManagesDocumentChapters.php b/app/Filament/Support/ManagesDocumentChapters.php new file mode 100644 index 0000000..2d2975d --- /dev/null +++ b/app/Filament/Support/ManagesDocumentChapters.php @@ -0,0 +1,506 @@ + Ungespeicherte Änderungen je Kapitel (Ziel => Titel und Text) */ + public array $chapterEdits = []; + + /** @var array 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 + */ + 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 + */ + 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'] === '' ? '

' : $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, '

'); + /** @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]); + } +} diff --git a/app/Filament/Support/ManagesEditorialSurface.php b/app/Filament/Support/ManagesEditorialSurface.php index 801b383..9b11d77 100644 --- a/app/Filament/Support/ManagesEditorialSurface.php +++ b/app/Filament/Support/ManagesEditorialSurface.php @@ -15,6 +15,7 @@ use App\Domain\Media\WebsiteRelease; use App\Filament\Resources\ContentElements\ContentElementResource; use App\Models\User; +use Filament\Forms\Components\RichEditor\EditorCommand; use Illuminate\Database\Eloquent\Model; use Livewire\Attributes\Url; @@ -66,6 +67,12 @@ trait ManagesEditorialSurface public bool $ausgabeOpen = false; + /** Der Editor, in den das gewählte Bild eingefügt wird (Eigenschaft der Seite), und seine Cursorstelle. */ + public string $textImageField = ''; + + /** @var array */ + public array $textImageSelection = []; + /** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */ public ?array $bestaetigung = null; @@ -596,6 +603,57 @@ public function closePicker(): void } } + /** + * Öffnet den gemeinsamen Picker für ein Bild im Text. Der Editor ruft das mit seinem Namen und der Cursorstelle auf + * ({@see RichField}). Gewählt wird eine freigegebene Bildfassung des Medienbestands; eine Adresse speichert der Text nie. + * + * @param array $selection + */ + public function openTextImagePicker(string $field, array $selection = []): void + { + if (! method_exists($this, 'richKomponente') || $this->richKomponente($field) === null) { + return; + } + + $this->textImageField = $field; + $this->textImageSelection = $selection; + $this->resetPicker('textbild'); + $this->pickerKind = 'bild'; + } + + /** + * Fügt die gewählte Bildfassung an der Cursorstelle ein. Nur freigegebene Fassungen: Der Text verweist auf genau + * diese Fassung, und eine Dokumentfassung kann später nur freigegebene Bilder festschreiben. + */ + protected function insertTextImage(string $target): void + { + $component = method_exists($this, 'richKomponente') ? $this->richKomponente($this->textImageField) : null; + $version = preg_match('/^element:(\d+)$/', $target, $match) === 1 + ? ContentElementVersion::query()->with('element')->find($match[1]) + : null; + + if ($component === null || ! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') { + $this->feedback('Dieses Bild lässt sich nicht einfügen.', true); + + return; + } + + if ($version->status !== ContentVersionStatus::Bereit) { + $this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist noch nicht freigegeben. Gib das Bild im Medienbestand frei, dann lässt es sich einfügen.', true); + + return; + } + + $alt = trim((string) ($version->element->website_alt ?: $version->element->display_title ?: $version->element->working_title)); + $component->runCommands([ + EditorCommand::make('insertContent', arguments: [[ + 'type' => 'image', + 'attrs' => ['alt' => $alt, 'id' => (string) $version->id, 'src' => route('content.file', ['version' => $version->id], false)], + ]]), + ], editorSelection: $this->textImageSelection === [] ? null : $this->textImageSelection); + $this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist im Text eingefügt. Gespeichert wird mit dem Text.'); + } + public function pickerAllowsMany(): bool { return $this->pickerPurpose === 'praesentation' && $this->roleAllowsMany($this->presentationRole); @@ -625,6 +683,14 @@ public function confirmPicker(): void return; } + if ($this->pickerPurpose === 'textbild') { + $target = $marked[0]; + $this->closePicker(); + $this->insertTextImage($target); + + return; + } + $this->guardEditorial(); if ($this->pickerPurpose === 'austausch' || ($this->pickerPurpose === 'praesentation' && $this->replacingKey !== null)) { @@ -684,12 +750,12 @@ public function assignFromPicker(string $target): void */ public function pickerKinds(): array { - if ($this->pickerPurpose === 'vorschaubild') { + if (in_array($this->pickerPurpose, ['vorschaubild', 'textbild'], true)) { return ['bild' => 'Bilder']; } if ($this->pickerPurpose === 'aufbau') { - return ['alle' => 'Alle Inhalte', 'film' => 'Filme', 'bild' => 'Bilder', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente', 'text' => 'Texte', 'modul' => 'Module']; + return ['alle' => 'Alle Inhalte', 'film' => 'Filme', 'bild' => 'Bilder', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente', 'text' => 'Texte', 'modul' => 'Module', 'dokumentfassung' => 'Dokumente (Fassungen)']; } return ['alle' => 'Alle Medien', 'bild' => 'Bilder', 'film' => 'Filme', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente']; @@ -709,6 +775,7 @@ public function pickerTitle(): string 'aufbau' => 'Bestandteil auswählen', 'austausch' => 'Medium austauschen', 'vorschaubild' => 'Vorschaubild aus dem Bestand', + 'textbild' => 'Bild in den Text einfügen', default => 'Medien auswählen', }; } @@ -725,6 +792,7 @@ public function pickerConfirmLabel(): string 'aufbau' => 'In den Aufbau übernehmen', 'austausch' => 'Austauschen', 'vorschaubild' => 'Als Vorschaubild übernehmen', + 'textbild' => 'Bild einfügen', default => $count === 1 ? '1 Medium übernehmen' : ($count === 0 ? 'Medien übernehmen' : $count.' Medien übernehmen'), }; } diff --git a/app/Filament/Support/ManagesRichFields.php b/app/Filament/Support/ManagesRichFields.php index 643d228..8403826 100644 --- a/app/Filament/Support/ManagesRichFields.php +++ b/app/Filament/Support/ManagesRichFields.php @@ -2,6 +2,7 @@ namespace App\Filament\Support; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\FormattedText; use Filament\Forms\Components\RichEditor; use Filament\Schemas\Components\Component; @@ -41,6 +42,16 @@ protected function richFelder(): array return []; } + /** + * Eigenschaften, deren Editor Bilder aus dem Medienbestand einfügen darf (Textinhalte, nicht Kurzangaben). + * + * @return list + */ + protected function richBilder(): array + { + return []; + } + /** @return list */ protected function richNamen(): array { @@ -51,7 +62,7 @@ public function richTextSchema(Schema $schema): Schema { return $schema ->statePath('rich') - ->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true), $this->richNamen(), $this->richFelder())); + ->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true, images: in_array($name, $this->richBilder(), true) && method_exists($this, 'openTextImagePicker')), $this->richNamen(), $this->richFelder())); } public function richKomponente(string $name): ?Component @@ -93,7 +104,7 @@ protected function richPush(string $name): void } $canonical = FormattedText::canonical((string) $this->{$name}); - $component->state($canonical === '' ? null : $canonical); + $component->state($canonical === '' ? null : FormattedText::forEditor($canonical, fn (int $id): string => EmbeddedImages::staffSource($id))); $this->richSeen[$name] = md5($canonical); } diff --git a/app/Filament/Support/MediaLibrary.php b/app/Filament/Support/MediaLibrary.php index 8e401a3..9c4d4a9 100644 --- a/app/Filament/Support/MediaLibrary.php +++ b/app/Filament/Support/MediaLibrary.php @@ -16,7 +16,6 @@ use App\Domain\Catalog\ReleaseContent; use App\Domain\Media\ThumbnailRef; use App\Filament\Resources\ContentElements\ContentElementResource; -use App\Filament\Resources\Practices\PracticeResource; use Illuminate\Support\Collection; use Illuminate\Support\Str; @@ -593,7 +592,8 @@ private function exerciseOf(ContentElement $element, bool $canEdit): ?array return [ 'title' => (string) ($exercise->display_title ?: $exercise->designation), - 'url' => $canEdit ? PracticeResource::getUrl('edit', ['record' => $exercise]) : null, + 'url' => $canEdit ? EditorialCatalog::editUrl($exercise) : null, + 'kind' => $exercise->kind instanceof CompositionKind ? $exercise->kind->deskLabel() : 'Übung', ]; } diff --git a/app/Filament/Support/MediumForm.php b/app/Filament/Support/MediumForm.php index e84a941..f25d001 100644 --- a/app/Filament/Support/MediumForm.php +++ b/app/Filament/Support/MediumForm.php @@ -7,6 +7,7 @@ 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\IdentityProfile; use App\Domain\Media\PresentationFile; @@ -221,7 +222,7 @@ public static function fill(ContentElement $element): array 'usage_note' => $element->usage_note, 'license_note' => $element->license_note, 'thumbnail_alt' => $element->thumbnail_alt, - 'body' => FormattedText::html($latest?->body), + 'body' => EmbeddedImages::forEditor($latest?->body), ]; } diff --git a/app/Filament/Support/RichField.php b/app/Filament/Support/RichField.php index 3cd8bb8..b3ee3a9 100644 --- a/app/Filament/Support/RichField.php +++ b/app/Filament/Support/RichField.php @@ -4,6 +4,9 @@ use App\Domain\Catalog\FormattedText; use Filament\Forms\Components\RichEditor; +use Filament\Forms\Components\RichEditor\RichEditorTool; +use Filament\Support\Icons\Heroicon; +use Illuminate\Support\Js; /** * Der eine Editor für formatierte Texte (ADR-50): immer dieselbe Symbolleiste, dasselbe Ergebnis (bereinigtes HTML). @@ -15,10 +18,27 @@ final class RichField * @param ?string $label Bezeichnung des Felds; sie ist auch der Name für Hilfstechnik * @param bool $live Arbeitsplätze gleichen beim Verlassen des Felds ab ({@see ManagesRichFields}); Dialoge nicht * @param bool $hideLabel Die Bezeichnung zeigt der Arbeitsplatz selbst + * @param bool $images Bilder aus dem Medienbestand einfügen; nur auf Seiten mit dem gemeinsamen Picker + * ({@see ManagesEditorialSurface::openTextImagePicker()}) */ - public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false): RichEditor + public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false, bool $images = false): RichEditor { - $field = RichEditor::make($name)->toolbarButtons(FormattedText::TOOLBAR); + $toolbar = FormattedText::TOOLBAR; + + if ($images) { + array_splice($toolbar, count($toolbar) - 1, 0, [['bild']]); + } + + $field = RichEditor::make($name)->toolbarButtons($toolbar); + + if ($images) { + $field->tools([ + RichEditorTool::make('bild') + ->label('Bild aus dem Medienbestand einfügen') + ->icon(Heroicon::Photo) + ->jsHandler('$wire.openTextImagePicker('.Js::from($name).', editorSelection)'), + ]); + } if ($live) { $field->live(onBlur: true); diff --git a/app/Http/Controllers/DocumentPreviewController.php b/app/Http/Controllers/DocumentPreviewController.php new file mode 100644 index 0000000..fc8fbdb --- /dev/null +++ b/app/Http/Controllers/DocumentPreviewController.php @@ -0,0 +1,86 @@ +authorizeStaff($composition); + $guide = $this->guide($composition); + $images = EmbeddedImages::staff(); + + foreach ($guide['chapters'] as $index => $chapter) { + $guide['chapters'][$index]['html'] = DocumentGuide::shiftHeadings(FormattedText::html($chapter['version']->body, $images)); + } + + return view('document.preview', ['guide' => $guide, 'composition' => $composition, 'pdfUrl' => route('editorial.document-preview.pdf', $composition)]); + } + + public function pdf(Composition $composition): Response + { + $this->authorizeStaff($composition); + $content = app(DocumentPdf::class)->render($this->guide($composition), 'Vorschau der Redaktion', 'vorschau', EmbeddedImages::forStaffPdf()); + + return response($content, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'inline; filename="vorschau.pdf"', + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * @return array + */ + private function guide(Composition $composition): array + { + $chapters = app(DocumentReader::class)->forStaff($composition); + abort_if($chapters === null, 404); + + foreach ($chapters as $index => $chapter) { + $chapters[$index] += [ + 'allowed' => true, + 'grant' => null, + 'may_download' => true, + 'download_grant' => null, + 'state' => 'ok', + 'html' => null, + 'blocks' => FormattedText::blocks($chapter['version']->body), + ]; + } + + return [ + 'title' => app(EditorialCatalog::class)->compositionTitle($composition), + 'summary_html' => FormattedText::html($composition->summary), + 'chapters' => $chapters, + ]; + } + + private function authorizeStaff(Composition $composition): void + { + $user = auth('staff')->user(); + abort_unless( + $user instanceof User && ($user->hasStaffRole(StaffRole::Redakteur) || $user->hasStaffRole(StaffRole::Katalogverwalter)), + 403, + ); + abort_unless($composition->kind === CompositionKind::Document, 404); + } +} diff --git a/app/Http/Controllers/Member/DocumentController.php b/app/Http/Controllers/Member/DocumentController.php new file mode 100644 index 0000000..aa9ab13 --- /dev/null +++ b/app/Http/Controllers/Member/DocumentController.php @@ -0,0 +1,91 @@ +load($request, $article, $release, $path); + $copy = DeliveryLog::newCopyId(); + $shown = false; + + foreach ($guide['chapters'] as $chapter) { + if ($chapter['allowed'] && $chapter['grant'] !== null) { + app(DeliveryLog::class)->write($chapter['grant'], $article, $release, $chapter['version'], 'ansehen', 'text', hash('sha256', (string) $chapter['version']->body), 'k2', $copy, $located['version']->id); + $shown = true; + } + } + + return view('member.document', [ + 'guide' => $guide, + 'reader' => $request->user()->name, + 'copy' => $shown ? $copy : null, + // Ohne Ablauf der Adresse: Die Seite bleibt lange offen; bei jedem Abruf entscheidet `DecideAccess` neu. + 'pdfUrl' => app(DocumentGuide::class)->pdfAllowed($guide) ? route('member.document.pdf', ['article' => $article, 'release' => $release, 'path' => $path]) : null, + ]); + } + + public function pdf(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): Response + { + [$guide, $located] = $this->load($request, $article, $release, $path); + abort_unless(app(DocumentGuide::class)->pdfAllowed($guide), 403, 'Für dieses PDF fehlt die Berechtigung für ein Kapitel.'); + + $copy = DeliveryLog::newCopyId(); + $images = app(EmbeddedImages::class)->forPdf($request->user(), $article, $release, array_map(fn (array $chapter): ContentElementVersion => $chapter['version'], $guide['chapters'])); + $content = app(DocumentPdf::class)->render($guide, $request->user()->name, $copy, $images); + $checksum = hash('sha256', $content); + + foreach ($guide['chapters'] as $chapter) { + $grant = $chapter['download_grant'] ?? $chapter['grant']; + + if ($grant !== null) { + app(DeliveryLog::class)->write($grant, $article, $release, $chapter['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id); + } + } + + foreach ($images->used() as $image) { + app(DeliveryLog::class)->write($image['grant'], $article, $release, $image['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id); + } + + return response($content, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'attachment; filename="'.(str($guide['title'])->slug()->value() ?: 'dokument').'.pdf"', + 'X-License-Copy' => $copy, + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * @return array{0: array, 1: array{version: CompositionVersion, selection: list|null}} + */ + private function load(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): array + { + $guides = app(ExerciseGuide::class); + abort_unless($guides->mayOpen($request->user(), $article, $release), 403); + $located = $guides->locate($release, $path, CompositionKind::Document); + abort_if($located === null, 404); + + return [app(DocumentGuide::class)->build($request->user(), $article, $release, $located['version']), $located]; + } +} diff --git a/app/Http/Controllers/Member/ExerciseController.php b/app/Http/Controllers/Member/ExerciseController.php index 91b53b1..d6b4382 100644 --- a/app/Http/Controllers/Member/ExerciseController.php +++ b/app/Http/Controllers/Member/ExerciseController.php @@ -4,6 +4,8 @@ use App\Domain\Catalog\ArticleRelease; use App\Domain\Catalog\CompositionVersion; +use App\Domain\Catalog\ContentElementVersion; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\ExerciseGuide; use App\Domain\Catalog\ExercisePdf; use App\Domain\Catalog\LicenseArticle; @@ -76,6 +78,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r $copy = DeliveryLog::newCopyId(); $variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']); + $images = app(EmbeddedImages::class)->forPdf($request->user(), $article, $release, array_values(array_map(fn (array $section): ContentElementVersion => $section['version'], array_filter($sections, fn (array $section): bool => $section['class'] === 'text')))); $content = $pdf->render( $guide, $sections, @@ -83,6 +86,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r $copy, (string) ($variant['name'] ?? ''), route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]), + $images, ); $checksum = hash('sha256', $content); @@ -94,6 +98,11 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r } } + // Bilder im Text sind eigene Fassungen: Auch sie stehen im Ausgabenachweis dieses PDF. + foreach ($images->used() as $image) { + app(DeliveryLog::class)->write($image['grant'], $article, $release, $image['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id); + } + $name = str($guide['title'])->slug()->value() ?: 'uebung'; return response($content, 200, [ diff --git a/app/Http/Controllers/Member/LibraryController.php b/app/Http/Controllers/Member/LibraryController.php index 1de6b95..3c77590 100644 --- a/app/Http/Controllers/Member/LibraryController.php +++ b/app/Http/Controllers/Member/LibraryController.php @@ -8,6 +8,7 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\IdentityDimension; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Pillar; @@ -240,6 +241,7 @@ public function show(Request $request, LicenseArticle $article): View 'class' => $class, 'content' => $content, 'version' => $version, + 'images' => $class === 'text' ? app(EmbeddedImages::class)->forView($request->user(), $article, $release, $version) : null, 'role' => $content->role, 'action' => $action, 'allowed' => $decision->allowed, @@ -319,6 +321,7 @@ public function media( 'article' => $article, 'version' => $version, 'license' => $decision->grant->rights_snapshot['purpose'] ?? null, + 'images' => app(EmbeddedImages::class)->forView($request->user(), $article, $release, $version), 'reader' => $request->user()->name, 'copy' => $delivery->copy_id, ]); diff --git a/app/Http/Controllers/Member/StandImageController.php b/app/Http/Controllers/Member/StandImageController.php new file mode 100644 index 0000000..56c9e71 --- /dev/null +++ b/app/Http/Controllers/Member/StandImageController.php @@ -0,0 +1,41 @@ +mayOpen($request->user(), $article, $release), 403); + + $served = app(EmbeddedImages::class)->serve($request->user(), $article, $release, $text, $version->id); + abort_if($served === null, 403); + + $file = EmbeddedImages::file($served['version']); + abort_if($file === null, 404); + + $disk = Storage::disk('media_derived'); + $delivery = app(DeliveryLog::class)->write($served['grant'], $article, $release, $served['version'], 'ansehen', 'bestand', hash_file('sha256', $disk->path($file)) ?: null, 'k0'); + $title = app(LibraryCatalog::class)->text($served['version']->element)['title']; + $name = ($title !== '' ? preg_replace('/[\x00-\x1F\x7F\/\\\\:*?"<>|]+/u', ' ', $title) : 'bild').'.'.strtolower(pathinfo($file, PATHINFO_EXTENSION)); + + return $disk->response($file, trim((string) $name), ['X-License-Copy' => $delivery->copy_id, 'Cache-Control' => 'private, max-age=300'], 'inline'); + } +} diff --git a/app/Http/LibraryCatalog.php b/app/Http/LibraryCatalog.php index 2e40ed6..5df9145 100644 --- a/app/Http/LibraryCatalog.php +++ b/app/Http/LibraryCatalog.php @@ -380,6 +380,8 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI } } + $document = $this->isDocument($node); + $documentUrl = $document ? $this->exerciseUrl($user, $rootId, $node) : null; $title = $node->title; if ($element !== null) { @@ -396,10 +398,11 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI 'kind' => $node->editorialKindLabel ?? $this->outputLabel($node->technicalKindLabel) ?? $node->technicalKindLabel, 'output_class' => $node->outputClass, 'playback' => $playback, - 'view_url' => $view, + 'view_url' => $view ?? $documentUrl, 'poster_url' => $poster, 'download_url' => $download, - 'program_url' => $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node), + 'program_url' => $documentUrl ?? $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node), + 'document' => $document, 'composition_id' => $node->compositionId, 'element_id' => $node->contentElementId, 'version_id' => $node->contentElementVersionId, @@ -407,13 +410,20 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI 'composition' => $rootId, 'version' => $node->contentElementVersionId, ]), - 'children' => array_map( + // Ein Dokument steht als ein Eintrag da; seine Kapitel lesen Mitglieder im Dokument selbst. + 'children' => $document ? [] : array_map( fn (StructureNode $child): array => $this->present($user, $child, $full, $rootId), $node->children, ), ]; } + private function isDocument(StructureNode $node): bool + { + return $node->compositionId !== null + && Composition::query()->whereKey($node->compositionId)->where('kind', CompositionKind::Document->value)->exists(); + } + /** * @param list> $nodes * @param list> $parents @@ -467,7 +477,7 @@ private function countCompositions(array $nodes): int $count = 0; foreach ($nodes as $node) { - if ($node['composition_id'] !== null) { + if ($node['composition_id'] !== null && empty($node['document'])) { $count++; } @@ -513,8 +523,9 @@ private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?str } $nested = CompositionVersion::query()->with('composition')->find($node->compositionVersionId); + $kind = $nested?->composition?->kind; - if ($nested?->composition?->kind !== CompositionKind::Exercise) { + if (! in_array($kind, [CompositionKind::Exercise, CompositionKind::Document], true)) { return null; } @@ -533,7 +544,7 @@ private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?str $path = $guide->pathTo($release->rootCompositionVersion, $nested->id); if ($path !== null) { - return route('member.exercise', ['article' => $grant->license_article_id, 'release' => $release->id, 'path' => $path]); + return route($kind === CompositionKind::Document ? 'member.document' : 'member.exercise', ['article' => $grant->license_article_id, 'release' => $release->id, 'path' => $path]); } } } diff --git a/database/migrations/2026_11_28_100000_add_documents.php b/database/migrations/2026_11_28_100000_add_documents.php new file mode 100644 index 0000000..b1de4d7 --- /dev/null +++ b/database/migrations/2026_11_28_100000_add_documents.php @@ -0,0 +1,38 @@ +insertOrIgnore([ + ['slug' => 'dokument', 'label' => 'Dokument', 'sort_order' => 27, 'is_active' => true, 'contexts' => json_encode(['dokument']), 'created_at' => $now, 'updated_at' => $now], + ['slug' => 'dokumentkapitel', 'label' => 'Dokumentkapitel', 'sort_order' => 28, 'is_active' => true, 'contexts' => json_encode([]), 'created_at' => $now, 'updated_at' => $now], + ]); + } + + public function down(): void + { + DB::table('content_elements') + ->whereIn('editorial_content_kind_id', DB::table('editorial_content_kinds')->where('slug', 'dokumentkapitel')->select('id')) + ->update(['editorial_content_kind_id' => null]); + DB::table('compositions') + ->whereIn('editorial_content_kind_id', DB::table('editorial_content_kinds')->where('slug', 'dokument')->select('id')) + ->update(['editorial_content_kind_id' => null]); + DB::table('editorial_content_kinds')->whereIn('slug', ['dokument', 'dokumentkapitel'])->delete(); + } +}; diff --git a/docs/architektur/12_Entscheidungsprotokoll_ADR.md b/docs/architektur/12_Entscheidungsprotokoll_ADR.md index a6b92c1..c6afb9e 100644 --- a/docs/architektur/12_Entscheidungsprotokoll_ADR.md +++ b/docs/architektur/12_Entscheidungsprotokoll_ADR.md @@ -727,3 +727,26 @@ ## ADR-50 – Formatierte Texte: bereinigtes HTML als einziges Format, ein Edito **Folgen.** Keine Migration. **Rückfall:** Sobald jemand mit diesem Stand einen Text in Modul, Programm, Übung, Medium oder Lizenzartikel speichert, liegt dort HTML. Setzt man danach nur den Code zurück, zeigt der vorherige Stand diese Texte mit sichtbaren Tags (Karten, Bibliothek, Shop, Mitgliederansicht); Daten gehen nicht verloren, denn die alten Felder speichern die Zeichenkette unverändert, und der neue Stand liest sie wieder richtig. Das gilt für den ganzen Katalog, nicht nur für Übungen; es gehört in die Zusammenfassung für den Merge `develop` → `main`. **Suche:** Datenbanksuchen mit `LIKE` über diese Spalten (Auswahl im Aufbau, Medienliste) treffen auch Bezeichnungen wie `strong` oder `li` und verfehlen Text mit `&`, weil er als `&` gespeichert ist. Die Suche in der Liste der Übungen und Module und im Shop vergleicht dagegen Klartext (`FormattedText::plain`). Die Datenbanksuchen bleiben eine bekannte Einschränkung. Die erste Übernahme mit HTML zählt für jeden Textabschnitt als Änderung der Quelle (die Formatierung kommt hinzu); wo ein Abschnitt lokal bearbeitet wurde, fragt die Vorschau nach. Das CMS nutzt weiter `RichText` (eigene Auswahl); die Umstellung auf denselben Baustein ist ein späterer Schritt. **Quelle.** Anfragen von Lars vom 23.11.2026 (Formatierung der Übungstexte, Editoren für alle Textfelder); Shinkan-Commit „Deliver stored exercise HTML on the catalog API“. + +## ADR-51 – Dokumente: Kapitel als Texte, Dokumentfassung als Komposition, Tabellen und Bilder im gemeinsamen Editor, PDF mit Inhaltsverzeichnis + +**Status:** umgesetzt, fachlich zu bestätigen. **Datum:** 24.11.2026. **Anlass:** Das Trainerhandbuch (mehr als 30 Seiten) braucht einen eigenen Eintrag unter „Inhalte“; Kapitel und Übungstexte sollen mit demselben Editor entstehen. + +**Entscheidung.** +- **Modell.** Ein Dokument ist eine `Composition` mit der neuen Art `document` (Übungsmuster, ADR-49), eine Dokumentfassung eine `CompositionVersion`. Ein Kapitel ist ein Text (`ContentElement` mit Textfassungen) mit der automatischen Materialart „Dokumentkapitel“ und dem Verweis auf sein Dokument (`origin_composition_id`), wie die Übungsabschnitte. Kapitel erscheinen im Medienbestand nur, wenn man die Materialart ankreuzt, und nie öffentlich. +- **Gliederung ohne Schemaänderung.** Die Ebene steht in der Rolle des Mitglieds: „Kapitel“ oder „Unterkapitel“ (zwei Ebenen). Nummern („3“, „3.2“) entstehen aus der Reihenfolge (`DocumentOutline`) und werden nirgends gespeichert; Editor, Seite und PDF zählen gleich. Die einzige Migration legt zwei Materialarten an (`dokument`, `dokumentkapitel`). +- **Wiederverwendung.** Fassung, Bindung, Einbindung in Module und Programme (derselbe Picker, Filter „Dokumente (Fassungen)“), Artikel-Stand (`ReleaseContent`), Rechteprüfung (`DecideAccess`), Fassungsverlauf und Verwendungsnachweis sind unverändert die der Übung. Ein Modul oder Programm bindet eine konkrete Dokumentfassung; ein älterer Stand liefert die darin gebundene Fassung weiter aus, weil der Stand auf die Fassung verweist und nicht auf das Dokument. +- **Bearbeiten.** Der Aufbaueditor hat für Dokumente den Kapitelarbeitsplatz (`ManagesDocumentChapters`): Kapitelübersicht mit Nummern, Anlegen, Ebene ändern, Ordnen (Ziehen, Alt+Pfeil, Knöpfe; immer ein Kapitel mit seinen Unterkapiteln), Löschen mit Rückfrage. Offene Eingaben liegen in `chapterEdits` und bleiben beim Wechsel erhalten; geschrieben wird erst mit „Entwurf speichern“, und zwar als Entwurfsfassung des Kapitels (`ContentService::reviseElementDraft`: eine festgeschriebene Fassung bleibt unverändert, es entsteht eine neue Entwurfsfassung). „Dokumentfassung bereitstellen“ speichert zuerst die offenen Kapitel und stellt dann Dokument und Kapitel gemeinsam bereit (Zustimmung wie bei jedem Aufbau). Ungespeicherte Kapitel zählen als Änderung des Entwurfs. +- **Vorschau.** Redaktionsvorschau als Seite und als PDF (`DocumentPreviewController`) aus dem gespeicherten Entwurf; sie nutzt denselben Baustein wie die Mitgliederansicht. +- **Ein Texteditor.** `FormattedText` und `RichField` (ADR-50) bekommen Tabellen und Bilder. Alle Texteditoren (Kapitel, Übungstexte, Medientexte) haben dieselbe Symbolleiste; das Bildwerkzeug erscheint dort, wo die Seite den gemeinsamen Picker hat (Aufbaueditor, Medienansicht). Kurzangaben (Beschreibung, Lernziel) bekommen die Tabelle, aber kein Bild. Die kanonische Form kennt `table`/`tr`/`th`/`td` (nur `colspan` und `rowspan` über 1, Zellen mit Absätzen) und `img`. +- **Bilder.** Ein Bild ist ein Verweis auf eine freigegebene Bildfassung des Medienbestands (`…`), nie eine Adresse und kein Upload. Der Editor bekommt eine Adresse der Verwaltung nur zur Anzeige; die Bereinigung entfernt sie wieder. Der Editor setzt ein Bild inline in einen Absatz oder als Block in eine Tabellenzelle; beides bleibt erhalten, in Überschrift, Liste und Zitat entfällt ein Bild. Im PDF teilt ein Bild im Absatz den Absatz, in einer Zelle steht es verkleinert in der Zelle. Ohne Auflösung gibt jede Ausgabe kein Bild aus (sichere Voreinstellung). Ein Text mit einem nicht freigegebenen oder gesperrten Bild lässt sich nicht festschreiben (`ContentService::imageProblem`). +- **Rechte für Bilder.** Ein Bild im Text gehört zum Text: Wer den Text ansehen darf, sieht die Bilder darin; wer ihn laden darf, bekommt sie im PDF. Es braucht kein eigenes Recht für Bilder. Bestehende Berechtigungen nennen nur Texte; ein eigenes Bildrecht hätte allen bisherigen Käufern die Bilder in Handbuch und Trainerhinweisen genommen. **Das ist eine fachliche Entscheidung, die Lars bestätigt oder ändert.** `ContentResolver::expand` führt die Bildfassungen eines Textes als ergänzende Zeilen im Stand (`release_contents`); die Auslieferung prüft, dass das Bild im Text vorkommt, zum Stand gehört, nicht gesperrt ist und der Text zulässig ist (`EmbeddedImages`, `StandImageController`). Die Adresse eines Bildes (`/bereich/stand/{Artikel}/{Stand}/bild/{Text}/{Bild}`) läuft nicht ab und entscheidet bei jedem Abruf neu, weil eine Seite lange offen bleibt; die Datei liegt nie unter einem öffentlichen Pfad. Eine Sperre der Bildfassung wirkt: Das Bild entfällt mit Hinweis, der Text bleibt lesbar. Das PDF des Dokuments liegt ebenfalls unter einer Adresse ohne Ablauf (angemeldetes Konto, Entscheidung je Abruf), damit der Knopf auf einer langen offenen Seite nicht ins Leere läuft; das Übungs-PDF bleibt signiert. Ausgabenachweis je gedrucktem Bild im PDF. Für das PDF braucht der Text `laden`; die Auswahl der Fähigkeiten im Rechteprofil bietet dafür jetzt „Text als PDF herunterladen“ (`text:laden`) an. +- **Ausgabe.** `DocumentGuide` liefert Kapitel mit Rechteentscheidung für Seite (`member.document`) und PDF (`member.document.pdf`); Zwischenüberschriften im Kapitel stehen eine Ebene unter dem Kapiteltitel. Ein Dokument in einem Modul erscheint als ein Eintrag, der zur gebundenen Fassung führt. Das PDF verlangt `laden` für jedes Kapitel, sonst fehlte ein Teil. +- **PDF ohne Bibliothek.** `PdfDocument` kann jetzt Flächen, JPEG-Bilder (aus GD neu kodiert, höchstens 1400 Pixel, auf Weiß), Verweise innerhalb des Dokuments und Lesezeichen; zusätzliche Objekte entstehen nur bei Bedarf und nach allen bisherigen, Belege und Übungs-PDFs bleiben byte-gleich (Test mit Prüfsummen). `PdfFlow` ist der gemeinsame Satz für Übung und Dokument (Absatz, Listen, Tabellen mit Spaltenbreiten nach Inhalt, Kopfzeile je Folgeseite, Zeilen zusammenhaltend, Bilder ungeteilt, Überschrift bleibt bei ihrem Text). `DocumentPdf` setzt Titelseite mit anklickbarem Inhaltsverzeichnis und Seitenzahlen, jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite, Fußzeile „Seite n von m“, Lesezeichen. Seitenzahlen stehen erst nach dem Satz fest; der Satz läuft bis zur Stabilität (in der Regel zweimal). +- **Bildformate.** Im Image ist GD mit JPEG, PNG und GIF gebaut, nicht mit WebP (`Dockerfile` unverändert). Ein Bild, das GD nicht liest, erscheint im PDF als Hinweis „Bild kann nicht gedruckt werden“. + +**Alternativen.** Eigene Dokumenttabellen mit Kapitelbaum (verworfen: dupliziert Fassung, Bindung, Auflösung und Rechte); Kapitel als Unterkompositionen (verworfen: Kapitel haben keinen eigenen Lebenslauf, Verschachtelung ist hier nur Gliederung); PDF-Bibliothek (verworfen: Abhängigkeit im Image und in `composer.lock`, byte-gleiche Ausgabe, prüfbarer Text; ein gestaltetes Handbuch mit Schriftart und Layout nach Marke würde eine Bibliothek rechtfertigen); Bilder als hochgeladene Anhänge des Editors (verworfen: eine zweite Medienverwaltung, der Web-Prozess schreibt nicht in `derived/`, keine Rechteentscheidung). + +**Folgen.** Eine Migration, additiv. **Rückfall:** Der vorherige Stand kennt die Art `document` nicht und blendet Dokumente über den Bereichsfilter aus (`SupportedKindScope`); Kapiteltexte bleiben als Texte erhalten. Die Rückfallsperre (ADR-49) muss auf `main` sein, bevor in Prod das erste Dokument entsteht. Nach einem Rückfall zeigt der vorherige Stand Tabellen und Bilder in Texten nicht mehr (sie fallen in der Bereinigung weg) und ein Modul, das eine Dokumentfassung bindet, zeigt das Dokument nicht. Einen Stand, der ein Dokument bindet, ändert der Rückfall nicht in der Datenbank. Offen: Abnahme auf luf-test (Browser, schmale Fenster, Tastatur), Schrift und Layout des Handbuch-PDF nach Marke (nur Helvetica), Silbentrennung im PDF (lange Wörter in schmalen Tabellenspalten werden hart getrennt). + +**Quelle.** Auftrag „Dokumente“ von Lars vom 24.11.2026. diff --git a/docs/ux/verwaltung/abnahme/dokumente.md b/docs/ux/verwaltung/abnahme/dokumente.md new file mode 100644 index 0000000..f2bfdff --- /dev/null +++ b/docs/ux/verwaltung/abnahme/dokumente.md @@ -0,0 +1,80 @@ +# Abnahme Dokumente (Stand 24.11.2026) + +Auftrag: „Dokumente“ als eigener Eintrag unter Inhalte, erster Fall Trainerhandbuch (mehr als 30 Seiten). Entscheidung: ADR-51. +Dieser Stand belegt die **lokale** Abnahme in der laufenden Anwendung (Arbeitsbaum `feature/dokumente`, lokaler Server, SQLite, +Demo-Konten aus `ShopDemoSeeder`) und die automatisierten Prüfungen. **Auf `luf-test` ist nichts geprüft:** Der Zweig liegt nicht auf +`develop`, und für die Mitgliederansicht ist dort kein Konto mit Lizenz bekannt (siehe unten). + +## 1. Ein Trainerhandbuch bearbeiten + +Gebaut wurde ein Dokument „Trainerhandbuch Gewaltprävention“ mit 12 Kapiteln und 11 Unterkapiteln, jedes Kapitel mit acht Absätzen, +Kapitel 1 mit Bild aus dem Medienbestand, Zwischenüberschrift und Tabelle (alles mit den Werkzeugen des Editors, nichts von Hand im HTML). + +| Schritt | Ergebnis | Beleg | +|---|---|---| +| Dokument anlegen (Inhalte → Dokumente → „Dokument anlegen“) | Es öffnet sich der Kapitelarbeitsplatz | `dokumente/01-liste-leer.png`, `03-leeres-dokument.png` | +| Kapitel und Unterkapitel anlegen | Nummern ergeben sich aus der Reihenfolge (1, 1.1, 2 …) | `04-erstes-kapitel.png` | +| Bild über den gemeinsamen Picker, Tabelle über die Symbolleiste | Bild und Tabelle im Editor | `05-bildauswahl.png`, `06-kapitel-mit-bild-und-tabelle.png` | +| Zwischen Kapiteln wechseln | Offene Eingabe in „Gruppenführung“ blieb erhalten, Tabelle und Bild in „Grundlagen“ blieben erhalten, Gliederung unverändert | `07-eingaben-erhalten.png` | +| Ein Kapitel umordnen (Kapitel 2 samt Unterkapitel nach unten) | Kapitel 2 und 2.1 wanderten zusammen hinter Kapitel 3; Nummern folgten | `08-reihenfolge-geaendert.png` | +| Entwurf speichern | „Der Entwurf ist gespeichert, auch die Texte der Kapitel. Es entsteht keine neue Dokumentfassung.“ | `09-entwurf-gespeichert.png` | +| Vorschau (Seite und PDF) | Seite mit Inhaltsverzeichnis in der neuen Reihenfolge; PDF-Vorschau 37 Seiten | `10-vorschau-seite.png` | +| Dokumentfassung bereitstellen | Dialog nennt jedes Kapitel; nach Zustimmung „Dokumentfassung 1 ist bereitgestellt“ | `11-bereitstellen-dialog.png`, `12-dokumentfassung-bereitgestellt.png` | + +## 2. Einbinden, Mitgliederansicht, PDF, zweite Fassung + +| Schritt | Ergebnis | Beleg | +|---|---|---| +| Modul anlegen, Dokumentfassung über den Picker einbinden (Filter „Dokumente (Fassungen)“) | Das Dokument steht als ein Bestandteil im Modul („Dokument · Fassung 1“) | `13-modul-picker-dokumentfassung.png`, `14-modul-mit-dokument.png` | +| Modulfassung freigeben, Artikel-Stand veröffentlichen, Konto `tina.trainerin` | Stand-Kennung 4 (Modul, Dokumentfassung 1) | `15-modul-freigabe.png` | +| Mitglied öffnet die Modulseite | Das Dokument ist ein Eintrag mit Link zur gebundenen Fassung, die Kapitel stehen nicht einzeln dort | `20-modulseite-mit-dokument.png` | +| Mitgliederansicht | Zusammenhängende Seite mit klickbarem Inhaltsverzeichnis (23 Einträge), Lizenzkennzeichnung, Bild geladen, Tabelle | `21-mitgliederansicht-dokument.png`, `23-kapitel-mit-bild-und-tabelle.png`, `24-tabelle.png` | +| Sprung im Inhaltsverzeichnis | Klick auf „Rechtliche Hinweise“ setzt `#kapitel-11` und scrollt das Kapitel an den oberen Rand | `22-sprung-zu-kapitel.png` | +| Schmales Fenster (390 px) | Kein waagerechtes Scrollen, Inhaltsverzeichnis und Kapitel lesbar | `25-schmales-fenster.png`, `26-schmales-fenster-kapitel.png` | +| Tastatur | Tab erreicht „Als PDF herunterladen“, dann das Inhaltsverzeichnis und seine Einträge in Reihenfolge | im Lauf geprüft | +| PDF | 37 Seiten, 23 Lesezeichen, 23 anklickbare Zeilen im Inhaltsverzeichnis, die Seitenzahlen im Inhaltsverzeichnis stimmen mit dem Ziel jedes Lesezeichens überein, Bild und Tabelle, „Seite n von 37“ und Lizenzkopie je Seite | `50-pdf-inhaltsverzeichnis.png`, `51-pdf-kapitel-mit-bild-und-tabelle.png`, `52-pdf-letzte-seite.png` | +| Zweite Dokumentfassung (Text in „Auswertung“ geändert, Kapitel „Nachtrag zur zweiten Fassung“ neu), im Modul auf Fassung 2 umgestellt, Modulfassung 2, Stand-Kennung 5 | Fassung 2 bereitgestellt; „Fassungen und Verwendung“ listet beide | `30-zweite-fassung-in-arbeit.png`, `31-fassungen-und-verwendung.png`, `32-modul-fassung-waehlen.png` | +| Beide Stände abrufen | Stand-Kennung 4 liefert Seite (23 Einträge) und PDF (37 Seiten) ohne die Änderung; Stand-Kennung 5 liefert Seite (24 Einträge) und PDF (38 Seiten) mit Änderung und Nachtrag | `33-stand-alt.png`, `33-stand-neu.png` | + +## 3. Trainerhinweis einer Übung mit demselben Editor + +Übung „Stopp sagen“ mit einem Trainerhinweis (Absatz, Liste), eingebunden in ein verkauftes Modul (Stand-Kennung 6). + +| Schritt | Ergebnis | Beleg | +|---|---|---| +| Trainerhinweis im Übungseditor öffnen (Register „Quelle“) | Dieselbe Symbolleiste wie im Kapitel (Überschrift, Listen, Link, Tabelle, Bild); die vorhandene Liste steht unverändert im Editor | `40-uebung-trainerhinweis-quelle.png` | +| Überschrift, Tabelle und Bild ergänzen, speichern | Neue Textfassung; die bisherige bleibt in den freigegebenen Aufbauten | `41-uebung-trainerhinweis-bearbeitet.png`, `42-uebung-trainerhinweis-gespeichert.png` | +| Übungsfassung freigeben, Modul auf Fassung 2 umstellen, Stand-Kennung 8 | – | `43-uebung-fassung-freigegeben.png` | +| Übungsansicht und Übungs-PDF, Stand-Kennung 8 | Überschrift, Liste, Tabelle und Bild erscheinen in Ansicht und PDF | `44-uebung-neu.png`, `53-pdf-uebung-neu.png` | +| Dieselben Ausgaben, Stand-Kennung 6 | Unverändert: nur die Liste, keine Tabelle, kein Bild | `44-uebung-alt.png`, `53-pdf-uebung-alt.png` | + +## Automatisierte Prüfungen (in der Suite) + +- `TextEditorWerkzeugeTest`: Tabelle und Bild durch die echte Filament-Komponente und zurück ohne Verlust; Bildwerkzeug nur dort, wo der Picker + steht; Picker bietet nur Bilder und setzt nur freigegebene Fassungen ein; Text mit nicht freigegebenem oder gesperrtem Bild lässt sich nicht festschreiben. +- `FormattedTextTest`: Tabellen, Bilder (inline, im Block, in der Zelle), Bereinigung, Stabilität der kanonischen Form, Klartext und Blöcke. +- `DokumentEditorTest`: Anlegen, Nummern, Wechsel ohne Verlust, Speichern als Entwurf, Ordnen als Block (Knöpfe und Ziehen), Ebene, Bereitstellen (eine + Fassung, gebundene Kapitelfassungen in Reihenfolge, spätere Bearbeitung ändert die bereitgestellte Fassung nicht), Picker für Module. +- `DokumentAusgabeTest`: Seite und PDF je Stand, mehr als 30 Seiten mit stimmenden Seitenzahlen, zwei Stände mit zwei Fassungen, Modulseite, + Bilder folgen den Rechten des Textes (Berechtigung nur für Texte zeigt die Bilder), ohne Recht am Text keine Seite, kein Bild und kein PDF, Bildadresse + gibt nur das Bild dieses Textes und Stands frei, Adresse und PDF-Knopf nach 45 Minuten noch gültig, PDF nur mit Download-Recht, gesperrtes Bild, fremdes Konto, + gleiche Kapitel in Seite und PDF. +- `UebungFormatierungTest`: Trainerhinweis mit Überschrift, Liste, Tabelle und Bild bleibt beim Öffnen und Speichern erhalten und erscheint in Ansicht und PDF. +- `PdfDocumentTest`: Prüfsummen für Belege und Übungs-PDF (byte-gleich), Verweise, Lesezeichen, Bilder, Kreuzverweistabelle, Nummerierung. +- `RueckfallschutzTest`: die Art `document` ist bewusst ergänzt. + +## Abweichungen und offene Punkte + +- **Nicht auf luf-test geprüft.** Dafür müsste der Zweig auf `develop` (Entscheidung von Lars). Für die Mitgliederansicht fehlt auf luf-test weiterhin ein + bekanntes Konto mit Lizenz. Alle Abläufe oben liefen lokal gegen die laufende Anwendung, die Mitgliederkonten stammen aus `ShopDemoSeeder`. +- **Verkauf und Bibliothek lokal per Skript.** Artikel, Stand, Berechtigung (Konto `tina.trainerin`) und die Anzeige des Moduls in der Mitgliederbibliothek + wurden für die Abnahme per Skript angelegt, nicht über die Oberfläche; das ist nicht Teil dieses Auftrags und seit ADR-49 unverändert. +- **Fachliche Entscheidung zu Bildern:** Bilder im Text folgen den Rechten des Textes (siehe ADR-51). Ohne diese Regel fehlten allen bisherigen Käufern die Bilder, + weil bestehende Profile nur Texte nennen. Lars bestätigt oder ändert das. +- **Schrift und Layout des PDF.** Nur Helvetica, keine Silbentrennung; sehr lange Wörter in schmalen Tabellenspalten werden hart getrennt. Ein Handbuch-PDF + nach Marke (Schrift, Kopfzeile, Titelseite) würde eine PDF-Bibliothek rechtfertigen. +- **Bildformate im PDF.** GD im Image kann JPEG, PNG und GIF, kein WebP; ein solches Bild erscheint im PDF als Hinweis. +- **Bilder in Listen, Zitaten, Überschriften** entfallen beim Speichern; im Absatz und in der Tabellenzelle bleiben sie. +- **Bildwerkzeug in den Dialogen „Medium anlegen“ und „Neue Fassung“** fehlt: Diese Formulare liegen im Dialog, der Picker gehört zur Seite. Tabellen gibt es + dort, Bilder lassen sich danach in der Medienansicht oder im Aufbaueditor einfügen. +- **Rückfall:** siehe ADR-51 („Folgen“). Der Rückfallschutz aus ADR-49 muss auf `main` sein, bevor in Prod das erste Dokument entsteht. diff --git a/docs/ux/verwaltung/abnahme/dokumente/01-liste-leer.png b/docs/ux/verwaltung/abnahme/dokumente/01-liste-leer.png new file mode 100644 index 0000000..fcd03c0 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/01-liste-leer.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/03-leeres-dokument.png b/docs/ux/verwaltung/abnahme/dokumente/03-leeres-dokument.png new file mode 100644 index 0000000..ca10da2 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/03-leeres-dokument.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/04-erstes-kapitel.png b/docs/ux/verwaltung/abnahme/dokumente/04-erstes-kapitel.png new file mode 100644 index 0000000..4d55b2b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/04-erstes-kapitel.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/05-bildauswahl.png b/docs/ux/verwaltung/abnahme/dokumente/05-bildauswahl.png new file mode 100644 index 0000000..549de40 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/05-bildauswahl.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/06-kapitel-mit-bild-und-tabelle.png b/docs/ux/verwaltung/abnahme/dokumente/06-kapitel-mit-bild-und-tabelle.png new file mode 100644 index 0000000..736a58d Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/06-kapitel-mit-bild-und-tabelle.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/07-eingaben-erhalten.png b/docs/ux/verwaltung/abnahme/dokumente/07-eingaben-erhalten.png new file mode 100644 index 0000000..11a82eb Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/07-eingaben-erhalten.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/08-reihenfolge-geaendert.png b/docs/ux/verwaltung/abnahme/dokumente/08-reihenfolge-geaendert.png new file mode 100644 index 0000000..a18ac6d Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/08-reihenfolge-geaendert.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/09-entwurf-gespeichert.png b/docs/ux/verwaltung/abnahme/dokumente/09-entwurf-gespeichert.png new file mode 100644 index 0000000..dcec0a4 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/09-entwurf-gespeichert.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/10-vorschau-seite.png b/docs/ux/verwaltung/abnahme/dokumente/10-vorschau-seite.png new file mode 100644 index 0000000..2cec88a Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/10-vorschau-seite.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/11-bereitstellen-dialog.png b/docs/ux/verwaltung/abnahme/dokumente/11-bereitstellen-dialog.png new file mode 100644 index 0000000..cc4ff35 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/11-bereitstellen-dialog.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/12-dokumentfassung-bereitgestellt.png b/docs/ux/verwaltung/abnahme/dokumente/12-dokumentfassung-bereitgestellt.png new file mode 100644 index 0000000..ac474ef Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/12-dokumentfassung-bereitgestellt.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/13-modul-picker-dokumentfassung.png b/docs/ux/verwaltung/abnahme/dokumente/13-modul-picker-dokumentfassung.png new file mode 100644 index 0000000..336da32 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/13-modul-picker-dokumentfassung.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/14-modul-mit-dokument.png b/docs/ux/verwaltung/abnahme/dokumente/14-modul-mit-dokument.png new file mode 100644 index 0000000..d050664 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/14-modul-mit-dokument.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/15-modul-freigabe.png b/docs/ux/verwaltung/abnahme/dokumente/15-modul-freigabe.png new file mode 100644 index 0000000..54dcd6e Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/15-modul-freigabe.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/20-modulseite-mit-dokument.png b/docs/ux/verwaltung/abnahme/dokumente/20-modulseite-mit-dokument.png new file mode 100644 index 0000000..7ff22ad Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/20-modulseite-mit-dokument.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/21-mitgliederansicht-dokument.png b/docs/ux/verwaltung/abnahme/dokumente/21-mitgliederansicht-dokument.png new file mode 100644 index 0000000..9afbfe0 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/21-mitgliederansicht-dokument.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/22-sprung-zu-kapitel.png b/docs/ux/verwaltung/abnahme/dokumente/22-sprung-zu-kapitel.png new file mode 100644 index 0000000..87a11a1 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/22-sprung-zu-kapitel.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/23-kapitel-mit-bild-und-tabelle.png b/docs/ux/verwaltung/abnahme/dokumente/23-kapitel-mit-bild-und-tabelle.png new file mode 100644 index 0000000..6333a2d Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/23-kapitel-mit-bild-und-tabelle.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/24-tabelle.png b/docs/ux/verwaltung/abnahme/dokumente/24-tabelle.png new file mode 100644 index 0000000..6040ff7 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/24-tabelle.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/25-schmales-fenster.png b/docs/ux/verwaltung/abnahme/dokumente/25-schmales-fenster.png new file mode 100644 index 0000000..39543ba Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/25-schmales-fenster.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/26-schmales-fenster-kapitel.png b/docs/ux/verwaltung/abnahme/dokumente/26-schmales-fenster-kapitel.png new file mode 100644 index 0000000..1125e5a Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/26-schmales-fenster-kapitel.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/30-zweite-fassung-in-arbeit.png b/docs/ux/verwaltung/abnahme/dokumente/30-zweite-fassung-in-arbeit.png new file mode 100644 index 0000000..9c3084b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/30-zweite-fassung-in-arbeit.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/31-fassungen-und-verwendung.png b/docs/ux/verwaltung/abnahme/dokumente/31-fassungen-und-verwendung.png new file mode 100644 index 0000000..62eb785 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/31-fassungen-und-verwendung.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/32-modul-fassung-waehlen.png b/docs/ux/verwaltung/abnahme/dokumente/32-modul-fassung-waehlen.png new file mode 100644 index 0000000..45b2c4b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/32-modul-fassung-waehlen.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/33-stand-alt.png b/docs/ux/verwaltung/abnahme/dokumente/33-stand-alt.png new file mode 100644 index 0000000..3ffdb85 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/33-stand-alt.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/33-stand-neu.png b/docs/ux/verwaltung/abnahme/dokumente/33-stand-neu.png new file mode 100644 index 0000000..adc5ecf Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/33-stand-neu.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/40-uebung-trainerhinweis-quelle.png b/docs/ux/verwaltung/abnahme/dokumente/40-uebung-trainerhinweis-quelle.png new file mode 100644 index 0000000..a83c189 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/40-uebung-trainerhinweis-quelle.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/41-uebung-trainerhinweis-bearbeitet.png b/docs/ux/verwaltung/abnahme/dokumente/41-uebung-trainerhinweis-bearbeitet.png new file mode 100644 index 0000000..edfdcc7 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/41-uebung-trainerhinweis-bearbeitet.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/42-uebung-trainerhinweis-gespeichert.png b/docs/ux/verwaltung/abnahme/dokumente/42-uebung-trainerhinweis-gespeichert.png new file mode 100644 index 0000000..65825d9 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/42-uebung-trainerhinweis-gespeichert.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/43-uebung-fassung-freigegeben.png b/docs/ux/verwaltung/abnahme/dokumente/43-uebung-fassung-freigegeben.png new file mode 100644 index 0000000..9a1288e Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/43-uebung-fassung-freigegeben.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/44-uebung-alt.png b/docs/ux/verwaltung/abnahme/dokumente/44-uebung-alt.png new file mode 100644 index 0000000..53f787f Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/44-uebung-alt.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/44-uebung-neu.png b/docs/ux/verwaltung/abnahme/dokumente/44-uebung-neu.png new file mode 100644 index 0000000..7fc73bf Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/44-uebung-neu.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/50-pdf-inhaltsverzeichnis.png b/docs/ux/verwaltung/abnahme/dokumente/50-pdf-inhaltsverzeichnis.png new file mode 100644 index 0000000..9b5e534 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/50-pdf-inhaltsverzeichnis.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/51-pdf-kapitel-mit-bild-und-tabelle.png b/docs/ux/verwaltung/abnahme/dokumente/51-pdf-kapitel-mit-bild-und-tabelle.png new file mode 100644 index 0000000..9fd2533 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/51-pdf-kapitel-mit-bild-und-tabelle.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/52-pdf-letzte-seite.png b/docs/ux/verwaltung/abnahme/dokumente/52-pdf-letzte-seite.png new file mode 100644 index 0000000..7dff64b Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/52-pdf-letzte-seite.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-alt.png b/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-alt.png new file mode 100644 index 0000000..726e2e5 Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-alt.png differ diff --git a/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-neu.png b/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-neu.png new file mode 100644 index 0000000..4bc49ef Binary files /dev/null and b/docs/ux/verwaltung/abnahme/dokumente/53-pdf-uebung-neu.png differ diff --git a/resources/css/components/lf-member.css b/resources/css/components/lf-member.css index 6599221..4e865dc 100644 --- a/resources/css/components/lf-member.css +++ b/resources/css/components/lf-member.css @@ -1136,9 +1136,11 @@ .mb-prose p { margin: 0 0 var(--space-3); } -.mb-prose h3 { +.mb-prose h3, +.mb-prose h4 { margin: var(--space-4) 0 var(--space-2); font-size: var(--text-body); + font-weight: 700; } .mb-prose ul, @@ -1179,6 +1181,48 @@ .mb-prose blockquote > p { margin-bottom: var(--space-2); } +/* Tabellen und Bilder in formatierten Texten (ADR-51) */ +.mb-prose table { + display: block; + max-width: 100%; + margin: 0 0 var(--space-3); + overflow-x: auto; + border-collapse: collapse; + font-size: var(--text-small, 0.95rem); +} + +.mb-prose th, +.mb-prose td { + min-width: 6rem; + padding: var(--space-2) var(--space-3); + border: 1px solid var(--color-border-strong); + text-align: left; + vertical-align: top; +} + +.mb-prose th { + background: var(--color-surface-subtle); + font-weight: 700; +} + +.mb-prose td > p, +.mb-prose th > p { + margin: 0 0 var(--space-1); +} + +.mb-prose img { + display: block; + max-width: 100%; + height: auto; + margin: 0 0 var(--space-3); + border-radius: var(--radius-card); +} + +.mb-prose .mb-bildhinweis { + color: var(--color-text-muted, inherit); + font-style: italic; +} + .mb-reading { max-width: var(--measure); padding: var(--pad-card); @@ -1788,3 +1832,97 @@ @media (max-width: 40rem) { grid-column: 1 / -1; } } + +/* Dokument mit Inhaltsverzeichnis (ADR-51) */ +.mb-document { + max-width: 62rem; +} + +.mb-doc { + display: grid; + gap: var(--space-5); +} + +@media (min-width: 62rem) { + .mb-doc { + grid-template-columns: 17rem minmax(0, 1fr); + align-items: start; + } + + .mb-doc-toc { + position: sticky; + top: var(--space-4); + max-height: calc(100vh - 2 * var(--space-4)); + overflow-y: auto; + } +} + +.mb-doc-toc { + padding: var(--pad-card); + border: 1px solid var(--color-border); + border-radius: var(--radius-card); + background: var(--color-surface-subtle); +} + +.mb-doc-toc summary { + font-weight: 700; + cursor: pointer; +} + +.mb-doc-toc ol { + display: grid; + gap: var(--space-1); + margin: var(--space-3) 0 0; + padding: 0; + list-style: none; +} + +.mb-doc-toc a { + display: block; + padding: var(--space-1) 0; + color: var(--color-text); + text-decoration: none; +} + +.mb-doc-toc a:hover, +.mb-doc-toc a:focus-visible { + text-decoration: underline; +} + +.mb-doc-toc-2 { + padding-left: var(--space-4); + font-size: 0.95em; +} + +.mb-doc-nr { + display: inline-block; + min-width: 2.2ch; + color: var(--lf-green-deep); + font-variant-numeric: tabular-nums; + font-weight: 700; +} + +.mb-doc-body { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.mb-doc-chapter { + scroll-margin-top: var(--space-5); +} + +.mb-doc-level-1 > h2 { + margin: 0 0 var(--space-3); + padding-bottom: var(--space-2); + border-bottom: 2px solid var(--color-accent); +} + +.mb-doc-level-2 > h3 { + margin: 0 0 var(--space-2); +} + +.mb-doc-up { + margin: var(--space-3) 0 0; + font-size: 0.9em; +} diff --git a/resources/views/content/player.blade.php b/resources/views/content/player.blade.php index fbe7786..5697bff 100644 --- a/resources/views/content/player.blade.php +++ b/resources/views/content/player.blade.php @@ -27,6 +27,6 @@ @if (filled($version->body))
- {!! \App\Domain\Catalog\FormattedText::display($version->body) !!} + {!! \App\Domain\Catalog\FormattedText::display($version->body, \App\Domain\Catalog\EmbeddedImages::staff()) !!}
@endif diff --git a/resources/views/document/preview.blade.php b/resources/views/document/preview.blade.php new file mode 100644 index 0000000..1f1d6e3 --- /dev/null +++ b/resources/views/document/preview.blade.php @@ -0,0 +1,24 @@ +@extends('layouts.site') + +@section('title', 'Vorschau: '.$guide['title']) + +{{-- Vorschau eines Dokuments für die Redaktion: so sehen Mitglieder die Seite; das PDF liegt daneben. Nur für die Verwaltung. --}} +@section('content') +
+

Vorschau für die Redaktion. Gezeigt wird der gespeicherte Entwurf, sonst die letzte bereitgestellte Fassung. Ungespeicherte Änderungen im Editor erscheinen hier erst nach „Entwurf speichern“.

+
+
+

{{ $guide['title'] }}

+ @if (filled($guide['summary_html'])) +
{!! $guide['summary_html'] !!}
+ @endif +
+

+ @if ($guide['chapters'] === []) +

Das Dokument hat noch kein Kapitel.

+ @else + @include('member.partials.document', ['guide' => $guide]) + @endif +
+
+@endsection diff --git a/resources/views/filament/editorial/editor.blade.php b/resources/views/filament/editorial/editor.blade.php index 250845b..f1de4a4 100644 --- a/resources/views/filament/editorial/editor.blade.php +++ b/resources/views/filament/editorial/editor.blade.php @@ -13,8 +13,9 @@ } $aktionen[] = ['label' => 'Redaktion bearbeiten', 'wire' => "openRedaktion('texte')", 'art' => 'line', 'icon' => 'stift']; $aktionen[] = ['label' => 'Entwurf speichern', 'wire' => 'saveDraft', 'art' => 'primary']; - $mehr = [['label' => 'Fassung freigeben', 'wire' => 'armRelease', 'hinweis' => 'Neue unveränderliche Fassung aus dem Aufbau.']]; - if ($bereit !== null) { + $dokument = $this->isDocument(); + $mehr = [['label' => $dokument ? 'Dokumentfassung bereitstellen' : 'Fassung freigeben', 'wire' => 'armRelease', 'hinweis' => $dokument ? 'Eine unveränderliche Fassung des ganzen Dokuments; Module und Programme binden genau diese ein.' : 'Neue unveränderliche Fassung aus dem Aufbau.']]; + if ($bereit !== null && ! $dokument) { $mehr[] = $this->isInLibrary() ? ['label' => 'Aus Mitgliederbibliothek ausblenden', 'wire' => "mountAction('displayRevoke')", 'hinweis' => 'Der Inhalt bleibt gespeichert.'] : ['label' => 'In Mitgliederbibliothek anzeigen', 'wire' => "mountAction('displayRelease')", 'hinweis' => 'Zeigt die letzte freigegebene Fassung.']; @@ -22,8 +23,8 @@ $mehr[] = ['label' => 'Entwurf verwerfen', 'wire' => 'discardDraft', 'hinweis' => 'Zurück zum letzten gespeicherten Aufbau.', 'gefahr' => true]; $anzahl = count($this->members); $typ = implode(' · ', array_filter([ - 'Aufbau', - $bereit !== null ? 'Fassung '.$bereit->number.' freigegeben' : 'Noch keine Fassung', + $dokument ? 'Kapitel' : 'Aufbau', + $bereit !== null ? 'Fassung '.$bereit->number.($dokument ? ' bereitgestellt' : ' freigegeben') : 'Noch keine Fassung', is_array($this->getRecord()->working_draft) && $this->getRecord()->working_draft !== [] ? 'Entwurf gespeichert' : null, ])); @endphp @@ -52,7 +53,11 @@

@endif -

@include('filament.verwaltung.icon', ['name' => 'info'])„Entwurf speichern“ sichert Aufbau, Rollen, Hinweise und Didaktik. Freigegebene Fassungen bleiben unverändert, bis du eine neue Fassung freigibst. Texte und Präsentation bearbeitest du in der Redaktion.

+ @if ($dokument) +

@include('filament.verwaltung.icon', ['name' => 'info'])„Entwurf speichern“ sichert Gliederung und Texte aller Kapitel. Bereitgestellte Dokumentfassungen bleiben unverändert, bis du eine neue Dokumentfassung bereitstellst. Titel, Beschreibung und Einordnung des Dokuments bearbeitest du in der Redaktion.

+ @else +

@include('filament.verwaltung.icon', ['name' => 'info'])„Entwurf speichern“ sichert Aufbau, Rollen, Hinweise und Didaktik. Freigegebene Fassungen bleiben unverändert, bis du eine neue Fassung freigibst. Texte und Präsentation bearbeitest du in der Redaktion.

+ @endif @foreach (array_unique(array_filter([$this->feedback, $this->deskFeedback])) as $meldung)

{{ $meldung }}

@@ -60,7 +65,7 @@
- @foreach (['aufbau' => 'Aufbau', 'angaben' => 'Didaktik und Katalogbild', 'verlauf' => 'Fassungen und Verwendung'] as $wert => $label) + @foreach (['aufbau' => $dokument ? 'Kapitel' : 'Aufbau', 'angaben' => $dokument ? 'Katalogbild' : 'Didaktik und Katalogbild', 'verlauf' => 'Fassungen und Verwendung'] as $wert => $label)
@@ -123,7 +130,7 @@
- +
diff --git a/resources/views/filament/verwaltung/aufbau-angaben.blade.php b/resources/views/filament/verwaltung/aufbau-angaben.blade.php index a6c345b..cecc69c 100644 --- a/resources/views/filament/verwaltung/aufbau-angaben.blade.php +++ b/resources/views/filament/verwaltung/aufbau-angaben.blade.php @@ -6,6 +6,14 @@ @endphp
+ @if ($this->isDocument()) +

Dokument

+

Ein Dokument hat keine Didaktikangaben. Die Kapitel schreibst du im Register „Kapitel“. Name, Beschreibung und Einordnung des Dokuments bearbeitest du in der Redaktion. +

+ + @else

Didaktik

Lernziel, Zeit und Material gehören zum fachlichen Stand {{ $ort }}. Sie werden mit „Entwurf speichern“ gesichert und erst mit „Fassung freigeben“ Teil einer neuen Fassung.

@@ -57,6 +65,7 @@ @endif

Name, Texte, Präsentationsmedien und Einordnung bearbeitest du in der Redaktion.

+ @endif
@if (! $isGroup && ! $node['view_url'])

Nicht enthalten. Für diesen Teil liegt keine Freigabe vor.

- @elseif ($isGroup && $node['children'] === []) + @elseif ($isGroup && $node['children'] === [] && empty($node['document']))

Nicht enthalten. Für diesen Teil liegt keine Freigabe vor.

@endif @if ($node['children'] !== []) diff --git a/resources/views/member/read.blade.php b/resources/views/member/read.blade.php index c290f80..e3a2767 100644 --- a/resources/views/member/read.blade.php +++ b/resources/views/member/read.blade.php @@ -14,7 +14,7 @@

Lizenzkennzeichnung: {{ $license }}

@endif
- {!! \App\Domain\Catalog\FormattedText::display($version->body) !!} + {!! \App\Domain\Catalog\FormattedText::display($version->body, $images ?? null) !!}
@endsection diff --git a/routes/web.php b/routes/web.php index 68cb9dd..150c687 100644 --- a/routes/web.php +++ b/routes/web.php @@ -6,13 +6,16 @@ use App\Http\Controllers\Auth\SessionController; use App\Http\Controllers\CartController; use App\Http\Controllers\ContentPreviewController; +use App\Http\Controllers\DocumentPreviewController; use App\Http\Controllers\EditorialPreviewController; use App\Http\Controllers\Member\CheckoutController; +use App\Http\Controllers\Member\DocumentController; use App\Http\Controllers\Member\ExerciseController; use App\Http\Controllers\Member\LibraryController; use App\Http\Controllers\Member\MemberController; use App\Http\Controllers\Member\PaymentController; use App\Http\Controllers\Member\ProfileController; +use App\Http\Controllers\Member\StandImageController; use App\Http\Controllers\PageController; use App\Http\Controllers\PublicCatalogController; use App\Http\Controllers\PublicMediaController; @@ -72,6 +75,14 @@ ->middleware('auth:staff') ->whereNumber('revision') ->name('pages.preview.devices'); +Route::get('/redaktion/dokument/{composition}', [DocumentPreviewController::class, 'show']) + ->middleware('auth:staff') + ->whereNumber('composition') + ->name('editorial.document-preview'); +Route::get('/redaktion/dokument/{composition}/pdf', [DocumentPreviewController::class, 'pdf']) + ->middleware('auth:staff') + ->whereNumber('composition') + ->name('editorial.document-preview.pdf'); Route::get('/redaktion/aufbau/{composition}/entwurf', [EditorialPreviewController::class, 'draft']) ->middleware('auth:staff') ->name('editorial.draft-preview'); @@ -135,6 +146,15 @@ ->where('path', '[0-9]+(?:-[0-9]+)*') ->middleware('signed:relative') ->name('exercise.pdf'); + Route::get('/stand/{article}/{release}/dokument/{path}', [DocumentController::class, 'show']) + ->where('path', '[0-9]+(?:-[0-9]+)*') + ->name('document'); + Route::get('/stand/{article}/{release}/dokument/{path}/pdf', [DocumentController::class, 'pdf']) + ->where('path', '[0-9]+(?:-[0-9]+)*') + ->name('document.pdf'); + Route::get('/stand/{article}/{release}/bild/{text}/{version}', StandImageController::class) + ->whereNumber(['text', 'version']) + ->name('stand.image'); Route::get('/abschnitt/{article}/{release}/{version}/{datei}', [LibraryController::class, 'rendition']) ->where('datei', '.*') ->middleware('signed:relative') diff --git a/tests/Feature/DokumentAusgabeTest.php b/tests/Feature/DokumentAusgabeTest.php new file mode 100644 index 0000000..fcdef1b --- /dev/null +++ b/tests/Feature/DokumentAusgabeTest.php @@ -0,0 +1,289 @@ +sold(); + + $response = $this->actingAs($member)->get($this->documentPage($article, $release))->assertOk(); + + $response->assertSee('Trainerhandbuch') + ->assertSee('Inhaltsverzeichnis') + ->assertSee('href="#kapitel-1"', false) + ->assertSee('href="#kapitel-1-1"', false) + ->assertSee('href="#kapitel-2"', false) + ->assertSee('id="kapitel-2"', false) + ->assertSee('Grundlagen') + ->assertSee('Haltung') + ->assertSee('Lizenzkopie LK-') + ->assertSee('Als PDF herunterladen'); + + $html = $response->getContent(); + $this->assertLessThan(strpos($html, 'Haltung', strpos($html, 'id="kapitel-1-1"')), strpos($html, 'id="kapitel-1"'), 'Die Kapitel stehen in ihrer Reihenfolge.'); + $this->assertStringContainsString('', $html); + $this->assertStringContainsString('Begrüßung', $html); + $this->assertStringContainsString('

Zwischenüberschrift

', $html, 'Zwischenüberschriften stehen eine Ebene unter dem Kapitel.'); + $this->assertMatchesRegularExpression('#Aufstellungid.'/'.$release->id.'/bild/\d+/'.$image->id.'"#', $html, 'Die Adresse des Bildes läuft nicht ab.'); + } + + public function test_the_image_address_delivers_only_the_bound_image_of_that_text_for_a_member_with_the_right_to_the_text(): void + { + [$article, $release, $member, $image] = $this->sold(); + $html = $this->actingAs($member)->get($this->documentPage($article, $release))->getContent(); + preg_match('#AufstellungactingAs($member)->get($src)->assertOk(); + $this->assertStringStartsWith('image/', (string) $response->headers->get('Content-Type')); + $this->assertContains($image->id, MediaDelivery::query()->pluck('content_element_version_id')->all(), 'Die Auslieferung steht im Nachweis.'); + + $other = $this->memberWith($this->fullRights(), [$this->publishFor('anderes', $this->document(['Anderes' => 'Text']))[0]]); + $this->actingAs($other)->get($src)->assertForbidden(); + + // Ein anderer Text des Stands enthält das Bild nicht: Die Adresse gibt es für ihn nicht frei. + $anhang = ContentElementVersion::query()->whereHas('element', fn ($query) => $query->where('working_title', 'Anhang'))->first(); + $this->actingAs($member)->get(route('member.stand.image', ['article' => $article, 'release' => $release, 'text' => $anhang->id, 'version' => $image->id]))->assertForbidden(); + $this->actingAs($member)->get(route('member.stand.image', ['article' => $article, 'release' => $release, 'text' => $anhang->id, 'version' => $anhang->id]))->assertForbidden(); + } + + public function test_a_long_reading_session_does_not_break_images_or_the_pdf_button(): void + { + [$article, $release, $member] = $this->sold(); + $html = $this->actingAs($member)->get($this->documentPage($article, $release))->getContent(); + preg_match('#Aufstellungtravel(45)->minutes(); + + $this->actingAs($member)->get(html_entity_decode($image[1]))->assertOk(); + $this->actingAs($member)->get(html_entity_decode($pdf[1]))->assertOk()->assertHeader('Content-Type', 'application/pdf'); + } + + public function test_the_pdf_has_the_table_of_contents_with_correct_page_numbers_tables_images_and_marking(): void + { + [$article, $release, $member, $image] = $this->sold(); + + $response = $this->actingAs($member)->get($this->pdfUrl($article, $release, $member)); + $response->assertOk()->assertHeader('Content-Type', 'application/pdf'); + $pdf = $response->getContent(); + $pages = $this->pdfPages($pdf); + $text = implode("\n", $pages); + + $this->assertStringContainsString('Inhaltsverzeichnis', $pages[0]); + $this->assertMatchesRegularExpression('/\/Subtype \/Link/', $pdf, 'Das Inhaltsverzeichnis ist anklickbar.'); + $this->assertStringContainsString('/Outlines', $pdf); + $this->assertStringContainsString('/Subtype /Image', $pdf); + $this->assertStringContainsString('/Filter /DCTDecode', $pdf); + $this->assertStringContainsString('Zeit', $text); + $this->assertStringContainsString('Begrüßung', $text); + $this->assertStringContainsString('Seite 1 von '.count($pages), $pages[0]); + $this->assertStringContainsString('Lizenziert für '.$member->name.' · Lizenzkopie LK-', $text); + + // Jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite; das Inhaltsverzeichnis nennt die richtige Seite. + foreach (['1' => 'Grundlagen', '1.1' => 'Haltung', '2' => 'Anhang'] as $number => $title) { + $start = null; + + foreach ($pages as $index => $page) { + if ($index > 0 && str_contains($page, $number.' '.$title)) { + $start = $index + 1; + break; + } + } + + $this->assertNotNull($start, 'Kapitel '.$title.' steht im PDF.'); + $this->assertMatchesRegularExpression('/'.preg_quote($number.' '.$title, '/').'\s+\.{3,}\s+'.$start.'\s/', $pages[0]); + } + + $rows = MediaDelivery::query()->where('format', 'pdf')->get(); + $this->assertContains($image->id, $rows->pluck('content_element_version_id')->all(), 'Das Bild steht im Ausgabenachweis des PDF.'); + $this->assertSame(['k2'], $rows->pluck('marking')->unique()->all()); + } + + public function test_a_handbook_of_more_than_thirty_pages_keeps_contents_and_page_numbers_consistent(): void + { + $chapters = []; + + foreach (range(1, 12) as $n) { + $chapters['Kapitel '.$n] = implode("\n\n", array_map(fn (int $p): string => "Absatz $p von Kapitel $n: ".str_repeat('Haltung zeigen und Abstand halten. ', 26), range(1, 12))); + $chapters['-Unterkapitel '.$n.'.1'] = "Text zu Unterkapitel $n.\n\n- Punkt A\n- Punkt B"; + } + + [$article, $release] = $this->publishFor('handbuch', $this->moduleWith('Modul lang', $this->document($chapters, 'Langes Handbuch'))); + $member = $this->memberWith($this->fullRights(), [$article]); + + $response = $this->actingAs($member)->get($this->pdfUrl($article, $release, $member))->assertOk(); + $pages = $this->pdfPages($response->getContent()); + + $this->assertGreaterThan(30, count($pages)); + $this->assertStringContainsString('Seite '.count($pages).' von '.count($pages), end($pages)); + $this->assertStringContainsString('Inhaltsverzeichnis', $pages[0]); + + foreach (range(1, 12) as $n) { + $start = null; + + foreach ($pages as $index => $page) { + if ($index > 0 && str_contains($page, $n.' Kapitel '.$n)) { + $start = $index + 1; + break; + } + } + + $this->assertNotNull($start); + $this->assertMatchesRegularExpression('/'.preg_quote($n.' Kapitel '.$n, '/').'\s+\.{3,}\s+'.$start.'\s/', implode("\n", array_slice($pages, 0, 2)), 'Seitenzahl im Inhaltsverzeichnis für Kapitel '.$n); + } + + $this->actingAs($member)->get($this->documentPage($article, $release))->assertOk()->assertSee('href="#kapitel-12-1"', false); + } + + public function test_an_older_stand_keeps_delivering_the_version_it_bound_while_a_newer_stand_shows_the_new_one(): void + { + $composition = $this->documentComposition(); + $first = $this->document(['Grundlagen' => 'Erste Fassung des Handbuchs.', '-Haltung' => 'Alt: Abstand halten.'], composition: $composition); + $second = $this->document(['Grundlagen' => 'Zweite Fassung des Handbuchs.', '-Haltung' => 'Neu: Abstand und Blickkontakt.', 'Anhang' => 'Neues Kapitel.'], composition: $composition); + $this->assertSame([1, 2], $composition->versions()->orderBy('number')->pluck('number')->all()); + + $articles = app(ArticleService::class); + $article = $articles->create('hb'); + $one = $articles->publishRelease($article, $this->moduleWith('Modul eins', $first), 'Stand 1.'); + $two = $articles->publishRelease($article->fresh(), $this->moduleWith('Modul zwei', $second), 'Stand 2.'); + $member = $this->memberWith($this->fullRights(), [$article]); + + $this->actingAs($member)->get($this->documentPage($article, $one))->assertOk() + ->assertSee('Erste Fassung des Handbuchs.')->assertSee('Alt: Abstand halten.')->assertDontSee('Zweite Fassung')->assertDontSee('Anhang'); + $this->actingAs($member)->get($this->documentPage($article, $two))->assertOk() + ->assertSee('Zweite Fassung des Handbuchs.')->assertSee('Anhang')->assertDontSee('Erste Fassung'); + + $oldPdf = $this->pdfText($this->actingAs($member)->get($this->pdfUrl($article, $one, $member))->getContent()); + $newPdf = $this->pdfText($this->actingAs($member)->get($this->pdfUrl($article, $two, $member))->getContent()); + $this->assertStringContainsString('Alt: Abstand halten.', $oldPdf); + $this->assertStringNotContainsString('Anhang', $oldPdf); + $this->assertStringContainsString('Neu: Abstand und Blickkontakt.', $newPdf); + $this->assertStringContainsString('Anhang', $newPdf); + } + + public function test_the_module_page_shows_the_document_as_one_entry_that_leads_to_the_bound_version(): void + { + [$article, $release, $member] = $this->sold(); + app(CompositionDisplayRelease::class)->release($release->rootCompositionVersion, $member); + + $page = $this->actingAs($member)->get(route('member.program', $release->rootCompositionVersion->composition_id))->assertOk(); + + $page->assertSee($this->documentPage($article, $release, '1'), false)->assertSee('Trainerhandbuch'); + $this->assertStringNotContainsString('id="kapitel-1"', $page->getContent()); + $page->assertDontSee('Nicht enthalten'); + } + + public function test_images_in_a_text_follow_the_rights_to_the_text_and_need_no_right_for_images(): void + { + [$article, $release, , $image] = $this->sold(); + // Bestehende Berechtigungen nennen nur Texte (kein `bild`): Die Bilder der Texte erscheinen trotzdem. + $member = $this->memberWith($this->rights(['text' => ['ansehen', 'laden']]), [$article]); + + $html = $this->actingAs($member)->get($this->documentPage($article, $release))->assertOk()->assertSee('Begrüßung')->getContent(); + $this->assertStringContainsString('AufstellungactingAs($member)->get($this->pdfUrl($article, $release, $member))->assertForbidden(); + $text = ContentElementVersion::query()->whereHas('element', fn ($query) => $query->where('working_title', 'Grundlagen'))->first(); + $this->actingAs($member)->get(route('member.stand.image', ['article' => $article, 'release' => $release, 'text' => $text->id, 'version' => $image->id]))->assertForbidden(); + } + + public function test_a_pdf_needs_the_download_right_for_every_chapter_but_the_page_stays_readable(): void + { + [$article, $release] = $this->sold(); + $reader = $this->memberWith($this->rights(['text' => ['ansehen'], 'bild' => ['ansehen']]), [$article]); + + $this->actingAs($reader)->get($this->documentPage($article, $release))->assertOk()->assertSee('Grundlagen')->assertDontSee('Als PDF herunterladen')->assertSee('Ein PDF ist für diese Lizenz oder derzeit nicht verfügbar.'); + $this->actingAs($reader)->get($this->pdfUrl($article, $release, $reader))->assertForbidden(); + } + + public function test_a_blocked_image_affects_only_the_image_and_a_foreign_account_sees_nothing(): void + { + [$article, $release, $member, $image] = $this->sold(); + app(ContentService::class)->block($image, 'Rechte geklärt: gesperrt'); + + $this->actingAs($member)->get($this->documentPage($article, $release))->assertOk()->assertSee('Begrüßung')->assertSee('Dieses Bild ist derzeit nicht verfügbar.'); + + $stranger = User::factory()->create(); + $this->actingAs($stranger)->get($this->documentPage($article, $release))->assertForbidden(); + } + + public function test_the_page_and_the_pdf_of_the_same_stand_list_the_same_chapters_in_the_same_order(): void + { + [$article, $release, $member] = $this->sold(); + $html = $this->actingAs($member)->get($this->documentPage($article, $release))->getContent(); + preg_match_all('#([\d.]+) ([^<]+)#', $html, $page); + $pdf = $this->pdfPages($this->actingAs($member)->get($this->pdfUrl($article, $release, $member))->getContent())[0]; + preg_match_all('/^([\d.]+) (.+)$/m', $pdf, $print); + + $this->assertSame(['1', '1.1', '2'], $page[1]); + $this->assertSame($page[1], array_slice($print[1], 0, 3)); + $this->assertSame($page[2], array_slice(array_map('trim', $print[2]), 0, 3)); + } + + /** + * Ein Handbuch mit Tabelle, Zwischenüberschrift und Bild, eingebunden in ein verkauftes Modul. + * + * @return array{0: LicenseArticle, 1: ArticleRelease, 2: User, 3: ContentElementVersion} + */ + private function sold(): array + { + $image = $this->picture('Aufstellung'); + $table = '

Zeit

Inhalt

10 Min.

Begrüßung

'; + $document = $this->document([ + 'Grundlagen' => '

Einleitung zum Handbuch.

Zwischenüberschrift

'.$table.'Aufstellung

Danach.

', + '-Haltung' => '

Sicher stehen.

  • Abstand

', + 'Anhang' => '

Weitere Hinweise.

', + ]); + $module = $this->moduleWith('Modul Handbuch', $document); + [$article, $release] = $this->publishFor('handbuch-modul', $module); + + return [$article, $release, $this->memberWith($this->fullRights(), [$article]), $image]; + } + + private function pdfUrl($article, $release, $member, string $path = '1'): string + { + return route('member.document.pdf', ['article' => $article, 'release' => $release, 'path' => $path]); + } +} diff --git a/tests/Feature/DokumentEditorTest.php b/tests/Feature/DokumentEditorTest.php new file mode 100644 index 0000000..9c78141 --- /dev/null +++ b/tests/Feature/DokumentEditorTest.php @@ -0,0 +1,260 @@ +create('Trainerhandbuch', CompositionKind::Document); + + $this->assertSame(CompositionKind::Document, $document->kind); + $this->assertSame('dokument', $document->editorialContentKind?->slug); + $this->assertStringEndsWith('/dokumente/'.$document->id, EditorialCatalog::editUrl($document)); + + $this->actingAs($this->editor(), 'staff')->get('/verwaltung/dokumente')->assertOk()->assertSee('Dokument anlegen')->assertSee('Trainerhandbuch'); + $this->actingAs($this->editor(), 'staff')->get('/verwaltung/dokumente/'.$document->id)->assertOk()->assertSee('Kapitelübersicht')->assertSee('Erstes Kapitel anlegen'); + } + + public function test_chapters_and_subchapters_get_numbers_from_their_order_and_are_marked_as_chapters_of_the_document(): void + { + [$component, $document] = $this->open(); + + $component->call('addChapter', 1)->call('addChapter', 2)->call('addChapter', 2)->call('addChapter', 1); + + $this->assertSame(['1', '1.1', '1.2', '2'], array_column($component->instance()->chapterRows(), 'number')); + $this->assertSame([1, 2, 2, 1], array_column($component->instance()->chapterRows(), 'level')); + + $element = ContentElementVersion::query()->with('element.editorialContentKind')->get()->first()->element; + $this->assertSame('dokumentkapitel', $element->editorialContentKind->slug); + $this->assertSame($document->id, $element->origin_composition_id); + } + + public function test_switching_chapters_keeps_open_input_and_the_outline_and_nothing_is_written_before_saving(): void + { + [$component, $document] = $this->open(); + $component->call('addChapter', 1)->call('addChapter', 1)->call('addChapter', 1); + $first = $component->get('members.0.target'); + + $component->call('selectChapter', 0) + ->set('partTitle', 'Grundlagen') + ->set('rich.partBody', $this->doc('Erster Text')) + ->call('selectChapter', 1) + ->set('partTitle', 'Aufbau') + ->set('rich.partBody', $this->doc('Zweiter Text')) + ->call('selectChapter', 2) + ->call('selectChapter', 0); + + $this->assertSame('Grundlagen', $component->get('partTitle'), 'Titel des ersten Kapitels ist wieder da.'); + $this->assertSame('

Erster Text

', $component->get('partBody')); + $this->assertCount(2, $component->get('chapterEdits'), 'Beide offenen Kapitel sind im Arbeitsstand.'); + $this->assertSame(['Grundlagen', 'Aufbau', 'Neues Kapitel'], array_column($component->instance()->chapterRows(), 'title')); + $this->assertStringContainsString('ungespeicherte Änderungen', $component->instance()->editorStatus()); + $this->assertSame('

', ContentElementVersion::query()->find((int) substr($first, 8))->body, 'Gespeichert ist noch nichts.'); + } + + public function test_saving_writes_every_chapter_as_a_draft_and_the_draft_survives_reopening(): void + { + [$component, $document] = $this->open(); + $component->call('addChapter', 1)->call('addChapter', 2) + ->call('selectChapter', 0)->set('partTitle', 'Grundlagen')->set('rich.partBody', $this->doc('Erster Text')) + ->call('selectChapter', 1)->set('partTitle', 'Haltung')->set('rich.partBody', $this->doc('Zweiter Text')) + ->call('saveDraft'); + + $this->assertSame([], $component->get('chapterEdits')); + $this->assertStringNotContainsString('ungespeicherte', $component->instance()->editorStatus()); + $this->assertSame(0, $document->versions()->count(), 'Es entsteht keine Dokumentfassung.'); + $versions = ContentElementVersion::query()->with('element')->orderBy('id')->get(); + $this->assertSame(['Grundlagen', 'Haltung'], $versions->pluck('element.working_title')->all()); + $this->assertSame('

Erster Text

', $versions[0]->body); + $this->assertSame(ContentVersionStatus::Entwurf, $versions[0]->status); + + $reopened = Livewire::actingAs($this->editor(), 'staff')->test(EditDocument::class, ['record' => $document->getKey()]); + $this->assertSame(['Grundlagen', 'Haltung'], array_column($reopened->instance()->chapterRows(), 'title')); + $this->assertSame(['Kapitel', 'Unterkapitel'], array_column($reopened->get('members'), 'role')); + } + + public function test_reordering_moves_a_chapter_with_its_subchapters_and_keeps_the_open_text(): void + { + [$component] = $this->open(); + $component->call('addChapter', 1)->call('addChapter', 2)->call('addChapter', 1)->call('addChapter', 2)->call('addChapter', 2); + $titles = ['A', 'A1', 'B', 'B1', 'B2']; + + foreach ($titles as $index => $title) { + $component->call('selectChapter', $index)->set('partTitle', $title); + } + + $component->call('selectChapter', 2)->set('rich.partBody', $this->doc('Text von B')); + $component->call('movePart', 2, -1); + $this->assertSame(['B', 'B1', 'B2', 'A', 'A1'], array_column($component->instance()->chapterRows(), 'title')); + $this->assertSame(['1', '1.1', '1.2', '2', '2.1'], array_column($component->instance()->chapterRows(), 'number')); + $this->assertSame(0, $component->get('selected'), 'Das gewählte Kapitel bleibt gewählt.'); + $this->assertSame('

Text von B

', $component->get('partBody'), 'Der offene Text ging nicht verloren.'); + + // Ziehen: das zweite Kapitel hinter das erste. + $component->call('moveTo', 3, 0); + $this->assertSame(['A', 'A1', 'B', 'B1', 'B2'], array_column($component->instance()->chapterRows(), 'title')); + + // Unterkapitel wandern innerhalb des Kapitels und über die Kapitelgrenze. + $component->call('movePart', 4, -1); + $this->assertSame(['A', 'A1', 'B', 'B2', 'B1'], array_column($component->instance()->chapterRows(), 'title')); + $component->call('movePart', 3, -1); + $this->assertSame(['A', 'A1', 'B2', 'B', 'B1'], array_column($component->instance()->chapterRows(), 'title')); + } + + public function test_the_level_changes_and_the_first_chapter_stays_a_chapter(): void + { + [$component] = $this->open(); + $component->call('addChapter', 1)->call('addChapter', 1); + + $component->call('setChapterLevel', 0, 2); + $this->assertSame('Kapitel', $component->get('members.0.role')); + + $component->call('setChapterLevel', 1, 2); + $this->assertSame(['1', '1.1'], array_column($component->instance()->chapterRows(), 'number')); + $component->call('setChapterLevel', 1, 1); + $this->assertSame(['1', '2'], array_column($component->instance()->chapterRows(), 'number')); + } + + public function test_providing_the_document_creates_one_version_that_binds_the_chapter_versions_in_order(): void + { + [$component, $document] = $this->open(); + $component->call('addChapter', 1)->call('addChapter', 2) + ->call('selectChapter', 0)->set('partTitle', 'Grundlagen')->set('rich.partBody', $this->doc('Erster Text')) + ->call('selectChapter', 1)->set('partTitle', 'Haltung')->set('rich.partBody', $this->doc('Zweiter Text')) + ->call('armRelease') + ->assertSet('releaseArmed', true); + + $this->assertSame([], $component->get('chapterEdits'), 'Die Texte wurden vor der Bereitstellung gespeichert.'); + $component->set('releaseConsent', true)->call('publishRevision'); + + $version = $document->versions()->with('members.contentElementVersion')->first(); + $this->assertSame(1, $version->number); + $this->assertSame(ContentVersionStatus::Bereit, $version->status); + $this->assertSame(['Kapitel', 'Unterkapitel'], $version->members->pluck('role')->all()); + $this->assertSame(['

Erster Text

', '

Zweiter Text

'], $version->members->map(fn ($member) => $member->contentElementVersion->body)->all()); + $this->assertTrue($version->members->every(fn ($member) => $member->contentElementVersion->status === ContentVersionStatus::Bereit)); + + // Eine spätere Bearbeitung ändert die bereitgestellte Fassung nicht: Sie erzeugt Entwürfe und erst mit der Bereitstellung eine zweite Fassung. + $component->call('selectChapter', 0)->set('rich.partBody', $this->doc('Geänderter Text'))->call('saveDraft'); + $this->assertSame(1, $document->versions()->count()); + $this->assertSame('

Erster Text

', $version->members()->first()->contentElementVersion()->first()->body); + $this->assertSame(ContentVersionStatus::Entwurf, ContentElementVersion::query()->latest('id')->first()->status); + + $component->call('armRelease')->set('releaseConsent', true)->call('publishRevision'); + $second = $document->versions()->where('number', 2)->with('members.contentElementVersion')->first(); + $this->assertSame('

Geänderter Text

', $second->members->first()->contentElementVersion->body); + $this->assertSame('

Zweiter Text

', $second->members->last()->contentElementVersion->body); + } + + public function test_a_module_offers_only_provided_document_versions_through_the_shared_picker(): void + { + $provided = $this->documentVersion('Handbuch fertig', 'Kapitel eins'); + $draftOnly = app(EditorialCatalog::class)->create('Handbuch im Entwurf', CompositionKind::Document); + $draftOnly->forceFill(['working_draft' => ['members' => [['role' => 'Kapitel', 'target' => 'element:1', 'note' => '']]]])->save(); + $module = app(EditorialCatalog::class)->create('Modul', CompositionKind::Uebung); + + $component = Livewire::actingAs($this->editor(), 'staff')->test(EditModule::class, ['record' => $module->getKey()])->call('openPicker'); + $titles = fn (string $kind): array => array_column($component->set('pickerKind', $kind)->instance()->pickerResult()['items'], 'title'); + + $this->assertArrayHasKey('dokumentfassung', $component->instance()->pickerKinds()); + $this->assertArrayHasKey('dokument', $component->instance()->pickerKinds(), 'Der bisherige Filter für Dokumentdateien bleibt.'); + $this->assertSame(['Handbuch fertig'], $titles('dokumentfassung')); + $this->assertContains('Handbuch fertig', $titles('alle')); + $this->assertNotContains('Handbuch im Entwurf', $titles('alle'), 'Ein Dokument ohne bereitgestellte Fassung lässt sich nicht einbinden.'); + $this->assertNotContains('Handbuch fertig', $titles('modul')); + + $component->call('markPicker', 'composition:'.$provided->id, true)->call('confirmPicker'); + $this->assertSame('composition:'.$provided->id, $component->get('members.0.target')); + } + + private function documentVersion(string $title, string $chapterTitle): CompositionVersion + { + $content = app(ContentService::class); + $document = app(EditorialCatalog::class)->create($title, CompositionKind::Document); + $chapter = $content->publishElementVersion($content->createElement('text', 'text', $chapterTitle), '

Text

'); + + return $content->publishComposition($document, [['role' => 'Kapitel', 'target' => $chapter]]); + } + + public function test_a_chapter_shows_in_the_media_library_with_a_link_to_its_document_and_stays_out_of_the_default_list(): void + { + [$component, $document] = $this->open(); + $component->call('addChapter', 1)->call('selectChapter', 0)->set('partTitle', 'Grundlagen')->call('saveDraft'); + $element = ContentElement::query()->where('working_title', 'Grundlagen')->firstOrFail(); + + $library = app(MediaLibrary::class); + $card = $library->cardFor($element->fresh(), true); + + $this->assertSame('Dokumentkapitel', $card['editorialKind']); + $this->assertSame('Trainerhandbuch', $card['exercise']['title']); + $this->assertSame('Dokument', $card['exercise']['kind']); + $this->assertStringEndsWith('/dokumente/'.$document->getKey(), (string) $card['exercise']['url']); + $this->assertTrue(EditorialContentKind::query()->where('slug', 'dokumentkapitel')->firstOrFail()->isAutomatic(), 'Wie die Übungsabschnitte nur automatisch gesetzt und standardmäßig ausgeblendet.'); + } + + public function test_a_chapter_cannot_be_saved_without_a_title(): void + { + [$component] = $this->open(); + $component->call('addChapter', 1)->call('selectChapter', 0)->set('partTitle', ' ')->call('saveDraft'); + + $this->assertStringContainsString('braucht einen Titel', (string) $component->get('feedback')); + $this->assertNull(Composition::query()->first()->working_draft); + } + + /** + * @return array{0: Testable, 1: Composition} + */ + private function open(): array + { + $document = app(EditorialCatalog::class)->create('Trainerhandbuch', CompositionKind::Document); + + return [Livewire::actingAs($this->editor(), 'staff')->test(EditDocument::class, ['record' => $document->getKey()]), $document]; + } + + /** @return array */ + private function doc(string $text): array + { + return ['type' => 'doc', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => $text]]]]]; + } + + private function editor(): User + { + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } +} diff --git a/tests/Feature/MedienFilterDialogTest.php b/tests/Feature/MedienFilterDialogTest.php index e8345e8..feb0e15 100644 --- a/tests/Feature/MedienFilterDialogTest.php +++ b/tests/Feature/MedienFilterDialogTest.php @@ -39,7 +39,7 @@ public function test_the_stock_is_reachable_with_a_closed_dialog_and_the_start_v ->test(ListContentElements::class) ->assertSee('Filter') ->assertSeeHtml('wire:click="openFilter"') - ->assertSee('Übungsabschnitte ausgeblendet') + ->assertSee('Übungsabschnitte und Dokumentkapitel ausgeblendet') ->assertDontSee('Die Auswahl wirkt erst mit „Anwenden“') ->assertSee('Film unbenutzt') ->assertDontSee('Abschnitt der Übung'); @@ -130,7 +130,7 @@ public function test_pills_name_short_selections_and_count_long_ones(): void $page->call('openFilter')->set('filterDraft.arten', ['k'.$merkblatt, 'k'.$trailer, 'ohne', 'k'.$this->kind('traineranleitung'), 'k'.$this->kind('uebungsabschnitt')])->call('applyFilter') ->assertSee('Materialart · 5 gewählt') - ->assertDontSee('Übungsabschnitte ausgeblendet'); + ->assertDontSee('Übungsabschnitte und Dokumentkapitel ausgeblendet'); } public function test_exercise_sections_come_back_with_a_check_and_the_hint_disappears(): void @@ -141,7 +141,7 @@ public function test_exercise_sections_come_back_with_a_check_and_the_hint_disap $page->call('openFilter', 'arten'); $draft = $page->instance()->filterDraft['arten']; $page->set('filterDraft.arten', [...$draft, 'k'.$this->kind('uebungsabschnitt')])->call('applyFilter') - ->assertDontSee('Übungsabschnitte ausgeblendet') + ->assertDontSee('Übungsabschnitte und Dokumentkapitel ausgeblendet') ->assertSee('Abschnitt der Übung'); $this->assertContains('Abschnitt der Übung', $this->titles($page)); } diff --git a/tests/Feature/RueckfallschutzTest.php b/tests/Feature/RueckfallschutzTest.php index 8bf3612..7fe2d10 100644 --- a/tests/Feature/RueckfallschutzTest.php +++ b/tests/Feature/RueckfallschutzTest.php @@ -64,7 +64,8 @@ protected function setUp(): void public function test_the_kind_values_are_the_ones_this_program_state_knows(): void { - $this->assertSame(['kombination', 'uebung', 'kurs', 'exercise'], CompositionKind::values()); + // Seit ADR-51 kennt dieser Stand auch das Dokument (`document`); der vorherige Stand blendet es über den Bereichsfilter aus. + $this->assertSame(['kombination', 'uebung', 'kurs', 'exercise', 'document'], CompositionKind::values()); $this->assertNotContains(self::FOREIGN, CompositionKind::values()); } diff --git a/tests/Feature/TextEditorWerkzeugeTest.php b/tests/Feature/TextEditorWerkzeugeTest.php new file mode 100644 index 0000000..b96930f --- /dev/null +++ b/tests/Feature/TextEditorWerkzeugeTest.php @@ -0,0 +1,147 @@ +create('Stopp sagen', CompositionKind::Exercise); + $cell = fn (string $type, string $text, array $attrs = []): array => ['type' => $type, 'attrs' => $attrs + ['colspan' => 1, 'rowspan' => 1, 'colwidth' => null], 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => $text]]]]]; + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->set('rich.partBody', ['type' => 'doc', 'content' => [ + ['type' => 'table', 'content' => [ + ['type' => 'tableRow', 'content' => [$cell('tableHeader', 'Zeit'), $cell('tableHeader', 'Inhalt')]], + ['type' => 'tableRow', 'content' => [$cell('tableCell', '10 Min.'), $cell('tableCell', 'Begrüßung')]], + ]], + ]]); + + $stored = '

Zeit

Inhalt

10 Min.

Begrüßung

'; + $this->assertSame($stored, $component->get('partBody')); + + // Zurück in den Editor und wieder heraus: kein Verlust, keine Scheinänderung. + $component->set('partBody', $stored)->assertOk(); + $this->assertSame('table', $component->get('rich.partBody.content.0.type')); + $this->assertSame('Begrüßung', $component->get('rich.partBody.content.0.content.1.content.1.content.0.content.0.text')); + $this->assertSame($stored, FormattedText::canonical($component->get('partBody'))); + } + + public function test_an_image_stays_a_reference_to_its_version_and_the_editor_gets_a_staff_address(): void + { + $image = $this->image('Stellung'); + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + $stored = '

Davor

Stellung

Danach

'; + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->set('partBody', $stored) + ->assertOk(); + + $node = $component->get('rich.partBody.content.1'); + $this->assertSame('image', $node['type']); + $this->assertSame((string) $image->id, (string) $node['attrs']['id']); + $this->assertSame(route('content.file', ['version' => $image->id], false), $node['attrs']['src']); + + // Der Editor gibt die Adresse mit zurück; gespeichert wird sie nie. + $component->set('rich.partBody', ['type' => 'doc', 'content' => [$node]]); + $this->assertSame('Stellung', $component->get('partBody')); + } + + public function test_the_image_tool_exists_only_in_text_editors_with_the_picker(): void + { + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]); + $page = $component->instance(); + + $this->assertContains('bild', collect($page->richKomponente('partBody')->getToolbarButtons())->flatten()->all()); + $this->assertContains('bild', collect($page->richKomponente('newTextBody')->getToolbarButtons())->flatten()->all()); + $this->assertNotContains('bild', collect($page->richKomponente('summary')->getToolbarButtons())->flatten()->all(), 'Kurzangaben nehmen keine Bilder auf.'); + + foreach (['partBody', 'summary', 'learningGoal'] as $field) { + $this->assertContains('table', collect($page->richKomponente($field)->getToolbarButtons())->flatten()->all(), $field.' hat dieselben Tabellenwerkzeuge.'); + } + } + + public function test_the_picker_offers_released_images_and_inserts_the_chosen_version_at_the_cursor(): void + { + $image = $this->image('Stellung'); + $draft = app(ContentService::class)->draftElementVersion(app(ContentService::class)->createElement('bild', 'bild', 'Entwurfsbild'), null, ['file' => 'inhalte/entwurf.jpg']); + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->call('openTextImagePicker', 'partBody', ['type' => 'text', 'anchor' => 1, 'head' => 1]) + ->assertSet('pickerOpen', true) + ->assertSet('pickerPurpose', 'textbild'); + + $this->assertSame('Bild einfügen', $component->instance()->pickerConfirmLabel()); + $this->assertSame(['bild' => 'Bilder'], $component->instance()->pickerKinds()); + + $component->call('markPicker', 'element:'.$image->id, true)->call('confirmPicker'); + $component->assertSet('pickerOpen', false)->assertDispatched('run-rich-editor-commands'); + + // Eine noch nicht freigegebene Fassung lässt sich nicht in einen Text einfügen. + $component->call('openTextImagePicker', 'partBody', [])->call('markPicker', 'element:'.$draft->id, true)->call('confirmPicker'); + $this->assertStringContainsString('noch nicht freigegeben', (string) $component->get('deskFeedback')); + } + + public function test_a_text_with_an_unreleased_image_cannot_be_frozen(): void + { + $content = app(ContentService::class); + $draftImage = $content->draftElementVersion($content->createElement('bild', 'bild', 'Entwurfsbild'), null, ['file' => 'inhalte/entwurf.jpg']); + $text = $content->draftElementVersion($content->createElement('text', 'text', 'Kapitel'), '

Text

'); + + $this->assertStringContainsString('noch nicht freigegeben', (string) $content->elementReleaseProblem($text)); + + $released = $content->releaseElementVersion($draftImage); + $this->assertNull($content->elementReleaseProblem($text->refresh())); + $this->assertSame($released->id, $draftImage->id); + + $content->block($released, 'Rechte'); + $this->assertStringContainsString('deaktiviert', (string) $content->imageProblem($text->body)); + } + + private function image(string $title) + { + $content = app(ContentService::class); + + return $content->publishElementVersion($content->createElement('bild', 'bild', $title), null, ['file' => 'inhalte/'.str($title)->slug().'.jpg']); + } + + private function editor(): User + { + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } +} diff --git a/tests/Feature/UebungFormatierungTest.php b/tests/Feature/UebungFormatierungTest.php new file mode 100644 index 0000000..c6ffc08 --- /dev/null +++ b/tests/Feature/UebungFormatierungTest.php @@ -0,0 +1,117 @@ +picture('Aufstellung'); + $table = '

Zeit

Hinweis

5 Min.

Abstand prüfen

'; + $note = '

Trainerhinweis

Vor dem Start klären.

  • Raum

'.$table.'Aufstellung'; + $setup = $this->exerciseWithNote($note); + + // Öffnen und erneut Speichern im selben Editor ändert nichts am Text. + $editor = Livewire::actingAs($this->editor(), 'staff')->test(EditPractice::class, ['record' => $setup['composition']->getKey()]); + $index = collect($editor->get('members'))->search(fn (array $member): bool => ($member['title'] ?? '') === 'Trainerhinweis Stopp'); + $editor->call('selectPart', $index)->set('detailTab', 'quelle'); + $this->assertSame('bild', collect($editor->instance()->richKomponente('partBody')->getToolbarButtons())->flatten()->first(fn ($tool) => $tool === 'bild'), 'Dieselben Werkzeuge wie im Kapitel, auch das Bild.'); + $this->assertSame(FormattedText::canonical($note), FormattedText::canonical($editor->get('partBody'))); + $this->assertSame('table', $editor->get('rich.partBody.content.3.type')); + $this->assertSame('image', $editor->get('rich.partBody.content.4.type')); + + $before = ContentElementVersion::query()->count(); + $editor->call('saveSourceText'); + $this->assertSame($before, ContentElementVersion::query()->count(), 'Unverändert gespeichert entsteht keine neue Fassung.'); + + // Eine Änderung mit den Werkzeugen des Editors: neue Zeile in der Tabelle bleibt neben Liste, Überschrift und Bild erhalten. + $changed = str_replace('', '

10 Min.

Neu ergänzt

', $table); + $editor->set('partBody', '

Trainerhinweis

Vor dem Start klären.

  • Raum

'.$changed.'Aufstellung')->call('saveSourceText'); + $saved = ContentElementVersion::query()->latest('id')->first(); + $this->assertStringContainsString('Neu ergänzt', (string) $saved->body); + $this->assertStringContainsString('
  • Raum

', (string) $saved->body); + $this->assertStringContainsString('Aufstellung', (string) $saved->body); + $this->assertSame(FormattedText::canonical($saved->body), $saved->body, 'Gespeichert ist die kanonische Form.'); + } + + public function test_the_exercise_page_and_pdf_show_table_list_heading_and_image_of_the_trainer_note(): void + { + $image = $this->picture('Aufstellung'); + $table = '

Zeit

Hinweis

5 Min.

Abstand prüfen

'; + $setup = $this->exerciseWithNote('

Trainerhinweis

Vor dem Start klären.

  • Raum

'.$table.'Aufstellung'); + $member = $setup['member']; + + $page = $this->actingAs($member)->get(route('member.exercise', ['article' => $setup['article'], 'release' => $setup['release'], 'path' => '1']))->assertOk(); + $page->assertSee('

Trainerhinweis

', false)->assertSee('
  • Raum

  • ', false)->assertSee('', false)->assertSee('Abstand prüfen', false) + ->assertSee('alt="Aufstellung"', false); + + $url = SignedLink::temporary('member.exercise.pdf', now()->addMinutes(10), ['article' => $setup['article']->id, 'release' => $setup['release']->id, 'path' => '1', 'variante' => null, 'reader' => $member->id]); + $response = $this->actingAs($member)->get($url)->assertOk(); + $pdf = $this->pdfText($response->getContent()); + + $this->assertStringContainsString('Trainerhinweis', $pdf); + $this->assertStringContainsString('Vor dem Start klären.', $pdf); + $this->assertStringContainsString('Raum', $pdf); + $this->assertStringContainsString('Zeit', $pdf); + $this->assertStringContainsString('Abstand', $pdf); + $this->assertStringContainsString('prüfen', $pdf); + $this->assertStringContainsString('/Subtype /Image', $response->getContent()); + } + + /** + * Eine Übung mit einem Trainerhinweis, eingebunden in ein verkauftes Modul. + * + * @return array + */ + private function exerciseWithNote(string $note): array + { + $content = ContentService::class; + $composition = $this->exerciseComposition('Stopp sagen'); + $text = $this->section('Trainerhinweis Stopp', $note); + ExerciseSections::class; + app(ExerciseSections::class)->mark($text->element, $composition); + $version = app($content)->publishComposition($composition, [['role' => 'Trainerhinweis', 'target' => $text]], null, null, ['learning_goal' => 'Stopp sagen']); + $module = $this->moduleWith('Modul Stopp', $version); + [$article, $release] = $this->publishFor('stopp-modul', $module); + + return ['composition' => $composition, 'article' => $article, 'release' => $release, 'member' => $this->memberWith($this->fullRights(), [$article])]; + } + + private function editor(): User + { + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } +} diff --git a/tests/Support/BuildsDocuments.php b/tests/Support/BuildsDocuments.php new file mode 100644 index 0000000..7f0e409 --- /dev/null +++ b/tests/Support/BuildsDocuments.php @@ -0,0 +1,148 @@ +createComposition($title, CompositionKind::Document); + $composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'dokument')->value('id'); + $composition->save(); + + return $composition; + } + + /** Ein Kapitel als bereitgestellte Textfassung im Medienbestand. */ + protected function chapter(Composition $document, string $title, string $body): ContentElementVersion + { + $version = $this->section($title, $body); + app(DocumentChapters::class)->mark($version->element, $document); + + return $version; + } + + /** + * Ein Dokument aus Kapiteln (Titel => Text; ein Titel mit führendem „-“ ist ein Unterkapitel). + * + * @param array $chapters + */ + protected function document(array $chapters, string $title = 'Trainerhandbuch', ?Composition $composition = null): CompositionVersion + { + $composition ??= $this->documentComposition($title); + $members = []; + + foreach ($chapters as $chapterTitle => $body) { + $sub = str_starts_with((string) $chapterTitle, '-'); + $name = ltrim((string) $chapterTitle, '-'); + $members[] = ['role' => $sub ? 'Unterkapitel' : 'Kapitel', 'target' => $this->chapter($composition, $name, $body)]; + } + + return app(ContentService::class)->publishComposition($composition, $members); + } + + /** Ein Bild im Medienbestand mit echter Datei im abgeleiteten Bestand. */ + protected function picture(string $title, int $width = 640, int $height = 360): ContentElementVersion + { + $content = app(ContentService::class); + $file = 'inhalte/'.str($title)->slug().'.png'; + $image = imagecreatetruecolor($width, $height); + imagefill($image, 0, 0, (int) imagecolorallocate($image, 40, 120, 90)); + ob_start(); + imagepng($image); + Storage::disk('media_derived')->put($file, (string) ob_get_clean()); + + return $content->publishElementVersion($content->createElement('bild', 'bild', $title), null, ['file' => $file]); + } + + protected function publishFor(string $code, CompositionVersion $root, ?LicenseArticle $article = null): array + { + $articles = app(ArticleService::class); + $article ??= $articles->create($code); + $release = $articles->publishRelease($article, $root, 'Stand '.$code.'.'); + + return [$article, $release]; + } + + protected function fullRights(): RightsProfileVersion + { + return $this->rights(['film' => ['streamen', 'laden'], 'text' => ['ansehen', 'laden'], 'document' => ['ansehen', 'laden'], 'bild' => ['ansehen', 'laden']]); + } + + /** + * @param array> $capabilities + */ + protected function rights(array $capabilities): RightsProfileVersion + { + return app(OfferService::class)->createRightsProfile('Profil '.md5(json_encode($capabilities)), 'ehrenamtlich', $capabilities); + } + + /** + * @param list $articles + */ + protected function memberWith(RightsProfileVersion $rights, array $articles): User + { + $offers = app(OfferService::class); + $offer = $offers->create('Angebot '.uniqid()); + $offers->activate($offer, array_map(fn (LicenseArticle $article): array => ['target' => $article->fresh(), 'rights' => $rights], $articles), ['grant_kind' => 'auf_abruf']); + $user = User::factory()->create(); + app(GrantIssuer::class)->claim($user, $offer); + + return $user; + } + + protected function documentPage(LicenseArticle $article, ArticleRelease $release, string $path = '1'): string + { + return route('member.document', ['article' => $article, 'release' => $release, 'path' => $path]); + } + + /** Text der Seiten aus dem unkomprimierten Inhalt; Windows-1252 wird nach UTF-8 gewandelt. */ + protected function pdfText(string $pdf): string + { + return implode("\n", $this->pdfPages($pdf)); + } + + /** + * Text je Seite. Die Seiteninhalte stehen in der Reihenfolge der Seiten im Dokument. + * + * @return list + */ + protected function pdfPages(string $pdf): array + { + preg_match_all('/\/Type \/Page \/Parent 2 0 R.*?\/Contents (\d+) 0 R/s', $pdf, $contents); + $pages = []; + + foreach ($contents[1] as $object) { + preg_match('/\n'.$object.' 0 obj\n<< \/Length \d+ >>\nstream\n(.*?)endstream/s', $pdf, $stream); + preg_match_all('/Td \((.*)\) Tj ET$/m', $stream[1] ?? '', $matches); + $pages[] = implode("\n", array_map( + fn (string $line): string => mb_convert_encoding(str_replace(['\\(', '\\)', '\\\\'], ['(', ')', '\\'], $line), 'UTF-8', 'Windows-1252'), + $matches[1], + )); + } + + return $pages; + } +} diff --git a/tests/Unit/FormattedTextTest.php b/tests/Unit/FormattedTextTest.php index 5b24619..b5a253e 100644 --- a/tests/Unit/FormattedTextTest.php +++ b/tests/Unit/FormattedTextTest.php @@ -101,4 +101,70 @@ public function test_blocks_carry_the_emphasis_for_the_pdf(): void $this->assertSame('bullets', $blocks[2]['type']); $this->assertTrue($blocks[2]['items'][0][1]['bold']); } + + public function test_a_table_keeps_its_structure_and_loses_widths_and_styling(): void + { + $html = FormattedText::canonical('

    Kopf

    a

    b x
    • eins
    '); + + $this->assertSame('

    Kopf

    a

    b x

    • eins

    ', $html); + $this->assertSame($html, FormattedText::canonical($html), 'Die kanonische Form ist stabil.'); + $this->assertTrue(FormattedText::isHtml($html), 'Ein Text, der mit einer Tabelle beginnt, bleibt HTML und wird nicht als Klartext maskiert.'); + } + + public function test_a_table_reaches_the_pdf_as_rows_and_plain_text_as_lines(): void + { + $html = '

    Zeit

    Inhalt

    10 Min.

    Begrüßung

    '; + $blocks = FormattedText::blocks($html); + + $this->assertSame('table', $blocks[0]['type']); + $this->assertCount(2, $blocks[0]['rows']); + $this->assertTrue($blocks[0]['rows'][0][0]['header']); + $this->assertSame('Begrüßung', $blocks[0]['rows'][1][1]['blocks'][0]['runs'][0]['text']); + $this->assertSame("Zeit | Inhalt\n10 Min. | Begrüßung", FormattedText::plain($html)); + } + + public function test_an_image_is_a_reference_to_an_image_version_and_never_an_address(): void + { + $html = FormattedText::canonical('

    Davor

    Ein Bild

    Danach

    Eingebettet x im Absatz

    '); + + $this->assertSame('

    Davor

    Ein Bild

    Danach

    Eingebettet x im Absatz

    ', $html, 'Der Editor setzt ein Bild mitten in einen Absatz; es bleibt dort.'); + $this->assertSame([12, 9], FormattedText::imageIds($html)); + $this->assertSame([['type' => 'paragraph', 'text' => 'Eingebettet'], ['type' => 'image', 'id' => 9], ['type' => 'paragraph', 'text' => 'im Absatz']], array_map(fn (array $block): array => $block['type'] === 'image' ? ['type' => 'image', 'id' => $block['id']] : ['type' => $block['type'], 'text' => trim(implode('', array_column($block['runs'], 'text')))], array_slice(FormattedText::blocks($html), 3)), 'Im PDF teilt das Bild den Absatz.'); + $this->assertSame('

    Kopf

    • Punkt

    ', FormattedText::canonical('

    Kopf

    • Punkt

    '), 'In Überschrift und Liste entfällt ein Bild.'); + $this->assertSame($html, FormattedText::canonical($html)); + $this->assertSame('', FormattedText::canonical(''), 'Ein Text nur aus einem Bild ist nicht leer.'); + } + + public function test_an_image_in_a_table_cell_is_kept_because_the_editor_can_put_it_there(): void + { + $html = FormattedText::canonical('

    Stuhlkreis

    Aufstellung
    '); + + $this->assertSame('

    Stuhlkreis

    Aufstellung
    ', $html); + $this->assertSame([7], FormattedText::imageIds($html)); + $this->assertSame('image', FormattedText::blocks($html)[0]['rows'][0][0]['blocks'][1]['type']); + $this->assertSame($html, FormattedText::canonical($html)); + $this->assertSame('
    ', FormattedText::canonical('
    '), 'Eine Zelle nur mit Bild bleibt erhalten.'); + } + + public function test_images_appear_only_where_the_reader_resolves_them(): void + { + $html = '

    Davor

    Ein BildAnderes

    Danach

    '; + + $this->assertSame('

    Davor

    Danach

    ', FormattedText::html($html), 'Ohne Auflösung zeigt die Ausgabe kein Bild.'); + $shown = FormattedText::html($html, fn (int $id): ?array => $id === 12 ? ['src' => '/b/12?sig=1'] : ['note' => 'Dieses Bild ist derzeit nicht verfügbar.']); + + $this->assertStringContainsString('Ein Bild', $shown); + $this->assertStringNotContainsString('data-id', $shown); + $this->assertStringContainsString('

    Dieses Bild ist derzeit nicht verfügbar.

    ', $shown); + $this->assertSame('Davor'."\n\n".'Danach', FormattedText::plain($html), 'Im Klartext hat ein Bild keinen Platz.'); + } + + public function test_the_editor_gets_an_address_for_every_image_and_loses_it_again_on_the_way_back(): void + { + $stored = FormattedText::canonical('

    Text

    Ein Bild'); + $forEditor = FormattedText::forEditor($stored, fn (int $id): string => "/redaktion/inhalt/{$id}/datei"); + + $this->assertStringContainsString('src="/redaktion/inhalt/12/datei"', $forEditor); + $this->assertSame($stored, FormattedText::canonicalHtml($forEditor)); + } } diff --git a/tests/Unit/PdfDocumentTest.php b/tests/Unit/PdfDocumentTest.php new file mode 100644 index 0000000..7e2e06b --- /dev/null +++ b/tests/Unit/PdfDocumentTest.php @@ -0,0 +1,103 @@ +addPage(); + $pdf->text(56, 780, 'Überschrift mit Umlauten äöü ß', 18, true); + $pdf->text(56, 760, 'Normal und kursiv', 10.5, false, true); + $pdf->text(56, 740, 'Fett kursiv', 10.5, true, true); + $pdf->line(56, 54, 539, 54, 0.4); + $pdf->textRight(539, 40, 'Seite 1', 8); + $pdf->addPage(); + $pdf->text(56, 780, 'Zweite Seite (Klammern) \\ Rest', 11); + + $this->assertSame('a2b11d725eecc67e7cbc07a98136a3a7', md5($pdf->output('Titel', 'Lizenzkopie X'))); + + $small = new PdfDocument; + $small->addPage(); + $small->text(10, 10, 'x'); + + $this->assertSame('2c520ed928e812821fa8fac19d236d88', md5($small->output('T'))); + } + + public function test_links_bookmarks_images_and_areas_form_a_readable_structure(): void + { + $image = PdfImage::fromBytes($this->png(300, 200)); + $this->assertNotNull($image); + + $pdf = new PdfDocument; + $pdf->addPage(); + $pdf->text(56, 780, 'Inhalt', 14, true); + $pdf->link(56, 770, 200, 14, 1, 790); + $pdf->fillRect(56, 700, 100, 20, 0.9); + $pdf->addPage(); + $pdf->bookmark('1 Kapitel', 1, 790, 1); + $pdf->bookmark('1.1 Unterkapitel (mit) Klammern', 1, 700, 2); + $pdf->bookmark('2 Kapitel', 1, 400, 1); + $pdf->image(56, 500, 200, 133, $image['jpeg'], $image['width'], $image['height']); + $pdf->image(300, 500, 200, 133, $image['jpeg'], $image['width'], $image['height']); + $out = $pdf->output('Probe'); + + $this->assertSame(1, substr_count($out, '/Subtype /Image'), 'Dasselbe Bild liegt nur einmal im Dokument.'); + $this->assertStringContainsString('/Annots [', $out); + $this->assertStringContainsString('/Dest [8 0 R /XYZ 0 790 null]', $out, 'Das Ziel ist die zweite Seite.'); + $this->assertStringContainsString('/Outlines', $out); + $this->assertStringContainsString('/PageMode /UseOutlines', $out); + $this->assertSame(4, substr_count($out, '/Title ('), 'Dokumenttitel und drei Lesezeichen.'); + $this->assertStringContainsString('1.1 Unterkapitel \\(mit\\) Klammern', $out); + $this->assertSame(1, preg_match('/\/Count 3 >>/', $out), 'Die Gliederung zählt alle Einträge.'); + + // Jede Objektnummer der Kreuzverweistabelle zeigt auf ein Objekt. + preg_match('/startxref\n(\d+)/', $out, $start); + $xref = substr($out, (int) $start[1]); + preg_match_all('/^(\d{10}) 00000 n $/m', $xref, $offsets); + + foreach ($offsets[1] as $number => $offset) { + $this->assertStringStartsWith(($number + 1).' 0 obj', substr($out, (int) $offset, 12), 'Objekt '.($number + 1)); + } + } + + public function test_images_are_reencoded_as_jpeg_scaled_and_flattened_on_white(): void + { + $large = PdfImage::fromBytes($this->png(3000, 1000)); + + $this->assertSame(PdfImage::MAX_EDGE, $large['width']); + $this->assertSame(467, $large['height']); + $this->assertSame("\xFF\xD8", substr($large['jpeg'], 0, 2)); + $this->assertNull(PdfImage::fromBytes('kein Bild')); + $this->assertNull(PdfImage::fromBytes('')); + } + + public function test_the_outline_numbers_chapters_and_subchapters_from_their_order(): void + { + $numbering = DocumentOutline::numbering(['Kapitel', 'Unterkapitel', 'Unterkapitel', 'Kapitel', 'Unterkapitel']); + + $this->assertSame(['1', '1.1', '1.2', '2', '2.1'], array_column($numbering, 'number')); + $this->assertSame(['kapitel-1', 'kapitel-1-1', 'kapitel-1-2', 'kapitel-2', 'kapitel-2-1'], array_column($numbering, 'anchor')); + $this->assertSame(['1', '2'], array_column(DocumentOutline::numbering(['Unterkapitel', 'Kapitel']), 'number'), 'Ein Unterkapitel ohne Kapitel davor zählt als Kapitel.'); + $this->assertSame(2, DocumentOutline::blockEnd(['Kapitel', 'Unterkapitel', 'Unterkapitel', 'Kapitel'], 0)); + $this->assertSame(1, DocumentOutline::blockEnd(['Kapitel', 'Unterkapitel', 'Unterkapitel', 'Kapitel'], 1)); + $this->assertSame(3, DocumentOutline::blockEnd(['Kapitel', 'Unterkapitel', 'Unterkapitel', 'Kapitel'], 3)); + } + + private function png(int $width, int $height): string + { + $image = imagecreatetruecolor($width, $height); + imagefill($image, 0, 0, (int) imagecolorallocate($image, 30, 90, 70)); + ob_start(); + imagepng($image); + + return (string) ob_get_clean(); + } +}