Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0022fd50cb | ||
|
|
1d1f0ebb1f | ||
|
|
da02e0bbda | ||
|
|
3f9e463dfa | ||
|
|
03737a5fc7 | ||
|
|
b453a8be10 | ||
|
|
a3c159a729 | ||
|
|
b3fb619bda | ||
|
|
78c8870e4e | ||
|
|
dd3cc83057 | ||
|
|
32272e8e40 | ||
|
|
9db3a98440 | ||
|
|
f87e67ce02 | ||
|
|
fe39e1efb6 | ||
|
|
6518d1b80f | ||
|
|
69a22deb1f | ||
|
|
f0287eec2f | ||
|
|
42e0a6bb93 | ||
|
|
76fab81386 | ||
|
|
1ce2e1e51f | ||
|
|
0154182f3b | ||
|
|
cb80835c92 | ||
|
|
e7efb073da | ||
|
|
433f9aee61 | ||
|
|
bb0949dcd9 | ||
|
|
2d54d39c24 | ||
|
|
cf50d341f5 | ||
|
|
8b644292a7 | ||
|
|
8ecc1ecdaa |
No files matched your search
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Berechtigter Nutzerkreis einer Lizenzoption: Einzellizenz (ein Trainer) oder Mehrfachlizenz (festgelegte Zahl von
|
||||
* Trainern). Das ist eine vertragliche Angabe der Lizenzoption. Sie ist unabhängig vom Lizenzinhaber (Person oder
|
||||
* Verein), vom technischen Downloadzugriff (nur das bestellende Konto) und vom Nutzungszweck (ehrenamtlich,
|
||||
* kommerziell, institutionell). Sie wird weder aus dem Zweck noch aus dem Preis abgeleitet.
|
||||
*/
|
||||
final class LicenceScope
|
||||
{
|
||||
public const SINGLE = 'einzel';
|
||||
|
||||
public const MULTI = 'mehrfach';
|
||||
|
||||
/** Obergrenze der Trainerzahl einer Mehrfachlizenz (Eingabeschutz). */
|
||||
public const MAX_TRAINERS = 999;
|
||||
|
||||
/**
|
||||
* @return array{0: ?string, 1: ?int} Nutzerkreis und Trainerzahl, geprüft und vereinheitlicht
|
||||
*/
|
||||
public static function normalise(?string $scope, mixed $trainers): array
|
||||
{
|
||||
$scope = filled($scope) ? (string) $scope : null;
|
||||
|
||||
if ($scope === null) {
|
||||
if (filled($trainers)) {
|
||||
throw new DomainRuleException('Die Trainerzahl gehört zu einer Einzel- oder Mehrfachlizenz. Wähle zuerst den Nutzerkreis.');
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
if ($scope === self::SINGLE) {
|
||||
if (filled($trainers) && (int) $trainers !== 1) {
|
||||
throw new DomainRuleException('Eine Einzellizenz gilt für genau einen Trainer.');
|
||||
}
|
||||
|
||||
return [self::SINGLE, 1];
|
||||
}
|
||||
|
||||
if ($scope === self::MULTI) {
|
||||
$count = filled($trainers) ? (int) $trainers : 0;
|
||||
|
||||
if ($count < 2 || $count > self::MAX_TRAINERS) {
|
||||
throw new DomainRuleException('Eine Mehrfachlizenz gilt für mindestens 2 und höchstens '.self::MAX_TRAINERS.' Trainer. Gib die Zahl der Trainer an.');
|
||||
}
|
||||
|
||||
return [self::MULTI, $count];
|
||||
}
|
||||
|
||||
throw new DomainRuleException('Der Nutzerkreis ist Einzellizenz oder Mehrfachlizenz.');
|
||||
}
|
||||
|
||||
/** Kurzform: „Einzellizenz · 1 Trainer“, „Mehrfachlizenz · bis zu 5 Trainer“ oder „keine Angabe“. */
|
||||
public static function label(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Einzellizenz · 1 Trainer',
|
||||
self::MULTI => 'Mehrfachlizenz · bis zu '.(int) $trainers.' Trainer',
|
||||
default => 'Nutzerkreis nicht festgelegt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Erklärung für Käufer: was der Umfang bedeutet und was er nicht bedeutet. */
|
||||
public static function explanation(?string $scope, ?int $trainers): ?string
|
||||
{
|
||||
return match ($scope) {
|
||||
self::SINGLE => 'Die Inhalte dürfen von einem Trainer eingesetzt werden.',
|
||||
self::MULTI => 'Die Inhalte dürfen von bis zu '.(int) $trainers.' Trainern eingesetzt werden. Zugriff und Download erhält zum Start nur das bestellende Konto.',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Wert für Vergleich identischer Lizenzen („Bereits erworben“). */
|
||||
public static function key(?string $scope, ?int $trainers): string
|
||||
{
|
||||
return ($scope ?? '-').'|'.($trainers ?? 0);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public static function options(): array
|
||||
{
|
||||
return [
|
||||
self::SINGLE => 'Einzellizenz (ein Trainer)',
|
||||
self::MULTI => 'Mehrfachlizenz (mehrere Trainer)',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
/**
|
||||
* Material-Tags des Brand-Kits (Film, Übung, PDF, Paket, Film + Übungen, Film + Merkblatt).
|
||||
*
|
||||
* Die Zuordnung hängt an Schlüsseln (Ausgabeklasse des Mediums, Kennung der redaktionellen Art), nie an Beschriftungen.
|
||||
* Was nicht eindeutig zuzuordnen ist, bekommt kein Tag und bleibt Text:
|
||||
* - „Paket“ und die beiden Kombinationen werden nicht automatisch vergeben (offen: Paket als Angebot oder als Programm;
|
||||
* Kombinationen aus dem Modulaufbau berechnen oder redaktionell wählen). Die Komponente kann sie darstellen.
|
||||
* - „Dokument“ ist nicht automatisch PDF; das Tag PDF gibt es nur für die Ausgabeklasse „pdf“.
|
||||
*/
|
||||
enum MaterialTag: string
|
||||
{
|
||||
case Film = 'film';
|
||||
case Uebung = 'uebung';
|
||||
case Pdf = 'pdf';
|
||||
case Paket = 'paket';
|
||||
case FilmUebungen = 'film-uebungen';
|
||||
case FilmMerkblatt = 'film-merkblatt';
|
||||
|
||||
private const FILM_KINDS = ['unterrichtsfilm', 'kurzfilm', 'trailer', 'interview'];
|
||||
|
||||
private const EXERCISE_KINDS = ['arbeitsblatt', 'uebungsbeschreibung'];
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'Film',
|
||||
self::Uebung => 'Übung',
|
||||
self::Pdf => 'PDF',
|
||||
self::Paket => 'Paket',
|
||||
self::FilmUebungen => 'Film + Übungen',
|
||||
self::FilmMerkblatt => 'Film + Merkblatt',
|
||||
};
|
||||
}
|
||||
|
||||
/** Name des Zeichens im Satz „glyphen“ (resources/svg/brand/glyphen). */
|
||||
public function glyph(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Film => 'film',
|
||||
self::Uebung => 'uebung',
|
||||
self::Pdf, self::FilmMerkblatt => 'dokument',
|
||||
self::Paket => 'paket',
|
||||
self::FilmUebungen => 'filmstreifen',
|
||||
};
|
||||
}
|
||||
|
||||
public static function fromContent(?string $outputClass, ?string $editorialKindSlug = null): ?self
|
||||
{
|
||||
return match (true) {
|
||||
$outputClass === 'film' => self::Film,
|
||||
$outputClass === 'pdf' => self::Pdf,
|
||||
in_array($editorialKindSlug, self::FILM_KINDS, true) => self::Film,
|
||||
in_array($editorialKindSlug, self::EXERCISE_KINDS, true) => self::Uebung,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,16 @@ class Offer extends Model
|
||||
'name',
|
||||
'composition_id',
|
||||
'option_label',
|
||||
'standalone_bundle',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'standalone_bundle' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/** Komposition, deren öffentliche Seite die Produktseite dieser Lizenzoption ist. */
|
||||
public function composition(): BelongsTo
|
||||
{
|
||||
|
||||
@@ -102,10 +102,18 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => false,
|
||||
'grant_kind' => 'kauf',
|
||||
'holder_kind' => 'person',
|
||||
'licence_scope' => null,
|
||||
'trainer_count' => null,
|
||||
], $attributes);
|
||||
|
||||
if ($offer->standalone_bundle && (count($lines) !== 1 || ! $lines[0]['target'] instanceof BundleVersion)) {
|
||||
throw new DomainRuleException('Ein Angebot mit eigener Paketseite besteht aus genau einer Paketfassung. Wähle eine Paketfassung oder ordne das Angebot der Seite eines Programms zu.');
|
||||
}
|
||||
|
||||
$this->assertAttributes($attributes);
|
||||
[$attributes['licence_scope'], $attributes['trainer_count']] = LicenceScope::normalise($attributes['licence_scope'], $attributes['trainer_count']);
|
||||
$scope = $this->scopeFor($lines);
|
||||
$this->assertSellableContent($scope);
|
||||
$this->assertCoverage($lines, $attributes);
|
||||
|
||||
return DB::transaction(function () use ($offer, $lines, $attributes, $scope): OfferVersion {
|
||||
@@ -126,6 +134,8 @@ public function activate(Offer $offer, array $lines, array $attributes = []): Of
|
||||
'dynamic' => $attributes['dynamic'],
|
||||
'grant_kind' => $attributes['grant_kind'],
|
||||
'holder_kind' => $attributes['holder_kind'],
|
||||
'licence_scope' => $attributes['licence_scope'],
|
||||
'trainer_count' => $attributes['trainer_count'],
|
||||
]);
|
||||
|
||||
foreach (array_values($lines) as $index => $line) {
|
||||
@@ -176,13 +186,18 @@ public function end(Offer $offer): OfferVersion
|
||||
* Produktzuordnung der Option: Die Komposition bestimmt die öffentliche Produktseite und die Alternativgruppe,
|
||||
* die Bezeichnung benennt die Option auf dieser Seite. Beides sind keine bindenden Konditionen.
|
||||
*/
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel): Offer
|
||||
public function assignProduct(Offer $offer, ?int $compositionId, ?string $optionLabel, bool $ownBundlePage = false): Offer
|
||||
{
|
||||
if ($compositionId !== null) {
|
||||
Composition::query()->findOrFail($compositionId);
|
||||
}
|
||||
|
||||
if ($ownBundlePage && $compositionId !== null) {
|
||||
throw new DomainRuleException('Ein Paket hat entweder eine eigene Paketseite oder die Seite eines Programms, nicht beides.');
|
||||
}
|
||||
|
||||
$offer->composition_id = $compositionId;
|
||||
$offer->standalone_bundle = $ownBundlePage;
|
||||
$offer->option_label = filled($optionLabel) ? trim((string) $optionLabel) : null;
|
||||
$offer->save();
|
||||
|
||||
@@ -219,6 +234,32 @@ private function assertAttributes(array $attributes): void
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Angebot ohne verkaufbaren Inhalt wird nicht aktiviert: Jeder Lizenzartikel des Umfangs braucht einen
|
||||
* veröffentlichten Stand, sonst erhielten Käufer nichts. Die Prüfung liegt im Domänenmodell, nicht nur in der
|
||||
* Maske, damit auch jeder andere Weg (Skript, Import) sie durchläuft.
|
||||
*
|
||||
* @param list<array{license_article_id: int, rights_profile_version_id: int}> $scope
|
||||
*/
|
||||
private function assertSellableContent(array $scope): void
|
||||
{
|
||||
$ids = array_values(array_unique(array_column($scope, 'license_article_id')));
|
||||
$missing = LicenseArticle::query()->with('currentRelease')->whereIn('id', $ids)->orderBy('code')->get()
|
||||
->filter(fn (LicenseArticle $article): bool => ! ($article->currentRelease instanceof ArticleRelease
|
||||
&& StatusValue::of($article->currentRelease->status) === ReleaseStatus::Veroeffentlicht->value));
|
||||
|
||||
if ($missing->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$names = $missing->map(fn (LicenseArticle $article): string => '„'.($article->working_title ?: $article->code).'“ ('.$article->code.')')->implode(', ');
|
||||
|
||||
throw new DomainRuleException(($missing->count() === 1 ? 'Der Lizenzartikel ' : 'Die Lizenzartikel ').$names
|
||||
.($missing->count() === 1 ? ' hat' : ' haben')
|
||||
.' noch keinen veröffentlichten Stand und vergibt'.($missing->count() === 1 ? '' : ' keine').' keine Inhalte. '
|
||||
.'Lege zuerst am Artikel den Inhalt fest, bevor das Angebot aktiviert wird.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{target: LicenseArticle|BundleVersion, rights: RightsProfileVersion}> $lines
|
||||
* @return list<array{license_article_id: int, rights_profile_version_id: int}>
|
||||
|
||||
@@ -19,6 +19,8 @@ class OfferVersion extends Model
|
||||
'dynamic',
|
||||
'grant_kind',
|
||||
'holder_kind',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'activated_at',
|
||||
];
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
* Redaktionsvorschau (Route editorial.card, nur für angemeldete Redaktion); öffentlich nie ausgegeben, weil es
|
||||
* keine Freigabe für die Website hat.
|
||||
* - missing: was für eine vollständige Karte fehlt, als Hinweis nur in der Redaktionsvorschau.
|
||||
* - tag: Schlüssel eines Material-Tags (App\Domain\Catalog\MaterialTag), nur wenn die Art eindeutig zuzuordnen ist;
|
||||
* sonst null, und die Karte zeigt die Art als Text wie bisher.
|
||||
* - texts: die zentralen Texte des Fachobjekts, aus denen die Karte einen wählen kann (teaser, summary, description).
|
||||
* summary bleibt der Text der Vorgabe („Automatisch“); texts wird nur gelesen, wenn die Redaktion einen wählt.
|
||||
*/
|
||||
@@ -39,6 +41,7 @@ public function __construct(
|
||||
public array $missing = [],
|
||||
public ?string $style = null,
|
||||
public array $texts = [],
|
||||
public ?string $tag = null,
|
||||
) {}
|
||||
|
||||
public function withText(?string $title, ?string $summary): self
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Domain\Catalog\ContentElement;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\MaterialTag;
|
||||
use App\Domain\Catalog\StructureNode;
|
||||
use App\Domain\Media\ThumbnailRef;
|
||||
use App\Domain\Media\WebsiteMedia;
|
||||
@@ -235,6 +236,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ?
|
||||
missing: $missing,
|
||||
style: $film ? 'media' : 'material',
|
||||
texts: $texts,
|
||||
tag: MaterialTag::fromContent((string) $shown->output_class, $element->editorialContentKind?->slug)?->value,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Commerce\Discount\DiscountService;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Models\User;
|
||||
@@ -20,6 +23,9 @@ class Cart
|
||||
{
|
||||
public const KEY = 'shop.cart';
|
||||
|
||||
/** Eingelöster Rabattcode (Kennung); höchstens einer je Bestellung. */
|
||||
public const DISCOUNT_KEY = 'shop.discount';
|
||||
|
||||
public const ADDED = 'added';
|
||||
|
||||
public const PRESENT = 'present';
|
||||
@@ -32,6 +38,7 @@ public function __construct(
|
||||
private readonly OwnershipCheck $ownership,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly OfferService $offers,
|
||||
private readonly DiscountService $discounts,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -57,7 +64,10 @@ public function has(Offer $offer): bool
|
||||
*/
|
||||
public function alternativeTo(Offer $offer): ?Offer
|
||||
{
|
||||
if ($offer->composition_id === null) {
|
||||
$products = app(ProductOptions::class);
|
||||
$group = $products->groupKey($offer);
|
||||
|
||||
if ($group === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -65,8 +75,8 @@ public function alternativeTo(Offer $offer): ?Offer
|
||||
|
||||
return $ids === [] ? null : Offer::query()
|
||||
->whereIn('id', $ids)
|
||||
->where('composition_id', $offer->composition_id)
|
||||
->first();
|
||||
->get()
|
||||
->first(fn (Offer $other): bool => $products->groupKey($other) === $group);
|
||||
}
|
||||
|
||||
public function add(Offer $offer): string
|
||||
@@ -133,13 +143,51 @@ public function acceptCurrent(Offer $offer): void
|
||||
|
||||
public function clear(): void
|
||||
{
|
||||
session()->forget(self::KEY);
|
||||
session()->forget([self::KEY, self::DISCOUNT_KEY]);
|
||||
}
|
||||
|
||||
/** Der im Warenkorb eingelöste Code, auch wenn er gerade nicht (mehr) gilt. */
|
||||
public function discountCode(): ?DiscountCode
|
||||
{
|
||||
$id = session()->get(self::DISCOUNT_KEY);
|
||||
|
||||
return is_numeric($id) ? DiscountCode::query()->with('targets')->find((int) $id) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Löst einen Code ein. Er wird nur vorgemerkt, wenn er für diesen Warenkorb und dieses Konto gilt; sonst bleibt
|
||||
* der bisherige Stand und das Ergebnis nennt den Grund. Ein zweiter Code ersetzt den ersten (höchstens ein Code).
|
||||
*/
|
||||
public function applyCode(string $input, ?User $user, ?int $holderPartyId = null): DiscountResult
|
||||
{
|
||||
$code = $this->discounts->find($input);
|
||||
|
||||
if ($code === null) {
|
||||
return new DiscountResult(null, DiscountResult::UNKNOWN, 'Diesen Code kennen wir nicht. Prüfe die Schreibweise.');
|
||||
}
|
||||
|
||||
$previous = session()->get(self::DISCOUNT_KEY);
|
||||
session()->put(self::DISCOUNT_KEY, $code->id);
|
||||
$result = $this->review($user, $holderPartyId)->discount;
|
||||
|
||||
if ($result === null || ! $result->applied()) {
|
||||
$previous === null ? session()->forget(self::DISCOUNT_KEY) : session()->put(self::DISCOUNT_KEY, $previous);
|
||||
|
||||
return $result ?? new DiscountResult($code, DiscountResult::NO_MATCH, 'Der Code kann auf diese Bestellung nicht angewendet werden.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function removeCode(): void
|
||||
{
|
||||
session()->forget(self::DISCOUNT_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
|
||||
*/
|
||||
public function review(?User $user = null, ?int $holderPartyId = null): CartReview
|
||||
public function review(?User $user = null, ?int $holderPartyId = null, bool $lockDiscount = false): CartReview
|
||||
{
|
||||
$offers = Offer::query()
|
||||
->whereIn('id', array_keys($this->items()))
|
||||
@@ -203,7 +251,15 @@ public function review(?User $user = null, ?int $holderPartyId = null): CartRevi
|
||||
}
|
||||
}
|
||||
|
||||
return new CartReview($lines, $holder);
|
||||
$code = $this->discountCode();
|
||||
$discount = null;
|
||||
|
||||
if ($code !== null) {
|
||||
$orderable = array_values(array_filter($lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
$discount = $this->discounts->evaluate($code, $user, $orderable, lock: $lockDiscount);
|
||||
}
|
||||
|
||||
return new CartReview($lines, $holder, $discount);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -45,6 +45,14 @@ public function blocks(): bool
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
if ($this->offer->standalone_bundle && $this->version !== null) {
|
||||
$bundle = app(ProductOptions::class)->bundleOf($this->version);
|
||||
|
||||
if ($bundle !== null) {
|
||||
return (string) $bundle->name;
|
||||
}
|
||||
}
|
||||
|
||||
$composition = $this->offer->composition;
|
||||
|
||||
return $composition !== null
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Commerce\Discount\DiscountResult;
|
||||
use App\Domain\Identity\Party;
|
||||
|
||||
/**
|
||||
@@ -16,6 +17,7 @@ final class CartReview
|
||||
public function __construct(
|
||||
public readonly array $lines,
|
||||
public readonly ?Party $holder,
|
||||
public readonly ?DiscountResult $discount = null,
|
||||
) {}
|
||||
|
||||
/** @return list<CartLine> */
|
||||
@@ -24,11 +26,35 @@ public function orderable(): array
|
||||
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
|
||||
}
|
||||
|
||||
public function totalCents(): int
|
||||
/** Summe der Listenpreise der Positionen, die in die Bestellung eingehen. */
|
||||
public function subtotalCents(): int
|
||||
{
|
||||
return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable()));
|
||||
}
|
||||
|
||||
public function discountCents(): int
|
||||
{
|
||||
return $this->discount?->totalCents() ?? 0;
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag: Listenpreise abzüglich Rabatt. */
|
||||
public function totalCents(): int
|
||||
{
|
||||
return $this->subtotalCents() - $this->discountCents();
|
||||
}
|
||||
|
||||
/** Rabatt einer Position in Cent. */
|
||||
public function discountFor(CartLine $line): int
|
||||
{
|
||||
return $this->discount?->forOffer($line->offer->id) ?? 0;
|
||||
}
|
||||
|
||||
/** Ein vorgemerkter Code, der jetzt nicht gilt, hält die Bestellung an, bis er entfernt wird. */
|
||||
public function discountBlocks(): bool
|
||||
{
|
||||
return $this->discount !== null && ! $this->discount->applied();
|
||||
}
|
||||
|
||||
public function blocked(): bool
|
||||
{
|
||||
foreach ($this->lines as $line) {
|
||||
@@ -47,7 +73,7 @@ public function empty(): bool
|
||||
|
||||
public function canOrder(): bool
|
||||
{
|
||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty();
|
||||
return $this->holder !== null && ! $this->blocked() && ! $this->empty() && ! $this->discountBlocks();
|
||||
}
|
||||
|
||||
public function digest(): string
|
||||
@@ -60,6 +86,6 @@ public function digest(): string
|
||||
|
||||
sort($parts);
|
||||
|
||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts));
|
||||
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts).'|'.($this->discount?->digestPart() ?? '-'));
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,18 @@
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
use App\Domain\Entitlement\Acquisition;
|
||||
use App\Domain\Entitlement\AcquisitionType;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\Party;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Mail\OrderConfirmed;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -23,6 +27,7 @@ public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -32,6 +37,12 @@ public function place(User $user, Offer $offer): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
// Dieser Einzelkauf kennt weder Zustimmungen noch „Zahlungspflichtig bestellen“. Im Livebetrieb gibt es nur den
|
||||
// Weg über die Kasse mit Pflichtangaben.
|
||||
if (Shop::live()) {
|
||||
throw new DomainRuleException('Bestelle über den Warenkorb und die Kasse.');
|
||||
}
|
||||
|
||||
$version = $this->offers->currentActiveVersion($offer);
|
||||
|
||||
if ($version->grant_kind !== 'kauf' || $version->holder_kind !== 'person') {
|
||||
@@ -44,7 +55,7 @@ public function place(User $user, Offer $offer): Order
|
||||
|
||||
$holder = $this->holders->resolve($user, null);
|
||||
|
||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]]));
|
||||
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,14 +64,25 @@ public function place(User $user, Offer $offer): Order
|
||||
* Bestellung und der Käufer sieht zuerst die aktualisierte Übersicht. Positionen, deren Umfang der Inhaber bereits
|
||||
* mit denselben Rechten besitzt, erzeugen keine Bestellposition.
|
||||
*/
|
||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest): Order
|
||||
public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, string $digest, ?array $consent = null, ?string $paymentMethod = null): Order
|
||||
{
|
||||
$this->assertActive($user);
|
||||
|
||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest): Order {
|
||||
// Optionen sperren, damit eine gleichzeitige Aktivierung die Prüfung nicht unterläuft.
|
||||
if ($consent === null && Shop::live()) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$order = DB::transaction(function () use ($user, $cart, $holderPartyId, $digest, $consent, $paymentMethod): Order {
|
||||
// Optionen und den Rabattcode sperren, damit eine gleichzeitige Aktivierung, Deaktivierung oder ein Entzug
|
||||
// der Freigabe die Prüfung nicht unterläuft.
|
||||
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
|
||||
$review = $cart->review($user, $holderPartyId);
|
||||
$discountId = session()->get(Cart::DISCOUNT_KEY);
|
||||
|
||||
if (is_numeric($discountId)) {
|
||||
DiscountCode::query()->whereKey((int) $discountId)->lockForUpdate()->first();
|
||||
}
|
||||
|
||||
$review = $cart->review($user, $holderPartyId, lockDiscount: true);
|
||||
|
||||
if ($review->holder === null) {
|
||||
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
|
||||
@@ -78,9 +100,19 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
|
||||
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
|
||||
}
|
||||
|
||||
if ($review->discountBlocks()) {
|
||||
throw new DomainRuleException(($review->discount?->message ?? 'Der Rabattcode gilt nicht.').' Entferne den Code, um ohne Rabatt zu bestellen.');
|
||||
}
|
||||
|
||||
$method = $paymentMethod ?? (Shop::driver() === 'stripe' ? 'stripe' : 'test');
|
||||
|
||||
if ($method === 'rechnung' && ! ($review->holder->type === PartyType::Organisation && Shop::invoice())) {
|
||||
throw new DomainRuleException('Der Kauf auf Rechnung ist nur für Vereine und Organisationen auf Anfrage möglich.');
|
||||
}
|
||||
|
||||
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
|
||||
|
||||
return $this->createOrder($user, $review->holder, $pairs);
|
||||
return $this->createOrder($user, $review->holder, $pairs, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
||||
});
|
||||
|
||||
$cart->clear();
|
||||
@@ -90,16 +122,28 @@ public function placeFromCart(User $user, Cart $cart, ?int $holderPartyId, strin
|
||||
|
||||
/**
|
||||
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
|
||||
* @param array<string, mixed>|null $terms Nachweis der Zustimmungen (SalesTerms::proof)
|
||||
*/
|
||||
private function createOrder(User $user, Party $holder, array $pairs): Order
|
||||
private function createOrder(User $user, Party $holder, array $pairs, ?CartReview $review, ?array $terms, string $method): Order
|
||||
{
|
||||
$subtotal = array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs));
|
||||
$discount = $review?->discount;
|
||||
$discountCents = $review?->discountCents() ?? 0;
|
||||
|
||||
$order = Order::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'party_id' => $holder->id,
|
||||
'status' => 'offen',
|
||||
'holder_kind' => $holder->type->value,
|
||||
'total_cents' => array_sum(array_map(fn (array $pair): int => (int) $pair[1]->price_cents, $pairs)),
|
||||
'subtotal_cents' => $subtotal,
|
||||
'discount_cents' => $discountCents,
|
||||
'total_cents' => $subtotal - $discountCents,
|
||||
'currency' => 'EUR',
|
||||
'discount_code_id' => $discountCents > 0 ? $discount?->code?->id : null,
|
||||
'discount_snapshot' => $discountCents > 0 ? $discount?->snapshot() : null,
|
||||
'payment_method' => $method,
|
||||
'terms_accepted_at' => $terms === null ? null : now(),
|
||||
'terms_snapshot' => $terms,
|
||||
]);
|
||||
|
||||
foreach ($pairs as [$offer, $version]) {
|
||||
@@ -114,6 +158,9 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
|
||||
'tax_class' => $version->tax_class,
|
||||
'grant_kind' => $version->grant_kind,
|
||||
'holder_party_id' => $holder->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0,
|
||||
]);
|
||||
$version->load('resolvedScopes.rights');
|
||||
|
||||
@@ -140,26 +187,49 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
|
||||
public function confirmTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return $this->settle($order, 'test', $reference);
|
||||
return $this->settle($order, 'test', $reference, null, now(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos.
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos. `$live` sagt, ob echtes Geld geflossen ist (Stripe meldet
|
||||
* es je Ereignis); ohne Angabe gilt der Betriebszustand des Shops. `$occurredAt` ist der Zeitpunkt der Zahlung
|
||||
* laut Anbieter, sonst jetzt.
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): Order
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency, ?bool $live = null, ?CarbonInterface $occurredAt = null, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents'));
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference);
|
||||
return $this->settle($order, $provider, $reference, null, $occurredAt ?? now(), $live ?? Shop::live(), $paymentIntent);
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference): Order
|
||||
/**
|
||||
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
|
||||
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
|
||||
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten. `$receivedOn` ist der Tag, an dem das Geld auf
|
||||
* dem Konto einging (nicht in der Zukunft, nicht vor der Bestellung); ohne Angabe gilt heute. Er bestimmt, in
|
||||
* welchen Zeitraum die Einnahme fällt.
|
||||
*/
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
if ($order->payment_method !== 'rechnung') {
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
$day = PaymentJournal::dayOf($receivedOn ?? now(PaymentJournal::TIMEZONE), $order->created_at);
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor, $day, Shop::live());
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
@@ -168,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, $occurredAt, $live, $paymentIntent, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -180,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
||||
}
|
||||
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$order->payments()->updateOrCreate(
|
||||
$payment = $order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
['provider' => $provider, 'status' => 'bestaetigt'],
|
||||
array_filter(
|
||||
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id, 'provider_payment_ref' => $paymentIntent],
|
||||
fn (mixed $value): bool => $value !== null,
|
||||
),
|
||||
);
|
||||
$this->journal->recordPayment($order, $payment, $occurredAt, $confirmedBy, $live);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
@@ -207,6 +281,7 @@ private function settle(Order $order, string $provider, string $reference): Orde
|
||||
public function failTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
$this->assertTestOrder($order);
|
||||
|
||||
return DB::transaction(function () use ($order, $reference): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
@@ -229,9 +304,14 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
|
||||
/**
|
||||
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt.
|
||||
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
||||
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
||||
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
||||
* Jede Erstattung wird im Zahlungsjournal gegengebucht, in derselben Transaktion: Bei Stripe mit Rückzahlungs-ID
|
||||
* und Zeitpunkt von Stripe, sonst (Überweisung, Testzahlung) mit `$refundedOn` (Tag der Rückzahlung, ohne Angabe
|
||||
* jetzt) und `$reference` (Überweisungsreferenz o. ä., sonst eine feste Kennung der Bestellung).
|
||||
*/
|
||||
public function refund(Order $order, string $reason): Order
|
||||
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null, ?User $actor = null, string|CarbonInterface|null $refundedOn = null, ?string $reference = null): Order
|
||||
{
|
||||
$reason = trim($reason);
|
||||
|
||||
@@ -239,7 +319,17 @@ public function refund(Order $order, string $reason): Order
|
||||
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason): Order {
|
||||
$current = Order::query()->findOrFail($order->id);
|
||||
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$manualAt = $refundedOn === null ? now() : PaymentJournal::dayOf($refundedOn, $current->created_at);
|
||||
$booking = null;
|
||||
|
||||
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
||||
$result = ($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$booking = ['reference' => $result['id'], 'status' => $result['status'], 'at' => $result['created'] ?? now()];
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
@@ -262,6 +352,16 @@ public function refund(Order $order, string $reason): Order
|
||||
}
|
||||
}
|
||||
|
||||
$payment = $order->payments()->where('status', 'bestaetigt')->latest('id')->first();
|
||||
$this->journal->recordRefund(
|
||||
$order,
|
||||
$payment,
|
||||
$booking['at'] ?? $manualAt,
|
||||
$actor,
|
||||
$reason,
|
||||
$booking['reference'] ?? (filled($reference) ? 'erstattung-'.trim((string) $reference) : 'erstattung-bestellung-'.$order->id),
|
||||
$booking['status'] ?? null,
|
||||
);
|
||||
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
||||
$order->status = 'erstattet';
|
||||
$order->save();
|
||||
@@ -270,6 +370,28 @@ public function refund(Order $order, string $reason): Order
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Mitglied erklärt den Widerruf (Verkaufsstart: kein Selbstbedienungs-Widerruf). Es entzieht nichts und
|
||||
* erstattet nichts; der Betreiber prüft den Fall (Erlöschen des Widerrufsrechts bei sofortiger Bereitstellung mit
|
||||
* ausdrücklicher Zustimmung) und erstattet bei Bedarf in der Bestellverwaltung.
|
||||
*/
|
||||
public function requestWithdrawal(Order $order, string $note): Order
|
||||
{
|
||||
if (! in_array($order->status, ['bezahlt', 'offen'], true)) {
|
||||
throw new DomainRuleException('Für diese Bestellung kann kein Widerruf erklärt werden.');
|
||||
}
|
||||
|
||||
if ($order->withdrawal_requested_at !== null) {
|
||||
return $order;
|
||||
}
|
||||
|
||||
$order->withdrawal_requested_at = now();
|
||||
$order->withdrawal_note = trim($note) !== '' ? trim($note) : null;
|
||||
$order->save();
|
||||
|
||||
return $order;
|
||||
}
|
||||
|
||||
private function assertActive(User $user): void
|
||||
{
|
||||
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
|
||||
@@ -277,6 +399,14 @@ private function assertActive(User $user): void
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Bestellung auf Rechnung oder über Stripe wird nie mit der Testzahlung bestätigt. */
|
||||
private function assertTestOrder(Order $order): void
|
||||
{
|
||||
if (in_array(Order::query()->whereKey($order->id)->value('payment_method'), ['rechnung', 'stripe'], true)) {
|
||||
throw new DomainRuleException('Diese Bestellung wird nicht mit der Testzahlung bezahlt.');
|
||||
}
|
||||
}
|
||||
|
||||
private function assertTestDriver(): void
|
||||
{
|
||||
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,39 @@ class Order extends Model
|
||||
'holder_kind',
|
||||
'total_cents',
|
||||
'currency',
|
||||
'subtotal_cents',
|
||||
'discount_cents',
|
||||
'discount_code_id',
|
||||
'discount_snapshot',
|
||||
'payment_method',
|
||||
'terms_accepted_at',
|
||||
'terms_snapshot',
|
||||
'withdrawal_requested_at',
|
||||
'withdrawal_note',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'discount_snapshot' => 'array',
|
||||
'terms_snapshot' => 'array',
|
||||
'terms_accepted_at' => 'datetime',
|
||||
'withdrawal_requested_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/** Listenpreise vor Rabatt; bei älteren Bestellungen die Summe der Positionen. */
|
||||
public function subtotal(): int
|
||||
{
|
||||
return (int) ($this->subtotal_cents ?? $this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
/** Endgültiger Zahlbetrag. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) ($this->total_cents ?? $this->lines->sum('price_cents'));
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
|
||||
@@ -22,8 +22,17 @@ class OrderLine extends Model
|
||||
'tax_class',
|
||||
'grant_kind',
|
||||
'holder_party_id',
|
||||
'licence_scope',
|
||||
'trainer_count',
|
||||
'discount_cents',
|
||||
];
|
||||
|
||||
/** Preis dieser Position nach Rabatt. */
|
||||
public function payable(): int
|
||||
{
|
||||
return (int) $this->price_cents - (int) $this->discount_cents;
|
||||
}
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\OfferVersion;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Entitlement\GrantStatus;
|
||||
@@ -27,12 +28,23 @@ public function covers(Party $holder, OfferVersion $version): bool
|
||||
$byAcquisition = Grant::query()
|
||||
->where('status', GrantStatus::Aktiv)
|
||||
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
|
||||
->with('acquisition')
|
||||
->get()
|
||||
->filter(fn (Grant $grant): bool => ($grant->valid_from === null || ! $grant->valid_from->greaterThan($now))
|
||||
&& ($grant->valid_until === null || $grant->valid_until->greaterThan($now)))
|
||||
->groupBy('acquisition_id');
|
||||
|
||||
$wanted = LicenceScope::key($version->licence_scope, $version->trainer_count);
|
||||
|
||||
foreach ($byAcquisition as $grants) {
|
||||
$conditions = (array) ($grants->first()->acquisition?->conditions ?? []);
|
||||
|
||||
// Gleicher Umfang heißt auch gleicher Nutzerkreis: Eine Einzellizenz deckt keine Mehrfachlizenz ab und
|
||||
// umgekehrt (der Nutzerkreis wird nicht aus Zweck oder Preis abgeleitet).
|
||||
if (LicenceScope::key($conditions['licence_scope'] ?? null, isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null) !== $wanted) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$have = [];
|
||||
|
||||
foreach ($grants as $grant) {
|
||||
|
||||
@@ -12,6 +12,9 @@ class Payment extends Model
|
||||
'provider',
|
||||
'status',
|
||||
'provider_reference',
|
||||
'provider_payment_ref',
|
||||
'amount_cents',
|
||||
'confirmed_by',
|
||||
];
|
||||
|
||||
public function order(): BelongsTo
|
||||
|
||||
@@ -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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\EditorialProfileReader;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -37,6 +39,125 @@ public function forComposition(Composition $composition): array
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kaufbare Optionen der eigenen Produktseite eines Pakets: Angebote mit eigener Paketseite, deren aktive Fassung
|
||||
* dieses Paket verkauft.
|
||||
*
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function forBundle(Bundle $bundle): array
|
||||
{
|
||||
$options = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
|
||||
if ($version !== null && $this->bundleOf($version)?->id === $bundle->id) {
|
||||
$options[] = $this->describe($offer, $version);
|
||||
}
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das Paket, das die Fassung unmittelbar verkauft (erste Paketposition), sonst null.
|
||||
*/
|
||||
public function bundleOf(OfferVersion $version): ?Bundle
|
||||
{
|
||||
$version->loadMissing('lines.bundleVersion.bundle');
|
||||
|
||||
return $version->lines->first(fn ($line): bool => $line->bundleVersion !== null)?->bundleVersion?->bundle;
|
||||
}
|
||||
|
||||
/** Gruppenschlüssel der Alternativen: Produktseite eines Programms oder eigene Paketseite. */
|
||||
public function groupKey(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return 'c:'.$offer->composition_id;
|
||||
}
|
||||
|
||||
if ($offer->standalone_bundle) {
|
||||
$version = $this->offers->purchasableVersion($offer) ?? $offer->versions()->orderByDesc('number')->first();
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
return $bundle === null ? null : 'b:'.$bundle->id;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Adresse der Produktseite, auf der die Option angeboten wird, sonst null. */
|
||||
public function pageUrl(Offer $offer): ?string
|
||||
{
|
||||
if ($offer->composition_id !== null) {
|
||||
return route('public.program', $offer->composition_id);
|
||||
}
|
||||
|
||||
$key = $this->groupKey($offer);
|
||||
|
||||
return $key !== null && str_starts_with($key, 'b:') ? route('public.package', (int) substr($key, 2)) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pakete mit eigener Produktseite und kaufbarer Option: Paketkennung => günstigster Preis und Zahl der Optionen.
|
||||
*
|
||||
* @return array<int, array{from_cents: int, count: int}>
|
||||
*/
|
||||
public function bundleSummaries(): array
|
||||
{
|
||||
$summary = [];
|
||||
|
||||
foreach (Offer::query()->where('standalone_bundle', true)->orderBy('id')->get() as $offer) {
|
||||
$version = $this->offers->purchasableVersion($offer);
|
||||
$bundle = $version === null ? null : $this->bundleOf($version);
|
||||
|
||||
if ($bundle === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$current = $summary[$bundle->id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
|
||||
$summary[$bundle->id] = [
|
||||
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
|
||||
'count' => $current['count'] + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Der tatsächliche Umfang einer Paketseite: die Artikel aller Optionen ohne Doppelte, in der Reihenfolge der
|
||||
* Optionen, mit Name und Kurzbeschreibung aus der Redaktion.
|
||||
*
|
||||
* @param list<array<string, mixed>> $options
|
||||
* @return list<array{title: string, teaser: string}>
|
||||
*/
|
||||
public function bundleContents(array $options): array
|
||||
{
|
||||
$contents = [];
|
||||
|
||||
foreach ($options as $option) {
|
||||
$option['version']->loadMissing('resolvedScopes.article');
|
||||
|
||||
foreach ($option['version']->resolvedScopes as $item) {
|
||||
$article = $item->article;
|
||||
|
||||
if ($article === null || isset($contents[$article->id])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$profile = app(EditorialProfileReader::class)->read($article, 'detail');
|
||||
$contents[$article->id] = [
|
||||
'title' => $this->articleTitle($article),
|
||||
'teaser' => trim((string) ($profile->value('teaser') ?? '')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($contents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
|
||||
*
|
||||
@@ -89,6 +210,10 @@ public function describe(Offer $offer, OfferVersion $version): array
|
||||
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'term' => self::termLabel($version),
|
||||
'licence' => LicenceScope::label($version->licence_scope, $version->trainer_count),
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
'licence_note' => LicenceScope::explanation($version->licence_scope, $version->trainer_count),
|
||||
'scope' => $scope,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Cms\Page;
|
||||
|
||||
/**
|
||||
* Pflichtangaben und Zustimmungen im Bestellablauf (Verkaufsstart Deutschland, PAY-005, PAY-009).
|
||||
*
|
||||
* Die finalen Rechtstexte (AGB, Lizenzbedingungen, Widerrufsbelehrung, Impressum, Datenschutz) liegen als Seiten im
|
||||
* CMS und werden hier nur verlinkt. Der Wortlaut der Zustimmungen unten ist ein ENTWURF zur Prüfung durch die
|
||||
* Rechtsberatung. Er ist nicht rechtlich freigegeben; `VERSION` hält fest, welcher Wortlaut galt, damit die Zustimmung
|
||||
* je Bestellung nachvollziehbar bleibt.
|
||||
*/
|
||||
final class SalesTerms
|
||||
{
|
||||
public const VERSION = '2026-11-24-entwurf';
|
||||
|
||||
/** Schaltfläche zum verbindlichen Abschluss (Button-Lösung, § 312j Abs. 3 BGB). */
|
||||
public const ORDER_BUTTON = 'Zahlungspflichtig bestellen';
|
||||
|
||||
public const ORDER_BUTTON_INVOICE = 'Zahlungspflichtig auf Rechnung bestellen';
|
||||
|
||||
/**
|
||||
* Seiten der Rechtstexte: Schlüssel => Bezeichnung und mögliche Pfade im CMS (erste veröffentlichte Seite gilt).
|
||||
*
|
||||
* @return array<string, array{label: string, paths: list<string>, required: bool}>
|
||||
*/
|
||||
public static function pages(): array
|
||||
{
|
||||
return [
|
||||
'agb' => ['label' => 'Allgemeine Geschäftsbedingungen', 'paths' => ['/agb'], 'required' => true],
|
||||
'lizenz' => ['label' => 'Lizenzbedingungen', 'paths' => ['/lizenzbedingungen', '/lizenz'], 'required' => true],
|
||||
'widerruf' => ['label' => 'Widerrufsbelehrung', 'paths' => ['/widerruf', '/widerrufsbelehrung'], 'required' => true],
|
||||
'impressum' => ['label' => 'Impressum', 'paths' => ['/impressum'], 'required' => true],
|
||||
'datenschutz' => ['label' => 'Datenschutzerklärung', 'paths' => ['/datenschutz'], 'required' => true],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Seite des Rechtstextes oder null.
|
||||
*/
|
||||
public static function page(string $key): ?Page
|
||||
{
|
||||
$definition = self::pages()[$key] ?? null;
|
||||
|
||||
if ($definition === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Page::query()
|
||||
->whereIn('path', $definition['paths'])
|
||||
->whereNotNull('published_revision_id')
|
||||
->orderBy('id')
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function url(string $key): ?string
|
||||
{
|
||||
return self::page($key)?->publicUrl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fehlende oder unveröffentlichte Rechtstexte (Schlüssel => Bezeichnung).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function missingPages(): array
|
||||
{
|
||||
$missing = [];
|
||||
|
||||
foreach (self::pages() as $key => $definition) {
|
||||
if ($definition['required'] && self::page($key) === null) {
|
||||
$missing[$key] = $definition['label'];
|
||||
}
|
||||
}
|
||||
|
||||
return $missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zustimmungen im Checkout: Schlüssel => Wortlaut (ENTWURF).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function consents(): array
|
||||
{
|
||||
return [
|
||||
'agb' => 'Ich habe die Allgemeinen Geschäftsbedingungen und die Lizenzbedingungen gelesen und stimme ihnen zu.',
|
||||
'sofort' => 'Ich verlange ausdrücklich, dass mit der Ausführung des Vertrags vor Ablauf der Widerrufsfrist begonnen wird und die digitalen Inhalte sofort nach Zahlungseingang bereitgestellt werden. Mir ist bekannt, dass ich mein Widerrufsrecht verliere, sobald die Ausführung begonnen hat.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft die Zustimmungen und liefert den Nachweis für die Bestellung (Wortlaut, Fassung, Seiten, Zeit).
|
||||
*
|
||||
* @param array<string, mixed> $accepted Schlüssel => angekreuzt
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function proof(array $accepted): array
|
||||
{
|
||||
$texts = [];
|
||||
|
||||
foreach (self::consents() as $key => $wording) {
|
||||
if (empty($accepted[$key])) {
|
||||
throw new DomainRuleException('Bitte bestätige die Zustimmungen vor dem verbindlichen Abschluss.');
|
||||
}
|
||||
|
||||
$texts[$key] = $wording;
|
||||
}
|
||||
|
||||
$pages = [];
|
||||
|
||||
foreach (array_keys(self::pages()) as $key) {
|
||||
$page = self::page($key);
|
||||
$pages[$key] = $page === null ? null : ['path' => $page->path, 'revision_id' => $page->published_revision_id];
|
||||
}
|
||||
|
||||
return [
|
||||
'version' => self::VERSION,
|
||||
'consents' => $texts,
|
||||
'pages' => $pages,
|
||||
'recorded_at' => now()->toIso8601String(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,12 @@
|
||||
namespace App\Domain\Commerce;
|
||||
|
||||
/**
|
||||
* Etappe 1 verwendet ausschließlich Testzahlung und erteilt keine Produktivfreigabe. Der Shop (Warenkorb, Kasse,
|
||||
* Kopflink) ist deshalb nur aktiv, wenn die Umgebung nicht Produktion ist und der Zahlungstreiber „test“ gilt.
|
||||
* Dieselbe Bedingung gilt für die Testzahlung der Bestellseite.
|
||||
* Wann der Shop (Warenkorb, Kasse, Kopflink) aktiv ist.
|
||||
*
|
||||
* Test und Sandbox: nicht in Produktion, Zahlungstreiber „test“ oder „stripe“ (Testschlüssel).
|
||||
* Produktion: nur mit der ausdrücklichen Produktivfreigabe (`SHOP_LIVE_RELEASE`, Entscheidung von Lars), dem
|
||||
* Zahlungstreiber „stripe“ mit Live-Schlüssel und veröffentlichten Rechtstexten. Fehlt eines davon, bleibt der Shop in
|
||||
* Produktion abgeschaltet. Die Freigabe ist standardmäßig aus.
|
||||
*/
|
||||
final class Shop
|
||||
{
|
||||
@@ -14,14 +17,45 @@ public static function driver(): string
|
||||
return (string) config('services.payment.driver');
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
/** Produktivbetrieb ist freigegeben und vollständig vorbereitet (Freigabe, Live-Schlüssel, Rechtstexte). */
|
||||
public static function live(): bool
|
||||
{
|
||||
return ! app()->isProduction() && in_array(self::driver(), ['test', 'stripe'], true);
|
||||
return app()->isProduction()
|
||||
&& config('shop.live_release') === true
|
||||
&& self::driver() === 'stripe'
|
||||
&& self::liveKey()
|
||||
&& SalesTerms::missingPages() === [];
|
||||
}
|
||||
|
||||
/** Stripe-Kasse (Etappe 1: nur Testmodus, nie in Produktion). */
|
||||
public static function enabled(): bool
|
||||
{
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return in_array(self::driver(), ['test', 'stripe'], true);
|
||||
}
|
||||
|
||||
/** Stripe-Kasse: im Test nur mit Testschlüsseln, in Produktion nur nach der Produktivfreigabe. */
|
||||
public static function stripe(): bool
|
||||
{
|
||||
return ! app()->isProduction() && self::driver() === 'stripe';
|
||||
if (app()->isProduction()) {
|
||||
return self::live();
|
||||
}
|
||||
|
||||
return self::driver() === 'stripe';
|
||||
}
|
||||
|
||||
/** Kauf auf Rechnung für Organisationen (manuelle Rechnung, Zahlungseingang durch den Betreiber). */
|
||||
public static function invoice(): bool
|
||||
{
|
||||
return self::enabled() && (bool) config('shop.invoice', true);
|
||||
}
|
||||
|
||||
private static function liveKey(): bool
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
return str_starts_with($secret, 'sk_live_') || str_starts_with($secret, 'rk_live_');
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
@@ -11,9 +15,11 @@
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Stripe-Kasse (Checkout Session) für die Testzahlung in Etappe 1. Ausschließlich Testschlüssel: Ein Live-Schlüssel
|
||||
* oder die Produktionsumgebung werden abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten
|
||||
* berühren diese Anwendung nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook).
|
||||
* Stripe-Kasse (Checkout Session). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
||||
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
||||
* Fall wird abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten berühren diese Anwendung
|
||||
* nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook). Der Betrag je Position ist der
|
||||
* Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht.
|
||||
*/
|
||||
class StripeGateway
|
||||
{
|
||||
@@ -24,7 +30,7 @@ class StripeGateway
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertSandbox();
|
||||
$this->assertAllowed();
|
||||
$order->loadMissing('lines', 'user');
|
||||
$taxRate = $this->taxRate();
|
||||
|
||||
@@ -32,6 +38,10 @@ public function checkoutFor(Order $order): array
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
if ($order->payment_method === 'rechnung') {
|
||||
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
|
||||
}
|
||||
|
||||
$open = $this->reusableSession($order);
|
||||
|
||||
if ($open !== null) {
|
||||
@@ -51,12 +61,18 @@ public function checkoutFor(Order $order): array
|
||||
];
|
||||
|
||||
foreach ($order->lines->values() as $index => $line) {
|
||||
$productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'];
|
||||
|
||||
if ((int) $line->discount_cents > 0) {
|
||||
$productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents);
|
||||
}
|
||||
|
||||
$params['line_items'][$index] = [
|
||||
'quantity' => 1,
|
||||
'price_data' => [
|
||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||
'unit_amount' => (int) $line->price_cents,
|
||||
'product_data' => ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'],
|
||||
'unit_amount' => $line->payable(),
|
||||
'product_data' => $productData,
|
||||
],
|
||||
];
|
||||
|
||||
@@ -82,21 +98,79 @@ public function checkoutFor(Order $order): array
|
||||
return ['id' => $id, 'url' => $url];
|
||||
}
|
||||
|
||||
public function assertSandbox(): void
|
||||
public function assertAllowed(): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
if (app()->isProduction()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Etappe 1 erlaubt nur den Stripe-Testmodus (Schlüssel sk_test_).');
|
||||
if (app()->isProduction()) {
|
||||
if (! Shop::live()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
|
||||
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
|
||||
* entzogen (Aufrufer: Checkout::refund). Geliefert werden Rückzahlungs-ID, Status (Stripe meldet unter Umständen
|
||||
* „pending“; er wird so festgehalten) und Zeitpunkt für das Zahlungsjournal.
|
||||
*
|
||||
* @return array{id: string, status: string, created: ?CarbonImmutable}
|
||||
*/
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
|
||||
if ($intent === '') {
|
||||
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
$this->assertOk($session, 'abgefragt');
|
||||
$intent = (string) $session->json('payment_intent');
|
||||
}
|
||||
|
||||
if ($intent === '') {
|
||||
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
|
||||
->post('/v1/refunds', [
|
||||
'payment_intent' => $intent,
|
||||
'amount' => $order->payable(),
|
||||
'reason' => 'requested_by_customer',
|
||||
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
|
||||
]);
|
||||
|
||||
$this->assertOk($response, 'erstattet');
|
||||
$id = (string) $response->json('id');
|
||||
$status = (string) $response->json('status');
|
||||
|
||||
if ($id === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Rückzahlung bestätigt. Prüfe den Fall im Stripe-Dashboard, bevor du es erneut versuchst.');
|
||||
}
|
||||
|
||||
if (in_array($status, ['failed', 'canceled'], true)) {
|
||||
throw new DomainRuleException('Stripe hat die Rückzahlung nicht ausgeführt (Status '.$status.'). Es wurde nichts verändert.');
|
||||
}
|
||||
|
||||
$payment->provider_payment_ref = $intent;
|
||||
$payment->save();
|
||||
|
||||
return [
|
||||
'id' => $id,
|
||||
'status' => $status !== '' ? $status : 'unbekannt',
|
||||
'created' => is_numeric($response->json('created')) ? CarbonImmutable::createFromTimestampUTC((int) $response->json('created')) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -101,6 +101,10 @@ public function issueFromOrderLine(OrderLine $line, Party $holder, User $actor):
|
||||
'update_promise' => $line->update_promise,
|
||||
'holder_kind' => $line->holder_kind,
|
||||
'offer_version_id' => $line->offer_version_id,
|
||||
'licence_scope' => $line->licence_scope,
|
||||
'trainer_count' => $line->trainer_count,
|
||||
'price_cents' => (int) $line->price_cents,
|
||||
'discount_cents' => (int) $line->discount_cents,
|
||||
],
|
||||
]);
|
||||
|
||||
@@ -150,6 +154,8 @@ public function issue(
|
||||
'update_promise' => $version->update_promise,
|
||||
'holder_kind' => $version->holder_kind,
|
||||
'offer_version_id' => $version->id,
|
||||
'licence_scope' => $version->licence_scope,
|
||||
'trainer_count' => $version->trainer_count,
|
||||
],
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Identity;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Rechnungsadresse eines Lizenzinhabers (Person oder Organisation). Eine je Inhaber. Sie wird nur gepflegt;
|
||||
* eine Bestellung kopiert sie erst, wenn die Rechnungsstellung sie braucht.
|
||||
*/
|
||||
class BillingAddress extends Model
|
||||
{
|
||||
/** Auswählbare Länder (ISO 3166-1 Alpha-2). */
|
||||
public const COUNTRIES = [
|
||||
'DE' => 'Deutschland',
|
||||
'AT' => 'Österreich',
|
||||
'CH' => 'Schweiz',
|
||||
'LI' => 'Liechtenstein',
|
||||
'LU' => 'Luxemburg',
|
||||
'BE' => 'Belgien',
|
||||
'NL' => 'Niederlande',
|
||||
'FR' => 'Frankreich',
|
||||
'IT' => 'Italien',
|
||||
'DK' => 'Dänemark',
|
||||
'PL' => 'Polen',
|
||||
'CZ' => 'Tschechien',
|
||||
];
|
||||
|
||||
protected $fillable = [
|
||||
'party_id',
|
||||
'recipient',
|
||||
'line2',
|
||||
'street',
|
||||
'postal_code',
|
||||
'city',
|
||||
'country',
|
||||
];
|
||||
|
||||
public function party(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Party::class);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ public function user(): HasOne
|
||||
return $this->hasOne(User::class);
|
||||
}
|
||||
|
||||
public function billingAddress(): HasOne
|
||||
{
|
||||
return $this->hasOne(BillingAddress::class);
|
||||
}
|
||||
|
||||
public function profile(): HasOne
|
||||
{
|
||||
return $this->hasOne(Profile::class);
|
||||
|
||||
@@ -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],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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\CompositionVersion;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -17,11 +18,13 @@
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use App\Filament\Pages\Zahlungsjournal;
|
||||
use App\Filament\Resources\Offers\OfferResource;
|
||||
use App\Filament\Support\CatalogLabels;
|
||||
use App\Filament\Support\CatalogOptions;
|
||||
use App\Filament\Support\PublicationReadiness;
|
||||
use App\Filament\Support\ReportsDomainRules;
|
||||
use App\Filament\Support\ShopAccess;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
@@ -45,6 +48,9 @@ class ViewOffer extends ViewRecord
|
||||
|
||||
protected static string $resource = OfferResource::class;
|
||||
|
||||
/** Wert der Auswahl „Produktseite“ für ein Paket mit eigener Seite. */
|
||||
private const OWN_BUNDLE_PAGE = '__paket';
|
||||
|
||||
public function getTitle(): string|Htmlable
|
||||
{
|
||||
return (string) $this->getRecord()->name;
|
||||
@@ -120,6 +126,16 @@ public function activateAction(): Action
|
||||
'organisation' => 'Organisationen und Vereine',
|
||||
])->required()
|
||||
->helperText('Wähle die Eignung passend zu den Rechten: Organisationslizenzen brauchen institutionelle Rechte. Das System erzwingt diese Kopplung nicht.'),
|
||||
Select::make('licence_scope')->label('Nutzerkreis')
|
||||
->options(LicenceScope::options())
|
||||
->required()
|
||||
->live()
|
||||
->helperText('Wie viele Trainer die Inhalte einsetzen dürfen. Das ist unabhängig vom Lizenzinhaber (Person oder Verein), vom Nutzungszweck der Rechte und vom Preis; es wird aus keinem davon abgeleitet. Der Download bleibt zum Start beim bestellenden Konto. Der Wert wird mit der Bestellung festgehalten.'),
|
||||
TextInput::make('trainer_count')->label('Anzahl Trainer')
|
||||
->numeric()->minValue(2)->maxValue(LicenceScope::MAX_TRAINERS)->integer()
|
||||
->required(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||
->visible(fn (Get $get): bool => $get('licence_scope') === LicenceScope::MULTI)
|
||||
->helperText('Höchstzahl der Trainer, die die Inhalte einsetzen dürfen, mindestens 2. Eine Einzellizenz gilt immer für genau einen Trainer.'),
|
||||
Select::make('grant_kind')->label('Vergabe')->options([
|
||||
'kauf' => 'Kauf',
|
||||
'auf_abruf' => 'Auf Abruf',
|
||||
@@ -201,13 +217,16 @@ public function activateAction(): Action
|
||||
$version = DB::transaction(function () use ($service, $offer, $data, $lines, $kept, $price) {
|
||||
$service->assignProduct(
|
||||
$offer,
|
||||
filled($data['composition_id'] ?? null) ? (int) $data['composition_id'] : null,
|
||||
filled($data['composition_id'] ?? null) && $data['composition_id'] !== self::OWN_BUNDLE_PAGE ? (int) $data['composition_id'] : null,
|
||||
$data['option_label'] ?? null,
|
||||
($data['composition_id'] ?? null) === self::OWN_BUNDLE_PAGE,
|
||||
);
|
||||
|
||||
return $service->activate($offer, $lines, [
|
||||
...$kept,
|
||||
'holder_kind' => $data['holder_kind'],
|
||||
'licence_scope' => $data['licence_scope'] ?? null,
|
||||
'trainer_count' => $data['trainer_count'] ?? null,
|
||||
'grant_kind' => $data['grant_kind'],
|
||||
'price_cents' => $price,
|
||||
'composition_version_id' => filled($data['composition_version_id'] ?? null) ? (int) $data['composition_version_id'] : null,
|
||||
@@ -267,7 +286,7 @@ private function productPages(): array
|
||||
{
|
||||
$catalog = app(PublicCatalogReader::class);
|
||||
|
||||
return Composition::query()
|
||||
return [self::OWN_BUNDLE_PAGE => 'Eigene Paketseite · zeigt den Umfang des Pakets (nur für ein Angebot aus genau einer Paketfassung)'] + Composition::query()
|
||||
->with('editorialContentKind')
|
||||
->whereNull('archived_at')
|
||||
->orderBy('designation')
|
||||
@@ -291,15 +310,17 @@ private function formFromActive(): array
|
||||
$active = $this->activeVersion();
|
||||
/** @var Offer $offer */
|
||||
$offer = $this->getRecord();
|
||||
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->composition_id];
|
||||
$option = ['option_label' => $offer->option_label, 'composition_id' => $offer->standalone_bundle ? self::OWN_BUNDLE_PAGE : $offer->composition_id];
|
||||
|
||||
if ($active === null) {
|
||||
return [...$option, 'holder_kind' => 'person', 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
||||
return [...$option, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'grant_kind' => 'kauf', 'lines' => [['kind' => 'article']]];
|
||||
}
|
||||
|
||||
return [
|
||||
...$option,
|
||||
'holder_kind' => $active->holder_kind,
|
||||
'licence_scope' => $active->licence_scope,
|
||||
'trainer_count' => $active->trainer_count,
|
||||
'grant_kind' => $active->grant_kind,
|
||||
'price_euro' => $active->price_cents === null ? null : number_format($active->price_cents / 100, 2, ',', ''),
|
||||
'lines' => $active->lines->sortBy('position')->map(fn ($line): array => [
|
||||
@@ -347,6 +368,11 @@ private function angebotDaten(): array
|
||||
'wire' => "mountAction('end')",
|
||||
'art' => 'line',
|
||||
]] : []),
|
||||
...(ShopAccess::allowed() ? [[
|
||||
'label' => 'Zahlungen zu diesem Angebot',
|
||||
'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']),
|
||||
'art' => 'quiet',
|
||||
]] : []),
|
||||
],
|
||||
],
|
||||
'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer),
|
||||
@@ -400,6 +426,7 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
|
||||
->unique()
|
||||
->implode('; ');
|
||||
$seite = $offer->composition;
|
||||
$eigeneSeite = $offer->standalone_bundle;
|
||||
$kaufbar = app(OfferService::class)->purchasableVersion($offer) !== null;
|
||||
|
||||
return [
|
||||
@@ -409,10 +436,11 @@ private function optionAbschnitt(Offer $offer, OfferVersion $active): array
|
||||
'zeilen' => [
|
||||
['text' => 'Preis: '.$option['price'], 'neben' => $active->grant_kind === 'kauf' ? 'Kauf mit Testzahlung' : CatalogLabels::vergabe($active)],
|
||||
['text' => 'Geeignet für: '.$option['for'], 'neben' => $option['term']],
|
||||
['text' => 'Nutzerkreis: '.$option['licence'], 'neben' => $option['licence_scope'] === null ? 'Mit „Geänderte Fassung aktivieren“ festlegen.' : 'Lizenzinhaber, Nutzerkreis und Downloadkonto sind getrennte Angaben.'],
|
||||
['text' => 'Rechte: '.($rechte !== '' ? $rechte : 'keine'), 'neben' => null],
|
||||
['text' => 'Zugrunde liegender Inhalt: '.($inhalt !== '' ? $inhalt : '–'), 'neben' => null],
|
||||
['text' => 'Status: '.($kaufbar ? 'Öffentlich kaufbar' : 'Nicht als Kauf angeboten'), 'neben' => $kaufbar ? 'Aktive Fassung '.$active->number : null],
|
||||
['text' => 'Produktseite: '.($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet'), 'neben' => $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
|
||||
['text' => 'Produktseite: '.($eigeneSeite ? 'eigene Paketseite mit dem Umfang des Pakets' : ($seite !== null ? ($seite->display_title ?: $seite->designation) : 'noch nicht zugeordnet')), 'neben' => $eigeneSeite || $seite !== null ? 'Option „'.$offer->optionName().'“' : 'Mit „Geänderte Fassung aktivieren“ zuordnen.'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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“.',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Commerce\Discount\DiscountCode;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
|
||||
/**
|
||||
* Die eine Maske für Rabattcodes: Anlegen und Bearbeiten nutzen dieselben Felder (FACH-20). Geltungsbereich und
|
||||
* Einlösungsberechtigung sind zwei voneinander unabhängige Einstellungen.
|
||||
*/
|
||||
final class DiscountCodeForm
|
||||
{
|
||||
/**
|
||||
* @return list<mixed>
|
||||
*/
|
||||
public static function schema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('code')->label('Code')->required()->maxLength(40)
|
||||
->helperText('So gibt ihn der Käufer ein, 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich. Groß- und Kleinschreibung spielen keine Rolle.'),
|
||||
TextInput::make('label')->label('Name für die Verwaltung')->required()->maxLength(120)
|
||||
->helperText('Nur intern, zum Beispiel „Zertifizierungscode 2026“. Der Käufer sieht ihn nicht.'),
|
||||
Select::make('kind')->label('Art des Rabatts')->options([
|
||||
DiscountCode::PERCENT => 'Prozent',
|
||||
DiscountCode::AMOUNT => 'Fester Betrag in Euro',
|
||||
])->required()->live(),
|
||||
TextInput::make('percent')->label('Prozent')->numeric()->minValue(1)->maxValue(100)->integer()->suffix('%')
|
||||
->required(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::PERCENT)
|
||||
->helperText('Je Position gerundet. Der Zahlbetrag der Bestellung darf 0,50 € nicht unterschreiten.'),
|
||||
TextInput::make('amount_euro')->label('Rabattbetrag')->suffix('€')
|
||||
->required(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||
->visible(fn (Get $get): bool => $get('kind') === DiscountCode::AMOUNT)
|
||||
->helperText('Gilt je Bestellung und wird anteilig auf die betroffenen Positionen verteilt, zum Beispiel 5,00.'),
|
||||
Select::make('scope')->label('Geltungsbereich')->options([
|
||||
DiscountCode::SCOPE_CART => 'Gesamter Warenkorb',
|
||||
DiscountCode::SCOPE_SELECTED => 'Nur ausdrücklich ausgewählte Angebote, Lizenzartikel oder Pakete',
|
||||
])->required()->live()
|
||||
->helperText('Wofür der Rabatt gilt. Unabhängig davon legst du unten fest, wer den Code einlösen darf.'),
|
||||
Select::make('offer_ids')->label('Angebote')->multiple()->searchable()
|
||||
->options(fn (): array => Offer::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Die gewählte Lizenzoption selbst (Fassung egal).'),
|
||||
Select::make('article_ids')->label('Lizenzartikel')->multiple()->searchable()
|
||||
->options(fn (): array => app(PublicationReadiness::class)->articleOptions())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Gilt für Angebote, die diesen Artikel unmittelbar als Position führen. Ein Artikel in einem Paket macht das Paket nicht rabattfähig.'),
|
||||
Select::make('bundle_ids')->label('Pakete')->multiple()->searchable()
|
||||
->options(fn (): array => Bundle::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->visible(fn (Get $get): bool => $get('scope') === DiscountCode::SCOPE_SELECTED)
|
||||
->helperText('Ein Paket wird gezielt gewählt. Es folgt nicht aus einem enthaltenen Artikel.'),
|
||||
Select::make('eligibility')->label('Wer darf den Code einlösen?')->options([
|
||||
DiscountCode::OPEN => 'Alle angemeldeten Käufer (allgemein einlösbar)',
|
||||
DiscountCode::RESTRICTED => 'Nur ausdrücklich freigeschaltete Konten',
|
||||
])->required()
|
||||
->helperText('Bei „freigeschaltete Konten“ schaltest du einzelne Konten auf der Seite des Codes frei und entziehst die Freigabe wieder. Eine Freigabe gilt nur für diesen Code.'),
|
||||
DatePicker::make('valid_from')->label('Gültig ab')->native(false)->displayFormat('d.m.Y')
|
||||
->helperText('Leer: sofort.'),
|
||||
DatePicker::make('valid_until')->label('Gültig bis einschließlich')->native(false)->displayFormat('d.m.Y')
|
||||
->helperText('Leer: unbegrenzt. Am Tag danach gilt der Code nicht mehr.'),
|
||||
Toggle::make('active')->label('Aktiv')->default(true)
|
||||
->helperText('Deaktivierte Codes lassen sich nicht einlösen; bereits aufgegebene Bestellungen bleiben unverändert.'),
|
||||
Textarea::make('note')->label('Notiz')->rows(2)->maxLength(500)
|
||||
->helperText('Zum Beispiel, woran die Berechtigung geprüft wird.'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Formularwerte → Angaben und Ziele des Dienstes.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array{0: array<string, mixed>, 1: list<array{type: string, id: int}>}
|
||||
*/
|
||||
public static function fromForm(array $data): array
|
||||
{
|
||||
$targets = [];
|
||||
|
||||
foreach ([
|
||||
DiscountCode::TARGET_OFFER => 'offer_ids',
|
||||
DiscountCode::TARGET_ARTICLE => 'article_ids',
|
||||
DiscountCode::TARGET_BUNDLE => 'bundle_ids',
|
||||
] as $type => $key) {
|
||||
foreach ((array) ($data[$key] ?? []) as $id) {
|
||||
$targets[] = ['type' => $type, 'id' => (int) $id];
|
||||
}
|
||||
}
|
||||
|
||||
return [$data, $targets];
|
||||
}
|
||||
|
||||
/**
|
||||
* Vorbelegung der Maske aus einem vorhandenen Code.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function fill(DiscountCode $code): array
|
||||
{
|
||||
$code->loadMissing('targets');
|
||||
$ids = fn (string $type): array => $code->targets->where('target_type', $type)->pluck('target_id')->map(fn ($id): int => (int) $id)->values()->all();
|
||||
|
||||
return [
|
||||
'code' => $code->code,
|
||||
'label' => $code->label,
|
||||
'kind' => $code->kind,
|
||||
'percent' => $code->percent,
|
||||
'amount_euro' => $code->amount_cents === null ? null : number_format($code->amount_cents / 100, 2, ',', ''),
|
||||
'scope' => $code->scope,
|
||||
'offer_ids' => $ids(DiscountCode::TARGET_OFFER),
|
||||
'article_ids' => $ids(DiscountCode::TARGET_ARTICLE),
|
||||
'bundle_ids' => $ids(DiscountCode::TARGET_BUNDLE),
|
||||
'eligibility' => $code->eligibility,
|
||||
'valid_from' => $code->valid_from?->timezone(config('app.timezone'))->toDateString(),
|
||||
'valid_until' => $code->valid_until?->timezone(config('app.timezone'))->toDateString(),
|
||||
'active' => $code->active,
|
||||
'note' => $code->note,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\BundleStatus;
|
||||
use App\Domain\Catalog\BundleVersion;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -227,7 +228,8 @@ public function forOffer(Offer $offer): array
|
||||
$missing = $this->unusableArticles($articleIds);
|
||||
$buyable = $hasActive && $this->offers->purchasableVersion($offer) !== null;
|
||||
$page = $offer->composition;
|
||||
$shown = $page !== null && $this->catalog->shownVersion($page) !== null;
|
||||
$own = (bool) $offer->standalone_bundle;
|
||||
$shown = $own || ($page !== null && $this->catalog->shownVersion($page) !== null);
|
||||
$pageName = $page !== null ? (string) ($page->display_title ?: $page->designation) : '';
|
||||
$activate = ['label' => $hasActive ? 'Geänderte Fassung aktivieren' : 'Angebot konfigurieren', 'wire' => "mountAction('activate')"];
|
||||
|
||||
@@ -258,21 +260,36 @@ public function forOffer(Offer $offer): array
|
||||
'stand' => $buyable ? 'erledigt' : 'offen',
|
||||
'aktion' => $buyable ? null : ($hasActive ? $activate : null),
|
||||
],
|
||||
[
|
||||
'titel' => 'Nutzerkreis festlegen',
|
||||
'text' => ! $hasActive
|
||||
? 'Wird mit der Fassung festgelegt: Einzellizenz (ein Trainer) oder Mehrfachlizenz (Zahl der Trainer).'
|
||||
: ($active->licence_scope !== null
|
||||
? LicenceScope::label($active->licence_scope, $active->trainer_count).'. Der Käufer sieht das auf der Produktseite und in der Bestellung.'
|
||||
: 'Diese Fassung hat keinen festgelegten Nutzerkreis. Käufer sehen „Nutzerkreis nicht festgelegt“. Lege ihn mit „Geänderte Fassung aktivieren“ fest.'),
|
||||
'stand' => $hasActive && $active->licence_scope !== null ? 'erledigt' : 'offen',
|
||||
'aktion' => $hasActive && $active->licence_scope === null ? $activate : null,
|
||||
'pflicht' => false,
|
||||
],
|
||||
[
|
||||
'titel' => 'Produktseite zuordnen',
|
||||
'text' => $page !== null
|
||||
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
|
||||
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket braucht eine eigene Produktseite, sonst ist es Alternative zu den Einzelangeboten dieser Seite.',
|
||||
'stand' => $page !== null ? 'erledigt' : 'offen',
|
||||
'aktion' => $page !== null ? null : $activate,
|
||||
'text' => $own
|
||||
? 'Eigene Paketseite: Sie zeigt den Umfang des Pakets. Optionen desselben Pakets sind Alternativen im Warenkorb.'
|
||||
: ($page !== null
|
||||
? 'Zugeordnet: „'.$pageName.'“. Optionen derselben Produktseite sind Alternativen im Warenkorb.'
|
||||
: 'Der Shop zeigt ein Angebot auf der Seite eines Programms. Wähle in der Maske die Produktseite. Ein Paket, das für sich verkauft wird, erhält dort „Eigene Paketseite“ und zeigt seinen Umfang; sonst erscheint es auf der Seite eines fremden Programms.'),
|
||||
'stand' => $own || $page !== null ? 'erledigt' : 'offen',
|
||||
'aktion' => $own || $page !== null ? null : $activate,
|
||||
],
|
||||
[
|
||||
'titel' => 'Produktseite öffentlich',
|
||||
'text' => $page === null
|
||||
'text' => ! $own && $page === null
|
||||
? 'Wird geprüft, sobald eine Produktseite zugeordnet ist.'
|
||||
: ($shown
|
||||
: ($own
|
||||
? 'Die eigene Paketseite ist öffentlich, sobald die aktive Fassung ein Kauf mit Preis ist.'
|
||||
: ($shown
|
||||
? 'Das Programm ist zur Anzeige freigegeben. Das Angebot erscheint in der Shop-Suche und auf der Produktseite.'
|
||||
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.'),
|
||||
: 'Das Programm „'.$pageName.'“ ist nicht zur Anzeige freigegeben oder kein Programm. Das Angebot ist dort nicht auffindbar.')),
|
||||
'stand' => $shown ? 'erledigt' : 'offen',
|
||||
'aktion' => $page === null || $shown ? null : ['label' => 'Programm öffnen', 'href' => EditorialCatalog::editUrl($page)],
|
||||
],
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Identity\StaffRole;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Wer Rabattcodes, Freigaben und Bestellungen verwalten darf: Katalogverwalter und Kundenbetreuung. Die
|
||||
* Berechtigung zum Verkaufen und Erstatten ist eine Betreiberaufgabe, nicht die der Redaktion.
|
||||
*/
|
||||
final class ShopAccess
|
||||
{
|
||||
public static function allowed(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User
|
||||
&& ($user->hasStaffRole(StaffRole::Katalogverwalter) || $user->hasStaffRole(StaffRole::Kundenbetreuung));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Domain\Commerce\Cart;
|
||||
use App\Domain\Commerce\Money;
|
||||
use App\Domain\Commerce\OrderHolders;
|
||||
use App\Domain\Commerce\ProductOptions;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
@@ -31,9 +32,8 @@ public function show(Request $request, Cart $cart, OrderHolders $holders): View
|
||||
public function add(Offer $offer, Cart $cart, PublicCatalogReader $catalog): RedirectResponse
|
||||
{
|
||||
$page = $offer->composition;
|
||||
$result = $page !== null && $catalog->shownVersion($page) !== null
|
||||
? $cart->add($offer)
|
||||
: Cart::UNAVAILABLE;
|
||||
$listed = $offer->standalone_bundle || ($page !== null && $catalog->shownVersion($page) !== null);
|
||||
$result = $listed ? $cart->add($offer) : Cart::UNAVAILABLE;
|
||||
$back = $this->productPage($offer);
|
||||
|
||||
return match ($result) {
|
||||
@@ -81,8 +81,8 @@ public function accept(Offer $offer, Cart $cart): RedirectResponse
|
||||
|
||||
private function productPage(Offer $offer): RedirectResponse
|
||||
{
|
||||
return $offer->composition_id !== null
|
||||
? redirect()->route('public.program', $offer->composition_id)
|
||||
: redirect()->route('cart');
|
||||
$url = app(ProductOptions::class)->pageUrl($offer);
|
||||
|
||||
return $url !== null ? redirect()->to($url) : redirect()->route('cart');
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,15 @@
|
||||
use App\Domain\Catalog\OfferStatus;
|
||||
use App\Domain\Commerce\Cart;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\LedgerEntry;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderHolders;
|
||||
use App\Domain\Commerce\SalesTerms;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\StaleOverview;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Domain\Identity\PartyType;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -67,9 +70,38 @@ public function checkout(Request $request, Cart $cart, OrderHolders $holders): V
|
||||
return view('shop.checkout', [
|
||||
'review' => $review,
|
||||
'holders' => $holders->for($request->user()),
|
||||
'consents' => SalesTerms::consents(),
|
||||
'legalPages' => SalesTerms::pages(),
|
||||
'invoice' => Shop::invoice() && $review->holder?->type === PartyType::Organisation,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rabattcode einlösen. Höchstens ein Code je Bestellung; ein zweiter ersetzt den ersten. Gilt der Code nicht,
|
||||
* bleibt der bisherige Stand und die Meldung nennt den Grund.
|
||||
*/
|
||||
public function applyCode(Request $request, Cart $cart): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['code' => ['required', 'string', 'max:60'], 'bestellen_als' => ['nullable', 'integer']], [
|
||||
'code.required' => 'Gib einen Rabattcode ein.',
|
||||
]);
|
||||
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
|
||||
$result = $cart->applyCode($data['code'], $request->user(), $holderId);
|
||||
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
|
||||
|
||||
return $result->applied()
|
||||
? $back->with('status', 'Der Rabattcode '.$result->code->code.' ist angewendet.')
|
||||
: $back->withErrors(['code' => $result->message ?? 'Der Code kann nicht angewendet werden.']);
|
||||
}
|
||||
|
||||
public function removeCode(Request $request, Cart $cart): RedirectResponse
|
||||
{
|
||||
$cart->removeCode();
|
||||
$holderId = $request->integer('bestellen_als') ?: null;
|
||||
|
||||
return redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]))->with('status', 'Der Rabattcode ist entfernt.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Legt die Bestellung an, aber nur, wenn die serverseitige Prüfung zur gezeigten Übersicht passt.
|
||||
*/
|
||||
@@ -78,19 +110,28 @@ public function placeOrder(Request $request, Cart $cart, Checkout $checkout): Re
|
||||
$data = $request->validate([
|
||||
'digest' => ['required', 'string'],
|
||||
'bestellen_als' => ['nullable', 'integer'],
|
||||
'zahlungsweg' => ['nullable', 'in:online,rechnung'],
|
||||
'zustimmung' => ['nullable', 'array'],
|
||||
]);
|
||||
$holderId = isset($data['bestellen_als']) ? (int) $data['bestellen_als'] : null;
|
||||
$back = redirect()->route('checkout', array_filter(['bestellen_als' => $holderId]));
|
||||
$method = ($data['zahlungsweg'] ?? 'online') === 'rechnung' ? 'rechnung' : null;
|
||||
|
||||
try {
|
||||
$order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest']);
|
||||
// Die Zustimmungen sind eine Pflichtangabe und werden serverseitig geprüft, nicht nur im Formular.
|
||||
SalesTerms::proof((array) ($data['zustimmung'] ?? []));
|
||||
$order = $checkout->placeFromCart($request->user(), $cart, $holderId, $data['digest'], (array) ($data['zustimmung'] ?? []), $method);
|
||||
} catch (StaleOverview $exception) {
|
||||
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
||||
} catch (DomainRuleException $exception) {
|
||||
return $back->withErrors(['checkout' => $exception->getMessage()]);
|
||||
}
|
||||
|
||||
return redirect()->route('member.order', $order)->with('status', 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.');
|
||||
return redirect()->route('member.order', $order)->with('status', match (true) {
|
||||
$order->payment_method === 'rechnung' => 'Deine Bestellung auf Rechnung ist eingegangen. Wir senden dir die Rechnung. Die Inhalte sind nach Zahlungseingang in der Bibliothek.',
|
||||
Shop::stripe() => 'Die Bestellung ist angelegt. Bezahle jetzt sicher bei Stripe.',
|
||||
default => 'Die Bestellung ist angelegt. Bestätige jetzt die Testzahlung.',
|
||||
});
|
||||
}
|
||||
|
||||
public function show(Request $request, Order $order): View
|
||||
@@ -103,9 +144,26 @@ public function show(Request $request, Order $order): View
|
||||
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
|
||||
'stripePayment' => Shop::stripe(),
|
||||
'zahlung' => $request->query('zahlung'),
|
||||
'live' => Shop::live(),
|
||||
'receipts' => LedgerEntry::query()->where('order_id', $order->id)->where('derived', false)->orderBy('occurred_at')->orderBy('id')->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Erklärt den Widerruf; der Betreiber prüft und erstattet gegebenenfalls in der Bestellverwaltung. */
|
||||
public function withdraw(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
||||
{
|
||||
abort_unless($order->user_id === $request->user()->id, 403);
|
||||
$data = $request->validate(['note' => ['nullable', 'string', 'max:1000']]);
|
||||
|
||||
try {
|
||||
$checkout->requestWithdrawal($order, (string) ($data['note'] ?? ''));
|
||||
} catch (DomainRuleException $exception) {
|
||||
return back()->withErrors(['payment' => $exception->getMessage()]);
|
||||
}
|
||||
|
||||
return redirect()->route('member.order', $order)->with('status', 'Dein Widerruf ist eingegangen. Wir prüfen ihn und melden uns per E-Mail.');
|
||||
}
|
||||
|
||||
/** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */
|
||||
public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse
|
||||
{
|
||||
@@ -150,6 +208,8 @@ public function fail(Request $request, Order $order, Checkout $checkout): Redire
|
||||
public function refund(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
||||
{
|
||||
abort_unless($order->user_id === $request->user()->id, 403);
|
||||
// Nur der Testzahlungsweg erstattet auf Knopfdruck. Echte Zahlungen erstattet der Betreiber nach Prüfung.
|
||||
abort_unless(! app()->isProduction() && Shop::driver() === 'test', 404);
|
||||
|
||||
try {
|
||||
$checkout->refund($order, 'Widerruf durch das Mitglied im Testmodus');
|
||||
|
||||
@@ -235,6 +235,8 @@ public function show(Request $request, LicenseArticle $article): View
|
||||
$download = app(DecideAccess::class)($request->user(), $article, $release, $version, 'laden');
|
||||
$file = $metadata['file'] ?? null;
|
||||
$entries[] = [
|
||||
'title' => app(LibraryCatalog::class)->text($version->element)['title'],
|
||||
'class' => $class,
|
||||
'content' => $content,
|
||||
'version' => $version,
|
||||
'role' => $content->role,
|
||||
@@ -447,10 +449,34 @@ private function fileResponse(
|
||||
'k0',
|
||||
);
|
||||
|
||||
return $disk->response($file, basename($file), [
|
||||
'Content-Disposition' => $action === 'laden' ? 'attachment' : 'inline',
|
||||
'X-License-Copy' => $delivery->copy_id,
|
||||
]);
|
||||
// Dateiname aus dem Anzeigetitel statt aus der Adresse („laden.mp4“); Laravel setzt Content-Disposition mit
|
||||
// ASCII-Rückfall und UTF-8-Name.
|
||||
return $disk->response(
|
||||
$file,
|
||||
$this->downloadName($version, $file),
|
||||
['X-License-Copy' => $delivery->copy_id],
|
||||
$action === 'laden' ? 'attachment' : 'inline',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dateiname für Ansicht und Download: Anzeigetitel des Mediums (Mitgliedertext, sonst Arbeitstitel) mit der
|
||||
* Endung der gespeicherten Datei. Zeichen, die in Dateinamen nicht erlaubt sind, entfallen.
|
||||
*/
|
||||
private function downloadName(ContentElementVersion $version, string $file): string
|
||||
{
|
||||
$element = $version->element;
|
||||
$title = $element === null ? '' : app(LibraryCatalog::class)->text($element)['title'];
|
||||
$title = (string) preg_replace('/[\x00-\x1F\x7F\/\\\\:*?"<>|]+/u', ' ', $title);
|
||||
$title = trim((string) preg_replace('/\s+/u', ' ', $title));
|
||||
$title = rtrim(mb_substr($title, 0, 120), '. ');
|
||||
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
|
||||
|
||||
if ($title === '') {
|
||||
return basename($file);
|
||||
}
|
||||
|
||||
return $extension === '' ? $title : $title.'.'.$extension;
|
||||
}
|
||||
|
||||
private function renditionBelongsTo(int $versionId, string $path): bool
|
||||
|
||||
@@ -2,11 +2,9 @@
|
||||
|
||||
namespace App\Http\Controllers\Member;
|
||||
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\LibraryCatalog;
|
||||
use App\Http\MemberLicenses;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
@@ -28,28 +26,4 @@ public function dashboard(Request $request): View
|
||||
'licenseCount' => app(MemberLicenses::class)->overview($request->user())->where('active', true)->count(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function profile(): View
|
||||
{
|
||||
return view('member.profile');
|
||||
}
|
||||
|
||||
public function updateProfile(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validate([
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
]);
|
||||
|
||||
$user->name = $data['name'];
|
||||
$user->save();
|
||||
|
||||
$user->party?->update(['display_name' => $data['name']]);
|
||||
$user->party?->profile?->update(['display_name' => $data['name']]);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Member;
|
||||
|
||||
use App\Domain\Identity\AccountStatus;
|
||||
use App\Domain\Identity\BillingAddress;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Notifications\ConfirmNewEmailAddress;
|
||||
use App\Notifications\EmailChangeRequested;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
* Mitgliederprofil: Name, E-Mail-Adresse, Passwort und Rechnungsadresse. Jeder Block hat seine eigene Speicherhandlung
|
||||
* und seine eigenen Fehlermeldungen; nichts wird verdeckt mitgespeichert. Sicherheitsrelevante Änderungen (Adresse,
|
||||
* Passwort) verlangen das aktuelle Passwort.
|
||||
*/
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
public function show(Request $request): View
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
return view('member.profile', [
|
||||
'address' => $user->party?->billingAddress,
|
||||
'countries' => BillingAddress::COUNTRIES,
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateName(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('name', [
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
]);
|
||||
|
||||
$user->name = $data['name'];
|
||||
$user->save();
|
||||
|
||||
$user->party?->update(['display_name' => $data['name']]);
|
||||
$user->party?->profile?->update(['display_name' => $data['name']]);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Der Name ist gespeichert. Er ist nicht öffentlich.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Die neue Adresse gilt erst nach Bestätigung über einen Link an sie. Bis dahin bleibt die bisherige Adresse
|
||||
* in Kraft und erhält einen Hinweis.
|
||||
*/
|
||||
public function requestEmail(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('email', [
|
||||
'email' => ['required', 'string', 'email:rfc', 'max:255', Rule::unique('users', 'email')],
|
||||
'current_password' => ['required', 'current_password'],
|
||||
], [
|
||||
'email.unique' => 'Diese Adresse ist bereits vergeben.',
|
||||
'current_password.current_password' => 'Das Passwort stimmt nicht.',
|
||||
]);
|
||||
|
||||
$new = mb_strtolower(trim($data['email']));
|
||||
|
||||
if ($new === mb_strtolower($user->email)) {
|
||||
return back()->withErrors(['email' => 'Das ist bereits deine Adresse.'], 'email');
|
||||
}
|
||||
|
||||
$user->forceFill(['pending_email' => $new])->save();
|
||||
Notification::route('mail', $new)->notify(new ConfirmNewEmailAddress($user->id, $new));
|
||||
$user->notify(new EmailChangeRequested($new));
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Wir haben einen Bestätigungslink an '.$new.' geschickt. Die Adresse wechselt, sobald du ihn öffnest.');
|
||||
}
|
||||
|
||||
public function confirmEmail(Request $request, int $id, string $hash): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_unless($user->id === $id, 403);
|
||||
$pending = $user->pending_email;
|
||||
|
||||
if (! is_string($pending) || $pending === '' || ! hash_equals(sha1($pending), $hash)) {
|
||||
return redirect()->route('member.profile')->withErrors(['email' => 'Dieser Link gilt nicht mehr. Fordere die Änderung bitte erneut an.'], 'email');
|
||||
}
|
||||
|
||||
if (User::query()->where('email', $pending)->whereKeyNot($user->id)->exists()) {
|
||||
$user->forceFill(['pending_email' => null])->save();
|
||||
|
||||
return redirect()->route('member.profile')->withErrors(['email' => 'Diese Adresse ist inzwischen vergeben.'], 'email');
|
||||
}
|
||||
|
||||
$user->forceFill(['email' => $pending, 'pending_email' => null, 'email_verified_at' => now()])->save();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Deine E-Mail-Adresse ist geändert.');
|
||||
}
|
||||
|
||||
public function cancelEmail(Request $request): RedirectResponse
|
||||
{
|
||||
$request->user()->forceFill(['pending_email' => null])->save();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Die Änderung der E-Mail-Adresse ist verworfen.');
|
||||
}
|
||||
|
||||
public function updatePassword(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv, 403);
|
||||
|
||||
$data = $request->validateWithBag('password', [
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'password' => ['required', 'confirmed', Password::defaults(), 'different:current_password'],
|
||||
], [
|
||||
'current_password.current_password' => 'Das bisherige Passwort stimmt nicht.',
|
||||
'password.different' => 'Das neue Passwort muss sich vom bisherigen unterscheiden.',
|
||||
]);
|
||||
|
||||
$user->forceFill(['password' => Hash::make($data['password'])])->save();
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Dein Passwort ist geändert.');
|
||||
}
|
||||
|
||||
public function updateAddress(Request $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
abort_if($user->status !== AccountStatus::Aktiv || $user->party === null, 403);
|
||||
|
||||
$data = $request->validateWithBag('address', [
|
||||
'recipient' => ['required', 'string', 'max:160'],
|
||||
'line2' => ['nullable', 'string', 'max:160'],
|
||||
'street' => ['required', 'string', 'max:160'],
|
||||
'postal_code' => ['required', 'string', 'max:16'],
|
||||
'city' => ['required', 'string', 'max:120'],
|
||||
'country' => ['required', Rule::in(array_keys(BillingAddress::COUNTRIES))],
|
||||
], [
|
||||
'recipient.required' => 'Bitte gib Name oder Firma an.',
|
||||
'street.required' => 'Bitte gib Straße und Hausnummer an.',
|
||||
'postal_code.required' => 'Bitte gib die Postleitzahl an.',
|
||||
'city.required' => 'Bitte gib den Ort an.',
|
||||
]);
|
||||
|
||||
BillingAddress::query()->updateOrCreate(['party_id' => $user->party_id], $data);
|
||||
|
||||
return redirect()->route('member.profile')->with('status', 'Die Rechnungsadresse ist gespeichert.');
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Catalog\CompositionStructureReader;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
@@ -17,6 +18,25 @@ public function index(PublicCatalogReader $catalog): View
|
||||
return view('public.programs', ['programs' => $catalog->publicPrograms()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Eigene Produktseite eines Pakets, das für sich vermarktet wird: Sie zeigt den tatsächlichen Umfang des Pakets
|
||||
* (die enthaltenen Artikel) und darunter die kaufbaren Lizenzoptionen. Ohne kaufbare Option gibt es sie nicht.
|
||||
*/
|
||||
public function package(Bundle $bundle, ProductOptions $products, Cart $cart): View
|
||||
{
|
||||
abort_unless(Shop::enabled(), 404);
|
||||
$options = $products->forBundle($bundle);
|
||||
abort_if($options === [], 404);
|
||||
|
||||
return view('public.package', [
|
||||
'bundle' => $bundle,
|
||||
'contents' => $products->bundleContents($options),
|
||||
'options' => $options,
|
||||
'cart' => $cart,
|
||||
'switchTo' => session('shop.switch'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function program(Composition $composition, PublicCatalogReader $catalog, ProductOptions $products, Cart $cart): View
|
||||
{
|
||||
$version = $catalog->shownVersion($composition);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Domain\Catalog\Bundle;
|
||||
use App\Domain\Catalog\Composition;
|
||||
use App\Domain\Cms\Catalog\PublicCatalogReader;
|
||||
use App\Domain\Commerce\Money;
|
||||
@@ -37,7 +38,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR
|
||||
|
||||
$summary = $summaries[$composition->id];
|
||||
$cards[] = [
|
||||
'composition' => $composition,
|
||||
'url' => route('public.program', $composition),
|
||||
'title' => $title,
|
||||
'teaser' => (string) ($composition->teaser ?: $composition->summary),
|
||||
'from' => Money::format($summary['from_cents']),
|
||||
@@ -45,6 +46,26 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR
|
||||
];
|
||||
}
|
||||
|
||||
// Pakete mit eigener Produktseite: gelistet mit Name und enthaltenen Artikeln.
|
||||
foreach (Bundle::query()->whereIn('id', array_keys($products->bundleSummaries()))->orderBy('name')->get() as $bundle) {
|
||||
$options = $products->forBundle($bundle);
|
||||
$contents = $products->bundleContents($options);
|
||||
$names = implode(', ', array_column($contents, 'title'));
|
||||
|
||||
if ($term !== '' && ! str_contains(mb_strtolower($bundle->name.' '.$names), mb_strtolower($term))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$summary = $products->bundleSummaries()[$bundle->id];
|
||||
$cards[] = [
|
||||
'url' => route('public.package', $bundle),
|
||||
'title' => (string) $bundle->name,
|
||||
'teaser' => 'Paket mit '.count($contents).' '.(count($contents) === 1 ? 'Inhalt' : 'Inhalten').($names !== '' ? ': '.$names : ''),
|
||||
'from' => Money::format($summary['from_cents']),
|
||||
'count' => $summary['count'],
|
||||
];
|
||||
}
|
||||
|
||||
return view('shop.index', ['cards' => $cards, 'term' => $term]);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\Stripe\StripeSignature;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
@@ -42,7 +43,7 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
|
||||
$session = (array) ($event['data']['object'] ?? []);
|
||||
|
||||
return match ($event['type']) {
|
||||
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout),
|
||||
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout, $event),
|
||||
'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']),
|
||||
default => response()->json(['received' => true, 'handled' => false]),
|
||||
};
|
||||
@@ -50,8 +51,9 @@ public function __invoke(Request $request, StripeSignature $signature, Checkout
|
||||
|
||||
/**
|
||||
* @param array<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') {
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
@@ -73,6 +75,9 @@ private function paid(array $session, Checkout $checkout): JsonResponse
|
||||
$reference,
|
||||
(int) ($session['amount_total'] ?? -1),
|
||||
(string) ($session['currency'] ?? ''),
|
||||
(bool) ($event['livemode'] ?? $session['livemode'] ?? false),
|
||||
is_numeric($event['created'] ?? null) ? CarbonImmutable::createFromTimestampUTC((int) $event['created']) : null,
|
||||
filled($session['payment_intent'] ?? null) ? (string) $session['payment_intent'] : null,
|
||||
);
|
||||
} catch (DomainRuleException $exception) {
|
||||
// Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur
|
||||
@@ -83,6 +88,10 @@ private function paid(array $session, Checkout $checkout): JsonResponse
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
}
|
||||
|
||||
if (filled($session['payment_intent'] ?? null)) {
|
||||
$order->payments()->where('provider_reference', $reference)->update(['provider_payment_ref' => (string) $session['payment_intent']]);
|
||||
}
|
||||
|
||||
return response()->json(['received' => true, 'handled' => true]);
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ private function entry(User $user, Grant $grant): array
|
||||
? 'Spätere freigegebene Fassungen sind eingeschlossen.'
|
||||
: null,
|
||||
'source' => $this->source($user, $grant),
|
||||
'licence_scope' => $conditions['licence_scope'] ?? null,
|
||||
'trainer_count' => isset($conditions['trainer_count']) ? (int) $conditions['trainer_count'] : null,
|
||||
'holder_kind' => $holderKind,
|
||||
'holder' => $holderKind === 'organisation' ? (string) ($grant->acquisition?->party?->display_name ?? 'Organisation') : 'Persönlich',
|
||||
'url' => route('member.grant', $grant),
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
#[Fillable(['party_id', 'name', 'email', 'password', 'status', 'confirmed_adult_at'])]
|
||||
#[Fillable(['party_id', 'name', 'email', 'password', 'status', 'confirmed_adult_at', 'pending_email'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable implements FilamentUser, HasAppAuthentication, HasAppAuthenticationRecovery, MustVerifyEmail
|
||||
{
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Notifications;
|
||||
|
||||
use App\Http\SignedLink;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Bestätigungslink an die NEUE Adresse. Erst der Klick darauf tauscht die Adresse des Kontos aus.
|
||||
*/
|
||||
class ConfirmNewEmailAddress extends Notification
|
||||
{
|
||||
public function __construct(private readonly int $userId, private readonly string $newEmail) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function via(mixed $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(mixed $notifiable): MailMessage
|
||||
{
|
||||
$url = SignedLink::temporary('member.profile.email.confirm', Carbon::now()->addMinutes(60), [
|
||||
'id' => $this->userId,
|
||||
'hash' => sha1($this->newEmail),
|
||||
]);
|
||||
|
||||
return (new MailMessage)
|
||||
->subject('Neue E-Mail-Adresse bestätigen')
|
||||
->line('Du hast gebeten, die E-Mail-Adresse deines Kontos bei Lara & Felix zu ändern. Bestätige mit dem Knopf, dass diese Adresse dir gehört.')
|
||||
->action('Adresse bestätigen', $url)
|
||||
->line('Der Link gilt 60 Minuten. Wenn du das nicht angefordert hast, ignoriere diese Nachricht; es ändert sich nichts.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Notifications;
|
||||
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
|
||||
/**
|
||||
* Hinweis an die bisherige Adresse, dass eine Änderung beantragt wurde (Schutz vor Kontoübernahme).
|
||||
*/
|
||||
class EmailChangeRequested extends Notification
|
||||
{
|
||||
public function __construct(private readonly string $newEmail) {}
|
||||
|
||||
/** @return list<string> */
|
||||
public function via(mixed $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(mixed $notifiable): MailMessage
|
||||
{
|
||||
return (new MailMessage)
|
||||
->subject('Änderung deiner E-Mail-Adresse beantragt')
|
||||
->line('Für dein Konto bei Lara & Felix wurde beantragt, die E-Mail-Adresse auf '.$this->newEmail.' zu ändern.')
|
||||
->line('Die Adresse wechselt erst, wenn die neue Adresse bestätigt wird. Warst du das nicht, ändere bitte dein Passwort und melde dich bei uns.');
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,12 @@ public function panel(Panel $panel): Panel
|
||||
->authMiddleware([
|
||||
Authenticate::class,
|
||||
])
|
||||
// Favicon zur Anfragezeit: ->favicon(asset(...)) würde beim Start der Anwendung berechnet, vor der
|
||||
// Auswertung von Proxy-Kopfzeilen und geöffneter Adresse, und könnte auf einen falschen Host zeigen.
|
||||
->renderHook(
|
||||
PanelsRenderHook::HEAD_END,
|
||||
fn (): string => view('components.site.favicon')->render(),
|
||||
)
|
||||
->renderHook(
|
||||
PanelsRenderHook::STYLES_AFTER,
|
||||
fn (): string => view('filament.cms.styles')->render().view('filament.verwaltung.styles')->render(),
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Brand;
|
||||
|
||||
use Illuminate\Support\HtmlString;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Kleingrafiken des Brand-Kits (docs/Brand-UI-Kit/16_Lara-Felix-Kleingrafiken) als Inline-SVG.
|
||||
*
|
||||
* - Nur Dateien aus resources/svg/brand/<Satz>/ sind zulässig; ein unbekannter Name ist ein Fehler, kein stiller Leerplatz.
|
||||
* - Die Kit-Dateien tragen alle dieselbe ID (motif-title) und einen Titel. Beim Einbetten werden ID, Titel, Rolle und feste
|
||||
* Größe entfernt, damit mehrere Symbole auf einer Seite keine doppelten IDs erzeugen. Symbole sind Beiwerk
|
||||
* (aria-hidden); die Aussage trägt immer der danebenstehende Text.
|
||||
* - Sätze: „symbole“ (Symbole und Akzente aus dem Kit, feste Markenfarben) und „glyphen“ (kleine Zeichen für Tags, Farbe
|
||||
* über currentColor, Geometrie aus den Tag-Dateien des Kits).
|
||||
* - Nicht enthalten: die Motive mit Text als Pfad (Pinsel, Pillen, Tags, Kompositionen). Text bleibt HTML.
|
||||
*/
|
||||
final class Symbols
|
||||
{
|
||||
public const SET_SYMBOLS = 'symbole';
|
||||
|
||||
public const SET_GLYPHS = 'glyphen';
|
||||
|
||||
/** @var array<string, string> */
|
||||
private static array $cache = [];
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function names(string $set = self::SET_SYMBOLS): array
|
||||
{
|
||||
$files = glob(self::directory($set).'/*.svg') ?: [];
|
||||
$names = array_map(fn (string $file): string => basename($file, '.svg'), $files);
|
||||
sort($names);
|
||||
|
||||
return $names;
|
||||
}
|
||||
|
||||
public static function symbol(string $name, string $attributes = ''): HtmlString
|
||||
{
|
||||
return self::render(self::SET_SYMBOLS, $name, $attributes);
|
||||
}
|
||||
|
||||
public static function glyph(string $name, string $attributes = ''): HtmlString
|
||||
{
|
||||
return self::render(self::SET_GLYPHS, $name, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $attributes bereits maskierte Attribute (aus der Attributtasche der Komponente)
|
||||
*/
|
||||
private static function render(string $set, string $name, string $attributes): HtmlString
|
||||
{
|
||||
if (! preg_match('/^[a-z0-9-]+$/', $name) || ! in_array($name, self::names($set), true)) {
|
||||
throw new InvalidArgumentException("Unbekanntes Markensymbol „{$name}“ im Satz „{$set}“.");
|
||||
}
|
||||
|
||||
$svg = self::$cache["$set/$name"] ??= self::clean((string) file_get_contents(self::directory($set)."/$name.svg"));
|
||||
$extra = trim($attributes) === '' ? '' : ' '.trim($attributes);
|
||||
|
||||
return new HtmlString(preg_replace('/^<svg\b/', '<svg aria-hidden="true" focusable="false"'.$extra, $svg, 1) ?? $svg);
|
||||
}
|
||||
|
||||
private static function clean(string $svg): string
|
||||
{
|
||||
$svg = trim($svg);
|
||||
$svg = preg_replace('#<title\b[^>]*>.*?</title>#s', '', $svg) ?? $svg;
|
||||
$svg = preg_replace('/\r?\n\s*/', '', $svg) ?? $svg;
|
||||
|
||||
return (string) preg_replace_callback('/^<svg\b[^>]*>/', function (array $root): string {
|
||||
return (string) preg_replace('/\s(?:id|role|aria-labelledby|width|height)="[^"]*"/', '', $root[0]);
|
||||
}, $svg);
|
||||
}
|
||||
|
||||
private static function directory(string $set): string
|
||||
{
|
||||
if (! in_array($set, [self::SET_SYMBOLS, self::SET_GLYPHS], true)) {
|
||||
throw new InvalidArgumentException("Unbekannter Symbolsatz „{$set}“.");
|
||||
}
|
||||
|
||||
return resource_path("svg/brand/$set");
|
||||
}
|
||||
}
|
||||
@@ -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.'),
|
||||
|
||||
];
|
||||
@@ -70,6 +70,13 @@ public function katalogverwalter(): static
|
||||
});
|
||||
}
|
||||
|
||||
public function kundenbetreuung(): static
|
||||
{
|
||||
return $this->afterCreating(function (User $user): void {
|
||||
$user->staffRoles()->create(['role' => StaffRole::Kundenbetreuung]);
|
||||
});
|
||||
}
|
||||
|
||||
public function redakteur(): static
|
||||
{
|
||||
return $this->afterCreating(function (User $user): void {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Mitgliederprofil (ADR-46): neue E-Mail-Adresse wartet auf Bestätigung (pending_email) und Rechnungsadresse je Lizenzinhaber.
|
||||
* Rein ergänzend: keine bestehende Spalte und Tabelle wird verändert; ein Code-Rollback ignoriert beides.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->string('pending_email')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('billing_addresses', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->foreignId('party_id')->unique()->constrained('parties')->cascadeOnDelete();
|
||||
$table->string('recipient', 160);
|
||||
$table->string('line2', 160)->nullable();
|
||||
$table->string('street', 160);
|
||||
$table->string('postal_code', 16);
|
||||
$table->string('city', 120);
|
||||
$table->string('country', 2)->default('DE');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('billing_addresses');
|
||||
Schema::table('users', function (Blueprint $table): void {
|
||||
$table->dropColumn('pending_email');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,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,6 +8,7 @@
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\EditorialContentKind;
|
||||
use App\Domain\Catalog\LicenceScope;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Offer;
|
||||
use App\Domain\Catalog\OfferService;
|
||||
@@ -78,14 +79,14 @@ public function run(): void
|
||||
'pdf' => ['ansehen', 'laden'],
|
||||
]);
|
||||
|
||||
$this->offer($offers, 'Konflikte im Training: Privatlizenz', 'Privatlizenz', $konflikteVersion, [$konflikteArticle, $privat], 4900, 'person');
|
||||
$this->offer($offers, 'Konflikte im Training: Vereinslizenz', 'Mehrfachlizenz für Vereine', $konflikteVersion, [$konflikteArticle, $verein], 14900, 'organisation');
|
||||
$this->offer($offers, 'Grenzen setzen: Privatlizenz', 'Privatlizenz', $grenzenVersion, [$grenzenArticle, $privat], 2900, 'person');
|
||||
$this->offer($offers, 'Konflikte im Training: Privatlizenz', 'Privatlizenz', $konflikteVersion, [$konflikteArticle, $privat], 4900, 'person', LicenceScope::SINGLE, 1);
|
||||
$this->offer($offers, 'Konflikte im Training: Vereinslizenz', 'Mehrfachlizenz für Vereine', $konflikteVersion, [$konflikteArticle, $verein], 14900, 'organisation', LicenceScope::MULTI, 5);
|
||||
$this->offer($offers, 'Grenzen setzen: Privatlizenz', 'Privatlizenz', $grenzenVersion, [$grenzenArticle, $privat], 2900, 'person', LicenceScope::SINGLE, 1);
|
||||
|
||||
$bundle = $bundles->create('Starterpaket');
|
||||
$starter = $bundles->publish($bundle, [$konflikteArticle->fresh(), $grenzenArticle->fresh(), $starterArticle->fresh()]);
|
||||
$paket = $offers->create('Starterpaket: Privatlizenz');
|
||||
$offers->activate($paket, [['target' => $starter, 'rights' => $privat]], ['grant_kind' => 'kauf', 'price_cents' => 5900, 'holder_kind' => 'person']);
|
||||
$offers->activate($paket, [['target' => $starter, 'rights' => $privat]], ['grant_kind' => 'kauf', 'price_cents' => 5900, 'holder_kind' => 'person', 'licence_scope' => LicenceScope::SINGLE, 'trainer_count' => 1]);
|
||||
$offers->assignProduct($paket, $starterVersion->composition_id, 'Starterpaket (zwei Programme und Einführung)');
|
||||
|
||||
$tina = $this->account('Tina Trainerin', 'tina.trainerin@example.test');
|
||||
@@ -160,13 +161,15 @@ private function program(
|
||||
/**
|
||||
* @param array{0: LicenseArticle, 1: RightsProfileVersion} $line
|
||||
*/
|
||||
private function offer(OfferService $offers, string $name, string $label, CompositionVersion $version, array $line, int $cents, string $holder): Offer
|
||||
private function offer(OfferService $offers, string $name, string $label, CompositionVersion $version, array $line, int $cents, string $holder, ?string $scope = null, ?int $trainers = null): Offer
|
||||
{
|
||||
$offer = $offers->create($name);
|
||||
$offers->activate($offer, [['target' => $line[0], 'rights' => $line[1]]], [
|
||||
'grant_kind' => 'kauf',
|
||||
'price_cents' => $cents,
|
||||
'holder_kind' => $holder,
|
||||
'licence_scope' => $scope,
|
||||
'trainer_count' => $trainers,
|
||||
]);
|
||||
$offers->assignProduct($offer, $version->composition_id, $label);
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 835 B |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
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 & 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 |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 4.5 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 7.3 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 9.1 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 8.4 KiB |