diff --git a/app/Domain/Catalog/ArticleService.php b/app/Domain/Catalog/ArticleService.php index e43f46c..c8eb61a 100644 --- a/app/Domain/Catalog/ArticleService.php +++ b/app/Domain/Catalog/ArticleService.php @@ -57,6 +57,8 @@ public function publishRelease( 'content_element_version_id' => $row['version_id'], 'role' => $row['role'] !== '' ? $row['role'] : $row['path'], 'path' => $row['path'], + 'requirement' => $row['requirement'] ?? null, + 'variant_key' => $row['variant'] ?? null, ]); } diff --git a/app/Domain/Catalog/CompatibilityAttestation.php b/app/Domain/Catalog/CompatibilityAttestation.php index ebdb261..6107f7e 100644 --- a/app/Domain/Catalog/CompatibilityAttestation.php +++ b/app/Domain/Catalog/CompatibilityAttestation.php @@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model protected $fillable = [ 'composition_version_id', 'resolved_hash', + 'structure_hash', 'confirmed_by', 'confirmed_at', 'note', diff --git a/app/Domain/Catalog/CompositionKind.php b/app/Domain/Catalog/CompositionKind.php index c96daee..3945b68 100644 --- a/app/Domain/Catalog/CompositionKind.php +++ b/app/Domain/Catalog/CompositionKind.php @@ -7,6 +7,8 @@ enum CompositionKind: string case Kombination = 'kombination'; case Uebung = 'uebung'; case Kurs = 'kurs'; + /** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */ + case Exercise = 'exercise'; /** * @return list @@ -20,8 +22,9 @@ public function label(): string { return match ($this) { self::Kombination => 'Fachliche Kombination', - self::Uebung => 'Übung', + self::Uebung => 'Modul', self::Kurs => 'Kurs', + self::Exercise => 'Übung', }; } @@ -29,8 +32,9 @@ public function plural(): string { return match ($this) { self::Kombination => 'Fachliche Kombinationen', - self::Uebung => 'Übungen', + self::Uebung => 'Module', self::Kurs => 'Kurse', + self::Exercise => 'Übungen', }; } @@ -38,8 +42,9 @@ public function createLabel(): string { return match ($this) { self::Kombination => 'Kombination anlegen', - self::Uebung => 'Übung anlegen', + self::Uebung => 'Modul anlegen', self::Kurs => 'Kurs anlegen', + self::Exercise => 'Übung anlegen', }; } @@ -49,6 +54,7 @@ public function explanation(): string self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.', self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.', self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.', + self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.', }; } @@ -58,6 +64,7 @@ public function deskLabel(): string self::Kombination => 'Fachliche Kombination', self::Uebung => 'Modul', self::Kurs => 'Programm', + self::Exercise => 'Übung', }; } @@ -67,6 +74,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(), }; } diff --git a/app/Domain/Catalog/CompositionMember.php b/app/Domain/Catalog/CompositionMember.php index 2555b61..e612775 100644 --- a/app/Domain/Catalog/CompositionMember.php +++ b/app/Domain/Catalog/CompositionMember.php @@ -14,8 +14,20 @@ class CompositionMember extends Model 'placement_note', 'content_element_version_id', 'nested_composition_version_id', + 'variant_id', + 'requirement', + 'variant_selection', ]; + public const REQUIRED = 'erforderlich'; + + public const SUPPLEMENTARY = 'ergaenzend'; + + protected function casts(): array + { + return ['variant_selection' => 'array']; + } + protected static function booted(): void { static::creating(function (CompositionMember $member): void { @@ -41,6 +53,11 @@ public function contentElementVersion(): BelongsTo return $this->belongsTo(ContentElementVersion::class); } + public function variant(): BelongsTo + { + return $this->belongsTo(CompositionVersionVariant::class, 'variant_id'); + } + public function nestedCompositionVersion(): BelongsTo { return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id'); diff --git a/app/Domain/Catalog/CompositionVersion.php b/app/Domain/Catalog/CompositionVersion.php index ab4e423..314aeb4 100644 --- a/app/Domain/Catalog/CompositionVersion.php +++ b/app/Domain/Catalog/CompositionVersion.php @@ -17,6 +17,9 @@ class CompositionVersion extends Model 'learning_goal', 'duration_minutes', 'material_note', + 'duration_max', + 'prerequisites', + 'structure_hash', ]; protected function casts(): array @@ -60,6 +63,11 @@ public function members(): HasMany return $this->hasMany(CompositionMember::class)->orderBy('position'); } + public function variants(): HasMany + { + return $this->hasMany(CompositionVersionVariant::class)->orderBy('position'); + } + public function attestations(): HasMany { return $this->hasMany(CompatibilityAttestation::class); diff --git a/app/Domain/Catalog/CompositionVersionVariant.php b/app/Domain/Catalog/CompositionVersionVariant.php new file mode 100644 index 0000000..59878a7 --- /dev/null +++ b/app/Domain/Catalog/CompositionVersionVariant.php @@ -0,0 +1,36 @@ +whereKey($variant->composition_version_id)->value('status'); + + if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) { + throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.'); + } + }); + + static::updating(function (): void { + throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.'); + }); + } + + public function compositionVersion(): BelongsTo + { + return $this->belongsTo(CompositionVersion::class); + } +} diff --git a/app/Domain/Catalog/ContentResolver.php b/app/Domain/Catalog/ContentResolver.php index 0a6e1a2..54098ba 100644 --- a/app/Domain/Catalog/ContentResolver.php +++ b/app/Domain/Catalog/ContentResolver.php @@ -5,9 +5,14 @@ class ContentResolver { /** - * @return list + * Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und + * den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl + * (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten). + * + * @param list|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle + * @return list */ - public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array + public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array { if ($node instanceof ContentElementVersion) { $node->loadMissing('element'); @@ -16,6 +21,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'version_id' => $node->id, 'role' => $path, 'path' => $path !== '' ? $path : $node->element->working_title, + 'requirement' => CompositionMember::REQUIRED, + 'variant' => null, ]]; } @@ -26,7 +33,13 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p $stack[] = $node->composition_id; $rows = []; - foreach ($node->members()->orderBy('position')->get() as $member) { + foreach ($node->members()->with('variant')->orderBy('position')->get() as $member) { + $variantKey = $member->variant?->key; + + if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) { + continue; + } + $segment = $path === '' ? $member->role : $path.' / '.$member->role; if ($member->content_element_version_id !== null) { @@ -34,6 +47,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'version_id' => $member->content_element_version_id, 'role' => $member->role, 'path' => $segment, + 'requirement' => $member->requirement ?: CompositionMember::REQUIRED, + 'variant' => $variantKey, ]; continue; @@ -53,7 +68,12 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p continue; } - $rows = array_merge($rows, $this->expand($nested, $segment, $stack)); + $rows = array_merge($rows, $this->expand( + $nested, + $segment, + $stack, + is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null, + )); } return $rows; diff --git a/app/Domain/Catalog/ContentService.php b/app/Domain/Catalog/ContentService.php index 66f74e5..7351d15 100644 --- a/app/Domain/Catalog/ContentService.php +++ b/app/Domain/Catalog/ContentService.php @@ -225,7 +225,9 @@ public function releaseElementVersion(ContentElementVersion $version): ContentEl } /** - * @param list $members + * @param list|null}> $members + * @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic + * @param list $variants Durchführungsvarianten einer Übung */ public function publishComposition( Composition $composition, @@ -233,18 +235,21 @@ public function publishComposition( ?User $confirmedBy = null, ?string $note = null, array $didactic = [], + array $variants = [], ): CompositionVersion { if ($members === []) { throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.'); } + $variants = $this->checkedVariants($variants); $this->assertAcyclic($composition->id, $members); foreach ($members as $member) { $this->assertReadyMember($member['target']); + $this->assertMemberPlacement($member, $variants); } - return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion { + return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): CompositionVersion { $number = ((int) $composition->versions()->max('number')) + 1; $version = $composition->versions()->create([ 'number' => $number, @@ -253,28 +258,49 @@ public function publishComposition( 'resolved_hash' => 'pending', 'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null), 'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null, + 'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null, 'material_note' => $this->optionalText($didactic['material_note'] ?? null), + 'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null), ]); + $variantIds = []; + + foreach ($variants as $index => $variant) { + $variantIds[$variant['key']] = $version->variants()->create([ + 'key' => $variant['key'], + 'position' => $index + 1, + 'name' => $variant['name'], + 'description' => $variant['description'], + ])->id; + } + foreach (array_values($members) as $index => $member) { $target = $member['target']; + $selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null; $version->members()->create([ 'position' => $index + 1, 'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'), 'placement_note' => $this->optionalText($member['note'] ?? null), 'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null, 'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null, + 'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null, + 'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED, + 'variant_selection' => $selection === null ? null : array_values($selection), ]); } + $version->load('members.variant', 'variants'); $resolvedHash = $this->resolver->resolvedHash($version); + $structureHash = $this->structureHash($version); $version->attestations()->create([ 'resolved_hash' => $resolvedHash, + 'structure_hash' => $structureHash, 'confirmed_by' => $confirmedBy?->id, 'confirmed_at' => now(), 'note' => $note, ]); $version->resolved_hash = $resolvedHash; + $version->structure_hash = $structureHash; $version->status = ContentVersionStatus::Bereit; $version->save(); @@ -282,6 +308,101 @@ public function publishComposition( }); } + /** + * Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der + * `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante, + * Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben. + */ + public function structureHash(CompositionVersion $version): string + { + $version->loadMissing('members.variant', 'variants'); + + return hash('sha256', json_encode([ + 'fields' => [ + $version->learning_goal, + $version->duration_minutes, + $version->duration_max, + $version->material_note, + $version->prerequisites, + ], + 'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [ + $variant->key, $variant->position, $variant->name, $variant->description, + ])->all(), + 'members' => $version->members->map(fn (CompositionMember $member): array => [ + $member->position, + $member->role, + $member->placement_note, + $member->content_element_version_id, + $member->nested_composition_version_id, + $member->variant?->key, + $member->requirement, + $member->variant_selection, + ])->all(), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)); + } + + /** + * @param list $variants + * @return list + */ + private function checkedVariants(array $variants): array + { + $checked = []; + $keys = []; + + foreach (array_values($variants) as $variant) { + $key = trim((string) ($variant['key'] ?? '')); + + if ($key === '' || in_array($key, $keys, true)) { + throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.'); + } + + $keys[] = $key; + $checked[] = [ + 'key' => $key, + 'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'), + 'description' => $this->optionalText($variant['description'] ?? null), + ]; + } + + return $checked; + } + + /** + * @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list|null} $member + * @param list $variants + */ + private function assertMemberPlacement(array $member, array $variants): void + { + $variant = $member['variant'] ?? null; + + if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) { + throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.'); + } + + $requirement = $member['requirement'] ?? CompositionMember::REQUIRED; + + if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) { + throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.'); + } + + $selection = $member['selection'] ?? null; + + if ($selection === null) { + return; + } + + if (! $member['target'] instanceof CompositionVersion) { + throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.'); + } + + $offered = $member['target']->variants()->pluck('key')->all(); + + if ($selection === [] || array_diff($selection, $offered) !== []) { + throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.'); + } + } + public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition { return Composition::query()->create([ @@ -369,6 +490,9 @@ private function membersHash(array $members): string 'note' => $this->optionalText($member['note'] ?? null), 'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null, 'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null, + 'variant' => $member['variant'] ?? null, + 'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED, + 'selection' => $member['selection'] ?? null, ]; } diff --git a/app/Domain/Catalog/EditorialContentKind.php b/app/Domain/Catalog/EditorialContentKind.php index 2c12e3a..51dafc9 100644 --- a/app/Domain/Catalog/EditorialContentKind.php +++ b/app/Domain/Catalog/EditorialContentKind.php @@ -17,6 +17,7 @@ class EditorialContentKind extends Model public const CONTEXTS = [ 'medium' => 'Medium', 'modul' => 'Modul', + 'uebung' => 'Übung', 'programm' => 'Programm', 'lizenzartikel' => 'Lizenzartikel', ]; @@ -26,7 +27,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', 'traineranleitung']; + public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung']; protected $fillable = [ 'slug', diff --git a/app/Domain/Catalog/EditorialVocabulary.php b/app/Domain/Catalog/EditorialVocabulary.php index 9aa6a5b..ecde016 100644 --- a/app/Domain/Catalog/EditorialVocabulary.php +++ b/app/Domain/Catalog/EditorialVocabulary.php @@ -46,6 +46,7 @@ public static function compositionContext(?CompositionKind $kind): ?string return match ($kind) { CompositionKind::Kurs => 'programm', CompositionKind::Uebung => 'modul', + CompositionKind::Exercise => 'uebung', default => null, }; } @@ -137,6 +138,7 @@ private function usedKindIds(string $context): array 'lizenzartikel' => DB::table('license_articles'), 'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value), 'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value), + 'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value), default => null, }; diff --git a/app/Domain/Catalog/ExerciseGuide.php b/app/Domain/Catalog/ExerciseGuide.php new file mode 100644 index 0000000..b0eb01a --- /dev/null +++ b/app/Domain/Catalog/ExerciseGuide.php @@ -0,0 +1,183 @@ +license_article_id !== $article->id + || ! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) { + return false; + } + + return Grant::query() + ->where('license_article_id', $article->id) + ->where('status', GrantStatus::Aktiv) + ->usableBy($user) + ->exists(); + } + + /** + * Die Übungsfassung an einer Stelle des Stands. Der Pfad nennt die Positionen der Mitglieder von der Wurzel des + * Stands abwärts („2“ oder „1-3“). So ist auch dieselbe Übung an zwei Stellen eines Produkts unterscheidbar. + * + * @return array{version: CompositionVersion, selection: list|null}|null + */ + public function locate(ArticleRelease $release, string $path): ?array + { + if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) { + return null; + } + + $version = $release->rootCompositionVersion; + $selection = null; + + foreach (array_map('intval', explode('-', $path)) as $position) { + if ($version === null) { + return null; + } + + $member = $version->members()->where('position', $position)->first(); + + if ($member === null || $member->nested_composition_version_id === null) { + return null; + } + + $selection = is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null; + $version = $member->nestedCompositionVersion; + } + + $version?->loadMissing('composition'); + + if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) { + return null; + } + + return ['version' => $version, 'selection' => $selection]; + } + + /** + * Pfad zur ersten Stelle, an der die Wurzel die Übungsfassung einbindet. + */ + public function pathTo(CompositionVersion $root, int $versionId, array $stack = []): ?string + { + if (in_array($root->id, $stack, true)) { + return null; + } + + foreach ($root->members()->orderBy('position')->get() as $member) { + if ($member->nested_composition_version_id === null) { + continue; + } + + if ($member->nested_composition_version_id === $versionId) { + return (string) $member->position; + } + + $below = $this->pathTo($member->nestedCompositionVersion, $versionId, [...$stack, $root->id]); + + if ($below !== null) { + return $member->position.'-'.$below; + } + } + + return null; + } + + /** + * @param list|null $selection angebotene Variantenschlüssel; null = alle + * @return array + */ + public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $exercise, ?array $selection, ?string $variantKey = null): array + { + $exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']); + $library = app(LibraryCatalog::class); + $offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values(); + $chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first(); + $entries = []; + + foreach ($exercise->members as $member) { + $version = $member->contentElementVersion; + + if ($version === null) { + continue; + } + + $key = $member->variant?->key; + $class = (string) $version->element->output_class; + $action = in_array($class, ['film', 'audio'], true) ? 'streamen' : 'ansehen'; + $decision = ($this->access)($user, $article, $release, $version, $action); + $download = $action === 'ansehen' ? ($this->access)($user, $article, $release, $version, 'laden') : null; + + $entries[] = [ + 'variant' => $key, + 'role' => $member->role, + 'note' => $member->placement_note, + 'title' => $library->text($version->element)['title'] ?: $version->element->working_title, + 'class' => $class, + 'requirement' => $member->requirement ?: CompositionMember::REQUIRED, + 'action' => $action, + 'version' => $version, + 'allowed' => $decision->allowed, + 'may_download' => $download?->allowed ?? false, + 'grant' => $decision->grant, + 'download_grant' => $download?->grant, + 'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'), + 'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null, + ]; + } + + $variants = $offered->map(function (CompositionVersionVariant $variant) use ($entries): array { + $missing = array_values(array_filter($entries, fn (array $entry): bool => ($entry['variant'] === null || $entry['variant'] === $variant->key) + && $entry['requirement'] === CompositionMember::REQUIRED + && ! $entry['allowed'])); + + return [ + 'key' => $variant->key, + 'name' => $variant->name, + 'description' => $variant->description, + 'complete' => $missing === [], + 'missing' => array_map(fn (array $entry): string => $entry['title'], $missing), + ]; + })->all(); + + $shown = array_values(array_filter($entries, fn (array $entry): bool => $entry['variant'] === null || $entry['variant'] === $chosen?->key)); + + return [ + 'exercise' => $exercise, + 'title' => $library->text($exercise->composition)['title'], + 'summary' => $library->text($exercise->composition)['summary'], + 'learning_goal' => $exercise->learning_goal, + 'duration_minutes' => $exercise->duration_minutes, + 'duration_max' => $exercise->duration_max, + 'prerequisites' => $exercise->prerequisites, + 'material_note' => $exercise->material_note, + 'variants' => $variants, + 'chosen' => $chosen?->key, + 'entries' => $shown, + 'entry_total' => count($entries), + ]; + } +} diff --git a/app/Domain/Catalog/ExercisePdf.php b/app/Domain/Catalog/ExercisePdf.php new file mode 100644 index 0000000..f016211 --- /dev/null +++ b/app/Domain/Catalog/ExercisePdf.php @@ -0,0 +1,207 @@ + $guide Ergebnis von {@see ExerciseGuide::build} + * @return list>|null + */ + public function sections(array $guide): ?array + { + $included = []; + + foreach ($guide['entries'] as $entry) { + if ($entry['class'] === 'text') { + if ($entry['may_download'] && $entry['allowed']) { + $included[] = $entry; + } elseif ($entry['requirement'] === CompositionMember::REQUIRED) { + return null; + } + + continue; + } + + if ($entry['allowed']) { + $included[] = $entry; + } + } + + return array_filter($included, fn (array $entry): bool => $entry['class'] === 'text') === [] ? null : $included; + } + + /** + * @param array $guide + * @param list> $sections + */ + public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string + { + $this->pdf = new PdfDocument; + $this->page = 0; + $this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId); + $this->newPage(); + + $this->write(self::printable((string) $guide['title']), 18, true, 8); + + if ($variantName !== '') { + $this->write(self::printable('Variante: '.$variantName), 11, true, 6); + } + + $facts = array_filter([ + filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null, + $guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null, + filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null, + filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null, + ]); + + foreach ($facts as $fact) { + $this->write(self::printable($fact), 10.5, false, 4); + } + + $this->y -= 6; + + foreach ($sections as $section) { + $this->section($section, $guideUrl); + } + + $this->closePage(); + + $ascii = Transliterator::create('Any-Latin; Latin-ASCII'); + + return $this->pdf->output($ascii?->transliterate((string) $guide['title']) ?: 'Uebung', 'Lizenzkopie '.$copyId); + } + + /** + * Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere + * lateinische Buchstaben); sonst bleibt „?“. + */ + public static function printable(string $text): string + { + $text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']); + $latin = Transliterator::create('Any-Latin; Latin-ASCII'); + $out = ''; + + foreach (mb_str_split($text) as $char) { + $encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8'); + $out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char; + } + + return $out; + } + + /** + * @param array $section + */ + private function section(array $section, string $guideUrl): void + { + $title = self::printable((string) $section['title']); + + if ($section['class'] !== 'text') { + $label = in_array($section['class'], ['film', 'audio'], true) + ? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl + : 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl; + $this->write(self::printable($label), 10, false, 6); + + return; + } + + $this->write($title, 12.5, true, 5); + + foreach ($section['blocks'] ?? [] as $block) { + match ($block['type']) { + 'heading' => $this->write(self::printable($block['text']), 11, true, 4), + 'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5), + 'bullets' => $this->items($block['items'], fn (int $n): string => '•'), + 'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'), + }; + } + + $this->y -= 4; + } + + /** + * @param list $items + */ + private function items(array $items, callable $marker): void + { + foreach ($items as $index => $item) { + $lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5); + + foreach ($lines as $line => $text) { + $this->room(14); + + if ($line === 0) { + $this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5); + } + + $this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5); + $this->y -= 14; + } + } + + $this->y -= 3; + } + + private function write(string $text, float $size, bool $bold, float $after): void + { + foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) { + $this->room($size + 4); + $this->pdf->text(self::LEFT, $this->y, $line, $size, $bold); + $this->y -= $size + 4; + } + + $this->y -= $after; + } + + private function room(float $needed): void + { + if ($this->y - $needed < self::BOTTOM) { + $this->closePage(); + $this->newPage(); + } + } + + private function newPage(): void + { + $this->pdf->addPage(); + $this->page++; + $this->y = self::TOP; + } + + private function closePage(): void + { + $this->pdf->line(self::LEFT, 54, self::RIGHT, 54, 0.4); + $this->pdf->text(self::LEFT, 40, $this->footer, 8); + $this->pdf->textRight(self::RIGHT, 40, 'Seite '.$this->page, 8); + } +} diff --git a/app/Domain/Catalog/GuideText.php b/app/Domain/Catalog/GuideText.php new file mode 100644 index 0000000..5031762 --- /dev/null +++ b/app/Domain/Catalog/GuideText.php @@ -0,0 +1,85 @@ +}> + */ + public static function blocks(?string $body): array + { + $blocks = []; + $paragraph = []; + $list = null; + + $flushParagraph = function () use (&$blocks, &$paragraph): void { + if ($paragraph !== []) { + $blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)]; + $paragraph = []; + } + }; + $flushList = function () use (&$blocks, &$list): void { + if ($list !== null) { + $blocks[] = ['type' => $list['type'], 'items' => $list['items']]; + $list = null; + } + }; + + foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) { + $line = rtrim($line); + + if (trim($line) === '') { + $flushParagraph(); + $flushList(); + + continue; + } + + if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) { + $flushParagraph(); + $flushList(); + $blocks[] = ['type' => 'heading', 'text' => trim($match[1])]; + + continue; + } + + if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) { + $flushParagraph(); + if ($list === null || $list['type'] !== 'bullets') { + $flushList(); + $list = ['type' => 'bullets', 'items' => []]; + } + + $list['items'][] = trim($match[1]); + + continue; + } + + if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) { + $flushParagraph(); + if ($list === null || $list['type'] !== 'numbered') { + $flushList(); + $list = ['type' => 'numbered', 'items' => []]; + } + + $list['items'][] = trim($match[1]); + + continue; + } + + $flushList(); + $paragraph[] = trim($line); + } + + $flushParagraph(); + $flushList(); + + return $blocks; + } +} diff --git a/app/Domain/Catalog/ReleaseContent.php b/app/Domain/Catalog/ReleaseContent.php index bdb3a4c..3322bee 100644 --- a/app/Domain/Catalog/ReleaseContent.php +++ b/app/Domain/Catalog/ReleaseContent.php @@ -13,6 +13,8 @@ class ReleaseContent extends Model 'content_element_version_id', 'role', 'path', + 'requirement', + 'variant_key', ]; protected static function booted(): void diff --git a/app/Domain/Commerce/Receipt/PdfDocument.php b/app/Domain/Commerce/Receipt/PdfDocument.php index e9fba4f..dabcfd2 100644 --- a/app/Domain/Commerce/Receipt/PdfDocument.php +++ b/app/Domain/Commerce/Receipt/PdfDocument.php @@ -107,7 +107,7 @@ public static function width(string $text, float $size = 10, bool $bold = false) /** * @param string $title Nur ASCII (Dokumenttitel) */ - public function output(string $title): string + public function output(string $title, ?string $keywords = null): string { $pages = $this->pages === [] ? [''] : $this->pages; $objects = []; @@ -125,7 +125,8 @@ public function output(string $title): string $objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>'; $objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'; $objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>'; - $objects[5] = '<< /Title ('.preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $title)).') /Producer (Lara und Felix) >>'; + $ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value)); + $objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>'; ksort($objects); $pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"; diff --git a/app/Domain/Entitlement/MediaDelivery.php b/app/Domain/Entitlement/MediaDelivery.php index 5318898..3ca11d4 100644 --- a/app/Domain/Entitlement/MediaDelivery.php +++ b/app/Domain/Entitlement/MediaDelivery.php @@ -16,6 +16,7 @@ class MediaDelivery extends Model 'copy_id', 'checksum', 'marking', + 'composition_version_id', 'delivered_at', ]; diff --git a/app/Domain/Media/DeliveryLog.php b/app/Domain/Media/DeliveryLog.php index 1f08038..8d3e7ef 100644 --- a/app/Domain/Media/DeliveryLog.php +++ b/app/Domain/Media/DeliveryLog.php @@ -19,6 +19,8 @@ public function write( string $format, ?string $checksum, string $marking, + ?string $copyId = null, + ?int $compositionVersionId = null, ): MediaDelivery { return MediaDelivery::query()->create([ 'grant_id' => $grant->id, @@ -27,10 +29,16 @@ public function write( 'content_element_version_id' => $version->id, 'action' => $action, 'format' => $format, - 'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))), + 'copy_id' => $copyId ?? self::newCopyId(), + 'composition_version_id' => $compositionVersionId, 'checksum' => $checksum, 'marking' => $marking, 'delivered_at' => now(), ]); } + + public static function newCopyId(): string + { + return 'LK-'.strtoupper(bin2hex(random_bytes(6))); + } } diff --git a/app/Http/Controllers/Member/ExerciseController.php b/app/Http/Controllers/Member/ExerciseController.php new file mode 100644 index 0000000..91b53b1 --- /dev/null +++ b/app/Http/Controllers/Member/ExerciseController.php @@ -0,0 +1,124 @@ +load($request, $article, $release, $path); + $user = $request->user(); + $copy = DeliveryLog::newCopyId(); + $shown = false; + + foreach ($guide['entries'] as $index => $entry) { + $link = fn (string $action) => SignedLink::temporary('member.media', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'version' => $entry['version']->id, + 'action' => $action, + 'reader' => $user->id, + ]); + $guide['entries'][$index]['url'] = $entry['allowed'] && $entry['class'] !== 'text' ? $link($entry['action']) : null; + $guide['entries'][$index]['download_url'] = $entry['allowed'] && $entry['may_download'] && $entry['class'] !== 'text' ? $link('laden') : null; + + if ($entry['allowed'] && $entry['class'] === 'text' && $entry['grant'] !== null) { + app(DeliveryLog::class)->write($entry['grant'], $article, $release, $entry['version'], 'ansehen', 'text', hash('sha256', (string) $entry['version']->body), 'k2', $copy, $located['version']->id); + $shown = true; + } + } + + $pdfAllowed = app(ExercisePdf::class)->sections($guide) !== null; + + return view('member.exercise', [ + 'guide' => $guide, + 'article' => $article, + 'release' => $release, + 'path' => $path, + 'reader' => $user->name, + 'copy' => $shown ? $copy : null, + 'pdfUrl' => $pdfAllowed ? SignedLink::temporary('member.exercise.pdf', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'path' => $path, + 'variante' => $guide['chosen'], + 'reader' => $user->id, + ]) : null, + 'variantUrl' => fn (string $key): string => route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $key]), + ]); + } + + 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); + $pdf = app(ExercisePdf::class); + $sections = $pdf->sections($guide); + abort_if($sections === null, 403, 'Für dieses PDF fehlt die Berechtigung oder ein erforderlicher Bestandteil.'); + + $copy = DeliveryLog::newCopyId(); + $variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']); + $content = $pdf->render( + $guide, + $sections, + $request->user()->name, + $copy, + (string) ($variant['name'] ?? ''), + route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]), + ); + $checksum = hash('sha256', $content); + + foreach ($sections as $section) { + $grant = $section['download_grant'] ?? $section['grant']; + + if ($grant !== null) { + app(DeliveryLog::class)->write($grant, $article, $release, $section['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id); + } + } + + $name = str($guide['title'])->slug()->value() ?: 'uebung'; + + return response($content, 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'attachment; filename="'.$name.'.pdf"', + 'X-License-Copy' => $copy, + 'Cache-Control' => 'private, no-store', + ]); + } + + /** + * @return array{0: array, 1: array{version: CompositionVersion, selection: list|null}} + */ + private function load(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): array + { + $guides = app(ExerciseGuide::class); + abort_unless($guides->mayOpen($request->user(), $article, $release), 403); + $located = $guides->locate($release, $path); + abort_if($located === null, 404); + + $variant = $request->query('variante'); + + return [ + $guides->build($request->user(), $article, $release, $located['version'], $located['selection'], is_string($variant) ? $variant : null), + $located, + ]; + } +} diff --git a/database/migrations/2026_11_26_100000_add_exercises.php b/database/migrations/2026_11_26_100000_add_exercises.php new file mode 100644 index 0000000..70fe72a --- /dev/null +++ b/database/migrations/2026_11_26_100000_add_exercises.php @@ -0,0 +1,90 @@ +unsignedInteger('duration_max')->nullable(); + $table->text('prerequisites')->nullable(); + // Änderungsnachweis über Felder, Varianten und Verwendungen; resolved_hash deckt nur die Medienmenge ab. + $table->string('structure_hash')->nullable(); + }); + + Schema::table('compatibility_attestations', function (Blueprint $table) { + $table->string('structure_hash')->nullable(); + }); + + Schema::create('composition_version_variants', function (Blueprint $table) { + $table->id(); + $table->foreignId('composition_version_id')->constrained()->cascadeOnDelete(); + $table->string('key'); + $table->unsignedInteger('position'); + $table->string('name'); + $table->text('description')->nullable(); + $table->timestamps(); + + $table->unique(['composition_version_id', 'key']); + $table->unique(['composition_version_id', 'position']); + }); + + Schema::table('composition_members', function (Blueprint $table) { + $table->foreignId('variant_id')->nullable()->constrained('composition_version_variants')->restrictOnDelete(); + $table->string('requirement')->default('erforderlich'); + $table->json('variant_selection')->nullable(); + }); + + Schema::table('release_contents', function (Blueprint $table) { + $table->string('requirement')->nullable(); + $table->string('variant_key')->nullable(); + }); + + Schema::table('media_deliveries', function (Blueprint $table) { + $table->unsignedBigInteger('composition_version_id')->nullable(); + }); + + $now = now(); + DB::table('editorial_content_kinds')->insertOrIgnore([ + 'slug' => 'uebung', + 'label' => 'Übung', + 'sort_order' => 25, + 'is_active' => true, + 'contexts' => json_encode(['uebung', 'lizenzartikel']), + 'created_at' => $now, + 'updated_at' => $now, + ]); + } + + public function down(): void + { + DB::table('editorial_content_kinds')->where('slug', 'uebung')->delete(); + + Schema::table('media_deliveries', function (Blueprint $table) { + $table->dropColumn('composition_version_id'); + }); + Schema::table('release_contents', function (Blueprint $table) { + $table->dropColumn(['requirement', 'variant_key']); + }); + Schema::table('composition_members', function (Blueprint $table) { + $table->dropConstrainedForeignId('variant_id'); + $table->dropColumn(['requirement', 'variant_selection']); + }); + Schema::dropIfExists('composition_version_variants'); + Schema::table('compatibility_attestations', function (Blueprint $table) { + $table->dropColumn('structure_hash'); + }); + Schema::table('composition_versions', function (Blueprint $table) { + $table->dropColumn(['duration_max', 'prerequisites', 'structure_hash']); + }); + } +}; diff --git a/resources/views/member/exercise.blade.php b/resources/views/member/exercise.blade.php new file mode 100644 index 0000000..c8e795f --- /dev/null +++ b/resources/views/member/exercise.blade.php @@ -0,0 +1,106 @@ +@extends('layouts.member') + +@section('title', $guide['title']) +@section('nav', 'bibliothek') + +{{-- + Übung als formatierte Anleitung im erworbenen Stand. Gezeigt wird die im Stand gebundene Fassung mit den dort + angebotenen Varianten. Über jeden Abschnitt und jedes Medium entscheidet die zentrale Rechteprüfung: Was fehlt oder + gesperrt ist, erscheint als Hinweis an seiner Stelle, die übrige Anleitung bleibt lesbar. +--}} +@section('content') +

+
+
+

{{ $guide['title'] }}

+ @if (filled($guide['summary'])) +

{{ $guide['summary'] }}

+ @endif +
+ + @if (filled($copy ?? null)) +

Lizenziert für {{ $reader }} · Lizenzkopie {{ $copy }}

+ @endif + +
+ @if (filled($guide['learning_goal'])) +
Lernziel
{{ $guide['learning_goal'] }}
+ @endif + @if ($guide['duration_minutes'] !== null) +
Dauer
{{ $guide['duration_minutes'] }}@if ($guide['duration_max'] !== null) bis {{ $guide['duration_max'] }}@endif Minuten
+ @endif + @if (filled($guide['prerequisites'])) +
Voraussetzungen
{{ $guide['prerequisites'] }}
+ @endif + @if (filled($guide['material_note'])) +
Ausstattung
{{ $guide['material_note'] }}
+ @endif +
+ + @if (count($guide['variants']) > 1) + + @endif + + @foreach ($guide['variants'] as $variant) + @if ($guide['chosen'] === $variant['key']) + @if (filled($variant['description'])) +

{{ $variant['description'] }}

+ @endif + @unless ($variant['complete']) +

+ Diese Variante ist derzeit nicht vollständig durchführbar: {{ implode(', ', $variant['missing']) }} ist nicht verfügbar. + @if (count($guide['variants']) > 1) Eine andere Variante steht weiter zur Verfügung. @endif +

+ @endunless + @endif + @endforeach + + @foreach ($guide['entries'] as $entry) +
+ @if ($entry['allowed'] && $entry['class'] === 'text') +

{{ $entry['title'] }}

+
+ @include('member.partials.guide-blocks', ['blocks' => $entry['blocks']]) +
+ @elseif ($entry['allowed']) +

{{ $entry['title'] }}

+

+ + {{ in_array($entry['class'], ['film', 'audio'], true) ? 'Ansehen' : 'Öffnen' }} + + @if ($entry['download_url']) + Herunterladen + @endif +

+ @elseif ($entry['requirement'] === 'ergaenzend') +

+ {{ $entry['title'] }}: Dieses ergänzende Material ist derzeit nicht verfügbar. Die Übung bleibt vollständig durchführbar. +

+ @else +

+ {{ $entry['title'] }}: Dieser Bestandteil ist derzeit nicht verfügbar. +

+ @endif +
+ @endforeach + +

+ @if ($pdfUrl) + + @else + Ein PDF ist für diese Lizenz oder derzeit nicht verfügbar. + @endif +

+
+@endsection diff --git a/resources/views/member/partials/guide-blocks.blade.php b/resources/views/member/partials/guide-blocks.blade.php new file mode 100644 index 0000000..1f00d05 --- /dev/null +++ b/resources/views/member/partials/guide-blocks.blade.php @@ -0,0 +1,23 @@ +@foreach ($blocks as $block) + @switch ($block['type']) + @case ('heading') +

{{ $block['text'] }}

+ @break + @case ('bullets') +
    + @foreach ($block['items'] as $item) +
  • {{ $item }}
  • + @endforeach +
+ @break + @case ('numbered') +
    + @foreach ($block['items'] as $item) +
  1. {{ $item }}
  2. + @endforeach +
+ @break + @default +

{{ $block['text'] }}

+ @endswitch +@endforeach diff --git a/routes/web.php b/routes/web.php index 5f15948..68cb9dd 100644 --- a/routes/web.php +++ b/routes/web.php @@ -8,6 +8,7 @@ use App\Http\Controllers\ContentPreviewController; use App\Http\Controllers\EditorialPreviewController; use App\Http\Controllers\Member\CheckoutController; +use App\Http\Controllers\Member\ExerciseController; use App\Http\Controllers\Member\LibraryController; use App\Http\Controllers\Member\MemberController; use App\Http\Controllers\Member\PaymentController; @@ -127,6 +128,13 @@ Route::get('/ausgabe/{article}/{release}/{version}/{action}', [LibraryController::class, 'media']) ->middleware('signed:relative') ->name('media'); + Route::get('/stand/{article}/{release}/uebung/{path}', [ExerciseController::class, 'show']) + ->where('path', '[0-9]+(?:-[0-9]+)*') + ->name('exercise'); + Route::get('/stand/{article}/{release}/uebung/{path}/pdf', [ExerciseController::class, 'pdf']) + ->where('path', '[0-9]+(?:-[0-9]+)*') + ->middleware('signed:relative') + ->name('exercise.pdf'); Route::get('/abschnitt/{article}/{release}/{version}/{datei}', [LibraryController::class, 'rendition']) ->where('datei', '.*') ->middleware('signed:relative') diff --git a/tests/Feature/RueckfallschutzTest.php b/tests/Feature/RueckfallschutzTest.php index 0905284..8bf3612 100644 --- a/tests/Feature/RueckfallschutzTest.php +++ b/tests/Feature/RueckfallschutzTest.php @@ -36,7 +36,7 @@ class RueckfallschutzTest extends TestCase { use RefreshDatabase; - private const FOREIGN = 'exercise'; + private const FOREIGN = 'art_von_morgen'; private ContentElementVersion $filmA; @@ -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'], CompositionKind::values()); + $this->assertSame(['kombination', 'uebung', 'kurs', 'exercise'], CompositionKind::values()); + $this->assertNotContains(self::FOREIGN, CompositionKind::values()); } public function test_a_composition_of_an_unknown_kind_does_not_crash_loading_and_stays_hidden(): void diff --git a/tests/Feature/UebungAusgabeTest.php b/tests/Feature/UebungAusgabeTest.php new file mode 100644 index 0000000..1e09b9b --- /dev/null +++ b/tests/Feature/UebungAusgabeTest.php @@ -0,0 +1,296 @@ + */ + private array $exercise; + + private LicenseArticle $moduleArticle; + + private ArticleRelease $moduleRelease; + + private LicenseArticle $programArticle; + + private ArticleRelease $programRelease; + + private User $member; + + protected function setUp(): void + { + parent::setUp(); + + $this->exercise = $this->exercise(); + $module = $this->moduleWith('Modul Stopp', $this->exercise['version'], ['a']); + $program = $this->moduleWith('Programm Stopp', $this->exercise['version'], ['b'], CompositionKind::Kurs); + $articles = app(ArticleService::class); + $this->moduleArticle = $articles->create('modul-stopp'); + $this->moduleRelease = $articles->publishRelease($this->moduleArticle, $module, 'Modul.'); + $this->programArticle = $articles->create('programm-stopp'); + $this->programRelease = $articles->publishRelease($this->programArticle, $program, 'Programm.'); + $this->member = $this->grantTo($this->full(), [$this->moduleArticle, $this->programArticle]); + } + + public function test_the_trainer_reads_the_bound_version_with_the_offered_variant_only(): void + { + $this->actingAs($this->member) + ->get($this->page($this->moduleArticle, $this->moduleRelease)) + ->assertOk() + ->assertSee('Stopp sagen') + ->assertSee('Nein sagen und Abstand halten') + ->assertSee('Sicher stehen') + ->assertSee('Variante A: Der Film zeigt die Situation.') + ->assertSee('Lizenzkopie LK-') + ->assertDontSee('Variante B: Ohne Film mit dem Arbeitsblatt.') + ->assertSee('Als PDF herunterladen'); + + $this->actingAs($this->member) + ->get($this->page($this->programArticle, $this->programRelease)) + ->assertOk() + ->assertSee('Variante B: Ohne Film mit dem Arbeitsblatt.') + ->assertDontSee('Variante A: Der Film zeigt die Situation.'); + } + + public function test_the_pdf_carries_the_same_version_the_marking_and_the_delivery_record(): void + { + $response = $this->actingAs($this->member)->get($this->pdf($this->moduleArticle, $this->moduleRelease, 'a')); + + $response->assertOk()->assertHeader('Content-Type', 'application/pdf'); + $this->assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control')); + $text = $this->pdfText($response->getContent()); + + $this->assertStringContainsString('Stopp sagen', $text); + $this->assertStringContainsString('Variante A: Der Film zeigt die Situation.', $text); + $this->assertStringContainsString('Sicher stehen', $text); + $this->assertStringNotContainsString('Variante B:', $text); + $this->assertStringContainsString('Lizenziert für '.$this->member->name.' · Lizenzkopie LK-', $text); + $this->assertStringContainsString('Seite 1', $text); + $this->assertStringContainsString('Lizenzkopie '.$response->headers->get('X-License-Copy'), $response->getContent(), 'Die Kennung steht auch in den Metadaten.'); + + $rows = MediaDelivery::query()->where('format', 'pdf')->get(); + $this->assertNotEmpty($rows); + $this->assertSame(['k2'], $rows->pluck('marking')->unique()->all()); + $this->assertSame(['laden'], $rows->pluck('action')->unique()->all()); + $this->assertSame($this->exercise['version']->id, $rows->first()->composition_version_id); + $this->assertSame(hash('sha256', $response->getContent()), $rows->first()->checksum); + } + + public function test_the_pdf_runs_over_several_pages_and_keeps_special_characters_readable(): void + { + $content = app(ContentService::class); + $long = implode("\n\n", array_map(fn (int $n): string => "Absatz $n: ".str_repeat('Abstand halten und Stopp sagen. ', 12), range(1, 30))); + $text = $this->section('Lang', "Gewaltprävention → Stopp ≥ 2 m Abstand; Łódź, naïve «Café».\n\n## Ablauf\n\n1. Erst aufwärmen\n2. Dann üben\n\n- Matten\n- Pratzen\n\n".$long); + $composition = $this->exerciseComposition('Lange Übung'); + $version = $content->publishComposition($composition, [['role' => 'Durchführung', 'target' => $text]], null, null, ['learning_goal' => 'Lang']); + $module = $this->moduleWith('Modul lang', $version); + $articles = app(ArticleService::class); + $article = $articles->create('lang'); + $release = $articles->publishRelease($article, $module, 'Lang.'); + $member = $this->grantTo($this->full(), [$article]); + + $response = $this->actingAs($member)->get($this->pdf($article, $release, null, $member)); + $response->assertOk(); + $pdf = $this->pdfText($response->getContent()); + + $this->assertGreaterThan(2, substr_count($response->getContent(), '/Type /Page /Parent')); + $this->assertStringContainsString('Seite 1', $pdf); + $this->assertStringContainsString('Seite 3', $pdf); + $this->assertStringContainsString('Gewaltprävention -> Stopp >= 2 m Abstand', $pdf); + $this->assertStringContainsString('Lódz', $pdf); + $this->assertStringContainsString('Ablauf', $pdf); + $this->assertStringContainsString('1. +Erst aufwärmen', $pdf); + $this->assertStringContainsString('•', $pdf); + $this->assertSame(substr_count($response->getContent(), '/Type /Page /Parent'), preg_match_all('/Lizenzkopie LK-[0-9A-F]{12}/', $pdf), 'Jede Seite trägt die Fußzeile.'); + } + + public function test_an_account_without_a_license_gets_neither_the_guide_nor_the_pdf(): void + { + $stranger = User::factory()->create(); + + $this->actingAs($stranger)->get($this->page($this->moduleArticle, $this->moduleRelease))->assertForbidden(); + $this->actingAs($stranger)->get($this->pdf($this->moduleArticle, $this->moduleRelease, 'a', $stranger))->assertForbidden(); + $this->actingAs($this->member)->get(route('member.exercise.pdf', ['article' => $this->moduleArticle, 'release' => $this->moduleRelease, 'path' => '1']))->assertForbidden(); + } + + public function test_without_the_download_right_the_guide_is_readable_but_the_pdf_is_refused(): void + { + $readOnly = $this->grantTo($this->profile(['film' => ['streamen'], 'text' => ['ansehen'], 'document' => ['ansehen']]), [$this->moduleArticle]); + + $this->actingAs($readOnly) + ->get($this->page($this->moduleArticle, $this->moduleRelease)) + ->assertOk() + ->assertSee('Variante A: Der Film zeigt die Situation.') + ->assertDontSee('Als PDF herunterladen'); + $this->actingAs($readOnly)->get($this->pdf($this->moduleArticle, $this->moduleRelease, 'a', $readOnly))->assertForbidden(); + } + + public function test_a_supplementary_medium_that_is_blocked_leaves_the_guide_and_the_pdf_usable(): void + { + app(ContentService::class)->block($this->exercise['sheetB'], 'Rechte zurückgezogen.'); + + $this->actingAs($this->member) + ->get($this->page($this->programArticle, $this->programRelease)) + ->assertOk() + ->assertSee('Variante B: Ohne Film mit dem Arbeitsblatt.') + ->assertSee('Dieses ergänzende Material ist derzeit nicht verfügbar') + ->assertDontSee('derzeit nicht vollständig durchführbar'); + + $pdf = $this->pdfText($this->actingAs($this->member)->get($this->pdf($this->programArticle, $this->programRelease, 'b'))->assertOk()->getContent()); + $this->assertStringContainsString('Variante B: Ohne Film mit dem Arbeitsblatt.', $pdf); + $this->assertStringNotContainsString('Arbeitsblatt B', $pdf); + + $direct = SignedLink::temporary('member.media', now()->addMinutes(10), [ + 'article' => $this->programArticle->id, + 'release' => $this->programRelease->id, + 'version' => $this->exercise['sheetB']->id, + 'action' => 'ansehen', + 'reader' => $this->member->id, + ]); + $this->actingAs($this->member)->get($direct)->assertForbidden(); + } + + public function test_a_required_medium_that_is_blocked_marks_only_its_variant_and_keeps_the_instructions(): void + { + $everything = $this->moduleWith('Modul alle', $this->exercise['version']); + $articles = app(ArticleService::class); + $article = $articles->create('alle'); + $release = $articles->publishRelease($article, $everything, 'Alle Varianten.'); + $member = $this->grantTo($this->full(), [$article]); + + app(ContentService::class)->block($this->exercise['filmA'], 'Rechte zurückgezogen.'); + + $this->actingAs($member) + ->get($this->page($article, $release)) + ->assertOk() + ->assertSee('Variante A: Der Film zeigt die Situation.') + ->assertSee('Diese Variante ist derzeit nicht vollständig durchführbar') + ->assertSee('Stopp sagen · Film A ist nicht verfügbar'); + + $this->actingAs($member) + ->get($this->page($article, $release).'?variante=b') + ->assertOk() + ->assertSee('Variante B: Ohne Film mit dem Arbeitsblatt.') + ->assertDontSee('Diese Variante ist derzeit nicht vollständig durchführbar'); + + $this->actingAs($member)->get($this->pdf($article, $release, 'a', $member))->assertOk(); + $direct = SignedLink::temporary('member.media', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'version' => $this->exercise['filmA']->id, + 'action' => 'streamen', + 'reader' => $member->id, + ]); + $this->actingAs($member)->get($direct)->assertForbidden(); + } + + public function test_the_stand_keeps_what_was_chosen_when_a_newer_exercise_version_appears(): void + { + $content = app(ContentService::class); + $revised = $content->publishElementVersion($this->exercise['textA']->element, 'Variante A, später überarbeitet.'); + $content->publishComposition($this->exercise['version']->composition, [ + ['role' => 'Durchführung A', 'target' => $revised, 'variant' => 'a'], + ], null, null, ['learning_goal' => 'Neu'], [['key' => 'a', 'name' => 'Mit Film']]); + + $this->actingAs($this->member) + ->get($this->page($this->moduleArticle, $this->moduleRelease)) + ->assertOk() + ->assertSee('Variante A: Der Film zeigt die Situation.') + ->assertDontSee('später überarbeitet') + ->assertSee('Nein sagen und Abstand halten'); + } + + public function test_a_wrong_path_is_not_found(): void + { + $this->actingAs($this->member)->get(route('member.exercise', ['article' => $this->moduleArticle, 'release' => $this->moduleRelease, 'path' => '7']))->assertNotFound(); + $this->actingAs($this->member)->get(route('member.exercise', ['article' => $this->moduleArticle, 'release' => $this->programRelease, 'path' => '1']))->assertForbidden(); + } + + public function test_the_path_finds_the_place_even_when_the_exercise_sits_deeper(): void + { + $inner = $this->moduleWith('Innen', $this->exercise['version'], ['a']); + $outer = $this->moduleWith('Außen', $inner, null, CompositionKind::Kurs); + $guide = app(ExerciseGuide::class); + + $this->assertSame('1-1', $guide->pathTo($outer, $this->exercise['version']->id)); + $this->assertNull($guide->pathTo($outer, 999999)); + } + + private function page(LicenseArticle $article, ArticleRelease $release): string + { + return route('member.exercise', ['article' => $article, 'release' => $release, 'path' => '1']); + } + + private function pdf(LicenseArticle $article, ArticleRelease $release, ?string $variant, ?User $reader = null): string + { + return SignedLink::temporary('member.exercise.pdf', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'path' => '1', + 'variante' => $variant, + 'reader' => ($reader ?? $this->member)->id, + ]); + } + + private function full(): RightsProfileVersion + { + return $this->profile(['film' => ['streamen', 'laden'], 'text' => ['ansehen', 'laden'], 'document' => ['ansehen', 'laden']]); + } + + /** + * @param array> $capabilities + */ + private function profile(array $capabilities): RightsProfileVersion + { + return app(OfferService::class)->createRightsProfile('Profil '.md5(json_encode($capabilities)), 'ehrenamtlich', $capabilities); + } + + /** + * @param list $articles + */ + private function grantTo(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; + } + + /** Text der Seiten aus dem unkomprimierten Inhalt; Windows-1252 wird nach UTF-8 gewandelt. */ + private function pdfText(string $pdf): string + { + preg_match_all('/Td \((.*)\) Tj ET$/m', $pdf, $matches); + + return implode("\n", array_map( + fn (string $line): string => mb_convert_encoding(str_replace(['\\(', '\\)', '\\\\'], ['(', ')', '\\'], $line), 'UTF-8', 'Windows-1252'), + $matches[1], + )); + } +} diff --git a/tests/Feature/UebungFassungTest.php b/tests/Feature/UebungFassungTest.php new file mode 100644 index 0000000..bda3f93 --- /dev/null +++ b/tests/Feature/UebungFassungTest.php @@ -0,0 +1,166 @@ +exercise(); + $version = $exercise['version']->fresh(['variants', 'members.variant']); + + $this->assertSame(CompositionKind::Exercise, $version->composition->kind); + $this->assertSame(['a', 'b'], $version->variants->pluck('key')->all()); + $this->assertSame(20, $version->duration_max); + $this->assertSame('Keine', $version->prerequisites); + $this->assertNull($version->members[0]->variant, 'Der Einstieg ist gemeinsam.'); + $this->assertSame('a', $version->members[2]->variant->key); + $this->assertSame('ergaenzend', $version->members[4]->requirement); + $this->assertNotNull($version->structure_hash); + $this->assertSame($version->structure_hash, $version->attestations()->first()->structure_hash); + } + + public function test_the_selection_decides_which_media_a_stand_freezes(): void + { + $exercise = $this->exercise(); + $withFilm = $this->moduleWith('Modul mit Film', $exercise['version'], ['a']); + $withoutFilm = $this->moduleWith('Modul ohne Film', $exercise['version'], ['b']); + $articles = app(ArticleService::class); + $first = $articles->publishRelease($articles->create('mit-film'), $withFilm, 'Filmvariante.'); + $second = $articles->publishRelease($articles->create('ohne-film'), $withoutFilm, 'Variante ohne Film.'); + + $this->assertEqualsCanonicalizing( + [$exercise['intro']->id, $exercise['textA']->id, $exercise['filmA']->id], + $first->contents->pluck('content_element_version_id')->all(), + ); + $this->assertEqualsCanonicalizing( + [$exercise['intro']->id, $exercise['textB']->id, $exercise['sheetB']->id], + $second->contents->pluck('content_element_version_id')->all(), + ); + $this->assertSame( + ['erforderlich', 'ergaenzend'], + $second->contents->whereIn('content_element_version_id', [$exercise['textB']->id, $exercise['sheetB']->id])->sortBy('position')->pluck('requirement')->map(fn ($r, $i) => $i === 0 ? 'erforderlich' : $r)->values()->all(), + ); + $this->assertSame('ergaenzend', $second->contents->firstWhere('content_element_version_id', $exercise['sheetB']->id)->requirement); + $this->assertSame('b', $second->contents->firstWhere('content_element_version_id', $exercise['sheetB']->id)->variant_key); + $this->assertNull($second->contents->firstWhere('content_element_version_id', $exercise['intro']->id)->variant_key); + } + + public function test_without_a_selection_all_variants_are_offered(): void + { + $exercise = $this->exercise(); + $all = $this->moduleWith('Modul mit allen', $exercise['version']); + + $this->assertCount(5, app(ContentResolver::class)->expand($all)); + } + + public function test_the_same_medium_in_the_common_part_and_a_variant_and_directly_in_the_product_is_frozen_each_time(): void + { + $content = app(ContentService::class); + $film = $this->film('Demonstration'); + $composition = $this->exerciseComposition('Doppelt'); + $exercise = $content->publishComposition($composition, [ + ['role' => 'Einstieg', 'target' => $film], + ['role' => 'Film in A', 'target' => $film, 'variant' => 'a'], + ['role' => 'Film in B', 'target' => $film, 'variant' => 'b'], + ], null, null, [], [['key' => 'a', 'name' => 'A'], ['key' => 'b', 'name' => 'B']]); + $module = $this->moduleWith('Modul', $exercise, ['a'], CompositionKind::Uebung, $film); + $articles = app(ArticleService::class); + $release = $articles->publishRelease($articles->create('doppelt'), $module, 'Mehrfach.'); + + $this->assertSame([$film->id, $film->id, $film->id], $release->contents->pluck('content_element_version_id')->all()); + $this->assertSame([null, 'a', null], $release->contents->pluck('variant_key')->all()); + } + + public function test_the_structure_hash_notices_what_the_media_set_does_not(): void + { + $content = app(ContentService::class); + $film = $this->film('Gleicher Film'); + $composition = $this->exerciseComposition('Hash'); + $variants = [['key' => 'a', 'name' => 'A']]; + $first = $content->publishComposition($composition, [['role' => 'Film', 'target' => $film, 'variant' => 'a', 'requirement' => 'erforderlich']], null, null, [], $variants); + $second = $content->publishComposition($composition, [['role' => 'Film', 'target' => $film, 'variant' => 'a', 'requirement' => 'ergaenzend']], null, null, [], $variants); + $third = $content->publishComposition($composition, [['role' => 'Film', 'target' => $film]], null, null, [], $variants); + + $this->assertSame($first->resolved_hash, $second->resolved_hash); + $this->assertSame($first->resolved_hash, $third->resolved_hash); + $this->assertCount(3, array_unique([$first->structure_hash, $second->structure_hash, $third->structure_hash])); + } + + public function test_two_stands_keep_different_versions_of_the_same_exercise(): void + { + $content = app(ContentService::class); + $exercise = $this->exercise(); + $moduleV1 = $this->moduleWith('Modul eins', $exercise['version'], ['a']); + $revisedText = $content->publishElementVersion($exercise['textA']->element, 'Variante A, überarbeitet.'); + $secondVersion = $content->publishComposition($exercise['version']->composition, [ + ['role' => 'Einstieg', 'target' => $exercise['intro']], + ['role' => 'Durchführung A', 'target' => $revisedText, 'variant' => 'a'], + ['role' => 'Film A', 'target' => $exercise['filmA'], 'variant' => 'a'], + ], null, null, ['learning_goal' => 'Neu gefasst'], [['key' => 'a', 'name' => 'Mit Film']]); + $moduleV2 = $this->moduleWith('Modul zwei', $secondVersion, ['a']); + + $articles = app(ArticleService::class); + $one = $articles->publishRelease($articles->create('eins'), $moduleV1, 'Alte Übung.'); + $two = $articles->publishRelease($articles->create('zwei'), $moduleV2, 'Neue Übung.'); + + $this->assertContains($exercise['textA']->id, $one->contents->pluck('content_element_version_id')->all()); + $this->assertNotContains($revisedText->id, $one->contents->pluck('content_element_version_id')->all()); + $this->assertContains($revisedText->id, $two->contents->pluck('content_element_version_id')->all()); + $this->assertSame('Nein sagen und Abstand halten', $exercise['version']->fresh()->learning_goal); + $this->assertSame(2, $exercise['version']->composition->versions()->count()); + } + + public function test_a_published_exercise_version_and_its_variants_stay_unchanged(): void + { + $exercise = $this->exercise(); + + $this->expectException(DomainRuleException::class); + $exercise['version']->variants()->first()->update(['name' => 'Anders']); + } + + public function test_invalid_placements_are_refused(): void + { + $content = app(ContentService::class); + $film = $this->film('Film'); + $composition = $this->exerciseComposition('Prüfung'); + $variants = [['key' => 'a', 'name' => 'A']]; + + foreach ([ + [['role' => 'x', 'target' => $film, 'variant' => 'zzz'], $variants], + [['role' => 'x', 'target' => $film, 'requirement' => 'vielleicht'], $variants], + [['role' => 'x', 'target' => $film, 'selection' => ['a']], $variants], + ] as [$member, $declared]) { + try { + $content->publishComposition($composition, [$member], null, null, [], $declared); + $this->fail('Eine ungültige Zuordnung wurde angenommen.'); + } catch (DomainRuleException) { + $this->addToAssertionCount(1); + } + } + + $exercise = $this->exercise('Andere'); + $module = $this->exerciseComposition('Wirt'); + + foreach ([['zzz'], []] as $selection) { + try { + $content->publishComposition($module, [['role' => 'Übung', 'target' => $exercise['version'], 'selection' => $selection]]); + $this->fail('Eine ungültige Variantenauswahl wurde angenommen.'); + } catch (DomainRuleException) { + $this->addToAssertionCount(1); + } + } + } +} diff --git a/tests/Support/BuildsExercises.php b/tests/Support/BuildsExercises.php new file mode 100644 index 0000000..a5ab08a --- /dev/null +++ b/tests/Support/BuildsExercises.php @@ -0,0 +1,93 @@ +publishElementVersion($content->createElement('film', 'film', $title), null, ['file' => $file]); + } + + protected function sheet(string $title): ContentElementVersion + { + $content = app(ContentService::class); + + return $content->publishElementVersion($content->createElement('document', 'document', $title), null, ['file' => 'inhalte/'.str($title)->slug().'.pdf']); + } + + protected function section(string $title, string $body): ContentElementVersion + { + $content = app(ContentService::class); + + return $content->publishElementVersion($content->createElement('text', 'text', $title), $body); + } + + /** + * Übung mit gemeinsamem Einstieg und zwei Varianten: A mit Film, B ohne Film (nur Arbeitsblatt). + * + * @return array{version: CompositionVersion, intro: ContentElementVersion, filmA: ContentElementVersion, sheetB: ContentElementVersion, textA: ContentElementVersion, textB: ContentElementVersion} + */ + protected function exercise(string $title = 'Stopp sagen', ?Composition $composition = null): array + { + $content = app(ContentService::class); + $intro = $this->section($title.' · Einstieg', "Gemeinsamer Einstieg.\n\n- Sicher stehen\n- Deutlich sprechen"); + $filmA = $this->film($title.' · Film A'); + $sheetB = $this->sheet($title.' · Arbeitsblatt B'); + $textA = $this->section($title.' · Durchführung A', 'Variante A: Der Film zeigt die Situation.'); + $textB = $this->section($title.' · Durchführung B', 'Variante B: Ohne Film mit dem Arbeitsblatt.'); + $composition ??= $this->exerciseComposition($title); + + $version = $content->publishComposition($composition, [ + ['role' => 'Einstieg', 'target' => $intro], + ['role' => 'Durchführung A', 'target' => $textA, 'variant' => 'a'], + ['role' => 'Film A', 'target' => $filmA, 'variant' => 'a', 'requirement' => 'erforderlich'], + ['role' => 'Durchführung B', 'target' => $textB, 'variant' => 'b'], + ['role' => 'Arbeitsblatt B', 'target' => $sheetB, 'variant' => 'b', 'requirement' => 'ergaenzend'], + ], null, null, ['learning_goal' => 'Nein sagen und Abstand halten', 'duration_minutes' => 15, 'duration_max' => 20, 'prerequisites' => 'Keine'], [ + ['key' => 'a', 'name' => 'Mit Film', 'description' => 'Einstieg über den Film'], + ['key' => 'b', 'name' => 'Ohne Film', 'description' => 'Nur mit Arbeitsblatt'], + ]); + + return compact('version', 'intro', 'filmA', 'sheetB', 'textA', 'textB'); + } + + protected function exerciseComposition(string $title): Composition + { + $composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise); + $composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id'); + $composition->save(); + + return $composition; + } + + /** + * @param list|null $selection + */ + protected function moduleWith(string $title, CompositionVersion $exercise, ?array $selection = null, CompositionKind $kind = CompositionKind::Uebung, ?ContentElementVersion $extra = null): CompositionVersion + { + $content = app(ContentService::class); + $composition = $content->createComposition($title, $kind); + $composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', $kind === CompositionKind::Kurs ? 'programm' : 'modul')->value('id'); + $composition->save(); + $members = [['role' => 'Übung', 'target' => $exercise, 'selection' => $selection]]; + + if ($extra !== null) { + $members[] = ['role' => 'Zusatz', 'target' => $extra]; + } + + return $content->publishComposition($composition, $members); + } +}