Führe ein unveränderliches Zahlungsjournal mit Ansicht und CSV-Export ein
Jede Zahlung und jede Erstattung wird in derselben Transaktion wie der Bestellstatus unveränderlich gebucht: Zeitpunkt, Betrag, Beleg beim Anbieter (Session, pi_, re_), handelnde Person, Begründung und Zahler samt Rechnungsadresse zum Zeitpunkt. Testzahlungen zählen nie als Umsatz. Verwaltung: Verkauf, Einnahmen und Erstattungen mit Zeitraum, Summen und Export. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6518d1b80f
commit
fe39e1efb6
15 files changed
+1485
-22
No files matched your search
@@ -17,6 +17,7 @@
|
||||
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;
|
||||
|
||||
@@ -26,6 +27,7 @@ public function __construct(
|
||||
private readonly GrantIssuer $grants,
|
||||
private readonly OfferService $offers,
|
||||
private readonly OrderHolders $holders,
|
||||
private readonly PaymentJournal $journal,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -187,14 +189,16 @@ 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') - $order->lines()->sum('discount_cents'));
|
||||
|
||||
@@ -202,15 +206,17 @@ public function confirmProviderPayment(Order $order, string $provider, string $r
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* (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): Order
|
||||
public function confirmInvoicePayment(Order $order, string $reference, User $actor, string|CarbonInterface|null $receivedOn = null): Order
|
||||
{
|
||||
$order->refresh();
|
||||
|
||||
@@ -218,10 +224,12 @@ public function confirmInvoicePayment(Order $order, string $reference, User $act
|
||||
throw new DomainRuleException('Nur eine Bestellung auf Rechnung wird manuell als bezahlt bestätigt.');
|
||||
}
|
||||
|
||||
return $this->settle($order, 'ueberweisung', 'rechnung-'.trim($reference), $actor);
|
||||
$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 = null): Order
|
||||
private function settle(Order $order, string $provider, string $reference, ?User $confirmedBy, CarbonInterface $occurredAt, bool $live, ?string $paymentIntent = null): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
@@ -230,7 +238,7 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, $confirmedBy, &$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') {
|
||||
@@ -242,10 +250,14 @@ private function settle(Order $order, string $provider, string $reference, ?User
|
||||
}
|
||||
|
||||
// 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', 'amount_cents' => $order->payable(), 'confirmed_by' => $confirmedBy?->id],
|
||||
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;
|
||||
@@ -295,8 +307,11 @@ public function failTestPayment(Order $order, string $reference): Order
|
||||
* (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, ?StripeGateway $stripe = null): 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);
|
||||
|
||||
@@ -306,12 +321,15 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
|
||||
$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) {
|
||||
($stripe ?? app(StripeGateway::class))->refund($current, $stripePayment, $reason);
|
||||
$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): Order {
|
||||
return DB::transaction(function () use ($order, $reason, $actor, $manualAt, $reference, $booking): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status !== 'bezahlt') {
|
||||
@@ -334,6 +352,16 @@ public function refund(Order $order, string $reason, ?StripeGateway $stripe = nu
|
||||
}
|
||||
}
|
||||
|
||||
$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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
<?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'): Collection
|
||||
{
|
||||
return LedgerEntry::query()
|
||||
->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)])
|
||||
->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();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int}
|
||||
*/
|
||||
public static function totals(Collection $entries): array
|
||||
{
|
||||
$in = $entries->where('kind', LedgerEntry::KIND_PAYMENT);
|
||||
$out = $entries->where('kind', LedgerEntry::KIND_REFUND);
|
||||
|
||||
return [
|
||||
'eingang' => (int) $in->sum('amount_cents'),
|
||||
'erstattung' => (int) abs($out->sum('amount_cents')),
|
||||
'saldo' => (int) $entries->sum('amount_cents'),
|
||||
'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
|
||||
*/
|
||||
public static function csv(Collection $entries): 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',
|
||||
];
|
||||
$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'),
|
||||
];
|
||||
}
|
||||
|
||||
$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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
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;
|
||||
@@ -121,9 +122,12 @@ public function assertAllowed(): void
|
||||
/**
|
||||
* 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).
|
||||
* 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): void
|
||||
public function refund(Order $order, Payment $payment, string $reason): array
|
||||
{
|
||||
$this->assertAllowed();
|
||||
$intent = (string) $payment->provider_payment_ref;
|
||||
@@ -148,8 +152,25 @@ public function refund(Order $order, Payment $payment, string $reason): void
|
||||
]);
|
||||
|
||||
$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,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user