From 3e2fd872c28a40f1bf73a0bcb8188b896e16c6b3 Mon Sep 17 00:00:00 2001 From: Lars Date: Tue, 24 Nov 2026 12:23:18 +0100 Subject: [PATCH] =?UTF-8?q?F=C3=BChre=20Dokumente=20mit=20Kapiteln,=20Fass?= =?UTF-8?q?ung,=20Seite=20und=20PDF=20mit=20Inhaltsverzeichnis=20ein=20(AD?= =?UTF-8?q?R-51)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ein Dokument ist eine Komposition der Art document, ein Kapitel ein Text mit der automatischen Materialart Dokumentkapitel; die Ebene steht in der Rolle. Der Aufbaueditor bekommt den Kapitelarbeitsplatz (Übersicht, Ordnen als Block, offene Eingaben bleiben beim Wechsel erhalten, Speichern als Entwurf, Bereitstellen als Dokumentfassung). Module und Programme binden eine Fassung über den gemeinsamen Picker ein. Mitglieder lesen sie mit anklickbarem Inhaltsverzeichnis und laden ein PDF mit Inhaltsverzeichnis, Seitenzahlen, Tabellen und Bildern. Ein älterer Stand liefert die gebundene Fassung weiter. Co-Authored-By: Claude Sonnet 5.5 --- app/Domain/Catalog/CompositionKind.php | 9 +- app/Domain/Catalog/ContentService.php | 36 ++ app/Domain/Catalog/DocumentChapters.php | 28 + app/Domain/Catalog/DocumentGuide.php | 91 ++++ app/Domain/Catalog/DocumentOutline.php | 83 +++ app/Domain/Catalog/DocumentPdf.php | 196 +++++++ app/Domain/Catalog/DocumentReader.php | 82 +++ app/Domain/Catalog/EditorialContentKind.php | 8 +- app/Domain/Catalog/EditorialVocabulary.php | 2 + app/Domain/Catalog/EmbeddedImages.php | 39 +- app/Domain/Catalog/ExerciseGuide.php | 4 +- app/Domain/Catalog/FormattedText.php | 80 ++- app/Domain/Catalog/PdfFlow.php | 59 +- .../Cms/Catalog/PublicMaterialReader.php | 2 +- .../Compositions/Pages/EditComposition.php | 83 ++- .../Pages/ListCompositionKind.php | 4 +- .../Resources/Documents/DocumentResource.php | 38 ++ .../Documents/Pages/EditDocument.php | 11 + .../Documents/Pages/ListDocuments.php | 17 + app/Filament/Support/EditorialCatalog.php | 13 +- app/Filament/Support/ListsCompositions.php | 5 + .../Support/ManagesDocumentChapters.php | 506 ++++++++++++++++++ .../Support/ManagesEditorialSurface.php | 2 +- .../Controllers/DocumentPreviewController.php | 86 +++ .../Controllers/Member/DocumentController.php | 97 ++++ app/Http/LibraryCatalog.php | 21 +- .../2026_11_28_100000_add_documents.php | 38 ++ resources/css/components/lf-member.css | 99 ++++ resources/views/document/preview.blade.php | 24 + .../views/filament/editorial/editor.blade.php | 23 +- .../verwaltung/aufbau-angaben.blade.php | 9 + .../filament/verwaltung/dokument.blade.php | 112 ++++ resources/views/member/document.blade.php | 35 ++ .../views/member/partials/document.blade.php | 37 ++ .../views/member/partials/structure.blade.php | 2 +- routes/web.php | 17 + tests/Feature/DokumentAusgabeTest.php | 264 +++++++++ tests/Feature/DokumentEditorTest.php | 241 +++++++++ tests/Feature/RueckfallschutzTest.php | 3 +- tests/Feature/UebungFormatierungTest.php | 117 ++++ tests/Support/BuildsDocuments.php | 148 +++++ tests/Unit/FormattedTextTest.php | 17 +- tests/Unit/PdfDocumentTest.php | 103 ++++ 43 files changed, 2827 insertions(+), 64 deletions(-) create mode 100644 app/Domain/Catalog/DocumentChapters.php create mode 100644 app/Domain/Catalog/DocumentGuide.php create mode 100644 app/Domain/Catalog/DocumentOutline.php create mode 100644 app/Domain/Catalog/DocumentPdf.php create mode 100644 app/Domain/Catalog/DocumentReader.php create mode 100644 app/Filament/Resources/Documents/DocumentResource.php create mode 100644 app/Filament/Resources/Documents/Pages/EditDocument.php create mode 100644 app/Filament/Resources/Documents/Pages/ListDocuments.php create mode 100644 app/Filament/Support/ManagesDocumentChapters.php create mode 100644 app/Http/Controllers/DocumentPreviewController.php create mode 100644 app/Http/Controllers/Member/DocumentController.php create mode 100644 database/migrations/2026_11_28_100000_add_documents.php create mode 100644 resources/views/document/preview.blade.php create mode 100644 resources/views/filament/verwaltung/dokument.blade.php create mode 100644 resources/views/member/document.blade.php create mode 100644 resources/views/member/partials/document.blade.php create mode 100644 tests/Feature/DokumentAusgabeTest.php create mode 100644 tests/Feature/DokumentEditorTest.php create mode 100644 tests/Feature/UebungFormatierungTest.php create mode 100644 tests/Support/BuildsDocuments.php create mode 100644 tests/Unit/PdfDocumentTest.php 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/ContentService.php b/app/Domain/Catalog/ContentService.php index f7bfd77..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'); 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..dbd0e99 --- /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); + $images = app(EmbeddedImages::class)->forView($user, $article, $release); + $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, $images)) : 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 index 9b468bb..110ba2c 100644 --- a/app/Domain/Catalog/EmbeddedImages.php +++ b/app/Domain/Catalog/EmbeddedImages.php @@ -91,11 +91,7 @@ public function forPdf(User $user, LicenseArticle $article, ArticleRelease $rele return ['note' => 'Bild nicht verfügbar', 'grant' => null, 'version' => null]; } - $file = $decision['version']->metadata['file'] ?? null; - $disk = Storage::disk('media_derived'); - $prepared = is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file) - ? PdfImage::fromBytes((string) $disk->get($file)) - : null; + $prepared = self::prepared($decision['version']); if ($prepared === null) { return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null]; @@ -105,6 +101,39 @@ public function forPdf(User $user, LicenseArticle $article, ArticleRelease $rele }); } + /** + * 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]; + }); + } + + /** + * 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 = $version->metadata['file'] ?? null; + $disk = Storage::disk('media_derived'); + + return is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file) + ? PdfImage::fromBytes((string) $disk->get($file)) + : null; + } + /** * @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null */ diff --git a/app/Domain/Catalog/ExerciseGuide.php b/app/Domain/Catalog/ExerciseGuide.php index 81408be..7078ea9 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; } diff --git a/app/Domain/Catalog/FormattedText.php b/app/Domain/Catalog/FormattedText.php index 708d6ce..11fb890 100644 --- a/app/Domain/Catalog/FormattedText.php +++ b/app/Domain/Catalog/FormattedText.php @@ -335,14 +335,43 @@ private static function extractBlocks(Node $parent): array continue; } - $blocks[] = [ - 'type' => match ($name) { - 'h3' => 'heading', - 'blockquote' => 'quote', - default => 'paragraph', - }, - 'runs' => self::runs($node), - ]; + $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; @@ -380,9 +409,10 @@ private static function normalize(string $html): string $document = HTMLDocument::createFromString(''.$html.'', LIBXML_NOERROR); $body = $document->body; - // Ein Bild steht zwischen den Absätzen (der Editor setzt es als Block) und braucht seine Bildfassung. + // 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 ($image->parentNode !== $body || (int) $image->getAttribute('data-id') < 1) { + if (! self::mayHoldImage($image->parentNode, $body) || (int) $image->getAttribute('data-id') < 1) { $image->remove(); } } @@ -459,7 +489,7 @@ private static function block(Node $node): string $inner = '

