All files / components/connexion RegisterClientForm.tsx

77.41% Statements 48/62
67.85% Branches 19/28
60% Functions 6/10
77.04% Lines 47/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260                                                                                1x 1x 1x 1x 1x           1x   35x             35x 35x 35x 35x 35x 35x 35x   35x 20x 20x     35x               35x 1x 1x 1x 1x 2x 2x   1x         35x 3x 3x       3x 3x             3x 3x 3x     3x 3x 2x 2x 2x 2x           1x 1x 1x 1x   3x       35x                                                                                                                                           3x                                                                                                                  
/**
 * @module components/connexion/RegisterClientForm
 * Module de composant RegisterClientForm pour l'inscription des nouveaux utilisateurs
 *
 * Ce module contient le composant RegisterClientForm qui gère le processus d'inscription
 * des nouveaux utilisateurs de l'application. Il offre un formulaire complet avec
 * validation côté client, gestion d'erreurs avancée et intégration avec l'API backend.
 *
 * ## Fonctionnalités principales
 * - Formulaire d'inscription avec 5 champs obligatoires
 * - Validation côté client avec messages d'erreur détaillés
 * - Gestion des états de chargement et protection anti-spam
 * - Acceptation des conditions d'utilisation
 * - Notifications de succès/erreur avec composant dédié
 * - Redirection automatique vers la connexion après succès
 *
 * ## Champs du formulaire
 * - **Nom** : Nom de famille de l'utilisateur
 * - **Prénom** : Prénom de l'utilisateur
 * - **Téléphone** : Numéro de téléphone avec validation
 * - **Email** : Adresse email avec validation format
 * - **Mot de passe** : Mot de passe sécurisé
 * - **CGU** : Acceptation des conditions générales (checkbox)
 *
 * ## Validation et sécurité
 * - Validation côté client avant soumission
 * - Protection contre les soumissions multiples
 * - Gestion détaillée des erreurs API avec parsing
 * - Autocomplétion des champs pour UX optimisée
 *
 * ## Intégration
 * - Appel à l'API registerClient pour inscription
 * - Utilise validateClientForm pour validation
 * - Basculement vers connexion après inscription réussie
 *
 * @group Components
 */
 
'use client';
 
import { useState, useCallback, useRef } from 'react';
import { registerClient } from '@/lib/api/auth/authService';
import Notification from '../common/Notification';
import Spinner from '../common/Spinner';
import { validateClientForm } from '@/utils/validateForms';
 
type Props = {
  onClick?: () => void;
}
 
