From 1ce2e1e51f3b1c0253924259f7a57e46da3db303 Mon Sep 17 00:00:00 2001 From: Lars Date: Sun, 22 Nov 2026 19:47:15 +0100 Subject: [PATCH] =?UTF-8?q?Gib=20Paketen=20eine=20eigene=20Produktseite=20?= =?UTF-8?q?und=20erg=C3=A4nze=20Tests=20zu=20Nutzerkreis=20und=20Verkaufss?= =?UTF-8?q?tart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ein eigenständig vermarktetes Paket (offers.standalone_bundle) erhält /pakete/{id} mit seinem tatsächlichen Umfang, Shop-Kachel und Suche. Die Angebotsmaske kennt Nutzerkreis und Anzahl Trainer. Zwei Bestandstests (CartTest, Vergleich der Rechte und Erwerbsarten) legen die Vergleichsangebote jetzt als Einzellizenz an, weil der Nutzerkreis zum identischen Umfang gehört; ihre Aussagen bleiben. Eine Rechnungs- oder Stripe-Bestellung lässt sich nicht mit der Testzahlung bestätigen. Co-Authored-By: Claude Sonnet 5.5 --- app/Domain/Catalog/Offer.php | 8 + app/Domain/Catalog/OfferService.php | 11 +- app/Domain/Commerce/Cart.php | 9 +- app/Domain/Commerce/CartLine.php | 8 + app/Domain/Commerce/Checkout.php | 10 + app/Domain/Commerce/ProductOptions.php | 120 ++++++ .../Resources/Offers/Pages/ViewOffer.php | 31 +- app/Filament/Support/PublicationReadiness.php | 34 +- app/Http/Controllers/CartController.php | 12 +- .../Controllers/PublicCatalogController.php | 20 + app/Http/Controllers/ShopController.php | 23 +- ...iscounts_licence_scope_and_sales_start.php | 8 + resources/views/member/order.blade.php | 2 +- resources/views/public/package.blade.php | 21 ++ resources/views/shop/index.blade.php | 4 +- resources/views/shop/optionen.blade.php | 2 +- routes/web.php | 1 + tests/Feature/BundleProductPageTest.php | 134 +++++++ tests/Feature/CartTest.php | 5 +- tests/Feature/LicenceScopeTest.php | 221 +++++++++++ tests/Feature/SalesStartTest.php | 344 ++++++++++++++++++ 21 files changed, 997 insertions(+), 31 deletions(-) create mode 100644 resources/views/public/package.blade.php create mode 100644 tests/Feature/BundleProductPageTest.php create mode 100644 tests/Feature/LicenceScopeTest.php create mode 100644 tests/Feature/SalesStartTest.php diff --git a/app/Domain/Catalog/Offer.php b/app/Domain/Catalog/Offer.php index 360d492..8e9e2ab 100644 --- a/app/Domain/Catalog/Offer.php +++ b/app/Domain/Catalog/Offer.php @@ -12,8 +12,16 @@ class Offer extends Model 'name', 'composition_id', 'option_label', + 'standalone_bundle', ]; + protected function casts(): array + { + return [ + 'standalone_bundle' => 'boolean', + ]; + } + /** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */ public function composition(): BelongsTo { diff --git a/app/Domain/Catalog/OfferService.php b/app/Domain/Catalog/OfferService.php index 2a3ab43..064c091 100644 --- a/app/Domain/Catalog/OfferService.php +++ b/app/Domain/Catalog/OfferService.php @@ -106,6 +106,10 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of '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); @@ -182,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(); diff --git a/app/Domain/Commerce/Cart.php b/app/Domain/Commerce/Cart.php index 1e102d8..7d1ed29 100644 --- a/app/Domain/Commerce/Cart.php +++ b/app/Domain/Commerce/Cart.php @@ -64,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; } @@ -72,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 diff --git a/app/Domain/Commerce/CartLine.php b/app/Domain/Commerce/CartLine.php index ac3457a..a9b98a0 100644 --- a/app/Domain/Commerce/CartLine.php +++ b/app/Domain/Commerce/CartLine.php @@ -45,6 +45,14 @@ public function blocks(): bool public function title(): string { + if ($this->offer->standalone_bundle && $this->version !== null) { + $bundle = app(ProductOptions::class)->bundleOf($this->version); + + if ($bundle !== null) { + return (string) $bundle->name; + } + } + $composition = $this->offer->composition; return $composition !== null diff --git a/app/Domain/Commerce/Checkout.php b/app/Domain/Commerce/Checkout.php index 0837f73..73b4304 100644 --- a/app/Domain/Commerce/Checkout.php +++ b/app/Domain/Commerce/Checkout.php @@ -175,6 +175,7 @@ private function createOrder(User $user, Party $holder, array $pairs, ?CartRevie public function confirmTestPayment(Order $order, string $reference): Order { $this->assertTestDriver(); + $this->assertTestOrder($order); return $this->settle($order, 'test', $reference); } @@ -258,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); @@ -359,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') { diff --git a/app/Domain/Commerce/ProductOptions.php b/app/Domain/Commerce/ProductOptions.php index 9c540d3..76077ac 100644 --- a/app/Domain/Commerce/ProductOptions.php +++ b/app/Domain/Commerce/ProductOptions.php @@ -2,6 +2,7 @@ namespace App\Domain\Commerce; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Catalog\EditorialProfileReader; use App\Domain\Catalog\LicenceScope; @@ -38,6 +39,125 @@ public function forComposition(Composition $composition): array return $options; } + /** + * Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung + * dieses Paket verkauft. + * + * @return list> + */ + public function forBundle(Bundle $bundle): array + { + $options = []; + + foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) { + $version = $this->offers->purchasableVersion($offer); + + if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) { + $options[] = $this->describe($offer, $version); + } + } + + return $options; + } + + /** + * Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null. + */ + public function bundleOf(OfferVersion $version): ?Bundle + { + $version->loadMissing('lines.bundleVersion.bundle'); + + return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle; + } + + /** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */ + public function groupKey(Offer $offer): ?string + { + if ($offer->composition_id !== null) { + return 'c:'.$offer->composition_id; + } + + if ($offer->standalone_bundle) { + $version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first(); + $bundle = $version === null ? null : $this->bundleOf($version); + + return $bundle === null ? null : 'b:'.$bundle->id; + } + + return null; + } + + /** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */ + public function pageUrl(Offer $offer): ?string + { + if ($offer->composition_id !== null) { + return route('public.program', $offer->composition_id); + } + + $key = $this->groupKey($offer); + + return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null; + } + + /** + * Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen. + * + * @return array + */ + public function bundleSummaries(): array + { + $summary = []; + + foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) { + $version = $this->offers->purchasableVersion($offer); + $bundle = $version === null ? null : $this->bundleOf($version); + + if ($bundle === null) { + continue; + } + + $current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0]; + $summary[$bundle->id] = [ + 'from_cents' => min($current['from_cents'], (int) $version->price_cents), + 'count' => $current['count'] + 1, + ]; + } + + return $summary; + } + + /** + * Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der + * Optionen, mit Name und Kurzbeschreibung aus der Redaktion. + * + * @param list> $options + * @return list + */ + public function bundleContents(array $options): array + { + $contents = []; + + foreach ($options as $option) { + $option['version']->loadMissing('resolvedScopes.article'); + + foreach ($option['version']->resolvedScopes as $item) { + $article = $item->article; + + if ($article === null || isset($contents[$article->id])) { + continue; + } + + $profile = app(EditorialProfileReader::class)->read($article, 'detail'); + $contents[$article->id] = [ + 'title' => $this->articleTitle($article), + 'teaser' => trim((string) ($profile->value('teaser') ?? '')), + ]; + } + } + + return array_values($contents); + } + /** * Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option. * diff --git a/app/Filament/Resources/Offers/Pages/ViewOffer.php b/app/Filament/Resources/Offers/Pages/ViewOffer.php index 54a03ae..079fe8c 100644 --- a/app/Filament/Resources/Offers/Pages/ViewOffer.php +++ b/app/Filament/Resources/Offers/Pages/ViewOffer.php @@ -7,6 +7,7 @@ use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionVersion; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; @@ -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.'], ], ]; } diff --git a/app/Filament/Support/PublicationReadiness.php b/app/Filament/Support/PublicationReadiness.php index 94c5953..05c1f1d 100644 --- a/app/Filament/Support/PublicationReadiness.php +++ b/app/Filament/Support/PublicationReadiness.php @@ -227,7 +227,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 +259,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 + ? \App\Domain\Catalog\LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.' + : 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'), + 'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen', + 'aktion' => $hasActive && $active->licence_scope === null ? $activate : null, + 'pflicht' => false, + ], [ 'titel' => 'Produktseite zuordnen', - 'text' => $page !== null - ? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.' - : 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket braucht eine eigene Produktseite, sonst ist es Alternative zu den Einzelangeboten dieser Seite.', - 'stand' => $page !== null ? 'erledigt' : 'offen', - 'aktion' => $page !== null ? null : $activate, + 'text' => $own + ? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.' + : ($page !== null + ? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.' + : 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'), + 'stand' => $own || $page !== null ? 'erledigt' : 'offen', + 'aktion' => $own || $page !== null ? null : $activate, ], [ 'titel' => 'Produktseite öffentlich', - 'text' => $page === null + 'text' => ! $own && $page === null ? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.' - : ($shown + : ($own + ? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.' + : ($shown ? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.' - : 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.'), + : 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')), 'stand' => $shown ? 'erledigt' : 'offen', 'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)], ], diff --git a/app/Http/Controllers/CartController.php b/app/Http/Controllers/CartController.php index 51efd3e..7b5eb7d 100644 --- a/app/Http/Controllers/CartController.php +++ b/app/Http/Controllers/CartController.php @@ -7,6 +7,7 @@ use App\Domain\Commerce\Cart; use App\Domain\Commerce\Money; use App\Domain\Commerce\OrderHolders; +use App\Domain\Commerce\ProductOptions; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\View\View; @@ -31,9 +32,8 @@ public function show(Request $request, Cart $cart, OrderHolders $holders): View public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse { $page = $offer->composition; - $result = $page !== null && $catalog->shownVersion($page) !== null - ? $cart->add($offer) - : Cart::UNAVAILABLE; + $listed = $offer->standalone_bundle || ($page !== null && $catalog->shownVersion($page) !== null); + $result = $listed ? $cart->add($offer) : Cart::UNAVAILABLE; $back = $this->productPage($offer); return match ($result) { @@ -81,8 +81,8 @@ public function accept(Offer $offer, Cart $cart): RedirectResponse private function productPage(Offer $offer): RedirectResponse { - return $offer->composition_id !== null - ? redirect()->route('public.program', $offer->composition_id) - : redirect()->route('cart'); + $url = app(ProductOptions::class)->pageUrl($offer); + + return $url !== null ? redirect()->to($url) : redirect()->route('cart'); } } diff --git a/app/Http/Controllers/PublicCatalogController.php b/app/Http/Controllers/PublicCatalogController.php index b746bf9..d20fab9 100644 --- a/app/Http/Controllers/PublicCatalogController.php +++ b/app/Http/Controllers/PublicCatalogController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Catalog\CompositionStructureReader; use App\Domain\Cms\Catalog\PublicCatalogReader; @@ -17,6 +18,25 @@ public function index(PublicCatalogReader $catalog): View return view('public.programs', ['programs' => $catalog->publicPrograms()]); } + /** + * Eigene Produktseite eines Pakets, das für sich vermarktet wird: Sie zeigt den tatsächlichen Umfang des Pakets + * (die enthaltenen Artikel) und darunter die kaufbaren Lizenzoptionen. Ohne kaufbare Option gibt es sie nicht. + */ + public function package(Bundle $bundle, ProductOptions $products, Cart $cart): View + { + abort_unless(Shop::enabled(), 404); + $options = $products->forBundle($bundle); + abort_if($options === [], 404); + + return view('public.package', [ + 'bundle' => $bundle, + 'contents' => $products->bundleContents($options), + 'options' => $options, + 'cart' => $cart, + 'switchTo' => session('shop.switch'), + ]); + } + public function program(Composition $composition, PublicCatalogReader $catalog, ProductOptions $products, Cart $cart): View { $version = $catalog->shownVersion($composition); diff --git a/app/Http/Controllers/ShopController.php b/app/Http/Controllers/ShopController.php index dadab27..92901f6 100644 --- a/app/Http/Controllers/ShopController.php +++ b/app/Http/Controllers/ShopController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Commerce\Money; @@ -37,7 +38,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR $summary = $summaries[$composition->id]; $cards[] = [ - 'composition' => $composition, + 'url' => route('public.program', $composition), 'title' => $title, 'teaser' => (string) ($composition->teaser ?: $composition->summary), 'from' => Money::format($summary['from_cents']), @@ -45,6 +46,26 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR ]; } + // Pakete mit eigener Produktseite: gelistet mit Name und enthaltenen Artikeln. + foreach (Bundle::query()->whereIn('id', array_keys($products->bundleSummaries()))->orderBy('name')->get() as $bundle) { + $options = $products->forBundle($bundle); + $contents = $products->bundleContents($options); + $names = implode(', ', array_column($contents, 'title')); + + if ($term !== '' && ! str_contains(mb_strtolower($bundle->name.' '.$names), mb_strtolower($term))) { + continue; + } + + $summary = $products->bundleSummaries()[$bundle->id]; + $cards[] = [ + 'url' => route('public.package', $bundle), + 'title' => (string) $bundle->name, + 'teaser' => 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : ''), + 'from' => Money::format($summary['from_cents']), + 'count' => $summary['count'], + ]; + } + return view('shop.index', ['cards' => $cards, 'term' => $term]); } } diff --git a/database/migrations/2026_11_24_100000_add_discounts_licence_scope_and_sales_start.php b/database/migrations/2026_11_24_100000_add_discounts_licence_scope_and_sales_start.php index 09e7169..e45b327 100644 --- a/database/migrations/2026_11_24_100000_add_discounts_licence_scope_and_sales_start.php +++ b/database/migrations/2026_11_24_100000_add_discounts_licence_scope_and_sales_start.php @@ -13,6 +13,7 @@ * - 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 { @@ -59,6 +60,10 @@ public function up(): void $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(); @@ -106,6 +111,9 @@ public function down(): void 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'); diff --git a/resources/views/member/order.blade.php b/resources/views/member/order.blade.php index c7f6013..8ed534b 100644 --- a/resources/views/member/order.blade.php +++ b/resources/views/member/order.blade.php @@ -62,7 +62,7 @@ @endif - @if ($testPayment && $order->status === 'offen') + @if ($testPayment && $order->status === 'offen' && ! $invoiceOrder && $order->payment_method !== 'stripe')
@csrf diff --git a/resources/views/public/package.blade.php b/resources/views/public/package.blade.php new file mode 100644 index 0000000..ea337e4 --- /dev/null +++ b/resources/views/public/package.blade.php @@ -0,0 +1,21 @@ +@extends('layouts.site') + +@section('title', $bundle->name) + +@section('content') +

