Führe Rabattcodes, Nutzerkreis der Lizenzoption und Pflichtangaben der Kasse ein
Domäne: Rabattcodes mit Geltungsbereich (Warenkorb oder gewählte Ziele) und Einlösungsberechtigung (allgemein oder freigeschaltete Konten) unabhängig voneinander; Prüfung bei Eingabe, in jeder Übersicht und unter Sperre vor Bestellabschluss (Prüfsumme der Übersicht enthält den Rabatt). Rabatt je Position, Zwischensumme und Zahlbetrag in der Bestellung; Stripe erhält den Preis nach Rabatt. Nutzerkreis (Einzel-/Mehrfachlizenz, Trainerzahl) an der Angebotsfassung, kopiert in Bestellposition und Erwerb, Teil der Prüfung "Bereits erworben". OfferService::activate lehnt Angebote ohne veröffentlichten Artikelstand ab. Kasse: Zustimmungen als Pflichtangabe mit Nachweis, "Zahlungspflichtig bestellen", Rechnungsweg für Organisationen, Erstattung über Stripe, Widerruf erklären. Produktivfreigabe SHOP_LIVE_RELEASE standardmäßig aus. Bestandstests geändert (fachlich überholt, Assertions nicht abgeschwächt): die Schaltfläche heißt "Zahlungspflichtig bestellen" (§ 312j BGB), die Summe heißt "Zu zahlen", der Vereinshinweis steht als Rollenliste; Bestellungen über die Kasse senden jetzt die Zustimmungen. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb80835c92
commit
0154182f3b
40 files changed
+2151
-92
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)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -102,10 +102,14 @@ 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);
|
||||
|
||||
$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 +130,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) {
|
||||
@@ -219,6 +225,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',
|
||||
];
|
||||
|
||||
|
||||
@@ -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,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -133,13 +140,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 +248,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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -150,7 +185,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 +194,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 +233,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();
|
||||
@@ -229,9 +280,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 +292,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 +330,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) {
|
||||
|
||||
@@ -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,320 @@
|
||||
<?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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private function date(mixed $value): ?CarbonInterface
|
||||
{
|
||||
return filled($value) ? Carbon::parse((string) $value, config('app.timezone')) : null;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
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;
|
||||
@@ -89,6 +90,10 @@ public function describe(Offer $offer, OfferVersion $version): array
|
||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'term' => self::termLabel($version),
|
||||
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count),
|
||||
'scope' => $scope,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
],
|
||||
]);
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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');
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ private function entry(User $user, Grant $grant): array
|
||||
? 'Spätere freigegebene Fassungen sind eingeschlossen.'
|
||||
: null,
|
||||
'source' => $this->source($user, $grant),
|
||||
'licence_scope' => $conditions['licence_scope'] ?? null,
|
||||
'trainer_count' => isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null,
|
||||
'holder_kind' => $holderKind,
|
||||
'holder' => $holderKind === 'organisation' ? (string) ($grant->acquisition?->party?->display_name ?? 'Organisation') : 'Persönlich',
|
||||
'url' => route('member.grant', $grant),
|
||||
|
||||
@@ -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.'),
|
||||
|
||||
];
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
<?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.
|
||||
*/
|
||||
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('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::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,4 +1,32 @@
|
||||
Ihre Bestellung {{ $order->id }} ist bezahlt. Die dazugehörigen Inhalte liegen in der Bibliothek.
|
||||
Vertragsbestätigung zu Ihrer Bestellung {{ $order->id }}
|
||||
|
||||
Ihre Bestellung ist bezahlt. Die dazugehörigen Inhalte liegen in der Bibliothek.
|
||||
|
||||
Lizenzinhaber: {{ $order->party?->display_name }}
|
||||
Bestellendes Konto (einziger Downloadzugriff aus dieser Bestellung): {{ $order->user?->name }}
|
||||
Zahlungsweg: {{ $order->payment_method === 'rechnung' ? 'Überweisung auf Rechnung' : ($order->payment_method === 'stripe' ? 'Stripe' : 'Testzahlung') }}
|
||||
|
||||
@foreach ($order->lines as $line)
|
||||
- {{ $line->offer_name }}: {{ number_format($line->price_cents / 100, 2, ',', '.') }} €
|
||||
- {{ $line->offer_name }}
|
||||
Nutzerkreis: {{ \App\Domain\Catalog\LicenceScope::label($line->licence_scope, $line->trainer_count) }}
|
||||
@if ($line->discount_cents > 0)
|
||||
Preis: {{ number_format($line->price_cents / 100, 2, ',', '.') }} € abzüglich Rabatt {{ number_format($line->discount_cents / 100, 2, ',', '.') }} € = {{ number_format($line->payable() / 100, 2, ',', '.') }} €
|
||||
@else
|
||||
Preis: {{ number_format($line->price_cents / 100, 2, ',', '.') }} €
|
||||
@endif
|
||||
@endforeach
|
||||
|
||||
@if ($order->discount_cents > 0)
|
||||
Zwischensumme: {{ number_format($order->subtotal() / 100, 2, ',', '.') }} €
|
||||
Rabattcode {{ $order->discount_snapshot['code'] ?? '' }}: −{{ number_format($order->discount_cents / 100, 2, ',', '.') }} €
|
||||
@endif
|
||||
Gezahlter Betrag: {{ number_format($order->payable() / 100, 2, ',', '.') }} €
|
||||
|
||||
@if ($order->terms_accepted_at)
|
||||
Ihre Zustimmungen am {{ $order->terms_accepted_at->timezone(config('app.timezone'))->format('d.m.Y H:i') }} Uhr (Fassung {{ $order->terms_snapshot['version'] ?? '' }}):
|
||||
@foreach (($order->terms_snapshot['consents'] ?? []) as $wording)
|
||||
- {{ $wording }}
|
||||
@endforeach
|
||||
@endif
|
||||
|
||||
Die Inhalte wurden Ihnen sofort nach Zahlungseingang bereitgestellt. Hinweise zum Widerruf stehen in der Widerrufsbelehrung.
|
||||
@@ -102,7 +102,11 @@
|
||||
@endif
|
||||
<div>
|
||||
<dt>Einzel- oder Mehrfachlizenz</dt>
|
||||
<dd>Nicht festgelegt. Die Lizenz enthält keine Angabe zur Nutzerzahl; sie gilt für {{ $holder_kind === 'organisation' ? 'die Organisation '.$holder : 'dein Konto' }}.</dd>
|
||||
@if ($licence_scope)
|
||||
<dd>{{ \App\Domain\Catalog\LicenceScope::label($licence_scope, $trainer_count) }}. {{ \App\Domain\Catalog\LicenceScope::explanation($licence_scope, $trainer_count) }} Lizenzinhaber ist {{ $holder_kind === 'organisation' ? 'die Organisation '.$holder : 'dein Konto' }}; Downloadzugriff hat das Konto, das bestellt hat.</dd>
|
||||
@else
|
||||
<dd>Nicht festgelegt. Die Lizenz enthält keine Angabe zur Nutzerzahl; sie gilt für {{ $holder_kind === 'organisation' ? 'die Organisation '.$holder : 'dein Konto' }}.</dd>
|
||||
@endif
|
||||
</div>
|
||||
<div>
|
||||
<dt>Artikel</dt>
|
||||
|
||||
@@ -5,14 +5,19 @@
|
||||
|
||||
@section('content')
|
||||
@php
|
||||
$invoiceOrder = $order->payment_method === 'rechnung';
|
||||
$paidWith = $invoiceOrder ? 'Überweisung auf Rechnung' : ($order->payment_method === 'stripe' ? 'Stripe' : 'Testzahlung');
|
||||
$statusText = [
|
||||
'offen' => 'Offen. Die Testzahlung steht noch aus, Rechte gibt es erst nach bestätigter Zahlung.',
|
||||
'bezahlt' => 'Bezahlt (Testzahlung). Die Inhalte liegen in der Bibliothek.',
|
||||
'fehlgeschlagen' => 'Die Testzahlung wurde abgelehnt. Es wurde keine Berechtigung vergeben.',
|
||||
'offen' => $invoiceOrder
|
||||
? 'Offen. Wir erstellen die Rechnung manuell und senden sie dir. Rechte gibt es erst nach Zahlungseingang.'
|
||||
: 'Offen. Die Zahlung steht noch aus, Rechte gibt es erst nach bestätigter Zahlung.',
|
||||
'bezahlt' => 'Bezahlt ('.$paidWith.'). Die Inhalte liegen in der Bibliothek.',
|
||||
'fehlgeschlagen' => 'Die Zahlung wurde abgelehnt. Es wurde keine Berechtigung vergeben.',
|
||||
'erstattet' => 'Erstattet. Die Berechtigungen dieser Bestellung sind widerrufen.',
|
||||
][$order->status] ?? $order->status;
|
||||
$money = fn (?int $cents): string => \App\Domain\Commerce\Money::format($cents);
|
||||
@endphp
|
||||
<x-member.hero kicker="Testzahlung" :title="'Bestellung '.$order->id" />
|
||||
<x-member.hero :kicker="$invoiceOrder ? 'Rechnung' : ($stripePayment ? 'Zahlung' : 'Testzahlung')" :title="'Bestellung '.$order->id" />
|
||||
@if ($errors->any())
|
||||
<div class="errors" role="alert">{{ $errors->first() }}</div>
|
||||
@endif
|
||||
@@ -24,21 +29,37 @@
|
||||
@endif
|
||||
<dl class="mb-dl mb-dl-cards">
|
||||
<div><dt>Lizenzinhaber</dt><dd>{{ $order->party?->display_name }}</dd></div>
|
||||
<div><dt>Bestellt von</dt><dd>{{ $order->user?->name }}</dd></div>
|
||||
<div><dt>Bestellt von (Konto mit Downloadzugriff)</dt><dd>{{ $order->user?->name }}</dd></div>
|
||||
<div><dt>Zahlungsweg</dt><dd>{{ $paidWith }}</dd></div>
|
||||
</dl>
|
||||
<ul class="mb-offers">
|
||||
@foreach ($order->lines as $line)
|
||||
<li class="mb-offer">
|
||||
<h2>{{ filled($line->offer_name) ? $line->offer_name : ($line->offerVersion->offer->name ?? 'Angebot') }}</h2>
|
||||
<p>{{ \App\Domain\Commerce\Money::format($line->price_cents) }}</p>
|
||||
<p class="shop-licence"><strong>Nutzerkreis:</strong> {{ \App\Domain\Catalog\LicenceScope::label($line->licence_scope, $line->trainer_count) }}</p>
|
||||
@if ($line->discount_cents > 0)
|
||||
<p><s>{{ $money($line->price_cents) }}</s> {{ $money($line->payable()) }} <span class="shop-badge shop-badge-discount">Rabatt −{{ $money($line->discount_cents) }}</span></p>
|
||||
@else
|
||||
<p>{{ $money($line->price_cents) }}</p>
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
<p class="state">Summe: {{ \App\Domain\Commerce\Money::format($order->total_cents ?? $order->lines->sum('price_cents')) }}</p>
|
||||
@if ($order->discount_cents > 0)
|
||||
<dl class="mb-dl">
|
||||
<div><dt>Zwischensumme</dt><dd>{{ $money($order->subtotal()) }}</dd></div>
|
||||
<div><dt>Rabattcode</dt><dd>{{ $order->discount_snapshot['code'] ?? '' }}</dd></div>
|
||||
<div><dt>Rabatt</dt><dd>−{{ $money($order->discount_cents) }}</dd></div>
|
||||
</dl>
|
||||
@endif
|
||||
<p class="state">Zu zahlen: <strong>{{ $money($order->payable()) }}</strong></p>
|
||||
@if ($order->terms_accepted_at)
|
||||
<p class="mb-muted">Zustimmung zu Bedingungen und sofortiger Bereitstellung am {{ $order->terms_accepted_at->timezone(config('app.timezone'))->format('d.m.Y H:i') }} Uhr (Fassung {{ $order->terms_snapshot['version'] ?? '' }}).</p>
|
||||
@endif
|
||||
@if ($stripePayment && $order->status === 'offen')
|
||||
<form method="post" action="{{ route('member.order.pay', $order) }}">
|
||||
@csrf
|
||||
<button class="button" type="submit">Jetzt bezahlen (Stripe-Testmodus)</button>
|
||||
<button class="button" type="submit">{{ $live ? 'Jetzt bezahlen' : 'Jetzt bezahlen (Stripe-Testmodus)' }}</button>
|
||||
</form>
|
||||
@endif
|
||||
@if ($testPayment && $order->status === 'offen')
|
||||
@@ -53,11 +74,27 @@
|
||||
@endif
|
||||
@if ($order->status === 'bezahlt')
|
||||
<p><a class="button" href="{{ route('member.library') }}">Zur Bibliothek</a></p>
|
||||
@if (! $stripePayment)
|
||||
@if (! $stripePayment && ! $invoiceOrder && ! app()->isProduction() && config('services.payment.driver') === 'test')
|
||||
<form method="post" action="{{ route('member.order.refund', $order) }}">
|
||||
@csrf
|
||||
<button class="button button-quiet" type="submit">Widerrufen</button>
|
||||
<button class="button button-quiet" type="submit">Widerrufen (Testzahlung)</button>
|
||||
</form>
|
||||
@endif
|
||||
@endif
|
||||
@if (in_array($order->status, ['bezahlt', 'offen'], true) && ($stripePayment || $invoiceOrder))
|
||||
@if ($order->withdrawal_requested_at)
|
||||
<p class="state" role="status">Du hast den Widerruf am {{ $order->withdrawal_requested_at->timezone(config('app.timezone'))->format('d.m.Y') }} erklärt. Wir prüfen ihn und melden uns per E-Mail.</p>
|
||||
@else
|
||||
<details class="mb-withdraw">
|
||||
<summary>Widerruf erklären</summary>
|
||||
<form method="post" action="{{ route('member.order.withdraw', $order) }}">
|
||||
@csrf
|
||||
<p class="mb-muted">Mit dem Absenden erklärst du den Widerruf dieser Bestellung. Wir prüfen ihn und melden uns. Bei sofortiger Bereitstellung der digitalen Inhalte mit deiner ausdrücklichen Zustimmung kann das Widerrufsrecht erloschen sein; die Widerrufsbelehrung beschreibt das.</p>
|
||||
<label for="widerruf-notiz">Anmerkung (freiwillig)</label>
|
||||
<textarea id="widerruf-notiz" name="note" rows="3" maxlength="1000"></textarea>
|
||||
<button class="button button-secondary" type="submit">Widerruf erklären</button>
|
||||
</form>
|
||||
</details>
|
||||
@endif
|
||||
@endif
|
||||
@endsection
|
||||
@@ -34,6 +34,9 @@
|
||||
<div class="shop-line-main">
|
||||
<h2>{{ $line->title() }}</h2>
|
||||
<p class="shop-line-option">{{ $line->offer->optionName() }}</p>
|
||||
@if ($line->version)
|
||||
<p class="shop-licence"><strong>Nutzerkreis:</strong> {{ \App\Domain\Catalog\LicenceScope::label($line->version->licence_scope, $line->version->trainer_count) }}</p>
|
||||
@endif
|
||||
|
||||
@if ($line->state === 'bereits_erworben')
|
||||
<p class="shop-badge shop-badge-owned">Bereits erworben · Wird nicht mitbestellt</p>
|
||||
@@ -86,10 +89,14 @@
|
||||
@endforeach
|
||||
</ul>
|
||||
|
||||
<div class="shop-total">
|
||||
<p><span>Summe</span> <strong>{{ \App\Domain\Commerce\Money::format($review->totalCents()) }}</strong></p>
|
||||
<p class="shop-note">Testzahlung. Es wird kein echtes Geld bewegt.</p>
|
||||
</div>
|
||||
<dl class="shop-total shop-total-table">
|
||||
@if ($review->discountCents() > 0)
|
||||
<div><dt>Zwischensumme</dt><dd>{{ \App\Domain\Commerce\Money::format($review->subtotalCents()) }}</dd></div>
|
||||
<div><dt>Rabatt ({{ $review->discount->code->code }})</dt><dd>−{{ \App\Domain\Commerce\Money::format($review->discountCents()) }}</dd></div>
|
||||
@endif
|
||||
<div class="shop-total-final"><dt>{{ $review->discountCents() > 0 ? 'Zu zahlen' : 'Summe' }}</dt><dd><strong>{{ \App\Domain\Commerce\Money::format($review->totalCents()) }}</strong></dd></div>
|
||||
</dl>
|
||||
<p class="shop-note">{{ config('shop.price_note') }} Einen Rabattcode gibst du in der Bestellübersicht ein.</p>
|
||||
|
||||
@if ($review->blocked())
|
||||
<p class="shop-note" role="status">Entferne die Positionen, die nicht bestellt werden können, oder wähle einen passenden Lizenzinhaber. Die übrigen Positionen bleiben bestellbar.</p>
|
||||
|
||||
@@ -3,11 +3,24 @@
|
||||
@section('title', 'Bestellübersicht')
|
||||
|
||||
@section('content')
|
||||
@php
|
||||
$money = fn (?int $cents): string => \App\Domain\Commerce\Money::format($cents);
|
||||
$live = \App\Domain\Commerce\Shop::live();
|
||||
$missingLegal = \App\Domain\Commerce\SalesTerms::missingPages();
|
||||
$holderQuery = array_filter(['bestellen_als' => $review->holder?->id]);
|
||||
@endphp
|
||||
<h1>Bestellübersicht</h1>
|
||||
<p class="lede">Prüfe deine Bestellung. Preis und Bedingungen gelten so, wie sie hier stehen. Bezahlt wird im nächsten Schritt mit der Testzahlung.</p>
|
||||
<p class="lede">Prüfe deine Bestellung. Preis und Bedingungen gelten so, wie sie hier stehen.</p>
|
||||
|
||||
@if ($errors->any())
|
||||
<p class="errors" role="alert">{{ $errors->first() }}</p>
|
||||
@unless ($live)
|
||||
<p class="shop-note shop-draft" role="note">Testbetrieb: Es wird kein echtes Geld bewegt. Rechtstexte und Steuerangaben sind noch nicht freigegeben.</p>
|
||||
@endunless
|
||||
|
||||
@if (session('status'))
|
||||
<p class="state" role="status">{{ session('status') }}</p>
|
||||
@endif
|
||||
@if ($errors->has('checkout') || $errors->has('zustimmung'))
|
||||
<p class="errors" role="alert">{{ $errors->first('checkout') ?: $errors->first('zustimmung') }}</p>
|
||||
@endif
|
||||
|
||||
@if ($holders->count() > 1)
|
||||
@@ -20,20 +33,29 @@
|
||||
</select>
|
||||
<button class="button button-secondary" type="submit">Übernehmen</button>
|
||||
</form>
|
||||
@elseif ($review->holder)
|
||||
<p>Lizenzinhaber: <strong>{{ $review->holder->display_name }}</strong></p>
|
||||
@endif
|
||||
|
||||
@if ($review->holder?->type->value === 'organisation')
|
||||
<p class="shop-note">Der Verein ist Lizenzinhaber. Herunterladen kann nur dieses Konto, das die Bestellung auslöst.</p>
|
||||
@if ($review->holder)
|
||||
<dl class="shop-roles">
|
||||
<div><dt>Lizenzinhaber</dt><dd>{{ $review->holder->display_name }}@if ($review->holder->type->value === 'organisation') (Verein oder Organisation)@endif</dd></div>
|
||||
<div><dt>Bestellendes Konto</dt><dd>{{ auth()->user()->name }}</dd></div>
|
||||
<div><dt>Downloadzugriff aus dieser Bestellung</dt><dd>@if ($review->holder->type->value === 'organisation')Nur dieses Konto, nicht weitere Mitglieder des Vereins.@else Dieses Konto.@endif</dd></div>
|
||||
</dl>
|
||||
@endif
|
||||
|
||||
<ul class="shop-lines shop-order-summary">
|
||||
@foreach ($review->lines as $line)
|
||||
@php
|
||||
$lineDiscount = $review->discountFor($line);
|
||||
$licence = $line->version ? \App\Domain\Catalog\LicenceScope::label($line->version->licence_scope, $line->version->trainer_count) : null;
|
||||
@endphp
|
||||
<li @class(['shop-line', 'is-owned' => $line->state === 'bereits_erworben', 'is-blocked' => $line->blocks()])>
|
||||
<div class="shop-line-main">
|
||||
<h2>{{ $line->title() }}</h2>
|
||||
<p class="shop-line-option">{{ $line->offer->optionName() }}</p>
|
||||
@if ($licence)
|
||||
<p class="shop-licence"><strong>Nutzerkreis:</strong> {{ $licence }}</p>
|
||||
@endif
|
||||
@if ($line->state === 'bereits_erworben')
|
||||
<p class="shop-badge shop-badge-owned">Bereits erworben · Wird nicht mitbestellt</p>
|
||||
@elseif ($line->blocks())
|
||||
@@ -41,45 +63,129 @@
|
||||
<p class="shop-note">{{ $line->note }}</p>
|
||||
@elseif ($line->state === 'preis_geaendert')
|
||||
<p class="shop-badge shop-badge-changed">Preis geändert</p>
|
||||
<p class="shop-note">Bisher {{ \App\Domain\Commerce\Money::format($line->seenPriceCents) }}, jetzt {{ \App\Domain\Commerce\Money::format($line->currentPriceCents) }}.</p>
|
||||
<p class="shop-note">Bisher {{ $money($line->seenPriceCents) }}, jetzt {{ $money($line->currentPriceCents) }}.</p>
|
||||
@elseif ($line->state === 'bedingungen_geaendert')
|
||||
<p class="shop-badge shop-badge-changed">Bedingungen aktualisiert</p>
|
||||
<p class="shop-note">{{ $line->note }}</p>
|
||||
@endif
|
||||
@if ($lineDiscount > 0)
|
||||
<p class="shop-badge shop-badge-discount">Rabatt {{ $review->discount->code->code }}: −{{ $money($lineDiscount) }}</p>
|
||||
@endif
|
||||
</div>
|
||||
<div class="shop-line-side">
|
||||
@if ($line->currentPriceCents !== null)
|
||||
<p @class(['shop-price', 'is-struck' => $line->state === 'bereits_erworben'])><span class="sr-only">Preis: </span>{{ \App\Domain\Commerce\Money::format($line->currentPriceCents) }}</p>
|
||||
<p @class(['shop-price', 'is-struck' => $line->state === 'bereits_erworben'])>
|
||||
@if ($lineDiscount > 0)
|
||||
<s class="shop-price-old"><span class="sr-only">Listenpreis: </span>{{ $money($line->currentPriceCents) }}</s>
|
||||
<span class="sr-only">Preis nach Rabatt: </span>{{ $money($line->currentPriceCents - $lineDiscount) }}
|
||||
@else
|
||||
<span class="sr-only">Preis: </span>{{ $money($line->currentPriceCents) }}
|
||||
@endif
|
||||
</p>
|
||||
@endif
|
||||
</div>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
|
||||
<div class="shop-total">
|
||||
<p><span>Summe</span> <strong>{{ \App\Domain\Commerce\Money::format($review->totalCents()) }}</strong></p>
|
||||
<p class="shop-note">Testzahlung. Es wird kein echtes Geld bewegt.</p>
|
||||
</div>
|
||||
|
||||
<div class="shop-actions">
|
||||
@if ($review->canOrder())
|
||||
<form method="post" action="{{ route('checkout.place') }}">
|
||||
<section class="shop-code" aria-labelledby="shop-code-title">
|
||||
<h2 id="shop-code-title">Rabattcode</h2>
|
||||
@if ($review->discount?->applied())
|
||||
<p class="shop-code-applied" role="status">
|
||||
<strong>{{ $review->discount->code->code }}</strong> ist angewendet
|
||||
({{ $review->discount->code->valueLabel() }}{{ $review->discount->code->forSelection() ? ', gilt nur für ausgewählte Angebote' : '' }}).
|
||||
</p>
|
||||
<form method="post" action="{{ route('checkout.code.remove') }}">
|
||||
@csrf
|
||||
<input type="hidden" name="digest" value="{{ $review->digest() }}">
|
||||
@if ($review->holder)<input type="hidden" name="bestellen_als" value="{{ $review->holder->id }}">@endif
|
||||
<button class="button" type="submit">Bestellung anlegen</button>
|
||||
<button class="button button-quiet" type="submit">Code entfernen</button>
|
||||
</form>
|
||||
@else
|
||||
<button class="button" type="button" disabled aria-disabled="true">Bestellung anlegen</button>
|
||||
@if ($review->discount !== null)
|
||||
<p class="errors" role="alert">Der Code {{ $review->discount->code?->code }} gilt gerade nicht. {{ $review->discount->message }}</p>
|
||||
<form method="post" action="{{ route('checkout.code.remove') }}">
|
||||
@csrf
|
||||
@if ($review->holder)<input type="hidden" name="bestellen_als" value="{{ $review->holder->id }}">@endif
|
||||
<button class="button button-secondary" type="submit">Code entfernen</button>
|
||||
</form>
|
||||
@endif
|
||||
<form class="shop-code-form" method="post" action="{{ route('checkout.code') }}">
|
||||
@csrf
|
||||
@if ($review->holder)<input type="hidden" name="bestellen_als" value="{{ $review->holder->id }}">@endif
|
||||
<label for="rabattcode">{{ $review->discount !== null ? 'Anderen Code eingeben' : 'Hast du einen Rabattcode?' }}</label>
|
||||
<div class="shop-code-row">
|
||||
<input id="rabattcode" name="code" type="text" autocomplete="off" autocapitalize="characters" spellcheck="false" maxlength="60" aria-describedby="rabattcode-hinweis @error('code') rabattcode-fehler @enderror" value="{{ old('code') }}">
|
||||
<button class="button button-secondary" type="submit">Code einlösen</button>
|
||||
</div>
|
||||
@error('code')
|
||||
<p class="errors" id="rabattcode-fehler" role="alert">{{ $message }}</p>
|
||||
@enderror
|
||||
<p class="shop-note" id="rabattcode-hinweis">Pro Bestellung gilt höchstens ein Code. Er ändert den Preis, nicht den Nutzungsumfang.</p>
|
||||
</form>
|
||||
@endif
|
||||
<a class="button button-secondary" href="{{ route('cart') }}">Zurück zum Warenkorb</a>
|
||||
</div>
|
||||
@if (! $review->canOrder())
|
||||
</section>
|
||||
|
||||
<dl class="shop-total shop-total-table">
|
||||
@if ($review->discountCents() > 0)
|
||||
<div><dt>Zwischensumme</dt><dd>{{ $money($review->subtotalCents()) }}</dd></div>
|
||||
<div><dt>Rabatt ({{ $review->discount->code->code }})</dt><dd>−{{ $money($review->discountCents()) }}</dd></div>
|
||||
@endif
|
||||
<div class="shop-total-final"><dt>Zu zahlen</dt><dd><strong>{{ $money($review->totalCents()) }}</strong></dd></div>
|
||||
</dl>
|
||||
<p class="shop-note">{{ config('shop.price_note') }}</p>
|
||||
|
||||
@if ($review->canOrder())
|
||||
<form class="shop-order-form" method="post" action="{{ route('checkout.place') }}">
|
||||
@csrf
|
||||
<input type="hidden" name="digest" value="{{ $review->digest() }}">
|
||||
@if ($review->holder)<input type="hidden" name="bestellen_als" value="{{ $review->holder->id }}">@endif
|
||||
|
||||
@if ($invoice)
|
||||
<fieldset class="shop-pay">
|
||||
<legend>Zahlungsweg</legend>
|
||||
<label><input type="radio" name="zahlungsweg" value="online" @checked(old('zahlungsweg', 'online') === 'online')> {{ \App\Domain\Commerce\Shop::stripe() ? 'Online bezahlen (Stripe)' : 'Testzahlung' }}</label>
|
||||
<label><input type="radio" name="zahlungsweg" value="rechnung" @checked(old('zahlungsweg') === 'rechnung')> Auf Rechnung (Überweisung, auf Anfrage)</label>
|
||||
<p class="shop-note">Bei Rechnung erstellen wir die Rechnung manuell und senden sie dir. Die Inhalte werden nach Zahlungseingang freigeschaltet.</p>
|
||||
</fieldset>
|
||||
@endif
|
||||
|
||||
<fieldset class="shop-legal">
|
||||
<legend>Dein Vertrag</legend>
|
||||
<p class="shop-note">
|
||||
Bitte lies vor dem Bestellen:
|
||||
@foreach ($legalPages as $key => $page)
|
||||
@php $url = \App\Domain\Commerce\SalesTerms::url($key); @endphp
|
||||
@if ($url)<a href="{{ $url }}" target="_blank" rel="noopener">{{ $page['label'] }}</a>@else<span class="shop-legal-missing">{{ $page['label'] }} (noch nicht veröffentlicht)</span>@endif{{ $loop->last ? '.' : ',' }}
|
||||
@endforeach
|
||||
</p>
|
||||
@foreach ($consents as $key => $wording)
|
||||
<label class="shop-consent">
|
||||
<input type="checkbox" name="zustimmung[{{ $key }}]" value="1" required @checked(old('zustimmung.'.$key))>
|
||||
<span>{{ $wording }}</span>
|
||||
</label>
|
||||
@endforeach
|
||||
@unless ($live)
|
||||
<p class="shop-note shop-draft">Entwurf: Der Wortlaut der Zustimmungen ist noch nicht rechtlich geprüft.@if ($missingLegal !== []) Es fehlen veröffentlichte Seiten: {{ implode(', ', $missingLegal) }}.@endif</p>
|
||||
@endunless
|
||||
</fieldset>
|
||||
|
||||
<div class="shop-actions">
|
||||
<button class="button" type="submit">{{ \App\Domain\Commerce\SalesTerms::ORDER_BUTTON }}</button>
|
||||
<a class="button button-secondary" href="{{ route('cart') }}">Zurück zum Warenkorb</a>
|
||||
</div>
|
||||
</form>
|
||||
@else
|
||||
<div class="shop-actions">
|
||||
<button class="button" type="button" disabled aria-disabled="true">{{ \App\Domain\Commerce\SalesTerms::ORDER_BUTTON }}</button>
|
||||
<a class="button button-secondary" href="{{ route('cart') }}">Zurück zum Warenkorb</a>
|
||||
</div>
|
||||
<p class="shop-note" role="status">
|
||||
@if ($review->holder === null)
|
||||
Für diesen Lizenzinhaber kannst du nicht bestellen. Wähle oben einen anderen Lizenzinhaber oder bestelle als Privatperson.
|
||||
@elseif ($review->blocked())
|
||||
Entferne zuerst die Positionen, die nicht bestellt werden können, oder wähle einen passenden Lizenzinhaber.
|
||||
@elseif ($review->discountBlocks())
|
||||
Entferne den Rabattcode oder ändere den Warenkorb, damit er passt. Erst dann kannst du bestellen.
|
||||
@else
|
||||
Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.
|
||||
@endif
|
||||
|
||||
@@ -39,7 +39,11 @@
|
||||
<dl class="shop-facts">
|
||||
<div><dt>Geeignet für</dt><dd>{{ $option['for'] }}</dd></div>
|
||||
<div><dt>Laufzeit</dt><dd>{{ $option['term'] }}</dd></div>
|
||||
<div><dt>Nutzerkreis</dt><dd>{{ $option['licence'] }}</dd></div>
|
||||
</dl>
|
||||
@if ($option['licence_note'])
|
||||
<p class="shop-note">{{ $option['licence_note'] }}</p>
|
||||
@endif
|
||||
<h4>Umfang und Nutzungsrechte</h4>
|
||||
<ul class="shop-scope">
|
||||
@foreach ($option['scope'] as $item)
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
Route::middleware(['auth', 'verified'])->group(function () {
|
||||
Route::get('/kasse', [CheckoutController::class, 'checkout'])->name('checkout');
|
||||
Route::post('/kasse', [CheckoutController::class, 'placeOrder'])->name('checkout.place');
|
||||
Route::post('/kasse/rabattcode', [CheckoutController::class, 'applyCode'])->name('checkout.code');
|
||||
Route::post('/kasse/rabattcode/entfernen', [CheckoutController::class, 'removeCode'])->name('checkout.code.remove');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -141,6 +143,7 @@
|
||||
Route::post('/bestellung/{order}/bestaetigen', [CheckoutController::class, 'confirm'])->name('order.confirm');
|
||||
Route::post('/bestellung/{order}/ablehnen', [CheckoutController::class, 'fail'])->name('order.fail');
|
||||
Route::post('/bestellung/{order}/widerrufen', [CheckoutController::class, 'refund'])->name('order.refund');
|
||||
Route::post('/bestellung/{order}/widerruf-erklaeren', [CheckoutController::class, 'withdraw'])->name('order.withdraw');
|
||||
Route::get('/profil', [ProfileController::class, 'show'])->name('profile');
|
||||
Route::post('/profil', [ProfileController::class, 'updateName'])->name('profile.update');
|
||||
Route::post('/profil/email', [ProfileController::class, 'requestEmail'])->middleware('throttle:6,1')->name('profile.email');
|
||||
|
||||
@@ -146,7 +146,7 @@ public function test_a_change_after_the_overview_was_shown_creates_no_order_and_
|
||||
$this->reprice($offer, 3500);
|
||||
|
||||
$this->actingAs($tina)
|
||||
->post(route('checkout.place'), ['digest' => $shown])
|
||||
->post(route('checkout.place'), ['digest' => $shown, ...$this->consentFields()])
|
||||
->assertRedirect(route('checkout'))
|
||||
->assertSessionHasErrors('checkout');
|
||||
|
||||
@@ -172,7 +172,7 @@ public function test_a_withdrawn_position_stays_visible_blocks_the_order_and_lea
|
||||
->assertSee('Nicht mehr erhältlich')
|
||||
->assertSee('Konflikte im Training')
|
||||
->assertSee('Entferne die Positionen, die nicht bestellt werden können');
|
||||
$this->post(route('checkout.place'), ['digest' => $review->digest()])->assertSessionHasErrors('checkout');
|
||||
$this->post(route('checkout.place'), ['digest' => $review->digest(), ...$this->consentFields()])->assertSessionHasErrors('checkout');
|
||||
$this->assertSame(0, Order::query()->count());
|
||||
|
||||
$cart->remove($withdrawn);
|
||||
@@ -217,7 +217,7 @@ public function test_when_everything_is_already_owned_the_checkout_stays_blocked
|
||||
$this->assertTrue($review->empty());
|
||||
$this->assertFalse($review->canOrder());
|
||||
$this->actingAs($tina)->get(route('cart'))->assertSee('Es gibt nichts zu bestellen');
|
||||
$this->actingAs($tina)->post(route('checkout.place'), ['digest' => $review->digest()])->assertSessionHasErrors('checkout');
|
||||
$this->actingAs($tina)->post(route('checkout.place'), ['digest' => $review->digest(), ...$this->consentFields()])->assertSessionHasErrors('checkout');
|
||||
$this->assertSame(1, Order::query()->count(), 'Nur die Vorbestellung existiert.');
|
||||
}
|
||||
|
||||
@@ -333,7 +333,7 @@ public function test_the_cart_survives_login_and_the_checkout_is_reached_in_the_
|
||||
$this->post('/anmelden', ['email' => 'tina.trainerin@example.test', 'password' => ShopDemoSeeder::PASSWORD])
|
||||
->assertRedirect(route('checkout'));
|
||||
|
||||
$this->get(route('checkout'))->assertOk()->assertSee('Konflikte im Training')->assertSee('Bestellung anlegen');
|
||||
$this->get(route('checkout'))->assertOk()->assertSee('Konflikte im Training')->assertSee('Zahlungspflichtig bestellen');
|
||||
}
|
||||
|
||||
public function test_the_cart_survives_registration_and_email_confirmation(): void
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Cart;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountRelease;
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\StaleOverview;
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Tests\Support\BuildsShop;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Rabattcodes (PAY-008, FACH-14): Geltungsbereich und Einlösungsberechtigung sind unabhängig, die Prüfung läuft
|
||||
* serverseitig bei der Einlösung und erneut vor Bestellabschluss, der Rabatt bleibt in der Bestellung nachvollziehbar.
|
||||
*/
|
||||
class DiscountCodeTest extends TestCase
|
||||
{
|
||||
use BuildsShop;
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->seedShop();
|
||||
$this->travelTo('2026-11-24 10:00:00');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @param list<array{type: string, id: int}> $targets
|
||||
*/
|
||||
private function code(string $code, array $data = [], array $targets = []): DiscountCode
|
||||
{
|
||||
return app(DiscountService::class)->save([
|
||||
'code' => $code,
|
||||
'label' => 'Test '.$code,
|
||||
'kind' => DiscountCode::PERCENT,
|
||||
'percent' => 10,
|
||||
'scope' => DiscountCode::SCOPE_CART,
|
||||
'eligibility' => DiscountCode::OPEN,
|
||||
'active' => true,
|
||||
...$data,
|
||||
], $targets);
|
||||
}
|
||||
|
||||
private function release(DiscountCode $code, User $member): DiscountRelease
|
||||
{
|
||||
return app(DiscountService::class)->release($code, $member, $this->vera(), null, 'Zertifikat geprüft');
|
||||
}
|
||||
|
||||
private function cartFor(User $user, array $offers, ?string $code = null): Cart
|
||||
{
|
||||
$cart = app(Cart::class);
|
||||
$cart->clear();
|
||||
|
||||
foreach ($offers as $offer) {
|
||||
$cart->add($offer);
|
||||
}
|
||||
|
||||
if ($code !== null) {
|
||||
$cart->applyCode($code, $user);
|
||||
}
|
||||
|
||||
return $cart;
|
||||
}
|
||||
|
||||
public function test_a_general_code_reduces_the_whole_cart(): void
|
||||
{
|
||||
$this->code('SOMMER10');
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte(), $this->privateGrenzen()], 'sommer10');
|
||||
|
||||
$review = $cart->review($tina);
|
||||
|
||||
$this->assertSame(7800, $review->subtotalCents());
|
||||
$this->assertSame(780, $review->discountCents());
|
||||
$this->assertSame(7020, $review->totalCents());
|
||||
|
||||
$order = app(Checkout::class)->placeFromCart($tina, $cart, null, $review->digest());
|
||||
|
||||
$this->assertSame(7800, $order->subtotal_cents);
|
||||
$this->assertSame(780, $order->discount_cents);
|
||||
$this->assertSame(7020, $order->total_cents);
|
||||
$this->assertSame('SOMMER10', $order->discount_snapshot['code']);
|
||||
$this->assertSame([490, 290], $order->lines->pluck('discount_cents')->all());
|
||||
$this->assertSame([4900, 2900], $order->lines->pluck('price_cents')->all(), 'Die Listenpreise bleiben unverändert gespeichert.');
|
||||
$this->assertSame(0, app(Cart::class)->count());
|
||||
$this->assertNull(session(Cart::DISCOUNT_KEY), 'Der Code gehört zur Bestellung und ist danach aus dem Warenkorb entfernt.');
|
||||
}
|
||||
|
||||
public function test_an_item_specific_code_reduces_only_the_selected_position_in_a_mixed_cart(): void
|
||||
{
|
||||
$konflikte = $this->privateKonflikte();
|
||||
$this->code('NURKONFLIKT', targets: [['type' => DiscountCode::TARGET_OFFER, 'id' => $konflikte->id]], data: ['scope' => DiscountCode::SCOPE_SELECTED]);
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$konflikte, $this->privateGrenzen()], 'NURKONFLIKT');
|
||||
|
||||
$review = $cart->review($tina);
|
||||
|
||||
$this->assertSame(490, $review->discountCents());
|
||||
$this->assertSame(490, $review->discountFor($review->lines[0]));
|
||||
$this->assertSame(0, $review->discountFor($review->lines[1]), 'Die nicht gewählte Position bleibt zum Listenpreis.');
|
||||
$this->assertSame(7310, $review->totalCents());
|
||||
}
|
||||
|
||||
public function test_a_license_article_target_does_not_make_a_bundle_containing_it_discountable_and_vice_versa(): void
|
||||
{
|
||||
$article = $this->article('shop-konflikte');
|
||||
$bundle = Bundle::query()->where('name', 'Starterpaket')->firstOrFail();
|
||||
$tina = $this->tina();
|
||||
|
||||
$this->code('ARTIKEL', ['scope' => DiscountCode::SCOPE_SELECTED], [['type' => DiscountCode::TARGET_ARTICLE, 'id' => $article->id]]);
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte(), $this->starter()], 'ARTIKEL');
|
||||
$review = $cart->review($tina);
|
||||
|
||||
$this->assertSame(490, $review->discountCents(), 'Zehn Prozent nur auf das Angebot, dessen Position der Artikel selbst ist.');
|
||||
$this->assertSame(0, $review->discountFor($review->lines[1]), 'Das Starterpaket enthält den Artikel, ist aber nicht als Ziel gewählt.');
|
||||
|
||||
$this->code('PAKET', ['scope' => DiscountCode::SCOPE_SELECTED], [['type' => DiscountCode::TARGET_BUNDLE, 'id' => $bundle->id]]);
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte(), $this->starter()], 'PAKET');
|
||||
$review = $cart->review($tina);
|
||||
|
||||
$this->assertSame(0, $review->discountFor($review->lines[0]), 'Der enthaltene Artikel wird durch ein Paketziel nicht rabattfähig.');
|
||||
$this->assertSame(590, $review->discountFor($review->lines[1]));
|
||||
}
|
||||
|
||||
public function test_a_restricted_code_works_repeatedly_for_a_released_account_only(): void
|
||||
{
|
||||
$x = $this->code('ZERT', ['eligibility' => DiscountCode::RESTRICTED, 'percent' => 20]);
|
||||
$this->release($x, $this->tina());
|
||||
|
||||
$first = $this->orderWithCode($this->tina(), 'ZERT');
|
||||
$second = $this->orderWithCode($this->tina(), 'ZERT');
|
||||
|
||||
$this->assertSame(980, $first->discount_cents);
|
||||
$this->assertSame(980, $second->discount_cents, 'Das freigeschaltete Konto löst den Code bei späteren Bestellungen erneut ein.');
|
||||
|
||||
$result = $this->cartFor($this->max(), [$this->privateKonflikte()])->applyCode('ZERT', $this->max());
|
||||
$this->assertSame(DiscountResult::NO_RELEASE, $result->state);
|
||||
$this->assertStringContainsString('nicht freigeschaltet', (string) $result->message);
|
||||
$this->assertSame(0, app(Cart::class)->review($this->max())->discountCents(), 'Wer den Code kennt, aber keine Freigabe hat, erhält keinen Rabatt.');
|
||||
}
|
||||
|
||||
public function test_a_release_for_one_code_does_not_entitle_to_another_code(): void
|
||||
{
|
||||
$x = $this->code('CODEX', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$y = $this->code('CODEY', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$tina = $this->tina();
|
||||
$this->release($x, $tina);
|
||||
|
||||
$this->cartFor($tina, [$this->privateKonflikte()]);
|
||||
$this->assertTrue(app(Cart::class)->applyCode('CODEX', $tina)->applied());
|
||||
$blocked = app(Cart::class)->applyCode('CODEY', $tina);
|
||||
|
||||
$this->assertSame(DiscountResult::NO_RELEASE, $blocked->state);
|
||||
$this->assertSame($x->id, app(Cart::class)->discountCode()?->id, 'Der abgelehnte zweite Code ändert den bisherigen nicht.');
|
||||
|
||||
$this->release($y, $tina);
|
||||
$this->assertTrue(app(Cart::class)->applyCode('CODEY', $tina)->applied());
|
||||
$this->assertSame($y->id, app(Cart::class)->discountCode()?->id, 'Pro Bestellung gilt höchstens ein Code: der zweite ersetzt den ersten.');
|
||||
}
|
||||
|
||||
public function test_a_revoked_release_stops_the_discount_and_keeps_the_history(): void
|
||||
{
|
||||
$code = $this->code('ZERT', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$release = $this->release($code, $this->tina());
|
||||
$this->assertTrue($this->cartFor($this->tina(), [$this->privateKonflikte()])->applyCode('ZERT', $this->tina())->applied());
|
||||
|
||||
app(DiscountService::class)->revoke($release, $this->vera(), 'Zertifikat abgelaufen');
|
||||
|
||||
$review = app(Cart::class)->review($this->tina());
|
||||
$this->assertSame(DiscountResult::NO_RELEASE, $review->discount?->state);
|
||||
$this->assertSame(0, $review->discountCents());
|
||||
$this->assertTrue($review->discountBlocks());
|
||||
$this->assertFalse($review->canOrder(), 'Ein vorgemerkter Code, der nicht mehr gilt, hält die Bestellung an.');
|
||||
$this->assertNotNull($release->fresh()->revoked_at);
|
||||
$this->assertSame($this->vera()->id, $release->fresh()->revoked_by);
|
||||
$this->assertSame(1, DiscountRelease::query()->count(), 'Freigaben werden nie gelöscht.');
|
||||
$this->assertSame(DiscountResult::NO_RELEASE, app(Cart::class)->applyCode('ZERT', $this->tina())->state);
|
||||
}
|
||||
|
||||
public function test_a_release_can_have_an_end_date_and_cannot_be_granted_twice_or_for_an_open_code(): void
|
||||
{
|
||||
$code = $this->code('BEFRISTET', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$service = app(DiscountService::class);
|
||||
$service->release($code, $this->tina(), $this->vera(), now()->addDays(2));
|
||||
|
||||
$this->assertTrue($this->cartFor($this->tina(), [$this->privateKonflikte()])->applyCode('BEFRISTET', $this->tina())->applied());
|
||||
$this->travelTo(now()->addDays(3));
|
||||
$this->assertSame(DiscountResult::NO_RELEASE, app(Cart::class)->review($this->tina())->discount?->state);
|
||||
|
||||
$this->expectException(DomainRuleException::class);
|
||||
$service->release($this->code('OFFEN'), $this->tina(), $this->vera());
|
||||
}
|
||||
|
||||
public function test_an_expired_deactivated_or_not_yet_valid_code_explains_itself(): void
|
||||
{
|
||||
$tina = $this->tina();
|
||||
$this->code('ALT', ['valid_until' => '2026-11-20']);
|
||||
$this->code('AUS', ['active' => false]);
|
||||
$this->code('SPAETER', ['valid_from' => '2026-12-01']);
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte()]);
|
||||
|
||||
$expired = $cart->applyCode('ALT', $tina);
|
||||
$this->assertSame(DiscountResult::EXPIRED, $expired->state);
|
||||
$this->assertStringContainsString('abgelaufen', (string) $expired->message);
|
||||
$this->assertStringContainsString('20.11.2026', (string) $expired->message);
|
||||
$this->assertSame(DiscountResult::INACTIVE, $cart->applyCode('AUS', $tina)->state);
|
||||
$this->assertStringContainsString('01.12.2026', (string) $cart->applyCode('SPAETER', $tina)->message);
|
||||
$this->assertSame(DiscountResult::UNKNOWN, $cart->applyCode('GIBTESNICHT', $tina)->state);
|
||||
$this->assertNull($cart->discountCode());
|
||||
}
|
||||
|
||||
public function test_a_code_that_matches_no_position_says_so(): void
|
||||
{
|
||||
$this->code('NURGRENZEN', ['scope' => DiscountCode::SCOPE_SELECTED], [['type' => DiscountCode::TARGET_OFFER, 'id' => $this->privateGrenzen()->id]]);
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte()]);
|
||||
|
||||
$result = $cart->applyCode('NURGRENZEN', $tina);
|
||||
|
||||
$this->assertSame(DiscountResult::NO_MATCH, $result->state);
|
||||
$this->assertStringContainsString('keines davon liegt in deiner Bestellung', (string) $result->message);
|
||||
}
|
||||
|
||||
public function test_an_owned_position_is_not_discounted_and_does_not_count_as_a_match(): void
|
||||
{
|
||||
$tina = $this->tina();
|
||||
$order = $this->orderOf($tina, [$this->privateKonflikte()]);
|
||||
app(Checkout::class)->confirmTestPayment($order, 'test-own');
|
||||
$this->code('NURKONFLIKT', ['scope' => DiscountCode::SCOPE_SELECTED], [['type' => DiscountCode::TARGET_OFFER, 'id' => $this->privateKonflikte()->id]]);
|
||||
|
||||
$result = $this->cartFor($tina, [$this->privateKonflikte(), $this->privateGrenzen()])->applyCode('NURKONFLIKT', $tina);
|
||||
|
||||
$this->assertSame(DiscountResult::NO_MATCH, $result->state, 'Die bereits erworbene Position geht nicht in die Bestellung ein.');
|
||||
}
|
||||
|
||||
public function test_a_revoked_release_between_overview_and_order_creates_no_order(): void
|
||||
{
|
||||
$code = $this->code('ZERT', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$release = $this->release($code, $this->tina());
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte()], 'ZERT');
|
||||
$shown = $cart->review($tina)->digest();
|
||||
|
||||
app(DiscountService::class)->revoke($release, $this->vera());
|
||||
|
||||
try {
|
||||
app(Checkout::class)->placeFromCart($tina, $cart, null, $shown);
|
||||
$this->fail('Die Bestellung zum rabattierten Preis darf nicht entstehen.');
|
||||
} catch (StaleOverview) {
|
||||
$this->assertSame(0, Order::query()->count());
|
||||
}
|
||||
}
|
||||
|
||||
public function test_a_code_deactivated_between_overview_and_order_creates_no_order(): void
|
||||
{
|
||||
$code = $this->code('SOMMER10');
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte()], 'SOMMER10');
|
||||
$shown = $cart->review($tina)->digest();
|
||||
|
||||
app(DiscountService::class)->setActive($code, false);
|
||||
|
||||
$this->expectException(StaleOverview::class);
|
||||
app(Checkout::class)->placeFromCart($tina, $cart, null, $shown);
|
||||
}
|
||||
|
||||
public function test_a_blocked_code_must_be_removed_before_ordering_at_full_price(): void
|
||||
{
|
||||
$code = $this->code('SOMMER10');
|
||||
$tina = $this->tina();
|
||||
$cart = $this->cartFor($tina, [$this->privateKonflikte()], 'SOMMER10');
|
||||
app(DiscountService::class)->setActive($code, false);
|
||||
$review = $cart->review($tina);
|
||||
|
||||
$this->assertFalse($review->canOrder());
|
||||
$this->expectException(DomainRuleException::class);
|
||||
app(Checkout::class)->placeFromCart($tina, $cart, null, $review->digest());
|
||||
}
|
||||
|
||||
public function test_the_discount_may_not_push_the_payable_amount_below_the_payment_minimum(): void
|
||||
{
|
||||
$this->code('GRATIS', ['percent' => 100]);
|
||||
$tina = $this->tina();
|
||||
|
||||
$result = $this->cartFor($tina, [$this->privateGrenzen()])->applyCode('GRATIS', $tina);
|
||||
|
||||
$this->assertSame(DiscountResult::TOO_HIGH, $result->state);
|
||||
$this->assertStringContainsString('0,50 €', (string) $result->message);
|
||||
}
|
||||
|
||||
public function test_the_checkout_page_applies_and_removes_a_code_and_shows_the_discount_and_payable_amount(): void
|
||||
{
|
||||
$this->code('SOMMER10');
|
||||
$tina = $this->tina();
|
||||
$this->actingAs($tina)->post(route('cart.add', $this->privateKonflikte()));
|
||||
|
||||
$this->post(route('checkout.code'), ['code' => 'sommer10'])->assertRedirect(route('checkout'));
|
||||
$this->get(route('checkout'))
|
||||
->assertOk()
|
||||
->assertSee('SOMMER10')
|
||||
->assertSee('Zwischensumme')
|
||||
->assertSee('−4,90 €')
|
||||
->assertSee('44,10 €')
|
||||
->assertSee('Code entfernen');
|
||||
|
||||
$this->post(route('checkout.code.remove'))->assertRedirect(route('checkout'));
|
||||
$this->get(route('checkout'))->assertOk()->assertDontSee('Zwischensumme')->assertSee('49,00 €');
|
||||
|
||||
$this->post(route('checkout.code'), ['code' => 'GIBTESNICHT'])->assertSessionHasErrors('code');
|
||||
$this->post(route('checkout.code'), ['code' => ''])->assertSessionHasErrors('code');
|
||||
}
|
||||
|
||||
public function test_the_checkout_page_explains_a_missing_release_in_plain_words(): void
|
||||
{
|
||||
$this->code('ZERT', ['eligibility' => DiscountCode::RESTRICTED]);
|
||||
$this->actingAs($this->max())->post(route('cart.add', $this->privateKonflikte()));
|
||||
|
||||
$response = $this->post(route('checkout.code'), ['code' => 'ZERT'])->assertSessionHasErrors('code');
|
||||
$this->assertStringContainsString('nicht freigeschaltet', $response->getSession()->get('errors')->first('code'));
|
||||
$this->get(route('checkout'))->assertOk()->assertSee('49,00 €')->assertDontSee('Zwischensumme');
|
||||
}
|
||||
|
||||
public function test_codes_are_validated_when_saved(): void
|
||||
{
|
||||
$service = app(DiscountService::class);
|
||||
$base = ['label' => 'x', 'kind' => 'prozent', 'percent' => 10, 'scope' => 'warenkorb', 'eligibility' => 'allgemein'];
|
||||
|
||||
foreach ([
|
||||
['code' => 'a b'],
|
||||
['code' => 'OK1', 'label' => ''],
|
||||
['code' => 'OK1', 'percent' => 0],
|
||||
['code' => 'OK1', 'percent' => 101],
|
||||
['code' => 'OK1', 'kind' => 'betrag', 'amount_euro' => '0'],
|
||||
['code' => 'OK1', 'scope' => 'auswahl'],
|
||||
['code' => 'OK1', 'valid_from' => '2026-12-01', 'valid_until' => '2026-11-01'],
|
||||
] as $override) {
|
||||
try {
|
||||
$service->save([...$base, ...$override], []);
|
||||
$this->fail('Ungültige Angaben müssen abgewiesen werden: '.json_encode($override));
|
||||
} catch (DomainRuleException) {
|
||||
$this->assertSame(0, DiscountCode::query()->count());
|
||||
}
|
||||
}
|
||||
|
||||
$service->save([...$base, 'code' => 'ok1'], []);
|
||||
$this->expectException(DomainRuleException::class);
|
||||
$service->save([...$base, 'code' => 'OK1'], []);
|
||||
}
|
||||
|
||||
private function orderWithCode(User $user, string $code): Order
|
||||
{
|
||||
$cart = $this->cartFor($user, [$this->privateKonflikte()], $code);
|
||||
|
||||
return app(Checkout::class)->placeFromCart($user, $cart, null, $cart->review($user)->digest());
|
||||
}
|
||||
}
|
||||
@@ -273,11 +273,11 @@ public function test_the_checkout_page_places_the_order_through_the_http_flow():
|
||||
$this->actingAs($tina)->post(route('cart.add', $this->privateKonflikte()));
|
||||
$this->post(route('cart.add', $this->privateGrenzen()));
|
||||
|
||||
$page = $this->get(route('checkout'))->assertOk()->assertSee('Summe')->assertSee('78,00 €');
|
||||
$page = $this->get(route('checkout'))->assertOk()->assertSee('Zu zahlen')->assertSee('78,00 €');
|
||||
preg_match('/name="digest" value="([a-f0-9]{64})"/', $page->getContent(), $match);
|
||||
$this->assertNotEmpty($match);
|
||||
|
||||
$this->post(route('checkout.place'), ['digest' => $match[1]])->assertRedirect(route('member.order', Order::query()->latest('id')->first() ?? 1));
|
||||
$this->post(route('checkout.place'), ['digest' => $match[1], ...$this->consentFields()])->assertRedirect(route('member.order', Order::query()->latest('id')->first() ?? 1));
|
||||
$order = Order::query()->latest('id')->firstOrFail();
|
||||
$this->post(route('member.order.confirm', $order))->assertRedirect(route('member.library'));
|
||||
|
||||
|
||||
@@ -232,7 +232,8 @@ public function test_the_checkout_offers_the_choice_between_person_and_club_and_
|
||||
->assertOk()
|
||||
->assertSee('Testverein Musterstadt e. V.')
|
||||
->assertSee('Verein oder Organisation')
|
||||
->assertSee('Der Verein ist Lizenzinhaber')
|
||||
->assertSee('Lizenzinhaber')
|
||||
->assertSee('Nur dieses Konto, nicht weitere Mitglieder des Vereins.')
|
||||
->assertSee('149,00 €');
|
||||
$this->get(route('checkout', ['bestellen_als' => $vera->party_id]))
|
||||
->assertOk()
|
||||
|
||||
@@ -27,6 +27,12 @@ protected function seedShop(): void
|
||||
$this->seed(ShopDemoSeeder::class);
|
||||
}
|
||||
|
||||
/** Die Zustimmungen der Kasse (Pflichtangabe), wie das Formular sie sendet. */
|
||||
protected function consentFields(): array
|
||||
{
|
||||
return ['zustimmung' => ['agb' => '1', 'sofort' => '1']];
|
||||
}
|
||||
|
||||
protected function offerNamed(string $name): Offer
|
||||
{
|
||||
return Offer::query()->where('name', $name)->firstOrFail();
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountCalculator;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Rechenregel des Rabatts je Position (ganze Cent). Die Rundung ist eine Entscheidung zur Bestätigung durch Lars;
|
||||
* die Tests halten fest, was heute gilt.
|
||||
*/
|
||||
class DiscountCalculatorTest extends TestCase
|
||||
{
|
||||
public function test_a_percentage_is_rounded_per_line_half_up(): void
|
||||
{
|
||||
// Drei Positionen zu je 0,99 €, 50 %: je Position 49,5 Cent, aufgerundet auf 50 Cent.
|
||||
$discounts = DiscountCalculator::allocate(DiscountCode::PERCENT, 50, null, [1 => 99, 2 => 99, 3 => 99]);
|
||||
|
||||
$this->assertSame([1 => 50, 2 => 50, 3 => 50], $discounts);
|
||||
$this->assertSame(150, array_sum($discounts), 'Auf der Warenkorbsumme gerundet wären es 149 Cent.');
|
||||
}
|
||||
|
||||
public function test_a_percentage_never_exceeds_the_line_price(): void
|
||||
{
|
||||
$this->assertSame([1 => 4900], DiscountCalculator::allocate(DiscountCode::PERCENT, 100, null, [1 => 4900]));
|
||||
$this->assertSame([1 => 4900], DiscountCalculator::allocate(DiscountCode::PERCENT, 250, null, [1 => 4900]));
|
||||
$this->assertSame([1 => 0], DiscountCalculator::allocate(DiscountCode::PERCENT, 0, null, [1 => 4900]));
|
||||
}
|
||||
|
||||
public function test_a_fixed_amount_is_distributed_in_proportion_to_the_prices(): void
|
||||
{
|
||||
$this->assertSame([1 => 600, 2 => 400], DiscountCalculator::allocate(DiscountCode::AMOUNT, null, 1000, [1 => 3000, 2 => 2000]));
|
||||
}
|
||||
|
||||
public function test_the_remaining_cents_go_to_the_largest_remainder_and_the_sum_is_exact(): void
|
||||
{
|
||||
$discounts = DiscountCalculator::allocate(DiscountCode::AMOUNT, null, 100, [1 => 3333, 2 => 3333, 3 => 3334]);
|
||||
|
||||
$this->assertSame([1 => 33, 2 => 33, 3 => 34], $discounts);
|
||||
$this->assertSame(100, array_sum($discounts));
|
||||
}
|
||||
|
||||
public function test_a_fixed_amount_is_capped_at_the_affected_total(): void
|
||||
{
|
||||
$discounts = DiscountCalculator::allocate(DiscountCode::AMOUNT, null, 99999, [1 => 2900, 2 => 4900]);
|
||||
|
||||
$this->assertSame([1 => 2900, 2 => 4900], $discounts);
|
||||
}
|
||||
|
||||
public function test_nothing_to_discount_yields_nothing(): void
|
||||
{
|
||||
$this->assertSame([], DiscountCalculator::allocate(DiscountCode::PERCENT, 10, null, []));
|
||||
$this->assertSame([1 => 0], DiscountCalculator::allocate(DiscountCode::AMOUNT, null, 0, [1 => 100]));
|
||||
}
|
||||
|
||||
public function test_codes_are_normalised_without_spaces_and_in_capitals(): void
|
||||
{
|
||||
$this->assertSame('ZERT-2026', DiscountCode::normalise(' zert-2026 '));
|
||||
$this->assertSame('SOMMER10', DiscountCode::normalise('sommer 10'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user