diff --git a/app/Domain/Commerce/PaymentJournal.php b/app/Domain/Commerce/PaymentJournal.php index 45c8e52..7673a48 100644 --- a/app/Domain/Commerce/PaymentJournal.php +++ b/app/Domain/Commerce/PaymentJournal.php @@ -123,10 +123,11 @@ public static function range(string $mode, int $year, int $index): array * @param 'echt'|'test'|'alle' $operation * @return Collection */ - public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt'): Collection + public function entries(CarbonInterface $from, CarbonInterface $to, string $kind = 'alle', string $provider = 'alle', string $operation = 'echt', ?int $offerId = null): Collection { return LedgerEntry::query() ->whereBetween('occurred_at', [$this->utc($from), $this->utc($to)]) + ->when($offerId !== null, fn ($query) => $query->whereHas('order.lines.offerVersion', fn ($versions) => $versions->where('offer_id', $offerId))) ->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)) @@ -136,6 +137,33 @@ public function entries(CarbonInterface $from, CarbonInterface $to, string $kind ->get(); } + /** + * Anteil eines Angebots an jeder Bewegung: die Positionen dieses Angebots in der Bestellung (Preis nach Rabatt, + * wie bei der Bestellung festgehalten), bei einer Erstattung negativ. Eine Buchung trägt den Betrag der ganzen + * Bestellung; ohne diese Aufteilung würde eine Bestellung mit mehreren Angeboten den Umsatz des einzelnen + * Angebots überzeichnen. Es gibt nur Vollerstattungen, deshalb ist der Anteil der Erstattung der gespiegelte. + * + * @param Collection $entries + * @return array Buchungsnummer => Anteil in Cent (mit Vorzeichen der Buchung) + */ + public function shares(Collection $entries, int $offerId): array + { + $perOrder = OrderLine::query() + ->whereIn('order_id', $entries->pluck('order_id')->unique()->all()) + ->whereHas('offerVersion', fn ($versions) => $versions->where('offer_id', $offerId)) + ->get() + ->groupBy('order_id') + ->map(fn (Collection $lines): int => (int) $lines->sum(fn (OrderLine $line): int => $line->payable())); + $shares = []; + + foreach ($entries as $entry) { + $share = (int) ($perOrder[$entry->order_id] ?? 0); + $shares[$entry->id] = $entry->isRefund() ? -$share : $share; + } + + return $shares; + } + /** * Anzahl der Bewegungen außerhalb des Betriebsfilters, damit ein leerer Echtbetrieb nicht wie „keine Daten“ wirkt. */ @@ -148,17 +176,19 @@ public function countByOperation(CarbonInterface $from, CarbonInterface $to): ar /** * @param Collection $entries + * @param array|null $shares Anteile eines Angebots (shares), sonst die ganzen Buchungen * @return array{eingang: int, erstattung: int, saldo: int, anzahl_eingang: int, anzahl_erstattung: int} */ - public static function totals(Collection $entries): array + public static function totals(Collection $entries, ?array $shares = null): array { $in = $entries->where('kind', LedgerEntry::KIND_PAYMENT); $out = $entries->where('kind', LedgerEntry::KIND_REFUND); + $amount = fn (LedgerEntry $entry): int => $shares === null ? $entry->amount_cents : (int) ($shares[$entry->id] ?? 0); return [ - 'eingang' => (int) $in->sum('amount_cents'), - 'erstattung' => (int) abs($out->sum('amount_cents')), - 'saldo' => (int) $entries->sum('amount_cents'), + 'eingang' => (int) $in->sum($amount), + 'erstattung' => (int) abs($out->sum($amount)), + 'saldo' => (int) $entries->sum($amount), 'anzahl_eingang' => $in->count(), 'anzahl_erstattung' => $out->count(), ]; @@ -189,13 +219,15 @@ public static function hasTime(LedgerEntry $entry): bool * Semikolon-getrennt, Dezimalkomma, UTF-8 mit BOM: öffnet in Excel und bei der Steuerberatung ohne Umweg. * * @param Collection $entries + * @param array|null $shares Mit Angebotsfilter eine zusätzliche Spalte „Anteil des Angebots“ */ - public static function csv(Collection $entries): string + public static function csv(Collection $entries, ?array $shares = null): 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', + ...($shares === null ? [] : ['Anteil des Angebots EUR']), ]; $rows = [$header]; @@ -235,6 +267,7 @@ public static function csv(Collection $entries): string $entry->reason, $entry->actor_name, self::local($entry->created_at)->format('d.m.Y H:i:s'), + ...($shares === null ? [] : [self::decimal((int) ($shares[$entry->id] ?? 0))]), ]; } diff --git a/app/Filament/Pages/Zahlungsjournal.php b/app/Filament/Pages/Zahlungsjournal.php index 0dcd7fb..30a9a04 100644 --- a/app/Filament/Pages/Zahlungsjournal.php +++ b/app/Filament/Pages/Zahlungsjournal.php @@ -2,6 +2,7 @@ namespace App\Filament\Pages; +use App\Domain\Catalog\Offer; use App\Domain\Commerce\LedgerEntry; use App\Domain\Commerce\PaymentJournal; use App\Filament\Support\ShopAccess; @@ -50,6 +51,10 @@ class Zahlungsjournal extends Page #[Url(as: 'betrieb')] public string $betrieb = 'echt'; + /** Kennung eines Angebots oder leer für alle (Zeichenkette, damit die Auswahl „Alle“ leer sein kann). */ + #[Url(as: 'angebot')] + public string $angebot = ''; + public static function canAccess(): bool { return ShopAccess::allowed(); @@ -95,6 +100,7 @@ private function normalize(): void $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->angebot = ctype_digit($this->angebot) && Offer::query()->whereKey((int) $this->angebot)->exists() ? $this->angebot : ''; $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))); @@ -126,13 +132,18 @@ public function daten(): array { [$from, $to] = $this->range(); $journal = app(PaymentJournal::class); - $entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb); + $offerId = $this->angebot === '' ? null : (int) $this->angebot; + $entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId); + $shares = $offerId === null ? null : $journal->shares($entries, $offerId); return [ 'zeitraum' => $this->zeitraumName(), 'eintraege' => $entries->take(PaymentJournal::DISPLAY_LIMIT), 'anzahl' => $entries->count(), - 'summen' => PaymentJournal::totals($entries), + 'angebote' => Offer::query()->orderBy('name')->pluck('name', 'id')->all(), + 'angebotName' => $offerId === null ? null : Offer::query()->find($offerId)?->name, + 'anteile' => $shares, + 'summen' => PaymentJournal::totals($entries, $shares), '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(), @@ -144,17 +155,20 @@ 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); + $journal = app(PaymentJournal::class); + $offerId = $this->angebot === '' ? null : (int) $this->angebot; + $entries = $journal->entries($from, $to, $this->art, $this->weg, $this->betrieb, $offerId); + $shares = $offerId === null ? null : $journal->shares($entries, $offerId); $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'; + }.($offerId === null ? '' : '-angebot-'.$offerId).'.csv'; - return response()->streamDownload(function () use ($entries): void { - echo PaymentJournal::csv($entries); + return response()->streamDownload(function () use ($entries, $shares): void { + echo PaymentJournal::csv($entries, $shares); }, $name, ['Content-Type' => 'text/csv; charset=UTF-8']); } } diff --git a/app/Filament/Resources/Offers/Pages/ViewOffer.php b/app/Filament/Resources/Offers/Pages/ViewOffer.php index 079fe8c..6677f1e 100644 --- a/app/Filament/Resources/Offers/Pages/ViewOffer.php +++ b/app/Filament/Resources/Offers/Pages/ViewOffer.php @@ -18,11 +18,13 @@ use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Commerce\Money; use App\Domain\Commerce\ProductOptions; +use App\Filament\Pages\Zahlungsjournal; use App\Filament\Resources\Offers\OfferResource; use App\Filament\Support\CatalogLabels; use App\Filament\Support\CatalogOptions; use App\Filament\Support\PublicationReadiness; use App\Filament\Support\ReportsDomainRules; +use App\Filament\Support\ShopAccess; use Filament\Actions\Action; use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; @@ -366,6 +368,11 @@ private function angebotDaten(): array 'wire' => "mountAction('end')", 'art' => 'line', ]] : []), + ...(ShopAccess::allowed() ? [[ + 'label' => 'Zahlungen zu diesem Angebot', + 'href' => Zahlungsjournal::getUrl(['angebot' => $offer->id, 'zeitraum' => 'jahr', 'betrieb' => 'alle']), + 'art' => 'quiet', + ]] : []), ], ], 'voraussetzungen' => app(PublicationReadiness::class)->forOffer($offer), diff --git a/resources/views/filament/pages/zahlungsjournal.blade.php b/resources/views/filament/pages/zahlungsjournal.blade.php index cb93304..495e021 100644 --- a/resources/views/filament/pages/zahlungsjournal.blade.php +++ b/resources/views/filament/pages/zahlungsjournal.blade.php @@ -76,15 +76,28 @@ +
+ + +
+ @if ($d['anteile'] !== null) +

