diff --git a/.env.example b/.env.example index f8df09f..c319db5 100644 --- a/.env.example +++ b/.env.example @@ -70,3 +70,8 @@ PAYMENT_DRIVER=test MEDIA_PUBLIC_PATH= MEDIA_DERIVED_PATH= MEDIA_ORIGINALS_PATH= + +# Übernahme von Übungen aus Shinkan. Die Adresse ist je Umgebung vorgegeben. Der Zugangsschlüssel kann hier stehen (hat +# Vorrang) oder in der Verwaltung hinterlegt werden (Inhalte -> Übungen aus Shinkan). Werte nie ins Repository. +SHINKAN_DISTRIBUTION_URL= +SHINKAN_DISTRIBUTION_KEY= diff --git a/CLAUDE.md b/CLAUDE.md index df51dc2..6d317e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,6 +41,7 @@ ## Server und Umgebungen - Test und Prod laufen vorerst **beide auf `llm-node` (192.168.2.144)**, getrennt durch Compose-Projekt (`luf-test`, `luf-prod`), Verzeichnis, Env-Datei, Volumes und Zugangsdaten. Der Raspberry Pi ist als späteres Testsystem vorgesehen (Umzug über die Variablen in `deploy-test.yml`). - Secrets liegen nur in `/etc/luf/test.env` und `/etc/luf/prod.env` auf dem Server. **Keine Secrets, Passwörter, Keys oder `.env`-Dateien ins Repo, in Commits, Logs oder Chat-Ausgaben.** + - **Ausnahme Shinkan-Zugangsschlüssel (ADR-49, Nachtrag vom 23.11.2026):** Dieser eine Schlüssel darf zusätzlich von Katalog- und Systemverwaltern in der Verwaltung hinterlegt werden (Inhalte → Übungen aus Shinkan). Er liegt je Umgebung getrennt mit dem Anwendungsschlüssel verschlüsselt in der Datenbank, wird nie angezeigt, zurückgegeben oder protokolliert. Ein Wert in `SHINKAN_DISTRIBUTION_KEY` (Serverdatei) hat Vorrang. Die Adresse (`SHINKAN_DISTRIBUTION_URL`) bleibt je Umgebung in der Serverdatei. Für alle anderen Schlüssel gilt die Regel unverändert. - **Auf Servern wird nur nach ausdrücklicher Freigabe geschrieben.** Rein lesende Abfragen über vorhandene SSH-Zugänge sind erlaubt. Keine SSH-Schlüssel, Benutzer, Firewall-, Proxy- oder Runner-Änderungen. Andere Anwendungen auf den Servern (Shinkan, Gitea, mindnet, qdrant, …) dürfen nicht verändert werden. - Ports werden nicht geraten: Vor jedem neuen Host-Port die tatsächliche Belegung prüfen (`ss`, `docker ps`). Aktuell vorgesehen: Test 3011, Prod 3010 (Stand 2026-11-15). Datenbank und PHP-FPM veröffentlichen keine Host-Ports. - Der Reverse Proxy (Synology NAS) wird von Lars verwaltet. diff --git a/app/Domain/Catalog/ArticleService.php b/app/Domain/Catalog/ArticleService.php index 4232704..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, ]); } @@ -141,6 +143,10 @@ private function checkedRows(ContentElementVersion|CompositionVersion $root): ar { $root->refresh(); + if (app(ForeignCompositions::class)->reaches($root)) { + throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Er wird hier nicht veröffentlicht, damit nichts fehlt oder zu viel ausgegeben wird.'); + } + if ($root->status !== ContentVersionStatus::Bereit) { throw new DomainRuleException('Ein Artikel-Stand kann nur eine bereitgestellte Fassung festschreiben.'); } 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/Composition.php b/app/Domain/Catalog/Composition.php index 0d5068a..4bd54c1 100644 --- a/app/Domain/Catalog/Composition.php +++ b/app/Domain/Catalog/Composition.php @@ -36,6 +36,11 @@ protected function casts(): array ]; } + protected static function booted(): void + { + static::addGlobalScope(new SupportedKindScope); + } + public function editorialContentKind(): BelongsTo { return $this->belongsTo(EditorialContentKind::class); diff --git a/app/Domain/Catalog/CompositionKind.php b/app/Domain/Catalog/CompositionKind.php index b84b275..3945b68 100644 --- a/app/Domain/Catalog/CompositionKind.php +++ b/app/Domain/Catalog/CompositionKind.php @@ -7,13 +7,24 @@ 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 + */ + public static function values(): array + { + return array_map(fn (self $case): string => $case->value, self::cases()); + } public function label(): string { return match ($this) { self::Kombination => 'Fachliche Kombination', - self::Uebung => 'Übung', + self::Uebung => 'Modul', self::Kurs => 'Kurs', + self::Exercise => 'Übung', }; } @@ -21,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', }; } @@ -30,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', }; } @@ -41,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.', }; } @@ -50,6 +64,7 @@ public function deskLabel(): string self::Kombination => 'Fachliche Kombination', self::Uebung => 'Modul', self::Kurs => 'Programm', + self::Exercise => 'Übung', }; } @@ -59,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..f63f391 100644 --- a/app/Domain/Catalog/CompositionMember.php +++ b/app/Domain/Catalog/CompositionMember.php @@ -14,8 +14,21 @@ class CompositionMember extends Model 'placement_note', 'content_element_version_id', 'nested_composition_version_id', + 'variant_id', + 'requirement', + 'variant_selection', + 'origin', ]; + public const REQUIRED = 'erforderlich'; + + public const SUPPLEMENTARY = 'ergaenzend'; + + protected function casts(): array + { + return ['variant_selection' => 'array']; + } + protected static function booted(): void { static::creating(function (CompositionMember $member): void { @@ -41,6 +54,11 @@ public function contentElementVersion(): BelongsTo return $this->belongsTo(ContentElementVersion::class); } + public function variant(): BelongsTo + { + return $this->belongsTo(CompositionVersionVariant::class, 'variant_id'); + } + public function nestedCompositionVersion(): BelongsTo { return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id'); diff --git a/app/Domain/Catalog/CompositionRelease.php b/app/Domain/Catalog/CompositionRelease.php index d44b2b6..2edc9c0 100644 --- a/app/Domain/Catalog/CompositionRelease.php +++ b/app/Domain/Catalog/CompositionRelease.php @@ -54,6 +54,7 @@ public function publish( ?string $note, array $didactic, bool $consent, + array $variants = [], ): CompositionVersion { $review = $this->review($host, $members); @@ -67,8 +68,8 @@ public function publish( $this->publishedDrafts = []; - return DB::transaction(function () use ($host, $members, $actor, $note, $didactic): CompositionVersion { - return $this->materialize($host, $members, $didactic, $actor, $note, []); + return DB::transaction(function () use ($host, $members, $actor, $note, $didactic, $variants): CompositionVersion { + return $this->materialize($host, $members, $didactic, $actor, $note, [], $variants); }); } @@ -220,6 +221,12 @@ private function inspectReleasedComposition( ): void { $version = CompositionVersion::query()->with('composition', 'members')->find($id); + if ($version instanceof CompositionVersion && $version->composition === null && app(ForeignCompositions::class)->isForeignVersion($version->id)) { + $blocked[] = $this->block('Bestandteil', 'Dieser Bestandteil stammt aus einer neueren Programmversion und kann hier nicht freigegeben werden.', $depth, null); + + return; + } + if (! $version instanceof CompositionVersion || $version->composition === null) { $blocked[] = $this->block('Modul', 'Ein Bestandteil ist nicht mehr vorhanden.', $depth, null); @@ -324,6 +331,7 @@ private function materialize( ?User $actor, ?string $note, array $stack, + array $variants = [], ): CompositionVersion { if (isset($this->publishedDrafts[$composition->id])) { return $this->publishedDrafts[$composition->id]; @@ -341,6 +349,10 @@ private function materialize( 'role' => trim((string) ($member['role'] ?? '')), 'note' => trim((string) ($member['note'] ?? '')), 'target' => $this->resolveTarget((string) ($member['target'] ?? ''), $actor, $stack), + 'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null, + 'requirement' => $member['requirement'] ?? 'erforderlich', + 'selection' => is_array($member['selection'] ?? null) && $member['selection'] !== [] ? array_values($member['selection']) : null, + 'origin' => $member['origin'] ?? 'lokal', ]; } @@ -352,8 +364,11 @@ private function materialize( [ 'learning_goal' => $didactic['learning_goal'] ?? null, 'duration_minutes' => $didactic['duration_minutes'] ?? null, + 'duration_max' => $didactic['duration_max'] ?? null, 'material_note' => $didactic['material_note'] ?? null, + 'prerequisites' => $didactic['prerequisites'] ?? null, ], + $variants, ); $this->publishedDrafts[$composition->id] = $version; @@ -414,11 +429,14 @@ private function resolveTarget(string $target, ?User $actor, array $stack): Cont [ 'learning_goal' => $draft['learning_goal'] ?? null, 'duration_minutes' => $draft['duration_minutes'] ?? null, + 'duration_max' => $draft['duration_max'] ?? null, 'material_note' => $draft['material_note'] ?? null, + 'prerequisites' => $draft['prerequisites'] ?? null, ], $actor, is_string($draft['revision_note'] ?? null) ? $draft['revision_note'] : null, $stack, + is_array($draft['variants'] ?? null) ? $draft['variants'] : [], ); app(EditorialWorkingDraft::class)->clear($composition); diff --git a/app/Domain/Catalog/CompositionStructureReader.php b/app/Domain/Catalog/CompositionStructureReader.php index d2ccf94..5705dca 100644 --- a/app/Domain/Catalog/CompositionStructureReader.php +++ b/app/Domain/Catalog/CompositionStructureReader.php @@ -60,6 +60,11 @@ private function members(CompositionVersion $version, array $stack = []): array $nested->loadMissing('composition.editorialContentKind', 'composition'); $composition = $nested->composition; + // Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht anzeigen (Rückfallschutz). + if ($composition === null) { + continue; + } + $nodes[] = new StructureNode( role: $member->role, position: $member->position, diff --git a/app/Domain/Catalog/CompositionVersion.php b/app/Domain/Catalog/CompositionVersion.php index ab4e423..6675c5c 100644 --- a/app/Domain/Catalog/CompositionVersion.php +++ b/app/Domain/Catalog/CompositionVersion.php @@ -17,6 +17,10 @@ class CompositionVersion extends Model 'learning_goal', 'duration_minutes', 'material_note', + 'duration_max', + 'prerequisites', + 'structure_hash', + 'source_snapshot_id', ]; protected function casts(): array @@ -60,6 +64,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..36c7d33 --- /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/ContentElement.php b/app/Domain/Catalog/ContentElement.php index d1aceef..fc028cb 100644 --- a/app/Domain/Catalog/ContentElement.php +++ b/app/Domain/Catalog/ContentElement.php @@ -31,6 +31,7 @@ class ContentElement extends Model 'preview_path', 'editorial_content_kind_id', 'archived_at', + 'source_ref', ]; protected function casts(): array diff --git a/app/Domain/Catalog/ContentResolver.php b/app/Domain/Catalog/ContentResolver.php index 4ed1470..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; @@ -45,7 +60,20 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p throw new DomainRuleException('Ein Kompositionsmitglied braucht genau ein Ziel.'); } - $rows = array_merge($rows, $this->expand($nested, $segment, $stack)); + // Bestandteil einer Art, die dieser Programmstand nicht kennt: nicht auflösen (Rückfallschutz). + // Veröffentlichen verweigern die aufrufenden Stellen über ForeignCompositions. + $nested->loadMissing('composition'); + + if ($nested->composition === null) { + continue; + } + + $rows = array_merge($rows, $this->expand( + $nested, + $segment, + $stack, + is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null, + )); } return $rows; diff --git a/app/Domain/Catalog/ContentService.php b/app/Domain/Catalog/ContentService.php index e00e812..fba9675 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,52 @@ 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), + 'source_snapshot_id' => isset($didactic['source_snapshot_id']) ? (int) $didactic['source_snapshot_id'] : null, ]); + $variantIds = []; + + foreach ($variants as $index => $variant) { + $variantIds[$variant['key']] = $version->variants()->create([ + 'key' => $variant['key'], + 'position' => $index + 1, + 'name' => $variant['name'], + 'description' => $variant['description'], + 'origin' => $variant['origin'], + ])->id; + } + foreach (array_values($members) as $index => $member) { $target = $member['target']; + $selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null; $version->members()->create([ 'position' => $index + 1, 'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'), 'placement_note' => $this->optionalText($member['note'] ?? null), 'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null, 'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null, + 'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null, + 'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED, + 'variant_selection' => $selection === null ? null : array_values($selection), + 'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal', ]); } + $version->load('members.variant', 'variants'); $resolvedHash = $this->resolver->resolvedHash($version); + $structureHash = $this->structureHash($version); $version->attestations()->create([ 'resolved_hash' => $resolvedHash, + 'structure_hash' => $structureHash, 'confirmed_by' => $confirmedBy?->id, 'confirmed_at' => now(), 'note' => $note, ]); $version->resolved_hash = $resolvedHash; + $version->structure_hash = $structureHash; $version->status = ContentVersionStatus::Bereit; $version->save(); @@ -282,6 +311,103 @@ 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, $variant->origin, + ])->all(), + 'members' => $version->members->map(fn (CompositionMember $member): array => [ + $member->position, + $member->role, + $member->placement_note, + $member->content_element_version_id, + $member->nested_composition_version_id, + $member->variant?->key, + $member->requirement, + $member->variant_selection, + $member->origin, + ])->all(), + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE)); + } + + /** + * @param list $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), + 'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal', + ]; + } + + 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([ @@ -345,6 +471,10 @@ private function assertAcyclic(int $compositionId, array $members, array $stack private function assertReadyMember(ContentElementVersion|CompositionVersion $target): void { + if (app(ForeignCompositions::class)->reaches($target)) { + throw new DomainRuleException('Dieser Bestandteil stammt aus einer neueren Programmversion und wird hier nicht in eine Fassung aufgenommen.'); + } + if ($target->status !== ContentVersionStatus::Bereit) { throw new DomainRuleException('Eine Komposition darf nur bereitgestellte Fassungen enthalten.'); } @@ -365,6 +495,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/ExerciseImportRun.php b/app/Domain/Catalog/ExerciseImportRun.php new file mode 100644 index 0000000..ec5960b --- /dev/null +++ b/app/Domain/Catalog/ExerciseImportRun.php @@ -0,0 +1,15 @@ + 'datetime', 'finished_at' => 'datetime']; + } +} 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/ExerciseSource.php b/app/Domain/Catalog/ExerciseSource.php new file mode 100644 index 0000000..f258467 --- /dev/null +++ b/app/Domain/Catalog/ExerciseSource.php @@ -0,0 +1,40 @@ + 'datetime']; + } + + public function composition(): BelongsTo + { + return $this->belongsTo(Composition::class); + } + + public function snapshots(): HasMany + { + return $this->hasMany(ExerciseSourceSnapshot::class)->orderBy('id'); + } + + public function latestSnapshot(): ?ExerciseSourceSnapshot + { + return $this->snapshots()->reorder()->orderByDesc('id')->first(); + } +} diff --git a/app/Domain/Catalog/ExerciseSourceSnapshot.php b/app/Domain/Catalog/ExerciseSourceSnapshot.php new file mode 100644 index 0000000..1c3079f --- /dev/null +++ b/app/Domain/Catalog/ExerciseSourceSnapshot.php @@ -0,0 +1,30 @@ + 'array', 'fetched_at' => 'datetime']; + } + + public function source(): BelongsTo + { + return $this->belongsTo(ExerciseSource::class, 'exercise_source_id'); + } + + public function adoptedVersion(): BelongsTo + { + return $this->belongsTo(CompositionVersion::class, 'adopted_version_id'); + } +} diff --git a/app/Domain/Catalog/ExerciseUsage.php b/app/Domain/Catalog/ExerciseUsage.php new file mode 100644 index 0000000..a948f2a --- /dev/null +++ b/app/Domain/Catalog/ExerciseUsage.php @@ -0,0 +1,106 @@ +>, releases: list>}> + */ + public function forComposition(Composition $composition): array + { + $guide = app(ExerciseGuide::class); + $result = []; + + foreach ($composition->versions()->orderBy('number')->get() as $version) { + $hosts = []; + $roots = [$version->id => $version]; + $queue = [$version->id]; + $seen = [$version->id]; + + while ($queue !== []) { + $current = array_shift($queue); + + foreach (CompositionMember::query()->where('nested_composition_version_id', $current)->with('compositionVersion.composition')->orderBy('id')->get() as $member) { + $host = $member->compositionVersion; + + if ($host === null || $host->composition === null) { + continue; + } + + $hosts[] = [ + 'composition' => $host->composition, + 'version' => $host, + 'role' => $member->role, + 'position' => $member->position, + 'selection' => $member->variant_selection, + 'direct' => $current === $version->id, + ]; + + if (! in_array($host->id, $seen, true)) { + $seen[] = $host->id; + $roots[$host->id] = $host; + $queue[] = $host->id; + } + } + } + + $releases = []; + + foreach (ArticleRelease::query()->whereIn('root_composition_version_id', array_keys($roots))->with('article')->orderBy('license_article_id')->orderBy('number')->get() as $release) { + $root = $roots[$release->root_composition_version_id]; + $releases[] = [ + 'article' => $release->article, + 'release' => $release, + 'status' => $release->status, + 'path' => $root->id === $version->id ? null : $guide->pathTo($root, $version->id), + 'root' => $root, + ]; + } + + $result[] = ['version' => $version, 'hosts' => $hosts, 'releases' => $releases]; + } + + return $result; + } + + /** + * Folgen einer Sperre dieser Medienfassung je Artikel-Stand. Die Festschreibung bleibt unverändert; gesperrt wird + * nur die Ausgabe des Mediums. + * + * @return list + */ + public function blockImpact(ContentElementVersion $version): array + { + $impact = []; + + foreach (ReleaseContent::query()->where('content_element_version_id', $version->id)->with('release.article')->orderBy('id')->get() as $content) { + $release = $content->release; + $required = ($content->requirement ?? CompositionMember::REQUIRED) === CompositionMember::REQUIRED; + $effect = match (true) { + ! $required => 'Nur dieses ergänzende Medium entfällt. Die Übung bleibt vollständig durchführbar.', + $content->variant_key !== null => 'Die Variante „'.$content->variant_key.'“ ist nicht mehr vollständig durchführbar. Andere Varianten bleiben nutzbar.', + default => 'Ein erforderlicher Bestandteil entfällt. Die Anleitung bleibt lesbar.', + }; + $impact[] = [ + 'article' => $release->article, + 'release' => $release, + 'status' => $release->status, + 'variant' => $content->variant_key, + 'requirement' => $content->requirement, + 'path' => $content->path, + 'effect' => $effect, + ]; + } + + return $impact; + } +} diff --git a/app/Domain/Catalog/ForeignCompositions.php b/app/Domain/Catalog/ForeignCompositions.php new file mode 100644 index 0000000..2e882cf --- /dev/null +++ b/app/Domain/Catalog/ForeignCompositions.php @@ -0,0 +1,93 @@ +join('compositions as c', 'c.id', '=', 'v.composition_id') + ->where('v.id', $compositionVersionId) + ->whereNotIn('c.kind', CompositionKind::values()) + ->exists(); + } + + /** + * @param string $target „composition:ID“ (Fassung) oder „composition-draft:ID“ (Komposition) + */ + public function isForeignTarget(string $target): bool + { + if (preg_match('/^composition:(\d+)$/', $target, $match) === 1) { + return $this->isForeignVersion((int) $match[1]); + } + + if (preg_match('/^composition-draft:(\d+)$/', $target, $match) === 1) { + return DB::table('compositions') + ->where('id', (int) $match[1]) + ->whereNotIn('kind', CompositionKind::values()) + ->exists(); + } + + return false; + } + + /** + * Ist die Fassung selbst unbekannt oder erreicht sie, auch verschachtelt, einen unbekannten Bestandteil? + */ + public function reaches(ContentElementVersion|CompositionVersion $node): bool + { + return $node instanceof CompositionVersion && $this->reachesVersion($node->id, []); + } + + /** + * Enthält irgendeine Fassung dieser Komposition einen unbekannten Bestandteil? + */ + public function compositionHasForeignMembers(int $compositionId): bool + { + return DB::table('composition_members as m') + ->join('composition_versions as host', 'host.id', '=', 'm.composition_version_id') + ->join('composition_versions as nested', 'nested.id', '=', 'm.nested_composition_version_id') + ->join('compositions as c', 'c.id', '=', 'nested.composition_id') + ->where('host.composition_id', $compositionId) + ->whereNotIn('c.kind', CompositionKind::values()) + ->exists(); + } + + /** + * @param list $seen + */ + private function reachesVersion(int $versionId, array $seen): bool + { + if (in_array($versionId, $seen, true)) { + return false; + } + + if ($this->isForeignVersion($versionId)) { + return true; + } + + $seen[] = $versionId; + + foreach (DB::table('composition_members') + ->where('composition_version_id', $versionId) + ->whereNotNull('nested_composition_version_id') + ->pluck('nested_composition_version_id') as $nestedId) { + if ($this->reachesVersion((int) $nestedId, $seen)) { + return true; + } + } + + return false; + } +} 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/LicenceScope.php b/app/Domain/Catalog/LicenceScope.php new file mode 100644 index 0000000..41f3567 --- /dev/null +++ b/app/Domain/Catalog/LicenceScope.php @@ -0,0 +1,90 @@ + self::MAX_TRAINERS) { + throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.'); + } + + return [self::MULTI, $count]; + } + + throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.'); + } + + /** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */ + public static function label(?string $scope, ?int $trainers): string + { + return match ($scope) { + self::SINGLE => 'Einzellizenz · 1 Trainer', + self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer', + default => 'Nutzerkreis nicht festgelegt', + }; + } + + /** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */ + public static function explanation(?string $scope, ?int $trainers): ?string + { + return match ($scope) { + self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.', + self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.', + default => null, + }; + } + + /** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */ + public static function key(?string $scope, ?int $trainers): string + { + return ($scope ?? '-').'|'.($trainers ?? 0); + } + + /** @return array */ + public static function options(): array + { + return [ + self::SINGLE => 'Einzellizenz (ein Trainer)', + self::MULTI => 'Mehrfachlizenz (mehrere Trainer)', + ]; + } +} diff --git a/app/Domain/Catalog/MaterialTag.php b/app/Domain/Catalog/MaterialTag.php new file mode 100644 index 0000000..9609940 --- /dev/null +++ b/app/Domain/Catalog/MaterialTag.php @@ -0,0 +1,61 @@ + 'Film', + self::Uebung => 'Übung', + self::Pdf => 'PDF', + self::Paket => 'Paket', + self::FilmUebungen => 'Film + Übungen', + self::FilmMerkblatt => 'Film + Merkblatt', + }; + } + + /** Name des Zeichens im Satz „glyphen“ (resources/svg/brand/glyphen). */ + public function glyph(): string + { + return match ($this) { + self::Film => 'film', + self::Uebung => 'uebung', + self::Pdf, self::FilmMerkblatt => 'dokument', + self::Paket => 'paket', + self::FilmUebungen => 'filmstreifen', + }; + } + + public static function fromContent(?string $outputClass, ?string $editorialKindSlug = null): ?self + { + return match (true) { + $outputClass === 'film' => self::Film, + $outputClass === 'pdf' => self::Pdf, + in_array($editorialKindSlug, self::FILM_KINDS, true) => self::Film, + in_array($editorialKindSlug, self::EXERCISE_KINDS, true) => self::Uebung, + default => null, + }; + } +} diff --git a/app/Domain/Catalog/Offer.php b/app/Domain/Catalog/Offer.php index 360d492..8e9e2ab 100644 --- a/app/Domain/Catalog/Offer.php +++ b/app/Domain/Catalog/Offer.php @@ -12,8 +12,16 @@ class Offer extends Model 'name', 'composition_id', 'option_label', + 'standalone_bundle', ]; + protected function casts(): array + { + return [ + 'standalone_bundle' => 'boolean', + ]; + } + /** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */ public function composition(): BelongsTo { diff --git a/app/Domain/Catalog/OfferCoverage.php b/app/Domain/Catalog/OfferCoverage.php index 6711c6e..368a8f7 100644 --- a/app/Domain/Catalog/OfferCoverage.php +++ b/app/Domain/Catalog/OfferCoverage.php @@ -6,6 +6,27 @@ class OfferCoverage { public function __construct(private readonly ContentResolver $resolver) {} + /** + * Bestandteile der Fassung, deren Medienfassung gesperrt ist. Ein Angebot soll nicht aktiviert werden, solange sein + * Umfang gesperrte Bestandteile enthält; die Prüfung nennt sie vorab. + * + * @return list + */ + public function blockedLeaves(CompositionVersion $version): array + { + $rows = $this->resolver->expand($version); + $blocked = ContentElementVersion::query() + ->whereIn('id', array_column($rows, 'version_id')) + ->where('status', ContentVersionStatus::Gesperrt->value) + ->pluck('id') + ->all(); + + return array_values(array_map( + fn (array $row): string => $row['path'], + array_filter($rows, fn (array $row): bool => in_array($row['version_id'], $blocked, true)), + )); + } + /** * @param list $articles * @return list diff --git a/app/Domain/Catalog/OfferService.php b/app/Domain/Catalog/OfferService.php index a245cbb..f584529 100644 --- a/app/Domain/Catalog/OfferService.php +++ b/app/Domain/Catalog/OfferService.php @@ -102,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of 'dynamic' => false, 'grant_kind' => 'kauf', 'holder_kind' => 'person', + 'licence_scope' => null, + 'trainer_count' => null, ], $attributes); + if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) { + throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.'); + } + $this->assertAttributes($attributes); + [$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']); $scope = $this->scopeFor($lines); + $this->assertSellableContent($scope); $this->assertCoverage($lines, $attributes); return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion { @@ -126,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of 'dynamic' => $attributes['dynamic'], 'grant_kind' => $attributes['grant_kind'], 'holder_kind' => $attributes['holder_kind'], + 'licence_scope' => $attributes['licence_scope'], + 'trainer_count' => $attributes['trainer_count'], ]); foreach (array_values($lines) as $index => $line) { @@ -176,13 +186,18 @@ public function end(Offer $offer): OfferVersion * Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe, * die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen. */ - public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel): Offer + public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer { if ($compositionId !== null) { Composition::query()->findOrFail($compositionId); } + if ($ownBundlePage && $compositionId !== null) { + throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.'); + } + $offer->composition_id = $compositionId; + $offer->standalone_bundle = $ownBundlePage; $offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null; $offer->save(); @@ -219,6 +234,32 @@ private function assertAttributes(array $attributes): void } } + /** + * Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen + * veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der + * Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft. + * + * @param list $scope + */ + private function assertSellableContent(array $scope): void + { + $ids = array_values(array_unique(array_column($scope, 'license_article_id'))); + $missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get() + ->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease + && StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value)); + + if ($missing->isEmpty()) { + return; + } + + $names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', '); + + throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names + .($missing->count() === 1 ? ' hat' : ' haben') + .' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. ' + .'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.'); + } + /** * @param list $lines * @return list @@ -236,6 +277,10 @@ private function assertCoverage(array $lines, array $attributes): void } $version = CompositionVersion::query()->findOrFail($versionId); + + if (app(ForeignCompositions::class)->reaches($version)) { + throw new DomainRuleException('Der Aufbau enthält einen Bestandteil, den dieser Programmstand nicht kennt. Das Angebot wird hier nicht aktiviert.'); + } $articles = []; foreach ($lines as $line) { @@ -244,6 +289,12 @@ private function assertCoverage(array $lines, array $attributes): void } } + $blocked = app(OfferCoverage::class)->blockedLeaves($version); + + if ($blocked !== []) { + throw new DomainRuleException('Das Angebot enthält gesperrte Bestandteile: '.implode(', ', $blocked)); + } + $missing = app(OfferCoverage::class)->missingLeaves($version, $articles); if ($missing !== []) { diff --git a/app/Domain/Catalog/OfferVersion.php b/app/Domain/Catalog/OfferVersion.php index 679b261..530615a 100644 --- a/app/Domain/Catalog/OfferVersion.php +++ b/app/Domain/Catalog/OfferVersion.php @@ -19,6 +19,8 @@ class OfferVersion extends Model 'dynamic', 'grant_kind', 'holder_kind', + 'licence_scope', + 'trainer_count', 'activated_at', ]; 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/Catalog/ShinkanConnection.php b/app/Domain/Catalog/ShinkanConnection.php new file mode 100644 index 0000000..8508942 --- /dev/null +++ b/app/Domain/Catalog/ShinkanConnection.php @@ -0,0 +1,123 @@ +serverKey(); + + if ($server !== null) { + return $server; + } + + $encrypted = $this->stored()['key'] ?? null; + + if (! is_string($encrypted) || $encrypted === '') { + return null; + } + + try { + return Crypt::decryptString($encrypted); + } catch (DecryptException) { + return null; + } + } + + /** + * Woher kommt der Schlüssel? `server`, `verwaltung` oder null. + */ + public function keySource(): ?string + { + if ($this->serverKey() !== null) { + return self::SERVER; + } + + return $this->apiKey() !== null ? self::ADMIN : null; + } + + public function configured(): bool + { + return $this->url() !== null && $this->apiKey() !== null; + } + + /** + * Hinterlegt oder ersetzt den Schlüssel. Der Schlüssel aus der Umgebung des Servers behält den Vorrang. + */ + public function saveKey(string $key, ?User $by = null): void + { + $key = trim($key); + + if ($key === '') { + throw new DomainRuleException('Der Zugangsschlüssel fehlt.'); + } + + $this->write(['key' => Crypt::encryptString($key)], $by); + } + + public function forgetKey(?User $by = null): void + { + $this->write([], $by); + } + + /** + * @return array + */ + private function stored(): array + { + $value = SiteSetting::query()->find(self::SETTING)?->value; + + return is_array($value) ? $value : []; + } + + /** + * @param array $stored + */ + private function write(array $stored, ?User $by): void + { + SiteSetting::query()->updateOrCreate(['key' => self::SETTING], ['value' => $stored, 'updated_by' => $by?->id]); + } + + private function serverKey(): ?string + { + $value = config('services.shinkan.key'); + + return is_string($value) && trim($value) !== '' ? trim($value) : null; + } +} diff --git a/app/Domain/Catalog/ShinkanImport.php b/app/Domain/Catalog/ShinkanImport.php new file mode 100644 index 0000000..d6569f2 --- /dev/null +++ b/app/Domain/Catalog/ShinkanImport.php @@ -0,0 +1,827 @@ + Bezeichnung. */ + public const SECTIONS = [ + 'preparation' => 'Vorbereitung', + 'execution' => 'Durchführung', + 'trainer_notes' => 'Trainerhinweise', + ]; + + /** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */ + private const IMPORT_NOTE = 'Übernahme aus Shinkan'; + + /** Fassungsfelder der Quelle: Katalogfeld => [Feld der lokalen Fassung, Bezeichnung]. */ + private const FIELDS = [ + 'goal' => ['learning_goal', 'Lernziel'], + 'duration_min' => ['duration_minutes', 'Dauer (von)'], + 'duration_max' => ['duration_max', 'Dauer (bis)'], + 'equipment' => ['material_note', 'Ausstattung'], + ]; + + public function configured(): bool + { + return app(ShinkanConnection::class)->configured(); + } + + /** + * Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt. + * + * @return array{url: bool, key: bool, host: string|null, key_source: string|null} + */ + public function status(): array + { + $connection = app(ShinkanConnection::class); + $url = $connection->url(); + + return [ + 'url' => $url !== null, + 'key' => $connection->apiKey() !== null, + 'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null, + 'key_source' => $connection->keySource(), + ]; + } + + /** + * Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel + * geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt. + * + * @return array{ok: bool, message: string} + */ + public function check(?string $candidateKey = null): array + { + $connection = app(ShinkanConnection::class); + $key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey(); + + if ($connection->url() === null || $key === null) { + return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.']; + } + + try { + $catalog = $this->get('/catalog', [], $key); + } catch (Throwable $exception) { + return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)]; + } + + $count = count((array) ($catalog['exercises'] ?? [])); + + return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.']; + } + + public function fetch(): ExerciseImportRun + { + $run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]); + + if (! $this->configured()) { + return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'); + } + + $previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor'); + $counts = ['added' => 0, 'updated' => 0, 'removed' => 0]; + + try { + try { + $catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]); + } catch (RequestException $exception) { + // Ein ungültiger Cursor heißt nur: ganz neu abgleichen. + if ($previous === null || $exception->response->status() !== 400) { + throw $exception; + } + + $catalog = $this->get('/catalog'); + } + + foreach ((array) ($catalog['changes'] ?? []) as $change) { + $id = (string) ($change['source_id'] ?? ''); + $kind = (string) ($change['change'] ?? ''); + + if ($id === '') { + continue; + } + + if ($kind === 'removed') { + ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id) + ->update(['availability' => ExerciseSource::WITHDRAWN]); + $counts['removed']++; + + continue; + } + + $document = $this->get('/catalog/'.$id); + $this->record($document); + $counts[$kind === 'added' ? 'added' : 'updated']++; + } + + foreach ((array) ($catalog['exercises'] ?? []) as $listed) { + ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? '')) + ->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]); + } + } catch (Throwable $exception) { + return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.'); + } + + return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous)); + } + + /** + * Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert. + * + * @param array $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern + */ + public function record(array $document): ExerciseSourceSnapshot + { + $id = (string) ($document['source_id'] ?? ''); + $hash = (string) ($document['content_hash'] ?? ''); + + if ($id === '' || $hash === '') { + throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.'); + } + + return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot { + $source = ExerciseSource::query()->firstOrCreate( + ['source_system' => 'shinkan', 'source_id' => $id], + ['title' => (string) ($document['title'] ?? '')], + ); + $source->update([ + 'title' => (string) ($document['title'] ?? $source->title), + 'availability' => ExerciseSource::PROVIDED, + 'last_hash' => $hash, + 'last_seen_at' => now(), + ]); + + return $source->snapshots()->firstOrCreate( + ['content_hash' => $hash], + ['payload' => $document, 'fetched_at' => now()], + ); + }); + } + + /** + * Zustand einer Quellübung für die Redaktion. + */ + public function state(ExerciseSource $source): string + { + $latest = $source->latestSnapshot(); + + return match (true) { + $source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt', + $latest === null => 'neu', + $latest->adopted_version_id !== null => 'uebernommen', + $source->composition_id !== null => 'geaendert', + default => 'neu', + }; + } + + /** + * Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die + * fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen. + * + * @return array + */ + public function preview(ExerciseSource $source): array + { + $snapshot = $source->latestSnapshot(); + $state = $this->state($source); + $document = $snapshot?->payload ?? []; + $previous = $this->lastAdopted($source); + $sections = []; + + foreach (self::SECTIONS as $field => $label) { + if (trim((string) ($document[$field] ?? '')) !== '') { + $sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')]; + } + } + + return [ + 'source' => $source->id, + 'snapshot' => $snapshot?->id, + 'hash' => $snapshot?->content_hash, + 'state' => $state, + 'title' => (string) ($document['title'] ?? $source->title), + 'summary' => (string) ($document['summary'] ?? ''), + 'goal' => (string) ($document['goal'] ?? ''), + 'duration' => $this->duration($document), + 'equipment' => (string) ($document['equipment'] ?? ''), + 'sections' => $sections, + 'variants' => array_map(fn (array $variant): array => [ + 'key' => (string) ($variant['id'] ?? ''), + 'name' => (string) ($variant['name'] ?? ''), + 'description' => (string) ($variant['description'] ?? ''), + 'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '', + ], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))), + 'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))), + 'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source), + 'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document), + 'text_conflicts' => $snapshot === null ? [] : $this->textDecisions($source, $document, 'conflict'), + 'kept_local' => $snapshot === null ? [] : array_column($this->textDecisions($source, $document, 'keep_local'), 'label'), + 'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null, + 'excluded' => $source->availability === ExerciseSource::WITHDRAWN, + ]; + } + + /** + * Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen. + * + * @param array $before + * @param array $after + * @return list + */ + public function changes(array $before, array $after, ?ExerciseSource $source = null): array + { + $lines = []; + $labels = [ + 'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung', + 'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)', + ] + self::SECTIONS; + + foreach ($labels as $field => $label) { + if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) { + $lines[] = $label.' geändert'; + } + } + + $old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? '')); + $new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? '')); + + foreach ($new->diffKeys($old) as $variant) { + $lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu'; + } + + foreach ($old->diffKeys($new) as $variant) { + $lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt'; + } + + foreach ($new->intersectByKeys($old) as $key => $variant) { + if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) { + $lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“'; + } + + if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? '')) + || trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) { + $lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert'; + } + } + + $common = $old->keys()->intersect($new->keys())->values()->all(); + + if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) { + $lines[] = 'Reihenfolge der Varianten geändert'; + } + + if ($source?->composition !== null) { + if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) { + $lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert'; + } + + if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) { + $lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert'; + } + } + + return $lines; + } + + /** + * Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt. + * Die Redaktion legt deren neue Zuordnung fest. + * + * @param array $document + * @return list}> + */ + public function conflicts(ExerciseSource $source, array $document): array + { + $latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first(); + + if ($latest === null) { + return []; + } + + $keep = array_merge( + array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')), + $latest->variants->where('origin', 'lokal')->pluck('key')->all(), + ); + $open = []; + + foreach ($latest->members->where('origin', 'lokal') as $member) { + $key = $member->variant?->key; + + if ($key !== null && ! in_array($key, $keep, true)) { + $open[$key]['key'] = $key; + $open[$key]['name'] = $member->variant->name; + $open[$key]['members'][] = $member->role; + } + } + + return array_values($open); + } + + /** + * Texte und Felder, die lokal bearbeitet wurden: `keep_local` bleiben erhalten, bei `conflict` hat auch die Quelle + * geändert und die Redaktion entscheidet. + * + * @param array $document + * @return list + */ + public function textDecisions(ExerciseSource $source, array $document, string $wanted): array + { + $previousSnapshot = $this->lastAdopted($source); + + if ($previousSnapshot === null || $source->composition === null) { + return []; + } + + $previousSource = $previousSnapshot->payload; + $result = []; + + foreach ($this->plan($source, $document, $previousSource) as $item) { + if ($item['kind'] === 'text' && $item['decision'] === $wanted) { + $result[] = ['key' => $item['key'], 'label' => $item['label']]; + } + } + + $latest = $source->composition->versions()->orderByDesc('number')->first(); + + foreach (self::FIELDS as $field => [$column, $label]) { + if ($latest !== null && $this->classifyField($latest->{$column}, $previousSource[$field] ?? null, $document[$field] ?? null) === $wanted) { + $result[] = ['key' => $field, 'label' => $label]; + } + } + + return $result; + } + + /** + * Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder + * wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung. + * + * @param array $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder '' + * @param array $choices bei lokal und in der Quelle geänderten Angaben: Schlüssel => `lokal` oder `quelle` + * @return array{status: string, message: string, version?: CompositionVersion} + */ + public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null, array $choices = []): array + { + $source->refresh(); + $latest = $source->latestSnapshot(); + + if ($source->availability === ExerciseSource::WITHDRAWN) { + return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.']; + } + + if ($latest === null || $latest->id !== $previewedSnapshot) { + return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.']; + } + + if ($latest->adopted_version_id !== null) { + return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion]; + } + + try { + $version = $this->adopt($latest, $actor, $reassign, $choices); + } catch (DomainRuleException $exception) { + return ['status' => 'fehler', 'message' => $exception->getMessage()]; + } + + return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version]; + } + + /** + * Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie, + * entsteht keine zweite Fassung. + * + * Eine importierte Übung ist eine Übung wie jede andere und lässt sich bearbeiten. Lokal bearbeitete Texte und Felder + * bleiben deshalb erhalten, solange die Quelle sie nicht ebenfalls geändert hat. Haben beide Seiten geändert, legt die + * Redaktion fest, welcher Stand gilt (`$choices`). Lokale Ergänzungen bleiben erhalten; entfällt ihre Quellvariante, + * legt die Redaktion die neue Zuordnung fest (`$reassign`). + * + * @param array $reassign + * @param array $choices Schlüssel => `lokal` oder `quelle` + */ + public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = [], array $choices = []): CompositionVersion + { + $snapshot->refresh(); + + if ($snapshot->adopted_version_id !== null) { + return $snapshot->adoptedVersion; + } + + return DB::transaction(function () use ($snapshot, $actor, $reassign, $choices): CompositionVersion { + $source = $snapshot->source; + $document = $snapshot->payload; + $content = app(ContentService::class); + $title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan'; + $previousSnapshot = $this->lastAdopted($source); + $previousSource = $previousSnapshot?->payload ?? []; + $composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? '')); + + if ($source->composition !== null && $previousSnapshot !== null) { + $this->carryOverTexts($composition, $previousSource, $document); + } + + $previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first(); + $variants = []; + $members = []; + + foreach ($this->plan($source, $document, $previousSource) as $item) { + if ($item['kind'] === 'variant') { + $variants[] = $item['variant']; + + continue; + } + + $latest = $item['latest']; + $decision = $item['decision']; + + if ($decision === 'conflict') { + $decision = ($choices[$item['key']] ?? null) === 'lokal' ? 'keep_local' + : (($choices[$item['key']] ?? null) === 'quelle' ? 'source' : 'conflict'); + } + + if ($decision === 'conflict') { + throw new DomainRuleException('„'.$item['label'].'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.'); + } + + $keepLocal = $decision === 'keep_local' && $latest !== null; + $target = $keepLocal ? $latest : $this->sectionVersion($source, $item['field'], $item['title'], $item['text'], $latest); + $members[] = array_filter([ + 'role' => $item['role'], + 'target' => $target, + 'variant' => $item['variant_key'], + 'origin' => $keepLocal || ($latest !== null && $latest->id === $target->id && $latest->change_note !== self::IMPORT_NOTE) ? 'lokal' : 'quelle', + ], fn ($value): bool => $value !== null); + } + + // Fassungsfelder: lokal geändert bleibt erhalten, solange die Quelle den Wert nicht ebenfalls geändert hat. + $fields = []; + + foreach (self::FIELDS as $field => [$column, $label]) { + $value = $document[$field] ?? null; + + if ($previous !== null && $previousSnapshot !== null) { + $decision = $this->classifyField($previous->{$column}, $previousSource[$field] ?? null, $value); + + if ($decision === 'conflict') { + $decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict'); + } + + if ($decision === 'conflict') { + throw new DomainRuleException('„'.$label.'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.'); + } + + $value = $decision === 'keep_local' ? $previous->{$column} : $value; + } + + $fields[$column] = $value; + } + + [$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign); + $version = $content->publishComposition( + $composition, + [...$members, ...$localMembers], + $actor, + self::IMPORT_NOTE, + [ + 'learning_goal' => $fields['learning_goal'], + 'duration_minutes' => $fields['duration_minutes'], + 'duration_max' => $fields['duration_max'], + 'material_note' => $fields['material_note'], + 'source_snapshot_id' => $snapshot->id, + ], + [...$variants, ...$localVariants], + ); + + $snapshot->update(['adopted_version_id' => $version->id]); + $source->update(['composition_id' => $composition->id]); + + return $version; + }); + } + + /** + * Was die Übernahme aus dem Quellstand anlegen würde, mit der Entscheidung je Text: `source` (Quelltext gilt), + * `keep_local` (lokal bearbeitet, die Quelle hat sich nicht geändert) oder `conflict` (beide haben geändert). + * + * @param array $document + * @param array $previousSource + * @return list> + */ + private function plan(ExerciseSource $source, array $document, array $previousSource): array + { + $plan = []; + $title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan'; + + foreach (self::SECTIONS as $field => $label) { + $text = trim((string) ($document[$field] ?? '')); + + if ($text !== '') { + $plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $previousSource[$field] ?? null); + } + } + + foreach ((array) ($document['variants'] ?? []) as $variant) { + $key = (string) ($variant['id'] ?? ''); + + if ($key === '') { + continue; + } + + $name = (string) ($variant['name'] ?? '') ?: 'Variante'; + $plan[] = [ + 'kind' => 'variant', + 'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'], + ]; + $changes = trim((string) ($variant['execution_changes'] ?? '')); + + if ($changes !== '') { + $before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key); + $plan[] = $this->textItem( + $source, + 'variant:'.$key, + 'Abweichung der Durchführung ('.$name.')', + $title.' · '.$name.' · Abweichung', + 'Abweichung der Durchführung', + $changes, + $key, + is_array($before) ? ($before['execution_changes'] ?? null) : null, + 'variant_'.$key, + ); + } + } + + return $plan; + } + + /** + * @return array + */ + private function textItem(ExerciseSource $source, string $field, string $label, string $title, string $role, string $text, ?string $variantKey, ?string $previousText, ?string $key = null): array + { + $element = ContentElement::query()->where('source_ref', 'shinkan:'.$source->source_id.':'.$field)->first(); + $latest = $element?->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first(); + + return [ + 'kind' => 'text', + 'key' => $key ?? $field, + 'field' => $field, + 'label' => $label, + 'title' => $title, + 'role' => $role, + 'text' => $text, + 'variant_key' => $variantKey, + 'latest' => $latest, + 'decision' => $this->classifyText($latest, $text, $previousText), + ]; + } + + private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string + { + if ($latest === null || trim((string) $latest->body) === $text || $latest->change_note === self::IMPORT_NOTE) { + return 'source'; + } + + return $previousText === null || trim($previousText) !== $text ? 'conflict' : 'keep_local'; + } + + private function classifyField(mixed $local, mixed $previousSource, mixed $new): string + { + $plain = fn (mixed $value): string => $value === null ? '' : trim((string) $value); + + if ($plain($local) === $plain($new) || $plain($local) === $plain($previousSource)) { + return 'source'; + } + + return $plain($previousSource) !== $plain($new) ? 'conflict' : 'keep_local'; + } + + /** + * Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie + * nicht lokal geändert hat; ein lokal geänderter Wert bleibt. + * + * @param array $before + * @param array $after + */ + private function carryOverTexts(Composition $composition, array $before, array $after): void + { + if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) { + $composition->designation = trim((string) $after['title']); + } + + if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) { + $composition->summary = trim((string) $after['summary']) ?: null; + } + + $composition->save(); + } + + private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot + { + return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first(); + } + + /** + * Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer + * Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung. + * + * @param list $sourceVariantKeys + * @param array $reassign + * @return array{0: list>, 1: list>} + */ + private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): array + { + if ($previous === null) { + return [[], []]; + } + + $localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [ + 'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal', + ])->values()->all(); + $known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')]; + $members = []; + + foreach ($previous->members->where('origin', 'lokal') as $member) { + $variant = $member->variant?->key; + + if ($variant !== null && ! in_array($variant, $known, true)) { + if (! array_key_exists($variant, $reassign)) { + throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.'); + } + + $target = (string) $reassign[$variant]; + + if ($target !== '' && ! in_array($target, $known, true)) { + throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.'); + } + + $variant = $target === '' ? null : $target; + } + + $members[] = [ + 'role' => $member->role, + 'note' => $member->placement_note, + 'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion, + 'variant' => $variant, + 'requirement' => $member->requirement, + 'selection' => $member->variant_selection, + 'origin' => 'lokal', + ]; + } + + return [$members, $localVariants]; + } + + /** + * Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung. + */ + private function sectionVersion(ExerciseSource $source, string $field, string $title, string $text, ?ContentElementVersion $latest): ContentElementVersion + { + $content = app(ContentService::class); + $ref = 'shinkan:'.$source->source_id.':'.$field; + $element = ContentElement::query()->where('source_ref', $ref)->first(); + + if ($element === null) { + $element = $content->createElement('text', 'text', $title); + $element->source_ref = $ref; + $element->save(); + } + + return $latest !== null && trim((string) $latest->body) === $text + ? $latest + : $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE); + } + + private function createComposition(string $title, string $summary): Composition + { + $composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise); + $composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id'); + + if ($summary !== '') { + $composition->summary = $summary; + } + + $composition->save(); + + return $composition; + } + + /** + * @param array $document + */ + private function duration(array $document): string + { + $min = $document['duration_min'] ?? null; + $max = $document['duration_max'] ?? null; + + return match (true) { + $min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten', + $min !== null => $min.' Minuten', + $max !== null => $max.' Minuten', + default => '', + }; + } + + /** + * @param array $query + * @return array + */ + private function get(string $path, array $query = [], ?string $key = null): array + { + $connection = app(ShinkanConnection::class); + $response = Http::withToken((string) ($key ?? $connection->apiKey())) + ->acceptJson() + ->timeout(20) + ->get((string) $connection->url().'/api/distribution/v1'.$path, $query) + ->throw(); + + $json = $response->json(); + + if (! is_array($json)) { + throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.'); + } + + return $json; + } + + /** + * @param array{added?: int, updated?: int, removed?: int} $counts + */ + private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun + { + $run->update([ + 'status' => $status, + 'cursor' => $cursor, + 'added' => $counts['added'] ?? 0, + 'updated' => $counts['updated'] ?? 0, + 'removed' => $counts['removed'] ?? 0, + 'error' => $error, + 'finished_at' => now(), + ]); + + return $run; + } + + /** Fehlertext ohne Adresse und Schlüssel. */ + private function plain(Throwable $exception): string + { + if ($exception instanceof RequestException) { + return match ($exception->response->status()) { + 401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').', + 404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).', + default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.', + }; + } + + if ($exception instanceof DomainRuleException) { + return $exception->getMessage(); + } + + return $this->networkCause($exception); + } + + /** + * Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der + * Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist. + */ + private function networkCause(Throwable $exception): string + { + $host = app(ShinkanConnection::class)->url(); + $host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle'); + preg_match('/cURL error (\d+)/', $exception->getMessage(), $match); + $code = isset($match[1]) ? (int) $match[1] : null; + + $cause = match (true) { + $code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).', + $code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).', + $code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).', + in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.', + $code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.', + $code !== null => 'Netzwerkfehler (cURL '.$code.').', + default => 'Netzwerkfehler.', + }; + + return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause; + } +} diff --git a/app/Domain/Catalog/SupportedKindScope.php b/app/Domain/Catalog/SupportedKindScope.php new file mode 100644 index 0000000..93c8893 --- /dev/null +++ b/app/Domain/Catalog/SupportedKindScope.php @@ -0,0 +1,21 @@ +whereIn($model->qualifyColumn('kind'), CompositionKind::values()); + } +} diff --git a/app/Domain/Cms/Catalog/CardSubject.php b/app/Domain/Cms/Catalog/CardSubject.php index d75a52f..9d16cbc 100644 --- a/app/Domain/Cms/Catalog/CardSubject.php +++ b/app/Domain/Cms/Catalog/CardSubject.php @@ -15,6 +15,8 @@ * Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es * keine Freigabe für die Website hat. * - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau. + * - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist; + * sonst null, und die Karte zeigt die Art als Text wie bisher. * - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description). * summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt. */ @@ -39,6 +41,7 @@ public function __construct( public array $missing = [], public ?string $style = null, public array $texts = [], + public ?string $tag = null, ) {} public function withText(?string $title, ?string $summary): self diff --git a/app/Domain/Cms/Catalog/PublicMaterialReader.php b/app/Domain/Cms/Catalog/PublicMaterialReader.php index 49780f9..78557d7 100644 --- a/app/Domain/Cms/Catalog/PublicMaterialReader.php +++ b/app/Domain/Cms/Catalog/PublicMaterialReader.php @@ -6,6 +6,7 @@ use App\Domain\Catalog\ContentElement; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialProfileReader; +use App\Domain\Catalog\MaterialTag; use App\Domain\Catalog\StructureNode; use App\Domain\Media\ThumbnailRef; use App\Domain\Media\WebsiteMedia; @@ -235,6 +236,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ? missing: $missing, style: $film ? 'media' : 'material', texts: $texts, + tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value, ); } diff --git a/app/Domain/Commerce/Cart.php b/app/Domain/Commerce/Cart.php index 7b75717..7d1ed29 100644 --- a/app/Domain/Commerce/Cart.php +++ b/app/Domain/Commerce/Cart.php @@ -6,6 +6,9 @@ use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferVersion; +use App\Domain\Commerce\Discount\DiscountCode; +use App\Domain\Commerce\Discount\DiscountResult; +use App\Domain\Commerce\Discount\DiscountService; use App\Domain\Identity\Party; use App\Domain\Identity\PartyType; use App\Models\User; @@ -20,6 +23,9 @@ class Cart { public const KEY = 'shop.cart'; + /** Eingelöster Rabattcode (Kennung); höchstens einer je Bestellung. */ + public const DISCOUNT_KEY = 'shop.discount'; + public const ADDED = 'added'; public const PRESENT = 'present'; @@ -32,6 +38,7 @@ public function __construct( private readonly OwnershipCheck $ownership, private readonly OrderHolders $holders, private readonly OfferService $offers, + private readonly DiscountService $discounts, ) {} /** @@ -57,7 +64,10 @@ public function has(Offer $offer): bool */ public function alternativeTo(Offer $offer): ?Offer { - if ($offer->composition_id === null) { + $products = app(ProductOptions::class); + $group = $products->groupKey($offer); + + if ($group === null) { return null; } @@ -65,8 +75,8 @@ public function alternativeTo(Offer $offer): ?Offer return $ids === [] ? null : Offer::query() ->whereIn('id', $ids) - ->where('composition_id', $offer->composition_id) - ->first(); + ->get() + ->first(fn (Offer $other): bool => $products->groupKey($other) === $group); } public function add(Offer $offer): string @@ -133,13 +143,51 @@ public function acceptCurrent(Offer $offer): void public function clear(): void { - session()->forget(self::KEY); + session()->forget([self::KEY, self::DISCOUNT_KEY]); + } + + /** Der im Warenkorb eingelöste Code, auch wenn er gerade nicht (mehr) gilt. */ + public function discountCode(): ?DiscountCode + { + $id = session()->get(self::DISCOUNT_KEY); + + return is_numeric($id) ? DiscountCode::query()->with('targets')->find((int) $id) : null; + } + + /** + * Löst einen Code ein. Er wird nur vorgemerkt, wenn er für diesen Warenkorb und dieses Konto gilt; sonst bleibt + * der bisherige Stand und das Ergebnis nennt den Grund. Ein zweiter Code ersetzt den ersten (höchstens ein Code). + */ + public function applyCode(string $input, ?User $user, ?int $holderPartyId = null): DiscountResult + { + $code = $this->discounts->find($input); + + if ($code === null) { + return new DiscountResult(null, DiscountResult::UNKNOWN, 'Diesen Code kennen wir nicht. Prüfe die Schreibweise.'); + } + + $previous = session()->get(self::DISCOUNT_KEY); + session()->put(self::DISCOUNT_KEY, $code->id); + $result = $this->review($user, $holderPartyId)->discount; + + if ($result === null || ! $result->applied()) { + $previous === null ? session()->forget(self::DISCOUNT_KEY) : session()->put(self::DISCOUNT_KEY, $previous); + + return $result ?? new DiscountResult($code, DiscountResult::NO_MATCH, 'Der Code kann auf diese Bestellung nicht angewendet werden.'); + } + + return $result; + } + + public function removeCode(): void + { + session()->forget(self::DISCOUNT_KEY); } /** * Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte. */ - public function review(?User $user = null, ?int $holderPartyId = null): CartReview + public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview { $offers = Offer::query() ->whereIn('id', array_keys($this->items())) @@ -203,7 +251,15 @@ public function review(?User $user = null, ?int $holderPartyId = null): CartRevi } } - return new CartReview($lines, $holder); + $code = $this->discountCode(); + $discount = null; + + if ($code !== null) { + $orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable())); + $discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount); + } + + return new CartReview($lines, $holder, $discount); } /** diff --git a/app/Domain/Commerce/CartLine.php b/app/Domain/Commerce/CartLine.php index ac3457a..a9b98a0 100644 --- a/app/Domain/Commerce/CartLine.php +++ b/app/Domain/Commerce/CartLine.php @@ -45,6 +45,14 @@ public function blocks(): bool public function title(): string { + if ($this->offer->standalone_bundle && $this->version !== null) { + $bundle = app(ProductOptions::class)->bundleOf($this->version); + + if ($bundle !== null) { + return (string) $bundle->name; + } + } + $composition = $this->offer->composition; return $composition !== null diff --git a/app/Domain/Commerce/CartReview.php b/app/Domain/Commerce/CartReview.php index e2e0ca5..b27c561 100644 --- a/app/Domain/Commerce/CartReview.php +++ b/app/Domain/Commerce/CartReview.php @@ -2,6 +2,7 @@ namespace App\Domain\Commerce; +use App\Domain\Commerce\Discount\DiscountResult; use App\Domain\Identity\Party; /** @@ -16,6 +17,7 @@ final class CartReview public function __construct( public readonly array $lines, public readonly ?Party $holder, + public readonly ?DiscountResult $discount = null, ) {} /** @return list */ @@ -24,11 +26,35 @@ public function orderable(): array return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable())); } - public function totalCents(): int + /** Summe der Listenpreise der Positionen, die in die Bestellung eingehen. */ + public function subtotalCents(): int { return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable())); } + public function discountCents(): int + { + return $this->discount?->totalCents() ?? 0; + } + + /** Endgültiger Zahlbetrag: Listenpreise abzüglich Rabatt. */ + public function totalCents(): int + { + return $this->subtotalCents() - $this->discountCents(); + } + + /** Rabatt einer Position in Cent. */ + public function discountFor(CartLine $line): int + { + return $this->discount?->forOffer($line->offer->id) ?? 0; + } + + /** Ein vorgemerkter Code, der jetzt nicht gilt, hält die Bestellung an, bis er entfernt wird. */ + public function discountBlocks(): bool + { + return $this->discount !== null && ! $this->discount->applied(); + } + public function blocked(): bool { foreach ($this->lines as $line) { @@ -47,7 +73,7 @@ public function empty(): bool public function canOrder(): bool { - return $this->holder !== null && ! $this->blocked() && ! $this->empty(); + return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks(); } public function digest(): string @@ -60,6 +86,6 @@ public function digest(): string sort($parts); - return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts)); + return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-')); } } diff --git a/app/Domain/Commerce/Checkout.php b/app/Domain/Commerce/Checkout.php index 902d131..87ab288 100644 --- a/app/Domain/Commerce/Checkout.php +++ b/app/Domain/Commerce/Checkout.php @@ -6,14 +6,18 @@ use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferVersion; +use App\Domain\Commerce\Discount\DiscountCode; +use App\Domain\Commerce\Stripe\StripeGateway; use App\Domain\Entitlement\Acquisition; use App\Domain\Entitlement\AcquisitionType; use App\Domain\Entitlement\GrantIssuer; use App\Domain\Entitlement\GrantStatus; use App\Domain\Identity\AccountStatus; use App\Domain\Identity\Party; +use App\Domain\Identity\PartyType; use App\Mail\OrderConfirmed; use App\Models\User; +use Carbon\CarbonInterface; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; @@ -23,6 +27,7 @@ public function __construct( private readonly GrantIssuer $grants, private readonly OfferService $offers, private readonly OrderHolders $holders, + private readonly PaymentJournal $journal, ) {} /** @@ -32,6 +37,12 @@ public function place(User $user, Offer $offer): Order { $this->assertActive($user); + // Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den + // Weg über die Kasse mit Pflichtangaben. + if (Shop::live()) { + throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.'); + } + $version = $this->offers->currentActiveVersion($offer); if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') { @@ -44,7 +55,7 @@ public function place(User $user, Offer $offer): Order $holder = $this->holders->resolve($user, null); - return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]])); + return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test')); } /** @@ -53,14 +64,25 @@ public function place(User $user, Offer $offer): Order * Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits * mit denselben Rechten besitzt, erzeugen keine Bestellposition. */ - public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest): Order + public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order { $this->assertActive($user); - $order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest): Order { - // Optionen sperren, damit eine gleichzeitige Aktivierung die Prüfung nicht unterläuft. + if ($consent === null && Shop::live()) { + throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.'); + } + + $order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order { + // Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug + // der Freigabe die Prüfung nicht unterläuft. Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get(); - $review = $cart->review($user, $holderPartyId); + $discountId = session()->get(Cart::DISCOUNT_KEY); + + if (is_numeric($discountId)) { + DiscountCode::query()->whereKey((int) $discountId)->lockForUpdate()->first(); + } + + $review = $cart->review($user, $holderPartyId, lockDiscount: true); if ($review->holder === null) { throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.'); @@ -78,9 +100,19 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.'); } + if ($review->discountBlocks()) { + throw new DomainRuleException(($review->discount?->message ?? 'Der Rabattcode gilt nicht.').' Entferne den Code, um ohne Rabatt zu bestellen.'); + } + + $method = $paymentMethod ?? (Shop::driver() === 'stripe' ? 'stripe' : 'test'); + + if ($method === 'rechnung' && ! ($review->holder->type === PartyType::Organisation && Shop::invoice())) { + throw new DomainRuleException('Der Kauf auf Rechnung ist nur für Vereine und Organisationen auf Anfrage möglich.'); + } + $pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable()); - return $this->createOrder($user, $review->holder, $pairs); + return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method); }); $cart->clear(); @@ -90,16 +122,28 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin /** * @param list $pairs + * @param array|null $terms Nachweis der Zustimmungen (SalesTerms::proof) */ - private function createOrder(User $user, Party $holder, array $pairs): Order + private function createOrder(User $user, Party $holder, array $pairs, ?CartReview $review, ?array $terms, string $method): Order { + $subtotal = array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs)); + $discount = $review?->discount; + $discountCents = $review?->discountCents() ?? 0; + $order = Order::query()->create([ 'user_id' => $user->id, 'party_id' => $holder->id, 'status' => 'offen', 'holder_kind' => $holder->type->value, - 'total_cents' => array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs)), + 'subtotal_cents' => $subtotal, + 'discount_cents' => $discountCents, + 'total_cents' => $subtotal - $discountCents, 'currency' => 'EUR', + 'discount_code_id' => $discountCents > 0 ? $discount?->code?->id : null, + 'discount_snapshot' => $discountCents > 0 ? $discount?->snapshot() : null, + 'payment_method' => $method, + 'terms_accepted_at' => $terms === null ? null : now(), + 'terms_snapshot' => $terms, ]); foreach ($pairs as [$offer, $version]) { @@ -114,6 +158,9 @@ private function createOrder(User $user, Party $holder, array $pairs): Order 'tax_class' => $version->tax_class, 'grant_kind' => $version->grant_kind, 'holder_party_id' => $holder->id, + 'licence_scope' => $version->licence_scope, + 'trainer_count' => $version->trainer_count, + 'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0, ]); $version->load('resolvedScopes.rights'); @@ -140,26 +187,49 @@ private function createOrder(User $user, Party $holder, array $pairs): Order public function confirmTestPayment(Order $order, string $reference): Order { $this->assertTestDriver(); + $this->assertTestOrder($order); - return $this->settle($order, 'test', $reference); + return $this->settle($order, 'test', $reference, null, now(), false); } /** * Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die - * Bestellung. Wiederholte Meldungen sind wirkungslos. + * Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet + * es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung + * laut Anbieter, sonst jetzt. */ - public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): Order + public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order { - $expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents')); + $expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents')); if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) { throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.'); } - return $this->settle($order, $provider, $reference); + return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent); } - private function settle(Order $order, string $provider, string $reference): Order + /** + * Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang. + * Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz + * (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf + * dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in + * welchen Zeitraum die Einnahme fällt. + */ + public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order + { + $order->refresh(); + + if ($order->payment_method !== 'rechnung') { + throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.'); + } + + $day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at); + + return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live()); + } + + private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order { $reference = trim($reference); @@ -168,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference): Orde } $paidNow = false; - $order = DB::transaction(function () use ($order, $provider, $reference, &$paidNow): Order { + $order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order { $order = Order::query()->lockForUpdate()->findOrFail($order->id); if ($order->status === 'bezahlt') { @@ -180,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference): Orde } // Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt. - $order->payments()->updateOrCreate( + $payment = $order->payments()->updateOrCreate( ['provider_reference' => $reference], - ['provider' => $provider, 'status' => 'bestaetigt'], + array_filter( + ['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent], + fn (mixed $value): bool => $value !== null, + ), ); + $this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live); $order->status = 'bezahlt'; $order->save(); $paidNow = true; @@ -207,6 +281,7 @@ private function settle(Order $order, string $provider, string $reference): Orde public function failTestPayment(Order $order, string $reference): Order { $this->assertTestDriver(); + $this->assertTestOrder($order); return DB::transaction(function () use ($order, $reference): Order { $order = Order::query()->lockForUpdate()->findOrFail($order->id); @@ -229,9 +304,14 @@ public function failTestPayment(Order $order, string $reference): Order /** * Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen - * (kostenlose Vergabe, frühere Käufe) bleiben unberührt. + * (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige + * Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe + * veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert. + * Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID + * und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe + * jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung). */ - public function refund(Order $order, string $reason): Order + public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order { $reason = trim($reason); @@ -239,7 +319,17 @@ public function refund(Order $order, string $reason): Order throw new DomainRuleException('Eine Erstattung braucht eine Begründung.'); } - return DB::transaction(function () use ($order, $reason): Order { + $current = Order::query()->findOrFail($order->id); + $stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first(); + $manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at); + $booking = null; + + if ($current->status === 'bezahlt' && $stripePayment !== null) { + $result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason); + $booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()]; + } + + return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order { $order = Order::query()->lockForUpdate()->findOrFail($order->id); if ($order->status !== 'bezahlt') { @@ -262,6 +352,16 @@ public function refund(Order $order, string $reason): Order } } + $payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first(); + $this->journal->recordRefund( + $order, + $payment, + $booking['at'] ?? $manualAt, + $actor, + $reason, + $booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id), + $booking['status'] ?? null, + ); $order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']); $order->status = 'erstattet'; $order->save(); @@ -270,6 +370,28 @@ public function refund(Order $order, string $reason): Order }); } + /** + * Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und + * erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit + * ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung. + */ + public function requestWithdrawal(Order $order, string $note): Order + { + if (! in_array($order->status, ['bezahlt', 'offen'], true)) { + throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.'); + } + + if ($order->withdrawal_requested_at !== null) { + return $order; + } + + $order->withdrawal_requested_at = now(); + $order->withdrawal_note = trim($note) !== '' ? trim($note) : null; + $order->save(); + + return $order; + } + private function assertActive(User $user): void { if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) { @@ -277,6 +399,14 @@ private function assertActive(User $user): void } } + /** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */ + private function assertTestOrder(Order $order): void + { + if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) { + throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.'); + } + } + private function assertTestDriver(): void { if (app()->isProduction() || config('services.payment.driver') !== 'test') { diff --git a/app/Domain/Commerce/Discount/DiscountCalculator.php b/app/Domain/Commerce/Discount/DiscountCalculator.php new file mode 100644 index 0000000..f3cab92 --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountCalculator.php @@ -0,0 +1,74 @@ + $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen) + * @return array Schlüssel => Rabatt in Cent + */ + public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array + { + $discounts = array_fill_keys(array_keys($prices), 0); + + if ($prices === []) { + return $discounts; + } + + if ($kind === DiscountCode::PERCENT) { + $percent = max(0, min(100, (int) $percent)); + + foreach ($prices as $key => $price) { + $discounts[$key] = min($price, intdiv($price * $percent + 50, 100)); + } + + return $discounts; + } + + $sum = array_sum($prices); + $total = min(max(0, (int) $amountCents), $sum); + + if ($total === 0 || $sum === 0) { + return $discounts; + } + + $remainders = []; + $given = 0; + + foreach ($prices as $key => $price) { + $share = intdiv($total * $price, $sum); + $discounts[$key] = $share; + $remainders[$key] = ($total * $price) % $sum; + $given += $share; + } + + $rest = $total - $given; + $order = array_keys($prices); + usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]); + + foreach ($order as $key) { + if ($rest === 0) { + break; + } + + if ($discounts[$key] < $prices[$key]) { + $discounts[$key]++; + $rest--; + } + } + + return $discounts; + } +} diff --git a/app/Domain/Commerce/Discount/DiscountCode.php b/app/Domain/Commerce/Discount/DiscountCode.php new file mode 100644 index 0000000..f062f32 --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountCode.php @@ -0,0 +1,103 @@ + 'datetime', + 'valid_until' => 'datetime', + 'active' => 'boolean', + ]; + } + + /** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */ + public static function normalise(string $input): string + { + return mb_strtoupper((string) preg_replace('/\s+/u', '', $input)); + } + + public function targets(): HasMany + { + return $this->hasMany(DiscountCodeTarget::class); + } + + public function releases(): HasMany + { + return $this->hasMany(DiscountRelease::class)->latest('id'); + } + + public function restricted(): bool + { + return $this->eligibility === self::RESTRICTED; + } + + public function forSelection(): bool + { + return $this->scope === self::SCOPE_SELECTED; + } + + /** Lesbare Höhe: „10 %“ oder „5,00 €“. */ + public function valueLabel(): string + { + return $this->kind === self::PERCENT + ? (int) $this->percent.' %' + : Money::format((int) $this->amount_cents); + } + + /** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */ + public function stateAt(CarbonInterface $now): string + { + return match (true) { + ! $this->active => 'deaktiviert', + $this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht', + $this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen', + default => 'aktiv', + }; + } +} diff --git a/app/Domain/Commerce/Discount/DiscountCodeTarget.php b/app/Domain/Commerce/Discount/DiscountCodeTarget.php new file mode 100644 index 0000000..b41c0a7 --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountCodeTarget.php @@ -0,0 +1,24 @@ +belongsTo(DiscountCode::class, 'discount_code_id'); + } +} diff --git a/app/Domain/Commerce/Discount/DiscountRelease.php b/app/Domain/Commerce/Discount/DiscountRelease.php new file mode 100644 index 0000000..fd80606 --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountRelease.php @@ -0,0 +1,59 @@ + 'datetime', + 'valid_until' => 'datetime', + 'revoked_at' => 'datetime', + ]; + } + + public function code(): BelongsTo + { + return $this->belongsTo(DiscountCode::class, 'discount_code_id'); + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + public function grantor(): BelongsTo + { + return $this->belongsTo(User::class, 'granted_by'); + } + + public function isActiveAt(CarbonInterface $now): bool + { + return $this->revoked_at === null + && $this->granted_at->lessThanOrEqualTo($now) + && ($this->valid_until === null || $this->valid_until->greaterThan($now)); + } +} diff --git a/app/Domain/Commerce/Discount/DiscountResult.php b/app/Domain/Commerce/Discount/DiscountResult.php new file mode 100644 index 0000000..487ca2e --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountResult.php @@ -0,0 +1,83 @@ + $perOffer Kennung der Option => Rabatt in Cent + */ + public function __construct( + public readonly ?DiscountCode $code, + public readonly string $state, + public readonly ?string $message = null, + public readonly array $perOffer = [], + ) {} + + public function applied(): bool + { + return $this->state === self::OK && $this->totalCents() > 0; + } + + public function totalCents(): int + { + return $this->state === self::OK ? array_sum($this->perOffer) : 0; + } + + public function forOffer(int $offerId): int + { + return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0; + } + + /** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */ + public function snapshot(): array + { + return [ + 'code' => $this->code?->code, + 'label' => $this->code?->label, + 'kind' => $this->code?->kind, + 'percent' => $this->code?->percent, + 'amount_cents' => $this->code?->amount_cents, + 'scope' => $this->code?->scope, + 'eligibility' => $this->code?->eligibility, + 'discount_cents' => $this->totalCents(), + ]; + } + + /** Teil der Prüfsumme der Bestellübersicht. */ + public function digestPart(): string + { + $parts = []; + $perOffer = $this->perOffer; + ksort($perOffer); + + foreach ($perOffer as $offerId => $cents) { + $parts[] = $offerId.'='.$cents; + } + + return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts); + } +} diff --git a/app/Domain/Commerce/Discount/DiscountService.php b/app/Domain/Commerce/Discount/DiscountService.php new file mode 100644 index 0000000..cec3208 --- /dev/null +++ b/app/Domain/Commerce/Discount/DiscountService.php @@ -0,0 +1,327 @@ +where('code', $code)->first(); + } + + /** + * @param list $lines nur Positionen, die in die Bestellung eingehen + */ + public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult + { + $now ??= now(); + + $timing = $code->stateAt($now); + + if ($timing !== 'aktiv') { + return new DiscountResult($code, $timing, match ($timing) { + 'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.', + 'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.', + default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').', + }); + } + + if ($code->restricted()) { + if ($user === null) { + return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.'); + } + + if ($this->activeRelease($code, $user, $now, $lock) === null) { + return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.'); + } + } + + $matching = []; + + foreach ($lines as $line) { + if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) { + $matching[$line->offer->id] = (int) $line->currentPriceCents; + } + } + + if ($matching === []) { + return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection() + ? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.' + : 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.'); + } + + $perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching); + $payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer); + + if ($payable < self::MIN_PAYABLE_CENTS) { + return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.'); + } + + return new DiscountResult($code, DiscountResult::OK, null, $perOffer); + } + + /** + * Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der + * Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht + * rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig. + */ + public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool + { + if (! $code->forSelection()) { + return true; + } + + $targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all()); + + if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) { + return true; + } + + $version->loadMissing('lines.bundleVersion'); + + foreach ($version->lines as $line) { + if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) { + return true; + } + + if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) { + return true; + } + } + + return false; + } + + public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease + { + $now ??= now(); + $query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at'); + + if ($lock) { + $query->lockForUpdate(); + } + + return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now)); + } + + /** + * Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten. + * + * @param array $data + * @param list $targets + */ + public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode + { + $code = DiscountCode::normalise((string) ($data['code'] ?? '')); + $label = trim((string) ($data['label'] ?? '')); + + if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) { + throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.'); + } + + if ($label === '') { + throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.'); + } + + if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) { + throw new DomainRuleException('Diesen Code gibt es schon.'); + } + + $kind = (string) ($data['kind'] ?? ''); + $percent = null; + $amount = null; + + if ($kind === DiscountCode::PERCENT) { + $percent = (int) ($data['percent'] ?? 0); + + if ($percent < 1 || $percent > 100) { + throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.'); + } + } elseif ($kind === DiscountCode::AMOUNT) { + $amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null)); + + if ($amount === null || $amount <= 0) { + throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.'); + } + } else { + throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.'); + } + + $scope = (string) ($data['scope'] ?? ''); + $eligibility = (string) ($data['eligibility'] ?? ''); + + if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) { + throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.'); + } + + if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) { + throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.'); + } + + $targets = $this->cleanTargets($targets); + + if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) { + throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.'); + } + + $from = $this->date($data['valid_from'] ?? null); + $until = $this->date($data['valid_until'] ?? null, true); + + if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) { + throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.'); + } + + return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode { + $model = $existing ?? new DiscountCode; + $model->fill([ + 'code' => $code, + 'label' => $label, + 'kind' => $kind, + 'percent' => $percent, + 'amount_cents' => $amount, + 'scope' => $scope, + 'eligibility' => $eligibility, + 'valid_from' => $from, + 'valid_until' => $until, + 'active' => (bool) ($data['active'] ?? true), + 'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null, + ]); + $model->save(); + + $model->targets()->delete(); + + if ($scope === DiscountCode::SCOPE_SELECTED) { + foreach ($targets as $target) { + $model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]); + } + } + + return $model->load('targets'); + }); + } + + public function setActive(DiscountCode $code, bool $active): DiscountCode + { + $code->active = $active; + $code->save(); + + return $code; + } + + /** + * Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht. + */ + public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease + { + if (! $code->restricted()) { + throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.'); + } + + if ($member->party_id === null) { + throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.'); + } + + return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease { + DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail(); + + if ($this->activeRelease($code, $member) !== null) { + throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.'); + } + + if ($until !== null && $until->lessThanOrEqualTo(now())) { + throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.'); + } + + return DiscountRelease::query()->create([ + 'discount_code_id' => $code->id, + 'user_id' => $member->id, + 'granted_by' => $actor?->id, + 'granted_at' => now(), + 'valid_until' => $until, + 'reason' => filled($reason) ? trim((string) $reason) : null, + ]); + }); + } + + /** + * Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert. + */ + public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease + { + return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease { + $release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id); + + if ($release->revoked_at !== null) { + throw new DomainRuleException('Diese Freigabe ist bereits entzogen.'); + } + + $release->revoked_at = now(); + $release->revoked_by = $actor?->id; + $release->reason = filled($reason) ? trim((string) $reason) : $release->reason; + $release->save(); + + return $release; + }); + } + + /** + * @param list $targets + * @return list + */ + private function cleanTargets(array $targets): array + { + $clean = []; + + foreach ($targets as $target) { + $type = (string) ($target['type'] ?? ''); + $id = (int) ($target['id'] ?? 0); + $exists = match ($type) { + DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(), + DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(), + DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(), + default => false, + }; + + if (! $exists) { + throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).'); + } + + $clean[$type.':'.$id] = ['type' => $type, 'id' => $id]; + } + + return array_values($clean); + } + + /** Ein Datum ohne Uhrzeit gilt als Tag: ab Tagesbeginn, als Ende einschließlich des ganzen Tages. */ + private function date(mixed $value, bool $endOfDay = false): ?CarbonInterface + { + if (! filled($value)) { + return null; + } + + $date = Carbon::parse((string) $value, config('app.timezone')); + + return $endOfDay && strlen(trim((string) $value)) <= 10 ? $date->endOfDay() : $date; + } +} diff --git a/app/Domain/Commerce/LedgerEntry.php b/app/Domain/Commerce/LedgerEntry.php new file mode 100644 index 0000000..3dbc8df --- /dev/null +++ b/app/Domain/Commerce/LedgerEntry.php @@ -0,0 +1,57 @@ + 'datetime', + 'amount_cents' => 'integer', + 'live' => 'boolean', + 'derived' => 'boolean', + 'payer' => 'array', + 'order_snapshot' => 'array', + ]; + } + + protected static function booted(): void + { + static::updating(function (): never { + throw new LogicException('Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.'); + }); + static::deleting(function (): never { + throw new LogicException('Das Zahlungsjournal ist unveränderlich. Einträge werden nie gelöscht.'); + }); + } + + public function order(): BelongsTo + { + return $this->belongsTo(Order::class); + } + + public function isRefund(): bool + { + return $this->kind === self::KIND_REFUND; + } +} diff --git a/app/Domain/Commerce/Order.php b/app/Domain/Commerce/Order.php index c6ef61d..2641083 100644 --- a/app/Domain/Commerce/Order.php +++ b/app/Domain/Commerce/Order.php @@ -17,8 +17,39 @@ class Order extends Model 'holder_kind', 'total_cents', 'currency', + 'subtotal_cents', + 'discount_cents', + 'discount_code_id', + 'discount_snapshot', + 'payment_method', + 'terms_accepted_at', + 'terms_snapshot', + 'withdrawal_requested_at', + 'withdrawal_note', ]; + protected function casts(): array + { + return [ + 'discount_snapshot' => 'array', + 'terms_snapshot' => 'array', + 'terms_accepted_at' => 'datetime', + 'withdrawal_requested_at' => 'datetime', + ]; + } + + /** Listenpreise vor Rabatt; bei älteren Bestellungen die Summe der Positionen. */ + public function subtotal(): int + { + return (int) ($this->subtotal_cents ?? $this->total_cents ?? $this->lines->sum('price_cents')); + } + + /** Endgültiger Zahlbetrag. */ + public function payable(): int + { + return (int) ($this->total_cents ?? $this->lines->sum('price_cents')); + } + public function user(): BelongsTo { return $this->belongsTo(User::class); diff --git a/app/Domain/Commerce/OrderLine.php b/app/Domain/Commerce/OrderLine.php index f37479c..d2e2283 100644 --- a/app/Domain/Commerce/OrderLine.php +++ b/app/Domain/Commerce/OrderLine.php @@ -22,8 +22,17 @@ class OrderLine extends Model 'tax_class', 'grant_kind', 'holder_party_id', + 'licence_scope', + 'trainer_count', + 'discount_cents', ]; + /** Preis dieser Position nach Rabatt. */ + public function payable(): int + { + return (int) $this->price_cents - (int) $this->discount_cents; + } + public function order(): BelongsTo { return $this->belongsTo(Order::class); diff --git a/app/Domain/Commerce/OwnershipCheck.php b/app/Domain/Commerce/OwnershipCheck.php index 04e211c..7bf80c1 100644 --- a/app/Domain/Commerce/OwnershipCheck.php +++ b/app/Domain/Commerce/OwnershipCheck.php @@ -2,6 +2,7 @@ namespace App\Domain\Commerce; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\OfferVersion; use App\Domain\Entitlement\Grant; use App\Domain\Entitlement\GrantStatus; @@ -27,12 +28,23 @@ public function covers(Party $holder, OfferVersion $version): bool $byAcquisition = Grant::query() ->where('status', GrantStatus::Aktiv) ->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id)) + ->with('acquisition') ->get() ->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now)) && ($grant->valid_until === null || $grant->valid_until->greaterThan($now))) ->groupBy('acquisition_id'); + $wanted = LicenceScope::key($version->licence_scope, $version->trainer_count); + foreach ($byAcquisition as $grants) { + $conditions = (array) ($grants->first()->acquisition?->conditions ?? []); + + // Gleicher Umfang heißt auch gleicher Nutzerkreis: Eine Einzellizenz deckt keine Mehrfachlizenz ab und + // umgekehrt (der Nutzerkreis wird nicht aus Zweck oder Preis abgeleitet). + if (LicenceScope::key($conditions['licence_scope'] ?? null, isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null) !== $wanted) { + continue; + } + $have = []; foreach ($grants as $grant) { diff --git a/app/Domain/Commerce/Payment.php b/app/Domain/Commerce/Payment.php index 782f04a..88a8873 100644 --- a/app/Domain/Commerce/Payment.php +++ b/app/Domain/Commerce/Payment.php @@ -12,6 +12,9 @@ class Payment extends Model 'provider', 'status', 'provider_reference', + 'provider_payment_ref', + 'amount_cents', + 'confirmed_by', ]; public function order(): BelongsTo diff --git a/app/Domain/Commerce/PaymentJournal.php b/app/Domain/Commerce/PaymentJournal.php new file mode 100644 index 0000000..7673a48 --- /dev/null +++ b/app/Domain/Commerce/PaymentJournal.php @@ -0,0 +1,353 @@ +firstOrCreate( + ['kind' => LedgerEntry::KIND_PAYMENT, 'provider' => $payment->provider, 'provider_reference' => $payment->provider_reference], + [ + 'order_id' => $order->id, + 'payment_id' => $payment->id, + 'occurred_at' => $this->utc($occurredAt), + 'amount_cents' => $order->payable(), + 'currency' => (string) ($order->currency ?? 'EUR'), + 'provider_payment_ref' => $payment->provider_payment_ref, + 'live' => $live, + 'actor_id' => $actor?->id, + 'actor_name' => $actor?->name, + 'payer' => $this->payer($order), + 'order_snapshot' => $this->orderSnapshot($order), + ], + ); + } + + /** + * Erstattung: eine Gegenbuchung in Höhe des Zahlbetrags. Das Echt-Kennzeichen folgt dem Zahlungseingang der + * Bestellung. `$reference` ist bei Stripe die Rückzahlungs-ID (re_...), sonst eine Referenz der Rückzahlung. + */ + public function recordRefund(Order $order, ?Payment $payment, CarbonInterface $occurredAt, ?User $actor, string $reason, string $reference, ?string $providerStatus = null): LedgerEntry + { + $original = LedgerEntry::query()->where('order_id', $order->id)->where('kind', LedgerEntry::KIND_PAYMENT)->orderBy('id')->first(); + + return LedgerEntry::query()->firstOrCreate( + ['kind' => LedgerEntry::KIND_REFUND, 'provider' => $payment?->provider ?? $original?->provider ?? 'unbekannt', 'provider_reference' => $reference], + [ + 'order_id' => $order->id, + 'payment_id' => $payment?->id, + 'occurred_at' => $this->utc($occurredAt), + 'amount_cents' => -$order->payable(), + 'currency' => (string) ($order->currency ?? 'EUR'), + 'provider_payment_ref' => $payment?->provider_payment_ref, + 'provider_status' => $providerStatus, + 'live' => $original?->live ?? false, + 'actor_id' => $actor?->id, + 'actor_name' => $actor?->name, + 'reason' => $reason, + 'payer' => $original?->payer ?? $this->payer($order), + 'order_snapshot' => $original?->order_snapshot ?? $this->orderSnapshot($order), + ], + ); + } + + /** + * Ein Datum ohne Uhrzeit (Zahlungseingang auf dem Konto): Beginn dieses Tages in deutscher Zeit. Nicht in der + * Zukunft; `$notBefore` ist der früheste zulässige Tag (Bestelldatum). + */ + public static function dayOf(string|CarbonInterface $date, ?CarbonInterface $notBefore = null): CarbonImmutable + { + $day = CarbonImmutable::parse($date instanceof CarbonInterface ? $date->format('Y-m-d') : $date, self::TIMEZONE)->startOfDay(); + + if ($day->greaterThan(CarbonImmutable::now(self::TIMEZONE)->endOfDay())) { + throw new DomainRuleException('Das Datum darf nicht in der Zukunft liegen.'); + } + + if ($notBefore !== null && $day->lessThan(CarbonImmutable::instance($notBefore)->setTimezone(self::TIMEZONE)->startOfDay())) { + throw new DomainRuleException('Das Datum liegt vor dem Bestelldatum.'); + } + + return $day; + } + + /** + * Von und bis (einschließlich) eines Zeitraums in UTC. + * + * @param 'monat'|'quartal'|'jahr' $mode + * @return array{0: CarbonImmutable, 1: CarbonImmutable} + */ + public static function range(string $mode, int $year, int $index): array + { + $from = CarbonImmutable::create($year, 1, 1, 0, 0, 0, self::TIMEZONE); + + $from = match ($mode) { + 'monat' => $from->setMonth(max(1, min(12, $index)))->startOfMonth(), + 'quartal' => $from->setMonth((max(1, min(4, $index)) - 1) * 3 + 1)->startOfMonth(), + default => $from->startOfYear(), + }; + $to = match ($mode) { + 'monat' => $from->endOfMonth(), + 'quartal' => $from->addMonths(2)->endOfMonth(), + default => $from->endOfYear(), + }; + + return [$from->setTimezone('UTC'), $to->setTimezone('UTC')]; + } + + /** + * @param 'alle'|'eingang'|'erstattung' $kind + * @param 'alle'|'stripe'|'ueberweisung'|'test' $provider + * @param 'echt'|'test'|'alle' $operation + * @return Collection + */ + public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection + { + return LedgerEntry::query() + ->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)]) + ->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))) + ->when($kind !== 'alle', fn ($query) => $query->where('kind', $kind)) + ->when($provider !== 'alle', fn ($query) => $query->where('provider', $provider)) + ->when($operation === 'echt', fn ($query) => $query->where('live', true)) + ->when($operation === 'test', fn ($query) => $query->where('live', false)) + ->orderBy('occurred_at') + ->orderBy('id') + ->get(); + } + + /** + * Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt, + * wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen + * Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen + * Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte. + * + * @param Collection $entries + * @return array Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung) + */ + public function shares(Collection $entries, int $offerId): array + { + $perOrder = OrderLine::query() + ->whereIn('order_id', $entries->pluck('order_id')->unique()->all()) + ->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)) + ->get() + ->groupBy('order_id') + ->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable())); + $shares = []; + + foreach ($entries as $entry) { + $share = (int) ($perOrder[$entry->order_id] ?? 0); + $shares[$entry->id] = $entry->isRefund() ? -$share : $share; + } + + return $shares; + } + + /** + * Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt. + */ + public function countByOperation(CarbonInterface $from, CarbonInterface $to): array + { + $rows = LedgerEntry::query()->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])->get(['live']); + + return ['echt' => $rows->where('live', true)->count(), 'test' => $rows->where('live', false)->count()]; + } + + /** + * @param Collection $entries + * @param array|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen + * @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int} + */ + public static function totals(Collection $entries, ?array $shares = null): array + { + $in = $entries->where('kind', LedgerEntry::KIND_PAYMENT); + $out = $entries->where('kind', LedgerEntry::KIND_REFUND); + $amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0); + + return [ + 'eingang' => (int) $in->sum($amount), + 'erstattung' => (int) abs($out->sum($amount)), + 'saldo' => (int) $entries->sum($amount), + 'anzahl_eingang' => $in->count(), + 'anzahl_erstattung' => $out->count(), + ]; + } + + public static function providerLabel(string $provider): string + { + return match ($provider) { + 'stripe' => 'Stripe', + 'ueberweisung' => 'Überweisung', + 'test' => 'Testzahlung', + default => $provider, + }; + } + + public static function local(CarbonInterface $moment): CarbonImmutable + { + return CarbonImmutable::instance($moment)->setTimezone(self::TIMEZONE); + } + + /** Hat die Bewegung eine belegte Uhrzeit? Datumsbuchungen (Überweisung) beginnen um 00:00 deutscher Zeit. */ + public static function hasTime(LedgerEntry $entry): bool + { + return self::local($entry->occurred_at)->format('H:i:s') !== '00:00:00'; + } + + /** + * Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg. + * + * @param Collection $entries + * @param array|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“ + */ + public static function csv(Collection $entries, ?array $shares = null): string + { + $header = [ + 'Buchungsnummer', 'Datum', 'Uhrzeit', 'Art', 'Betrag EUR', 'Währung', 'Bestellung', 'Zahlungsweg', 'Betrieb', 'Herkunft', + 'Referenz', 'Zahlungsvorgang', 'Status beim Anbieter', 'Lizenzinhaber', 'Rechnungsempfänger', 'Zusatz', 'Straße', 'PLZ', 'Ort', 'Land', + 'Besteller', 'Zwischensumme EUR', 'Rabatt EUR', 'Rabattcode', 'Positionen', 'Begründung', 'Gebucht von', 'Gebucht am', + ...($shares === null ? [] : ['Anteil des Angebots EUR']), + ]; + $rows = [$header]; + + foreach ($entries as $entry) { + $local = self::local($entry->occurred_at); + $payer = (array) $entry->payer; + $billing = (array) ($payer['billing'] ?? []); + $snapshot = (array) $entry->order_snapshot; + $lines = collect($snapshot['lines'] ?? [])->map(fn (array $line): string => ($line['name'] ?? '').' '.self::decimal((int) ($line['price_cents'] ?? 0) - (int) ($line['discount_cents'] ?? 0)))->implode(' | '); + + $rows[] = [ + $entry->id, + $local->format('d.m.Y'), + self::hasTime($entry) ? $local->format('H:i:s') : '', + $entry->isRefund() ? 'Erstattung' : 'Zahlungseingang', + self::decimal($entry->amount_cents), + $entry->currency, + $entry->order_id, + self::providerLabel($entry->provider), + $entry->live ? 'echt' : 'Test', + $entry->derived ? 'nachgetragen (Datum abgeleitet)' : 'belegt', + $entry->provider_reference, + $entry->provider_payment_ref, + $entry->provider_status, + $payer['holder'] ?? null, + $billing['recipient'] ?? null, + $billing['line2'] ?? null, + $billing['street'] ?? null, + $billing['postal_code'] ?? null, + $billing['city'] ?? null, + $billing['country'] ?? null, + $payer['buyer'] ?? null, + self::decimal((int) ($snapshot['subtotal_cents'] ?? 0)), + self::decimal((int) ($snapshot['discount_cents'] ?? 0)), + $snapshot['discount_code'] ?? null, + $lines, + $entry->reason, + $entry->actor_name, + self::local($entry->created_at)->format('d.m.Y H:i:s'), + ...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]), + ]; + } + + $handle = fopen('php://temp', 'r+'); + + foreach ($rows as $row) { + fputcsv($handle, array_map(self::cell(...), $row), ';', '"', '\\', "\r\n"); + } + + rewind($handle); + $csv = (string) stream_get_contents($handle); + fclose($handle); + + return "\xEF\xBB\xBF".$csv; + } + + public static function decimal(int $cents): string + { + return number_format($cents / 100, 2, ',', ''); + } + + /** Verhindert, dass ein Zellinhalt in der Tabellenkalkulation als Formel ausgeführt wird. */ + private static function cell(mixed $value): string + { + $text = (string) $value; + + if ($text !== '' && preg_match('/^[=+\-@\t\r]/', $text) === 1 && preg_match('/^-?\d+(,\d+)?$/', $text) !== 1) { + return "'".$text; + } + + return $text; + } + + private function utc(CarbonInterface $moment): CarbonImmutable + { + return CarbonImmutable::instance($moment)->setTimezone('UTC'); + } + + /** + * Zahler zum Zeitpunkt der Bewegung. Spätere Änderungen an Profil oder Rechnungsadresse ändern sie nicht. + * + * @return array + */ + private function payer(Order $order): array + { + $order->loadMissing('user', 'party.billingAddress'); + $address = $order->party?->billingAddress; + + return [ + 'holder' => $order->party?->display_name, + 'holder_kind' => $order->holder_kind, + 'buyer' => $order->user?->name, + 'buyer_email' => $order->user?->email, + 'billing' => $address === null ? null : [ + 'recipient' => $address->recipient, + 'line2' => $address->line2, + 'street' => $address->street, + 'postal_code' => $address->postal_code, + 'city' => $address->city, + 'country' => $address->country, + ], + ]; + } + + /** + * @return array + */ + private function orderSnapshot(Order $order): array + { + $order->loadMissing('lines'); + + return [ + 'subtotal_cents' => $order->subtotal(), + 'discount_cents' => (int) $order->discount_cents, + 'discount_code' => $order->discount_snapshot['code'] ?? null, + 'lines' => $order->lines->map(fn (OrderLine $line): array => [ + 'name' => $line->offer_name, + 'price_cents' => (int) $line->price_cents, + 'discount_cents' => (int) $line->discount_cents, + ])->values()->all(), + ]; + } +} diff --git a/app/Domain/Commerce/ProductOptions.php b/app/Domain/Commerce/ProductOptions.php index 27bb74f..76077ac 100644 --- a/app/Domain/Commerce/ProductOptions.php +++ b/app/Domain/Commerce/ProductOptions.php @@ -2,8 +2,10 @@ namespace App\Domain\Commerce; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Catalog\EditorialProfileReader; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; @@ -37,6 +39,125 @@ public function forComposition(Composition $composition): array return $options; } + /** + * Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung + * dieses Paket verkauft. + * + * @return list> + */ + public function forBundle(Bundle $bundle): array + { + $options = []; + + foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) { + $version = $this->offers->purchasableVersion($offer); + + if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) { + $options[] = $this->describe($offer, $version); + } + } + + return $options; + } + + /** + * Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null. + */ + public function bundleOf(OfferVersion $version): ?Bundle + { + $version->loadMissing('lines.bundleVersion.bundle'); + + return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle; + } + + /** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */ + public function groupKey(Offer $offer): ?string + { + if ($offer->composition_id !== null) { + return 'c:'.$offer->composition_id; + } + + if ($offer->standalone_bundle) { + $version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first(); + $bundle = $version === null ? null : $this->bundleOf($version); + + return $bundle === null ? null : 'b:'.$bundle->id; + } + + return null; + } + + /** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */ + public function pageUrl(Offer $offer): ?string + { + if ($offer->composition_id !== null) { + return route('public.program', $offer->composition_id); + } + + $key = $this->groupKey($offer); + + return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null; + } + + /** + * Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen. + * + * @return array + */ + public function bundleSummaries(): array + { + $summary = []; + + foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) { + $version = $this->offers->purchasableVersion($offer); + $bundle = $version === null ? null : $this->bundleOf($version); + + if ($bundle === null) { + continue; + } + + $current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0]; + $summary[$bundle->id] = [ + 'from_cents' => min($current['from_cents'], (int) $version->price_cents), + 'count' => $current['count'] + 1, + ]; + } + + return $summary; + } + + /** + * Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der + * Optionen, mit Name und Kurzbeschreibung aus der Redaktion. + * + * @param list> $options + * @return list + */ + public function bundleContents(array $options): array + { + $contents = []; + + foreach ($options as $option) { + $option['version']->loadMissing('resolvedScopes.article'); + + foreach ($option['version']->resolvedScopes as $item) { + $article = $item->article; + + if ($article === null || isset($contents[$article->id])) { + continue; + } + + $profile = app(EditorialProfileReader::class)->read($article, 'detail'); + $contents[$article->id] = [ + 'title' => $this->articleTitle($article), + 'teaser' => trim((string) ($profile->value('teaser') ?? '')), + ]; + } + } + + return array_values($contents); + } + /** * Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option. * @@ -89,6 +210,10 @@ public function describe(Offer $offer, OfferVersion $version): array 'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen', 'holder_kind' => $version->holder_kind, 'term' => self::termLabel($version), + 'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count), + 'licence_scope' => $version->licence_scope, + 'trainer_count' => $version->trainer_count, + 'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count), 'scope' => $scope, ]; } diff --git a/app/Domain/Commerce/Receipt/PaymentReceipt.php b/app/Domain/Commerce/Receipt/PaymentReceipt.php new file mode 100644 index 0000000..aaf3f73 --- /dev/null +++ b/app/Domain/Commerce/Receipt/PaymentReceipt.php @@ -0,0 +1,173 @@ +derived; + } + + public static function filename(LedgerEntry $entry): string + { + return ($entry->isRefund() ? 'Erstattungsbeleg' : 'Zahlungsbeleg').'-Bestellung-'.$entry->order_id.'-Buchung-'.$entry->id.'.pdf'; + } + + public static function render(LedgerEntry $entry): string + { + $refund = $entry->isRefund(); + $payer = (array) $entry->payer; + $billing = (array) ($payer['billing'] ?? []); + $snapshot = (array) $entry->order_snapshot; + $money = fn (int $cents): string => Money::format($cents); + $when = PaymentJournal::local($entry->occurred_at); + $title = $refund ? 'Erstattungsbeleg' : 'Zahlungsbeleg'; + $pdf = new PdfDocument; + $pdf->addPage(); + $y = 790.0; + + $pdf->text(self::LEFT, $y, $title, 22, true); + $issuer = array_values(array_filter(array_map('trim', explode('|', (string) config('shop.receipt.issuer'))))); + $yIssuer = $y + 4; + + foreach ($issuer as $i => $line) { + $pdf->textRight(self::RIGHT, $yIssuer - $i * 12, $line, 9, $i === 0); + } + + $y = min($y - 26, $yIssuer - 12 * count($issuer) - 8); + + if (! $entry->live) { + $pdf->text(self::LEFT, $y, 'TESTZAHLUNG - kein Umsatz, kein Beleg für eine echte Zahlung', 10, true); + $y -= 16; + } + + $y -= 6; + $meta = [ + ['Bestellung', (string) $entry->order_id], + ['Buchung', (string) $entry->id], + [$refund ? 'Rückzahlung am' : 'Zahlung am', $when->format('d.m.Y').(PaymentJournal::hasTime($entry) ? ', '.$when->format('H:i').' Uhr' : '')], + ['Zahlungsweg', PaymentJournal::providerLabel($entry->provider)], + ['Referenz', (string) $entry->provider_reference], + ]; + + foreach ($meta as [$label, $value]) { + $pdf->text(self::LEFT, $y, $label, 9); + + foreach (PdfDocument::wrap($value, 330, 10) as $i => $part) { + $pdf->text(160, $y - $i * 12, $part, 10); + } + + $y -= 14 * max(1, count(PdfDocument::wrap($value, 330, 10))); + } + + $y -= 10; + $pdf->text(self::LEFT, $y, $refund ? 'Erstattung an' : 'Zahler', 9); + $recipient = $billing !== [] ? array_values(array_filter([ + $billing['recipient'] ?? null, + $billing['line2'] ?? null, + $billing['street'] ?? null, + trim(($billing['postal_code'] ?? '').' '.($billing['city'] ?? '')), + ($billing['country'] ?? 'DE') !== 'DE' ? (BillingAddress::COUNTRIES[$billing['country']] ?? $billing['country']) : null, + ])) : array_values(array_filter([$payer['holder'] ?? null, 'Keine Rechnungsadresse hinterlegt'])); + + foreach ($recipient as $i => $line) { + $pdf->text(160, $y - $i * 13, (string) $line, 10, $i === 0); + } + + $y -= 13 * count($recipient); + + if (filled($payer['buyer'] ?? null) && ($payer['buyer'] ?? '') !== ($billing['recipient'] ?? $payer['holder'] ?? '')) { + $pdf->text(160, $y, 'Bestellt von '.$payer['buyer'], 9); + $y -= 13; + } + + $y -= 16; + $pdf->line(self::LEFT, $y + 12, self::RIGHT, $y + 12, 0.8); + $pdf->text(self::LEFT, $y, 'Position', 9, true); + $pdf->textRight(400, $y, 'Preis', 9, true); + $pdf->textRight(472, $y, 'Rabatt', 9, true); + $pdf->textRight(self::RIGHT, $y, 'Betrag', 9, true); + $y -= 6; + $pdf->line(self::LEFT, $y, self::RIGHT, $y, 0.4); + $y -= 14; + + foreach ((array) ($snapshot['lines'] ?? []) as $line) { + $lines = PdfDocument::wrap((string) ($line['name'] ?? 'Angebot'), 270, 10); + + if ($y - 13 * count($lines) < 140) { + $pdf->addPage(); + $y = 790.0; + } + + $price = (int) ($line['price_cents'] ?? 0); + $discount = (int) ($line['discount_cents'] ?? 0); + + foreach ($lines as $i => $part) { + $pdf->text(self::LEFT, $y - $i * 13, $part, 10); + } + + $pdf->textRight(400, $y, $money($price), 10); + $pdf->textRight(472, $y, $discount > 0 ? '-'.$money($discount) : '', 10); + $pdf->textRight(self::RIGHT, $y, $money($price - $discount), 10); + $y -= 13 * count($lines) + 4; + } + + $y -= 6; + $pdf->line(self::LEFT, $y + 10, self::RIGHT, $y + 10, 0.4); + $y -= 6; + + if ((int) ($snapshot['discount_cents'] ?? 0) > 0) { + $pdf->text(300, $y, 'Zwischensumme', 10); + $pdf->textRight(self::RIGHT, $y, $money((int) ($snapshot['subtotal_cents'] ?? 0)), 10); + $y -= 14; + $pdf->text(300, $y, 'Rabatt'.(filled($snapshot['discount_code'] ?? null) ? ' (Code '.$snapshot['discount_code'].')' : ''), 10); + $pdf->textRight(self::RIGHT, $y, '-'.$money((int) $snapshot['discount_cents']), 10); + $y -= 14; + } + + $pdf->text(300, $y, $refund ? 'Erstatteter Betrag' : 'Gezahlter Betrag', 11, true); + $pdf->textRight(self::RIGHT, $y, $money(abs($entry->amount_cents)), 11, true); + $y -= 26; + + $notes = [ + $refund + ? 'Dieser Beleg bestätigt die Rückzahlung zur genannten Bestellung. Die Berechtigungen aus dieser Bestellung sind widerrufen.' + : 'Dieser Beleg bestätigt die Zahlung zur genannten Bestellung.', + 'Er enthält keine Rechnungsnummer und keine steuerlichen Angaben und wurde aus den bei der Zahlung festgehaltenen Angaben erstellt.', + ]; + + if (filled(config('shop.receipt.note'))) { + $notes[] = (string) config('shop.receipt.note'); + } + + foreach ($notes as $note) { + foreach (PdfDocument::wrap($note, self::RIGHT - self::LEFT, 9) as $part) { + $pdf->text(self::LEFT, $y, $part, 9); + $y -= 12; + } + + $y -= 3; + } + + return $pdf->output($title.' Bestellung '.$entry->order_id); + } +} diff --git a/app/Domain/Commerce/Receipt/PdfDocument.php b/app/Domain/Commerce/Receipt/PdfDocument.php new file mode 100644 index 0000000..dabcfd2 --- /dev/null +++ b/app/Domain/Commerce/Receipt/PdfDocument.php @@ -0,0 +1,173 @@ + */ + private array $pages = []; + + public function addPage(): void + { + $this->pages[] = ''; + } + + public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void + { + $this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text))); + } + + public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void + { + $this->text($xRight - self::width($text, $size, $bold), $y, $text, $size, $bold); + } + + public function line(float $x1, float $y1, float $x2, float $y2, float $width = 0.5): void + { + $this->append(sprintf("%s w %s %s m %s %s l S\n", $this->n($width), $this->n($x1), $this->n($y1), $this->n($x2), $this->n($y2))); + } + + /** + * Zeilenumbruch nach Wörtern. Die Breite ist eine bewusst großzügige Schätzung der Helvetica-Breiten, damit nichts + * über den Rand läuft; ein einzelnes zu langes Wort wird hart getrennt. + * + * @return list + */ + public static function wrap(string $text, float $maxWidth, float $size = 10, bool $bold = false): array + { + $lines = []; + + foreach (preg_split('/\R/u', trim($text)) ?: [''] as $paragraph) { + $current = ''; + + foreach (preg_split('/\s+/u', trim($paragraph)) ?: [] as $word) { + while (mb_strlen($word) > 1 && self::width($word, $size, $bold) > $maxWidth) { + $cut = mb_strlen($word) - 1; + + while ($cut > 1 && self::width(mb_substr($word, 0, $cut), $size, $bold) > $maxWidth) { + $cut--; + } + + if ($current !== '') { + $lines[] = $current; + $current = ''; + } + + $lines[] = mb_substr($word, 0, $cut); + $word = mb_substr($word, $cut); + } + + $candidate = $current === '' ? $word : $current.' '.$word; + + if ($current !== '' && self::width($candidate, $size, $bold) > $maxWidth) { + $lines[] = $current; + $current = $word; + } else { + $current = $candidate; + } + } + + $lines[] = $current; + } + + return $lines; + } + + /** Geschätzte Textbreite in Punkt (Helvetica; Ziffern und Währung exakt, Buchstaben großzügig). */ + public static function width(string $text, float $size = 10, bool $bold = false): float + { + $units = 0.0; + + foreach (mb_str_split($text) as $char) { + $width = match (true) { + $char === ' ', $char === ',', $char === '.', $char === ':', $char === ';', $char === "'", $char === '|', $char === 'i', $char === 'l', $char === 'I', $char === 'j', $char === 't', $char === 'f' => 0.3, + $char === '-', $char === '(', $char === ')', $char === '/', $char === 'r' => 0.35, + ctype_digit($char), $char === '€' => 0.556, + mb_strtoupper($char) === $char && $char !== mb_strtolower($char) => 0.75, + $char === 'm', $char === 'w', $char === 'M', $char === 'W' => 0.85, + default => 0.57, + }; + // Fette Ziffern, Währung und Satzzeichen sind in Helvetica so breit wie normale; nur Buchstaben werden breiter. + $units += $bold && ctype_alpha($char) ? $width * 1.08 : $width; + } + + return $units * $size; + } + + /** + * @param string $title Nur ASCII (Dokumenttitel) + */ + public function output(string $title, ?string $keywords = null): string + { + $pages = $this->pages === [] ? [''] : $this->pages; + $objects = []; + $objects[1] = '<< /Type /Catalog /Pages 2 0 R >>'; + $kids = []; + $next = 6; + + foreach ($pages as $stream) { + $kids[] = $next.' 0 R'; + $objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.($next + 1).' 0 R >>'; + $objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream'; + $next += 2; + } + + $objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>'; + $objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>'; + $objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>'; + $ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value)); + $objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>'; + ksort($objects); + + $pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n"; + $offsets = []; + + foreach ($objects as $number => $body) { + $offsets[$number] = strlen($pdf); + $pdf .= $number." 0 obj\n".$body."\nendobj\n"; + } + + $xref = strlen($pdf); + $pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n"; + + foreach ($offsets as $offset) { + $pdf .= sprintf("%010d 00000 n \n", $offset); + } + + return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n"; + } + + private function append(string $operators): void + { + if ($this->pages === []) { + $this->addPage(); + } + + $this->pages[array_key_last($this->pages)] .= $operators; + } + + private function n(float $value): string + { + return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.') ?: '0'; + } + + /** Windows-1252, geklammert für PDF-Zeichenketten. */ + private static function escape(string $text): string + { + $text = strtr($text, ["\u{2212}" => '-', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ', "\u{202F}" => ' ']); + $text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/u', '', $text); + $encoded = mb_convert_encoding($text, 'Windows-1252', 'UTF-8'); + + return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $encoded); + } +} diff --git a/app/Domain/Commerce/SalesTerms.php b/app/Domain/Commerce/SalesTerms.php new file mode 100644 index 0000000..56f4c81 --- /dev/null +++ b/app/Domain/Commerce/SalesTerms.php @@ -0,0 +1,127 @@ + Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt). + * + * @return array, required: bool}> + */ + public static function pages(): array + { + return [ + 'agb' => ['label' => 'Allgemeine Geschäftsbedingungen', 'paths' => ['/agb'], 'required' => true], + 'lizenz' => ['label' => 'Lizenzbedingungen', 'paths' => ['/lizenzbedingungen', '/lizenz'], 'required' => true], + 'widerruf' => ['label' => 'Widerrufsbelehrung', 'paths' => ['/widerruf', '/widerrufsbelehrung'], 'required' => true], + 'impressum' => ['label' => 'Impressum', 'paths' => ['/impressum'], 'required' => true], + 'datenschutz' => ['label' => 'Datenschutzerklärung', 'paths' => ['/datenschutz'], 'required' => true], + ]; + } + + /** + * Veröffentlichte Seite des Rechtstextes oder null. + */ + public static function page(string $key): ?Page + { + $definition = self::pages()[$key] ?? null; + + if ($definition === null) { + return null; + } + + return Page::query() + ->whereIn('path', $definition['paths']) + ->whereNotNull('published_revision_id') + ->orderBy('id') + ->first(); + } + + public static function url(string $key): ?string + { + return self::page($key)?->publicUrl(); + } + + /** + * Fehlende oder unveröffentlichte Rechtstexte (Schlüssel => Bezeichnung). + * + * @return array + */ + public static function missingPages(): array + { + $missing = []; + + foreach (self::pages() as $key => $definition) { + if ($definition['required'] && self::page($key) === null) { + $missing[$key] = $definition['label']; + } + } + + return $missing; + } + + /** + * Zustimmungen im Checkout: Schlüssel => Wortlaut (ENTWURF). + * + * @return array + */ + public static function consents(): array + { + return [ + 'agb' => 'Ich habe die Allgemeinen Geschäftsbedingungen und die Lizenzbedingungen gelesen und stimme ihnen zu.', + 'sofort' => 'Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird und die digitalen Inhalte sofort nach Zahlungseingang bereitgestellt werden. Mir ist bekannt, dass ich mein Widerrufsrecht verliere, sobald die Ausführung begonnen hat.', + ]; + } + + /** + * Prüft die Zustimmungen und liefert den Nachweis für die Bestellung (Wortlaut, Fassung, Seiten, Zeit). + * + * @param array $accepted Schlüssel => angekreuzt + * @return array + */ + public static function proof(array $accepted): array + { + $texts = []; + + foreach (self::consents() as $key => $wording) { + if (empty($accepted[$key])) { + throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.'); + } + + $texts[$key] = $wording; + } + + $pages = []; + + foreach (array_keys(self::pages()) as $key) { + $page = self::page($key); + $pages[$key] = $page === null ? null : ['path' => $page->path, 'revision_id' => $page->published_revision_id]; + } + + return [ + 'version' => self::VERSION, + 'consents' => $texts, + 'pages' => $pages, + 'recorded_at' => now()->toIso8601String(), + ]; + } +} diff --git a/app/Domain/Commerce/Shop.php b/app/Domain/Commerce/Shop.php index 93c7070..cffb5ff 100644 --- a/app/Domain/Commerce/Shop.php +++ b/app/Domain/Commerce/Shop.php @@ -3,9 +3,12 @@ namespace App\Domain\Commerce; /** - * Etappe 1 verwendet ausschließlich Testzahlung und erteilt keine Produktivfreigabe. Der Shop (Warenkorb, Kasse, - * Kopflink) ist deshalb nur aktiv, wenn die Umgebung nicht Produktion ist und der Zahlungstreiber „test“ gilt. - * Dieselbe Bedingung gilt für die Testzahlung der Bestellseite. + * Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist. + * + * Test und Sandbox: nicht in Produktion, Zahlungstreiber „test“ oder „stripe“ (Testschlüssel). + * Produktion: nur mit der ausdrücklichen Produktivfreigabe (`SHOP_LIVE_RELEASE`, Entscheidung von Lars), dem + * Zahlungstreiber „stripe“ mit Live-Schlüssel und veröffentlichten Rechtstexten. Fehlt eines davon, bleibt der Shop in + * Produktion abgeschaltet. Die Freigabe ist standardmäßig aus. */ final class Shop { @@ -14,14 +17,45 @@ public static function driver(): string return (string) config('services.payment.driver'); } - public static function enabled(): bool + /** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */ + public static function live(): bool { - return ! app()->isProduction() && in_array(self::driver(), ['test', 'stripe'], true); + return app()->isProduction() + && config('shop.live_release') === true + && self::driver() === 'stripe' + && self::liveKey() + && SalesTerms::missingPages() === []; } - /** Stripe-Kasse (Etappe 1: nur Testmodus, nie in Produktion). */ + public static function enabled(): bool + { + if (app()->isProduction()) { + return self::live(); + } + + return in_array(self::driver(), ['test', 'stripe'], true); + } + + /** Stripe-Kasse: im Test nur mit Testschlüsseln, in Produktion nur nach der Produktivfreigabe. */ public static function stripe(): bool { - return ! app()->isProduction() && self::driver() === 'stripe'; + if (app()->isProduction()) { + return self::live(); + } + + return self::driver() === 'stripe'; + } + + /** Kauf auf Rechnung für Organisationen (manuelle Rechnung, Zahlungseingang durch den Betreiber). */ + public static function invoice(): bool + { + return self::enabled() && (bool) config('shop.invoice', true); + } + + private static function liveKey(): bool + { + $secret = (string) config('services.stripe.secret'); + + return str_starts_with($secret, 'sk_live_') || str_starts_with($secret, 'rk_live_'); } } diff --git a/app/Domain/Commerce/Stripe/StripeGateway.php b/app/Domain/Commerce/Stripe/StripeGateway.php index 3634e30..37a4819 100644 --- a/app/Domain/Commerce/Stripe/StripeGateway.php +++ b/app/Domain/Commerce/Stripe/StripeGateway.php @@ -3,7 +3,11 @@ namespace App\Domain\Commerce\Stripe; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Commerce\Money; use App\Domain\Commerce\Order; +use App\Domain\Commerce\Payment; +use App\Domain\Commerce\Shop; +use Carbon\CarbonImmutable; use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\Response; @@ -11,9 +15,11 @@ use Illuminate\Support\Facades\Log; /** - * Stripe-Kasse (Checkout Session) für die Testzahlung in Etappe 1. Ausschließlich Testschlüssel: Ein Live-Schlüssel - * oder die Produktionsumgebung werden abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten - * berühren diese Anwendung nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). + * Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort + * abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen + * Fall wird abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten berühren diese Anwendung + * nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). Der Betrag je Position ist der + * Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht. */ class StripeGateway { @@ -24,7 +30,7 @@ class StripeGateway */ public function checkoutFor(Order $order): array { - $this->assertSandbox(); + $this->assertAllowed(); $order->loadMissing('lines', 'user'); $taxRate = $this->taxRate(); @@ -32,6 +38,10 @@ public function checkoutFor(Order $order): array throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.'); } + if ($order->payment_method === 'rechnung') { + throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.'); + } + $open = $this->reusableSession($order); if ($open !== null) { @@ -51,12 +61,18 @@ public function checkoutFor(Order $order): array ]; foreach ($order->lines->values() as $index => $line) { + $productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz']; + + if ((int) $line->discount_cents > 0) { + $productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents); + } + $params['line_items'][$index] = [ 'quantity' => 1, 'price_data' => [ 'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')), - 'unit_amount' => (int) $line->price_cents, - 'product_data' => ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'], + 'unit_amount' => $line->payable(), + 'product_data' => $productData, ], ]; @@ -82,21 +98,79 @@ public function checkoutFor(Order $order): array return ['id' => $id, 'url' => $url]; } - public function assertSandbox(): void + public function assertAllowed(): void { $secret = (string) config('services.stripe.secret'); - if (app()->isProduction()) { - throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.'); - } - if ($secret === '') { throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.'); } - if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) { - throw new DomainRuleException('Etappe 1 erlaubt nur den Stripe-Testmodus (Schlüssel sk_test_).'); + if (app()->isProduction()) { + if (! Shop::live()) { + throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.'); + } + + return; } + + if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) { + throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).'); + } + } + + /** + * Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der + * Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts + * entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen + * „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal. + * + * @return array{id: string, status: string, created: ?CarbonImmutable} + */ + public function refund(Order $order, Payment $payment, string $reason): array + { + $this->assertAllowed(); + $intent = (string) $payment->provider_payment_ref; + + if ($intent === '') { + $session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference); + $this->assertOk($session, 'abgefragt'); + $intent = (string) $session->json('payment_intent'); + } + + if ($intent === '') { + throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.'); + } + + $response = $this->request() + ->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id]) + ->post('/v1/refunds', [ + 'payment_intent' => $intent, + 'amount' => $order->payable(), + 'reason' => 'requested_by_customer', + 'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)], + ]); + + $this->assertOk($response, 'erstattet'); + $id = (string) $response->json('id'); + $status = (string) $response->json('status'); + + if ($id === '') { + throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.'); + } + + if (in_array($status, ['failed', 'canceled'], true)) { + throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.'); + } + + $payment->provider_payment_ref = $intent; + $payment->save(); + + return [ + 'id' => $id, + 'status' => $status !== '' ? $status : 'unbekannt', + 'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null, + ]; } /** diff --git a/app/Domain/Entitlement/GrantIssuer.php b/app/Domain/Entitlement/GrantIssuer.php index f0f3ccd..144a482 100644 --- a/app/Domain/Entitlement/GrantIssuer.php +++ b/app/Domain/Entitlement/GrantIssuer.php @@ -101,6 +101,10 @@ public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor): 'update_promise' => $line->update_promise, 'holder_kind' => $line->holder_kind, 'offer_version_id' => $line->offer_version_id, + 'licence_scope' => $line->licence_scope, + 'trainer_count' => $line->trainer_count, + 'price_cents' => (int) $line->price_cents, + 'discount_cents' => (int) $line->discount_cents, ], ]); @@ -150,6 +154,8 @@ public function issue( 'update_promise' => $version->update_promise, 'holder_kind' => $version->holder_kind, 'offer_version_id' => $version->id, + 'licence_scope' => $version->licence_scope, + 'trainer_count' => $version->trainer_count, ], ]); 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/Filament/Pages/RedaktionelleStammdaten.php b/app/Filament/Pages/RedaktionelleStammdaten.php index b6b033f..851eb26 100644 --- a/app/Filament/Pages/RedaktionelleStammdaten.php +++ b/app/Filament/Pages/RedaktionelleStammdaten.php @@ -52,11 +52,11 @@ class RedaktionelleStammdaten extends Page implements HasTable { use InteractsWithTable; - protected static string|\UnitEnum|null $navigationGroup = 'Inhalte'; + protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten'; protected static ?string $navigationLabel = 'Redaktionelle Stammdaten'; - protected static ?int $navigationSort = 6; + protected static ?int $navigationSort = 2; protected static ?string $slug = 'stammdaten'; diff --git a/app/Filament/Pages/Uebernahme.php b/app/Filament/Pages/Uebernahme.php new file mode 100644 index 0000000..5f57a2e --- /dev/null +++ b/app/Filament/Pages/Uebernahme.php @@ -0,0 +1,324 @@ + Markierte Quellübungen (Kennung in der Datenbank) */ + public array $selected = []; + + /** auswahl | vorschau | ergebnis */ + public string $step = 'auswahl'; + + /** @var list> */ + public array $preview = []; + + /** @var array> Quellübung => (entfallene Quellvariante => neue Zuordnung) */ + public array $reassign = []; + + /** @var array> Quellübung => (Text oder Feld => `lokal` oder `quelle`) */ + public array $textChoice = []; + + /** @var list> */ + public array $results = []; + + public string $feedback = ''; + + public bool $feedbackError = false; + + /** + * Die Übernahme ist ein Weg im Übungsbestand („Aus Shinkan übernehmen“) und kein eigener Einstieg. Nur wer die + * Anbindung pflegen darf, aber den Übungsbestand nicht sieht, bekommt den Eintrag in der Navigation. + */ + public static function shouldRegisterNavigation(): bool + { + return static::canConfigure() && ! ContentElementResource::editor(); + } + + public static function canAccess(): bool + { + return ContentElementResource::editor() || static::canConfigure(); + } + + /** Den Schlüssel ändern dürfen nur Katalogverwalter und Systemverwalter. */ + public static function canConfigure(): bool + { + $user = Filament::auth()->user(); + + return $user instanceof User + && ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Systemverwalter)); + } + + public function getHeading(): string|Htmlable|null + { + return null; + } + + public function getMaxContentWidth(): Width|string|null + { + return Width::Full; + } + + public function saveKey(): void + { + abort_unless(static::canConfigure(), 403); + + try { + app(ShinkanConnection::class)->saveKey($this->apiKey, $this->actor()); + $this->say('Der Zugangsschlüssel ist gespeichert. Prüfe jetzt die Verbindung. Der Schlüssel wird nie wieder angezeigt.'); + } catch (DomainRuleException $exception) { + $this->say($exception->getMessage(), true); + } + + $this->apiKey = ''; + } + + public function removeKey(): void + { + abort_unless(static::canConfigure(), 403); + + app(ShinkanConnection::class)->forgetKey($this->actor()); + $this->say('Der in der Verwaltung hinterlegte Zugangsschlüssel ist entfernt. Ein Schlüssel aus der Umgebung des Servers bleibt davon unberührt.'); + } + + /** + * Prüft die Verbindung. Ein eingetragener, noch nicht gespeicherter Schlüssel wird mitgeprüft (nur Verwalter). + */ + public function check(): void + { + abort_unless(static::canAccess(), 403); + + $candidate = static::canConfigure() ? $this->apiKey : ''; + $result = app(ShinkanImport::class)->check($candidate); + $this->apiKey = ''; + $this->say($result['message'], ! $result['ok']); + } + + public function fetch(): void + { + abort_unless(static::canAccess(), 403); + + $run = app(ShinkanImport::class)->fetch(); + $this->say( + $run->status === 'ok' + ? 'Abruf abgeschlossen: '.$run->added.' neu, '.$run->updated.' geändert, '.$run->removed.' nicht mehr bereitgestellt. Es wurde noch keine lokale Fassung angelegt.' + : (string) $run->error, + $run->status !== 'ok', + ); + } + + public function review(): void + { + abort_unless(static::canAccess(), 403); + + $ids = array_values(array_unique(array_map('intval', $this->selected))); + + if ($ids === []) { + $this->say('Markiere mindestens eine Übung.', true); + + return; + } + + $this->buildPreview($ids); + $this->step = 'vorschau'; + $this->say(''); + } + + public function backToSelection(): void + { + $this->step = 'auswahl'; + $this->preview = []; + $this->say(''); + } + + public function confirm(): void + { + abort_unless(static::canAccess(), 403); + + $import = app(ShinkanImport::class); + $changed = []; + $open = []; + + foreach ($this->preview as $entry) { + $source = ExerciseSource::query()->find($entry['source']); + + if ($source === null) { + continue; + } + + $latest = $source->latestSnapshot(); + + if (($source->availability === ExerciseSource::WITHDRAWN) !== (bool) $entry['excluded'] || $latest?->id !== $entry['snapshot']) { + $changed[] = $entry['title']; + } + + foreach ($entry['text_conflicts'] as $conflict) { + if (! in_array($this->textChoice[$entry['source']][$conflict['key']] ?? 'offen', ['lokal', 'quelle'], true)) { + $open[] = $entry['title'].': '.$conflict['label']; + } + } + + foreach ($entry['conflicts'] as $conflict) { + if (! isset($this->reassign[$entry['source']][$conflict['key']]) || $this->reassign[$entry['source']][$conflict['key']] === 'offen') { + $open[] = $entry['title'].': '.implode(', ', $conflict['members']); + } + } + } + + if ($changed !== []) { + $this->buildPreview(array_map(fn (array $entry): int => (int) $entry['source'], $this->preview)); + $this->say('Der Quellstand hat sich seit der Vorschau geändert ('.implode(', ', $changed).'). Die Vorschau ist aktualisiert. Prüfe sie und bestätige den neuen Stand bewusst. Es wurde nichts übernommen.', true); + + return; + } + + if ($open !== []) { + $this->say('Lege zuerst fest, was gilt: '.implode('; ', $open).'.', true); + + return; + } + + $this->results = []; + + foreach ($this->preview as $entry) { + $source = ExerciseSource::query()->findOrFail($entry['source']); + $reassign = array_map(fn (string $value): string => $value === 'gemeinsam' ? '' : $value, $this->reassign[$entry['source']] ?? []); + $result = $import->adoptPreviewed($source, (int) $entry['snapshot'], $reassign, $this->actor(), $this->textChoice[$entry['source']] ?? []); + $source->refresh(); + $this->results[] = [ + 'title' => $entry['title'], + 'status' => $result['status'], + 'message' => $result['message'], + 'url' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]), + ]; + } + + $this->selected = []; + $this->preview = []; + $this->step = 'ergebnis'; + $this->say(''); + } + + public function done(): void + { + $this->step = 'auswahl'; + $this->results = []; + $this->say(''); + } + + /** + * @return array + */ + public function daten(): array + { + $import = app(ShinkanImport::class); + $labels = [ + 'neu' => ['Neu', 'is-neu'], + 'geaendert' => ['Geänderter Quellstand', 'is-geaendert'], + 'uebernommen' => ['Übernommen', 'is-eigen'], + 'nicht_mehr_bereitgestellt' => ['Nicht mehr bereitgestellt', ''], + ]; + $needle = mb_strtolower(trim($this->search)); + $rows = []; + $total = 0; + + foreach (ExerciseSource::query()->with('composition')->orderBy('title')->get() as $source) { + $total++; + $state = $import->state($source); + + if (($this->statusFilter !== 'alle' && $this->statusFilter !== $state) + || ($needle !== '' && ! str_contains(mb_strtolower(($source->title ?? '').' '.$source->source_id), $needle))) { + continue; + } + + $rows[] = [ + 'id' => $source->id, + 'titel' => $source->title ?: $source->source_id, + 'zustand' => $labels[$state][0], + 'ton' => $labels[$state][1], + 'state' => $state, + 'markierbar' => $state !== 'nicht_mehr_bereitgestellt', + 'lokal' => $source->composition === null ? null : PracticeResource::getUrl('edit', ['record' => $source->composition]), + 'hinweis' => $state === 'nicht_mehr_bereitgestellt' + ? 'Lokale Fassungen und Verwendungen bleiben unverändert. Eine rechtliche Sperre ist ein eigener Vorgang am Medium.' + : null, + ]; + } + + return [ + 'zeilen' => $rows, + 'gesamt' => $total, + 'optionen' => ['alle' => 'Alle Zustände', 'neu' => 'Neu', 'geaendert' => 'Geänderter Quellstand', 'uebernommen' => 'Übernommen', 'nicht_mehr_bereitgestellt' => 'Nicht mehr bereitgestellt'], + 'eingerichtet' => $import->configured(), + 'anbindung' => $import->status(), + 'darfAendern' => static::canConfigure(), + 'letzterLauf' => ExerciseImportRun::query()->orderByDesc('id')->first(), + ]; + } + + /** + * @param list $ids + */ + private function buildPreview(array $ids): void + { + $import = app(ShinkanImport::class); + $this->preview = []; + + foreach (ExerciseSource::query()->whereIn('id', $ids)->orderBy('title')->get() as $source) { + $this->preview[] = $import->preview($source); + } + } + + private function actor(): ?User + { + $user = Filament::auth()->user(); + + return $user instanceof User ? $user : null; + } + + private function say(string $message, bool $error = false): void + { + $this->feedback = $message; + $this->feedbackError = $error; + } +} diff --git a/app/Filament/Pages/Verkaufsstart.php b/app/Filament/Pages/Verkaufsstart.php new file mode 100644 index 0000000..9fa7c44 --- /dev/null +++ b/app/Filament/Pages/Verkaufsstart.php @@ -0,0 +1,111 @@ + + */ + public function daten(): array + { + $legal = []; + + foreach (SalesTerms::pages() as $key => $definition) { + $page = SalesTerms::page($key); + $legal[] = [ + 'text' => $definition['label'], + 'neben' => $page === null + ? 'Fehlt: Es gibt keine veröffentlichte Seite unter '.implode(' oder ', $definition['paths']).'. Die Seite pflegst du in der Webpräsenz; den Text liefert die Rechtsberatung.' + : 'Veröffentlicht unter '.$page->path.'. Inhalt und Vollständigkeit prüft die Rechtsberatung.', + 'zustand' => $page === null ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => 'Veröffentlicht', 'ton' => 'gut'], + ]; + } + + $secret = (string) config('services.stripe.secret'); + $mode = match (true) { + $secret === '' => 'nicht eingerichtet', + str_starts_with($secret, 'sk_test_'), str_starts_with($secret, 'rk_test_') => 'Testmodus', + str_starts_with($secret, 'sk_live_'), str_starts_with($secret, 'rk_live_') => 'Live-Schlüssel', + default => 'unbekanntes Format', + }; + $withoutScope = DB::table('offer_versions')->where('status', 'aktiv')->where('grant_kind', 'kauf')->whereNull('licence_scope')->count(); + + $zahlung = [ + ['text' => 'Zahlungsweg: '.Shop::driver(), 'neben' => 'Test: Testzahlung ohne Anbieter. Stripe: Kasse bei Stripe.', 'zustand' => Shop::driver() === 'stripe' ? ['label' => 'Stripe', 'ton' => 'gut'] : ['label' => 'Test', 'ton' => 'neutral']], + ['text' => 'Stripe-Schlüssel: '.$mode, 'neben' => 'Der Schlüssel steht nur in der Umgebungsdatei des Servers und wird hier nie angezeigt.', 'zustand' => $mode === 'nicht eingerichtet' ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => $mode, 'ton' => 'neutral']], + ['text' => 'Signaturschlüssel für Stripe-Meldungen: '.(filled(config('services.stripe.webhook_secret')) ? 'gesetzt' : 'fehlt'), 'neben' => 'Ohne ihn weist die Anwendung jede Meldung von Stripe ab; Zahlungen schalten dann nichts frei.', 'zustand' => filled(config('services.stripe.webhook_secret')) ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Fehlt', 'ton' => 'offen']], + ['text' => 'Steuersatz bei Stripe: '.(filled(config('services.stripe.tax_rate')) ? 'hinterlegt' : 'nicht hinterlegt'), 'neben' => 'Steuerstatus und Belegangaben sind noch nicht entschieden (OPEN-06). Ohne sie gibt es keinen Steuerausweis auf der Stripe-Kasse und keine Rechnungsvorlage.', 'zustand' => filled(config('services.stripe.tax_rate')) ? ['label' => 'Hinterlegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']], + ['text' => 'Aussteller auf dem Zahlungsbeleg: '.(filled(config('shop.receipt.issuer')) ? 'gepflegt' : 'nicht gepflegt'), 'neben' => 'Mitglieder laden zu jeder Zahlung einen Beleg (PDF) herunter. Er nennt den Aussteller nur, wenn er mit SHOP_RECEIPT_ISSUER gepflegt ist (Zeilen durch „|“ getrennt). Name und Anschrift des Verkäufers, Steuerangaben und eine Rechnungsnummer hängen an der rechtlichen Klärung (OPEN-06); bis dahin trägt der Beleg keine steuerlichen Angaben.', 'zustand' => filled(config('shop.receipt.issuer')) ? ['label' => 'Gepflegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']], + ['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => Shop::invoice() + ? 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung. Vereine sehen die Möglichkeit im Checkout.' + : 'Mitglieder sehen die Möglichkeit nicht. Sie wird erst angeboten, wenn der Prozess vollständig ist: Rechnungserstellung mit Nummernkreis, Benachrichtigung des Betreibers bei neuer Rechnungsbestellung und die rechtliche Klärung (OPEN-06). Die Umsetzung ist vorbereitet; schaltest du sie mit SHOP_INVOICE=true in der Umgebungsdatei ein, erscheint sie im Checkout. Bereits angelegte Rechnungsbestellungen bleiben in der Bestellverwaltung bearbeitbar.', + 'zustand' => Shop::invoice() ? ['label' => 'Angeboten', 'ton' => 'neutral'] : ['label' => 'Aus', 'ton' => 'neutral']], + ]; + + $freigabe = [ + ['text' => 'Produktivfreigabe (SHOP_LIVE_RELEASE): '.(config('shop.live_release') === true ? 'gesetzt' : 'nicht gesetzt'), 'neben' => 'Standardmäßig aus. Setzt Lars in der Umgebungsdatei des Servers, wenn er den Verkauf freigibt. Ohne sie bleibt der Shop in Produktion abgeschaltet und Stripe nimmt dort keine Zahlung an.', 'zustand' => config('shop.live_release') === true ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Aus', 'ton' => 'neutral']], + ['text' => 'Umgebung: '.(app()->isProduction() ? 'Produktion' : 'Test oder lokal'), 'neben' => app()->isProduction() ? 'Der Shop ist hier '.(Shop::enabled() ? 'aktiv.' : 'abgeschaltet.') : 'Hier läuft der Shop mit Test- oder Sandbox-Zahlung.', 'zustand' => app()->isProduction() ? (Shop::enabled() ? ['label' => 'Live', 'ton' => 'gut'] : ['label' => 'Abgeschaltet', 'ton' => 'neutral']) : ['label' => 'Test', 'ton' => 'neutral']], + ]; + + $angebote = [ + ['text' => $withoutScope === 0 ? 'Alle aktiven Käufe haben einen Nutzerkreis.' : $withoutScope.' aktive Kaufangebote ohne festgelegten Nutzerkreis', 'neben' => $withoutScope === 0 ? null : 'Käufer sähen „Nutzerkreis nicht festgelegt“. Lege Einzel- oder Mehrfachlizenz mit „Geänderte Fassung aktivieren“ am Angebot fest.', 'zustand' => $withoutScope === 0 ? ['label' => 'Vollständig', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']], + ]; + + return [ + 'kopf' => [ + 'titel' => 'Verkaufsstart', + 'typ' => 'Bereitschaft für den Verkauf in Deutschland', + 'status' => ['text' => SalesTerms::missingPages() === [] ? 'Alle Rechtstexte sind veröffentlicht. Die rechtliche Freigabe der Inhalte steht aus, bis die Rechtsberatung sie bestätigt.' : 'Es fehlen veröffentlichte Rechtstexte. Ohne sie bleibt der Shop in Produktion abgeschaltet.', 'ton' => SalesTerms::missingPages() === [] ? 'gut' : 'offen'], + ], + 'haupt' => [ + ['titel' => 'Rechtstexte im Bestellablauf', 'hilfe' => 'Der Checkout verlinkt diese Seiten und hält mit jeder Bestellung fest, welche Fassung galt. Den Wortlaut der Zustimmungen im Checkout hat der Betreiber noch rechtlich zu prüfen (Entwurf '.SalesTerms::VERSION.').', 'zeilen' => $legal], + ['titel' => 'Zahlung und Belege', 'zeilen' => $zahlung], + ], + 'seite' => [ + ['titel' => 'Freigabe', 'zeilen' => $freigabe, 'hilfe' => 'Die Produktivfreigabe liegt bei Lars. Sie wird nicht über diese Oberfläche gesetzt.'], + ['titel' => 'Angebote', 'zeilen' => $angebote], + ], + ]; + } +} diff --git a/app/Filament/Pages/Zahlungsjournal.php b/app/Filament/Pages/Zahlungsjournal.php new file mode 100644 index 0000000..fd325b4 --- /dev/null +++ b/app/Filament/Pages/Zahlungsjournal.php @@ -0,0 +1,182 @@ +jahr ??= $now->year; + $this->nr ??= $this->modus === 'quartal' ? $now->quarter : $now->month; + $this->betrieb ??= self::defaultBetrieb(); + $this->normalize(); + } + + /** Nur Prod zeigt standardmäßig echte Zahlungen; auf anderen Instanzen entstehen Buchungen nur aus der Sandbox. */ + public static function defaultBetrieb(): string + { + return app()->isProduction() ? 'echt' : 'test'; + } + + /** Beim Wechsel zwischen Monat und Quartal bleibt der gewählte Zeitraum erhalten. */ + public function updatingModus(string $value): void + { + if ($this->modus === 'monat' && $value === 'quartal') { + $this->nr = (int) ceil(((int) $this->nr) / 3); + } elseif ($this->modus === 'quartal' && $value === 'monat') { + $this->nr = (((int) $this->nr) - 1) * 3 + 1; + } + } + + public function updated(): void + { + $this->normalize(); + } + + /** Ungültige Eingaben aus der Adresszeile fallen auf zulässige Werte zurück. */ + private function normalize(): void + { + $this->modus = in_array($this->modus, ['monat', 'quartal', 'jahr'], true) ? $this->modus : 'monat'; + $this->art = in_array($this->art, ['alle', LedgerEntry::KIND_PAYMENT, LedgerEntry::KIND_REFUND], true) ? $this->art : 'alle'; + $this->weg = in_array($this->weg, ['alle', 'stripe', 'ueberweisung', 'test'], true) ? $this->weg : 'alle'; + $this->betrieb = in_array($this->betrieb, ['echt', 'test', 'alle'], true) ? $this->betrieb : self::defaultBetrieb(); + $this->angebot = ctype_digit($this->angebot) && Offer::query()->whereKey((int) $this->angebot)->exists() ? $this->angebot : ''; + $this->jahr = max(2020, min((int) CarbonImmutable::now(PaymentJournal::TIMEZONE)->year + 1, (int) ($this->jahr ?? 2026))); + $max = $this->modus === 'quartal' ? 4 : 12; + $this->nr = max(1, min($max, (int) ($this->nr ?? 1))); + } + + /** + * @return array{0: CarbonImmutable, 1: CarbonImmutable} + */ + private function range(): array + { + return PaymentJournal::range($this->modus, (int) $this->jahr, (int) $this->nr); + } + + public function zeitraumName(): string + { + $months = [1 => 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; + + return match ($this->modus) { + 'monat' => $months[(int) $this->nr].' '.$this->jahr, + 'quartal' => $this->nr.'. Quartal '.$this->jahr, + default => 'Jahr '.$this->jahr, + }; + } + + /** + * @return array + */ + public function daten(): array + { + [$from, $to] = $this->range(); + $journal = app(PaymentJournal::class); + $offerId = $this->angebot === '' ? null : (int) $this->angebot; + $entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId); + $shares = $offerId === null ? null : $journal->shares($entries, $offerId); + + return [ + 'zeitraum' => $this->zeitraumName(), + 'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT), + 'anzahl' => $entries->count(), + 'angebote' => Offer::query()->orderBy('name')->pluck('name', 'id')->all(), + 'angebotName' => $offerId === null ? null : Offer::query()->find($offerId)?->name, + 'anteile' => $shares, + 'summen' => PaymentJournal::totals($entries, $shares), + 'nachBetrieb' => $journal->countByOperation($from, $to), + 'ohneAdresse' => $entries->filter(fn (LedgerEntry $entry): bool => $entry->kind === LedgerEntry::KIND_PAYMENT && empty(($entry->payer ?? [])['billing']))->count(), + 'nachgetragen' => $entries->where('derived', true)->count(), + ]; + } + + public function exportieren(): StreamedResponse + { + abort_unless(ShopAccess::allowed(), 403); + + [$from, $to] = $this->range(); + $journal = app(PaymentJournal::class); + $offerId = $this->angebot === '' ? null : (int) $this->angebot; + $entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId); + $shares = $offerId === null ? null : $journal->shares($entries, $offerId); + $name = 'zahlungsjournal-'.match ($this->modus) { + 'monat' => $this->jahr.'-'.str_pad((string) $this->nr, 2, '0', STR_PAD_LEFT), + 'quartal' => $this->jahr.'-Q'.$this->nr, + default => (string) $this->jahr, + }.'-'.match ($this->betrieb) { + 'echt' => 'echt', 'test' => 'test', default => 'alle' + }.($offerId === null ? '' : '-angebot-'.$offerId).'.csv'; + + return response()->streamDownload(function () use ($entries, $shares): void { + echo PaymentJournal::csv($entries, $shares); + }, $name, ['Content-Type' => 'text/csv; charset=UTF-8']); + } +} diff --git a/app/Filament/Resources/Combinations/CombinationResource.php b/app/Filament/Resources/Combinations/CombinationResource.php index 3225278..bbb38e5 100644 --- a/app/Filament/Resources/Combinations/CombinationResource.php +++ b/app/Filament/Resources/Combinations/CombinationResource.php @@ -17,7 +17,7 @@ class CombinationResource extends CompositionKindResource protected static ?string $pluralModelLabel = 'Fachliche Kombinationen'; - protected static ?int $navigationSort = 2; + protected static ?int $navigationSort = 5; public static function kind(): CompositionKind { diff --git a/app/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index 31d4f0c..4b705a1 100644 --- a/app/Filament/Resources/Compositions/Pages/EditComposition.php +++ b/app/Filament/Resources/Compositions/Pages/EditComposition.php @@ -15,6 +15,7 @@ use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\EditorialVocabulary; use App\Domain\Catalog\EditorialWorkingDraft; +use App\Domain\Catalog\ForeignCompositions; use App\Domain\Catalog\IdentityDimension; use App\Domain\Catalog\IdentityDimensionValue; use App\Domain\Catalog\IdentityProfile; @@ -39,6 +40,7 @@ use Filament\Support\Exceptions\Halt; use Illuminate\Contracts\Support\Htmlable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Str; use Livewire\Features\SupportFileUploads\TemporaryUploadedFile; use Livewire\WithFileUploads; @@ -68,6 +70,15 @@ abstract class EditComposition extends EditRecord public string $materialNote = ''; + /** @var list Durchführungsvarianten einer Übung */ + public array $variants = []; + + public string $durationMax = ''; + + public string $prerequisites = ''; + + public string $newVariantName = ''; + public string $revisionNote = ''; public string $search = ''; @@ -489,8 +500,173 @@ public function cancelText(): void $this->newTextBody = ''; } + public function isExercise(): bool + { + return $this->hostKind() === CompositionKind::Exercise; + } + + public function addVariant(): void + { + $name = trim($this->newVariantName); + + if ($name === '') { + $this->feedback = 'Eine Variante braucht einen Namen.'; + + return; + } + + $base = Str::slug($name) ?: 'variante'; + $key = $base; + $n = 2; + + while (in_array($key, array_column($this->variants, 'key'), true)) { + $key = $base.'-'.$n++; + } + + $this->variants[] = ['key' => $key, 'name' => $name, 'description' => '', 'origin' => 'lokal']; + $this->newVariantName = ''; + $this->feedback = 'Variante „'.$name.'“ ist angelegt. Ordne ihr Bestandteile zu. Gespeichert wird mit „Entwurf speichern“.'; + } + + public function removeVariant(string $key): void + { + foreach ($this->members as $member) { + if (($member['variant'] ?? null) === $key) { + $this->feedback = 'Diese Variante hat noch Bestandteile. Ordne sie zuerst einer anderen Variante oder dem gemeinsamen Teil zu.'; + + return; + } + } + + $this->variants = array_values(array_filter($this->variants, fn (array $variant): bool => $variant['key'] !== $key)); + $this->feedback = 'Die Variante ist aus diesem Entwurf genommen. Eine freigegebene Fassung bleibt unverändert.'; + } + + public function setMemberVariant(int $index, string $key): void + { + if (! isset($this->members[$index])) { + return; + } + + $this->members[$index]['variant'] = $key === '' ? null : $key; + } + + public function setMemberRequirement(int $index, string $requirement): void + { + if (! isset($this->members[$index]) || ! in_array($requirement, ['erforderlich', 'ergaenzend'], true)) { + return; + } + + $this->members[$index]['requirement'] = $requirement; + } + + /** + * Angebotene Varianten der eingebundenen Übungsfassung. Ohne Auswahl werden alle angeboten. + */ + public function toggleVariantSelection(int $index, string $key): void + { + if (! isset($this->members[$index])) { + return; + } + + $all = array_column($this->offeredVariants((string) ($this->members[$index]['target'] ?? '')), 'key'); + $current = $this->members[$index]['selection'] ?? null; + $current = is_array($current) ? $current : $all; + $current = in_array($key, $current, true) ? array_values(array_diff($current, [$key])) : [...$current, $key]; + + if ($current === []) { + $this->feedback = 'Mindestens eine Variante muss angeboten werden.'; + + return; + } + + $this->members[$index]['selection'] = count($current) === count($all) ? null : array_values($current); + } + + /** + * @return list + */ + public function offeredVariants(string $target): array + { + if (preg_match('/^composition:(\d+)$/', $target, $match) !== 1) { + return []; + } + + return CompositionVersion::query()->find((int) $match[1])?->variants + ->map(fn ($variant): array => ['key' => $variant->key, 'name' => $variant->name]) + ->all() ?? []; + } + + /** + * @param array $member + * @return array{variant: string|null, requirement: string, selection: list|null, origin: string} + */ + private function memberExtras(array $member): array + { + $selection = $member['selection'] ?? null; + + return [ + 'variant' => isset($member['variant']) && $member['variant'] !== '' ? (string) $member['variant'] : null, + 'requirement' => ($member['requirement'] ?? 'erforderlich') === 'ergaenzend' ? 'ergaenzend' : 'erforderlich', + 'selection' => is_array($selection) && $selection !== [] ? array_values(array_map('strval', $selection)) : null, + 'origin' => ($member['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal', + ]; + } + + /** + * @return list + */ + private function normalizeVariants(mixed $variants): array + { + $result = []; + + foreach (is_array($variants) ? $variants : [] as $variant) { + if (is_array($variant) && trim((string) ($variant['key'] ?? '')) !== '') { + $result[] = [ + 'key' => trim((string) $variant['key']), + 'name' => trim((string) ($variant['name'] ?? '')), + 'description' => trim((string) ($variant['description'] ?? '')), + 'origin' => ($variant['origin'] ?? 'lokal') === 'quelle' ? 'quelle' : 'lokal', + ]; + } + } + + return $result; + } + + /** + * Rückfallschutz: Enthält dieser Aufbau (in einer Fassung oder im Entwurf) einen Bestandteil, den dieser Programmstand + * nicht kennt, bleibt er schreibgeschützt. Der Editor könnte den Bestandteil sonst nicht laden und würde ihn beim + * Speichern oder Freigeben still weglassen. + */ + public function schreibschutz(): ?string + { + $foreign = app(ForeignCompositions::class); + $reason = 'Dieser Aufbau enthält einen Bestandteil aus einer neueren Programmversion. Er kann hier nur angesehen werden, damit nichts verloren geht.'; + + if ($foreign->compositionHasForeignMembers((int) $this->getRecord()->getKey())) { + return $reason; + } + + $draft = app(EditorialWorkingDraft::class)->read($this->getRecord()); + + foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) { + if (is_array($member) && $foreign->isForeignTarget((string) ($member['target'] ?? ''))) { + return $reason; + } + } + + return null; + } + public function saveDraft(): void { + if (($reason = $this->schreibschutz()) !== null) { + $this->feedback = $reason; + + return; + } + $this->commitRoleDraft(); $minutes = $this->minutes($this->durationMinutes); @@ -508,6 +684,13 @@ public function saveDraft(): void public function armRelease(): void { + if (($reason = $this->schreibschutz()) !== null) { + $this->releaseArmed = false; + $this->feedback = $reason; + + return; + } + $this->commitRoleDraft(); if ($this->members === []) { @@ -585,6 +768,12 @@ protected function selectFirstPart(): void public function discardDraft(): void { + if (($reason = $this->schreibschutz()) !== null) { + $this->feedback = $reason; + + return; + } + /** @var Composition $record */ $record = $this->getRecord(); app(EditorialWorkingDraft::class)->clear($record); @@ -924,7 +1113,7 @@ private function includePart(string $target, bool $allowDraft): bool return false; } - foreach ($this->members as $index => $member) { + foreach ($this->isExercise() ? [] : $this->members as $index => $member) { if (($member['target'] ?? '') === $target) { $this->selected = $index; $this->panel = 'bestandteil'; @@ -944,6 +1133,7 @@ private function includePart(string $target, bool $allowDraft): bool $row['role'] = app(EditorialCatalog::class)->defaultRole((string) $row['kind']); $row['note'] = ''; + $row = [...$row, ...$this->memberExtras([])]; $this->members[] = $row; $this->members = array_values($this->members); $this->selected = array_key_last($this->members); @@ -1034,6 +1224,7 @@ public function useVersion(int $index, string $target): void $this->commitRoleDraft(); $row['role'] = $this->members[$index]['role'] ?? $row['kind']; $row['note'] = $this->members[$index]['note'] ?? ''; + $row = [...$row, ...$this->memberExtras($this->members[$index])]; $this->members[$index] = $row; $this->syncRoleDraft(); $this->feedback = $row['version_label'].' ist für diese Stelle ausgewählt. Der Entwurf speichert das. Eine freigegebene Fassung bleibt unverändert.'; @@ -1521,6 +1712,12 @@ public function presentationChips(): array public function publishRevision(): bool { + if (($reason = $this->schreibschutz()) !== null) { + $this->feedback = $reason; + + return false; + } + $this->commitRoleDraft(); if ($this->members === []) { @@ -1560,9 +1757,12 @@ public function publishRevision(): bool [ 'learning_goal' => $this->blank($this->learningGoal), 'duration_minutes' => $minutes, + 'duration_max' => $this->blank($this->durationMax), 'material_note' => $this->blank($this->materialNote), + 'prerequisites' => $this->blank($this->prerequisites), ], $this->releaseConsent, + $this->normalizeVariants($this->variants), ); } catch (DomainRuleException $exception) { $this->feedback = $exception->getMessage(); @@ -1679,7 +1879,8 @@ protected function loadAufbau(): void $this->imageCaptionText = $this->captionFor($composition->thumbnail_source); $this->catalogScope = match ($this->hostKind()) { CompositionKind::Kurs => 'module', - CompositionKind::Uebung => 'medien', + CompositionKind::Uebung => 'uebungen', + CompositionKind::Exercise => 'medien', default => 'alles', }; @@ -1693,6 +1894,9 @@ protected function loadAufbau(): void if ($version === null) { $this->members = []; + $this->variants = []; + $this->durationMax = ''; + $this->prerequisites = ''; $this->learningGoal = ''; $this->durationMinutes = ''; $this->materialNote = ''; @@ -1726,10 +1930,14 @@ protected function applyDraft(array $draft): void $row['role'] = (string) ($member['role'] ?? $row['kind']); $row['note'] = trim((string) ($member['note'] ?? '')); + $row = [...$row, ...$this->memberExtras($member)]; $rows[] = $row; } $this->members = $rows; + $this->variants = $this->normalizeVariants($draft['variants'] ?? []); + $this->durationMax = ($draft['duration_max'] ?? null) === null ? '' : (string) $draft['duration_max']; + $this->prerequisites = (string) ($draft['prerequisites'] ?? ''); $this->learningGoal = (string) ($draft['learning_goal'] ?? ''); $this->durationMinutes = ($draft['duration_minutes'] ?? null) === null ? '' : (string) $draft['duration_minutes']; $this->materialNote = (string) ($draft['material_note'] ?? ''); @@ -1747,6 +1955,11 @@ protected function applyDraft(array $draft): void protected function applyVersion(CompositionVersion $version): void { $this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey()); + $this->variants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [ + 'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin, + ])->all()); + $this->durationMax = $version->duration_max === null ? '' : (string) $version->duration_max; + $this->prerequisites = (string) ($version->prerequisites ?? ''); $this->learningGoal = (string) ($version->learning_goal ?? ''); $this->durationMinutes = $version->duration_minutes === null ? '' : (string) $version->duration_minutes; $this->materialNote = (string) ($version->material_note ?? ''); @@ -1833,18 +2046,21 @@ protected function needsRevision(): bool protected function sameMembers(CompositionVersion $version): bool { - $version->loadMissing('members'); + $version->loadMissing('members.variant'); $current = $version->members->map(function ($member): string { $target = $member->content_element_version_id ? 'element:'.$member->content_element_version_id : 'composition:'.$member->nested_composition_version_id; - return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? '')); + return $member->role.'|'.$target.'|'.trim((string) ($member->placement_note ?? '')) + .'|'.($member->variant?->key ?? '').'|'.($member->requirement ?: 'erforderlich').'|'.json_encode($member->variant_selection); })->all(); - $next = array_values(array_map( - fn (array $member): string => trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')), - $this->members, - )); + $next = array_values(array_map(function (array $member): string { + $extras = $this->memberExtras($member); + + return trim((string) ($member['role'] ?? '')).'|'.($member['target'] ?? '').'|'.trim((string) ($member['note'] ?? '')) + .'|'.($extras['variant'] ?? '').'|'.$extras['requirement'].'|'.json_encode($extras['selection']); + }, $this->members)); return $current === $next; } @@ -1859,8 +2075,15 @@ protected function didacticChanged(CompositionVersion $version): bool $storedMinutes = $version->duration_minutes === null ? null : (int) $version->duration_minutes; + $storedVariants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [ + 'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin, + ])->all()); + return $version->learning_goal !== $this->blank($this->learningGoal) || $version->material_note !== $this->blank($this->materialNote) + || $version->prerequisites !== $this->blank($this->prerequisites) + || ($version->duration_max === null ? null : (string) $version->duration_max) !== $this->blank($this->durationMax) + || $storedVariants !== $this->normalizeVariants($this->variants) || $storedMinutes !== $minutes; } @@ -1929,6 +2152,12 @@ protected function persistRedaktion(): bool protected function persistDraft(): bool { + if (($reason = $this->schreibschutz()) !== null) { + $this->feedback = $reason; + + return false; + } + if ($this->minutes($this->durationMinutes) === false) { $this->feedback = 'Der Zeitbedarf ist eine Zahl von Minuten oder bleibt leer.'; @@ -2065,12 +2294,16 @@ protected function payload(): array 'learning_goal' => $this->blank($this->learningGoal), 'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes, 'material_note' => $this->blank($this->materialNote), + 'duration_max' => $this->blank($this->durationMax), + 'prerequisites' => $this->blank($this->prerequisites), + 'variants' => $this->normalizeVariants($this->variants), 'revision_note' => $this->blank($this->revisionNote), 'members' => array_values(array_map( fn (array $member): array => [ 'role' => trim((string) ($member['role'] ?? '')), 'target' => (string) ($member['target'] ?? ''), 'note' => trim((string) ($member['note'] ?? '')), + ...$this->memberExtras($member), ], $members, )), @@ -2105,6 +2338,9 @@ protected function readyPayload(): array 'learning_goal' => null, 'duration_minutes' => null, 'material_note' => null, + 'duration_max' => null, + 'prerequisites' => null, + 'variants' => [], 'revision_note' => null, 'members' => [], ]; @@ -2116,12 +2352,18 @@ protected function readyPayload(): array 'learning_goal' => $version->learning_goal, 'duration_minutes' => $version->duration_minutes === null ? null : (int) $version->duration_minutes, 'material_note' => $version->material_note, + 'duration_max' => $version->duration_max === null ? null : (string) $version->duration_max, + 'prerequisites' => $version->prerequisites, + 'variants' => $this->normalizeVariants($version->variants->map(fn ($variant): array => [ + 'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin, + ])->all()), 'revision_note' => null, 'members' => array_values(array_map( fn (array $row): array => [ 'role' => trim((string) ($row['role'] ?? '')), 'target' => (string) ($row['target'] ?? ''), 'note' => trim((string) ($row['note'] ?? '')), + ...$this->memberExtras($row), ], $rows, )), @@ -2145,6 +2387,7 @@ protected function normalizePayload(array $payload): array 'role' => trim((string) ($member['role'] ?? '')), 'target' => (string) ($member['target'] ?? ''), 'note' => trim((string) ($member['note'] ?? '')), + ...$this->memberExtras($member), ]; } @@ -2152,6 +2395,9 @@ protected function normalizePayload(array $payload): array 'learning_goal' => $payload['learning_goal'] ?? null, 'duration_minutes' => $payload['duration_minutes'] ?? null, 'material_note' => $payload['material_note'] ?? null, + 'duration_max' => isset($payload['duration_max']) && $payload['duration_max'] !== '' ? (string) $payload['duration_max'] : null, + 'prerequisites' => $payload['prerequisites'] ?? null, + 'variants' => $this->normalizeVariants($payload['variants'] ?? []), 'revision_note' => $payload['revision_note'] ?? null, 'members' => $members, ]; diff --git a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php index 6bb179e..bb89d40 100644 --- a/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php +++ b/app/Filament/Resources/Compositions/Pages/ListCompositionKind.php @@ -4,6 +4,7 @@ use App\Domain\Catalog\CompositionKind; use App\Domain\Catalog\ContentService; +use App\Filament\Pages\Uebernahme; use App\Filament\Resources\ContentElements\ContentElementResource; use App\Filament\Support\ListsCompositions; use App\Filament\Support\ReportsDomainRules; @@ -33,12 +34,12 @@ protected function fixedKind(): ?CompositionKind private function onDesk(): bool { - return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung], true); + return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise], true); } public function getSubheading(): string|Htmlable|null { - $desk = $this->onDesk() ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : ''; + $desk = $this->onDesk() && $this->kind() !== CompositionKind::Exercise ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : ''; return $this->kind()->deskExplanation().$desk; } @@ -55,6 +56,18 @@ public function content(Schema $schema): Schema protected function getHeaderActions(): array { + if ($this->kind() === CompositionKind::Exercise) { + return [ + $this->createCompositionAction($this->kind()), + Action::make('shinkan') + ->label('Aus Shinkan übernehmen') + ->icon('heroicon-o-arrow-down-tray') + ->color('gray') + ->visible(fn (): bool => ContentElementResource::editor()) + ->url(fn (): string => Uebernahme::getUrl()), + ]; + } + if ($this->onDesk()) { return [$this->createCompositionAction($this->kind())]; } diff --git a/app/Filament/Resources/DiscountCodes/DiscountCodeResource.php b/app/Filament/Resources/DiscountCodes/DiscountCodeResource.php new file mode 100644 index 0000000..80a7615 --- /dev/null +++ b/app/Filament/Resources/DiscountCodes/DiscountCodeResource.php @@ -0,0 +1,65 @@ +columns([ + TextColumn::make('code')->label('Code')->searchable(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListDiscountCodes::route('/'), + 'view' => ViewDiscountCode::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/DiscountCodes/Pages/ListDiscountCodes.php b/app/Filament/Resources/DiscountCodes/Pages/ListDiscountCodes.php new file mode 100644 index 0000000..318e577 --- /dev/null +++ b/app/Filament/Resources/DiscountCodes/Pages/ListDiscountCodes.php @@ -0,0 +1,103 @@ +label('Code anlegen') + ->modalHeading('Neuer Rabattcode') + ->modalDescription('Dieselbe Maske öffnet sich später beim Bearbeiten. Freigaben für einzelne Konten verwaltest du danach auf der Seite des Codes.') + ->modalSubmitActionLabel('Code anlegen') + ->modalWidth('3xl') + ->fillForm(['kind' => DiscountCode::PERCENT, 'scope' => DiscountCode::SCOPE_CART, 'eligibility' => DiscountCode::OPEN, 'active' => true]) + ->schema(DiscountCodeForm::schema()) + ->action(function (array $data): void { + $code = null; + $this->report(function () use ($data, &$code): void { + [$fields, $targets] = DiscountCodeForm::fromForm($data); + $code = app(DiscountService::class)->save($fields, $targets); + }, 'Der Rabattcode ist angelegt.'); + + if ($code instanceof DiscountCode) { + $this->redirect(DiscountCodeResource::getUrl('view', ['record' => $code])); + } + }), + ]; + } + + protected function catalogRows(): array + { + $rows = []; + $now = now(); + + foreach (DiscountCode::query()->with('targets')->withCount(['releases as active_releases_count' => fn ($query) => $query->whereNull('revoked_at')])->orderByDesc('id')->get() as $code) { + $state = $code->stateAt($now); + $url = DiscountCodeResource::getUrl('view', ['record' => $code]); + $rows[] = [ + 'schluessel' => 'c'.$code->id, + 'titel' => $code->code, + 'meta' => 'Rabattcode · '.$code->label, + 'text' => $code->valueLabel().' · '.($code->forSelection() ? 'ausgewählte Ziele ('.$code->targets->count().')' : 'gesamter Warenkorb').' · '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein einlösbar'), + 'symbol' => 'etikett', + 'url' => $url, + 'chips' => [ + match ($state) { + 'aktiv' => ['label' => 'Gültig', 'ton' => 'gut'], + 'abgelaufen' => ['label' => 'Abgelaufen', 'ton' => 'leise'], + 'noch_nicht' => ['label' => 'Noch nicht gültig', 'ton' => 'offen'], + default => ['label' => 'Deaktiviert', 'ton' => 'leise'], + }, + ['label' => $code->valueLabel(), 'ton' => 'neutral'], + ['label' => $code->restricted() ? $code->active_releases_count.' freigeschaltet' : 'Allgemein', 'ton' => 'neutral'], + ], + 'zustand' => [$state === 'aktiv' ? 'aktiv' : 'inaktiv'], + 'aktionen' => [['label' => 'Öffnen', 'href' => $url]], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return ['alle' => 'Jeder Zustand', 'aktiv' => 'Gerade gültig', 'inaktiv' => 'Abgelaufen, deaktiviert oder noch nicht gültig']; + } + + protected function suchPlatzhalter(): string + { + return 'Code oder Name'; + } + + protected function einheit(): array + { + return ['Rabattcode', 'Rabattcodes']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Rabattcodes', 'text' => 'Mit „Code anlegen“ oben entsteht der erste Rabattcode, zum Beispiel der gemeinsame Zertifizierungscode.']; + } +} diff --git a/app/Filament/Resources/DiscountCodes/Pages/ViewDiscountCode.php b/app/Filament/Resources/DiscountCodes/Pages/ViewDiscountCode.php new file mode 100644 index 0000000..7e5d0ea --- /dev/null +++ b/app/Filament/Resources/DiscountCodes/Pages/ViewDiscountCode.php @@ -0,0 +1,293 @@ +getRecord()->code; + } + + public function getHeading(): string|Htmlable + { + return ''; + } + + public function getMaxContentWidth(): Width|string|null + { + return Width::Full; + } + + protected function getHeaderActions(): array + { + return []; + } + + /** + * @return array + */ + public function getBreadcrumbs(): array + { + return []; + } + + public function infolist(Schema $schema): Schema + { + return $schema->components([ + View::make('filament.catalog.objekt')->viewData(fn (): array => $this->codeDaten())->columnSpanFull(), + ])->columns(1); + } + + private function code(): DiscountCode + { + /** @var DiscountCode $code */ + $code = $this->getRecord(); + + return $code; + } + + public function editAction(): Action + { + return Action::make('edit') + ->label('Code bearbeiten') + ->modalHeading(fn (): string => 'Rabattcode „'.$this->code()->code.'“ bearbeiten') + ->modalDescription('Bestellungen, die schon aufgegeben sind, behalten ihren gespeicherten Rabatt. Eine Änderung wirkt auf künftige Einlösungen und auf offene Warenkörbe. „Abbrechen“ verwirft die Eingaben.') + ->modalSubmitActionLabel('Änderungen speichern') + ->modalWidth('3xl') + ->fillForm(fn (): array => DiscountCodeForm::fill($this->code())) + ->schema(DiscountCodeForm::schema()) + ->action(function (array $data): void { + $this->report(function () use ($data): void { + [$fields, $targets] = DiscountCodeForm::fromForm($data); + app(DiscountService::class)->save($fields, $targets, $this->code()); + }, 'Der Rabattcode ist gespeichert.'); + $this->refreshRecord(); + }); + } + + public function toggleAction(): Action + { + return Action::make('toggle') + ->label(fn (): string => $this->code()->active ? 'Code deaktivieren' : 'Code aktivieren') + ->color(fn (): string => $this->code()->active ? 'danger' : 'success') + ->requiresConfirmation() + ->modalHeading(fn (): string => $this->code()->active ? 'Code „'.$this->code()->code.'“ deaktivieren?' : 'Code „'.$this->code()->code.'“ aktivieren?') + ->modalDescription(fn (): string => $this->code()->active + ? 'Der Code lässt sich danach nicht mehr einlösen. In offenen Warenkörben zeigt die Bestellübersicht den Grund; bereits aufgegebene Bestellungen bleiben unverändert. Freigaben und Einstellungen bleiben erhalten.' + : 'Der Code lässt sich danach wieder einlösen, soweit sein Gültigkeitszeitraum und die Freigaben es zulassen.') + ->modalSubmitActionLabel(fn (): string => $this->code()->active ? 'Deaktivieren' : 'Aktivieren') + ->action(function (): void { + $code = $this->code(); + $this->report(function () use ($code): string { + app(DiscountService::class)->setActive($code, ! $code->active); + + return $code->active ? 'Der Code ist aktiviert.' : 'Der Code ist deaktiviert.'; + }, 'Gespeichert.'); + $this->refreshRecord(); + }); + } + + public function releaseAction(): Action + { + return Action::make('release') + ->label('Konto freischalten') + ->modalHeading(fn (): string => 'Konto für den Code „'.$this->code()->code.'“ freischalten') + ->modalDescription('Das Konto darf genau diesen Code einlösen, solange Code und Freigabe gültig sind, auch bei späteren Bestellungen. Die Freigabe gilt nicht für andere Codes. Prüfe vorher die Zertifizierung des Kontos.') + ->modalSubmitActionLabel('Konto freischalten') + ->schema([ + Select::make('user_id')->label('Mitgliedskonto')->required()->searchable() + ->getSearchResultsUsing(fn (string $search): array => $this->searchMembers($search)) + ->getOptionLabelUsing(fn ($value): ?string => ($user = User::query()->find($value)) === null ? null : $user->name.' ('.$user->email.')') + ->helperText('Suche nach Name oder E-Mail-Adresse. Nur Konten mit Mitgliedsprofil.'), + DatePicker::make('valid_until')->label('Freigabe gültig bis einschließlich')->native(false)->displayFormat('d.m.Y') + ->helperText('Leer: ohne Ende. Danach gilt der Code für dieses Konto nicht mehr.'), + Textarea::make('reason')->label('Grundlage der Freigabe')->rows(2)->maxLength(500) + ->helperText('Zum Beispiel „Zertifikat vom 12.11.2026 geprüft“. Bleibt im Verlauf stehen.'), + ]) + ->visible(fn (): bool => $this->code()->restricted()) + ->action(function (array $data): void { + $this->report(function () use ($data): string { + $member = User::query()->findOrFail($data['user_id']); + $until = filled($data['valid_until'] ?? null) ? Carbon::parse((string) $data['valid_until'], config('app.timezone'))->endOfDay() : null; + app(DiscountService::class)->release($this->code(), $member, auth('staff')->user() ?? auth()->user(), $until, $data['reason'] ?? null); + + return 'Das Konto von '.$member->name.' ist für den Code freigeschaltet.'; + }, 'Das Konto ist freigeschaltet.'); + $this->refreshRecord(); + }); + } + + public function revokeAction(): Action + { + return Action::make('revoke') + ->label('Freigabe entziehen') + ->color('danger') + ->requiresConfirmation() + ->modalHeading('Freigabe entziehen?') + ->modalDescription('Das Konto kann diesen Code danach nicht mehr einlösen. Offene Warenkörbe des Kontos zeigen den Grund und lassen sich erst ohne Code bestellen. Aufgegebene Bestellungen bleiben unverändert; die Freigabe bleibt mit dem Entzug im Verlauf stehen.') + ->modalSubmitActionLabel('Freigabe entziehen') + ->schema([ + Textarea::make('reason')->label('Grund')->rows(2)->maxLength(500), + ]) + ->action(function (array $data, array $arguments): void { + $this->report(function () use ($data, $arguments): string { + $release = DiscountRelease::query()->where('discount_code_id', $this->code()->id)->findOrFail((int) ($arguments['release'] ?? 0)); + app(DiscountService::class)->revoke($release, auth('staff')->user() ?? auth()->user(), $data['reason'] ?? null); + + return 'Die Freigabe ist entzogen.'; + }, 'Die Freigabe ist entzogen.'); + $this->refreshRecord(); + }); + } + + private function refreshRecord(): void + { + $this->getRecord()->unsetRelations(); + $this->getRecord()->refresh(); + } + + /** + * @return array + */ + private function searchMembers(string $search): array + { + $like = '%'.mb_strtolower(trim($search)).'%'; + + return User::query() + ->whereNotNull('party_id') + ->where(fn ($query) => $query->whereRaw('LOWER(name) LIKE ?', [$like])->orWhereRaw('LOWER(email) LIKE ?', [$like])) + ->orderBy('name') + ->limit(20) + ->get() + ->mapWithKeys(fn (User $user): array => [$user->id => $user->name.' ('.$user->email.')']) + ->all(); + } + + /** + * @return array + */ + private function codeDaten(): array + { + $code = $this->code(); + $code->loadMissing('targets'); + $state = $code->stateAt(now()); + $date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y'); + $targets = []; + + foreach ($code->targets as $target) { + $targets[] = match ($target->target_type) { + DiscountCode::TARGET_OFFER => 'Angebot „'.(Offer::query()->find($target->target_id)?->name ?? 'gelöscht').'“', + DiscountCode::TARGET_ARTICLE => 'Lizenzartikel '.(LicenseArticle::query()->find($target->target_id)?->code ?? 'gelöscht'), + DiscountCode::TARGET_BUNDLE => 'Paket „'.(Bundle::query()->find($target->target_id)?->name ?? 'gelöscht').'“', + default => 'Ziel', + }; + } + + $releases = $code->releases()->with(['user', 'grantor'])->get(); + $active = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at === null); + $past = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at !== null); + $orders = Order::query()->where('discount_code_id', $code->id)->with('user')->latest('id')->limit(10)->get(); + $paid = Order::query()->where('discount_code_id', $code->id)->where('status', 'bezahlt')->count(); + + return [ + 'kopf' => [ + 'brot' => [['label' => 'Rabattcodes', 'href' => DiscountCodeResource::getUrl('index')], $code->code], + 'titel' => $code->code, + 'typ' => 'Rabattcode · '.$code->label, + 'status' => match ($state) { + 'aktiv' => ['text' => 'Gerade gültig'.($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ''), 'ton' => 'gut'], + 'abgelaufen' => ['text' => 'Abgelaufen am '.$date($code->valid_until).'. Der Code lässt sich nicht mehr einlösen.', 'ton' => 'offen'], + 'noch_nicht' => ['text' => 'Gilt erst ab dem '.$date($code->valid_from).'.', 'ton' => 'offen'], + default => ['text' => 'Deaktiviert. Der Code lässt sich nicht einlösen.', 'ton' => 'offen'], + }, + 'aktionen' => [ + ['label' => 'Code bearbeiten', 'wire' => "mountAction('edit')", 'art' => 'primary'], + ...($code->restricted() ? [['label' => 'Konto freischalten', 'wire' => "mountAction('release')", 'art' => 'line']] : []), + ['label' => $code->active ? 'Code deaktivieren' : 'Code aktivieren', 'wire' => "mountAction('toggle')", 'art' => 'line'], + ], + ], + 'haupt' => [ + [ + 'titel' => 'Der Code auf einen Blick', + 'hilfe' => 'Geltungsbereich und Einlösungsberechtigung sind zwei getrennte Einstellungen. Der Rabatt ändert den Preis, nie den Nutzungsumfang.', + 'zeilen' => [ + ['text' => 'Rabatt: '.$code->valueLabel(), 'neben' => $code->kind === DiscountCode::PERCENT ? 'Je Position gerundet.' : 'Je Bestellung, anteilig auf die betroffenen Positionen verteilt.'], + ['text' => 'Geltungsbereich: '.($code->forSelection() ? 'nur ausgewählte Ziele' : 'gesamter Warenkorb'), 'neben' => $code->forSelection() ? 'Ein Paket ist ein eigenes Ziel und folgt nicht aus einem enthaltenen Artikel.' : null], + ...array_map(fn (string $target): array => ['text' => '· '.$target, 'neben' => null], $targets), + ['text' => 'Einlösung: '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein, für alle angemeldeten Käufer'), 'neben' => 'Pro Bestellung gilt höchstens ein Code.'], + ['text' => 'Gültigkeit: '.($code->valid_from ? 'ab '.$date($code->valid_from) : 'sofort').($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ', unbegrenzt'), 'neben' => $code->active ? 'Aktiv' : 'Deaktiviert'], + ...(filled($code->note) ? [['text' => 'Notiz: '.$code->note, 'neben' => null]] : []), + ], + ], + [ + 'titel' => $code->restricted() ? 'Freigeschaltete Konten' : 'Freigaben', + 'zusatz' => $code->restricted() ? $active->count().' aktiv' : null, + 'hilfe' => $code->restricted() + ? 'Nur diese Konten können den Code einlösen. Die Freigabe gilt nur für diesen Code und wiederholt, solange Code und Freigabe gültig sind.' + : 'Der Code ist allgemein einlösbar. Freigaben sind nicht nötig. Stelle „Einlösung“ auf freigeschaltete Konten, um den Code zu beschränken.', + 'zeilen' => $code->restricted() ? $active->map(fn (DiscountRelease $release): array => [ + 'text' => ($release->user?->name ?? 'Konto').' ('.($release->user?->email ?? '').')', + 'neben' => 'freigeschaltet am '.$date($release->granted_at).($release->grantor ? ' von '.$release->grantor->name : '').($release->valid_until ? ', gültig bis einschließlich '.$date($release->valid_until) : '').(filled($release->reason) ? ' · '.$release->reason : ''), + 'aktion' => ['label' => 'Entziehen', 'wire' => "mountAction('revoke', { release: ".$release->id.' })'], + ])->values()->all() : [], + 'leer' => ['titel' => $code->restricted() ? 'Noch kein Konto freigeschaltet' : 'Keine Freigaben nötig', 'text' => $code->restricted() ? 'Mit „Konto freischalten“ oben gibst du ein Konto für diesen Code frei, zum Beispiel nach der Prüfung eines Zertifikats.' : 'Jeder angemeldete Käufer kann den Code einlösen.'], + ], + ], + 'seite' => [ + [ + 'titel' => 'Verwendung', + 'zeilen' => $orders->map(fn (Order $order): array => [ + 'text' => 'Bestellung '.$order->id.' · −'.Money::format((int) $order->discount_cents), + 'zustand' => ['label' => match ($order->status) { + 'bezahlt' => 'Bezahlt', 'erstattet' => 'Erstattet', 'fehlgeschlagen' => 'Fehlgeschlagen', default => 'Offen' + }, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'leise'], + 'neben' => ($order->user?->name ?? '').' · '.$date($order->created_at), + ])->all(), + 'leer' => 'Der Code wurde noch in keiner Bestellung verwendet.', + 'hilfe' => $orders->isEmpty() ? null : $paid.' bezahlte Bestellung'.($paid === 1 ? '' : 'en').' mit diesem Code. Gezeigt werden die letzten zehn.', + ], + [ + 'titel' => 'Entzogene Freigaben', + 'zeilen' => $past->map(fn (DiscountRelease $release): array => [ + 'text' => ($release->user?->name ?? 'Konto'), + 'neben' => 'entzogen am '.$date($release->revoked_at).(filled($release->reason) ? ' · '.$release->reason : ''), + ])->values()->all(), + 'leer' => 'Keine Freigabe wurde entzogen.', + 'hilfe' => 'Der Verlauf bleibt erhalten.', + ], + ], + ]; + } +} diff --git a/app/Filament/Resources/Offers/Pages/ViewOffer.php b/app/Filament/Resources/Offers/Pages/ViewOffer.php index 54a03ae..6677f1e 100644 --- a/app/Filament/Resources/Offers/Pages/ViewOffer.php +++ b/app/Filament/Resources/Offers/Pages/ViewOffer.php @@ -7,6 +7,7 @@ use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionVersion; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; @@ -17,11 +18,13 @@ use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Commerce\Money; use App\Domain\Commerce\ProductOptions; +use App\Filament\Pages\Zahlungsjournal; use App\Filament\Resources\Offers\OfferResource; use App\Filament\Support\CatalogLabels; use App\Filament\Support\CatalogOptions; use App\Filament\Support\PublicationReadiness; use App\Filament\Support\ReportsDomainRules; +use App\Filament\Support\ShopAccess; use Filament\Actions\Action; use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; @@ -45,6 +48,9 @@ class ViewOffer extends ViewRecord protected static string $resource = OfferResource::class; + /** Wert der Auswahl „Produktseite“ für ein Paket mit eigener Seite. */ + private const OWN_BUNDLE_PAGE = '__paket'; + public function getTitle(): string|Htmlable { return (string) $this->getRecord()->name; @@ -120,6 +126,16 @@ public function activateAction(): Action 'organisation' => 'Organisationen und Vereine', ])->required() ->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'), + Select::make('licence_scope')->label('Nutzerkreis') + ->options(LicenceScope::options()) + ->required() + ->live() + ->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Das ist unabhängig vom Lizenzinhaber (Person oder Verein), vom Nutzungszweck der Rechte und vom Preis; es wird aus keinem davon abgeleitet. Der Download bleibt zum Start beim bestellenden Konto. Der Wert wird mit der Bestellung festgehalten.'), + TextInput::make('trainer_count')->label('Anzahl Trainer') + ->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer() + ->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI) + ->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI) + ->helperText('Höchstzahl der Trainer, die die Inhalte einsetzen dürfen, mindestens 2. Eine Einzellizenz gilt immer für genau einen Trainer.'), Select::make('grant_kind')->label('Vergabe')->options([ 'kauf' => 'Kauf', 'auf_abruf' => 'Auf Abruf', @@ -201,13 +217,16 @@ public function activateAction(): Action $version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) { $service->assignProduct( $offer, - filled($data['composition_id'] ?? null) ? (int) $data['composition_id'] : null, + filled($data['composition_id'] ?? null) && $data['composition_id'] !== self::OWN_BUNDLE_PAGE ? (int) $data['composition_id'] : null, $data['option_label'] ?? null, + ($data['composition_id'] ?? null) === self::OWN_BUNDLE_PAGE, ); return $service->activate($offer, $lines, [ ...$kept, 'holder_kind' => $data['holder_kind'], + 'licence_scope' => $data['licence_scope'] ?? null, + 'trainer_count' => $data['trainer_count'] ?? null, 'grant_kind' => $data['grant_kind'], 'price_cents' => $price, 'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null, @@ -267,7 +286,7 @@ private function productPages(): array { $catalog = app(PublicCatalogReader::class); - return Composition::query() + return [self::OWN_BUNDLE_PAGE => 'Eigene Paketseite · zeigt den Umfang des Pakets (nur für ein Angebot aus genau einer Paketfassung)'] + Composition::query() ->with('editorialContentKind') ->whereNull('archived_at') ->orderBy('designation') @@ -291,15 +310,17 @@ private function formFromActive(): array $active = $this->activeVersion(); /** @var Offer $offer */ $offer = $this->getRecord(); - $option = ['option_label' => $offer->option_label, 'composition_id' => $offer->composition_id]; + $option = ['option_label' => $offer->option_label, 'composition_id' => $offer->standalone_bundle ? self::OWN_BUNDLE_PAGE : $offer->composition_id]; if ($active === null) { - return [...$option, 'holder_kind' => 'person', 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]]; + return [...$option, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]]; } return [ ...$option, 'holder_kind' => $active->holder_kind, + 'licence_scope' => $active->licence_scope, + 'trainer_count' => $active->trainer_count, 'grant_kind' => $active->grant_kind, 'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''), 'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [ @@ -347,6 +368,11 @@ private function angebotDaten(): array 'wire' => "mountAction('end')", 'art' => 'line', ]] : []), + ...(ShopAccess::allowed() ? [[ + 'label' => 'Zahlungen zu diesem Angebot', + 'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']), + 'art' => 'quiet', + ]] : []), ], ], 'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer), @@ -400,6 +426,7 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array ->unique() ->implode('; '); $seite = $offer->composition; + $eigeneSeite = $offer->standalone_bundle; $kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null; return [ @@ -409,10 +436,11 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array 'zeilen' => [ ['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)], ['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']], + ['text' => 'Nutzerkreis: '.$option['licence'], 'neben' => $option['licence_scope'] === null ? 'Mit „Geänderte Fassung aktivieren“ festlegen.' : 'Lizenzinhaber, Nutzerkreis und Downloadkonto sind getrennte Angaben.'], ['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null], ['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null], ['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null], - ['text' => 'Produktseite: '.($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet'), 'neben' => $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'], + ['text' => 'Produktseite: '.($eigeneSeite ? 'eigene Paketseite mit dem Umfang des Pakets' : ($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet')), 'neben' => $eigeneSeite || $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'], ], ]; } diff --git a/app/Filament/Resources/Orders/OrderResource.php b/app/Filament/Resources/Orders/OrderResource.php new file mode 100644 index 0000000..84e6037 --- /dev/null +++ b/app/Filament/Resources/Orders/OrderResource.php @@ -0,0 +1,68 @@ +columns([ + TextColumn::make('id')->label('Bestellung'), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListOrders::route('/'), + 'view' => ViewOrder::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Resources/Orders/Pages/ListOrders.php b/app/Filament/Resources/Orders/Pages/ListOrders.php new file mode 100644 index 0000000..6825308 --- /dev/null +++ b/app/Filament/Resources/Orders/Pages/ListOrders.php @@ -0,0 +1,104 @@ +with(['lines', 'user', 'party'])->orderByDesc('id')->limit(300)->get() as $order) { + $url = OrderResource::getUrl('view', ['record' => $order]); + $zustand = [$order->status]; + $chips = [ + match ($order->status) { + 'bezahlt' => ['label' => 'Bezahlt', 'ton' => 'gut'], + 'erstattet' => ['label' => 'Erstattet', 'ton' => 'leise'], + 'fehlgeschlagen' => ['label' => 'Fehlgeschlagen', 'ton' => 'leise'], + default => ['label' => $order->payment_method === 'rechnung' ? 'Offen: wartet auf Zahlungseingang' : 'Offen', 'ton' => 'offen'], + }, + ['label' => match ($order->payment_method) { + 'rechnung' => 'Rechnung', 'stripe' => 'Stripe', default => 'Testzahlung' + }, 'ton' => 'neutral'], + ['label' => Money::format($order->payable()), 'ton' => 'neutral'], + ]; + + if ($order->discount_cents > 0) { + $chips[] = ['label' => 'Rabatt '.($order->discount_snapshot['code'] ?? ''), 'ton' => 'neutral']; + } + + if ($order->withdrawal_requested_at !== null) { + $chips[] = ['label' => 'Widerruf erklärt', 'ton' => 'offen']; + $zustand[] = 'widerruf'; + } + + if ($order->payment_method === 'rechnung' && $order->status === 'offen') { + $zustand[] = 'rechnung_offen'; + } + + $rows[] = [ + 'schluessel' => 'o'.$order->id, + 'titel' => 'Bestellung '.$order->id, + 'meta' => ($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–'), + 'text' => $order->lines->pluck('offer_name')->implode('; '), + 'suchtext' => (string) ($order->user?->email ?? ''), + 'symbol' => 'etikett', + 'url' => $url, + 'chips' => $chips, + 'zustand' => $zustand, + 'aktionen' => [['label' => 'Öffnen', 'href' => $url]], + ]; + } + + return $rows; + } + + protected function zustandOptionen(): array + { + return [ + 'alle' => 'Jeder Zustand', + 'rechnung_offen' => 'Rechnung: wartet auf Zahlungseingang', + 'widerruf' => 'Widerruf erklärt', + 'offen' => 'Offen', + 'bezahlt' => 'Bezahlt', + 'erstattet' => 'Erstattet', + ]; + } + + protected function suchPlatzhalter(): string + { + return 'Nummer, Name, E-Mail oder Angebot'; + } + + protected function einheit(): array + { + return ['Bestellung', 'Bestellungen']; + } + + protected function leer(): array + { + return ['titel' => 'Noch keine Bestellungen', 'text' => 'Sobald im Shop bestellt wird, erscheinen die Bestellungen hier.']; + } +} diff --git a/app/Filament/Resources/Orders/Pages/ViewOrder.php b/app/Filament/Resources/Orders/Pages/ViewOrder.php new file mode 100644 index 0000000..758b3a8 --- /dev/null +++ b/app/Filament/Resources/Orders/Pages/ViewOrder.php @@ -0,0 +1,248 @@ +order()->id; + } + + public function getHeading(): string|Htmlable + { + return ''; + } + + public function getMaxContentWidth(): Width|string|null + { + return Width::Full; + } + + protected function getHeaderActions(): array + { + return []; + } + + /** + * @return array + */ + public function getBreadcrumbs(): array + { + return []; + } + + public function infolist(Schema $schema): Schema + { + return $schema->components([ + View::make('filament.catalog.objekt')->viewData(fn (): array => $this->bestellDaten())->columnSpanFull(), + ])->columns(1); + } + + private function hasStripePayment(): bool + { + return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists(); + } + + private function order(): Order + { + /** @var Order $order */ + $order = $this->getRecord(); + + return $order; + } + + public function confirmInvoiceAction(): Action + { + return Action::make('confirmInvoice') + ->label('Zahlungseingang bestätigen') + ->modalHeading(fn (): string => 'Zahlungseingang für Bestellung '.$this->order()->id.' bestätigen') + ->modalDescription(fn (): string => 'Du bestätigst, dass '.Money::format($this->order()->payable()).' für die Rechnung eingegangen sind. Die Inhalte werden sofort für das bestellende Konto freigeschaltet; Lizenzinhaber bleibt '.($this->order()->party?->display_name ?? 'der Käufer').'. Die Bestätigung lässt sich nicht zurücknehmen, nur die Bestellung erstatten.') + ->modalSubmitActionLabel('Zahlungseingang bestätigen') + ->schema([ + TextInput::make('reference')->label('Rechnungsnummer oder Buchungsreferenz')->required()->maxLength(120) + ->helperText('Bleibt an der Zahlung gespeichert, zum Beispiel „RE-2026-014“.'), + DatePicker::make('received_on')->label('Zahlungseingang am')->required()->native(false)->displayFormat('d.m.Y') + ->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d')) + ->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d')) + ->helperText('Der Tag, an dem das Geld auf dem Konto einging. Er bestimmt, in welchen Zeitraum die Einnahme im Zahlungsjournal fällt.'), + ]) + ->visible(fn (): bool => $this->order()->payment_method === 'rechnung' && $this->order()->status === 'offen') + ->action(function (array $data): void { + $this->report(function () use ($data): string { + app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user(), (string) $data['received_on']); + + return 'Der Zahlungseingang ist bestätigt. Die Inhalte sind freigeschaltet.'; + }, 'Bestätigt.'); + $this->order()->unsetRelations(); + $this->order()->refresh(); + }); + } + + public function refundAction(): Action + { + return Action::make('refund') + ->label('Bestellung erstatten') + ->color('danger') + ->modalHeading(fn (): string => 'Bestellung '.$this->order()->id.' vollständig erstatten?') + ->modalDescription(fn (): string => 'Alle Positionen dieser Bestellung werden zurückgegeben: Die Berechtigungen daraus werden widerrufen, andere Erwerbsquellen (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Pakete sind eine Einheit; Teilerstattungen gibt es zum Start nicht. '.( + $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists() + ? 'Die Rückzahlung von '.Money::format($this->order()->payable()).' wird bei Stripe veranlasst; nur wenn Stripe sie annimmt, werden die Rechte entzogen.' + : 'Die Rückzahlung selbst veranlasst du außerhalb dieser Anwendung, zum Beispiel per Überweisung.' + )) + ->modalSubmitActionLabel('Vollständig erstatten') + ->schema([ + Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500) + ->helperText('Bleibt am Widerruf der Berechtigungen und im Zahlungsjournal stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'), + DatePicker::make('refunded_on')->label('Rückzahlung am')->native(false)->displayFormat('d.m.Y') + ->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d')) + ->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d')) + ->visible(fn (): bool => ! $this->hasStripePayment()) + ->helperText('Der Tag, an dem du das Geld zurücküberwiesen hast. Bei Stripe gilt der Zeitpunkt von Stripe.'), + TextInput::make('refund_reference')->label('Referenz der Rückzahlung')->maxLength(120) + ->visible(fn (): bool => ! $this->hasStripePayment()) + ->helperText('Optional, zum Beispiel Buchungstext oder Gutschriftnummer.'), + ]) + ->visible(fn (): bool => $this->order()->status === 'bezahlt') + ->action(function (array $data): void { + $this->report(function () use ($data): string { + app(Checkout::class)->refund( + $this->order(), + (string) $data['reason'], + null, + Filament::auth()->user(), + $this->hasStripePayment() ? null : ($data['refunded_on'] ?? null), + $this->hasStripePayment() ? null : ($data['refund_reference'] ?? null), + ); + + return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.'; + }, 'Erstattet.'); + $this->order()->unsetRelations(); + $this->order()->refresh(); + }); + } + + /** + * @return array + */ + private function bestellDaten(): array + { + $order = $this->order(); + $order->loadMissing(['lines', 'user', 'party', 'payments']); + $date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y H:i'); + $method = match ($order->payment_method) { + 'rechnung' => 'Überweisung auf Rechnung (manuell)', + 'stripe' => 'Stripe', + default => 'Testzahlung', + }; + + return [ + 'kopf' => [ + 'brot' => [['label' => 'Bestellungen', 'href' => OrderResource::getUrl('index')], 'Bestellung '.$order->id], + 'titel' => 'Bestellung '.$order->id, + 'typ' => 'Lizenzinhaber: '.($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–').' ('.($order->user?->email ?? '').')', + 'status' => [ + ['text' => match ($order->status) { + 'bezahlt' => 'Bezahlt ('.$method.')', + 'erstattet' => 'Erstattet. Die Berechtigungen sind widerrufen.', + 'fehlgeschlagen' => 'Zahlung fehlgeschlagen. Es wurde nichts freigeschaltet.', + default => $order->payment_method === 'rechnung' ? 'Offen: Rechnung erstellen und Zahlungseingang bestätigen.' : 'Offen: Zahlung steht aus.', + }, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'offen'], + $order->withdrawal_requested_at !== null ? ['text' => 'Widerruf erklärt am '.$date($order->withdrawal_requested_at).'. Prüfen und gegebenenfalls erstatten.', 'ton' => 'offen'] : null, + ], + 'aktionen' => [ + ...($order->payment_method === 'rechnung' && $order->status === 'offen' ? [['label' => 'Zahlungseingang bestätigen', 'wire' => "mountAction('confirmInvoice')", 'art' => 'primary']] : []), + ...($order->status === 'bezahlt' ? [['label' => 'Bestellung erstatten', 'wire' => "mountAction('refund')", 'art' => 'line']] : []), + ], + ], + 'haupt' => [ + [ + 'titel' => 'Positionen', + 'hilfe' => 'Fassung, Preis, Rabatt, Nutzerkreis und Umfang sind beim Kauf festgehalten und ändern sich nicht.', + 'zeilen' => $order->lines->map(fn (OrderLine $line): array => [ + 'text' => ($line->offer_name ?: 'Angebot').': '.Money::format((int) $line->price_cents).($line->discount_cents > 0 ? ' − Rabatt '.Money::format((int) $line->discount_cents).' = '.Money::format($line->payable()) : ''), + 'neben' => LicenceScope::label($line->licence_scope, $line->trainer_count).' · Angebotsfassung '.($line->offerVersion?->number ?? '–'), + ])->values()->all(), + 'leer' => ['titel' => 'Keine Positionen', 'text' => 'Diese Bestellung hat keine Positionen.'], + ], + [ + 'titel' => 'Beträge', + 'zeilen' => [ + ['text' => 'Zwischensumme (Listenpreise): '.Money::format($order->subtotal()), 'neben' => null], + ...($order->discount_cents > 0 ? [['text' => 'Rabatt: −'.Money::format((int) $order->discount_cents), 'neben' => 'Code '.($order->discount_snapshot['code'] ?? '').' · '.($order->discount_snapshot['label'] ?? '')]] : []), + ['text' => 'Zahlbetrag: '.Money::format($order->payable()), 'neben' => 'Dieser Betrag ging an '.$method.'.'], + ], + ], + [ + 'titel' => 'Zahlungen', + 'zeilen' => $order->payments->map(fn (Payment $payment): array => [ + 'text' => match ($payment->provider) { + 'stripe' => 'Stripe', 'ueberweisung' => 'Überweisung', default => 'Testzahlung' + }.' · '.match ($payment->status) { + 'bestaetigt' => 'bestätigt', 'erstattet' => 'erstattet', 'offen' => 'offen', 'abgelaufen' => 'abgelaufen', 'zu_pruefen' => 'zu prüfen', 'fehlgeschlagen' => 'fehlgeschlagen', default => $payment->status + }, + 'neben' => $payment->provider_reference.($payment->amount_cents !== null ? ' · '.Money::format((int) $payment->amount_cents) : ''), + ])->values()->all(), + 'leer' => ['titel' => 'Noch keine Zahlung', 'text' => 'Es gibt noch keinen Zahlungsvorgang zu dieser Bestellung.'], + ], + [ + 'titel' => 'Buchungen im Zahlungsjournal', + 'hilfe' => 'Unveränderlich festgehalten, mit Datum, Beleg beim Anbieter und Rechnungsempfänger zum Zeitpunkt der Buchung. Alle Buchungen eines Zeitraums und den Export findest du unter „Einnahmen und Erstattungen“.', + 'zeilen' => LedgerEntry::query()->where('order_id', $order->id)->orderBy('occurred_at')->orderBy('id')->get()->map(fn (LedgerEntry $entry): array => [ + 'text' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y').' · '.($entry->isRefund() ? 'Erstattung −' : 'Zahlungseingang ').Money::format(abs($entry->amount_cents)).($entry->live ? '' : ' (Test, kein Umsatz)').($entry->derived ? ' (nachgetragen)' : ''), + 'neben' => PaymentJournal::providerLabel($entry->provider).' · '.$entry->provider_reference.(filled($entry->actor_name) ? ' · gebucht von '.$entry->actor_name : ''), + ])->values()->all(), + 'leer' => ['titel' => 'Noch keine Buchung', 'text' => 'Zahlungseingang und Erstattung dieser Bestellung erscheinen hier.'], + ], + ], + 'seite' => [ + [ + 'titel' => 'Zustimmung', + 'zeilen' => $order->terms_accepted_at === null ? [] : [ + ['text' => 'Zugestimmt am '.$date($order->terms_accepted_at), 'neben' => 'Fassung der Texte: '.($order->terms_snapshot['version'] ?? '–')], + ...collect($order->terms_snapshot['consents'] ?? [])->map(fn (string $wording): array => ['text' => $wording, 'neben' => null])->values()->all(), + ], + 'leer' => 'Zu dieser Bestellung ist keine Zustimmung festgehalten (Bestellung vor dem Verkaufsstart oder über den Testweg).', + ], + [ + 'titel' => 'Widerruf', + 'zeilen' => $order->withdrawal_requested_at === null ? [] : [ + ['text' => 'Erklärt am '.$date($order->withdrawal_requested_at), 'neben' => filled($order->withdrawal_note) ? $order->withdrawal_note : null], + ], + 'leer' => 'Kein Widerruf erklärt.', + 'hilfe' => 'Der Widerruf entzieht nichts. Du prüfst ihn (bei sofortiger Bereitstellung mit Zustimmung kann das Recht erloschen sein) und erstattest bei Bedarf über „Bestellung erstatten“.', + ], + ], + ]; + } +} diff --git a/app/Filament/Resources/Pillars/PillarResource.php b/app/Filament/Resources/Pillars/PillarResource.php index c7c0e16..d57303b 100644 --- a/app/Filament/Resources/Pillars/PillarResource.php +++ b/app/Filament/Resources/Pillars/PillarResource.php @@ -20,7 +20,7 @@ class PillarResource extends Resource { protected static ?string $model = Pillar::class; - protected static string|\UnitEnum|null $navigationGroup = 'Inhalte'; + protected static string|\UnitEnum|null $navigationGroup = 'Stammdaten'; protected static ?string $navigationLabel = 'Fachliche Säulen'; @@ -32,7 +32,7 @@ class PillarResource extends Resource protected static ?string $slug = 'saeulen'; - protected static ?int $navigationSort = 5; + protected static ?int $navigationSort = 1; public static function canViewAny(): bool { diff --git a/app/Filament/Resources/Practices/Pages/EditPractice.php b/app/Filament/Resources/Practices/Pages/EditPractice.php new file mode 100644 index 0000000..d1fda47 --- /dev/null +++ b/app/Filament/Resources/Practices/Pages/EditPractice.php @@ -0,0 +1,11 @@ + ListPractices::route('/'), + 'edit' => EditPractice::route('/{record}'), + ]; + } +} diff --git a/app/Filament/Support/CatalogOptions.php b/app/Filament/Support/CatalogOptions.php index 6c0a9f8..b863f47 100644 --- a/app/Filament/Support/CatalogOptions.php +++ b/app/Filament/Support/CatalogOptions.php @@ -37,7 +37,7 @@ public static function assignmentTargets(?int $exceptCompositionId = null): arra $media['element:'.$version->id] = self::elementLabel($version); } - foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) { + foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) { if ($exceptCompositionId !== null && (int) $version->composition_id === $exceptCompositionId) { continue; } @@ -94,7 +94,7 @@ public static function readyTargets(): array $options['element:'.$version->id] = self::elementLabel($version); } - foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->with('composition.editorialContentKind')->orderBy('id')->get() as $version) { + foreach (CompositionVersion::query()->where('status', ContentVersionStatus::Bereit)->whereHas('composition')->with('composition.editorialContentKind')->orderBy('id')->get() as $version) { $options['composition:'.$version->id] = self::compositionLabel($version); } diff --git a/app/Filament/Support/CatalogReading.php b/app/Filament/Support/CatalogReading.php index d9ca6f1..75cfdcf 100644 --- a/app/Filament/Support/CatalogReading.php +++ b/app/Filament/Support/CatalogReading.php @@ -266,7 +266,7 @@ public function elementUsage(ContentElement $element): array ->get(); foreach ($members as $member) { - $lines[] = self::compositionLabel($member->compositionVersion->composition) + $lines[] = self::compositionLabelOf($member->compositionVersion->composition) .' · Fassung '.$member->compositionVersion->number .' · Rolle '.$member->role; } @@ -280,7 +280,9 @@ public function elementUsage(ContentElement $element): array foreach ($contents as $content) { $lines[] = 'Lizenzartikel '.$content->release->article->code .' · Stand '.$content->release->number - .' · '.$content->path; + .' · '.$content->path + .($content->variant_key !== null ? ' · Variante '.$content->variant_key : '') + .($content->requirement === CompositionMember::SUPPLEMENTARY ? ' · ergänzend' : ''); } return $lines === [] @@ -313,7 +315,7 @@ public function compositionMembers(Composition $composition): array } $nested = $member->nestedCompositionVersion; - $lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabel($nested->composition)); + $lines[] = $member->role.' — '.($nested === null ? 'fehlt' : self::compositionLabelOf($nested->composition)); } return $lines; @@ -365,7 +367,7 @@ public function compositionUsage(Composition $composition): array ->get(); foreach ($parents as $member) { - $lines[] = self::compositionLabel($member->compositionVersion->composition) + $lines[] = self::compositionLabelOf($member->compositionVersion->composition) .' · Fassung '.$member->compositionVersion->number .' · Rolle '.$member->role; } @@ -448,6 +450,16 @@ private function purpose(string $purpose): string }; } + /** + * Eine Zusammenstellung, die dieser Programmstand nicht kennt, erscheint nur als Hinweis ohne Namen und Inhalt. + */ + private static function compositionLabelOf(?Composition $composition): string + { + return $composition === null + ? 'Zusammenstellung einer neueren Programmversion' + : self::compositionLabel($composition); + } + private static function compositionLabel(Composition $composition): string { $kind = $composition->kind; diff --git a/app/Filament/Support/DiscountCodeForm.php b/app/Filament/Support/DiscountCodeForm.php new file mode 100644 index 0000000..bf577b0 --- /dev/null +++ b/app/Filament/Support/DiscountCodeForm.php @@ -0,0 +1,126 @@ + + */ + public static function schema(): array + { + return [ + TextInput::make('code')->label('Code')->required()->maxLength(40) + ->helperText('So gibt ihn der Käufer ein, 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich. Groß- und Kleinschreibung spielen keine Rolle.'), + TextInput::make('label')->label('Name für die Verwaltung')->required()->maxLength(120) + ->helperText('Nur intern, zum Beispiel „Zertifizierungscode 2026“. Der Käufer sieht ihn nicht.'), + Select::make('kind')->label('Art des Rabatts')->options([ + DiscountCode::PERCENT => 'Prozent', + DiscountCode::AMOUNT => 'Fester Betrag in Euro', + ])->required()->live(), + TextInput::make('percent')->label('Prozent')->numeric()->minValue(1)->maxValue(100)->integer()->suffix('%') + ->required(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT) + ->visible(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT) + ->helperText('Je Position gerundet. Der Zahlbetrag der Bestellung darf 0,50 € nicht unterschreiten.'), + TextInput::make('amount_euro')->label('Rabattbetrag')->suffix('€') + ->required(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT) + ->visible(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT) + ->helperText('Gilt je Bestellung und wird anteilig auf die betroffenen Positionen verteilt, zum Beispiel 5,00.'), + Select::make('scope')->label('Geltungsbereich')->options([ + DiscountCode::SCOPE_CART => 'Gesamter Warenkorb', + DiscountCode::SCOPE_SELECTED => 'Nur ausdrücklich ausgewählte Angebote, Lizenzartikel oder Pakete', + ])->required()->live() + ->helperText('Wofür der Rabatt gilt. Unabhängig davon legst du unten fest, wer den Code einlösen darf.'), + Select::make('offer_ids')->label('Angebote')->multiple()->searchable() + ->options(fn (): array => Offer::query()->orderBy('name')->pluck('name', 'id')->all()) + ->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED) + ->helperText('Die gewählte Lizenzoption selbst (Fassung egal).'), + Select::make('article_ids')->label('Lizenzartikel')->multiple()->searchable() + ->options(fn (): array => app(PublicationReadiness::class)->articleOptions()) + ->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED) + ->helperText('Gilt für Angebote, die diesen Artikel unmittelbar als Position führen. Ein Artikel in einem Paket macht das Paket nicht rabattfähig.'), + Select::make('bundle_ids')->label('Pakete')->multiple()->searchable() + ->options(fn (): array => Bundle::query()->orderBy('name')->pluck('name', 'id')->all()) + ->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED) + ->helperText('Ein Paket wird gezielt gewählt. Es folgt nicht aus einem enthaltenen Artikel.'), + Select::make('eligibility')->label('Wer darf den Code einlösen?')->options([ + DiscountCode::OPEN => 'Alle angemeldeten Käufer (allgemein einlösbar)', + DiscountCode::RESTRICTED => 'Nur ausdrücklich freigeschaltete Konten', + ])->required() + ->helperText('Bei „freigeschaltete Konten“ schaltest du einzelne Konten auf der Seite des Codes frei und entziehst die Freigabe wieder. Eine Freigabe gilt nur für diesen Code.'), + DatePicker::make('valid_from')->label('Gültig ab')->native(false)->displayFormat('d.m.Y') + ->helperText('Leer: sofort.'), + DatePicker::make('valid_until')->label('Gültig bis einschließlich')->native(false)->displayFormat('d.m.Y') + ->helperText('Leer: unbegrenzt. Am Tag danach gilt der Code nicht mehr.'), + Toggle::make('active')->label('Aktiv')->default(true) + ->helperText('Deaktivierte Codes lassen sich nicht einlösen; bereits aufgegebene Bestellungen bleiben unverändert.'), + Textarea::make('note')->label('Notiz')->rows(2)->maxLength(500) + ->helperText('Zum Beispiel, woran die Berechtigung geprüft wird.'), + ]; + } + + /** + * Formularwerte → Angaben und Ziele des Dienstes. + * + * @param array $data + * @return array{0: array, 1: list} + */ + public static function fromForm(array $data): array + { + $targets = []; + + foreach ([ + DiscountCode::TARGET_OFFER => 'offer_ids', + DiscountCode::TARGET_ARTICLE => 'article_ids', + DiscountCode::TARGET_BUNDLE => 'bundle_ids', + ] as $type => $key) { + foreach ((array) ($data[$key] ?? []) as $id) { + $targets[] = ['type' => $type, 'id' => (int) $id]; + } + } + + return [$data, $targets]; + } + + /** + * Vorbelegung der Maske aus einem vorhandenen Code. + * + * @return array + */ + public static function fill(DiscountCode $code): array + { + $code->loadMissing('targets'); + $ids = fn (string $type): array => $code->targets->where('target_type', $type)->pluck('target_id')->map(fn ($id): int => (int) $id)->values()->all(); + + return [ + 'code' => $code->code, + 'label' => $code->label, + 'kind' => $code->kind, + 'percent' => $code->percent, + 'amount_euro' => $code->amount_cents === null ? null : number_format($code->amount_cents / 100, 2, ',', ''), + 'scope' => $code->scope, + 'offer_ids' => $ids(DiscountCode::TARGET_OFFER), + 'article_ids' => $ids(DiscountCode::TARGET_ARTICLE), + 'bundle_ids' => $ids(DiscountCode::TARGET_BUNDLE), + 'eligibility' => $code->eligibility, + 'valid_from' => $code->valid_from?->timezone(config('app.timezone'))->toDateString(), + 'valid_until' => $code->valid_until?->timezone(config('app.timezone'))->toDateString(), + 'active' => $code->active, + 'note' => $code->note, + ]; + } +} diff --git a/app/Filament/Support/EditorialCatalog.php b/app/Filament/Support/EditorialCatalog.php index 36ef686..70cd2b8 100644 --- a/app/Filament/Support/EditorialCatalog.php +++ b/app/Filament/Support/EditorialCatalog.php @@ -21,6 +21,7 @@ use App\Filament\Resources\ContentElements\ContentElementResource; use App\Filament\Resources\Courses\CourseResource; use App\Filament\Resources\Exercises\ExerciseResource; +use App\Filament\Resources\Practices\PracticeResource; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; @@ -33,6 +34,7 @@ class EditorialCatalog public function rows(CompositionVersion $version, int $exceptCompositionId): array { $version->loadMissing([ + 'members.variant', 'members.contentElementVersion.element.editorialContentKind', 'members.nestedCompositionVersion.composition.editorialContentKind', ]); @@ -50,6 +52,10 @@ public function rows(CompositionVersion $version, int $exceptCompositionId): arr $row['role'] = $member->role; $row['note'] = trim((string) ($member->placement_note ?? '')); + $row['variant'] = $member->variant?->key; + $row['requirement'] = $member->requirement ?: 'erforderlich'; + $row['selection'] = is_array($member->variant_selection) ? $member->variant_selection : null; + $row['origin'] = $member->origin ?: 'lokal'; $rows[] = $row; } @@ -140,6 +146,12 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all } $composition = $version->composition; + + // Art, die dieser Programmstand nicht kennt: nicht anbieten und nicht laden (Rückfallschutz). + if ($composition === null) { + return null; + } + $kind = $composition->editorialContentKind?->label ?: ($composition->kind instanceof CompositionKind ? $composition->kind->deskLabel() : 'Zusammenstellung'); @@ -238,7 +250,11 @@ public function search(string $query, string $scope, int $exceptCompositionId): ->with('composition.editorialContentKind') ->whereHas('composition', function ($builder) use ($scope, $query, $like): void { if ($scope === 'module') { - $builder->where('kind', CompositionKind::Uebung); + $builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]); + } + + if ($scope === 'uebungen') { + $builder->where('kind', CompositionKind::Exercise); } if ($query === '') { @@ -311,7 +327,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce ->where('composition_id', '!=', $exceptCompositionId) ->whereHas('composition', function ($builder) use ($query, $like, $kind, $dimensionId, $pillarId): void { if ($kind === 'modul') { - $builder->where('kind', CompositionKind::Uebung); + $builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]); } if ($dimensionId > 0) { @@ -357,7 +373,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce $builder->where('status', ContentVersionStatus::Bereit); }) ->when($kind === 'modul', function ($builder): void { - $builder->where('kind', CompositionKind::Uebung); + $builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]); }) ->orderByDesc('id') ->get(); @@ -1028,6 +1044,10 @@ private function suggestPicture(array $members, array $seen = []): ?array $nested = $version->composition; + if ($nested === null) { + continue; + } + if ($this->cardUrl('komposition', $nested->id, $nested->thumbnail_path) !== null) { return [ 'kind' => 'komposition', @@ -1063,6 +1083,7 @@ public function create(string $designation, CompositionKind $kind): Composition $slug = match ($kind) { CompositionKind::Kurs => 'programm', CompositionKind::Uebung => 'modul', + CompositionKind::Exercise => 'uebung', default => null, }; $editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first(); @@ -1084,6 +1105,7 @@ public static function editUrl(Composition $composition): string CompositionKind::Kurs => CourseResource::class, CompositionKind::Kombination => CombinationResource::class, CompositionKind::Uebung => ExerciseResource::class, + CompositionKind::Exercise => PracticeResource::class, }; return $resource::getUrl('edit', ['record' => $composition]); diff --git a/app/Filament/Support/ListsCompositions.php b/app/Filament/Support/ListsCompositions.php index 54fb114..143ee51 100644 --- a/app/Filament/Support/ListsCompositions.php +++ b/app/Filament/Support/ListsCompositions.php @@ -4,8 +4,10 @@ use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionKind; +use App\Domain\Catalog\CompositionMember; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\ExerciseSource; use App\Domain\Catalog\IdentityDimensionValue; use App\Domain\Catalog\Pillar; use App\Domain\Catalog\PillarFilterCompat; @@ -74,6 +76,7 @@ public function bestand(): array $einheit = match ($fixed) { CompositionKind::Kurs => ['Programm', 'Programme'], CompositionKind::Uebung => ['Modul', 'Module'], + CompositionKind::Exercise => ['Übung', 'Übungen'], CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'], default => ['Programm oder Modul', 'Programme und Module'], }; @@ -150,6 +153,10 @@ public function entries(): array $canEdit = ContentElementResource::editor(); $rows = []; + $shinkan = $kinds === [CompositionKind::Exercise] || in_array(CompositionKind::Exercise, $kinds, true) + ? ExerciseSource::query()->whereNotNull('composition_id')->pluck('composition_id')->all() + : []; + $compositions = Composition::query() ->whereIn('kind', $kinds) ->with(['editorialContentKind', 'versions.members.contentElementVersion.element']) @@ -188,7 +195,7 @@ public function entries(): array $rows[] = [ 'schluessel' => 'c'.$composition->id, 'titel' => $title, - 'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : ''), + 'meta' => $kind->deskLabel().($title !== $composition->designation ? ' · '.$composition->designation : '').($kind === CompositionKind::Exercise ? ' · Herkunft: '.$this->exerciseOrigin($composition, $shinkan) : ''), 'text' => $summary, 'bild' => $cover['url'], 'bildFehlt' => 'Kein Titelbild', @@ -214,16 +221,41 @@ public function entries(): array return $rows; } + /** + * Herkunft einer Übung: lokal angelegt, aus Shinkan übernommen oder aus Shinkan übernommen und lokal ergänzt. + * + * @param list $shinkan Übungen mit Quellbindung + */ + private function exerciseOrigin(Composition $composition, array $shinkan): string + { + if (! in_array($composition->id, $shinkan, true)) { + return 'lokal'; + } + + $latest = $composition->versions->sortByDesc('number')->first(); + $local = $latest !== null && CompositionMember::query()->where('composition_version_id', $latest->id)->where('origin', 'lokal')->exists(); + + return $local ? 'Shinkan, lokal bearbeitet' : 'Shinkan'; + } + /** * Anlegedialog für Module und Programme; derselbe auf dem Arbeitsplatz und in den Listen. */ protected function createCompositionAction(CompositionKind $kind): Action { - $label = $kind === CompositionKind::Kurs ? 'Programm' : 'Modul'; + $label = match ($kind) { + CompositionKind::Kurs => 'Programm', + CompositionKind::Exercise => 'Übung', + default => 'Modul', + }; - return Action::make($kind === CompositionKind::Kurs ? 'createProgram' : 'createModule') + return Action::make(match ($kind) { + CompositionKind::Kurs => 'createProgram', + CompositionKind::Exercise => 'createExercise', + default => 'createModule', + }) ->label($label.' anlegen') - ->modalHeading('Neues '.$label) + ->modalHeading(($kind === CompositionKind::Exercise ? 'Neue ' : 'Neues ').$label) ->modalDescription('Der Name genügt. Danach öffnet sich der Aufbau; Texte, Bilder und Einordnung folgen dort und in der Redaktion.') ->modalSubmitActionLabel($label.' anlegen') ->modalWidth('lg') diff --git a/app/Filament/Support/PublicationReadiness.php b/app/Filament/Support/PublicationReadiness.php index 94c5953..fe0ca2d 100644 --- a/app/Filament/Support/PublicationReadiness.php +++ b/app/Filament/Support/PublicationReadiness.php @@ -8,6 +8,7 @@ use App\Domain\Catalog\BundleStatus; use App\Domain\Catalog\BundleVersion; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; @@ -227,7 +228,8 @@ public function forOffer(Offer $offer): array $missing = $this->unusableArticles($articleIds); $buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null; $page = $offer->composition; - $shown = $page !== null && $this->catalog->shownVersion($page) !== null; + $own = (bool) $offer->standalone_bundle; + $shown = $own || ($page !== null && $this->catalog->shownVersion($page) !== null); $pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : ''; $activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"]; @@ -258,21 +260,36 @@ public function forOffer(Offer $offer): array 'stand' => $buyable ? 'erledigt' : 'offen', 'aktion' => $buyable ? null : ($hasActive ? $activate : null), ], + [ + 'titel' => 'Nutzerkreis festlegen', + 'text' => ! $hasActive + ? 'Wird mit der Fassung festgelegt: Einzellizenz (ein Trainer) oder Mehrfachlizenz (Zahl der Trainer).' + : ($active->licence_scope !== null + ? LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.' + : 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'), + 'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen', + 'aktion' => $hasActive && $active->licence_scope === null ? $activate : null, + 'pflicht' => false, + ], [ 'titel' => 'Produktseite zuordnen', - 'text' => $page !== null - ? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.' - : 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket braucht eine eigene Produktseite, sonst ist es Alternative zu den Einzelangeboten dieser Seite.', - 'stand' => $page !== null ? 'erledigt' : 'offen', - 'aktion' => $page !== null ? null : $activate, + 'text' => $own + ? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.' + : ($page !== null + ? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.' + : 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'), + 'stand' => $own || $page !== null ? 'erledigt' : 'offen', + 'aktion' => $own || $page !== null ? null : $activate, ], [ 'titel' => 'Produktseite öffentlich', - 'text' => $page === null + 'text' => ! $own && $page === null ? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.' - : ($shown + : ($own + ? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.' + : ($shown ? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.' - : 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.'), + : 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')), 'stand' => $shown ? 'erledigt' : 'offen', 'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)], ], diff --git a/app/Filament/Support/ShopAccess.php b/app/Filament/Support/ShopAccess.php new file mode 100644 index 0000000..eae8d5d --- /dev/null +++ b/app/Filament/Support/ShopAccess.php @@ -0,0 +1,22 @@ +user(); + + return $user instanceof User + && ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung)); + } +} diff --git a/app/Http/Controllers/CartController.php b/app/Http/Controllers/CartController.php index 51efd3e..7b5eb7d 100644 --- a/app/Http/Controllers/CartController.php +++ b/app/Http/Controllers/CartController.php @@ -7,6 +7,7 @@ use App\Domain\Commerce\Cart; use App\Domain\Commerce\Money; use App\Domain\Commerce\OrderHolders; +use App\Domain\Commerce\ProductOptions; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\View\View; @@ -31,9 +32,8 @@ public function show(Request $request, Cart $cart, OrderHolders $holders): View public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse { $page = $offer->composition; - $result = $page !== null && $catalog->shownVersion($page) !== null - ? $cart->add($offer) - : Cart::UNAVAILABLE; + $listed = $offer->standalone_bundle || ($page !== null && $catalog->shownVersion($page) !== null); + $result = $listed ? $cart->add($offer) : Cart::UNAVAILABLE; $back = $this->productPage($offer); return match ($result) { @@ -81,8 +81,8 @@ public function accept(Offer $offer, Cart $cart): RedirectResponse private function productPage(Offer $offer): RedirectResponse { - return $offer->composition_id !== null - ? redirect()->route('public.program', $offer->composition_id) - : redirect()->route('cart'); + $url = app(ProductOptions::class)->pageUrl($offer); + + return $url !== null ? redirect()->to($url) : redirect()->route('cart'); } } diff --git a/app/Http/Controllers/Member/CheckoutController.php b/app/Http/Controllers/Member/CheckoutController.php index b89e285..c7e7d2f 100644 --- a/app/Http/Controllers/Member/CheckoutController.php +++ b/app/Http/Controllers/Member/CheckoutController.php @@ -7,12 +7,15 @@ use App\Domain\Catalog\OfferStatus; use App\Domain\Commerce\Cart; use App\Domain\Commerce\Checkout; +use App\Domain\Commerce\LedgerEntry; use App\Domain\Commerce\Order; use App\Domain\Commerce\OrderHolders; +use App\Domain\Commerce\SalesTerms; use App\Domain\Commerce\Shop; use App\Domain\Commerce\StaleOverview; use App\Domain\Commerce\Stripe\StripeGateway; use App\Domain\Entitlement\GrantIssuer; +use App\Domain\Identity\PartyType; use App\Http\Controllers\Controller; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -67,9 +70,38 @@ public function checkout(Request $request, Cart $cart, OrderHolders $holders): V return view('shop.checkout', [ 'review' => $review, 'holders' => $holders->for($request->user()), + 'consents' => SalesTerms::consents(), + 'legalPages' => SalesTerms::pages(), + 'invoice' => Shop::invoice() && $review->holder?->type === PartyType::Organisation, ]); } + /** + * Rabattcode einlösen. Höchstens ein Code je Bestellung; ein zweiter ersetzt den ersten. Gilt der Code nicht, + * bleibt der bisherige Stand und die Meldung nennt den Grund. + */ + public function applyCode(Request $request, Cart $cart): RedirectResponse + { + $data = $request->validate(['code' => ['required', 'string', 'max:60'], 'bestellen_als' => ['nullable', 'integer']], [ + 'code.required' => 'Gib einen Rabattcode ein.', + ]); + $holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null; + $result = $cart->applyCode($data['code'], $request->user(), $holderId); + $back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId])); + + return $result->applied() + ? $back->with('status', 'Der Rabattcode '.$result->code->code.' ist angewendet.') + : $back->withErrors(['code' => $result->message ?? 'Der Code kann nicht angewendet werden.']); + } + + public function removeCode(Request $request, Cart $cart): RedirectResponse + { + $cart->removeCode(); + $holderId = $request->integer('bestellen_als') ?: null; + + return redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]))->with('status', 'Der Rabattcode ist entfernt.'); + } + /** * Legt die Bestellung an, aber nur, wenn die serverseitige Prüfung zur gezeigten Übersicht passt. */ @@ -78,19 +110,28 @@ public function placeOrder(Request $request, Cart $cart, Checkout $checkout): Re $data = $request->validate([ 'digest' => ['required', 'string'], 'bestellen_als' => ['nullable', 'integer'], + 'zahlungsweg' => ['nullable', 'in:online,rechnung'], + 'zustimmung' => ['nullable', 'array'], ]); $holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null; $back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId])); + $method = ($data['zahlungsweg'] ?? 'online') === 'rechnung' ? 'rechnung' : null; try { - $order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest']); + // Die Zustimmungen sind eine Pflichtangabe und werden serverseitig geprüft, nicht nur im Formular. + SalesTerms::proof((array) ($data['zustimmung'] ?? [])); + $order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest'], (array) ($data['zustimmung'] ?? []), $method); } catch (StaleOverview $exception) { return $back->withErrors(['checkout' => $exception->getMessage()]); } catch (DomainRuleException $exception) { return $back->withErrors(['checkout' => $exception->getMessage()]); } - return redirect()->route('member.order', $order)->with('status', 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.'); + return redirect()->route('member.order', $order)->with('status', match (true) { + $order->payment_method === 'rechnung' => 'Deine Bestellung auf Rechnung ist eingegangen. Wir senden dir die Rechnung. Die Inhalte sind nach Zahlungseingang in der Bibliothek.', + Shop::stripe() => 'Die Bestellung ist angelegt. Bezahle jetzt sicher bei Stripe.', + default => 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.', + }); } public function show(Request $request, Order $order): View @@ -103,9 +144,26 @@ public function show(Request $request, Order $order): View 'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test', 'stripePayment' => Shop::stripe(), 'zahlung' => $request->query('zahlung'), + 'live' => Shop::live(), + 'receipts' => LedgerEntry::query()->where('order_id', $order->id)->where('derived', false)->orderBy('occurred_at')->orderBy('id')->get(), ]); } + /** Erklärt den Widerruf; der Betreiber prüft und erstattet gegebenenfalls in der Bestellverwaltung. */ + public function withdraw(Request $request, Order $order, Checkout $checkout): RedirectResponse + { + abort_unless($order->user_id === $request->user()->id, 403); + $data = $request->validate(['note' => ['nullable', 'string', 'max:1000']]); + + try { + $checkout->requestWithdrawal($order, (string) ($data['note'] ?? '')); + } catch (DomainRuleException $exception) { + return back()->withErrors(['payment' => $exception->getMessage()]); + } + + return redirect()->route('member.order', $order)->with('status', 'Dein Widerruf ist eingegangen. Wir prüfen ihn und melden uns per E-Mail.'); + } + /** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */ public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse { @@ -150,6 +208,8 @@ public function fail(Request $request, Order $order, Checkout $checkout): Redire public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse { abort_unless($order->user_id === $request->user()->id, 403); + // Nur der Testzahlungsweg erstattet auf Knopfdruck. Echte Zahlungen erstattet der Betreiber nach Prüfung. + abort_unless(! app()->isProduction() && Shop::driver() === 'test', 404); try { $checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus'); 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/app/Http/Controllers/Member/LibraryController.php b/app/Http/Controllers/Member/LibraryController.php index c8754fd..1de6b95 100644 --- a/app/Http/Controllers/Member/LibraryController.php +++ b/app/Http/Controllers/Member/LibraryController.php @@ -6,6 +6,7 @@ use App\Domain\Catalog\Composition; use App\Domain\Catalog\ContentElement; use App\Domain\Catalog\ContentElementVersion; +use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialVocabulary; use App\Domain\Catalog\IdentityDimension; use App\Domain\Catalog\LicenseArticle; @@ -501,8 +502,10 @@ private function maySeeThumbnail(Request $request, string $kind, int $subject): return true; } + // Ein gesperrtes Medium zeigt auch kein Vorschaubild mehr (Sperre gilt für Ausgaben und Ableitungen). if ($kind === 'element' && $release->contents->contains( - fn ($content): bool => $content->elementVersion?->content_element_id === $subject, + fn ($content): bool => $content->elementVersion?->content_element_id === $subject + && $content->elementVersion->status !== ContentVersionStatus::Gesperrt, )) { return true; } diff --git a/app/Http/Controllers/Member/PaymentController.php b/app/Http/Controllers/Member/PaymentController.php new file mode 100644 index 0000000..6d39f56 --- /dev/null +++ b/app/Http/Controllers/Member/PaymentController.php @@ -0,0 +1,56 @@ +whereHas('order', fn ($orders) => $orders->where('user_id', $request->user()->id)) + ->orderByDesc('occurred_at') + ->orderByDesc('id') + ->get(); + + return view('member.payments', [ + 'rows' => $entries->map(fn (LedgerEntry $entry): array => [ + 'id' => $entry->id, + 'order' => $entry->order_id, + 'refund' => $entry->isRefund(), + 'date' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y'), + 'products' => collect((array) (($entry->order_snapshot ?? [])['lines'] ?? []))->pluck('name')->filter()->values()->all(), + 'amount' => $entry->amount_cents, + 'provider' => PaymentJournal::providerLabel($entry->provider), + 'test' => ! $entry->live, + 'receipt' => PaymentReceipt::available($entry), + ])->all(), + ]); + } + + public function receipt(Request $request, LedgerEntry $entry): Response + { + $entry->loadMissing('order'); + abort_unless($entry->order?->user_id === $request->user()->id, 403); + abort_unless(PaymentReceipt::available($entry), 404); + + return response(PaymentReceipt::render($entry), 200, [ + 'Content-Type' => 'application/pdf', + 'Content-Disposition' => 'attachment; filename="'.PaymentReceipt::filename($entry).'"', + 'Cache-Control' => 'private, no-store', + 'X-Content-Type-Options' => 'nosniff', + ]); + } +} diff --git a/app/Http/Controllers/PublicCatalogController.php b/app/Http/Controllers/PublicCatalogController.php index b746bf9..d20fab9 100644 --- a/app/Http/Controllers/PublicCatalogController.php +++ b/app/Http/Controllers/PublicCatalogController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionStructureReader; use App\Domain\Cms\Catalog\PublicCatalogReader; @@ -17,6 +18,25 @@ public function index(PublicCatalogReader $catalog): View return view('public.programs', ['programs' => $catalog->publicPrograms()]); } + /** + * Eigene Produktseite eines Pakets, das für sich vermarktet wird: Sie zeigt den tatsächlichen Umfang des Pakets + * (die enthaltenen Artikel) und darunter die kaufbaren Lizenzoptionen. Ohne kaufbare Option gibt es sie nicht. + */ + public function package(Bundle $bundle, ProductOptions $products, Cart $cart): View + { + abort_unless(Shop::enabled(), 404); + $options = $products->forBundle($bundle); + abort_if($options === [], 404); + + return view('public.package', [ + 'bundle' => $bundle, + 'contents' => $products->bundleContents($options), + 'options' => $options, + 'cart' => $cart, + 'switchTo' => session('shop.switch'), + ]); + } + public function program(Composition $composition, PublicCatalogReader $catalog, ProductOptions $products, Cart $cart): View { $version = $catalog->shownVersion($composition); diff --git a/app/Http/Controllers/ShopController.php b/app/Http/Controllers/ShopController.php index dadab27..92901f6 100644 --- a/app/Http/Controllers/ShopController.php +++ b/app/Http/Controllers/ShopController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Commerce\Money; @@ -37,7 +38,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR $summary = $summaries[$composition->id]; $cards[] = [ - 'composition' => $composition, + 'url' => route('public.program', $composition), 'title' => $title, 'teaser' => (string) ($composition->teaser ?: $composition->summary), 'from' => Money::format($summary['from_cents']), @@ -45,6 +46,26 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR ]; } + // Pakete mit eigener Produktseite: gelistet mit Name und enthaltenen Artikeln. + foreach (Bundle::query()->whereIn('id', array_keys($products->bundleSummaries()))->orderBy('name')->get() as $bundle) { + $options = $products->forBundle($bundle); + $contents = $products->bundleContents($options); + $names = implode(', ', array_column($contents, 'title')); + + if ($term !== '' && ! str_contains(mb_strtolower($bundle->name.' '.$names), mb_strtolower($term))) { + continue; + } + + $summary = $products->bundleSummaries()[$bundle->id]; + $cards[] = [ + 'url' => route('public.package', $bundle), + 'title' => (string) $bundle->name, + 'teaser' => 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : ''), + 'from' => Money::format($summary['from_cents']), + 'count' => $summary['count'], + ]; + } + return view('shop.index', ['cards' => $cards, 'term' => $term]); } } diff --git a/app/Http/Controllers/StripeWebhookController.php b/app/Http/Controllers/StripeWebhookController.php index b18fd0b..5a77b9f 100644 --- a/app/Http/Controllers/StripeWebhookController.php +++ b/app/Http/Controllers/StripeWebhookController.php @@ -8,6 +8,7 @@ use App\Domain\Commerce\Payment; use App\Domain\Commerce\Shop; use App\Domain\Commerce\Stripe\StripeSignature; +use Carbon\CarbonImmutable; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; @@ -42,7 +43,7 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout $session = (array) ($event['data']['object'] ?? []); return match ($event['type']) { - 'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout), + 'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout, $event), 'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']), default => response()->json(['received' => true, 'handled' => false]), }; @@ -50,8 +51,9 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout /** * @param array $session + * @param array $event */ - private function paid(array $session, Checkout $checkout): JsonResponse + private function paid(array $session, Checkout $checkout, array $event): JsonResponse { if (($session['payment_status'] ?? null) !== 'paid') { return response()->json(['received' => true, 'handled' => false]); @@ -73,6 +75,9 @@ private function paid(array $session, Checkout $checkout): JsonResponse $reference, (int) ($session['amount_total'] ?? -1), (string) ($session['currency'] ?? ''), + (bool) ($event['livemode'] ?? $session['livemode'] ?? false), + is_numeric($event['created'] ?? null) ? CarbonImmutable::createFromTimestampUTC((int) $event['created']) : null, + filled($session['payment_intent'] ?? null) ? (string) $session['payment_intent'] : null, ); } catch (DomainRuleException $exception) { // Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur @@ -83,6 +88,10 @@ private function paid(array $session, Checkout $checkout): JsonResponse return response()->json(['received' => true, 'handled' => false]); } + if (filled($session['payment_intent'] ?? null)) { + $order->payments()->where('provider_reference', $reference)->update(['provider_payment_ref' => (string) $session['payment_intent']]); + } + return response()->json(['received' => true, 'handled' => true]); } diff --git a/app/Http/LibraryCatalog.php b/app/Http/LibraryCatalog.php index f3d2539..d715389 100644 --- a/app/Http/LibraryCatalog.php +++ b/app/Http/LibraryCatalog.php @@ -5,11 +5,13 @@ use App\Domain\Catalog\ArticleRelease; use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionDisplayRelease; +use App\Domain\Catalog\CompositionKind; use App\Domain\Catalog\CompositionStructureReader; use App\Domain\Catalog\CompositionVersion; use App\Domain\Catalog\ContentElement; use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\EditorialProfileReader; +use App\Domain\Catalog\ExerciseGuide; use App\Domain\Catalog\ReleaseStatus; use App\Domain\Catalog\StructureNode; use App\Domain\Entitlement\DecideAccess; @@ -389,7 +391,7 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI 'view_url' => $view, 'poster_url' => $poster, 'download_url' => $download, - 'program_url' => $this->programUrl($node), + 'program_url' => $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node), 'composition_id' => $node->compositionId, 'element_id' => $node->contentElementId, 'version_id' => $node->contentElementVersionId, @@ -491,6 +493,46 @@ private function element(int $id): ?ContentElement return $this->elements[$id]; } + /** + * Eine Übung im Zusammenhang des erworbenen Moduls oder Programms: die im Stand gebundene Fassung und ihre Varianten, + * nicht die jeweils neueste Fassung der Übung. Gefunden wird der jüngste auslieferbare Stand des Kontos, dessen + * festgeschriebene Wurzel diese Fassung an einer Stelle einbindet. + */ + private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?string + { + if ($node->compositionVersionId === null) { + return null; + } + + $nested = CompositionVersion::query()->with('composition')->find($node->compositionVersionId); + + if ($nested?->composition?->kind !== CompositionKind::Exercise) { + return null; + } + + $guide = app(ExerciseGuide::class); + + foreach ($this->grants($user) as $grant) { + $releases = ArticleRelease::query() + ->where('license_article_id', $grant->license_article_id) + ->whereIn('status', [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar]) + ->whereHas('rootCompositionVersion', fn ($query) => $query->where('composition_id', $rootId)) + ->with('rootCompositionVersion') + ->orderByDesc('number') + ->get(); + + foreach ($releases as $release) { + $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 null; + } + private function programUrl(StructureNode $node): ?string { if ($node->compositionId === null || $node->compositionVersionId === null) { diff --git a/app/Http/MemberLicenses.php b/app/Http/MemberLicenses.php index f995c9b..9ff1a54 100644 --- a/app/Http/MemberLicenses.php +++ b/app/Http/MemberLicenses.php @@ -158,6 +158,8 @@ private function entry(User $user, Grant $grant): array ? 'Spätere freigegebene Fassungen sind eingeschlossen.' : null, 'source' => $this->source($user, $grant), + 'licence_scope' => $conditions['licence_scope'] ?? null, + 'trainer_count' => isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null, 'holder_kind' => $holderKind, 'holder' => $holderKind === 'organisation' ? (string) ($grant->acquisition?->party?->display_name ?? 'Organisation') : 'Persönlich', 'url' => route('member.grant', $grant), diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 89f9729..4138c79 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -67,6 +67,12 @@ public function panel(Panel $panel): Panel ->authMiddleware([ Authenticate::class, ]) + // Favicon zur Anfragezeit: ->favicon(asset(...)) würde beim Start der Anwendung berechnet, vor der + // Auswertung von Proxy-Kopfzeilen und geöffneter Adresse, und könnte auf einen falschen Host zeigen. + ->renderHook( + PanelsRenderHook::HEAD_END, + fn (): string => view('components.site.favicon')->render(), + ) ->renderHook( PanelsRenderHook::STYLES_AFTER, fn (): string => view('filament.cms.styles')->render().view('filament.verwaltung.styles')->render(), diff --git a/app/Support/Brand/Symbols.php b/app/Support/Brand/Symbols.php new file mode 100644 index 0000000..af63267 --- /dev/null +++ b/app/Support/Brand/Symbols.php @@ -0,0 +1,84 @@ +/ sind zulässig; ein unbekannter Name ist ein Fehler, kein stiller Leerplatz. + * - Die Kit-Dateien tragen alle dieselbe ID (motif-title) und einen Titel. Beim Einbetten werden ID, Titel, Rolle und feste + * Größe entfernt, damit mehrere Symbole auf einer Seite keine doppelten IDs erzeugen. Symbole sind Beiwerk + * (aria-hidden); die Aussage trägt immer der danebenstehende Text. + * - Sätze: „symbole“ (Symbole und Akzente aus dem Kit, feste Markenfarben) und „glyphen“ (kleine Zeichen für Tags, Farbe + * über currentColor, Geometrie aus den Tag-Dateien des Kits). + * - Nicht enthalten: die Motive mit Text als Pfad (Pinsel, Pillen, Tags, Kompositionen). Text bleibt HTML. + */ +final class Symbols +{ + public const SET_SYMBOLS = 'symbole'; + + public const SET_GLYPHS = 'glyphen'; + + /** @var array */ + private static array $cache = []; + + /** + * @return list + */ + public static function names(string $set = self::SET_SYMBOLS): array + { + $files = glob(self::directory($set).'/*.svg') ?: []; + $names = array_map(fn (string $file): string => basename($file, '.svg'), $files); + sort($names); + + return $names; + } + + public static function symbol(string $name, string $attributes = ''): HtmlString + { + return self::render(self::SET_SYMBOLS, $name, $attributes); + } + + public static function glyph(string $name, string $attributes = ''): HtmlString + { + return self::render(self::SET_GLYPHS, $name, $attributes); + } + + /** + * @param string $attributes bereits maskierte Attribute (aus der Attributtasche der Komponente) + */ + private static function render(string $set, string $name, string $attributes): HtmlString + { + if (! preg_match('/^[a-z0-9-]+$/', $name) || ! in_array($name, self::names($set), true)) { + throw new InvalidArgumentException("Unbekanntes Markensymbol „{$name}“ im Satz „{$set}“."); + } + + $svg = self::$cache["$set/$name"] ??= self::clean((string) file_get_contents(self::directory($set)."/$name.svg")); + $extra = trim($attributes) === '' ? '' : ' '.trim($attributes); + + return new HtmlString(preg_replace('/^