- Wired the checkout wizard for Google “comfort login”: added Socialite controller + dependency, new Google env
hooks in config/services.php/.env.example, and updated wizard steps/controllers to store session payloads, attach packages, and surface localized success/error states. - Retooled payment handling for both Stripe and PayPal, adding richer status management in CheckoutController/ PayPalController, fallback flows in the wizard’s PaymentStep.tsx, and fresh feature tests for intent creation, webhooks, and the wizard CTA. - Introduced a consent-aware Matomo analytics stack: new consent context, cookie-banner UI, useAnalytics/ useCtaExperiment hooks, and MatomoTracker component, then instrumented marketing pages (Home, Packages, Checkout) with localized copy and experiment tracking. - Polished package presentation across marketing UIs by centralizing formatting in PresentsPackages, surfacing localized description tables/placeholders, tuning badges/layouts, and syncing guest/marketing translations. - Expanded docs & reference material (docs/prp/*, TODOs, public gallery overview) and added a Playwright smoke test for the hero CTA while reconciling outstanding checklist items.
This commit is contained in:
@@ -10,6 +10,7 @@ import i18n from './i18n';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { Elements } from '@stripe/react-stripe-js';
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
import { ConsentProvider } from './contexts/consent';
|
||||
|
||||
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
|
||||
|
||||
@@ -42,10 +43,12 @@ createInertiaApp({
|
||||
|
||||
root.render(
|
||||
<Elements stripe={stripePromise}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<App {...props} />
|
||||
<Toaster position="top-right" toastOptions={{ duration: 4000 }} />
|
||||
</I18nextProvider>
|
||||
<ConsentProvider>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<App {...props} />
|
||||
<Toaster position="top-right" toastOptions={{ duration: 4000 }} />
|
||||
</I18nextProvider>
|
||||
</ConsentProvider>
|
||||
</Elements>
|
||||
);
|
||||
},
|
||||
|
||||
104
resources/js/components/analytics/MatomoTracker.tsx
Normal file
104
resources/js/components/analytics/MatomoTracker.tsx
Normal file
@@ -0,0 +1,104 @@
|
||||
import { useEffect } from 'react';
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import { useConsent } from '@/contexts/consent';
|
||||
|
||||
export type MatomoConfig = {
|
||||
enabled: boolean;
|
||||
url?: string;
|
||||
siteId?: string;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
_paq?: any[];
|
||||
}
|
||||
}
|
||||
|
||||
interface MatomoTrackerProps {
|
||||
config: MatomoConfig | undefined;
|
||||
}
|
||||
|
||||
const MatomoTracker: React.FC<MatomoTrackerProps> = ({ config }) => {
|
||||
const page = usePage();
|
||||
const { hasConsent } = useConsent();
|
||||
const analyticsConsent = hasConsent('analytics');
|
||||
|
||||
useEffect(() => {
|
||||
if (!config?.enabled || !config.url || !config.siteId || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const base = config.url.replace(/\/$/, '');
|
||||
const scriptSelector = `script[data-matomo="${base}"]`;
|
||||
|
||||
if (!analyticsConsent) {
|
||||
const existing = document.querySelector<HTMLScriptElement>(scriptSelector);
|
||||
existing?.remove();
|
||||
if (window._paq) {
|
||||
window._paq.length = 0;
|
||||
}
|
||||
delete (window as any).__matomoInitialized;
|
||||
return;
|
||||
}
|
||||
|
||||
window._paq = window._paq || [];
|
||||
const { _paq } = window;
|
||||
|
||||
if (!(window as any).__matomoInitialized) {
|
||||
_paq.push(['setTrackerUrl', `${base}/matomo.php`]);
|
||||
_paq.push(['setSiteId', config.siteId]);
|
||||
_paq.push(['disableCookies']);
|
||||
_paq.push(['enableLinkTracking']);
|
||||
|
||||
if (!document.querySelector(scriptSelector)) {
|
||||
const script = document.createElement('script');
|
||||
script.async = true;
|
||||
script.src = `${base}/matomo.js`;
|
||||
script.dataset.matomo = base;
|
||||
document.body.appendChild(script);
|
||||
}
|
||||
|
||||
(window as any).__matomoInitialized = true;
|
||||
}
|
||||
}, [config, analyticsConsent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!config?.enabled ||
|
||||
!config.url ||
|
||||
!config.siteId ||
|
||||
typeof window === 'undefined' ||
|
||||
!analyticsConsent
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
window._paq = window._paq || [];
|
||||
const { _paq } = window;
|
||||
const currentUrl =
|
||||
typeof window !== 'undefined' ? `${window.location.origin}${page.url}` : page.url;
|
||||
|
||||
_paq.push(['setCustomUrl', currentUrl]);
|
||||
if (typeof document !== 'undefined') {
|
||||
_paq.push(['setDocumentTitle', document.title]);
|
||||
}
|
||||
_paq.push(['trackPageView']);
|
||||
}, [config, analyticsConsent, page.url]);
|
||||
|
||||
if (!config?.enabled || !config.url || !config.siteId || !analyticsConsent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const base = config.url.replace(/\/$/, '');
|
||||
const noscriptSrc = `${base}/matomo.php?idsite=${encodeURIComponent(config.siteId)}&rec=1`;
|
||||
|
||||
return (
|
||||
<noscript>
|
||||
<p>
|
||||
<img src={noscriptSrc} style={{ border: 0 }} alt="" />
|
||||
</p>
|
||||
</noscript>
|
||||
);
|
||||
};
|
||||
|
||||
export default MatomoTracker;
|
||||
175
resources/js/components/consent/CookieBanner.tsx
Normal file
175
resources/js/components/consent/CookieBanner.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useConsent, ConsentPreferences } from '@/contexts/consent';
|
||||
|
||||
const CookieBanner: React.FC = () => {
|
||||
const { t } = useTranslation('common');
|
||||
const {
|
||||
showBanner,
|
||||
acceptAll,
|
||||
rejectAll,
|
||||
preferences,
|
||||
savePreferences,
|
||||
isPreferencesOpen,
|
||||
openPreferences,
|
||||
closePreferences,
|
||||
} = useConsent();
|
||||
|
||||
const [draftPreferences, setDraftPreferences] = useState<ConsentPreferences>(preferences);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPreferencesOpen) {
|
||||
setDraftPreferences(preferences);
|
||||
}
|
||||
}, [isPreferencesOpen, preferences]);
|
||||
|
||||
const analyticsDescription = useMemo(
|
||||
() => t('consent.modal.analytics_desc'),
|
||||
[t],
|
||||
);
|
||||
|
||||
const handleSave = () => {
|
||||
savePreferences({ analytics: draftPreferences.analytics });
|
||||
};
|
||||
|
||||
const handleOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
openPreferences();
|
||||
return;
|
||||
}
|
||||
closePreferences();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{showBanner && !isPreferencesOpen && (
|
||||
<div
|
||||
className="fixed inset-x-0 bottom-0 z-40 px-4 pb-6 sm:px-6"
|
||||
role="region"
|
||||
aria-label={t('consent.accessibility.banner_label')}
|
||||
>
|
||||
<div className="mx-auto max-w-5xl rounded-3xl border border-gray-200 bg-white/95 p-6 shadow-2xl backdrop-blur-md dark:border-gray-700 dark:bg-gray-900/95">
|
||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{t('consent.banner.title')}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">
|
||||
{t('consent.banner.body')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="min-w-[140px]"
|
||||
onClick={rejectAll}
|
||||
>
|
||||
{t('consent.banner.reject')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
className="min-w-[140px]"
|
||||
onClick={openPreferences}
|
||||
>
|
||||
{t('consent.banner.customize')}
|
||||
</Button>
|
||||
<Button className="min-w-[140px]" onClick={acceptAll}>
|
||||
{t('consent.banner.accept')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={isPreferencesOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent className="sm:max-w-xl md:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('consent.modal.title')}</DialogTitle>
|
||||
<DialogDescription className="text-sm text-muted-foreground">
|
||||
{t('consent.modal.description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="rounded-2xl border border-gray-200 bg-gray-50/80 p-4 dark:border-gray-700 dark:bg-gray-800/60">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-white">
|
||||
{t('consent.modal.functional')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('consent.modal.functional_desc')}
|
||||
</p>
|
||||
</div>
|
||||
<span className="rounded-full bg-gray-200 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-gray-600 dark:bg-gray-700 dark:text-gray-200">
|
||||
{t('consent.modal.required')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-gray-200 p-4 dark:border-gray-700">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-gray-900 dark:text-white">
|
||||
{t('consent.modal.analytics')}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">{analyticsDescription}</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={draftPreferences.analytics}
|
||||
onCheckedChange={(checked) =>
|
||||
setDraftPreferences((prev) => ({
|
||||
...prev,
|
||||
analytics: checked,
|
||||
functional: true,
|
||||
}))
|
||||
}
|
||||
aria-label={t('consent.modal.analytics')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<DialogFooter className="flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="flex w-full flex-wrap gap-2 sm:w-auto">
|
||||
<Button type="button" variant="outline" onClick={rejectAll}>
|
||||
{t('consent.modal.reject_all')}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={acceptAll}>
|
||||
{t('consent.modal.accept_all')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex w-full flex-wrap gap-2 sm:w-auto sm:justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => closePreferences()}
|
||||
>
|
||||
{t('consent.modal.cancel')}
|
||||
</Button>
|
||||
<Button type="button" onClick={handleSave}>
|
||||
{t('consent.modal.save')}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default CookieBanner;
|
||||
185
resources/js/contexts/consent.tsx
Normal file
185
resources/js/contexts/consent.tsx
Normal file
@@ -0,0 +1,185 @@
|
||||
import React, {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
|
||||
const CONSENT_STORAGE_KEY = 'fotospiel.consent';
|
||||
const CONSENT_VERSION = '2025-10-17-1';
|
||||
|
||||
export type ConsentCategory = 'functional' | 'analytics';
|
||||
|
||||
export type ConsentPreferences = Record<ConsentCategory, boolean>;
|
||||
|
||||
interface StoredConsent {
|
||||
version: string;
|
||||
preferences: ConsentPreferences;
|
||||
decisionMade: boolean;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
const defaultPreferences: ConsentPreferences = {
|
||||
functional: true,
|
||||
analytics: false,
|
||||
};
|
||||
|
||||
const defaultState: StoredConsent = {
|
||||
version: CONSENT_VERSION,
|
||||
preferences: { ...defaultPreferences },
|
||||
decisionMade: false,
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
interface ConsentContextValue {
|
||||
preferences: ConsentPreferences;
|
||||
decisionMade: boolean;
|
||||
showBanner: boolean;
|
||||
acceptAll: () => void;
|
||||
rejectAll: () => void;
|
||||
savePreferences: (preferences: Partial<ConsentPreferences>) => void;
|
||||
hasConsent: (category: ConsentCategory) => boolean;
|
||||
openPreferences: () => void;
|
||||
closePreferences: () => void;
|
||||
isPreferencesOpen: boolean;
|
||||
}
|
||||
|
||||
const ConsentContext = createContext<ConsentContextValue | undefined>(undefined);
|
||||
|
||||
function normalizeState(state: StoredConsent | null): StoredConsent {
|
||||
if (!state || state.version !== CONSENT_VERSION) {
|
||||
return { ...defaultState };
|
||||
}
|
||||
|
||||
return {
|
||||
version: CONSENT_VERSION,
|
||||
decisionMade: state.decisionMade ?? false,
|
||||
updatedAt: state.updatedAt ?? null,
|
||||
preferences: {
|
||||
...defaultPreferences,
|
||||
...state.preferences,
|
||||
functional: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getInitialState(): StoredConsent {
|
||||
if (typeof window === 'undefined') {
|
||||
return { ...defaultState };
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(CONSENT_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return { ...defaultState };
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as StoredConsent;
|
||||
return normalizeState(parsed);
|
||||
} catch {
|
||||
return { ...defaultState };
|
||||
}
|
||||
}
|
||||
|
||||
export const ConsentProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [state, setState] = useState<StoredConsent>(() => getInitialState());
|
||||
const [isPreferencesOpen, setPreferencesOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
window.localStorage.setItem(CONSENT_STORAGE_KEY, JSON.stringify(state));
|
||||
}, [state]);
|
||||
|
||||
const acceptAll = useCallback(() => {
|
||||
setState({
|
||||
version: CONSENT_VERSION,
|
||||
preferences: { functional: true, analytics: true },
|
||||
decisionMade: true,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
setPreferencesOpen(false);
|
||||
}, []);
|
||||
|
||||
const rejectAll = useCallback(() => {
|
||||
setState({
|
||||
version: CONSENT_VERSION,
|
||||
preferences: { functional: true, analytics: false },
|
||||
decisionMade: true,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
setPreferencesOpen(false);
|
||||
}, []);
|
||||
|
||||
const savePreferences = useCallback((preferences: Partial<ConsentPreferences>) => {
|
||||
setState((prev) => ({
|
||||
version: CONSENT_VERSION,
|
||||
preferences: {
|
||||
...defaultPreferences,
|
||||
...prev.preferences,
|
||||
...preferences,
|
||||
functional: true,
|
||||
},
|
||||
decisionMade: true,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}));
|
||||
setPreferencesOpen(false);
|
||||
}, []);
|
||||
|
||||
const hasConsent = useCallback(
|
||||
(category: ConsentCategory) => {
|
||||
return Boolean(state.preferences?.[category]);
|
||||
},
|
||||
[state.preferences],
|
||||
);
|
||||
|
||||
const openPreferences = useCallback(() => {
|
||||
setPreferencesOpen(true);
|
||||
}, []);
|
||||
|
||||
const closePreferences = useCallback(() => {
|
||||
setPreferencesOpen(false);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<ConsentContextValue>(
|
||||
() => ({
|
||||
preferences: state.preferences,
|
||||
decisionMade: state.decisionMade,
|
||||
showBanner: !state.decisionMade,
|
||||
acceptAll,
|
||||
rejectAll,
|
||||
savePreferences,
|
||||
hasConsent,
|
||||
openPreferences,
|
||||
closePreferences,
|
||||
isPreferencesOpen,
|
||||
}),
|
||||
[
|
||||
state.preferences,
|
||||
state.decisionMade,
|
||||
acceptAll,
|
||||
rejectAll,
|
||||
savePreferences,
|
||||
hasConsent,
|
||||
openPreferences,
|
||||
closePreferences,
|
||||
isPreferencesOpen,
|
||||
],
|
||||
);
|
||||
|
||||
return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>;
|
||||
};
|
||||
|
||||
export const useConsent = (): ConsentContextValue => {
|
||||
const context = useContext(ConsentContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useConsent must be used within a ConsentProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
@@ -16,8 +16,8 @@ interface EmotionPickerProps {
|
||||
}
|
||||
|
||||
export default function EmotionPicker({ onSelect }: EmotionPickerProps) {
|
||||
const { token: slug } = useParams<{ token: string }>();
|
||||
const eventKey = slug ?? '';
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const eventKey = token ?? '';
|
||||
const navigate = useNavigate();
|
||||
const [emotions, setEmotions] = useState<Emotion[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { getDeviceId } from '../lib/device';
|
||||
import { usePollGalleryDelta } from '../polling/usePollGalleryDelta';
|
||||
|
||||
type Props = { slug: string };
|
||||
type Props = { token: string };
|
||||
|
||||
export default function GalleryPreview({ slug }: Props) {
|
||||
const { photos, loading } = usePollGalleryDelta(slug);
|
||||
export default function GalleryPreview({ token }: Props) {
|
||||
const { photos, loading } = usePollGalleryDelta(token);
|
||||
const [mode, setMode] = React.useState<'latest' | 'popular' | 'myphotos'>('latest');
|
||||
|
||||
const items = React.useMemo(() => {
|
||||
@@ -82,7 +81,7 @@ export default function GalleryPreview({ slug }: Props) {
|
||||
My Photos
|
||||
</button>
|
||||
</div>
|
||||
<Link to={`/e/${encodeURIComponent(slug)}/gallery?mode=${mode}`} className="text-sm text-pink-600 hover:text-pink-700 font-medium">
|
||||
<Link to={`/e/${encodeURIComponent(token)}/gallery?mode=${mode}`} className="text-sm text-pink-600 hover:text-pink-700 font-medium">
|
||||
Alle ansehen →
|
||||
</Link>
|
||||
</div>
|
||||
@@ -97,7 +96,7 @@ export default function GalleryPreview({ slug }: Props) {
|
||||
)}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{items.map((p: any) => (
|
||||
<Link key={p.id} to={`/e/${encodeURIComponent(slug)}/gallery?photoId=${p.id}`} className="block">
|
||||
<Link key={p.id} to={`/e/${encodeURIComponent(token)}/gallery?photoId=${p.id}`} className="block">
|
||||
<div className="relative">
|
||||
<img
|
||||
src={p.thumbnail_path || p.file_path}
|
||||
|
||||
@@ -68,12 +68,12 @@ function renderEventAvatar(name: string, icon: unknown) {
|
||||
);
|
||||
}
|
||||
|
||||
export default function Header({ slug, title = '' }: { slug?: string; title?: string }) {
|
||||
export default function Header({ eventToken, title = '' }: { eventToken?: string; title?: string }) {
|
||||
const statsContext = useOptionalEventStats();
|
||||
const identity = useOptionalGuestIdentity();
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (!slug) {
|
||||
if (!eventToken) {
|
||||
const guestName = identity?.name && identity?.hydrated ? identity.name : null;
|
||||
return (
|
||||
<div className="sticky top-0 z-20 flex items-center justify-between border-b bg-white/70 px-4 py-2 backdrop-blur dark:bg-black/40">
|
||||
@@ -95,7 +95,7 @@ export default function Header({ slug, title = '' }: { slug?: string; title?: st
|
||||
|
||||
const { event, status } = useEventData();
|
||||
const guestName =
|
||||
identity && identity.eventKey === slug && identity.hydrated && identity.name ? identity.name : null;
|
||||
identity && identity.eventKey === eventToken && identity.hydrated && identity.name ? identity.name : null;
|
||||
|
||||
if (status === 'loading') {
|
||||
return (
|
||||
@@ -114,7 +114,7 @@ export default function Header({ slug, title = '' }: { slug?: string; title?: st
|
||||
}
|
||||
|
||||
const stats =
|
||||
statsContext && statsContext.eventKey === slug ? statsContext : undefined;
|
||||
statsContext && statsContext.eventKey === eventToken ? statsContext : undefined;
|
||||
|
||||
return (
|
||||
<div className="sticky top-0 z-20 flex items-center justify-between border-b bg-white/70 px-4 py-2 backdrop-blur dark:bg-black/40">
|
||||
|
||||
@@ -272,17 +272,17 @@ function SummaryCards({ data }: { data: AchievementsPayload }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PersonalActions({ slug }: { slug: string }) {
|
||||
function PersonalActions({ token }: { token: string }) {
|
||||
return (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button asChild>
|
||||
<Link to={`/e/${encodeURIComponent(slug)}/upload`} className="flex items-center gap-2">
|
||||
<Link to={`/e/${encodeURIComponent(token)}/upload`} className="flex items-center gap-2">
|
||||
<Camera className="h-4 w-4" />
|
||||
Neues Foto hochladen
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link to={`/e/${encodeURIComponent(slug)}/tasks`} className="flex items-center gap-2">
|
||||
<Link to={`/e/${encodeURIComponent(token)}/tasks`} className="flex items-center gap-2">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Aufgabe ziehen
|
||||
</Link>
|
||||
@@ -292,7 +292,7 @@ function PersonalActions({ slug }: { slug: string }) {
|
||||
}
|
||||
|
||||
export default function AchievementsPage() {
|
||||
const { token: slug } = useParams<{ token: string }>();
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const identity = useGuestIdentity();
|
||||
const [data, setData] = useState<AchievementsPayload | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -302,12 +302,12 @@ export default function AchievementsPage() {
|
||||
const personalName = identity.hydrated && identity.name ? identity.name : undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!slug) return;
|
||||
if (!token) return;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
fetchAchievements(slug, personalName, controller.signal)
|
||||
fetchAchievements(token, personalName, controller.signal)
|
||||
.then((payload) => {
|
||||
setData(payload);
|
||||
if (!payload.personal) {
|
||||
@@ -322,11 +322,11 @@ export default function AchievementsPage() {
|
||||
.finally(() => setLoading(false));
|
||||
|
||||
return () => controller.abort();
|
||||
}, [slug, personalName]);
|
||||
}, [token, personalName]);
|
||||
|
||||
const hasPersonal = Boolean(data?.personal);
|
||||
|
||||
if (!slug) {
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -407,7 +407,7 @@ export default function AchievementsPage() {
|
||||
{data.personal.photos} Fotos | {data.personal.tasks} Aufgaben | {data.personal.likes} Likes
|
||||
</CardDescription>
|
||||
</div>
|
||||
<PersonalActions slug={slug} />
|
||||
<PersonalActions token={token} />
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Page } from './_util';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { usePollGalleryDelta } from '../polling/usePollGalleryDelta';
|
||||
@@ -12,8 +12,8 @@ import PhotoLightbox from './PhotoLightbox';
|
||||
import { fetchEvent, getEventPackage, fetchStats, type EventData, type EventPackage, type EventStats } from '../services/eventApi';
|
||||
|
||||
export default function GalleryPage() {
|
||||
const { token: slug } = useParams<{ token?: string }>();
|
||||
const { photos, loading, newCount, acknowledgeNew } = usePollGalleryDelta(slug ?? '');
|
||||
const { token } = useParams<{ token?: string }>();
|
||||
const { photos, loading, newCount, acknowledgeNew } = usePollGalleryDelta(token ?? '');
|
||||
const [filter, setFilter] = React.useState<GalleryFilter>('latest');
|
||||
const [currentPhotoIndex, setCurrentPhotoIndex] = React.useState<number | null>(null);
|
||||
const [hasOpenedPhoto, setHasOpenedPhoto] = useState(false);
|
||||
@@ -38,15 +38,15 @@ export default function GalleryPage() {
|
||||
|
||||
// Load event and package info
|
||||
useEffect(() => {
|
||||
if (!slug) return;
|
||||
if (!token) return;
|
||||
|
||||
const loadEventData = async () => {
|
||||
try {
|
||||
setEventLoading(true);
|
||||
const [eventData, packageData, statsData] = await Promise.all([
|
||||
fetchEvent(slug),
|
||||
getEventPackage(slug),
|
||||
fetchStats(slug),
|
||||
fetchEvent(token),
|
||||
getEventPackage(token),
|
||||
fetchStats(token),
|
||||
]);
|
||||
setEvent(eventData);
|
||||
setEventPackage(packageData);
|
||||
@@ -59,7 +59,7 @@ export default function GalleryPage() {
|
||||
};
|
||||
|
||||
loadEventData();
|
||||
}, [slug]);
|
||||
}, [token]);
|
||||
|
||||
const myPhotoIds = React.useMemo(() => {
|
||||
try {
|
||||
@@ -99,7 +99,7 @@ export default function GalleryPage() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!slug) {
|
||||
if (!token) {
|
||||
return <Page title="Galerie"><p>Event nicht gefunden.</p></Page>;
|
||||
}
|
||||
|
||||
@@ -236,7 +236,7 @@ export default function GalleryPage() {
|
||||
currentIndex={currentPhotoIndex}
|
||||
onClose={() => setCurrentPhotoIndex(null)}
|
||||
onIndexChange={(index: number) => setCurrentPhotoIndex(index)}
|
||||
slug={slug}
|
||||
token={token}
|
||||
/>
|
||||
)}
|
||||
</Page>
|
||||
|
||||
@@ -141,7 +141,7 @@ export default function HomePage() {
|
||||
|
||||
<EmotionPicker />
|
||||
|
||||
<GalleryPreview slug={token} />
|
||||
<GalleryPreview token={token} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -61,7 +61,11 @@ export default function LandingPage() {
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
const targetKey = data.join_token ?? data.slug ?? normalized;
|
||||
const targetKey = data.join_token ?? '';
|
||||
if (!targetKey) {
|
||||
setErrorKey('eventClosed');
|
||||
return;
|
||||
}
|
||||
const storedName = readGuestName(targetKey);
|
||||
if (!storedName) {
|
||||
nav(`/setup/${encodeURIComponent(targetKey)}`);
|
||||
|
||||
@@ -23,15 +23,15 @@ interface Props {
|
||||
currentIndex?: number;
|
||||
onClose?: () => void;
|
||||
onIndexChange?: (index: number) => void;
|
||||
slug?: string;
|
||||
token?: string;
|
||||
}
|
||||
|
||||
export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexChange, slug }: Props) {
|
||||
export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexChange, token }: Props) {
|
||||
const params = useParams<{ token?: string; photoId?: string }>();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const photoId = params.photoId;
|
||||
const eventSlug = params.token || slug;
|
||||
const eventToken = params.token || token;
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [standalonePhoto, setStandalonePhoto] = useState<Photo | null>(null);
|
||||
@@ -53,7 +53,7 @@ export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexCh
|
||||
|
||||
// Fetch single photo for standalone mode
|
||||
useEffect(() => {
|
||||
if (isStandalone && photoId && !standalonePhoto && eventSlug) {
|
||||
if (isStandalone && photoId && !standalonePhoto && eventToken) {
|
||||
const fetchPhoto = async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
@@ -80,7 +80,7 @@ export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexCh
|
||||
} else if (!isStandalone) {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [isStandalone, photoId, eventSlug, standalonePhoto, location.state, t]);
|
||||
}, [isStandalone, photoId, eventToken, standalonePhoto, location.state, t]);
|
||||
|
||||
// Update likes when photo changes
|
||||
React.useEffect(() => {
|
||||
@@ -133,7 +133,7 @@ export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexCh
|
||||
|
||||
// Load task info if photo has task_id and event key is available
|
||||
React.useEffect(() => {
|
||||
if (!photo?.task_id || !eventSlug) {
|
||||
if (!photo?.task_id || !eventToken) {
|
||||
setTask(null);
|
||||
setTaskLoading(false);
|
||||
return;
|
||||
@@ -144,7 +144,7 @@ export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexCh
|
||||
(async () => {
|
||||
setTaskLoading(true);
|
||||
try {
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(eventSlug)}/tasks`);
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(eventToken)}/tasks`);
|
||||
if (res.ok) {
|
||||
const tasks = await res.json();
|
||||
const foundTask = tasks.find((t: any) => t.id === taskId);
|
||||
@@ -175,7 +175,7 @@ export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexCh
|
||||
setTaskLoading(false);
|
||||
}
|
||||
})();
|
||||
}, [photo?.task_id, eventSlug, t]);
|
||||
}, [photo?.task_id, eventToken, t]);
|
||||
|
||||
async function onLike() {
|
||||
if (liked || !photo) return;
|
||||
|
||||
@@ -28,8 +28,8 @@ const TASK_PROGRESS_TARGET = 5;
|
||||
const TIMER_VIBRATION = [0, 60, 120, 60];
|
||||
|
||||
export default function TaskPickerPage() {
|
||||
const { token: slug } = useParams<{ token: string }>();
|
||||
const eventKey = slug ?? '';
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const eventKey = token ?? '';
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
@@ -92,12 +92,12 @@ export default function TaskPickerPage() {
|
||||
map.set(task.emotion.slug, task.emotion.name);
|
||||
}
|
||||
});
|
||||
return Array.from(map.entries()).map(([slugValue, name]) => ({ slug: slugValue, name }));
|
||||
return Array.from(map.entries()).map(([slugValue, name]) => ({ slug: tokenValue, name }));
|
||||
}, [tasks]);
|
||||
|
||||
const filteredTasks = React.useMemo(() => {
|
||||
if (selectedEmotion === 'all') return tasks;
|
||||
return tasks.filter((task) => task.emotion?.slug === selectedEmotion);
|
||||
return tasks.filter((task) => task.emotion?.token === selectedEmotion);
|
||||
}, [tasks, selectedEmotion]);
|
||||
|
||||
const selectRandomTask = React.useCallback(
|
||||
|
||||
@@ -56,13 +56,13 @@ const DEFAULT_PREFS: CameraPreferences = {
|
||||
};
|
||||
|
||||
export default function UploadPage() {
|
||||
const { token: slug } = useParams<{ token: string }>();
|
||||
const eventKey = slug ?? '';
|
||||
const { token } = useParams<{ token: string }>();
|
||||
const eventKey = token ?? '';
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { appearance } = useAppearance();
|
||||
const isDarkMode = appearance === 'dark';
|
||||
const { markCompleted } = useGuestTaskProgress(slug);
|
||||
const { markCompleted } = useGuestTaskProgress(token);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const taskIdParam = searchParams.get('task');
|
||||
@@ -138,7 +138,7 @@ export default function UploadPage() {
|
||||
|
||||
// Load task metadata
|
||||
useEffect(() => {
|
||||
if (!slug || !taskId) {
|
||||
if (!token || !taskId) {
|
||||
setTaskError(t('upload.loadError.title'));
|
||||
setLoadingTask(false);
|
||||
return;
|
||||
@@ -545,7 +545,7 @@ export default function UploadPage() {
|
||||
if (!supportsCamera && !task) {
|
||||
return (
|
||||
<div className="pb-16">
|
||||
<Header slug={eventKey} title={t('upload.cameraTitle')} />
|
||||
<Header eventToken={eventKey} title={t('upload.cameraTitle')} />
|
||||
<main className="px-4 py-6">
|
||||
<Alert>
|
||||
<AlertDescription>{t('upload.cameraUnsupported.message')}</AlertDescription>
|
||||
@@ -559,7 +559,7 @@ export default function UploadPage() {
|
||||
if (loadingTask) {
|
||||
return (
|
||||
<div className="pb-16">
|
||||
<Header slug={eventKey} title={t('upload.cameraTitle')} />
|
||||
<Header eventToken={eventKey} title={t('upload.cameraTitle')} />
|
||||
<main className="px-4 py-6 flex flex-col items-center justify-center text-center">
|
||||
<Loader2 className="h-10 w-10 animate-spin text-pink-500 mb-4" />
|
||||
<p className="text-sm text-muted-foreground">{t('upload.preparing')}</p>
|
||||
@@ -572,7 +572,7 @@ export default function UploadPage() {
|
||||
if (!canUpload) {
|
||||
return (
|
||||
<div className="pb-16">
|
||||
<Header slug={eventKey} title={t('upload.cameraTitle')} />
|
||||
<Header eventToken={eventKey} title={t('upload.cameraTitle')} />
|
||||
<main className="px-4 py-6">
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
@@ -638,7 +638,7 @@ export default function UploadPage() {
|
||||
|
||||
return (
|
||||
<div className="pb-16">
|
||||
<Header slug={eventKey} title={t('upload.cameraTitle')} />
|
||||
<Header eventToken={eventKey} title={t('upload.cameraTitle')} />
|
||||
<main className="relative flex flex-col gap-4 pb-4">
|
||||
<div className="absolute left-0 right-0 top-0" aria-hidden="true">
|
||||
{renderPrimer()}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
type Photo = { id: number; file_path?: string; thumbnail_path?: string; created_at?: string };
|
||||
|
||||
export function usePollGalleryDelta(slug: string) {
|
||||
export function usePollGalleryDelta(token: string) {
|
||||
const [photos, setPhotos] = useState<Photo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [newCount, setNewCount] = useState(0);
|
||||
@@ -13,14 +13,14 @@ export function usePollGalleryDelta(slug: string) {
|
||||
);
|
||||
|
||||
async function fetchDelta() {
|
||||
if (!slug) {
|
||||
if (!token) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const qs = latestAt.current ? `?since=${encodeURIComponent(latestAt.current)}` : '';
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(slug)}/photos${qs}`, {
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(token)}/photos${qs}`, {
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
});
|
||||
|
||||
@@ -90,7 +90,7 @@ export function usePollGalleryDelta(slug: string) {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!slug) {
|
||||
if (!token) {
|
||||
setPhotos([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
@@ -107,7 +107,7 @@ export function usePollGalleryDelta(slug: string) {
|
||||
return () => {
|
||||
if (timer.current) window.clearInterval(timer.current);
|
||||
};
|
||||
}, [slug, visible]);
|
||||
}, [token, visible]);
|
||||
|
||||
function acknowledgeNew() { setNewCount(0); }
|
||||
return { loading, photos, newCount, acknowledgeNew };
|
||||
|
||||
@@ -6,7 +6,7 @@ type SyncManager = { register(tag: string): Promise<void>; };
|
||||
|
||||
export type QueueItem = {
|
||||
id?: number;
|
||||
slug: string;
|
||||
eventToken: string;
|
||||
fileName: string;
|
||||
blob: Blob;
|
||||
emotion_id?: number | null;
|
||||
@@ -77,7 +77,7 @@ async function attemptUpload(it: QueueItem): Promise<boolean> {
|
||||
if (!navigator.onLine) return false;
|
||||
try {
|
||||
const json = await createUpload(
|
||||
`/api/v1/events/${encodeURIComponent(it.slug)}/photos`,
|
||||
`/api/v1/events/${encodeURIComponent(it.eventToken)}/photos`,
|
||||
it,
|
||||
getDeviceId(),
|
||||
(pct) => {
|
||||
|
||||
@@ -97,7 +97,7 @@ function EventBoundary({ token }: { token: string }) {
|
||||
<LocaleProvider defaultLocale={eventLocale} storageKey={localeStorageKey}>
|
||||
<EventStatsProvider eventKey={token}>
|
||||
<div className="pb-16">
|
||||
<Header slug={token} />
|
||||
<Header eventToken={token} />
|
||||
<div className="px-4 py-3">
|
||||
<Outlet />
|
||||
</div>
|
||||
@@ -119,7 +119,7 @@ function SetupLayout() {
|
||||
<LocaleProvider defaultLocale={eventLocale} storageKey={localeStorageKey}>
|
||||
<EventStatsProvider eventKey={token}>
|
||||
<div className="pb-0">
|
||||
<Header slug={token} />
|
||||
<Header eventToken={token} />
|
||||
<Outlet />
|
||||
</div>
|
||||
</EventStatsProvider>
|
||||
|
||||
@@ -87,7 +87,7 @@ function safeString(value: unknown): string {
|
||||
}
|
||||
|
||||
export async function fetchAchievements(
|
||||
slug: string,
|
||||
eventToken: string,
|
||||
guestName?: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<AchievementsPayload> {
|
||||
@@ -96,7 +96,7 @@ export async function fetchAchievements(
|
||||
params.set('guest_name', guestName.trim());
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/v1/events/${encodeURIComponent(slug)}/achievements?${params.toString()}`, {
|
||||
const response = await fetch(`/api/v1/events/${encodeURIComponent(eventToken)}/achievements?${params.toString()}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Device-Id': getDeviceId(),
|
||||
|
||||
@@ -183,8 +183,8 @@ export async function fetchStats(eventKey: string): Promise<EventStats> {
|
||||
};
|
||||
}
|
||||
|
||||
export async function getEventPackage(slug: string): Promise<EventPackage | null> {
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(slug)}/package`);
|
||||
export async function getEventPackage(eventToken: string): Promise<EventPackage | null> {
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(eventToken)}/package`);
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) return null;
|
||||
throw new Error('Failed to load event package');
|
||||
|
||||
@@ -70,14 +70,14 @@ export async function likePhoto(id: number): Promise<number> {
|
||||
return json.likes_count ?? json.data?.likes_count ?? 0;
|
||||
}
|
||||
|
||||
export async function uploadPhoto(slug: string, file: File, taskId?: number, emotionSlug?: string): Promise<number> {
|
||||
export async function uploadPhoto(eventToken: string, file: File, taskId?: number, emotionSlug?: string): Promise<number> {
|
||||
const formData = new FormData();
|
||||
formData.append('photo', file, `photo-${Date.now()}.jpg`);
|
||||
if (taskId) formData.append('task_id', taskId.toString());
|
||||
if (emotionSlug) formData.append('emotion_slug', emotionSlug);
|
||||
formData.append('device_id', getDeviceId());
|
||||
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(slug)}/upload`, {
|
||||
const res = await fetch(`/api/v1/events/${encodeURIComponent(eventToken)}/upload`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: formData,
|
||||
|
||||
44
resources/js/hooks/useAnalytics.ts
Normal file
44
resources/js/hooks/useAnalytics.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useConsent } from '@/contexts/consent';
|
||||
|
||||
type AnalyticsEvent = {
|
||||
category: string;
|
||||
action: string;
|
||||
name?: string;
|
||||
value?: number;
|
||||
};
|
||||
|
||||
export function useAnalytics() {
|
||||
const { hasConsent } = useConsent();
|
||||
|
||||
const trackEvent = useCallback(
|
||||
({ category, action, name, value }: AnalyticsEvent) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasConsent('analytics')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const queue = (window._paq = window._paq || []);
|
||||
const payload: (string | number)[] = ['trackEvent', category, action];
|
||||
|
||||
if (typeof name === 'string') {
|
||||
payload.push(name);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
if (payload.length === 3) {
|
||||
payload.push('');
|
||||
}
|
||||
payload.push(value);
|
||||
}
|
||||
|
||||
queue.push(payload);
|
||||
},
|
||||
[hasConsent],
|
||||
);
|
||||
|
||||
return { trackEvent };
|
||||
}
|
||||
58
resources/js/hooks/useCtaExperiment.ts
Normal file
58
resources/js/hooks/useCtaExperiment.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { useAnalytics } from '@/hooks/useAnalytics';
|
||||
|
||||
type CtaVariant = 'gradient' | 'neutral';
|
||||
|
||||
const STORAGE_KEY = 'marketing_cta_variant_v1';
|
||||
|
||||
function determineVariant(): CtaVariant {
|
||||
if (typeof window === 'undefined') {
|
||||
return 'gradient';
|
||||
}
|
||||
|
||||
const stored = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (stored === 'gradient' || stored === 'neutral') {
|
||||
return stored;
|
||||
}
|
||||
|
||||
const assigned: CtaVariant = Math.random() < 0.5 ? 'gradient' : 'neutral';
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, assigned);
|
||||
} catch (error) {
|
||||
// localStorage may be unavailable; ignore and fallback to the assigned variant in memory
|
||||
console.warn('Unable to persist CTA variant assignment', error);
|
||||
}
|
||||
return assigned;
|
||||
}
|
||||
|
||||
export function useCtaExperiment(placement: string) {
|
||||
const { trackEvent } = useAnalytics();
|
||||
const [variant] = useState<CtaVariant>(() => determineVariant());
|
||||
|
||||
const trackingLabel = useMemo(() => `${placement}:${variant}`, [placement, variant]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
trackEvent({
|
||||
category: 'marketing_experiment',
|
||||
action: 'cta_impression',
|
||||
name: trackingLabel,
|
||||
});
|
||||
}, [trackEvent, trackingLabel]);
|
||||
|
||||
const trackClick = useCallback(() => {
|
||||
trackEvent({
|
||||
category: 'marketing_experiment',
|
||||
action: 'cta_click',
|
||||
name: trackingLabel,
|
||||
});
|
||||
}, [trackEvent, trackingLabel]);
|
||||
|
||||
return {
|
||||
variant,
|
||||
trackClick,
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import React from 'react';
|
||||
import { Link } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { usePage } from '@inertiajs/react';
|
||||
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
|
||||
import { useAppearance } from '@/hooks/use-appearance';
|
||||
|
||||
import { useConsent } from '@/contexts/consent';
|
||||
|
||||
const Footer: React.FC = () => {
|
||||
|
||||
const { t } = useTranslation(['marketing', 'legal']);
|
||||
const { t } = useTranslation(['marketing', 'legal', 'common']);
|
||||
const { openPreferences } = useConsent();
|
||||
|
||||
|
||||
return (
|
||||
@@ -36,6 +34,15 @@ const Footer: React.FC = () => {
|
||||
<li><Link href="/datenschutz" className="hover:text-pink-500 transition-colors">{t('legal:datenschutz')}</Link></li>
|
||||
<li><Link href="/agb" className="hover:text-pink-500 transition-colors">{t('legal:agb')}</Link></li>
|
||||
<li><Link href="/kontakt" className="hover:text-pink-500 transition-colors">{t('marketing:nav.contact')}</Link></li>
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onClick={openPreferences}
|
||||
className="hover:text-pink-500 transition-colors"
|
||||
>
|
||||
{t('common:consent.footer.manage_link')}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -119,7 +119,7 @@ const Header: React.FC = () => {
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Link href={localizedPath('/')} 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" />
|
||||
<span className="text-2xl font-bold font-display text-pink-500">
|
||||
FotoSpiel.App
|
||||
</span>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { Head, Link, usePage, router } from '@inertiajs/react';
|
||||
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
|
||||
import { Head, usePage, router } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import MatomoTracker, { MatomoConfig } from '@/components/analytics/MatomoTracker';
|
||||
import CookieBanner from '@/components/consent/CookieBanner';
|
||||
|
||||
interface MarketingLayoutProps {
|
||||
children: React.ReactNode;
|
||||
@@ -9,12 +10,15 @@ interface MarketingLayoutProps {
|
||||
}
|
||||
|
||||
const MarketingLayout: React.FC<MarketingLayoutProps> = ({ children, title }) => {
|
||||
const page = usePage<{ translations?: Record<string, Record<string, string>> }>();
|
||||
const page = usePage<{
|
||||
translations?: Record<string, Record<string, string>>;
|
||||
locale?: string;
|
||||
analytics?: { matomo?: MatomoConfig };
|
||||
}>();
|
||||
const { url } = page;
|
||||
const { t } = useTranslation('marketing');
|
||||
const i18n = useTranslation();
|
||||
const { locale } = usePage().props as any;
|
||||
const { localizedPath } = useLocalizedRoutes();
|
||||
const { locale, analytics } = page.props;
|
||||
|
||||
useEffect(() => {
|
||||
if (locale && i18n.i18n.language !== locale) {
|
||||
@@ -61,6 +65,8 @@ const MarketingLayout: React.FC<MarketingLayoutProps> = ({ children, title }) =>
|
||||
<link rel="canonical" href={canonicalUrl} />
|
||||
<link rel="alternate" hrefLang="x-default" href="https://fotospiel.app/" />
|
||||
</Head>
|
||||
<MatomoTracker config={analytics?.matomo} />
|
||||
<CookieBanner />
|
||||
<div className="min-h-screen bg-white">
|
||||
<header className="bg-white shadow-sm">
|
||||
<div className="container mx-auto px-4 py-4">
|
||||
|
||||
@@ -3,6 +3,8 @@ import { Head, Link, useForm } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useLocalizedRoutes } from '@/hooks/useLocalizedRoutes';
|
||||
import MarketingLayout from '@/layouts/mainWebsite';
|
||||
import { useAnalytics } from '@/hooks/useAnalytics';
|
||||
import { useCtaExperiment } from '@/hooks/useCtaExperiment';
|
||||
|
||||
interface Package {
|
||||
id: number;
|
||||
@@ -18,6 +20,11 @@ interface Props {
|
||||
const Home: React.FC<Props> = ({ packages }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { localizedPath } = useLocalizedRoutes();
|
||||
const { trackEvent } = useAnalytics();
|
||||
const {
|
||||
variant: heroCtaVariant,
|
||||
trackClick: trackHeroCtaClick,
|
||||
} = useCtaExperiment('home_hero_cta');
|
||||
const { data, setData, post, processing, errors, reset } = useForm({
|
||||
name: '',
|
||||
email: '',
|
||||
@@ -27,7 +34,13 @@ const Home: React.FC<Props> = ({ packages }) => {
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
post(localizedPath('/kontakt'), {
|
||||
onSuccess: () => reset(),
|
||||
onSuccess: () => {
|
||||
trackEvent({
|
||||
category: 'marketing_home',
|
||||
action: 'contact_submit',
|
||||
});
|
||||
reset();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -49,9 +62,22 @@ const Home: React.FC<Props> = ({ packages }) => {
|
||||
<p className="text-xl md:text-2xl mb-8 font-sans-marketing">{t('home.hero_description')}</p>
|
||||
<Link
|
||||
href={localizedPath('/packages')}
|
||||
className="bg-white dark:bg-gray-800 text-[#FFB6C1] px-8 py-4 rounded-full font-bold hover:bg-gray-100 dark:hover:bg-gray-700 transition duration-300 inline-block"
|
||||
onClick={() => {
|
||||
trackHeroCtaClick();
|
||||
trackEvent({
|
||||
category: 'marketing_home',
|
||||
action: 'hero_cta',
|
||||
name: `packages:${heroCtaVariant}`,
|
||||
});
|
||||
}}
|
||||
className={[
|
||||
'inline-block rounded-full px-8 py-4 font-bold transition duration-300',
|
||||
heroCtaVariant === 'gradient'
|
||||
? 'bg-gradient-to-r from-rose-500 via-pink-500 to-amber-400 text-white shadow-lg shadow-rose-500/40 hover:from-rose-500/95 hover:via-pink-500/95 hover:to-amber-400/95'
|
||||
: 'bg-white text-[#FFB6C1] hover:bg-gray-100 dark:bg-gray-800 dark:text-rose-200 dark:hover:bg-gray-700',
|
||||
].join(' ')}
|
||||
>
|
||||
{t('home.cta_explore')}
|
||||
{heroCtaVariant === 'gradient' ? t('home.cta_explore_highlight') : t('home.cta_explore')}
|
||||
</Link>
|
||||
</div>
|
||||
<div className="md:w-1/2">
|
||||
@@ -125,14 +151,34 @@ const Home: React.FC<Props> = ({ packages }) => {
|
||||
<h3 className="text-2xl font-bold mb-2">{pkg.name}</h3>
|
||||
<p className="text-gray-600 dark:text-gray-300 mb-4">{pkg.description}</p>
|
||||
<p className="text-3xl font-bold text-[#FFB6C1]">{pkg.price} {t('currency.euro')}</p>
|
||||
<Link href={`${localizedPath('/register')}?package_id=${pkg.id}`} className="mt-4 inline-block bg-[#FFB6C1] text-white px-6 py-2 rounded-full hover:bg-pink-600">
|
||||
<Link
|
||||
href={`${localizedPath('/packages')}?package_id=${pkg.id}`}
|
||||
onClick={() =>
|
||||
trackEvent({
|
||||
category: 'marketing_home',
|
||||
action: 'package_teaser_cta',
|
||||
name: pkg.name,
|
||||
value: pkg.price,
|
||||
})
|
||||
}
|
||||
className="mt-4 inline-block bg-[#FFB6C1] text-white px-6 py-2 rounded-full hover:bg-pink-600"
|
||||
>
|
||||
{t('home.view_details')}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<Link href={localizedPath('/packages')} className="bg-[#FFB6C1] text-white px-8 py-4 rounded-full font-bold hover:bg-pink-600 transition">
|
||||
<Link
|
||||
href={localizedPath('/packages')}
|
||||
onClick={() =>
|
||||
trackEvent({
|
||||
category: 'marketing_home',
|
||||
action: 'all_packages_cta',
|
||||
})
|
||||
}
|
||||
className="bg-[#FFB6C1] text-white px-8 py-4 rounded-full font-bold hover:bg-pink-600 transition"
|
||||
>
|
||||
{t('home.all_packages')}
|
||||
</Link>
|
||||
</div>
|
||||
@@ -235,4 +281,4 @@ const Home: React.FC<Props> = ({ packages }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
||||
export default Home;
|
||||
|
||||
@@ -13,6 +13,8 @@ import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { cn } from '@/lib/utils';
|
||||
import MarketingLayout from '@/layouts/mainWebsite';
|
||||
import { useAnalytics } from '@/hooks/useAnalytics';
|
||||
import { useCtaExperiment } from '@/hooks/useCtaExperiment';
|
||||
import { ArrowRight, ShoppingCart, Check, X, Users, Image, Shield, Star, Sparkles } from 'lucide-react';
|
||||
|
||||
interface Package {
|
||||
@@ -50,11 +52,15 @@ interface PackagesProps {
|
||||
const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackages }) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [selectedPackage, setSelectedPackage] = useState<Package | null>(null);
|
||||
const [currentStep, setCurrentStep] = useState('step1');
|
||||
const [currentStep, setCurrentStep] = useState<'overview' | 'deep' | 'testimonials'>('overview');
|
||||
const { props } = usePage();
|
||||
const { auth } = props as any;
|
||||
const { t } = useTranslation('marketing');
|
||||
const { t: tCommon } = useTranslation('common');
|
||||
const {
|
||||
variant: packagesHeroVariant,
|
||||
trackClick: trackPackagesHeroClick,
|
||||
} = useCtaExperiment('packages_hero_cta');
|
||||
|
||||
useEffect(() => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
@@ -65,7 +71,7 @@ const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackag
|
||||
if (pkg) {
|
||||
setSelectedPackage(pkg);
|
||||
setOpen(true);
|
||||
setCurrentStep('step1');
|
||||
setCurrentStep('overview');
|
||||
}
|
||||
}
|
||||
}, [endcustomerPackages, resellerPackages]);
|
||||
@@ -78,27 +84,34 @@ const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackag
|
||||
|
||||
const allPackages = [...endcustomerPackages, ...resellerPackages];
|
||||
|
||||
const highlightEndcustomerId = useMemo(() => {
|
||||
if (!endcustomerPackages.length) {
|
||||
const selectHighlightPackageId = (packages: Package[]): number | null => {
|
||||
const count = packages.length;
|
||||
if (count <= 1) {
|
||||
return null;
|
||||
}
|
||||
const best = endcustomerPackages.reduce((prev, current) => {
|
||||
if (!prev) return current;
|
||||
return current.price > prev.price ? current : prev;
|
||||
}, null as Package | null);
|
||||
return best?.id ?? endcustomerPackages[0].id;
|
||||
}, [endcustomerPackages]);
|
||||
|
||||
const highlightResellerId = useMemo(() => {
|
||||
if (!resellerPackages.length) {
|
||||
return null;
|
||||
const sortedByPrice = [...packages].sort((a, b) => a.price - b.price);
|
||||
|
||||
if (count === 2) {
|
||||
return sortedByPrice[1]?.id ?? null;
|
||||
}
|
||||
const best = resellerPackages.reduce((prev, current) => {
|
||||
if (!prev) return current;
|
||||
return current.price > prev.price ? current : prev;
|
||||
}, null as Package | null);
|
||||
return best?.id ?? resellerPackages[0].id;
|
||||
}, [resellerPackages]);
|
||||
|
||||
if (count === 3) {
|
||||
return sortedByPrice[1]?.id ?? null;
|
||||
}
|
||||
|
||||
return sortedByPrice[count - 2]?.id ?? null;
|
||||
};
|
||||
|
||||
const highlightEndcustomerId = useMemo(
|
||||
() => selectHighlightPackageId(endcustomerPackages),
|
||||
[endcustomerPackages],
|
||||
);
|
||||
|
||||
const highlightResellerId = useMemo(
|
||||
() => selectHighlightPackageId(resellerPackages),
|
||||
[resellerPackages],
|
||||
);
|
||||
|
||||
function isHighlightedPackage(pkg: Package, variant: 'endcustomer' | 'reseller') {
|
||||
return variant === 'reseller' ? pkg.id === highlightResellerId : pkg.id === highlightEndcustomerId;
|
||||
@@ -113,12 +126,29 @@ const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackag
|
||||
? isHighlightedPackage(selectedPackage, selectedVariant)
|
||||
: false;
|
||||
|
||||
const handleCardClick = (pkg: Package) => {
|
||||
const { trackEvent } = useAnalytics();
|
||||
|
||||
const handleCardClick = (pkg: Package, variant: 'endcustomer' | 'reseller') => {
|
||||
trackEvent({
|
||||
category: 'marketing_packages',
|
||||
action: 'open_dialog',
|
||||
name: `${variant}:${pkg.name}`,
|
||||
value: pkg.price,
|
||||
});
|
||||
setSelectedPackage(pkg);
|
||||
setCurrentStep('step1');
|
||||
setCurrentStep('overview');
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const handleCtaClick = (pkg: Package, variant: 'endcustomer' | 'reseller') => {
|
||||
trackEvent({
|
||||
category: 'marketing_packages',
|
||||
action: 'cta_dialog',
|
||||
name: `${variant}:${pkg.name}`,
|
||||
value: pkg.price,
|
||||
});
|
||||
};
|
||||
|
||||
// nextStep entfernt, da Tabs nun parallel sind
|
||||
|
||||
const getFeatureIcon = (feature: string) => {
|
||||
@@ -428,8 +458,24 @@ function PackageCard({
|
||||
<div className="container mx-auto text-center">
|
||||
<h1 className="text-4xl md:text-6xl font-bold mb-4 font-display">{t('packages.hero_title')}</h1>
|
||||
<p className="text-xl md:text-2xl mb-8 max-w-3xl mx-auto font-sans-marketing">{t('packages.hero_description')}</p>
|
||||
<Link href="#endcustomer" className="bg-white dark:bg-gray-800 text-[#FFB6C1] px-8 py-4 rounded-full font-semibold text-lg font-sans-marketing hover:bg-gray-100 dark:hover:bg-gray-700 transition">
|
||||
{t('packages.cta_explore')}
|
||||
<Link
|
||||
href="#endcustomer"
|
||||
onClick={() => {
|
||||
trackPackagesHeroClick();
|
||||
trackEvent({
|
||||
category: 'marketing_packages',
|
||||
action: 'hero_cta',
|
||||
name: `endcustomer:${packagesHeroVariant}`,
|
||||
});
|
||||
}}
|
||||
className={cn(
|
||||
'rounded-full px-8 py-4 text-lg font-semibold font-sans-marketing transition duration-300',
|
||||
packagesHeroVariant === 'gradient'
|
||||
? 'bg-gradient-to-r from-rose-500 via-pink-500 to-amber-400 text-white shadow-lg shadow-rose-500/40 hover:from-rose-500/95 hover:via-pink-500/95 hover:to-amber-400/95'
|
||||
: 'bg-white text-[#FFB6C1] hover:bg-gray-100 dark:bg-gray-800 dark:text-rose-200 dark:hover:bg-gray-700',
|
||||
)}
|
||||
>
|
||||
{packagesHeroVariant === 'gradient' ? t('packages.cta_explore_highlight') : t('packages.cta_explore')}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
@@ -447,7 +493,7 @@ function PackageCard({
|
||||
pkg={pkg}
|
||||
variant="endcustomer"
|
||||
highlight={pkg.id === highlightEndcustomerId}
|
||||
onSelect={handleCardClick}
|
||||
onSelect={(pkg) => handleCardClick(pkg, 'endcustomer')}
|
||||
className="h-full"
|
||||
/>
|
||||
</CarouselItem>
|
||||
@@ -465,7 +511,7 @@ function PackageCard({
|
||||
pkg={pkg}
|
||||
variant="endcustomer"
|
||||
highlight={pkg.id === highlightEndcustomerId}
|
||||
onSelect={handleCardClick}
|
||||
onSelect={(pkg) => handleCardClick(pkg, 'endcustomer')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -615,7 +661,7 @@ function PackageCard({
|
||||
pkg={pkg}
|
||||
variant="reseller"
|
||||
highlight={pkg.id === highlightResellerId}
|
||||
onSelect={handleCardClick}
|
||||
onSelect={(pkg) => handleCardClick(pkg, 'reseller')}
|
||||
className="h-full"
|
||||
/>
|
||||
</CarouselItem>
|
||||
@@ -633,7 +679,7 @@ function PackageCard({
|
||||
pkg={pkg}
|
||||
variant="reseller"
|
||||
highlight={pkg.id === highlightResellerId}
|
||||
onSelect={handleCardClick}
|
||||
onSelect={(pkg) => handleCardClick(pkg, 'reseller')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -715,15 +761,20 @@ function PackageCard({
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<Tabs value={currentStep} onValueChange={setCurrentStep} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2 rounded-full bg-white/60 p-1 text-sm shadow-sm dark:bg-gray-900/60">
|
||||
<TabsTrigger className="rounded-full" value="step1">{t('packages.details')}</TabsTrigger>
|
||||
<TabsTrigger className="rounded-full" value="step2">{t('packages.customer_opinions')}</TabsTrigger>
|
||||
<TabsList className="grid w-full grid-cols-3 rounded-full bg-white/60 p-1 text-sm shadow-sm dark:bg-gray-900/60">
|
||||
<TabsTrigger className="rounded-full" value="overview">{t('packages.details')}</TabsTrigger>
|
||||
<TabsTrigger className="rounded-full" value="deep">{t('packages.more_details_tab')}</TabsTrigger>
|
||||
<TabsTrigger className="rounded-full" value="testimonials">{t('packages.customer_opinions')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="step1" className="mt-6 space-y-6">
|
||||
<TabsContent value="overview" className="mt-6 space-y-6">
|
||||
{(() => {
|
||||
const accent = getAccentTheme(selectedVariant);
|
||||
const metrics = resolvePackageMetrics(selectedPackage, selectedVariant, t, tCommon);
|
||||
const descriptionEntries = selectedPackage.description_breakdown ?? [];
|
||||
const topFeatureBadges = selectedPackage.features.slice(0, 3);
|
||||
const hasMoreFeatures = selectedPackage.features.length > topFeatureBadges.length;
|
||||
const quickFacts = metrics.slice(0, 2);
|
||||
const showDeepLink =
|
||||
hasMoreFeatures || (selectedPackage.description_breakdown?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1.2fr),minmax(0,0.8fr)]">
|
||||
@@ -740,64 +791,177 @@ function PackageCard({
|
||||
'radial-gradient(circle at top left, rgba(255,182,193,0.45), transparent 55%), radial-gradient(circle at bottom right, rgba(250,204,21,0.35), transparent 55%)',
|
||||
}}
|
||||
/>
|
||||
<div className="relative space-y-4">
|
||||
<Badge className="inline-flex w-fit items-center gap-1 rounded-full bg-gray-900/90 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-white shadow-md dark:bg-white/90 dark:text-gray-900">
|
||||
<Sparkles className="h-3.5 w-3.5" />
|
||||
{t('packages.features_label')}
|
||||
</Badge>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{selectedPackage.features.map((feature) => (
|
||||
<Badge
|
||||
key={feature}
|
||||
variant="outline"
|
||||
className="flex items-center gap-1 rounded-full border-transparent bg-white/80 px-3 py-1 text-xs font-medium text-gray-700 shadow-sm dark:bg-gray-800/70 dark:text-gray-200"
|
||||
<div className="relative flex h-full flex-col justify-between gap-5">
|
||||
<div className="space-y-5">
|
||||
<Badge className="inline-flex w-fit items-center gap-1 rounded-full bg-gray-900/90 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-white shadow-md dark:bg-white/90 dark:text-gray-900">
|
||||
<Sparkles className="h-3.5 w-3.5" />
|
||||
{t('packages.feature_highlights')}
|
||||
</Badge>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{topFeatureBadges.map((feature) => (
|
||||
<Badge
|
||||
key={feature}
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'flex items-center gap-1 rounded-full border-transparent bg-white/80 px-3 py-1 text-xs font-medium text-gray-700 shadow-sm transition-colors hover:bg-white dark:bg-gray-800/70 dark:text-gray-200',
|
||||
selectedHighlight && 'bg-white/85 dark:bg-white/10',
|
||||
)}
|
||||
>
|
||||
{getFeatureIcon(feature)}
|
||||
<span>{t(`packages.feature_${feature}`)}</span>
|
||||
</Badge>
|
||||
))}
|
||||
{selectedPackage.watermark_allowed === false && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-emerald-100/80 px-3 py-1 text-xs font-medium text-emerald-700 shadow-sm dark:bg-emerald-500/20 dark:text-emerald-100">
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
{t('packages.no_watermark')}
|
||||
</Badge>
|
||||
)}
|
||||
{selectedPackage.branding_allowed && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-sky-100/80 px-3 py-1 text-xs font-medium text-sky-700 shadow-sm dark:bg-sky-500/20 dark:text-sky-100">
|
||||
<Sparkles className="h-3.5 w-3.5" />
|
||||
{t('packages.custom_branding')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{showDeepLink && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCurrentStep('deep')}
|
||||
className="inline-flex items-center gap-2 text-sm font-semibold text-rose-500 transition-colors hover:text-rose-600 dark:text-rose-300 dark:hover:text-rose-200"
|
||||
>
|
||||
{getFeatureIcon(feature)}
|
||||
<span>{t(`packages.feature_${feature}`)}</span>
|
||||
</Badge>
|
||||
))}
|
||||
{selectedPackage.watermark_allowed === false && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-emerald-100/80 px-3 py-1 text-xs font-medium text-emerald-700 shadow-sm dark:bg-emerald-500/20 dark:text-emerald-100">
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
{t('packages.no_watermark')}
|
||||
</Badge>
|
||||
)}
|
||||
{selectedPackage.branding_allowed && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-sky-100/80 px-3 py-1 text-xs font-medium text-sky-700 shadow-sm dark:bg-sky-500/20 dark:text-sky-100">
|
||||
<Sparkles className="h-3.5 w-3.5" />
|
||||
{t('packages.custom_branding')}
|
||||
</Badge>
|
||||
{t('packages.more_details_link')}
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</button>
|
||||
)}
|
||||
<Button
|
||||
asChild
|
||||
className={cn(
|
||||
'w-full justify-center gap-2 rounded-full py-3 text-base font-semibold transition-all duration-300',
|
||||
accent.ctaShadow,
|
||||
selectedHighlight ? accent.buttonHighlight : accent.buttonDefault,
|
||||
)}
|
||||
>
|
||||
<Link
|
||||
href={`/purchase-wizard/${selectedPackage.id}`}
|
||||
onClick={() => {
|
||||
if (selectedPackage) {
|
||||
handleCtaClick(selectedPackage, selectedVariant);
|
||||
}
|
||||
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
||||
}}
|
||||
>
|
||||
{t('packages.to_order')}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<p className="text-xs text-center text-gray-500 dark:text-gray-400">
|
||||
{t('packages.order_hint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
{descriptionEntries.length > 0 && (
|
||||
<div className="rounded-3xl border border-gray-200/80 bg-white/90 p-6 shadow-xl dark:border-gray-700/70 dark:bg-gray-900/90">
|
||||
<h3 className="text-sm font-semibold uppercase tracking-[0.3em] text-gray-400 dark:text-gray-500">
|
||||
{t('packages.breakdown_label')}
|
||||
</h3>
|
||||
<div className="mt-4 grid gap-3">
|
||||
{descriptionEntries.map((entry, index) => (
|
||||
<div
|
||||
key={`${entry.title}-${index}`}
|
||||
className="rounded-2xl bg-gradient-to-r from-rose-50/90 via-white to-white p-4 shadow-sm dark:from-gray-800 dark:via-gray-900 dark:to-gray-900"
|
||||
>
|
||||
{entry.title && (
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-rose-500 dark:text-rose-200">
|
||||
{entry.title}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 text-sm text-gray-700 dark:text-gray-300">{entry.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex h-full flex-col gap-4 rounded-3xl border border-gray-200/70 bg-white/90 p-6 shadow-lg dark:border-gray-700/70 dark:bg-gray-900/85">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{t('packages.quick_facts')}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300">
|
||||
{t('packages.quick_facts_hint')}
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{quickFacts.map((metric) => (
|
||||
<li
|
||||
key={metric.key}
|
||||
className="rounded-2xl border border-gray-200/70 bg-white/80 p-4 dark:border-gray-700/70 dark:bg-gray-800/70"
|
||||
>
|
||||
<p className="text-lg font-semibold text-gray-900 dark:text-white">{metric.value}</p>
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">
|
||||
{metric.label}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{showDeepLink && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="mt-auto w-full justify-center rounded-full border-rose-200/70 text-rose-600 hover:bg-rose-50 dark:border-rose-500/40 dark:text-rose-200 dark:hover:bg-rose-500/10"
|
||||
onClick={() => setCurrentStep('deep')}
|
||||
>
|
||||
{t('packages.more_details_link')}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="rounded-3xl border border-gray-200/80 bg-white/90 p-6 shadow-xl dark:border-gray-700/70 dark:bg-gray-900/90">
|
||||
<h3 className="text-sm font-semibold uppercase tracking-[0.3em] text-gray-400 dark:text-gray-500">
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="deep" className="mt-6 space-y-6">
|
||||
{(() => {
|
||||
const accent = getAccentTheme(selectedVariant);
|
||||
const metrics = resolvePackageMetrics(selectedPackage, selectedVariant, t, tCommon);
|
||||
const descriptionEntries = selectedPackage.description_breakdown ?? [];
|
||||
const entriesWithTitle = descriptionEntries.filter((entry) => entry.title);
|
||||
const entriesWithoutTitle = descriptionEntries.filter((entry) => !entry.title);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section className="rounded-3xl border border-gray-200/70 bg-white/95 p-6 shadow-lg dark:border-gray-700/70 dark:bg-gray-900/85">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge className="rounded-full bg-gray-900/90 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-white shadow-md dark:bg-white/90 dark:text-gray-900">
|
||||
{t('packages.features_label')}
|
||||
</Badge>
|
||||
{selectedHighlight && (
|
||||
<Badge className="rounded-full bg-gradient-to-r from-rose-500 via-pink-500 to-amber-400 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-white shadow-sm">
|
||||
{t('packages.badge_deep_dive')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{selectedPackage.features.map((feature) => (
|
||||
<Badge
|
||||
key={feature}
|
||||
variant="outline"
|
||||
className={cn(
|
||||
'flex items-center gap-1 rounded-full border-transparent bg-white/85 px-3 py-1 text-xs font-medium text-gray-700 shadow-sm transition-colors hover:bg-white dark:bg-gray-800/70 dark:text-gray-200',
|
||||
selectedHighlight && 'bg-white/85 dark:bg-white/10',
|
||||
)}
|
||||
>
|
||||
{getFeatureIcon(feature)}
|
||||
<span>{t(`packages.feature_${feature}`)}</span>
|
||||
</Badge>
|
||||
))}
|
||||
{selectedPackage.watermark_allowed === false && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-emerald-100/80 px-3 py-1 text-xs font-medium text-emerald-700 shadow-sm dark:bg-emerald-500/20 dark:text-emerald-100">
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
{t('packages.no_watermark')}
|
||||
</Badge>
|
||||
)}
|
||||
{selectedPackage.branding_allowed && (
|
||||
<Badge className="flex items-center gap-1 rounded-full bg-sky-100/80 px-3 py-1 text-xs font-medium text-sky-700 shadow-sm dark:bg-sky-500/20 dark:text-sky-100">
|
||||
<Sparkles className="h-3.5 w-3.5" />
|
||||
{t('packages.custom_branding')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{metrics.length > 0 && (
|
||||
<section
|
||||
className={cn(
|
||||
'rounded-3xl border border-gray-200/70 bg-white/95 p-6 shadow-lg dark:border-gray-700/70 dark:bg-gray-900/85',
|
||||
selectedHighlight && `ring-2 ${accent.ring}`,
|
||||
)}
|
||||
>
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{t('packages.limits_label')}
|
||||
</h3>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-300">
|
||||
{t('packages.limits_label_hint')}
|
||||
</p>
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{metrics.map((metric) => (
|
||||
<div
|
||||
@@ -811,41 +975,59 @@ function PackageCard({
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
asChild
|
||||
className={cn(
|
||||
'w-full justify-center gap-2 rounded-full py-3 text-base font-semibold transition-all duration-300',
|
||||
accent.ctaShadow,
|
||||
selectedHighlight ? accent.buttonHighlight : accent.buttonDefault,
|
||||
)}
|
||||
>
|
||||
<Link
|
||||
href={`/purchase-wizard/${selectedPackage.id}`}
|
||||
onClick={() => {
|
||||
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
||||
}}
|
||||
>
|
||||
{t('packages.to_order')}
|
||||
<ArrowRight className="ml-2 h-4 w-4" aria-hidden />
|
||||
</Link>
|
||||
</Button>
|
||||
<p className="text-xs text-center text-gray-500 dark:text-gray-400">
|
||||
{t('packages.order_hint')}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{descriptionEntries.length > 0 && (
|
||||
<section className="rounded-3xl border border-gray-200/70 bg-white/95 p-6 shadow-lg dark:border-gray-700/70 dark:bg-gray-900/85">
|
||||
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{t('packages.breakdown_label')}
|
||||
</h3>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-300">
|
||||
{t('packages.breakdown_label_hint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{entriesWithTitle.length > 0 && (
|
||||
<Accordion type="single" collapsible className="mt-4 space-y-3">
|
||||
{entriesWithTitle.map((entry, index) => (
|
||||
<AccordionItem
|
||||
key={`${entry.title}-${index}`}
|
||||
value={`entry-${index}`}
|
||||
className="overflow-hidden rounded-2xl border border-gray-200/70 bg-white/85 shadow-sm dark:border-gray-700/70 dark:bg-gray-900/80"
|
||||
>
|
||||
<AccordionTrigger className="px-4 text-left text-sm font-semibold text-gray-900 hover:no-underline dark:text-white">
|
||||
{entry.title}
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4 text-sm text-gray-600 dark:text-gray-300 whitespace-pre-line">
|
||||
{entry.value}
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
)}
|
||||
{entriesWithoutTitle.length > 0 && (
|
||||
<div className="mt-4 space-y-3">
|
||||
{entriesWithoutTitle.map((entry, index) => (
|
||||
<div
|
||||
key={`plain-${index}`}
|
||||
className="rounded-2xl border border-gray-200/70 bg-white/85 p-4 text-sm text-gray-600 shadow-sm dark:border-gray-700/70 dark:bg-gray-900/80 dark:text-gray-300 whitespace-pre-line"
|
||||
>
|
||||
{entry.value}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</TabsContent>
|
||||
<TabsContent value="step2" className="mt-6">
|
||||
<TabsContent value="testimonials" className="mt-6">
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-xl font-semibold font-display text-gray-900 dark:text-white">
|
||||
{t('packages.what_customers_say')}
|
||||
</h3>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="flex flex-col gap-4">
|
||||
{testimonials.map((testimonial, index) => (
|
||||
<div
|
||||
key={index}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useMemo, useRef, useEffect } from "react";
|
||||
import React, { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Steps } from "@/components/ui/Steps";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -9,6 +9,7 @@ import { PackageStep } from "./steps/PackageStep";
|
||||
import { AuthStep } from "./steps/AuthStep";
|
||||
import { PaymentStep } from "./steps/PaymentStep";
|
||||
import { ConfirmationStep } from "./steps/ConfirmationStep";
|
||||
import { useAnalytics } from '@/hooks/useAnalytics';
|
||||
|
||||
interface CheckoutWizardProps {
|
||||
initialPackage: CheckoutPackage;
|
||||
@@ -56,6 +57,7 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
const { currentStep, nextStep, previousStep } = useCheckoutWizard();
|
||||
const progressRef = useRef<HTMLDivElement | null>(null);
|
||||
const hasMountedRef = useRef(false);
|
||||
const { trackEvent } = useAnalytics();
|
||||
|
||||
const stepConfig = useMemo(() =>
|
||||
baseStepConfig.map(step => ({
|
||||
@@ -75,6 +77,14 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
return (currentIndex / (stepConfig.length - 1)) * 100;
|
||||
}, [currentIndex, stepConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
trackEvent({
|
||||
category: 'marketing_checkout',
|
||||
action: 'step_view',
|
||||
name: currentStep,
|
||||
});
|
||||
}, [currentStep, trackEvent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined' || !progressRef.current) {
|
||||
return;
|
||||
@@ -95,6 +105,34 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
});
|
||||
}, [currentStep]);
|
||||
|
||||
const handleNext = useCallback(() => {
|
||||
const targetStep = stepConfig[currentIndex + 1]?.id ?? 'end';
|
||||
trackEvent({
|
||||
category: 'marketing_checkout',
|
||||
action: 'step_next',
|
||||
name: `${currentStep}->${targetStep}`,
|
||||
});
|
||||
nextStep();
|
||||
}, [currentIndex, currentStep, nextStep, stepConfig, trackEvent]);
|
||||
|
||||
const handlePrevious = useCallback(() => {
|
||||
const targetStep = stepConfig[currentIndex - 1]?.id ?? 'start';
|
||||
trackEvent({
|
||||
category: 'marketing_checkout',
|
||||
action: 'step_previous',
|
||||
name: `${currentStep}->${targetStep}`,
|
||||
});
|
||||
previousStep();
|
||||
}, [currentIndex, currentStep, previousStep, stepConfig, trackEvent]);
|
||||
|
||||
const handleViewProfile = useCallback(() => {
|
||||
window.location.href = '/settings/profile';
|
||||
}, []);
|
||||
|
||||
const handleGoToAdmin = useCallback(() => {
|
||||
window.location.href = '/event-admin';
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div ref={progressRef} className="space-y-4">
|
||||
@@ -108,14 +146,16 @@ const WizardBody: React.FC<{ stripePublishableKey: string; paypalClientId: strin
|
||||
{currentStep === "payment" && (
|
||||
<PaymentStep stripePublishableKey={stripePublishableKey} paypalClientId={paypalClientId} />
|
||||
)}
|
||||
{currentStep === "confirmation" && <ConfirmationStep />}
|
||||
{currentStep === "confirmation" && (
|
||||
<ConfirmationStep onViewProfile={handleViewProfile} onGoToAdmin={handleGoToAdmin} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<Button variant="ghost" onClick={previousStep} disabled={currentIndex <= 0}>
|
||||
<Button variant="ghost" onClick={handlePrevious} disabled={currentIndex <= 0}>
|
||||
{t('checkout.back')}
|
||||
</Button>
|
||||
<Button onClick={nextStep} disabled={currentIndex >= stepConfig.length - 1}>
|
||||
<Button onClick={handleNext} disabled={currentIndex >= stepConfig.length - 1}>
|
||||
{t('checkout.next')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { usePage } from "@inertiajs/react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
@@ -6,17 +6,52 @@ import { useCheckoutWizard } from "../WizardContext";
|
||||
import LoginForm, { AuthUserPayload } from "../../../auth/LoginForm";
|
||||
import RegisterForm, { RegisterSuccessPayload } from "../../../auth/RegisterForm";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import toast from 'react-hot-toast';
|
||||
import { LoaderCircle } from "lucide-react";
|
||||
|
||||
interface AuthStepProps {
|
||||
privacyHtml: string;
|
||||
}
|
||||
|
||||
type GoogleAuthFlash = {
|
||||
status?: string | null;
|
||||
error?: string | null;
|
||||
};
|
||||
|
||||
const GoogleIcon: React.FC<{ className?: string }> = ({ className }) => (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<path fill="#EA4335" d="M12 11.999v4.8h6.7c-.3 1.7-2 4.9-6.7 4.9-4 0-7.4-3.3-7.4-7.4S8 6 12 6c2.3 0 3.9 1 4.8 1.9l3.3-3.2C18.1 2.6 15.3 1 12 1 5.9 1 1 5.9 1 12s4.9 11 11 11c6.3 0 10.5-4.4 10.5-10.6 0-.7-.1-1.2-.2-1.8H12z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const page = usePage<{ locale?: string }>();
|
||||
const locale = page.props.locale ?? "de";
|
||||
const googleAuth = useMemo<GoogleAuthFlash>(() => {
|
||||
const props = page.props as Record<string, any>;
|
||||
return props.googleAuth ?? {};
|
||||
}, [page.props]);
|
||||
const { isAuthenticated, authUser, setAuthUser, nextStep, selectedPackage } = useCheckoutWizard();
|
||||
const [mode, setMode] = useState<'login' | 'register'>('register');
|
||||
const [isRedirectingToGoogle, setIsRedirectingToGoogle] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.status === 'success') {
|
||||
toast.success(t('checkout.auth_step.google_success_toast'));
|
||||
}
|
||||
}, [googleAuth?.status, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (googleAuth?.error) {
|
||||
toast.error(googleAuth.error);
|
||||
}
|
||||
}, [googleAuth?.error]);
|
||||
|
||||
const handleLoginSuccess = (payload: AuthUserPayload | null) => {
|
||||
if (!payload) {
|
||||
@@ -46,6 +81,20 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
nextStep();
|
||||
};
|
||||
|
||||
const handleGoogleLogin = useCallback(() => {
|
||||
if (!selectedPackage) {
|
||||
toast.error(t('checkout.auth_step.google_missing_package'));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRedirectingToGoogle(true);
|
||||
const params = new URLSearchParams({
|
||||
package_id: String(selectedPackage.id),
|
||||
locale,
|
||||
});
|
||||
window.location.href = `/checkout/auth/google?${params.toString()}`;
|
||||
}, [locale, selectedPackage, t]);
|
||||
|
||||
if (isAuthenticated && authUser) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -79,11 +128,28 @@ export const AuthStep: React.FC<AuthStepProps> = ({ privacyHtml }) => {
|
||||
>
|
||||
{t('checkout.auth_step.switch_to_login')}
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t('checkout.auth_step.google_coming_soon')}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleGoogleLogin}
|
||||
disabled={isRedirectingToGoogle}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
{isRedirectingToGoogle ? (
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<GoogleIcon className="h-4 w-4" />
|
||||
)}
|
||||
{t('checkout.auth_step.continue_with_google')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{googleAuth?.error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>{t('checkout.auth_step.google_error_title')}</AlertTitle>
|
||||
<AlertDescription>{googleAuth.error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
{mode === 'register' ? (
|
||||
selectedPackage && (
|
||||
|
||||
@@ -6,11 +6,27 @@ import { useTranslation } from 'react-i18next';
|
||||
|
||||
interface ConfirmationStepProps {
|
||||
onViewProfile?: () => void;
|
||||
onGoToAdmin?: () => void;
|
||||
}
|
||||
|
||||
export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfile }) => {
|
||||
export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfile, onGoToAdmin }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage } = useCheckoutWizard();
|
||||
const handleProfile = React.useCallback(() => {
|
||||
if (typeof onViewProfile === 'function') {
|
||||
onViewProfile();
|
||||
return;
|
||||
}
|
||||
window.location.href = '/settings/profile';
|
||||
}, [onViewProfile]);
|
||||
|
||||
const handleAdmin = React.useCallback(() => {
|
||||
if (typeof onGoToAdmin === 'function') {
|
||||
onGoToAdmin();
|
||||
return;
|
||||
}
|
||||
window.location.href = '/event-admin';
|
||||
}, [onGoToAdmin]);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -22,10 +38,10 @@ export const ConfirmationStep: React.FC<ConfirmationStepProps> = ({ onViewProfil
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex flex-wrap gap-3 justify-end">
|
||||
<Button variant="outline" onClick={onViewProfile}>
|
||||
<Button variant="outline" onClick={handleProfile}>
|
||||
{t('checkout.confirmation_step.open_profile')}
|
||||
</Button>
|
||||
<Button>{t('checkout.confirmation_step.to_admin')}</Button>
|
||||
<Button onClick={handleAdmin}>{t('checkout.confirmation_step.to_admin')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Check, Package as PackageIcon, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
@@ -13,14 +14,19 @@ const currencyFormatter = new Intl.NumberFormat("de-DE", {
|
||||
minimumFractionDigits: 2,
|
||||
});
|
||||
|
||||
function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
function translateFeature(feature: string, t: TFunction<'marketing'>) {
|
||||
const fallback = feature.replace(/_/g, ' ');
|
||||
return t(`packages.feature_${feature}`, { defaultValue: fallback });
|
||||
}
|
||||
|
||||
function PackageSummary({ pkg, t }: { pkg: CheckoutPackage; t: TFunction<'marketing'> }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
<Card className={`shadow-sm ${isFree ? "opacity-75" : ""}`}>
|
||||
<Card className={`shadow-sm ${isFree ? 'opacity-75' : ''}`}>
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className={`flex items-center gap-3 text-2xl ${isFree ? "text-muted-foreground" : ""}`}>
|
||||
<PackageIcon className={`h-6 w-6 ${isFree ? "text-muted-foreground" : "text-primary"}`} />
|
||||
<CardTitle className={`flex items-center gap-3 text-2xl ${isFree ? 'text-muted-foreground' : ''}`}>
|
||||
<PackageIcon className={`h-6 w-6 ${isFree ? 'text-muted-foreground' : 'text-primary'}`} />
|
||||
{pkg.name}
|
||||
</CardTitle>
|
||||
<CardDescription className="text-base text-muted-foreground">
|
||||
@@ -29,19 +35,41 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className={`text-3xl font-semibold ${isFree ? "text-muted-foreground" : ""}`}>
|
||||
{pkg.price === 0 ? "Kostenlos" : currencyFormatter.format(pkg.price)}
|
||||
<span className={`text-3xl font-semibold ${isFree ? 'text-muted-foreground' : ''}`}>
|
||||
{pkg.price === 0 ? t('packages.free') : currencyFormatter.format(pkg.price)}
|
||||
</span>
|
||||
<Badge variant={isFree ? "outline" : "secondary"} className="uppercase tracking-wider text-xs">
|
||||
{pkg.type === "reseller" ? "Reseller" : "Endkunde"}
|
||||
<Badge variant={isFree ? 'outline' : 'secondary'} className="uppercase tracking-wider text-xs">
|
||||
{pkg.type === 'reseller' ? t('packages.subscription') : t('packages.one_time')}
|
||||
</Badge>
|
||||
</div>
|
||||
{pkg.gallery_duration_label && (
|
||||
<div className="rounded-md border border-dashed border-muted px-3 py-2 text-sm text-muted-foreground">
|
||||
{t('packages.gallery_days_label')}: {pkg.gallery_duration_label}
|
||||
</div>
|
||||
)}
|
||||
{Array.isArray(pkg.description_breakdown) && pkg.description_breakdown.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{t('packages.breakdown_label')}
|
||||
</h4>
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{pkg.description_breakdown.map((row, index) => (
|
||||
<div key={index} className="rounded-lg border border-muted/40 bg-muted/20 px-3 py-2">
|
||||
{row.title && (
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{row.title}</p>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">{row.value}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{Array.isArray(pkg.features) && pkg.features.length > 0 && (
|
||||
<ul className="space-y-3">
|
||||
{pkg.features.map((feature, index) => (
|
||||
<li key={index} className="flex items-start gap-3 text-sm text-muted-foreground">
|
||||
<Check className={`mt-0.5 h-4 w-4 ${isFree ? "text-muted-foreground" : "text-primary"}`} />
|
||||
<span>{feature}</span>
|
||||
<Check className={`mt-0.5 h-4 w-4 ${isFree ? 'text-muted-foreground' : 'text-primary'}`} />
|
||||
<span>{translateFeature(feature, t)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -51,7 +79,7 @@ function PackageSummary({ pkg }: { pkg: CheckoutPackage }) {
|
||||
);
|
||||
}
|
||||
|
||||
function PackageOption({ pkg, isActive, onSelect }: { pkg: CheckoutPackage; isActive: boolean; onSelect: () => void }) {
|
||||
function PackageOption({ pkg, isActive, onSelect, t }: { pkg: CheckoutPackage; isActive: boolean; onSelect: () => void; t: TFunction<'marketing'> }) {
|
||||
const isFree = pkg.price === 0;
|
||||
|
||||
return (
|
||||
@@ -69,7 +97,7 @@ function PackageOption({ pkg, isActive, onSelect }: { pkg: CheckoutPackage; isAc
|
||||
<div className="flex items-center justify-between text-sm font-medium">
|
||||
<span className={isFree ? "text-muted-foreground" : ""}>{pkg.name}</span>
|
||||
<span className={isFree ? "text-muted-foreground font-normal" : "text-muted-foreground"}>
|
||||
{pkg.price === 0 ? "Kostenlos" : currencyFormatter.format(pkg.price)}
|
||||
{pkg.price === 0 ? t('packages.free') : currencyFormatter.format(pkg.price)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-1 line-clamp-2 text-xs text-muted-foreground">{pkg.description}</p>
|
||||
@@ -125,7 +153,7 @@ export const PackageStep: React.FC = () => {
|
||||
return (
|
||||
<div className="grid gap-8 lg:grid-cols-[2fr_1fr]">
|
||||
<div className="space-y-6">
|
||||
<PackageSummary pkg={selectedPackage} />
|
||||
<PackageSummary pkg={selectedPackage} t={t} />
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={handleNextStep} disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
@@ -150,6 +178,7 @@ export const PackageStep: React.FC = () => {
|
||||
pkg={pkg}
|
||||
isActive={pkg.id === selectedPackage.id}
|
||||
onSelect={() => handlePackageChange(pkg)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
{comparablePackages.length === 0 && (
|
||||
|
||||
@@ -1,35 +1,47 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useStripe, useElements, PaymentElement, Elements } from '@stripe/react-stripe-js';
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { useCheckoutWizard } from "../WizardContext";
|
||||
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';
|
||||
|
||||
interface PaymentStepProps {
|
||||
stripePublishableKey: string;
|
||||
paypalClientId: string;
|
||||
}
|
||||
|
||||
// Komponente für Stripe-Zahlungen
|
||||
const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess: () => void; selectedPackage: any; t: any }> = ({ onError, onSuccess, selectedPackage, t }) => {
|
||||
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 [error, setError] = useState<string>('');
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent) => {
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!stripe || !elements) {
|
||||
onError(t('checkout.payment_step.stripe_not_loaded'));
|
||||
const message = t('checkout.payment_step.stripe_not_loaded');
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
onProcessing();
|
||||
setIsProcessing(true);
|
||||
setError('');
|
||||
setErrorMessage('');
|
||||
|
||||
try {
|
||||
const { error: stripeError, paymentIntent } = await stripe.confirmPayment({
|
||||
@@ -41,38 +53,41 @@ const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
});
|
||||
|
||||
if (stripeError) {
|
||||
console.error('Stripe Payment Error:', stripeError);
|
||||
let errorMessage = t('checkout.payment_step.payment_failed');
|
||||
let message = t('checkout.payment_step.payment_failed');
|
||||
|
||||
switch (stripeError.type) {
|
||||
case 'card_error':
|
||||
errorMessage += stripeError.message || t('checkout.payment_step.error_card');
|
||||
message += stripeError.message || t('checkout.payment_step.error_card');
|
||||
break;
|
||||
case 'validation_error':
|
||||
errorMessage += t('checkout.payment_step.error_validation');
|
||||
message += t('checkout.payment_step.error_validation');
|
||||
break;
|
||||
case 'api_connection_error':
|
||||
errorMessage += t('checkout.payment_step.error_connection');
|
||||
message += t('checkout.payment_step.error_connection');
|
||||
break;
|
||||
case 'api_error':
|
||||
errorMessage += t('checkout.payment_step.error_server');
|
||||
message += t('checkout.payment_step.error_server');
|
||||
break;
|
||||
case 'authentication_error':
|
||||
errorMessage += t('checkout.payment_step.error_auth');
|
||||
message += t('checkout.payment_step.error_auth');
|
||||
break;
|
||||
default:
|
||||
errorMessage += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
message += stripeError.message || t('checkout.payment_step.error_unknown');
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
onError(errorMessage);
|
||||
} else if (paymentIntent && paymentIntent.status === 'succeeded') {
|
||||
onSuccess();
|
||||
} else if (paymentIntent) {
|
||||
onError(t('checkout.payment_step.unexpected_status', { status: paymentIntent.status }));
|
||||
setErrorMessage(message);
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Unexpected payment error:', err);
|
||||
|
||||
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);
|
||||
@@ -81,56 +96,83 @@ const StripePaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{error && (
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
<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>
|
||||
<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 ? t('checkout.payment_step.processing_btn') : t('checkout.payment_step.pay_now', { price: selectedPackage?.price || 0 })}
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
// Komponente für PayPal-Zahlungen
|
||||
const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess: () => void; selectedPackage: any; t: any; authUser: any; paypalClientId: string }> = ({ onError, onSuccess, selectedPackage, t, authUser, paypalClientId }) => {
|
||||
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 {
|
||||
const response = await fetch('/paypal/create-order', {
|
||||
onProcessing();
|
||||
|
||||
const endpoint = isReseller ? '/paypal/create-subscription' : '/paypal/create-order';
|
||||
const payload: Record<string, unknown> = {
|
||||
package_id: selectedPackage.id,
|
||||
};
|
||||
|
||||
if (isReseller) {
|
||||
if (!paypalPlanId) {
|
||||
const message = t('checkout.payment_step.paypal_missing_plan');
|
||||
onError(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
payload.plan_id = paypalPlanId;
|
||||
}
|
||||
|
||||
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({
|
||||
tenant_id: authUser?.tenant_id || authUser?.id, // Annahme: tenant_id verfügbar
|
||||
package_id: selectedPackage?.id,
|
||||
}),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.id) {
|
||||
return data.id;
|
||||
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'));
|
||||
throw new Error('Failed to create order');
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
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 err;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -142,9 +184,7 @@ const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
order_id: data.orderID,
|
||||
}),
|
||||
body: JSON.stringify({ order_id: data.orderID }),
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
@@ -154,105 +194,209 @@ const PayPalPaymentForm: React.FC<{ onError: (error: string) => void; onSuccess:
|
||||
} else {
|
||||
onError(result.error || t('checkout.payment_step.paypal_capture_error'));
|
||||
}
|
||||
} catch (err) {
|
||||
} catch (error) {
|
||||
console.error('PayPal capture failed', error);
|
||||
onError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
|
||||
const onErrorHandler = (error: any) => {
|
||||
console.error('PayPal Error:', error);
|
||||
const handleError = (error: unknown) => {
|
||||
console.error('PayPal error', error);
|
||||
onError(t('checkout.payment_step.paypal_error'));
|
||||
};
|
||||
|
||||
const onCancel = () => {
|
||||
const handleCancel = () => {
|
||||
onError(t('checkout.payment_step.paypal_cancelled'));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<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_paypal_desc') || 'Bezahlen Sie sicher mit PayPal.'}
|
||||
</p>
|
||||
<PayPalButtons
|
||||
style={{ layout: 'vertical' }}
|
||||
createOrder={createOrder}
|
||||
onApprove={onApprove}
|
||||
onError={onErrorHandler}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
</div>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
// Wrapper-Komponente
|
||||
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 }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const { selectedPackage, authUser, nextStep, resetPaymentState } = useCheckoutWizard();
|
||||
const [clientSecret, setClientSecret] = useState<string>('');
|
||||
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'paypal'>('stripe');
|
||||
const [error, setError] = useState<string>('');
|
||||
const [isFree, setIsFree] = useState(false);
|
||||
|
||||
const [paymentMethod, setPaymentMethod] = useState<Provider>('stripe');
|
||||
const [clientSecret, setClientSecret] = useState('');
|
||||
const [status, setStatus] = useState<PaymentStatus>('idle');
|
||||
const [statusDetail, setStatusDetail] = useState<string>('');
|
||||
const [intentRefreshKey, setIntentRefreshKey] = useState(0);
|
||||
const [processingProvider, setProcessingProvider] = useState<Provider | null>(null);
|
||||
|
||||
const stripePromise = useMemo(() => loadStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
const isFree = useMemo(() => (selectedPackage ? selectedPackage.price <= 0 : false), [selectedPackage]);
|
||||
const isReseller = selectedPackage?.type === 'reseller';
|
||||
|
||||
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(() => {
|
||||
const free = selectedPackage ? selectedPackage.price <= 0 : false;
|
||||
setIsFree(free);
|
||||
if (free) {
|
||||
setStatus('idle');
|
||||
setStatusDetail('');
|
||||
setClientSecret('');
|
||||
setProcessingProvider(null);
|
||||
}, [selectedPackage?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isFree) {
|
||||
resetPaymentState();
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
return;
|
||||
}
|
||||
|
||||
if (paymentMethod === 'stripe' && authUser && selectedPackage) {
|
||||
const loadPaymentIntent = 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,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.client_secret) {
|
||||
setClientSecret(data.client_secret);
|
||||
setError('');
|
||||
} else {
|
||||
setError(data.error || t('checkout.payment_step.payment_intent_error'));
|
||||
}
|
||||
} catch (err) {
|
||||
setError(t('checkout.payment_step.network_error'));
|
||||
}
|
||||
};
|
||||
|
||||
loadPaymentIntent();
|
||||
} else {
|
||||
setClientSecret('');
|
||||
if (!selectedPackage) {
|
||||
return;
|
||||
}
|
||||
}, [selectedPackage?.id, authUser, paymentMethod, isFree, t, resetPaymentState]);
|
||||
|
||||
const handlePaymentError = (errorMsg: string) => {
|
||||
setError(errorMsg);
|
||||
if (paymentMethod === 'paypal') {
|
||||
if (paypalDisabled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.paypal_missing_plan'));
|
||||
} else {
|
||||
setStatus('ready');
|
||||
setStatusDetail('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!authUser) {
|
||||
setStatus('error');
|
||||
setStatusDetail(t('checkout.payment_step.auth_required'));
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
setStatus('loading');
|
||||
setStatusDetail(t('checkout.payment_step.status_loading'));
|
||||
setClientSecret('');
|
||||
|
||||
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 }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.client_secret) {
|
||||
const message = data.error || t('checkout.payment_step.payment_intent_error');
|
||||
if (!cancelled) {
|
||||
setStatus('error');
|
||||
setStatusDetail(message);
|
||||
}
|
||||
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'));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadIntent();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [authUser, intentRefreshKey, isFree, paymentMethod, paypalDisabled, resetPaymentState, selectedPackage, t]);
|
||||
|
||||
const providerLabel = useCallback((provider: Provider) => {
|
||||
switch (provider) {
|
||||
case 'paypal':
|
||||
return 'PayPal';
|
||||
default:
|
||||
return 'Stripe';
|
||||
}
|
||||
}, []);
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
const handlePaymentSuccess = () => {
|
||||
setTimeout(() => nextStep(), 1000);
|
||||
};
|
||||
|
||||
// Für kostenlose Pakete
|
||||
if (isFree) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Alert>
|
||||
<AlertTitle>{t('checkout.payment_step.free_package_title')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
{t('checkout.payment_step.free_package_desc')}
|
||||
</AlertDescription>
|
||||
<AlertDescription>{t('checkout.payment_step.free_package_desc')}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button size="lg" onClick={nextStep}>
|
||||
@@ -263,78 +407,93 @@ export const PaymentStep: React.FC<PaymentStepProps> = ({ stripePublishableKey,
|
||||
);
|
||||
}
|
||||
|
||||
// Fehler anzeigen
|
||||
if (error && !clientSecret) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
<div className="flex justify-end">
|
||||
<Button onClick={() => setError('')}>Versuchen Sie es erneut</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const renderStatusAlert = () => {
|
||||
if (status === 'idle') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stripePromise = loadStripe(stripePublishableKey);
|
||||
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">
|
||||
{/* Zahlungsmethode Auswahl */}
|
||||
<div className="flex space-x-4">
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
variant={paymentMethod === 'stripe' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('stripe')}
|
||||
className="flex-1"
|
||||
disabled={paymentMethod === 'stripe'}
|
||||
>
|
||||
Kreditkarte (Stripe)
|
||||
{t('checkout.payment_step.method_stripe')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={paymentMethod === 'paypal' ? 'default' : 'outline'}
|
||||
onClick={() => setPaymentMethod('paypal')}
|
||||
className="flex-1"
|
||||
disabled={paypalDisabled || paymentMethod === 'paypal'}
|
||||
>
|
||||
PayPal
|
||||
{t('checkout.payment_step.method_paypal')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{renderStatusAlert()}
|
||||
|
||||
{paymentMethod === 'stripe' && (
|
||||
{paymentMethod === 'stripe' && clientSecret && (
|
||||
<Elements stripe={stripePromise} options={{ clientSecret }}>
|
||||
<StripePaymentForm
|
||||
onError={handlePaymentError}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
selectedPackage={selectedPackage}
|
||||
onProcessing={() => handleProcessing('stripe')}
|
||||
onSuccess={() => handleSuccess('stripe')}
|
||||
onError={(message) => handleError('stripe', message)}
|
||||
t={t}
|
||||
/>
|
||||
</Elements>
|
||||
)}
|
||||
|
||||
{paymentMethod === 'paypal' && (
|
||||
{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
|
||||
onError={handlePaymentError}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
isReseller={Boolean(isReseller)}
|
||||
onProcessing={() => handleProcessing('paypal')}
|
||||
onSuccess={() => handleSuccess('paypal')}
|
||||
onError={(message) => handleError('paypal', message)}
|
||||
paypalPlanId={paypalPlanId}
|
||||
selectedPackage={selectedPackage}
|
||||
t={t}
|
||||
authUser={authUser}
|
||||
paypalClientId={paypalClientId}
|
||||
/>
|
||||
</PayPalScriptProvider>
|
||||
)}
|
||||
|
||||
{!clientSecret && paymentMethod === 'stripe' && (
|
||||
<div className="rounded-lg border bg-card p-6 shadow-sm">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('checkout.payment_step.loading_payment')}
|
||||
</p>
|
||||
</div>
|
||||
{paymentMethod === 'paypal' && paypalDisabled && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{t('checkout.payment_step.paypal_missing_plan')}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,10 +5,17 @@ export interface CheckoutPackage {
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
description_breakdown?: Array<{
|
||||
title?: string | null;
|
||||
value: string;
|
||||
}>;
|
||||
gallery_duration_label?: string | null;
|
||||
events?: number | null;
|
||||
currency?: string;
|
||||
type: 'endcustomer' | 'reseller';
|
||||
features: string[];
|
||||
limits?: Record<string, unknown>;
|
||||
paypal_plan_id?: string | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -37,4 +44,3 @@ export interface CheckoutWizardContextValue extends CheckoutWizardState {
|
||||
resetPaymentState: () => void;
|
||||
cancelCheckout: () => void;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user