Shop

+

{{ $bundle->name }}

+

Ein Paket mit {{ count($contents) }} {{ count($contents) === 1 ? 'Inhalt' : 'Inhalten' }}. Es wird nur zusammen gekauft.

+
+

Das ist im Paket enthalten

+
    + @foreach ($contents as $item) +
  • + {{ $item['title'] }} + @if ($item['teaser'] !== ''){{ $item['teaser'] }}@endif +
  • + @endforeach +
+
+ @include('shop.optionen', ['options' => $options, 'cart' => $cart, 'switchTo' => $switchTo]) +@endsection diff --git a/resources/views/shop/index.blade.php b/resources/views/shop/index.blade.php index 13123d3..974ff4b 100644 --- a/resources/views/shop/index.blade.php +++ b/resources/views/shop/index.blade.php @@ -4,7 +4,7 @@ @section('content')

Shop

-

Hier findest du kaufbare Programme. Jede Kachel öffnet die Produktseite mit Inhalt und den verfügbaren Lizenzoptionen.

+

Hier findest du kaufbare Programme und Pakete. Jede Kachel öffnet die Produktseite mit Inhalt und den verfügbaren Lizenzoptionen.

@@ -25,7 +25,7 @@
    @foreach ($cards as $card)
  • -

    {{ $card['title'] }}

    +

    {{ $card['title'] }}

    @if ($card['teaser'] !== '')

    {{ $card['teaser'] }}

    @endif

    ab {{ $card['from'] }} · {{ $card['count'] }} {{ $card['count'] === 1 ? 'Lizenzoption' : 'Lizenzoptionen' }}

  • diff --git a/resources/views/shop/optionen.blade.php b/resources/views/shop/optionen.blade.php index 59d1802..e8f5565 100644 --- a/resources/views/shop/optionen.blade.php +++ b/resources/views/shop/optionen.blade.php @@ -25,7 +25,7 @@ @csrf - Bei „{{ $current->optionName() }}“ bleiben + Bei „{{ $current->optionName() }}“ bleiben @endif diff --git a/routes/web.php b/routes/web.php index bf0d6a6..ce12137 100644 --- a/routes/web.php +++ b/routes/web.php @@ -26,6 +26,7 @@ Route::get('/themen', [ThemeController::class, 'index'])->name('themes'); Route::get('/programme', [PublicCatalogController::class, 'index'])->name('public.programs'); Route::get('/programme/{composition}', [PublicCatalogController::class, 'program'])->name('public.program'); +Route::get('/pakete/{bundle}', [PublicCatalogController::class, 'package'])->whereNumber('bundle')->name('public.package'); Route::get('/themen/{slug}', [ThemeController::class, 'show'])->name('theme')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); Route::get('/medien/{path}', [PublicMediaController::class, 'show'])->where('path', '.*')->name('media.public'); Route::get('/website-medien/{element}', [WebsiteMediaController::class, 'show'])->whereNumber('element')->name('website.media'); diff --git a/tests/Feature/BundleProductPageTest.php b/tests/Feature/BundleProductPageTest.php new file mode 100644 index 0000000..42f310a --- /dev/null +++ b/tests/Feature/BundleProductPageTest.php @@ -0,0 +1,134 @@ +seedShop(); + } + + private function bundle(): Bundle + { + return Bundle::query()->where('name', 'Starterpaket')->firstOrFail(); + } + + private function standaloneOffer(string $name, int $cents, string $scope = 'einzel', ?int $trainers = null): Offer + { + $version = $this->bundle()->versions()->firstOrFail(); + $rights = app(OfferService::class)->currentActiveVersion($this->privateKonflikte())->lines()->first()->rights; + $offers = app(OfferService::class); + $offer = $offers->create($name); + $offers->assignProduct($offer, null, $name, true); + $offers->activate($offer, [['target' => $version, 'rights' => $rights]], [ + 'grant_kind' => 'kauf', 'price_cents' => $cents, 'holder_kind' => 'person', 'licence_scope' => $scope, 'trainer_count' => $trainers, + ]); + + return $offer->refresh(); + } + + public function test_the_package_page_shows_what_the_package_actually_contains(): void + { + $this->standaloneOffer('Starterpaket solo', 5500); + + $this->get(route('public.package', $this->bundle())) + ->assertOk() + ->assertSee('Starterpaket') + ->assertSee('Das ist im Paket enthalten') + ->assertSee('Konflikte im Training') + ->assertSee('Grenzen setzen im Verein') + ->assertSee('Starterpaket für neue Trainer') + ->assertSee('Ein Paket mit 3 Inhalten') + ->assertSee('55,00 €') + ->assertSee('Einzellizenz · 1 Trainer') + ->assertSee('In den Warenkorb'); + } + + public function test_the_shop_lists_the_package_with_its_contents_and_finds_it_by_a_content_name(): void + { + $this->standaloneOffer('Starterpaket solo', 5500); + + $this->get(route('shop'))->assertOk() + ->assertSee(route('public.package', $this->bundle()), false) + ->assertSee('Paket mit 3 Inhalten') + ->assertSee('ab 55,00 €'); + $this->get(route('shop', ['suche' => 'Grenzen setzen']))->assertSee(route('public.package', $this->bundle()), false); + $this->get(route('shop', ['suche' => 'gibtesnicht']))->assertDontSee(route('public.package', $this->bundle()), false); + } + + public function test_the_package_offer_is_added_under_the_package_name_and_alternatives_need_a_switch(): void + { + $first = $this->standaloneOffer('Starterpaket Einzel', 5500); + $second = $this->standaloneOffer('Starterpaket Mehrfach', 9900, 'mehrfach', 3); + $tina = $this->tina(); + + $this->actingAs($tina)->post(route('cart.add', $first))->assertRedirect(route('public.package', $this->bundle())); + $this->post(route('cart.add', $second))->assertSessionHas('shop.switch', $second->id); + + $cart = app(Cart::class); + $review = $cart->review($tina); + $this->assertSame(CartLine::OK, $review->lines[0]->state); + $this->assertSame('Starterpaket', $review->lines[0]->title()); + $this->assertSame($first->id, $cart->alternativeTo($second)?->id); + + $this->post(route('cart.switch', $second))->assertRedirect(route('cart')); + $this->get(route('cart'))->assertSee('Mehrfachlizenz · bis zu 3 Trainer')->assertDontSee('Starterpaket Einzel'); + } + + public function test_the_package_page_is_gone_without_a_purchasable_option(): void + { + $offer = $this->standaloneOffer('Starterpaket solo', 5500); + $this->get(route('public.package', $this->bundle()))->assertOk(); + + app(OfferService::class)->end($offer); + + $this->get(route('public.package', $this->bundle()))->assertNotFound(); + $this->get(route('shop'))->assertDontSee(route('public.package', $this->bundle()), false); + } + + public function test_an_offer_with_an_own_package_page_consists_of_exactly_one_package_version(): void + { + $offers = app(OfferService::class); + $offer = $offers->create('Falsch'); + $offers->assignProduct($offer, null, 'Falsch', true); + $rights = $offers->currentActiveVersion($this->privateKonflikte())->lines()->first()->rights; + + $this->expectException(DomainRuleException::class); + $offers->activate($offer, [['target' => $this->article('shop-konflikte'), 'rights' => $rights]], ['grant_kind' => 'kauf', 'price_cents' => 1000]); + } + + public function test_a_package_has_either_an_own_page_or_a_program_page(): void + { + $offer = app(OfferService::class)->create('Beides'); + + $this->expectException(DomainRuleException::class); + app(OfferService::class)->assignProduct($offer, $this->program('Konflikte im Training')->id, 'Beides', true); + } + + public function test_the_package_page_does_not_exist_outside_the_shop(): void + { + $this->standaloneOffer('Starterpaket solo', 5500); + $this->app['env'] = 'production'; + + $this->get(route('public.package', $this->bundle()))->assertNotFound(); + } +} diff --git a/tests/Feature/CartTest.php b/tests/Feature/CartTest.php index 7c3f7bd..4d87828 100644 --- a/tests/Feature/CartTest.php +++ b/tests/Feature/CartTest.php @@ -3,6 +3,7 @@ namespace Tests\Feature; use App\Domain\Catalog\CompositionVersionDisplayEvent; +use App\Domain\Catalog\LicenceScope; use App\Domain\Catalog\Offer; use App\Domain\Catalog\OfferService; use App\Domain\Commerce\Cart; @@ -293,7 +294,7 @@ public function test_the_rights_order_does_not_matter_when_comparing_owned_scope ]); $this->ownByPurchase($tina, $this->privateGrenzen()); $same = $offers->create('Grenzen gleiche Rechte'); - $offers->activate($same, [['target' => $this->article('shop-grenzen'), 'rights' => $reordered]], ['grant_kind' => 'kauf', 'price_cents' => 1900]); + $offers->activate($same, [['target' => $this->article('shop-grenzen'), 'rights' => $reordered]], ['grant_kind' => 'kauf', 'price_cents' => 1900, 'licence_scope' => LicenceScope::SINGLE]); $cart = app(Cart::class); $cart->add($same); @@ -310,7 +311,7 @@ public function test_free_grants_and_manual_grants_count_as_owned_but_expired_or 'pdf' => ['ansehen', 'laden'], ]); $free = $offers->create('Grenzen gratis'); - $offers->activate($free, [['target' => $this->article('shop-grenzen'), 'rights' => $rights]], ['grant_kind' => 'auf_abruf']); + $offers->activate($free, [['target' => $this->article('shop-grenzen'), 'rights' => $rights]], ['grant_kind' => 'auf_abruf', 'licence_scope' => LicenceScope::SINGLE]); $acquisition = app(GrantIssuer::class)->claim($tina, $free); $cart = app(Cart::class); diff --git a/tests/Feature/LicenceScopeTest.php b/tests/Feature/LicenceScopeTest.php new file mode 100644 index 0000000..b534ace --- /dev/null +++ b/tests/Feature/LicenceScopeTest.php @@ -0,0 +1,221 @@ +seedShop(); + } + + /** + * Eine weitere Option mit denselben Positionen und Rechten wie die Quelle. + * + * @param array $attributes + */ + private function variant(Offer $source, string $name, array $attributes): Offer + { + $active = app(OfferService::class)->currentActiveVersion($source); + $lines = $active->lines()->with('article', 'bundleVersion', 'rights')->get()->map(fn ($line): array => [ + 'target' => $line->article ?? $line->bundleVersion, + 'rights' => $line->rights, + ])->all(); + $offer = app(OfferService::class)->create($name); + app(OfferService::class)->activate($offer, $lines, [ + 'grant_kind' => 'kauf', + 'price_cents' => 4900, + 'holder_kind' => $active->holder_kind, + ...$attributes, + ]); + $offer->update(['composition_id' => $source->composition_id]); + + return $offer->refresh(); + } + + public function test_the_scope_is_validated_when_a_version_is_activated(): void + { + $source = $this->privateKonflikte(); + + foreach ([ + ['licence_scope' => 'einzel', 'trainer_count' => 3], + ['licence_scope' => 'mehrfach', 'trainer_count' => 1], + ['licence_scope' => 'mehrfach', 'trainer_count' => null], + ['licence_scope' => 'mehrfach', 'trainer_count' => 100000], + ['licence_scope' => null, 'trainer_count' => 4], + ['licence_scope' => 'gruppe', 'trainer_count' => 2], + ] as $attributes) { + try { + $this->variant($source, 'Ungültig', $attributes); + $this->fail('Ungültiger Nutzerkreis muss abgewiesen werden: '.json_encode($attributes)); + } catch (DomainRuleException) { + $this->assertNull(Offer::query()->where('name', 'Ungültig')->first()?->versions()->where('status', 'aktiv')->first()); + } + } + } + + public function test_a_single_license_always_means_exactly_one_trainer(): void + { + $offer = $this->variant($this->privateKonflikte(), 'Einzel ohne Zahl', ['licence_scope' => 'einzel']); + + $version = app(OfferService::class)->currentActiveVersion($offer); + + $this->assertSame('einzel', $version->licence_scope); + $this->assertSame(1, $version->trainer_count); + } + + public function test_the_scope_is_not_derived_from_purpose_price_or_discount(): void + { + $institutional = app(OfferService::class)->currentActiveVersion($this->clubKonflikte())->lines()->first()->rights; + $this->assertSame('institutionell', $institutional->purpose); + + $single = $this->variant($this->clubKonflikte(), 'Institutionell, ein Trainer', ['licence_scope' => 'einzel', 'holder_kind' => 'organisation', 'price_cents' => 99900]); + $legacy = $this->variant($this->privateGrenzen(), 'Ohne Angabe', ['price_cents' => 1900]); + + $this->assertSame('Einzellizenz · 1 Trainer', LicenceScope::label($single->versions()->first()->licence_scope, $single->versions()->first()->trainer_count)); + $this->assertNull($legacy->versions()->first()->licence_scope, 'Ohne Angabe bleibt es ohne Angabe, auch bei anderem Preis oder Zweck.'); + $this->assertNull($legacy->versions()->first()->trainer_count); + } + + public function test_the_product_page_tells_single_and_multi_licenses_apart(): void + { + $page = $this->program('Konflikte im Training'); + $this->variant($this->privateKonflikte(), 'Ohne Angabe', ['price_cents' => 1900]); + + $this->get(route('public.program', $page)) + ->assertOk() + ->assertSee('Nutzerkreis') + ->assertSee('Einzellizenz · 1 Trainer') + ->assertSee('Mehrfachlizenz · bis zu 5 Trainer') + ->assertSee('Die Inhalte dürfen von einem Trainer eingesetzt werden.') + ->assertSee('Die Inhalte dürfen von bis zu 5 Trainern eingesetzt werden.') + ->assertSee('Nutzerkreis nicht festgelegt'); + } + + public function test_cart_checkout_and_order_show_the_scope_and_keep_the_agreed_one(): void + { + $tina = $this->tina(); + $offer = $this->privateKonflikte(); + + $this->actingAs($tina)->post(route('cart.add', $offer)); + $this->get(route('cart'))->assertSee('Einzellizenz · 1 Trainer'); + $this->get(route('checkout'))->assertSee('Einzellizenz · 1 Trainer'); + + $order = $this->orderOf($tina, [$offer]); + $line = $order->lines->first(); + $this->assertSame('einzel', $line->licence_scope); + $this->assertSame(1, $line->trainer_count); + + app(Checkout::class)->confirmTestPayment($order, 'test-scope'); + $conditions = Acquisition::query()->where('reference_type', 'order_line')->firstOrFail()->conditions; + $this->assertSame('einzel', $conditions['licence_scope']); + $this->assertSame(1, $conditions['trainer_count']); + + // Eine spätere Fassung mit anderem Nutzerkreis ändert den gekauften Umfang nicht. + $lines = app(OfferService::class)->currentActiveVersion($offer)->lines()->with('article', 'rights')->get()->map(fn ($l): array => ['target' => $l->article, 'rights' => $l->rights])->all(); + app(OfferService::class)->activate($offer, $lines, ['grant_kind' => 'kauf', 'price_cents' => 4900, 'licence_scope' => 'mehrfach', 'trainer_count' => 3]); + + $this->assertSame('einzel', $line->fresh()->licence_scope); + $this->assertSame('einzel', Acquisition::query()->where('reference_type', 'order_line')->firstOrFail()->conditions['licence_scope']); + $this->get(route('member.order', $order))->assertOk()->assertSee('Einzellizenz · 1 Trainer')->assertDontSee('bis zu 3 Trainer'); + } + + public function test_a_club_purchase_keeps_the_club_as_holder_and_only_the_ordering_account_downloads(): void + { + $vera = $this->vera(); + $order = $this->orderOf($vera, [$this->clubKonflikte()], $this->club()->id); + app(Checkout::class)->confirmTestPayment($order, 'test-club'); + $order = $order->fresh(['lines']); + + $this->assertSame($this->club()->id, $order->party_id, 'Lizenzinhaber ist der Verein.'); + $this->assertSame($vera->id, $order->user_id, 'Das bestellende Konto bleibt davon getrennt festgehalten.'); + $this->assertSame('mehrfach', $order->lines->first()->licence_scope); + $this->assertSame(5, $order->lines->first()->trainer_count); + + $acquisition = Acquisition::query()->where('reference_type', 'order_line')->firstOrFail(); + $this->assertSame($this->club()->id, $acquisition->party_id); + $this->assertSame($vera->id, $acquisition->acting_user_id); + $this->assertSame(5, $acquisition->conditions['trainer_count']); + $this->assertSame(1, Acquisition::query()->count(), 'Eine Mehrfachlizenz erzeugt zum Start keine weiteren Downloadkonten.'); + + $this->assertTrue(Grant::query()->usableBy($vera)->exists()); + $this->assertFalse(Grant::query()->usableBy($this->max())->exists()); + $this->assertFalse(Grant::query()->usableBy($this->tina())->exists()); + + $this->actingAs($vera)->get(route('member.order', $order))->assertOk() + ->assertSee('Testverein Musterstadt e. V.') + ->assertSee('Mehrfachlizenz · bis zu 5 Trainer'); + } + + public function test_an_owned_single_license_does_not_cover_a_multi_license_with_the_same_rights(): void + { + $tina = $this->tina(); + $owned = $this->privateKonflikte(); + $order = $this->orderOf($tina, [$owned]); + app(Checkout::class)->confirmTestPayment($order, 'test-own'); + + $multi = $this->variant($owned, 'Konflikte Mehrfach 3', ['licence_scope' => 'mehrfach', 'trainer_count' => 3]); + $single = $this->variant($owned, 'Konflikte Einzel nochmal', ['licence_scope' => 'einzel']); + $cart = app(Cart::class); + $cart->clear(); + + $cart->add($multi); + $this->assertSame(CartLine::OK, $cart->review($tina)->lines[0]->state, 'Eine Einzellizenz macht eine Mehrfachlizenz nicht zur „bereits erworben“.'); + + $cart->clear(); + $cart->add($single); + $this->assertSame(CartLine::OWNED, $cart->review($tina)->lines[0]->state); + } + + public function test_an_offer_without_published_content_cannot_be_activated(): void + { + $empty = app(ArticleService::class)->create('leer-ohne-stand'); + $rights = app(OfferService::class)->currentActiveVersion($this->privateKonflikte())->lines()->first()->rights; + $offers = app(OfferService::class); + $offer = $offers->create('Ohne Inhalt'); + + try { + $offers->activate($offer, [['target' => $empty, 'rights' => $rights]], ['grant_kind' => 'kauf', 'price_cents' => 1000]); + $this->fail('Ein Artikel ohne veröffentlichten Stand darf nicht verkauft werden.'); + } catch (DomainRuleException $exception) { + $this->assertStringContainsString('leer-ohne-stand', $exception->getMessage()); + $this->assertStringContainsString('keinen veröffentlichten Stand', $exception->getMessage()); + } + + $bundles = app(BundleService::class); + $bundle = $bundles->publish($bundles->create('Leeres Paket'), [$empty]); + + try { + $offers->activate($offer, [['target' => $bundle, 'rights' => $rights]], ['grant_kind' => 'kauf', 'price_cents' => 1000]); + $this->fail('Auch ein Paket mit einem Artikel ohne Stand darf nicht verkauft werden.'); + } catch (DomainRuleException) { + $this->assertSame(0, $offer->versions()->count(), 'Es entsteht keine halbe Fassung.'); + } + + $offers->activate($offer, [['target' => $this->article('shop-konflikte'), 'rights' => $rights]], ['grant_kind' => 'kauf', 'price_cents' => 1000]); + $this->assertSame(1, $offer->versions()->count()); + } +} diff --git a/tests/Feature/SalesStartTest.php b/tests/Feature/SalesStartTest.php new file mode 100644 index 0000000..27b3ef4 --- /dev/null +++ b/tests/Feature/SalesStartTest.php @@ -0,0 +1,344 @@ +seedShop(); + $this->travelTo('2026-11-24 10:00:00'); + } + + private function publishLegalPage(string $path): void + { + $page = Page::query()->firstOrCreate(['path' => $path]); + $revision = PageRevision::query()->create(['page_id' => $page->id, 'blocks' => [], 'sections' => [], 'seo_title' => ltrim($path, '/')]); + $page->published_revision_id = $revision->id; + $page->save(); + } + + private function checkoutDigest(): string + { + $page = $this->get(route('checkout'))->assertOk(); + preg_match('/name="digest" value="([a-f0-9]{64})"/', $page->getContent(), $match); + $this->assertNotEmpty($match, 'Die Bestellübersicht muss bestellbar sein.'); + + return $match[1]; + } + + public function test_the_checkout_shows_the_mandatory_information_and_the_order_button(): void + { + $this->actingAs($this->tina())->post(route('cart.add', $this->privateKonflikte())); + $this->publishLegalPage('/agb'); + + $this->get(route('checkout'))->assertOk() + ->assertSee('Zahlungspflichtig bestellen') + ->assertSee('Dein Vertrag') + ->assertSee('Allgemeine Geschäftsbedingungen') + ->assertSee('Widerrufsbelehrung (noch nicht veröffentlicht)') + ->assertSee('Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird') + ->assertSee('Mir ist bekannt, dass ich mein Widerrufsrecht verliere') + ->assertSee('Testbetrieb') + ->assertSee('Entwurf: Der Wortlaut der Zustimmungen ist noch nicht rechtlich geprüft.') + ->assertSee('Es fehlen veröffentlichte Seiten') + ->assertSee(url('/agb'), false); + } + + public function test_an_order_needs_both_consents_and_keeps_the_proof(): void + { + $tina = $this->tina(); + $this->actingAs($tina)->post(route('cart.add', $this->privateKonflikte())); + $digest = $this->checkoutDigest(); + + $this->post(route('checkout.place'), ['digest' => $digest])->assertSessionHasErrors('checkout'); + $this->post(route('checkout.place'), ['digest' => $digest, 'zustimmung' => ['agb' => '1']])->assertSessionHasErrors('checkout'); + $this->assertSame(0, Order::query()->count(), 'Ohne beide Zustimmungen entsteht keine Bestellung.'); + + $this->post(route('checkout.place'), ['digest' => $digest, ...$this->consentFields()])->assertRedirect(); + $order = Order::query()->firstOrFail(); + + $this->assertSame($tina->id, $order->user_id); + $this->assertSame('2026-11-24 10:00:00', $order->terms_accepted_at->format('Y-m-d H:i:s')); + $this->assertSame(SalesTerms::VERSION, $order->terms_snapshot['version']); + $this->assertSame(SalesTerms::consents()['sofort'], $order->terms_snapshot['consents']['sofort']); + $this->assertSame(SalesTerms::consents()['agb'], $order->terms_snapshot['consents']['agb']); + $this->assertArrayHasKey('widerruf', $order->terms_snapshot['pages']); + } + + public function test_the_confirmation_mail_repeats_scope_discount_and_consent(): void + { + Mail::fake(); + app(DiscountService::class)->save(['code' => 'SOMMER10', 'label' => 'Sommer', 'kind' => 'prozent', 'percent' => 10, 'scope' => 'warenkorb', 'eligibility' => 'allgemein'], []); + $tina = $this->tina(); + $cart = app(\App\Domain\Commerce\Cart::class); + $cart->add($this->privateKonflikte()); + $cart->applyCode('SOMMER10', $tina); + $order = app(Checkout::class)->placeFromCart($tina, $cart, null, $cart->review($tina)->digest(), ['agb' => 1, 'sofort' => 1]); + + app(Checkout::class)->confirmTestPayment($order, 'test-mail'); + + Mail::assertSent(OrderConfirmed::class, function (OrderConfirmed $mail): bool { + $text = $mail->render(); + + return str_contains($text, 'Vertragsbestätigung') + && str_contains($text, 'Einzellizenz · 1 Trainer') + && str_contains($text, 'Rabattcode SOMMER10') + && str_contains($text, 'Gezahlter Betrag: 44,10 €') + && str_contains($text, 'Mir ist bekannt, dass ich mein Widerrufsrecht verliere'); + }); + } + + public function test_the_order_page_shows_discount_and_payable_amount_and_stripe_receives_the_discounted_amount(): void + { + config([ + 'services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_test_nur_fuer_tests', + 'services.stripe.webhook_secret' => 'whsec_x', 'services.stripe.api_base' => 'https://stripe.test', + ]); + app(DiscountService::class)->save(['code' => 'SOMMER10', 'label' => 'Sommer', 'kind' => 'prozent', 'percent' => 10, 'scope' => 'warenkorb', 'eligibility' => 'allgemein'], []); + $tina = $this->tina(); + $cart = app(\App\Domain\Commerce\Cart::class); + $cart->add($this->privateKonflikte()); + $cart->add($this->privateGrenzen()); + $cart->applyCode('SOMMER10', $tina); + $order = app(Checkout::class)->placeFromCart($tina, $cart, null, $cart->review($tina)->digest(), ['agb' => 1, 'sofort' => 1]); + Http::fake(['stripe.test/v1/checkout/sessions' => Http::response(['id' => 'cs_test_d', 'url' => 'https://checkout.stripe.test/c/pay/cs_test_d'])]); + + $this->actingAs($tina)->get(route('member.order', $order))->assertOk() + ->assertSee('Zu zahlen')->assertSee('70,20 €')->assertSee('Rabattcode')->assertSee('SOMMER10')->assertSee('−7,80 €'); + $this->post(route('member.order.pay', $order))->assertRedirect('https://checkout.stripe.test/c/pay/cs_test_d'); + + Http::assertSent(function (HttpRequest $request): bool { + parse_str($request->body(), $body); + + return (int) $body['line_items'][0]['price_data']['unit_amount'] === 4410 + && (int) $body['line_items'][1]['price_data']['unit_amount'] === 2610 + && str_contains((string) $body['line_items'][0]['price_data']['product_data']['description'], 'Listenpreis 49,00 €'); + }); + + // Die Summe bei Stripe ist der gespeicherte Zahlbetrag; der Listenpreis wird nicht akzeptiert. + $checkout = app(Checkout::class); + try { + $checkout->confirmProviderPayment($order, 'stripe', 'cs_test_d', 7800, 'eur'); + $this->fail('Der Listenpreis weicht vom Zahlbetrag ab.'); + } catch (DomainRuleException) { + $this->assertSame('offen', $order->fresh()->status); + $this->assertSame(0, Acquisition::query()->count()); + } + + $checkout->confirmProviderPayment($order, 'stripe', 'cs_test_d', 7020, 'eur'); + $checkout->confirmProviderPayment($order, 'stripe', 'cs_test_d', 7020, 'eur'); + $this->assertSame('bezahlt', $order->fresh()->status); + $this->assertSame(2, Acquisition::query()->count(), 'Eine wiederholte Bestätigung schaltet nichts doppelt frei.'); + } + + public function test_a_club_can_order_on_invoice_and_only_the_operator_confirms_the_payment(): void + { + $vera = $this->vera(); + $this->actingAs($vera)->post(route('cart.add', $this->clubKonflikte())); + + $this->get(route('checkout'))->assertOk()->assertSee('Auf Rechnung (Überweisung, auf Anfrage)'); + $this->post(route('checkout.place'), ['digest' => $this->checkoutDigest(), 'zahlungsweg' => 'rechnung', ...$this->consentFields()])->assertRedirect(); + $order = Order::query()->firstOrFail(); + + $this->assertSame('rechnung', $order->payment_method); + $this->assertSame('offen', $order->status); + $this->assertSame($this->club()->id, $order->party_id); + $this->get(route('member.order', $order))->assertOk() + ->assertSee('Wir erstellen die Rechnung manuell') + ->assertDontSee('Testzahlung bestätigen') + ->assertDontSee('Jetzt bezahlen'); + $this->post(route('member.order.confirm', $order))->assertSessionHasErrors('payment'); + $this->assertSame('offen', $order->fresh()->status, 'Das Mitglied kann den Zahlungseingang nicht selbst bestätigen.'); + $this->assertFalse(Grant::query()->usableBy($vera)->exists()); + + app(Checkout::class)->confirmInvoicePayment($order, 'RE-2026-001', $this->tina()); + app(Checkout::class)->confirmInvoicePayment($order, 'RE-2026-001', $this->tina()); + + $this->assertSame('bezahlt', $order->fresh()->status); + $this->assertSame('ueberweisung', $order->payments()->firstOrFail()->provider); + $this->assertSame(1, Acquisition::query()->count()); + $this->assertTrue(Grant::query()->usableBy($vera)->exists()); + $this->assertFalse(Grant::query()->usableBy($this->max())->exists()); + } + + public function test_a_private_buyer_cannot_order_on_invoice_and_a_test_order_cannot_be_confirmed_as_invoice(): void + { + $tina = $this->tina(); + $this->actingAs($tina)->post(route('cart.add', $this->privateKonflikte())); + $this->get(route('checkout'))->assertOk()->assertDontSee('Auf Rechnung'); + + $this->post(route('checkout.place'), ['digest' => $this->checkoutDigest(), 'zahlungsweg' => 'rechnung', ...$this->consentFields()])->assertSessionHasErrors('checkout'); + $this->assertSame(0, Order::query()->count()); + + $order = $this->orderOf($tina, [$this->privateKonflikte()]); + $this->expectException(DomainRuleException::class); + app(Checkout::class)->confirmInvoicePayment($order, 'RE-1', $this->vera()); + } + + public function test_a_paid_stripe_order_is_refunded_at_stripe_before_rights_are_revoked(): void + { + config(['services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_test_nur_fuer_tests', 'services.stripe.api_base' => 'https://stripe.test']); + $order = $this->orderOf($this->tina(), [$this->privateKonflikte(), $this->privateGrenzen()]); + app(Checkout::class)->confirmProviderPayment($order, 'stripe', 'cs_test_r', 7800, 'eur'); + $order->payments()->update(['provider_payment_ref' => 'pi_test_r']); + Http::fake(['stripe.test/v1/refunds' => Http::response(['id' => 're_1', 'status' => 'succeeded'])]); + + app(Checkout::class)->refund($order, 'Widerruf geprüft'); + + Http::assertSent(function (HttpRequest $request) use ($order): bool { + parse_str($request->body(), $body); + + return $request->url() === 'https://stripe.test/v1/refunds' + && $body['payment_intent'] === 'pi_test_r' + && (int) $body['amount'] === 7800 + && $request->header('Idempotency-Key')[0] === 'luf-refund-'.$order->id.'-'.$order->payments()->firstOrFail()->id; + }); + $this->assertSame('erstattet', $order->fresh()->status); + $this->assertSame(0, Grant::query()->where('status', GrantStatus::Aktiv)->count()); + } + + public function test_a_failed_refund_at_stripe_revokes_nothing(): void + { + config(['services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_test_nur_fuer_tests', 'services.stripe.api_base' => 'https://stripe.test']); + $order = $this->orderOf($this->tina(), [$this->privateKonflikte()]); + app(Checkout::class)->confirmProviderPayment($order, 'stripe', 'cs_test_f', 4900, 'eur'); + $order->payments()->update(['provider_payment_ref' => 'pi_test_f']); + Http::fake(['stripe.test/v1/refunds' => Http::response(['error' => ['type' => 'invalid_request_error', 'message' => 'x']], 400)]); + + try { + app(Checkout::class)->refund($order, 'Widerruf geprüft'); + $this->fail('Ohne Rückzahlung bei Stripe darf nichts entzogen werden.'); + } catch (DomainRuleException) { + $this->assertSame('bezahlt', $order->fresh()->status); + $this->assertSame(1, Grant::query()->where('status', GrantStatus::Aktiv)->count()); + } + } + + public function test_an_invoice_order_is_refunded_without_stripe_and_free_grants_stay(): void + { + $vera = $this->vera(); + $order = $this->orderOf($vera, [$this->clubKonflikte()], $this->club()->id); + $order->update(['payment_method' => 'rechnung']); + app(Checkout::class)->confirmInvoicePayment($order, 'RE-9', $this->tina()); + Http::fake(); + + app(Checkout::class)->refund($order, 'Storno nach Rücksprache'); + + Http::assertNothingSent(); + $this->assertSame('erstattet', $order->fresh()->status); + $this->assertFalse(Grant::query()->usableBy($vera)->where('status', GrantStatus::Aktiv)->exists()); + } + + public function test_the_member_declares_a_withdrawal_and_the_operator_decides(): void + { + config(['services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_test_nur_fuer_tests']); + $tina = $this->tina(); + $order = $this->orderOf($tina, [$this->privateKonflikte()]); + app(Checkout::class)->confirmProviderPayment($order, 'stripe', 'cs_test_w', 4900, 'eur'); + + $this->actingAs($tina)->get(route('member.order', $order))->assertOk()->assertSee('Widerruf erklären')->assertDontSee('Widerrufen (Testzahlung)'); + $this->post(route('member.order.refund', $order))->assertNotFound(); + + $this->post(route('member.order.withdraw', $order), ['note' => 'Passt nicht'])->assertRedirect(route('member.order', $order)); + $this->assertNotNull($order->fresh()->withdrawal_requested_at); + $this->assertSame('Passt nicht', $order->fresh()->withdrawal_note); + $this->assertSame('bezahlt', $order->fresh()->status, 'Die Erklärung entzieht und erstattet nichts; der Betreiber prüft.'); + $this->assertSame(1, Grant::query()->where('status', GrantStatus::Aktiv)->count()); + + $this->actingAs($this->max())->post(route('member.order.withdraw', $order))->assertForbidden(); + } + + public function test_the_shop_stays_off_in_production_unless_released_keyed_and_documented(): void + { + $this->app['env'] = 'production'; + config(['services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_live_nur_fuer_tests']); + + $this->assertFalse(config('shop.live_release'), 'Die Freigabe ist standardmäßig aus.'); + $this->assertFalse(Shop::enabled()); + $this->assertFalse(Shop::stripe()); + + config(['shop.live_release' => true]); + $this->assertFalse(Shop::live(), 'Ohne veröffentlichte Rechtstexte bleibt der Shop aus.'); + + foreach (['/agb', '/lizenzbedingungen', '/widerruf', '/impressum', '/datenschutz'] as $path) { + $this->publishLegalPage($path); + } + + $this->assertTrue(Shop::live()); + $this->assertTrue(Shop::enabled()); + $this->assertTrue(Shop::stripe()); + + config(['services.stripe.secret' => 'sk_test_nur_fuer_tests']); + $this->assertFalse(Shop::live(), 'Mit einem Testschlüssel ist Produktion nie live.'); + + config(['services.stripe.secret' => 'sk_live_nur_fuer_tests', 'services.payment.driver' => 'test']); + $this->assertFalse(Shop::live(), 'Der Testzahlungsweg gibt Produktion nie frei.'); + + config(['services.payment.driver' => 'stripe', 'shop.live_release' => false]); + $this->assertFalse(Shop::live()); + } + + public function test_stripe_refuses_a_live_key_outside_production_and_any_call_in_production_without_release(): void + { + $order = $this->orderOf($this->tina(), [$this->privateKonflikte()]); + config(['services.payment.driver' => 'stripe', 'services.stripe.secret' => 'sk_live_nur_fuer_tests']); + Http::fake(); + + try { + app(StripeGateway::class)->checkoutFor($order); + $this->fail('Ein Live-Schlüssel darf außerhalb der Produktion nicht verwendet werden.'); + } catch (DomainRuleException $exception) { + $this->assertStringContainsString('Testmodus', $exception->getMessage()); + } + + $this->app['env'] = 'production'; + + try { + app(StripeGateway::class)->checkoutFor($order); + $this->fail('Ohne Produktivfreigabe geht kein Aufruf an Stripe.'); + } catch (DomainRuleException $exception) { + $this->assertStringContainsString('nicht freigegeben', $exception->getMessage()); + } + + Http::assertNothingSent(); + } + + public function test_the_checkout_and_the_order_say_that_the_code_changes_the_price_not_the_scope(): void + { + $code = DiscountCode::query()->count(); + $this->assertSame(0, $code); + $this->actingAs($this->tina())->post(route('cart.add', $this->privateKonflikte())); + + $this->get(route('checkout'))->assertOk()->assertSee('Pro Bestellung gilt höchstens ein Code. Er ändert den Preis, nicht den Nutzungsumfang.'); + } +}