Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0287eec2f | ||
|
|
42e0a6bb93 | ||
|
|
76fab81386 | ||
|
|
1ce2e1e51f | ||
|
|
0154182f3b | ||
|
|
cb80835c92 | ||
|
|
e7efb073da | ||
|
|
433f9aee61 | ||
|
|
bb0949dcd9 | ||
|
|
2d54d39c24 | ||
|
|
cf50d341f5 | ||
|
|
8b644292a7 | ||
|
|
0c4ef4c4ed | ||
|
|
2e6260acca | ||
|
|
8ecc1ecdaa | ||
|
|
9f070fbab2 | ||
|
|
ca0f68e8f6 | ||
|
|
aa1e6eb6ac | ||
|
|
b8c5c68887 | ||
|
|
acb88e4a1d | ||
|
|
2a54347d50 | ||
|
|
992171bb7a | ||
|
|
061181f30d |
No files matched your search
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > 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<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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<array{license_article_id: int, rights_profile_version_id: int}> $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<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
||||
|
||||
@@ -19,6 +19,8 @@ class OfferVersion extends Model
|
||||
'dynamic',
|
||||
'grant_kind',
|
||||
'holder_kind',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'activated_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -115,10 +115,18 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['accent'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'heading_level' => ['Überschriftenebene', 'Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'],
|
||||
'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -117,11 +117,19 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Aussehen' => ['surface'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -176,19 +176,34 @@ public function settings(): array
|
||||
];
|
||||
}
|
||||
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [
|
||||
'Bild und Video' => ['format', 'fit', 'clip'],
|
||||
'Texte auf der Karte' => ['show_body', 'text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'],
|
||||
'Seitenstruktur' => ['heading_level'],
|
||||
];
|
||||
}
|
||||
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
// „Texte auf der Karte: Ausblenden“ macht die Einzelschalter wirkungslos; sie bleiben gespeichert, aber unsichtbar.
|
||||
return array_fill_keys(['text_source', 'show_summary', 'show_kind', 'show_meta', 'show_action'], ['show_body', 'no']);
|
||||
}
|
||||
|
||||
public function settingLabels(): array
|
||||
{
|
||||
return [
|
||||
'text_source' => ['Text der Karte', 'Welche Angabe aus der Redaktion die Karte zeigt. Vorgabe: Automatisch. Der gewählte Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Text.'],
|
||||
'format' => ['Bildformat', 'Seitenverhältnis des Bildes oder Videos. Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bildausschnitt', 'Ausschnitt füllt die ganze Fläche; „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche. Vorgabe: Ausschnitt.'],
|
||||
'clip' => ['Trailer auf der Karte', 'Spielt den freigegebenen Trailer als stumme Vorschau, solange die Maus auf der Karte steht; ein Klick oder Tipp auf das Bild oder die kleine Schaltfläche (auch per Tastatur) spielt ihn mit Ton. Gewählt wird der Trailer (sonst der Vorschauclip) in der Präsentation des Objekts, bei einem Film ersatzweise sein freigegebener Teaser. Ohne freigegebenen Clip bleibt das Kartenbild. Vorgabe: Abspielen.'],
|
||||
'show_body' => ['Texte neben dem Bild', 'Ausblenden zeigt nur Bild und Video, ohne Titel, Text, Art, Zusatzangaben und Aktion. Für Hilfstechnik bleibt der Titel unsichtbar erhalten. Sinnvoll, wenn das Video allein erklärt. Vorgabe: anzeigen.'],
|
||||
'format' => ['Bildformat', 'Vorgabe: Querformat 16:9. Gilt auch neben dem Text; das Motiv wird nicht nachträglich hochkant beschnitten.'],
|
||||
'fit' => ['Bilddarstellung', 'Vorgabe: Ausschnitt. „Ganzes Bild“ zeigt Dokumente und Poster vollständig auf ruhiger Fläche.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
'show_summary' => ['Text anzeigen', 'Aus den Fachdaten. Vorgabe: anzeigen.'],
|
||||
'show_kind' => ['Art oder Label', 'Zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: anzeigen.'],
|
||||
'show_action' => ['Aktion', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: anzeigen.'],
|
||||
'show_body' => ['Texte auf der Karte', 'Hauptschalter für alle Texte neben dem Bild. „Ausblenden“ zeigt nur Bild und Video, ohne Titel, Beschreibung, Art, Zusatzangaben und Schaltfläche; die Einzelschalter darunter verschwinden dann. Für Hilfstechnik bleibt der Titel unsichtbar erhalten. Sinnvoll, wenn das Video allein erklärt. Vorgabe: Anzeigen.'],
|
||||
'text_source' => ['Quelle der Beschreibung', 'Welche Angabe aus der Redaktion als Beschreibung erscheint. Vorgabe: Automatisch. Der Text erscheint öffentlich, wenn die Karte öffentlich ist; ist er nicht gepflegt, bleibt die Karte ohne Beschreibung.'],
|
||||
'show_summary' => ['Beschreibung', 'Der Beschreibungstext unter dem Titel, aus den Fachdaten. Vorgabe: Anzeigen.'],
|
||||
'show_kind' => ['Art-Label', 'Kleines Label über dem Titel, zum Beispiel „Thema“ oder „Merkblatt“. Vorgabe: Anzeigen.'],
|
||||
'show_meta' => ['Zusatzangaben', 'Angaben aus den Fachdaten, zum Beispiel Ausgabeart oder Programmzugehörigkeit. Vorgabe: Anzeigen.'],
|
||||
'show_action' => ['Schaltfläche', 'Verweis auf die öffentliche Seite des Fachobjekts, falls es eine gibt. Vorgabe: Anzeigen.'],
|
||||
'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Vorgabe: H3, passend unter einer Abschnittsüberschrift (H2).'],
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -194,6 +194,29 @@ public function settingLabels(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung der Einstellungen im Reiter „Darstellung“: Gruppentitel => Schlüssel der Einstellungen in der
|
||||
* Reihenfolge der Anzeige. Variante und Höhe stehen immer in der ersten Gruppe „Aufbau“. Einstellungen ohne
|
||||
* Gruppe erscheinen unter „Weitere Einstellungen“, so geht keine verloren.
|
||||
*
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function settingGroups(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Einstellungen, die im Editor ausgeblendet werden, solange eine andere Einstellung einen bestimmten Wert hat:
|
||||
* Schlüssel => [steuernde Einstellung, Wert, bei dem ausgeblendet wird]. Die Werte bleiben dabei erhalten.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: string}>
|
||||
*/
|
||||
public function settingHiddenWhen(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle zulässigen Einstellungen einschließlich der gemeinsamen Höhe. Registry-Prüfung, Editor und Darstellung
|
||||
* verwenden ausschließlich diese Zusammenführung.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<CartLine> */
|
||||
@@ -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() ?? '-'));
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,15 @@
|
||||
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 Illuminate\Support\Facades\DB;
|
||||
@@ -44,7 +47,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 +56,21 @@ 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.
|
||||
$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 +88,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 +110,28 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
|
||||
|
||||
/**
|
||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
||||
* @param array<string, mixed>|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 +146,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,6 +175,7 @@ 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);
|
||||
}
|
||||
@@ -150,7 +186,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): 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.');
|
||||
@@ -159,6 +195,22 @@ public function confirmProviderPayment(Order $order, string $provider, string $r
|
||||
return $this->settle($order, $provider, $reference);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
if ($order->payment_method !== 'rechnung') {
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference));
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
@@ -182,7 +234,7 @@ 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(
|
||||
['provider_reference' => $reference],
|
||||
['provider' => $provider, 'status' => 'bestaetigt'],
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable()],
|
||||
);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
@@ -207,6 +259,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 +282,11 @@ 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.
|
||||
*/
|
||||
public function refund(Order $order, string $reason): Order
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null): Order
|
||||
{
|
||||
$reason = trim($reason);
|
||||
|
||||
@@ -239,6 +294,13 @@ public function refund(Order $order, string $reason): Order
|
||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
||||
}
|
||||
|
||||
$current = Order::query()->findOrFail($order->id);
|
||||
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
||||
|
||||
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
||||
($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
@@ -270,6 +332,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 +361,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') {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
|
||||
*
|
||||
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
|
||||
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
|
||||
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
|
||||
*
|
||||
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
|
||||
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
|
||||
* frühere Position.
|
||||
*/
|
||||
final class DiscountCalculator
|
||||
{
|
||||
/**
|
||||
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
|
||||
* @return array<int|string, int> 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
|
||||
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
|
||||
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
|
||||
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
|
||||
*/
|
||||
class DiscountCode extends Model
|
||||
{
|
||||
public const PERCENT = 'prozent';
|
||||
|
||||
public const AMOUNT = 'betrag';
|
||||
|
||||
public const SCOPE_CART = 'warenkorb';
|
||||
|
||||
public const SCOPE_SELECTED = 'auswahl';
|
||||
|
||||
public const OPEN = 'allgemein';
|
||||
|
||||
public const RESTRICTED = 'freigabe';
|
||||
|
||||
public const TARGET_OFFER = 'angebot';
|
||||
|
||||
public const TARGET_ARTICLE = 'lizenzartikel';
|
||||
|
||||
public const TARGET_BUNDLE = 'paket';
|
||||
|
||||
protected $fillable = [
|
||||
'code',
|
||||
'label',
|
||||
'kind',
|
||||
'percent',
|
||||
'amount_cents',
|
||||
'scope',
|
||||
'eligibility',
|
||||
'valid_from',
|
||||
'valid_until',
|
||||
'active',
|
||||
'note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'valid_from' => '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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
|
||||
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
|
||||
*/
|
||||
class DiscountCodeTarget extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'target_type',
|
||||
'target_id',
|
||||
];
|
||||
|
||||
public function code(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
|
||||
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
|
||||
*/
|
||||
class DiscountRelease extends Model
|
||||
{
|
||||
protected $table = 'discount_code_releases';
|
||||
|
||||
protected $fillable = [
|
||||
'discount_code_id',
|
||||
'user_id',
|
||||
'granted_by',
|
||||
'granted_at',
|
||||
'valid_until',
|
||||
'revoked_by',
|
||||
'revoked_at',
|
||||
'reason',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'granted_at' => '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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
/**
|
||||
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
|
||||
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
|
||||
* den Grund erfährt.
|
||||
*/
|
||||
final class DiscountResult
|
||||
{
|
||||
public const OK = 'ok';
|
||||
|
||||
public const UNKNOWN = 'unbekannt';
|
||||
|
||||
public const INACTIVE = 'deaktiviert';
|
||||
|
||||
public const NOT_YET = 'noch_nicht';
|
||||
|
||||
public const EXPIRED = 'abgelaufen';
|
||||
|
||||
public const LOGIN = 'anmeldung';
|
||||
|
||||
public const NO_RELEASE = 'keine_freigabe';
|
||||
|
||||
public const NO_MATCH = 'keine_position';
|
||||
|
||||
public const TOO_HIGH = 'zu_hoch';
|
||||
|
||||
/**
|
||||
* @param array<int, int> $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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Discount;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\CartLine;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
|
||||
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
|
||||
*/
|
||||
class DiscountService
|
||||
{
|
||||
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
|
||||
public const MIN_PAYABLE_CENTS = 50;
|
||||
|
||||
public function find(string $input): ?DiscountCode
|
||||
{
|
||||
$code = DiscountCode::normalise($input);
|
||||
|
||||
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<CartLine> $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<string, mixed> $data
|
||||
* @param list<array{type: string, id: int}> $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<array{type: string, id: int}> $targets
|
||||
* @return list<array{type: string, id: int}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -12,6 +12,8 @@ class Payment extends Model
|
||||
'provider',
|
||||
'status',
|
||||
'provider_reference',
|
||||
'provider_payment_ref',
|
||||
'amount_cents',
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
|
||||
@@ -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<array<string, mixed>>
|
||||
*/
|
||||
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<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
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<array<string, mixed>> $options
|
||||
* @return list<array{title: string, teaser: string}>
|
||||
*/
|
||||
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,18 +210,28 @@ 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,
|
||||
];
|
||||
}
|
||||
|
||||
public static function termLabel(OfferVersion $version): string
|
||||
{
|
||||
return match ($version->term_rule) {
|
||||
return self::termRuleLabel($version->term_rule);
|
||||
}
|
||||
|
||||
/** Laufzeitregel aus der Angebotsfassung oder aus den Bedingungen eines Erwerbs (gleiche Schlüssel). */
|
||||
public static function termRuleLabel(?string $rule): string
|
||||
{
|
||||
return match ((string) $rule) {
|
||||
'dauerhaft' => 'Dauerhaft nutzbar',
|
||||
'befristet' => 'Befristet',
|
||||
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
|
||||
'periodisch' => 'Laufend, periodisch',
|
||||
default => (string) $version->term_rule,
|
||||
default => (string) $rule,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Page;
|
||||
|
||||
/**
|
||||
* Pflichtangaben und Zustimmungen im Bestellablauf (Verkaufsstart Deutschland, PAY-005, PAY-009).
|
||||
*
|
||||
* Die finalen Rechtstexte (AGB, Lizenzbedingungen, Widerrufsbelehrung, Impressum, Datenschutz) liegen als Seiten im
|
||||
* CMS und werden hier nur verlinkt. Der Wortlaut der Zustimmungen unten ist ein ENTWURF zur Prüfung durch die
|
||||
* Rechtsberatung. Er ist nicht rechtlich freigegeben; `VERSION` hält fest, welcher Wortlaut galt, damit die Zustimmung
|
||||
* je Bestellung nachvollziehbar bleibt.
|
||||
*/
|
||||
final class SalesTerms
|
||||
{
|
||||
public const VERSION = '2026-11-24-entwurf';
|
||||
|
||||
/** Schaltfläche zum verbindlichen Abschluss (Button-Lösung, § 312j Abs. 3 BGB). */
|
||||
public const ORDER_BUTTON = 'Zahlungspflichtig bestellen';
|
||||
|
||||
public const ORDER_BUTTON_INVOICE = 'Zahlungspflichtig auf Rechnung bestellen';
|
||||
|
||||
/**
|
||||
* Seiten der Rechtstexte: Schlüssel => Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt).
|
||||
*
|
||||
* @return array<string, array{label: string, paths: list<string>, 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<string, string>
|
||||
*/
|
||||
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<string, string>
|
||||
*/
|
||||
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<string, mixed> $accepted Schlüssel => angekreuzt
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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_');
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,10 @@
|
||||
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 Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
@@ -11,9 +14,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 +29,7 @@ class StripeGateway
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertSandbox();
|
||||
$this->assertAllowed();
|
||||
$order->loadMissing('lines', 'user');
|
||||
$taxRate = $this->taxRate();
|
||||
|
||||
@@ -51,12 +56,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 +93,59 @@ 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).
|
||||
*/
|
||||
public function refund(Order $order, Payment $payment, string $reason): void
|
||||
{
|
||||
$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');
|
||||
$payment->provider_payment_ref = $intent;
|
||||
$payment->save();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Rechnungsadresse eines Lizenzinhabers (Person oder Organisation). Eine je Inhaber. Sie wird nur gepflegt;
|
||||
* eine Bestellung kopiert sie erst, wenn die Rechnungsstellung sie braucht.
|
||||
*/
|
||||
class BillingAddress extends Model
|
||||
{
|
||||
/** Auswählbare Länder (ISO 3166-1 Alpha-2). */
|
||||
public const COUNTRIES = [
|
||||
'DE' => 'Deutschland',
|
||||
'AT' => 'Österreich',
|
||||
'CH' => 'Schweiz',
|
||||
'LI' => 'Liechtenstein',
|
||||
'LU' => 'Luxemburg',
|
||||
'BE' => 'Belgien',
|
||||
'NL' => 'Niederlande',
|
||||
'FR' => 'Frankreich',
|
||||
'IT' => 'Italien',
|
||||
'DK' => 'Dänemark',
|
||||
'PL' => 'Polen',
|
||||
'CZ' => 'Tschechien',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'party_id',
|
||||
'recipient',
|
||||
'line2',
|
||||
'street',
|
||||
'postal_code',
|
||||
'city',
|
||||
'country',
|
||||
];
|
||||
|
||||
public function party(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ public function user(): HasOne
|
||||
return $this->hasOne(User::class);
|
||||
}
|
||||
|
||||
public function billingAddress(): HasOne
|
||||
{
|
||||
return $this->hasOne(BillingAddress::class);
|
||||
}
|
||||
|
||||
public function profile(): HasOne
|
||||
{
|
||||
return $this->hasOne(Profile::class);
|
||||
|
||||
@@ -49,9 +49,10 @@ public function mount(): void
|
||||
$this->ladeGespeicherte();
|
||||
}
|
||||
|
||||
/** Die Überschrift steht im gemeinsamen Objektkopf (filament.verwaltung.kopf), nicht doppelt im Seitenkopf. */
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return 'Größen';
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
@@ -78,6 +79,12 @@ public function geaendert(): bool
|
||||
return $aktuell !== $this->gespeichert();
|
||||
}
|
||||
|
||||
/** Eine Eingabe wurde geändert: ihre Fehlermeldung vom letzten Speichern entfällt. */
|
||||
public function updatedWerte(mixed $value, string $key): void
|
||||
{
|
||||
unset($this->fehler[$key]);
|
||||
}
|
||||
|
||||
public function speichern(): void
|
||||
{
|
||||
$this->fehler = DesignSettings::save($this->werte, auth()->user());
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Domain\Commerce\SalesTerms;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Verkaufsstart: Was ist bereit, was fehlt noch? Die Seite liest nur. Sie nennt die fehlenden Rechtstexte, den
|
||||
* Zustand der Zahlungseinrichtung und der Produktivfreigabe, ohne Schlüssel oder Werte zu zeigen. Die Produktivfreigabe
|
||||
* ist eine Entscheidung von Lars und wird nicht hier, sondern in der Umgebungsdatei des Servers gesetzt.
|
||||
*/
|
||||
class Verkaufsstart extends Page
|
||||
{
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Verkaufsstart';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
protected static ?string $slug = 'verkaufsstart';
|
||||
|
||||
protected static ?string $title = 'Verkaufsstart';
|
||||
|
||||
protected string $view = 'filament.pages.verkaufsstart';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable|null
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung.', 'zustand' => ['label' => Shop::invoice() ? 'Bereit' : '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],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
@@ -1046,18 +1047,20 @@ public function previewHtml(): string
|
||||
if ($this->previewSurface === 'bibliothek') {
|
||||
$title = trim($this->displayTitle) !== '' ? trim($this->displayTitle) : trim($this->workingTitle);
|
||||
|
||||
return view('member.partials.card', [
|
||||
'href' => '#vorschau',
|
||||
// Dieselbe Karte wie im Mitgliederbereich (<x-member.card>), ohne Verfügbarkeit: Die entscheidet die Lizenz.
|
||||
return Blade::render('<x-member.card :card="$card" />', [
|
||||
'card' => [
|
||||
'type' => $element->output_class === 'film' ? 'film' : 'material',
|
||||
'url' => '#vorschau',
|
||||
'title' => $title !== '' ? $title : $element->working_title,
|
||||
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
|
||||
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
|
||||
'coverage' => 'offen',
|
||||
'hide_status' => true,
|
||||
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
|
||||
'image_url' => ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path),
|
||||
'error' => 'Vorschau der Kartenform. Ob jemand sie öffnen darf, entscheidet die Lizenz.',
|
||||
],
|
||||
])->render();
|
||||
]);
|
||||
}
|
||||
|
||||
$subject = app(PublicMaterialReader::class)->subject($element->id, true, $draft);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Filament\Resources\DiscountCodes\Pages\ListDiscountCodes;
|
||||
use App\Filament\Resources\DiscountCodes\Pages\ViewDiscountCode;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Rabattcodes (FACH-14): anlegen, bearbeiten, zeitlich begrenzen, deaktivieren und einzelne Konten freischalten.
|
||||
* Die Seiten nutzen die gemeinsamen Bausteine (Bestandsliste, Objektseite, Dialoge) wie die übrigen Kataloglisten.
|
||||
*/
|
||||
class DiscountCodeResource extends Resource
|
||||
{
|
||||
protected static ?string $model = DiscountCode::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Rabattcodes';
|
||||
|
||||
protected static ?string $modelLabel = 'Rabattcode';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Rabattcodes';
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'code';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public static function getViewAuthorizationResponse(Model $record): Response
|
||||
{
|
||||
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table->columns([
|
||||
TextColumn::make('code')->label('Code')->searchable(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListDiscountCodes::route('/'),
|
||||
'view' => ViewDiscountCode::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||
use App\Filament\Support\DiscountCodeForm;
|
||||
use App\Filament\Support\ListsCatalog;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
class ListDiscountCodes extends ListRecords
|
||||
{
|
||||
use ListsCatalog;
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = DiscountCodeResource::class;
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Ein Code gilt für den ganzen Warenkorb oder nur für ausgewählte Ziele, und er ist allgemein einlösbar oder nur für freigeschaltete Konten. Beides stellst du unabhängig voneinander ein. Pro Bestellung gilt höchstens ein Code.';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('create')->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.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DiscountCodes\Pages;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountRelease;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
|
||||
use App\Filament\Support\DiscountCodeForm;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Rabattcode im gemeinsamen Rahmen. Bearbeiten nutzt dieselbe Maske wie Anlegen. Konten werden für genau diesen Code
|
||||
* freigeschaltet und die Freigabe wird mit Begründung entzogen; der Verlauf bleibt stehen.
|
||||
*/
|
||||
class ViewDiscountCode extends ViewRecord
|
||||
{
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = DiscountCodeResource::class;
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return (string) $this->getRecord()->code;
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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<string, mixed>
|
||||
*/
|
||||
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.',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -45,6 +46,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 +124,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 +215,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 +284,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 +308,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 => [
|
||||
@@ -400,6 +419,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 +429,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.'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders;
|
||||
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\Orders\Pages\ListOrders;
|
||||
use App\Filament\Resources\Orders\Pages\ViewOrder;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Bestellverwaltung (PAY-006): Bestellungen lesen, bei Kauf auf Rechnung den Zahlungseingang bestätigen und
|
||||
* bezahlte Bestellungen vollständig erstatten. Es gibt keine Bearbeitung der gespeicherten Konditionen.
|
||||
*/
|
||||
class OrderResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Order::class;
|
||||
|
||||
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
|
||||
|
||||
protected static ?string $navigationLabel = 'Bestellungen';
|
||||
|
||||
protected static ?string $modelLabel = 'Bestellung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Bestellungen';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function canViewAny(): bool
|
||||
{
|
||||
return ShopAccess::allowed();
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getViewAuthorizationResponse(Model $record): Response
|
||||
{
|
||||
return ShopAccess::allowed() ? Response::allow() : Response::deny();
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema;
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table->columns([
|
||||
TextColumn::make('id')->label('Bestellung'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListOrders::route('/'),
|
||||
'view' => ViewOrder::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders\Pages;
|
||||
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Filament\Resources\Orders\OrderResource;
|
||||
use App\Filament\Support\ListsCatalog;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
|
||||
class ListOrders extends ListRecords
|
||||
{
|
||||
use ListsCatalog;
|
||||
|
||||
protected static string $resource = OrderResource::class;
|
||||
|
||||
public function getSubheading(): string|Htmlable|null
|
||||
{
|
||||
return 'Bestellungen mit Lizenzinhaber, Zahlungsweg und Zahlbetrag. Bei Kauf auf Rechnung bestätigst du hier den Zahlungseingang; bezahlte Bestellungen erstattest du vollständig.';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
protected function catalogRows(): array
|
||||
{
|
||||
$rows = [];
|
||||
|
||||
foreach (Order::query()->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.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Orders\Pages;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Filament\Resources\Orders\OrderResource;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Enums\Width;
|
||||
use Illuminate\Contracts\Support\Htmlable;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Bestellung im gemeinsamen Rahmen. Die gespeicherten Konditionen sind unveränderlich; der Betreiber bestätigt bei
|
||||
* Kauf auf Rechnung den Zahlungseingang und erstattet bezahlte Bestellungen vollständig (Bundles als Einheit).
|
||||
*/
|
||||
class ViewOrder extends ViewRecord
|
||||
{
|
||||
use ReportsDomainRules;
|
||||
|
||||
protected static string $resource = OrderResource::class;
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return 'Bestellung '.$this->order()->id;
|
||||
}
|
||||
|
||||
public function getHeading(): string|Htmlable
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function getMaxContentWidth(): Width|string|null
|
||||
{
|
||||
return Width::Full;
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
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 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“.'),
|
||||
])
|
||||
->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());
|
||||
|
||||
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 stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
|
||||
])
|
||||
->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']);
|
||||
|
||||
return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.';
|
||||
}, 'Erstattet.');
|
||||
$this->order()->unsetRelations();
|
||||
$this->order()->refresh();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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.'],
|
||||
],
|
||||
],
|
||||
'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“.',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
|
||||
/**
|
||||
* Die eine Maske für Rabattcodes: Anlegen und Bearbeiten nutzen dieselben Felder (FACH-20). Geltungsbereich und
|
||||
* Einlösungsberechtigung sind zwei voneinander unabhängige Einstellungen.
|
||||
*/
|
||||
final class DiscountCodeForm
|
||||
{
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
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<string, mixed> $data
|
||||
* @return array{0: array<string, mixed>, 1: list<array{type: string, id: int}>}
|
||||
*/
|
||||
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<string, mixed>
|
||||
*/
|
||||
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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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)],
|
||||
],
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Wer Rabattcodes, Freigaben und Bestellungen verwalten darf: Katalogverwalter und Kundenbetreuung. Die
|
||||
* Berechtigung zum Verkaufen und Erstatten ist eine Betreiberaufgabe, nicht die der Redaktion.
|
||||
*/
|
||||
final class ShopAccess
|
||||
{
|
||||
public static function allowed(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung));
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
use Filament\Forms\Components\ToggleButtons;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
@@ -121,45 +122,92 @@ public static function slotBuilder(string $name = 'widget'): Builder
|
||||
->columnSpanFull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Erklärung als kleines (i) neben der Bezeichnung: erscheint beim Überfahren und beim Fokussieren.
|
||||
*/
|
||||
private static function withInfo(ToggleButtons|Select $component, ?string $help): ToggleButtons|Select
|
||||
{
|
||||
return filled($help)
|
||||
? $component->hintIcon('heroicon-m-information-circle', tooltip: $help)->hintColor('gray')
|
||||
: $component;
|
||||
}
|
||||
|
||||
public static function block(WidgetType $type): Block
|
||||
{
|
||||
$icons = $type->optionIcons();
|
||||
$display = [];
|
||||
|
||||
// Aufbau: Anordnung (Variante) und gemeinsame Höhe. Erklärungen stehen im (i) neben der Bezeichnung.
|
||||
$layout = [];
|
||||
if (count($type->variants()) > 1) {
|
||||
$display[] = ToggleButtons::make('variant')
|
||||
->label('Darstellung')
|
||||
$layout[] = self::withInfo(ToggleButtons::make('variant')
|
||||
->label('Anordnung')
|
||||
->options($type->variants())
|
||||
->icons($icons['variant'] ?? [])
|
||||
->default($type->defaultVariant())
|
||||
->inline()
|
||||
->required()
|
||||
->live();
|
||||
->live(), 'Wie Bild und Text zueinander stehen. Bei wenig Platz stellt sich jede Anordnung selbständig um; die gespeicherte Seite bleibt erhalten.');
|
||||
}
|
||||
|
||||
$settings = [];
|
||||
$options = $type->settingOptions();
|
||||
$labels = $type->settingLabels();
|
||||
foreach ($type->settingOptions() as $key => $options) {
|
||||
$hiddenWhen = $type->settingHiddenWhen();
|
||||
|
||||
$field = function (string $key) use ($options, $labels, $type, $icons, $hiddenWhen): Select|ToggleButtons {
|
||||
$help = $labels[$key][1] ?? null;
|
||||
// Gemeinsame Höhe (ADR-38): immer als sichtbare Auswahl mit Vorgabe, nie als freie Eingabe.
|
||||
$settings[] = $key === 'height'
|
||||
$component = $key === 'height'
|
||||
? ToggleButtons::make('height')
|
||||
->label('Höhe')
|
||||
->helperText('Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.')
|
||||
->options($options)
|
||||
->options($options['height'])
|
||||
->icons($icons['height'] ?? [])
|
||||
->default($type->defaultHeight())
|
||||
->inline()
|
||||
->live()
|
||||
: Select::make($key)
|
||||
->label($labels[$key][0] ?? Str::headline($key))
|
||||
->helperText($labels[$key][1] ?? null)
|
||||
->placeholder('Vorgabe der Darstellung')
|
||||
->options($options)
|
||||
->options($options[$key])
|
||||
->live();
|
||||
|
||||
if ($key === 'height') {
|
||||
$help = 'Gestaltungsparameter, keine Begrenzung: Längere Inhalte erhalten immer den nötigen Platz.';
|
||||
}
|
||||
|
||||
if (isset($hiddenWhen[$key])) {
|
||||
[$controller, $value] = $hiddenWhen[$key];
|
||||
// Ausgeblendete Werte bleiben gespeichert, damit ein späteres Einblenden nichts zurücksetzt.
|
||||
$component->hidden(fn (Get $get): bool => ($get($controller) ?? null) === $value)->dehydratedWhenHidden();
|
||||
}
|
||||
|
||||
return self::withInfo($component, $help);
|
||||
};
|
||||
|
||||
if (isset($options['height'])) {
|
||||
$layout[] = Group::make([$field('height')])->statePath('settings');
|
||||
}
|
||||
|
||||
if ($settings !== []) {
|
||||
$display[] = Grid::make(['default' => 1, 'md' => 2])->schema($settings)->statePath('settings');
|
||||
if ($layout !== []) {
|
||||
$display[] = Section::make('Aufbau')->compact()->schema($layout);
|
||||
}
|
||||
|
||||
$grouped = [];
|
||||
foreach ($type->settingGroups() as $title => $keys) {
|
||||
$keys = array_values(array_filter($keys, fn (string $key): bool => isset($options[$key]) && $key !== 'height'));
|
||||
$grouped = [...$grouped, ...$keys];
|
||||
if ($keys !== []) {
|
||||
$display[] = Section::make($title)->compact()->schema([
|
||||
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $keys))->statePath('settings'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$rest = array_values(array_filter(array_keys($options), fn (string $key): bool => $key !== 'height' && ! in_array($key, $grouped, true)));
|
||||
if ($rest !== []) {
|
||||
$display[] = Section::make($grouped === [] && $layout === [] ? 'Einstellungen' : 'Weitere Einstellungen')->compact()->schema([
|
||||
Grid::make(['default' => 1, 'md' => 2])->schema(array_map($field, $rest))->statePath('settings'),
|
||||
]);
|
||||
}
|
||||
|
||||
$variantField = count($type->variants()) > 1 ? [] : [Hidden::make('variant')->default($type->defaultVariant())];
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,12 @@
|
||||
use App\Domain\Commerce\Checkout;
|
||||
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;
|
||||
@@ -39,7 +41,7 @@ public function claim(Request $request, Offer $offer, GrantIssuer $issuer): Redi
|
||||
return back()->withErrors(['offer' => $exception->getMessage()]);
|
||||
}
|
||||
|
||||
return redirect()->route('member.library')->with('status', 'Das Angebot liegt in Ihrer Bibliothek.');
|
||||
return redirect()->route('member.library')->with('status', 'Das Angebot liegt in deiner Bibliothek.');
|
||||
}
|
||||
|
||||
public function place(Request $request, Offer $offer, Checkout $checkout): RedirectResponse
|
||||
@@ -67,9 +69,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 +109,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 +143,25 @@ 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(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** 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 +206,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');
|
||||
|
||||
@@ -21,8 +21,10 @@
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\CourseOutline;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Http\MemberLicenses;
|
||||
use App\Http\SignedLink;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Collection;
|
||||
@@ -32,12 +34,28 @@
|
||||
|
||||
class LibraryController extends Controller
|
||||
{
|
||||
/** Inhaltsarten der Bibliothek (Schlüssel der Adresse und des Filters). */
|
||||
public const TYPES = [
|
||||
'programm' => 'Programme',
|
||||
'modul' => 'Module',
|
||||
'film' => 'Filme',
|
||||
'material' => 'Materialien',
|
||||
];
|
||||
|
||||
public function index(Request $request, ?string $sicht = null): View
|
||||
{
|
||||
$catalog = app(LibraryCatalog::class)->index($request->user());
|
||||
$untouched = $catalog['programs'] === [] && $catalog['modules'] === [] && $catalog['materials'] === [];
|
||||
$items = [...$catalog['programs'], ...$catalog['modules'], ...$catalog['materials']];
|
||||
$untouched = $items === [];
|
||||
$query = trim((string) $request->query('q', ''));
|
||||
$nutzung = (string) $request->query('nutzung', '');
|
||||
$sortierung = $request->query('sortierung') === 'titel' ? 'titel' : 'standard';
|
||||
$art = match ($sicht) {
|
||||
'programme' => 'programm',
|
||||
'module' => 'modul',
|
||||
default => (string) $request->query('art', ''),
|
||||
};
|
||||
$art = array_key_exists($art, self::TYPES) ? $art : '';
|
||||
$dimensionIds = array_values(array_filter(array_map(intval(...), (array) $request->query('dimension', []))));
|
||||
$saeuleIds = array_values(array_filter(array_map(intval(...), (array) $request->query('saeule', []))));
|
||||
$dimensions = app(IdentityDimension::class);
|
||||
@@ -52,94 +70,60 @@ public function index(Request $request, ?string $sicht = null): View
|
||||
|
||||
$dimensionIds = array_values($dimensionIds);
|
||||
$saeuleIds = array_values(array_unique($saeuleIds));
|
||||
$pillarOptions = $this->visiblePillars($catalog, $saeuleIds);
|
||||
$pillarOptions = $this->visiblePillars($items, $saeuleIds);
|
||||
|
||||
foreach (['programs', 'modules'] as $shelf) {
|
||||
if ($query !== '') {
|
||||
$catalog[$shelf] = array_values(array_filter(
|
||||
$catalog[$shelf],
|
||||
fn (array $card): bool => $this->matches($card, $query),
|
||||
));
|
||||
}
|
||||
if ($dimensionIds !== []) {
|
||||
$catalog[$shelf] = array_values(array_filter(
|
||||
$catalog[$shelf],
|
||||
fn (array $card): bool => $dimensions->matches($card['composition'], $dimensionIds),
|
||||
));
|
||||
}
|
||||
if ($saeuleIds !== []) {
|
||||
$catalog[$shelf] = array_values(array_filter(
|
||||
$catalog[$shelf],
|
||||
fn (array $card): bool => $this->hasPillar($card['composition'], $saeuleIds),
|
||||
));
|
||||
}
|
||||
if (in_array($nutzung, ['nutzbar', 'teilweise', 'nicht enthalten'], true)) {
|
||||
$catalog[$shelf] = array_values(array_filter(
|
||||
$catalog[$shelf],
|
||||
fn (array $card): bool => ($card['coverage'] ?? '') === $nutzung,
|
||||
));
|
||||
// Gemeinsame Filter für alle Inhaltsarten. Die Zahl je Art zeigt, was die übrigen Filter übrig lassen.
|
||||
$matching = array_values(array_filter($items, function (array $card) use ($query, $nutzung, $dimensionIds, $saeuleIds, $dimensions): bool {
|
||||
return ($query === '' || $this->matches($card, $query))
|
||||
&& ($dimensionIds === [] || $dimensions->matches($card['subject'], $dimensionIds))
|
||||
&& ($saeuleIds === [] || $this->hasPillar($card['subject'], $saeuleIds))
|
||||
&& (! in_array($nutzung, ['nutzbar', 'teilweise', 'nicht enthalten'], true) || ($card['coverage'] ?? '') === $nutzung);
|
||||
}));
|
||||
$counts = array_fill_keys(array_keys(self::TYPES), 0);
|
||||
|
||||
foreach ($matching as $card) {
|
||||
$counts[$card['type']]++;
|
||||
}
|
||||
|
||||
$shown = $art === '' ? $matching : array_values(array_filter($matching, fn (array $card): bool => $card['type'] === $art));
|
||||
|
||||
if ($sortierung === 'titel') {
|
||||
usort($shown, fn (array $left, array $right): int => strcoll(mb_strtolower($left['title']), mb_strtolower($right['title'])));
|
||||
}
|
||||
|
||||
$shelves = [];
|
||||
|
||||
foreach (self::TYPES as $type => $label) {
|
||||
$cards = array_values(array_filter($shown, fn (array $card): bool => $card['type'] === $type));
|
||||
|
||||
if ($cards !== []) {
|
||||
$shelves[$type] = ['label' => $label, 'cards' => $cards];
|
||||
}
|
||||
}
|
||||
|
||||
if ($query !== '') {
|
||||
$catalog['materials'] = array_values(array_filter(
|
||||
$catalog['materials'],
|
||||
fn (array $card): bool => $this->matches($card, $query),
|
||||
));
|
||||
}
|
||||
|
||||
if ($dimensionIds !== []) {
|
||||
$catalog['materials'] = array_values(array_filter(
|
||||
$catalog['materials'],
|
||||
function (array $card) use ($dimensions, $dimensionIds): bool {
|
||||
$release = $card['article']->currentRelease;
|
||||
$subject = $release?->rootCompositionVersion?->composition
|
||||
?? $release?->rootElementVersion?->element
|
||||
?? $card['article'];
|
||||
|
||||
return $dimensions->matches($subject, $dimensionIds);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
if ($saeuleIds !== []) {
|
||||
$catalog['materials'] = array_values(array_filter(
|
||||
$catalog['materials'],
|
||||
fn (array $card): bool => $this->hasPillar($this->materialSubject($card), $saeuleIds),
|
||||
));
|
||||
}
|
||||
|
||||
if ($nutzung === 'teilweise' || $nutzung === 'nicht enthalten') {
|
||||
$catalog['materials'] = [];
|
||||
}
|
||||
$filterActive = $query !== '' || $nutzung !== '' || $dimensionIds !== [] || $saeuleIds !== [] || $art !== '';
|
||||
|
||||
return view('member.library', [
|
||||
...$catalog,
|
||||
'shelves' => $shelves,
|
||||
'total' => count($shown),
|
||||
'counts' => $counts,
|
||||
'allCount' => count($matching),
|
||||
'art' => $art,
|
||||
'types' => self::TYPES,
|
||||
'query' => $query,
|
||||
'sicht' => $sicht,
|
||||
'nutzung' => $nutzung,
|
||||
'sortierung' => $sortierung,
|
||||
'dimensionIds' => $dimensionIds,
|
||||
'saeuleIds' => $saeuleIds,
|
||||
'filterPillars' => $pillarOptions,
|
||||
'filterDimensions' => app(EditorialVocabulary::class)->memberFilterDimensions(array_map(intval(...), $dimensionIds)),
|
||||
'libraryEmpty' => $untouched,
|
||||
'filterActive' => $filterActive,
|
||||
'filterCount' => count($dimensionIds) + count($saeuleIds) + ($nutzung !== '' ? 1 : 0),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subjekt eines Materialkarte: Programm oder Modul, Medium oder der Artikel selbst.
|
||||
*
|
||||
* @param array<string, mixed> $card
|
||||
*/
|
||||
private function materialSubject(array $card): Model
|
||||
{
|
||||
$release = $card['article']->currentRelease;
|
||||
|
||||
return $release?->rootCompositionVersion?->composition
|
||||
?? $release?->rootElementVersion?->element
|
||||
?? $card['article'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Direkte Säulenzuordnung des Objekts selbst; die Säulen enthaltener Medien zählen hier nicht.
|
||||
*
|
||||
@@ -154,22 +138,16 @@ private function hasPillar(Model $subject, array $pillarIds): bool
|
||||
* Säulen für den Filter: nur solche, die ein sichtbares Objekt der Bibliothek tatsächlich trägt, und eine bereits
|
||||
* gewählte. So erscheinen neue oder interne Säulen ohne Zuordnung nicht in der Bibliothek.
|
||||
*
|
||||
* @param array<string, mixed> $catalog
|
||||
* @param list<array<string, mixed>> $items
|
||||
* @param list<int> $selected
|
||||
* @return Collection<int, Pillar>
|
||||
*/
|
||||
private function visiblePillars(array $catalog, array $selected)
|
||||
private function visiblePillars(array $items, array $selected)
|
||||
{
|
||||
$used = [];
|
||||
|
||||
foreach (array_merge($catalog['programs'], $catalog['modules']) as $card) {
|
||||
foreach ($card['composition']->pillars()->pluck('pillars.id') as $id) {
|
||||
$used[(int) $id] = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($catalog['materials'] as $card) {
|
||||
foreach ($this->materialSubject($card)->pillars()->pluck('pillars.id') as $id) {
|
||||
foreach ($items as $card) {
|
||||
foreach ($card['subject']->pillars()->pluck('pillars.id') as $id) {
|
||||
$used[(int) $id] = true;
|
||||
}
|
||||
}
|
||||
@@ -193,20 +171,55 @@ public function program(Request $request, Composition $composition): View
|
||||
return view('member.program', app(LibraryCatalog::class)->program($request->user(), $composition));
|
||||
}
|
||||
|
||||
public function materials(Request $request): View
|
||||
/**
|
||||
* Film oder Material im Zusammenhang seines Programms oder Moduls. Die Seite zeigt nur Stellen, die in der
|
||||
* angezeigten Fassung des Programms stehen; die Wiedergabe- und Downloadadressen kommen aus DecideAccess.
|
||||
*/
|
||||
public function content(Request $request, Composition $composition, int $version): View|Response
|
||||
{
|
||||
return view('member.materials', [
|
||||
'grants' => $this->grantQuery($request)->with('article.currentRelease.contents.elementVersion.element')->get(),
|
||||
]);
|
||||
$data = app(LibraryCatalog::class)->content($request->user(), $composition, $version);
|
||||
abort_if($data === null, 404);
|
||||
|
||||
return response()->view('member.content', $data, $data['allowed'] ? 200 : 403);
|
||||
}
|
||||
|
||||
/** Die frühere Seite „Materialien“ ist ein Filter der Bibliothek (eine Navigation statt zwei). */
|
||||
public function materials(): RedirectResponse
|
||||
{
|
||||
return redirect()->route('member.library', ['art' => 'material']);
|
||||
}
|
||||
|
||||
public function grants(Request $request): View
|
||||
{
|
||||
$entries = app(MemberLicenses::class)->overview($request->user());
|
||||
$filter = in_array($request->query('status'), ['aktiv', 'inaktiv'], true) ? (string) $request->query('status') : 'alle';
|
||||
|
||||
return view('member.grants', [
|
||||
'grants' => $this->grantQuery($request)->get(),
|
||||
'entries' => match ($filter) {
|
||||
'aktiv' => $entries->where('active', true)->values(),
|
||||
'inaktiv' => $entries->where('active', false)->values(),
|
||||
default => $entries,
|
||||
},
|
||||
'filter' => $filter,
|
||||
'counts' => [
|
||||
'aktiv' => $entries->where('active', true)->count(),
|
||||
'inaktiv' => $entries->where('active', false)->count(),
|
||||
'alle' => $entries->count(),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/** Eine einzelne Berechtigung. Nur eigene (oder die der eigenen Organisation mit Bestellrecht); sonst nicht gefunden. */
|
||||
public function grant(Request $request, Grant $grant): View
|
||||
{
|
||||
abort_unless(
|
||||
Grant::query()->usableBy($request->user())->whereKey($grant->id)->exists(),
|
||||
404,
|
||||
);
|
||||
|
||||
return view('member.grant', app(MemberLicenses::class)->detail($request->user(), $grant));
|
||||
}
|
||||
|
||||
public function show(Request $request, LicenseArticle $article): View
|
||||
{
|
||||
$release = $article->currentRelease()->with('contents.elementVersion.element.pillars')->first();
|
||||
@@ -219,8 +232,11 @@ public function show(Request $request, LicenseArticle $article): View
|
||||
$metadata = is_array($version->metadata) ? $version->metadata : [];
|
||||
$action = $class === 'film' || $class === 'audio' ? 'streamen' : 'ansehen';
|
||||
$decision = app(DecideAccess::class)($request->user(), $article, $release, $version, $action);
|
||||
$download = app(DecideAccess::class)($request->user(), $article, $release, $version, 'laden');
|
||||
$file = $metadata['file'] ?? null;
|
||||
$entries[] = [
|
||||
'title' => app(LibraryCatalog::class)->text($version->element)['title'],
|
||||
'class' => $class,
|
||||
'content' => $content,
|
||||
'version' => $version,
|
||||
'role' => $content->role,
|
||||
@@ -232,6 +248,15 @@ public function show(Request $request, LicenseArticle $article): View
|
||||
: null,
|
||||
'playable' => $decision->allowed && is_string($file) && $file !== '' && ($class === 'film' || $class === 'audio'),
|
||||
'playback' => app(FilmPlayback::class)->mode($version->id),
|
||||
'download_url' => $download->allowed
|
||||
? SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||
'article' => $article->id,
|
||||
'release' => $release->id,
|
||||
'version' => $version->id,
|
||||
'action' => 'laden',
|
||||
'reader' => $request->user()->id,
|
||||
])
|
||||
: null,
|
||||
'pillars' => $version->element->pillars->pluck('name')->all(),
|
||||
'url' => $decision->allowed
|
||||
? SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||
@@ -352,7 +377,7 @@ public function thumbnail(Request $request, string $kind, int $subject): Streame
|
||||
*/
|
||||
private function matches(array $card, string $query): bool
|
||||
{
|
||||
$haystack = mb_strtolower(($card['title'] ?? '').' '.($card['summary'] ?? ''));
|
||||
$haystack = mb_strtolower(($card['title'] ?? '').' '.($card['summary'] ?? '').' '.($card['subject']->search_terms ?? ''));
|
||||
|
||||
return str_contains($haystack, mb_strtolower($query));
|
||||
}
|
||||
@@ -424,10 +449,34 @@ private function fileResponse(
|
||||
'k0',
|
||||
);
|
||||
|
||||
return $disk->response($file, basename($file), [
|
||||
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
|
||||
'X-License-Copy' => $delivery->copy_id,
|
||||
]);
|
||||
// Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“); Laravel setzt Content-Disposition mit
|
||||
// ASCII-Rückfall und UTF-8-Name.
|
||||
return $disk->response(
|
||||
$file,
|
||||
$this->downloadName($version, $file),
|
||||
['X-License-Copy' => $delivery->copy_id],
|
||||
$action === 'laden' ? 'attachment' : 'inline',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dateiname für Ansicht und Download: Anzeigetitel des Mediums (Mitgliedertext, sonst Arbeitstitel) mit der
|
||||
* Endung der gespeicherten Datei. Zeichen, die in Dateinamen nicht erlaubt sind, entfallen.
|
||||
*/
|
||||
private function downloadName(ContentElementVersion $version, string $file): string
|
||||
{
|
||||
$element = $version->element;
|
||||
$title = $element === null ? '' : app(LibraryCatalog::class)->text($element)['title'];
|
||||
$title = (string) preg_replace('/[\x00-\x1F\x7F\/\\\\:*?"<>|]+/u', ' ', $title);
|
||||
$title = trim((string) preg_replace('/\s+/u', ' ', $title));
|
||||
$title = rtrim(mb_substr($title, 0, 120), '. ');
|
||||
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
|
||||
|
||||
if ($title === '') {
|
||||
return basename($file);
|
||||
}
|
||||
|
||||
return $extension === '' ? $title : $title.'.'.$extension;
|
||||
}
|
||||
|
||||
private function renditionBelongsTo(int $versionId, string $path): bool
|
||||
|
||||
@@ -2,10 +2,9 @@
|
||||
|
||||
namespace App\Http\Controllers\Member;
|
||||
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\LibraryCatalog;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use App\Http\MemberLicenses;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
@@ -14,35 +13,17 @@ class MemberController extends Controller
|
||||
public function dashboard(Request $request): View
|
||||
{
|
||||
$catalog = app(LibraryCatalog::class)->index($request->user());
|
||||
$films = array_filter($catalog['materials'], fn (array $card): bool => $card['type'] === 'film');
|
||||
|
||||
return view('member.dashboard', [
|
||||
'programCount' => count($catalog['programs']),
|
||||
'moduleCount' => count($catalog['modules']),
|
||||
'materialCount' => count($catalog['materials']),
|
||||
'programs' => array_slice($catalog['programs'], 0, 4),
|
||||
'counts' => [
|
||||
'programm' => count($catalog['programs']),
|
||||
'modul' => count($catalog['modules']),
|
||||
'film' => count($films),
|
||||
'material' => count($catalog['materials']) - count($films),
|
||||
],
|
||||
'licenseCount' => app(MemberLicenses::class)->overview($request->user())->where('active', true)->count(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function profile(): View
|
||||
{
|
||||
return view('member.profile');
|
||||
}
|
||||
|
||||
public function updateProfile(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validate([
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
]);
|
||||
|
||||
$user->name = $data['name'];
|
||||
$user->save();
|
||||
|
||||
$user->party?->update(['display_name' => $data['name']]);
|
||||
$user->party?->profile?->update(['display_name' => $data['name']]);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Member;
|
||||
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\BillingAddress;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Notifications\ConfirmNewEmailAddress;
|
||||
use App\Notifications\EmailChangeRequested;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
* Mitgliederprofil: Name, E-Mail-Adresse, Passwort und Rechnungsadresse. Jeder Block hat seine eigene Speicherhandlung
|
||||
* und seine eigenen Fehlermeldungen; nichts wird verdeckt mitgespeichert. Sicherheitsrelevante Änderungen (Adresse,
|
||||
* Passwort) verlangen das aktuelle Passwort.
|
||||
*/
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
public function show(Request $request): View
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return view('member.profile', [
|
||||
'address' => $user->party?->billingAddress,
|
||||
'countries' => BillingAddress::COUNTRIES,
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateName(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('name', [
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
]);
|
||||
|
||||
$user->name = $data['name'];
|
||||
$user->save();
|
||||
|
||||
$user->party?->update(['display_name' => $data['name']]);
|
||||
$user->party?->profile?->update(['display_name' => $data['name']]);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Die neue Adresse gilt erst nach Bestätigung über einen Link an sie. Bis dahin bleibt die bisherige Adresse
|
||||
* in Kraft und erhält einen Hinweis.
|
||||
*/
|
||||
public function requestEmail(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('email', [
|
||||
'email' => ['required', 'string', 'email:rfc', 'max:255', Rule::unique('users', 'email')],
|
||||
'current_password' => ['required', 'current_password'],
|
||||
], [
|
||||
'email.unique' => 'Diese Adresse ist bereits vergeben.',
|
||||
'current_password.current_password' => 'Das Passwort stimmt nicht.',
|
||||
]);
|
||||
|
||||
$new = mb_strtolower(trim($data['email']));
|
||||
|
||||
if ($new === mb_strtolower($user->email)) {
|
||||
return back()->withErrors(['email' => 'Das ist bereits deine Adresse.'], 'email');
|
||||
}
|
||||
|
||||
$user->forceFill(['pending_email' => $new])->save();
|
||||
Notification::route('mail', $new)->notify(new ConfirmNewEmailAddress($user->id, $new));
|
||||
$user->notify(new EmailChangeRequested($new));
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Wir haben einen Bestätigungslink an '.$new.' geschickt. Die Adresse wechselt, sobald du ihn öffnest.');
|
||||
}
|
||||
|
||||
public function confirmEmail(Request $request, int $id, string $hash): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_unless($user->id === $id, 403);
|
||||
$pending = $user->pending_email;
|
||||
|
||||
if (! is_string($pending) || $pending === '' || ! hash_equals(sha1($pending), $hash)) {
|
||||
return redirect()->route('member.profile')->withErrors(['email' => 'Dieser Link gilt nicht mehr. Fordere die Änderung bitte erneut an.'], 'email');
|
||||
}
|
||||
|
||||
if (User::query()->where('email', $pending)->whereKeyNot($user->id)->exists()) {
|
||||
$user->forceFill(['pending_email' => null])->save();
|
||||
|
||||
return redirect()->route('member.profile')->withErrors(['email' => 'Diese Adresse ist inzwischen vergeben.'], 'email');
|
||||
}
|
||||
|
||||
$user->forceFill(['email' => $pending, 'pending_email' => null, 'email_verified_at' => now()])->save();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Deine E-Mail-Adresse ist geändert.');
|
||||
}
|
||||
|
||||
public function cancelEmail(Request $request): RedirectResponse
|
||||
{
|
||||
$request->user()->forceFill(['pending_email' => null])->save();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Die Änderung der E-Mail-Adresse ist verworfen.');
|
||||
}
|
||||
|
||||
public function updatePassword(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('password', [
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'password' => ['required', 'confirmed', Password::defaults(), 'different:current_password'],
|
||||
], [
|
||||
'current_password.current_password' => 'Das bisherige Passwort stimmt nicht.',
|
||||
'password.different' => 'Das neue Passwort muss sich vom bisherigen unterscheiden.',
|
||||
]);
|
||||
|
||||
$user->forceFill(['password' => Hash::make($data['password'])])->save();
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Dein Passwort ist geändert.');
|
||||
}
|
||||
|
||||
public function updateAddress(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv || $user->party === null, 403);
|
||||
|
||||
$data = $request->validateWithBag('address', [
|
||||
'recipient' => ['required', 'string', 'max:160'],
|
||||
'line2' => ['nullable', 'string', 'max:160'],
|
||||
'street' => ['required', 'string', 'max:160'],
|
||||
'postal_code' => ['required', 'string', 'max:16'],
|
||||
'city' => ['required', 'string', 'max:120'],
|
||||
'country' => ['required', Rule::in(array_keys(BillingAddress::COUNTRIES))],
|
||||
], [
|
||||
'recipient.required' => 'Bitte gib Name oder Firma an.',
|
||||
'street.required' => 'Bitte gib Straße und Hausnummer an.',
|
||||
'postal_code.required' => 'Bitte gib die Postleitzahl an.',
|
||||
'city.required' => 'Bitte gib den Ort an.',
|
||||
]);
|
||||
|
||||
BillingAddress::query()->updateOrCreate(['party_id' => $user->party_id], $data);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Die Rechnungsadresse ist gespeichert.');
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,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]);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\ReleaseStatus;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
@@ -18,24 +19,48 @@
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Filament\Support\EditorialCatalog;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Liest die Mitgliederbibliothek aus den vorhandenen Fachobjekten (Kompositionen, Medien, Artikelstände, Berechtigungen).
|
||||
* Sie hält keine eigenen Daten. Jede Zugriffsfrage entscheidet DecideAccess; die Oberfläche zeigt nur das Ergebnis.
|
||||
*
|
||||
* Einmalaufbau: Der Strukturbaum einer Komposition wird je Anfrage nur einmal gebaut und für Verfügbarkeit,
|
||||
* Zählungen und die programmübergreifende Medienliste gemeinsam genutzt.
|
||||
*/
|
||||
class LibraryCatalog
|
||||
{
|
||||
/** @var array<string, list<array<string, mixed>>> */
|
||||
private array $trees = [];
|
||||
|
||||
/** @var array<string, array{title: string, summary: ?string, description: ?string}> */
|
||||
private array $texts = [];
|
||||
|
||||
/** @var array<int, ?ContentElement> */
|
||||
private array $elements = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly CompositionDisplayRelease $display,
|
||||
private readonly CompositionStructureReader $structure,
|
||||
private readonly DecideAccess $access,
|
||||
private readonly EditorialProfileReader $profiles,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Programme, Module und einzelne Medien (Filme und Materialien) der Berechtigungen des Kontos.
|
||||
*
|
||||
* Einzelne Medien erscheinen genau einmal je stabiler Medienidentität (Inhaltselement), gleich in wie vielen Programmen
|
||||
* oder Modulen sie vorkommen. „used_in“ nennt diese Verwendungen. Innerhalb eines Programms bleibt jede Einbindung an
|
||||
* ihrer Stelle erhalten (program()). Gleiche Titel verschiedener Elemente bleiben getrennt.
|
||||
*
|
||||
* @return array{programs: list<array<string, mixed>>, modules: list<array<string, mixed>>, materials: list<array<string, mixed>>}
|
||||
*/
|
||||
public function index(User $user): array
|
||||
{
|
||||
$programs = [];
|
||||
$modules = [];
|
||||
$materials = [];
|
||||
$media = [];
|
||||
|
||||
foreach ($this->grants($user) as $grant) {
|
||||
$article = $grant->article;
|
||||
@@ -44,124 +69,365 @@ public function index(User $user): array
|
||||
$version = $release?->rootCompositionVersion;
|
||||
|
||||
if ($composition !== null && $version !== null && $this->display->isReleased($version)) {
|
||||
$shown = $this->display->highestReleasedVersion($composition);
|
||||
$nodes = $shown === null ? [] : $this->tree($user, $shown, false, $composition->id);
|
||||
$picture = app(EditorialCatalog::class)->visiblePicture($composition, $version);
|
||||
$text = $this->text($composition);
|
||||
$card = [
|
||||
'type' => $composition->editorialContentKind?->slug === 'modul' ? 'modul' : 'programm',
|
||||
'composition' => $composition,
|
||||
'subject' => $composition,
|
||||
'version' => $version,
|
||||
'title' => filled($composition->display_title) ? $composition->display_title : $composition->designation,
|
||||
'summary' => $composition->summary,
|
||||
'title' => $text['title'],
|
||||
'summary' => $text['summary'],
|
||||
'kind' => $composition->editorialContentKind?->label
|
||||
?? ($composition->kind?->label()),
|
||||
'coverage' => $this->coverageLabel($user, $composition),
|
||||
'coverage' => $this->coverage($nodes),
|
||||
'module_count' => $this->countCompositions($nodes),
|
||||
'duration_minutes' => $shown?->duration_minutes,
|
||||
'image' => $picture['alt'] ?? null,
|
||||
'image_url' => $picture === null ? null : route('member.thumbnail', [
|
||||
'kind' => $picture['kind'],
|
||||
'subject' => $picture['subject'],
|
||||
]),
|
||||
'url' => route('member.program', $composition),
|
||||
];
|
||||
$shelf = $composition->editorialContentKind?->slug === 'modul' ? 'modules' : 'programs';
|
||||
if ($shelf === 'modules') {
|
||||
|
||||
if ($card['type'] === 'modul') {
|
||||
$modules[$composition->id] = $card;
|
||||
} else {
|
||||
$programs[$composition->id] = $card;
|
||||
}
|
||||
|
||||
$this->collect($media, $nodes, [['title' => $text['title'], 'url' => $card['url'], 'id' => $composition->id]], $composition);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$element = $release?->rootElementVersion?->element;
|
||||
$elementId = $element?->id;
|
||||
$key = $composition !== null
|
||||
? 'komposition-'.$composition->id
|
||||
: ($elementId !== null ? 'element-'.$elementId : 'artikel-'.$article->id);
|
||||
: ($element?->id !== null ? 'element-'.$element->id : 'artikel-'.$article->id);
|
||||
$subject = $element ?? $composition ?? $article;
|
||||
$text = $element !== null ? $this->text($element) : null;
|
||||
$imageUrl = $element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
|
||||
$materials[$key] = [
|
||||
'article' => $article,
|
||||
'title' => app(CourseOutline::class)->title($article),
|
||||
'summary' => $element?->summary ?? $composition?->summary,
|
||||
'kind' => app(CourseOutline::class)->kindLabel($article),
|
||||
'coverage' => 'nutzbar',
|
||||
'image' => $imageUrl === null ? null : ($element->thumbnail_alt ?: $element->working_title),
|
||||
'image_url' => $imageUrl,
|
||||
$media[$key] = ($media[$key] ?? []) + [
|
||||
'used_in' => [],
|
||||
'versions' => [],
|
||||
'context' => null,
|
||||
];
|
||||
$media[$key] = [
|
||||
...$media[$key],
|
||||
'key' => $key,
|
||||
'type' => $element?->output_class === 'film' ? 'film' : 'material',
|
||||
'article' => $article,
|
||||
'subject' => $subject,
|
||||
'title' => $text['title'] ?? app(CourseOutline::class)->title($article),
|
||||
'summary' => $text['summary'] ?? $element?->summary ?? $composition?->summary,
|
||||
'kind' => app(CourseOutline::class)->kindLabel($article) ?? ($element === null ? null : $this->outputLabel($element->output_class)),
|
||||
'coverage' => 'nutzbar',
|
||||
'image' => $imageUrl === null ? null : ($element->thumbnail_alt ?: ($text['title'] ?? $element->working_title)),
|
||||
'image_url' => $imageUrl,
|
||||
'url' => route('member.article', $article),
|
||||
];
|
||||
}
|
||||
|
||||
foreach ($media as $key => $item) {
|
||||
if (! isset($item['url'])) {
|
||||
$media[$key]['url'] = route('member.content', [
|
||||
'composition' => $item['context']['composition']->id,
|
||||
'version' => $item['context']['version_id'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'programs' => array_values($programs),
|
||||
'modules' => array_values($modules),
|
||||
'materials' => array_values($materials),
|
||||
'materials' => array_values($media),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{composition: Composition, title: string, kind: ?string, nodes: list<array<string, mixed>>}
|
||||
* Programm- oder Moduldetail: gesamte Struktur mit allen Einbindungen an ihrer Stelle.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function program(User $user, Composition $composition): array
|
||||
{
|
||||
$version = $this->display->highestReleasedVersion($composition);
|
||||
abort_if($version === null, 404);
|
||||
|
||||
$nodes = array_map(
|
||||
fn (StructureNode $node): array => $this->present($user, $node),
|
||||
$this->structure->tree($version),
|
||||
);
|
||||
$nodes = $this->tree($user, $version, true, $composition->id);
|
||||
$leaves = $this->leaves($nodes);
|
||||
$open = count(array_filter($leaves, fn (array $leaf): bool => $leaf['view_url'] !== null));
|
||||
$text = $this->text($composition);
|
||||
|
||||
return [
|
||||
'composition' => $composition,
|
||||
'picture' => app(EditorialCatalog::class)->visiblePicture($composition, $version),
|
||||
'title' => filled($composition->display_title) ? $composition->display_title : $composition->designation,
|
||||
'summary' => $composition->summary,
|
||||
'title' => $text['title'],
|
||||
'summary' => $text['summary'],
|
||||
'description' => $text['description'],
|
||||
'kind' => $composition->editorialContentKind?->label
|
||||
?? ($composition->kind?->label()),
|
||||
'is_module' => $composition->editorialContentKind?->slug === 'modul',
|
||||
'learning_goal' => $version->learning_goal,
|
||||
'duration_minutes' => $version->duration_minutes,
|
||||
'material_note' => $version->material_note,
|
||||
'coverage' => $leaves === [] ? 'nicht enthalten' : ($open === count($leaves) ? 'nutzbar' : ($open === 0 ? 'nicht enthalten' : 'teilweise')),
|
||||
'coverage' => $this->coverage($nodes),
|
||||
'module_count' => $this->countCompositions($nodes),
|
||||
'film_count' => count(array_filter($leaves, fn (array $leaf): bool => $leaf['output_class'] === 'film')),
|
||||
'material_count' => count(array_filter($leaves, fn (array $leaf): bool => $leaf['element_id'] !== null && $leaf['output_class'] !== 'film')),
|
||||
'open_count' => count(array_filter($leaves, fn (array $leaf): bool => $leaf['view_url'] !== null)),
|
||||
'leaf_count' => count($leaves),
|
||||
'nodes' => $nodes,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Filmstelle oder ein Material im Zusammenhang seines Programms oder Moduls.
|
||||
* Gesucht wird die Einbindung in der angezeigten Fassung; was dort nicht steht, gibt es hier nicht.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function content(User $user, Composition $composition, int $elementVersionId): ?array
|
||||
{
|
||||
$version = $this->display->highestReleasedVersion($composition);
|
||||
|
||||
if ($version === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nodes = $this->tree($user, $version, true, $composition->id);
|
||||
$found = $this->locate($nodes, $elementVersionId, []);
|
||||
|
||||
if ($found === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$node = $found['node'];
|
||||
$element = $node['element_id'] === null ? null : $this->element($node['element_id']);
|
||||
$text = $element === null ? ['title' => $node['title'], 'summary' => null, 'description' => null] : $this->text($element);
|
||||
$rootText = $this->text($composition);
|
||||
$trail = [['label' => $rootText['title'], 'url' => route('member.program', $composition)]];
|
||||
|
||||
foreach ($found['parents'] as $parent) {
|
||||
if ($parent['program_url'] !== null && $parent['composition_id'] !== $composition->id) {
|
||||
$trail[] = ['label' => $parent['title'], 'url' => $parent['program_url']];
|
||||
}
|
||||
}
|
||||
|
||||
$companions = array_values(array_filter(
|
||||
$found['siblings'],
|
||||
fn (array $sibling): bool => $sibling['children'] === []
|
||||
&& $sibling['element_id'] !== null
|
||||
&& $sibling['version_id'] !== $elementVersionId,
|
||||
));
|
||||
|
||||
return [
|
||||
'composition' => $composition,
|
||||
'program_title' => $rootText['title'],
|
||||
'node' => $node,
|
||||
'element' => $element,
|
||||
'title' => $text['title'],
|
||||
'summary' => $text['summary'],
|
||||
'description' => $text['description'],
|
||||
'trail' => $trail,
|
||||
'back' => $trail[array_key_last($trail)],
|
||||
'companions' => $companions,
|
||||
'allowed' => $node['view_url'] !== null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Anzeigetitel und -texte für die Mitgliederbibliothek: Abweichung für „Mitgliederbibliothek“, sonst die zentrale Angabe,
|
||||
* zuletzt die interne Bezeichnung. Nichts wird kopiert oder ergänzt.
|
||||
*
|
||||
* @return array{title: string, summary: ?string, description: ?string}
|
||||
*/
|
||||
public function text(Model $subject): array
|
||||
{
|
||||
$key = $subject->getMorphClass().':'.$subject->getKey();
|
||||
|
||||
if (isset($this->texts[$key])) {
|
||||
return $this->texts[$key];
|
||||
}
|
||||
|
||||
$profile = $this->profiles->read($subject, 'bibliothek');
|
||||
|
||||
return $this->texts[$key] = [
|
||||
'title' => $profile->value('display_title') ?? $profile->workingTitle ?? '',
|
||||
'summary' => $profile->value('summary') ?? $profile->value('teaser'),
|
||||
'description' => $profile->value('description'),
|
||||
];
|
||||
}
|
||||
|
||||
public function outputLabel(?string $outputClass): ?string
|
||||
{
|
||||
return match ($outputClass) {
|
||||
'film' => 'Film',
|
||||
'audio' => 'Hörstück',
|
||||
'document', 'pdf' => 'Dokument',
|
||||
'text' => 'Text',
|
||||
'bild' => 'Bild',
|
||||
null => null,
|
||||
default => $outputClass,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $nodes
|
||||
* @param list<array{title: string, url: string, id: int}> $contexts
|
||||
* @param array<string, array<string, mixed>> $media
|
||||
*/
|
||||
private function collect(array &$media, array $nodes, array $contexts, Composition $root): void
|
||||
{
|
||||
foreach ($nodes as $node) {
|
||||
if ($node['children'] !== []) {
|
||||
$nested = $contexts;
|
||||
|
||||
if ($node['composition_id'] !== null && $node['program_url'] !== null && $node['composition_id'] !== $root->id) {
|
||||
$nested[] = ['title' => $node['title'], 'url' => $node['program_url'], 'id' => $node['composition_id']];
|
||||
}
|
||||
|
||||
$this->collect($media, $node['children'], $nested, $root);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($node['element_id'] === null || $node['view_url'] === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$key = 'element-'.$node['element_id'];
|
||||
$element = $this->element($node['element_id']);
|
||||
|
||||
if ($element === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = $this->text($element);
|
||||
$item = $media[$key] ?? [
|
||||
'key' => $key,
|
||||
'type' => $node['output_class'] === 'film' ? 'film' : 'material',
|
||||
'article' => null,
|
||||
'subject' => $element,
|
||||
'title' => $text['title'],
|
||||
'summary' => $text['summary'],
|
||||
'kind' => $node['kind'] ?? $this->outputLabel($node['output_class']),
|
||||
'coverage' => 'nutzbar',
|
||||
'image' => $node['poster_url'] === null ? null : ($element->thumbnail_alt ?: $text['title']),
|
||||
'image_url' => $node['poster_url'],
|
||||
'used_in' => [],
|
||||
'versions' => [],
|
||||
'context' => null,
|
||||
];
|
||||
|
||||
foreach ($contexts as $context) {
|
||||
$item['used_in'][$context['id']] = ['title' => $context['title'], 'url' => $context['url']];
|
||||
}
|
||||
|
||||
$item['versions'][$node['version_id']] = true;
|
||||
$item['context'] ??= ['composition' => $root, 'version_id' => $node['version_id']];
|
||||
$media[$key] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private function tree(User $user, CompositionVersion $version, bool $full, int $rootId): array
|
||||
{
|
||||
$key = $version->id.':'.($full ? 'voll' : 'kurz').':'.$rootId;
|
||||
|
||||
return $this->trees[$key] ??= array_map(
|
||||
fn (StructureNode $node): array => $this->present($user, $node, $full, $rootId),
|
||||
$this->structure->tree($version),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function present(User $user, StructureNode $node): array
|
||||
private function present(User $user, StructureNode $node, bool $full, int $rootId): array
|
||||
{
|
||||
$view = null;
|
||||
$download = null;
|
||||
|
||||
$playback = 'file';
|
||||
|
||||
$poster = null;
|
||||
$element = $node->contentElementId === null ? null : $this->element($node->contentElementId);
|
||||
|
||||
if ($node->contentElementVersionId !== null) {
|
||||
$view = $this->open($user, $node->contentElementVersionId, $this->viewAction($node->outputClass));
|
||||
$download = $this->open($user, $node->contentElementVersionId, 'laden');
|
||||
$playback = app(FilmPlayback::class)->mode($node->contentElementVersionId);
|
||||
if ($view !== null && $node->contentElementId !== null) {
|
||||
$path = ContentElement::query()->whereKey($node->contentElementId)->value('thumbnail_path');
|
||||
$poster = ThumbnailRef::url('member.thumbnail', 'element', $node->contentElementId, $path);
|
||||
|
||||
if ($full) {
|
||||
$download = $this->open($user, $node->contentElementVersionId, 'laden');
|
||||
$playback = app(FilmPlayback::class)->mode($node->contentElementVersionId);
|
||||
}
|
||||
|
||||
if ($view !== null && $element !== null) {
|
||||
$poster = ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path);
|
||||
}
|
||||
}
|
||||
|
||||
$title = $node->title;
|
||||
|
||||
if ($element !== null) {
|
||||
$title = $this->text($element)['title'] ?: $title;
|
||||
} elseif ($node->compositionId !== null) {
|
||||
$nested = Composition::query()->find($node->compositionId);
|
||||
$title = $nested === null ? $title : ($this->text($nested)['title'] ?: $title);
|
||||
}
|
||||
|
||||
return [
|
||||
'role' => $node->role,
|
||||
'title' => $node->title,
|
||||
'kind' => $node->editorialKindLabel ?? $node->technicalKindLabel,
|
||||
'title' => $title,
|
||||
'summary' => $element === null ? null : $this->text($element)['summary'],
|
||||
'kind' => $node->editorialKindLabel ?? $this->outputLabel($node->technicalKindLabel) ?? $node->technicalKindLabel,
|
||||
'output_class' => $node->outputClass,
|
||||
'playback' => $playback,
|
||||
'view_url' => $view,
|
||||
'poster_url' => $poster,
|
||||
'download_url' => $download,
|
||||
'program_url' => $this->programUrl($node),
|
||||
'composition_id' => $node->compositionId,
|
||||
'element_id' => $node->contentElementId,
|
||||
'version_id' => $node->contentElementVersionId,
|
||||
'content_url' => $node->contentElementVersionId === null ? null : route('member.content', [
|
||||
'composition' => $rootId,
|
||||
'version' => $node->contentElementVersionId,
|
||||
]),
|
||||
'children' => array_map(
|
||||
fn (StructureNode $child): array => $this->present($user, $child),
|
||||
fn (StructureNode $child): array => $this->present($user, $child, $full, $rootId),
|
||||
$node->children,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $nodes
|
||||
* @param list<array<string, mixed>> $parents
|
||||
* @return array{node: array<string, mixed>, parents: list<array<string, mixed>>, siblings: list<array<string, mixed>>}|null
|
||||
*/
|
||||
private function locate(array $nodes, int $versionId, array $parents): ?array
|
||||
{
|
||||
foreach ($nodes as $node) {
|
||||
if ($node['version_id'] === $versionId) {
|
||||
return ['node' => $node, 'parents' => $parents, 'siblings' => $nodes];
|
||||
}
|
||||
|
||||
if ($node['children'] !== []) {
|
||||
$found = $this->locate($node['children'], $versionId, [...$parents, $node]);
|
||||
|
||||
if ($found !== null) {
|
||||
return $found;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $nodes
|
||||
* @return list<array<string, mixed>>
|
||||
@@ -183,18 +449,29 @@ private function leaves(array $nodes): array
|
||||
return $leaves;
|
||||
}
|
||||
|
||||
private function coverageLabel(User $user, Composition $composition): string
|
||||
/**
|
||||
* @param list<array<string, mixed>> $nodes
|
||||
*/
|
||||
private function countCompositions(array $nodes): int
|
||||
{
|
||||
$version = $this->display->highestReleasedVersion($composition);
|
||||
$count = 0;
|
||||
|
||||
if ($version === null) {
|
||||
return 'nicht enthalten';
|
||||
foreach ($nodes as $node) {
|
||||
if ($node['composition_id'] !== null) {
|
||||
$count++;
|
||||
}
|
||||
|
||||
$count += $this->countCompositions($node['children']);
|
||||
}
|
||||
|
||||
$nodes = array_map(
|
||||
fn (StructureNode $node): array => $this->present($user, $node),
|
||||
$this->structure->tree($version),
|
||||
);
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $nodes
|
||||
*/
|
||||
private function coverage(array $nodes): string
|
||||
{
|
||||
$leaves = $this->leaves($nodes);
|
||||
$open = count(array_filter($leaves, fn (array $leaf): bool => $leaf['view_url'] !== null));
|
||||
|
||||
@@ -205,6 +482,15 @@ private function coverageLabel(User $user, Composition $composition): string
|
||||
return $open === count($leaves) ? 'nutzbar' : 'teilweise';
|
||||
}
|
||||
|
||||
private function element(int $id): ?ContentElement
|
||||
{
|
||||
if (! array_key_exists($id, $this->elements)) {
|
||||
$this->elements[$id] = ContentElement::query()->find($id);
|
||||
}
|
||||
|
||||
return $this->elements[$id];
|
||||
}
|
||||
|
||||
private function programUrl(StructureNode $node): ?string
|
||||
{
|
||||
if ($node->compositionId === null || $node->compositionVersionId === null) {
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use App\Domain\Catalog\CompositionStructureReader;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Commerce\OrderLine;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Domain\Entitlement\AcquisitionType;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Lizenzübersicht für Mitglieder: macht Erwerb, Zweck, Aktionen und Zeitraum je Berechtigung lesbar.
|
||||
*
|
||||
* Es gibt keine eigene Rechtelogik. Gezeigt wird je Berechtigung (Grant) genau das, was in ihr steht; Rechte verschiedener
|
||||
* Erwerbe werden weder zusammengezählt noch zu einem Gesamtprofil vereinigt. Den Zustand „aktiv“ bestimmt dieselbe Regel
|
||||
* wie die Zugriffsentscheidung (Status, Beginn und Ende), damit die Anzeige nie mehr verspricht als DecideAccess erlaubt.
|
||||
*/
|
||||
class MemberLicenses
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LibraryCatalog $catalog,
|
||||
private readonly CompositionStructureReader $structure,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function overview(User $user): Collection
|
||||
{
|
||||
return $this->grants($user)->map(fn (Grant $grant): array => $this->entry($user, $grant))->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function detail(User $user, Grant $grant): array
|
||||
{
|
||||
$grant->loadMissing('article.currentRelease.contents.elementVersion.element', 'article.currentRelease.rootCompositionVersion.composition');
|
||||
$entry = $this->entry($user, $grant);
|
||||
$release = $grant->article->currentRelease;
|
||||
$classes = [];
|
||||
$contents = [];
|
||||
|
||||
foreach ($release?->contents ?? [] as $content) {
|
||||
$element = $content->elementVersion?->element;
|
||||
|
||||
if ($element === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$classes[$element->output_class] = ($classes[$element->output_class] ?? 0) + 1;
|
||||
$contents[$element->id] = [
|
||||
'title' => $this->catalog->text($element)['title'],
|
||||
'kind' => $this->catalog->outputLabel($element->output_class),
|
||||
'role' => $content->role,
|
||||
];
|
||||
}
|
||||
|
||||
$moduleCount = 0;
|
||||
$rootVersion = $release?->rootCompositionVersion;
|
||||
|
||||
if ($rootVersion !== null) {
|
||||
$moduleCount = $this->countCompositions($this->structure->tree($rootVersion));
|
||||
}
|
||||
|
||||
$scope = [];
|
||||
|
||||
if ($moduleCount > 0) {
|
||||
$scope[] = $moduleCount.' '.($moduleCount === 1 ? 'Modul' : 'Module');
|
||||
}
|
||||
|
||||
foreach ($classes as $class => $count) {
|
||||
$scope[] = $count.' '.$this->plural((string) $class, $count);
|
||||
}
|
||||
|
||||
$granted = $this->granted($grant);
|
||||
$restrictions = [];
|
||||
|
||||
foreach (array_keys($classes) as $class) {
|
||||
foreach (CatalogLabels::FAEHIGKEITEN as $key => $label) {
|
||||
if (str_starts_with($key, $class.':') && ! in_array($key, $granted, true)) {
|
||||
$restrictions[] = $label.' ist in diesem Erwerb nicht enthalten.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($entry['state'] !== 'aktiv') {
|
||||
array_unshift($restrictions, $entry['state_note']);
|
||||
}
|
||||
|
||||
if ($entry['holder_kind'] === 'organisation') {
|
||||
$restrictions[] = 'Die Nutzung gilt, solange deine Mitgliedschaft in dieser Organisation mit Bestellberechtigung besteht.';
|
||||
}
|
||||
|
||||
return $entry + [
|
||||
'scope' => $scope,
|
||||
'contents' => array_values($contents),
|
||||
'restrictions' => $restrictions,
|
||||
'composition' => $rootVersion?->composition,
|
||||
'open_url' => $rootVersion?->composition !== null
|
||||
? route('member.program', $rootVersion->composition)
|
||||
: route('member.article', $grant->article),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function entry(User $user, Grant $grant): array
|
||||
{
|
||||
$grant->loadMissing('article.currentRelease.rootCompositionVersion.composition.editorialContentKind', 'article.currentRelease.rootElementVersion.element', 'acquisition.party');
|
||||
$article = $grant->article;
|
||||
$release = $article->currentRelease;
|
||||
$state = $this->state($grant);
|
||||
$snapshot = is_array($grant->rights_snapshot) ? $grant->rights_snapshot : [];
|
||||
$conditions = is_array($grant->acquisition?->conditions) ? $grant->acquisition->conditions : [];
|
||||
$holderKind = $grant->acquisition?->party?->type === PartyType::Organisation ? 'organisation' : 'person';
|
||||
$composition = $release?->rootCompositionVersion?->composition;
|
||||
$element = $release?->rootElementVersion?->element;
|
||||
$imageUrl = null;
|
||||
|
||||
if ($grant->status === GrantStatus::Aktiv) {
|
||||
$imageUrl = $composition !== null
|
||||
? ThumbnailRef::url('member.thumbnail', 'komposition', $composition->id, $composition->thumbnail_path)
|
||||
: ($element === null ? null : ThumbnailRef::url('member.thumbnail', 'element', $element->id, $element->thumbnail_path));
|
||||
}
|
||||
|
||||
$title = $composition !== null
|
||||
? $this->catalog->text($composition)['title']
|
||||
: ($element !== null ? $this->catalog->text($element)['title'] : app(CourseOutline::class)->title($article));
|
||||
|
||||
return [
|
||||
'grant' => $grant,
|
||||
'id' => $grant->id,
|
||||
'title' => $title !== '' ? $title : $article->code,
|
||||
'kind' => app(CourseOutline::class)->kindLabel($article),
|
||||
'code' => $article->code,
|
||||
'image_url' => $imageUrl,
|
||||
'state' => $state['key'],
|
||||
'state_label' => $state['label'],
|
||||
'state_note' => $state['note'],
|
||||
'active' => $state['key'] === 'aktiv',
|
||||
'purpose' => filled($snapshot['purpose'] ?? null) ? CatalogLabels::zweck((string) $snapshot['purpose']) : null,
|
||||
'rights' => CatalogLabels::faehigkeiten(is_array($snapshot['capabilities'] ?? null) ? $snapshot['capabilities'] : []),
|
||||
'valid_from' => $grant->valid_from,
|
||||
'valid_until' => $grant->valid_until,
|
||||
'validity' => $this->validity($grant, $conditions),
|
||||
'term' => filled($conditions['term_rule'] ?? null) ? ProductOptions::termRuleLabel((string) $conditions['term_rule']) : null,
|
||||
'updates' => ($conditions['update_promise'] ?? null) === 'alle_freigegebenen_fassungen'
|
||||
? '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),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustand wie in DecideAccess: Status aktiv, Beginn erreicht, Ende nicht überschritten.
|
||||
*
|
||||
* @return array{key: string, label: string, note: string}
|
||||
*/
|
||||
private function state(Grant $grant): array
|
||||
{
|
||||
$now = now();
|
||||
|
||||
if ($grant->status === GrantStatus::Widerrufen) {
|
||||
return ['key' => 'widerrufen', 'label' => 'Widerrufen', 'note' => 'Diese Berechtigung wurde widerrufen.'.$this->reason($grant)];
|
||||
}
|
||||
|
||||
if ($grant->status === GrantStatus::Ausgesetzt) {
|
||||
return ['key' => 'ausgesetzt', 'label' => 'Ausgesetzt', 'note' => 'Diese Berechtigung ist derzeit ausgesetzt.'.$this->reason($grant)];
|
||||
}
|
||||
|
||||
if ($grant->status === GrantStatus::Abgelaufen || ($grant->valid_until !== null && ! $grant->valid_until->greaterThan($now))) {
|
||||
return ['key' => 'abgelaufen', 'label' => 'Abgelaufen', 'note' => 'Der Zeitraum dieser Berechtigung ist abgelaufen.'];
|
||||
}
|
||||
|
||||
if ($grant->valid_from !== null && $grant->valid_from->greaterThan($now)) {
|
||||
return ['key' => 'geplant', 'label' => 'Noch nicht gültig', 'note' => 'Diese Berechtigung beginnt am '.$this->date($grant->valid_from).'.'];
|
||||
}
|
||||
|
||||
return ['key' => 'aktiv', 'label' => 'Aktiv', 'note' => ''];
|
||||
}
|
||||
|
||||
private function reason(Grant $grant): string
|
||||
{
|
||||
return filled($grant->status_reason) ? ' Grund: '.$grant->status_reason : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $conditions
|
||||
*/
|
||||
private function validity(Grant $grant, array $conditions): string
|
||||
{
|
||||
$parts = [];
|
||||
|
||||
if ($grant->valid_from !== null) {
|
||||
$parts[] = 'seit '.$this->date($grant->valid_from);
|
||||
}
|
||||
|
||||
if ($grant->valid_until !== null) {
|
||||
$parts[] = 'bis '.$this->date($grant->valid_until);
|
||||
} elseif (($conditions['term_rule'] ?? 'dauerhaft') === 'dauerhaft') {
|
||||
$parts[] = 'ohne Ablaufdatum';
|
||||
} else {
|
||||
$parts[] = 'Ende nicht hinterlegt';
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Herkunft des Rechts: Art des Erwerbs und, soweit vorhanden, die Bezeichnung des Angebots.
|
||||
*
|
||||
* @return array{label: string, detail: ?string, url: ?string}
|
||||
*/
|
||||
private function source(User $user, Grant $grant): array
|
||||
{
|
||||
$acquisition = $grant->acquisition;
|
||||
$type = $acquisition?->type;
|
||||
$label = match ($type) {
|
||||
AcquisitionType::Bestellposition => 'Kauf',
|
||||
AcquisitionType::FreierAbruf => 'Kostenloser Abruf',
|
||||
AcquisitionType::ManuelleVergabe => 'Vergabe durch das Team',
|
||||
AcquisitionType::Abonnement => 'Abonnement',
|
||||
default => 'Erwerb',
|
||||
};
|
||||
$detail = null;
|
||||
$url = null;
|
||||
|
||||
if ($type === AcquisitionType::Bestellposition && $acquisition?->reference_type === 'order_line') {
|
||||
$line = OrderLine::query()->with('order')->find($acquisition->reference_id);
|
||||
|
||||
if ($line !== null) {
|
||||
$detail = $line->offer_name;
|
||||
|
||||
if ($line->order?->user_id === $user->id) {
|
||||
$url = route('member.order', $line->order);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['label' => $label, 'detail' => $detail, 'url' => $url];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string> Schlüssel „Klasse:Aktion“ der Berechtigung
|
||||
*/
|
||||
private function granted(Grant $grant): array
|
||||
{
|
||||
$keys = [];
|
||||
$capabilities = is_array($grant->rights_snapshot['capabilities'] ?? null) ? $grant->rights_snapshot['capabilities'] : [];
|
||||
|
||||
foreach ($capabilities as $class => $actions) {
|
||||
foreach ((array) $actions as $action) {
|
||||
$keys[] = $class.':'.$action;
|
||||
}
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<StructureNode> $nodes
|
||||
*/
|
||||
private function countCompositions(array $nodes): int
|
||||
{
|
||||
$count = 0;
|
||||
|
||||
foreach ($nodes as $node) {
|
||||
if ($node->compositionId !== null) {
|
||||
$count++;
|
||||
}
|
||||
|
||||
$count += $this->countCompositions($node->children);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
private function plural(string $class, int $count): string
|
||||
{
|
||||
$forms = match ($class) {
|
||||
'film' => ['Film', 'Filme'],
|
||||
'audio' => ['Hörstück', 'Hörstücke'],
|
||||
'document', 'pdf' => ['Dokument', 'Dokumente'],
|
||||
'text' => ['Text', 'Texte'],
|
||||
'bild' => ['Bild', 'Bilder'],
|
||||
default => [$class, $class],
|
||||
};
|
||||
|
||||
return $count === 1 ? $forms[0] : $forms[1];
|
||||
}
|
||||
|
||||
private function date(CarbonInterface $date): string
|
||||
{
|
||||
return $date->timezone(config('app.timezone'))->format('d.m.Y');
|
||||
}
|
||||
|
||||
/**
|
||||
* Alle Berechtigungen des Kontos, auch nicht mehr aktive: Inaktive sollen nachvollziehbar bleiben.
|
||||
*
|
||||
* @return Collection<int, Grant>
|
||||
*/
|
||||
private function grants(User $user): Collection
|
||||
{
|
||||
return Grant::query()
|
||||
->usableBy($user)
|
||||
->with('article.currentRelease', 'acquisition.party')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
#[Fillable(['party_id', 'name', 'email', 'password', 'status', 'confirmed_adult_at'])]
|
||||
#[Fillable(['party_id', 'name', 'email', 'password', 'status', 'confirmed_adult_at', 'pending_email'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable implements FilamentUser, HasAppAuthentication, HasAppAuthenticationRecovery, MustVerifyEmail
|
||||
{
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Notifications;
|
||||
|
||||
use App\Http\SignedLink;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Bestätigungslink an die NEUE Adresse. Erst der Klick darauf tauscht die Adresse des Kontos aus.
|
||||
*/
|
||||
class ConfirmNewEmailAddress extends Notification
|
||||
{
|
||||
public function __construct(private readonly int $userId, private readonly string $newEmail) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function via(mixed $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(mixed $notifiable): MailMessage
|
||||
{
|
||||
$url = SignedLink::temporary('member.profile.email.confirm', Carbon::now()->addMinutes(60), [
|
||||
'id' => $this->userId,
|
||||
'hash' => sha1($this->newEmail),
|
||||
]);
|
||||
|
||||
return (new MailMessage)
|
||||
->subject('Neue E-Mail-Adresse bestätigen')
|
||||
->line('Du hast gebeten, die E-Mail-Adresse deines Kontos bei Lara & Felix zu ändern. Bestätige mit dem Knopf, dass diese Adresse dir gehört.')
|
||||
->action('Adresse bestätigen', $url)
|
||||
->line('Der Link gilt 60 Minuten. Wenn du das nicht angefordert hast, ignoriere diese Nachricht; es ändert sich nichts.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Notifications;
|
||||
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
|
||||
/**
|
||||
* Hinweis an die bisherige Adresse, dass eine Änderung beantragt wurde (Schutz vor Kontoübernahme).
|
||||
*/
|
||||
class EmailChangeRequested extends Notification
|
||||
{
|
||||
public function __construct(private readonly string $newEmail) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function via(mixed $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(mixed $notifiable): MailMessage
|
||||
{
|
||||
return (new MailMessage)
|
||||
->subject('Änderung deiner E-Mail-Adresse beantragt')
|
||||
->line('Für dein Konto bei Lara & Felix wurde beantragt, die E-Mail-Adresse auf '.$this->newEmail.' zu ändern.')
|
||||
->line('Die Adresse wechselt erst, wenn die neue Adresse bestätigt wird. Warst du das nicht, ändere bitte dein Passwort und melde dich bei uns.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Produktivfreigabe des Shops (Verkaufsstart Deutschland)
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Ohne diese Freigabe bleibt der Shop in Produktion abgeschaltet, und Stripe nimmt dort keine Zahlung an. Die
|
||||
| Freigabe ist eine Entscheidung von Lars; sie wird ausschließlich in /etc/luf/prod.env gesetzt (SHOP_LIVE_RELEASE=true),
|
||||
| nie im Repository. Zusätzlich verlangt Shop::live() einen Live-Schlüssel (sk_live_), den Zahlungstreiber „stripe“
|
||||
| und veröffentlichte Rechtstexte (SalesTerms::missingPages()).
|
||||
|
|
||||
*/
|
||||
|
||||
'live_release' => (bool) env('SHOP_LIVE_RELEASE', false),
|
||||
|
||||
/*
|
||||
| Kauf auf Rechnung für Vereine und Organisationen (PAY-006): auf Anfrage, Rechnung manuell durch den Betreiber.
|
||||
*/
|
||||
|
||||
'invoice' => (bool) env('SHOP_INVOICE', true),
|
||||
|
||||
/*
|
||||
| Preis- und Steuerhinweis im Warenkorb und in der Bestellübersicht. Der Wortlaut hängt an der Steuerentscheidung
|
||||
| (OPEN-06) und wird erst mit ihr festgelegt (Umgebungsvariable SHOP_PRICE_NOTE).
|
||||
*/
|
||||
|
||||
'price_note' => env('SHOP_PRICE_NOTE', 'Alle Preise in Euro.'),
|
||||
|
||||
];
|
||||
@@ -70,6 +70,13 @@ public function katalogverwalter(): static
|
||||
});
|
||||
}
|
||||
|
||||
public function kundenbetreuung(): static
|
||||
{
|
||||
return $this->afterCreating(function (User $user): void {
|
||||
$user->staffRoles()->create(['role' => StaffRole::Kundenbetreuung]);
|
||||
});
|
||||
}
|
||||
|
||||
public function redakteur(): static
|
||||
{
|
||||
return $this->afterCreating(function (User $user): void {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Mitgliederprofil (ADR-46): neue E-Mail-Adresse wartet auf Bestätigung (pending_email) und Rechnungsadresse je Lizenzinhaber.
|
||||
* Rein ergänzend: keine bestehende Spalte und Tabelle wird verändert; ein Code-Rollback ignoriert beides.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->string('pending_email')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('billing_addresses', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('party_id')->unique()->constrained('parties')->cascadeOnDelete();
|
||||
$table->string('recipient', 160);
|
||||
$table->string('line2', 160)->nullable();
|
||||
$table->string('street', 160);
|
||||
$table->string('postal_code', 16);
|
||||
$table->string('city', 120);
|
||||
$table->string('country', 2)->default('DE');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('billing_addresses');
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->dropColumn('pending_email');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Verkaufsstart Deutschland (A1): nur ergänzend, nichts wird gelöscht oder umbenannt; ein Rollback des Codes lässt
|
||||
* die neuen Spalten und Tabellen liegen (der frühere Code kennt sie nicht).
|
||||
*
|
||||
* - Rabattcodes mit Geltungsbereich (Warenkorb oder ausgewählte Ziele) und Einlösungsberechtigung (allgemein oder
|
||||
* nur für freigeschaltete Konten). Freigaben werden nie gelöscht, nur entzogen.
|
||||
* - Nutzerkreis der Lizenzoption (Einzel- oder Mehrfachlizenz, Zahl der Trainer) an der Angebotsfassung, kopiert in
|
||||
* die Bestellposition. Lizenzinhaber, berechtigte Trainer und Downloadzugriff sind getrennte Angaben.
|
||||
* - Rabatt, Zahlbetrag, Zahlungsweg und Zustimmungsnachweis an der Bestellung.
|
||||
* - Ein eigenständig vermarktetes Paket hat eine eigene Produktseite (offers.standalone_bundle), die seinen Umfang zeigt.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('discount_codes', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('code')->unique();
|
||||
$table->string('label');
|
||||
$table->string('kind', 12);
|
||||
$table->unsignedTinyInteger('percent')->nullable();
|
||||
$table->unsignedInteger('amount_cents')->nullable();
|
||||
$table->string('scope', 12)->default('warenkorb');
|
||||
$table->string('eligibility', 12)->default('allgemein');
|
||||
$table->timestamp('valid_from')->nullable();
|
||||
$table->timestamp('valid_until')->nullable();
|
||||
$table->boolean('active')->default(true);
|
||||
$table->text('note')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('discount_code_targets', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('discount_code_id')->constrained('discount_codes')->cascadeOnDelete();
|
||||
$table->string('target_type', 16);
|
||||
$table->unsignedBigInteger('target_id');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['discount_code_id', 'target_type', 'target_id']);
|
||||
});
|
||||
|
||||
Schema::create('discount_code_releases', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('discount_code_id')->constrained('discount_codes')->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
|
||||
$table->foreignId('granted_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('granted_at');
|
||||
$table->timestamp('valid_until')->nullable();
|
||||
$table->foreignId('revoked_by')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('revoked_at')->nullable();
|
||||
$table->text('reason')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['discount_code_id', 'user_id']);
|
||||
});
|
||||
|
||||
Schema::table('offers', function (Blueprint $table) {
|
||||
$table->boolean('standalone_bundle')->default(false);
|
||||
});
|
||||
|
||||
Schema::table('offer_versions', function (Blueprint $table) {
|
||||
$table->string('licence_scope', 12)->nullable();
|
||||
$table->unsignedSmallInteger('trainer_count')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('order_lines', function (Blueprint $table) {
|
||||
$table->string('licence_scope', 12)->nullable();
|
||||
$table->unsignedSmallInteger('trainer_count')->nullable();
|
||||
$table->unsignedInteger('discount_cents')->default(0);
|
||||
});
|
||||
|
||||
Schema::table('orders', function (Blueprint $table) {
|
||||
$table->unsignedInteger('subtotal_cents')->nullable();
|
||||
$table->unsignedInteger('discount_cents')->default(0);
|
||||
$table->foreignId('discount_code_id')->nullable()->constrained('discount_codes')->nullOnDelete();
|
||||
$table->json('discount_snapshot')->nullable();
|
||||
$table->string('payment_method', 16)->nullable();
|
||||
$table->timestamp('terms_accepted_at')->nullable();
|
||||
$table->json('terms_snapshot')->nullable();
|
||||
$table->timestamp('withdrawal_requested_at')->nullable();
|
||||
$table->text('withdrawal_note')->nullable();
|
||||
});
|
||||
|
||||
Schema::table('payments', function (Blueprint $table) {
|
||||
$table->string('provider_payment_ref')->nullable();
|
||||
$table->unsignedInteger('amount_cents')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('payments', function (Blueprint $table) {
|
||||
$table->dropColumn(['provider_payment_ref', 'amount_cents']);
|
||||
});
|
||||
Schema::table('orders', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('discount_code_id');
|
||||
$table->dropColumn([
|
||||
'subtotal_cents', 'discount_cents', 'discount_snapshot', 'payment_method',
|
||||
'terms_accepted_at', 'terms_snapshot', 'withdrawal_requested_at', 'withdrawal_note',
|
||||
]);
|
||||
});
|
||||
Schema::table('order_lines', function (Blueprint $table) {
|
||||
$table->dropColumn(['licence_scope', 'trainer_count', 'discount_cents']);
|
||||
});
|
||||
Schema::table('offer_versions', function (Blueprint $table) {
|
||||
$table->dropColumn(['licence_scope', 'trainer_count']);
|
||||
});
|
||||
Schema::table('offers', function (Blueprint $table) {
|
||||
$table->dropColumn('standalone_bundle');
|
||||
});
|
||||
Schema::dropIfExists('discount_code_releases');
|
||||
Schema::dropIfExists('discount_code_targets');
|
||||
Schema::dropIfExists('discount_codes');
|
||||
}
|
||||
};
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -78,14 +79,14 @@ public function run(): void
|
||||
'pdf' => ['ansehen', 'laden'],
|
||||
]);
|
||||
|
||||
$this->offer($offers, 'Konflikte im Training: Privatlizenz', 'Privatlizenz', $konflikteVersion, [$konflikteArticle, $privat], 4900, 'person');
|
||||
$this->offer($offers, 'Konflikte im Training: Vereinslizenz', 'Mehrfachlizenz für Vereine', $konflikteVersion, [$konflikteArticle, $verein], 14900, 'organisation');
|
||||
$this->offer($offers, 'Grenzen setzen: Privatlizenz', 'Privatlizenz', $grenzenVersion, [$grenzenArticle, $privat], 2900, 'person');
|
||||
$this->offer($offers, 'Konflikte im Training: Privatlizenz', 'Privatlizenz', $konflikteVersion, [$konflikteArticle, $privat], 4900, 'person', LicenceScope::SINGLE, 1);
|
||||
$this->offer($offers, 'Konflikte im Training: Vereinslizenz', 'Mehrfachlizenz für Vereine', $konflikteVersion, [$konflikteArticle, $verein], 14900, 'organisation', LicenceScope::MULTI, 5);
|
||||
$this->offer($offers, 'Grenzen setzen: Privatlizenz', 'Privatlizenz', $grenzenVersion, [$grenzenArticle, $privat], 2900, 'person', LicenceScope::SINGLE, 1);
|
||||
|
||||
$bundle = $bundles->create('Starterpaket');
|
||||
$starter = $bundles->publish($bundle, [$konflikteArticle->fresh(), $grenzenArticle->fresh(), $starterArticle->fresh()]);
|
||||
$paket = $offers->create('Starterpaket: Privatlizenz');
|
||||
$offers->activate($paket, [['target' => $starter, 'rights' => $privat]], ['grant_kind' => 'kauf', 'price_cents' => 5900, 'holder_kind' => 'person']);
|
||||
$offers->activate($paket, [['target' => $starter, 'rights' => $privat]], ['grant_kind' => 'kauf', 'price_cents' => 5900, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'trainer_count' => 1]);
|
||||
$offers->assignProduct($paket, $starterVersion->composition_id, 'Starterpaket (zwei Programme und Einführung)');
|
||||
|
||||
$tina = $this->account('Tina Trainerin', 'tina.trainerin@example.test');
|
||||
@@ -160,13 +161,15 @@ private function program(
|
||||
/**
|
||||
* @param array{0: LicenseArticle, 1: RightsProfileVersion} $line
|
||||
*/
|
||||
private function offer(OfferService $offers, string $name, string $label, CompositionVersion $version, array $line, int $cents, string $holder): Offer
|
||||
private function offer(OfferService $offers, string $name, string $label, CompositionVersion $version, array $line, int $cents, string $holder, ?string $scope = null, ?int $trainers = null): Offer
|
||||
{
|
||||
$offer = $offers->create($name);
|
||||
$offers->activate($offer, [['target' => $line[0], 'rights' => $line[1]]], [
|
||||
'grant_kind' => 'kauf',
|
||||
'price_cents' => $cents,
|
||||
'holder_kind' => $holder,
|
||||
'licence_scope' => $scope,
|
||||
'trainer_count' => $trainers,
|
||||
]);
|
||||
$offers->assignProduct($offer, $version->composition_id, $label);
|
||||
|
||||
|
||||
@@ -1,3 +1,42 @@
|
||||
# Kanonische Adresse: https://lara-und-felix.de. Der Synology-Reverse-Proxy beendet HTTPS und spricht intern HTTP mit
|
||||
# diesem Container. Das öffentliche Protokoll steht deshalb in X-Forwarded-Proto, der öffentliche Host in
|
||||
# X-Forwarded-Host (falls die Synology ihn setzt) oder sonst im Host-Header.
|
||||
#
|
||||
# Weitergeleitet werden nur normale Seitenaufrufe (GET und HEAD):
|
||||
# - www.lara-und-felix.de und www.laraundfelix.de (HTTP und HTTPS, Protokoll egal) -> https://lara-und-felix.de
|
||||
# - http://lara-und-felix.de, aber nur wenn X-Forwarded-Proto ausdrücklich "http" lautet. Fehlt der Header
|
||||
# (direkter Zugriff, Health-Check auf 127.0.0.1), wird nie weitergeleitet. Das verhindert Schleifen, falls ein
|
||||
# HTTPS-Aufruf ohne den Header ankommt.
|
||||
# Ebenfalls nur bei ausdrücklichem X-Forwarded-Proto "http", auf genau diesen drei Hostnamen (lara-und-felix.de,
|
||||
# www.lara-und-felix.de, www.laraundfelix.de): alle anderen Methoden (POST, PUT, DELETE, ...) enden hier mit 403 und
|
||||
# erreichen Laravel nicht. Ein 301 wäre für sie falsch (der Client schickte den Inhalt erneut oder als GET), und über
|
||||
# unverschlüsseltes HTTP sollen keine Eingaben oder Zugangsdaten ankommen. Über HTTPS (zum Beispiel der Stripe-Webhook)
|
||||
# und ohne X-Forwarded-Proto (direkter Zugriff, Health-Check) ändert sich nichts.
|
||||
# Nie angefasst werden: die ACME-Prüfung unter /.well-known/acme-challenge/ (jede Methode), dev.laraundfelix.de und
|
||||
# alles, was nicht in der Liste steht.
|
||||
# Das Ziel ist fest; Pfad und Query-String bleiben über $request_uri erhalten.
|
||||
map $http_x_forwarded_host $luf_forwarded_host {
|
||||
default "";
|
||||
"~*^\s*(?<luf_fh>[^,\s:]+)" $luf_fh;
|
||||
}
|
||||
|
||||
map $luf_forwarded_host $luf_public_host {
|
||||
"" $host;
|
||||
default $luf_forwarded_host;
|
||||
}
|
||||
|
||||
# Schlüssel: Methode|X-Forwarded-Proto|öffentlicher Host|Pfad. Die Einträge werden der Reihe nach geprüft, der erste
|
||||
# Treffer gilt: die ACME-Ausnahme steht vor den Weiterleitungen (1), diese vor der Sperre für andere Methoden (2).
|
||||
# Die Sperre braucht deshalb keine Methodenliste: GET und HEAD sind in den Zeilen davor bereits entschieden.
|
||||
map "$request_method|$http_x_forwarded_proto|$luf_public_host|$uri" $luf_canonical_redirect {
|
||||
default 0;
|
||||
"~*^[^|]*\|[^|]*\|[^|]*\|/\.well-known/acme-challenge/" 0;
|
||||
"~*^(GET|HEAD)\|[^|]*\|www\.lara-und-felix\.de\.?\|" 1;
|
||||
"~*^(GET|HEAD)\|[^|]*\|www\.laraundfelix\.de\.?\|" 1;
|
||||
"~*^(GET|HEAD)\|\s*http\s*(,[^|]*)?\|lara-und-felix\.de\.?\|" 1;
|
||||
"~*^[^|]*\|\s*http\s*(,[^|]*)?\|(www\.lara-und-felix|www\.laraundfelix|lara-und-felix)\.de\.?\|" 2;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
@@ -9,6 +48,14 @@ server {
|
||||
# alte Adresse und antwortet mit 502 – etwa bei einem erneuten Deploy-Lauf nach einer Änderung der Env-Datei.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
|
||||
# Läuft vor der Auswahl der location (Rewrite-Phase des Servers), daher steckt die ACME-Ausnahme in der map oben.
|
||||
if ($luf_canonical_redirect = 1) {
|
||||
return 301 https://lara-und-felix.de$request_uri;
|
||||
}
|
||||
if ($luf_canonical_redirect = 2) {
|
||||
return 403;
|
||||
}
|
||||
|
||||
client_max_body_size 2048m;
|
||||
client_body_timeout 3600s;
|
||||
send_timeout 3600s;
|
||||
|
||||
@@ -65,6 +65,8 @@ ## Übersicht der Architekturentscheidungen
|
||||
| ADR-42 | Angebot und Warenkorb | Fachlich beschlossen | Gemeinsame Angebotsseite mit Lizenzwahl, Mehrangebotswarenkorb und Geltung der Bestellfassung je Position |
|
||||
| ADR-43 | Trailer auf Karten | Umgesetzt auf Test (21.11.2026); Abnahme offen | Medien-, Programm- und Modulkarte spielen den für die Website freigegebenen Trailer beim Überfahren oder Antippen; ohne Freigabe nur das Bild |
|
||||
| ADR-44 | Gemeinsame, konfigurierbare Größenskala | Umgesetzt auf `develop` (22.11.2026); Abnahme durch den Betreiber offen | Zehn Basiswerte steuern Typografie, Abstände, Kopfzeile, Breite und Bildhöhen für Website, CMS-Vorschau und gemeinsam genutzte Komponenten; einstellbar in „Website → Design → Größen“ ohne Deployment |
|
||||
| ADR-45 | Mitgliederbereich nach Brand-UI-Kit 14 | Umgesetzt auf `develop` (22.11.2026); Abnahme durch den Betreiber offen | Eine Navigation (Bibliothek, Programme, Lizenzen, Konto), eine Karte je Medienidentität in der übergreifenden Liste, Film und Material im Zusammenhang, Lizenzdetail je Berechtigung; keine neuen Datenmodelle, Größen nur aus der Skala |
|
||||
| ADR-46 | Mitgliederprofil | Umgesetzt auf `develop` (23.11.2026); Abnahme offen | Name, E-Mail (mit Bestätigung der neuen Adresse), Passwort und Rechnungsadresse je Lizenzinhaber im Mitgliederbereich; Fußzeile mit Rechtlichem; Download-Dateiname aus dem Titel |
|
||||
|
||||
---
|
||||
|
||||
@@ -592,8 +594,39 @@ ## ADR-44 – Gemeinsame, konfigurierbare Größenskala
|
||||
- **Konfiguration in der Verwaltung:** Seite „Website → Design → Größen“ (`App\Filament\Pages\DesignGroessen`, Navigationsgruppe „Design“), nur für den Systemverwalter. Arbeitsstand mit einer Speicherhandlung, Prüfung der Wertebereiche und der Reihenfolge (Fließtext + 6 ≤ Überschrift 2, Überschrift 2 + 4 ≤ Überschrift 1 ≤ Display), „Standardwerte wiederherstellen“ mit Bestätigung. Speicher: Tabelle `site_settings` (Schlüssel `design.scale`, JSON), rein ergänzende Migration; ohne Zeile gelten die Standardwerte, „Wiederherstellen“ löscht die Zeile.
|
||||
- **Wirkung ohne Deployment:** Abweichende Werte werden als Inline-Stylesheet (`<style id="lf-design-scale">:root{…}</style>`) nach dem Stylesheet in `layouts/site`, `layouts/member` und in alle CMS-Vorschauen (`WidgetEditor::previewStylesheets()`) eingefügt. Ausgegeben werden nur geprüfte ganze Zahlen zu bekannten Schlüsseln. Lesen ist ausfallsicher: fehlende Tabelle, Datenbankfehler oder beschädigte Daten ergeben die Standardwerte, nie eine Fehlerseite (deshalb ist auch ein Code-Rollback folgenlos).
|
||||
- **Nicht einstellbar (Barrierefreiheit):** Trefferflächen 44 px; Fließtext nie unter 16 px, auch auf Smartphones; Fokusdarstellung.
|
||||
- **Mitgliederbereich:** Er verwendet dieselben Tokens und folgt daher Fließtext, Überschrift 3, kleiner Schrift und Abstandsraster. Seine festen Überschriften H1/H2 und sein Layout bleiben unverändert. Kopfzeile, Abschnittsabstände, Inhaltsbreite und Bildhöhen werden nur von der öffentlichen Website verwendet. Die Überarbeitung des Mitgliederbereichs nach seinem eigenen Design-Kit ist ein eigenes Arbeitspaket und nutzt diese Grundlage.
|
||||
- **Mitgliederbereich:** Er verwendet dieselben Tokens und folgt daher Fließtext, Überschrift 3, kleiner Schrift und Abstandsraster. Seine festen Überschriften H1/H2 und sein Layout bleiben unverändert. Kopfzeile, Abschnittsabstände, Inhaltsbreite und Bildhöhen werden nur von der öffentlichen Website verwendet. Die Überarbeitung des Mitgliederbereichs nach seinem eigenen Design-Kit ist mit ADR-45 erfolgt; er bindet seine Überschriften, Abstände, Kopfzeile und Breite jetzt an die Tokens.
|
||||
- **Verwaltungsoberfläche:** Die Filament-Oberfläche lädt `app.css` nicht und bleibt unberührt. Die Vorschau-Iframes laden es und zeigen deshalb die aktiven Werte.
|
||||
**Alternativen.** Je CSS-Eigenschaft eine Einstellung (verworfen: nicht wartbar, Fehleinstellungen); Größen nur im Code (verworfen: Betreiber will praktisch feinjustieren); Ableitung in PHP und Ausgabe aller Tokens (verworfen: zweite Quelle der Regeln neben dem Stylesheet); `zoom`, `transform: scale()` oder globale Prozentskalierung (verworfen: Lesbarkeit, Barrierefreiheit); getrennte Skalen für Website und Mitgliederbereich (verworfen: widerspricht ADR-36).
|
||||
**Folgen.** Neue Komponenten verwenden die abgeleiteten Tokens, keine eigenen Größen. Neue Basiswerte erfordern Eintrag in `tokens.css` und `DesignScale::PARAMETERS`. Die Kit-Komponenten weichen weiter vom Brand-UI-Kit v1.6/v1.7 ab (dokumentiert in `designsystem.md` §15). Die Abnahmebilder der Verwaltung mit Vorschau sind bei Änderung der Werte nicht mehr maßgeblich für Größen.
|
||||
**Quelle.** Analysebericht vom 22.11.2026; Designprinzipien §§5, 9, 11–13; ADR-36, ADR-38, ADR-39; `designsystem.md` §15.
|
||||
|
||||
## ADR-45 – Mitgliederbereich nach Brand-UI-Kit 14
|
||||
|
||||
**Status am 22.11.2026:** Umgesetzt auf `develop` (Branch `feature/mitgliederbereich-v2`); Abnahme durch den Betreiber offen. Technische Fertigstellung ist keine UX-Abnahme. Baut auf ADR-36 (Designsystem) und ADR-44 (Größenskala) auf; die Fachregeln stehen in `docs/fachkonzept/produktkonfiguration-und-mitgliederbereich.md` §§6–11.
|
||||
**Kontext.** Die drei freigegebenen Entwürfe unter `docs/Brand-UI-Kit/14_mitgliederbereich_v2.0/` geben Gestaltungsrichtung und Informationshierarchie vor, keine Pixel, Daten oder Rechte. Der bestehende Mitgliederbereich hatte eine Seitenleiste und eine zweite untere Leiste mit fünf Zielen, feste Überschriftengrößen, eine eingebettete Wiedergabe in der Programmstruktur und eine Lizenzliste nur mit Artikelcode.
|
||||
**Entscheidung.**
|
||||
- **Eine Navigation.** Kopfzeile mit der freigegebenen Wortmarke, „Meine Bibliothek“, „Programme“, „Meine Lizenzen“ und dem Konto-Menü (Profil, Angebote, Abmelden). Unter 56 rem ersetzt eine untere Leiste mit denselben drei Zielen die Hauptnavigation; ein Hamburger-Menü entfällt, weil es dieselben Ziele doppeln würde. „Module“ und „Materialien“ sind keine Navigationspunkte mehr, sondern Werte des Filters „Inhaltsart“ (Programme, Module, Filme, Materialien); die Adressen `/bereich/bibliothek/module` und `/bereich/materialien` bleiben (Letztere leitet auf den Filter).
|
||||
- **Eine Karte je Medienidentität.** `App\Http\LibraryCatalog` baut den Strukturbaum je Komposition einmal pro Anfrage und führt zugängliche Einzelmedien nach Inhaltselement (stabile Identität) zusammen; „Verwendet in“ nennt die Programme und Module. Innerhalb eines Programms bleibt jede Einbindung an ihrer Stelle. Gleiche Titel verschiedener Elemente bleiben getrennte Karten; mehrere Fassungen derselben Identität werden kenntlich gemacht. Es gibt keine neue Tabelle.
|
||||
- **Film und Material im Zusammenhang.** Neue Route `member.content` (`/bereich/bibliothek/programm/{composition}/inhalt/{version}`) zeigt Player, Beschreibung, Begleitmaterial (Geschwister im selben Modul) und den Weg zurück. Sie findet nur Stellen, die in der angezeigten Fassung des Programms stehen (sonst 404). Wiedergabe-, Ansicht- und Downloadadresse kommen weiter ausschließlich aus `DecideAccess` und den signierten Medienrouten; ohne Recht antwortet die Seite mit 403 und enthält keine Adresse. Ansehen und Laden werden getrennt entschieden.
|
||||
- **Lizenzübersicht je Berechtigung.** Neue Leseschicht `App\Http\MemberLicenses` und Route `member.grant` (`/bereich/berechtigungen/{grant}`, nur für Berechtigungen, die das Konto nutzen darf, sonst 404). Je Grant ein Eintrag mit Herkunft (Erwerbsart, Angebotsname), Inhaber, Zweck, erlaubten Aktionen, Zeitraum und Zustand. Der Zustand folgt der Regel von `DecideAccess` (Status, Beginn, Ende), damit die Anzeige nie mehr verspricht als die Entscheidung erlaubt. Rechte verschiedener Erwerbe werden weder addiert noch vereinigt; zwei Berechtigungen für denselben Artikel sind zwei Einträge. Nicht mehr aktive Berechtigungen bleiben unter „Inaktiv“ nachvollziehbar. Nicht gezeigt wird, was nicht vorliegt: Lizenzbedingungen als Dokument, Preise, erfundene Laufzeiten.
|
||||
- **Anzeigetexte** der Bibliothek kommen aus `EditorialProfileReader` mit dem Kontext „Mitgliederbibliothek“ (Abweichung, sonst zentrale Angabe, sonst interne Bezeichnung), also aus der Fachverwaltung, nicht aus Kopien.
|
||||
- **Größen.** `resources/css/components/lf-member.css` ersetzt den Block `body.member` und verwendet nur Tokens der Größenskala (`--text-*`, `--space-*`, `--pad-card`, `--touch-target`, `--width-standard`, `--header-height`, `--grid-gap`) und ein abgeleitetes Token `--card-min` (80 % der Bildhöhe `--ds-media`). Es gibt keinen neuen Basiswert und keine zweite Größenverwaltung. Auf Smartphones sind Karten kompakt (Bild links).
|
||||
- **Nicht enthalten, bewusst:** „Zuletzt genutzt“ und Favoriten (es gibt keine Nutzungshistorie; `DeliveryLog` ist ein Lizenznachweis, keine Nutzerhistorie), Karten-/Listenwechsel, Fortschritt, Denkpause, Kursplayer, Zahlen je Filterwert.
|
||||
- **Ansprache.** Die überarbeiteten Mitgliederseiten verwenden „du“ wie die Entwürfe und der Shop. Anmeldeseiten und Systemmeldungen anderer Abläufe sind unverändert („Sie“); eine einheitliche Regel steht aus und ist eine Entscheidung des Betreibers.
|
||||
**Alternativen.** Eigene Bibliotheks-Tabelle oder Suchindex (verworfen: zweite Wahrheit neben den Fachobjekten); „Verwendet in“ als gespeicherte Beziehung (verworfen: abgeleitet aus den Strukturen); Player weiter eingebettet in der Programmstruktur (verworfen: lädt jeden Film der Seite, trennt Film und Begleitmaterial nicht); Übernahme der Entwurfspixel (verworfen: widerspricht ADR-44).
|
||||
**Folgen.** Tests, die Markup der alten Ansichten prüften, sind bewusst geändert (Begründung im Commit). Die Vorschau der Bibliothekskarte in der Verwaltung rendert dieselbe Komponente `<x-member.card>`. Offene Abhängigkeiten zur Fachverwaltung stehen im Abschlussbericht `docs/ux/mitgliederbereich/abschlussbericht.md`.
|
||||
**Quelle.** `docs/Brand-UI-Kit/14_mitgliederbereich_v2.0/` (Handoff, Implementierungsbrief), Fachkonzept §§6–11 und 13, ADR-36, ADR-44.
|
||||
|
||||
## ADR-46 – Mitgliederprofil, Fußzeile und Dateiname
|
||||
|
||||
**Status am 23.11.2026:** Umgesetzt auf `develop` (Branch `feature/mitglieder-nachbesserung`); Abnahme offen. Ergänzt ADR-45 nach der ersten Sichtung auf luf-test.
|
||||
**Kontext.** Das Profil bot nur den Namen. Mitglieder brauchen Adresse, Passwort und Rechnungsadresse selbst; Impressum und Datenschutz fehlten im Mitgliederbereich; Downloads hießen nach der Adresse („laden.mp4“).
|
||||
**Entscheidung.**
|
||||
- **Profil in vier Blöcken** mit je eigener Speicherhandlung und eigenen Fehlern (`App\Http\Controllers\Member\ProfileController`). **E-Mail:** Die neue Adresse wird als `users.pending_email` vorgemerkt und gilt erst, wenn ein signierter Link (60 Minuten) an die neue Adresse geöffnet wird; die bisherige Adresse erhält einen Hinweis; verlangt wird das aktuelle Passwort; der Link gilt nur für das eigene Konto und die vorgemerkte Adresse. **Passwort:** bisheriges Passwort, Regeln wie bei der Registrierung, neues muss abweichen. **Rechnungsadresse:** Tabelle `billing_addresses`, eine je Lizenzinhaber (Party), gepflegt, aber noch nicht in Bestellungen kopiert. Beide Migrationen sind rein ergänzend (Rollback-sicher).
|
||||
- **Fußzeile** `x-member.footer`: Links aus der CMS-Navigation (Plätze Rechtliches und Kontakt), ersatzweise die veröffentlichten Seiten `/impressum` und `/datenschutz`; keine fest codierten Texte.
|
||||
- **Dateiname** von Download und Ansicht aus dem Anzeigetitel des Mediums plus Dateiendung; ein eigenes Feld im Medienmanager ist nicht beschlossen.
|
||||
- **Player:** Der Anfangsscan von `app.js` bindet auch im Quelltext stehende HLS-Videos an hls.js an (bisher übersprungen, weil `document` kein `Element` ist).
|
||||
- **Einzel-/Mehrfachlizenz:** nicht vorhanden; die Lizenzdetailseite benennt das offen. Ein Vorschlag steht in `docs/ux/mitgliederbereich/nachbesserung-2026-11-23.md`.
|
||||
**Alternativen.** E-Mail sofort ändern (verworfen: Tippfehler sperrt das Konto aus, Kontoübernahme ohne Gegenprobe); Adresse als Freitext am Konto (verworfen: Rechnungsadresse gehört zum Lizenzinhaber, auch für Organisationen); Fußzeile des Website-Gerüsts übernehmen (verworfen: zu groß für die Arbeitsoberfläche).
|
||||
**Folgen.** Rechnungsstellung und Bestellübersicht müssen die Adresse später in die Bestellung kopieren (Stand zum Kaufzeitpunkt). Pflege der Rechtsseiten bleibt Aufgabe der Redaktion im CMS.
|
||||
**Quelle.** Rückmeldung des Betreibers vom 23.11.2026; ADR-45; `05_Lizenz_und_Berechtigungslogik.md` §9.
|
||||
@@ -110,7 +110,7 @@ ## 4. Registrierte Widget-Arten
|
||||
|
||||
## 5. Neues Widget hinzufügen
|
||||
|
||||
1. Klasse unter `app/Domain/Cms/Widgets/Types/` anlegen, von `WidgetType` ableiten. Pflicht: `key()`, `label()`, `description()`, `dataRules()`, `dataFields()`. Je nach Bedarf: `variants()`, Layoutvertrag `supportedUnits()`/`preferredUnits()`/`heights()`/`stages()`/`narrowBehavior()` (Abschnitt 12), `settings()`/`settingLabels()`/`optionIcons()`, `mediaSchema()` für den Reiter „Medien“, `refRules()`, `refFields()`, `clean()` (Links mit `SafeUrl`, Text mit `RichText::sanitize`, Bilder mit `ImageRefFields::clean`), `resolve()`, `mediaPaths()`, `summary()`, `schematic()`, `icon()`.
|
||||
1. Klasse unter `app/Domain/Cms/Widgets/Types/` anlegen, von `WidgetType` ableiten. Pflicht: `key()`, `label()`, `description()`, `dataRules()`, `dataFields()`. Je nach Bedarf: `variants()`, Layoutvertrag `supportedUnits()`/`preferredUnits()`/`heights()`/`stages()`/`narrowBehavior()` (Abschnitt 12), `settings()`/`settingLabels()` (Bezeichnung und Erklärung für das (i))/`settingGroups()`/`settingHiddenWhen()`/`optionIcons()`, `mediaSchema()` für den Reiter „Medien“, `refRules()`, `refFields()`, `clean()` (Links mit `SafeUrl`, Text mit `RichText::sanitize`, Bilder mit `ImageRefFields::clean`), `resolve()`, `mediaPaths()`, `summary()`, `schematic()`, `icon()`.
|
||||
2. Ansicht `resources/views/widgets/<kennung>.blade.php` anlegen. Verfügbar: `$data`, `$refs`, `$variant`, `$settings`, `$first`, `$context` (Vorschau ja/nein) und die Rückgabe von `resolve()`. Kein `{!! !!}` außer für mit `RichText::sanitize` bereinigten Text. Breitenabhängige Regeln als Container-Abfrage `@container slot (…)`, nicht als Fenster-Medienabfrage; Farben nur über Bedeutungs-Tokens.
|
||||
3. Klasse in `config/cms.php` unter `widgets` eintragen.
|
||||
4. Tests ergänzen (Registrierung und Prüfregeln in `tests/Unit/WidgetRegistryTest.php`, Darstellung in `tests/Feature/CmsWidgetRenderingTest.php` bzw. `CmsSectionRenderingTest.php`).
|
||||
@@ -154,7 +154,7 @@ ## 8. Editor und Vorschau
|
||||
- **Raster**: grafische Auswahl mit sechs Kacheln. Raster mit weniger Plätzen als eingesetzten Widgets sind gesperrt. Beim Wechsel entfallen zuerst leere Plätze; Widgets behalten ihre Reihenfolge (`SectionEditor::arrangeSlots`). Kein Wechsel entfernt ein Widget.
|
||||
- **Gestaltung des Abschnitts** (eingeklappt, Zusammenfassung im Kopf): Hintergrund, Breite, **Abstand oben**, **Abstand unten**, **Widget-Abstand** (je Kein Abstand / Kompakt / Normal / Großzügig, siehe §11), Trenner; bei Hintergrundbild zusätzlich Bild (Auswahl oder Upload), Fokuspunkt und Überlagerung. Abschnitts- und Widget-Einstellungen sind getrennt.
|
||||
- **Plätze** stehen im Verhältnis des Desktop-Rasters nebeneinander; Widgets lassen sich per Ziehen zwischen Plätzen tauschen. Der Platzkopf nennt Breite und warnt, wenn das Widget breiter sein müsste. Ein freier Platz bietet „Widget einsetzen“ (Auswahl mit Name, Beschreibung, Symbolbild, Mindestbreite), danach öffnet der Widget-Dialog. Ein Klick auf die Vorschau öffnet denselben Dialog: eine Dialogebene.
|
||||
- **Widget-Dialog**: Arten mit Darstellungsoptionen oder Medien gliedern den Dialog in die Reiter **Inhalt**, **Medien** und **Darstellung** (generisch aus der Registry: `editorSchema()`, `mediaSchema()`, Varianten und `settingOptions()`); andere Arten zeigen ihre Felder direkt. Varianten und Höhen sind sichtbare Auswahlknöpfe mit Symbol, Bildfokus zwei Schieberegler (0–100). „Darstellung“ nennt die zulässigen Platzbreiten und das Verhalten bei wenig Platz.
|
||||
- **Widget-Dialog**: Arten mit Darstellungsoptionen oder Medien gliedern den Dialog in die Reiter **Inhalt**, **Medien** und **Darstellung** (generisch aus der Registry: `editorSchema()`, `mediaSchema()`, Varianten und `settingOptions()`); andere Arten zeigen ihre Felder direkt. Varianten und Höhen sind sichtbare Auswahlknöpfe mit Symbol, Bildfokus zwei Schieberegler (0–100). „Darstellung“ nennt die zulässigen Platzbreiten und das Verhalten bei wenig Platz. Der Reiter „Darstellung“ ist gegliedert: **Aufbau** (Anordnung und Höhe), danach die Gruppen der Art aus `settingGroups()` (bei den Karten „Bild und Video“, „Texte auf der Karte“, „Seitenstruktur“; bei Hero und Bild-Text-Widget „Aussehen“ und „Seitenstruktur“). Einstellungen ohne Gruppe erscheinen unter „Weitere Einstellungen“. Die Erklärung zu jeder Einstellung steht im kleinen (i) neben der Bezeichnung (`settingLabels()`, zweiter Eintrag; Tooltip beim Überfahren). `settingHiddenWhen()` blendet abhängige Schalter aus, ohne ihre Werte zu verlieren: Bei „Texte auf der Karte: Ausblenden“ verschwinden Quelle der Beschreibung, Beschreibung, Art-Label, Zusatzangaben und Schaltfläche.
|
||||
- **Live-Vorschau im Dialog**: rendert den ungespeicherten Zustand mit derselben Ansicht wie die Website (`WidgetEditor::renderPreview`) in einer wählbaren logischen Platzbreite (Smartphone 390 px und die zulässigen Einheiten: 310/640/960/1300 px, entsprechend dem Standardabschnitt bei 1440 px Fensterbreite) und verkleinert sie auf die Dialogbreite. Die Breitenwahl wird nicht gespeichert.
|
||||
- **Widget-Vorschau im Platz**: dieselbe Ansicht im isolierten `iframe` in der Breite des Platzes im Editor; über 28 rem gekürzt mit Hinweis „vollständig in der Seitenvorschau“.
|
||||
- „Entwurf speichern“ erzeugt eine Revision (bei unverändertem Stand keine weitere). „Veröffentlichen“ speichert zuerst den aktuellen Stand im Editor und veröffentlicht genau diesen; enthält er Fehler, wird nichts veröffentlicht. Vorher veröffentlichte „Veröffentlichen“ nur die zuletzt gespeicherte Revision, sodass übernommene, aber ungespeicherte Änderungen (etwa ein gewähltes Bild) verloren gingen.
|
||||
@@ -316,7 +316,7 @@ ## 13. Premium-Karten (Brand-UI-Kit v1.7, ADR-39)
|
||||
|
||||
**Video im Einstieg (Hero, Variante `photo_split`).** Optional `refs.video`: ein Film aus dem Medienmanager (Auswahl über `HeroVideo`, geprüft: Film, nicht archiviert, nicht gesperrt, keine Traineranleitung). Gespielt wird der freigegebene Clip nach der Regel der Karte (`CardClip`: Trailer, Vorschauclip, sonst die freigegebene Website-Datei des Films). Das Video liegt stumm auf der Fläche des Fotos, startet nach dem Laden von selbst (nicht bei „reduzierte Bewegung“, Datensparmodus, 2G), hat eine Schaltfläche zum Anhalten und fällt bei Fehlern auf das Foto zurück; `resources/js/hero-video.js`. Die Markenfläche zeigt kein Video. Entscheidung: ADR-43 (Nachtrag).
|
||||
|
||||
**Karte ohne Texte (Medien-, Programm- und Modulkarte).** Einstellung `settings.show_body` (`yes` Vorgabe, `no`; Darstellung → „Texte neben dem Bild“). Bei `no` zeigt die Karte nur Bild oder Video: ohne Titel, Text, Art, Zusatzangaben, Aktion und Marke im Bild, immer Bild über dem (leeren) Textbereich. Der Titel bleibt als `visually-hidden`-Überschrift für Hilfstechnik, ein Trailer läuft weiter, die Redaktionsvorschau zeigt ihre Hinweise weiter. Die Themenkarte hat die Einstellung nicht (sie bliebe leer).
|
||||
**Karte ohne Texte (Medien-, Programm- und Modulkarte).** Einstellung `settings.show_body` (`yes` Vorgabe, `no`; Darstellung → „Texte auf der Karte“). Bei `no` zeigt die Karte nur Bild oder Video: ohne Titel, Text, Art, Zusatzangaben, Aktion und Marke im Bild, immer Bild über dem (leeren) Textbereich. Der Titel bleibt als `visually-hidden`-Überschrift für Hilfstechnik, ein Trailer läuft weiter, die Redaktionsvorschau zeigt ihre Hinweise weiter. Die Themenkarte hat die Einstellung nicht (sie bliebe leer).
|
||||
|
||||
**Trailer auf der Karte (Medien-, Programm- und Modulkarte).** Einstellung `settings.clip` (`yes` Vorgabe, `no`). Der Clip ist der Trailer des Objekts (Präsentationsrolle „Trailer“, sonst „Vorschauclip“, bei einem Film ersatzweise sein freigegebener Teaser), nur wenn er für die Website freigegeben ist (`CardClip`). Er liegt über dem Kartenbild: Beim Überfahren mit der Maus läuft eine stumme Vorschau in Schleife; ein Klick oder Tipp (Handy) auf das Bild oder die kleine Schaltfläche (auch per Tastatur) spielt ihn mit Ton ab; `resources/js/card-clip.js`. Ohne Freigabe bleibt das Bild; die Redaktionsvorschau nennt den Grund. Entscheidung: ADR-43.
|
||||
|
||||
|
||||
@@ -123,7 +123,7 @@ ## 9. Website-Gerüst (Designiteration 1)
|
||||
|
||||
- **Wortmarke**: freigegebene Lara-&-Felix-Wortmarke (Kompaktfassung) als Bild mit festen Maßen im Markup; die Breitenmessung der Navigation stimmt dadurch schon vor dem Laden des Bildes.
|
||||
- **Kopfzeile, zwei Zustände ohne Layoutsprung.** (Maße seit ADR-44 aus dem Basiswert „Höhe der Kopfzeile“, Standard 80: Box 80 px ab 75 rem, sonst 64 px, kompakte Leiste 64 px, Wortmarke im Ausgangszustand 1,25-fach; die folgenden Pixelangaben nennen den Stand vor ADR-44.) Die Box ist immer `--header-height-initial` hoch (104 px ab 75 rem, sonst 64 px) und klebt mit negativem Abstand (`top: kompakt − initial`). Die innere Leiste (`.site-header-bar`, 72 px) klebt oben. Beim Scrollen wandert sie 16 px nach oben und bleibt dann stehen; der Seitenfluss ändert sich nie. Ein Beobachter (`data-site-header-sentinel`) setzt `.is-compact`: Wortmarke von 1,16-facher auf normale Größe (nur `transform`) und Schatten. Unter `prefers-reduced-motion` ohne Übergang. Ohne JavaScript klebt die Kopfzeile genauso; nur die Wortmarke bleibt groß.
|
||||
- **Breitenstufen der Navigation** (`site-nav.js`, Messung an einer unsichtbaren Kopie): 1. Navigation und Kontozugang mit Beschriftung in einer Zeile; 2. sonst Kontozugang nur als Symbol (`.is-account-compact`); 3. sonst und immer unter 75 rem Menümodus (`.is-menu-mode`). Die Navigation bricht nie um; deshalb ist die Kopfzeile auf allen Seiten gleich hoch, unabhängig von Anzahl und Länge der CMS-Einträge. Die Messung steht inline direkt nach der Kopfzeile (`window.lufHeaderMode`) und setzt die Stufe vor dem ersten Zeichnen; `site-nav.js` wiederholt sie bei Größenänderungen und nach dem Laden der Schriften.
|
||||
- **Breitenstufen der Navigation** (`site-nav.js`, Messung des echten Platzbedarfs der Einträge): 1. Navigation und Kontozugang mit Beschriftung in einer Zeile; 2. sonst Kontozugang und Warenkorb nur als Symbol (`.is-account-compact`); 3. sonst zusätzlich engere Navigation mit kleinerem Abstand und Schrift (`.is-nav-tight`); 4. sonst und immer unter 75 rem Menümodus (`.is-menu-mode`). Auf dem Desktop steht die Navigation damit offen, der Burger ist dort nur die letzte Stufe (Stand 2026-11-22: luf-test mit 8 Einträgen offen ab 1280 px, bei 1200 px Menümodus). Die Navigation bricht nie um; deshalb ist die Kopfzeile auf allen Seiten gleich hoch, unabhängig von Anzahl und Länge der CMS-Einträge. Die Messung steht inline direkt nach der Kopfzeile (`window.lufHeaderMode`) und setzt die Stufe vor dem ersten Zeichnen; `site-nav.js` wiederholt sie bei Größenänderungen und nach dem Laden der Schriften.
|
||||
- **Hauptnavigation**: aus `navigation_items` (`header`), aktiver Eintrag mit gelber Markenunterstreichung und `aria-current`, eine Ebene Untermenü als Aufklappliste (Schaltfläche mit `aria-expanded`, Escape schließt, Klick außerhalb schließt).
|
||||
- **Menümodus**: Menü-Schaltfläche (Symbol und Text) öffnet eine Fläche direkt unter dem sichtbaren Teil der Kopfzeile, 48 px hohe Einträge, Untermenüs eingerückt; Fokus springt in das Menü, Tabulator läuft im Kreis zwischen Schaltfläche und Einträgen, Escape schließt und gibt den Fokus zurück. Keine untere Navigationsleiste auf der Website. Ohne JavaScript bleibt die Navigation unter 75 rem als umbrechende Liste sichtbar.
|
||||
- **Kontozugang** „Mitgliederbereich“ (für alle Besucher gleich; Gäste werden zur Anmeldung geleitet) und vorbereiteter Warenkorbzugang (`config/cms.php` → `cart.enabled`, Vorgabe aus: es wird nichts ausgegeben).
|
||||
@@ -217,10 +217,11 @@ ### 15.4 Gemeinsam genutzt und nur Website
|
||||
| Wert | Website | Mitgliederbereich (heute) |
|
||||
|---|---|---|
|
||||
| Fließtext, Überschrift 3, kleine Schrift, Schaltflächentext, Basisabstand | ja | folgt (gleiche Tokens) |
|
||||
| Überschrift 1 und 2, Display | ja | unverändert: feste Überschriften in `app.css` (`body.member h1/h2`) |
|
||||
| Abschnittsabstände, Kopfzeile, Inhaltsbreite, Bildhöhen, Karten-Innenabstand (Widgets) | ja | nicht verwendet |
|
||||
| Überschrift 1 und 2, Display | ja | ja (seit ADR-45): H1 `--text-h1`, Abschnittstitel `--text-h2`, Kartentitel `--text-h3` |
|
||||
| Kopfzeile, Inhaltsbreite, Karten-Innenabstand | ja | ja: `--header-height`, `--width-standard`, `--pad-card` |
|
||||
| Abschnittsabstände, Bildhöhen (Widgets) | ja | Abstände über `--space-*`; Kartenbreite über das abgeleitete Token `--card-min` (80 % von `--ds-media`) |
|
||||
|
||||
Die Überarbeitung des Mitgliederbereichs nach seinem eigenen Design-Kit ist ein eigenes Arbeitspaket; es nutzt dieselben Basiswerte und Tokens und kann seine Überschriften an `--text-h1|h2` anbinden.
|
||||
Der Mitgliederbereich (`resources/css/components/lf-member.css`, ADR-45) verwendet ausschließlich diese Tokens; Karten- und Listentext sind `--text-small`, Trefferflächen `--touch-target`. Er hat keine eigenen Basiswerte.
|
||||
|
||||
### 15.5 Abweichung vom Brand-UI-Kit
|
||||
|
||||
|
||||
@@ -99,6 +99,29 @@ ## Medien-Ablage auf dem NAS
|
||||
- Die CI-Tests mounten keine Medien (`Storage::fake()`).
|
||||
- Datensicherung: Originale sind laut `11_Betrieb_Sicherheit_Datenschutz.md` kritisch (NAS und außer Haus). Snapshots und Replikation für `luf_media` sind Sache des NAS und noch nicht eingerichtet.
|
||||
|
||||
## Kanonische Adresse und Weiterleitungen (Nginx im Shop-Container)
|
||||
|
||||
Die Shop-Adresse ist `https://lara-und-felix.de`. Der Nginx des Containers (`docker/nginx/default.conf`) leitet normale Seitenaufrufe (`GET`, `HEAD`) mit `301` auf diese feste Adresse um, Pfad und Query-String bleiben erhalten. Die Entscheidung trifft eine `map` über Methode, `X-Forwarded-Proto`, öffentlichen Host und Pfad.
|
||||
|
||||
| Aufruf (Methode `GET`/`HEAD`) | Verhalten |
|
||||
|---|---|
|
||||
| `http://lara-und-felix.de` (nur bei `X-Forwarded-Proto: http`) | `301` auf `https://lara-und-felix.de` |
|
||||
| `http://` und `https://www.lara-und-felix.de` | `301` direkt auf `https://lara-und-felix.de` |
|
||||
| `http://` und `https://www.laraundfelix.de` | `301` direkt auf `https://lara-und-felix.de` |
|
||||
| `https://lara-und-felix.de` | Shop |
|
||||
| `dev.laraundfelix.de` | Testinstanz, unverändert |
|
||||
| `laraundfelix.de` ohne `www` | nicht betroffen, die STRATO-Weiterleitung übernimmt |
|
||||
| Jede andere Methode (`POST`, `PUT`, `DELETE` …) auf den drei Shop-Hosts, nur bei `X-Forwarded-Proto: http` | `403` im Nginx, die Anfrage erreicht Laravel nicht |
|
||||
|
||||
- **Öffentlicher Host:** erster Wert von `X-Forwarded-Host`, sonst der `Host`-Header (ohne Port, Groß-/Kleinschreibung egal). Eine Adresse ohne Proxy (`127.0.0.1:3010`, `192.168.2.144:3011`) trifft keine Regel.
|
||||
- **Öffentliches Protokoll:** nur `X-Forwarded-Proto`, nie das lokale Schema. Fehlt der Header, wird `lara-und-felix.de` **nicht** weitergeleitet. Dadurch gibt es keine Schleife, falls ein HTTPS-Aufruf ohne den Header ankäme, und der Health-Check des Deploys (`http://127.0.0.1:$WEB_PORT/up`) bleibt unberührt. Die `www`-Adressen werden unabhängig vom Protokoll weitergeleitet.
|
||||
- **Andere Methoden:** Auf `lara-und-felix.de`, `www.lara-und-felix.de` und `www.laraundfelix.de` endet jede Methode außer `GET`/`HEAD` mit `403` im Nginx, **wenn** der Proxy ausdrücklich `X-Forwarded-Proto: http` setzt (erster Wert der Liste). Ein `301` wäre für sie falsch, und über unverschlüsseltes HTTP sollen keine Eingaben ankommen. Unverändert an die Anwendung gehen: alle Methoden über HTTPS (der Stripe-Webhook `/stripe/webhook` ist ein `POST` und muss als `https://` in Stripe eingetragen sein), alle Methoden ohne `X-Forwarded-Proto` (direkter Zugriff, Health-Check) und `dev.laraundfelix.de`. Im Repository ist keine Webhook-Adresse hinterlegt; welche Adresse im Stripe-Dashboard steht, ist [?] nicht geprüft. **Vor dem Aktivieren der HTTP-Regeln prüfen:** Steht dort `http://…`, würde der Webhook mit `403` abgewiesen und muss auf `https://` umgestellt werden.
|
||||
- **ACME:** `/.well-known/acme-challenge/` wird nie umgeleitet oder gesperrt, für jede Methode (Ausnahme zuerst in der `map`), auch nicht auf den `www`-Hosts. Der Shop beantwortet diesen Pfad selbst nicht (Laravel liefert 404); das Zertifikat holt die Synology, sie muss die Prüfung also selbst beantworten und darf sie nicht an den Shop weiterreichen. [?] Beim ersten Erneuern beobachten.
|
||||
- **Signierte URLs:** `App\Http\SignedLink` signiert nur den Pfad (relative Signatur), der Host fließt nicht ein. Ein Wechsel zwischen den Alias-Hosts macht Links also nicht ungültig. Im Repository kommt kein Alias-Host vor; Stripe-Rücksprungadressen entstehen aus `route()` und damit aus `APP_URL` bzw. dem Anfrage-Host.
|
||||
- **Synology:** Setzt der Reverse-Proxy `X-Forwarded-Proto` nicht von selbst, dann einen eigenen Kopfzeilen-Eintrag `X-Forwarded-Proto` mit dem Wert `$scheme` anlegen. Für die Testinstanz ist belegt, dass Protokoll und Host der Synology in der Anwendung ankommen (Stand 2026-11-22: `https://dev.laraundfelix.de/verwaltung` leitet auf `https://dev.laraundfelix.de/verwaltung/login`). Für die Prod-Regeln ist das [?] nicht geprüft.
|
||||
- **Prüfung:** Die Fälle der Tabelle, `HEAD`, Pfad mit Query, Großschreibung, Port im Host, `X-Forwarded-Host`, `POST`/`PUT`, direkter Zugriff und ACME wurden 2026-11-22 mit Windows-nginx 1.27.5 (nicht das Alpine-Image) und `php-cgi` als Upstream durchgespielt (30 Fälle). Reihenfolge und Zusagen der Konfiguration sichert `tests/Unit/NginxConfigTest.php`.
|
||||
- **Nach dem Deploy auf Test** (Lars oder Claude, nur gegen `192.168.2.144:3011`, nie gegen Prod): `curl -sI -H 'Host: www.laraundfelix.de' -H 'X-Forwarded-Proto: https' 'http://192.168.2.144:3011/a?b=1'` muss `301` mit `Location: https://lara-und-felix.de/a?b=1` liefern.
|
||||
|
||||
## Einmalig auf llm-node vorzubereiten (nicht automatisiert, braucht `sudo`)
|
||||
|
||||
1. `sudo mkdir -p /etc/luf && sudo chown llmadmin:llmadmin /etc/luf && sudo chmod 750 /etc/luf`
|
||||
|
||||
@@ -12,7 +12,8 @@ ## 1. Inhalt (Stand 21.11.2026 abends: 22 Commits seit `main`)
|
||||
| Programm- und Modulkarte | Text der Karte wählen (zusätzlich Lernziel); Vorschaubild als Website-Bild übernehmen | Claude |
|
||||
| Trailer auf Karten | Medien-, Programm- und Modulkarte spielen den für die Website freigegebenen Trailer (Rolle Trailer, sonst Vorschauclip, bei Filmen ersatzweise der eigene Teaser) beim Überfahren mit der Maus als stumme Vorschau und per Klick oder Tipp mit Ton ab (kleine Symbolschaltfläche); je Karte abschaltbar; die Medienroute beantwortet Bereichsabrufe (ADR-43). Auf luf-test mit einem echten Clip geprüft. Keine Migration | Claude |
|
||||
| Medienkarte: Film nur mit Website-Datei | Ein Medium ohne Fassung (z. B. Teaser) ist auf der Medienkarte wählbar und erscheint öffentlich, sobald die Datei für die Website freigegeben ist (ohne Programmseite, ohne Aktion). Keine Migration | Claude |
|
||||
| Karte ohne Texte | Medien- und Programmkarte: Einstellung „Texte neben dem Bild“ (Ausblenden) zeigt nur Bild oder Video; der Titel bleibt für Hilfstechnik. Keine Migration | Claude |
|
||||
| Karte ohne Texte | Medien- und Programmkarte: Einstellung „Texte auf der Karte“ (Ausblenden) zeigt nur Bild oder Video; der Titel bleibt für Hilfstechnik. Keine Migration | Claude |
|
||||
| Reiter „Darstellung“ gegliedert | Aufbau, Gruppen je Widget, Erklärungen im (i), Einzelschalter für Texte verschwinden bei „Texte auf der Karte: Ausblenden“; Bezeichnungen vereinheitlicht. Keine Migration, gespeicherte Werte unverändert | Claude |
|
||||
| Hero mit Video | Der Einstieg (Variante Foto mit Textfläche) spielt auf Wunsch ein freigegebenes Video stumm auf der Fläche des Fotos ab, mit Schaltfläche zum Anhalten; Foto als Rückfall (ADR-43 Nachtrag). Keine Migration | Claude |
|
||||
| Website-Datei eines Films | Ablage der Datei eines eigenständigen Präsentationsmediums über die Warteschlange, nachträgliches Hochladen am Medium (Behebung: der Web-Prozess darf `derived/` nicht schreiben) | Lars (anderer Rechner) |
|
||||
| Medienmanager | „Medium löschen“ erreicht Standbilder und übernommene CMS-Bilder (Fremdschlüssel gelockert) | Claude |
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Abnahmebilder auf luf-test (23.11.2026)
|
||||
|
||||
Aufgenommen mit Chromium gegen `https://dev.laraundfelix.de` (Stand `develop` Lauf 5048) mit einem Mitgliedskonto des Betreibers, nur lesend (kein Speichern von Profil-, Passwort- oder Adressdaten). Echte Fachobjekte: Programm Abstand, Modul Hilfe, Film „Lara im Park“ (HLS), Trainerunterlage. Geprüft: Film startet (HLS, Wiedergabezeit 5 s), Download heißt „Lara im Park.mp4“, Profil mit vier Blöcken, Fußzeile mit Impressum und Datenschutz (beide Seiten erreichbar), Lizenzdetail mit Hinweis zu Einzel-/Mehrfachlizenz, Smartphone ohne waagerechten Überlauf.
|
||||
|
||||
`20` Start, `21` Bibliothek, `22` Film, `23` Profil, `24` Lizenzen, `25` Lizenzdetail (Desktop); `30`–`33` Smartphone.
|
||||
|
After Width: | Height: | Size: 282 KiB |
|
After Width: | Height: | Size: 370 KiB |
|
After Width: | Height: | Size: 933 KiB |
|
After Width: | Height: | Size: 206 KiB |
|
After Width: | Height: | Size: 562 KiB |
|
After Width: | Height: | Size: 216 KiB |
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 220 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 738 KiB |
@@ -0,0 +1,20 @@
|
||||
# Abnahmebilder Mitgliederbereich (lokal, Demodaten)
|
||||
|
||||
Aufgenommen am 22.11.2026 mit Chromium gegen die lokale Anwendung (Stand `2e6260a`, SQLite, `ShopDemoSeeder`), **nicht auf luf-test**. Die Demodaten haben keine Vorschaubilder und keine Mediendateien: Karten zeigen den Platzhalter, der Player ist leer. Konten: Tina (zwei Lizenzen), Max (keine Lizenz). Breiten: `desktop` 1280 px, `mobil` 390 px. In ganzseitigen Aufnahmen steht die untere Leiste mitten im Bild; sie klebt am Fensterrand.
|
||||
|
||||
| Nr. | Ansicht |
|
||||
|---|---|
|
||||
| 01 | Startseite |
|
||||
| 02 | Meine Bibliothek, alle Inhaltsarten |
|
||||
| 03 | Programme |
|
||||
| 04 | Meine Lizenzen |
|
||||
| 05 | Programm mit Struktur |
|
||||
| 06 | Film im Zusammenhang mit Begleitmaterial |
|
||||
| 07 | Lizenzdetail |
|
||||
| 08 | Bibliothek gefiltert auf Filme |
|
||||
| 09 | Startseite ohne Lizenz (Leerzustand) |
|
||||
| 10 | Programm ohne Berechtigung (alle Teile „Nicht enthalten“) |
|
||||
| 11 | Film ohne Berechtigung (HTTP 403, keine Medienadresse) |
|
||||
| 12 | Lizenzen ohne Lizenz |
|
||||
|
||||
Die Entwürfe liegen unter `docs/Brand-UI-Kit/14_mitgliederbereich_v2.0/01_freigegebene_entwuerfe/`.
|
||||
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 202 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 203 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 141 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 165 KiB |
|
After Width: | Height: | Size: 133 KiB |
|
After Width: | Height: | Size: 153 KiB |
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 114 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 46 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 94 KiB |