Führe Rabattcodes, Nutzerkreis der Lizenzoption und Pflichtangaben der Kasse ein

Domäne: Rabattcodes mit Geltungsbereich (Warenkorb oder gewählte Ziele) und
Einlösungsberechtigung (allgemein oder freigeschaltete Konten) unabhängig
voneinander; Prüfung bei Eingabe, in jeder Übersicht und unter Sperre vor
Bestellabschluss (Prüfsumme der Übersicht enthält den Rabatt). Rabatt je
Position, Zwischensumme und Zahlbetrag in der Bestellung; Stripe erhält den
Preis nach Rabatt. Nutzerkreis (Einzel-/Mehrfachlizenz, Trainerzahl) an der
Angebotsfassung, kopiert in Bestellposition und Erwerb, Teil der Prüfung
"Bereits erworben". OfferService::activate lehnt Angebote ohne veröffentlichten
Artikelstand ab. Kasse: Zustimmungen als Pflichtangabe mit Nachweis,
"Zahlungspflichtig bestellen", Rechnungsweg für Organisationen, Erstattung über
Stripe, Widerruf erklären. Produktivfreigabe SHOP_LIVE_RELEASE standardmäßig aus.

Bestandstests geändert (fachlich überholt, Assertions nicht abgeschwächt): die
Schaltfläche heißt "Zahlungspflichtig bestellen" (§ 312j BGB), die Summe heißt
"Zu zahlen", der Vereinshinweis steht als Rollenliste; Bestellungen über die
Kasse senden jetzt die Zustimmungen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-22 19:42:02 +01:00
1 parent cb80835c92
commit 0154182f3b
40 files changed
+2151 -92

No files matched your search

