verpfuschter stand von codex
This commit is contained in:
203
resources/js/pages/auth/LoginForm.tsx
Normal file
203
resources/js/pages/auth/LoginForm.tsx
Normal file
@@ -0,0 +1,203 @@
|
||||
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import InputError from '@/components/input-error';
|
||||
import TextLink from '@/components/text-link';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSuccess?: (payload: any) => void;
|
||||
canResetPassword?: boolean;
|
||||
}
|
||||
|
||||
const getCsrfToken = () =>
|
||||
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||
|
||||
const parseJson = async (response: Response) => {
|
||||
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||
const json = await response.json().catch(() => null);
|
||||
if (json) return json;
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
throw new Error(text || 'Invalid server response (unexpected end of data or non-JSON).');
|
||||
};
|
||||
|
||||
export default function LoginForm({ onSuccess, canResetPassword = true }: LoginFormProps) {
|
||||
const { t } = useTranslation('auth');
|
||||
const csrfToken = useMemo(getCsrfToken, []);
|
||||
|
||||
const { data, setData, errors, setError, clearErrors, reset } = useForm({
|
||||
login: '',
|
||||
password: '',
|
||||
remember: false,
|
||||
});
|
||||
|
||||
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setHasTriedSubmit(true);
|
||||
setSubmitting(true);
|
||||
setFormError(null);
|
||||
clearErrors();
|
||||
|
||||
try {
|
||||
const response = await fetch('/purchase/auth/login', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-CSRF-TOKEN': csrfToken,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
login: data.login,
|
||||
password: data.password,
|
||||
remember: data.remember,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const payload = await parseJson(response);
|
||||
reset({ login: payload?.user?.email ?? data.login, password: '', remember: false });
|
||||
setHasTriedSubmit(false);
|
||||
if (onSuccess) {
|
||||
onSuccess(payload);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 422) {
|
||||
const body = await parseJson(response);
|
||||
const validationErrors = body.errors ?? {};
|
||||
let fallbackMessage: string | null = body.message ?? null;
|
||||
|
||||
Object.entries(validationErrors as Record<string, string | string[]>).forEach(([key, value]) => {
|
||||
const message = Array.isArray(value) ? value[0] : value;
|
||||
if (typeof message === 'string') {
|
||||
setError(key as keyof typeof data, message);
|
||||
if (!fallbackMessage) {
|
||||
fallbackMessage = message;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (fallbackMessage) {
|
||||
setFormError(fallbackMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setFormError(t('login.generic_error', { defaultValue: 'Login failed. Please try again.' }));
|
||||
} catch (error) {
|
||||
setFormError(t('login.generic_error', { defaultValue: 'Login failed. Please try again.' }));
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasTriedSubmit) {
|
||||
return;
|
||||
}
|
||||
|
||||
const errorKeys = Object.keys(errors);
|
||||
if (errorKeys.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const field = document.querySelector<HTMLInputElement>(`[name="${errorKeys[0]}"]`);
|
||||
|
||||
if (field) {
|
||||
field.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
field.focus();
|
||||
}
|
||||
}, [errors, hasTriedSubmit]);
|
||||
|
||||
return (
|
||||
<form className="flex flex-col gap-6" onSubmit={handleSubmit} noValidate>
|
||||
<div className="grid gap-6">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="login">{t('login.email')}</Label>
|
||||
<Input
|
||||
id="login"
|
||||
type="text"
|
||||
name="login"
|
||||
autoComplete="username"
|
||||
required
|
||||
autoFocus
|
||||
placeholder={t('login.email_placeholder')}
|
||||
value={data.login}
|
||||
onChange={(event) => {
|
||||
setData('login', event.target.value);
|
||||
if (errors.login) {
|
||||
clearErrors('login');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<InputError message={errors.login} />
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<div className="flex items-center">
|
||||
<Label htmlFor="password">{t('login.password')}</Label>
|
||||
{canResetPassword && (
|
||||
<TextLink href="/forgot-password" className="ml-auto text-sm">
|
||||
{t('login.forgot')}
|
||||
</TextLink>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
name="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
placeholder={t('login.password_placeholder')}
|
||||
value={data.password}
|
||||
onChange={(event) => {
|
||||
setData('password', event.target.value);
|
||||
if (errors.password) {
|
||||
clearErrors('password');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<InputError message={errors.password} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
<Checkbox
|
||||
id="remember"
|
||||
name="remember"
|
||||
checked={data.remember}
|
||||
onCheckedChange={(checked) => setData('remember', Boolean(checked))}
|
||||
/>
|
||||
<Label htmlFor="remember">{t('login.remember')}</Label>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting && <LoaderCircle className="h-4 w-4 animate-spin mr-2" />}
|
||||
{t('login.submit')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{(formError || Object.keys(errors).length > 0) && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{formError || Object.values(errors).join(' ')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
412
resources/js/pages/auth/RegisterForm.tsx
Normal file
412
resources/js/pages/auth/RegisterForm.tsx
Normal file
@@ -0,0 +1,412 @@
|
||||
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LoaderCircle, User, Mail, Phone, Lock, MapPin } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
interface RegisterFormProps {
|
||||
packageId?: number;
|
||||
onSuccess?: (payload: any) => void;
|
||||
privacyHtml: string;
|
||||
}
|
||||
|
||||
const getCsrfToken = () =>
|
||||
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||
|
||||
export default function RegisterForm({ packageId, onSuccess, privacyHtml }: RegisterFormProps) {
|
||||
const { t } = useTranslation(['auth', 'common']);
|
||||
const csrfToken = useMemo(getCsrfToken, []);
|
||||
|
||||
const { data, setData, errors, setError, clearErrors, reset } = useForm({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
password_confirmation: '',
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
address: '',
|
||||
phone: '',
|
||||
privacy_consent: false,
|
||||
package_id: packageId ?? null,
|
||||
});
|
||||
|
||||
const [privacyOpen, setPrivacyOpen] = useState(false);
|
||||
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setData('package_id', packageId ?? null);
|
||||
}, [packageId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasTriedSubmit) {
|
||||
return;
|
||||
}
|
||||
|
||||
const errorKeys = Object.keys(errors);
|
||||
if (errorKeys.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const firstError = errorKeys[0];
|
||||
const field = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(`[name="${firstError}"]`);
|
||||
|
||||
if (field) {
|
||||
field.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
field.focus();
|
||||
}
|
||||
}, [errors, hasTriedSubmit]);
|
||||
|
||||
const parseJson = async (response: Response) => {
|
||||
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||
const json = await response.json().catch(() => null);
|
||||
if (json) return json;
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
throw new Error(text || 'Invalid server response (unexpected end of data or non-JSON).');
|
||||
};
|
||||
|
||||
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setHasTriedSubmit(true);
|
||||
setSubmitting(true);
|
||||
setFormError(null);
|
||||
clearErrors();
|
||||
|
||||
try {
|
||||
const response = await fetch('/purchase/auth/register', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
'X-CSRF-TOKEN': csrfToken,
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...data,
|
||||
privacy_consent: Boolean(data.privacy_consent),
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const payload = await parseJson(response);
|
||||
reset({
|
||||
username: '',
|
||||
email: '',
|
||||
password: '',
|
||||
password_confirmation: '',
|
||||
first_name: '',
|
||||
last_name: '',
|
||||
address: '',
|
||||
phone: '',
|
||||
privacy_consent: false,
|
||||
package_id: packageId ?? null,
|
||||
});
|
||||
setHasTriedSubmit(false);
|
||||
if (onSuccess) {
|
||||
onSuccess(payload);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 422) {
|
||||
const body = await parseJson(response);
|
||||
const validationErrors = body.errors ?? {};
|
||||
let fallbackMessage: string | null = body.message ?? null;
|
||||
|
||||
Object.entries(validationErrors).forEach(([key, value]) => {
|
||||
const message = Array.isArray(value) ? value[0] : value;
|
||||
if (typeof message === 'string') {
|
||||
setError(key, message);
|
||||
if (!fallbackMessage) {
|
||||
fallbackMessage = message;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (fallbackMessage) {
|
||||
setFormError(fallbackMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setFormError(t('register.generic_error', { defaultValue: 'Registrierung fehlgeschlagen. Bitte versuche es erneut.' }));
|
||||
} catch (error) {
|
||||
const message = (error as Error).message || t('register.generic_error', { defaultValue: 'Registrierung fehlgeschlagen. Bitte versuche es erneut.' });
|
||||
setFormError(message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="space-y-6" onSubmit={submit} noValidate>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="first_name" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.first_name')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="first_name"
|
||||
name="first_name"
|
||||
type="text"
|
||||
required
|
||||
value={data.first_name}
|
||||
onChange={(event) => {
|
||||
setData('first_name', event.target.value);
|
||||
if (errors.first_name) {
|
||||
clearErrors('first_name');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.first_name ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.first_name_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.first_name && <p className="text-sm text-red-600 mt-1">{errors.first_name}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="last_name" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.last_name')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="last_name"
|
||||
name="last_name"
|
||||
type="text"
|
||||
required
|
||||
value={data.last_name}
|
||||
onChange={(event) => {
|
||||
setData('last_name', event.target.value);
|
||||
if (errors.last_name) {
|
||||
clearErrors('last_name');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.last_name ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.last_name_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.last_name && <p className="text-sm text-red-600 mt-1">{errors.last_name}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.email')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
value={data.email}
|
||||
onChange={(event) => {
|
||||
setData('email', event.target.value);
|
||||
if (errors.email) {
|
||||
clearErrors('email');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.email_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.email && <p className="text-sm text-red-600 mt-1">{errors.email}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.username')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
required
|
||||
value={data.username}
|
||||
onChange={(event) => {
|
||||
setData('username', event.target.value);
|
||||
if (errors.username) {
|
||||
clearErrors('username');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.username ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.username_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.username && <p className="text-sm text-red-600 mt-1">{errors.username}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.phone')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Phone className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="phone"
|
||||
name="phone"
|
||||
type="tel"
|
||||
required
|
||||
value={data.phone}
|
||||
onChange={(event) => {
|
||||
setData('phone', event.target.value);
|
||||
if (errors.phone) {
|
||||
clearErrors('phone');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.phone_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.phone && <p className="text-sm text-red-600 mt-1">{errors.phone}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2">
|
||||
<label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.address')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<MapPin className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<textarea
|
||||
id="address"
|
||||
name="address"
|
||||
required
|
||||
value={data.address}
|
||||
onChange={(event) => {
|
||||
setData('address', event.target.value);
|
||||
if (errors.address) {
|
||||
clearErrors('address');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.address ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.address_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.address && <p className="text-sm text-red-600 mt-1">{errors.address}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.password')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
value={data.password}
|
||||
onChange={(event) => {
|
||||
setData('password', event.target.value);
|
||||
if (errors.password) {
|
||||
clearErrors('password');
|
||||
}
|
||||
if (data.password_confirmation && event.target.value === data.password_confirmation) {
|
||||
clearErrors('password_confirmation');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.password ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.password_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.password && <p className="text-sm text-red-600 mt-1">{errors.password}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-1">
|
||||
<label htmlFor="password_confirmation" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
{t('register.confirm_password')} {t('common:required')}
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||
<input
|
||||
id="password_confirmation"
|
||||
name="password_confirmation"
|
||||
type="password"
|
||||
required
|
||||
value={data.password_confirmation}
|
||||
onChange={(event) => {
|
||||
setData('password_confirmation', event.target.value);
|
||||
if (errors.password_confirmation) {
|
||||
clearErrors('password_confirmation');
|
||||
}
|
||||
if (data.password && event.target.value === data.password) {
|
||||
clearErrors('password_confirmation');
|
||||
}
|
||||
}}
|
||||
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.password_confirmation ? 'border-red-500' : 'border-gray-300'}`}
|
||||
placeholder={t('register.confirm_password_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
{errors.password_confirmation && <p className="text-sm text-red-600 mt-1">{errors.password_confirmation}</p>}
|
||||
</div>
|
||||
|
||||
<div className="md:col-span-2 flex items-start">
|
||||
<input
|
||||
id="privacy_consent"
|
||||
name="privacy_consent"
|
||||
type="checkbox"
|
||||
required
|
||||
checked={data.privacy_consent}
|
||||
onChange={(event) => {
|
||||
setData('privacy_consent', event.target.checked);
|
||||
if (event.target.checked && errors.privacy_consent) {
|
||||
clearErrors('privacy_consent');
|
||||
}
|
||||
}}
|
||||
className="h-4 w-4 text-[#FFB6C1] focus:ring-[#FFB6C1] border-gray-300 rounded"
|
||||
/>
|
||||
<label htmlFor="privacy_consent" className="ml-2 block text-sm text-gray-900">
|
||||
{t('register.privacy_consent')}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPrivacyOpen(true)}
|
||||
className="text-[#FFB6C1] hover:underline inline bg-transparent border-none cursor-pointer p-0 font-medium"
|
||||
>
|
||||
{t('register.privacy_policy')}
|
||||
</button>.
|
||||
</label>
|
||||
{errors.privacy_consent && <p className="mt-2 text-sm text-red-600">{errors.privacy_consent}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(formError || Object.keys(errors).length > 0) && (
|
||||
<Alert>
|
||||
{formError && <AlertDescription>{formError}</AlertDescription>}
|
||||
{Object.keys(errors).length > 0 && !formError && (
|
||||
<AlertDescription>{Object.values(errors).join(' ')}</AlertDescription>
|
||||
)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-[#FFB6C1] hover:bg-[#FF69B4] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#FFB6C1] transition duration-300 disabled:opacity-50"
|
||||
>
|
||||
{submitting && <LoaderCircle className="h-4 w-4 animate-spin mr-2" />}
|
||||
{t('register.submit')}
|
||||
</button>
|
||||
|
||||
<Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto p-0">
|
||||
<DialogTitle className="sr-only">Datenschutzerkl<EFBFBD>rung</DialogTitle>
|
||||
<DialogDescription className="sr-only">Lesen Sie unsere Datenschutzerkl<EFBFBD>rung.</DialogDescription>
|
||||
<div className="p-6">
|
||||
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LoaderCircle, User, Mail, Phone, Lock, Home, MapPin } from 'lucide-react';
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
||||
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||
|
||||
interface RegisterProps {
|
||||
package?: {
|
||||
@@ -11,7 +11,7 @@ interface RegisterProps {
|
||||
description: string;
|
||||
price: number;
|
||||
} | null;
|
||||
privacyHtml: string;
|
||||
privacyHtml?: string;
|
||||
}
|
||||
|
||||
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
|
||||
@@ -356,8 +356,14 @@ export default function Register({ package: initialPackage, privacyHtml }: Regis
|
||||
|
||||
<Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto p-0">
|
||||
<DialogTitle className="sr-only">Datenschutzerklärung</DialogTitle>
|
||||
<DialogDescription className="sr-only">Lesen Sie unsere Datenschutzerklärung.</DialogDescription>
|
||||
<div className="p-6">
|
||||
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
||||
{privacyHtml ? (
|
||||
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
||||
) : (
|
||||
<p>Datenschutzerklärung wird geladen...</p>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -489,24 +489,15 @@ const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackag
|
||||
)}
|
||||
</div>
|
||||
<div className="text-center">
|
||||
{auth.user ? (
|
||||
<Link
|
||||
href={`/buy-packages/${selectedPackage.id}`}
|
||||
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
||||
>
|
||||
{t('packages.to_order')}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href={`/register?package_id=${selectedPackage.id}`}
|
||||
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
||||
onClick={() => {
|
||||
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
||||
}}
|
||||
>
|
||||
{t('packages.to_order')}
|
||||
</Link>
|
||||
)}
|
||||
<Link
|
||||
href={`/purchase-wizard/${selectedPackage.id}`}
|
||||
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
||||
onClick={() => {
|
||||
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
||||
}}
|
||||
>
|
||||
{t('packages.to_order')}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
450
resources/js/pages/marketing/PaymentForm.tsx
Normal file
450
resources/js/pages/marketing/PaymentForm.tsx
Normal file
@@ -0,0 +1,450 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Elements, CardElement, useElements, useStripe } from '@stripe/react-stripe-js';
|
||||
import type { Stripe as StripeInstance } from '@stripe/stripe-js';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
|
||||
type StripePromise = Promise<StripeInstance | null>;
|
||||
|
||||
interface PaymentFormProps {
|
||||
packageId: number;
|
||||
packageName: string;
|
||||
price: number;
|
||||
currency?: string;
|
||||
stripePromise: StripePromise;
|
||||
paypalClientId?: string | null;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
paypal?: any;
|
||||
}
|
||||
}
|
||||
|
||||
const formatCurrency = (value: number, currency = 'EUR') =>
|
||||
new Intl.NumberFormat('de-DE', {
|
||||
style: 'currency',
|
||||
currency,
|
||||
}).format(value);
|
||||
|
||||
const getCsrfToken = () =>
|
||||
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||
|
||||
async function postJson<T>(url: string, body: unknown, csrfToken: string): Promise<T> {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'X-CSRF-TOKEN': csrfToken,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
if (!response.ok) {
|
||||
const message = (data as { message?: string; error?: string }).message ?? (data as { message?: string; error?: string }).error ?? 'Request failed.';
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export default function PaymentForm({
|
||||
packageId,
|
||||
packageName,
|
||||
price,
|
||||
currency = 'EUR',
|
||||
stripePromise,
|
||||
paypalClientId,
|
||||
onSuccess,
|
||||
}: PaymentFormProps) {
|
||||
const { t } = useTranslation('marketing');
|
||||
const csrfToken = useMemo(getCsrfToken, []);
|
||||
const [provider, setProvider] = useState<'stripe' | 'paypal'>('stripe');
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [freeStatus, setFreeStatus] = useState<'idle' | 'loading' | 'done' | 'error'>('idle');
|
||||
|
||||
useEffect(() => {
|
||||
setErrorMessage(null);
|
||||
setStatusMessage(null);
|
||||
}, [provider]);
|
||||
|
||||
useEffect(() => {
|
||||
if (price === 0 && freeStatus === 'idle') {
|
||||
const assignFree = async () => {
|
||||
try {
|
||||
setFreeStatus('loading');
|
||||
await postJson<{ status: string }>('/purchase/free', { package_id: packageId }, csrfToken);
|
||||
setFreeStatus('done');
|
||||
setStatusMessage(
|
||||
t('payment.free_assigned', {
|
||||
defaultValue: 'Kostenloses Paket wurde zugewiesen.',
|
||||
package: packageName,
|
||||
})
|
||||
);
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
setFreeStatus('error');
|
||||
setErrorMessage((error as Error).message ?? 'Free package assignment failed.');
|
||||
}
|
||||
};
|
||||
|
||||
assignFree();
|
||||
}
|
||||
}, [csrfToken, freeStatus, onSuccess, packageId, packageName, price, t]);
|
||||
|
||||
if (price === 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('payment.title', { defaultValue: 'Zahlung' })}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{freeStatus === 'loading' && (
|
||||
<div className="flex items-center space-x-2 text-sm text-gray-600">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span>{t('payment.processing_free', { defaultValue: 'Paket wird freigeschaltet <20>' })}</span>
|
||||
</div>
|
||||
)}
|
||||
{statusMessage && (
|
||||
<Alert variant="success">
|
||||
<AlertDescription>{statusMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('payment.title', { defaultValue: 'Zahlung' })}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{t('payment.total_due', { defaultValue: 'Gesamtbetrag' })}</p>
|
||||
<p className="text-lg font-semibold">{formatCurrency(price, currency)}</p>
|
||||
</div>
|
||||
<div className="inline-flex rounded-md shadow-sm" role="group">
|
||||
<Button
|
||||
type="button"
|
||||
variant={provider === 'stripe' ? 'default' : 'outline'}
|
||||
onClick={() => setProvider('stripe')}
|
||||
>
|
||||
Stripe
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant={provider === 'paypal' ? 'default' : 'outline'}
|
||||
onClick={() => setProvider('paypal')}
|
||||
>
|
||||
PayPal
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{provider === 'stripe' ? (
|
||||
<Elements stripe={stripePromise} options={{ appearance: { theme: 'stripe' } }}>
|
||||
<StripeCardForm
|
||||
packageId={packageId}
|
||||
csrfToken={csrfToken}
|
||||
amountLabel={formatCurrency(price, currency)}
|
||||
onSuccess={() => {
|
||||
setStatusMessage(t('payment.success_stripe', { defaultValue: 'Stripe-Zahlung erfolgreich.' }));
|
||||
onSuccess();
|
||||
}}
|
||||
onError={(message) => setErrorMessage(message)}
|
||||
/>
|
||||
</Elements>
|
||||
) : (
|
||||
<PayPalSection
|
||||
packageId={packageId}
|
||||
amount={price}
|
||||
currency={currency}
|
||||
clientId={paypalClientId}
|
||||
csrfToken={csrfToken}
|
||||
onSuccess={() => {
|
||||
setStatusMessage(t('payment.success_paypal', { defaultValue: 'PayPal-Zahlung erfolgreich.' }));
|
||||
onSuccess();
|
||||
}}
|
||||
onError={(message) => setErrorMessage(message)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{statusMessage && (
|
||||
<Alert variant="success">
|
||||
<AlertDescription>{statusMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{errorMessage && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{errorMessage}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
interface StripeCardFormProps {
|
||||
packageId: number;
|
||||
csrfToken: string;
|
||||
amountLabel: string;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
}
|
||||
|
||||
const StripeCardForm: React.FC<StripeCardFormProps> = ({ packageId, csrfToken, amountLabel, onSuccess, onError }) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const stripe = useStripe();
|
||||
const elements = useElements();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [localError, setLocalError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (!stripe || !elements) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cardElement = elements.getElement(CardElement);
|
||||
if (!cardElement) {
|
||||
setLocalError('Card element not found.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSubmitting(true);
|
||||
setLocalError(null);
|
||||
|
||||
const { client_secret: clientSecret, payment_intent_id: paymentIntentId } = await postJson<{
|
||||
client_secret: string;
|
||||
payment_intent_id: string;
|
||||
}>('/purchase/stripe/intent', { package_id: packageId }, csrfToken);
|
||||
|
||||
const confirmation = await stripe.confirmCardPayment(clientSecret, {
|
||||
payment_method: {
|
||||
card: cardElement,
|
||||
},
|
||||
});
|
||||
|
||||
if (confirmation.error) {
|
||||
throw new Error(confirmation.error.message || 'Card confirmation failed.');
|
||||
}
|
||||
|
||||
if (confirmation.paymentIntent?.status !== 'succeeded') {
|
||||
throw new Error('Stripe did not confirm the payment.');
|
||||
}
|
||||
|
||||
await postJson('/purchase/stripe/complete', {
|
||||
package_id: packageId,
|
||||
payment_intent_id: confirmation.paymentIntent.id || paymentIntentId,
|
||||
}, csrfToken);
|
||||
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
const message = (error as Error).message || 'Stripe payment failed.';
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="card-element" className="text-sm font-medium">
|
||||
{t('payment.card_details', { defaultValue: 'Kartendaten' })}
|
||||
</label>
|
||||
<div className="p-3 border border-gray-300 rounded-md">
|
||||
<CardElement
|
||||
options={{
|
||||
hidePostalCode: true,
|
||||
style: {
|
||||
base: {
|
||||
fontSize: '16px',
|
||||
color: '#424770',
|
||||
'::placeholder': {
|
||||
color: '#aab7c4',
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{localError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{localError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={!stripe || isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||
{t('payment.submit', {
|
||||
defaultValue: 'Jetzt bezahlen',
|
||||
price: amountLabel,
|
||||
})}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
|
||||
interface PayPalSectionProps {
|
||||
packageId: number;
|
||||
amount: number;
|
||||
currency: string;
|
||||
clientId?: string | null;
|
||||
csrfToken: string;
|
||||
onSuccess: () => void;
|
||||
onError: (message: string) => void;
|
||||
}
|
||||
|
||||
const PayPalSection: React.FC<PayPalSectionProps> = ({
|
||||
packageId,
|
||||
amount,
|
||||
currency,
|
||||
clientId,
|
||||
csrfToken,
|
||||
onSuccess,
|
||||
onError,
|
||||
}) => {
|
||||
const { t } = useTranslation('marketing');
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const [isSdkReady, setIsSdkReady] = useState(false);
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [localError, setLocalError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!clientId) {
|
||||
const message = t('payment.paypal_missing_key', { defaultValue: 'PayPal ist derzeit nicht konfiguriert.' });
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.paypal) {
|
||||
setIsSdkReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}¤cy=${currency}&intent=capture&components=buttons`;
|
||||
script.async = true;
|
||||
script.onload = () => setIsSdkReady(true);
|
||||
script.onerror = () => {
|
||||
const message = t('payment.paypal_sdk_failed', { defaultValue: 'PayPal-SDK konnte nicht geladen werden.' });
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
};
|
||||
document.body.appendChild(script);
|
||||
|
||||
return () => {
|
||||
script.remove();
|
||||
};
|
||||
}, [clientId, currency, onError, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isSdkReady || !window.paypal || !containerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const buttons = window.paypal.Buttons({
|
||||
style: {
|
||||
layout: 'vertical',
|
||||
color: 'gold',
|
||||
shape: 'rect',
|
||||
},
|
||||
createOrder: async () => {
|
||||
try {
|
||||
setIsProcessing(true);
|
||||
const { order_id: orderId } = await postJson<{ order_id: string }>('/purchase/paypal/order', {
|
||||
package_id: packageId,
|
||||
}, csrfToken);
|
||||
return orderId;
|
||||
} catch (error) {
|
||||
const message = (error as Error).message || 'PayPal order creation failed.';
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
setIsProcessing(false);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
onApprove: async (data: { orderID: string }) => {
|
||||
try {
|
||||
await postJson('/purchase/paypal/capture', {
|
||||
order_id: data.orderID,
|
||||
package_id: packageId,
|
||||
}, csrfToken);
|
||||
setIsProcessing(false);
|
||||
setLocalError(null);
|
||||
onSuccess();
|
||||
} catch (error) {
|
||||
const message = (error as Error).message || 'PayPal capture failed.';
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
setIsProcessing(false);
|
||||
}
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
const message = error?.message || 'PayPal payment failed.';
|
||||
setLocalError(message);
|
||||
onError(message);
|
||||
setIsProcessing(false);
|
||||
},
|
||||
});
|
||||
|
||||
buttons.render(containerRef.current);
|
||||
|
||||
return () => {
|
||||
try {
|
||||
buttons.close();
|
||||
} catch (error) {
|
||||
// ignore close errors
|
||||
}
|
||||
};
|
||||
}, [csrfToken, isSdkReady, onError, onSuccess, packageId]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div ref={containerRef} />
|
||||
{isProcessing && (
|
||||
<div className="flex items-center space-x-2 text-sm text-gray-600">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span>{t('payment.processing_paypal', { defaultValue: 'PayPal-Zahlung wird verarbeitet <20>' })}</span>
|
||||
</div>
|
||||
)}
|
||||
{localError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{localError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<p className="text-xs text-gray-500">
|
||||
{t('payment.paypal_hint', {
|
||||
defaultValue: 'Der Betrag von {{amount}} wird bei PayPal angezeigt.',
|
||||
amount: formatCurrency(amount, currency),
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
297
resources/js/pages/marketing/PurchaseWizard.tsx
Normal file
297
resources/js/pages/marketing/PurchaseWizard.tsx
Normal file
@@ -0,0 +1,297 @@
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Head, usePage } from '@inertiajs/react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
import { Steps } from '@/components/ui/steps';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
|
||||
import RegisterForm from '../auth/RegisterForm';
|
||||
import LoginForm from '../auth/LoginForm';
|
||||
import PaymentForm from './PaymentForm';
|
||||
import SuccessStep from './SuccessStep';
|
||||
|
||||
interface Package {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
features: string[];
|
||||
}
|
||||
|
||||
interface PurchaseWizardProps {
|
||||
package: Package;
|
||||
stripePublishableKey: string;
|
||||
paypalClientId?: string | null;
|
||||
privacyHtml: string;
|
||||
}
|
||||
|
||||
type StepId = 'package' | 'auth' | 'payment' | 'success';
|
||||
|
||||
interface WizardUser {
|
||||
id: number;
|
||||
email: string;
|
||||
name?: string;
|
||||
pending_purchase?: boolean;
|
||||
email_verified?: boolean;
|
||||
}
|
||||
|
||||
interface AuthSuccessPayload {
|
||||
status: 'authenticated' | 'registered';
|
||||
user?: WizardUser;
|
||||
next_step?: StepId | 'verification';
|
||||
needs_verification?: boolean;
|
||||
package?: {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
type: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
const steps: Array<{ id: StepId; title: string; description: string }> = [
|
||||
{ id: 'package', title: 'Paket ausw<73>hlen', description: 'Best<73>tigen Sie Ihr gew<65>hltes Paket' },
|
||||
{ id: 'auth', title: 'Anmelden oder Registrieren', description: 'Erstellen oder melden Sie sich an' },
|
||||
{ id: 'payment', title: 'Zahlung', description: 'Sichern Sie Ihr Paket ab' },
|
||||
{ id: 'success', title: 'Erfolg', description: 'Willkommen!' },
|
||||
];
|
||||
|
||||
export default function PurchaseWizard({
|
||||
package: initialPackage,
|
||||
stripePublishableKey,
|
||||
paypalClientId,
|
||||
privacyHtml,
|
||||
}: PurchaseWizardProps) {
|
||||
const { t } = useTranslation(['marketing', 'auth']);
|
||||
const { props } = usePage();
|
||||
const serverUser = (props as any)?.auth?.user ?? null;
|
||||
|
||||
const [currentStepIndex, setCurrentStepIndex] = useState(0);
|
||||
const [authType, setAuthType] = useState<'register' | 'login'>('register');
|
||||
const [wizardUser, setWizardUser] = useState<WizardUser | null>(serverUser);
|
||||
const [authNotice, setAuthNotice] = useState<string | null>(null);
|
||||
|
||||
const isAuthenticated = Boolean(wizardUser);
|
||||
|
||||
useEffect(() => {
|
||||
if (serverUser) {
|
||||
setWizardUser(serverUser);
|
||||
}
|
||||
}, [serverUser ? serverUser.id : null]);
|
||||
|
||||
const stripePromise = useMemo(() => loadStripe(stripePublishableKey), [stripePublishableKey]);
|
||||
|
||||
const goToStep = useCallback((stepId: StepId) => {
|
||||
const idx = steps.findIndex((step) => step.id === stepId);
|
||||
if (idx >= 0) {
|
||||
setCurrentStepIndex(idx);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleContinue = useCallback(() => {
|
||||
let nextIndex = Math.min(currentStepIndex + 1, steps.length - 1);
|
||||
if (steps[nextIndex]?.id === 'auth' && isAuthenticated) {
|
||||
nextIndex = Math.min(nextIndex + 1, steps.length - 1);
|
||||
}
|
||||
setCurrentStepIndex(nextIndex);
|
||||
}, [currentStepIndex, isAuthenticated]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
let nextIndex = Math.max(currentStepIndex - 1, 0);
|
||||
if (steps[nextIndex]?.id === 'auth' && isAuthenticated) {
|
||||
nextIndex = Math.max(nextIndex - 1, 0);
|
||||
}
|
||||
setCurrentStepIndex(nextIndex);
|
||||
}, [currentStepIndex, isAuthenticated]);
|
||||
|
||||
const handleAuthSuccess = useCallback(
|
||||
(payload: AuthSuccessPayload) => {
|
||||
if (payload?.user) {
|
||||
setWizardUser(payload.user);
|
||||
}
|
||||
|
||||
if (payload?.needs_verification) {
|
||||
setAuthNotice(t('auth:verify_notice', { defaultValue: 'Bitte best<73>tige deine E-Mail-Adresse, um fortzufahren.' }));
|
||||
} else {
|
||||
setAuthNotice(null);
|
||||
}
|
||||
|
||||
const next = payload?.next_step;
|
||||
if (next === 'success') {
|
||||
goToStep('success');
|
||||
} else {
|
||||
goToStep('payment');
|
||||
}
|
||||
},
|
||||
[goToStep, t],
|
||||
);
|
||||
|
||||
const handlePaymentSuccess = useCallback(() => {
|
||||
goToStep('success');
|
||||
}, [goToStep]);
|
||||
|
||||
const renderPackageStep = () => (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{initialPackage.name}</CardTitle>
|
||||
<CardDescription>{initialPackage.description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p>
|
||||
{t('marketing:payment.price_label', { defaultValue: 'Preis' })}:
|
||||
{' '}
|
||||
{initialPackage.price === 0
|
||||
? t('marketing:payment.free', { defaultValue: 'Kostenlos' })
|
||||
: new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(initialPackage.price)}
|
||||
</p>
|
||||
<ul className="list-disc pl-5 mt-4 space-y-1">
|
||||
{initialPackage.features.map((feature, index) => (
|
||||
<li key={index}>{feature}</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button onClick={handleContinue} className="w-full mt-6">
|
||||
{t('marketing:payment.continue', { defaultValue: 'Weiter' })}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
const renderAuthStep = () => {
|
||||
if (isAuthenticated) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t('auth:already_authenticated', { defaultValue: 'Bereits angemeldet' })}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{t('auth:logged_in_as', {
|
||||
defaultValue: 'Du bist angemeldet als {{email}}.',
|
||||
email: wizardUser?.email ?? wizardUser?.name ?? t('auth:user', { defaultValue: 'aktueller Nutzer' }),
|
||||
})}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
{authNotice && (
|
||||
<Alert>
|
||||
<AlertDescription>{authNotice}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<Button onClick={() => goToStep('payment')} className="w-full">
|
||||
{t('auth:skip_to_payment', { defaultValue: 'Weiter zur Zahlung' })}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-center gap-3">
|
||||
<Button
|
||||
variant={authType === 'register' ? 'default' : 'outline'}
|
||||
onClick={() => {
|
||||
setAuthType('register');
|
||||
setAuthNotice(null);
|
||||
}}
|
||||
>
|
||||
{t('auth:register.title', { defaultValue: 'Registrieren' })}
|
||||
</Button>
|
||||
<Button
|
||||
variant={authType === 'login' ? 'default' : 'outline'}
|
||||
onClick={() => {
|
||||
setAuthType('login');
|
||||
setAuthNotice(null);
|
||||
}}
|
||||
>
|
||||
{t('auth:login.title', { defaultValue: 'Anmelden' })}
|
||||
</Button>
|
||||
</div>
|
||||
{authNotice && (
|
||||
<Alert>
|
||||
<AlertDescription>{authNotice}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{authType === 'register' ? (
|
||||
<RegisterForm
|
||||
packageId={initialPackage.id}
|
||||
privacyHtml={privacyHtml}
|
||||
onSuccess={handleAuthSuccess}
|
||||
/>
|
||||
) : (
|
||||
<LoginForm onSuccess={handleAuthSuccess} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderPaymentStep = () => (
|
||||
<div className="space-y-4">
|
||||
{isAuthenticated && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
{t('marketing:payment.authenticated_notice', {
|
||||
defaultValue: 'Angemeldet als {{email}}. Zahlungsmethode ausw<73>hlen.',
|
||||
email: wizardUser?.email ?? wizardUser?.name ?? t('auth:user', { defaultValue: 'aktueller Nutzer' }),
|
||||
})}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{authNotice && (
|
||||
<Alert>
|
||||
<AlertDescription>{authNotice}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<PaymentForm
|
||||
packageId={initialPackage.id}
|
||||
packageName={initialPackage.name}
|
||||
price={initialPackage.price}
|
||||
currency="EUR"
|
||||
stripePromise={stripePromise}
|
||||
paypalClientId={paypalClientId}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderSuccessStep = () => <SuccessStep package={initialPackage} />;
|
||||
|
||||
const currentStep = steps[currentStepIndex];
|
||||
|
||||
const renderStepContent = () => {
|
||||
switch (currentStep.id) {
|
||||
case 'package':
|
||||
return renderPackageStep();
|
||||
case 'auth':
|
||||
return renderAuthStep();
|
||||
case 'payment':
|
||||
return renderPaymentStep();
|
||||
case 'success':
|
||||
return renderSuccessStep();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<MarketingLayout title={t('marketing:payment.wizard_title', { defaultValue: 'Kauf-Wizard' })}>
|
||||
<Head title={t('marketing:payment.wizard_title', { defaultValue: 'Kauf-Wizard' })} />
|
||||
<div className="min-h-screen bg-gray-50 py-12">
|
||||
<div className="max-w-2xl mx-auto px-4">
|
||||
<Progress value={(currentStepIndex / (steps.length - 1)) * 100} className="mb-6" />
|
||||
<Steps steps={steps} currentStep={currentStepIndex} />
|
||||
{renderStepContent()}
|
||||
{currentStep.id !== 'success' && currentStep.id !== 'package' && (
|
||||
<div className="mt-6">
|
||||
<Button variant="outline" onClick={handleBack}>
|
||||
{t('marketing:payment.back', { defaultValue: 'Zur<75>ck' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</MarketingLayout>
|
||||
);
|
||||
}
|
||||
43
resources/js/pages/marketing/SuccessStep.tsx
Normal file
43
resources/js/pages/marketing/SuccessStep.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { CheckCircle } from 'lucide-react';
|
||||
import { router } from '@inertiajs/react';
|
||||
|
||||
interface Package {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
price: number;
|
||||
}
|
||||
|
||||
interface SuccessStepProps {
|
||||
package: Package;
|
||||
}
|
||||
|
||||
export default function SuccessStep({ package: pkg }: SuccessStepProps) {
|
||||
const { t } = useTranslation('marketing');
|
||||
|
||||
const handleDashboard = () => {
|
||||
router.visit('/admin');
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
|
||||
<CardTitle className="text-2xl">{t('success.title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-center">
|
||||
<p>{t('success.message', { package: pkg.name })}</p>
|
||||
<p className="text-lg font-semibold">
|
||||
{pkg.price === 0 ? t('success.free_assigned') : t('success.paid_assigned')}
|
||||
</p>
|
||||
<Button onClick={handleDashboard} className="w-full">
|
||||
{t('success.go_to_dashboard')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user