Führe ein unveränderliches Zahlungsjournal mit Ansicht und CSV-Export ein
CI Feature / test (push) Successful in 3m41s
Deploy Test / test (push) Successful in 3m34s
Deploy Test / deploy (push) Successful in 46s

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:
LarsandClaude Sonnet 5.5 committed 2026-11-23 07:34:41 +01:00
1 parent 6518d1b80f
commit fe39e1efb6
15 files changed
+1485 -22

No files matched your search

+42 -14
View File
@@ -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();
+57
View File
@@ -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;
}
}
+320
View File
@@ -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(),
];
}
}
+23 -2
View File
@@ -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,
];
}
/**
+160
View File
@@ -0,0 +1,160 @@
<?php
namespace App\Filament\Pages;
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';
#[Url(as: 'betrieb')]
public string $betrieb = 'echt';
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->normalize();
}
/** 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 : 'echt';
$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);
$entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb);
return [
'zeitraum' => $this->zeitraumName(),
'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT),
'anzahl' => $entries->count(),
'summen' => PaymentJournal::totals($entries),
'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();
$entries = app(PaymentJournal::class)->entries($from, $to, $this->art, $this->weg, $this->betrieb);
$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'
}.'.csv';
return response()->streamDownload(function () use ($entries): void {
echo PaymentJournal::csv($entries);
}, $name, ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}
@@ -4,14 +4,17 @@
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;
@@ -66,6 +69,11 @@ public function infolist(Schema $schema): Schema
])->columns(1);
}
private function hasStripePayment(): bool
{
return $this->order()->payments()->where('provider', 'stripe')->where('status', 'bestaetigt')->exists();
}
private function order(): Order
{
/** @var Order $order */
@@ -84,11 +92,15 @@ public function confirmInvoiceAction(): Action
->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());
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.');
@@ -111,12 +123,27 @@ public function refundAction(): Action
->modalSubmitActionLabel('Vollständig erstatten')
->schema([
Textarea::make('reason')->label('Begründung')->required()->rows(2)->maxLength(500)
->helperText('Bleibt am Widerruf der Berechtigungen stehen, zum Beispiel „Widerruf geprüft, Frist gewahrt“.'),
->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']);
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.');
@@ -188,6 +215,15 @@ private function bestellDaten(): array
])->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' => [
[
@@ -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