@@ -0,0 +1,74 @@
<?php
namespace App\Domain\Commerce\Discount;
/**
* Reine Rechenregel für den Rabatt je Position (ganze Cent, keine Datenbank, keine Uhr).
*
* Prozent: je Position gerundet (kaufmännisch, ab 0,5 Cent nach oben), höchstens der Positionspreis. Die Summe ist
* die Summe der gerundeten Positionsrabatte. Das kann um bis zu einen Cent je Position von der Rundung auf der
* Warenkorbsumme abweichen (Rechenbeispiel in der Abnahme zum Verkaufsstart, Fachfrage).
*
* Betrag: Der Festbetrag gilt je Bestellung, höchstens bis zur Summe der betroffenen Positionen. Er wird anteilig
* zum Positionspreis verteilt; verbleibende Cent erhalten die Positionen mit dem größten Rest, bei Gleichstand die
* frühere Position.
*/
final class DiscountCalculator
{
/**
* @param array<int|string, int> $prices Schlüssel der Position => Preis in Cent (nur betroffene Positionen)
* @return array<int|string, int> Schlüssel => Rabatt in Cent
*/
public static function allocate(string $kind, ?int $percent, ?int $amountCents, array $prices): array
{
$discounts = array_fill_keys(array_keys($prices), 0);
if ($prices === []) {
return $discounts;
}
if ($kind === DiscountCode::PERCENT) {
$percent = max(0, min(100, (int) $percent));
foreach ($prices as $key => $price) {
$discounts[$key] = min($price, intdiv($price * $percent + 50, 100));
}
return $discounts;
}
$sum = array_sum($prices);
$total = min(max(0, (int) $amountCents), $sum);
if ($total === 0 || $sum === 0) {
return $discounts;
}
$remainders = [];
$given = 0;
foreach ($prices as $key => $price) {
$share = intdiv($total * $price, $sum);
$discounts[$key] = $share;
$remainders[$key] = ($total * $price) % $sum;
$given += $share;
}
$rest = $total - $given;
$order = array_keys($prices);
usort($order, fn ($left, $right): int => $remainders[$right] <=> $remainders[$left]);
foreach ($order as $key) {
if ($rest === 0) {
break;
}
if ($discounts[$key] < $prices[$key]) {
$discounts[$key]++;
$rest--;
}
}
return $discounts;
}
}
@@ -0,0 +1,103 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Domain\Commerce\Money;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Rabattcode (PAY-008, FACH-14). Zwei voneinander unabhängige Einstellungen:
* - Geltungsbereich: gesamter Warenkorb oder nur ausdrücklich gewählte Ziele (Angebot, Lizenzartikel, Paket);
* - Einlösungsberechtigung: allgemein oder nur für ausdrücklich freigeschaltete Konten (Freigabe gilt nur für diesen Code).
* Der Rabatt ändert den Preis, nie den Nutzungsumfang.
*/
class DiscountCode extends Model
{
public const PERCENT = 'prozent';
public const AMOUNT = 'betrag';
public const SCOPE_CART = 'warenkorb';
public const SCOPE_SELECTED = 'auswahl';
public const OPEN = 'allgemein';
public const RESTRICTED = 'freigabe';
public const TARGET_OFFER = 'angebot';
public const TARGET_ARTICLE = 'lizenzartikel';
public const TARGET_BUNDLE = 'paket';
protected $fillable = [
'code',
'label',
'kind',
'percent',
'amount_cents',
'scope',
'eligibility',
'valid_from',
'valid_until',
'active',
'note',
];
protected function casts(): array
{
return [
'valid_from' => 'datetime',
'valid_until' => 'datetime',
'active' => 'boolean',
];
}
/** Eingabe und Speicherung vereinheitlicht: ohne Leerzeichen, Großschreibung. */
public static function normalise(string $input): string
{
return mb_strtoupper((string) preg_replace('/\s+/u', '', $input));
}
public function targets(): HasMany
{
return $this->hasMany(DiscountCodeTarget::class);
}
public function releases(): HasMany
{
return $this->hasMany(DiscountRelease::class)->latest('id');
}
public function restricted(): bool
{
return $this->eligibility === self::RESTRICTED;
}
public function forSelection(): bool
{
return $this->scope === self::SCOPE_SELECTED;
}
/** Lesbare Höhe: „10 %“ oder „5,00 €“. */
public function valueLabel(): string
{
return $this->kind === self::PERCENT
? (int) $this->percent.' %'
: Money::format((int) $this->amount_cents);
}
/** Zeitlicher Zustand zum Zeitpunkt: 'aktiv', 'abgelaufen', 'noch_nicht' oder 'deaktiviert'. */
public function stateAt(CarbonInterface $now): string
{
return match (true) {
! $this->active => 'deaktiviert',
$this->valid_from !== null && $this->valid_from->greaterThan($now) => 'noch_nicht',
$this->valid_until !== null && ! $this->valid_until->greaterThan($now) => 'abgelaufen',
default => 'aktiv',
};
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Domain\Commerce\Discount;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Ausdrücklich gewähltes Ziel eines Codes mit Geltungsbereich „Auswahl“. Ein Paket ist ein eigenes Ziel; seine
* Rabattfähigkeit folgt nie aus einem enthaltenen Lizenzartikel und umgekehrt.
*/
class DiscountCodeTarget extends Model
{
protected $fillable = [
'discount_code_id',
'target_type',
'target_id',
];
public function code(): BelongsTo
{
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Freigabe eines Mitgliedskontos für genau einen Code. Freigaben werden nie gelöscht, nur entzogen; Verlauf und
* Begründung bleiben erhalten. Eine Freigabe für Code X berechtigt nicht zur Nutzung von Code Y.
*/
class DiscountRelease extends Model
{
protected $table = 'discount_code_releases';
protected $fillable = [
'discount_code_id',
'user_id',
'granted_by',
'granted_at',
'valid_until',
'revoked_by',
'revoked_at',
'reason',
];
protected function casts(): array
{
return [
'granted_at' => 'datetime',
'valid_until' => 'datetime',
'revoked_at' => 'datetime',
];
}
public function code(): BelongsTo
{
return $this->belongsTo(DiscountCode::class, 'discount_code_id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function grantor(): BelongsTo
{
return $this->belongsTo(User::class, 'granted_by');
}
public function isActiveAt(CarbonInterface $now): bool
{
return $this->revoked_at === null
&& $this->granted_at->lessThanOrEqualTo($now)
&& ($this->valid_until === null || $this->valid_until->greaterThan($now));
}
}
@@ -0,0 +1,83 @@
<?php
namespace App\Domain\Commerce\Discount;
/**
* Ergebnis der Prüfung eines Codes gegen einen Warenkorb: angewandt (Rabatt je Option) oder nicht angewandt mit
* einer verständlichen Begründung. Ein Code, der gerade nicht gilt, bleibt als Ergebnis sichtbar, damit der Käufer
* den Grund erfährt.
*/
final class DiscountResult
{
public const OK = 'ok';
public const UNKNOWN = 'unbekannt';
public const INACTIVE = 'deaktiviert';
public const NOT_YET = 'noch_nicht';
public const EXPIRED = 'abgelaufen';
public const LOGIN = 'anmeldung';
public const NO_RELEASE = 'keine_freigabe';
public const NO_MATCH = 'keine_position';
public const TOO_HIGH = 'zu_hoch';
/**
* @param array<int, int> $perOffer Kennung der Option => Rabatt in Cent
*/
public function __construct(
public readonly ?DiscountCode $code,
public readonly string $state,
public readonly ?string $message = null,
public readonly array $perOffer = [],
) {}
public function applied(): bool
{
return $this->state === self::OK && $this->totalCents() > 0;
}
public function totalCents(): int
{
return $this->state === self::OK ? array_sum($this->perOffer) : 0;
}
public function forOffer(int $offerId): int
{
return $this->state === self::OK ? (int) ($this->perOffer[$offerId] ?? 0) : 0;
}
/** Für die Bestellung festgehaltene Angaben zum Zeitpunkt der Bestellung. */
public function snapshot(): array
{
return [
'code' => $this->code?->code,
'label' => $this->code?->label,
'kind' => $this->code?->kind,
'percent' => $this->code?->percent,
'amount_cents' => $this->code?->amount_cents,
'scope' => $this->code?->scope,
'eligibility' => $this->code?->eligibility,
'discount_cents' => $this->totalCents(),
];
}
/** Teil der Prüfsumme der Bestellübersicht. */
public function digestPart(): string
{
$parts = [];
$perOffer = $this->perOffer;
ksort($perOffer);
foreach ($perOffer as $offerId => $cents) {
$parts[] = $offerId.'='.$cents;
}
return ($this->code?->id ?? 0).':'.$this->state.':'.implode(',', $parts);
}
}
@@ -0,0 +1,320 @@
<?php
namespace App\Domain\Commerce\Discount;
use App\Domain\Catalog\Bundle;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Commerce\CartLine;
use App\Domain\Commerce\Money;
use App\Models\User;
use Carbon\CarbonInterface;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
/**
* Prüfung und Pflege von Rabattcodes. Die Prüfung läuft serverseitig bei der Eingabe, in jeder Übersicht und
* unmittelbar vor Bestellabschluss (unter Sperre); sie liest nur und ändert keine Bestellung.
*/
class DiscountService
{
/** Kleinster Zahlbetrag einer Bestellung mit Rabatt (Mindestbetrag der Kartenzahlung bei Stripe: 0,50 EUR). */
public const MIN_PAYABLE_CENTS = 50;
public function find(string $input): ?DiscountCode
{
$code = DiscountCode::normalise($input);
return $code === '' ? null : DiscountCode::query()->where('code', $code)->first();
}
/**
* @param list<CartLine> $lines nur Positionen, die in die Bestellung eingehen
*/
public function evaluate(DiscountCode $code, ?User $user, array $lines, ?CarbonInterface $now = null, bool $lock = false): DiscountResult
{
$now ??= now();
$timing = $code->stateAt($now);
if ($timing !== 'aktiv') {
return new DiscountResult($code, $timing, match ($timing) {
'deaktiviert' => 'Dieser Code ist nicht mehr gültig, der Betreiber hat ihn deaktiviert.',
'noch_nicht' => 'Dieser Code gilt erst ab dem '.$code->valid_from?->timezone(config('app.timezone'))->format('d.m.Y').'.',
default => 'Dieser Code ist abgelaufen (gültig bis '.$code->valid_until?->timezone(config('app.timezone'))->format('d.m.Y').').',
});
}
if ($code->restricted()) {
if ($user === null) {
return new DiscountResult($code, DiscountResult::LOGIN, 'Dieser Code gilt nur für freigeschaltete Konten. Melde dich an, damit wir prüfen können, ob er für dein Konto gilt.');
}
if ($this->activeRelease($code, $user, $now, $lock) === null) {
return new DiscountResult($code, DiscountResult::NO_RELEASE, 'Dieser Code ist für dein Konto nicht freigeschaltet. Er gilt nur für Konten, die der Betreiber ausdrücklich dafür freigegeben hat. Wenn du denkst, dass dir die Freigabe zusteht, wende dich an den Betreiber.');
}
}
$matching = [];
foreach ($lines as $line) {
if ($line->version !== null && $this->matches($code, $line->offer, $line->version)) {
$matching[$line->offer->id] = (int) $line->currentPriceCents;
}
}
if ($matching === []) {
return new DiscountResult($code, DiscountResult::NO_MATCH, $code->forSelection()
? 'Dieser Code gilt nur für bestimmte Angebote, und keines davon liegt in deiner Bestellung.'
: 'In deiner Bestellung gibt es keine Position, auf die der Code angewendet werden kann.');
}
$perOffer = DiscountCalculator::allocate($code->kind, $code->percent, $code->amount_cents, $matching);
$payable = array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $lines)) - array_sum($perOffer);
if ($payable < self::MIN_PAYABLE_CENTS) {
return new DiscountResult($code, DiscountResult::TOO_HIGH, 'Mit diesem Code läge der Zahlbetrag unter '.Money::format(self::MIN_PAYABLE_CENTS).'. Das ist beim Start nicht vorgesehen. Wähle zusätzlich eine weitere Position oder verzichte auf den Code.');
}
return new DiscountResult($code, DiscountResult::OK, null, $perOffer);
}
/**
* Passt die Position? Verglichen werden nur die ausdrücklich gewählten Ziele mit den unmittelbaren Positionen der
* Angebotsfassung. Ein Paket gilt nur, wenn es selbst gewählt ist; ein enthaltener Artikel macht es nicht
* rabattfähig, und ein Artikel in einem Paket macht das Angebot nicht rabattfähig.
*/
public function matches(DiscountCode $code, Offer $offer, OfferVersion $version): bool
{
if (! $code->forSelection()) {
return true;
}
$targets = $code->targets->groupBy('target_type')->map(fn ($rows) => $rows->pluck('target_id')->map(fn ($id): int => (int) $id)->all());
if (in_array($offer->id, $targets->get(DiscountCode::TARGET_OFFER, []), true)) {
return true;
}
$version->loadMissing('lines.bundleVersion');
foreach ($version->lines as $line) {
if ($line->license_article_id !== null && in_array((int) $line->license_article_id, $targets->get(DiscountCode::TARGET_ARTICLE, []), true)) {
return true;
}
if ($line->bundleVersion !== null && in_array((int) $line->bundleVersion->bundle_id, $targets->get(DiscountCode::TARGET_BUNDLE, []), true)) {
return true;
}
}
return false;
}
public function activeRelease(DiscountCode $code, User $user, ?CarbonInterface $now = null, bool $lock = false): ?DiscountRelease
{
$now ??= now();
$query = DiscountRelease::query()->where('discount_code_id', $code->id)->where('user_id', $user->id)->whereNull('revoked_at');
if ($lock) {
$query->lockForUpdate();
}
return $query->get()->first(fn (DiscountRelease $release): bool => $release->isActiveAt($now));
}
/**
* Legt einen Code an oder ändert ihn. Gleiche Prüfung für Anlegen und Bearbeiten.
*
* @param array<string, mixed> $data
* @param list<array{type: string, id: int}> $targets
*/
public function save(array $data, array $targets, ?DiscountCode $existing = null): DiscountCode
{
$code = DiscountCode::normalise((string) ($data['code'] ?? ''));
$label = trim((string) ($data['label'] ?? ''));
if (preg_match('/^[A-Z0-9][A-Z0-9_-]{2,39}$/', $code) !== 1) {
throw new DomainRuleException('Der Code besteht aus 3 bis 40 Zeichen: Buchstaben, Ziffern, Bindestrich oder Unterstrich, ohne Leerzeichen.');
}
if ($label === '') {
throw new DomainRuleException('Der Name des Codes fehlt. Er ist nur für die Verwaltung und erscheint nicht im Shop.');
}
if (DiscountCode::query()->where('code', $code)->when($existing !== null, fn ($query) => $query->whereKeyNot($existing->id))->exists()) {
throw new DomainRuleException('Diesen Code gibt es schon.');
}
$kind = (string) ($data['kind'] ?? '');
$percent = null;
$amount = null;
if ($kind === DiscountCode::PERCENT) {
$percent = (int) ($data['percent'] ?? 0);
if ($percent < 1 || $percent > 100) {
throw new DomainRuleException('Der Prozentsatz liegt zwischen 1 und 100.');
}
} elseif ($kind === DiscountCode::AMOUNT) {
$amount = Money::parse($data['amount_euro'] ?? ($data['amount_cents'] ?? null));
if ($amount === null || $amount <= 0) {
throw new DomainRuleException('Der Rabattbetrag ist ein Eurobetrag über 0,00 €.');
}
} else {
throw new DomainRuleException('Die Art des Rabatts ist Prozent oder fester Betrag.');
}
$scope = (string) ($data['scope'] ?? '');
$eligibility = (string) ($data['eligibility'] ?? '');
if (! in_array($scope, [DiscountCode::SCOPE_CART, DiscountCode::SCOPE_SELECTED], true)) {
throw new DomainRuleException('Der Geltungsbereich ist der gesamte Warenkorb oder eine Auswahl.');
}
if (! in_array($eligibility, [DiscountCode::OPEN, DiscountCode::RESTRICTED], true)) {
throw new DomainRuleException('Die Einlösung ist allgemein oder auf freigeschaltete Konten beschränkt.');
}
$targets = $this->cleanTargets($targets);
if ($scope === DiscountCode::SCOPE_SELECTED && $targets === []) {
throw new DomainRuleException('Wähle mindestens ein Angebot, einen Lizenzartikel oder ein Paket, für das der Code gilt, oder lass ihn für den gesamten Warenkorb gelten.');
}
$from = $this->date($data['valid_from'] ?? null);
$until = $this->date($data['valid_until'] ?? null);
if ($from !== null && $until !== null && $until->lessThanOrEqualTo($from)) {
throw new DomainRuleException('Das Ende der Gültigkeit liegt vor dem Beginn.');
}
return DB::transaction(function () use ($existing, $code, $label, $kind, $percent, $amount, $scope, $eligibility, $from, $until, $data, $targets): DiscountCode {
$model = $existing ?? new DiscountCode;
$model->fill([
'code' => $code,
'label' => $label,
'kind' => $kind,
'percent' => $percent,
'amount_cents' => $amount,
'scope' => $scope,
'eligibility' => $eligibility,
'valid_from' => $from,
'valid_until' => $until,
'active' => (bool) ($data['active'] ?? true),
'note' => filled($data['note'] ?? null) ? trim((string) $data['note']) : null,
]);
$model->save();
$model->targets()->delete();
if ($scope === DiscountCode::SCOPE_SELECTED) {
foreach ($targets as $target) {
$model->targets()->create(['target_type' => $target['type'], 'target_id' => $target['id']]);
}
}
return $model->load('targets');
});
}
public function setActive(DiscountCode $code, bool $active): DiscountCode
{
$code->active = $active;
$code->save();
return $code;
}
/**
* Schaltet ein Konto für genau diesen Code frei. Eine zweite aktive Freigabe desselben Kontos gibt es nicht.
*/
public function release(DiscountCode $code, User $member, ?User $actor, ?CarbonInterface $until = null, ?string $reason = null): DiscountRelease
{
if (! $code->restricted()) {
throw new DomainRuleException('Dieser Code ist allgemein einlösbar. Freigaben gibt es nur für Codes mit beschränkter Einlösung.');
}
if ($member->party_id === null) {
throw new DomainRuleException('Nur ein Mitgliedskonto kann für einen Code freigeschaltet werden.');
}
return DB::transaction(function () use ($code, $member, $actor, $until, $reason): DiscountRelease {
DiscountCode::query()->whereKey($code->id)->lockForUpdate()->firstOrFail();
if ($this->activeRelease($code, $member) !== null) {
throw new DomainRuleException('Dieses Konto ist für den Code bereits freigeschaltet.');
}
if ($until !== null && $until->lessThanOrEqualTo(now())) {
throw new DomainRuleException('Das Ende der Freigabe liegt in der Vergangenheit.');
}
return DiscountRelease::query()->create([
'discount_code_id' => $code->id,
'user_id' => $member->id,
'granted_by' => $actor?->id,
'granted_at' => now(),
'valid_until' => $until,
'reason' => filled($reason) ? trim((string) $reason) : null,
]);
});
}
/**
* Entzieht die Freigabe. Sie bleibt mit Zeitpunkt, Person und Begründung gespeichert.
*/
public function revoke(DiscountRelease $release, ?User $actor, ?string $reason = null): DiscountRelease
{
return DB::transaction(function () use ($release, $actor, $reason): DiscountRelease {
$release = DiscountRelease::query()->lockForUpdate()->findOrFail($release->id);
if ($release->revoked_at !== null) {
throw new DomainRuleException('Diese Freigabe ist bereits entzogen.');
}
$release->revoked_at = now();
$release->revoked_by = $actor?->id;
$release->reason = filled($reason) ? trim((string) $reason) : $release->reason;
$release->save();
return $release;
});
}
/**
* @param list<array{type: string, id: int}> $targets
* @return list<array{type: string, id: int}>
*/
private function cleanTargets(array $targets): array
{
$clean = [];
foreach ($targets as $target) {
$type = (string) ($target['type'] ?? '');
$id = (int) ($target['id'] ?? 0);
$exists = match ($type) {
DiscountCode::TARGET_OFFER => Offer::query()->whereKey($id)->exists(),
DiscountCode::TARGET_ARTICLE => LicenseArticle::query()->whereKey($id)->exists(),
DiscountCode::TARGET_BUNDLE => Bundle::query()->whereKey($id)->exists(),
default => false,
};
if (! $exists) {
throw new DomainRuleException('Ein gewähltes Ziel des Codes gibt es nicht (mehr).');
}
$clean[$type.':'.$id] = ['type' => $type, 'id' => $id];
}
return array_values($clean);
}
private function date(mixed $value): ?CarbonInterface
{
return filled($value) ? Carbon::parse((string) $value, config('app.timezone')) : null;
}
}