Files
laraundfelix/tests/Feature/PaymentReceiptTest.php
LarsandClaude Sonnet 5.5 78c8870e4e
CI Feature / test (push) Successful in 3m23s
Deploy Test / test (push) Successful in 3m45s
Deploy Test / deploy (push) Successful in 39s
Füge Zahlungshistorie und Einzelbeleg (PDF) im Mitgliederbereich hinzu
Mein Konto, Zahlungen: eigene Zahlungen und Rückzahlungen mit Beleg als PDF, auch von der
Bestellseite verlinkt. Der Beleg entsteht aus den bei der Buchung festgehaltenen Angaben und ist
byte-gleich; er heißt nie Rechnung und trägt weder Rechnungsnummer noch Steuerangaben. Kleiner
PDF-Schreiber ohne neue Abhängigkeit. Aussteller und Hinweis nur bei Pflege (SHOP_RECEIPT_*).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:23:40 +01:00

270 lines
13 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace Tests\Feature;
use App\Domain\Commerce\Checkout;
use App\Domain\Commerce\LedgerEntry;
use App\Domain\Commerce\Order;
use App\Domain\Commerce\Receipt\PaymentReceipt;
use App\Domain\Commerce\Receipt\PdfDocument;
use App\Domain\Identity\BillingAddress;
use App\Models\User;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Zahlungshistorie des Mitglieds und Einzelbeleg (PDF). Der Beleg entsteht aus den bei der Buchung festgehaltenen
* Angaben und ist bei jedem Abruf byte-gleich.
*/
class PaymentReceiptTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
config([
'services.payment.driver' => 'stripe',
'services.stripe.secret' => 'sk_test_nur_fuer_tests',
'services.stripe.api_base' => 'https://stripe.test',
]);
$this->travelTo('2026-11-24 10:00:00');
}
/** Alle Textstellen einer PDF-Datei (Tj), als UTF-8. */
private function textOf(string $pdf): string
{
preg_match_all('/\((.*)\) Tj/', $pdf, $matches);
$parts = array_map(fn (string $raw): string => mb_convert_encoding(preg_replace('/\\\\([\\\\()])/', '$1', $raw), 'UTF-8', 'Windows-1252'), $matches[1]);
return implode("\n", $parts);
}
private function address(User $user, string $recipient): void
{
BillingAddress::query()->updateOrCreate(['party_id' => $user->party_id], [
'recipient' => $recipient, 'street' => 'Hauptstraße 1', 'postal_code' => '50667', 'city' => 'Köln', 'country' => 'DE',
]);
}
private function paid(User $buyer, string $offer = 'konflikte', int $amount = 4900, string $session = 'cs_rec_1', bool $live = true): Order
{
$order = $this->orderOf($buyer, [$offer === 'grenzen' ? $this->privateGrenzen() : $this->privateKonflikte()]);
app(Checkout::class)->confirmProviderPayment($order, 'stripe', $session, $amount, 'eur', $live, CarbonImmutable::parse('2026-11-24 09:30:00', 'UTC'), 'pi_'.$session);
return $order->fresh();
}
public function test_the_pdf_writer_makes_a_valid_file_with_correct_offsets_and_windows_1252_text(): void
{
$pdf = new PdfDocument;
$pdf->addPage();
$pdf->text(50, 700, 'Größe (Äpfel) \\ 49,00 € − „Test“ 😀', 12, true);
$file = $pdf->output('Titel (x)');
$this->assertStringStartsWith('%PDF-1.4', $file);
$this->assertStringEndsWith("%%EOF\n", $file);
preg_match('/startxref\n(\d+)\n/', $file, $start);
$this->assertSame('xref', substr($file, (int) $start[1], 4), 'startxref zeigt auf die xref-Tabelle (Byte-Offset).');
preg_match_all('/^(\d{10}) 00000 n $/m', $file, $offsets);
foreach ($offsets[1] as $index => $offset) {
$this->assertStringStartsWith(($index + 1).' 0 obj', substr($file, (int) $offset, 12), 'Offset von Objekt '.($index + 1));
}
$this->assertStringContainsString("Gr\xF6\xDFe", $file, 'ö und ß als Windows-1252-Bytes.');
$this->assertStringContainsString("\\(\xC4pfel\\) \\\\ 49,00 \x80 - ", $file, 'Klammern und Rückstrich maskiert, € als 0x80, U+2212 als Minus.');
$this->assertStringContainsString("\x84Test\x93 ?", $file, 'Anführungszeichen vorhanden, Emoji ersetzt.');
$this->assertStringNotContainsString('CreationDate', $file, 'Kein Zeitstempel, damit der Abruf byte-gleich bleibt.');
}
public function test_wrapping_never_exceeds_the_width_and_splits_long_words(): void
{
$lines = PdfDocument::wrap('Ein sehr langer Angebotsname mit Paketumfang und Begleitmaterial Donaudampfschifffahrtsgesellschaftskapitän', 150, 10);
$this->assertGreaterThan(2, count($lines));
foreach ($lines as $line) {
$this->assertLessThanOrEqual(150, PdfDocument::width($line, 10), $line);
}
$this->assertStringContainsString('Donaudampf', implode('', $lines));
}
public function test_a_payment_receipt_shows_the_frozen_details_and_is_byte_identical_on_each_call(): void
{
$tina = $this->tina();
$this->address($tina, 'Tina Trainerin GbR');
$order = $this->paid($tina);
$entry = LedgerEntry::query()->sole();
$first = PaymentReceipt::render($entry);
$this->address($tina, 'Ganz Andere GmbH');
$this->travelTo('2027-03-01 12:00:00');
$second = PaymentReceipt::render($entry->fresh());
$text = $this->textOf($first);
$this->assertSame($first, $second, 'Spätere Adressänderung und anderes Datum ändern den Beleg nicht.');
$this->assertStringContainsString('Zahlungsbeleg', $text);
$this->assertStringContainsString((string) $order->id, $text);
$this->assertStringContainsString('Tina Trainerin GbR', $text);
$this->assertStringNotContainsString('Ganz Andere', $text);
$this->assertStringContainsString('Hauptstraße 1', $text);
$this->assertStringContainsString('50667 Köln', $text);
$this->assertStringContainsString('24.11.2026, 10:30 Uhr', $text, 'Zeitpunkt der Zahlung in deutscher Zeit.');
$this->assertStringContainsString('Stripe', $text);
$this->assertStringContainsString('cs_rec_1', $text);
$this->assertStringContainsString('Konflikte im Training: Privatlizenz', $text);
$this->assertStringContainsString('Gezahlter Betrag', $text);
$this->assertStringContainsString('49,00 €', $text);
$this->assertStringNotContainsString('TESTZAHLUNG', $text, 'Eine echte Zahlung trägt keinen Testvermerk.');
$this->assertStringContainsString('keine Rechnungsnummer und keine steuerlichen Angaben', $text);
$this->assertSame('Zahlungsbeleg-Bestellung-'.$order->id.'-Buchung-'.$entry->id.'.pdf', PaymentReceipt::filename($entry));
}
public function test_a_discounted_order_shows_list_price_discount_code_and_paid_amount(): void
{
$tina = $this->tina();
$order = $this->orderOf($tina, [$this->privateKonflikte()]);
$order->lines()->firstOrFail()->update(['discount_cents' => 400]);
$order->update(['total_cents' => 4500, 'discount_cents' => 400, 'discount_snapshot' => ['code' => 'ZERTX']]);
app(Checkout::class)->confirmProviderPayment($order, 'stripe', 'cs_disc', 4500, 'eur', true);
$text = $this->textOf(PaymentReceipt::render(LedgerEntry::query()->sole()));
$this->assertStringContainsString('Zwischensumme', $text);
$this->assertStringContainsString('Rabatt (Code ZERTX)', $text);
$this->assertStringContainsString('-4,00 €', $text);
$this->assertStringContainsString('45,00 €', $text);
}
public function test_a_refund_receipt_and_a_test_payment_are_marked(): void
{
$order = $this->paid($this->tina());
Http::fake(['stripe.test/v1/refunds' => Http::response(['id' => 're_rec', 'status' => 'succeeded', 'created' => CarbonImmutable::parse('2026-11-25 10:00:00', 'UTC')->getTimestamp()])]);
app(Checkout::class)->refund($order, 'Interner Grund, nicht für das Mitglied');
$refund = LedgerEntry::query()->where('kind', LedgerEntry::KIND_REFUND)->sole();
$text = $this->textOf(PaymentReceipt::render($refund));
$this->assertStringContainsString('Erstattungsbeleg', $text);
$this->assertStringContainsString('Rückzahlung am', $text);
$this->assertStringContainsString('Erstatteter Betrag', $text);
$this->assertStringContainsString('re_rec', $text);
$this->assertStringNotContainsString('Interner Grund', $text, 'Die interne Begründung gehört nicht auf den Beleg.');
$this->assertStringStartsWith('Erstattungsbeleg-Bestellung-', PaymentReceipt::filename($refund));
$testOrder = $this->paid($this->vera(), 'grenzen', 2900, 'cs_test_mode', false);
$testText = $this->textOf(PaymentReceipt::render(LedgerEntry::query()->where('order_id', $testOrder->id)->sole()));
$this->assertStringContainsString('TESTZAHLUNG - kein Umsatz', $testText);
}
public function test_issuer_and_note_appear_only_when_configured(): void
{
$this->paid($this->tina());
$entry = LedgerEntry::query()->sole();
$this->assertStringNotContainsString('Musterfirma', $this->textOf(PaymentReceipt::render($entry)));
config(['shop.receipt.issuer' => 'Musterfirma GmbH|Beispielweg 1|12345 Beispielstadt', 'shop.receipt.note' => 'Zusatzhinweis für den Test.']);
$text = $this->textOf(PaymentReceipt::render($entry));
$this->assertStringContainsString('Musterfirma GmbH', $text);
$this->assertStringContainsString('12345 Beispielstadt', $text);
$this->assertStringContainsString('Zusatzhinweis für den Test.', $text);
}
public function test_many_positions_continue_on_a_second_page(): void
{
$this->paid($this->tina());
$entry = LedgerEntry::query()->sole();
$snapshot = $entry->order_snapshot;
$snapshot['lines'] = array_map(fn (int $i): array => ['name' => 'Angebot Nummer '.$i, 'price_cents' => 1000, 'discount_cents' => 0], range(1, 60));
$entry->setRawAttributes(array_merge($entry->getAttributes(), ['order_snapshot' => json_encode($snapshot)]));
$pdf = PaymentReceipt::render($entry);
$this->assertStringContainsString('/Count 2', $pdf);
$this->assertStringContainsString('Angebot Nummer 60', $this->textOf($pdf));
}
public function test_the_member_sees_own_payments_and_downloads_the_receipt(): void
{
$tina = $this->tina();
$order = $this->paid($tina);
$this->paid($this->vera(), 'grenzen', 2900, 'cs_other');
$entry = LedgerEntry::query()->where('order_id', $order->id)->sole();
$this->actingAs($tina)->get(route('member.payments'))
->assertOk()
->assertSee('Meine Zahlungen')
->assertSee('49,00 €')
->assertSee('Konflikte im Training: Privatlizenz')
->assertDontSee('29,00 €', 'Zahlungen anderer Konten erscheinen nicht.')
->assertSee('Beleg herunterladen (PDF)')
->assertSee('/bereich/zahlungen/'.$entry->id.'/beleg', false);
$response = $this->get(route('member.payments.receipt', $entry))->assertOk();
$this->assertSame('application/pdf', $response->headers->get('Content-Type'));
$this->assertStringContainsString('attachment; filename="Zahlungsbeleg-Bestellung-'.$order->id.'-Buchung-'.$entry->id.'.pdf"', (string) $response->headers->get('Content-Disposition'));
$this->assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
$this->assertStringStartsWith('%PDF-', $response->getContent());
$this->assertSame(PaymentReceipt::render($entry), $response->getContent());
}
public function test_another_member_and_guests_get_no_receipt_and_no_list(): void
{
$order = $this->paid($this->tina());
$entry = LedgerEntry::query()->where('order_id', $order->id)->sole();
$this->get(route('member.payments.receipt', $entry))->assertRedirect(route('login'));
$this->get(route('member.payments'))->assertRedirect(route('login'));
$this->actingAs($this->max())->get(route('member.payments.receipt', $entry))->assertForbidden();
$this->get(route('member.payments'))->assertOk()->assertSee('Noch keine Zahlung')->assertDontSee('49,00 €');
$this->get(route('member.payments.receipt', 99999))->assertNotFound();
}
public function test_the_club_member_who_did_not_order_gets_no_receipt(): void
{
$vera = $this->vera();
$order = $this->orderOf($vera, [$this->clubKonflikte()], $this->club()->id);
app(Checkout::class)->confirmProviderPayment($order, 'stripe', 'cs_club', $order->payable(), 'eur', true);
$entry = LedgerEntry::query()->sole();
$this->actingAs($vera)->get(route('member.payments.receipt', $entry))->assertOk();
$this->actingAs($this->tina())->get(route('member.payments.receipt', $entry))->assertForbidden();
}
public function test_a_carried_over_entry_has_no_receipt(): void
{
$tina = $this->tina();
$order = $this->paid($tina);
$entry = LedgerEntry::query()->where('order_id', $order->id)->sole();
$this->assertTrue(PaymentReceipt::available($entry));
DB::table('payment_ledger')->where('id', $entry->id)->update(['derived' => true]);
$this->actingAs($tina)->get(route('member.payments'))->assertOk()->assertSee('Kein Beleg verfügbar');
$this->get(route('member.payments.receipt', $entry))->assertNotFound();
}
public function test_the_order_page_and_the_account_menu_link_to_the_receipts(): void
{
$tina = $this->tina();
$order = $this->paid($tina);
$entry = LedgerEntry::query()->sole();
$this->actingAs($tina)->get(route('member.order', $order))
->assertOk()
->assertSee('Belege zu dieser Bestellung')
->assertSee(route('member.payments.receipt', $entry), false)
->assertSee('Alle meine Zahlungen')
->assertSee(route('member.payments'), false);
}
}