export default function RegisterClientForm({onClick}: Props) {
    
    const [formData, setFormData] = useState({
        email: '',
        password: '',
        nom: '',
        prenom: '',
        telephone: '',
    });
    const [error, setError] = useState<string | null>(null);
    const [successMessage, setSuccessMessage] = useState<string | null>(null);
    const [acceptTerms, setAcceptTerms] = useState(false);
    const [showNotification, setShowNotification] = useState(false);
    const [notificationType, setNotificationType] = useState<'error' | 'success'>('error');
    const [isLoading, setIsLoading] = useState(false);
    const submitTimeoutRef = useRef<NodeJS.Timeout | null>(null);
 
    const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    }, []);
 
    const handleCloseNotification = useCallback(() => {
        requestAnimationFrame(() => {
            setShowNotification(false);
            setError(null);
            setSuccessMessage(null);
        });
    }, []);
 
    const processError = useCallback((err: unknown) => {
        if (err && typeof err === 'object' && 'data' in err) {
            const errorData = (err as { data: Record<string, string | string[]> }).data;
            const errorMessages = [];
            for (const [field, messages] of Object.entries(errorData)) {
                const message = Array.isArray(messages) ? messages.join(', ') : messages;
                errorMessages.push(`${field}: ${message}`);
            }
            return errorMessages.join(' | ');
        }
        return err instanceof Error ? err.message : 'Erreur inconnue';
    }, []);
 
    const handleSubmit = useCallback(async (e: React.FormEvent) => {
        e.preventDefault();
        Iif (submitTimeoutRef.current || isLoading) {
            return;
        }
        
        const validationErrors = validateClientForm({ ...formData, acceptTerms });
        Iif (Object.keys(validationErrors).length > 0) {
            const firstErrorKey = Object.keys(validationErrors)[0] as keyof typeof validationErrors;
            setError(validationErrors[firstErrorKey] || 'Erreur de validation');
            setNotificationType('error');
            setShowNotification(true);
            return;
        }
        setError(null);
        setIsLoading(true);
        submitTimeoutRef.current = setTimeout(() => {
            submitTimeoutRef.current = null;
        }, 1000);
        try {
            await registerClient(formData);
            setSuccessMessage('Inscription réussie ! Vous pouvez maintenant vous connecter.');
            setNotificationType('success');
            setShowNotification(true);
            setTimeout(() => {
                Iif (onClick) {
                    onClick();
                }
            }, 2000);
        } catch (err: unknown) {
            const errorMessage = processError(err);
            setError(errorMessage);
            setNotificationType('error');
            setShowNotification(true);
        } finally {
            setIsLoading(false);
        }
    }, [formData, acceptTerms, processError, isLoading, onClick]);
 
    return (
        <>
            <div className='flex flex-col items-center justify-between p-[10%] h-full'>
                <h2 className="text-3xl font-bold text-black mt-3">INSCRIPTION</h2>
                <form onSubmit={handleSubmit} className="gap-4 p-4 flex items-center flex-col w-full">
 
                    <div className="w-full flex flex-col mb-2">
                        <input 
                            name="nom" 
                            type="text"
                            placeholder="Nom" 
                            value={formData.nom} 
                            onChange={handleChange} 
                            required 
                            autoComplete='family-name'
                            className="w-full border-0 border-b border-black/20 text-black p-2 placeholder-gray-400"
                        />
                    </div>
                    <div className="w-full flex flex-col mb-2">
                        <input 
                            name="prenom" 
                            type="text"
                            placeholder="Prénom" 
                            value={formData.prenom} 
                            onChange={handleChange} 
                            required
                            autoComplete='given-name'
                            className="w-full border-0 border-b border-black/20 text-black p-2 placeholder-gray-400"
                        />
                    </div>
                    <div className="w-full flex flex-col mb-2">
                        <input 
                            name="telephone" 
                            type="tel"
                            placeholder="Téléphone" 
                            value={formData.telephone} 
                            onChange={handleChange} 
                            required 
                            autoComplete='tel'
                            className="w-full border-0 border-b border-black/20 text-black p-2 placeholder-gray-400"
                        />
                    </div><div className="w-full flex flex-col mb-2">
                        <input
                            name="email"
                            type="email"
                            placeholder="Email"
                            value={formData.email}
                            onChange={handleChange}
                            required
                            autoComplete='email'
                            className="w-full border-0 border-b border-black/20 text-black p-2 placeholder-gray-400"
                        />
                    </div>
                    <div className="w-full flex flex-col mb-2">
                        <input
                            name="password"
                            type="password"
                            placeholder="Mot de passe"
                            value={formData.password}
                            onChange={handleChange}
                            required
                            autoComplete='new-password'
                            className="w-full border-0 border-b border-black/20 text-black p-2 placeholder-gray-400"
                        />
                    </div>
                    <div className="w-full flex items-start gap-2 mb-4">
                        <input 
                            type="checkbox"
                            id="acceptTerms"
                            checked={acceptTerms}
                            onChange={(e) => setAcceptTerms(e.target.checked)}
                            required
                            className="mt-1 w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                        />
                        <label htmlFor="acceptTerms" className="text-sm text-black">
                            J&apos;accepte les{' '}
                            <button 
                                type="button" 
                                className="text-blue-600 underline hover:text-blue-800"
                            >
                                Conditions Générales d&apos;Utilisation
                            </button>
                            {' '}et la{' '}
                            <button 
                                type="button" 
                                className="text-blue-600 underline hover:text-blue-800"
                            >
                                Politique de Confidentialité
                            </button>
                        </label>
                    </div>
                    <button 
                        type="submit" 
                        disabled={isLoading}
                        className={`bg-blue-600 text-white px-4 py-2 rounded flex items-center justify-center gap-2 min-w-[120px] ${isLoading ? 'opacity-75 cursor-not-allowed' : 'hover:bg-blue-700'}`}
                    >
                        {isLoading ? (
                            <>
                                <Spinner size="small" color="white" />
                                Inscription...
                            </>
                        ) : (
                            "S'inscrire"
                        )}
                    </button>
                </form>
                {onClick && (
                    <div className='flex justify-center items-center gap-2 mt-4 mb-6 text-black'>
                        <span>Déjà un compte?</span>
                        <button onClick={onClick}
                            className="font-bold underline"
                        >
                            Se connecter
                        </button>
                    </div>
                )}
            </div>
            {(showNotification && (error || successMessage)) && (
                <Notification 
                    message={error || successMessage || ''} 
                    type={notificationType} 
                    onCloseAction={handleCloseNotification}
                />
            )}
        </>
    );
}