CI Feature / test (push) Successful in 2m52s
Eine Bestellung auf Rechnung lässt sich auch mit dem Stripe-Treiber nicht per Karte bezahlen; der Betreiber, der den Zahlungseingang bestätigt, wird an der Zahlung festgehalten; im Livebetrieb ist der alte Einzelkauf ohne Pflichtangaben gesperrt und placeFromCart verlangt die Zustimmungen. ADR-47, Domänenmodell, Lizenzlogik, Kernabläufe, Szenarien, Fachanforderungen und DEPLOYMENT nachgeführt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
389 lines
16 KiB
PHP
389 lines
16 KiB
PHP
<?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\Commerce\Discount\DiscountCode;
|
|
use App\Domain\Commerce\Stripe\StripeGateway;
|
|
use App\Domain\Entitlement\Acquisition;
|
|
use App\Domain\Entitlement\AcquisitionType;
|
|
use App\Domain\Entitlement\GrantIssuer;
|
|
use App\Domain\Entitlement\GrantStatus;
|
|
use App\Domain\Identity\AccountStatus;
|
|
use App\Domain\Identity\Party;
|
|
use App\Domain\Identity\PartyType;
|
|
use App\Mail\OrderConfirmed;
|
|
use App\Models\User;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Mail;
|
|
|
|
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
|
|
{
|
|
$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') {
|
|
throw new DomainRuleException('Dieses Angebot kann nicht als persönlicher Kauf bestellt werden.');
|
|
}
|
|
|
|
if ($version->price_cents === null) {
|
|
throw new DomainRuleException('Der Kauf braucht einen Preis an der Angebotsfassung.');
|
|
}
|
|
|
|
$holder = $this->holders->resolve($user, null);
|
|
|
|
return DB::transaction(fn (): Order => $this->createOrder($user, $holder, [[$offer, $version]], null, null, Shop::driver() === 'stripe' ? 'stripe' : 'test'));
|
|
}
|
|
|
|
/**
|
|
* 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, ?array $consent = null, ?string $paymentMethod = null): Order
|
|
{
|
|
$this->assertActive($user);
|
|
|
|
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();
|
|
$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.');
|
|
}
|
|
|
|
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.');
|
|
}
|
|
|
|
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, $review, $consent === null ? null : SalesTerms::proof($consent), $method);
|
|
});
|
|
|
|
$cart->clear();
|
|
|
|
return $order;
|
|
}
|
|
|
|
/**
|
|
* @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, ?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,
|
|
'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]) {
|
|
$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,
|
|
'licence_scope' => $version->licence_scope,
|
|
'trainer_count' => $version->trainer_count,
|
|
'discount_cents' => $discountCents > 0 ? $discount->forOffer($offer->id) : 0,
|
|
]);
|
|
$version->load('resolvedScopes.rights');
|
|
|
|
foreach ($version->resolvedScopes as $scope) {
|
|
$line->scopeItems()->create([
|
|
'license_article_id' => $scope->license_article_id,
|
|
'rights_profile_version_id' => $scope->rights_profile_version_id,
|
|
'rights_snapshot' => [
|
|
'purpose' => $scope->rights->purpose,
|
|
'capabilities' => $scope->rights->capabilities,
|
|
'options' => $scope->rights->options ?? [],
|
|
],
|
|
]);
|
|
}
|
|
}
|
|
|
|
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();
|
|
$this->assertTestOrder($order);
|
|
|
|
return $this->settle($order, 'test', $reference);
|
|
}
|
|
|
|
/**
|
|
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
|
* Bestellung. Wiederholte Meldungen sind wirkungslos.
|
|
*/
|
|
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): Order
|
|
{
|
|
$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);
|
|
}
|
|
|
|
/**
|
|
* Kauf auf Rechnung (PAY-006): Der Betreiber hat die Rechnung manuell erstellt und bestätigt den Zahlungseingang.
|
|
* Nur für Bestellungen mit Zahlungsweg „Rechnung“; das Mitglied kann das nicht selbst auslösen. Die Referenz
|
|
* (Rechnungsnummer oder Buchung) wird an der Zahlung festgehalten.
|
|
*/
|
|
public function confirmInvoicePayment(Order $order, string $reference, User $actor): Order
|
|
{
|
|
$order->refresh();
|
|
|
|
if ($order->payment_method !== 'rechnung') {
|
|
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
|
}
|
|
|
|
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor);
|
|
}
|
|
|
|
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy = null): Order
|
|
{
|
|
$reference = trim($reference);
|
|
|
|
if ($reference === '') {
|
|
throw new DomainRuleException('Die Zahlungsreferenz fehlt.');
|
|
}
|
|
|
|
$paidNow = false;
|
|
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, &$paidNow): Order {
|
|
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
|
|
|
if ($order->status === 'bezahlt') {
|
|
return $order->load('lines', 'payments');
|
|
}
|
|
|
|
if ($order->status !== 'offen') {
|
|
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
|
}
|
|
|
|
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
|
$order->payments()->updateOrCreate(
|
|
['provider_reference' => $reference],
|
|
['provider' => $provider, 'status' => 'bestaetigt', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id],
|
|
);
|
|
$order->status = 'bezahlt';
|
|
$order->save();
|
|
$paidNow = true;
|
|
$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');
|
|
});
|
|
|
|
if ($paidNow) {
|
|
Mail::to($order->user)->send(new OrderConfirmed($order));
|
|
}
|
|
|
|
return $order;
|
|
}
|
|
|
|
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);
|
|
|
|
if ($order->status !== 'offen') {
|
|
return $order;
|
|
}
|
|
|
|
$order->payments()->create([
|
|
'provider' => 'test',
|
|
'status' => 'fehlgeschlagen',
|
|
'provider_reference' => $reference,
|
|
]);
|
|
$order->status = 'fehlgeschlagen';
|
|
$order->save();
|
|
|
|
return $order;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Vollerstattung: widerruft die Berechtigungen aller Positionen dieser Bestellung. Andere Erwerbsquellen
|
|
* (kostenlose Vergabe, frühere Käufe) bleiben unberührt. Bundles sind Rückgabeeinheiten; freiwillige
|
|
* Teilerstattungen gibt es zum Start nicht. Bei einer Zahlung über Stripe wird die Rückzahlung zuerst bei Stripe
|
|
* veranlasst; erst wenn Stripe sie annimmt, werden Rechte entzogen. Wirkt sie dort nicht, bleibt alles unverändert.
|
|
*/
|
|
public function refund(Order $order, string $reason, ?StripeGateway $stripe = null): Order
|
|
{
|
|
$reason = trim($reason);
|
|
|
|
if ($reason === '') {
|
|
throw new DomainRuleException('Eine Erstattung braucht eine Begründung.');
|
|
}
|
|
|
|
$current = Order::query()->findOrFail($order->id);
|
|
$stripePayment = $current->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->latest('id')->first();
|
|
|
|
if ($current->status === 'bezahlt' && $stripePayment !== null) {
|
|
($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
|
}
|
|
|
|
return DB::transaction(function () use ($order, $reason): Order {
|
|
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
|
|
|
if ($order->status !== 'bezahlt') {
|
|
throw new DomainRuleException('Nur eine bezahlte Bestellung kann erstattet werden.');
|
|
}
|
|
|
|
foreach ($order->lines()->orderBy('id')->get() as $line) {
|
|
$acquisition = Acquisition::query()->where([
|
|
'type' => AcquisitionType::Bestellposition,
|
|
'reference_type' => 'order_line',
|
|
'reference_id' => $line->id,
|
|
])->first();
|
|
|
|
foreach ($acquisition?->grants ?? [] as $grant) {
|
|
if ($grant->status === GrantStatus::Aktiv) {
|
|
$grant->status = GrantStatus::Widerrufen;
|
|
$grant->status_reason = $reason;
|
|
$grant->save();
|
|
}
|
|
}
|
|
}
|
|
|
|
$order->payments()->where('status', 'bestaetigt')->update(['status' => 'erstattet']);
|
|
$order->status = 'erstattet';
|
|
$order->save();
|
|
|
|
return $order->refresh();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 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) {
|
|
throw new DomainRuleException('Nur ein aktives Mitglied kann kaufen.');
|
|
}
|
|
}
|
|
|
|
/** 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') {
|
|
throw new DomainRuleException('Der Testzahlungsweg ist nicht aktiv.');
|
|
}
|
|
}
|
|
}
|