feat: Folgeraten über Stripe Billing einziehen

Statt eigener Off-Session-Einzüge durch den Worker legt die Anwendung nach
bezahlter erster Rate einen Stripe Subscription Schedule an. Stripe übernimmt
Einzug, Wiederholungen (Smart Retries), 3-D-Secure-Links und Mahnungen.

- Gateway: Zeitplan anlegen/beenden, Rechnungen lesen; chargeOffSession entfällt
- Webhook: invoice.paid, invoice.payment_failed, invoice.payment_action_required
- Worker: fehlende Zeitpläne anlegen, überfällige Raten abgleichen,
  Zeitpläne stornierter Buchungen beenden
- Storno beendet den Zeitplan und storniert offene Rechnungen
- "Rate bezahlen" führt auf Stripes Rechnungsseite
- Migration: Booking.stripeScheduleId, Installment.stripeInvoiceId

Zeitplan-Form mit Stripe-Testuhr gegen die Test-API geprüft.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-10-05 23:52:43 +02:00
1 parent bcf0f5c937
commit c1ad9ad2ca
18 files changed
+800 -555

No files matched your search

+92 -30
View File
@@ -1,30 +1,32 @@
import type {
CheckoutSessionInfo,
CreateCheckoutParams,
OffSessionResult,
CreateInstallmentScheduleParams,
InvoiceInfo,
PaymentGateway,
PaymentIntentInfo,
} from "@/lib/payment-gateway";
import type { StripeMode } from "@/lib/sales-gate";
type StoredSession = CheckoutSessionInfo & { params: CreateCheckoutParams };
type StoredSchedule = { id: string; status: "active" | "canceled"; params: CreateInstallmentScheduleParams; invoiceIds: string[] };
/**
* Stripe-Attrappe im Speicher. Bildet die fuer die Geschaeftslogik
* relevanten Eigenschaften nach: Idempotenzschluessel, Session-Zustaende,
* PaymentIntents und das Ergebnis von Off-Session-Einzuegen.
* PaymentIntents und die Rechnungen eines Stripe-Billing-Ratenplans.
*/
export class FakeGateway implements PaymentGateway {
private seq = 0;
private readonly byKey = new Map<string, unknown>();
readonly sessions = new Map<string, StoredSession>();
readonly paymentIntents = new Map<string, PaymentIntentInfo>();
readonly offSessionCharges: { key: string; amountCents: number; installmentId: string }[] = [];
readonly schedules = new Map<string, StoredSchedule>();
readonly invoices = new Map<string, InvoiceInfo>();
readonly detached: string[] = [];
readonly refunds: { id: string; paymentIntentId: string; amountCents: number }[] = [];
/** Ergebnisse fuer die naechsten Off-Session-Einzuege (Standard: Erfolg). */
offSessionOutcomes: OffSessionResult["outcome"][] = [];
failNextCheckout = false;
failNextSchedule = false;
constructor(readonly mode: StripeMode = "test") {}
@@ -101,34 +103,94 @@ export class FakeGateway implements PaymentGateway {
return { ...pi };
}
async chargeOffSession(
params: { customerId: string; paymentMethodId: string; amountCents: number; metadata: Record<string, string> },
key: string,
): Promise<OffSessionResult> {
return this.once(`pi:${key}`, () => {
const outcome = this.offSessionOutcomes.shift() ?? "succeeded";
const piId = this.id("pi");
const chargeId = outcome === "succeeded" ? this.id("ch") : null;
this.paymentIntents.set(piId, {
id: piId,
status: outcome === "succeeded" ? "succeeded" : outcome === "processing" ? "processing" : outcome === "requires_action" ? "requires_action" : "requires_payment_method",
amountReceived: outcome === "succeeded" ? params.amountCents : 0,
paymentMethodId: params.paymentMethodId,
chargeId,
metadata: params.metadata,
});
if (outcome === "succeeded") {
this.offSessionCharges.push({ key, amountCents: params.amountCents, installmentId: params.metadata.installmentId! });
}
return {
outcome,
paymentIntentId: piId,
chargeId,
failureCode: outcome === "failed" ? "card_declined" : outcome === "requires_action" ? "authentication_required" : null,
};
async createInstallmentSchedule(params: CreateInstallmentScheduleParams, key: string) {
if (this.failNextSchedule) {
this.failNextSchedule = false;
throw new Error("Stripe nicht erreichbar (simuliert)");
}
return this.once(`sub_sched:${key}`, () => {
const id = this.id("sub_sched");
this.schedules.set(id, { id, status: "active", params, invoiceIds: [] });
return { id };
});
}
async cancelInstallmentSchedule(id: string): Promise<void> {
const schedule = this.schedules.get(id);
if (!schedule) throw new Error(`Unbekannter Zeitplan ${id}`);
schedule.status = "canceled";
for (const invoiceId of schedule.invoiceIds) {
const invoice = this.invoices.get(invoiceId)!;
if (invoice.status === "open") this.invoices.set(invoiceId, { ...invoice, status: "void", hostedInvoiceUrl: null });
}
}
async retrieveInvoice(id: string): Promise<InvoiceInfo> {
const invoice = this.invoices.get(id);
if (!invoice) throw new Error(`Unbekannte Rechnung ${id}`);
return { ...invoice };
}
async listScheduleInvoices(scheduleId: string): Promise<InvoiceInfo[]> {
return (this.schedules.get(scheduleId)?.invoiceIds ?? []).map((id) => ({ ...this.invoices.get(id)! }));
}
/**
* Simuliert den naechsten Einzug durch Stripe Billing: erzeugt die
* naechste Rechnung des Zeitplans, bezahlt oder offen. Ein aktiver Zeitplan
* erzeugt nie mehr Rechnungen als Folgeraten.
*/
billNextInstallment(scheduleId: string, outcome: "paid" | "failed" | "requires_action" = "paid", opts: { finalAttempt?: boolean } = {}): InvoiceInfo {
const schedule = this.schedules.get(scheduleId);
if (!schedule || schedule.status !== "active") throw new Error(`Zeitplan ${scheduleId} ist nicht aktiv`);
if (schedule.invoiceIds.length >= schedule.params.count) throw new Error("Zeitplan hat bereits alle Raten abgerechnet");
const id = this.id("in");
schedule.invoiceIds.push(id);
const invoice = this.invoiceResult(id, schedule, outcome, 1, opts.finalAttempt ?? false);
this.invoices.set(id, invoice);
return { ...invoice };
}
/** Simuliert einen weiteren Versuch (Smart Retry oder Zahlung ueber die Rechnungsseite). */
retryInvoice(invoiceId: string, outcome: "paid" | "failed" | "requires_action", opts: { finalAttempt?: boolean } = {}): InvoiceInfo {
const current = this.invoices.get(invoiceId)!;
if (current.status !== "open") throw new Error(`Rechnung ${invoiceId} ist nicht offen`);
const schedule = [...this.schedules.values()].find((s) => s.invoiceIds.includes(invoiceId))!;
const invoice = this.invoiceResult(invoiceId, schedule, outcome, current.attemptCount + 1, opts.finalAttempt ?? false);
this.invoices.set(invoiceId, invoice);
return { ...invoice };
}
private invoiceResult(id: string, schedule: StoredSchedule, outcome: "paid" | "failed" | "requires_action", attempt: number, finalAttempt: boolean): InvoiceInfo {
let paymentIntentId: string | null = null;
if (outcome === "paid") {
paymentIntentId = this.id("pi");
this.paymentIntents.set(paymentIntentId, {
id: paymentIntentId,
status: "succeeded",
amountReceived: schedule.params.amountCents,
paymentMethodId: schedule.params.paymentMethodId,
chargeId: this.id("ch"),
metadata: {},
});
}
return {
id,
status: outcome === "paid" ? "paid" : "open",
amountPaidCents: outcome === "paid" ? schedule.params.amountCents : 0,
paymentIntentId,
hostedInvoiceUrl: outcome === "paid" ? null : `https://invoice.stripe.test/${id}`,
attemptCount: attempt,
nextPaymentAttempt: outcome === "failed" && !finalAttempt ? new Date(Date.UTC(2027, 0, 1) + attempt * 86_400_000) : null,
metadata: schedule.params.metadata,
};
}
/** Summe aller ueber den Zeitplan eingezogenen Betraege. */
get billedCents(): number {
return [...this.invoices.values()].reduce((sum, i) => sum + i.amountPaidCents, 0);
}
async detachPaymentMethod(id: string): Promise<void> {
this.detached.push(id);
}