Anbindung Shinkan, Übungsverwaltung #7

Merged
Lars merged 34 commits from develop into main 2026-11-23 19:10:35 +01:00
5 changed files with 183 additions and 16 deletions
Showing only changes of commit dd3cc83057 - Show all commits

No files matched your search

+39 -6
View File
@@ -123,10 +123,11 @@ public static function range(string $mode, int $year, int $index): array
* @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
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<int, LedgerEntry> $entries
* @return array<int, int> 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<int, LedgerEntry> $entries
* @param array<int, int>|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<int, LedgerEntry> $entries
* @param array<int, int>|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))]),
];
}
+20 -6
View File
@@ -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']);
}
}
@@ -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),
@@ -76,15 +76,28 @@
<option value="alle">Echte und Testzahlungen</option>
</select>
</div>
<div class="vw-bestand-filter">
<label class="vw-feldlabel" for="journal-angebot">Gekauftes Angebot</label>
<select id="journal-angebot" class="vw-auswahlfeld" wire:model.live="angebot">
<option value="">Alle Angebote</option>
@foreach ($d['angebote'] as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</select>
</div>
</div>
@if ($d['anteile'] !== null)
<p class="vw-band" role="note">Gezeigt werden Bestellungen mit dem Angebot „{{ $d['angebotName'] }}“. Die Beträge und Summen sind der <strong>Anteil dieses Angebots</strong> an der jeweiligen Bestellung (Preis nach Rabatt); enthält eine Bestellung weitere Angebote, steht die Gesamtbuchung darunter.</p>
@endif
@if ($this->betrieb === 'echt' && $d['nachBetrieb']['test'] > 0)
<p class="vw-band" role="note">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.</p>
@elseif ($this->betrieb !== 'echt')
<p class="vw-band" role="note"><strong>Achtung:</strong> Testzahlungen sind kein Umsatz. Sie dürfen nicht in eine Aufstellung für das Finanzamt eingehen.</p>
@endif
<dl class="vw-journal-summen" aria-label="Summen im {{ $d['zeitraum'] }}">
<dl class="vw-journal-summen" aria-label="Summen im {{ $d['zeitraum'] }}{{ $d['anteile'] !== null ? ' für das Angebot '.$d['angebotName'] : '' }}">
<div><dt>Einnahmen</dt><dd>{{ $euro($summen['eingang']) }}</dd><dd class="vw-feld-hilfe">{{ $summen['anzahl_eingang'] }} Zahlung{{ $summen['anzahl_eingang'] === 1 ? '' : 'en' }}, brutto</dd></div>
<div><dt>Erstattungen</dt><dd>−{{ $euro($summen['erstattung']) }}</dd><dd class="vw-feld-hilfe">{{ $summen['anzahl_erstattung'] }} Rückzahlung{{ $summen['anzahl_erstattung'] === 1 ? '' : 'en' }}</dd></div>
<div class="is-saldo"><dt>Saldo</dt><dd>{{ $euro($summen['saldo']) }}</dd><dd class="vw-feld-hilfe">Einnahmen minus Erstattungen</dd></div>
@@ -98,7 +111,7 @@
<p class="vw-hinweis-offen" role="note">Bei {{ $d['ohneAdresse'] }} Zahlung{{ $d['ohneAdresse'] === 1 ? '' : 'en' }} war keine Rechnungsadresse hinterlegt. Es ist nur Lizenzinhaber und Besteller festgehalten.</p>
@endif
<div wire:loading.class="vw-laedt" wire:target="modus,jahr,nr,art,weg,betrieb">
<div wire:loading.class="vw-laedt" wire:target="modus,jahr,nr,art,weg,betrieb,angebot">
@if ($d['anzahl'] === 0)
<div class="vw-leer vw-leer-breit">
<strong>Keine Bewegungen</strong>
@@ -113,7 +126,7 @@
<tr>
<th scope="col">Datum</th>
<th scope="col">Art</th>
<th scope="col" class="is-zahl">Betrag</th>
<th scope="col" class="is-zahl">{{ $d['anteile'] === null ? 'Betrag' : 'Anteil des Angebots' }}</th>
<th scope="col">Bestellung</th>
<th scope="col">Zahler und Rechnungsempfänger</th>
<th scope="col">Zahlungsweg und Beleg</th>
@@ -130,7 +143,15 @@
<tr wire:key="journal-{{ $e->id }}" @class(['is-erstattung' => $e->isRefund()])>
<td data-label="Datum" class="is-kurz">{{ $lokal->format('d.m.Y') }}@if (\App\Domain\Commerce\PaymentJournal::hasTime($e)) <span class="vw-feld-hilfe">{{ $lokal->format('H:i') }}</span>@endif</td>
<td data-label="Art"><span @class(['vw-zustand', 'is-gut' => ! $e->isRefund(), 'is-offen' => $e->isRefund()])>{{ $e->isRefund() ? 'Erstattung' : 'Zahlungseingang' }}</span></td>
<td data-label="Betrag" class="is-zahl"><strong>{{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }}</strong></td>
@php($anteil = $d['anteile'][$e->id] ?? null)
<td data-label="{{ $anteil === null ? 'Betrag' : 'Anteil' }}" class="is-zahl">
@if ($anteil === null)
<strong>{{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }}</strong>
@else
<strong>{{ $anteil < 0 ? '−' : '' }}{{ $euro(abs($anteil)) }}</strong>
@if (abs($anteil) !== abs($e->amount_cents))<span class="vw-feld-hilfe">Buchung gesamt {{ $e->amount_cents < 0 ? '−' : '' }}{{ $euro(abs($e->amount_cents)) }}</span>@endif
@endif
</td>
<td data-label="Bestellung" class="is-kurz"><a class="vw-link" href="{{ \App\Filament\Resources\Orders\OrderResource::getUrl('view', ['record' => $e->order_id]) }}">Bestellung {{ $e->order_id }}</a></td>
<td data-label="Zahler">
@if ($billing !== [])
+92
View File
@@ -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');