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 */ 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 $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 $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 */ 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 */ 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(), ]; } }