ADD new frontend
This commit is contained in:
319
frontend/src/components/domain/auth/LoginForm.tsx
Normal file
319
frontend/src/components/domain/auth/LoginForm.tsx
Normal file
@@ -0,0 +1,319 @@
|
||||
import React, { useState, useRef, useEffect } from 'react';
|
||||
import { Button, Input, Card } from '../../ui';
|
||||
import { useAuth } from '../../../hooks/api/useAuth';
|
||||
import { UserLogin } from '../../../types/auth.types';
|
||||
import { useToast } from '../../../hooks/ui/useToast';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSuccess?: () => void;
|
||||
onRegisterClick?: () => void;
|
||||
onForgotPasswordClick?: () => void;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
interface ExtendedUserLogin extends UserLogin {
|
||||
remember_me: boolean;
|
||||
}
|
||||
|
||||
export const LoginForm: React.FC<LoginFormProps> = ({
|
||||
onSuccess,
|
||||
onRegisterClick,
|
||||
onForgotPasswordClick,
|
||||
className,
|
||||
autoFocus = true
|
||||
}) => {
|
||||
const [credentials, setCredentials] = useState<ExtendedUserLogin>({
|
||||
email: '',
|
||||
password: '',
|
||||
remember_me: false
|
||||
});
|
||||
const [errors, setErrors] = useState<Partial<ExtendedUserLogin>>({});
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const emailInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const { login, isLoading, error } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
|
||||
// Auto-focus on email field when component mounts
|
||||
useEffect(() => {
|
||||
if (autoFocus && emailInputRef.current) {
|
||||
emailInputRef.current.focus();
|
||||
}
|
||||
}, [autoFocus]);
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: Partial<ExtendedUserLogin> = {};
|
||||
|
||||
if (!credentials.email.trim()) {
|
||||
newErrors.email = 'El email es requerido';
|
||||
} else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(credentials.email)) {
|
||||
newErrors.email = 'Por favor, ingrese un email válido';
|
||||
}
|
||||
|
||||
if (!credentials.password) {
|
||||
newErrors.password = 'La contraseña es requerida';
|
||||
} else if (credentials.password.length < 6) {
|
||||
newErrors.password = 'La contraseña debe tener al menos 6 caracteres';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateForm()) {
|
||||
// Focus on first error field
|
||||
const firstErrorField = Object.keys(errors)[0];
|
||||
if (firstErrorField === 'email' && emailInputRef.current) {
|
||||
emailInputRef.current.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const loginData: UserLogin = {
|
||||
email: credentials.email,
|
||||
password: credentials.password,
|
||||
remember_me: credentials.remember_me
|
||||
};
|
||||
|
||||
const success = await login(loginData);
|
||||
if (success) {
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Sesión iniciada correctamente',
|
||||
message: '¡Bienvenido de vuelta a tu panadería!'
|
||||
});
|
||||
onSuccess?.();
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al iniciar sesión',
|
||||
message: error || 'Email o contraseña incorrectos. Verifica tus credenciales.'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (field: keyof ExtendedUserLogin) => (value: string | boolean) => {
|
||||
setCredentials(prev => ({ ...prev, [field]: value }));
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isLoading) {
|
||||
handleSubmit(e as any);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className={`p-8 w-full max-w-md ${className || ''}`} role="main">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-2">
|
||||
Iniciar Sesión
|
||||
</h1>
|
||||
<p className="text-text-secondary">
|
||||
Accede al panel de control de tu panadería
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="space-y-6"
|
||||
noValidate
|
||||
aria-label="Formulario de inicio de sesión"
|
||||
onKeyDown={handleKeyDown}
|
||||
>
|
||||
<div>
|
||||
<Input
|
||||
ref={emailInputRef}
|
||||
type="email"
|
||||
label="Correo Electrónico"
|
||||
placeholder="tu.email@panaderia.com"
|
||||
value={credentials.email}
|
||||
onChange={handleInputChange('email')}
|
||||
error={errors.email}
|
||||
disabled={isLoading}
|
||||
autoComplete="email"
|
||||
required
|
||||
aria-describedby={errors.email ? 'email-error' : undefined}
|
||||
leftIcon={
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p id="email-error" className="text-color-error text-sm mt-1" role="alert">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
label="Contraseña"
|
||||
placeholder="Tu contraseña segura"
|
||||
value={credentials.password}
|
||||
onChange={handleInputChange('password')}
|
||||
error={errors.password}
|
||||
disabled={isLoading}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
aria-describedby={errors.password ? 'password-error' : undefined}
|
||||
leftIcon={
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
}
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-text-secondary hover:text-text-primary transition-colors"
|
||||
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
||||
tabIndex={0}
|
||||
>
|
||||
{showPassword ? (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p id="password-error" className="text-color-error text-sm mt-1" role="alert">
|
||||
{errors.password}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="flex items-center cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={credentials.remember_me}
|
||||
onChange={(e) => handleInputChange('remember_me')(e.target.checked)}
|
||||
className="rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0 h-4 w-4"
|
||||
disabled={isLoading}
|
||||
aria-describedby="remember-me-description"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-text-secondary select-none">
|
||||
Mantener sesión iniciada
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{onForgotPasswordClick && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onForgotPasswordClick}
|
||||
className="text-sm text-color-primary hover:text-color-primary-dark transition-colors underline-offset-2 hover:underline focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2 rounded"
|
||||
disabled={isLoading}
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div id="remember-me-description" className="sr-only">
|
||||
Al activar esta opción, tu sesión permanecerá activa durante más tiempo
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mt-0.5 flex-shrink-0"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||
</svg>
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
isFullWidth
|
||||
isLoading={isLoading}
|
||||
loadingText="Verificando credenciales..."
|
||||
disabled={isLoading}
|
||||
aria-describedby="login-button-description"
|
||||
>
|
||||
{isLoading ? 'Iniciando sesión...' : 'Acceder a mi Panadería'}
|
||||
</Button>
|
||||
|
||||
<div id="login-button-description" className="sr-only">
|
||||
Presiona Enter o haz clic para iniciar sesión con tus credenciales
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{onRegisterClick && (
|
||||
<div className="mt-8 text-center border-t border-border-primary pt-6">
|
||||
<p className="text-text-secondary mb-4">
|
||||
¿Aún no tienes una cuenta para tu panadería?
|
||||
</p>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onRegisterClick}
|
||||
disabled={isLoading}
|
||||
className="focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2"
|
||||
>
|
||||
Registrar mi Panadería
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginForm;
|
||||
606
frontend/src/components/domain/auth/PasswordResetForm.tsx
Normal file
606
frontend/src/components/domain/auth/PasswordResetForm.tsx
Normal file
@@ -0,0 +1,606 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Button, Input, Card } from '../../ui';
|
||||
import { useAuth } from '../../../hooks/api/useAuth';
|
||||
import { useToast } from '../../../hooks/ui/useToast';
|
||||
|
||||
interface PasswordResetFormProps {
|
||||
token?: string;
|
||||
onSuccess?: () => void;
|
||||
onBackClick?: () => void;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
mode?: 'request' | 'reset';
|
||||
}
|
||||
|
||||
export const PasswordResetForm: React.FC<PasswordResetFormProps> = ({
|
||||
token,
|
||||
onSuccess,
|
||||
onBackClick,
|
||||
className,
|
||||
autoFocus = true,
|
||||
mode
|
||||
}) => {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [isEmailSent, setIsEmailSent] = useState(false);
|
||||
const [passwordStrength, setPasswordStrength] = useState(0);
|
||||
const [isTokenValid, setIsTokenValid] = useState<boolean | null>(null);
|
||||
|
||||
const emailInputRef = useRef<HTMLInputElement>(null);
|
||||
const passwordInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const { requestPasswordReset, resetPassword, isLoading, error } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
|
||||
const isResetMode = Boolean(token) || mode === 'reset';
|
||||
|
||||
// Auto-focus on appropriate field when component mounts
|
||||
useEffect(() => {
|
||||
if (autoFocus) {
|
||||
if (isResetMode && passwordInputRef.current) {
|
||||
passwordInputRef.current.focus();
|
||||
} else if (!isResetMode && emailInputRef.current) {
|
||||
emailInputRef.current.focus();
|
||||
}
|
||||
}
|
||||
}, [autoFocus, isResetMode]);
|
||||
|
||||
// Token validation effect
|
||||
useEffect(() => {
|
||||
if (token) {
|
||||
// Simple token format validation (you might want to add actual API validation)
|
||||
const isValidFormat = /^[A-Za-z0-9+/=_-]+$/.test(token) && token.length > 20;
|
||||
setIsTokenValid(isValidFormat);
|
||||
|
||||
if (!isValidFormat) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Token inválido',
|
||||
message: 'El enlace de restablecimiento no es válido o ha expirado'
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [token, showToast]);
|
||||
|
||||
// Calculate password strength
|
||||
const calculatePasswordStrength = (password: string): number => {
|
||||
let strength = 0;
|
||||
if (password.length >= 8) strength += 25;
|
||||
if (/[a-z]/.test(password)) strength += 25;
|
||||
if (/[A-Z]/.test(password)) strength += 25;
|
||||
if (/[0-9]/.test(password)) strength += 15;
|
||||
if (/[^A-Za-z0-9]/.test(password)) strength += 10;
|
||||
return Math.min(strength, 100);
|
||||
};
|
||||
|
||||
const getPasswordStrengthLabel = (strength: number): string => {
|
||||
if (strength < 25) return 'Muy débil';
|
||||
if (strength < 50) return 'Débil';
|
||||
if (strength < 75) return 'Media';
|
||||
return 'Fuerte';
|
||||
};
|
||||
|
||||
const getPasswordStrengthColor = (strength: number): string => {
|
||||
if (strength < 25) return 'bg-color-error';
|
||||
if (strength < 50) return 'bg-yellow-500';
|
||||
if (strength < 75) return 'bg-blue-500';
|
||||
return 'bg-color-success';
|
||||
};
|
||||
|
||||
const validateEmail = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!email.trim()) {
|
||||
newErrors.email = 'El email es requerido';
|
||||
} else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
|
||||
newErrors.email = 'Por favor, ingrese un email válido';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const validatePasswords = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!password) {
|
||||
newErrors.password = 'La contraseña es requerida';
|
||||
} else if (password.length < 8) {
|
||||
newErrors.password = 'La contraseña debe tener al menos 8 caracteres';
|
||||
} else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(password)) {
|
||||
newErrors.password = 'La contraseña debe contener mayúsculas, minúsculas y números';
|
||||
} else if (passwordStrength < 50) {
|
||||
newErrors.password = 'La contraseña es demasiado débil. Intenta con una más segura';
|
||||
}
|
||||
|
||||
if (!confirmPassword) {
|
||||
newErrors.confirmPassword = 'Confirma tu nueva contraseña';
|
||||
} else if (password !== confirmPassword) {
|
||||
newErrors.confirmPassword = 'Las contraseñas no coinciden';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Handle password change to update strength
|
||||
const handlePasswordChange = (value: string) => {
|
||||
setPassword(value);
|
||||
setPasswordStrength(calculatePasswordStrength(value));
|
||||
clearError('password');
|
||||
};
|
||||
|
||||
const handleRequestReset = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateEmail()) {
|
||||
// Focus on email field if validation fails
|
||||
if (emailInputRef.current) {
|
||||
emailInputRef.current.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const success = await requestPasswordReset(email);
|
||||
if (success) {
|
||||
setIsEmailSent(true);
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Email enviado correctamente',
|
||||
message: 'Te hemos enviado las instrucciones para restablecer tu contraseña'
|
||||
});
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al enviar email',
|
||||
message: error || 'No se pudo enviar el email. Verifica que la dirección sea correcta.'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validatePasswords()) {
|
||||
// Focus on password field if validation fails
|
||||
if (passwordInputRef.current) {
|
||||
passwordInputRef.current.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!token || isTokenValid === false) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Token inválido',
|
||||
message: 'El enlace de restablecimiento no es válido. Solicita uno nuevo.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const success = await resetPassword(token, password);
|
||||
if (success) {
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Contraseña actualizada',
|
||||
message: '¡Tu contraseña ha sido restablecida exitosamente! Ya puedes iniciar sesión.'
|
||||
});
|
||||
onSuccess?.();
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al restablecer contraseña',
|
||||
message: error || 'El enlace ha expirado o no es válido. Solicita un nuevo restablecimiento.'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const clearError = (field: string) => {
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
// Handle Enter key submission
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !isLoading) {
|
||||
if (isResetMode) {
|
||||
handleResetPassword(e as any);
|
||||
} else {
|
||||
handleRequestReset(e as any);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Success screen for email sent
|
||||
if (isEmailSent && !isResetMode) {
|
||||
return (
|
||||
<Card className={`p-8 w-full max-w-md text-center ${className || ''}`} role="main">
|
||||
<div className="mb-8">
|
||||
<div className="w-20 h-20 bg-color-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg
|
||||
className="w-10 h-10 text-color-success"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-4">
|
||||
¡Email enviado correctamente!
|
||||
</h1>
|
||||
<div className="bg-background-secondary rounded-lg p-6 mb-6">
|
||||
<p className="text-text-secondary mb-2">
|
||||
Hemos enviado las instrucciones de restablecimiento a:
|
||||
</p>
|
||||
<p className="text-text-primary font-semibold text-lg mb-4">
|
||||
{email}
|
||||
</p>
|
||||
<p className="text-text-secondary text-sm">
|
||||
Revisa tu bandeja de entrada (y la carpeta de spam). El enlace es válido por 24 horas.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={() => {
|
||||
setIsEmailSent(false);
|
||||
setEmail('');
|
||||
setErrors({});
|
||||
if (emailInputRef.current) {
|
||||
emailInputRef.current.focus();
|
||||
}
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
Enviar a Otra Dirección
|
||||
</Button>
|
||||
|
||||
{onBackClick && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onBackClick}
|
||||
className="w-full"
|
||||
>
|
||||
Volver al Login
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Show token validation error
|
||||
if (isResetMode && isTokenValid === false) {
|
||||
return (
|
||||
<Card className={`p-8 w-full max-w-md text-center ${className || ''}`} role="main">
|
||||
<div className="mb-8">
|
||||
<div className="w-20 h-20 bg-color-error/10 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg
|
||||
className="w-10 h-10 text-color-error"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.464 0L3.34 16.5c-.77.833.192 2.5 1.732 2.5z" />
|
||||
</svg>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-4">
|
||||
Enlace No Válido
|
||||
</h1>
|
||||
<p className="text-text-secondary mb-6">
|
||||
El enlace de restablecimiento no es válido o ha expirado.
|
||||
Solicita un nuevo enlace para restablecer tu contraseña.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{onBackClick && (
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onBackClick}
|
||||
className="w-full"
|
||||
>
|
||||
Volver al Login
|
||||
</Button>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={`p-8 w-full max-w-md ${className || ''}`} role="main">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-2xl font-bold text-text-primary mb-2">
|
||||
{isResetMode ? 'Crear Nueva Contraseña' : 'Restablecer Contraseña'}
|
||||
</h1>
|
||||
<p className="text-text-secondary">
|
||||
{isResetMode
|
||||
? 'Crea una contraseña segura para acceder a tu cuenta'
|
||||
: 'Te enviaremos un enlace seguro para restablecer tu contraseña'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={isResetMode ? handleResetPassword : handleRequestReset}
|
||||
className="space-y-6"
|
||||
noValidate
|
||||
onKeyDown={handleKeyDown}
|
||||
aria-label={isResetMode ? 'Formulario de nueva contraseña' : 'Formulario de solicitud de restablecimiento'}
|
||||
>
|
||||
{!isResetMode && (
|
||||
<div>
|
||||
<Input
|
||||
ref={emailInputRef}
|
||||
type="email"
|
||||
label="Correo Electrónico"
|
||||
placeholder="tu.email@panaderia.com"
|
||||
value={email}
|
||||
onChange={(value) => {
|
||||
setEmail(value);
|
||||
clearError('email');
|
||||
}}
|
||||
error={errors.email}
|
||||
disabled={isLoading}
|
||||
autoComplete="email"
|
||||
required
|
||||
aria-describedby={errors.email ? 'email-error' : undefined}
|
||||
leftIcon={
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p id="email-error" className="text-color-error text-sm mt-1" role="alert">
|
||||
{errors.email}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isResetMode && (
|
||||
<>
|
||||
<div>
|
||||
<Input
|
||||
ref={passwordInputRef}
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
label="Nueva Contraseña"
|
||||
placeholder="Contraseña segura"
|
||||
value={password}
|
||||
onChange={handlePasswordChange}
|
||||
error={errors.password}
|
||||
disabled={isLoading}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
aria-describedby={`${errors.password ? 'password-error' : ''} password-strength`}
|
||||
leftIcon={
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
}
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-text-secondary hover:text-text-primary transition-colors"
|
||||
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
||||
tabIndex={0}
|
||||
>
|
||||
{showPassword ? (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Password Strength Indicator */}
|
||||
{password && (
|
||||
<div className="mt-2">
|
||||
<div className="flex justify-between text-xs mb-1">
|
||||
<span className="text-text-secondary">Seguridad:</span>
|
||||
<span className={`font-medium ${passwordStrength < 50 ? 'text-color-error' : passwordStrength < 75 ? 'text-yellow-600' : 'text-color-success'}`}>
|
||||
{getPasswordStrengthLabel(passwordStrength)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="w-full bg-background-secondary rounded-full h-2">
|
||||
<div
|
||||
className={`h-2 rounded-full transition-all duration-300 ${getPasswordStrengthColor(passwordStrength)}`}
|
||||
style={{ width: `${passwordStrength}%` }}
|
||||
role="progressbar"
|
||||
aria-valuenow={passwordStrength}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-label={`Fuerza de la contraseña: ${getPasswordStrengthLabel(passwordStrength)}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{errors.password && (
|
||||
<p id="password-error" className="text-color-error text-sm mt-1" role="alert">
|
||||
{errors.password}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Input
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
label="Confirmar Nueva Contraseña"
|
||||
placeholder="Repite tu nueva contraseña"
|
||||
value={confirmPassword}
|
||||
onChange={(value) => {
|
||||
setConfirmPassword(value);
|
||||
clearError('confirmPassword');
|
||||
}}
|
||||
error={errors.confirmPassword}
|
||||
disabled={isLoading}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
aria-describedby={errors.confirmPassword ? 'confirm-password-error' : undefined}
|
||||
leftIcon={
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="text-text-secondary hover:text-text-primary transition-colors"
|
||||
aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
||||
tabIndex={0}
|
||||
>
|
||||
{showConfirmPassword ? (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<p id="confirm-password-error" className="text-color-error text-sm mt-1" role="alert">
|
||||
{errors.confirmPassword}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div
|
||||
className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5 mt-0.5 flex-shrink-0"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||
</svg>
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
isFullWidth
|
||||
isLoading={isLoading}
|
||||
loadingText={isResetMode ? 'Restableciendo contraseña...' : 'Enviando enlace...'}
|
||||
disabled={isLoading || (isResetMode && isTokenValid === false)}
|
||||
aria-describedby={isResetMode ? 'reset-button-description' : 'request-button-description'}
|
||||
>
|
||||
{isResetMode ? 'Actualizar Contraseña' : 'Enviar Enlace de Restablecimiento'}
|
||||
</Button>
|
||||
|
||||
<div id={isResetMode ? 'reset-button-description' : 'request-button-description'} className="sr-only">
|
||||
{isResetMode
|
||||
? 'Presiona Enter o haz clic para actualizar tu contraseña'
|
||||
: 'Presiona Enter o haz clic para enviar el enlace de restablecimiento'
|
||||
}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{onBackClick && (
|
||||
<div className="mt-8 text-center border-t border-border-primary pt-6">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onBackClick}
|
||||
disabled={isLoading}
|
||||
className="w-full focus:outline-none focus:ring-2 focus:ring-color-primary focus:ring-offset-2"
|
||||
>
|
||||
Volver al Inicio de Sesión
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default PasswordResetForm;
|
||||
704
frontend/src/components/domain/auth/ProfileSettings.tsx
Normal file
704
frontend/src/components/domain/auth/ProfileSettings.tsx
Normal file
@@ -0,0 +1,704 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Button, Input, Card, Select, Avatar, Modal } from '../../ui';
|
||||
import { useAuth } from '../../../hooks/api/useAuth';
|
||||
import { User } from '../../../types/auth.types';
|
||||
import { useToast } from '../../../hooks/ui/useToast';
|
||||
|
||||
interface ProfileSettingsProps {
|
||||
onSuccess?: () => void;
|
||||
className?: string;
|
||||
initialTab?: 'profile' | 'security' | 'preferences' | 'notifications';
|
||||
}
|
||||
|
||||
interface ProfileFormData {
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
language: string;
|
||||
timezone: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
interface BakeryFormData {
|
||||
bakery_name: string;
|
||||
bakery_type: string;
|
||||
address: string;
|
||||
city: string;
|
||||
postal_code: string;
|
||||
country: string;
|
||||
website?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface NotificationSettings {
|
||||
email_notifications: boolean;
|
||||
order_notifications: boolean;
|
||||
marketing_notifications: boolean;
|
||||
security_notifications: boolean;
|
||||
low_stock_alerts: boolean;
|
||||
production_reminders: boolean;
|
||||
}
|
||||
|
||||
interface PasswordChangeData {
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
confirmNewPassword: string;
|
||||
}
|
||||
|
||||
export const ProfileSettings: React.FC<ProfileSettingsProps> = ({
|
||||
onSuccess,
|
||||
className,
|
||||
initialTab = 'profile'
|
||||
}) => {
|
||||
const { user, updateProfile, isLoading, error } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [activeTab, setActiveTab] = useState<'profile' | 'security' | 'preferences' | 'notifications'>(initialTab);
|
||||
const [profileData, setProfileData] = useState<ProfileFormData>({
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
language: 'es',
|
||||
timezone: 'Europe/Madrid',
|
||||
avatar_url: ''
|
||||
});
|
||||
|
||||
const [bakeryData, setBakeryData] = useState<BakeryFormData>({
|
||||
bakery_name: '',
|
||||
bakery_type: 'traditional',
|
||||
address: '',
|
||||
city: '',
|
||||
postal_code: '',
|
||||
country: 'España',
|
||||
website: '',
|
||||
description: ''
|
||||
});
|
||||
|
||||
const [notificationSettings, setNotificationSettings] = useState<NotificationSettings>({
|
||||
email_notifications: true,
|
||||
order_notifications: true,
|
||||
marketing_notifications: false,
|
||||
security_notifications: true,
|
||||
low_stock_alerts: true,
|
||||
production_reminders: true
|
||||
});
|
||||
|
||||
const [passwordData, setPasswordData] = useState<PasswordChangeData>({
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
confirmNewPassword: ''
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [showPasswords, setShowPasswords] = useState({
|
||||
current: false,
|
||||
new: false,
|
||||
confirm: false
|
||||
});
|
||||
const [hasChanges, setHasChanges] = useState({
|
||||
profile: false,
|
||||
bakery: false,
|
||||
notifications: false
|
||||
});
|
||||
const [uploadingImage, setUploadingImage] = useState(false);
|
||||
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||
const [previewImage, setPreviewImage] = useState<string | null>(null);
|
||||
|
||||
const bakeryTypeOptions = [
|
||||
{ value: 'traditional', label: 'Panadería Tradicional' },
|
||||
{ value: 'artisan', label: 'Panadería Artesanal' },
|
||||
{ value: 'industrial', label: 'Panadería Industrial' },
|
||||
{ value: 'confectionery', label: 'Pastelería' },
|
||||
{ value: 'bakery_cafe', label: 'Panadería Cafetería' },
|
||||
{ value: 'specialty', label: 'Panadería Especializada' },
|
||||
{ value: 'patisserie', label: 'Pastelería Francesa' },
|
||||
{ value: 'organic', label: 'Panadería Orgánica' },
|
||||
{ value: 'gluten_free', label: 'Panadería Sin Gluten' }
|
||||
];
|
||||
|
||||
const languageOptions = [
|
||||
{ value: 'es', label: 'Español' },
|
||||
{ value: 'ca', label: 'Català' },
|
||||
{ value: 'eu', label: 'Euskera' },
|
||||
{ value: 'gl', label: 'Galego' },
|
||||
{ value: 'en', label: 'English' }
|
||||
];
|
||||
|
||||
const timezoneOptions = [
|
||||
{ value: 'Europe/Madrid', label: 'Madrid (CET/CEST)' },
|
||||
{ value: 'Atlantic/Canary', label: 'Canarias (WET/WEST)' },
|
||||
{ value: 'Europe/London', label: 'Londres (GMT/BST)' },
|
||||
{ value: 'Europe/Paris', label: 'París (CET/CEST)' },
|
||||
{ value: 'Europe/Rome', label: 'Roma (CET/CEST)' }
|
||||
];
|
||||
|
||||
// Initialize form data with user data
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setProfileData({
|
||||
full_name: user.full_name || '',
|
||||
email: user.email || '',
|
||||
phone: user.phone || '',
|
||||
language: user.language || 'es',
|
||||
timezone: user.timezone || 'Europe/Madrid',
|
||||
avatar_url: user.avatar_url || ''
|
||||
});
|
||||
|
||||
// Initialize bakery data (would come from a separate bakery API)
|
||||
setBakeryData({
|
||||
bakery_name: (user as any).bakery_name || '',
|
||||
bakery_type: (user as any).bakery_type || 'traditional',
|
||||
address: (user as any).address || '',
|
||||
city: (user as any).city || '',
|
||||
postal_code: (user as any).postal_code || '',
|
||||
country: (user as any).country || 'España',
|
||||
website: (user as any).website || '',
|
||||
description: (user as any).description || ''
|
||||
});
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Profile picture upload handler
|
||||
const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Archivo inválido',
|
||||
message: 'Por favor, selecciona una imagen válida'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file size (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Archivo muy grande',
|
||||
message: 'La imagen debe ser menor a 5MB'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadingImage(true);
|
||||
try {
|
||||
// Create preview
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
setPreviewImage(e.target?.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
|
||||
// Here you would upload to your image service
|
||||
// For now, we'll simulate the upload
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
const newImageUrl = URL.createObjectURL(file); // Temporary URL
|
||||
setProfileData(prev => ({ ...prev, avatar_url: newImageUrl }));
|
||||
setHasChanges(prev => ({ ...prev, profile: true }));
|
||||
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Imagen subida',
|
||||
message: 'Tu foto de perfil ha sido actualizada'
|
||||
});
|
||||
} catch (error) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al subir imagen',
|
||||
message: 'No se pudo subir la imagen. Intenta de nuevo.'
|
||||
});
|
||||
} finally {
|
||||
setUploadingImage(false);
|
||||
setPreviewImage(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveImage = () => {
|
||||
setProfileData(prev => ({ ...prev, avatar_url: '' }));
|
||||
setHasChanges(prev => ({ ...prev, profile: true }));
|
||||
setShowDeleteConfirm(false);
|
||||
};
|
||||
|
||||
const validateProfileForm = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!profileData.full_name.trim()) {
|
||||
newErrors.full_name = 'El nombre completo es requerido';
|
||||
} else if (profileData.full_name.trim().length < 2) {
|
||||
newErrors.full_name = 'El nombre debe tener al menos 2 caracteres';
|
||||
}
|
||||
|
||||
if (!profileData.email.trim()) {
|
||||
newErrors.email = 'El email es requerido';
|
||||
} else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(profileData.email)) {
|
||||
newErrors.email = 'Por favor, ingrese un email válido';
|
||||
}
|
||||
|
||||
if (profileData.phone && !/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(profileData.phone.replace(/\s/g, ''))) {
|
||||
newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const validateBakeryForm = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!bakeryData.bakery_name.trim()) {
|
||||
newErrors.bakery_name = 'El nombre de la panadería es requerido';
|
||||
}
|
||||
|
||||
if (!bakeryData.address.trim()) {
|
||||
newErrors.address = 'La dirección es requerida';
|
||||
}
|
||||
|
||||
if (!bakeryData.city.trim()) {
|
||||
newErrors.city = 'La ciudad es requerida';
|
||||
}
|
||||
|
||||
if (bakeryData.postal_code && !/^[0-5][0-9]{4}$/.test(bakeryData.postal_code)) {
|
||||
newErrors.postal_code = 'Por favor, ingrese un código postal español válido';
|
||||
}
|
||||
|
||||
if (bakeryData.website && !/^https?:\/\/.+\..+/.test(bakeryData.website)) {
|
||||
newErrors.website = 'Por favor, ingrese una URL válida (ej: https://mipanaderia.com)';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const validatePasswordForm = (): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!passwordData.currentPassword) {
|
||||
newErrors.currentPassword = 'La contraseña actual es requerida';
|
||||
}
|
||||
|
||||
if (!passwordData.newPassword) {
|
||||
newErrors.newPassword = 'La nueva contraseña es requerida';
|
||||
} else if (passwordData.newPassword.length < 8) {
|
||||
newErrors.newPassword = 'La contraseña debe tener al menos 8 caracteres';
|
||||
} else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(passwordData.newPassword)) {
|
||||
newErrors.newPassword = 'La contraseña debe contener mayúsculas, minúsculas y números';
|
||||
}
|
||||
|
||||
if (!passwordData.confirmNewPassword) {
|
||||
newErrors.confirmNewPassword = 'Confirma tu nueva contraseña';
|
||||
} else if (passwordData.newPassword !== passwordData.confirmNewPassword) {
|
||||
newErrors.confirmNewPassword = 'Las contraseñas no coinciden';
|
||||
}
|
||||
|
||||
if (passwordData.currentPassword === passwordData.newPassword) {
|
||||
newErrors.newPassword = 'La nueva contraseña debe ser diferente a la actual';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleProfileSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateProfileForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const success = await updateProfile(profileData);
|
||||
if (success) {
|
||||
setHasChanges(false);
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Perfil actualizado',
|
||||
message: 'Tu información ha sido guardada correctamente'
|
||||
});
|
||||
onSuccess?.();
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al actualizar',
|
||||
message: error || 'No se pudo actualizar tu perfil'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo conectar con el servidor'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handlePasswordSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validatePasswordForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Note: This would typically call a separate password change endpoint
|
||||
// For now, we'll show a placeholder message
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Contraseña actualizada',
|
||||
message: 'Tu contraseña ha sido cambiada correctamente'
|
||||
});
|
||||
|
||||
setPasswordData({
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
confirmNewPassword: ''
|
||||
});
|
||||
};
|
||||
|
||||
const handleProfileInputChange = (field: keyof ProfileFormData) => (value: string) => {
|
||||
setProfileData(prev => ({ ...prev, [field]: value }));
|
||||
setHasChanges(true);
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const handlePasswordInputChange = (field: keyof PasswordChangeData) => (value: string) => {
|
||||
setPasswordData(prev => ({ ...prev, [field]: value }));
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const togglePasswordVisibility = (field: 'current' | 'new' | 'confirm') => {
|
||||
setShowPasswords(prev => ({
|
||||
...prev,
|
||||
[field]: !prev[field]
|
||||
}));
|
||||
};
|
||||
|
||||
const tabs = [
|
||||
{ id: 'profile' as const, label: 'Perfil', icon: 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z' },
|
||||
{ id: 'security' as const, label: 'Seguridad', icon: 'M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z' },
|
||||
{ id: 'preferences' as const, label: 'Preferencias', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z' }
|
||||
];
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card className={`p-8 ${className || ''}`}>
|
||||
<div className="text-center text-text-secondary">
|
||||
Cargando información del usuario...
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`space-y-6 ${className || ''}`}>
|
||||
{/* Header */}
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center space-x-4">
|
||||
<Avatar
|
||||
src={user.avatar_url}
|
||||
name={`${user.first_name} ${user.last_name}`}
|
||||
size="lg"
|
||||
/>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-text-primary">
|
||||
{user.first_name} {user.last_name}
|
||||
</h1>
|
||||
<p className="text-text-secondary">{user.email}</p>
|
||||
<p className="text-sm text-text-secondary">{user.bakery_name}</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Tabs */}
|
||||
<Card className="overflow-hidden">
|
||||
<div className="border-b border-border-primary">
|
||||
<nav className="flex">
|
||||
{tabs.map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`flex items-center space-x-2 px-6 py-4 text-sm font-medium transition-colors ${
|
||||
activeTab === tab.id
|
||||
? 'text-color-primary border-b-2 border-color-primary'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={tab.icon} />
|
||||
</svg>
|
||||
<span>{tab.label}</span>
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div className="p-6">
|
||||
{activeTab === 'profile' && (
|
||||
<form onSubmit={handleProfileSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
|
||||
Información Personal
|
||||
</h3>
|
||||
|
||||
<Input
|
||||
label="Nombre"
|
||||
value={profileData.first_name}
|
||||
onChange={handleProfileInputChange('first_name')}
|
||||
error={errors.first_name}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="Apellidos"
|
||||
value={profileData.last_name}
|
||||
onChange={handleProfileInputChange('last_name')}
|
||||
error={errors.last_name}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="email"
|
||||
label="Email"
|
||||
value={profileData.email}
|
||||
onChange={handleProfileInputChange('email')}
|
||||
error={errors.email}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="tel"
|
||||
label="Teléfono"
|
||||
value={profileData.phone}
|
||||
onChange={handleProfileInputChange('phone')}
|
||||
error={errors.phone}
|
||||
disabled={isLoading}
|
||||
placeholder="+34 600 000 000"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
|
||||
Información del Negocio
|
||||
</h3>
|
||||
|
||||
<Input
|
||||
label="Nombre de la Panadería"
|
||||
value={profileData.bakery_name}
|
||||
onChange={handleProfileInputChange('bakery_name')}
|
||||
error={errors.bakery_name}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Tipo de Panadería"
|
||||
options={bakeryTypeOptions}
|
||||
value={profileData.bakery_type}
|
||||
onChange={handleProfileInputChange('bakery_type')}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="Dirección"
|
||||
value={profileData.address}
|
||||
onChange={handleProfileInputChange('address')}
|
||||
error={errors.address}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="Ciudad"
|
||||
value={profileData.city}
|
||||
onChange={handleProfileInputChange('city')}
|
||||
error={errors.city}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="País"
|
||||
value={profileData.country}
|
||||
onChange={handleProfileInputChange('country')}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-4 pt-6 border-t border-border-primary">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
if (user) {
|
||||
setProfileData({
|
||||
first_name: user.first_name || '',
|
||||
last_name: user.last_name || '',
|
||||
email: user.email || '',
|
||||
phone: user.phone || '',
|
||||
bakery_name: user.bakery_name || '',
|
||||
bakery_type: user.bakery_type || 'traditional',
|
||||
address: user.address || '',
|
||||
city: user.city || '',
|
||||
country: user.country || 'España',
|
||||
avatar_url: user.avatar_url || ''
|
||||
});
|
||||
setHasChanges(false);
|
||||
setErrors({});
|
||||
}
|
||||
}}
|
||||
disabled={!hasChanges || isLoading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
isLoading={isLoading}
|
||||
loadingText="Guardando..."
|
||||
disabled={!hasChanges}
|
||||
>
|
||||
Guardar Cambios
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{activeTab === 'security' && (
|
||||
<form onSubmit={handlePasswordSubmit} className="space-y-6 max-w-md">
|
||||
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
|
||||
Cambiar Contraseña
|
||||
</h3>
|
||||
|
||||
<Input
|
||||
type={showPasswords.current ? 'text' : 'password'}
|
||||
label="Contraseña Actual"
|
||||
value={passwordData.currentPassword}
|
||||
onChange={handlePasswordInputChange('currentPassword')}
|
||||
error={errors.currentPassword}
|
||||
disabled={isLoading}
|
||||
required
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => togglePasswordVisibility('current')}
|
||||
className="text-text-secondary hover:text-text-primary"
|
||||
>
|
||||
{showPasswords.current ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type={showPasswords.new ? 'text' : 'password'}
|
||||
label="Nueva Contraseña"
|
||||
value={passwordData.newPassword}
|
||||
onChange={handlePasswordInputChange('newPassword')}
|
||||
error={errors.newPassword}
|
||||
disabled={isLoading}
|
||||
required
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => togglePasswordVisibility('new')}
|
||||
className="text-text-secondary hover:text-text-primary"
|
||||
>
|
||||
{showPasswords.new ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type={showPasswords.confirm ? 'text' : 'password'}
|
||||
label="Confirmar Nueva Contraseña"
|
||||
value={passwordData.confirmNewPassword}
|
||||
onChange={handlePasswordInputChange('confirmNewPassword')}
|
||||
error={errors.confirmNewPassword}
|
||||
disabled={isLoading}
|
||||
required
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => togglePasswordVisibility('confirm')}
|
||||
className="text-text-secondary hover:text-text-primary"
|
||||
>
|
||||
{showPasswords.confirm ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
isLoading={isLoading}
|
||||
loadingText="Actualizando..."
|
||||
>
|
||||
Cambiar Contraseña
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{activeTab === 'preferences' && (
|
||||
<div className="space-y-6">
|
||||
<h3 className="text-lg font-semibold text-text-primary border-b border-border-primary pb-2">
|
||||
Preferencias
|
||||
</h3>
|
||||
|
||||
<div className="text-text-secondary">
|
||||
<p>Configuraciones de preferencias estarán disponibles próximamente.</p>
|
||||
<div className="mt-4 space-y-2 text-sm">
|
||||
<p>• Configuración de idioma</p>
|
||||
<p>• Zona horaria</p>
|
||||
<p>• Formato de fecha y hora</p>
|
||||
<p>• Notificaciones</p>
|
||||
<p>• Tema de la aplicación</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProfileSettings;
|
||||
805
frontend/src/components/domain/auth/RegisterForm.tsx
Normal file
805
frontend/src/components/domain/auth/RegisterForm.tsx
Normal file
@@ -0,0 +1,805 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Button, Input, Card, Select } from '../../ui';
|
||||
import { useAuth } from '../../../hooks/api/useAuth';
|
||||
import { UserRegistration } from '../../../types/auth.types';
|
||||
import { useToast } from '../../../hooks/ui/useToast';
|
||||
|
||||
interface RegisterFormProps {
|
||||
onSuccess?: () => void;
|
||||
onLoginClick?: () => void;
|
||||
className?: string;
|
||||
showProgressSteps?: boolean;
|
||||
}
|
||||
|
||||
type RegistrationStep = 'personal' | 'bakery' | 'security' | 'verification';
|
||||
|
||||
interface ExtendedUserRegistration {
|
||||
// Personal Information
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
|
||||
// Bakery Information
|
||||
tenant_name: string;
|
||||
bakery_type: string;
|
||||
address: string;
|
||||
city: string;
|
||||
postal_code: string;
|
||||
country: string;
|
||||
|
||||
// Security
|
||||
password: string;
|
||||
confirmPassword: string;
|
||||
|
||||
// Terms
|
||||
acceptTerms: boolean;
|
||||
acceptPrivacy: boolean;
|
||||
acceptMarketing: boolean;
|
||||
}
|
||||
|
||||
export const RegisterForm: React.FC<RegisterFormProps> = ({
|
||||
onSuccess,
|
||||
onLoginClick,
|
||||
className,
|
||||
showProgressSteps = true
|
||||
}) => {
|
||||
const [currentStep, setCurrentStep] = useState<RegistrationStep>('personal');
|
||||
const [completedSteps, setCompletedSteps] = useState<Set<RegistrationStep>>(new Set());
|
||||
const [isEmailVerificationSent, setIsEmailVerificationSent] = useState(false);
|
||||
|
||||
const [formData, setFormData] = useState<ExtendedUserRegistration>({
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
tenant_name: '',
|
||||
bakery_type: 'traditional',
|
||||
address: '',
|
||||
city: '',
|
||||
postal_code: '',
|
||||
country: 'España',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
acceptTerms: false,
|
||||
acceptPrivacy: false,
|
||||
acceptMarketing: false
|
||||
});
|
||||
|
||||
const [errors, setErrors] = useState<Partial<ExtendedUserRegistration>>({});
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
|
||||
const { register, verifyEmail, isLoading, error } = useAuth();
|
||||
const { showToast } = useToast();
|
||||
|
||||
const steps: { id: RegistrationStep; title: string; description: string }[] = [
|
||||
{ id: 'personal', title: 'Información Personal', description: 'Tus datos básicos' },
|
||||
{ id: 'bakery', title: 'Tu Panadería', description: 'Detalles del negocio' },
|
||||
{ id: 'security', title: 'Seguridad', description: 'Contraseña y términos' },
|
||||
{ id: 'verification', title: 'Verificación', description: 'Confirmar email' }
|
||||
];
|
||||
|
||||
const bakeryTypeOptions = [
|
||||
{ value: 'traditional', label: 'Panadería Tradicional' },
|
||||
{ value: 'artisan', label: 'Panadería Artesanal' },
|
||||
{ value: 'industrial', label: 'Panadería Industrial' },
|
||||
{ value: 'confectionery', label: 'Pastelería' },
|
||||
{ value: 'bakery_cafe', label: 'Panadería Cafetería' },
|
||||
{ value: 'specialty', label: 'Panadería Especializada' },
|
||||
{ value: 'patisserie', label: 'Pastelería Francesa' },
|
||||
{ value: 'organic', label: 'Panadería Orgánica' }
|
||||
];
|
||||
|
||||
const validatePersonalStep = (): boolean => {
|
||||
const newErrors: Partial<ExtendedUserRegistration> = {};
|
||||
|
||||
if (!formData.full_name.trim()) {
|
||||
newErrors.full_name = 'El nombre completo es requerido';
|
||||
} else if (formData.full_name.trim().length < 2) {
|
||||
newErrors.full_name = 'El nombre debe tener al menos 2 caracteres';
|
||||
}
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = 'El email es requerido';
|
||||
} else if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(formData.email)) {
|
||||
newErrors.email = 'Por favor, ingrese un email válido';
|
||||
}
|
||||
|
||||
if (!formData.phone.trim()) {
|
||||
newErrors.phone = 'El teléfono es requerido';
|
||||
} else if (!/^(\+34|0034|34)?[6-9][0-9]{8}$/.test(formData.phone.replace(/\s/g, ''))) {
|
||||
newErrors.phone = 'Por favor, ingrese un teléfono español válido (ej: +34 600 000 000)';
|
||||
}
|
||||
|
||||
setErrors(prev => ({ ...prev, ...newErrors }));
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const validateBakeryStep = (): boolean => {
|
||||
const newErrors: Partial<ExtendedUserRegistration> = {};
|
||||
|
||||
if (!formData.tenant_name.trim()) {
|
||||
newErrors.tenant_name = 'El nombre de la panadería es requerido';
|
||||
} else if (formData.tenant_name.trim().length < 2) {
|
||||
newErrors.tenant_name = 'El nombre debe tener al menos 2 caracteres';
|
||||
}
|
||||
|
||||
if (!formData.address.trim()) {
|
||||
newErrors.address = 'La dirección es requerida';
|
||||
}
|
||||
|
||||
if (!formData.city.trim()) {
|
||||
newErrors.city = 'La ciudad es requerida';
|
||||
}
|
||||
|
||||
if (!formData.postal_code.trim()) {
|
||||
newErrors.postal_code = 'El código postal es requerido';
|
||||
} else if (!/^[0-5][0-9]{4}$/.test(formData.postal_code)) {
|
||||
newErrors.postal_code = 'Por favor, ingrese un código postal español válido (ej: 28001)';
|
||||
}
|
||||
|
||||
setErrors(prev => ({ ...prev, ...newErrors }));
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const validateSecurityStep = (): boolean => {
|
||||
const newErrors: Partial<ExtendedUserRegistration> = {};
|
||||
|
||||
if (!formData.password) {
|
||||
newErrors.password = 'La contraseña es requerida';
|
||||
} else if (formData.password.length < 8) {
|
||||
newErrors.password = 'La contraseña debe tener al menos 8 caracteres';
|
||||
} else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])?/.test(formData.password)) {
|
||||
newErrors.password = 'La contraseña debe contener mayúsculas, minúsculas y números';
|
||||
}
|
||||
|
||||
if (!formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Confirma tu contraseña';
|
||||
} else if (formData.password !== formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Las contraseñas no coinciden';
|
||||
}
|
||||
|
||||
if (!formData.acceptTerms) {
|
||||
newErrors.acceptTerms = 'Debes aceptar los términos y condiciones';
|
||||
}
|
||||
|
||||
if (!formData.acceptPrivacy) {
|
||||
newErrors.acceptPrivacy = 'Debes aceptar la política de privacidad';
|
||||
}
|
||||
|
||||
setErrors(prev => ({ ...prev, ...newErrors }));
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
const handleNextStep = (e?: React.FormEvent) => {
|
||||
if (e) e.preventDefault();
|
||||
|
||||
let isValid = false;
|
||||
switch (currentStep) {
|
||||
case 'personal':
|
||||
isValid = validatePersonalStep();
|
||||
break;
|
||||
case 'bakery':
|
||||
isValid = validateBakeryStep();
|
||||
break;
|
||||
case 'security':
|
||||
isValid = validateSecurityStep();
|
||||
break;
|
||||
default:
|
||||
isValid = true;
|
||||
}
|
||||
|
||||
if (isValid) {
|
||||
setCompletedSteps(prev => new Set([...prev, currentStep]));
|
||||
|
||||
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
|
||||
const currentIndex = stepOrder.indexOf(currentStep);
|
||||
|
||||
if (currentIndex < stepOrder.length - 1) {
|
||||
setCurrentStep(stepOrder[currentIndex + 1]);
|
||||
setErrors({}); // Clear errors when moving to next step
|
||||
}
|
||||
|
||||
// If this is the security step, submit the registration
|
||||
if (currentStep === 'security') {
|
||||
handleSubmitRegistration();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handlePreviousStep = () => {
|
||||
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
|
||||
const currentIndex = stepOrder.indexOf(currentStep);
|
||||
|
||||
if (currentIndex > 0) {
|
||||
setCurrentStep(stepOrder[currentIndex - 1]);
|
||||
setErrors({}); // Clear errors when going back
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmitRegistration = async () => {
|
||||
try {
|
||||
const registrationData: UserRegistration = {
|
||||
full_name: formData.full_name,
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
tenant_name: formData.tenant_name,
|
||||
phone: formData.phone
|
||||
};
|
||||
|
||||
const success = await register(registrationData);
|
||||
|
||||
if (success) {
|
||||
setIsEmailVerificationSent(true);
|
||||
setCurrentStep('verification');
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Cuenta creada exitosamente',
|
||||
message: 'Revisa tu email para verificar tu cuenta y completar el registro'
|
||||
});
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error al crear la cuenta',
|
||||
message: error || 'No se pudo crear la cuenta. Verifica que el email no esté en uso.'
|
||||
});
|
||||
setCurrentStep('personal'); // Go back to first step to fix issues
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo conectar con el servidor. Verifica tu conexión a internet.'
|
||||
});
|
||||
setCurrentStep('personal');
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (field: keyof ExtendedUserRegistration) => (value: string | boolean) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: undefined }));
|
||||
}
|
||||
};
|
||||
|
||||
const getCurrentStepIndex = () => {
|
||||
const stepOrder: RegistrationStep[] = ['personal', 'bakery', 'security', 'verification'];
|
||||
return stepOrder.indexOf(currentStep);
|
||||
};
|
||||
|
||||
const getProgressPercentage = () => {
|
||||
return ((getCurrentStepIndex()) / (steps.length - 1)) * 100;
|
||||
};
|
||||
|
||||
// Email verification success handler
|
||||
const handleEmailVerification = async (token: string) => {
|
||||
try {
|
||||
const success = await verifyEmail(token);
|
||||
if (success) {
|
||||
showToast({
|
||||
type: 'success',
|
||||
title: 'Email verificado exitosamente',
|
||||
message: '¡Tu cuenta ha sido activada! Ya puedes iniciar sesión.'
|
||||
});
|
||||
onSuccess?.();
|
||||
} else {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de verificación',
|
||||
message: 'El enlace de verificación no es válido o ha expirado'
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
showToast({
|
||||
type: 'error',
|
||||
title: 'Error de conexión',
|
||||
message: 'No se pudo verificar el email. Intenta más tarde.'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className={`p-8 w-full max-w-4xl ${className || ''}`} role="main">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-text-primary mb-2">
|
||||
Registra tu Panadería
|
||||
</h1>
|
||||
<p className="text-text-secondary text-lg">
|
||||
Crea tu cuenta y comienza a digitalizar tu negocio
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Progress Indicator */}
|
||||
{showProgressSteps && (
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
{steps.map((step, index) => (
|
||||
<div
|
||||
key={step.id}
|
||||
className="flex flex-col items-center flex-1"
|
||||
role="progressbar"
|
||||
aria-valuenow={getCurrentStepIndex() + 1}
|
||||
aria-valuemax={steps.length}
|
||||
aria-label={`Paso ${index + 1} de ${steps.length}: ${step.title}`}
|
||||
>
|
||||
<div className={`w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold mb-2 transition-all duration-300 ${
|
||||
completedSteps.has(step.id)
|
||||
? 'bg-color-success text-white'
|
||||
: currentStep === step.id
|
||||
? 'bg-color-primary text-white ring-4 ring-color-primary/20'
|
||||
: 'bg-background-secondary text-text-secondary'
|
||||
}`}>
|
||||
{completedSteps.has(step.id) ? (
|
||||
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
|
||||
</svg>
|
||||
) : (
|
||||
index + 1
|
||||
)}
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className={`text-xs font-medium ${
|
||||
currentStep === step.id ? 'text-color-primary' : 'text-text-secondary'
|
||||
}`}>
|
||||
{step.title}
|
||||
</div>
|
||||
<div className="text-xs text-text-secondary mt-1">
|
||||
{step.description}
|
||||
</div>
|
||||
</div>
|
||||
{index < steps.length - 1 && (
|
||||
<div className={`absolute top-5 left-1/2 w-full h-0.5 -z-10 ${
|
||||
completedSteps.has(step.id) ? 'bg-color-success' : 'bg-background-secondary'
|
||||
}`} style={{ marginLeft: '2.5rem' }} />
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Progress Bar */}
|
||||
<div className="w-full bg-background-secondary rounded-full h-2">
|
||||
<div
|
||||
className="bg-color-primary h-2 rounded-full transition-all duration-500 ease-in-out"
|
||||
style={{ width: `${getProgressPercentage()}%` }}
|
||||
role="progressbar"
|
||||
aria-label="Progreso del registro"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Step Content */}
|
||||
{currentStep !== 'verification' ? (
|
||||
<form onSubmit={handleNextStep} className="space-y-8">
|
||||
{/* Personal Information Step */}
|
||||
{currentStep === 'personal' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-xl font-semibold text-text-primary mb-2">
|
||||
Información Personal
|
||||
</h2>
|
||||
<p className="text-text-secondary">
|
||||
Cuéntanos sobre ti para personalizar tu experiencia
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6">
|
||||
<Input
|
||||
label="Nombre Completo"
|
||||
placeholder="Juan Pérez García"
|
||||
value={formData.full_name}
|
||||
onChange={handleInputChange('full_name')}
|
||||
error={errors.full_name}
|
||||
disabled={isLoading}
|
||||
required
|
||||
autoComplete="name"
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="email"
|
||||
label="Correo Electrónico"
|
||||
placeholder="tu.email@panaderia.com"
|
||||
value={formData.email}
|
||||
onChange={handleInputChange('email')}
|
||||
error={errors.email}
|
||||
disabled={isLoading}
|
||||
required
|
||||
autoComplete="email"
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="tel"
|
||||
label="Teléfono"
|
||||
placeholder="+34 600 000 000"
|
||||
value={formData.phone}
|
||||
onChange={handleInputChange('phone')}
|
||||
error={errors.phone}
|
||||
disabled={isLoading}
|
||||
required
|
||||
autoComplete="tel"
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* Bakery Information Step */}
|
||||
{currentStep === 'bakery' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-xl font-semibold text-text-primary mb-2">
|
||||
Información de tu Panadería
|
||||
</h2>
|
||||
<p className="text-text-secondary">
|
||||
Déjanos conocer los detalles de tu negocio
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<Input
|
||||
label="Nombre de la Panadería"
|
||||
placeholder="Panadería San José"
|
||||
value={formData.tenant_name}
|
||||
onChange={handleInputChange('tenant_name')}
|
||||
error={errors.tenant_name}
|
||||
disabled={isLoading}
|
||||
required
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
|
||||
<Select
|
||||
label="Tipo de Panadería"
|
||||
options={bakeryTypeOptions}
|
||||
value={formData.bakery_type}
|
||||
onChange={handleInputChange('bakery_type')}
|
||||
error={errors.bakery_type}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Dirección"
|
||||
placeholder="Calle Principal 123"
|
||||
value={formData.address}
|
||||
onChange={handleInputChange('address')}
|
||||
error={errors.address}
|
||||
disabled={isLoading}
|
||||
required
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Input
|
||||
label="Ciudad"
|
||||
placeholder="Madrid"
|
||||
value={formData.city}
|
||||
onChange={handleInputChange('city')}
|
||||
error={errors.city}
|
||||
disabled={isLoading}
|
||||
required
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="Código Postal"
|
||||
placeholder="28001"
|
||||
value={formData.postal_code}
|
||||
onChange={handleInputChange('postal_code')}
|
||||
error={errors.postal_code}
|
||||
disabled={isLoading}
|
||||
required
|
||||
maxLength={5}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label="País"
|
||||
value={formData.country}
|
||||
onChange={handleInputChange('country')}
|
||||
disabled={true}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Security Step */}
|
||||
{currentStep === 'security' && (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center mb-6">
|
||||
<h2 className="text-xl font-semibold text-text-primary mb-2">
|
||||
Seguridad y Términos
|
||||
</h2>
|
||||
<p className="text-text-secondary">
|
||||
Crea una contraseña segura y acepta nuestros términos
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<Input
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
label="Contraseña"
|
||||
placeholder="Contraseña segura"
|
||||
value={formData.password}
|
||||
onChange={handleInputChange('password')}
|
||||
error={errors.password}
|
||||
disabled={isLoading}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
|
||||
</svg>
|
||||
}
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="text-text-secondary hover:text-text-primary"
|
||||
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
||||
>
|
||||
{showPassword ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
label="Confirmar Contraseña"
|
||||
placeholder="Repite tu contraseña"
|
||||
value={formData.confirmPassword}
|
||||
onChange={handleInputChange('confirmPassword')}
|
||||
error={errors.confirmPassword}
|
||||
disabled={isLoading}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
leftIcon={
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
rightIcon={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="text-text-secondary hover:text-text-primary"
|
||||
aria-label={showConfirmPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
||||
>
|
||||
{showConfirmPassword ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 pt-4 border-t border-border-primary">
|
||||
<div className="flex items-start space-x-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="acceptTerms"
|
||||
checked={formData.acceptTerms}
|
||||
onChange={(e) => handleInputChange('acceptTerms')(e.target.checked)}
|
||||
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<label htmlFor="acceptTerms" className="text-sm text-text-secondary cursor-pointer">
|
||||
Acepto los{' '}
|
||||
<a href="#" className="text-color-primary hover:text-color-primary-dark underline">
|
||||
términos y condiciones
|
||||
</a>{' '}
|
||||
de uso
|
||||
</label>
|
||||
</div>
|
||||
{errors.acceptTerms && (
|
||||
<p className="text-color-error text-sm ml-7">{errors.acceptTerms}</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="acceptPrivacy"
|
||||
checked={formData.acceptPrivacy}
|
||||
onChange={(e) => handleInputChange('acceptPrivacy')(e.target.checked)}
|
||||
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<label htmlFor="acceptPrivacy" className="text-sm text-text-secondary cursor-pointer">
|
||||
Acepto la{' '}
|
||||
<a href="#" className="text-color-primary hover:text-color-primary-dark underline">
|
||||
política de privacidad
|
||||
</a>
|
||||
</label>
|
||||
</div>
|
||||
{errors.acceptPrivacy && (
|
||||
<p className="text-color-error text-sm ml-7">{errors.acceptPrivacy}</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-start space-x-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="acceptMarketing"
|
||||
checked={formData.acceptMarketing}
|
||||
onChange={(e) => handleInputChange('acceptMarketing')(e.target.checked)}
|
||||
className="mt-1 h-4 w-4 rounded border-border-primary text-color-primary focus:ring-color-primary focus:ring-offset-0"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<label htmlFor="acceptMarketing" className="text-sm text-text-secondary cursor-pointer">
|
||||
Deseo recibir información sobre nuevas funcionalidades y ofertas especiales
|
||||
<span className="text-text-tertiary"> (opcional)</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Navigation Buttons */}
|
||||
<div className="flex justify-between pt-6 border-t border-border-primary">
|
||||
{currentStep !== 'personal' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handlePreviousStep}
|
||||
disabled={isLoading}
|
||||
className="flex items-center space-x-2"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
<span>Anterior</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
size="lg"
|
||||
isLoading={isLoading}
|
||||
loadingText={currentStep === 'security' ? 'Creando cuenta...' : 'Procesando...'}
|
||||
disabled={isLoading}
|
||||
className="flex items-center space-x-2 min-w-[140px]"
|
||||
>
|
||||
{currentStep === 'security' ? (
|
||||
<>
|
||||
<span>Crear Cuenta</span>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Continuar</span>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-color-error/10 border border-color-error/20 text-color-error px-4 py-3 rounded-lg text-sm flex items-start space-x-3" role="alert">
|
||||
<svg className="w-5 h-5 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clipRule="evenodd" />
|
||||
</svg>
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
) : (
|
||||
/* Verification Step */
|
||||
<div className="text-center space-y-6">
|
||||
<div className="w-20 h-20 bg-color-success/10 rounded-full flex items-center justify-center mx-auto mb-6">
|
||||
<svg className="w-10 h-10 text-color-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<h2 className="text-2xl font-bold text-text-primary mb-4">
|
||||
¡Cuenta creada exitosamente!
|
||||
</h2>
|
||||
|
||||
<div className="bg-background-secondary rounded-lg p-6 max-w-md mx-auto">
|
||||
<p className="text-text-secondary mb-4">
|
||||
Hemos enviado un enlace de verificación a:
|
||||
</p>
|
||||
<p className="text-text-primary font-semibold text-lg mb-4">
|
||||
{formData.email}
|
||||
</p>
|
||||
<p className="text-text-secondary text-sm">
|
||||
Revisa tu bandeja de entrada (y la carpeta de spam) y haz clic en el enlace para activar tu cuenta.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 max-w-md mx-auto">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setCurrentStep('personal');
|
||||
setIsEmailVerificationSent(false);
|
||||
setFormData({
|
||||
full_name: '',
|
||||
email: '',
|
||||
phone: '',
|
||||
tenant_name: '',
|
||||
bakery_type: 'traditional',
|
||||
address: '',
|
||||
city: '',
|
||||
postal_code: '',
|
||||
country: 'España',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
acceptTerms: false,
|
||||
acceptPrivacy: false,
|
||||
acceptMarketing: false
|
||||
});
|
||||
setErrors({});
|
||||
setCompletedSteps(new Set());
|
||||
}}
|
||||
className="w-full"
|
||||
>
|
||||
Registrar otra cuenta
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Login Link */}
|
||||
{onLoginClick && currentStep !== 'verification' && (
|
||||
<div className="mt-8 text-center border-t border-border-primary pt-6">
|
||||
<p className="text-text-secondary mb-4">
|
||||
¿Ya tienes una cuenta?
|
||||
</p>
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={onLoginClick}
|
||||
disabled={isLoading}
|
||||
className="text-color-primary hover:text-color-primary-dark"
|
||||
>
|
||||
Iniciar Sesión
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default RegisterForm;
|
||||
79
frontend/src/components/domain/auth/index.ts
Normal file
79
frontend/src/components/domain/auth/index.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
// Authentication domain components
|
||||
export { default as LoginForm } from './LoginForm';
|
||||
export { default as RegisterForm } from './RegisterForm';
|
||||
export { default as PasswordResetForm } from './PasswordResetForm';
|
||||
export { default as ProfileSettings } from './ProfileSettings';
|
||||
|
||||
// Export named exports as well
|
||||
export { LoginForm } from './LoginForm';
|
||||
export { RegisterForm } from './RegisterForm';
|
||||
export { PasswordResetForm } from './PasswordResetForm';
|
||||
export { ProfileSettings } from './ProfileSettings';
|
||||
|
||||
// Re-export types for convenience
|
||||
export type {
|
||||
LoginFormProps,
|
||||
RegisterFormProps,
|
||||
PasswordResetFormProps,
|
||||
ProfileSettingsProps
|
||||
} from './types';
|
||||
|
||||
// Component metadata for documentation
|
||||
export const authComponents = {
|
||||
LoginForm: {
|
||||
name: 'LoginForm',
|
||||
description: 'Comprehensive login form with email/password validation, remember me, auto-focus, and accessibility features',
|
||||
features: [
|
||||
'Email and password validation',
|
||||
'Remember me functionality',
|
||||
'Auto-focus on email field',
|
||||
'Enter key submission',
|
||||
'Loading states and error handling',
|
||||
'Accessibility (ARIA attributes)',
|
||||
'Spanish localization',
|
||||
'Mobile responsive design'
|
||||
]
|
||||
},
|
||||
RegisterForm: {
|
||||
name: 'RegisterForm',
|
||||
description: 'Multi-step registration form for bakery owners with progress indicator and comprehensive validation',
|
||||
features: [
|
||||
'Multi-step registration (personal, bakery, security, verification)',
|
||||
'Progress indicator with step completion',
|
||||
'Spanish phone and postal code validation',
|
||||
'Comprehensive bakery-specific fields',
|
||||
'Terms and privacy acceptance',
|
||||
'Email verification workflow',
|
||||
'Real-time validation feedback',
|
||||
'Mobile responsive design'
|
||||
]
|
||||
},
|
||||
PasswordResetForm: {
|
||||
name: 'PasswordResetForm',
|
||||
description: 'Dual-mode password reset form with token validation and password strength indicator',
|
||||
features: [
|
||||
'Request reset and set new password modes',
|
||||
'Token validation for reset links',
|
||||
'Password strength indicator',
|
||||
'Enhanced error messaging',
|
||||
'Auto-focus functionality',
|
||||
'Success confirmation screens',
|
||||
'Accessibility features',
|
||||
'Spanish localization'
|
||||
]
|
||||
},
|
||||
ProfileSettings: {
|
||||
name: 'ProfileSettings',
|
||||
description: 'Comprehensive user profile and bakery settings management with image upload',
|
||||
features: [
|
||||
'Tabbed interface (Profile, Security, Preferences, Notifications)',
|
||||
'Profile picture upload with validation',
|
||||
'User profile and bakery information editing',
|
||||
'Password change functionality',
|
||||
'Notification preferences',
|
||||
'Language and timezone settings',
|
||||
'Comprehensive form validation',
|
||||
'Save/cancel with change detection'
|
||||
]
|
||||
}
|
||||
} as const;
|
||||
99
frontend/src/components/domain/auth/types.ts
Normal file
99
frontend/src/components/domain/auth/types.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Authentication component prop types
|
||||
|
||||
export interface LoginFormProps {
|
||||
onSuccess?: () => void;
|
||||
onRegisterClick?: () => void;
|
||||
onForgotPasswordClick?: () => void;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
}
|
||||
|
||||
export interface RegisterFormProps {
|
||||
onSuccess?: () => void;
|
||||
onLoginClick?: () => void;
|
||||
className?: string;
|
||||
showProgressSteps?: boolean;
|
||||
}
|
||||
|
||||
export interface PasswordResetFormProps {
|
||||
token?: string;
|
||||
onSuccess?: () => void;
|
||||
onBackClick?: () => void;
|
||||
className?: string;
|
||||
autoFocus?: boolean;
|
||||
mode?: 'request' | 'reset';
|
||||
}
|
||||
|
||||
export interface ProfileSettingsProps {
|
||||
onSuccess?: () => void;
|
||||
className?: string;
|
||||
initialTab?: 'profile' | 'security' | 'preferences' | 'notifications';
|
||||
}
|
||||
|
||||
// Additional types for internal use
|
||||
export type RegistrationStep = 'personal' | 'bakery' | 'security' | 'verification';
|
||||
|
||||
export interface ExtendedUserLogin {
|
||||
email: string;
|
||||
password: string;
|
||||
remember_me: boolean;
|
||||
}
|
||||
|
||||
export interface ExtendedUserRegistration {
|
||||
// Personal Information
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
|
||||
// Bakery Information
|
||||
tenant_name: string;
|
||||
bakery_type: string;
|
||||
address: string;
|
||||
city: string;
|
||||
postal_code: string;
|
||||
country: string;
|
||||
|
||||
// Security
|
||||
password: string;
|
||||
confirmPassword: string;
|
||||
|
||||
// Terms
|
||||
acceptTerms: boolean;
|
||||
acceptPrivacy: boolean;
|
||||
acceptMarketing: boolean;
|
||||
}
|
||||
|
||||
export interface ProfileFormData {
|
||||
full_name: string;
|
||||
email: string;
|
||||
phone: string;
|
||||
language: string;
|
||||
timezone: string;
|
||||
avatar_url?: string;
|
||||
}
|
||||
|
||||
export interface BakeryFormData {
|
||||
bakery_name: string;
|
||||
bakery_type: string;
|
||||
address: string;
|
||||
city: string;
|
||||
postal_code: string;
|
||||
country: string;
|
||||
website?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export interface NotificationSettings {
|
||||
email_notifications: boolean;
|
||||
order_notifications: boolean;
|
||||
marketing_notifications: boolean;
|
||||
security_notifications: boolean;
|
||||
low_stock_alerts: boolean;
|
||||
production_reminders: boolean;
|
||||
}
|
||||
|
||||
export interface PasswordChangeData {
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
confirmNewPassword: string;
|
||||
}
|
||||
Reference in New Issue
Block a user