Gezeigt werden Bestellungen mit dem Angebot „{{ $d['angebotName'] }}“. Die Beträge und Summen sind der Anteil dieses Angebots an der jeweiligen Bestellung (Preis nach Rabatt); enthält eine Bestellung weitere Angebote, steht die Gesamtbuchung darunter.

+ @endif + @if ($this->betrieb === 'echt' && $d['nachBetrieb']['test'] > 0)

In diesem Zeitraum gibt es zusätzlich {{ $d['nachBetrieb']['test'] }} Testbewegung{{ $d['nachBetrieb']['test'] === 1 ? '' : 'en' }}. Sie sind kein Umsatz und zählen hier nicht mit; über den Filter „Betrieb“ siehst du sie getrennt.

@elseif ($this->betrieb !== 'echt')

Achtung: Testzahlungen sind kein Umsatz. Sie dürfen nicht in eine Aufstellung für das Finanzamt eingehen.

@endif -
+
Einnahmen
{{ $euro($summen['eingang']) }}
{{ $summen['anzahl_eingang'] }} Zahlung{{ $summen['anzahl_eingang'] === 1 ? '' : 'en' }}, brutto
Erstattungen
−{{ $euro($summen['erstattung']) }}
{{ $summen['anzahl_erstattung'] }} Rückzahlung{{ $summen['anzahl_erstattung'] === 1 ? '' : 'en' }}
Saldo
{{ $euro($summen['saldo']) }}
Einnahmen minus Erstattungen
@@ -98,7 +111,7 @@

