Compare commits

...
Author SHA1 Message Date
LarsandClaude Sonnet 5.5 1d1f0ebb1f Binde das Favicon ein und lege Favicon und Kleingrafiken des Brand-Kits ab
CI Feature / test (push) Successful in 3m50s
Die Datei public/favicon.ico war leer; im head fehlte jeder Icon-Verweis.
- Favicon (ICO, SVG, Apple-Touch-Icon) in public/, gemeinsame Komponente
  x-site.favicon in Website-, Mitglieder- und Vorschau-Layouts
- Verwaltung: Icon per Render-Hook zur Anfragezeit statt ->favicon(asset()),
  weil asset() beim Start den falschen Host liefert
- FaviconTest (Dateien, Verweise, Adresse hinter dem Proxy)
- Brand-Kit: 15_Lara-Felix-Favicon und 16_Lara-Felix-Kleingrafiken (freigegeben)
- KIT_ERGAENZUNG_v2.1_kleingrafiken.md: Prüfung und Umsetzungsvorschlag

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 11:27:56 +01:00
LarsandClaude Sonnet 5.5 da02e0bbda Belege die Standardansicht des Zahlungsjournals je Umgebung auf luf-test
CI Feature / test (push) Successful in 3m27s
Deploy Test / test (push) Successful in 3m27s
Deploy Test / deploy (push) Successful in 34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 10:54:20 +01:00
LarsandClaude Sonnet 5.5 3f9e463dfa Zeige im Zahlungsjournal ausserhalb von Prod standardmaessig die Testzahlungen
CI Feature / test (push) Successful in 3m41s
Deploy Test / test (push) Successful in 3m39s
Deploy Test / deploy (push) Successful in 40s
Auf Prod bleibt die Ansicht bei den echten Zahlungen. Die Markierung der Buchung
(live) folgt weiter dem Modus des Zahlungsanbieters und nicht der Umgebung.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 10:43:18 +01:00
LarsandClaude Sonnet 5.5 03737a5fc7 Belege Rechnungsweg aus, Zahlungen je Angebot und Zahlungshistorie auf luf-test im Abnahmeprotokoll
CI Feature / test (push) Successful in 3m23s
Deploy Test / test (push) Successful in 3m43s
Deploy Test / deploy (push) Successful in 33s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 09:02:51 +01:00
LarsandClaude Sonnet 5.5 b453a8be10 Lass die Tabelle des Zahlungsjournals innen scrollen statt die Seite zu verbreitern
CI Feature / test (push) Successful in 3m42s
Deploy Test / test (push) Successful in 3m50s
Deploy Test / deploy (push) Successful in 37s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:52:58 +01:00
LarsandClaude Sonnet 5.5 a3c159a729 Behebe den Überlauf des Angebotshinweises im Zahlungsjournal
CI Feature / test (push) Successful in 3m45s
Deploy Test / test (push) Successful in 3m53s
Deploy Test / deploy (push) Successful in 39s
Der Hinweis mit fettem Text zerfiel in der Flex-Box in Spalten und verbreiterte die Seite.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:43:14 +01:00
LarsandClaude Sonnet 5.5 b3fb619bda Zeige auf der Bestellseite die Überschrift der Belege
CI Feature / test (push) Successful in 3m54s
Deploy Test / test (push) Successful in 3m27s
Deploy Test / deploy (push) Successful in 39s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:33:32 +01:00
LarsandClaude Sonnet 5.5 78c8870e4e Füge Zahlungshistorie und Einzelbeleg (PDF) im Mitgliederbereich hinzu
CI Feature / test (push) Successful in 3m23s
Deploy Test / test (push) Successful in 3m45s
Deploy Test / deploy (push) Successful in 39s
Mein Konto, Zahlungen: eigene Zahlungen und Rückzahlungen mit Beleg als PDF, auch von der
Bestellseite verlinkt. Der Beleg entsteht aus den bei der Buchung festgehaltenen Angaben und ist
byte-gleich; er heißt nie Rechnung und trägt weder Rechnungsnummer noch Steuerangaben. Kleiner
PDF-Schreiber ohne neue Abhängigkeit. Aussteller und Hinweis nur bei Pflege (SHOP_RECEIPT_*).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:23:40 +01:00
LarsandClaude Sonnet 5.5 dd3cc83057 Zeige im Zahlungsjournal die Zahlungen je gekauftem Angebot
Filter nach Angebot mit dem Anteil des Angebots an der Bestellung (Preis nach Rabatt), damit eine
Bestellung mit mehreren Angeboten den Umsatz des einzelnen nicht überzeichnet. Zusätzliche CSV-Spalte,
Link von der Angebotsseite.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:16:13 +01:00
LarsandClaude Sonnet 5.5 32272e8e40 Biete den Kauf auf Rechnung im Frontend erst bei vollständigem Prozess an
SHOP_INVOICE ist jetzt standardmäßig aus; die Umsetzung bleibt vollständig erhalten, vorhandene
Rechnungsbestellungen bleiben in der Verwaltung bearbeitbar. Zwei Tests schalten die Option bewusst
ein, zwei neue prüfen Standard (nicht angeboten, gefälschte Anfrage abgewiesen) und Weiterbearbeitung.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:14:04 +01:00
LarsandClaude Sonnet 5.5 9db3a98440 Belege das Zahlungsjournal auf luf-test im Abnahmeprotokoll
CI Feature / test (push) Successful in 3m33s
Deploy Test / test (push) Successful in 3m47s
Deploy Test / deploy (push) Successful in 41s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 07:56:18 +01:00
LarsandClaude Sonnet 5.5 f87e67ce02 Verhindere Umbruch von Datum und Bestellnummer im Zahlungsjournal
CI Feature / test (push) Successful in 3m58s
Deploy Test / test (push) Successful in 3m32s
Deploy Test / deploy (push) Successful in 39s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 07:46:01 +01:00
LarsandClaude Sonnet 5.5 fe39e1efb6 Führe ein unveränderliches Zahlungsjournal mit Ansicht und CSV-Export ein
CI Feature / test (push) Successful in 3m41s
Deploy Test / test (push) Successful in 3m34s
Deploy Test / deploy (push) Successful in 46s
Jede Zahlung und jede Erstattung wird in derselben Transaktion wie der Bestellstatus
unveränderlich gebucht: Zeitpunkt, Betrag, Beleg beim Anbieter (Session, pi_, re_), handelnde
Person, Begründung und Zahler samt Rechnungsadresse zum Zeitpunkt. Testzahlungen zählen nie
als Umsatz. Verwaltung: Verkauf, Einnahmen und Erstattungen mit Zeitraum, Summen und Export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 07:34:41 +01:00
LarsandClaude Sonnet 5.5 6518d1b80f Belege die Verkaufsstart-Etappe auf luf-test im Abnahmeprotokoll
CI Feature / test (push) Successful in 2m52s
Deploy Test / test (push) Successful in 3m6s
Deploy Test / deploy (push) Successful in 34s
Abschnitt im Abnahmeprotokoll mit geprüftem Commit, Workflow-Status, Klickfolge,
Browserbelegen, nicht geprüften Punkten (Verein, PDF, Stripe-Wiederholung, Mail)
und offenen Freigabepunkten. Nur Dokumentation; der Anwendungscode entspricht 69a22de.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 22:46:50 +01:00
LarsandClaude Sonnet 5.5 69a22deb1f Sichere Rechnungs- und Livepfad ab und dokumentiere die Entscheidungen zum Verkaufsstart
CI Feature / test (push) Successful in 2m52s
Deploy Test / test (push) Successful in 2m40s
Deploy Test / deploy (push) Successful in 40s
Eine Bestellung auf Rechnung lässt sich auch mit dem Stripe-Treiber nicht per Karte
bezahlen; der Betreiber, der den Zahlungseingang bestätigt, wird an der Zahlung
festgehalten; im Livebetrieb ist der alte Einzelkauf ohne Pflichtangaben gesperrt und
placeFromCart verlangt die Zustimmungen. ADR-47, Domänenmodell, Lizenzlogik,
Kernabläufe, Szenarien, Fachanforderungen und DEPLOYMENT nachgeführt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 20:11:24 +01:00
LarsandClaude Sonnet 5.5 f0287eec2f Mache den Anmeldetest deterministisch und entferne die doppelte Meldung in der Kasse
CI Feature / test (push) Successful in 3m26s
RegistrationTest: Der Name kam aus dem Faker und enthielt gelegentlich ein
Apostroph (O'Hara), das im HTML maskiert wird; der Test schlug dadurch zufällig im
Gitea-Lauf fehl. Der Name ist jetzt fest, die Assertion unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 20:02:41 +01:00
LarsandClaude Sonnet 5.5 42e0a6bb93 Mache den Download bei reiner Download-Lizenz erreichbar und zeige den Stand zum Verkaufsstart
CI Feature / test (push) Failing after 3m2s
Die Artikelseite zeigte bei einer Lizenz nur zum Herunterladen (kein Streamen oder
Ansehen) "Nicht enthalten"; jetzt bietet sie den Download. Tests belegen Einzelfilm
und Begleit-PDF aus der Bibliothek mit Dateiname und Zugriffsgrenzen. Neue
Verwaltungsseite Verkaufsstart nennt fehlende Rechtstexte und den Zustand der
Zahlungseinrichtung, ohne Schlüssel zu zeigen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:58:22 +01:00
LarsandClaude Sonnet 5.5 76fab81386 Verwalte Rabattcodes mit Kontofreigabe und Bestellungen mit Rechnungsweg und Erstattung
Neue Verwaltungsseiten Rabattcodes (Anlegen und Bearbeiten in einer Maske, Konten
für genau diesen Code freischalten und entziehen) und Bestellungen (Zahlungseingang
bei Rechnung bestätigen, vollständig erstatten). Der Nutzerkreis ist in der
Angebotsmaske ein Pflichtfeld. BestandslisteTest: die Fassung ohne Nutzerkreis
verlangt jetzt dessen Angabe beim Bearbeiten; die geprüfte Aussage (verdeckte
Konditionen bleiben erhalten) ist unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:53:56 +01:00
LarsandClaude Sonnet 5.5 1ce2e1e51f Gib Paketen eine eigene Produktseite und ergänze Tests zu Nutzerkreis und Verkaufsstart
Ein eigenständig vermarktetes Paket (offers.standalone_bundle) erhält /pakete/{id}
mit seinem tatsächlichen Umfang, Shop-Kachel und Suche. Die Angebotsmaske kennt
Nutzerkreis und Anzahl Trainer. Zwei Bestandstests (CartTest, Vergleich der
Rechte und Erwerbsarten) legen die Vergleichsangebote jetzt als Einzellizenz an,
weil der Nutzerkreis zum identischen Umfang gehört; ihre Aussagen bleiben.
Eine Rechnungs- oder Stripe-Bestellung lässt sich nicht mit der Testzahlung bestätigen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:47:15 +01:00
LarsandClaude Sonnet 5.5 0154182f3b 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>
2026-11-22 19:42:02 +01:00
245 changed files with 7989 additions and 147 deletions

No files matched your search

+90
View File
@@ -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)',
];
}
}
+8
View File
@@ -12,8 +12,16 @@ class Offer extends Model
'name', 'name',
'composition_id', 'composition_id',
'option_label', 'option_label',
'standalone_bundle',
]; ];
protected function casts(): array
{
return [
'standalone_bundle' => 'boolean',
];
}
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */ /** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
public function composition(): BelongsTo public function composition(): BelongsTo
{ {
+42 -1
View File
@@ -102,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
'dynamic' => false, 'dynamic' => false,
'grant_kind' => 'kauf', 'grant_kind' => 'kauf',
'holder_kind' => 'person', 'holder_kind' => 'person',
'licence_scope' => null,
'trainer_count' => null,
], $attributes); ], $attributes);
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
}
$this->assertAttributes($attributes); $this->assertAttributes($attributes);
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
$scope = $this->scopeFor($lines); $scope = $this->scopeFor($lines);
$this->assertSellableContent($scope);
$this->assertCoverage($lines, $attributes); $this->assertCoverage($lines, $attributes);
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion { return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
@@ -126,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
'dynamic' => $attributes['dynamic'], 'dynamic' => $attributes['dynamic'],
'grant_kind' => $attributes['grant_kind'], 'grant_kind' => $attributes['grant_kind'],
'holder_kind' => $attributes['holder_kind'], 'holder_kind' => $attributes['holder_kind'],
'licence_scope' => $attributes['licence_scope'],
'trainer_count' => $attributes['trainer_count'],
]); ]);
foreach (array_values($lines) as $index => $line) { foreach (array_values($lines) as $index => $line) {
@@ -176,13 +186,18 @@ public function end(Offer $offer): OfferVersion
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe, * Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen. * die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
*/ */
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel): Offer public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
{ {
if ($compositionId !== null) { if ($compositionId !== null) {
Composition::query()->findOrFail($compositionId); Composition::query()->findOrFail($compositionId);
} }
if ($ownBundlePage && $compositionId !== null) {
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
}
$offer->composition_id = $compositionId; $offer->composition_id = $compositionId;
$offer->standalone_bundle = $ownBundlePage;
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null; $offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
$offer->save(); $offer->save();
@@ -219,6 +234,32 @@ private function assertAttributes(array $attributes): void
} }
} }
/**
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
*
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
*/
private function assertSellableContent(array $scope): void
{
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
if ($missing->isEmpty()) {
return;
}
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
.($missing->count() === 1 ? ' hat' : ' haben')
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
}
/** /**
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines * @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
* @return list<array{license_article_id: int, rights_profile_version_id: int}> * @return list<array{license_article_id: int, rights_profile_version_id: int}>
+2
View File
@@ -19,6 +19,8 @@ class OfferVersion extends Model
'dynamic', 'dynamic',
'grant_kind', 'grant_kind',
'holder_kind', 'holder_kind',
'licence_scope',
'trainer_count',
'activated_at', 'activated_at',
]; ];
+62 -6
View File
@@ -6,6 +6,9 @@
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferVersion; 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\Party;
use App\Domain\Identity\PartyType; use App\Domain\Identity\PartyType;
use App\Models\User; use App\Models\User;
@@ -20,6 +23,9 @@ class Cart
{ {
public const KEY = 'shop.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 ADDED = 'added';
public const PRESENT = 'present'; public const PRESENT = 'present';
@@ -32,6 +38,7 @@ public function __construct(
private readonly OwnershipCheck $ownership, private readonly OwnershipCheck $ownership,
private readonly OrderHolders $holders, private readonly OrderHolders $holders,
private readonly OfferService $offers, private readonly OfferService $offers,
private readonly DiscountService $discounts,
) {} ) {}
/** /**
@@ -57,7 +64,10 @@ public function has(Offer $offer): bool
*/ */
public function alternativeTo(Offer $offer): ?Offer public function alternativeTo(Offer $offer): ?Offer
{ {
if ($offer->composition_id === null) { $products = app(ProductOptions::class);
$group = $products->groupKey($offer);
if ($group === null) {
return null; return null;
} }
@@ -65,8 +75,8 @@ public function alternativeTo(Offer $offer): ?Offer
return $ids === [] ? null : Offer::query() return $ids === [] ? null : Offer::query()
->whereIn('id', $ids) ->whereIn('id', $ids)
->where('composition_id', $offer->composition_id) ->get()
->first(); ->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
} }
public function add(Offer $offer): string public function add(Offer $offer): string
@@ -133,13 +143,51 @@ public function acceptCurrent(Offer $offer): void
public function clear(): 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. * 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() $offers = Offer::query()
->whereIn('id', array_keys($this->items())) ->whereIn('id', array_keys($this->items()))
@@ -203,7 +251,15 @@ public function review(?User $user = null, ?int $holderPartyId = null): CartRevi
} }
} }
return new CartReview($lines, $holder); $code = $this->discountCode();
$discount = null;
if ($code !== null) {
$orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable()));
$discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount);
}
return new CartReview($lines, $holder, $discount);
} }
/** /**
+8
View File
@@ -45,6 +45,14 @@ public function blocks(): bool
public function title(): string public function title(): string
{ {
if ($this->offer->standalone_bundle && $this->version !== null) {
$bundle = app(ProductOptions::class)->bundleOf($this->version);
if ($bundle !== null) {
return (string) $bundle->name;
}
}
$composition = $this->offer->composition; $composition = $this->offer->composition;
return $composition !== null return $composition !== null
+29 -3
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Commerce; namespace App\Domain\Commerce;
use App\Domain\Commerce\Discount\DiscountResult;
use App\Domain\Identity\Party; use App\Domain\Identity\Party;
/** /**
@@ -16,6 +17,7 @@ final class CartReview
public function __construct( public function __construct(
public readonly array $lines, public readonly array $lines,
public readonly ?Party $holder, public readonly ?Party $holder,
public readonly ?DiscountResult $discount = null,
) {} ) {}
/** @return list<CartLine> */ /** @return list<CartLine> */
@@ -24,11 +26,35 @@ public function orderable(): array
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable())); 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())); 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 public function blocked(): bool
{ {
foreach ($this->lines as $line) { foreach ($this->lines as $line) {
@@ -47,7 +73,7 @@ public function empty(): bool
public function canOrder(): 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 public function digest(): string
@@ -60,6 +86,6 @@ public function digest(): string
sort($parts); sort($parts);
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts)); return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
} }
} }
+150 -20
View File
@@ -6,14 +6,18 @@
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferVersion; 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\Acquisition;
use App\Domain\Entitlement\AcquisitionType; use App\Domain\Entitlement\AcquisitionType;
use App\Domain\Entitlement\GrantIssuer; use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Entitlement\GrantStatus; use App\Domain\Entitlement\GrantStatus;
use App\Domain\Identity\AccountStatus; use App\Domain\Identity\AccountStatus;
use App\Domain\Identity\Party; use App\Domain\Identity\Party;
use App\Domain\Identity\PartyType;
use App\Mail\OrderConfirmed; use App\Mail\OrderConfirmed;
use App\Models\User; use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Mail;
@@ -23,6 +27,7 @@ public function __construct(
private readonly GrantIssuer $grants, private readonly GrantIssuer $grants,
private readonly OfferService $offers, private readonly OfferService $offers,
private readonly OrderHolders $holders, private readonly OrderHolders $holders,
private readonly PaymentJournal $journal,
) {} ) {}
/** /**
@@ -32,6 +37,12 @@ public function place(User $user, Offer $offer): Order
{ {
$this->assertActive($user); $this->assertActive($user);
// Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den
// Weg über die Kasse mit Pflichtangaben.
if (Shop::live()) {
throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.');
}
$version = $this->offers->currentActiveVersion($offer); $version = $this->offers->currentActiveVersion($offer);
if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') { if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
@@ -44,7 +55,7 @@ public function place(User $user, Offer $offer): Order
$holder = $this->holders->resolve($user, null); $holder = $this->holders->resolve($user, null);
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]])); return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
} }
/** /**
@@ -53,14 +64,25 @@ public function place(User $user, Offer $offer): Order
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits * Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
* mit denselben Rechten besitzt, erzeugen keine Bestellposition. * 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); $this->assertActive($user);
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest): Order { if ($consent === null && Shop::live()) {
// Optionen sperren, damit eine gleichzeitige Aktivierung die Prüfung nicht unterläuft. throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
}
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order {
// Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug
// der Freigabe die Prüfung nicht unterläuft.
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get(); 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) { if ($review->holder === null) {
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.'); throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
@@ -78,9 +100,19 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.'); 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()); $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(); $cart->clear();
@@ -90,16 +122,28 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
/** /**
* @param list<array{0: Offer, 1: OfferVersion}> $pairs * @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([ $order = Order::query()->create([
'user_id' => $user->id, 'user_id' => $user->id,
'party_id' => $holder->id, 'party_id' => $holder->id,
'status' => 'offen', 'status' => 'offen',
'holder_kind' => $holder->type->value, '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', '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]) { foreach ($pairs as [$offer, $version]) {
@@ -114,6 +158,9 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
'tax_class' => $version->tax_class, 'tax_class' => $version->tax_class,
'grant_kind' => $version->grant_kind, 'grant_kind' => $version->grant_kind,
'holder_party_id' => $holder->id, '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'); $version->load('resolvedScopes.rights');
@@ -140,26 +187,49 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
public function confirmTestPayment(Order $order, string $reference): Order public function confirmTestPayment(Order $order, string $reference): Order
{ {
$this->assertTestDriver(); $this->assertTestDriver();
$this->assertTestOrder($order);
return $this->settle($order, 'test', $reference); return $this->settle($order, 'test', $reference, null, now(), false);
} }
/** /**
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die * Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
* Bestellung. Wiederholte Meldungen sind wirkungslos. * Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet
* es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung
* laut Anbieter, sonst jetzt.
*/ */
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): Order public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order
{ {
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents')); $expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents'));
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) { if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.'); throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
} }
return $this->settle($order, $provider, $reference); return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
} }
private function settle(Order $order, string $provider, string $reference): Order /**
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf
* dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in
* welchen Zeitraum die Einnahme fällt.
*/
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
{
$order->refresh();
if ($order->payment_method !== 'rechnung') {
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
}
$day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at);
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live());
}
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
{ {
$reference = trim($reference); $reference = trim($reference);
@@ -168,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
} }
$paidNow = false; $paidNow = false;
$order = DB::transaction(function () use ($order, $provider, $reference, &$paidNow): Order { $order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id); $order = Order::query()->lockForUpdate()->findOrFail($order->id);
if ($order->status === 'bezahlt') { if ($order->status === 'bezahlt') {
@@ -180,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference): Orde
} }
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt. // Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
$order->payments()->updateOrCreate( $payment = $order->payments()->updateOrCreate(
['provider_reference' => $reference], ['provider_reference' => $reference],
['provider' => $provider, 'status' => 'bestaetigt'], array_filter(
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
fn (mixed $value): bool => $value !== null,
),
); );
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
$order->status = 'bezahlt'; $order->status = 'bezahlt';
$order->save(); $order->save();
$paidNow = true; $paidNow = true;
@@ -207,6 +281,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
public function failTestPayment(Order $order, string $reference): Order public function failTestPayment(Order $order, string $reference): Order
{ {
$this->assertTestDriver(); $this->assertTestDriver();
$this->assertTestOrder($order);
return DB::transaction(function () use ($order, $reference): Order { return DB::transaction(function () use ($order, $reference): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id); $order = Order::query()->lockForUpdate()->findOrFail($order->id);
@@ -229,9 +304,14 @@ public function failTestPayment(Order $order, string $reference): Order
/** /**
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen * Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. * (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
*/ */
public function refund(Order $order, string $reason): Order public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order
{ {
$reason = trim($reason); $reason = trim($reason);
@@ -239,7 +319,17 @@ public function refund(Order $order, string $reason): Order
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.'); throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
} }
return DB::transaction(function () use ($order, $reason): Order { $current = Order::query()->findOrFail($order->id);
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
$manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at);
$booking = null;
if ($current->status === 'bezahlt' && $stripePayment !== null) {
$result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
$booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()];
}
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
$order = Order::query()->lockForUpdate()->findOrFail($order->id); $order = Order::query()->lockForUpdate()->findOrFail($order->id);
if ($order->status !== 'bezahlt') { if ($order->status !== 'bezahlt') {
@@ -262,6 +352,16 @@ public function refund(Order $order, string $reason): Order
} }
} }
$payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first();
$this->journal->recordRefund(
$order,
$payment,
$booking['at'] ?? $manualAt,
$actor,
$reason,
$booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id),
$booking['status'] ?? null,
);
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']); $order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
$order->status = 'erstattet'; $order->status = 'erstattet';
$order->save(); $order->save();
@@ -270,6 +370,28 @@ public function refund(Order $order, string $reason): Order
}); });
} }
/**
* Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und
* erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit
* ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung.
*/
public function requestWithdrawal(Order $order, string $note): Order
{
if (! in_array($order->status, ['bezahlt', 'offen'], true)) {
throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.');
}
if ($order->withdrawal_requested_at !== null) {
return $order;
}
$order->withdrawal_requested_at = now();
$order->withdrawal_note = trim($note) !== '' ? trim($note) : null;
$order->save();
return $order;
}
private function assertActive(User $user): void private function assertActive(User $user): void
{ {
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) { if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
@@ -277,6 +399,14 @@ private function assertActive(User $user): void
} }
} }
/** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */
private function assertTestOrder(Order $order): void
{
if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) {
throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.');
}
}
private function assertTestDriver(): void private function assertTestDriver(): void
{ {
if (app()->isProduction() || config('services.payment.driver') !== 'test') { if (app()->isProduction() || config('services.payment.driver') !== 'test') {
@@ -0,0 +1,74 @@
<?php
namespace App\Domain\Commerce\Discount;
/**
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
*
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
*
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
* frühere Position.
*/
final class DiscountCalculator
{
/**
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
* @return array<int|string, int> Schlüssel => Rabatt in Cent
*/
public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array
{
$discounts = array_fill_keys(array_keys($prices), 0);
if ($prices === []) {
return $discounts;
}
if ($kind === DiscountCode::PERCENT) {
$percent = max(0, min(100, (int) $percent));
foreach ($prices as $key => $price) {
$discounts[$key] = min($price, intdiv($price * $percent + 50, 100));
}
return $discounts;
}
$sum = array_sum($prices);
$total = min(max(0, (int) $amountCents), $sum);
if ($total === 0 || $sum === 0) {
return $discounts;
}
$remainders = [];
$given = 0;
foreach ($prices as $key => $price) {
$share = intdiv($total * $price, $sum);
$discounts[$key] = $share;
$remainders[$key] = ($total * $price) % $sum;
$given += $share;
}
$rest = $total - $given;
$order = array_keys($prices);
usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]);
foreach ($order as $key) {
if ($rest === 0) {
break;
}
if ($discounts[$key] < $prices[$key]) {
$discounts[$key]++;
$rest--;
}
}
return $discounts;
}
}
@@ -0,0 +1,103 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Domain\Commerce\Money;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
*/
class DiscountCode extends Model
{
public const PERCENT = 'prozent';
public const AMOUNT = 'betrag';
public const SCOPE_CART = 'warenkorb';
public const SCOPE_SELECTED = 'auswahl';
public const OPEN = 'allgemein';
public const RESTRICTED = 'freigabe';
public const TARGET_OFFER = 'angebot';
public const TARGET_ARTICLE = 'lizenzartikel';
public const TARGET_BUNDLE = 'paket';
protected $fillable = [
'code',
'label',
'kind',
'percent',
'amount_cents',
'scope',
'eligibility',
'valid_from',
'valid_until',
'active',
'note',
];
protected function casts(): array
{
return [
'valid_from' => 'datetime',
'valid_until' => 'datetime',
'active' => 'boolean',
];
}
/** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */
public static function normalise(string $input): string
{
return mb_strtoupper((string) preg_replace('/\s+/u', '', $input));
}
public function targets(): HasMany
{
return $this->hasMany(DiscountCodeTarget::class);
}
public function releases(): HasMany
{
return $this->hasMany(DiscountRelease::class)->latest('id');
}
public function restricted(): bool
{
return $this->eligibility === self::RESTRICTED;
}
public function forSelection(): bool
{
return $this->scope === self::SCOPE_SELECTED;
}
/** Lesbare Höhe: „10 %“ oder „5,00 €“. */
public function valueLabel(): string
{
return $this->kind === self::PERCENT
? (int) $this->percent.' %'
: Money::format((int) $this->amount_cents);
}
/** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */
public function stateAt(CarbonInterface $now): string
{
return match (true) {
! $this->active => 'deaktiviert',
$this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht',
$this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen',
default => 'aktiv',
};
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Domain\Commerce\Discount;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
*/
class DiscountCodeTarget extends Model
{
protected $fillable = [
'discount_code_id',
'target_type',
'target_id',
];
public function code(): BelongsTo
{
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
*/
class DiscountRelease extends Model
{
protected $table = 'discount_code_releases';
protected $fillable = [
'discount_code_id',
'user_id',
'granted_by',
'granted_at',
'valid_until',
'revoked_by',
'revoked_at',
'reason',
];
protected function casts(): array
{
return [
'granted_at' => 'datetime',
'valid_until' => 'datetime',
'revoked_at' => 'datetime',
];
}
public function code(): BelongsTo
{
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function grantor(): BelongsTo
{
return $this->belongsTo(User::class, 'granted_by');
}
public function isActiveAt(CarbonInterface $now): bool
{
return $this->revoked_at === null
&& $this->granted_at->lessThanOrEqualTo($now)
&& ($this->valid_until === null || $this->valid_until->greaterThan($now));
}
}
@@ -0,0 +1,83 @@
<?php
namespace App\Domain\Commerce\Discount;
/**
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
* den Grund erfährt.
*/
final class DiscountResult
{
public const OK = 'ok';
public const UNKNOWN = 'unbekannt';
public const INACTIVE = 'deaktiviert';
public const NOT_YET = 'noch_nicht';
public const EXPIRED = 'abgelaufen';
public const LOGIN = 'anmeldung';
public const NO_RELEASE = 'keine_freigabe';
public const NO_MATCH = 'keine_position';
public const TOO_HIGH = 'zu_hoch';
/**
* @param array<int, int> $perOffer Kennung der Option => Rabatt in Cent
*/
public function __construct(
public readonly ?DiscountCode $code,
public readonly string $state,
public readonly ?string $message = null,
public readonly array $perOffer = [],
) {}
public function applied(): bool
{
return $this->state === self::OK && $this->totalCents() > 0;
}
public function totalCents(): int
{
return $this->state === self::OK ? array_sum($this->perOffer) : 0;
}
public function forOffer(int $offerId): int
{
return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0;
}
/** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */
public function snapshot(): array
{
return [
'code' => $this->code?->code,
'label' => $this->code?->label,
'kind' => $this->code?->kind,
'percent' => $this->code?->percent,
'amount_cents' => $this->code?->amount_cents,
'scope' => $this->code?->scope,
'eligibility' => $this->code?->eligibility,
'discount_cents' => $this->totalCents(),
];
}
/** Teil der Prüfsumme der Bestellübersicht. */
public function digestPart(): string
{
$parts = [];
$perOffer = $this->perOffer;
ksort($perOffer);
foreach ($perOffer as $offerId => $cents) {
$parts[] = $offerId.'='.$cents;
}
return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts);
}
}
@@ -0,0 +1,327 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Commerce\CartLine;
use App\Domain\Commerce\Money;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
/**
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
*/
class DiscountService
{
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
public const MIN_PAYABLE_CENTS = 50;
public function find(string $input): ?DiscountCode
{
$code = DiscountCode::normalise($input);
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
}
/**
* @param list<CartLine> $lines nur Positionen, die in die Bestellung eingehen
*/
public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult
{
$now ??= now();
$timing = $code->stateAt($now);
if ($timing !== 'aktiv') {
return new DiscountResult($code, $timing, match ($timing) {
'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.',
'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.',
default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').',
});
}
if ($code->restricted()) {
if ($user === null) {
return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.');
}
if ($this->activeRelease($code, $user, $now, $lock) === null) {
return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.');
}
}
$matching = [];
foreach ($lines as $line) {
if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) {
$matching[$line->offer->id] = (int) $line->currentPriceCents;
}
}
if ($matching === []) {
return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection()
? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.'
: 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.');
}
$perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching);
$payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer);
if ($payable < self::MIN_PAYABLE_CENTS) {
return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.');
}
return new DiscountResult($code, DiscountResult::OK, null, $perOffer);
}
/**
* Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der
* Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht
* rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig.
*/
public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool
{
if (! $code->forSelection()) {
return true;
}
$targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all());
if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) {
return true;
}
$version->loadMissing('lines.bundleVersion');
foreach ($version->lines as $line) {
if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) {
return true;
}
if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) {
return true;
}
}
return false;
}
public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease
{
$now ??= now();
$query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at');
if ($lock) {
$query->lockForUpdate();
}
return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now));
}
/**
* Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten.
*
* @param array<string, mixed> $data
* @param list<array{type: string, id: int}> $targets
*/
public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode
{
$code = DiscountCode::normalise((string) ($data['code'] ?? ''));
$label = trim((string) ($data['label'] ?? ''));
if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) {
throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.');
}
if ($label === '') {
throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.');
}
if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) {
throw new DomainRuleException('Diesen Code gibt es schon.');
}
$kind = (string) ($data['kind'] ?? '');
$percent = null;
$amount = null;
if ($kind === DiscountCode::PERCENT) {
$percent = (int) ($data['percent'] ?? 0);
if ($percent < 1 || $percent > 100) {
throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.');
}
} elseif ($kind === DiscountCode::AMOUNT) {
$amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null));
if ($amount === null || $amount <= 0) {
throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.');
}
} else {
throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.');
}
$scope = (string) ($data['scope'] ?? '');
$eligibility = (string) ($data['eligibility'] ?? '');
if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) {
throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.');
}
if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) {
throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.');
}
$targets = $this->cleanTargets($targets);
if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) {
throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.');
}
$from = $this->date($data['valid_from'] ?? null);
$until = $this->date($data['valid_until'] ?? null, true);
if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) {
throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.');
}
return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode {
$model = $existing ?? new DiscountCode;
$model->fill([
'code' => $code,
'label' => $label,
'kind' => $kind,
'percent' => $percent,
'amount_cents' => $amount,
'scope' => $scope,
'eligibility' => $eligibility,
'valid_from' => $from,
'valid_until' => $until,
'active' => (bool) ($data['active'] ?? true),
'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null,
]);
$model->save();
$model->targets()->delete();
if ($scope === DiscountCode::SCOPE_SELECTED) {
foreach ($targets as $target) {
$model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]);
}
}
return $model->load('targets');
});
}
public function setActive(DiscountCode $code, bool $active): DiscountCode
{
$code->active = $active;
$code->save();
return $code;
}
/**
* Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht.
*/
public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease
{
if (! $code->restricted()) {
throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.');
}
if ($member->party_id === null) {
throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.');
}
return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease {
DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail();
if ($this->activeRelease($code, $member) !== null) {
throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.');
}
if ($until !== null && $until->lessThanOrEqualTo(now())) {
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
}
return DiscountRelease::query()->create([
'discount_code_id' => $code->id,
'user_id' => $member->id,
'granted_by' => $actor?->id,
'granted_at' => now(),
'valid_until' => $until,
'reason' => filled($reason) ? trim((string) $reason) : null,
]);
});
}
/**
* Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert.
*/
public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease
{
return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease {
$release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id);
if ($release->revoked_at !== null) {
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
}
$release->revoked_at = now();
$release->revoked_by = $actor?->id;
$release->reason = filled($reason) ? trim((string) $reason) : $release->reason;
$release->save();
return $release;
});
}
/**
* @param list<array{type: string, id: int}> $targets
* @return list<array{type: string, id: int}>
*/
private function cleanTargets(array $targets): array
{
$clean = [];
foreach ($targets as $target) {
$type = (string) ($target['type'] ?? '');
$id = (int) ($target['id'] ?? 0);
$exists = match ($type) {
DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(),
DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(),
DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(),
default => false,
};
if (! $exists) {
throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).');
}
$clean[$type.':'.$id] = ['type' => $type, 'id' => $id];
}
return array_values($clean);
}
/** Ein Datum ohne Uhrzeit gilt als Tag: ab Tagesbeginn, als Ende einschließlich des ganzen Tages. */
private function date(mixed $value, bool $endOfDay = false): ?CarbonInterface
{
if (! filled($value)) {
return null;
}
$date = Carbon::parse((string) $value, config('app.timezone'));
return $endOfDay && strlen(trim((string) $value)) <= 10 ? $date->endOfDay() : $date;
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Domain\Commerce;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use LogicException;
/**
* Eine Geldbewegung im Zahlungsjournal (Zahlungseingang oder Erstattung). Unveränderlich: Eine Zeile wird nur
* angelegt, nie geändert oder gelöscht. Eine Korrektur ist eine neue Gegenbuchung. Beträge sind vorzeichenbehaftet
* (Eingang positiv, Erstattung negativ), sodass die Summe den Saldo ergibt.
*/
class LedgerEntry extends Model
{
public const KIND_PAYMENT = 'eingang';
public const KIND_REFUND = 'erstattung';
public const UPDATED_AT = null;
protected $table = 'payment_ledger';
protected $guarded = [];
protected function casts(): array
{
return [
'occurred_at' => 'datetime',
'amount_cents' => 'integer',
'live' => 'boolean',
'derived' => 'boolean',
'payer' => 'array',
'order_snapshot' => 'array',
];
}
protected static function booted(): void
{
static::updating(function (): never {
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.');
});
static::deleting(function (): never {
throw new LogicException('Das Zahlungsjournal ist unveränderlich. Einträge werden nie gelöscht.');
});
}
public function order(): BelongsTo
{
return $this->belongsTo(Order::class);
}
public function isRefund(): bool
{
return $this->kind === self::KIND_REFUND;
}
}
+31
View File
@@ -17,8 +17,39 @@ class Order extends Model
'holder_kind', 'holder_kind',
'total_cents', 'total_cents',
'currency', '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 public function user(): BelongsTo
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
+9
View File
@@ -22,8 +22,17 @@ class OrderLine extends Model
'tax_class', 'tax_class',
'grant_kind', 'grant_kind',
'holder_party_id', '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 public function order(): BelongsTo
{ {
return $this->belongsTo(Order::class); return $this->belongsTo(Order::class);
+12
View File
@@ -2,6 +2,7 @@
namespace App\Domain\Commerce; namespace App\Domain\Commerce;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\OfferVersion; use App\Domain\Catalog\OfferVersion;
use App\Domain\Entitlement\Grant; use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus; use App\Domain\Entitlement\GrantStatus;
@@ -27,12 +28,23 @@ public function covers(Party $holder, OfferVersion $version): bool
$byAcquisition = Grant::query() $byAcquisition = Grant::query()
->where('status', GrantStatus::Aktiv) ->where('status', GrantStatus::Aktiv)
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id)) ->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
->with('acquisition')
->get() ->get()
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now)) ->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now))) && ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
->groupBy('acquisition_id'); ->groupBy('acquisition_id');
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
foreach ($byAcquisition as $grants) { 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 = []; $have = [];
foreach ($grants as $grant) { foreach ($grants as $grant) {
+3
View File
@@ -12,6 +12,9 @@ class Payment extends Model
'provider', 'provider',
'status', 'status',
'provider_reference', 'provider_reference',
'provider_payment_ref',
'amount_cents',
'confirmed_by',
]; ];
public function order(): BelongsTo public function order(): BelongsTo
+353
View File
@@ -0,0 +1,353 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
use App\Models\User;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
/**
* Zahlungsjournal: schreibt und liest die unveränderlichen Geldbewegungen (LedgerEntry). Geschrieben wird nur aus
* derselben Transaktion, die die Bestellung auf „bezahlt“ oder „erstattet“ setzt, sodass beides nie auseinanderläuft.
* Zeiträume und Datumsangaben gelten in deutscher Zeit (Geschäftsjahr, Monats- und Quartalsgrenzen); gespeichert wird
* in UTC. Der Nachweis ist an die Grundsätze der ordnungsmäßigen Buchführung angelehnt (unveränderbar, nachvollziehbar);
* ob er den Anforderungen der Steuerberatung genügt, ist dort zu bestätigen.
*/
final class PaymentJournal
{
public const TIMEZONE = 'Europe/Berlin';
/** Höchstzahl der in der Verwaltung gezeigten Zeilen; der Export enthält immer alle des Zeitraums. */
public const DISPLAY_LIMIT = 500;
/**
* Zahlungseingang. Wiederholte Meldung derselben Zahlung legt keine zweite Zeile an (Schlüssel: Art, Anbieter,
* Referenz).
*/
public function recordPayment(Order $order, Payment $payment, CarbonInterface $occurredAt, ?User $actor, bool $live): LedgerEntry
{
return LedgerEntry::query()->firstOrCreate(
['kind' => LedgerEntry::KIND_PAYMENT, 'provider' => $payment->provider, 'provider_reference' => $payment->provider_reference],
[
'order_id' => $order->id,
'payment_id' => $payment->id,
'occurred_at' => $this->utc($occurredAt),
'amount_cents' => $order->payable(),
'currency' => (string) ($order->currency ?? 'EUR'),
'provider_payment_ref' => $payment->provider_payment_ref,
'live' => $live,
'actor_id' => $actor?->id,
'actor_name' => $actor?->name,
'payer' => $this->payer($order),
'order_snapshot' => $this->orderSnapshot($order),
],
);
}
/**
* Erstattung: eine Gegenbuchung in Höhe des Zahlbetrags. Das Echt-Kennzeichen folgt dem Zahlungseingang der
* Bestellung. `$reference` ist bei Stripe die Rückzahlungs-ID (re_...), sonst eine Referenz der Rückzahlung.
*/
public function recordRefund(Order $order, ?Payment $payment, CarbonInterface $occurredAt, ?User $actor, string $reason, string $reference, ?string $providerStatus = null): LedgerEntry
{
$original = LedgerEntry::query()->where('order_id', $order->id)->where('kind', LedgerEntry::KIND_PAYMENT)->orderBy('id')->first();
return LedgerEntry::query()->firstOrCreate(
['kind' => LedgerEntry::KIND_REFUND, 'provider' => $payment?->provider ?? $original?->provider ?? 'unbekannt', 'provider_reference' => $reference],
[
'order_id' => $order->id,
'payment_id' => $payment?->id,
'occurred_at' => $this->utc($occurredAt),
'amount_cents' => -$order->payable(),
'currency' => (string) ($order->currency ?? 'EUR'),
'provider_payment_ref' => $payment?->provider_payment_ref,
'provider_status' => $providerStatus,
'live' => $original?->live ?? false,
'actor_id' => $actor?->id,
'actor_name' => $actor?->name,
'reason' => $reason,
'payer' => $original?->payer ?? $this->payer($order),
'order_snapshot' => $original?->order_snapshot ?? $this->orderSnapshot($order),
],
);
}
/**
* Ein Datum ohne Uhrzeit (Zahlungseingang auf dem Konto): Beginn dieses Tages in deutscher Zeit. Nicht in der
* Zukunft; `$notBefore` ist der früheste zulässige Tag (Bestelldatum).
*/
public static function dayOf(string|CarbonInterface $date, ?CarbonInterface $notBefore = null): CarbonImmutable
{
$day = CarbonImmutable::parse($date instanceof CarbonInterface ? $date->format('Y-m-d') : $date, self::TIMEZONE)->startOfDay();
if ($day->greaterThan(CarbonImmutable::now(self::TIMEZONE)->endOfDay())) {
throw new DomainRuleException('Das Datum darf nicht in der Zukunft liegen.');
}
if ($notBefore !== null && $day->lessThan(CarbonImmutable::instance($notBefore)->setTimezone(self::TIMEZONE)->startOfDay())) {
throw new DomainRuleException('Das Datum liegt vor dem Bestelldatum.');
}
return $day;
}
/**
* Von und bis (einschließlich) eines Zeitraums in UTC.
*
* @param 'monat'|'quartal'|'jahr' $mode
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
*/
public static function range(string $mode, int $year, int $index): array
{
$from = CarbonImmutable::create($year, 1, 1, 0, 0, 0, self::TIMEZONE);
$from = match ($mode) {
'monat' => $from->setMonth(max(1, min(12, $index)))->startOfMonth(),
'quartal' => $from->setMonth((max(1, min(4, $index)) - 1) * 3 + 1)->startOfMonth(),
default => $from->startOfYear(),
};
$to = match ($mode) {
'monat' => $from->endOfMonth(),
'quartal' => $from->addMonths(2)->endOfMonth(),
default => $from->endOfYear(),
};
return [$from->setTimezone('UTC'), $to->setTimezone('UTC')];
}
/**
* @param 'alle'|'eingang'|'erstattung' $kind
* @param 'alle'|'stripe'|'ueberweisung'|'test' $provider
* @param 'echt'|'test'|'alle' $operation
* @return Collection<int, LedgerEntry>
*/
public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection
{
return LedgerEntry::query()
->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])
->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)))
->when($kind !== 'alle', fn ($query) => $query->where('kind', $kind))
->when($provider !== 'alle', fn ($query) => $query->where('provider', $provider))
->when($operation === 'echt', fn ($query) => $query->where('live', true))
->when($operation === 'test', fn ($query) => $query->where('live', false))
->orderBy('occurred_at')
->orderBy('id')
->get();
}
/**
* Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt,
* wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen
* Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen
* Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte.
*
* @param Collection<int, LedgerEntry> $entries
* @return array<int, int> Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung)
*/
public function shares(Collection $entries, int $offerId): array
{
$perOrder = OrderLine::query()
->whereIn('order_id', $entries->pluck('order_id')->unique()->all())
->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))
->get()
->groupBy('order_id')
->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable()));
$shares = [];
foreach ($entries as $entry) {
$share = (int) ($perOrder[$entry->order_id] ?? 0);
$shares[$entry->id] = $entry->isRefund() ? -$share : $share;
}
return $shares;
}
/**
* Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt.
*/
public function countByOperation(CarbonInterface $from, CarbonInterface $to): array
{
$rows = LedgerEntry::query()->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])->get(['live']);
return ['echt' => $rows->where('live', true)->count(), 'test' => $rows->where('live', false)->count()];
}
/**
* @param Collection<int, LedgerEntry> $entries
* @param array<int, int>|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen
* @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int}
*/
public static function totals(Collection $entries, ?array $shares = null): array
{
$in = $entries->where('kind', LedgerEntry::KIND_PAYMENT);
$out = $entries->where('kind', LedgerEntry::KIND_REFUND);
$amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0);
return [
'eingang' => (int) $in->sum($amount),
'erstattung' => (int) abs($out->sum($amount)),
'saldo' => (int) $entries->sum($amount),
'anzahl_eingang' => $in->count(),
'anzahl_erstattung' => $out->count(),
];
}
public static function providerLabel(string $provider): string
{
return match ($provider) {
'stripe' => 'Stripe',
'ueberweisung' => 'Überweisung',
'test' => 'Testzahlung',
default => $provider,
};
}
public static function local(CarbonInterface $moment): CarbonImmutable
{
return CarbonImmutable::instance($moment)->setTimezone(self::TIMEZONE);
}
/** Hat die Bewegung eine belegte Uhrzeit? Datumsbuchungen (Überweisung) beginnen um 00:00 deutscher Zeit. */
public static function hasTime(LedgerEntry $entry): bool
{
return self::local($entry->occurred_at)->format('H:i:s') !== '00:00:00';
}
/**
* Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg.
*
* @param Collection<int, LedgerEntry> $entries
* @param array<int, int>|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“
*/
public static function csv(Collection $entries, ?array $shares = null): string
{
$header = [
'Buchungsnummer', 'Datum', 'Uhrzeit', 'Art', 'Betrag EUR', 'Währung', 'Bestellung', 'Zahlungsweg', 'Betrieb', 'Herkunft',
'Referenz', 'Zahlungsvorgang', 'Status beim Anbieter', 'Lizenzinhaber', 'Rechnungsempfänger', 'Zusatz', 'Straße', 'PLZ', 'Ort', 'Land',
'Besteller', 'Zwischensumme EUR', 'Rabatt EUR', 'Rabattcode', 'Positionen', 'Begründung', 'Gebucht von', 'Gebucht am',
...($shares === null ? [] : ['Anteil des Angebots EUR']),
];
$rows = [$header];
foreach ($entries as $entry) {
$local = self::local($entry->occurred_at);
$payer = (array) $entry->payer;
$billing = (array) ($payer['billing'] ?? []);
$snapshot = (array) $entry->order_snapshot;
$lines = collect($snapshot['lines'] ?? [])->map(fn (array $line): string => ($line['name'] ?? '').' '.self::decimal((int) ($line['price_cents'] ?? 0) - (int) ($line['discount_cents'] ?? 0)))->implode(' | ');
$rows[] = [
$entry->id,
$local->format('d.m.Y'),
self::hasTime($entry) ? $local->format('H:i:s') : '',
$entry->isRefund() ? 'Erstattung' : 'Zahlungseingang',
self::decimal($entry->amount_cents),
$entry->currency,
$entry->order_id,
self::providerLabel($entry->provider),
$entry->live ? 'echt' : 'Test',
$entry->derived ? 'nachgetragen (Datum abgeleitet)' : 'belegt',
$entry->provider_reference,
$entry->provider_payment_ref,
$entry->provider_status,
$payer['holder'] ?? null,
$billing['recipient'] ?? null,
$billing['line2'] ?? null,
$billing['street'] ?? null,
$billing['postal_code'] ?? null,
$billing['city'] ?? null,
$billing['country'] ?? null,
$payer['buyer'] ?? null,
self::decimal((int) ($snapshot['subtotal_cents'] ?? 0)),
self::decimal((int) ($snapshot['discount_cents'] ?? 0)),
$snapshot['discount_code'] ?? null,
$lines,
$entry->reason,
$entry->actor_name,
self::local($entry->created_at)->format('d.m.Y H:i:s'),
...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]),
];
}
$handle = fopen('php://temp', 'r+');
foreach ($rows as $row) {
fputcsv($handle, array_map(self::cell(...), $row), ';', '"', '\\', "\r\n");
}
rewind($handle);
$csv = (string) stream_get_contents($handle);
fclose($handle);
return "\xEF\xBB\xBF".$csv;
}
public static function decimal(int $cents): string
{
return number_format($cents / 100, 2, ',', '');
}
/** Verhindert, dass ein Zellinhalt in der Tabellenkalkulation als Formel ausgeführt wird. */
private static function cell(mixed $value): string
{
$text = (string) $value;
if ($text !== '' && preg_match('/^[=+\-@\t\r]/', $text) === 1 && preg_match('/^-?\d+(,\d+)?$/', $text) !== 1) {
return "'".$text;
}
return $text;
}
private function utc(CarbonInterface $moment): CarbonImmutable
{
return CarbonImmutable::instance($moment)->setTimezone('UTC');
}
/**
* Zahler zum Zeitpunkt der Bewegung. Spätere Änderungen an Profil oder Rechnungsadresse ändern sie nicht.
*
* @return array<string, mixed>
*/
private function payer(Order $order): array
{
$order->loadMissing('user', 'party.billingAddress');
$address = $order->party?->billingAddress;
return [
'holder' => $order->party?->display_name,
'holder_kind' => $order->holder_kind,
'buyer' => $order->user?->name,
'buyer_email' => $order->user?->email,
'billing' => $address === null ? null : [
'recipient' => $address->recipient,
'line2' => $address->line2,
'street' => $address->street,
'postal_code' => $address->postal_code,
'city' => $address->city,
'country' => $address->country,
],
];
}
/**
* @return array<string, mixed>
*/
private function orderSnapshot(Order $order): array
{
$order->loadMissing('lines');
return [
'subtotal_cents' => $order->subtotal(),
'discount_cents' => (int) $order->discount_cents,
'discount_code' => $order->discount_snapshot['code'] ?? null,
'lines' => $order->lines->map(fn (OrderLine $line): array => [
'name' => $line->offer_name,
'price_cents' => (int) $line->price_cents,
'discount_cents' => (int) $line->discount_cents,
])->values()->all(),
];
}
}
+125
View File
@@ -2,8 +2,10 @@
namespace App\Domain\Commerce; namespace App\Domain\Commerce;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\Composition; use App\Domain\Catalog\Composition;
use App\Domain\Catalog\EditorialProfileReader; use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
@@ -37,6 +39,125 @@ public function forComposition(Composition $composition): array
return $options; return $options;
} }
/**
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
* dieses Paket verkauft.
*
* @return list<array<string, mixed>>
*/
public function forBundle(Bundle $bundle): array
{
$options = [];
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
$version = $this->offers->purchasableVersion($offer);
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
$options[] = $this->describe($offer, $version);
}
}
return $options;
}
/**
* Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null.
*/
public function bundleOf(OfferVersion $version): ?Bundle
{
$version->loadMissing('lines.bundleVersion.bundle');
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
}
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
public function groupKey(Offer $offer): ?string
{
if ($offer->composition_id !== null) {
return 'c:'.$offer->composition_id;
}
if ($offer->standalone_bundle) {
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
$bundle = $version === null ? null : $this->bundleOf($version);
return $bundle === null ? null : 'b:'.$bundle->id;
}
return null;
}
/** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */
public function pageUrl(Offer $offer): ?string
{
if ($offer->composition_id !== null) {
return route('public.program', $offer->composition_id);
}
$key = $this->groupKey($offer);
return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null;
}
/**
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
*
* @return array<int, array{from_cents: int, count: int}>
*/
public function bundleSummaries(): array
{
$summary = [];
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
$version = $this->offers->purchasableVersion($offer);
$bundle = $version === null ? null : $this->bundleOf($version);
if ($bundle === null) {
continue;
}
$current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
$summary[$bundle->id] = [
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
'count' => $current['count'] + 1,
];
}
return $summary;
}
/**
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
*
* @param list<array<string, mixed>> $options
* @return list<array{title: string, teaser: string}>
*/
public function bundleContents(array $options): array
{
$contents = [];
foreach ($options as $option) {
$option['version']->loadMissing('resolvedScopes.article');
foreach ($option['version']->resolvedScopes as $item) {
$article = $item->article;
if ($article === null || isset($contents[$article->id])) {
continue;
}
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
$contents[$article->id] = [
'title' => $this->articleTitle($article),
'teaser' => trim((string) ($profile->value('teaser') ?? '')),
];
}
}
return array_values($contents);
}
/** /**
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option. * Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
* *
@@ -89,6 +210,10 @@ public function describe(Offer $offer, OfferVersion $version): array
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen', 'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
'holder_kind' => $version->holder_kind, 'holder_kind' => $version->holder_kind,
'term' => self::termLabel($version), '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, 'scope' => $scope,
]; ];
} }
@@ -0,0 +1,173 @@
<?php
namespace App\Domain\Commerce\Receipt;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\PaymentJournal;
use App\Domain\Identity\BillingAddress;
/**
* Zahlungs- oder Erstattungsbeleg zu einer Buchung des Zahlungsjournals als PDF. Gebaut wird ausschließlich aus den
* bei der Buchung festgehaltenen Angaben (Zahler, Positionen, Beträge, Zeitpunkt, Beleg beim Anbieter), nie aus dem
* heutigen Profil oder der heutigen Bestellung: Spätere Änderungen der Adresse ändern den Beleg nicht, und jeder Abruf
* liefert dieselben Bytes. Der Beleg bestätigt die Zahlung. Er enthält weder Rechnungsnummer noch Steuerangaben; ob eine
* Rechnung zu stellen ist, ist rechtlich noch nicht geklärt (OPEN-06). Aussteller und Zusatzhinweis kommen aus
* `config('shop.receipt')` und werden nur gedruckt, wenn sie gepflegt sind. Zu nachgetragenen Buchungen (abgeleitetes
* Datum) gibt es keinen Beleg.
*/
final class PaymentReceipt
{
private const LEFT = 50;
private const RIGHT = 545;
public static function available(LedgerEntry $entry): bool
{
return ! $entry->derived;
}
public static function filename(LedgerEntry $entry): string
{
return ($entry->isRefund() ? 'Erstattungsbeleg' : 'Zahlungsbeleg').'-Bestellung-'.$entry->order_id.'-Buchung-'.$entry->id.'.pdf';
}
public static function render(LedgerEntry $entry): string
{
$refund = $entry->isRefund();
$payer = (array) $entry->payer;
$billing = (array) ($payer['billing'] ?? []);
$snapshot = (array) $entry->order_snapshot;
$money = fn (int $cents): string => Money::format($cents);
$when = PaymentJournal::local($entry->occurred_at);
$title = $refund ? 'Erstattungsbeleg' : 'Zahlungsbeleg';
$pdf = new PdfDocument;
$pdf->addPage();
$y = 790.0;
$pdf->text(self::LEFT, $y, $title, 22, true);
$issuer = array_values(array_filter(array_map('trim', explode('|', (string) config('shop.receipt.issuer')))));
$yIssuer = $y + 4;
foreach ($issuer as $i => $line) {
$pdf->textRight(self::RIGHT, $yIssuer - $i * 12, $line, 9, $i === 0);
}
$y = min($y - 26, $yIssuer - 12 * count($issuer) - 8);
if (! $entry->live) {
$pdf->text(self::LEFT, $y, 'TESTZAHLUNG - kein Umsatz, kein Beleg für eine echte Zahlung', 10, true);
$y -= 16;
}
$y -= 6;
$meta = [
['Bestellung', (string) $entry->order_id],
['Buchung', (string) $entry->id],
[$refund ? 'Rückzahlung am' : 'Zahlung am', $when->format('d.m.Y').(PaymentJournal::hasTime($entry) ? ', '.$when->format('H:i').' Uhr' : '')],
['Zahlungsweg', PaymentJournal::providerLabel($entry->provider)],
['Referenz', (string) $entry->provider_reference],
];
foreach ($meta as [$label, $value]) {
$pdf->text(self::LEFT, $y, $label, 9);
foreach (PdfDocument::wrap($value, 330, 10) as $i => $part) {
$pdf->text(160, $y - $i * 12, $part, 10);
}
$y -= 14 * max(1, count(PdfDocument::wrap($value, 330, 10)));
}
$y -= 10;
$pdf->text(self::LEFT, $y, $refund ? 'Erstattung an' : 'Zahler', 9);
$recipient = $billing !== [] ? array_values(array_filter([
$billing['recipient'] ?? null,
$billing['line2'] ?? null,
$billing['street'] ?? null,
trim(($billing['postal_code'] ?? '').' '.($billing['city'] ?? '')),
($billing['country'] ?? 'DE') !== 'DE' ? (BillingAddress::COUNTRIES[$billing['country']] ?? $billing['country']) : null,
])) : array_values(array_filter([$payer['holder'] ?? null, 'Keine Rechnungsadresse hinterlegt']));
foreach ($recipient as $i => $line) {
$pdf->text(160, $y - $i * 13, (string) $line, 10, $i === 0);
}
$y -= 13 * count($recipient);
if (filled($payer['buyer'] ?? null) && ($payer['buyer'] ?? '') !== ($billing['recipient'] ?? $payer['holder'] ?? '')) {
$pdf->text(160, $y, 'Bestellt von '.$payer['buyer'], 9);
$y -= 13;
}
$y -= 16;
$pdf->line(self::LEFT, $y + 12, self::RIGHT, $y + 12, 0.8);
$pdf->text(self::LEFT, $y, 'Position', 9, true);
$pdf->textRight(400, $y, 'Preis', 9, true);
$pdf->textRight(472, $y, 'Rabatt', 9, true);
$pdf->textRight(self::RIGHT, $y, 'Betrag', 9, true);
$y -= 6;
$pdf->line(self::LEFT, $y, self::RIGHT, $y, 0.4);
$y -= 14;
foreach ((array) ($snapshot['lines'] ?? []) as $line) {
$lines = PdfDocument::wrap((string) ($line['name'] ?? 'Angebot'), 270, 10);
if ($y - 13 * count($lines) < 140) {
$pdf->addPage();
$y = 790.0;
}
$price = (int) ($line['price_cents'] ?? 0);
$discount = (int) ($line['discount_cents'] ?? 0);
foreach ($lines as $i => $part) {
$pdf->text(self::LEFT, $y - $i * 13, $part, 10);
}
$pdf->textRight(400, $y, $money($price), 10);
$pdf->textRight(472, $y, $discount > 0 ? '-'.$money($discount) : '', 10);
$pdf->textRight(self::RIGHT, $y, $money($price - $discount), 10);
$y -= 13 * count($lines) + 4;
}
$y -= 6;
$pdf->line(self::LEFT, $y + 10, self::RIGHT, $y + 10, 0.4);
$y -= 6;
if ((int) ($snapshot['discount_cents'] ?? 0) > 0) {
$pdf->text(300, $y, 'Zwischensumme', 10);
$pdf->textRight(self::RIGHT, $y, $money((int) ($snapshot['subtotal_cents'] ?? 0)), 10);
$y -= 14;
$pdf->text(300, $y, 'Rabatt'.(filled($snapshot['discount_code'] ?? null) ? ' (Code '.$snapshot['discount_code'].')' : ''), 10);
$pdf->textRight(self::RIGHT, $y, '-'.$money((int) $snapshot['discount_cents']), 10);
$y -= 14;
}
$pdf->text(300, $y, $refund ? 'Erstatteter Betrag' : 'Gezahlter Betrag', 11, true);
$pdf->textRight(self::RIGHT, $y, $money(abs($entry->amount_cents)), 11, true);
$y -= 26;
$notes = [
$refund
? 'Dieser Beleg bestätigt die Rückzahlung zur genannten Bestellung. Die Berechtigungen aus dieser Bestellung sind widerrufen.'
: 'Dieser Beleg bestätigt die Zahlung zur genannten Bestellung.',
'Er enthält keine Rechnungsnummer und keine steuerlichen Angaben und wurde aus den bei der Zahlung festgehaltenen Angaben erstellt.',
];
if (filled(config('shop.receipt.note'))) {
$notes[] = (string) config('shop.receipt.note');
}
foreach ($notes as $note) {
foreach (PdfDocument::wrap($note, self::RIGHT - self::LEFT, 9) as $part) {
$pdf->text(self::LEFT, $y, $part, 9);
$y -= 12;
}
$y -= 3;
}
return $pdf->output($title.' Bestellung '.$entry->order_id);
}
}
+172
View File
@@ -0,0 +1,172 @@
<?php
namespace App\Domain\Commerce\Receipt;
/**
* Minimaler PDF-Schreiber für einseitige bis wenige Seiten Text (DIN A4, Standardschriften Helvetica, Kodierung
* WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und
* enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können.
* Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“).
*/
final class PdfDocument
{
public const WIDTH = 595;
public const HEIGHT = 842;
/** @var list<string> */
private array $pages = [];
public function addPage(): void
{
$this->pages[] = '';
}
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void
{
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
}
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
{
$this->text($xRight - self::width($text, $size, $bold), $y, $text, $size, $bold);
}
public function line(float $x1, float $y1, float $x2, float $y2, float $width = 0.5): void
{
$this->append(sprintf("%s w %s %s m %s %s l S\n", $this->n($width), $this->n($x1), $this->n($y1), $this->n($x2), $this->n($y2)));
}
/**
* Zeilenumbruch nach Wörtern. Die Breite ist eine bewusst großzügige Schätzung der Helvetica-Breiten, damit nichts
* über den Rand läuft; ein einzelnes zu langes Wort wird hart getrennt.
*
* @return list<string>
*/
public static function wrap(string $text, float $maxWidth, float $size = 10, bool $bold = false): array
{
$lines = [];
foreach (preg_split('/\R/u', trim($text)) ?: [''] as $paragraph) {
$current = '';
foreach (preg_split('/\s+/u', trim($paragraph)) ?: [] as $word) {
while (mb_strlen($word) > 1 && self::width($word, $size, $bold) > $maxWidth) {
$cut = mb_strlen($word) - 1;
while ($cut > 1 && self::width(mb_substr($word, 0, $cut), $size, $bold) > $maxWidth) {
$cut--;
}
if ($current !== '') {
$lines[] = $current;
$current = '';
}
$lines[] = mb_substr($word, 0, $cut);
$word = mb_substr($word, $cut);
}
$candidate = $current === '' ? $word : $current.' '.$word;
if ($current !== '' && self::width($candidate, $size, $bold) > $maxWidth) {
$lines[] = $current;
$current = $word;
} else {
$current = $candidate;
}
}
$lines[] = $current;
}
return $lines;
}
/** Geschätzte Textbreite in Punkt (Helvetica; Ziffern und Währung exakt, Buchstaben großzügig). */
public static function width(string $text, float $size = 10, bool $bold = false): float
{
$units = 0.0;
foreach (mb_str_split($text) as $char) {
$width = match (true) {
$char === ' ', $char === ',', $char === '.', $char === ':', $char === ';', $char === "'", $char === '|', $char === 'i', $char === 'l', $char === 'I', $char === 'j', $char === 't', $char === 'f' => 0.3,
$char === '-', $char === '(', $char === ')', $char === '/', $char === 'r' => 0.35,
ctype_digit($char), $char === '€' => 0.556,
mb_strtoupper($char) === $char && $char !== mb_strtolower($char) => 0.75,
$char === 'm', $char === 'w', $char === 'M', $char === 'W' => 0.85,
default => 0.57,
};
// Fette Ziffern, Währung und Satzzeichen sind in Helvetica so breit wie normale; nur Buchstaben werden breiter.
$units += $bold && ctype_alpha($char) ? $width * 1.08 : $width;
}
return $units * $size;
}
/**
* @param string $title Nur ASCII (Dokumenttitel)
*/
public function output(string $title): string
{
$pages = $this->pages === [] ? [''] : $this->pages;
$objects = [];
$objects[1] = '<< /Type /Catalog /Pages 2 0 R >>';
$kids = [];
$next = 6;
foreach ($pages as $stream) {
$kids[] = $next.' 0 R';
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.($next + 1).' 0 R >>';
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
$next += 2;
}
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
$objects[5] = '<< /Title ('.preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $title)).') /Producer (Lara und Felix) >>';
ksort($objects);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$offsets = [];
foreach ($objects as $number => $body) {
$offsets[$number] = strlen($pdf);
$pdf .= $number." 0 obj\n".$body."\nendobj\n";
}
$xref = strlen($pdf);
$pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$pdf .= sprintf("%010d 00000 n \n", $offset);
}
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n";
}
private function append(string $operators): void
{
if ($this->pages === []) {
$this->addPage();
}
$this->pages[array_key_last($this->pages)] .= $operators;
}
private function n(float $value): string
{
return rtrim(rtrim(number_format($value, 2, '.', ''), '0'), '.') ?: '0';
}
/** Windows-1252, geklammert für PDF-Zeichenketten. */
private static function escape(string $text): string
{
$text = strtr($text, ["\u{2212}" => '-', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ', "\u{202F}" => ' ']);
$text = (string) preg_replace('/[\x00-\x08\x0B-\x1F\x7F]/u', '', $text);
$encoded = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $encoded);
}
}
+127
View File
@@ -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(),
];
}
}
+41 -7
View File
@@ -3,9 +3,12 @@
namespace App\Domain\Commerce; namespace App\Domain\Commerce;
/** /**
* Etappe 1 verwendet ausschließlich Testzahlung und erteilt keine Produktivfreigabe. Der Shop (Warenkorb, Kasse, * Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
* 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. * 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 final class Shop
{ {
@@ -14,14 +17,45 @@ public static function driver(): string
return (string) config('services.payment.driver'); 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 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_');
} }
} }
+87 -13
View File
@@ -3,7 +3,11 @@
namespace App\Domain\Commerce\Stripe; namespace App\Domain\Commerce\Stripe;
use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\DomainRuleException;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\Order; use App\Domain\Commerce\Order;
use App\Domain\Commerce\Payment;
use App\Domain\Commerce\Shop;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest; use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response; use Illuminate\Http\Client\Response;
@@ -11,9 +15,11 @@
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
/** /**
* Stripe-Kasse (Checkout Session) für die Testzahlung in Etappe 1. Ausschließlich Testschlüssel: Ein Live-Schlüssel * Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
* oder die Produktionsumgebung werden abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten * abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
* berühren diese Anwendung nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). * 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 class StripeGateway
{ {
@@ -24,7 +30,7 @@ class StripeGateway
*/ */
public function checkoutFor(Order $order): array public function checkoutFor(Order $order): array
{ {
$this->assertSandbox(); $this->assertAllowed();
$order->loadMissing('lines', 'user'); $order->loadMissing('lines', 'user');
$taxRate = $this->taxRate(); $taxRate = $this->taxRate();
@@ -32,6 +38,10 @@ public function checkoutFor(Order $order): array
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.'); throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
} }
if ($order->payment_method === 'rechnung') {
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
}
$open = $this->reusableSession($order); $open = $this->reusableSession($order);
if ($open !== null) { if ($open !== null) {
@@ -51,12 +61,18 @@ public function checkoutFor(Order $order): array
]; ];
foreach ($order->lines->values() as $index => $line) { 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] = [ $params['line_items'][$index] = [
'quantity' => 1, 'quantity' => 1,
'price_data' => [ 'price_data' => [
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')), 'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
'unit_amount' => (int) $line->price_cents, 'unit_amount' => $line->payable(),
'product_data' => ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'], 'product_data' => $productData,
], ],
]; ];
@@ -82,21 +98,79 @@ public function checkoutFor(Order $order): array
return ['id' => $id, 'url' => $url]; return ['id' => $id, 'url' => $url];
} }
public function assertSandbox(): void public function assertAllowed(): void
{ {
$secret = (string) config('services.stripe.secret'); $secret = (string) config('services.stripe.secret');
if (app()->isProduction()) {
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
}
if ($secret === '') { if ($secret === '') {
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.'); throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
} }
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) { if (app()->isProduction()) {
throw new DomainRuleException('Etappe 1 erlaubt nur den Stripe-Testmodus (Schlüssel sk_test_).'); if (! Shop::live()) {
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
}
return;
} }
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
}
}
/**
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
* entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen
* „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal.
*
* @return array{id: string, status: string, created: ?CarbonImmutable}
*/
public function refund(Order $order, Payment $payment, string $reason): array
{
$this->assertAllowed();
$intent = (string) $payment->provider_payment_ref;
if ($intent === '') {
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
$this->assertOk($session, 'abgefragt');
$intent = (string) $session->json('payment_intent');
}
if ($intent === '') {
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
}
$response = $this->request()
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
->post('/v1/refunds', [
'payment_intent' => $intent,
'amount' => $order->payable(),
'reason' => 'requested_by_customer',
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
]);
$this->assertOk($response, 'erstattet');
$id = (string) $response->json('id');
$status = (string) $response->json('status');
if ($id === '') {
throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.');
}
if (in_array($status, ['failed', 'canceled'], true)) {
throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.');
}
$payment->provider_payment_ref = $intent;
$payment->save();
return [
'id' => $id,
'status' => $status !== '' ? $status : 'unbekannt',
'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null,
];
} }
/** /**
+6
View File
@@ -101,6 +101,10 @@ public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor):
'update_promise' => $line->update_promise, 'update_promise' => $line->update_promise,
'holder_kind' => $line->holder_kind, 'holder_kind' => $line->holder_kind,
'offer_version_id' => $line->offer_version_id, '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, 'update_promise' => $version->update_promise,
'holder_kind' => $version->holder_kind, 'holder_kind' => $version->holder_kind,
'offer_version_id' => $version->id, 'offer_version_id' => $version->id,
'licence_scope' => $version->licence_scope,
'trainer_count' => $version->trainer_count,
], ],
]); ]);
+111
View File
@@ -0,0 +1,111 @@
<?php
namespace App\Filament\Pages;
use App\Domain\Commerce\SalesTerms;
use App\Domain\Commerce\Shop;
use App\Filament\Support\ShopAccess;
use Filament\Pages\Page;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\DB;
/**
* Verkaufsstart: Was ist bereit, was fehlt noch? Die Seite liest nur. Sie nennt die fehlenden Rechtstexte, den
* Zustand der Zahlungseinrichtung und der Produktivfreigabe, ohne Schlüssel oder Werte zu zeigen. Die Produktivfreigabe
* ist eine Entscheidung von Lars und wird nicht hier, sondern in der Umgebungsdatei des Servers gesetzt.
*/
class Verkaufsstart extends Page
{
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
protected static ?string $navigationLabel = 'Verkaufsstart';
protected static ?int $navigationSort = 3;
protected static ?string $slug = 'verkaufsstart';
protected static ?string $title = 'Verkaufsstart';
protected string $view = 'filament.pages.verkaufsstart';
public static function canAccess(): bool
{
return ShopAccess::allowed();
}
public function getHeading(): string|Htmlable|null
{
return null;
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
/**
* @return array<string, mixed>
*/
public function daten(): array
{
$legal = [];
foreach (SalesTerms::pages() as $key => $definition) {
$page = SalesTerms::page($key);
$legal[] = [
'text' => $definition['label'],
'neben' => $page === null
? 'Fehlt: Es gibt keine veröffentlichte Seite unter '.implode(' oder ', $definition['paths']).'. Die Seite pflegst du in der Webpräsenz; den Text liefert die Rechtsberatung.'
: 'Veröffentlicht unter '.$page->path.'. Inhalt und Vollständigkeit prüft die Rechtsberatung.',
'zustand' => $page === null ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => 'Veröffentlicht', 'ton' => 'gut'],
];
}
$secret = (string) config('services.stripe.secret');
$mode = match (true) {
$secret === '' => 'nicht eingerichtet',
str_starts_with($secret, 'sk_test_'), str_starts_with($secret, 'rk_test_') => 'Testmodus',
str_starts_with($secret, 'sk_live_'), str_starts_with($secret, 'rk_live_') => 'Live-Schlüssel',
default => 'unbekanntes Format',
};
$withoutScope = DB::table('offer_versions')->where('status', 'aktiv')->where('grant_kind', 'kauf')->whereNull('licence_scope')->count();
$zahlung = [
['text' => 'Zahlungsweg: '.Shop::driver(), 'neben' => 'Test: Testzahlung ohne Anbieter. Stripe: Kasse bei Stripe.', 'zustand' => Shop::driver() === 'stripe' ? ['label' => 'Stripe', 'ton' => 'gut'] : ['label' => 'Test', 'ton' => 'neutral']],
['text' => 'Stripe-Schlüssel: '.$mode, 'neben' => 'Der Schlüssel steht nur in der Umgebungsdatei des Servers und wird hier nie angezeigt.', 'zustand' => $mode === 'nicht eingerichtet' ? ['label' => 'Fehlt', 'ton' => 'offen'] : ['label' => $mode, 'ton' => 'neutral']],
['text' => 'Signaturschlüssel für Stripe-Meldungen: '.(filled(config('services.stripe.webhook_secret')) ? 'gesetzt' : 'fehlt'), 'neben' => 'Ohne ihn weist die Anwendung jede Meldung von Stripe ab; Zahlungen schalten dann nichts frei.', 'zustand' => filled(config('services.stripe.webhook_secret')) ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Fehlt', 'ton' => 'offen']],
['text' => 'Steuersatz bei Stripe: '.(filled(config('services.stripe.tax_rate')) ? 'hinterlegt' : 'nicht hinterlegt'), 'neben' => 'Steuerstatus und Belegangaben sind noch nicht entschieden (OPEN-06). Ohne sie gibt es keinen Steuerausweis auf der Stripe-Kasse und keine Rechnungsvorlage.', 'zustand' => filled(config('services.stripe.tax_rate')) ? ['label' => 'Hinterlegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
['text' => 'Aussteller auf dem Zahlungsbeleg: '.(filled(config('shop.receipt.issuer')) ? 'gepflegt' : 'nicht gepflegt'), 'neben' => 'Mitglieder laden zu jeder Zahlung einen Beleg (PDF) herunter. Er nennt den Aussteller nur, wenn er mit SHOP_RECEIPT_ISSUER gepflegt ist (Zeilen durch „|“ getrennt). Name und Anschrift des Verkäufers, Steuerangaben und eine Rechnungsnummer hängen an der rechtlichen Klärung (OPEN-06); bis dahin trägt der Beleg keine steuerlichen Angaben.', 'zustand' => filled(config('shop.receipt.issuer')) ? ['label' => 'Gepflegt', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
['text' => 'Kauf auf Rechnung für Vereine: '.(Shop::invoice() ? 'angeboten' : 'aus'), 'neben' => Shop::invoice()
? 'Die Rechnung erstellt der Betreiber manuell; den Zahlungseingang bestätigst du in der Bestellverwaltung. Vereine sehen die Möglichkeit im Checkout.'
: 'Mitglieder sehen die Möglichkeit nicht. Sie wird erst angeboten, wenn der Prozess vollständig ist: Rechnungserstellung mit Nummernkreis, Benachrichtigung des Betreibers bei neuer Rechnungsbestellung und die rechtliche Klärung (OPEN-06). Die Umsetzung ist vorbereitet; schaltest du sie mit SHOP_INVOICE=true in der Umgebungsdatei ein, erscheint sie im Checkout. Bereits angelegte Rechnungsbestellungen bleiben in der Bestellverwaltung bearbeitbar.',
'zustand' => Shop::invoice() ? ['label' => 'Angeboten', 'ton' => 'neutral'] : ['label' => 'Aus', 'ton' => 'neutral']],
];
$freigabe = [
['text' => 'Produktivfreigabe (SHOP_LIVE_RELEASE): '.(config('shop.live_release') === true ? 'gesetzt' : 'nicht gesetzt'), 'neben' => 'Standardmäßig aus. Setzt Lars in der Umgebungsdatei des Servers, wenn er den Verkauf freigibt. Ohne sie bleibt der Shop in Produktion abgeschaltet und Stripe nimmt dort keine Zahlung an.', 'zustand' => config('shop.live_release') === true ? ['label' => 'Gesetzt', 'ton' => 'gut'] : ['label' => 'Aus', 'ton' => 'neutral']],
['text' => 'Umgebung: '.(app()->isProduction() ? 'Produktion' : 'Test oder lokal'), 'neben' => app()->isProduction() ? 'Der Shop ist hier '.(Shop::enabled() ? 'aktiv.' : 'abgeschaltet.') : 'Hier läuft der Shop mit Test- oder Sandbox-Zahlung.', 'zustand' => app()->isProduction() ? (Shop::enabled() ? ['label' => 'Live', 'ton' => 'gut'] : ['label' => 'Abgeschaltet', 'ton' => 'neutral']) : ['label' => 'Test', 'ton' => 'neutral']],
];
$angebote = [
['text' => $withoutScope === 0 ? 'Alle aktiven Käufe haben einen Nutzerkreis.' : $withoutScope.' aktive Kaufangebote ohne festgelegten Nutzerkreis', 'neben' => $withoutScope === 0 ? null : 'Käufer sähen „Nutzerkreis nicht festgelegt“. Lege Einzel- oder Mehrfachlizenz mit „Geänderte Fassung aktivieren“ am Angebot fest.', 'zustand' => $withoutScope === 0 ? ['label' => 'Vollständig', 'ton' => 'gut'] : ['label' => 'Offen', 'ton' => 'offen']],
];
return [
'kopf' => [
'titel' => 'Verkaufsstart',
'typ' => 'Bereitschaft für den Verkauf in Deutschland',
'status' => ['text' => SalesTerms::missingPages() === [] ? 'Alle Rechtstexte sind veröffentlicht. Die rechtliche Freigabe der Inhalte steht aus, bis die Rechtsberatung sie bestätigt.' : 'Es fehlen veröffentlichte Rechtstexte. Ohne sie bleibt der Shop in Produktion abgeschaltet.', 'ton' => SalesTerms::missingPages() === [] ? 'gut' : 'offen'],
],
'haupt' => [
['titel' => 'Rechtstexte im Bestellablauf', 'hilfe' => 'Der Checkout verlinkt diese Seiten und hält mit jeder Bestellung fest, welche Fassung galt. Den Wortlaut der Zustimmungen im Checkout hat der Betreiber noch rechtlich zu prüfen (Entwurf '.SalesTerms::VERSION.').', 'zeilen' => $legal],
['titel' => 'Zahlung und Belege', 'zeilen' => $zahlung],
],
'seite' => [
['titel' => 'Freigabe', 'zeilen' => $freigabe, 'hilfe' => 'Die Produktivfreigabe liegt bei Lars. Sie wird nicht über diese Oberfläche gesetzt.'],
['titel' => 'Angebote', 'zeilen' => $angebote],
],
];
}
}
+182
View File
@@ -0,0 +1,182 @@
<?php
namespace App\Filament\Pages;
use App\Domain\Catalog\Offer;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\PaymentJournal;
use App\Filament\Support\ShopAccess;
use Carbon\CarbonImmutable;
use Filament\Pages\Page;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Livewire\Attributes\Url;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Einnahmen und Erstattungen (Zahlungsjournal): Jede Geldbewegung steht unveränderlich mit Datum, Betrag, Beleg beim
* Anbieter, handelnder Person, Begründung und Zahler da. Die Seite liest nur; es gibt nichts zu bearbeiten oder zu
* löschen. Standardmäßig zählen nur echte Zahlungen; Testzahlungen sind ein eigener Filter und fließen nie in die
* Summen echter Einnahmen. Der Export (CSV) enthält alle Zeilen des gewählten Zeitraums und Filters.
*/
class Zahlungsjournal extends Page
{
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
protected static ?string $navigationLabel = 'Einnahmen und Erstattungen';
protected static ?int $navigationSort = 2;
protected static ?string $slug = 'zahlungsjournal';
protected static ?string $title = 'Einnahmen und Erstattungen';
protected string $view = 'filament.pages.zahlungsjournal';
#[Url(as: 'zeitraum')]
public string $modus = 'monat';
#[Url(as: 'jahr')]
public ?int $jahr = null;
#[Url(as: 'nr')]
public ?int $nr = null;
#[Url(as: 'art')]
public string $art = 'alle';
#[Url(as: 'weg')]
public string $weg = 'alle';
/** Ohne Angabe: auf Prod die echten Zahlungen, auf jeder anderen Instanz (Test, lokal) die Testzahlungen. */
#[Url(as: 'betrieb')]
public ?string $betrieb = null;
/** Kennung eines Angebots oder leer für alle (Zeichenkette, damit die Auswahl „Alle“ leer sein kann). */
#[Url(as: 'angebot')]
public string $angebot = '';
public static function canAccess(): bool
{
return ShopAccess::allowed();
}
public function getHeading(): string|Htmlable|null
{
return null;
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
public function mount(): void
{
$now = CarbonImmutable::now(PaymentJournal::TIMEZONE);
$this->jahr ??= $now->year;
$this->nr ??= $this->modus === 'quartal' ? $now->quarter : $now->month;
$this->betrieb ??= self::defaultBetrieb();
$this->normalize();
}
/** Nur Prod zeigt standardmäßig echte Zahlungen; auf anderen Instanzen entstehen Buchungen nur aus der Sandbox. */
public static function defaultBetrieb(): string
{
return app()->isProduction() ? 'echt' : 'test';
}
/** Beim Wechsel zwischen Monat und Quartal bleibt der gewählte Zeitraum erhalten. */
public function updatingModus(string $value): void
{
if ($this->modus === 'monat' && $value === 'quartal') {
$this->nr = (int) ceil(((int) $this->nr) / 3);
} elseif ($this->modus === 'quartal' && $value === 'monat') {
$this->nr = (((int) $this->nr) - 1) * 3 + 1;
}
}
public function updated(): void
{
$this->normalize();
}
/** Ungültige Eingaben aus der Adresszeile fallen auf zulässige Werte zurück. */
private function normalize(): void
{
$this->modus = in_array($this->modus, ['monat', 'quartal', 'jahr'], true) ? $this->modus : 'monat';
$this->art = in_array($this->art, ['alle', LedgerEntry::KIND_PAYMENT, LedgerEntry::KIND_REFUND], true) ? $this->art : 'alle';
$this->weg = in_array($this->weg, ['alle', 'stripe', 'ueberweisung', 'test'], true) ? $this->weg : 'alle';
$this->betrieb = in_array($this->betrieb, ['echt', 'test', 'alle'], true) ? $this->betrieb : self::defaultBetrieb();
$this->angebot = ctype_digit($this->angebot) && Offer::query()->whereKey((int) $this->angebot)->exists() ? $this->angebot : '';
$this->jahr = max(2020, min((int) CarbonImmutable::now(PaymentJournal::TIMEZONE)->year + 1, (int) ($this->jahr ?? 2026)));
$max = $this->modus === 'quartal' ? 4 : 12;
$this->nr = max(1, min($max, (int) ($this->nr ?? 1)));
}
/**
* @return array{0: CarbonImmutable, 1: CarbonImmutable}
*/
private function range(): array
{
return PaymentJournal::range($this->modus, (int) $this->jahr, (int) $this->nr);
}
public function zeitraumName(): string
{
$months = [1 => 'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
return match ($this->modus) {
'monat' => $months[(int) $this->nr].' '.$this->jahr,
'quartal' => $this->nr.'. Quartal '.$this->jahr,
default => 'Jahr '.$this->jahr,
};
}
/**
* @return array<string, mixed>
*/
public function daten(): array
{
[$from, $to] = $this->range();
$journal = app(PaymentJournal::class);
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
return [
'zeitraum' => $this->zeitraumName(),
'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT),
'anzahl' => $entries->count(),
'angebote' => Offer::query()->orderBy('name')->pluck('name', 'id')->all(),
'angebotName' => $offerId === null ? null : Offer::query()->find($offerId)?->name,
'anteile' => $shares,
'summen' => PaymentJournal::totals($entries, $shares),
'nachBetrieb' => $journal->countByOperation($from, $to),
'ohneAdresse' => $entries->filter(fn (LedgerEntry $entry): bool => $entry->kind === LedgerEntry::KIND_PAYMENT && empty(($entry->payer ?? [])['billing']))->count(),
'nachgetragen' => $entries->where('derived', true)->count(),
];
}
public function exportieren(): StreamedResponse
{
abort_unless(ShopAccess::allowed(), 403);
[$from, $to] = $this->range();
$journal = app(PaymentJournal::class);
$offerId = $this->angebot === '' ? null : (int) $this->angebot;
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId);
$shares = $offerId === null ? null : $journal->shares($entries, $offerId);
$name = 'zahlungsjournal-'.match ($this->modus) {
'monat' => $this->jahr.'-'.str_pad((string) $this->nr, 2, '0', STR_PAD_LEFT),
'quartal' => $this->jahr.'-Q'.$this->nr,
default => (string) $this->jahr,
}.'-'.match ($this->betrieb) {
'echt' => 'echt', 'test' => 'test', default => 'alle'
}.($offerId === null ? '' : '-angebot-'.$offerId).'.csv';
return response()->streamDownload(function () use ($entries, $shares): void {
echo PaymentJournal::csv($entries, $shares);
}, $name, ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\Filament\Resources\DiscountCodes;
use App\Domain\Commerce\Discount\DiscountCode;
use App\Filament\Resources\DiscountCodes\Pages\ListDiscountCodes;
use App\Filament\Resources\DiscountCodes\Pages\ViewDiscountCode;
use App\Filament\Support\ShopAccess;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Auth\Access\Response;
use Illuminate\Database\Eloquent\Model;
/**
* Rabattcodes (FACH-14): anlegen, bearbeiten, zeitlich begrenzen, deaktivieren und einzelne Konten freischalten.
* Die Seiten nutzen die gemeinsamen Bausteine (Bestandsliste, Objektseite, Dialoge) wie die übrigen Kataloglisten.
*/
class DiscountCodeResource extends Resource
{
protected static ?string $model = DiscountCode::class;
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
protected static ?string $navigationLabel = 'Rabattcodes';
protected static ?string $modelLabel = 'Rabattcode';
protected static ?string $pluralModelLabel = 'Rabattcodes';
protected static ?string $recordTitleAttribute = 'code';
protected static ?int $navigationSort = 2;
public static function canViewAny(): bool
{
return ShopAccess::allowed();
}
public static function getViewAuthorizationResponse(Model $record): Response
{
return ShopAccess::allowed() ? Response::allow() : Response::deny();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('code')->label('Code')->searchable(),
]);
}
public static function getPages(): array
{
return [
'index' => ListDiscountCodes::route('/'),
'view' => ViewDiscountCode::route('/{record}'),
];
}
}
@@ -0,0 +1,103 @@
<?php
namespace App\Filament\Resources\DiscountCodes\Pages;
use App\Domain\Commerce\Discount\DiscountCode;
use App\Domain\Commerce\Discount\DiscountService;
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
use App\Filament\Support\DiscountCodeForm;
use App\Filament\Support\ListsCatalog;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListDiscountCodes extends ListRecords
{
use ListsCatalog;
use ReportsDomainRules;
protected static string $resource = DiscountCodeResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Ein Code gilt für den ganzen Warenkorb oder nur für ausgewählte Ziele, und er ist allgemein einlösbar oder nur für freigeschaltete Konten. Beides stellst du unabhängig voneinander ein. Pro Bestellung gilt höchstens ein Code.';
}
protected function getHeaderActions(): array
{
return [
Action::make('create')->label('Code anlegen')
->modalHeading('Neuer Rabattcode')
->modalDescription('Dieselbe Maske öffnet sich später beim Bearbeiten. Freigaben für einzelne Konten verwaltest du danach auf der Seite des Codes.')
->modalSubmitActionLabel('Code anlegen')
->modalWidth('3xl')
->fillForm(['kind' => DiscountCode::PERCENT, 'scope' => DiscountCode::SCOPE_CART, 'eligibility' => DiscountCode::OPEN, 'active' => true])
->schema(DiscountCodeForm::schema())
->action(function (array $data): void {
$code = null;
$this->report(function () use ($data, &$code): void {
[$fields, $targets] = DiscountCodeForm::fromForm($data);
$code = app(DiscountService::class)->save($fields, $targets);
}, 'Der Rabattcode ist angelegt.');
if ($code instanceof DiscountCode) {
$this->redirect(DiscountCodeResource::getUrl('view', ['record' => $code]));
}
}),
];
}
protected function catalogRows(): array
{
$rows = [];
$now = now();
foreach (DiscountCode::query()->with('targets')->withCount(['releases as active_releases_count' => fn ($query) => $query->whereNull('revoked_at')])->orderByDesc('id')->get() as $code) {
$state = $code->stateAt($now);
$url = DiscountCodeResource::getUrl('view', ['record' => $code]);
$rows[] = [
'schluessel' => 'c'.$code->id,
'titel' => $code->code,
'meta' => 'Rabattcode · '.$code->label,
'text' => $code->valueLabel().' · '.($code->forSelection() ? 'ausgewählte Ziele ('.$code->targets->count().')' : 'gesamter Warenkorb').' · '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein einlösbar'),
'symbol' => 'etikett',
'url' => $url,
'chips' => [
match ($state) {
'aktiv' => ['label' => 'Gültig', 'ton' => 'gut'],
'abgelaufen' => ['label' => 'Abgelaufen', 'ton' => 'leise'],
'noch_nicht' => ['label' => 'Noch nicht gültig', 'ton' => 'offen'],
default => ['label' => 'Deaktiviert', 'ton' => 'leise'],
},
['label' => $code->valueLabel(), 'ton' => 'neutral'],
['label' => $code->restricted() ? $code->active_releases_count.' freigeschaltet' : 'Allgemein', 'ton' => 'neutral'],
],
'zustand' => [$state === 'aktiv' ? 'aktiv' : 'inaktiv'],
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return ['alle' => 'Jeder Zustand', 'aktiv' => 'Gerade gültig', 'inaktiv' => 'Abgelaufen, deaktiviert oder noch nicht gültig'];
}
protected function suchPlatzhalter(): string
{
return 'Code oder Name';
}
protected function einheit(): array
{
return ['Rabattcode', 'Rabattcodes'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Rabattcodes', 'text' => 'Mit „Code anlegen“ oben entsteht der erste Rabattcode, zum Beispiel der gemeinsame Zertifizierungscode.'];
}
}
@@ -0,0 +1,293 @@
<?php
namespace App\Filament\Resources\DiscountCodes\Pages;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Commerce\Discount\DiscountCode;
use App\Domain\Commerce\Discount\DiscountRelease;
use App\Domain\Commerce\Discount\DiscountService;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\Order;
use App\Filament\Resources\DiscountCodes\DiscountCodeResource;
use App\Filament\Support\DiscountCodeForm;
use App\Filament\Support\ReportsDomainRules;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Carbon;
/**
* Rabattcode im gemeinsamen Rahmen. Bearbeiten nutzt dieselbe Maske wie Anlegen. Konten werden für genau diesen Code
* freigeschaltet und die Freigabe wird mit Begründung entzogen; der Verlauf bleibt stehen.
*/
class ViewDiscountCode extends ViewRecord
{
use ReportsDomainRules;
protected static string $resource = DiscountCodeResource::class;
public function getTitle(): string|Htmlable
{
return (string) $this->getRecord()->code;
}
public function getHeading(): string|Htmlable
{
return '';
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
protected function getHeaderActions(): array
{
return [];
}
/**
* @return array<string, string>
*/
public function getBreadcrumbs(): array
{
return [];
}
public function infolist(Schema $schema): Schema
{
return $schema->components([
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->codeDaten())->columnSpanFull(),
])->columns(1);
}
private function code(): DiscountCode
{
/** @var DiscountCode $code */
$code = $this->getRecord();
return $code;
}
public function editAction(): Action
{
return Action::make('edit')
->label('Code bearbeiten')
->modalHeading(fn (): string => 'Rabattcode „'.$this->code()->code.'“ bearbeiten')
->modalDescription('Bestellungen, die schon aufgegeben sind, behalten ihren gespeicherten Rabatt. Eine Änderung wirkt auf künftige Einlösungen und auf offene Warenkörbe. „Abbrechen“ verwirft die Eingaben.')
->modalSubmitActionLabel('Änderungen speichern')
->modalWidth('3xl')
->fillForm(fn (): array => DiscountCodeForm::fill($this->code()))
->schema(DiscountCodeForm::schema())
->action(function (array $data): void {
$this->report(function () use ($data): void {
[$fields, $targets] = DiscountCodeForm::fromForm($data);
app(DiscountService::class)->save($fields, $targets, $this->code());
}, 'Der Rabattcode ist gespeichert.');
$this->refreshRecord();
});
}
public function toggleAction(): Action
{
return Action::make('toggle')
->label(fn (): string => $this->code()->active ? 'Code deaktivieren' : 'Code aktivieren')
->color(fn (): string => $this->code()->active ? 'danger' : 'success')
->requiresConfirmation()
->modalHeading(fn (): string => $this->code()->active ? 'Code „'.$this->code()->code.'“ deaktivieren?' : 'Code „'.$this->code()->code.'“ aktivieren?')
->modalDescription(fn (): string => $this->code()->active
? 'Der Code lässt sich danach nicht mehr einlösen. In offenen Warenkörben zeigt die Bestellübersicht den Grund; bereits aufgegebene Bestellungen bleiben unverändert. Freigaben und Einstellungen bleiben erhalten.'
: 'Der Code lässt sich danach wieder einlösen, soweit sein Gültigkeitszeitraum und die Freigaben es zulassen.')
->modalSubmitActionLabel(fn (): string => $this->code()->active ? 'Deaktivieren' : 'Aktivieren')
->action(function (): void {
$code = $this->code();
$this->report(function () use ($code): string {
app(DiscountService::class)->setActive($code, ! $code->active);
return $code->active ? 'Der Code ist aktiviert.' : 'Der Code ist deaktiviert.';
}, 'Gespeichert.');
$this->refreshRecord();
});
}
public function releaseAction(): Action
{
return Action::make('release')
->label('Konto freischalten')
->modalHeading(fn (): string => 'Konto für den Code „'.$this->code()->code.'“ freischalten')
->modalDescription('Das Konto darf genau diesen Code einlösen, solange Code und Freigabe gültig sind, auch bei späteren Bestellungen. Die Freigabe gilt nicht für andere Codes. Prüfe vorher die Zertifizierung des Kontos.')
->modalSubmitActionLabel('Konto freischalten')
->schema([
Select::make('user_id')->label('Mitgliedskonto')->required()->searchable()
->getSearchResultsUsing(fn (string $search): array => $this->searchMembers($search))
->getOptionLabelUsing(fn ($value): ?string => ($user = User::query()->find($value)) === null ? null : $user->name.' ('.$user->email.')')
->helperText('Suche nach Name oder E-Mail-Adresse. Nur Konten mit Mitgliedsprofil.'),
DatePicker::make('valid_until')->label('Freigabe gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
->helperText('Leer: ohne Ende. Danach gilt der Code für dieses Konto nicht mehr.'),
Textarea::make('reason')->label('Grundlage der Freigabe')->rows(2)->maxLength(500)
->helperText('Zum Beispiel „Zertifikat vom 12.11.2026 geprüft“. Bleibt im Verlauf stehen.'),
])
->visible(fn (): bool => $this->code()->restricted())
->action(function (array $data): void {
$this->report(function () use ($data): string {
$member = User::query()->findOrFail($data['user_id']);
$until = filled($data['valid_until'] ?? null) ? Carbon::parse((string) $data['valid_until'], config('app.timezone'))->endOfDay() : null;
app(DiscountService::class)->release($this->code(), $member, auth('staff')->user() ?? auth()->user(), $until, $data['reason'] ?? null);
return 'Das Konto von '.$member->name.' ist für den Code freigeschaltet.';
}, 'Das Konto ist freigeschaltet.');
$this->refreshRecord();
});
}
public function revokeAction(): Action
{
return Action::make('revoke')
->label('Freigabe entziehen')
->color('danger')
->requiresConfirmation()
->modalHeading('Freigabe entziehen?')
->modalDescription('Das Konto kann diesen Code danach nicht mehr einlösen. Offene Warenkörbe des Kontos zeigen den Grund und lassen sich erst ohne Code bestellen. Aufgegebene Bestellungen bleiben unverändert; die Freigabe bleibt mit dem Entzug im Verlauf stehen.')
->modalSubmitActionLabel('Freigabe entziehen')
->schema([
Textarea::make('reason')->label('Grund')->rows(2)->maxLength(500),
])
->action(function (array $data, array $arguments): void {
$this->report(function () use ($data, $arguments): string {
$release = DiscountRelease::query()->where('discount_code_id', $this->code()->id)->findOrFail((int) ($arguments['release'] ?? 0));
app(DiscountService::class)->revoke($release, auth('staff')->user() ?? auth()->user(), $data['reason'] ?? null);
return 'Die Freigabe ist entzogen.';
}, 'Die Freigabe ist entzogen.');
$this->refreshRecord();
});
}
private function refreshRecord(): void
{
$this->getRecord()->unsetRelations();
$this->getRecord()->refresh();
}
/**
* @return array<int, string>
*/
private function searchMembers(string $search): array
{
$like = '%'.mb_strtolower(trim($search)).'%';
return User::query()
->whereNotNull('party_id')
->where(fn ($query) => $query->whereRaw('LOWER(name) LIKE ?', [$like])->orWhereRaw('LOWER(email) LIKE ?', [$like]))
->orderBy('name')
->limit(20)
->get()
->mapWithKeys(fn (User $user): array => [$user->id => $user->name.' ('.$user->email.')'])
->all();
}
/**
* @return array<string, mixed>
*/
private function codeDaten(): array
{
$code = $this->code();
$code->loadMissing('targets');
$state = $code->stateAt(now());
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y');
$targets = [];
foreach ($code->targets as $target) {
$targets[] = match ($target->target_type) {
DiscountCode::TARGET_OFFER => 'Angebot „'.(Offer::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
DiscountCode::TARGET_ARTICLE => 'Lizenzartikel '.(LicenseArticle::query()->find($target->target_id)?->code ?? 'gelöscht'),
DiscountCode::TARGET_BUNDLE => 'Paket „'.(Bundle::query()->find($target->target_id)?->name ?? 'gelöscht').'“',
default => 'Ziel',
};
}
$releases = $code->releases()->with(['user', 'grantor'])->get();
$active = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at === null);
$past = $releases->filter(fn (DiscountRelease $release): bool => $release->revoked_at !== null);
$orders = Order::query()->where('discount_code_id', $code->id)->with('user')->latest('id')->limit(10)->get();
$paid = Order::query()->where('discount_code_id', $code->id)->where('status', 'bezahlt')->count();
return [
'kopf' => [
'brot' => [['label' => 'Rabattcodes', 'href' => DiscountCodeResource::getUrl('index')], $code->code],
'titel' => $code->code,
'typ' => 'Rabattcode · '.$code->label,
'status' => match ($state) {
'aktiv' => ['text' => 'Gerade gültig'.($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ''), 'ton' => 'gut'],
'abgelaufen' => ['text' => 'Abgelaufen am '.$date($code->valid_until).'. Der Code lässt sich nicht mehr einlösen.', 'ton' => 'offen'],
'noch_nicht' => ['text' => 'Gilt erst ab dem '.$date($code->valid_from).'.', 'ton' => 'offen'],
default => ['text' => 'Deaktiviert. Der Code lässt sich nicht einlösen.', 'ton' => 'offen'],
},
'aktionen' => [
['label' => 'Code bearbeiten', 'wire' => "mountAction('edit')", 'art' => 'primary'],
...($code->restricted() ? [['label' => 'Konto freischalten', 'wire' => "mountAction('release')", 'art' => 'line']] : []),
['label' => $code->active ? 'Code deaktivieren' : 'Code aktivieren', 'wire' => "mountAction('toggle')", 'art' => 'line'],
],
],
'haupt' => [
[
'titel' => 'Der Code auf einen Blick',
'hilfe' => 'Geltungsbereich und Einlösungsberechtigung sind zwei getrennte Einstellungen. Der Rabatt ändert den Preis, nie den Nutzungsumfang.',
'zeilen' => [
['text' => 'Rabatt: '.$code->valueLabel(), 'neben' => $code->kind === DiscountCode::PERCENT ? 'Je Position gerundet.' : 'Je Bestellung, anteilig auf die betroffenen Positionen verteilt.'],
['text' => 'Geltungsbereich: '.($code->forSelection() ? 'nur ausgewählte Ziele' : 'gesamter Warenkorb'), 'neben' => $code->forSelection() ? 'Ein Paket ist ein eigenes Ziel und folgt nicht aus einem enthaltenen Artikel.' : null],
...array_map(fn (string $target): array => ['text' => '· '.$target, 'neben' => null], $targets),
['text' => 'Einlösung: '.($code->restricted() ? 'nur freigeschaltete Konten' : 'allgemein, für alle angemeldeten Käufer'), 'neben' => 'Pro Bestellung gilt höchstens ein Code.'],
['text' => 'Gültigkeit: '.($code->valid_from ? 'ab '.$date($code->valid_from) : 'sofort').($code->valid_until ? ' bis einschließlich '.$date($code->valid_until) : ', unbegrenzt'), 'neben' => $code->active ? 'Aktiv' : 'Deaktiviert'],
...(filled($code->note) ? [['text' => 'Notiz: '.$code->note, 'neben' => null]] : []),
],
],
[
'titel' => $code->restricted() ? 'Freigeschaltete Konten' : 'Freigaben',
'zusatz' => $code->restricted() ? $active->count().' aktiv' : null,
'hilfe' => $code->restricted()
? 'Nur diese Konten können den Code einlösen. Die Freigabe gilt nur für diesen Code und wiederholt, solange Code und Freigabe gültig sind.'
: 'Der Code ist allgemein einlösbar. Freigaben sind nicht nötig. Stelle „Einlösung“ auf freigeschaltete Konten, um den Code zu beschränken.',
'zeilen' => $code->restricted() ? $active->map(fn (DiscountRelease $release): array => [
'text' => ($release->user?->name ?? 'Konto').' ('.($release->user?->email ?? '').')',
'neben' => 'freigeschaltet am '.$date($release->granted_at).($release->grantor ? ' von '.$release->grantor->name : '').($release->valid_until ? ', gültig bis einschließlich '.$date($release->valid_until) : '').(filled($release->reason) ? ' · '.$release->reason : ''),
'aktion' => ['label' => 'Entziehen', 'wire' => "mountAction('revoke', { release: ".$release->id.' })'],
])->values()->all() : [],
'leer' => ['titel' => $code->restricted() ? 'Noch kein Konto freigeschaltet' : 'Keine Freigaben nötig', 'text' => $code->restricted() ? 'Mit „Konto freischalten“ oben gibst du ein Konto für diesen Code frei, zum Beispiel nach der Prüfung eines Zertifikats.' : 'Jeder angemeldete Käufer kann den Code einlösen.'],
],
],
'seite' => [
[
'titel' => 'Verwendung',
'zeilen' => $orders->map(fn (Order $order): array => [
'text' => 'Bestellung '.$order->id.' · −'.Money::format((int) $order->discount_cents),
'zustand' => ['label' => match ($order->status) {
'bezahlt' => 'Bezahlt', 'erstattet' => 'Erstattet', 'fehlgeschlagen' => 'Fehlgeschlagen', default => 'Offen'
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'leise'],
'neben' => ($order->user?->name ?? '').' · '.$date($order->created_at),
])->all(),
'leer' => 'Der Code wurde noch in keiner Bestellung verwendet.',
'hilfe' => $orders->isEmpty() ? null : $paid.' bezahlte Bestellung'.($paid === 1 ? '' : 'en').' mit diesem Code. Gezeigt werden die letzten zehn.',
],
[
'titel' => 'Entzogene Freigaben',
'zeilen' => $past->map(fn (DiscountRelease $release): array => [
'text' => ($release->user?->name ?? 'Konto'),
'neben' => 'entzogen am '.$date($release->revoked_at).(filled($release->reason) ? ' · '.$release->reason : ''),
])->values()->all(),
'leer' => 'Keine Freigabe wurde entzogen.',
'hilfe' => 'Der Verlauf bleibt erhalten.',
],
],
];
}
}
@@ -7,6 +7,7 @@
use App\Domain\Catalog\Composition; use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionVersion; use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
@@ -17,11 +18,13 @@
use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Cms\Catalog\PublicCatalogReader;
use App\Domain\Commerce\Money; use App\Domain\Commerce\Money;
use App\Domain\Commerce\ProductOptions; use App\Domain\Commerce\ProductOptions;
use App\Filament\Pages\Zahlungsjournal;
use App\Filament\Resources\Offers\OfferResource; use App\Filament\Resources\Offers\OfferResource;
use App\Filament\Support\CatalogLabels; use App\Filament\Support\CatalogLabels;
use App\Filament\Support\CatalogOptions; use App\Filament\Support\CatalogOptions;
use App\Filament\Support\PublicationReadiness; use App\Filament\Support\PublicationReadiness;
use App\Filament\Support\ReportsDomainRules; use App\Filament\Support\ReportsDomainRules;
use App\Filament\Support\ShopAccess;
use Filament\Actions\Action; use Filament\Actions\Action;
use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select; use Filament\Forms\Components\Select;
@@ -45,6 +48,9 @@ class ViewOffer extends ViewRecord
protected static string $resource = OfferResource::class; protected static string $resource = OfferResource::class;
/** Wert der Auswahl „Produktseite“ für ein Paket mit eigener Seite. */
private const OWN_BUNDLE_PAGE = '__paket';
public function getTitle(): string|Htmlable public function getTitle(): string|Htmlable
{ {
return (string) $this->getRecord()->name; return (string) $this->getRecord()->name;
@@ -120,6 +126,16 @@ public function activateAction(): Action
'organisation' => 'Organisationen und Vereine', 'organisation' => 'Organisationen und Vereine',
])->required() ])->required()
->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'), ->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'),
Select::make('licence_scope')->label('Nutzerkreis')
->options(LicenceScope::options())
->required()
->live()
->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Das ist unabhängig vom Lizenzinhaber (Person oder Verein), vom Nutzungszweck der Rechte und vom Preis; es wird aus keinem davon abgeleitet. Der Download bleibt zum Start beim bestellenden Konto. Der Wert wird mit der Bestellung festgehalten.'),
TextInput::make('trainer_count')->label('Anzahl Trainer')
->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer()
->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
->helperText('Höchstzahl der Trainer, die die Inhalte einsetzen dürfen, mindestens 2. Eine Einzellizenz gilt immer für genau einen Trainer.'),
Select::make('grant_kind')->label('Vergabe')->options([ Select::make('grant_kind')->label('Vergabe')->options([
'kauf' => 'Kauf', 'kauf' => 'Kauf',
'auf_abruf' => 'Auf Abruf', 'auf_abruf' => 'Auf Abruf',
@@ -201,13 +217,16 @@ public function activateAction(): Action
$version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) { $version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) {
$service->assignProduct( $service->assignProduct(
$offer, $offer,
filled($data['composition_id'] ?? null) ? (int) $data['composition_id'] : null, filled($data['composition_id'] ?? null) && $data['composition_id'] !== self::OWN_BUNDLE_PAGE ? (int) $data['composition_id'] : null,
$data['option_label'] ?? null, $data['option_label'] ?? null,
($data['composition_id'] ?? null) === self::OWN_BUNDLE_PAGE,
); );
return $service->activate($offer, $lines, [ return $service->activate($offer, $lines, [
...$kept, ...$kept,
'holder_kind' => $data['holder_kind'], 'holder_kind' => $data['holder_kind'],
'licence_scope' => $data['licence_scope'] ?? null,
'trainer_count' => $data['trainer_count'] ?? null,
'grant_kind' => $data['grant_kind'], 'grant_kind' => $data['grant_kind'],
'price_cents' => $price, 'price_cents' => $price,
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null, 'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
@@ -267,7 +286,7 @@ private function productPages(): array
{ {
$catalog = app(PublicCatalogReader::class); $catalog = app(PublicCatalogReader::class);
return Composition::query() return [self::OWN_BUNDLE_PAGE => 'Eigene Paketseite · zeigt den Umfang des Pakets (nur für ein Angebot aus genau einer Paketfassung)'] + Composition::query()
->with('editorialContentKind') ->with('editorialContentKind')
->whereNull('archived_at') ->whereNull('archived_at')
->orderBy('designation') ->orderBy('designation')
@@ -291,15 +310,17 @@ private function formFromActive(): array
$active = $this->activeVersion(); $active = $this->activeVersion();
/** @var Offer $offer */ /** @var Offer $offer */
$offer = $this->getRecord(); $offer = $this->getRecord();
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->composition_id]; $option = ['option_label' => $offer->option_label, 'composition_id' => $offer->standalone_bundle ? self::OWN_BUNDLE_PAGE : $offer->composition_id];
if ($active === null) { if ($active === null) {
return [...$option, 'holder_kind' => 'person', 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]]; return [...$option, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
} }
return [ return [
...$option, ...$option,
'holder_kind' => $active->holder_kind, 'holder_kind' => $active->holder_kind,
'licence_scope' => $active->licence_scope,
'trainer_count' => $active->trainer_count,
'grant_kind' => $active->grant_kind, 'grant_kind' => $active->grant_kind,
'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''), 'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''),
'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [ 'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [
@@ -347,6 +368,11 @@ private function angebotDaten(): array
'wire' => "mountAction('end')", 'wire' => "mountAction('end')",
'art' => 'line', 'art' => 'line',
]] : []), ]] : []),
...(ShopAccess::allowed() ? [[
'label' => 'Zahlungen zu diesem Angebot',
'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']),
'art' => 'quiet',
]] : []),
], ],
], ],
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer), 'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
@@ -400,6 +426,7 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
->unique() ->unique()
->implode('; '); ->implode('; ');
$seite = $offer->composition; $seite = $offer->composition;
$eigeneSeite = $offer->standalone_bundle;
$kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null; $kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null;
return [ return [
@@ -409,10 +436,11 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
'zeilen' => [ 'zeilen' => [
['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)], ['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)],
['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']], ['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']],
['text' => 'Nutzerkreis: '.$option['licence'], 'neben' => $option['licence_scope'] === null ? 'Mit „Geänderte Fassung aktivieren“ festlegen.' : 'Lizenzinhaber, Nutzerkreis und Downloadkonto sind getrennte Angaben.'],
['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null], ['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null],
['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null], ['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null],
['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null], ['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null],
['text' => 'Produktseite: '.($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet'), 'neben' => $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'], ['text' => 'Produktseite: '.($eigeneSeite ? 'eigene Paketseite mit dem Umfang des Pakets' : ($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet')), 'neben' => $eigeneSeite || $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
], ],
]; ];
} }
@@ -0,0 +1,68 @@
<?php
namespace App\Filament\Resources\Orders;
use App\Domain\Commerce\Order;
use App\Filament\Resources\Orders\Pages\ListOrders;
use App\Filament\Resources\Orders\Pages\ViewOrder;
use App\Filament\Support\ShopAccess;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Auth\Access\Response;
use Illuminate\Database\Eloquent\Model;
/**
* Bestellverwaltung (PAY-006): Bestellungen lesen, bei Kauf auf Rechnung den Zahlungseingang bestätigen und
* bezahlte Bestellungen vollständig erstatten. Es gibt keine Bearbeitung der gespeicherten Konditionen.
*/
class OrderResource extends Resource
{
protected static ?string $model = Order::class;
protected static string|\UnitEnum|null $navigationGroup = 'Verkauf';
protected static ?string $navigationLabel = 'Bestellungen';
protected static ?string $modelLabel = 'Bestellung';
protected static ?string $pluralModelLabel = 'Bestellungen';
protected static ?int $navigationSort = 1;
public static function canViewAny(): bool
{
return ShopAccess::allowed();
}
public static function canCreate(): bool
{
return false;
}
public static function getViewAuthorizationResponse(Model $record): Response
{
return ShopAccess::allowed() ? Response::allow() : Response::deny();
}
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table->columns([
TextColumn::make('id')->label('Bestellung'),
]);
}
public static function getPages(): array
{
return [
'index' => ListOrders::route('/'),
'view' => ViewOrder::route('/{record}'),
];
}
}
@@ -0,0 +1,104 @@
<?php
namespace App\Filament\Resources\Orders\Pages;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\Order;
use App\Filament\Resources\Orders\OrderResource;
use App\Filament\Support\ListsCatalog;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Contracts\Support\Htmlable;
class ListOrders extends ListRecords
{
use ListsCatalog;
protected static string $resource = OrderResource::class;
public function getSubheading(): string|Htmlable|null
{
return 'Bestellungen mit Lizenzinhaber, Zahlungsweg und Zahlbetrag. Bei Kauf auf Rechnung bestätigst du hier den Zahlungseingang; bezahlte Bestellungen erstattest du vollständig.';
}
protected function getHeaderActions(): array
{
return [];
}
protected function catalogRows(): array
{
$rows = [];
foreach (Order::query()->with(['lines', 'user', 'party'])->orderByDesc('id')->limit(300)->get() as $order) {
$url = OrderResource::getUrl('view', ['record' => $order]);
$zustand = [$order->status];
$chips = [
match ($order->status) {
'bezahlt' => ['label' => 'Bezahlt', 'ton' => 'gut'],
'erstattet' => ['label' => 'Erstattet', 'ton' => 'leise'],
'fehlgeschlagen' => ['label' => 'Fehlgeschlagen', 'ton' => 'leise'],
default => ['label' => $order->payment_method === 'rechnung' ? 'Offen: wartet auf Zahlungseingang' : 'Offen', 'ton' => 'offen'],
},
['label' => match ($order->payment_method) {
'rechnung' => 'Rechnung', 'stripe' => 'Stripe', default => 'Testzahlung'
}, 'ton' => 'neutral'],
['label' => Money::format($order->payable()), 'ton' => 'neutral'],
];
if ($order->discount_cents > 0) {
$chips[] = ['label' => 'Rabatt '.($order->discount_snapshot['code'] ?? ''), 'ton' => 'neutral'];
}
if ($order->withdrawal_requested_at !== null) {
$chips[] = ['label' => 'Widerruf erklärt', 'ton' => 'offen'];
$zustand[] = 'widerruf';
}
if ($order->payment_method === 'rechnung' && $order->status === 'offen') {
$zustand[] = 'rechnung_offen';
}
$rows[] = [
'schluessel' => 'o'.$order->id,
'titel' => 'Bestellung '.$order->id,
'meta' => ($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–'),
'text' => $order->lines->pluck('offer_name')->implode('; '),
'suchtext' => (string) ($order->user?->email ?? ''),
'symbol' => 'etikett',
'url' => $url,
'chips' => $chips,
'zustand' => $zustand,
'aktionen' => [['label' => 'Öffnen', 'href' => $url]],
];
}
return $rows;
}
protected function zustandOptionen(): array
{
return [
'alle' => 'Jeder Zustand',
'rechnung_offen' => 'Rechnung: wartet auf Zahlungseingang',
'widerruf' => 'Widerruf erklärt',
'offen' => 'Offen',
'bezahlt' => 'Bezahlt',
'erstattet' => 'Erstattet',
];
}
protected function suchPlatzhalter(): string
{
return 'Nummer, Name, E-Mail oder Angebot';
}
protected function einheit(): array
{
return ['Bestellung', 'Bestellungen'];
}
protected function leer(): array
{
return ['titel' => 'Noch keine Bestellungen', 'text' => 'Sobald im Shop bestellt wird, erscheinen die Bestellungen hier.'];
}
}
@@ -0,0 +1,248 @@
<?php
namespace App\Filament\Resources\Orders\Pages;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\Money;
use App\Domain\Commerce\Order;
use App\Domain\Commerce\OrderLine;
use App\Domain\Commerce\Payment;
use App\Domain\Commerce\PaymentJournal;
use App\Filament\Resources\Orders\OrderResource;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\View;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Carbon;
/**
* Bestellung im gemeinsamen Rahmen. Die gespeicherten Konditionen sind unveränderlich; der Betreiber bestätigt bei
* Kauf auf Rechnung den Zahlungseingang und erstattet bezahlte Bestellungen vollständig (Bundles als Einheit).
*/
class ViewOrder extends ViewRecord
{
use ReportsDomainRules;
protected static string $resource = OrderResource::class;
public function getTitle(): string|Htmlable
{
return 'Bestellung '.$this->order()->id;
}
public function getHeading(): string|Htmlable
{
return '';
}
public function getMaxContentWidth(): Width|string|null
{
return Width::Full;
}
protected function getHeaderActions(): array
{
return [];
}
/**
* @return array<string, string>
*/
public function getBreadcrumbs(): array
{
return [];
}
public function infolist(Schema $schema): Schema
{
return $schema->components([
View::make('filament.catalog.objekt')->viewData(fn (): array => $this->bestellDaten())->columnSpanFull(),
])->columns(1);
}
private function hasStripePayment(): bool
{
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
}
private function order(): Order
{
/** @var Order $order */
$order = $this->getRecord();
return $order;
}
public function confirmInvoiceAction(): Action
{
return Action::make('confirmInvoice')
->label('Zahlungseingang bestätigen')
->modalHeading(fn (): string => 'Zahlungseingang für Bestellung '.$this->order()->id.' bestätigen')
->modalDescription(fn (): string => 'Du bestätigst, dass '.Money::format($this->order()->payable()).' für die Rechnung eingegangen sind. Die Inhalte werden sofort für das bestellende Konto freigeschaltet; Lizenzinhaber bleibt '.($this->order()->party?->display_name ?? 'der Käufer').'. Die Bestätigung lässt sich nicht zurücknehmen, nur die Bestellung erstatten.')
->modalSubmitActionLabel('Zahlungseingang bestätigen')
->schema([
TextInput::make('reference')->label('Rechnungsnummer oder Buchungsreferenz')->required()->maxLength(120)
->helperText('Bleibt an der Zahlung gespeichert, zum Beispiel „RE-2026-014“.'),
DatePicker::make('received_on')->label('Zahlungseingang am')->required()->native(false)->displayFormat('d.m.Y')
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
->helperText('Der Tag, an dem das Geld auf dem Konto einging. Er bestimmt, in welchen Zeitraum die Einnahme im Zahlungsjournal fällt.'),
])
->visible(fn (): bool => $this->order()->payment_method === 'rechnung' && $this->order()->status === 'offen')
->action(function (array $data): void {
$this->report(function () use ($data): string {
app(Checkout::class)->confirmInvoicePayment($this->order(), (string) $data['reference'], Filament::auth()->user(), (string) $data['received_on']);
return 'Der Zahlungseingang ist bestätigt. Die Inhalte sind freigeschaltet.';
}, 'Bestätigt.');
$this->order()->unsetRelations();
$this->order()->refresh();
});
}
public function refundAction(): Action
{
return Action::make('refund')
->label('Bestellung erstatten')
->color('danger')
->modalHeading(fn (): string => 'Bestellung '.$this->order()->id.' vollständig erstatten?')
->modalDescription(fn (): string => 'Alle Positionen dieser Bestellung werden zurückgegeben: Die Berechtigungen daraus werden widerrufen, andere Erwerbsquellen (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Pakete sind eine Einheit; Teilerstattungen gibt es zum Start nicht. '.(
$this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists()
? 'Die Rückzahlung von '.Money::format($this->order()->payable()).' wird bei Stripe veranlasst; nur wenn Stripe sie annimmt, werden die Rechte entzogen.'
: 'Die Rückzahlung selbst veranlasst du außerhalb dieser Anwendung, zum Beispiel per Überweisung.'
))
->modalSubmitActionLabel('Vollständig erstatten')
->schema([
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
->helperText('Bleibt am Widerruf der Berechtigungen und im Zahlungsjournal stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
DatePicker::make('refunded_on')->label('Rückzahlung am')->native(false)->displayFormat('d.m.Y')
->default(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
->maxDate(fn (): string => now(PaymentJournal::TIMEZONE)->format('Y-m-d'))
->visible(fn (): bool => ! $this->hasStripePayment())
->helperText('Der Tag, an dem du das Geld zurücküberwiesen hast. Bei Stripe gilt der Zeitpunkt von Stripe.'),
TextInput::make('refund_reference')->label('Referenz der Rückzahlung')->maxLength(120)
->visible(fn (): bool => ! $this->hasStripePayment())
->helperText('Optional, zum Beispiel Buchungstext oder Gutschriftnummer.'),
])
->visible(fn (): bool => $this->order()->status === 'bezahlt')
->action(function (array $data): void {
$this->report(function () use ($data): string {
app(Checkout::class)->refund(
$this->order(),
(string) $data['reason'],
null,
Filament::auth()->user(),
$this->hasStripePayment() ? null : ($data['refunded_on'] ?? null),
$this->hasStripePayment() ? null : ($data['refund_reference'] ?? null),
);
return 'Die Bestellung ist erstattet. Die Berechtigungen sind widerrufen.';
}, 'Erstattet.');
$this->order()->unsetRelations();
$this->order()->refresh();
});
}
/**
* @return array<string, mixed>
*/
private function bestellDaten(): array
{
$order = $this->order();
$order->loadMissing(['lines', 'user', 'party', 'payments']);
$date = fn (?Carbon $value): string => $value === null ? '' : $value->timezone(config('app.timezone'))->format('d.m.Y H:i');
$method = match ($order->payment_method) {
'rechnung' => 'Überweisung auf Rechnung (manuell)',
'stripe' => 'Stripe',
default => 'Testzahlung',
};
return [
'kopf' => [
'brot' => [['label' => 'Bestellungen', 'href' => OrderResource::getUrl('index')], 'Bestellung '.$order->id],
'titel' => 'Bestellung '.$order->id,
'typ' => 'Lizenzinhaber: '.($order->party?->display_name ?? '–').' · bestellt von '.($order->user?->name ?? '–').' ('.($order->user?->email ?? '').')',
'status' => [
['text' => match ($order->status) {
'bezahlt' => 'Bezahlt ('.$method.')',
'erstattet' => 'Erstattet. Die Berechtigungen sind widerrufen.',
'fehlgeschlagen' => 'Zahlung fehlgeschlagen. Es wurde nichts freigeschaltet.',
default => $order->payment_method === 'rechnung' ? 'Offen: Rechnung erstellen und Zahlungseingang bestätigen.' : 'Offen: Zahlung steht aus.',
}, 'ton' => $order->status === 'bezahlt' ? 'gut' : 'offen'],
$order->withdrawal_requested_at !== null ? ['text' => 'Widerruf erklärt am '.$date($order->withdrawal_requested_at).'. Prüfen und gegebenenfalls erstatten.', 'ton' => 'offen'] : null,
],
'aktionen' => [
...($order->payment_method === 'rechnung' && $order->status === 'offen' ? [['label' => 'Zahlungseingang bestätigen', 'wire' => "mountAction('confirmInvoice')", 'art' => 'primary']] : []),
...($order->status === 'bezahlt' ? [['label' => 'Bestellung erstatten', 'wire' => "mountAction('refund')", 'art' => 'line']] : []),
],
],
'haupt' => [
[
'titel' => 'Positionen',
'hilfe' => 'Fassung, Preis, Rabatt, Nutzerkreis und Umfang sind beim Kauf festgehalten und ändern sich nicht.',
'zeilen' => $order->lines->map(fn (OrderLine $line): array => [
'text' => ($line->offer_name ?: 'Angebot').': '.Money::format((int) $line->price_cents).($line->discount_cents > 0 ? ' − Rabatt '.Money::format((int) $line->discount_cents).' = '.Money::format($line->payable()) : ''),
'neben' => LicenceScope::label($line->licence_scope, $line->trainer_count).' · Angebotsfassung '.($line->offerVersion?->number ?? '–'),
])->values()->all(),
'leer' => ['titel' => 'Keine Positionen', 'text' => 'Diese Bestellung hat keine Positionen.'],
],
[
'titel' => 'Beträge',
'zeilen' => [
['text' => 'Zwischensumme (Listenpreise): '.Money::format($order->subtotal()), 'neben' => null],
...($order->discount_cents > 0 ? [['text' => 'Rabatt: −'.Money::format((int) $order->discount_cents), 'neben' => 'Code '.($order->discount_snapshot['code'] ?? '').' · '.($order->discount_snapshot['label'] ?? '')]] : []),
['text' => 'Zahlbetrag: '.Money::format($order->payable()), 'neben' => 'Dieser Betrag ging an '.$method.'.'],
],
],
[
'titel' => 'Zahlungen',
'zeilen' => $order->payments->map(fn (Payment $payment): array => [
'text' => match ($payment->provider) {
'stripe' => 'Stripe', 'ueberweisung' => 'Überweisung', default => 'Testzahlung'
}.' · '.match ($payment->status) {
'bestaetigt' => 'bestätigt', 'erstattet' => 'erstattet', 'offen' => 'offen', 'abgelaufen' => 'abgelaufen', 'zu_pruefen' => 'zu prüfen', 'fehlgeschlagen' => 'fehlgeschlagen', default => $payment->status
},
'neben' => $payment->provider_reference.($payment->amount_cents !== null ? ' · '.Money::format((int) $payment->amount_cents) : ''),
])->values()->all(),
'leer' => ['titel' => 'Noch keine Zahlung', 'text' => 'Es gibt noch keinen Zahlungsvorgang zu dieser Bestellung.'],
],
[
'titel' => 'Buchungen im Zahlungsjournal',
'hilfe' => 'Unveränderlich festgehalten, mit Datum, Beleg beim Anbieter und Rechnungsempfänger zum Zeitpunkt der Buchung. Alle Buchungen eines Zeitraums und den Export findest du unter „Einnahmen und Erstattungen“.',
'zeilen' => LedgerEntry::query()->where('order_id', $order->id)->orderBy('occurred_at')->orderBy('id')->get()->map(fn (LedgerEntry $entry): array => [
'text' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y').' · '.($entry->isRefund() ? 'Erstattung −' : 'Zahlungseingang ').Money::format(abs($entry->amount_cents)).($entry->live ? '' : ' (Test, kein Umsatz)').($entry->derived ? ' (nachgetragen)' : ''),
'neben' => PaymentJournal::providerLabel($entry->provider).' · '.$entry->provider_reference.(filled($entry->actor_name) ? ' · gebucht von '.$entry->actor_name : ''),
])->values()->all(),
'leer' => ['titel' => 'Noch keine Buchung', 'text' => 'Zahlungseingang und Erstattung dieser Bestellung erscheinen hier.'],
],
],
'seite' => [
[
'titel' => 'Zustimmung',
'zeilen' => $order->terms_accepted_at === null ? [] : [
['text' => 'Zugestimmt am '.$date($order->terms_accepted_at), 'neben' => 'Fassung der Texte: '.($order->terms_snapshot['version'] ?? '–')],
...collect($order->terms_snapshot['consents'] ?? [])->map(fn (string $wording): array => ['text' => $wording, 'neben' => null])->values()->all(),
],
'leer' => 'Zu dieser Bestellung ist keine Zustimmung festgehalten (Bestellung vor dem Verkaufsstart oder über den Testweg).',
],
[
'titel' => 'Widerruf',
'zeilen' => $order->withdrawal_requested_at === null ? [] : [
['text' => 'Erklärt am '.$date($order->withdrawal_requested_at), 'neben' => filled($order->withdrawal_note) ? $order->withdrawal_note : null],
],
'leer' => 'Kein Widerruf erklärt.',
'hilfe' => 'Der Widerruf entzieht nichts. Du prüfst ihn (bei sofortiger Bereitstellung mit Zustimmung kann das Recht erloschen sein) und erstattest bei Bedarf über „Bestellung erstatten“.',
],
],
];
}
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\Offer;
use App\Domain\Commerce\Discount\DiscountCode;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Utilities\Get;
/**
* Die eine Maske für Rabattcodes: Anlegen und Bearbeiten nutzen dieselben Felder (FACH-20). Geltungsbereich und
* Einlösungsberechtigung sind zwei voneinander unabhängige Einstellungen.
*/
final class DiscountCodeForm
{
/**
* @return list<mixed>
*/
public static function schema(): array
{
return [
TextInput::make('code')->label('Code')->required()->maxLength(40)
->helperText('So gibt ihn der Käufer ein, 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich. Groß- und Kleinschreibung spielen keine Rolle.'),
TextInput::make('label')->label('Name für die Verwaltung')->required()->maxLength(120)
->helperText('Nur intern, zum Beispiel „Zertifizierungscode 2026“. Der Käufer sieht ihn nicht.'),
Select::make('kind')->label('Art des Rabatts')->options([
DiscountCode::PERCENT => 'Prozent',
DiscountCode::AMOUNT => 'Fester Betrag in Euro',
])->required()->live(),
TextInput::make('percent')->label('Prozent')->numeric()->minValue(1)->maxValue(100)->integer()->suffix('%')
->required(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
->helperText('Je Position gerundet. Der Zahlbetrag der Bestellung darf 0,50 € nicht unterschreiten.'),
TextInput::make('amount_euro')->label('Rabattbetrag')->suffix('€')
->required(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
->helperText('Gilt je Bestellung und wird anteilig auf die betroffenen Positionen verteilt, zum Beispiel 5,00.'),
Select::make('scope')->label('Geltungsbereich')->options([
DiscountCode::SCOPE_CART => 'Gesamter Warenkorb',
DiscountCode::SCOPE_SELECTED => 'Nur ausdrücklich ausgewählte Angebote, Lizenzartikel oder Pakete',
])->required()->live()
->helperText('Wofür der Rabatt gilt. Unabhängig davon legst du unten fest, wer den Code einlösen darf.'),
Select::make('offer_ids')->label('Angebote')->multiple()->searchable()
->options(fn (): array => Offer::query()->orderBy('name')->pluck('name', 'id')->all())
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
->helperText('Die gewählte Lizenzoption selbst (Fassung egal).'),
Select::make('article_ids')->label('Lizenzartikel')->multiple()->searchable()
->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
->helperText('Gilt für Angebote, die diesen Artikel unmittelbar als Position führen. Ein Artikel in einem Paket macht das Paket nicht rabattfähig.'),
Select::make('bundle_ids')->label('Pakete')->multiple()->searchable()
->options(fn (): array => Bundle::query()->orderBy('name')->pluck('name', 'id')->all())
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
->helperText('Ein Paket wird gezielt gewählt. Es folgt nicht aus einem enthaltenen Artikel.'),
Select::make('eligibility')->label('Wer darf den Code einlösen?')->options([
DiscountCode::OPEN => 'Alle angemeldeten Käufer (allgemein einlösbar)',
DiscountCode::RESTRICTED => 'Nur ausdrücklich freigeschaltete Konten',
])->required()
->helperText('Bei „freigeschaltete Konten“ schaltest du einzelne Konten auf der Seite des Codes frei und entziehst die Freigabe wieder. Eine Freigabe gilt nur für diesen Code.'),
DatePicker::make('valid_from')->label('Gültig ab')->native(false)->displayFormat('d.m.Y')
->helperText('Leer: sofort.'),
DatePicker::make('valid_until')->label('Gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
->helperText('Leer: unbegrenzt. Am Tag danach gilt der Code nicht mehr.'),
Toggle::make('active')->label('Aktiv')->default(true)
->helperText('Deaktivierte Codes lassen sich nicht einlösen; bereits aufgegebene Bestellungen bleiben unverändert.'),
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(500)
->helperText('Zum Beispiel, woran die Berechtigung geprüft wird.'),
];
}
/**
* Formularwerte → Angaben und Ziele des Dienstes.
*
* @param array<string, mixed> $data
* @return array{0: array<string, mixed>, 1: list<array{type: string, id: int}>}
*/
public static function fromForm(array $data): array
{
$targets = [];
foreach ([
DiscountCode::TARGET_OFFER => 'offer_ids',
DiscountCode::TARGET_ARTICLE => 'article_ids',
DiscountCode::TARGET_BUNDLE => 'bundle_ids',
] as $type => $key) {
foreach ((array) ($data[$key] ?? []) as $id) {
$targets[] = ['type' => $type, 'id' => (int) $id];
}
}
return [$data, $targets];
}
/**
* Vorbelegung der Maske aus einem vorhandenen Code.
*
* @return array<string, mixed>
*/
public static function fill(DiscountCode $code): array
{
$code->loadMissing('targets');
$ids = fn (string $type): array => $code->targets->where('target_type', $type)->pluck('target_id')->map(fn ($id): int => (int) $id)->values()->all();
return [
'code' => $code->code,
'label' => $code->label,
'kind' => $code->kind,
'percent' => $code->percent,
'amount_euro' => $code->amount_cents === null ? null : number_format($code->amount_cents / 100, 2, ',', ''),
'scope' => $code->scope,
'offer_ids' => $ids(DiscountCode::TARGET_OFFER),
'article_ids' => $ids(DiscountCode::TARGET_ARTICLE),
'bundle_ids' => $ids(DiscountCode::TARGET_BUNDLE),
'eligibility' => $code->eligibility,
'valid_from' => $code->valid_from?->timezone(config('app.timezone'))->toDateString(),
'valid_until' => $code->valid_until?->timezone(config('app.timezone'))->toDateString(),
'active' => $code->active,
'note' => $code->note,
];
}
}
+26 -9
View File
@@ -8,6 +8,7 @@
use App\Domain\Catalog\BundleStatus; use App\Domain\Catalog\BundleStatus;
use App\Domain\Catalog\BundleVersion; use App\Domain\Catalog\BundleVersion;
use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
@@ -227,7 +228,8 @@ public function forOffer(Offer $offer): array
$missing = $this->unusableArticles($articleIds); $missing = $this->unusableArticles($articleIds);
$buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null; $buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null;
$page = $offer->composition; $page = $offer->composition;
$shown = $page !== null && $this->catalog->shownVersion($page) !== null; $own = (bool) $offer->standalone_bundle;
$shown = $own || ($page !== null && $this->catalog->shownVersion($page) !== null);
$pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : ''; $pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : '';
$activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"]; $activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"];
@@ -258,21 +260,36 @@ public function forOffer(Offer $offer): array
'stand' => $buyable ? 'erledigt' : 'offen', 'stand' => $buyable ? 'erledigt' : 'offen',
'aktion' => $buyable ? null : ($hasActive ? $activate : null), 'aktion' => $buyable ? null : ($hasActive ? $activate : null),
], ],
[
'titel' => 'Nutzerkreis festlegen',
'text' => ! $hasActive
? 'Wird mit der Fassung festgelegt: Einzellizenz (ein Trainer) oder Mehrfachlizenz (Zahl der Trainer).'
: ($active->licence_scope !== null
? LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.'
: 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'),
'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen',
'aktion' => $hasActive && $active->licence_scope === null ? $activate : null,
'pflicht' => false,
],
[ [
'titel' => 'Produktseite zuordnen', 'titel' => 'Produktseite zuordnen',
'text' => $page !== null 'text' => $own
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.' ? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.'
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket braucht eine eigene Produktseite, sonst ist es Alternative zu den Einzelangeboten dieser Seite.', : ($page !== null
'stand' => $page !== null ? 'erledigt' : 'offen', ? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
'aktion' => $page !== null ? null : $activate, : 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'),
'stand' => $own || $page !== null ? 'erledigt' : 'offen',
'aktion' => $own || $page !== null ? null : $activate,
], ],
[ [
'titel' => 'Produktseite öffentlich', 'titel' => 'Produktseite öffentlich',
'text' => $page === null 'text' => ! $own && $page === null
? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.' ? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.'
: ($shown : ($own
? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.'
: ($shown
? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.' ? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.'
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.'), : 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')),
'stand' => $shown ? 'erledigt' : 'offen', 'stand' => $shown ? 'erledigt' : 'offen',
'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)], 'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)],
], ],
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Support;
use App\Domain\Identity\StaffRole;
use App\Models\User;
use Filament\Facades\Filament;
/**
* Wer Rabattcodes, Freigaben und Bestellungen verwalten darf: Katalogverwalter und Kundenbetreuung. Die
* Berechtigung zum Verkaufen und Erstatten ist eine Betreiberaufgabe, nicht die der Redaktion.
*/
final class ShopAccess
{
public static function allowed(): bool
{
$user = Filament::auth()->user();
return $user instanceof User
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung));
}
}
+6 -6
View File
@@ -7,6 +7,7 @@
use App\Domain\Commerce\Cart; use App\Domain\Commerce\Cart;
use App\Domain\Commerce\Money; use App\Domain\Commerce\Money;
use App\Domain\Commerce\OrderHolders; use App\Domain\Commerce\OrderHolders;
use App\Domain\Commerce\ProductOptions;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\View\View; use Illuminate\View\View;
@@ -31,9 +32,8 @@ public function show(Request $request, Cart $cart, OrderHolders $holders): View
public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse
{ {
$page = $offer->composition; $page = $offer->composition;
$result = $page !== null && $catalog->shownVersion($page) !== null $listed = $offer->standalone_bundle || ($page !== null && $catalog->shownVersion($page) !== null);
? $cart->add($offer) $result = $listed ? $cart->add($offer) : Cart::UNAVAILABLE;
: Cart::UNAVAILABLE;
$back = $this->productPage($offer); $back = $this->productPage($offer);
return match ($result) { return match ($result) {
@@ -81,8 +81,8 @@ public function accept(Offer $offer, Cart $cart): RedirectResponse
private function productPage(Offer $offer): RedirectResponse private function productPage(Offer $offer): RedirectResponse
{ {
return $offer->composition_id !== null $url = app(ProductOptions::class)->pageUrl($offer);
? redirect()->route('public.program', $offer->composition_id)
: redirect()->route('cart'); return $url !== null ? redirect()->to($url) : redirect()->route('cart');
} }
} }
@@ -7,12 +7,15 @@
use App\Domain\Catalog\OfferStatus; use App\Domain\Catalog\OfferStatus;
use App\Domain\Commerce\Cart; use App\Domain\Commerce\Cart;
use App\Domain\Commerce\Checkout; use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\Order; use App\Domain\Commerce\Order;
use App\Domain\Commerce\OrderHolders; use App\Domain\Commerce\OrderHolders;
use App\Domain\Commerce\SalesTerms;
use App\Domain\Commerce\Shop; use App\Domain\Commerce\Shop;
use App\Domain\Commerce\StaleOverview; use App\Domain\Commerce\StaleOverview;
use App\Domain\Commerce\Stripe\StripeGateway; use App\Domain\Commerce\Stripe\StripeGateway;
use App\Domain\Entitlement\GrantIssuer; use App\Domain\Entitlement\GrantIssuer;
use App\Domain\Identity\PartyType;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -67,9 +70,38 @@ public function checkout(Request $request, Cart $cart, OrderHolders $holders): V
return view('shop.checkout', [ return view('shop.checkout', [
'review' => $review, 'review' => $review,
'holders' => $holders->for($request->user()), '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. * Legt die Bestellung an, aber nur, wenn die serverseitige Prüfung zur gezeigten Übersicht passt.
*/ */
@@ -78,19 +110,28 @@ public function placeOrder(Request $request, Cart $cart, Checkout $checkout): Re
$data = $request->validate([ $data = $request->validate([
'digest' => ['required', 'string'], 'digest' => ['required', 'string'],
'bestellen_als' => ['nullable', 'integer'], 'bestellen_als' => ['nullable', 'integer'],
'zahlungsweg' => ['nullable', 'in:online,rechnung'],
'zustimmung' => ['nullable', 'array'],
]); ]);
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null; $holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId])); $back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
$method = ($data['zahlungsweg'] ?? 'online') === 'rechnung' ? 'rechnung' : null;
try { 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) { } catch (StaleOverview $exception) {
return $back->withErrors(['checkout' => $exception->getMessage()]); return $back->withErrors(['checkout' => $exception->getMessage()]);
} catch (DomainRuleException $exception) { } catch (DomainRuleException $exception) {
return $back->withErrors(['checkout' => $exception->getMessage()]); 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 public function show(Request $request, Order $order): View
@@ -103,9 +144,26 @@ public function show(Request $request, Order $order): View
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test', 'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
'stripePayment' => Shop::stripe(), 'stripePayment' => Shop::stripe(),
'zahlung' => $request->query('zahlung'), 'zahlung' => $request->query('zahlung'),
'live' => Shop::live(),
'receipts' => LedgerEntry::query()->where('order_id', $order->id)->where('derived', false)->orderBy('occurred_at')->orderBy('id')->get(),
]); ]);
} }
/** Erklärt den Widerruf; der Betreiber prüft und erstattet gegebenenfalls in der Bestellverwaltung. */
public function withdraw(Request $request, Order $order, Checkout $checkout): RedirectResponse
{
abort_unless($order->user_id === $request->user()->id, 403);
$data = $request->validate(['note' => ['nullable', 'string', 'max:1000']]);
try {
$checkout->requestWithdrawal($order, (string) ($data['note'] ?? ''));
} catch (DomainRuleException $exception) {
return back()->withErrors(['payment' => $exception->getMessage()]);
}
return redirect()->route('member.order', $order)->with('status', 'Dein Widerruf ist eingegangen. Wir prüfen ihn und melden uns per E-Mail.');
}
/** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */ /** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */
public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse
{ {
@@ -150,6 +208,8 @@ public function fail(Request $request, Order $order, Checkout $checkout): Redire
public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse
{ {
abort_unless($order->user_id === $request->user()->id, 403); 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 { try {
$checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus'); $checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus');
@@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\PaymentJournal;
use App\Domain\Commerce\Receipt\PaymentReceipt;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Zahlungshistorie des Mitglieds mit Einzelbeleg. Sie zeigt nur Buchungen zu Bestellungen, die das angemeldete Konto
* selbst aufgegeben hat (bei Vereinskäufen also nur das bestellende Konto, wie beim Download). Der Beleg wird aus den
* festgehaltenen Angaben der Buchung gebaut (PaymentReceipt).
*/
class PaymentController extends Controller
{
public function index(Request $request): View
{
$entries = LedgerEntry::query()
->whereHas('order', fn ($orders) => $orders->where('user_id', $request->user()->id))
->orderByDesc('occurred_at')
->orderByDesc('id')
->get();
return view('member.payments', [
'rows' => $entries->map(fn (LedgerEntry $entry): array => [
'id' => $entry->id,
'order' => $entry->order_id,
'refund' => $entry->isRefund(),
'date' => PaymentJournal::local($entry->occurred_at)->format('d.m.Y'),
'products' => collect((array) (($entry->order_snapshot ?? [])['lines'] ?? []))->pluck('name')->filter()->values()->all(),
'amount' => $entry->amount_cents,
'provider' => PaymentJournal::providerLabel($entry->provider),
'test' => ! $entry->live,
'receipt' => PaymentReceipt::available($entry),
])->all(),
]);
}
public function receipt(Request $request, LedgerEntry $entry): Response
{
$entry->loadMissing('order');
abort_unless($entry->order?->user_id === $request->user()->id, 403);
abort_unless(PaymentReceipt::available($entry), 404);
return response(PaymentReceipt::render($entry), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.PaymentReceipt::filename($entry).'"',
'Cache-Control' => 'private, no-store',
'X-Content-Type-Options' => 'nosniff',
]);
}
}
@@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\Composition; use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionStructureReader; use App\Domain\Catalog\CompositionStructureReader;
use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Cms\Catalog\PublicCatalogReader;
@@ -17,6 +18,25 @@ public function index(PublicCatalogReader $catalog): View
return view('public.programs', ['programs' => $catalog->publicPrograms()]); return view('public.programs', ['programs' => $catalog->publicPrograms()]);
} }
/**
* Eigene Produktseite eines Pakets, das für sich vermarktet wird: Sie zeigt den tatsächlichen Umfang des Pakets
* (die enthaltenen Artikel) und darunter die kaufbaren Lizenzoptionen. Ohne kaufbare Option gibt es sie nicht.
*/
public function package(Bundle $bundle, ProductOptions $products, Cart $cart): View
{
abort_unless(Shop::enabled(), 404);
$options = $products->forBundle($bundle);
abort_if($options === [], 404);
return view('public.package', [
'bundle' => $bundle,
'contents' => $products->bundleContents($options),
'options' => $options,
'cart' => $cart,
'switchTo' => session('shop.switch'),
]);
}
public function program(Composition $composition, PublicCatalogReader $catalog, ProductOptions $products, Cart $cart): View public function program(Composition $composition, PublicCatalogReader $catalog, ProductOptions $products, Cart $cart): View
{ {
$version = $catalog->shownVersion($composition); $version = $catalog->shownVersion($composition);
+22 -1
View File
@@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\Composition; use App\Domain\Catalog\Composition;
use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Cms\Catalog\PublicCatalogReader;
use App\Domain\Commerce\Money; use App\Domain\Commerce\Money;
@@ -37,7 +38,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR
$summary = $summaries[$composition->id]; $summary = $summaries[$composition->id];
$cards[] = [ $cards[] = [
'composition' => $composition, 'url' => route('public.program', $composition),
'title' => $title, 'title' => $title,
'teaser' => (string) ($composition->teaser ?: $composition->summary), 'teaser' => (string) ($composition->teaser ?: $composition->summary),
'from' => Money::format($summary['from_cents']), 'from' => Money::format($summary['from_cents']),
@@ -45,6 +46,26 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR
]; ];
} }
// Pakete mit eigener Produktseite: gelistet mit Name und enthaltenen Artikeln.
foreach (Bundle::query()->whereIn('id', array_keys($products->bundleSummaries()))->orderBy('name')->get() as $bundle) {
$options = $products->forBundle($bundle);
$contents = $products->bundleContents($options);
$names = implode(', ', array_column($contents, 'title'));
if ($term !== '' && ! str_contains(mb_strtolower($bundle->name.' '.$names), mb_strtolower($term))) {
continue;
}
$summary = $products->bundleSummaries()[$bundle->id];
$cards[] = [
'url' => route('public.package', $bundle),
'title' => (string) $bundle->name,
'teaser' => 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : ''),
'from' => Money::format($summary['from_cents']),
'count' => $summary['count'],
];
}
return view('shop.index', ['cards' => $cards, 'term' => $term]); return view('shop.index', ['cards' => $cards, 'term' => $term]);
} }
} }
@@ -8,6 +8,7 @@
use App\Domain\Commerce\Payment; use App\Domain\Commerce\Payment;
use App\Domain\Commerce\Shop; use App\Domain\Commerce\Shop;
use App\Domain\Commerce\Stripe\StripeSignature; use App\Domain\Commerce\Stripe\StripeSignature;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@@ -42,7 +43,7 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
$session = (array) ($event['data']['object'] ?? []); $session = (array) ($event['data']['object'] ?? []);
return match ($event['type']) { return match ($event['type']) {
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout), 'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout, $event),
'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']), 'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']),
default => response()->json(['received' => true, 'handled' => false]), default => response()->json(['received' => true, 'handled' => false]),
}; };
@@ -50,8 +51,9 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
/** /**
* @param array<string, mixed> $session * @param array<string, mixed> $session
* @param array<string, mixed> $event
*/ */
private function paid(array $session, Checkout $checkout): JsonResponse private function paid(array $session, Checkout $checkout, array $event): JsonResponse
{ {
if (($session['payment_status'] ?? null) !== 'paid') { if (($session['payment_status'] ?? null) !== 'paid') {
return response()->json(['received' => true, 'handled' => false]); return response()->json(['received' => true, 'handled' => false]);
@@ -73,6 +75,9 @@ private function paid(array $session, Checkout $checkout): JsonResponse
$reference, $reference,
(int) ($session['amount_total'] ?? -1), (int) ($session['amount_total'] ?? -1),
(string) ($session['currency'] ?? ''), (string) ($session['currency'] ?? ''),
(bool) ($event['livemode'] ?? $session['livemode'] ?? false),
is_numeric($event['created'] ?? null) ? CarbonImmutable::createFromTimestampUTC((int) $event['created']) : null,
filled($session['payment_intent'] ?? null) ? (string) $session['payment_intent'] : null,
); );
} catch (DomainRuleException $exception) { } catch (DomainRuleException $exception) {
// Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur // Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur
@@ -83,6 +88,10 @@ private function paid(array $session, Checkout $checkout): JsonResponse
return response()->json(['received' => true, 'handled' => false]); 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]); return response()->json(['received' => true, 'handled' => true]);
} }
+2
View File
@@ -158,6 +158,8 @@ private function entry(User $user, Grant $grant): array
? 'Spätere freigegebene Fassungen sind eingeschlossen.' ? 'Spätere freigegebene Fassungen sind eingeschlossen.'
: null, : null,
'source' => $this->source($user, $grant), '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_kind' => $holderKind,
'holder' => $holderKind === 'organisation' ? (string) ($grant->acquisition?->party?->display_name ?? 'Organisation') : 'Persönlich', 'holder' => $holderKind === 'organisation' ? (string) ($grant->acquisition?->party?->display_name ?? 'Organisation') : 'Persönlich',
'url' => route('member.grant', $grant), 'url' => route('member.grant', $grant),
@@ -67,6 +67,12 @@ public function panel(Panel $panel): Panel
->authMiddleware([ ->authMiddleware([
Authenticate::class, Authenticate::class,
]) ])
// Favicon zur Anfragezeit: ->favicon(asset(...)) würde beim Start der Anwendung berechnet, vor der
// Auswertung von Proxy-Kopfzeilen und geöffneter Adresse, und könnte auf einen falschen Host zeigen.
->renderHook(
PanelsRenderHook::HEAD_END,
fn (): string => view('components.site.favicon')->render(),
)
->renderHook( ->renderHook(
PanelsRenderHook::STYLES_AFTER, PanelsRenderHook::STYLES_AFTER,
fn (): string => view('filament.cms.styles')->render().view('filament.verwaltung.styles')->render(), fn (): string => view('filament.cms.styles')->render().view('filament.verwaltung.styles')->render(),
+46
View File
@@ -0,0 +1,46 @@
<?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.
| Standardmäßig aus: Das Mitglied sieht die Möglichkeit erst, wenn der Prozess vollständig ist (Rechnungserstellung
| und Nummernkreis, Benachrichtigung des Betreibers, rechtliche Klärung OPEN-06). Die Umsetzung bleibt erhalten;
| bereits angelegte Rechnungsbestellungen bleiben in der Verwaltung bearbeitbar.
*/
'invoice' => (bool) env('SHOP_INVOICE', false),
/*
| Zahlungsbeleg für Mitglieder (PDF). Aussteller: Zeilen durch „|“ getrennt (zum Beispiel Name|Straße|PLZ Ort), erst
| zu pflegen, wenn die Angaben feststehen; ohne sie druckt der Beleg keinen Aussteller. Hinweis: optionaler Zusatztext
| (Umgebungsvariablen SHOP_RECEIPT_ISSUER, SHOP_RECEIPT_NOTE). Beide hängen an der rechtlichen Klärung (OPEN-06).
*/
'receipt' => [
'issuer' => env('SHOP_RECEIPT_ISSUER'),
'note' => env('SHOP_RECEIPT_NOTE'),
],
/*
| 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.'),
];
+7
View File
@@ -70,6 +70,13 @@ public function katalogverwalter(): static
}); });
} }
public function kundenbetreuung(): static
{
return $this->afterCreating(function (User $user): void {
$user->staffRoles()->create(['role' => StaffRole::Kundenbetreuung]);
});
}
public function redakteur(): static public function redakteur(): static
{ {
return $this->afterCreating(function (User $user): void { return $this->afterCreating(function (User $user): void {
@@ -0,0 +1,123 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Verkaufsstart Deutschland (A1): nur ergänzend, nichts wird gelöscht oder umbenannt; ein Rollback des Codes lässt
* die neuen Spalten und Tabellen liegen (der frühere Code kennt sie nicht).
*
* - Rabattcodes mit Geltungsbereich (Warenkorb oder ausgewählte Ziele) und Einlösungsberechtigung (allgemein oder
* nur für freigeschaltete Konten). Freigaben werden nie gelöscht, nur entzogen.
* - Nutzerkreis der Lizenzoption (Einzel- oder Mehrfachlizenz, Zahl der Trainer) an der Angebotsfassung, kopiert in
* die Bestellposition. Lizenzinhaber, berechtigte Trainer und Downloadzugriff sind getrennte Angaben.
* - Rabatt, Zahlbetrag, Zahlungsweg und Zustimmungsnachweis an der Bestellung.
* - Ein eigenständig vermarktetes Paket hat eine eigene Produktseite (offers.standalone_bundle), die seinen Umfang zeigt.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('discount_codes', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('label');
$table->string('kind', 12);
$table->unsignedTinyInteger('percent')->nullable();
$table->unsignedInteger('amount_cents')->nullable();
$table->string('scope', 12)->default('warenkorb');
$table->string('eligibility', 12)->default('allgemein');
$table->timestamp('valid_from')->nullable();
$table->timestamp('valid_until')->nullable();
$table->boolean('active')->default(true);
$table->text('note')->nullable();
$table->timestamps();
});
Schema::create('discount_code_targets', function (Blueprint $table) {
$table->id();
$table->foreignId('discount_code_id')->constrained('discount_codes')->cascadeOnDelete();
$table->string('target_type', 16);
$table->unsignedBigInteger('target_id');
$table->timestamps();
$table->unique(['discount_code_id', 'target_type', 'target_id']);
});
Schema::create('discount_code_releases', function (Blueprint $table) {
$table->id();
$table->foreignId('discount_code_id')->constrained('discount_codes')->cascadeOnDelete();
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
$table->foreignId('granted_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamp('granted_at');
$table->timestamp('valid_until')->nullable();
$table->foreignId('revoked_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamp('revoked_at')->nullable();
$table->text('reason')->nullable();
$table->timestamps();
$table->index(['discount_code_id', 'user_id']);
});
Schema::table('offers', function (Blueprint $table) {
$table->boolean('standalone_bundle')->default(false);
});
Schema::table('offer_versions', function (Blueprint $table) {
$table->string('licence_scope', 12)->nullable();
$table->unsignedSmallInteger('trainer_count')->nullable();
});
Schema::table('order_lines', function (Blueprint $table) {
$table->string('licence_scope', 12)->nullable();
$table->unsignedSmallInteger('trainer_count')->nullable();
$table->unsignedInteger('discount_cents')->default(0);
});
Schema::table('orders', function (Blueprint $table) {
$table->unsignedInteger('subtotal_cents')->nullable();
$table->unsignedInteger('discount_cents')->default(0);
$table->foreignId('discount_code_id')->nullable()->constrained('discount_codes')->nullOnDelete();
$table->json('discount_snapshot')->nullable();
$table->string('payment_method', 16)->nullable();
$table->timestamp('terms_accepted_at')->nullable();
$table->json('terms_snapshot')->nullable();
$table->timestamp('withdrawal_requested_at')->nullable();
$table->text('withdrawal_note')->nullable();
});
Schema::table('payments', function (Blueprint $table) {
$table->string('provider_payment_ref')->nullable();
$table->unsignedInteger('amount_cents')->nullable();
$table->foreignId('confirmed_by')->nullable()->constrained('users')->nullOnDelete();
});
}
public function down(): void
{
Schema::table('payments', function (Blueprint $table) {
$table->dropConstrainedForeignId('confirmed_by');
$table->dropColumn(['provider_payment_ref', 'amount_cents']);
});
Schema::table('orders', function (Blueprint $table) {
$table->dropConstrainedForeignId('discount_code_id');
$table->dropColumn([
'subtotal_cents', 'discount_cents', 'discount_snapshot', 'payment_method',
'terms_accepted_at', 'terms_snapshot', 'withdrawal_requested_at', 'withdrawal_note',
]);
});
Schema::table('order_lines', function (Blueprint $table) {
$table->dropColumn(['licence_scope', 'trainer_count', 'discount_cents']);
});
Schema::table('offer_versions', function (Blueprint $table) {
$table->dropColumn(['licence_scope', 'trainer_count']);
});
Schema::table('offers', function (Blueprint $table) {
$table->dropColumn('standalone_bundle');
});
Schema::dropIfExists('discount_code_releases');
Schema::dropIfExists('discount_code_targets');
Schema::dropIfExists('discount_codes');
}
};
@@ -0,0 +1,163 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Zahlungsjournal: eine unveränderliche Zeile je Geldbewegung (Zahlungseingang, Erstattung). Rein ergänzend.
*
* Die Tabelle `payments` hält nur den aktuellen Zustand einer Zahlung und überschreibt ihn bei der Erstattung. Für den
* Nachweis gegenüber dem Finanzamt braucht es dagegen je Bewegung Datum, Betrag, Beleg beim Anbieter, handelnde
* Person, Begründung und den Zahler zum Zeitpunkt der Bewegung. Zeilen werden nie geändert oder gelöscht; eine
* Korrektur ist eine neue Gegenbuchung. Auf PostgreSQL erzwingt das ein Trigger auch gegen direkte SQL-Zugriffe.
*
* Bestehende bestätigte und erstattete Zahlungen werden nachgetragen und als „nachgetragen“ markiert: Ihr Datum ist
* aus den Zeitstempeln der Zahlung abgeleitet und nicht der belegte Zahlungs- oder Erstattungszeitpunkt.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('payment_ledger', function (Blueprint $table): void {
$table->id();
$table->string('kind', 16);
$table->foreignId('order_id')->constrained('orders')->restrictOnDelete();
$table->foreignId('payment_id')->nullable()->constrained('payments')->restrictOnDelete();
$table->timestamp('occurred_at');
$table->integer('amount_cents');
$table->string('currency', 3)->default('EUR');
$table->string('provider', 32);
$table->string('provider_reference', 191);
$table->string('provider_payment_ref', 191)->nullable();
$table->string('provider_status', 32)->nullable();
$table->boolean('live')->default(false);
$table->boolean('derived')->default(false);
$table->unsignedBigInteger('actor_id')->nullable();
$table->string('actor_name', 160)->nullable();
$table->text('reason')->nullable();
$table->json('payer');
$table->json('order_snapshot');
$table->timestamp('created_at')->useCurrent();
$table->unique(['kind', 'provider', 'provider_reference'], 'payment_ledger_event_unique');
$table->index(['occurred_at']);
$table->index(['order_id']);
});
$this->backfill();
if (DB::getDriverName() === 'pgsql') {
DB::unprepared(<<<'SQL'
CREATE FUNCTION payment_ledger_immutable() RETURNS trigger AS $$
BEGIN
RAISE EXCEPTION 'Das Zahlungsjournal ist unveränderlich. Korrekturen sind neue Gegenbuchungen.';
END;
$$ LANGUAGE plpgsql
SQL);
DB::unprepared('CREATE TRIGGER payment_ledger_no_change BEFORE UPDATE OR DELETE ON payment_ledger FOR EACH ROW EXECUTE PROCEDURE payment_ledger_immutable()');
}
}
public function down(): void
{
if (DB::getDriverName() === 'pgsql') {
DB::unprepared('DROP TRIGGER IF EXISTS payment_ledger_no_change ON payment_ledger');
DB::unprepared('DROP FUNCTION IF EXISTS payment_ledger_immutable()');
}
Schema::dropIfExists('payment_ledger');
}
private function backfill(): void
{
$payments = DB::table('payments')->whereIn('status', ['bestaetigt', 'erstattet'])->orderBy('id')->get();
foreach ($payments as $payment) {
$order = DB::table('orders')->where('id', $payment->order_id)->first();
if ($order === null) {
continue;
}
$amount = (int) ($payment->amount_cents ?? $order->total_cents ?? 0);
$payer = json_encode($this->payer($order), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$snapshot = json_encode($this->orderSnapshot($order), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
$base = [
'order_id' => $order->id,
'payment_id' => $payment->id,
'currency' => $order->currency ?? 'EUR',
'provider' => $payment->provider,
'provider_payment_ref' => $payment->provider_payment_ref,
'live' => false,
'derived' => true,
'actor_id' => $payment->confirmed_by,
'payer' => $payer,
'order_snapshot' => $snapshot,
];
DB::table('payment_ledger')->insert($base + [
'kind' => 'eingang',
'occurred_at' => $payment->created_at ?? $order->created_at,
'amount_cents' => $amount,
'provider_reference' => $payment->provider_reference,
]);
if ($payment->status === 'erstattet') {
DB::table('payment_ledger')->insert($base + [
'kind' => 'erstattung',
'occurred_at' => $payment->updated_at ?? $payment->created_at ?? $order->created_at,
'amount_cents' => -$amount,
'provider_reference' => 'nachgetragen-'.$payment->id,
'actor_id' => null,
'reason' => 'Nachgetragen: Zeitpunkt, Referenz und Begründung der Erstattung wurden damals nicht festgehalten.',
]);
}
}
}
/**
* @return array<string, mixed>
*/
private function payer(object $order): array
{
$party = $order->party_id === null ? null : DB::table('parties')->where('id', $order->party_id)->first();
$user = $order->user_id === null ? null : DB::table('users')->where('id', $order->user_id)->first();
$address = $order->party_id === null ? null : DB::table('billing_addresses')->where('party_id', $order->party_id)->first();
return [
'holder' => $party?->display_name,
'holder_kind' => $order->holder_kind,
'buyer' => $user?->name,
'buyer_email' => $user?->email,
'billing' => $address === null ? null : [
'recipient' => $address->recipient,
'line2' => $address->line2,
'street' => $address->street,
'postal_code' => $address->postal_code,
'city' => $address->city,
'country' => $address->country,
],
];
}
/**
* @return array<string, mixed>
*/
private function orderSnapshot(object $order): array
{
$lines = DB::table('order_lines')->where('order_id', $order->id)->orderBy('id')->get(['offer_name', 'price_cents', 'discount_cents']);
return [
'subtotal_cents' => (int) ($order->subtotal_cents ?? $order->total_cents ?? 0),
'discount_cents' => (int) ($order->discount_cents ?? 0),
'discount_code' => json_decode((string) ($order->discount_snapshot ?? 'null'), true)['code'] ?? null,
'lines' => $lines->map(fn (object $line): array => [
'name' => $line->offer_name,
'price_cents' => (int) $line->price_cents,
'discount_cents' => (int) ($line->discount_cents ?? 0),
])->all(),
];
}
};
+8 -5
View File
@@ -8,6 +8,7 @@
use App\Domain\Catalog\CompositionVersion; use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ContentService; use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\EditorialContentKind; use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Catalog\LicenceScope;
use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer; use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService; use App\Domain\Catalog\OfferService;
@@ -78,14 +79,14 @@ public function run(): void
'pdf' => ['ansehen', 'laden'], 'pdf' => ['ansehen', 'laden'],
]); ]);
$this->offer($offers, 'Konflikte im Training: Privatlizenz', 'Privatlizenz', $konflikteVersion, [$konflikteArticle, $privat], 4900, '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'); $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'); $this->offer($offers, 'Grenzen setzen: Privatlizenz', 'Privatlizenz', $grenzenVersion, [$grenzenArticle, $privat], 2900, 'person', LicenceScope::SINGLE, 1);
$bundle = $bundles->create('Starterpaket'); $bundle = $bundles->create('Starterpaket');
$starter = $bundles->publish($bundle, [$konflikteArticle->fresh(), $grenzenArticle->fresh(), $starterArticle->fresh()]); $starter = $bundles->publish($bundle, [$konflikteArticle->fresh(), $grenzenArticle->fresh(), $starterArticle->fresh()]);
$paket = $offers->create('Starterpaket: Privatlizenz'); $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)'); $offers->assignProduct($paket, $starterVersion->composition_id, 'Starterpaket (zwei Programme und Einführung)');
$tina = $this->account('Tina Trainerin', 'tina.trainerin@example.test'); $tina = $this->account('Tina Trainerin', 'tina.trainerin@example.test');
@@ -160,13 +161,15 @@ private function program(
/** /**
* @param array{0: LicenseArticle, 1: RightsProfileVersion} $line * @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); $offer = $offers->create($name);
$offers->activate($offer, [['target' => $line[0], 'rights' => $line[1]]], [ $offers->activate($offer, [['target' => $line[0], 'rights' => $line[1]]], [
'grant_kind' => 'kauf', 'grant_kind' => 'kauf',
'price_cents' => $cents, 'price_cents' => $cents,
'holder_kind' => $holder, 'holder_kind' => $holder,
'licence_scope' => $scope,
'trainer_count' => $trainers,
]); ]);
$offers->assignProduct($offer, $version->composition_id, $label); $offers->assignProduct($offer, $version->composition_id, $label);
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 835 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-labelledby="favicon-title">
<title id="favicon-title">Lara &amp; Felix</title>
<rect x="1" y="1" width="62" height="62" rx="15" fill="#032551" stroke="#426184" stroke-width="2"/>
<g fill="none" stroke="#fff" stroke-width="8.4" stroke-linecap="round" stroke-linejoin="round">
<path d="M14.8 20 Q14 31 14.8 39 Q20.6 39 25.4 37.8"/>
<path d="M37.4 38.8 Q36.8 29.1 37.8 18.6 Q44.6 17.1 50.1 18.2 M37.5 28.7 Q43 27.9 47.4 28.1"/>
</g>
<path d="M13 51 Q31 44.2 51 49.3" fill="none" stroke="#FCD10A" stroke-width="5.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 661 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 129" width="250" height="129" role="img" aria-labelledby="motif-title">
<title id="motif-title">Alltagssituationen</title>
<g transform="translate(81 2) scale(.92)"><g transform="translate(0 5) rotate(-7 36 54)"><rect x="10" y="47" width="53" height="33" rx="4.7" fill="none" stroke="#032551" stroke-width="3.9"/><g transform="translate(16.9 44.8) scale(.38)"><path d="M37 26 Q37 22 41 24 L72 43 Q77 47 72 51 L41 70 Q37 73 37 68Z" fill="#032551"/></g><g transform="rotate(-11 11 48)"><rect x="10" y="36" width="53" height="12" rx="3.7" fill="none" stroke="#032551" stroke-width="3.8"/><path d="M16 46 L22 37 M27 47 L33 37 M39 47 L45 37 M51 47 L57 37" fill="none" stroke="#032551" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round"/></g></g><g transform="translate(61 2) rotate(8 16 20) scale(.86)"><path d="M5 23 L9 9 M16 26 L28 16 M20 35 L35 33" fill="none" stroke="#FCD10A" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"/></g></g><path d="M36.25 115.08Q36.33 115.33 36.33 115.57Q36.33 115.9 36.19 116.16Q36.05 116.43 35.82 116.61Q35.59 116.79 35.3 116.89Q35 116.99 34.7 116.99Q34.25 116.99 33.85 116.74Q33.45 116.49 33.32 115.95L32.05 112.69H24.22L22.97 115.95Q22.82 116.5 22.44 116.74Q22.05 116.99 21.61 116.99Q21.32 116.99 21.03 116.89Q20.73 116.79 20.51 116.61Q20.28 116.43 20.14 116.17Q20 115.91 20 115.6Q20 115.47 20.02 115.35Q20.04 115.22 20.1 115.08L25.23 102.27Q25.53 101.41 25.84 100.87Q26.14 100.33 26.49 100.01Q26.84 99.7 27.25 99.58Q27.65 99.46 28.16 99.46Q28.67 99.46 29.08 99.59Q29.5 99.71 29.85 100.03Q30.19 100.35 30.5 100.89Q30.8 101.44 31.1 102.27ZM28.12 101.96 24.9 110.64H31.38L28.17 101.96ZM38.85 100.87Q38.85 100.52 38.97 100.26Q39.1 100 39.3 99.82Q39.5 99.64 39.76 99.55Q40.02 99.46 40.29 99.46Q40.56 99.46 40.82 99.55Q41.07 99.64 41.27 99.82Q41.48 100 41.6 100.26Q41.72 100.52 41.72 100.87V115.58Q41.72 115.94 41.59 116.2Q41.46 116.46 41.26 116.64Q41.06 116.82 40.8 116.91Q40.54 117 40.27 117Q40 117 39.74 116.91Q39.49 116.83 39.29 116.65Q39.1 116.48 38.97 116.21Q38.85 115.94 38.85 115.58ZM45.21 100.87Q45.21 100.52 45.34 100.26Q45.46 100 45.66 99.82Q45.86 99.64 46.12 99.55Q46.39 99.46 46.65 99.46Q46.92 99.46 47.18 99.55Q47.44 99.64 47.64 99.82Q47.84 100 47.96 100.26Q48.08 100.52 48.08 100.87V115.58Q48.08 115.94 47.95 116.2Q47.83 116.46 47.62 116.64Q47.42 116.82 47.16 116.91Q46.9 117 46.63 117Q46.36 117 46.11 116.91Q45.85 116.83 45.65 116.65Q45.46 116.48 45.34 116.21Q45.21 115.94 45.21 115.58ZM52.65 104.78 52.88 101.5Q52.91 101.23 53.04 101.01Q53.16 100.8 53.36 100.65Q53.55 100.51 53.79 100.44Q54.02 100.36 54.25 100.36Q54.69 100.36 55.03 100.63Q55.37 100.9 55.37 101.47V104.78H57.24Q57.74 104.78 58 105.09Q58.25 105.4 58.25 105.77Q58.25 106.14 58 106.44Q57.75 106.75 57.24 106.75H55.37V111.82Q55.37 112.69 55.4 113.29Q55.43 113.89 55.56 114.26Q55.69 114.63 55.97 114.8Q56.24 114.96 56.73 114.96Q56.85 114.96 57 114.95Q57.14 114.94 57.29 114.92Q57.44 114.9 57.56 114.89Q57.69 114.88 57.77 114.88Q58.23 114.88 58.49 115.18Q58.74 115.49 58.74 115.86Q58.74 116.26 58.5 116.5Q58.27 116.74 57.88 116.89Q57.5 117.04 57.02 117.09Q56.55 117.15 56.06 117.15Q55.2 117.15 54.54 116.93Q53.88 116.71 53.43 116.2Q52.98 115.69 52.74 114.86Q52.5 114.03 52.5 112.83V106.75H51.32Q50.81 106.75 50.56 106.44Q50.31 106.14 50.31 105.77Q50.31 105.4 50.56 105.09Q50.82 104.78 51.33 104.78ZM67.95 108.87Q67.95 108.25 67.77 107.83Q67.6 107.42 67.28 107.16Q66.96 106.9 66.52 106.79Q66.07 106.69 65.53 106.69Q64.92 106.69 64.42 106.75Q63.92 106.82 63.49 106.94Q63.05 107.06 62.68 107.22Q62.3 107.37 61.93 107.54Q61.75 107.61 61.57 107.61Q61.39 107.61 61.24 107.55Q61.09 107.48 60.97 107.36Q60.86 107.25 60.79 107.09Q60.72 106.94 60.72 106.78Q60.72 106.65 60.77 106.54Q60.81 106.44 60.89 106.31Q61.48 105.43 62.71 105.03Q63.95 104.63 65.69 104.63Q66.75 104.63 67.66 104.88Q68.57 105.12 69.23 105.65Q69.89 106.18 70.26 107.03Q70.64 107.88 70.64 109.09V115.74Q70.62 116.06 70.51 116.29Q70.39 116.52 70.2 116.68Q70.01 116.84 69.77 116.92Q69.54 117 69.29 117Q69.06 117 68.83 116.93Q68.61 116.85 68.43 116.71Q68.25 116.56 68.14 116.34Q68.03 116.12 68.02 115.83V114.91Q67.77 115.35 67.35 115.8Q66.92 116.24 66.38 116.54Q65.84 116.84 65.23 116.99Q64.62 117.15 63.99 117.15Q63.12 117.15 62.35 116.9Q61.59 116.66 61.03 116.19Q60.48 115.73 60.16 115.05Q59.84 114.36 59.84 113.64Q59.84 112.52 60.33 111.73Q60.81 110.95 61.71 110.45Q62.6 109.96 63.87 109.74Q65.14 109.52 66.72 109.52Q66.96 109.52 67.32 109.52Q67.68 109.53 67.95 109.54ZM67.94 111.14Q67.84 111.14 67.7 111.15Q67.56 111.15 67.41 111.15Q67.25 111.15 67.1 111.15Q66.95 111.15 66.83 111.15Q66.06 111.15 65.29 111.24Q64.52 111.32 63.9 111.57Q63.29 111.82 62.9 112.28Q62.52 112.74 62.52 113.47Q62.52 113.84 62.7 114.23Q62.88 114.62 63.19 114.88Q63.51 115.13 63.93 115.26Q64.36 115.39 64.85 115.4Q65.5 115.39 66.05 115.17Q66.61 114.95 67.02 114.52Q67.44 114.08 67.67 113.52Q67.91 112.96 67.94 112.12ZM82.83 110.92Q82.83 109.97 82.67 109.23Q82.5 108.49 82.12 107.88Q81.75 107.26 81.12 106.9Q80.49 106.54 79.56 106.54Q78.66 106.54 78.07 106.88Q77.47 107.22 77.11 107.83Q76.75 108.43 76.61 109.25Q76.46 110.07 76.46 110.88Q76.46 112.03Line truncated
</svg>

After

Width:  |  Height:  |  Size: 19 KiB

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" width="96" height="96" role="img" aria-labelledby="motif-title">
<title id="motif-title">Bildung</title>
<path d="M25 47 V64 C37 75 59 75 71 64 V47 M82 44 V65" fill="none" stroke="#032551" stroke-width="4.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M9 37 L48 22 L87 37 L48 53Z" fill="none" stroke="#3B7B09" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round"/><circle cx="82" cy="68" r="3.6" fill="#FCD10A" stroke="none" stroke-width="0"/>
</svg>

After

Width:  |  Height:  |  Size: 541 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" width="96" height="96" role="img" aria-labelledby="motif-title">
<title id="motif-title">Aufgeschlagenes Buch</title>
<path d="M19 29 C29 24 39 25 48 32 C57 25 67 24 77 29 V66 C65 62 55 64 48 70 C41 64 31 62 19 66Z M48 32 V70" fill="none" stroke="#032551" stroke-width="4.3" stroke-linecap="round" stroke-linejoin="round"/><path d="M19 33 H12 V75 C24 70 37 71 48 77 C59 71 72 70 84 75 V33 H77" fill="none" stroke="#3B7B09" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 560 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 176 71" width="176" height="71" role="img" aria-labelledby="motif-title">
<title id="motif-title">Das ist nicht okay!</title>
<rect x="5" y="5" width="166" height="61" rx="30.5" fill="#FFF2F1" stroke="#E6BDC1" stroke-width="1.5"/><circle cx="37" cy="35.5" r="22.5" fill="#BC2335" stroke="none" stroke-width="0"/><g transform="translate(9.2 7.7) scale(.58)"><path d="M33 33 L63 63 M63 33 L33 63" fill="none" stroke="#FFFFFF" stroke-width="7.5" stroke-linecap="round" stroke-linejoin="round"/></g><path d="M70.7 31Q70.45 31 70.23 30.91Q70 30.82 69.84 30.65Q69.67 30.49 69.57 30.27Q69.48 30.05 69.48 29.81V19Q69.48 18.75 69.57 18.53Q69.67 18.31 69.84 18.15Q70 17.99 70.23 17.9Q70.45 17.8 70.7 17.8H73.97Q75.75 17.8 77.07 18.24Q78.39 18.69 79.27 19.54Q80.14 20.39 80.58 21.63Q81.01 22.87 81.01 24.45Q81.01 26.04 80.53 27.26Q80.06 28.48 79.17 29.32Q78.28 30.15 76.99 30.57Q75.69 31 74.06 31ZM71.92 29.32H73.99Q75.19 29.32 76.03 28.99Q76.87 28.65 77.4 28.02Q77.93 27.38 78.18 26.47Q78.42 25.57 78.42 24.41Q78.42 23.13 78.11 22.21Q77.79 21.28 77.19 20.67Q76.58 20.07 75.69 19.78Q74.8 19.49 73.65 19.49H71.92ZM88.75 24.89Q88.75 24.42 88.62 24.11Q88.48 23.79 88.24 23.6Q88 23.41 87.67 23.33Q87.33 23.24 86.93 23.24Q86.47 23.24 86.1 23.29Q85.72 23.34 85.39 23.44Q85.07 23.53 84.78 23.64Q84.5 23.76 84.22 23.89Q84.09 23.94 83.95 23.94Q83.82 23.94 83.7 23.89Q83.59 23.84 83.5 23.75Q83.41 23.67 83.36 23.55Q83.31 23.44 83.31 23.32Q83.31 23.22 83.35 23.14Q83.38 23.06 83.44 22.96Q83.88 22.3 84.81 22Q85.74 21.7 87.05 21.7Q87.85 21.7 88.53 21.88Q89.22 22.07 89.71 22.47Q90.21 22.87 90.49 23.5Q90.77 24.14 90.77 25.05V30.05Q90.76 30.29 90.67 30.47Q90.58 30.64 90.44 30.76Q90.3 30.88 90.12 30.94Q89.94 31 89.76 31Q89.58 31 89.41 30.94Q89.24 30.89 89.11 30.78Q88.98 30.67 88.9 30.5Q88.81 30.34 88.8 30.12V29.43Q88.61 29.76 88.29 30.1Q87.98 30.43 87.57 30.66Q87.16 30.88 86.7 31Q86.24 31.11 85.77 31.11Q85.11 31.11 84.54 30.93Q83.97 30.74 83.55 30.39Q83.13 30.05 82.89 29.53Q82.65 29.02 82.65 28.48Q82.65 27.63 83.02 27.04Q83.38 26.45 84.05 26.08Q84.73 25.7 85.68 25.54Q86.64 25.37 87.82 25.37Q88 25.37 88.28 25.38Q88.55 25.38 88.75 25.39ZM88.74 26.59Q88.67 26.59 88.56 26.6Q88.45 26.6 88.34 26.6Q88.23 26.6 88.11 26.6Q88 26.6 87.9 26.6Q87.33 26.6 86.75 26.67Q86.17 26.73 85.71 26.92Q85.24 27.11 84.95 27.45Q84.66 27.8 84.66 28.35Q84.66 28.62 84.8 28.92Q84.94 29.21 85.17 29.4Q85.41 29.6 85.73 29.69Q86.05 29.79 86.42 29.8Q86.9 29.79 87.32 29.62Q87.74 29.46 88.05 29.13Q88.36 28.81 88.54 28.38Q88.72 27.96 88.74 27.33ZM95.08 24.18Q95.08 24.46 95.24 24.66Q95.41 24.85 95.69 24.99Q95.97 25.13 96.36 25.24Q96.75 25.34 97.2 25.44Q97.65 25.54 98.14 25.68Q98.63 25.81 99.11 25.98Q99.99 26.24 100.49 26.79Q100.99 27.34 100.99 28.16Q100.99 28.84 100.67 29.41Q100.34 29.98 99.78 30.36Q99.22 30.73 98.48 30.92Q97.73 31.11 96.87 31.11Q96.1 31.11 95.41 30.98Q94.72 30.85 94.19 30.63Q93.67 30.41 93.36 30.12Q93.06 29.82 93.06 29.49Q93.06 29.24 93.26 29.06Q93.46 28.89 93.77 28.89Q93.96 28.89 94.27 29.01Q94.58 29.13 95 29.29Q95.42 29.46 95.94 29.58Q96.45 29.7 97.05 29.7Q97.42 29.7 97.76 29.62Q98.11 29.54 98.38 29.37Q98.66 29.2 98.82 28.94Q98.99 28.68 98.99 28.32Q98.99 27.99 98.7 27.7Q98.41 27.41 97.88 27.25Q97.27 27.08 96.68 26.95Q96.09 26.82 95.55 26.68Q95.01 26.54 94.56 26.36Q94.1 26.17 93.78 25.89Q93.45 25.61 93.26 25.21Q93.07 24.8 93.07 24.23Q93.07 23.67 93.37 23.17Q93.66 22.67 94.18 22.34Q94.7 22.01 95.41 21.86Q96.11 21.7 96.94 21.7Q97.8 21.7 98.44 21.83Q99.09 21.96 99.51 22.16Q99.94 22.37 100.15 22.63Q100.36 22.89 100.36 23.16Q100.36 23.42 100.16 23.56Q99.96 23.7 99.67 23.7Q99.56 23.7 99.46 23.68Q99.35 23.66 99.25 23.6Q98.88 23.39 98.35 23.26Q97.81 23.13 97.03 23.13Q96.59 23.13 96.23 23.19Q95.86 23.25 95.61 23.39Q95.36 23.53 95.22 23.77Q95.08 24.01 95.08 24.18ZM111.14 18.76Q111.14 19.21 110.79 19.5Q110.43 19.79 109.87 19.79Q109.59 19.79 109.36 19.71Q109.12 19.64 108.95 19.5Q108.78 19.36 108.69 19.17Q108.59 18.98 108.59 18.76Q108.59 18.54 108.69 18.35Q108.78 18.17 108.95 18.03Q109.12 17.89 109.36 17.81Q109.6 17.74 109.88 17.74Q110.15 17.74 110.39 17.81Q110.62 17.89 110.79 18.03Q110.95 18.17 111.05 18.35Q111.14 18.54 111.14 18.76ZM108.79 22.88Q108.79 22.61 108.89 22.41Q108.98 22.22 109.13 22.08Q109.28 21.95 109.48 21.88Q109.68 21.81 109.88 21.81Q110.08 21.81 110.27 21.88Q110.46 21.95 110.62 22.08Q110.77 22.22 110.86 22.41Q110.95 22.61 110.95 22.88V29.94Q110.95 30.2 110.86 30.4Q110.76 30.6 110.61 30.73Q110.46 30.86 110.26 30.93Q110.06 31 109.86 31Q109.66 31 109.46 30.94Q109.27 30.87 109.12 30.74Q108.98 30.61 108.89 30.4Q108.79 30.2 108.79 29.94ZM115.3 24.18Q115.3 24.46 115.46 24.66Q115.63 24.85 115.91 24.99Q116.2 25.13 116.58 25.24Q116.97 25.34 117.42 25.44Q117.87 25.54 118.36 25.68Q118.85 25.81 119.33 25.98Q120.21 26.24 120.71 26.79Q121.21 27.34 121.21 28.16Q121.21 28.84 120.89 29.41Q120.56 29.98 120 30.36Q119.44 30.73 118.7 30.92Q117.95 31.11 117.09 31.11Q116.32 31.11 115.63 30.98Q114.94 30.85 114.41 30.63Q113.89 30.41 113.58 30.12Q113.28 29.82 113.28 29.49Q113.28 29.24 113.48 29.06Q113.68 28.89 113.99 28.89Q114.18 28.89 114.49 29.01Q114.8 29.13 115.22 29.29Q115.64 29.46 116.16 29.58Q116.67 29.7 117.27 29.7Q1Line truncated
</svg>

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 176 71" width="176" height="71" role="img" aria-labelledby="motif-title">
<title id="motif-title">Das ist okay!</title>
<rect x="5" y="5" width="166" height="61" rx="30.5" fill="#F1F6E9" stroke="#B8CDA7" stroke-width="1.5"/><circle cx="37" cy="35.5" r="22.5" fill="#3B7B09" stroke="none" stroke-width="0"/><g transform="translate(9.2 7.7) scale(.58)"><path d="M27 49 L41 63 L70 33" fill="none" stroke="#FFFFFF" stroke-width="7.5" stroke-linecap="round" stroke-linejoin="round"/></g><path d="M70.7 31Q70.45 31 70.23 30.91Q70 30.82 69.84 30.65Q69.67 30.49 69.57 30.27Q69.48 30.05 69.48 29.81V19Q69.48 18.75 69.57 18.53Q69.67 18.31 69.84 18.15Q70 17.99 70.23 17.9Q70.45 17.8 70.7 17.8H73.97Q75.75 17.8 77.07 18.24Q78.39 18.69 79.27 19.54Q80.14 20.39 80.58 21.63Q81.01 22.87 81.01 24.45Q81.01 26.04 80.53 27.26Q80.06 28.48 79.17 29.32Q78.28 30.15 76.99 30.57Q75.69 31 74.06 31ZM71.92 29.32H73.99Q75.19 29.32 76.03 28.99Q76.87 28.65 77.4 28.02Q77.93 27.38 78.18 26.47Q78.42 25.57 78.42 24.41Q78.42 23.13 78.11 22.21Q77.79 21.28 77.19 20.67Q76.58 20.07 75.69 19.78Q74.8 19.49 73.65 19.49H71.92ZM88.75 24.89Q88.75 24.42 88.62 24.11Q88.48 23.79 88.24 23.6Q88 23.41 87.67 23.33Q87.33 23.24 86.93 23.24Q86.47 23.24 86.1 23.29Q85.72 23.34 85.39 23.44Q85.07 23.53 84.78 23.64Q84.5 23.76 84.22 23.89Q84.09 23.94 83.95 23.94Q83.82 23.94 83.7 23.89Q83.59 23.84 83.5 23.75Q83.41 23.67 83.36 23.55Q83.31 23.44 83.31 23.32Q83.31 23.22 83.35 23.14Q83.38 23.06 83.44 22.96Q83.88 22.3 84.81 22Q85.74 21.7 87.05 21.7Q87.85 21.7 88.53 21.88Q89.22 22.07 89.71 22.47Q90.21 22.87 90.49 23.5Q90.77 24.14 90.77 25.05V30.05Q90.76 30.29 90.67 30.47Q90.58 30.64 90.44 30.76Q90.3 30.88 90.12 30.94Q89.94 31 89.76 31Q89.58 31 89.41 30.94Q89.24 30.89 89.11 30.78Q88.98 30.67 88.9 30.5Q88.81 30.34 88.8 30.12V29.43Q88.61 29.76 88.29 30.1Q87.98 30.43 87.57 30.66Q87.16 30.88 86.7 31Q86.24 31.11 85.77 31.11Q85.11 31.11 84.54 30.93Q83.97 30.74 83.55 30.39Q83.13 30.05 82.89 29.53Q82.65 29.02 82.65 28.48Q82.65 27.63 83.02 27.04Q83.38 26.45 84.05 26.08Q84.73 25.7 85.68 25.54Q86.64 25.37 87.82 25.37Q88 25.37 88.28 25.38Q88.55 25.38 88.75 25.39ZM88.74 26.59Q88.67 26.59 88.56 26.6Q88.45 26.6 88.34 26.6Q88.23 26.6 88.11 26.6Q88 26.6 87.9 26.6Q87.33 26.6 86.75 26.67Q86.17 26.73 85.71 26.92Q85.24 27.11 84.95 27.45Q84.66 27.8 84.66 28.35Q84.66 28.62 84.8 28.92Q84.94 29.21 85.17 29.4Q85.41 29.6 85.73 29.69Q86.05 29.79 86.42 29.8Q86.9 29.79 87.32 29.62Q87.74 29.46 88.05 29.13Q88.36 28.81 88.54 28.38Q88.72 27.96 88.74 27.33ZM95.08 24.18Q95.08 24.46 95.24 24.66Q95.41 24.85 95.69 24.99Q95.97 25.13 96.36 25.24Q96.75 25.34 97.2 25.44Q97.65 25.54 98.14 25.68Q98.63 25.81 99.11 25.98Q99.99 26.24 100.49 26.79Q100.99 27.34 100.99 28.16Q100.99 28.84 100.67 29.41Q100.34 29.98 99.78 30.36Q99.22 30.73 98.48 30.92Q97.73 31.11 96.87 31.11Q96.1 31.11 95.41 30.98Q94.72 30.85 94.19 30.63Q93.67 30.41 93.36 30.12Q93.06 29.82 93.06 29.49Q93.06 29.24 93.26 29.06Q93.46 28.89 93.77 28.89Q93.96 28.89 94.27 29.01Q94.58 29.13 95 29.29Q95.42 29.46 95.94 29.58Q96.45 29.7 97.05 29.7Q97.42 29.7 97.76 29.62Q98.11 29.54 98.38 29.37Q98.66 29.2 98.82 28.94Q98.99 28.68 98.99 28.32Q98.99 27.99 98.7 27.7Q98.41 27.41 97.88 27.25Q97.27 27.08 96.68 26.95Q96.09 26.82 95.55 26.68Q95.01 26.54 94.56 26.36Q94.1 26.17 93.78 25.89Q93.45 25.61 93.26 25.21Q93.07 24.8 93.07 24.23Q93.07 23.67 93.37 23.17Q93.66 22.67 94.18 22.34Q94.7 22.01 95.41 21.86Q96.11 21.7 96.94 21.7Q97.8 21.7 98.44 21.83Q99.09 21.96 99.51 22.16Q99.94 22.37 100.15 22.63Q100.36 22.89 100.36 23.16Q100.36 23.42 100.16 23.56Q99.96 23.7 99.67 23.7Q99.56 23.7 99.46 23.68Q99.35 23.66 99.25 23.6Q98.88 23.39 98.35 23.26Q97.81 23.13 97.03 23.13Q96.59 23.13 96.23 23.19Q95.86 23.25 95.61 23.39Q95.36 23.53 95.22 23.77Q95.08 24.01 95.08 24.18ZM111.14 18.76Q111.14 19.21 110.79 19.5Q110.43 19.79 109.87 19.79Q109.59 19.79 109.36 19.71Q109.12 19.64 108.95 19.5Q108.78 19.36 108.69 19.17Q108.59 18.98 108.59 18.76Q108.59 18.54 108.69 18.35Q108.78 18.17 108.95 18.03Q109.12 17.89 109.36 17.81Q109.6 17.74 109.88 17.74Q110.15 17.74 110.39 17.81Q110.62 17.89 110.79 18.03Q110.95 18.17 111.05 18.35Q111.14 18.54 111.14 18.76ZM108.79 22.88Q108.79 22.61 108.89 22.41Q108.98 22.22 109.13 22.08Q109.28 21.95 109.48 21.88Q109.68 21.81 109.88 21.81Q110.08 21.81 110.27 21.88Q110.46 21.95 110.62 22.08Q110.77 22.22 110.86 22.41Q110.95 22.61 110.95 22.88V29.94Q110.95 30.2 110.86 30.4Q110.76 30.6 110.61 30.73Q110.46 30.86 110.26 30.93Q110.06 31 109.86 31Q109.66 31 109.46 30.94Q109.27 30.87 109.12 30.74Q108.98 30.61 108.89 30.4Q108.79 30.2 108.79 29.94ZM115.3 24.18Q115.3 24.46 115.46 24.66Q115.63 24.85 115.91 24.99Q116.2 25.13 116.58 25.24Q116.97 25.34 117.42 25.44Q117.87 25.54 118.36 25.68Q118.85 25.81 119.33 25.98Q120.21 26.24 120.71 26.79Q121.21 27.34 121.21 28.16Q121.21 28.84 120.89 29.41Q120.56 29.98 120 30.36Q119.44 30.73 118.7 30.92Q117.95 31.11 117.09 31.11Q116.32 31.11 115.63 30.98Q114.94 30.85 114.41 30.63Q113.89 30.41 113.58 30.12Q113.28 29.82 113.28 29.49Q113.28 29.24 113.48 29.06Q113.68 28.89 113.99 28.89Q114.18 28.89 114.49 29.01Q114.8 29.13 115.22 29.29Q115.64 29.46 116.16 29.58Q116.67 29.7 117.27 29.7Q117.64 2Line truncated
</svg>

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 224 74" width="224" height="74" role="img" aria-labelledby="motif-title">
<title id="motif-title">Denkpause</title>
<rect x="10" y="11" width="207" height="51" rx="25.5" fill="#3B7B09" stroke="#FFFFFF" stroke-width="2.3"/><circle cx="33" cy="36.5" r="27.7" fill="#3B7B09" stroke="#FFFFFF" stroke-width="3.1"/><g transform="translate(9 10) scale(.55)"><path d="M30 51 V31 C30 25 37 24 38 31 V45 V19 C38 13 46 13 46 19 V43 V15 C46 9 54 9 54 15 V43 V21 C54 15 62 15 62 21 V46 V29 C62 23 70 23 70 29 V58 C70 73 62 83 49 83 H44 C36 82 30 77 25 69 L17 56 C13 49 21 45 26 50 L34 58 L30 51Z" fill="#FFFFFF"/><path d="M34 57 Q43 58 46 66" fill="none" stroke="#3B7B09" stroke-width="3.6" stroke-linecap="round" stroke-linejoin="round"/></g><path d="M74.33 45Q74 45 73.7 44.88Q73.4 44.76 73.18 44.54Q72.96 44.32 72.84 44.03Q72.71 43.74 72.71 43.41V29.05Q72.71 28.72 72.84 28.42Q72.96 28.13 73.18 27.92Q73.4 27.7 73.7 27.57Q74 27.45 74.33 27.45H78.68Q81.04 27.45 82.8 28.04Q84.56 28.63 85.73 29.76Q86.89 30.89 87.47 32.54Q88.04 34.18 88.04 36.3Q88.04 38.41 87.41 40.03Q86.78 41.66 85.6 42.76Q84.41 43.86 82.69 44.43Q80.97 45 78.8 45ZM75.95 42.77H78.71Q80.3 42.77 81.42 42.32Q82.53 41.88 83.24 41.03Q83.95 40.19 84.27 38.98Q84.6 37.77 84.6 36.24Q84.6 34.54 84.18 33.31Q83.77 32.07 82.96 31.27Q82.16 30.46 80.97 30.08Q79.79 29.69 78.26 29.69H75.95ZM102.57 38.49Q102.57 38.82 102.35 39.07Q102.14 39.32 101.7 39.32H93.39Q93.5 41.09 94.48 42.07Q95.46 43.05 97.08 43.05Q98.06 43.05 98.94 42.77Q99.82 42.49 100.74 42.02Q100.96 41.91 101.15 41.91Q101.48 41.91 101.68 42.16Q101.88 42.4 101.88 42.72Q101.88 42.85 101.84 43Q101.8 43.16 101.7 43.29Q101.31 43.79 100.74 44.15Q100.18 44.5 99.52 44.72Q98.86 44.94 98.16 45.04Q97.45 45.15 96.79 45.15Q95.46 45.15 94.32 44.71Q93.17 44.27 92.32 43.43Q91.47 42.6 90.99 41.37Q90.51 40.14 90.51 38.84Q90.51 37.72 90.96 36.58Q91.41 35.43 92.2 34.58Q92.99 33.72 94.09 33.18Q95.2 32.63 96.66 32.63Q98.16 32.63 99.25 33.11Q100.35 33.59 101.07 34.38Q101.8 35.17 102.17 36.28Q102.54 37.38 102.57 38.49ZM100.03 37.86Q99.98 37.27 99.75 36.61Q99.52 35.95 99.1 35.48Q98.67 35.01 98.07 34.78Q97.47 34.54 96.68 34.54Q95.98 34.54 95.4 34.79Q94.82 35.05 94.4 35.54Q93.97 36.03 93.72 36.67Q93.46 37.32 93.41 37.86ZM105.4 34.12Q105.4 33.79 105.53 33.54Q105.65 33.28 105.85 33.12Q106.05 32.95 106.31 32.87Q106.58 32.78 106.84 32.78Q107.11 32.78 107.36 32.86Q107.61 32.94 107.81 33.1Q108.02 33.27 108.14 33.51Q108.26 33.75 108.27 34.07V35.03Q108.49 34.58 108.91 34.1Q109.33 33.62 109.88 33.3Q110.43 32.98 111.07 32.81Q111.7 32.63 112.36 32.63Q113.22 32.63 113.99 32.9Q114.77 33.17 115.36 33.74Q115.95 34.31 116.3 35.19Q116.65 36.08 116.65 37.3V43.62Q116.65 43.96 116.52 44.22Q116.4 44.48 116.2 44.65Q116 44.83 115.74 44.91Q115.47 45 115.21 45Q114.94 45 114.69 44.91Q114.44 44.83 114.24 44.65Q114.03 44.48 113.91 44.22Q113.79 43.96 113.79 43.62V37.27Q113.79 36.58 113.59 36.06Q113.4 35.55 113.07 35.21Q112.74 34.87 112.3 34.7Q111.86 34.54 111.37 34.54Q110.73 34.54 110.16 34.75Q109.6 34.95 109.18 35.37Q108.76 35.8 108.52 36.35Q108.27 36.89 108.27 37.75V43.62Q108.27 43.96 108.15 44.22Q108.03 44.48 107.83 44.65Q107.62 44.83 107.36 44.91Q107.1 45 106.83 45Q106.56 45 106.31 44.91Q106.05 44.83 105.85 44.65Q105.65 44.48 105.53 44.22Q105.4 43.96 105.4 43.62ZM123.08 38.49V43.57Q123.08 43.93 122.95 44.19Q122.83 44.46 122.62 44.64Q122.42 44.82 122.16 44.91Q121.9 45 121.63 45Q121.36 45 121.11 44.91Q120.86 44.82 120.67 44.64Q120.47 44.46 120.35 44.19Q120.23 43.93 120.23 43.57V28.87Q120.23 28.53 120.35 28.26Q120.47 28 120.67 27.82Q120.87 27.64 121.13 27.55Q121.39 27.46 121.67 27.46Q121.93 27.46 122.18 27.55Q122.44 27.64 122.64 27.82Q122.84 28 122.96 28.26Q123.08 28.53 123.08 28.87V37.69L127.9 33.29Q128.17 33.05 128.41 32.92Q128.65 32.78 128.92 32.78Q129.17 32.78 129.41 32.87Q129.64 32.96 129.82 33.12Q130 33.28 130.11 33.49Q130.22 33.7 130.22 33.93Q130.22 34.12 130.16 34.3Q130.09 34.48 129.92 34.62L125.87 38.1L130.48 43.14Q130.63 43.3 130.66 43.47Q130.7 43.65 130.7 43.8Q130.7 44.05 130.58 44.27Q130.47 44.49 130.27 44.65Q130.08 44.82 129.83 44.91Q129.58 45 129.32 45Q129.03 45 128.77 44.84Q128.51 44.68 128.27 44.4ZM135.76 34.99Q136.09 34.49 136.55 34.03Q137.01 33.56 137.57 33.25Q138.12 32.94 138.75 32.79Q139.38 32.63 140.04 32.63Q141.3 32.63 142.24 33.16Q143.19 33.68 143.82 34.58Q144.45 35.47 144.76 36.63Q145.07 37.8 145.07 38.97Q145.07 40.14 144.73 41.3Q144.4 42.46 143.75 43.32Q143.1 44.17 142.16 44.66Q141.21 45.15 139.98 45.15Q139.36 45.15 138.75 44.99Q138.14 44.84 137.59 44.54Q137.04 44.23 136.57 43.77Q136.1 43.32 135.76 42.86V48.32Q135.76 48.65 135.63 48.91Q135.51 49.16 135.31 49.33Q135.11 49.49 134.85 49.58Q134.6 49.66 134.33 49.66Q134.06 49.66 133.8 49.58Q133.55 49.49 133.34 49.33Q133.14 49.16 133.02 48.91Q132.9 48.65 132.9 48.32V34.14Q132.9 33.79 133.02 33.54Q133.14 33.29 133.34 33.12Q133.53 32.95 133.78 32.87Q134.03 32.78 134.3 32.78Q134.56 32.78 134.8 32.86Q135.05 32.94 135.25 33.09Q135.45 33.24 135.58 33.48Q135.72 33.71 135.76 34.01ZM135.77 38.93Q135.77 39.79 135.95 40.52Q136.12 41.25 136.51 41.86Q136.9 42.47 137.53 42.83Q138.16 43.19 139.06 43.19Q139.97 43.19 140.56 42.8Q141.15 Line truncated
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff. Show more