'.$inner.'

'; } - return self::hasText($inner) ? '<'.$name.'>'.$inner.'' : ''; + return self::hasContent($inner) ? '<'.$name.'>'.$inner.'' : ''; } /** @@ -490,7 +520,7 @@ private static function table(Node $table): string } $inner = self::inner($cell); - $cells .= '<'.$name.$attributes.'>'.($inner === '' ? '

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

'.$inner.'

')).''; + $cells .= '<'.$name.$attributes.'>'.($inner === '' ? '

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

'.$inner.'

')).''; } if ($cells !== '') { @@ -498,7 +528,7 @@ private static function table(Node $table): string } } - return $rows !== '' && self::hasText($rows) ? ''.$rows.'
' : ''; + return $rows !== '' && (self::hasText($rows) || str_contains($rows, ''.$rows.'' : ''; } private static function inner(Node $node): string @@ -506,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; @@ -518,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, 'room($height + 8); - $this->pdf->image($x, $this->y - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']); - $this->y -= $height + 8; + $this->room($height + 16); + $this->pdf->image($x, $this->y + 4 - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']); + $this->y -= $height + 16; } /** @@ -330,7 +330,7 @@ private function table(array $rows, float $x): void $this->depth++; $cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']); $this->depth--; - $cell['height'] = max(1, count($cell['lines'])) * $lineHeight + 2 * $pad; + $cell['height'] = max($lineHeight, array_sum(array_column($cell['lines'], 'height'))) + 2 * $pad; $prepared[] = $cell; } @@ -363,7 +363,7 @@ private function table(array $rows, float $x): void return; } - $drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad, $lineHeight): void { + $drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad): void { $y = $this->y; for ($r = $from; $r <= $to; $r++) { @@ -379,6 +379,13 @@ private function table(array $rows, float $x): void $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']); } @@ -390,7 +397,7 @@ private function table(array $rows, float $x): void $cursor += PdfDocument::exactWidth($text, $size, $isBold || $cell['header']); } - $textY -= $lineHeight; + $textY -= $line['height']; } } @@ -528,10 +535,21 @@ private function columnWidths(array $cells, int $columns, float $available, floa 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); - $wishes = array_sum($want) - array_sum($min); + $open = array_keys($min); + usort($open, fn (int $a, int $b): int => ($want[$a] - $min[$a]) <=> ($want[$b] - $min[$b])); - return array_map(fn (float $m, float $w): float => $m + $room * (($w - $m) / max(1.0, $wishes)), $min, $want); + foreach ($open as $position => $c) { + $share = $room / (count($open) - $position); + $give = min($want[$c] - $min[$c], $share); + $widths[$c] += $give; + $room -= $give; + } + + return $widths; } /** @@ -553,32 +571,49 @@ private function cellText(array $blocks): string } /** - * Zeilen einer Tabellenzelle: Absätze, Aufzählungen und Zwischenüberschriften; ein Bild in der Zelle entfällt. + * 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, indent: float, marker: ?string}> + * @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]; + $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]; + $out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight]; } } 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/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index 6268d48..467ba9e 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.', @@ -705,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 @@ -722,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.'; @@ -807,6 +835,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(); @@ -852,6 +881,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); @@ -1184,6 +1219,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); @@ -1206,7 +1246,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, ]; @@ -1221,6 +1263,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; @@ -1754,6 +1802,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.'; @@ -1813,7 +1865,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; @@ -1969,6 +2023,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'] ?? ''); @@ -1989,6 +2044,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()); @@ -2014,6 +2070,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); } @@ -2023,6 +2086,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'] ?? '') : ''; } @@ -2340,6 +2410,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'] ?? '')), @@ -2442,6 +2514,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/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 @@ +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/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 af94bdd..9b11d77 100644 --- a/app/Filament/Support/ManagesEditorialSurface.php +++ b/app/Filament/Support/ManagesEditorialSurface.php @@ -755,7 +755,7 @@ public function pickerKinds(): array } 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']; 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..108db8e --- /dev/null +++ b/app/Http/Controllers/Member/DocumentController.php @@ -0,0 +1,97 @@ +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, + 'pdfUrl' => app(DocumentGuide::class)->pdfAllowed($guide) ? SignedLink::temporary('member.document.pdf', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'path' => $path, + 'reader' => $request->user()->id, + ]) : null, + ]); + } + + public function pdf(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): Response + { + abort_unless((int) $request->query('reader') === $request->user()->id, 403); + + [$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); + $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/LibraryCatalog.php b/app/Http/LibraryCatalog.php index 2e40ed6..ed380b9 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 @@ -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/resources/css/components/lf-member.css b/resources/css/components/lf-member.css index b5884fc..745ec51 100644 --- a/resources/css/components/lf-member.css +++ b/resources/css/components/lf-member.css @@ -1830,3 +1830,102 @@ @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-chapter .mb-prose h4 { + margin: var(--space-4) 0 var(--space-2); + font-size: var(--text-body); +} + +.mb-doc-up { + margin: var(--space-3) 0 0; + font-size: 0.9em; +} 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..8a5f951 100644 --- a/resources/views/filament/editorial/editor.blade.php +++ b/resources/views/filament/editorial/editor.blade.php @@ -13,7 +13,8 @@ } $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.']]; + $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) { $mehr[] = $this->isInLibrary() ? ['label' => 'Aus Mitgliederbibliothek ausblenden', 'wire' => "mountAction('displayRevoke')", 'hinweis' => 'Der Inhalt bleibt gespeichert.'] @@ -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/routes/web.php b/routes/web.php index 68cb9dd..7fff82c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -6,8 +6,10 @@ 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; @@ -72,6 +74,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 +145,13 @@ ->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]+)*') + ->middleware('signed:relative') + ->name('document.pdf'); 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..cf6d5d0 --- /dev/null +++ b/tests/Feature/DokumentAusgabeTest.php @@ -0,0 +1,264 @@ +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.'/'.$image->id.'/ansehen[^"]*signature=#', $html); + } + + public function test_the_signed_image_link_delivers_the_bound_image_only_for_a_member_with_rights(): void + { + [$article, $release, $member, $image] = $this->sold(); + $html = $this->actingAs($member)->get($this->documentPage($article, $release))->getContent(); + preg_match('#AufstellungactingAs($member)->get($src)->assertOk(); + + $other = $this->memberWith($this->fullRights(), [$this->publishFor('anderes', $this->document(['Anderes' => 'Text']))[0]]); + $this->actingAs($other)->get($src)->assertForbidden(); + } + + 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_without_the_right_to_see_images_the_text_stays_readable_and_the_pdf_notes_the_missing_image(): void + { + [$article, $release, , $image] = $this->sold(); + $member = $this->memberWith($this->rights(['text' => ['ansehen', 'laden']]), [$article]); + + $this->actingAs($member)->get($this->documentPage($article, $release))->assertOk() + ->assertSee('Begrüßung')->assertSee('Dieses Bild ist derzeit nicht verfügbar.')->assertDontSee('/ansehen?', false); + + $response = $this->actingAs($member)->get($this->pdfUrl($article, $release, $member))->assertOk(); + $this->assertStringNotContainsString('/Subtype /Image', $response->getContent()); + $this->assertStringContainsString('[Bild nicht verfügbar]', $this->pdfText($response->getContent())); + $this->assertNotContains($image->id, MediaDelivery::query()->pluck('content_element_version_id')->all()); + } + + 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 SignedLink::temporary('member.document.pdf', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'path' => $path, + 'reader' => $member->id, + ]); + } +} diff --git a/tests/Feature/DokumentEditorTest.php b/tests/Feature/DokumentEditorTest.php new file mode 100644 index 0000000..7e90c19 --- /dev/null +++ b/tests/Feature/DokumentEditorTest.php @@ -0,0 +1,241 @@ +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_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/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/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 ebdd5a3..b5a253e 100644 --- a/tests/Unit/FormattedTextTest.php +++ b/tests/Unit/FormattedTextTest.php @@ -127,12 +127,25 @@ public function test_an_image_is_a_reference_to_an_image_version_and_never_an_ad { $html = FormattedText::canonical('

    Davor

    Ein Bild

    Danach

    Eingebettet x im Absatz

    '); - $this->assertSame('

    Davor

    Ein Bild

    Danach

    Eingebettet im Absatz

    ', $html); - $this->assertSame([12], FormattedText::imageIds($html)); + $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

    '; 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(); + } +}