Bei {{ $d['ohneAdresse'] }} Zahlung{{ $d['ohneAdresse'] === 1 ? '' : 'en' }} war keine Rechnungsadresse hinterlegt. Es ist nur Lizenzinhaber und Besteller festgehalten.

@endif -
+
@if ($d['anzahl'] === 0)
Keine Bewegungen @@ -113,7 +126,7 @@ Datum Art - Betrag + {{ $d['anteile'] === null ? 'Betrag' : 'Anteil des Angebots' }} Bestellung Zahler und Rechnungsempfänger Zahlungsweg und Beleg @@ -130,7 +143,15 @@ $e->isRefund()])> {{ $lokal->format('d.m.Y') }}@if (\App\Domain\Commerce\PaymentJournal::hasTime($e)) {{ $lokal->format('H:i') }}@endif ! $e->isRefund(), 'is-offen' => $e->isRefund()])>{{ $e->isRefund() ? 'Erstattung' : 'Zahlungseingang' }} - {{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }} + @php($anteil = $d['anteile'][$e->id] ?? null) + + @if ($anteil === null) + {{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }} + @else + {{ $anteil < 0 ? '−' : '' }}{{ $euro(abs($anteil)) }} + @if (abs($anteil) !== abs($e->amount_cents))Buchung gesamt {{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }}@endif + @endif + Bestellung {{ $e->order_id }} @if ($billing !== []) diff --git a/tests/Feature/PaymentJournalTest.php b/tests/Feature/PaymentJournalTest.php index 6afbbb2..b17c340 100644 --- a/tests/Feature/PaymentJournalTest.php +++ b/tests/Feature/PaymentJournalTest.php @@ -12,6 +12,7 @@ use App\Domain\Entitlement\GrantStatus; use App\Domain\Identity\BillingAddress; use App\Filament\Pages\Zahlungsjournal; +use App\Filament\Resources\Offers\Pages\ViewOffer; use App\Filament\Resources\Orders\Pages\ViewOrder; use App\Models\User; use Carbon\CarbonImmutable; @@ -394,6 +395,97 @@ public function test_the_page_shows_totals_and_entries_and_hides_test_money_by_d ->assertSee('Keine Bewegungen'); } + /** Bestellung mit zwei Angeboten (49 € mit 4 € Rabatt und 29 €), bezahlt über Stripe. */ + private function paidTwoLineOrder(string $session = 'cs_two'): Order + { + $tina = $this->tina(); + $this->address($tina, $tina->name); + $order = $this->orderOf($tina, [$this->privateKonflikte(), $this->privateGrenzen()]); + $order->lines()->orderBy('id')->firstOrFail()->update(['discount_cents' => 400]); + $order->update(['total_cents' => 7400, 'discount_cents' => 400]); + $this->webhook($this->paidEvent($order, $session, 7400, true, CarbonImmutable::parse('2026-11-24 09:30:00', 'UTC')->getTimestamp()))->assertOk(); + + return $order->fresh(); + } + + public function test_a_product_filter_shows_only_orders_with_that_offer_and_only_its_share(): void + { + $this->paidTwoLineOrder(); + $this->paidStripeOrder(true, 'cs_other', $this->vera(), 'grenzen', 2900); + [$from, $to] = PaymentJournal::range('monat', 2026, 11); + $journal = app(PaymentJournal::class); + $konflikte = $this->privateKonflikte()->id; + $grenzen = $this->privateGrenzen()->id; + + $this->assertCount(2, $journal->entries($from, $to), 'Ohne Filter beide Bestellungen.'); + $this->assertCount(1, $journal->entries($from, $to, offerId: $konflikte), 'Nur die Bestellung mit dem Angebot.'); + $this->assertCount(2, $journal->entries($from, $to, offerId: $grenzen)); + + $entries = $journal->entries($from, $to, offerId: $grenzen); + $shares = $journal->shares($entries, $grenzen); + $this->assertSame(2900 + 2900, array_sum($shares)); + $this->assertSame(7400, PaymentJournal::totals($journal->entries($from, $to, offerId: $konflikte))['eingang'], 'Ohne Aufteilung stünde hier die ganze Bestellung.'); + + $entries = $journal->entries($from, $to, offerId: $konflikte); + $shares = $journal->shares($entries, $konflikte); + $this->assertSame(4500, array_sum($shares), 'Anteil: 49,00 € minus 4,00 € Rabatt, nicht die 74,00 € der Bestellung.'); + $this->assertSame(4500, PaymentJournal::totals($entries, $shares)['eingang']); + } + + public function test_a_refund_mirrors_the_share_and_the_csv_names_it(): void + { + $order = $this->paidTwoLineOrder(); + Http::fake(['stripe.test/v1/refunds' => Http::response(['id' => 're_two', 'status' => 'succeeded', 'created' => CarbonImmutable::parse('2026-11-26 10:00:00', 'UTC')->getTimestamp()])]); + app(Checkout::class)->refund($order, 'Widerruf geprüft'); + [$from, $to] = PaymentJournal::range('monat', 2026, 11); + $journal = app(PaymentJournal::class); + $grenzen = $this->privateGrenzen()->id; + $entries = $journal->entries($from, $to, offerId: $grenzen); + $shares = $journal->shares($entries, $grenzen); + $totals = PaymentJournal::totals($entries, $shares); + + $this->assertSame(2900, $totals['eingang']); + $this->assertSame(2900, $totals['erstattung']); + $this->assertSame(0, $totals['saldo']); + + $csv = PaymentJournal::csv($entries, $shares); + $lines = array_values(array_filter(explode("\r\n", $csv))); + $this->assertStringEndsWith(';"Anteil des Angebots EUR"', $lines[0]); + $this->assertStringEndsWith(';29,00', $lines[1]); + $this->assertStringEndsWith(';-29,00', $lines[2]); + $this->assertStringContainsString(';74,00;', $lines[1], 'Die Buchung zeigt weiter den Betrag der ganzen Bestellung.'); + } + + public function test_the_page_filters_by_offer_validates_the_parameter_and_exports_with_the_offer_in_the_name(): void + { + $this->paidTwoLineOrder(); + $konflikte = $this->privateKonflikte(); + $staff = $this->staff('kundenbetreuung'); + + Livewire::actingAs($staff, 'staff')->test(Zahlungsjournal::class, ['angebot' => (string) $konflikte->id]) + ->assertSee('Gekauftes Angebot') + ->assertSee('Anteil dieses Angebots') + ->assertSee('45,00 €') + ->assertSee('Buchung gesamt 74,00 €') + ->call('exportieren') + ->assertFileDownloaded('zahlungsjournal-2026-11-echt-angebot-'.$konflikte->id.'.csv') + ->set('angebot', '') + ->assertSee('74,00 €') + ->assertDontSee('Anteil dieses Angebots'); + + Livewire::actingAs($staff, 'staff')->test(Zahlungsjournal::class, ['angebot' => '99999'])->assertSet('angebot', ''); + Livewire::actingAs($staff, 'staff')->test(Zahlungsjournal::class, ['angebot' => 'x; DROP'])->assertSet('angebot', ''); + } + + public function test_the_offer_page_links_to_its_payments_for_those_who_may_see_them(): void + { + $offer = $this->privateKonflikte(); + + Livewire::actingAs($this->staff('katalogverwalter'), 'staff')->test(ViewOffer::class, ['record' => $offer->getKey()]) + ->assertSee('Zahlungen zu diesem Angebot') + ->assertSee('angebot='.$offer->id, false); + } + public function test_the_page_exports_the_filtered_period_as_a_csv_download(): void { $this->paidStripeOrder(true, 'cs_live_1');