Dokumente #10

Merged
Lars merged 4 commits from develop into main 2026-11-24 13:50:29 +01:00
43 changed files with 2827 additions and 64 deletions
Showing only changes of commit 3e2fd872c2 - Show all commits

No files matched your search

+8 -1
View File
@@ -9,6 +9,8 @@ enum CompositionKind: string
case Kurs = 'kurs';
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
case Exercise = 'exercise';
/** Ein zusammenhängendes Dokument aus Kapiteln, zum Beispiel ein Trainerhandbuch (ADR-51). */
case Document = 'document';
/**
* @return list<string>
@@ -25,6 +27,7 @@ public function label(): string
self::Uebung => 'Modul',
self::Kurs => 'Kurs',
self::Exercise => 'Übung',
self::Document => 'Dokument',
};
}
@@ -35,6 +38,7 @@ public function plural(): string
self::Uebung => 'Module',
self::Kurs => 'Kurse',
self::Exercise => 'Übungen',
self::Document => 'Dokumente',
};
}
@@ -45,6 +49,7 @@ public function createLabel(): string
self::Uebung => 'Modul anlegen',
self::Kurs => 'Kurs anlegen',
self::Exercise => 'Übung anlegen',
self::Document => 'Dokument anlegen',
};
}
@@ -55,6 +60,7 @@ public function explanation(): string
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
self::Document => 'Ein zusammenhängendes Dokument, zum Beispiel ein Trainerhandbuch, aus Kapiteln und Unterkapiteln. Eine Fassung schreibt Reihenfolge und Texte fest; sie wird in Module und Programme aufgenommen und erscheint für Mitglieder mit Inhaltsverzeichnis und als PDF.',
};
}
@@ -65,6 +71,7 @@ public function deskLabel(): string
self::Uebung => 'Modul',
self::Kurs => 'Programm',
self::Exercise => 'Übung',
self::Document => 'Dokument',
};
}
@@ -74,7 +81,7 @@ public function deskExplanation(): string
self::Kombination => $this->explanation(),
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
self::Exercise => $this->explanation(),
self::Exercise, self::Document => $this->explanation(),
};
}
+36
View File
@@ -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');
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Domain\Catalog;
/**
* Kapitel eines Dokuments: Textabschnitte im gemeinsamen Medienbestand mit der automatischen Materialart „Dokumentkapitel“
* und dem Verweis auf ihr Dokument (`origin_composition_id`), wie die Übungsabschnitte ({@see ExerciseSections}).
*/
final class DocumentChapters
{
public function kindId(): ?int
{
$id = EditorialContentKind::query()->where('slug', EditorialContentKind::DOCUMENT_CHAPTER_SLUG)->value('id');
return $id === null ? null : (int) $id;
}
public function mark(ContentElement $element, Composition $document): void
{
$element->origin_composition_id = $document->getKey();
if ($element->editorial_content_kind_id === null) {
$element->editorial_content_kind_id = $this->kindId();
}
$element->save();
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Entitlement\DecideAccess;
use App\Http\LibraryCatalog;
use App\Models\User;
/**
* Das Dokument, wie ein Stand es festschreibt: die im Stand gebundene Dokumentfassung mit ihren Kapiteln und je Kapitel die
* Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und PDF lesen dieses Ergebnis; beide zeigen dieselbe
* Kapitelreihenfolge und dieselben gebundenen Textfassungen. Eine spätere Bearbeitung des Dokuments ändert einen älteren Stand
* nicht: Der Stand verweist auf die Fassung, die er festgeschrieben hat.
*/
class DocumentGuide
{
public function __construct(
private readonly DecideAccess $access,
private readonly DocumentReader $reader,
) {}
/**
* @return array<string, mixed>
*/
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $document): array
{
$document->loadMissing('composition');
$library = app(LibraryCatalog::class);
$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<string, mixed> $guide
*/
public function pdfAllowed(array $guide): bool
{
if ($guide['chapters'] === []) {
return false;
}
foreach ($guide['chapters'] as $chapter) {
if (! $chapter['allowed'] || ! $chapter['may_download']) {
return false;
}
}
return true;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Domain\Catalog;
/**
* Gliederung eines Dokuments (ADR-51). Ein Dokument ist eine flache Folge von Kapiteln; die Ebene steht in der Rolle des
* Mitglieds: „Kapitel“ (Ebene 1) oder „Unterkapitel“ (Ebene 2). Ein Unterkapitel gehört zum Kapitel davor. Die Nummern
* („3“, „3.2“) entstehen aus der Reihenfolge und werden nirgends gespeichert; Editor, Ansicht und PDF zählen gleich.
*/
final class DocumentOutline
{
public const CHAPTER = 'Kapitel';
public const SUBCHAPTER = 'Unterkapitel';
public static function level(?string $role): int
{
return trim((string) $role) === self::SUBCHAPTER ? 2 : 1;
}
public static function role(int $level): string
{
return $level >= 2 ? self::SUBCHAPTER : self::CHAPTER;
}
/**
* Ebene und Nummer je Eintrag. Ein Unterkapitel ohne Kapitel davor zählt als Kapitel.
*
* @param list<string> $roles
* @return list<array{level: int, number: string, anchor: string}>
*/
public static function numbering(array $roles): array
{
$chapter = 0;
$sub = 0;
$out = [];
foreach ($roles as $role) {
$level = self::level($role);
if ($level === 2 && $chapter === 0) {
$level = 1;
}
if ($level === 1) {
$chapter++;
$sub = 0;
$number = (string) $chapter;
} else {
$sub++;
$number = $chapter.'.'.$sub;
}
$out[] = ['level' => $level, 'number' => $number, 'anchor' => 'kapitel-'.str_replace('.', '-', $number)];
}
return $out;
}
/**
* Letzter Index des Blocks, den der Eintrag bei `$index` mit seinen Unterkapiteln bildet.
*
* @param list<string> $roles
*/
public static function blockEnd(array $roles, int $index): int
{
if (self::numbering($roles)[$index]['level'] === 2) {
return $index;
}
$end = $index;
for ($i = $index + 1; $i < count($roles); $i++) {
if (self::level($roles[$i]) !== 2) {
break;
}
$end = $i;
}
return $end;
}
}
+196
View File
@@ -0,0 +1,196 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Commerce\Receipt\PdfDocument;
use Closure;
use Transliterator;
/**
* Druckbare Ausgabe eines Dokuments (DIN A4) aus demselben Ergebnis wie die Ansicht ({@see DocumentGuide}): Titelseite mit
* anklickbarem Inhaltsverzeichnis samt Seitenzahlen, jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite,
* Lesezeichen für die Gliederung des PDF-Betrachters. Fußzeile mit Lizenznehmer, Lizenzkopie und „Seite n von m“ auf jeder
* Seite (K2), die Kennung in den Metadaten (K1). Die Datei wird bei jedem Abruf neu erzeugt und nie abgelegt.
*
* Seitenzahlen stehen erst nach dem Satz fest. Der Satz läuft deshalb so oft, bis Inhaltsverzeichnis, Kapitelanfänge und
* Seitenzahl sich nicht mehr ändern (in der Regel zweimal).
*/
class DocumentPdf
{
private const LEFT = 56.0;
private const RIGHT = 539.0;
private const TOP = 790.0;
private const BOTTOM = 72.0;
private PdfDocument $pdf;
private PdfFlow $flow;
private int $page = 0;
private string $footer = '';
private int $total = 0;
/** @var array<string, array{page: int, top: float}> */
private array $starts = [];
/**
* @param array<string, mixed> $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<string, mixed> $guide
* @param array<string, array{page: int, top: float}> $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<string, mixed> $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<string, mixed> $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';
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Domain\Catalog;
/**
* Liest die Kapitel eines Dokuments in ihrer Reihenfolge: aus einer Fassung (gebundene Textfassungen) oder aus dem
* gespeicherten Entwurf (jeweils verwiesene Fassung). Ansicht, PDF und Vorschau zählen dadurch dieselben Kapitel und
* Nummern ({@see DocumentOutline}).
*/
final class DocumentReader
{
/**
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
*/
public function fromVersion(CompositionVersion $document): array
{
$document->loadMissing('members.contentElementVersion.element');
$items = [];
foreach ($document->members as $member) {
if ($member->contentElementVersion !== null) {
$items[] = ['role' => (string) $member->role, 'version' => $member->contentElementVersion];
}
}
return $this->number($items);
}
/**
* Der gespeicherte Entwurf; ohne Entwurf die letzte bereitgestellte Fassung. Null, wenn beides fehlt.
*
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>|null
*/
public function forStaff(Composition $document): ?array
{
$draft = app(EditorialWorkingDraft::class)->read($document);
if ($draft === null) {
$ready = $document->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
return $ready instanceof CompositionVersion ? $this->fromVersion($ready) : null;
}
$items = [];
foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) {
if (! is_array($member) || preg_match('/^element:(\d+)$/', (string) ($member['target'] ?? ''), $match) !== 1) {
continue;
}
$version = ContentElementVersion::query()->with('element')->find($match[1]);
if ($version instanceof ContentElementVersion && $version->element !== null) {
$items[] = ['role' => (string) ($member['role'] ?? ''), 'version' => $version];
}
}
return $this->number($items);
}
public static function title(ContentElementVersion $version): string
{
$element = $version->element;
return $element === null ? 'Kapitel' : (filled($element->display_title) ? (string) $element->display_title : (string) $element->working_title);
}
/**
* @param list<array{role: string, version: ContentElementVersion}> $items
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
*/
private function number(array $items): array
{
$numbering = DocumentOutline::numbering(array_column($items, 'role'));
return array_map(fn (array $item, array $number): array => $number + [
'role' => DocumentOutline::role($number['level']),
'title' => self::title($item['version']),
'version' => $item['version'],
], $items, $numbering);
}
}
+6 -2
View File
@@ -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
@@ -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,
};
+34 -5
View File
@@ -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
*/
+2 -2
View File
@@ -45,7 +45,7 @@ public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $rel
*
* @return array{version: CompositionVersion, selection: list<string>|null}|null
*/
public function locate(ArticleRelease $release, string $path): ?array
public function locate(ArticleRelease $release, string $path, CompositionKind $kind = CompositionKind::Exercise): ?array
{
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
return null;
@@ -71,7 +71,7 @@ public function locate(ArticleRelease $release, string $path): ?array
$version?->loadMissing('composition');
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
if ($version === null || $version->composition === null || $version->composition->kind !== $kind) {
return null;
}
+66 -14
View File
@@ -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('<body>'.$html.'</body>', 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 = '<p>'.$inner.'</p>';
}
return self::hasText($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
}
/**
@@ -490,7 +520,7 @@ private static function table(Node $table): string
}
$inner = self::inner($cell);
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h3)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h3|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
}
if ($cells !== '') {
@@ -498,7 +528,7 @@ private static function table(Node $table): string
}
}
return $rows !== '' && self::hasText($rows) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
}
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, '<img');
}
private static function hasText(string $html): bool
{
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
+47 -12
View File
@@ -279,9 +279,9 @@ private function image(array $block, float $x): void
$width = max(1.0, $found['width'] * $scale);
$height = max(1.0, $found['height'] * $scale);
$this->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<array<string, mixed>> $blocks
* @return list<array{segments: list<array{0: string, 1: bool, 2: bool}>, indent: float, marker: ?string}>
* @return list<array<string, mixed>>
*/
private function cellLines(array $blocks, float $width, float $size, bool $header): array
{
$out = [];
$lineHeight = $size + 3;
foreach ($blocks as $block) {
if (in_array($block['type'], ['bullets', 'numbered'], true)) {
foreach ($block['items'] as $index => $item) {
foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) {
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null];
$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];
}
}
@@ -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<int, array{id: int, title: string}>|null Element-ID => erstes öffentliches Programm */
private ?array $publicIndex = null;
@@ -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,
];
}
@@ -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;
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\Documents;
use App\Domain\Catalog\CompositionKind;
use App\Filament\Resources\Compositions\CompositionKindResource;
use App\Filament\Resources\Documents\Pages\EditDocument;
use App\Filament\Resources\Documents\Pages\ListDocuments;
/**
* Dokumente unter „Inhalte“: zusammenhängende Texte aus Kapiteln, der erste Fall ist das Trainerhandbuch (ADR-51).
* Wie Übungen sind es Kompositionen mit eigener Art; Fassung, Einbindung und Stand arbeiten mit denselben Bausteinen.
*/
class DocumentResource extends CompositionKindResource
{
protected static ?string $slug = 'dokumente';
protected static ?string $navigationLabel = 'Dokumente';
protected static ?string $modelLabel = 'Dokument';
protected static ?string $pluralModelLabel = 'Dokumente';
protected static ?int $navigationSort = 4;
public static function kind(): CompositionKind
{
return CompositionKind::Document;
}
public static function getPages(): array
{
return [
'index' => ListDocuments::route('/'),
'edit' => EditDocument::route('/{record}'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Documents\Pages;
use App\Filament\Resources\Compositions\Pages\EditComposition;
use App\Filament\Resources\Documents\DocumentResource;
class EditDocument extends EditComposition
{
protected static string $resource = DocumentResource::class;
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Documents\Pages;
use App\Domain\Catalog\CompositionKind;
use App\Filament\Resources\Compositions\Pages\ListCompositionKind;
use App\Filament\Resources\Documents\DocumentResource;
class ListDocuments extends ListCompositionKind
{
protected static string $resource = DocumentResource::class;
protected function kind(): CompositionKind
{
return CompositionKind::Document;
}
}
+11 -2
View File
@@ -21,6 +21,7 @@
use App\Filament\Resources\Combinations\CombinationResource;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Resources\Courses\CourseResource;
use App\Filament\Resources\Documents\DocumentResource;
use App\Filament\Resources\Exercises\ExerciseResource;
use App\Filament\Resources\Practices\PracticeResource;
use Illuminate\Database\Eloquent\Builder;
@@ -297,7 +298,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$rows = [];
$dimensionId = ctype_digit($dimension) ? (int) $dimension : 0;
if ($kind !== 'modul') {
if (! in_array($kind, ['modul', 'dokumentfassung'], true)) {
$latestElements = ContentElementVersion::query()
->selectRaw('MAX(id)')
->whereIn('status', [ContentVersionStatus::Bereit, ContentVersionStatus::Entwurf])
@@ -321,7 +322,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
}
}
if (! $elementsOnly && in_array($kind, ['alle', 'modul'], true)) {
if (! $elementsOnly && in_array($kind, ['alle', 'modul', 'dokumentfassung'], true)) {
$latestCompositions = CompositionVersion::query()
->selectRaw('MAX(id)')
->where('status', ContentVersionStatus::Bereit)
@@ -331,6 +332,10 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
}
if ($kind === 'dokumentfassung') {
$builder->where('kind', CompositionKind::Document);
}
if ($dimensionId > 0) {
$builder->whereIn('id', $this->dimensionSubjectIds(Composition::class, $dimensionId));
}
@@ -370,6 +375,8 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$unreleased = Composition::query()
->where('id', '!=', $exceptCompositionId)
->whereNotNull('working_draft')
// Ein Dokument bindet man nur als bereitgestellte Fassung ein, nie als Entwurf.
->where('kind', '!=', CompositionKind::Document->value)
->whereDoesntHave('versions', function ($builder): void {
$builder->where('status', ContentVersionStatus::Bereit);
})
@@ -1085,6 +1092,7 @@ public function create(string $designation, CompositionKind $kind): Composition
CompositionKind::Kurs => 'programm',
CompositionKind::Uebung => 'modul',
CompositionKind::Exercise => 'uebung',
CompositionKind::Document => 'dokument',
default => null,
};
$editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first();
@@ -1107,6 +1115,7 @@ public static function editUrl(Composition $composition): string
CompositionKind::Kombination => CombinationResource::class,
CompositionKind::Uebung => ExerciseResource::class,
CompositionKind::Exercise => PracticeResource::class,
CompositionKind::Document => DocumentResource::class,
};
return $resource::getUrl('edit', ['record' => $composition]);
@@ -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')
@@ -0,0 +1,506 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DocumentChapters;
use App\Domain\Catalog\DocumentOutline;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\FormattedText;
use App\Filament\Resources\Compositions\Pages\EditComposition;
/**
* Kapitelarbeitsplatz eines Dokuments im Aufbaueditor (ADR-51). Der Arbeitsplatz hält die Kapitel wie jeden Aufbau als
* Mitglieder in `$members`; die Ebene steht in der Rolle („Kapitel“, „Unterkapitel“). Das Kapitel, das gerade offen ist,
* liegt in `$partTitle` und `$partBody` (derselbe Editor wie bei jedem Text).
*
* Offene Eingaben bleiben beim Wechsel des Kapitels erhalten: Der Wechsel legt Titel und Text des verlassenen Kapitels in
* `$chapterEdits` ab, und das Öffnen eines Kapitels liest zuerst dort. Geschrieben wird erst mit „Entwurf speichern“
* ({@see self::persistChapterEdits()}), und zwar als Entwurfsfassung des Kapitels; bereitgestellt wird erst mit der
* Dokumentfassung. Die Reihenfolge ändert immer den ganzen Block aus Kapitel und seinen Unterkapiteln.
*
* Die Seite stellt `members`, `selected`, `partTitle`, `partBody`, `feedback` und `memberExtras()` bereit
* ({@see EditComposition}).
*/
trait ManagesDocumentChapters
{
/** @var array<string, array{title: string, body: string}> Ungespeicherte Änderungen je Kapitel (Ziel => Titel und Text) */
public array $chapterEdits = [];
/** @var array<string, string> Gespeicherter Text je Ziel, nur für den Vergleich innerhalb einer Anfrage */
private array $chapterBase = [];
public function isDocument(): bool
{
return $this->hostKind() === CompositionKind::Document;
}
/**
* Die Kapitelübersicht: Nummer, Ebene, Titel (auch ein noch nicht gespeicherter) und Stand je Kapitel.
*
* @return list<array{index: int, number: string, level: int, anchor: string, title: string, changed: bool, draft: bool, selected: bool, first: bool, last: bool}>
*/
public function chapterRows(): array
{
$numbering = DocumentOutline::numbering(array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members));
$open = $this->openChapterEdit();
$rows = [];
foreach ($this->members as $index => $member) {
$target = (string) ($member['target'] ?? '');
$edit = $this->chapterEdits[$target] ?? null;
$title = $this->selected === $index && $open !== null ? $open['title'] : ($edit['title'] ?? (string) ($member['title'] ?? ''));
$rows[] = $numbering[$index] + [
'index' => $index,
'title' => trim($title) === '' ? 'Ohne Titel' : $title,
'changed' => $edit !== null || ($this->selected === $index && $open !== null),
'draft' => ($member['version_label'] ?? '') === 'Entwurf',
'selected' => $this->selected === $index,
'first' => $index === 0,
'last' => $index === count($this->members) - 1,
];
}
return $rows;
}
public function chapterCount(): int
{
return count($this->members);
}
/** Anzahl der Kapitel mit offenen Änderungen (gespeichert wird mit „Entwurf speichern“). */
public function chapterEditCount(): int
{
return count($this->chapterEditsNow());
}
/**
* Wechselt das Kapitel. Das verlassene bleibt mit seinen offenen Eingaben erhalten.
*/
public function selectChapter(int $index): void
{
if (! isset($this->members[$index])) {
return;
}
$this->commitRoleDraft();
$this->selected = $index;
$this->panel = 'bestandteil';
$this->aufbauTab = 'aufbau';
$this->syncRoleDraft();
}
/** Legt das offene Kapitel in den Arbeitsstand, wenn es vom gespeicherten abweicht. */
protected function stashChapter(): void
{
$open = $this->openChapterEdit();
$target = $this->selectedChapterTarget();
if ($target === null) {
return;
}
if ($open === null) {
unset($this->chapterEdits[$target]);
return;
}
$this->chapterEdits[$target] = $open;
}
/**
* Das offene Kapitel, falls Titel oder Text vom gespeicherten Stand abweichen.
*
* @return array{title: string, body: string}|null
*/
protected function openChapterEdit(): ?array
{
$target = $this->selectedChapterTarget();
if ($target === null) {
return null;
}
$title = trim($this->partTitle);
$body = FormattedText::canonical($this->partBody);
$storedTitle = trim((string) ($this->members[$this->selected]['title'] ?? ''));
if ($title === $storedTitle && FormattedText::same($body, $this->storedChapterBody($target))) {
return null;
}
return ['title' => $title, 'body' => $body];
}
/**
* Alle Änderungen, auch die des gerade offenen Kapitels.
*
* @return array<string, array{title: string, body: string}>
*/
public function chapterEditsNow(): array
{
$edits = $this->chapterEdits;
$target = $this->selectedChapterTarget();
if ($target !== null) {
$open = $this->openChapterEdit();
if ($open === null) {
unset($edits[$target]);
} else {
$edits[$target] = $open;
}
}
ksort($edits);
return $edits;
}
private function selectedChapterTarget(): ?string
{
if (! $this->isDocument() || $this->selected === null || ! isset($this->members[$this->selected])) {
return null;
}
$target = (string) ($this->members[$this->selected]['target'] ?? '');
return preg_match('/^element:\d+$/', $target) === 1 ? $target : null;
}
private function storedChapterBody(string $target): string
{
if (! array_key_exists($target, $this->chapterBase)) {
$version = ContentElementVersion::query()->find((int) substr($target, 8));
$this->chapterBase[$target] = $version instanceof ContentElementVersion ? (string) $version->body : '';
}
return $this->chapterBase[$target];
}
/**
* Titel und Text des gewählten Kapitels in die Eingabefelder laden: zuerst die offenen Eingaben, sonst den gespeicherten Stand.
*/
protected function loadChapterFields(): void
{
$target = $this->selectedChapterTarget();
if ($target === null) {
$this->partTitle = '';
$this->partBody = '';
return;
}
$edit = $this->chapterEdits[$target] ?? null;
$this->partTitle = $edit['title'] ?? (string) ($this->members[$this->selected]['title'] ?? '');
$this->partBody = $edit['body'] ?? FormattedText::canonical($this->storedChapterBody($target));
}
/**
* Schreibt die offenen Kapitel als Entwurfsfassungen und übernimmt sie in den Aufbau. Eine festgeschriebene Fassung
* bleibt unverändert; es entsteht eine neue Entwurfsfassung, die erst mit der Dokumentfassung bereitgestellt wird.
*/
protected function persistChapterEdits(): bool
{
if (! $this->isDocument()) {
return true;
}
$this->stashChapter();
foreach ($this->chapterEdits as $target => $edit) {
if (trim($edit['title']) === '') {
$this->feedback = 'Jedes Kapitel braucht einen Titel.';
$this->selectTarget($target);
return false;
}
}
$service = app(ContentService::class);
foreach ($this->chapterEdits as $target => $edit) {
$index = $this->memberIndex($target);
$version = $index === null ? null : ContentElementVersion::query()->with('element')->find((int) substr($target, 8));
if ($index === null || ! $version instanceof ContentElementVersion || $version->element === null) {
continue;
}
try {
$service->describe($version->element, trim($edit['title']), $version->element->description);
$updated = $service->reviseElementDraft($version, $edit['body'] === '' ? '<p></p>' : $edit['body']);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return false;
}
if ($updated->id !== $version->id) {
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$updated->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
if ($row === null) {
$this->feedback = 'Die neue Fassung des Kapitels ließ sich nicht übernehmen.';
return false;
}
$this->members[$index] = [...$row, 'role' => (string) $this->members[$index]['role'], 'note' => (string) ($this->members[$index]['note'] ?? ''), ...$this->memberExtras($this->members[$index])];
} else {
$this->members[$index]['title'] = trim($edit['title']);
}
}
$this->chapterEdits = [];
$this->chapterBase = [];
$this->slimChapterMembers();
$this->syncRoleDraft();
return true;
}
/**
* Ein Kapitelmitglied trägt nur, was die Übersicht braucht. Der Text eines Kapitels liegt in der Datenbank und wird beim
* Öffnen gelesen; so bleibt der Zustand der Seite klein, auch bei einem Handbuch mit vielen Kapiteln (jede Anfrage sendet ihn).
*/
protected function slimChapterMembers(): void
{
if (! $this->isDocument()) {
return;
}
foreach ($this->members as $index => $member) {
unset($this->members[$index]['body'], $this->members[$index]['summary'], $this->members[$index]['medium_description'], $this->members[$index]['usage_note'], $this->members[$index]['license_note']);
}
}
private function memberIndex(string $target): ?int
{
foreach ($this->members as $index => $member) {
if (($member['target'] ?? '') === $target) {
return $index;
}
}
return null;
}
private function selectTarget(string $target): void
{
$index = $this->memberIndex($target);
if ($index !== null) {
$this->selected = $index;
$this->syncRoleDraft();
}
}
/**
* Legt ein neues Kapitel (Ebene 1) oder Unterkapitel (Ebene 2) an. Es steht hinter dem gewählten Kapitel samt dessen
* Unterkapiteln beziehungsweise hinter dem gewählten Unterkapitel und ist sofort zum Schreiben geöffnet.
*/
public function addChapter(int $level = 1): void
{
abort_unless($this->canEditEditorial(), 403);
if (($reason = $this->schreibschutz()) !== null) {
$this->feedback = $reason;
return;
}
$this->commitRoleDraft();
$level = $level >= 2 && $this->members !== [] ? 2 : 1;
$title = $level === 2 ? 'Neues Unterkapitel' : 'Neues Kapitel';
try {
$service = app(ContentService::class);
$element = $service->createElement('text', 'text', $title);
$version = $service->draftElementVersion($element, '<p></p>');
/** @var Composition $document */
$document = $this->getRecord();
app(DocumentChapters::class)->mark($element, $document);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return;
}
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$version->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
if ($row === null) {
$this->feedback = 'Das Kapitel ließ sich nicht anlegen.';
return;
}
$row['role'] = DocumentOutline::role($level);
$row['note'] = '';
$row = [...$row, ...$this->memberExtras([])];
unset($row['body'], $row['summary'], $row['medium_description'], $row['usage_note'], $row['license_note']);
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$at = count($this->members);
if ($this->selected !== null && isset($this->members[$this->selected])) {
$base = $this->selected;
$levels = array_column(DocumentOutline::numbering($roles), 'level');
// Ein neues Kapitel steht hinter dem ganzen gewählten Kapitel, ein Unterkapitel hinter dem gewählten Eintrag.
while ($level === 1 && $levels[$base] === 2 && $base > 0) {
$base--;
}
$at = DocumentOutline::blockEnd($roles, $base) + 1;
}
array_splice($this->members, $at, 0, [$row]);
$this->members = array_values($this->members);
$this->selected = $at;
$this->panel = 'bestandteil';
$this->syncRoleDraft();
$this->feedback = '„'.$title.'“ steht jetzt an Stelle '.($at + 1).'. Gib dem Kapitel einen Titel und schreibe den Text; gespeichert wird mit „Entwurf speichern“.';
}
/** Ändert die Ebene: Kapitel oder Unterkapitel. Das erste Kapitel bleibt immer ein Kapitel. */
public function setChapterLevel(int $index, int $level): void
{
if (! isset($this->members[$index])) {
return;
}
$this->commitRoleDraft();
if ($index === 0 && $level >= 2) {
$this->feedback = 'Das erste Kapitel bleibt ein Kapitel: Ein Unterkapitel braucht ein Kapitel davor.';
return;
}
$this->members[$index]['role'] = DocumentOutline::role($level);
$this->syncRoleDraft();
$this->feedback = '„'.$this->members[$index]['title'].'“ ist jetzt ein '.DocumentOutline::role($level).'. Die Nummern folgen der Reihenfolge. Gespeichert ist das erst mit „Entwurf speichern“.';
}
/** Verschiebt ein Kapitel mit seinen Unterkapiteln um eine Stelle; ein Unterkapitel wandert auch in das Nachbarkapitel. */
public function moveChapter(int $index, int $direction): void
{
$this->commitRoleDraft();
if (! isset($this->members[$index]) || ! in_array($direction, [-1, 1], true)) {
return;
}
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$levels = array_column(DocumentOutline::numbering($roles), 'level');
$end = DocumentOutline::blockEnd($roles, $index);
$after = null;
if ($levels[$index] === 1) {
if ($direction < 0) {
$previous = null;
for ($i = $index - 1; $i >= 0; $i--) {
if ($levels[$i] === 1) {
$previous = $i;
break;
}
}
$after = $previous === null ? null : $previous - 1;
} elseif (isset($this->members[$end + 1])) {
$after = DocumentOutline::blockEnd($roles, $end + 1);
}
} elseif ($direction < 0) {
if ($index > 0 && $levels[$index - 1] === 2) {
$after = $index - 2;
} elseif ($index - 1 > 0) {
// Das erste Unterkapitel wandert ans Ende des vorigen Kapitels.
$after = $index - 2;
}
} elseif (isset($levels[$index + 1])) {
// Hinter das nächste Unterkapitel, beziehungsweise als erstes Unterkapitel in das nächste Kapitel.
$after = $index + 1;
}
if ($after === null) {
$this->feedback = 'Weiter lässt sich dieses Kapitel nicht verschieben.';
return;
}
$this->relocate($index, $end, $after);
}
/** Ablegen per Ziehen: Der Block des gezogenen Kapitels wandert an die Stelle des Ziels. */
protected function moveChapterTo(int $from, int $to): void
{
$this->commitRoleDraft();
if (! isset($this->members[$from], $this->members[$to]) || $from === $to) {
return;
}
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$levels = array_column(DocumentOutline::numbering($roles), 'level');
$end = DocumentOutline::blockEnd($roles, $from);
if ($to >= $from && $to <= $end) {
return;
}
if ($levels[$from] === 1) {
// Ein Kapitel zieht man auf ein Kapitel; ein Unterkapitel als Ziel zählt als sein Kapitel.
while ($levels[$to] === 2 && $to > 0) {
$to--;
}
$after = $to < $from ? $to - 1 : DocumentOutline::blockEnd($roles, $to);
} else {
$after = $to < $from ? $to - 1 : $to;
}
$this->relocate($from, $end, $after);
}
/**
* Setzt den Block `$start..$end` hinter den Eintrag mit dem ursprünglichen Index `$after` (−1 = an den Anfang).
*/
private function relocate(int $start, int $end, int $after): void
{
$selectedTarget = $this->selected !== null ? ($this->members[$this->selected]['target'] ?? null) : null;
$block = array_slice($this->members, $start, $end - $start + 1);
$position = 0;
foreach (array_keys($this->members) as $i) {
if ($i <= $after && ($i < $start || $i > $end)) {
$position++;
}
}
$rest = array_values(array_filter($this->members, fn (int $i): bool => $i < $start || $i > $end, ARRAY_FILTER_USE_KEY));
array_splice($rest, $position, 0, $block);
$this->members = $rest;
// Ein Unterkapitel am Anfang hätte kein Kapitel davor.
if (DocumentOutline::level((string) ($this->members[0]['role'] ?? '')) === 2) {
$this->members[0]['role'] = DocumentOutline::CHAPTER;
}
$this->selected = $this->memberIndex((string) $selectedTarget) ?? $this->selected;
$this->syncRoleDraft();
$this->feedback = 'Die Reihenfolge ist geändert. Die Nummern folgen ihr. Gespeichert ist das erst mit „Entwurf speichern“.';
}
/** Entfernt ein Kapitel aus dem Dokument; seine offenen Eingaben entfallen, der Text bleibt im Medienbestand. */
protected function forgetChapter(int $index): void
{
$target = (string) ($this->members[$index]['target'] ?? '');
unset($this->chapterEdits[$target]);
}
}
@@ -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'];
@@ -0,0 +1,86 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\DocumentGuide;
use App\Domain\Catalog\DocumentPdf;
use App\Domain\Catalog\DocumentReader;
use App\Domain\Catalog\EmbeddedImages;
use App\Domain\Catalog\FormattedText;
use App\Domain\Identity\StaffRole;
use App\Filament\Support\EditorialCatalog;
use App\Models\User;
use Illuminate\Http\Response;
use Illuminate\View\View;
/**
* Vorschau eines Dokuments für die Redaktion: der gespeicherte Entwurf, sonst die letzte bereitgestellte Fassung, so wie ein
* Mitglied sie als Seite und als PDF sieht (ohne Rechteprüfung und ohne Ausgabenachweis). Ungespeicherte Eingaben im Editor
* erscheinen hier erst nach „Entwurf speichern“.
*/
class DocumentPreviewController extends Controller
{
public function show(Composition $composition): View
{
$this->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<string, mixed>
*/
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);
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\DocumentGuide;
use App\Domain\Catalog\DocumentPdf;
use App\Domain\Catalog\EmbeddedImages;
use App\Domain\Catalog\ExerciseGuide;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Media\DeliveryLog;
use App\Http\Controllers\Controller;
use App\Http\SignedLink;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Das Dokument innerhalb des erworbenen Moduls oder Programms: als zusammenhängende Seite mit anklickbarem
* Inhaltsverzeichnis und als PDF. Beide zeigen die im Artikel-Stand gebundene Dokumentfassung (ADR-51); über jedes Kapitel
* und jedes Bild entscheidet `DecideAccess`, auch die direkte PDF-Adresse wird bei jedem Abruf neu entschieden.
*/
class DocumentController extends Controller
{
public function show(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): View
{
[$guide, $located] = $this->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<string, mixed>, 1: array{version: CompositionVersion, selection: list<string>|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];
}
}
+16 -5
View File
@@ -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<array<string, mixed>> $nodes
* @param list<array<string, mixed>> $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]);
}
}
}
@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
/**
* Dokumente (ADR-51), rein additiv: zwei redaktionelle Materialarten ohne neue Spalte und ohne neue Tabelle.
*
* - `dokument`: Art des Dokuments selbst, wählbar im Kontext „Dokument“.
* - `dokumentkapitel`: Art der Kapiteltexte, nur automatisch gesetzt (kein wählbarer Kontext), im Medienbestand wie die
* Übungsabschnitte standardmäßig ausgeblendet.
*
* Der Rückfall auf den vorherigen Programmstand setzt nur den Code zurück. Dieser kennt die Kompositionsart `document`
* nicht und blendet Dokumente über den Bereichsfilter (SupportedKindScope) aus; die Kapiteltexte bleiben als Texte
* erhalten. Ein Stand, der ein Dokument bindet, bleibt in der Datenbank unverändert.
*/
return new class extends Migration
{
public function up(): void
{
$now = now();
DB::table('editorial_content_kinds')->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();
}
};
+99
View File
@@ -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;
}
@@ -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')
<div class="member">
<p class="state state-hinweis" role="note">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“.</p>
<article class="mb-document">
<header class="mb-content-head">
<h1 class="mb-title">{{ $guide['title'] }}</h1>
@if (filled($guide['summary_html']))
<div class="mb-lead mb-prose">{!! $guide['summary_html'] !!}</div>
@endif
</header>
<p class="mb-actions"><a class="button button-secondary" href="{{ $pdfUrl }}" target="_blank" rel="noopener"><x-heroicon-o-arrow-down-tray aria-hidden="true" /> PDF-Vorschau öffnen</a></p>
@if ($guide['chapters'] === [])
<p class="state state-hinweis">Das Dokument hat noch kein Kapitel.</p>
@else
@include('member.partials.document', ['guide' => $guide])
@endif
</article>
</div>
@endsection
@@ -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 @@
</button>
</p>
@endif
<p class="vw-band">@include('filament.verwaltung.icon', ['name' => 'info'])<span>„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.</span></p>
@if ($dokument)
<p class="vw-band">@include('filament.verwaltung.icon', ['name' => 'info'])<span>„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.</span></p>
@else
<p class="vw-band">@include('filament.verwaltung.icon', ['name' => 'info'])<span>„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.</span></p>
@endif
@foreach (array_unique(array_filter([$this->feedback, $this->deskFeedback])) as $meldung)
<p class="vw-meldung" role="status"><span>{{ $meldung }}</span>
<button type="button" class="vw-link is-quiet" wire:click="clearFeedback">Ausblenden</button></p>
@@ -60,7 +65,7 @@
</div>
<div class="vw-register" role="tablist" aria-label="Bereiche">
@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)
<button type="button" role="tab" aria-selected="{{ $this->aufbauTab === $wert ? 'true' : 'false' }}" tabindex="{{ $this->aufbauTab === $wert ? '0' : '-1' }}"
wire:click="showAufbauTab('{{ $wert }}')"
x-on:keydown.right.prevent="$el.nextElementSibling?.focus()" x-on:keydown.left.prevent="$el.previousElementSibling?.focus()">
@@ -74,6 +79,8 @@
@include('filament.verwaltung.aufbau-angaben')
@elseif ($this->aufbauTab === 'verlauf')
@include('filament.verwaltung.aufbau-verlauf')
@elseif ($dokument)
@include('filament.verwaltung.dokument')
@else
@include('filament.verwaltung.aufbau')
@endif
@@ -84,8 +91,8 @@
<div class="vw-dialog-karte is-schmal">
<div class="vw-dialog-kopf">
<div>
<h2 id="freigabe-titel">Fassung freigeben</h2>
<p>Freigegeben wird {{ $review['next_label'] }} von {{ $review['host_label'] }} „{{ $review['title'] }}“. Eine frühere Fassung bleibt unverändert. Mitgliederbibliothek, Website und Angebote ändern sich dadurch nicht.</p>
<h2 id="freigabe-titel">{{ $dokument ? 'Dokumentfassung bereitstellen' : 'Fassung freigeben' }}</h2>
<p>{{ $dokument ? 'Bereitgestellt' : 'Freigegeben' }} wird {{ $review['next_label'] }} von {{ $review['host_label'] }} „{{ $review['title'] }}“. Eine frühere Fassung bleibt unverändert. Mitgliederbibliothek, Website und Angebote ändern sich dadurch nicht.</p>
</div>
<button type="button" class="vw-btn is-icon" wire:click="cancelRelease" aria-label="Schließen">@include('filament.verwaltung.icon', ['name' => 'x'])</button>
</div>
@@ -123,7 +130,7 @@
<div class="vw-dialog-fuss-zeile">
<div class="vw-knoepfe">
<button type="button" class="vw-btn" wire:click="cancelRelease">Abbrechen</button>
<button type="button" class="vw-btn is-primary" wire:click="publishRevision" @disabled($review['blocked'] !== [] || ($review['needs_consent'] && ! $this->releaseConsent))>Jetzt freigeben</button>
<button type="button" class="vw-btn is-primary" wire:click="publishRevision" @disabled($review['blocked'] !== [] || ($review['needs_consent'] && ! $this->releaseConsent))>{{ $dokument ? 'Jetzt bereitstellen' : 'Jetzt freigeben' }}</button>
</div>
</div>
</div>
@@ -6,6 +6,14 @@
@endphp
<div class="vw-medien-raster">
<section class="vw-medien-haupt" aria-labelledby="didaktik-titel">
@if ($this->isDocument())
<h2 id="didaktik-titel" class="vw-abschnitt-titel">Dokument</h2>
<p class="vw-feld-hilfe">Ein Dokument hat keine Didaktikangaben. Die Kapitel schreibst du im Register „Kapitel“. Name, Beschreibung und Einordnung des Dokuments bearbeitest du in der Redaktion.
<button type="button" class="vw-link" wire:click="openRedaktion('texte')">Redaktion öffnen</button></p>
<label class="vw-feldlabel">Notiz zur nächsten Dokumentfassung
<input class="vw-eingabe" type="text" wire:model.live.blur="revisionNote">
</label>
@else
<h2 id="didaktik-titel" class="vw-abschnitt-titel">Didaktik</h2>
<p class="vw-feld-hilfe">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.</p>
<div class="vw-feldlabel" role="group" aria-labelledby="lernziel-label">
@@ -57,6 +65,7 @@
@endif
<p class="vw-feld-hilfe">Name, Texte, Präsentationsmedien und Einordnung bearbeitest du in der Redaktion.
<button type="button" class="vw-link" wire:click="openRedaktion('texte')">Redaktion öffnen</button></p>
@endif
</section>
<aside class="vw-medien-seite" aria-labelledby="katalogbild-titel">
@@ -0,0 +1,112 @@
{{-- Kapitelarbeitsplatz eines Dokuments: Kapitelübersicht links, das offene Kapitel mit dem gemeinsamen Texteditor rechts (ADR-51). --}}
@php
$kapitel = $this->chapterRows();
$anzahl = count($kapitel);
$auswahl = $this->selected !== null && isset($kapitel[$this->selected]) ? $this->selected : null;
$aktuell = $auswahl !== null ? $kapitel[$auswahl] : null;
$offen = $this->chapterEditCount();
@endphp
<div class="vw-aufbau vw-dokument">
<section class="vw-struktur" aria-labelledby="kapitel-titel">
<div class="vw-struktur-kopf">
<h2 id="kapitel-titel">Kapitelübersicht <span class="vw-rolle-zahl">· {{ $anzahl }} {{ $anzahl === 1 ? 'Eintrag' : 'Einträge' }}@if ($offen > 0), {{ $offen }} mit offenen Änderungen @endif</span></h2>
<span class="vw-sortierer">
<button type="button" class="vw-btn is-line is-small" wire:click="addChapter(1)">@include('filament.verwaltung.icon', ['name' => 'plus'])Kapitel</button>
<button type="button" class="vw-btn is-line is-small" wire:click="addChapter(2)" @disabled($anzahl === 0)>@include('filament.verwaltung.icon', ['name' => 'plus'])Unterkapitel</button>
</span>
</div>
@if ($anzahl === 0)
<div class="vw-leer">
<strong>Noch kein Kapitel</strong>
<p>Lege das erste Kapitel an. Unterkapitel gliedern ein Kapitel weiter; die Nummern ergeben sich aus der Reihenfolge.</p>
<button type="button" class="vw-btn is-line" wire:click="addChapter(1)">@include('filament.verwaltung.icon', ['name' => 'plus'])Erstes Kapitel anlegen</button>
</div>
@else
<ol class="vw-struktur-liste" x-data="{ von: null, ueber: null }" aria-label="Kapitel in Reihenfolge, sortierbar">
@foreach ($kapitel as $zeile)
<li wire:key="kapitel-{{ $this->members[$zeile['index']]['target'] }}-{{ $zeile['index'] }}"
@class(['vw-baustein', 'is-gewaehlt' => $zeile['selected'], 'vw-unterkapitel' => $zeile['level'] === 2])
style="{{ $zeile['level'] === 2 ? 'margin-left: 1.5rem;' : '' }}"
draggable="true"
x-on:dragstart="von = {{ $zeile['index'] }}; $event.dataTransfer.effectAllowed = 'move'"
x-on:dragend="von = null; ueber = null"
x-on:dragover.prevent="ueber = {{ $zeile['index'] }}"
x-on:drop.prevent="if (von !== null && von !== {{ $zeile['index'] }}) { $wire.moveTo(von, {{ $zeile['index'] }}) } von = null; ueber = null"
x-bind:class="{ 'is-ziehen': von === {{ $zeile['index'] }}, 'is-ziel': ueber === {{ $zeile['index'] }} && von !== {{ $zeile['index'] }} }">
<div class="vw-baustein-zeile">
<span class="vw-griff" title="Ziehen zum Sortieren. Ohne Ziehen: Alt+Pfeil oder die Knöpfe unter der Liste.">@include('filament.verwaltung.icon', ['name' => 'griff'])<span class="vw-sr">Ziehgriff</span></span>
<span class="vw-position" aria-hidden="true">{{ $zeile['number'] }}</span>
<button type="button" class="vw-baustein-haupt" wire:click="selectChapter({{ $zeile['index'] }})"
@if ($zeile['selected']) aria-current="true" @endif
aria-label="{{ $zeile['level'] === 2 ? 'Unterkapitel' : 'Kapitel' }} {{ $zeile['number'] }}: {{ $zeile['title'] }}@if ($zeile['changed']), ungespeicherte Änderungen @endif"
x-on:keydown.alt.arrow-up.prevent="$wire.movePart({{ $zeile['index'] }}, -1)"
x-on:keydown.alt.arrow-down.prevent="$wire.movePart({{ $zeile['index'] }}, 1)">
<span class="vw-baustein-text">
<strong>{{ $zeile['title'] }}</strong>
<span>
{{ $zeile['level'] === 2 ? 'Unterkapitel' : 'Kapitel' }}
@if ($zeile['changed']) · <em>geändert, nicht gespeichert</em>@elseif ($zeile['draft']) · Entwurf @endif
</span>
</span>
</button>
</div>
</li>
@endforeach
</ol>
<div class="vw-struktur-fuss" role="group" aria-label="Das gewählte Kapitel ordnen">
<span>@if ($auswahl !== null) Eintrag {{ $auswahl + 1 }} von {{ $anzahl }} @else Kein Kapitel gewählt @endif</span>
<span class="vw-sortierer">
<button type="button" class="vw-btn is-small is-icon" wire:click="movePart({{ $auswahl ?? 0 }}, -1)" @disabled($auswahl === null || $auswahl === 0) aria-label="Kapitel mit seinen Unterkapiteln nach oben">@include('filament.verwaltung.icon', ['name' => 'hoch'])</button>
<button type="button" class="vw-btn is-small is-icon" wire:click="movePart({{ $auswahl ?? 0 }}, 1)" @disabled($auswahl === null || $auswahl === $anzahl - 1) aria-label="Kapitel mit seinen Unterkapiteln nach unten">@include('filament.verwaltung.icon', ['name' => 'runter'])</button>
</span>
</div>
@endif
</section>
<section class="vw-detailbereich" aria-label="Offenes Kapitel">
@if ($aktuell === null)
<div class="vw-leer">
<strong>Kein Kapitel geöffnet</strong>
<p>Wähle links ein Kapitel. Seine Eingaben bleiben erhalten, wenn du zu einem anderen Kapitel wechselst.</p>
</div>
@else
<div class="vw-detail-kopf">
<div>
<h2>{{ $aktuell['number'] }} {{ $aktuell['title'] }}</h2>
<p class="vw-kopf-typ">{{ $aktuell['level'] === 2 ? 'Unterkapitel' : 'Kapitel' }} · Stelle {{ $auswahl + 1 }} von {{ $anzahl }}</p>
</div>
<div class="vw-mehr" x-data="{ offen: false }" x-on:keydown.escape.stop="offen = false; $refs.knopf.focus()" x-on:click.outside="offen = false">
<button type="button" class="vw-btn" x-ref="knopf" x-on:click="offen = ! offen" x-bind:aria-expanded="offen" aria-haspopup="true" aria-label="Weitere Aktionen für Kapitel {{ $aktuell['number'] }}">Weitere Aktionen @include('filament.verwaltung.icon', ['name' => 'runter'])</button>
<div class="vw-mehr-menue" x-show="offen" x-cloak>
@if ($aktuell['level'] === 2)
<button type="button" wire:click="setChapterLevel({{ $auswahl }}, 1)" x-on:click="offen = false"><span>Zum Kapitel machen<small>Es steht dann nicht mehr unter dem Kapitel davor.</small></span></button>
@elseif (! $aktuell['first'])
<button type="button" wire:click="setChapterLevel({{ $auswahl }}, 2)" x-on:click="offen = false"><span>Zum Unterkapitel machen<small>Es gehört dann zum Kapitel davor.</small></span></button>
@endif
<hr>
<button type="button" wire:click="askConfirmation('removePart', {{ $auswahl }})" x-on:click="offen = false" style="color: var(--vw-error)"><span>Kapitel entfernen<small>Der Text bleibt im Medienbestand.</small></span></button>
</div>
</div>
</div>
<div class="vw-detail-inhalt">
<label class="vw-feldlabel">Titel des {{ $aktuell['level'] === 2 ? 'Unterkapitels' : 'Kapitels' }}
<input class="vw-eingabe" type="text" wire:model.live.blur="partTitle" maxlength="255">
</label>
<div class="vw-feldlabel" role="group" aria-labelledby="kapitel-text-label">
<span id="kapitel-text-label">Text</span>
<div class="vw-rich-eingabe">{{ $this->richKomponente('partBody') }}</div>
</div>
<p class="vw-feld-hilfe">
Überschriften, Listen, Links, Tabellen und Bilder aus dem Medienbestand. Eingaben bleiben beim Wechsel zu einem anderen Kapitel erhalten.
Gespeichert wird mit „Entwurf speichern“ als Entwurf des Kapitels; eine Dokumentfassung entsteht erst, wenn du sie bereitstellst.
</p>
<div class="vw-sortierer">
<button type="button" class="vw-btn" wire:click="selectChapter({{ max(0, $auswahl - 1) }})" @disabled($auswahl === 0)>@include('filament.verwaltung.icon', ['name' => 'hoch'])Voriges Kapitel</button>
<button type="button" class="vw-btn" wire:click="selectChapter({{ min($anzahl - 1, $auswahl + 1) }})" @disabled($auswahl === $anzahl - 1)>@include('filament.verwaltung.icon', ['name' => 'runter'])Nächstes Kapitel</button>
</div>
</div>
@endif
</section>
</div>
+35
View File
@@ -0,0 +1,35 @@
@extends('layouts.member')
@section('title', $guide['title'])
@section('nav', 'bibliothek')
{{--
Dokument (zum Beispiel Trainerhandbuch) im erworbenen Stand: die im Stand gebundene Fassung als zusammenhängende Seite
mit anklickbarem Inhaltsverzeichnis; derselbe Inhalt als PDF. Über jedes Kapitel und jedes Bild entscheidet die zentrale
Rechteprüfung.
--}}
@section('content')
<p class="mb-crumb"><a href="{{ route('member.library') }}"><x-heroicon-o-arrow-left aria-hidden="true" /> Zur Bibliothek</a></p>
<article class="mb-document">
<header class="mb-content-head">
<h1 class="mb-title">{{ $guide['title'] }}</h1>
@if (filled($guide['summary_html']))
<div class="mb-lead mb-prose">{!! $guide['summary_html'] !!}</div>
@endif
</header>
@if (filled($copy ?? null))
<p class="state state-hinweis">Lizenziert für {{ $reader }} · Lizenzkopie {{ $copy }}</p>
@endif
<p class="mb-actions">
@if ($pdfUrl)
<a class="button button-secondary" href="{{ $pdfUrl }}"><x-heroicon-o-arrow-down-tray aria-hidden="true" /> Als PDF herunterladen</a>
@else
<span class="state state-hinweis">Ein PDF ist für diese Lizenz oder derzeit nicht verfügbar.</span>
@endif
</p>
@include('member.partials.document', ['guide' => $guide])
</article>
@endsection
@@ -0,0 +1,37 @@
{{--
Ein Dokument als zusammenhängende Seite: anklickbares Inhaltsverzeichnis und die Kapitel in ihrer Reihenfolge. Die Mitgliederansicht
und die Vorschau der Redaktion nutzen denselben Baustein. Erwartet $guide mit title, summary_html und chapters
(number, level, anchor, title, allowed, html). Ein Kapitel ohne Berechtigung zeigt einen Hinweis an seiner Stelle.
--}}
<div class="mb-doc">
<nav class="mb-doc-toc" aria-labelledby="dokument-inhalt" id="inhaltsverzeichnis">
<details open>
<summary id="dokument-inhalt">Inhaltsverzeichnis</summary>
<ol>
@foreach ($guide['chapters'] as $chapter)
<li class="mb-doc-toc-{{ $chapter['level'] }}">
<a href="#{{ $chapter['anchor'] }}"><span class="mb-doc-nr">{{ $chapter['number'] }}</span> {{ $chapter['title'] }}</a>
</li>
@endforeach
</ol>
</details>
</nav>
<div class="mb-doc-body">
@foreach ($guide['chapters'] as $chapter)
<section class="mb-doc-chapter mb-doc-level-{{ $chapter['level'] }}" id="{{ $chapter['anchor'] }}" aria-labelledby="{{ $chapter['anchor'] }}-titel">
@if ($chapter['level'] === 1)
<h2 id="{{ $chapter['anchor'] }}-titel"><span class="mb-doc-nr">{{ $chapter['number'] }}</span> {{ $chapter['title'] }}</h2>
@else
<h3 id="{{ $chapter['anchor'] }}-titel"><span class="mb-doc-nr">{{ $chapter['number'] }}</span> {{ $chapter['title'] }}</h3>
@endif
@if ($chapter['allowed'])
<div class="mb-prose">{!! $chapter['html'] !!}</div>
@else
<p class="state state-hinweis" role="note">Dieses Kapitel ist derzeit nicht verfügbar.</p>
@endif
<p class="mb-doc-up"><a href="#inhaltsverzeichnis">Zum Inhaltsverzeichnis</a></p>
</section>
@endforeach
</div>
</div>
@@ -56,7 +56,7 @@
</div>
@if (! $isGroup && ! $node['view_url'])
<p class="mb-outline-locked">Nicht enthalten. Für diesen Teil liegt keine Freigabe vor.</p>
@elseif ($isGroup && $node['children'] === [])
@elseif ($isGroup && $node['children'] === [] && empty($node['document']))
<p class="mb-outline-locked">Nicht enthalten. Für diesen Teil liegt keine Freigabe vor.</p>
@endif
@if ($node['children'] !== [])
+17
View File
@@ -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')
+264
View File
@@ -0,0 +1,264 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\CompositionDisplayRelease;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Entitlement\MediaDelivery;
use App\Http\SignedLink;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\Support\BuildsDocuments;
use Tests\TestCase;
/**
* Durchstich der Ausgabe eines Dokuments (ADR-51): Ein Handbuch steckt in einem verkauften Modul. Mitglieder lesen die im
* Stand gebundene Fassung als Seite mit Inhaltsverzeichnis und laden daraus das PDF; beide zeigen dieselben Kapitel,
* Tabellen und Bilder. Eine spätere Bearbeitung ändert einen älteren Stand nicht.
*/
class DokumentAusgabeTest extends TestCase
{
use BuildsDocuments;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('media_derived');
}
public function test_the_member_reads_the_document_with_a_clickable_table_of_contents(): void
{
[$article, $release, $member, $image] = $this->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('<table>', $html);
$this->assertStringContainsString('Begrüßung', $html);
$this->assertStringContainsString('<h4>Zwischenüberschrift</h4>', $html, 'Zwischenüberschriften stehen eine Ebene unter dem Kapitel.');
$this->assertMatchesRegularExpression('#<img alt="Aufstellung" src="[^"]*ausgabe/'.$article->id.'/'.$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('#<img alt="Aufstellung" src="([^"]+)"#', $html, $match);
$src = html_entity_decode($match[1]);
$this->actingAs($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('#<a href="\#kapitel-[\d-]+"><span class="mb-doc-nr">([\d.]+)</span> ([^<]+)</a>#', $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 = '<table><tbody><tr><th><p>Zeit</p></th><th><p>Inhalt</p></th></tr><tr><td><p>10 Min.</p></td><td><p>Begrüßung</p></td></tr></tbody></table>';
$document = $this->document([
'Grundlagen' => '<p>Einleitung zum Handbuch.</p><h3>Zwischenüberschrift</h3>'.$table.'<img data-id="'.$image->id.'" alt="Aufstellung"><p>Danach.</p>',
'-Haltung' => '<p>Sicher stehen.</p><ul><li><p>Abstand</p></li></ul>',
'Anhang' => '<p>Weitere Hinweise.</p>',
]);
$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,
]);
}
}
+241
View File
@@ -0,0 +1,241 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ContentVersionStatus;
use App\Filament\Resources\Documents\Pages\EditDocument;
use App\Filament\Resources\Exercises\Pages\EditExercise as EditModule;
use App\Filament\Support\EditorialCatalog;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use Tests\TestCase;
/**
* Dokumente bearbeiten (ADR-51): Kapitel und Unterkapitel anlegen, ordnen und schreiben, ohne dass offene Eingaben beim
* Wechsel verloren gehen; speichern als Entwurf; bereitstellen als zusammenhängende Dokumentfassung.
*/
class DokumentEditorTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_a_document_is_created_under_inhalte_and_opens_the_chapter_workplace(): void
{
$document = app(EditorialCatalog::class)->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('<p>Erster Text</p>', $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('<p></p>', 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('<p>Erster Text</p>', $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('<p>Text von B</p>', $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(['<p>Erster Text</p>', '<p>Zweiter Text</p>'], $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('<p>Erster Text</p>', $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('<p>Geänderter Text</p>', $second->members->first()->contentElementVersion->body);
$this->assertSame('<p>Zweiter Text</p>', $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), '<p>Text</p>');
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<string, mixed> */
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;
}
}
+2 -1
View File
@@ -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());
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ExerciseSections;
use App\Domain\Catalog\FormattedText;
use App\Filament\Resources\Practices\Pages\EditPractice;
use App\Http\SignedLink;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\Support\BuildsDocuments;
use Tests\TestCase;
/**
* Derselbe Texteditor für Übungstexte und Kapitel (ADR-51): Ein Trainerhinweis in einer Übung wird mit denselben Werkzeugen
* bearbeitet wie ein Handbuchkapitel; seine Formatierung (Überschrift, Liste, Tabelle, Bild) bleibt beim Öffnen und erneuten
* Speichern erhalten und erscheint in der Übungsansicht und im Übungs-PDF.
*/
class UebungFormatierungTest extends TestCase
{
use BuildsDocuments;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('media_derived');
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_a_trainer_note_is_edited_with_the_chapter_editor_and_keeps_its_formatting_in_view_and_pdf(): void
{
$image = $this->picture('Aufstellung');
$table = '<table><tbody><tr><th><p>Zeit</p></th><th><p>Hinweis</p></th></tr><tr><td><p>5 Min.</p></td><td><p>Abstand <strong>prüfen</strong></p></td></tr></tbody></table>';
$note = '<h3>Trainerhinweis</h3><p>Vor dem Start klären.</p><ul><li><p>Raum</p></li></ul>'.$table.'<img data-id="'.$image->id.'" alt="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('</tbody>', '<tr><td><p>10 Min.</p></td><td><p>Neu ergänzt</p></td></tr></tbody>', $table);
$editor->set('partBody', '<h3>Trainerhinweis</h3><p>Vor dem Start klären.</p><ul><li><p>Raum</p></li></ul>'.$changed.'<img data-id="'.$image->id.'" alt="Aufstellung">')->call('saveSourceText');
$saved = ContentElementVersion::query()->latest('id')->first();
$this->assertStringContainsString('Neu ergänzt', (string) $saved->body);
$this->assertStringContainsString('<ul><li><p>Raum</p></li></ul>', (string) $saved->body);
$this->assertStringContainsString('<img data-id="'.$image->id.'" alt="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 = '<table><tbody><tr><th><p>Zeit</p></th><th><p>Hinweis</p></th></tr><tr><td><p>5 Min.</p></td><td><p>Abstand <strong>prüfen</strong></p></td></tr></tbody></table>';
$setup = $this->exerciseWithNote('<h3>Trainerhinweis</h3><p>Vor dem Start klären.</p><ul><li><p>Raum</p></li></ul>'.$table.'<img data-id="'.$image->id.'" alt="Aufstellung">');
$member = $setup['member'];
$page = $this->actingAs($member)->get(route('member.exercise', ['article' => $setup['article'], 'release' => $setup['release'], 'path' => '1']))->assertOk();
$page->assertSee('<h3>Trainerhinweis</h3>', false)->assertSee('<li><p>Raum</p></li>', false)->assertSee('<table>', false)->assertSee('Abstand <strong>prüfen</strong>', 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<string, mixed>
*/
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;
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
namespace Tests\Support;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\ArticleService;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DocumentChapters;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\RightsProfileVersion;
use App\Domain\Entitlement\GrantIssuer;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
/**
* Baut Dokumente für Tests: ein Handbuch mit Kapiteln, Tabellen und Bildern, Module, die eine Dokumentfassung einbinden,
* Artikel-Stände und Konten mit Rechten.
*/
trait BuildsDocuments
{
use BuildsExercises;
protected function documentComposition(string $title = 'Trainerhandbuch'): Composition
{
$composition = app(ContentService::class)->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<string, string> $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<string, list<string>> $capabilities
*/
protected function rights(array $capabilities): RightsProfileVersion
{
return app(OfferService::class)->createRightsProfile('Profil '.md5(json_encode($capabilities)), 'ehrenamtlich', $capabilities);
}
/**
* @param list<LicenseArticle> $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<string>
*/
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;
}
}
+15 -2
View File
@@ -127,12 +127,25 @@ public function test_an_image_is_a_reference_to_an_image_version_and_never_an_ad
{
$html = FormattedText::canonical('<p>Davor</p><img data-id="12" alt="Ein Bild" src="https://evil.example/x.png" onerror="x()" width="40"><p>Danach</p><img src="y.png"><p>Eingebettet <img data-id="9" alt="x"> im Absatz</p>');
$this->assertSame('<p>Davor</p><img data-id="12" alt="Ein Bild"><p>Danach</p><p>Eingebettet im Absatz</p>', $html);
$this->assertSame([12], FormattedText::imageIds($html));
$this->assertSame('<p>Davor</p><img data-id="12" alt="Ein Bild"><p>Danach</p><p>Eingebettet <img data-id="9" alt="x"> im Absatz</p>', $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('<h3>Kopf</h3><ul><li><p>Punkt</p></li></ul>', FormattedText::canonical('<h3>Kopf<img data-id="5"></h3><ul><li><p>Punkt<img data-id="6"></p></li></ul>'), 'In Überschrift und Liste entfällt ein Bild.');
$this->assertSame($html, FormattedText::canonical($html));
$this->assertSame('<img data-id="3" alt="">', FormattedText::canonical('<img data-id="3" alt="">'), '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('<table><tbody><tr><td><p>Stuhlkreis</p><img data-id="7" alt="Aufstellung" src="x.png"></td></tr></tbody></table>');
$this->assertSame('<table><tbody><tr><td><p>Stuhlkreis</p><img data-id="7" alt="Aufstellung"></td></tr></tbody></table>', $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('<table><tbody><tr><td><img data-id="7" alt=""></td></tr></tbody></table>', FormattedText::canonical('<table><tbody><tr><td><img data-id="7"></td></tr></tbody></table>'), 'Eine Zelle nur mit Bild bleibt erhalten.');
}
public function test_images_appear_only_where_the_reader_resolves_them(): void
{
$html = '<p>Davor</p><img data-id="12" alt="Ein Bild"><img data-id="13" alt="Anderes"><p>Danach</p>';
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace Tests\Unit;
use App\Domain\Catalog\DocumentOutline;
use App\Domain\Commerce\Receipt\PdfDocument;
use App\Domain\Media\PdfImage;
use Tests\TestCase;
class PdfDocumentTest extends TestCase
{
public function test_a_document_without_the_new_features_keeps_its_exact_bytes(): void
{
// Prüfsummen aus dem Stand vor ADR-51: Belege und Übungs-PDFs ändern sich durch den erweiterten Schreiber nicht.
$pdf = new PdfDocument;
$pdf->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();
}
}