switched to paddle inline checkout, removed paypal and most of stripe. added product sync between app and paddle.
This commit is contained in:
@@ -119,6 +119,20 @@ export type CreditBalance = {
|
||||
free_event_granted_at?: string | null;
|
||||
};
|
||||
|
||||
export type PaddleTransactionSummary = {
|
||||
id: string | null;
|
||||
status: string | null;
|
||||
amount: number | null;
|
||||
currency: string | null;
|
||||
origin: string | null;
|
||||
checkout_id: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
receipt_url?: string | null;
|
||||
grand_total?: number | null;
|
||||
tax?: number | null;
|
||||
};
|
||||
|
||||
export type CreditLedgerEntry = {
|
||||
id: number;
|
||||
delta: number;
|
||||
@@ -444,6 +458,25 @@ function normalizeTenantPackage(pkg: JsonValue): TenantPackageSummary {
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePaddleTransaction(entry: JsonValue): PaddleTransactionSummary {
|
||||
const amountValue = entry.amount ?? entry.grand_total ?? (entry.totals && entry.totals.grand_total);
|
||||
const taxValue = entry.tax ?? (entry.totals && entry.totals.tax_total);
|
||||
|
||||
return {
|
||||
id: typeof entry.id === 'string' ? entry.id : entry.id ? String(entry.id) : null,
|
||||
status: entry.status ?? null,
|
||||
amount: amountValue !== undefined && amountValue !== null ? Number(amountValue) : null,
|
||||
currency: entry.currency ?? entry.currency_code ?? 'EUR',
|
||||
origin: entry.origin ?? null,
|
||||
checkout_id: entry.checkout_id ?? (entry.details?.checkout_id ?? null),
|
||||
created_at: entry.created_at ?? null,
|
||||
updated_at: entry.updated_at ?? null,
|
||||
receipt_url: entry.receipt_url ?? entry.invoice_url ?? null,
|
||||
grand_total: entry.grand_total !== undefined && entry.grand_total !== null ? Number(entry.grand_total) : null,
|
||||
tax: taxValue !== undefined && taxValue !== null ? Number(taxValue) : null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeTask(task: JsonValue): TenantTask {
|
||||
const titleTranslations = normalizeTranslationMap(task.title_translations ?? task.title ?? {});
|
||||
const descriptionTranslations = normalizeTranslationMap(task.description_translations ?? task.description ?? {});
|
||||
@@ -813,6 +846,35 @@ export async function getTenantPackagesOverview(): Promise<{
|
||||
return { packages, activePackage };
|
||||
}
|
||||
|
||||
export async function getTenantPaddleTransactions(cursor?: string): Promise<{
|
||||
data: PaddleTransactionSummary[];
|
||||
nextCursor: string | null;
|
||||
hasMore: boolean;
|
||||
}> {
|
||||
const query = cursor ? `?cursor=${encodeURIComponent(cursor)}` : '';
|
||||
const response = await authorizedFetch(`/api/v1/tenant/billing/transactions${query}`);
|
||||
|
||||
if (response.status === 404) {
|
||||
return { data: [], nextCursor: null, hasMore: false };
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = await safeJson(response);
|
||||
console.error('[API] Failed to load Paddle transactions', response.status, payload);
|
||||
throw new Error('Failed to load Paddle transactions');
|
||||
}
|
||||
|
||||
const payload = await safeJson(response) ?? {};
|
||||
const entries = Array.isArray(payload.data) ? payload.data : [];
|
||||
const meta = payload.meta ?? {};
|
||||
|
||||
return {
|
||||
data: entries.map(normalizePaddleTransaction),
|
||||
nextCursor: typeof meta.next === 'string' ? meta.next : null,
|
||||
hasMore: Boolean(meta.has_more),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCreditBalance(): Promise<CreditBalance> {
|
||||
const response = await authorizedFetch('/api/v1/tenant/credits/balance');
|
||||
if (response.status === 404) {
|
||||
@@ -868,17 +930,17 @@ export async function createTenantPackagePaymentIntent(packageId: number): Promi
|
||||
export async function completeTenantPackagePurchase(params: {
|
||||
packageId: number;
|
||||
paymentMethodId?: string;
|
||||
paypalOrderId?: string;
|
||||
paddleTransactionId?: string;
|
||||
}): Promise<void> {
|
||||
const { packageId, paymentMethodId, paypalOrderId } = params;
|
||||
const { packageId, paymentMethodId, paddleTransactionId } = params;
|
||||
const payload: Record<string, unknown> = { package_id: packageId };
|
||||
|
||||
if (paymentMethodId) {
|
||||
payload.payment_method_id = paymentMethodId;
|
||||
}
|
||||
|
||||
if (paypalOrderId) {
|
||||
payload.paypal_order_id = paypalOrderId;
|
||||
if (paddleTransactionId) {
|
||||
payload.paddle_transaction_id = paddleTransactionId;
|
||||
}
|
||||
|
||||
const response = await authorizedFetch('/api/v1/tenant/packages/complete', {
|
||||
@@ -904,8 +966,8 @@ export async function assignFreeTenantPackage(packageId: number): Promise<void>
|
||||
await jsonOrThrow(response, 'Failed to assign free package');
|
||||
}
|
||||
|
||||
export async function createTenantPayPalOrder(packageId: number): Promise<string> {
|
||||
const response = await authorizedFetch('/api/v1/tenant/packages/paypal-create', {
|
||||
export async function createTenantPaddleCheckout(packageId: number): Promise<{ checkout_url: string }> {
|
||||
const response = await authorizedFetch('/api/v1/tenant/packages/paddle-checkout', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -913,24 +975,12 @@ export async function createTenantPayPalOrder(packageId: number): Promise<string
|
||||
body: JSON.stringify({ package_id: packageId }),
|
||||
});
|
||||
|
||||
const data = await jsonOrThrow<{ orderID: string }>(response, 'Failed to create PayPal order');
|
||||
if (!data.orderID) {
|
||||
throw new Error('Missing PayPal order ID');
|
||||
const data = await jsonOrThrow<{ checkout_url: string }>(response, 'Failed to create Paddle checkout');
|
||||
if (!data.checkout_url) {
|
||||
throw new Error('Missing Paddle checkout URL');
|
||||
}
|
||||
|
||||
return data.orderID;
|
||||
}
|
||||
|
||||
export async function captureTenantPayPalOrder(orderId: string): Promise<void> {
|
||||
const response = await authorizedFetch('/api/v1/tenant/packages/paypal-capture', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ order_id: orderId }),
|
||||
});
|
||||
|
||||
await jsonOrThrow(response, 'Failed to capture PayPal order');
|
||||
return { checkout_url: data.checkout_url };
|
||||
}
|
||||
|
||||
export async function recordCreditPurchase(payload: {
|
||||
|
||||
@@ -58,6 +58,7 @@ export interface StoredTokens {
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
scope?: string;
|
||||
clientId?: string;
|
||||
}
|
||||
|
||||
export interface TokenResponse {
|
||||
@@ -83,13 +84,14 @@ export function loadTokens(): StoredTokens | null {
|
||||
return stored;
|
||||
}
|
||||
|
||||
export function saveTokens(response: TokenResponse): StoredTokens {
|
||||
export function saveTokens(response: TokenResponse, clientId: string = getClientId()): StoredTokens {
|
||||
const expiresAt = Date.now() + Math.max(response.expires_in - 30, 0) * 1000;
|
||||
const stored: StoredTokens = {
|
||||
accessToken: response.access_token,
|
||||
refreshToken: response.refresh_token,
|
||||
expiresAt,
|
||||
scope: response.scope,
|
||||
clientId,
|
||||
};
|
||||
localStorage.setItem(TOKEN_STORAGE_KEY, JSON.stringify(stored));
|
||||
return stored;
|
||||
@@ -110,19 +112,21 @@ export async function ensureAccessToken(): Promise<string> {
|
||||
return tokens.accessToken;
|
||||
}
|
||||
|
||||
return refreshAccessToken(tokens.refreshToken);
|
||||
return refreshAccessToken(tokens);
|
||||
}
|
||||
|
||||
async function refreshAccessToken(refreshToken: string): Promise<string> {
|
||||
if (!refreshToken) {
|
||||
async function refreshAccessToken(tokens: StoredTokens): Promise<string> {
|
||||
const clientId = tokens.clientId ?? getClientId();
|
||||
|
||||
if (!tokens.refreshToken) {
|
||||
notifyAuthFailure();
|
||||
throw new AuthError('unauthenticated', 'Missing refresh token');
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshToken,
|
||||
client_id: getClientId(),
|
||||
refresh_token: tokens.refreshToken,
|
||||
client_id: clientId,
|
||||
});
|
||||
|
||||
const response = await fetch(TOKEN_ENDPOINT, {
|
||||
@@ -138,7 +142,7 @@ async function refreshAccessToken(refreshToken: string): Promise<string> {
|
||||
}
|
||||
|
||||
const data = (await response.json()) as TokenResponse;
|
||||
const stored = saveTokens(data);
|
||||
const stored = saveTokens(data, clientId);
|
||||
return stored.accessToken;
|
||||
}
|
||||
|
||||
@@ -215,10 +219,12 @@ export async function completeOAuthCallback(params: URLSearchParams): Promise<st
|
||||
localStorage.removeItem(CODE_VERIFIER_KEY);
|
||||
localStorage.removeItem(STATE_KEY);
|
||||
|
||||
const clientId = getClientId();
|
||||
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
client_id: getClientId(),
|
||||
client_id: clientId,
|
||||
redirect_uri: buildRedirectUri(),
|
||||
code_verifier: verifier,
|
||||
});
|
||||
@@ -237,7 +243,7 @@ export async function completeOAuthCallback(params: URLSearchParams): Promise<st
|
||||
}
|
||||
|
||||
const data = (await response.json()) as TokenResponse;
|
||||
saveTokens(data);
|
||||
saveTokens(data, clientId);
|
||||
|
||||
const redirectTarget = sessionStorage.getItem(REDIRECT_KEY);
|
||||
if (redirectTarget) {
|
||||
|
||||
@@ -4,6 +4,7 @@ if (import.meta.env.DEV || import.meta.env.VITE_ENABLE_TENANT_SWITCHER === 'true
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
scope?: string;
|
||||
clientId?: string;
|
||||
};
|
||||
|
||||
const CLIENTS: Record<string, string> = {
|
||||
@@ -29,11 +30,9 @@ if (import.meta.env.DEV || import.meta.env.VITE_ENABLE_TENANT_SWITCHER === 'true
|
||||
localStorage.setItem('tenant_oauth_tokens.v1', JSON.stringify(tokens));
|
||||
window.location.assign('/event-admin/dashboard');
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
console.error('[DevAuth] Failed to login', error.message);
|
||||
} else {
|
||||
console.error('[DevAuth] Failed to login', error);
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error('[DevAuth] Failed to login', message);
|
||||
throw error instanceof Error ? error : new Error(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +83,7 @@ if (import.meta.env.DEV || import.meta.env.VITE_ENABLE_TENANT_SWITCHER === 'true
|
||||
refreshToken: body.refresh_token,
|
||||
expiresAt: Date.now() + Math.max(expiresIn - 30, 0) * 1000,
|
||||
scope: body.scope,
|
||||
clientId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -126,9 +126,11 @@ function requestAuthorization(url: string): Promise<URL> {
|
||||
}
|
||||
|
||||
const responseUrl = xhr.responseURL || xhr.getResponseHeader('Location');
|
||||
if (xhr.status >= 200 && xhr.status < 400 && responseUrl) {
|
||||
resolve(new URL(responseUrl, window.location.origin));
|
||||
return;
|
||||
if ((xhr.status >= 200 && xhr.status < 400) || xhr.status === 0) {
|
||||
if (responseUrl) {
|
||||
resolve(new URL(responseUrl, window.location.origin));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
reject(new Error(`Authorize failed with ${xhr.status}`));
|
||||
|
||||
@@ -45,6 +45,27 @@
|
||||
"available": "Verfügbar",
|
||||
"expires": "Läuft ab"
|
||||
}
|
||||
},
|
||||
"transactions": {
|
||||
"title": "Paddle-Transaktionen",
|
||||
"description": "Neueste Paddle-Transaktionen für diesen Tenant.",
|
||||
"empty": "Noch keine Paddle-Transaktionen.",
|
||||
"labels": {
|
||||
"transactionId": "Transaktion {{id}}",
|
||||
"checkoutId": "Checkout-ID: {{id}}",
|
||||
"origin": "Herkunft: {{origin}}",
|
||||
"receipt": "Beleg ansehen",
|
||||
"tax": "Steuer: {{value}}"
|
||||
},
|
||||
"status": {
|
||||
"completed": "Abgeschlossen",
|
||||
"processing": "Verarbeitung",
|
||||
"failed": "Fehlgeschlagen",
|
||||
"cancelled": "Storniert",
|
||||
"unknown": "Unbekannt"
|
||||
},
|
||||
"loadMore": "Weitere Transaktionen laden",
|
||||
"loadingMore": "Laden…"
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
@@ -149,8 +170,7 @@
|
||||
"high": "Hoch",
|
||||
"urgent": "Dringend"
|
||||
}
|
||||
}
|
||||
,
|
||||
},
|
||||
"collections": {
|
||||
"title": "Aufgabenvorlagen",
|
||||
"subtitle": "Durchstöbere kuratierte Vorlagen oder aktiviere sie für deine Events.",
|
||||
@@ -244,58 +264,56 @@
|
||||
"cancel": "Abbrechen",
|
||||
"submit": "Emotion speichern"
|
||||
}
|
||||
}
|
||||
,
|
||||
"management": {
|
||||
"billing": {
|
||||
"title": "Pakete & Abrechnung",
|
||||
"subtitle": "Verwalte deine gebuchten Pakete und behalte Laufzeiten im Blick.",
|
||||
"actions": {
|
||||
"refresh": "Aktualisieren",
|
||||
"exportCsv": "Export als CSV"
|
||||
},
|
||||
"errors": {
|
||||
"load": "Paketdaten konnten nicht geladen werden.",
|
||||
"more": "Weitere Einträge konnten nicht geladen werden."
|
||||
},
|
||||
"sections": {
|
||||
"overview": {
|
||||
"title": "Paketübersicht",
|
||||
"description": "Dein aktives Paket und die wichtigsten Kennzahlen.",
|
||||
"empty": "Noch kein Paket aktiv.",
|
||||
"emptyBadge": "Kein aktives Paket",
|
||||
"cards": {
|
||||
"package": {
|
||||
"label": "Aktives Paket",
|
||||
"helper": "Aktuell zugewiesen"
|
||||
},
|
||||
"used": {
|
||||
"label": "Genutzte Events",
|
||||
"helper": "Verfügbar: {{count}}"
|
||||
},
|
||||
"price": {
|
||||
"label": "Preis (netto)"
|
||||
},
|
||||
"expires": {
|
||||
"label": "Läuft ab",
|
||||
"helper": "Automatische Verlängerung, falls aktiv"
|
||||
}
|
||||
},
|
||||
"management": {
|
||||
"billing": {
|
||||
"title": "Pakete & Abrechnung",
|
||||
"subtitle": "Verwalte deine gebuchten Pakete und behalte Laufzeiten im Blick.",
|
||||
"actions": {
|
||||
"refresh": "Aktualisieren",
|
||||
"exportCsv": "Export als CSV"
|
||||
},
|
||||
"errors": {
|
||||
"load": "Paketdaten konnten nicht geladen werden.",
|
||||
"more": "Weitere Einträge konnten nicht geladen werden."
|
||||
},
|
||||
"sections": {
|
||||
"overview": {
|
||||
"title": "Paketübersicht",
|
||||
"description": "Dein aktives Paket und die wichtigsten Kennzahlen.",
|
||||
"empty": "Noch kein Paket aktiv.",
|
||||
"emptyBadge": "Kein aktives Paket",
|
||||
"cards": {
|
||||
"package": {
|
||||
"label": "Aktives Paket",
|
||||
"helper": "Aktuell zugewiesen"
|
||||
},
|
||||
"used": {
|
||||
"label": "Genutzte Events",
|
||||
"helper": "Verfügbar: {{count}}"
|
||||
},
|
||||
"price": {
|
||||
"label": "Preis (netto)"
|
||||
},
|
||||
"expires": {
|
||||
"label": "Läuft ab",
|
||||
"helper": "Automatische Verlängerung, falls aktiv"
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
"title": "Paket-Historie",
|
||||
"description": "Übersicht über aktuelle und vergangene Pakete.",
|
||||
"empty": "Noch keine Pakete gebucht.",
|
||||
"card": {
|
||||
"statusActive": "Aktiv",
|
||||
"statusInactive": "Inaktiv",
|
||||
"used": "Genutzte Events",
|
||||
"available": "Verfügbar",
|
||||
"expires": "Läuft ab"
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
"title": "Paket-Historie",
|
||||
"description": "Übersicht über aktuelle und vergangene Pakete.",
|
||||
"empty": "Noch keine Pakete gebucht.",
|
||||
"card": {
|
||||
"statusActive": "Aktiv",
|
||||
"statusInactive": "Inaktiv",
|
||||
"used": "Genutzte Events",
|
||||
"available": "Verfügbar",
|
||||
"expires": "Läuft ab"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -165,46 +165,25 @@
|
||||
"failureTitle": "Aktivierung fehlgeschlagen",
|
||||
"errorMessage": "Kostenloses Paket konnte nicht aktiviert werden."
|
||||
},
|
||||
"stripe": {
|
||||
"sectionTitle": "Kartenzahlung (Stripe)",
|
||||
"heading": "Kartenzahlung",
|
||||
"notReady": "Zahlungsmodul noch nicht bereit. Bitte lade die Seite neu.",
|
||||
"genericError": "Zahlung fehlgeschlagen. Bitte erneut versuchen.",
|
||||
"missingPaymentId": "Zahlung konnte nicht bestätigt werden (fehlende Zahlungs-ID).",
|
||||
"completionFailed": "Der Kauf wurde bei uns noch nicht verbucht. Bitte kontaktiere den Support mit deiner Zahlungsbestätigung.",
|
||||
"errorTitle": "Zahlung fehlgeschlagen",
|
||||
"submitting": "Zahlung wird bestätigt …",
|
||||
"submit": "Jetzt bezahlen",
|
||||
"hint": "Sicherer Checkout über Stripe. Du erhältst eine Bestätigung, sobald der Kauf verbucht wurde.",
|
||||
"loading": "Zahlungsdetails werden geladen …",
|
||||
"unavailableTitle": "Stripe nicht verfügbar",
|
||||
"unavailableDescription": "Stripe konnte nicht initialisiert werden.",
|
||||
"missingKey": "Stripe Publishable Key fehlt. Bitte konfiguriere VITE_STRIPE_PUBLISHABLE_KEY.",
|
||||
"intentFailed": "Stripe-Zahlung konnte nicht vorbereitet werden."
|
||||
},
|
||||
"paypal": {
|
||||
"sectionTitle": "PayPal",
|
||||
"heading": "PayPal",
|
||||
"createFailed": "PayPal-Bestellung konnte nicht erstellt werden. Bitte versuche es erneut.",
|
||||
"captureFailed": "PayPal-Zahlung konnte nicht abgeschlossen werden. Bitte kontaktiere den Support, falls der Betrag bereits abgebucht wurde.",
|
||||
"errorTitle": "PayPal-Fehler",
|
||||
"genericError": "PayPal hat ein Problem gemeldet. Bitte versuche es später erneut.",
|
||||
"missingOrderId": "PayPal hat keine Order-ID geliefert.",
|
||||
"cancelled": "PayPal-Zahlung wurde abgebrochen.",
|
||||
"hint": "PayPal leitet dich ggf. weiter, um die Zahlung zu bestätigen. Anschließend kommst du automatisch zurück.",
|
||||
"notConfiguredTitle": "PayPal nicht konfiguriert",
|
||||
"notConfiguredDescription": "Hinterlege VITE_PAYPAL_CLIENT_ID, damit Gastgeber optional mit PayPal bezahlen können."
|
||||
"paddle": {
|
||||
"sectionTitle": "Paddle",
|
||||
"heading": "Checkout mit Paddle",
|
||||
"genericError": "Der Paddle-Checkout konnte nicht geöffnet werden. Bitte versuche es erneut.",
|
||||
"errorTitle": "Paddle-Fehler",
|
||||
"processing": "Paddle-Checkout wird geöffnet …",
|
||||
"cta": "Paddle-Checkout öffnen",
|
||||
"hint": "Es öffnet sich ein neuer Tab über Paddle (Merchant of Record). Schließe dort die Zahlung ab und kehre anschließend zurück."
|
||||
},
|
||||
"nextStepsTitle": "Nächste Schritte",
|
||||
"nextSteps": [
|
||||
"Optional: Abrechnung abschließen (Stripe/PayPal) im Billing-Bereich.",
|
||||
"Optional: Abrechnung über Paddle im Billing-Bereich abschließen.",
|
||||
"Event-Setup durchlaufen und Aufgaben, Team & Galerie konfigurieren.",
|
||||
"Vor dem Go-Live Credits prüfen und Gäste-Link teilen."
|
||||
],
|
||||
"cta": {
|
||||
"billing": {
|
||||
"label": "Abrechnung starten",
|
||||
"description": "Öffnet den Billing-Bereich mit allen Kaufoptionen (Stripe, PayPal, Credits).",
|
||||
"description": "Öffnet den Billing-Bereich mit Paddle- und Credit-Optionen.",
|
||||
"button": "Zu Billing & Zahlung"
|
||||
},
|
||||
"setup": {
|
||||
@@ -261,8 +240,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -45,6 +45,27 @@
|
||||
"available": "Remaining",
|
||||
"expires": "Expires"
|
||||
}
|
||||
},
|
||||
"transactions": {
|
||||
"title": "Paddle transactions",
|
||||
"description": "Recent Paddle transactions for this tenant.",
|
||||
"empty": "No Paddle transactions yet.",
|
||||
"labels": {
|
||||
"transactionId": "Transaction {{id}}",
|
||||
"checkoutId": "Checkout ID: {{id}}",
|
||||
"origin": "Origin: {{origin}}",
|
||||
"receipt": "View receipt",
|
||||
"tax": "Tax: {{value}}"
|
||||
},
|
||||
"status": {
|
||||
"completed": "Completed",
|
||||
"processing": "Processing",
|
||||
"failed": "Failed",
|
||||
"cancelled": "Cancelled",
|
||||
"unknown": "Unknown"
|
||||
},
|
||||
"loadMore": "Load more transactions",
|
||||
"loadingMore": "Loading…"
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
@@ -149,8 +170,7 @@
|
||||
"high": "High",
|
||||
"urgent": "Urgent"
|
||||
}
|
||||
}
|
||||
,
|
||||
},
|
||||
"collections": {
|
||||
"title": "Task collections",
|
||||
"subtitle": "Browse curated task bundles or activate them for your events.",
|
||||
@@ -244,57 +264,56 @@
|
||||
"cancel": "Cancel",
|
||||
"submit": "Save emotion"
|
||||
}
|
||||
}
|
||||
,
|
||||
"management": {
|
||||
"billing": {
|
||||
"title": "Packages & billing",
|
||||
"subtitle": "Manage your purchased packages and track their durations.",
|
||||
"actions": {
|
||||
"refresh": "Refresh",
|
||||
"exportCsv": "Export CSV"
|
||||
},
|
||||
"errors": {
|
||||
"load": "Unable to load package data.",
|
||||
"more": "Unable to load more entries."
|
||||
},
|
||||
"sections": {
|
||||
"overview": {
|
||||
"title": "Package overview",
|
||||
"description": "Your active package and the most important metrics.",
|
||||
"empty": "No active package yet.",
|
||||
"emptyBadge": "No active package",
|
||||
"cards": {
|
||||
"package": {
|
||||
"label": "Active package",
|
||||
"helper": "Currently assigned"
|
||||
},
|
||||
"used": {
|
||||
"label": "Events used",
|
||||
"helper": "Remaining: {{count}}"
|
||||
},
|
||||
"price": {
|
||||
"label": "Price (net)"
|
||||
},
|
||||
"expires": {
|
||||
"label": "Expires",
|
||||
"helper": "Auto-renews if enabled"
|
||||
}
|
||||
},
|
||||
"management": {
|
||||
"billing": {
|
||||
"title": "Packages & billing",
|
||||
"subtitle": "Manage your purchased packages and track their durations.",
|
||||
"actions": {
|
||||
"refresh": "Refresh",
|
||||
"exportCsv": "Export CSV"
|
||||
},
|
||||
"errors": {
|
||||
"load": "Unable to load package data.",
|
||||
"more": "Unable to load more entries."
|
||||
},
|
||||
"sections": {
|
||||
"overview": {
|
||||
"title": "Package overview",
|
||||
"description": "Your active package and the most important metrics.",
|
||||
"empty": "No active package yet.",
|
||||
"emptyBadge": "No active package",
|
||||
"cards": {
|
||||
"package": {
|
||||
"label": "Active package",
|
||||
"helper": "Currently assigned"
|
||||
},
|
||||
"used": {
|
||||
"label": "Events used",
|
||||
"helper": "Remaining: {{count}}"
|
||||
},
|
||||
"price": {
|
||||
"label": "Price (net)"
|
||||
},
|
||||
"expires": {
|
||||
"label": "Expires",
|
||||
"helper": "Auto-renews if enabled"
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
"title": "Package history",
|
||||
"description": "Overview of current and past packages.",
|
||||
"empty": "No packages purchased yet.",
|
||||
"card": {
|
||||
"statusActive": "Active",
|
||||
"statusInactive": "Inactive",
|
||||
"used": "Used events",
|
||||
"available": "Available",
|
||||
"expires": "Expires"
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages": {
|
||||
"title": "Package history",
|
||||
"description": "Overview of current and past packages.",
|
||||
"empty": "No packages purchased yet.",
|
||||
"card": {
|
||||
"statusActive": "Active",
|
||||
"statusInactive": "Inactive",
|
||||
"used": "Used events",
|
||||
"available": "Available",
|
||||
"expires": "Expires"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,46 +165,25 @@
|
||||
"failureTitle": "Activation failed",
|
||||
"errorMessage": "The free package could not be activated."
|
||||
},
|
||||
"stripe": {
|
||||
"sectionTitle": "Card payment (Stripe)",
|
||||
"heading": "Card payment",
|
||||
"notReady": "Payment module not ready yet. Please refresh.",
|
||||
"genericError": "Payment failed. Please try again.",
|
||||
"missingPaymentId": "Could not confirm payment (missing payment ID).",
|
||||
"completionFailed": "Purchase not recorded yet. Contact support with your payment confirmation.",
|
||||
"errorTitle": "Payment failed",
|
||||
"submitting": "Confirming payment …",
|
||||
"submit": "Pay now",
|
||||
"hint": "Secure checkout via Stripe. You'll receive confirmation once recorded.",
|
||||
"loading": "Loading payment details …",
|
||||
"unavailableTitle": "Stripe unavailable",
|
||||
"unavailableDescription": "Stripe could not be initialised.",
|
||||
"missingKey": "Stripe publishable key missing. Configure VITE_STRIPE_PUBLISHABLE_KEY.",
|
||||
"intentFailed": "Stripe could not prepare the payment."
|
||||
},
|
||||
"paypal": {
|
||||
"sectionTitle": "PayPal",
|
||||
"heading": "PayPal",
|
||||
"createFailed": "PayPal order could not be created. Please try again.",
|
||||
"captureFailed": "PayPal payment could not be captured. Contact support if funds were withdrawn.",
|
||||
"errorTitle": "PayPal error",
|
||||
"genericError": "PayPal reported a problem. Please try again later.",
|
||||
"missingOrderId": "PayPal did not return an order ID.",
|
||||
"cancelled": "PayPal payment was cancelled.",
|
||||
"hint": "PayPal may redirect you briefly to confirm. You'll return automatically afterwards.",
|
||||
"notConfiguredTitle": "PayPal not configured",
|
||||
"notConfiguredDescription": "Provide VITE_PAYPAL_CLIENT_ID so hosts can pay with PayPal."
|
||||
"paddle": {
|
||||
"sectionTitle": "Paddle",
|
||||
"heading": "Checkout with Paddle",
|
||||
"genericError": "The Paddle checkout could not be opened. Please try again.",
|
||||
"errorTitle": "Paddle error",
|
||||
"processing": "Opening the Paddle checkout …",
|
||||
"cta": "Open Paddle checkout",
|
||||
"hint": "A new tab opens via Paddle (merchant of record). Complete the payment there, then return to continue."
|
||||
},
|
||||
"nextStepsTitle": "Next steps",
|
||||
"nextSteps": [
|
||||
"Optional: finish billing (Stripe/PayPal) inside the billing area.",
|
||||
"Optional: finish billing via Paddle inside the billing area.",
|
||||
"Complete the event setup and configure tasks, team, and gallery.",
|
||||
"Check credits before go-live and share your guest link."
|
||||
],
|
||||
"cta": {
|
||||
"billing": {
|
||||
"label": "Start billing",
|
||||
"description": "Opens the billing area with Stripe, PayPal, and credit options.",
|
||||
"description": "Opens the billing area with Paddle and credit options.",
|
||||
"button": "Go to billing"
|
||||
},
|
||||
"setup": {
|
||||
@@ -261,4 +240,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,176 +1,65 @@
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import {
|
||||
StripeCheckoutForm,
|
||||
PayPalCheckout,
|
||||
} from '../pages/WelcomeOrderSummaryPage';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { PaddleCheckout } from '../pages/WelcomeOrderSummaryPage';
|
||||
|
||||
const stripeRef: { current: any } = { current: null };
|
||||
const elementsRef: { current: any } = { current: null };
|
||||
const paypalPropsRef: { current: any } = { current: null };
|
||||
|
||||
const {
|
||||
confirmPaymentMock,
|
||||
completePurchaseMock,
|
||||
createPayPalOrderMock,
|
||||
capturePayPalOrderMock,
|
||||
} = vi.hoisted(() => ({
|
||||
confirmPaymentMock: vi.fn(),
|
||||
completePurchaseMock: vi.fn(),
|
||||
createPayPalOrderMock: vi.fn(),
|
||||
capturePayPalOrderMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@stripe/react-stripe-js', () => ({
|
||||
useStripe: () => stripeRef.current,
|
||||
useElements: () => elementsRef.current,
|
||||
PaymentElement: () => <div data-testid="stripe-payment-element" />,
|
||||
Elements: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
|
||||
vi.mock('@paypal/react-paypal-js', () => ({
|
||||
PayPalScriptProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
PayPalButtons: (props: any) => {
|
||||
paypalPropsRef.current = props;
|
||||
return <button type="button" data-testid="paypal-button">PayPal</button>;
|
||||
},
|
||||
const { createPaddleCheckoutMock } = vi.hoisted(() => ({
|
||||
createPaddleCheckoutMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api', () => ({
|
||||
completeTenantPackagePurchase: completePurchaseMock,
|
||||
createTenantPackagePaymentIntent: vi.fn(),
|
||||
assignFreeTenantPackage: vi.fn(),
|
||||
createTenantPayPalOrder: createPayPalOrderMock,
|
||||
captureTenantPayPalOrder: capturePayPalOrderMock,
|
||||
createTenantPaddleCheckout: createPaddleCheckoutMock,
|
||||
}));
|
||||
|
||||
describe('StripeCheckoutForm', () => {
|
||||
describe('PaddleCheckout', () => {
|
||||
beforeEach(() => {
|
||||
confirmPaymentMock.mockReset();
|
||||
completePurchaseMock.mockReset();
|
||||
stripeRef.current = { confirmPayment: confirmPaymentMock };
|
||||
elementsRef.current = {};
|
||||
createPaddleCheckoutMock.mockReset();
|
||||
});
|
||||
|
||||
const renderStripeForm = (overrides?: Partial<React.ComponentProps<typeof StripeCheckoutForm>>) =>
|
||||
render(
|
||||
<StripeCheckoutForm
|
||||
clientSecret="secret"
|
||||
packageId={42}
|
||||
onSuccess={vi.fn()}
|
||||
t={(key: string) => key}
|
||||
{...overrides}
|
||||
/>
|
||||
);
|
||||
|
||||
it('completes the purchase when Stripe reports a successful payment', async () => {
|
||||
const onSuccess = vi.fn();
|
||||
confirmPaymentMock.mockResolvedValue({
|
||||
error: null,
|
||||
paymentIntent: { payment_method: 'pm_123' },
|
||||
});
|
||||
completePurchaseMock.mockResolvedValue(undefined);
|
||||
|
||||
const { container } = renderStripeForm({ onSuccess });
|
||||
const form = container.querySelector('form');
|
||||
expect(form).toBeTruthy();
|
||||
fireEvent.submit(form!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(completePurchaseMock).toHaveBeenCalledWith({
|
||||
packageId: 42,
|
||||
paymentMethodId: 'pm_123',
|
||||
});
|
||||
});
|
||||
expect(onSuccess).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows Stripe errors returned by confirmPayment', async () => {
|
||||
confirmPaymentMock.mockResolvedValue({
|
||||
error: { message: 'Card declined' },
|
||||
});
|
||||
|
||||
const { container } = renderStripeForm();
|
||||
fireEvent.submit(container.querySelector('form')!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Card declined')).toBeInTheDocument();
|
||||
});
|
||||
expect(completePurchaseMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports missing payment method id', async () => {
|
||||
confirmPaymentMock.mockResolvedValue({
|
||||
error: null,
|
||||
paymentIntent: {},
|
||||
});
|
||||
|
||||
const { container } = renderStripeForm();
|
||||
fireEvent.submit(container.querySelector('form')!);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('summary.stripe.missingPaymentId')).toBeInTheDocument();
|
||||
});
|
||||
expect(completePurchaseMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PayPalCheckout', () => {
|
||||
beforeEach(() => {
|
||||
paypalPropsRef.current = null;
|
||||
createPayPalOrderMock.mockReset();
|
||||
capturePayPalOrderMock.mockReset();
|
||||
});
|
||||
|
||||
it('creates and captures a PayPal order successfully', async () => {
|
||||
createPayPalOrderMock.mockResolvedValue('ORDER-123');
|
||||
capturePayPalOrderMock.mockResolvedValue(undefined);
|
||||
it('opens Paddle checkout when created successfully', async () => {
|
||||
createPaddleCheckoutMock.mockResolvedValue({ checkout_url: 'https://paddle.example/checkout' });
|
||||
const onSuccess = vi.fn();
|
||||
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
|
||||
render(
|
||||
<PayPalCheckout
|
||||
<PaddleCheckout
|
||||
packageId={99}
|
||||
onSuccess={onSuccess}
|
||||
t={(key: string) => key}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(paypalPropsRef.current).toBeTruthy();
|
||||
const { createOrder, onApprove } = paypalPropsRef.current;
|
||||
await act(async () => {
|
||||
const orderId = await createOrder();
|
||||
expect(orderId).toBe('ORDER-123');
|
||||
});
|
||||
await act(async () => {
|
||||
await onApprove({ orderID: 'ORDER-123' });
|
||||
screen.getByRole('button').click();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createPayPalOrderMock).toHaveBeenCalledWith(99);
|
||||
expect(capturePayPalOrderMock).toHaveBeenCalledWith('ORDER-123');
|
||||
expect(createPaddleCheckoutMock).toHaveBeenCalledWith(99);
|
||||
expect(openSpy).toHaveBeenCalledWith('https://paddle.example/checkout', '_blank', 'noopener');
|
||||
expect(onSuccess).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
openSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('surfaces missing order id errors', async () => {
|
||||
createPayPalOrderMock.mockResolvedValue('ORDER-123');
|
||||
it('shows an error message on failure', async () => {
|
||||
createPaddleCheckoutMock.mockRejectedValue(new Error('boom'));
|
||||
|
||||
render(
|
||||
<PayPalCheckout
|
||||
<PaddleCheckout
|
||||
packageId={99}
|
||||
onSuccess={vi.fn()}
|
||||
t={(key: string) => key}
|
||||
/>
|
||||
);
|
||||
|
||||
const { onApprove } = paypalPropsRef.current;
|
||||
await act(async () => {
|
||||
await onApprove({ orderID: undefined });
|
||||
screen.getByRole('button').click();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('summary.paypal.missingOrderId')).toBeInTheDocument();
|
||||
expect(screen.getByText('summary.paddle.genericError')).toBeInTheDocument();
|
||||
});
|
||||
expect(capturePayPalOrderMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,6 @@ import {
|
||||
AlertTriangle,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Elements, PaymentElement, useElements, useStripe } from "@stripe/react-stripe-js";
|
||||
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
|
||||
|
||||
import {
|
||||
TenantWelcomeLayout,
|
||||
@@ -26,30 +24,15 @@ import { ADMIN_BILLING_PATH, ADMIN_WELCOME_EVENT_PATH, ADMIN_WELCOME_PACKAGES_PA
|
||||
import { useTenantPackages } from "../hooks/useTenantPackages";
|
||||
import {
|
||||
assignFreeTenantPackage,
|
||||
completeTenantPackagePurchase,
|
||||
createTenantPackagePaymentIntent,
|
||||
createTenantPayPalOrder,
|
||||
captureTenantPayPalOrder,
|
||||
createTenantPaddleCheckout,
|
||||
} from "../../api";
|
||||
import { getStripe } from '@/utils/stripe';
|
||||
|
||||
const stripePublishableKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY ?? "";
|
||||
const paypalClientId = import.meta.env.VITE_PAYPAL_CLIENT_ID ?? "";
|
||||
|
||||
type StripeCheckoutProps = {
|
||||
clientSecret: string;
|
||||
type PaddleCheckoutProps = {
|
||||
packageId: number;
|
||||
onSuccess: () => void;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
};
|
||||
|
||||
type PayPalCheckoutProps = {
|
||||
packageId: number;
|
||||
onSuccess: () => void;
|
||||
t: ReturnType<typeof useTranslation>["t"];
|
||||
currency?: string;
|
||||
};
|
||||
|
||||
function useLocaleFormats(locale: string) {
|
||||
const currencyFormatter = React.useMemo(
|
||||
() =>
|
||||
@@ -86,175 +69,53 @@ function humanizeFeature(t: ReturnType<typeof useTranslation>["t"], key: string)
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function StripeCheckoutForm({ clientSecret, packageId, onSuccess, t }: StripeCheckoutProps) {
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const [submitting, setSubmitting] = React.useState(false);
|
||||
function PaddleCheckout({ packageId, onSuccess, t }: PaddleCheckoutProps) {
|
||||
const [status, setStatus] = React.useState<'idle' | 'processing' | 'success' | 'error'>('idle');
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!stripe || !elements) {
|
||||
setError(t("summary.stripe.notReady"));
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
setError(null);
|
||||
|
||||
const result = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: window.location.href,
|
||||
},
|
||||
redirect: "if_required",
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message ?? t("summary.stripe.genericError"));
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const paymentIntent = result.paymentIntent;
|
||||
const paymentMethodId =
|
||||
typeof paymentIntent?.payment_method === "string"
|
||||
? paymentIntent.payment_method
|
||||
: typeof paymentIntent?.id === "string"
|
||||
? paymentIntent.id
|
||||
: null;
|
||||
|
||||
if (!paymentMethodId) {
|
||||
setError(t("summary.stripe.missingPaymentId"));
|
||||
setSubmitting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const handleCheckout = React.useCallback(async () => {
|
||||
try {
|
||||
await completeTenantPackagePurchase({
|
||||
packageId,
|
||||
paymentMethodId,
|
||||
});
|
||||
setStatus('processing');
|
||||
setError(null);
|
||||
const { checkout_url } = await createTenantPaddleCheckout(packageId);
|
||||
window.open(checkout_url, '_blank', 'noopener');
|
||||
setStatus('success');
|
||||
onSuccess();
|
||||
} catch (purchaseError) {
|
||||
console.error("[Onboarding] Purchase completion failed", purchaseError);
|
||||
setError(
|
||||
purchaseError instanceof Error
|
||||
? purchaseError.message
|
||||
: t("summary.stripe.completionFailed")
|
||||
);
|
||||
setSubmitting(false);
|
||||
} catch (err) {
|
||||
console.error('[Onboarding] Paddle checkout failed', err);
|
||||
setStatus('error');
|
||||
setError(err instanceof Error ? err.message : t('summary.paddle.genericError'));
|
||||
}
|
||||
};
|
||||
}, [packageId, onSuccess, t]);
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6 rounded-2xl border border-brand-rose-soft bg-brand-card p-6 shadow-brand-primary">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm font-medium text-brand-slate">{t("summary.stripe.heading")}</p>
|
||||
<PaymentElement id="payment-element" />
|
||||
</div>
|
||||
<div className="space-y-3 rounded-2xl border border-brand-rose-soft bg-white/85 p-6 shadow-inner">
|
||||
<p className="text-sm font-medium text-brand-slate">{t('summary.paddle.heading')}</p>
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t("summary.stripe.errorTitle")}</AlertTitle>
|
||||
<AlertTitle>{t('summary.paddle.errorTitle')}</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={submitting || !stripe || !elements}
|
||||
size="lg"
|
||||
className="w-full rounded-full bg-brand-rose text-white shadow-lg shadow-rose-400/40 hover:bg-[var(--brand-rose-strong)] disabled:opacity-60"
|
||||
disabled={status === 'processing'}
|
||||
onClick={handleCheckout}
|
||||
>
|
||||
{submitting ? (
|
||||
{status === 'processing' ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
{t("summary.stripe.submitting")}
|
||||
{t('summary.paddle.processing')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CreditCard className="mr-2 size-4" />
|
||||
{t("summary.stripe.submit")}
|
||||
{t('summary.paddle.cta')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
<p className="text-xs text-brand-navy/70">{t("summary.stripe.hint")}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function PayPalCheckout({ packageId, onSuccess, t, currency = "EUR" }: PayPalCheckoutProps) {
|
||||
const [status, setStatus] = React.useState<"idle" | "creating" | "capturing" | "error" | "success">("idle");
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const handleCreateOrder = React.useCallback(async () => {
|
||||
try {
|
||||
setStatus("creating");
|
||||
const orderId = await createTenantPayPalOrder(packageId);
|
||||
setStatus("idle");
|
||||
setError(null);
|
||||
return orderId;
|
||||
} catch (err) {
|
||||
console.error("[Onboarding] PayPal create order failed", err);
|
||||
setStatus("error");
|
||||
setError(
|
||||
err instanceof Error ? err.message : t("summary.paypal.createFailed")
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
}, [packageId, t]);
|
||||
|
||||
const handleApprove = React.useCallback(
|
||||
async (orderId: string) => {
|
||||
try {
|
||||
setStatus("capturing");
|
||||
await captureTenantPayPalOrder(orderId);
|
||||
setStatus("success");
|
||||
setError(null);
|
||||
onSuccess();
|
||||
} catch (err) {
|
||||
console.error("[Onboarding] PayPal capture failed", err);
|
||||
setStatus("error");
|
||||
setError(
|
||||
err instanceof Error ? err.message : t("summary.paypal.captureFailed")
|
||||
);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
[onSuccess, t]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-3 rounded-2xl border border-brand-rose-soft bg-white/85 p-6 shadow-inner">
|
||||
<p className="text-sm font-medium text-brand-slate">{t("summary.paypal.heading")}</p>
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t("summary.paypal.errorTitle")}</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<PayPalButtons
|
||||
style={{ layout: "vertical" }}
|
||||
forceReRender={[packageId, currency]}
|
||||
createOrder={async () => handleCreateOrder()}
|
||||
onApprove={async (data) => {
|
||||
if (!data.orderID) {
|
||||
setError(t("summary.paypal.missingOrderId"));
|
||||
setStatus("error");
|
||||
return;
|
||||
}
|
||||
await handleApprove(data.orderID);
|
||||
}}
|
||||
onError={(err) => {
|
||||
console.error("[Onboarding] PayPal onError", err);
|
||||
setStatus("error");
|
||||
setError(t("summary.paypal.genericError"));
|
||||
}}
|
||||
onCancel={() => {
|
||||
setStatus("idle");
|
||||
setError(t("summary.paypal.cancelled"));
|
||||
}}
|
||||
disabled={status === "creating" || status === "capturing"}
|
||||
/>
|
||||
<p className="text-xs text-brand-navy/70">{t("summary.paypal.hint")}</p>
|
||||
<p className="text-xs text-brand-navy/70">{t('summary.paddle.hint')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -267,7 +128,6 @@ export default function WelcomeOrderSummaryPage() {
|
||||
const { t, i18n } = useTranslation("onboarding");
|
||||
const locale = i18n.language?.startsWith("en") ? "en-GB" : "de-DE";
|
||||
const { currencyFormatter, dateFormatter } = useLocaleFormats(locale);
|
||||
const stripePromise = React.useMemo(() => getStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
|
||||
const packageIdFromState = typeof location.state === "object" ? (location.state as any)?.packageId : undefined;
|
||||
const selectedPackageId = progress.selectedPackage?.id ?? packageIdFromState ?? null;
|
||||
@@ -295,48 +155,9 @@ export default function WelcomeOrderSummaryPage() {
|
||||
const isSubscription = Boolean(packageDetails?.features?.subscription);
|
||||
const requiresPayment = Boolean(packageDetails && packageDetails.price > 0);
|
||||
|
||||
const [clientSecret, setClientSecret] = React.useState<string | null>(null);
|
||||
const [intentStatus, setIntentStatus] = React.useState<"idle" | "loading" | "error" | "ready">("idle");
|
||||
const [intentError, setIntentError] = React.useState<string | null>(null);
|
||||
const [freeAssignStatus, setFreeAssignStatus] = React.useState<"idle" | "loading" | "success" | "error">("idle");
|
||||
const [freeAssignError, setFreeAssignError] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!requiresPayment || !packageDetails) {
|
||||
setClientSecret(null);
|
||||
setIntentStatus("idle");
|
||||
setIntentError(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!stripePromise) {
|
||||
setIntentError(t("summary.stripe.missingKey"));
|
||||
setIntentStatus("error");
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setIntentStatus("loading");
|
||||
setIntentError(null);
|
||||
|
||||
createTenantPackagePaymentIntent(packageDetails.id)
|
||||
.then((secret) => {
|
||||
if (cancelled) return;
|
||||
setClientSecret(secret);
|
||||
setIntentStatus("ready");
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[Onboarding] Payment intent failed", error);
|
||||
if (cancelled) return;
|
||||
setIntentStatus("error");
|
||||
setIntentError(error instanceof Error ? error.message : t("summary.stripe.intentFailed"));
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [requiresPayment, packageDetails, stripePromise, t]);
|
||||
|
||||
const priceText =
|
||||
progress.selectedPackage?.priceText ??
|
||||
(packageDetails && typeof packageDetails.price === "number"
|
||||
@@ -534,63 +355,16 @@ export default function WelcomeOrderSummaryPage() {
|
||||
)}
|
||||
|
||||
{requiresPayment && (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-lg font-semibold text-brand-slate">{t("summary.stripe.sectionTitle")}</h4>
|
||||
{intentStatus === "loading" && (
|
||||
<div className="flex items-center gap-3 rounded-2xl border border-brand-rose-soft bg-brand-card p-6 text-sm text-brand-navy/80">
|
||||
<Loader2 className="size-4 animate-spin text-brand-rose" />
|
||||
{t("summary.stripe.loading")}
|
||||
</div>
|
||||
)}
|
||||
{intentStatus === "error" && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t("summary.stripe.unavailableTitle")}</AlertTitle>
|
||||
<AlertDescription>{intentError ?? t("summary.stripe.unavailableDescription")}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{intentStatus === "ready" && clientSecret && stripePromise && (
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<StripeCheckoutForm
|
||||
clientSecret={clientSecret}
|
||||
packageId={packageDetails.id}
|
||||
onSuccess={() => {
|
||||
markStep({ packageSelected: true });
|
||||
navigate(ADMIN_WELCOME_EVENT_PATH, { replace: true });
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{paypalClientId ? (
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-lg font-semibold text-brand-slate">{t("summary.paypal.sectionTitle")}</h4>
|
||||
<PayPalScriptProvider
|
||||
options={{
|
||||
clientId: paypalClientId,
|
||||
"client-id": paypalClientId,
|
||||
currency: "EUR",
|
||||
intent: "CAPTURE",
|
||||
}}
|
||||
>
|
||||
<PayPalCheckout
|
||||
packageId={packageDetails.id}
|
||||
onSuccess={() => {
|
||||
markStep({ packageSelected: true });
|
||||
navigate(ADMIN_WELCOME_EVENT_PATH, { replace: true });
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
</PayPalScriptProvider>
|
||||
</div>
|
||||
) : (
|
||||
<Alert variant="default" className="border-amber-200 bg-amber-50 text-amber-700">
|
||||
<AlertTitle>{t("summary.paypal.notConfiguredTitle")}</AlertTitle>
|
||||
<AlertDescription>{t("summary.paypal.notConfiguredDescription")}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="space-y-4">
|
||||
<h4 className="text-lg font-semibold text-brand-slate">{t('summary.paddle.sectionTitle')}</h4>
|
||||
<PaddleCheckout
|
||||
packageId={packageDetails.id}
|
||||
onSuccess={() => {
|
||||
markStep({ packageSelected: true });
|
||||
navigate(ADMIN_WELCOME_EVENT_PATH, { replace: true });
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -634,4 +408,4 @@ export default function WelcomeOrderSummaryPage() {
|
||||
);
|
||||
}
|
||||
|
||||
export { StripeCheckoutForm, PayPalCheckout };
|
||||
export { PaddleCheckout };
|
||||
|
||||
@@ -9,7 +9,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
import { AdminLayout } from '../components/AdminLayout';
|
||||
import { getTenantPackagesOverview, TenantPackageSummary } from '../api';
|
||||
import { getTenantPackagesOverview, getTenantPaddleTransactions, PaddleTransactionSummary, TenantPackageSummary } from '../api';
|
||||
import { isAuthError } from '../auth/tokens';
|
||||
|
||||
export default function BillingPage() {
|
||||
@@ -21,6 +21,10 @@ export default function BillingPage() {
|
||||
|
||||
const [packages, setPackages] = React.useState<TenantPackageSummary[]>([]);
|
||||
const [activePackage, setActivePackage] = React.useState<TenantPackageSummary | null>(null);
|
||||
const [transactions, setTransactions] = React.useState<PaddleTransactionSummary[]>([]);
|
||||
const [transactionCursor, setTransactionCursor] = React.useState<string | null>(null);
|
||||
const [transactionsHasMore, setTransactionsHasMore] = React.useState(false);
|
||||
const [transactionsLoading, setTransactionsLoading] = React.useState(false);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
@@ -57,9 +61,18 @@ export default function BillingPage() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const packagesResult = await getTenantPackagesOverview();
|
||||
const [packagesResult, paddleTransactions] = await Promise.all([
|
||||
getTenantPackagesOverview(),
|
||||
getTenantPaddleTransactions().catch((err) => {
|
||||
console.warn('Failed to load Paddle transactions', err);
|
||||
return { data: [] as PaddleTransactionSummary[], nextCursor: null, hasMore: false };
|
||||
}),
|
||||
]);
|
||||
setPackages(packagesResult.packages);
|
||||
setActivePackage(packagesResult.activePackage);
|
||||
setTransactions(paddleTransactions.data);
|
||||
setTransactionCursor(paddleTransactions.nextCursor);
|
||||
setTransactionsHasMore(paddleTransactions.hasMore);
|
||||
} catch (err) {
|
||||
if (!isAuthError(err)) {
|
||||
setError(t('billing.errors.load'));
|
||||
@@ -69,6 +82,25 @@ export default function BillingPage() {
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
const loadMoreTransactions = React.useCallback(async () => {
|
||||
if (!transactionsHasMore || transactionsLoading || !transactionCursor) {
|
||||
return;
|
||||
}
|
||||
|
||||
setTransactionsLoading(true);
|
||||
try {
|
||||
const result = await getTenantPaddleTransactions(transactionCursor);
|
||||
setTransactions((current) => [...current, ...result.data]);
|
||||
setTransactionCursor(result.nextCursor);
|
||||
setTransactionsHasMore(result.hasMore && Boolean(result.nextCursor));
|
||||
} catch (error) {
|
||||
console.warn('Failed to load additional Paddle transactions', error);
|
||||
setTransactionsHasMore(false);
|
||||
} finally {
|
||||
setTransactionsLoading(false);
|
||||
}
|
||||
}, [transactionCursor, transactionsHasMore, transactionsLoading]);
|
||||
|
||||
React.useEffect(() => {
|
||||
void loadAll();
|
||||
}, [loadAll]);
|
||||
@@ -176,11 +208,134 @@ export default function BillingPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-0 bg-white/85 shadow-xl shadow-sky-100/60">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-xl text-slate-900">
|
||||
<Sparkles className="h-5 w-5 text-sky-500" />
|
||||
{t('billing.sections.transactions.title')}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-sm text-slate-600">
|
||||
{t('billing.sections.transactions.description')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{transactions.length === 0 ? (
|
||||
<EmptyState message={t('billing.sections.transactions.empty')} />
|
||||
) : (
|
||||
<div className="grid gap-3">
|
||||
{transactions.map((transaction) => (
|
||||
<TransactionCard
|
||||
key={transaction.id ?? Math.random().toString(36).slice(2)}
|
||||
transaction={transaction}
|
||||
formatCurrency={formatCurrency}
|
||||
formatDate={formatDate}
|
||||
locale={locale}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{transactionsHasMore && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => void loadMoreTransactions()}
|
||||
disabled={transactionsLoading}
|
||||
>
|
||||
{transactionsLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('billing.sections.transactions.loadingMore')}
|
||||
</>
|
||||
) : (
|
||||
t('billing.sections.transactions.loadMore')
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</>
|
||||
)}
|
||||
</AdminLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function TransactionCard({
|
||||
transaction,
|
||||
formatCurrency,
|
||||
formatDate,
|
||||
locale,
|
||||
t,
|
||||
}: {
|
||||
transaction: PaddleTransactionSummary;
|
||||
formatCurrency: (value: number | null | undefined, currency?: string) => string;
|
||||
formatDate: (value: string | null | undefined) => string;
|
||||
locale: string;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}) {
|
||||
const amount = transaction.grand_total ?? transaction.amount ?? null;
|
||||
const currency = transaction.currency ?? 'EUR';
|
||||
const createdAtIso = transaction.created_at ?? null;
|
||||
const createdAt = createdAtIso ? new Date(createdAtIso) : null;
|
||||
const createdLabel = createdAt
|
||||
? createdAt.toLocaleString(locale, {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
})
|
||||
: formatDate(createdAtIso);
|
||||
const statusKey = transaction.status ? `billing.sections.transactions.status.${transaction.status}` : 'billing.sections.transactions.status.unknown';
|
||||
const statusText = t(statusKey, {
|
||||
defaultValue: (transaction.status ?? 'unknown').replace(/_/g, ' '),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3 rounded-2xl border border-slate-200 bg-white/80 p-4 shadow-sm md:flex-row md:items-center md:justify-between">
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-semibold text-slate-800">
|
||||
{t('billing.sections.transactions.labels.transactionId', { id: transaction.id ?? '—' })}
|
||||
</p>
|
||||
<p className="text-xs uppercase tracking-wide text-slate-500">{createdLabel}</p>
|
||||
{transaction.checkout_id && (
|
||||
<p className="text-xs text-slate-500">
|
||||
{t('billing.sections.transactions.labels.checkoutId', { id: transaction.checkout_id })}
|
||||
</p>
|
||||
)}
|
||||
{transaction.origin && (
|
||||
<p className="text-xs text-slate-500">
|
||||
{t('billing.sections.transactions.labels.origin', { origin: transaction.origin })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col items-start gap-2 text-sm font-medium text-slate-700 md:flex-row md:items-center md:gap-4">
|
||||
<Badge className="bg-sky-100 text-sky-700">
|
||||
{statusText}
|
||||
</Badge>
|
||||
<div className="text-base font-semibold text-slate-900">
|
||||
{formatCurrency(amount, currency)}
|
||||
</div>
|
||||
{transaction.tax !== undefined && transaction.tax !== null && (
|
||||
<span className="text-xs text-slate-500">
|
||||
{t('billing.sections.transactions.labels.tax', { value: formatCurrency(transaction.tax, currency) })}
|
||||
</span>
|
||||
)}
|
||||
{transaction.receipt_url && (
|
||||
<a
|
||||
href={transaction.receipt_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="text-xs font-medium text-sky-600 hover:text-sky-700"
|
||||
>
|
||||
{t('billing.sections.transactions.labels.receipt')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoCard({
|
||||
label,
|
||||
value,
|
||||
|
||||
@@ -15,10 +15,10 @@ const Footer: React.FC = () => {
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
|
||||
<div>
|
||||
<div className="flex items-center gap-4">
|
||||
<img src="logo-transparent-md.png" alt="FotoSpiel.App Logo" className="h-12 w-auto" />
|
||||
<img src="/logo-transparent-md.png" alt="FotoSpiel.App Logo" className="h-12 w-auto" />
|
||||
<div>
|
||||
<Link href="/" className="text-2xl font-bold font-display text-pink-500">
|
||||
FotoSpiel.App
|
||||
Die FotoSpiel.App
|
||||
</Link>
|
||||
<p className="text-gray-600 font-sans-marketing mt-2">
|
||||
Deine Plattform für Event-Fotos.
|
||||
@@ -57,7 +57,7 @@ const Footer: React.FC = () => {
|
||||
</div>
|
||||
|
||||
<div className="border-t border-gray-200 mt-8 pt-8 text-center text-sm text-gray-500 font-sans-marketing">
|
||||
© 2025 FotoSpiel.App - Alle Rechte vorbehalten.
|
||||
© 2025 Die FotoSpiel.App - Alle Rechte vorbehalten.
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -121,7 +121,7 @@ const Header: React.FC = () => {
|
||||
<Link href={localizedPath('/')} className="flex items-center gap-4">
|
||||
<img src="/logo-transparent-md.png" alt="FotoSpiel.App Logo" className="h-12 w-auto" />
|
||||
<span className="text-2xl font-bold font-display text-pink-500">
|
||||
FotoSpiel.App
|
||||
Die FotoSpiel.App
|
||||
</span>
|
||||
</Link>
|
||||
<NavigationMenu className="hidden lg:flex flex-1 justify-center" viewport={false}>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import toast from 'react-hot-toast';
|
||||
import { LoaderCircle, User, Mail, Phone, Lock, MapPin } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||
import type { GoogleProfilePrefill } from '../marketing/checkout/types';
|
||||
|
||||
declare const route: (name: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
@@ -18,6 +19,8 @@ interface RegisterFormProps {
|
||||
onSuccess?: (payload: RegisterSuccessPayload) => void;
|
||||
privacyHtml: string;
|
||||
locale?: string;
|
||||
prefill?: GoogleProfilePrefill;
|
||||
onClearGoogleProfile?: () => void;
|
||||
}
|
||||
|
||||
type RegisterFormFields = {
|
||||
@@ -30,13 +33,15 @@ type RegisterFormFields = {
|
||||
address: string;
|
||||
phone: string;
|
||||
privacy_consent: boolean;
|
||||
terms: boolean;
|
||||
package_id: number | null;
|
||||
};
|
||||
|
||||
export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale }: RegisterFormProps) {
|
||||
export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale, prefill, onClearGoogleProfile }: RegisterFormProps) {
|
||||
const [privacyOpen, setPrivacyOpen] = useState(false);
|
||||
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [prefillApplied, setPrefillApplied] = useState(false);
|
||||
const { t } = useTranslation(['auth', 'common']);
|
||||
const page = usePage<{ errors: Record<string, string>; locale?: string; auth?: { user?: any | null } }>();
|
||||
const resolvedLocale = locale ?? page.props.locale ?? 'de';
|
||||
@@ -51,6 +56,7 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
address: '',
|
||||
phone: '',
|
||||
privacy_consent: false,
|
||||
terms: false,
|
||||
package_id: packageId || null,
|
||||
});
|
||||
|
||||
@@ -61,6 +67,62 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
}, [errors, hasTriedSubmit]);
|
||||
|
||||
const registerEndpoint = '/checkout/register';
|
||||
|
||||
const namePrefill = useMemo(() => {
|
||||
const rawFirst = prefill?.given_name ?? prefill?.name?.split(' ')[0] ?? '';
|
||||
const remaining = prefill?.name ? prefill.name.split(' ').slice(1).join(' ') : '';
|
||||
const rawLast = prefill?.family_name ?? remaining;
|
||||
|
||||
return {
|
||||
first: rawFirst ?? '',
|
||||
last: rawLast ?? '',
|
||||
};
|
||||
}, [prefill]);
|
||||
|
||||
const suggestedUsername = useMemo(() => {
|
||||
if (prefill?.email) {
|
||||
const localPart = prefill.email.split('@')[0];
|
||||
if (localPart) {
|
||||
return localPart.slice(0, 30);
|
||||
}
|
||||
}
|
||||
|
||||
const first = prefill?.given_name ?? prefill?.name?.split(' ')[0] ?? '';
|
||||
const last = prefill?.family_name ?? prefill?.name?.split(' ').slice(1).join(' ') ?? '';
|
||||
const combined = `${first}${last}`.trim();
|
||||
if (!combined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return combined
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '')
|
||||
.slice(0, 30) || undefined;
|
||||
}, [prefill]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!prefill || prefillApplied) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (namePrefill.first && !data.first_name) {
|
||||
setData('first_name', namePrefill.first);
|
||||
}
|
||||
|
||||
if (namePrefill.last && !data.last_name) {
|
||||
setData('last_name', namePrefill.last);
|
||||
}
|
||||
|
||||
if (prefill.email && !data.email) {
|
||||
setData('email', prefill.email);
|
||||
}
|
||||
|
||||
if (suggestedUsername && !data.username) {
|
||||
setData('username', suggestedUsername);
|
||||
}
|
||||
|
||||
setPrefillApplied(true);
|
||||
}, [prefill, namePrefill.first, namePrefill.last, data.first_name, data.last_name, data.email, data.username, prefillApplied, setData, suggestedUsername]);
|
||||
|
||||
const submit = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
@@ -95,6 +157,7 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
redirect: json?.redirect ?? null,
|
||||
pending_purchase: json?.pending_purchase ?? json?.user?.pending_purchase ?? false,
|
||||
});
|
||||
onClearGoogleProfile?.();
|
||||
reset();
|
||||
setHasTriedSubmit(false);
|
||||
return;
|
||||
@@ -362,9 +425,13 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
checked={data.privacy_consent}
|
||||
onChange={(e) => {
|
||||
setData('privacy_consent', e.target.checked);
|
||||
setData('terms', e.target.checked);
|
||||
if (e.target.checked && errors.privacy_consent) {
|
||||
clearErrors('privacy_consent');
|
||||
}
|
||||
if (e.target.checked && errors.terms) {
|
||||
clearErrors('terms');
|
||||
}
|
||||
}}
|
||||
className="h-4 w-4 text-[#FFB6C1] focus:ring-[#FFB6C1] border-gray-300 rounded"
|
||||
/>
|
||||
@@ -379,6 +446,7 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
</button>.
|
||||
</label>
|
||||
{errors.privacy_consent && <p className="mt-2 text-sm text-red-600">{errors.privacy_consent}</p>}
|
||||
{errors.terms && <p className="mt-2 text-sm text-red-600">{errors.terms}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -419,8 +487,3 @@ export default function RegisterForm({ packageId, onSuccess, privacyHtml, locale
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from "react";
|
||||
import { Head, usePage } from "@inertiajs/react";
|
||||
import MarketingLayout from "@/layouts/mainWebsite";
|
||||
import type { CheckoutPackage } from "./checkout/types";
|
||||
import type { CheckoutPackage, GoogleProfilePrefill } from "./checkout/types";
|
||||
import { CheckoutWizard } from "./checkout/CheckoutWizard";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { X } from "lucide-react";
|
||||
@@ -9,20 +9,28 @@ import { X } from "lucide-react";
|
||||
interface CheckoutWizardPageProps {
|
||||
package: CheckoutPackage;
|
||||
packageOptions: CheckoutPackage[];
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
privacyHtml: string;
|
||||
googleAuth?: {
|
||||
status?: string | null;
|
||||
error?: string | null;
|
||||
profile?: GoogleProfilePrefill | null;
|
||||
};
|
||||
paddle?: {
|
||||
environment?: string | null;
|
||||
client_token?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
export default function CheckoutWizardPage({
|
||||
package: initialPackage,
|
||||
packageOptions,
|
||||
stripePublishableKey,
|
||||
paypalClientId,
|
||||
privacyHtml,
|
||||
googleAuth,
|
||||
paddle,
|
||||
}: CheckoutWizardPageProps) {
|
||||
const page = usePage<{ auth?: { user?: { id: number; email: string; name?: string; pending_purchase?: boolean } | null } }>();
|
||||
const currentUser = page.props.auth?.user ?? null;
|
||||
const googleProfile = googleAuth?.profile ?? null;
|
||||
|
||||
|
||||
const dedupedOptions = React.useMemo(() => {
|
||||
@@ -58,10 +66,10 @@ export default function CheckoutWizardPage({
|
||||
<CheckoutWizard
|
||||
initialPackage={initialPackage}
|
||||
packageOptions={dedupedOptions}
|
||||
stripePublishableKey={stripePublishableKey}
|
||||
paypalClientId={paypalClientId}
|
||||
privacyHtml={privacyHtml}
|
||||
initialAuthUser={currentUser ? { id: currentUser.id, email: currentUser.email ?? '', name: currentUser.name ?? undefined, pending_purchase: Boolean(currentUser.pending_purchase) } : null}
|
||||
googleProfile={googleProfile}
|
||||
paddle={paddle ?? null}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import React, { useMemo, useRef, useEffect, useCallback, Suspense, lazy } from "react";
|
||||
import React, { useMemo, useRef, useEffect, useCallback, Suspense, lazy, useState } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Steps } from "@/components/ui/Steps";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { CheckoutWizardProvider, useCheckoutWizard } from "./WizardContext";
|
||||
import type { CheckoutPackage, CheckoutStepId } from "./types";
|
||||
import type { CheckoutPackage, CheckoutStepId, GoogleProfilePrefill } from "./types";
|
||||
import { PackageStep } from "./steps/PackageStep";
|
||||
import { AuthStep } from "./steps/AuthStep";
|
||||
import { ConfirmationStep } from "./steps/ConfirmationStep";
|
||||
@@ -15,8 +15,6 @@ const PaymentStep = lazy(() => import('./steps/PaymentStep').then((module) => ({
|
||||
interface CheckoutWizardProps {
|
||||
initialPackage: CheckoutPackage;
|
||||
packageOptions: CheckoutPackage[];
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
privacyHtml: string;
|
||||
initialAuthUser?: {
|
||||
id: number;
|
||||
@@ -25,6 +23,11 @@ interface CheckoutWizardProps {
|
||||
pending_purchase?: boolean;
|
||||
} | null;
|
||||
initialStep?: CheckoutStepId;
|
||||
googleProfile?: GoogleProfilePrefill | null;
|
||||
paddle?: {
|
||||
environment?: string | null;
|
||||
client_token?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
const baseStepConfig: { id: CheckoutStepId; titleKey: string; descriptionKey: string; detailsKey: string }[] = [
|
||||
@@ -61,13 +64,34 @@ const PaymentStepFallback: React.FC = () => (
|
||||
</div>
|
||||
);
|
||||
|
||||
const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: string; privacyHtml: string }> = ({ stripePublishableKey, paypalClientId, privacyHtml }) => {
|
||||
const WizardBody: React.FC<{
|
||||
privacyHtml: string;
|
||||
googleProfile?: GoogleProfilePrefill | null;
|
||||
onClearGoogleProfile?: () => void;
|
||||
}> = ({ privacyHtml, googleProfile, onClearGoogleProfile }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { currentStep, nextStep, previousStep } = useCheckoutWizard();
|
||||
const {
|
||||
currentStep,
|
||||
nextStep,
|
||||
previousStep,
|
||||
selectedPackage,
|
||||
authUser,
|
||||
isAuthenticated,
|
||||
paymentCompleted,
|
||||
} = useCheckoutWizard();
|
||||
const progressRef = useRef<HTMLDivElement | null>(null);
|
||||
const hasMountedRef = useRef(false);
|
||||
const { trackEvent } = useAnalytics();
|
||||
|
||||
const isFreeSelected = useMemo(() => {
|
||||
if (!selectedPackage) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const priceValue = Number(selectedPackage.price);
|
||||
return Number.isFinite(priceValue) && priceValue <= 0;
|
||||
}, [selectedPackage]);
|
||||
|
||||
const stepConfig = useMemo(() =>
|
||||
baseStepConfig.map(step => ({
|
||||
id: step.id,
|
||||
@@ -114,7 +138,41 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
});
|
||||
}, [currentStep]);
|
||||
|
||||
const atLastStep = currentIndex >= stepConfig.length - 1;
|
||||
|
||||
const canProceedToNextStep = useMemo(() => {
|
||||
if (atLastStep) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (currentStep === 'package') {
|
||||
return Boolean(selectedPackage);
|
||||
}
|
||||
|
||||
if (currentStep === 'auth') {
|
||||
return Boolean(isAuthenticated && authUser);
|
||||
}
|
||||
|
||||
if (currentStep === 'payment') {
|
||||
return isFreeSelected || paymentCompleted;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, [atLastStep, authUser, currentStep, isAuthenticated, isFreeSelected, paymentCompleted, selectedPackage]);
|
||||
|
||||
const shouldShowNextButton = useMemo(() => {
|
||||
if (currentStep !== 'payment') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isFreeSelected || paymentCompleted;
|
||||
}, [currentStep, isFreeSelected, paymentCompleted]);
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
if (!canProceedToNextStep) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetStep = stepConfig[currentIndex + 1]?.id ?? 'end';
|
||||
trackEvent({
|
||||
category: 'marketing_checkout',
|
||||
@@ -122,7 +180,7 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
name: `${currentStep}->${targetStep}`,
|
||||
});
|
||||
nextStep();
|
||||
}, [currentIndex, currentStep, nextStep, stepConfig, trackEvent]);
|
||||
}, [canProceedToNextStep, currentIndex, currentStep, nextStep, stepConfig, trackEvent]);
|
||||
|
||||
const handlePrevious = useCallback(() => {
|
||||
const targetStep = stepConfig[currentIndex - 1]?.id ?? 'start';
|
||||
@@ -151,10 +209,16 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
|
||||
<div className="space-y-6">
|
||||
{currentStep === "package" && <PackageStep />}
|
||||
{currentStep === "auth" && <AuthStep privacyHtml={privacyHtml} />}
|
||||
{currentStep === "auth" && (
|
||||
<AuthStep
|
||||
privacyHtml={privacyHtml}
|
||||
googleProfile={googleProfile ?? undefined}
|
||||
onClearGoogleProfile={onClearGoogleProfile}
|
||||
/>
|
||||
)}
|
||||
{currentStep === "payment" && (
|
||||
<Suspense fallback={<PaymentStepFallback />}>
|
||||
<PaymentStep stripePublishableKey={stripePublishableKey} paypalClientId={paypalClientId} />
|
||||
<PaymentStep />
|
||||
</Suspense>
|
||||
)}
|
||||
{currentStep === "confirmation" && (
|
||||
@@ -162,13 +226,17 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<Button variant="ghost" onClick={handlePrevious} disabled={currentIndex <= 0}>
|
||||
{t('checkout.back')}
|
||||
</Button>
|
||||
<Button onClick={handleNext} disabled={currentIndex >= stepConfig.length - 1}>
|
||||
{t('checkout.next')}
|
||||
</Button>
|
||||
{shouldShowNextButton ? (
|
||||
<Button onClick={handleNext} disabled={!canProceedToNextStep}>
|
||||
{t('checkout.next')}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="h-10 min-w-[128px]" aria-hidden="true" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -177,12 +245,51 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
|
||||
initialPackage,
|
||||
packageOptions,
|
||||
stripePublishableKey,
|
||||
paypalClientId,
|
||||
privacyHtml,
|
||||
initialAuthUser,
|
||||
initialStep,
|
||||
googleProfile,
|
||||
paddle,
|
||||
}) => {
|
||||
const [storedProfile, setStoredProfile] = useState<GoogleProfilePrefill | null>(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem('checkout-google-profile');
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as GoogleProfilePrefill;
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse checkout google profile from storage', error);
|
||||
window.localStorage.removeItem('checkout-google-profile');
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!googleProfile) {
|
||||
return;
|
||||
}
|
||||
|
||||
setStoredProfile(googleProfile);
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.setItem('checkout-google-profile', JSON.stringify(googleProfile));
|
||||
}
|
||||
}, [googleProfile]);
|
||||
|
||||
const clearStoredProfile = useCallback(() => {
|
||||
setStoredProfile(null);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage.removeItem('checkout-google-profile');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const effectiveProfile = googleProfile ?? storedProfile;
|
||||
|
||||
return (
|
||||
<CheckoutWizardProvider
|
||||
@@ -191,8 +298,13 @@ export const CheckoutWizard: React.FC<CheckoutWizardProps> = ({
|
||||
initialStep={initialStep}
|
||||
initialAuthUser={initialAuthUser ?? undefined}
|
||||
initialIsAuthenticated={Boolean(initialAuthUser)}
|
||||
paddle={paddle ?? null}
|
||||
>
|
||||
<WizardBody stripePublishableKey={stripePublishableKey} paypalClientId={paypalClientId} privacyHtml={privacyHtml} />
|
||||
<WizardBody
|
||||
privacyHtml={privacyHtml}
|
||||
googleProfile={effectiveProfile}
|
||||
onClearGoogleProfile={clearStoredProfile}
|
||||
/>
|
||||
</CheckoutWizardProvider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ interface CheckoutState {
|
||||
paymentIntent: string | null;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
paymentCompleted: boolean;
|
||||
}
|
||||
|
||||
interface CheckoutWizardContextType {
|
||||
@@ -19,6 +20,11 @@ interface CheckoutWizardContextType {
|
||||
currentStep: CheckoutStepId;
|
||||
isAuthenticated: boolean;
|
||||
authUser: any;
|
||||
paddleConfig?: {
|
||||
environment?: string | null;
|
||||
client_token?: string | null;
|
||||
} | null;
|
||||
paymentCompleted: boolean;
|
||||
selectPackage: (pkg: CheckoutPackage) => void;
|
||||
setSelectedPackage: (pkg: CheckoutPackage) => void;
|
||||
setAuthUser: (user: any) => void;
|
||||
@@ -31,6 +37,7 @@ interface CheckoutWizardContextType {
|
||||
setLoading: (loading: boolean) => void;
|
||||
setError: (error: string | null) => void;
|
||||
resetPaymentState: () => void;
|
||||
setPaymentCompleted: (completed: boolean) => void;
|
||||
}
|
||||
|
||||
const CheckoutWizardContext = createContext<CheckoutWizardContextType | null>(null);
|
||||
@@ -44,6 +51,7 @@ const initialState: CheckoutState = {
|
||||
paymentIntent: null,
|
||||
loading: false,
|
||||
error: null,
|
||||
paymentCompleted: false,
|
||||
};
|
||||
|
||||
type CheckoutAction =
|
||||
@@ -54,14 +62,15 @@ type CheckoutAction =
|
||||
| { type: 'GO_TO_STEP'; payload: CheckoutStepId }
|
||||
| { type: 'UPDATE_PAYMENT_INTENT'; payload: string | null }
|
||||
| { type: 'SET_LOADING'; payload: boolean }
|
||||
| { type: 'SET_ERROR'; payload: string | null };
|
||||
| { type: 'SET_ERROR'; payload: string | null }
|
||||
| { type: 'SET_PAYMENT_COMPLETED'; payload: boolean };
|
||||
|
||||
function checkoutReducer(state: CheckoutState, action: CheckoutAction): CheckoutState {
|
||||
switch (action.type) {
|
||||
case 'SELECT_PACKAGE':
|
||||
return { ...state, selectedPackage: action.payload };
|
||||
return { ...state, selectedPackage: action.payload, paymentCompleted: false };
|
||||
case 'SET_AUTH_USER':
|
||||
return { ...state, authUser: action.payload };
|
||||
return { ...state, authUser: action.payload, isAuthenticated: Boolean(action.payload) };
|
||||
case 'NEXT_STEP':
|
||||
const steps: CheckoutStepId[] = ['package', 'auth', 'payment', 'confirmation'];
|
||||
const currentIndex = steps.indexOf(state.currentStep);
|
||||
@@ -84,6 +93,8 @@ function checkoutReducer(state: CheckoutState, action: CheckoutAction): Checkout
|
||||
return { ...state, loading: action.payload };
|
||||
case 'SET_ERROR':
|
||||
return { ...state, error: action.payload };
|
||||
case 'SET_PAYMENT_COMPLETED':
|
||||
return { ...state, paymentCompleted: action.payload };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
@@ -96,6 +107,10 @@ interface CheckoutWizardProviderProps {
|
||||
initialStep?: CheckoutStepId;
|
||||
initialAuthUser?: any;
|
||||
initialIsAuthenticated?: boolean;
|
||||
paddle?: {
|
||||
environment?: string | null;
|
||||
client_token?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export function CheckoutWizardProvider({
|
||||
@@ -104,7 +119,8 @@ export function CheckoutWizardProvider({
|
||||
packageOptions,
|
||||
initialStep,
|
||||
initialAuthUser,
|
||||
initialIsAuthenticated
|
||||
initialIsAuthenticated,
|
||||
paddle,
|
||||
}: CheckoutWizardProviderProps) {
|
||||
const customInitialState: CheckoutState = {
|
||||
...initialState,
|
||||
@@ -124,7 +140,8 @@ export function CheckoutWizardProvider({
|
||||
if (savedState) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedState);
|
||||
if (parsed.selectedPackage && initialPackage && parsed.selectedPackage.id === initialPackage.id && parsed.currentStep !== 'confirmation') {
|
||||
const hasValidPackage = parsed.selectedPackage && typeof parsed.selectedPackage.paddle_price_id === 'string' && parsed.selectedPackage.paddle_price_id !== '';
|
||||
if (hasValidPackage && initialPackage && parsed.selectedPackage.id === initialPackage.id && parsed.currentStep !== 'confirmation') {
|
||||
// Restore state selectively
|
||||
if (parsed.selectedPackage) dispatch({ type: 'SELECT_PACKAGE', payload: parsed.selectedPackage });
|
||||
if (parsed.currentStep) dispatch({ type: 'GO_TO_STEP', payload: parsed.currentStep });
|
||||
@@ -192,6 +209,11 @@ export function CheckoutWizardProvider({
|
||||
dispatch({ type: 'UPDATE_PAYMENT_INTENT', payload: null });
|
||||
dispatch({ type: 'SET_LOADING', payload: false });
|
||||
dispatch({ type: 'SET_ERROR', payload: null });
|
||||
dispatch({ type: 'SET_PAYMENT_COMPLETED', payload: false });
|
||||
}, []);
|
||||
|
||||
const setPaymentCompleted = useCallback((completed: boolean) => {
|
||||
dispatch({ type: 'SET_PAYMENT_COMPLETED', payload: completed });
|
||||
}, []);
|
||||
|
||||
const cancelCheckout = useCallback(() => {
|
||||
@@ -226,6 +248,8 @@ export function CheckoutWizardProvider({
|
||||
currentStep: state.currentStep,
|
||||
isAuthenticated: state.isAuthenticated,
|
||||
authUser: state.authUser,
|
||||
paddleConfig: paddle ?? null,
|
||||
paymentCompleted: state.paymentCompleted,
|
||||
selectPackage,
|
||||
setSelectedPackage,
|
||||
setAuthUser,
|
||||
@@ -238,6 +262,7 @@ export function CheckoutWizardProvider({
|
||||
setLoading,
|
||||
setError,
|
||||
resetPaymentState,
|
||||
setPaymentCompleted,
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import React from 'react';
|
||||
import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest';
|
||||
import { cleanup, render, screen, fireEvent } from '@testing-library/react';
|
||||
import { CheckoutWizard } from '../CheckoutWizard';
|
||||
import { useCheckoutWizard } from '../WizardContext';
|
||||
|
||||
vi.mock('@/hooks/useAnalytics', () => ({
|
||||
useAnalytics: () => ({ trackEvent: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock('../steps/PackageStep', () => ({
|
||||
PackageStep: () => <div data-testid="package-step" />,
|
||||
}));
|
||||
|
||||
vi.mock('../steps/AuthStep', () => ({
|
||||
AuthStep: () => <div data-testid="auth-step" />,
|
||||
}));
|
||||
|
||||
vi.mock('../steps/PaymentStep', () => ({
|
||||
PaymentStep: () => {
|
||||
const { setPaymentCompleted } = useCheckoutWizard();
|
||||
|
||||
return (
|
||||
<div data-testid="payment-step">
|
||||
<button type="button" onClick={() => setPaymentCompleted(true)}>
|
||||
mark-complete
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../steps/ConfirmationStep', () => ({
|
||||
ConfirmationStep: () => <div data-testid="confirmation-step" />,
|
||||
}));
|
||||
|
||||
const basePackage = {
|
||||
id: 1,
|
||||
name: 'Starter',
|
||||
description: 'Test package',
|
||||
price: 0,
|
||||
type: 'endcustomer' as const,
|
||||
features: [],
|
||||
};
|
||||
|
||||
describe('CheckoutWizard auth step navigation guard', () => {
|
||||
beforeAll(() => {
|
||||
// jsdom does not implement scrollTo, but the wizard calls it on step changes.
|
||||
Object.defineProperty(window, 'scrollTo', { value: vi.fn(), writable: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('disables the next button when the user is not authenticated on the auth step', () => {
|
||||
render(
|
||||
<CheckoutWizard
|
||||
initialPackage={basePackage}
|
||||
packageOptions={[basePackage]}
|
||||
privacyHtml="<p>privacy</p>"
|
||||
initialAuthUser={null}
|
||||
initialStep="auth"
|
||||
/>,
|
||||
);
|
||||
|
||||
const nextButton = screen.getByRole('button', { name: 'checkout.next' });
|
||||
expect(nextButton).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables the next button once the user is authenticated on the auth step', () => {
|
||||
render(
|
||||
<CheckoutWizard
|
||||
initialPackage={basePackage}
|
||||
packageOptions={[basePackage]}
|
||||
privacyHtml="<p>privacy</p>"
|
||||
initialAuthUser={{ id: 42, email: 'user@example.com' }}
|
||||
initialStep="auth"
|
||||
/>,
|
||||
);
|
||||
|
||||
const nextButton = screen.getByRole('button', { name: 'checkout.next' });
|
||||
expect(nextButton).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('only renders the next button on the payment step after the payment is completed', async () => {
|
||||
const paidPackage = { ...basePackage, id: 2, price: 99 };
|
||||
|
||||
render(
|
||||
<CheckoutWizard
|
||||
initialPackage={paidPackage}
|
||||
packageOptions={[paidPackage]}
|
||||
privacyHtml="<p>privacy</p>"
|
||||
initialAuthUser={{ id: 42, email: 'user@example.com' }}
|
||||
initialStep="payment"
|
||||
/>,
|
||||
);
|
||||
|
||||
await screen.findByTestId('payment-step');
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'checkout.next' })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'mark-complete' }));
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'checkout.next' })).toBeEnabled();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { usePage } from "@inertiajs/react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { useCheckoutWizard } from "../WizardContext";
|
||||
import type { GoogleProfilePrefill } from '../types';
|
||||
import LoginForm, { AuthUserPayload } from "../../../auth/LoginForm";
|
||||
import RegisterForm, { RegisterSuccessPayload } from "../../../auth/RegisterForm";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -11,6 +12,8 @@ import { LoaderCircle } from "lucide-react";
|
||||
|
||||
interface AuthStepProps {
|
||||
privacyHtml: string;
|
||||
googleProfile?: GoogleProfilePrefill;
|
||||
onClearGoogleProfile?: () => void;
|
||||
}
|
||||
|
||||
type GoogleAuthFlash = {
|
||||
@@ -29,7 +32,7 @@ const GoogleIcon: React.FC<{ className?: string }> = ({ className }) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml, googleProfile, onClearGoogleProfile }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const page = usePage<{ locale?: string }>();
|
||||
const locale = page.props.locale ?? "de";
|
||||
@@ -42,10 +45,11 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.status === 'success') {
|
||||
if (googleAuth?.status === 'signin') {
|
||||
toast.success(t('checkout.auth_step.google_success_toast'));
|
||||
onClearGoogleProfile?.();
|
||||
}
|
||||
}, [googleAuth?.status, t]);
|
||||
}, [googleAuth?.status, onClearGoogleProfile, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.error) {
|
||||
@@ -64,6 +68,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
name: payload.name ?? undefined,
|
||||
pending_purchase: Boolean(payload.pending_purchase),
|
||||
});
|
||||
onClearGoogleProfile?.();
|
||||
nextStep();
|
||||
};
|
||||
|
||||
@@ -78,6 +83,7 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
});
|
||||
}
|
||||
|
||||
onClearGoogleProfile?.();
|
||||
nextStep();
|
||||
};
|
||||
|
||||
@@ -158,6 +164,8 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
privacyHtml={privacyHtml}
|
||||
locale={locale}
|
||||
onSuccess={handleRegisterSuccess}
|
||||
prefill={googleProfile}
|
||||
onClearGoogleProfile={onClearGoogleProfile}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
|
||||
@@ -1,401 +1,332 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useStripe, useElements, PaymentElement, Elements } from '@stripe/react-stripe-js';
|
||||
import { PayPalButtons, PayPalScriptProvider } from '@paypal/react-paypal-js';
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
import { useCheckoutWizard } from '../WizardContext';
|
||||
import { getStripe } from '@/utils/stripe';
|
||||
|
||||
interface PaymentStepProps {
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
}
|
||||
type PaymentStatus = 'idle' | 'processing' | 'ready' | 'error';
|
||||
|
||||
type Provider = 'stripe' | 'paypal';
|
||||
type PaymentStatus = 'idle' | 'loading' | 'ready' | 'processing' | 'error' | 'success';
|
||||
|
||||
interface StripePaymentFormProps {
|
||||
onProcessing: () => void;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
selectedPackage: any;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const StripePaymentForm: React.FC<StripePaymentFormProps> = ({ onProcessing, onSuccess, onError, selectedPackage, t }) => {
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!stripe || !elements) {
|
||||
const message = t('checkout.payment_step.stripe_not_loaded');
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
onProcessing();
|
||||
setIsProcessing(true);
|
||||
setErrorMessage('');
|
||||
|
||||
try {
|
||||
const { error: stripeError, paymentIntent } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
return_url: `${window.location.origin}/checkout/success`,
|
||||
},
|
||||
redirect: 'if_required',
|
||||
});
|
||||
|
||||
if (stripeError) {
|
||||
let message = t('checkout.payment_step.payment_failed');
|
||||
|
||||
switch (stripeError.type) {
|
||||
case 'card_error':
|
||||
message += stripeError.message || t('checkout.payment_step.error_card');
|
||||
break;
|
||||
case 'validation_error':
|
||||
message += t('checkout.payment_step.error_validation');
|
||||
break;
|
||||
case 'api_connection_error':
|
||||
message += t('checkout.payment_step.error_connection');
|
||||
break;
|
||||
case 'api_error':
|
||||
message += t('checkout.payment_step.error_server');
|
||||
break;
|
||||
case 'authentication_error':
|
||||
message += t('checkout.payment_step.error_auth');
|
||||
break;
|
||||
default:
|
||||
message += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
}
|
||||
|
||||
setErrorMessage(message);
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentIntent && paymentIntent.status === 'succeeded') {
|
||||
onSuccess();
|
||||
return;
|
||||
}
|
||||
|
||||
onError(t('checkout.payment_step.unexpected_status', { status: paymentIntent?.status }));
|
||||
} catch (error) {
|
||||
console.error('Stripe payment failed', error);
|
||||
onError(t('checkout.payment_step.error_unknown'));
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<p className="text-sm text-muted-foreground">{t('checkout.payment_step.secure_payment_desc')}</p>
|
||||
<PaymentElement />
|
||||
<Button type="submit" disabled={!stripe || isProcessing} size="lg" className="w-full">
|
||||
{isProcessing && <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('checkout.payment_step.pay_now', { price: selectedPackage?.price || 0 })}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
interface PayPalPaymentFormProps {
|
||||
onProcessing: () => void;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
selectedPackage: any;
|
||||
isReseller: boolean;
|
||||
paypalPlanId?: string | null;
|
||||
t: (key: string, options?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
const PayPalPaymentForm: React.FC<PayPalPaymentFormProps> = ({ onProcessing, onSuccess, onError, selectedPackage, isReseller, paypalPlanId, t }) => {
|
||||
const createOrder = async () => {
|
||||
if (!selectedPackage?.id) {
|
||||
const message = t('checkout.payment_step.paypal_order_error');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
try {
|
||||
onProcessing();
|
||||
|
||||
const endpoint = isReseller ? '/paypal/create-subscription' : '/paypal/create-order';
|
||||
const payload: Record<string, unknown> = {
|
||||
package_id: selectedPackage.id,
|
||||
declare global {
|
||||
interface Window {
|
||||
Paddle?: {
|
||||
Environment?: {
|
||||
set: (environment: string) => void;
|
||||
};
|
||||
Initialize?: (options: { token: string }) => void;
|
||||
Checkout: {
|
||||
open: (options: Record<string, unknown>) => void;
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (isReseller) {
|
||||
if (!paypalPlanId) {
|
||||
const message = t('checkout.payment_step.paypal_missing_plan');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
payload.plan_id = paypalPlanId;
|
||||
}
|
||||
const PADDLE_SCRIPT_URL = 'https://cdn.paddle.com/paddle/v2/paddle.js';
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
type PaddleEnvironment = 'sandbox' | 'production';
|
||||
|
||||
const data = await response.json();
|
||||
let paddleLoaderPromise: Promise<typeof window.Paddle | null> | null = null;
|
||||
|
||||
if (response.ok) {
|
||||
const orderId = isReseller ? data.order_id : data.id;
|
||||
if (typeof orderId === 'string' && orderId.length > 0) {
|
||||
return orderId;
|
||||
}
|
||||
} else {
|
||||
onError(data.error || t('checkout.payment_step.paypal_order_error'));
|
||||
}
|
||||
function configurePaddle(paddle: typeof window.Paddle | undefined | null, environment: PaddleEnvironment): typeof window.Paddle | null {
|
||||
if (!paddle) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new Error('Failed to create PayPal order');
|
||||
} catch (error) {
|
||||
console.error('PayPal create order failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
try {
|
||||
paddle.Environment?.set?.(environment);
|
||||
} catch (error) {
|
||||
console.warn('[Paddle] Failed to set environment', error);
|
||||
}
|
||||
|
||||
const onApprove = async (data: any) => {
|
||||
try {
|
||||
const response = await fetch('/paypal/capture-order', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({ order_id: data.orderID }),
|
||||
});
|
||||
return paddle;
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
async function loadPaddle(environment: PaddleEnvironment): Promise<typeof window.Paddle | null> {
|
||||
if (typeof window === 'undefined') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (response.ok && result.status === 'captured') {
|
||||
onSuccess();
|
||||
} else {
|
||||
onError(result.error || t('checkout.payment_step.paypal_capture_error'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('PayPal capture failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
if (window.Paddle) {
|
||||
return configurePaddle(window.Paddle, environment);
|
||||
}
|
||||
|
||||
const handleError = (error: unknown) => {
|
||||
console.error('PayPal error', error);
|
||||
onError(t('checkout.payment_step.paypal_error'));
|
||||
};
|
||||
if (!paddleLoaderPromise) {
|
||||
paddleLoaderPromise = new Promise<typeof window.Paddle | null>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = PADDLE_SCRIPT_URL;
|
||||
script.async = true;
|
||||
script.onload = () => resolve(window.Paddle ?? null);
|
||||
script.onerror = (error) => reject(error);
|
||||
document.head.appendChild(script);
|
||||
}).catch((error) => {
|
||||
console.error('Failed to load Paddle.js', error);
|
||||
paddleLoaderPromise = null;
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
onError(t('checkout.payment_step.paypal_cancelled'));
|
||||
};
|
||||
const paddle = await paddleLoaderPromise;
|
||||
|
||||
return configurePaddle(paddle, environment);
|
||||
}
|
||||
|
||||
const PaddleCta: React.FC<{ onCheckout: () => Promise<void>; disabled: boolean; isProcessing: boolean }> = ({ onCheckout, disabled, isProcessing }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<p className="text-sm text-muted-foreground">{t('checkout.payment_step.secure_paypal_desc') || 'Bezahlen Sie sicher mit PayPal.'}</p>
|
||||
<PayPalButtons
|
||||
style={{ layout: 'vertical' }}
|
||||
createOrder={async () => createOrder()}
|
||||
onApprove={onApprove}
|
||||
onError={handleError}
|
||||
onCancel={handleCancel}
|
||||
/>
|
||||
</div>
|
||||
<Button size="lg" className="w-full" disabled={disabled} onClick={onCheckout}>
|
||||
{isProcessing && <LoaderCircle className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('checkout.payment_step.pay_with_paddle')}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
const statusVariantMap: Record<PaymentStatus, 'default' | 'destructive' | 'success' | 'secondary'> = {
|
||||
idle: 'secondary',
|
||||
loading: 'secondary',
|
||||
ready: 'secondary',
|
||||
processing: 'secondary',
|
||||
error: 'destructive',
|
||||
success: 'success',
|
||||
};
|
||||
|
||||
export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey, paypalClientId }) => {
|
||||
export const PaymentStep: React.FC = () => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage, authUser, nextStep, resetPaymentState } = useCheckoutWizard();
|
||||
|
||||
const [paymentMethod, setPaymentMethod] = useState<Provider>('stripe');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const { selectedPackage, nextStep, paddleConfig, authUser, setPaymentCompleted } = useCheckoutWizard();
|
||||
const [status, setStatus] = useState<PaymentStatus>('idle');
|
||||
const [statusDetail, setStatusDetail] = useState<string>('');
|
||||
const [intentRefreshKey, setIntentRefreshKey] = useState(0);
|
||||
const [processingProvider, setProcessingProvider] = useState<Provider | null>(null);
|
||||
const [message, setMessage] = useState<string>('');
|
||||
const [initialised, setInitialised] = useState(false);
|
||||
const [inlineActive, setInlineActive] = useState(false);
|
||||
const paddleRef = useRef<typeof window.Paddle | null>(null);
|
||||
const eventCallbackRef = useRef<(event: any) => void>();
|
||||
const checkoutContainerClass = 'paddle-checkout-container';
|
||||
|
||||
const stripePromise = useMemo(() => getStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
const isFree = useMemo(() => (selectedPackage ? selectedPackage.price <= 0 : false), [selectedPackage]);
|
||||
const isReseller = selectedPackage?.type === 'reseller';
|
||||
const isFree = useMemo(() => (selectedPackage ? Number(selectedPackage.price) <= 0 : false), [selectedPackage]);
|
||||
|
||||
const paypalPlanId = useMemo(() => {
|
||||
if (!selectedPackage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof selectedPackage.paypal_plan_id === 'string' && selectedPackage.paypal_plan_id.trim().length > 0) {
|
||||
return selectedPackage.paypal_plan_id;
|
||||
}
|
||||
|
||||
const metadata = (selectedPackage as Record<string, unknown>)?.metadata;
|
||||
if (metadata && typeof metadata === 'object') {
|
||||
const value = (metadata as Record<string, unknown>).paypal_plan_id;
|
||||
if (typeof value === 'string' && value.trim().length > 0) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [selectedPackage]);
|
||||
|
||||
const paypalDisabled = isReseller && !paypalPlanId;
|
||||
|
||||
useEffect(() => {
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setClientSecret('');
|
||||
setProcessingProvider(null);
|
||||
}, [selectedPackage?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isFree) {
|
||||
resetPaymentState();
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
return;
|
||||
}
|
||||
const handleFreeActivation = async () => {
|
||||
setPaymentCompleted(true);
|
||||
nextStep();
|
||||
};
|
||||
|
||||
const startPaddleCheckout = async () => {
|
||||
if (!selectedPackage) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentMethod === 'paypal') {
|
||||
if (paypalDisabled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.paypal_missing_plan'));
|
||||
} else {
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!stripePromise) {
|
||||
if (!selectedPackage.paddle_price_id) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.stripe_not_loaded'));
|
||||
setMessage(t('checkout.payment_step.paddle_not_configured'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authUser) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.auth_required'));
|
||||
return;
|
||||
}
|
||||
setPaymentCompleted(false);
|
||||
setStatus('processing');
|
||||
setMessage(t('checkout.payment_step.paddle_preparing'));
|
||||
setInlineActive(false);
|
||||
|
||||
let cancelled = false;
|
||||
setStatus('loading');
|
||||
setStatusDetail(t('checkout.payment_step.status_loading'));
|
||||
setClientSecret('');
|
||||
try {
|
||||
const inlineSupported = initialised && !!paddleConfig?.client_token;
|
||||
|
||||
const loadIntent = async () => {
|
||||
try {
|
||||
const response = await fetch('/stripe/create-payment-intent', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({ package_id: selectedPackage.id }),
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Paddle inline status', {
|
||||
inlineSupported,
|
||||
initialised,
|
||||
hasClientToken: Boolean(paddleConfig?.client_token),
|
||||
environment: paddleConfig?.environment,
|
||||
paddlePriceId: selectedPackage.paddle_price_id,
|
||||
});
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (inlineSupported) {
|
||||
const paddle = paddleRef.current;
|
||||
|
||||
if (!response.ok || !data.client_secret) {
|
||||
const message = data.error || t('checkout.payment_step.payment_intent_error');
|
||||
if (!cancelled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
if (!paddle || !paddle.Checkout || typeof paddle.Checkout.open !== 'function') {
|
||||
throw new Error('Inline Paddle checkout is not available.');
|
||||
}
|
||||
|
||||
const inlinePayload: Record<string, unknown> = {
|
||||
items: [
|
||||
{
|
||||
priceId: selectedPackage.paddle_price_id,
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
settings: {
|
||||
displayMode: 'inline',
|
||||
frameTarget: checkoutContainerClass,
|
||||
frameInitialHeight: '550',
|
||||
frameStyle: 'width: 100%; min-width: 320px; background-color: transparent; border: none;',
|
||||
theme: 'light',
|
||||
locale: typeof document !== 'undefined' ? document.documentElement.lang ?? 'de' : 'de',
|
||||
},
|
||||
customData: {
|
||||
package_id: String(selectedPackage.id),
|
||||
},
|
||||
};
|
||||
|
||||
const customerEmail = authUser?.email ?? null;
|
||||
if (customerEmail) {
|
||||
inlinePayload.customer = { email: customerEmail };
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Opening inline Paddle checkout', inlinePayload);
|
||||
}
|
||||
|
||||
paddle.Checkout.open(inlinePayload);
|
||||
|
||||
setInlineActive(true);
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_overlay_ready'));
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch('/paddle/create-checkout', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
package_id: selectedPackage.id,
|
||||
}),
|
||||
});
|
||||
|
||||
const rawBody = await response.text();
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Hosted checkout response', { status: response.status, rawBody });
|
||||
}
|
||||
|
||||
let data: any = null;
|
||||
try {
|
||||
data = rawBody && rawBody.trim().startsWith('{') ? JSON.parse(rawBody) : null;
|
||||
} catch (parseError) {
|
||||
console.warn('Failed to parse Paddle checkout payload as JSON', parseError);
|
||||
data = null;
|
||||
}
|
||||
|
||||
let checkoutUrl: string | null = typeof data?.checkout_url === 'string' ? data.checkout_url : null;
|
||||
|
||||
if (!checkoutUrl) {
|
||||
const trimmed = rawBody.trim();
|
||||
if (/^https?:\/\//i.test(trimmed)) {
|
||||
checkoutUrl = trimmed;
|
||||
} else if (trimmed.startsWith('<')) {
|
||||
const match = trimmed.match(/https?:\/\/["'a-zA-Z0-9._~:\/?#\[\]@!$&'()*+,;=%-]+/);
|
||||
if (match) {
|
||||
checkoutUrl = match[0];
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setClientSecret(data.client_secret);
|
||||
setStatus('ready');
|
||||
setStatusDetail(t('checkout.payment_step.status_ready'));
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
console.error('Failed to load payment intent', error);
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
if (!response.ok || !checkoutUrl) {
|
||||
const message = data?.message || rawBody || 'Unable to create Paddle checkout.';
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
window.open(checkoutUrl, '_blank', 'noopener');
|
||||
setInlineActive(false);
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_ready'));
|
||||
} catch (error) {
|
||||
console.error('Failed to start Paddle checkout', error);
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const environment = paddleConfig?.environment === 'sandbox' ? 'sandbox' : 'production';
|
||||
const clientToken = paddleConfig?.client_token ?? null;
|
||||
|
||||
eventCallbackRef.current = (event) => {
|
||||
if (!event?.name) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.debug('[Checkout] Paddle event', event);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.completed') {
|
||||
setStatus('ready');
|
||||
setMessage(t('checkout.payment_step.paddle_overlay_ready'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(true);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.closed') {
|
||||
setStatus('idle');
|
||||
setMessage('');
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
|
||||
if (event.name === 'checkout.error') {
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setInlineActive(false);
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadIntent();
|
||||
(async () => {
|
||||
const paddle = await loadPaddle(environment);
|
||||
|
||||
if (cancelled || !paddle) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let inlineReady = false;
|
||||
if (typeof paddle.Initialize === 'function' && clientToken) {
|
||||
if (typeof window !== 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.info('[Checkout] Initializing Paddle.js', { environment, hasToken: Boolean(clientToken) });
|
||||
}
|
||||
paddle.Initialize({
|
||||
token: clientToken,
|
||||
checkout: {
|
||||
settings: {
|
||||
displayMode: 'inline',
|
||||
frameTarget: checkoutContainerClass,
|
||||
frameInitialHeight: '550',
|
||||
frameStyle: 'width: 100%; min-width: 320px; background-color: transparent; border: none;',
|
||||
locale: typeof document !== 'undefined' ? document.documentElement.lang ?? 'de' : 'de',
|
||||
},
|
||||
},
|
||||
eventCallback: (event: any) => eventCallbackRef.current?.(event),
|
||||
});
|
||||
inlineReady = true;
|
||||
}
|
||||
|
||||
paddleRef.current = paddle;
|
||||
setInitialised(inlineReady);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Paddle', error);
|
||||
setInitialised(false);
|
||||
setStatus('error');
|
||||
setMessage(t('checkout.payment_step.paddle_error'));
|
||||
setPaymentCompleted(false);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authUser, intentRefreshKey, isFree, paymentMethod, paypalDisabled, resetPaymentState, selectedPackage, stripePromise, t]);
|
||||
}, [paddleConfig?.environment, paddleConfig?.client_token, setPaymentCompleted, t]);
|
||||
|
||||
const providerLabel = useCallback((provider: Provider) => {
|
||||
switch (provider) {
|
||||
case 'paypal':
|
||||
return 'PayPal';
|
||||
default:
|
||||
return 'Stripe';
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setPaymentCompleted(false);
|
||||
}, [selectedPackage?.id, setPaymentCompleted]);
|
||||
|
||||
const handleProcessing = useCallback((provider: Provider) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('processing');
|
||||
setStatusDetail(t('checkout.payment_step.status_processing', { provider: providerLabel(provider) }));
|
||||
}, [providerLabel, t]);
|
||||
|
||||
const handleSuccess = useCallback((provider: Provider) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('success');
|
||||
setStatusDetail(t('checkout.payment_step.status_success'));
|
||||
setTimeout(() => nextStep(), 600);
|
||||
}, [nextStep, t]);
|
||||
|
||||
const handleError = useCallback((provider: Provider, message: string) => {
|
||||
setProcessingProvider(provider);
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
}, []);
|
||||
|
||||
const handleRetry = () => {
|
||||
if (paymentMethod === 'stripe') {
|
||||
setIntentRefreshKey((key) => key + 1);
|
||||
}
|
||||
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setProcessingProvider(null);
|
||||
};
|
||||
if (!selectedPackage) {
|
||||
return (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t('checkout.payment_step.no_package_title')}</AlertTitle>
|
||||
<AlertDescription>{t('checkout.payment_step.no_package_description')}</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
if (isFree) {
|
||||
return (
|
||||
@@ -405,7 +336,7 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
<AlertDescription>{t('checkout.payment_step.free_package_desc')}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={nextStep}>
|
||||
<Button size="lg" onClick={handleFreeActivation}>
|
||||
{t('checkout.payment_step.activate_package')}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -413,94 +344,44 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
);
|
||||
}
|
||||
|
||||
const renderStatusAlert = () => {
|
||||
if (status === 'idle') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const variant = statusVariantMap[status];
|
||||
|
||||
return (
|
||||
<Alert variant={variant}>
|
||||
<AlertTitle>
|
||||
{status === 'error'
|
||||
? t('checkout.payment_step.status_error_title')
|
||||
: status === 'success'
|
||||
? t('checkout.payment_step.status_success_title')
|
||||
: t('checkout.payment_step.status_info_title')}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="flex items-center justify-between gap-4">
|
||||
<span>{statusDetail}</span>
|
||||
{status === 'processing' && <LoaderCircle className="h-4 w-4 animate-spin" />}
|
||||
{status === 'error' && (
|
||||
<Button size="sm" variant="outline" onClick={handleRetry}>
|
||||
{t('checkout.payment_step.status_retry')}
|
||||
</Button>
|
||||
)}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
variant={paymentMethod === 'stripe' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('stripe')}
|
||||
disabled={paymentMethod === 'stripe'}
|
||||
>
|
||||
{t('checkout.payment_step.method_stripe')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={paymentMethod === 'paypal' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('paypal')}
|
||||
disabled={paypalDisabled || paymentMethod === 'paypal'}
|
||||
>
|
||||
{t('checkout.payment_step.method_paypal')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('checkout.payment_step.paddle_intro')}
|
||||
</p>
|
||||
|
||||
{renderStatusAlert()}
|
||||
|
||||
{paymentMethod === 'stripe' && clientSecret && stripePromise && (
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<StripePaymentForm
|
||||
selectedPackage={selectedPackage}
|
||||
onProcessing={() => handleProcessing('stripe')}
|
||||
onSuccess={() => handleSuccess('stripe')}
|
||||
onError={(message) => handleError('stripe', message)}
|
||||
t={t}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'stripe' && !clientSecret && status === 'loading' && (
|
||||
<div className="rounded-lg border bg-card p-6 text-sm text-muted-foreground shadow-sm">
|
||||
<LoaderCircle className="mb-3 h-4 w-4 animate-spin" />
|
||||
{t('checkout.payment_step.status_loading')}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && !paypalDisabled && (
|
||||
<PayPalScriptProvider options={{ clientId: paypalClientId, currency: 'EUR' }}>
|
||||
<PayPalPaymentForm
|
||||
isReseller={Boolean(isReseller)}
|
||||
onProcessing={() => handleProcessing('paypal')}
|
||||
onSuccess={() => handleSuccess('paypal')}
|
||||
onError={(message) => handleError('paypal', message)}
|
||||
paypalPlanId={paypalPlanId}
|
||||
selectedPackage={selectedPackage}
|
||||
t={t}
|
||||
/>
|
||||
</PayPalScriptProvider>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && paypalDisabled && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{t('checkout.payment_step.paypal_missing_plan')}</AlertDescription>
|
||||
{status !== 'idle' && (
|
||||
<Alert variant={status === 'error' ? 'destructive' : 'secondary'}>
|
||||
<AlertTitle>
|
||||
{status === 'processing'
|
||||
? t('checkout.payment_step.status_processing_title')
|
||||
: status === 'ready'
|
||||
? t('checkout.payment_step.status_ready_title')
|
||||
: status === 'error'
|
||||
? t('checkout.payment_step.status_error_title')
|
||||
: t('checkout.payment_step.status_info_title')}
|
||||
</AlertTitle>
|
||||
<AlertDescription className="flex items-center gap-3">
|
||||
<span>{message}</span>
|
||||
{status === 'processing' && <LoaderCircle className="h-4 w-4 animate-spin" />}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm space-y-4">
|
||||
<div className={`${checkoutContainerClass} min-h-[200px]`} />
|
||||
{!inlineActive && (
|
||||
<PaddleCta
|
||||
onCheckout={startPaddleCheckout}
|
||||
disabled={status === 'processing'}
|
||||
isProcessing={status === 'processing'}
|
||||
/>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('checkout.payment_step.paddle_disclaimer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
export type CheckoutStepId = 'package' | 'auth' | 'payment' | 'confirmation';
|
||||
|
||||
export interface GoogleProfilePrefill {
|
||||
email?: string;
|
||||
name?: string;
|
||||
given_name?: string;
|
||||
family_name?: string;
|
||||
avatar?: string;
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export interface CheckoutPackage {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -15,7 +24,8 @@ export interface CheckoutPackage {
|
||||
type: 'endcustomer' | 'reseller';
|
||||
features: string[];
|
||||
limits?: Record<string, unknown>;
|
||||
paypal_plan_id?: string | null;
|
||||
paddle_price_id?: string | null;
|
||||
paddle_product_id?: string | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -30,7 +40,7 @@ export interface CheckoutWizardState {
|
||||
name?: string;
|
||||
pending_purchase?: boolean;
|
||||
} | null;
|
||||
paymentProvider?: 'stripe' | 'paypal';
|
||||
paymentProvider?: 'stripe' | 'paddle';
|
||||
isProcessing?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,14 +12,14 @@ return [
|
||||
'contact' => 'Kontakt',
|
||||
'vat_id' => 'Umsatzsteuer-ID: DE123456789',
|
||||
'monetization' => 'Monetarisierung',
|
||||
'monetization_desc' => 'Wir monetarisieren über Packages (Einmalkäufe und Abos) via Stripe und PayPal. Preise exkl. MwSt. Support: support@fotospiel.de',
|
||||
'monetization_desc' => 'Wir monetarisieren über Packages (Einmalkäufe und Abos) via Paddle. Preise exkl. MwSt. Support: support@fotospiel.de',
|
||||
'register_court' => 'Registergericht: Amtsgericht Musterstadt',
|
||||
'commercial_register' => 'Handelsregister: HRB 12345',
|
||||
'datenschutz_intro' => 'Wir nehmen den Schutz Ihrer persönlichen Daten sehr ernst und halten uns strikt an die Regeln der Datenschutzgesetze.',
|
||||
'responsible' => 'Verantwortlich: Fotospiel GmbH, Musterstraße 1, 12345 Musterstadt',
|
||||
'data_collection' => 'Datenerfassung: Keine PII-Speicherung, anonyme Sessions für Gäste. E-Mails werden nur für Kontaktzwecke verarbeitet.',
|
||||
'payments' => 'Zahlungen und Packages',
|
||||
'payments_desc' => 'Wir verarbeiten Zahlungen für Packages über Stripe und PayPal. Karteninformationen werden nicht gespeichert – alle Daten werden verschlüsselt übertragen.',
|
||||
'payments_desc' => 'Wir verarbeiten Zahlungen für Packages über Paddle. Zahlungsinformationen werden sicher und verschlüsselt durch Paddle als Merchant of Record verarbeitet.',
|
||||
'data_retention' => 'Package-Daten (Limits, Features) sind anonymisiert und werden nur für die Funktionalität benötigt. Consent für Zahlungen und E-Mails wird bei Kauf eingeholt. Daten werden nach 10 Jahren gelöscht.',
|
||||
'rights' => 'Ihre Rechte: Auskunft, Löschung, Widerspruch.',
|
||||
'cookies' => 'Cookies: Nur funktionale Cookies für die PWA.',
|
||||
@@ -34,5 +34,4 @@ return [
|
||||
'version' => 'Version :version',
|
||||
'and' => 'und',
|
||||
'stripe_privacy' => 'Stripe Datenschutz',
|
||||
'paypal_privacy' => 'PayPal Datenschutz',
|
||||
];
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
"faq_q3": "Was passiert bei Ablauf?",
|
||||
"faq_a3": "Die Galerie bleibt lesbar, aber Uploads sind blockiert. Verlängern Sie einfach.",
|
||||
"faq_q4": "Zahlungssicher?",
|
||||
"faq_a4": "Ja, via Stripe oder PayPal – sicher und GDPR-konform.",
|
||||
"faq_a4": "Ja, via Paddle – sicher und GDPR-konform.",
|
||||
"final_cta": "Bereit für Ihr nächstes Event?",
|
||||
"contact_us": "Kontaktieren Sie uns",
|
||||
"feature_live_slideshow": "Live-Slideshow",
|
||||
@@ -245,4 +245,4 @@
|
||||
"euro": "€"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ return [
|
||||
'faq_q3' => 'Was passiert bei Ablauf?',
|
||||
'faq_a3' => 'Die Galerie bleibt lesbar, aber Uploads sind blockiert. Verlängern Sie einfach.',
|
||||
'faq_q4' => 'Zahlungssicher?',
|
||||
'faq_a4' => 'Ja, via Stripe oder PayPal – sicher und GDPR-konform.',
|
||||
'faq_a4' => 'Ja, via Paddle – sicher und GDPR-konform.',
|
||||
'final_cta' => 'Bereit für Ihr nächstes Event?',
|
||||
'contact_us' => 'Kontaktieren Sie uns',
|
||||
'feature_live_slideshow' => 'Live-Slideshow',
|
||||
@@ -60,10 +60,12 @@ return [
|
||||
'max_guests_label' => 'Max. Gäste',
|
||||
'gallery_days_label' => 'Galerie-Tage',
|
||||
'feature_overview' => 'Feature-Überblick',
|
||||
'order_hint' => 'Sofort startklar – keine versteckten Kosten, sichere Zahlung via Stripe oder PayPal.',
|
||||
'order_hint' => 'Sofort startklar – keine versteckten Kosten, sichere Zahlung über Paddle.',
|
||||
'features_label' => 'Features',
|
||||
'breakdown_label' => 'Leistungsübersicht',
|
||||
'limits_label' => 'Limits & Kapazitäten',
|
||||
'paddle_not_configured' => 'Dieses Package ist noch nicht für den Paddle-Checkout konfiguriert. Bitte kontaktiere den Support.',
|
||||
'paddle_checkout_failed' => 'Der Paddle-Checkout konnte nicht gestartet werden. Bitte versuche es später erneut.',
|
||||
],
|
||||
'nav' => [
|
||||
'home' => 'Startseite',
|
||||
|
||||
@@ -12,14 +12,14 @@ return [
|
||||
'contact' => 'Contact',
|
||||
'vat_id' => 'VAT ID: DE123456789',
|
||||
'monetization' => 'Monetization',
|
||||
'monetization_desc' => 'We monetize through Packages (one-time purchases and subscriptions) via Stripe and PayPal. Prices excl. VAT. Support: support@fotospiel.de',
|
||||
'monetization_desc' => 'We monetize through Packages (one-time purchases and subscriptions) via Paddle. Prices excl. VAT. Support: support@fotospiel.de',
|
||||
'register_court' => 'Register Court: District Court Musterstadt',
|
||||
'commercial_register' => 'Commercial Register: HRB 12345',
|
||||
'datenschutz_intro' => 'We take the protection of your personal data very seriously and strictly adhere to the rules of data protection laws.',
|
||||
'responsible' => 'Responsible: Fotospiel GmbH, Musterstraße 1, 12345 Musterstadt',
|
||||
'data_collection' => 'Data collection: No PII storage, anonymous sessions for guests. Emails are only processed for contact purposes.',
|
||||
'payments' => 'Payments and Packages',
|
||||
'payments_desc' => 'We process payments for Packages via Stripe and PayPal. Card information is not stored – all data is transmitted encrypted. See Stripe Privacy and PayPal Privacy.',
|
||||
'payments_desc' => 'We process payments for Packages via Paddle. Payment information is handled securely and encrypted by Paddle as the merchant of record.',
|
||||
'data_retention' => 'Package data (limits, features) is anonymized and only required for functionality. Consent for payments and emails is obtained at purchase. Data is deleted after 10 years.',
|
||||
'rights' => 'Your rights: Information, deletion, objection. Contact us under Contact.',
|
||||
'cookies' => 'Cookies: Only functional cookies for the PWA.',
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
"faq_q3": "What happens when it expires?",
|
||||
"faq_a3": "The gallery remains readable, but uploads are blocked. Simply extend it.",
|
||||
"faq_q4": "Payment secure?",
|
||||
"faq_a4": "Yes, via Stripe or PayPal – secure and GDPR-compliant.",
|
||||
"faq_a4": "Yes, via Paddle – secure and GDPR-compliant.",
|
||||
"final_cta": "Ready for your next event?",
|
||||
"contact_us": "Contact Us",
|
||||
"feature_live_slideshow": "Live Slideshow",
|
||||
@@ -240,4 +240,4 @@
|
||||
"currency": {
|
||||
"euro": "€"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ return [
|
||||
'faq_q3' => 'What happens when it expires?',
|
||||
'faq_a3' => 'The gallery remains readable, but uploads are blocked. Simply extend it.',
|
||||
'faq_q4' => 'Payment secure?',
|
||||
'faq_a4' => 'Yes, via Stripe or PayPal – secure and GDPR-compliant.',
|
||||
'faq_a4' => 'Yes, via Paddle – secure and GDPR-compliant.',
|
||||
'final_cta' => 'Ready for your next event?',
|
||||
'contact_us' => 'Contact Us',
|
||||
'feature_live_slideshow' => 'Live Slideshow',
|
||||
@@ -60,10 +60,12 @@ return [
|
||||
'max_guests_label' => 'Max. guests',
|
||||
'gallery_days_label' => 'Gallery days',
|
||||
'feature_overview' => 'Feature overview',
|
||||
'order_hint' => 'Ready to launch instantly – secure Stripe or PayPal checkout, no hidden fees.',
|
||||
'order_hint' => 'Ready to launch instantly – secure Paddle checkout, no hidden fees.',
|
||||
'features_label' => 'Features',
|
||||
'breakdown_label' => 'At-a-glance',
|
||||
'limits_label' => 'Limits & Capacity',
|
||||
'paddle_not_configured' => 'This package is not ready for Paddle checkout. Please contact support.',
|
||||
'paddle_checkout_failed' => 'We could not start the Paddle checkout. Please try again later.',
|
||||
],
|
||||
'nav' => [
|
||||
'home' => 'Home',
|
||||
|
||||
Reference in New Issue
Block a user