Add feature tests for shop functionality and organization purchases
Deploy Test / test (push) Successful in 1m38s
Deploy Test / deploy (push) Successful in 31s

- Implement OfferOptionAdminTest to validate offer option management, including price display, activation, and cancellation.
- Create OrganizationPurchaseTest to ensure correct handling of organization purchases, including access control and order processing.
- Add ShopProductPageTest to verify shop product listings, search functionality, and product page details.
- Introduce BuildsShop trait for seeding test data related to shop functionality.
- Implement MoneyTest to validate money parsing and formatting, ensuring correct handling of euro amounts.
This commit is contained in:
Lars committed 2026-11-21 12:06:24 +01:00
1 parent 6c8bbee363
commit 4e0760db1e
106 files changed
+4068 -76

No files matched your search

+244
View File
@@ -0,0 +1,244 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Identity\Party;
use App\Domain\Identity\PartyType;
use App\Models\User;
/**
* Sitzungsgebundener Mehrangebotswarenkorb (Etappe 1). Er bleibt in derselben Browsersitzung über Anmeldung,
* Registrierung und E-Mail-Bestätigung erhalten. Je Option gibt es genau eine Position. Optionen derselben Produktseite
* (gleiche Komposition) sind Alternativen und werden nur nach ausdrücklichem Wechsel ersetzt.
* Der Warenkorb reserviert weder Preis noch Konditionen; er merkt sich, was der Käufer gesehen hat.
*/
class Cart
{
public const KEY = 'shop.cart';
public const ADDED = 'added';
public const PRESENT = 'present';
public const ALTERNATIVE = 'alternative';
public const UNAVAILABLE = 'unavailable';
public function __construct(
private readonly OwnershipCheck $ownership,
private readonly OrderHolders $holders,
private readonly OfferService $offers,
) {}
/**
* @return array<int, array{version_id: int, price_cents: int}>
*/
public function items(): array
{
return (array) session()->get(self::KEY, []);
}
public function count(): int
{
return count($this->items());
}
public function has(Offer $offer): bool
{
return isset($this->items()[$offer->id]);
}
/**
* Die bereits enthaltene Alternative derselben Produktseite, falls vorhanden.
*/
public function alternativeTo(Offer $offer): ?Offer
{
if ($offer->composition_id === null) {
return null;
}
$ids = array_diff(array_keys($this->items()), [$offer->id]);
return $ids === [] ? null : Offer::query()
->whereIn('id', $ids)
->where('composition_id', $offer->composition_id)
->first();
}
public function add(Offer $offer): string
{
$version = $this->purchasable($offer);
if ($version === null) {
return self::UNAVAILABLE;
}
if ($this->has($offer)) {
return self::PRESENT;
}
if ($this->alternativeTo($offer) !== null) {
return self::ALTERNATIVE;
}
$this->put($offer, $version);
return self::ADDED;
}
/**
* Ausdrücklicher Wechsel: die Alternative wird durch die gewählte Option ersetzt.
*/
public function switchTo(Offer $offer): bool
{
$version = $this->purchasable($offer);
if ($version === null) {
return false;
}
$alternative = $this->alternativeTo($offer);
if ($alternative !== null) {
$this->remove($alternative);
}
$this->put($offer, $version);
return true;
}
public function remove(Offer $offer): void
{
$items = $this->items();
unset($items[$offer->id]);
session()->put(self::KEY, $items);
}
/**
* Der Käufer übernimmt Preis und Fassung, die der Shop jetzt zeigt.
*/
public function acceptCurrent(Offer $offer): void
{
$version = $this->purchasable($offer);
if ($version !== null && $this->has($offer)) {
$this->put($offer, $version);
}
}
public function clear(): void
{
session()->forget(self::KEY);
}
/**
* Serverseitige Prüfung: aktuelle Fassung, Preis, Kaufbarkeit, passende Inhaberart, vorhandene Rechte.
*/
public function review(?User $user = null, ?int $holderPartyId = null): CartReview
{
$offers = Offer::query()
->whereIn('id', array_keys($this->items()))
->with('composition')
->get()
->keyBy('id');
$versions = [];
foreach ($this->items() as $offerId => $item) {
$offer = $offers->get($offerId);
if ($offer !== null) {
$versions[$offerId] = $this->purchasable($offer);
}
}
$holder = $user === null ? null : $this->holderFor($user, $holderPartyId, $versions);
$lines = [];
foreach ($this->items() as $offerId => $item) {
$offer = $offers->get($offerId);
if ($offer === null) {
continue;
}
$version = $versions[$offerId] ?? null;
$seen = (int) $item['price_cents'];
if ($version === null) {
$lines[] = new CartLine($offer, null, CartLine::WITHDRAWN, $seen, null,
'Diese Option ist nicht mehr erhältlich. Entferne sie, um mit den übrigen Positionen fortzufahren.');
continue;
}
$current = (int) $version->price_cents;
if ($holder !== null && ! $this->suitsHolder($version, $holder)) {
$lines[] = new CartLine($offer, $version, CartLine::WRONG_HOLDER, $seen, $current,
$version->holder_kind === 'organisation'
? 'Diese Option ist für Organisationen. Bestelle als Verein oder entferne sie.'
: 'Diese Option ist für Privatpersonen. Bestelle als Privatperson oder entferne sie.');
continue;
}
if ($holder !== null && $this->ownership->covers($holder, $version)) {
$lines[] = new CartLine($offer, $version, CartLine::OWNED, $seen, $current);
continue;
}
if ($current !== $seen) {
$lines[] = new CartLine($offer, $version, CartLine::PRICE_CHANGED, $seen, $current);
} elseif ((int) $item['version_id'] !== $version->id) {
$lines[] = new CartLine($offer, $version, CartLine::TERMS_CHANGED, $seen, $current,
'Die Bedingungen dieser Option wurden aktualisiert. Bitte prüfe die Übersicht.');
} else {
$lines[] = new CartLine($offer, $version, CartLine::OK, $seen, $current);
}
}
return new CartReview($lines, $holder);
}
/**
* Die aktive, als Kauf angebotene Fassung der Option; sonst null (nicht kaufbar oder zurückgezogen).
*/
public function purchasable(Offer $offer): ?OfferVersion
{
return $this->offers->purchasableVersion($offer);
}
private function put(Offer $offer, OfferVersion $version): void
{
$items = $this->items();
$items[$offer->id] = ['version_id' => $version->id, 'price_cents' => (int) $version->price_cents];
session()->put(self::KEY, $items);
}
/**
* @param array<int, OfferVersion|null> $versions
*/
private function holderFor(User $user, ?int $partyId, array $versions): ?Party
{
$onlyOrganisations = $versions !== [] && collect($versions)
->filter()
->every(fn (OfferVersion $version): bool => $version->holder_kind === 'organisation');
try {
return $this->holders->resolve($user, $partyId, $onlyOrganisations);
} catch (DomainRuleException) {
return null;
}
}
private function suitsHolder(OfferVersion $version, Party $holder): bool
{
return ($version->holder_kind === 'organisation') === ($holder->type === PartyType::Organisation);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferVersion;
/**
* Eine Position des Warenkorbs mit dem Ergebnis der serverseitigen Prüfung.
*/
final class CartLine
{
public const OK = 'ok';
public const PRICE_CHANGED = 'preis_geaendert';
public const TERMS_CHANGED = 'bedingungen_geaendert';
public const WITHDRAWN = 'zurueckgezogen';
public const OWNED = 'bereits_erworben';
public const WRONG_HOLDER = 'falscher_inhaber';
public function __construct(
public readonly Offer $offer,
public readonly ?OfferVersion $version,
public readonly string $state,
public readonly int $seenPriceCents,
public readonly ?int $currentPriceCents,
public readonly ?string $note = null,
) {}
/** Geht in Summe und Bestellung ein. */
public function orderable(): bool
{
return in_array($this->state, [self::OK, self::PRICE_CHANGED, self::TERMS_CHANGED], true);
}
/** Verhindert den Abschluss, bis der Käufer die Position selbst entfernt oder den Inhaber wechselt. */
public function blocks(): bool
{
return in_array($this->state, [self::WITHDRAWN, self::WRONG_HOLDER], true);
}
public function title(): string
{
$composition = $this->offer->composition;
return $composition !== null
? (string) ($composition->display_title ?: $composition->designation)
: (string) $this->offer->name;
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Identity\Party;
/**
* Prüfergebnis des Warenkorbs für einen vorgesehenen Lizenzinhaber. Die Prüfsumme bindet die Bestellung an genau
* diese Übersicht: Inhaber, Fassung und Preis jeder Position samt Zustand, auch der ausgeschlossenen.
*/
final class CartReview
{
/**
* @param list<CartLine> $lines
*/
public function __construct(
public readonly array $lines,
public readonly ?Party $holder,
) {}
/** @return list<CartLine> */
public function orderable(): array
{
return array_values(array_filter($this->lines, fn (CartLine $line): bool => $line->orderable()));
}
public function totalCents(): int
{
return array_sum(array_map(fn (CartLine $line): int => (int) $line->currentPriceCents, $this->orderable()));
}
public function blocked(): bool
{
foreach ($this->lines as $line) {
if ($line->blocks()) {
return true;
}
}
return false;
}
public function empty(): bool
{
return $this->orderable() === [];
}
public function canOrder(): bool
{
return $this->holder !== null && ! $this->blocked() && ! $this->empty();
}
public function digest(): string
{
$parts = [];
foreach ($this->lines as $line) {
$parts[] = $line->offer->id.':'.($line->version?->id ?? 0).':'.$line->currentPriceCents.':'.$line->state;
}
sort($parts);
return hash('sha256', ($this->holder?->id ?? 0).'|'.implode(',', $parts));
}
}
+102 -28
View File
@@ -5,11 +5,13 @@
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferVersion;
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\Mail\OrderConfirmed;
use App\Models\User;
use Illuminate\Support\Facades\DB;
@@ -20,13 +22,15 @@ class Checkout
public function __construct(
private readonly GrantIssuer $grants,
private readonly OfferService $offers,
private readonly OrderHolders $holders,
) {}
/**
* Einzelkauf einer Option als Person (bestehender Weg, ohne Warenkorb).
*/
public function place(User $user, Offer $offer): Order
{
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
}
$this->assertActive($user);
$version = $this->offers->currentActiveVersion($offer);
@@ -38,20 +42,78 @@ public function place(User $user, Offer $offer): Order
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
}
return DB::transaction(function () use ($user, $offer, $version): Order {
$order = Order::query()->create([
'user_id' => $user->id,
'party_id' => $user->party_id,
'status' => 'offen',
'holder_kind' => 'person',
]);
$holder = $this->holders->resolve($user, null);
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]]));
}
/**
* Bestellung aus dem Warenkorb, erst nach serverseitiger Prüfung. Die Prüfsumme bindet die Bestellung an die
* Übersicht, die der Käufer gesehen hat: Hat sich Preis, Fassung oder Bedingung seither geändert, entsteht keine
* 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
{
$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.
Offer::query()->whereIn('id', array_keys($cart->items()))->orderBy('id')->lockForUpdate()->get();
$review = $cart->review($user, $holderPartyId);
if ($review->holder === null) {
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
}
if (! hash_equals($review->digest(), $digest)) {
throw new StaleOverview('Die Übersicht hat sich geändert. Bitte prüfe die aktualisierte Bestellübersicht.');
}
if ($review->blocked()) {
throw new DomainRuleException('Entferne zuerst die Positionen, die nicht bestellt werden können.');
}
if ($review->empty()) {
throw new DomainRuleException('Es gibt nichts zu bestellen. Alle Positionen sind bereits erworben.');
}
$pairs = array_map(fn (CartLine $line): array => [$line->offer, $line->version], $review->orderable());
return $this->createOrder($user, $review->holder, $pairs);
});
$cart->clear();
return $order;
}
/**
* @param list<array{0: Offer, 1: OfferVersion}> $pairs
*/
private function createOrder(User $user, Party $holder, array $pairs): Order
{
$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)),
'currency' => 'EUR',
]);
foreach ($pairs as [$offer, $version]) {
$line = $order->lines()->create([
'offer_version_id' => $version->id,
'offer_name' => $offer->name,
'price_cents' => $version->price_cents,
'currency' => 'EUR',
'term_rule' => $version->term_rule,
'update_promise' => $version->update_promise,
'holder_kind' => $version->holder_kind,
'tax_class' => $version->tax_class,
'grant_kind' => $version->grant_kind,
'holder_party_id' => $holder->id,
]);
$version->load('resolvedScopes.rights');
@@ -66,11 +128,15 @@ public function place(User $user, Offer $offer): Order
],
]);
}
}
return $order->load('lines.scopeItems');
});
return $order->load('lines.scopeItems');
}
/**
* Freischaltung nach bestätigter Testzahlung: alle Bestellpositionen aus ihrem festgehaltenen Umfang, in einer
* Transaktion. Wiederholte Bestätigung ist wirkungslos; ein Fehler hinterlässt weder Zahlung noch Rechte.
*/
public function confirmTestPayment(Order $order, string $reference): Order
{
$this->assertTestDriver();
@@ -100,14 +166,12 @@ public function confirmTestPayment(Order $order, string $reference): Order
$order->status = 'bezahlt';
$order->save();
$paidNow = true;
$line = $order->lines()->firstOrFail();
$this->grants->issue(
$order->user,
$line->offerVersion,
AcquisitionType::Bestellposition,
'order_line',
$line->id,
);
$actor = User::query()->findOrFail($order->user_id);
foreach ($order->lines()->orderBy('id')->get() as $line) {
$holder = Party::query()->findOrFail($line->holder_party_id ?? $order->party_id);
$this->grants->issueFromOrderLine($line, $holder, $actor);
}
return $order->load('lines', 'payments');
});
@@ -142,6 +206,10 @@ 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.
*/
public function refund(Order $order, string $reason): Order
{
$reason = trim($reason);
@@ -157,15 +225,14 @@ public function refund(Order $order, string $reason): Order
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
}
$line = $order->lines()->firstOrFail();
$acquisition = Acquisition::query()->where([
'type' => AcquisitionType::Bestellposition,
'reference_type' => 'order_line',
'reference_id' => $line->id,
])->first();
foreach ($order->lines()->orderBy('id')->get() as $line) {
$acquisition = Acquisition::query()->where([
'type' => AcquisitionType::Bestellposition,
'reference_type' => 'order_line',
'reference_id' => $line->id,
])->first();
if ($acquisition !== null) {
foreach ($acquisition->grants as $grant) {
foreach ($acquisition?->grants ?? [] as $grant) {
if ($grant->status === GrantStatus::Aktiv) {
$grant->status = GrantStatus::Widerrufen;
$grant->status_reason = $reason;
@@ -182,6 +249,13 @@ public function refund(Order $order, string $reason): Order
});
}
private function assertActive(User $user): void
{
if ($user->status !== AccountStatus::Aktiv || $user->party_id === null) {
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
}
}
private function assertTestDriver(): void
{
if (app()->isProduction() || config('services.payment.driver') !== 'test') {
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
/**
* Beträge werden als ganze Cent gespeichert und in Euro angezeigt und eingegeben (deutsches Format).
*/
final class Money
{
/** Obergrenze eines Preises (1.000.000 €), weit unter dem Wertebereich der Datenbank. */
public const MAX_CENTS = 100_000_000;
public static function format(?int $cents): string
{
return $cents === null ? '–' : number_format($cents / 100, 2, ',', '.').' €';
}
/**
* Euro-Eingabe („12,50“, „1.299“, „5“) als Cent. Leere Eingabe ergibt null.
*/
public static function parse(string|int|float|null $input): ?int
{
if ($input === null) {
return null;
}
$text = trim((string) $input);
if ($text === '') {
return null;
}
$text = str_replace([' ', '€'], '', $text);
if (str_contains($text, ',')) {
$text = str_replace('.', '', $text);
$text = str_replace(',', '.', $text);
} elseif (preg_match('/^\d{1,3}(\.\d{3})+$/', $text) === 1) {
$text = str_replace('.', '', $text);
}
if (preg_match('/^\d+(\.\d{1,2})?$/', $text) !== 1) {
throw new DomainRuleException('Der Preis ist kein gültiger Eurobetrag, zum Beispiel 12,50.');
}
$cents = (int) round(((float) $text) * 100);
if ($cents > self::MAX_CENTS) {
throw new DomainRuleException('Der Preis ist zu hoch. Zulässig sind höchstens '.self::format(self::MAX_CENTS).'.');
}
return $cents;
}
}
+2
View File
@@ -15,6 +15,8 @@ class Order extends Model
'party_id',
'status',
'holder_kind',
'total_cents',
'currency',
];
public function user(): BelongsTo
+75
View File
@@ -0,0 +1,75 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Identity\Membership;
use App\Domain\Identity\Party;
use App\Domain\Identity\PartyType;
use App\Models\User;
use Illuminate\Support\Collection;
/**
* Für wen ein Konto bestellen darf: für sich selbst (Person) und für Organisationen, bei denen es eine aktive
* Mitgliedschaft mit Bestellberechtigung hat. Eine Bestellung hat genau einen Lizenzinhaber.
*/
class OrderHolders
{
/**
* @return Collection<int, Party>
*/
public function for(User $user): Collection
{
$holders = collect();
if ($user->party_id !== null) {
$person = Party::query()->find($user->party_id);
if ($person !== null) {
$holders->push($person);
}
}
$organisations = Membership::query()
->active()
->where('user_id', $user->id)
->where('may_order', true)
->with('organisation')
->orderBy('id')
->get()
->map(fn (Membership $membership): ?Party => $membership->organisation)
->filter(fn (?Party $party): bool => $party !== null && $party->type === PartyType::Organisation);
return $holders->concat($organisations)->values();
}
/**
* Der gewählte Inhaber; ohne Wahl die Person, bei Angeboten nur für Organisationen die erste Organisation.
*/
public function resolve(User $user, ?int $partyId, bool $preferOrganisation = false): Party
{
$holders = $this->for($user);
if ($partyId !== null) {
$chosen = $holders->first(fn (Party $party): bool => $party->id === $partyId);
if ($chosen === null) {
throw new DomainRuleException('Für diesen Lizenzinhaber ist das Konto nicht bestellberechtigt.');
}
return $chosen;
}
if ($preferOrganisation) {
$organisation = $holders->first(fn (Party $party): bool => $party->type === PartyType::Organisation);
if ($organisation !== null) {
return $organisation;
}
}
$person = $holders->first(fn (Party $party): bool => $party->type === PartyType::Person);
return $person ?? throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
}
}
+10
View File
@@ -3,6 +3,7 @@
namespace App\Domain\Commerce;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Identity\Party;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
@@ -17,6 +18,10 @@ class OrderLine extends Model
'term_rule',
'update_promise',
'holder_kind',
'currency',
'tax_class',
'grant_kind',
'holder_party_id',
];
public function order(): BelongsTo
@@ -24,6 +29,11 @@ public function order(): BelongsTo
return $this->belongsTo(Order::class);
}
public function holder(): BelongsTo
{
return $this->belongsTo(Party::class, 'holder_party_id');
}
public function offerVersion(): BelongsTo
{
return $this->belongsTo(OfferVersion::class);
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\OfferVersion;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Domain\Identity\Party;
/**
* „Bereits erworben“ (FACH-59): Der vorgesehene Lizenzinhaber hat bereits eine gültige Lizenz mit demselben Umfang
* und denselben Nutzungsrechten. Maßgeblich ist genau ein Erwerb, der jeden Umfangsposten der Angebotsfassung mit
* gleichem Zweck, gleichen Fähigkeiten und gleichen Optionen trägt. Rechte mehrerer Erwerbe werden nicht zu einer
* neuen Lizenz kombiniert. Alle Erwerbsarten zählen (Kauf, freier Abruf, manuelle Vergabe), sofern aktiv und gültig.
*/
class OwnershipCheck
{
public function covers(Party $holder, OfferVersion $version): bool
{
$needed = $this->needed($version);
if ($needed === []) {
return false;
}
$now = now();
$byAcquisition = Grant::query()
->where('status', GrantStatus::Aktiv)
->whereHas('acquisition', fn ($query) => $query->where('party_id', $holder->id))
->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');
foreach ($byAcquisition as $grants) {
$have = [];
foreach ($grants as $grant) {
$have[$grant->license_article_id.'|'.$this->fingerprint($grant->rights_snapshot ?? [])] = true;
}
if (array_diff_key($needed, $have) === []) {
return true;
}
}
return false;
}
/**
* @return array<string, true>
*/
private function needed(OfferVersion $version): array
{
$needed = [];
$version->loadMissing('resolvedScopes.rights');
foreach ($version->resolvedScopes as $scope) {
$needed[$scope->license_article_id.'|'.$this->fingerprint([
'purpose' => $scope->rights->purpose,
'capabilities' => $scope->rights->capabilities,
'options' => $scope->rights->options ?? [],
])] = true;
}
return $needed;
}
/**
* Reihenfolge von Schlüsseln und Aktionen spielt keine Rolle.
*
* @param array<string, mixed> $rights
*/
private function fingerprint(array $rights): string
{
$capabilities = [];
foreach ((array) ($rights['capabilities'] ?? []) as $class => $actions) {
$actions = array_values(array_unique((array) $actions));
sort($actions);
$capabilities[(string) $class] = $actions;
}
ksort($capabilities);
$options = (array) ($rights['options'] ?? []);
ksort($options);
return md5(json_encode([
'purpose' => (string) ($rights['purpose'] ?? ''),
'capabilities' => $capabilities,
'options' => $options,
], JSON_THROW_ON_ERROR));
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\Offer;
use App\Domain\Catalog\OfferService;
use App\Domain\Catalog\OfferVersion;
use App\Filament\Support\CatalogLabels;
/**
* Kaufbare Lizenzoptionen einer Produktseite aus dem veröffentlichten Katalog: aktive Angebotsfassungen mit Preis,
* Eignung, Laufzeit, Umfang und Nutzungsrechten. Die Seite selbst (Titel, Beschreibung, Struktur) kommt aus der
* zur Anzeige freigegebenen Komposition; hier entsteht kein zweiter Text.
*/
class ProductOptions
{
public function __construct(private readonly OfferService $offers) {}
/**
* @return list<array<string, mixed>>
*/
public function forComposition(Composition $composition): array
{
$options = [];
foreach (Offer::query()->where('composition_id', $composition->id)->orderBy('id')->get() as $offer) {
$version = $this->offers->purchasableVersion($offer);
if ($version !== null) {
$options[] = $this->describe($offer, $version);
}
}
return $options;
}
/**
* Zeilen für Shop-Suche und Kacheln: je Komposition die günstigste Option.
*
* @return array<int, array{from_cents: int, count: int}>
*/
public function summaries(): array
{
$summary = [];
foreach (Offer::query()->whereNotNull('composition_id')->orderBy('id')->get() as $offer) {
$version = $this->offers->purchasableVersion($offer);
if ($version === null) {
continue;
}
$current = $summary[$offer->composition_id] ?? ['from_cents' => PHP_INT_MAX, 'count' => 0];
$summary[$offer->composition_id] = [
'from_cents' => min($current['from_cents'], (int) $version->price_cents),
'count' => $current['count'] + 1,
];
}
return $summary;
}
/**
* @return array<string, mixed>
*/
public function describe(Offer $offer, OfferVersion $version): array
{
$version->loadMissing('resolvedScopes.article', 'resolvedScopes.rights');
$scope = [];
foreach ($version->resolvedScopes as $item) {
$faehigkeiten = CatalogLabels::faehigkeiten($item->rights?->capabilities);
$scope[] = [
'article' => $this->articleTitle($item->article),
'purpose' => CatalogLabels::zweck($item->rights?->purpose),
'rights' => $faehigkeiten,
];
}
return [
'offer' => $offer,
'version' => $version,
'name' => $offer->optionName(),
'price_cents' => (int) $version->price_cents,
'price' => Money::format((int) $version->price_cents),
'for' => $version->holder_kind === 'organisation' ? 'Organisationen und Vereine' : 'Privatpersonen',
'holder_kind' => $version->holder_kind,
'term' => self::termLabel($version),
'scope' => $scope,
];
}
public static function termLabel(OfferVersion $version): string
{
return match ($version->term_rule) {
'dauerhaft' => 'Dauerhaft nutzbar',
'befristet' => 'Befristet',
'solange_angebot_aktiv' => 'Solange das Angebot aktiv ist',
'periodisch' => 'Laufend, periodisch',
default => (string) $version->term_rule,
};
}
public function articleTitle(?LicenseArticle $article): string
{
if ($article === null) {
return '–';
}
return (string) ($article->display_title ?: $article->working_title ?: $article->code);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
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.
*/
final class Shop
{
public static function enabled(): bool
{
return ! app()->isProduction() && config('services.payment.driver') === 'test';
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Domain\Commerce;
use App\Domain\Catalog\DomainRuleException;
/**
* Preis oder bindende Bedingungen haben sich nach Anzeige der Bestellübersicht geändert. Es entsteht keine
* Bestellung; der Käufer sieht zuerst die aktualisierte Übersicht (FACH-59).
*/
class StaleOverview extends DomainRuleException {}