All files / src/pages SignupPage.tsx

100% Statements 79/79
100% Branches 66/66
100% Functions 14/14
100% Lines 78/78

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314                                                      88x 88x 88x 88x 88x 88x     88x 88x 88x 88x 88x 88x 88x 88x 88x 88x             88x     88x 88x     88x 88x 88x   88x 15x 15x 15x     15x 1x 1x   14x 1x 1x   13x 1x 1x   12x 1x 1x     11x 11x 11x                         3x 2x   2x     8x 8x 8x   8x 7x     7x 1x 1x     6x 1x 1x     5x 3x 3x 3x 1x   2x   3x     2x 1x   1x     1x         88x                             88x                                                                         1x 1x                     1x 1x                       1x 1x                     1x               16x                                             1x 1x                                                                                            
import React, { useState, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import Seo from '../components/Seo';
import { PageWrapper } from '../components/PageWrapper';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
import logoImg from '../assets/logos/jo_logo.png';
import ReCAPTCHA from 'react-google-recaptcha';
import { registerUser } from '../services/authService';
import AlertMessage from '../components/AlertMessage';
import { getErrorMessage } from '../utils/errorUtils';
import { RECAPTCHA_SITE_KEY } from '../config'
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { useLanguageStore } from '../stores/useLanguageStore';
import axios from 'axios';
import { useSignupValidation } from '../hooks/useSignupValidation';
import PasswordWithConfirmation from '../components/PasswordWithConfirmation';
import CircularProgress from '@mui/material/CircularProgress';
 
export default function SignupPage() {
  const { t } = useTranslation('signup');
  const lang = useLanguageStore(state => state.lang);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const isDarkMode = theme.palette.mode === 'dark';
  const widgetKey = `${lang}-${isDarkMode ? 'dark' : 'light'}-${isMobile ? 'compact' : 'normal'}`;
 
  // états champs
  const [firstname, setFirstname] = useState('');
  const [lastname, setLastname] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [acceptTerms, setAcceptTerms] = useState(false);
  const [firstnameTouched, setFirstnameTouched] = useState(false);
  const [lastnameTouched, setLastnameTouched]   = useState(false);
  const [emailTouched, setEmailTouched]         = useState(false);
  const [pwdTouched, setPwdTouched]      = useState(false);
 
  // validation front
  const {
    firstnameError, lastnameError, emailError,
    pwStrong, pwsMatch,
    isFirstnameValid, isLastnameValid, isEmailValid
  } = useSignupValidation({firstname, lastname, email, password, confirmPassword, firstnameTouched, lastnameTouched, emailTouched});
 
  // état captcha
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const captchaRef = useRef<ReCAPTCHA>(null);
 
  // états UI
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);
 
    // validations front
    if (!pwStrong) {
      setErrorMsg(t('errors.passwordNotStrong')); 
      return;
    }
    if (!pwsMatch) {
      setErrorMsg(t('errors.passwordsDontMatch'));
      return;
    }
    if (!acceptTerms) {
      setErrorMsg(t('errors.mustAgreeTOS'));
      return;
    }
    if (!captchaToken) {
      setErrorMsg(t('errors.captchaRequired'));
      return;
    }
 
    setLoading(true);
    try {
      const { status } = await registerUser(
        {
          firstname,
          lastname,
          email,
          password,
          password_confirmation: confirmPassword,
          captcha_token: captchaToken,
          accept_terms: acceptTerms,
        },
        lang
      );
 
      if (status === 201) {
        setSuccessMsg(t('signup.successMessage'));
        // reset captcha pour éviter double envoi
        captchaRef.current?.reset();
      }
    } catch (err: any) {
      setLoading(false);
      captchaRef.current?.reset();
      setCaptchaToken(null);
 
      if (axios.isAxiosError(err) && err.response) {
        const { status, data } = err.response;
 
        // cas trop de requêtes
        if (status === 429) {
          setErrorMsg(getErrorMessage(t, 'too_many_requests'));
          return;
        }
        // cas erreur serveur
        if (status === 500) {
          setErrorMsg(getErrorMessage(t, 'internal_error'));
          return;
        }
        // cas validation back inattendu (shouldn’t arriver en normal)
        if (status === 422 && data.code === 'validation_error') {
          const emailErrors: string[] = data.errors?.email || [];
          setErrorMsg(getErrorMessage(t, data.code));
          if (emailErrors.includes('validation.unique')) {
            setErrorMsg(getErrorMessage(t, 'email_already_registered'));
          } else {
            setErrorMsg(getErrorMessage(t, 'validation_error'));
          }
          return;
        }
        // toutes les autres erreurs métiers
        if (data.code) {
          setErrorMsg(getErrorMessage(t, data.code));
        } else {
          setErrorMsg(getErrorMessage(t, 'generic_error'));
        }
      } else {
        setErrorMsg(getErrorMessage(t, 'network_error'));
      }
    }
  }
 
  return (
    <>
      <Seo title={t('seo.title')} description={t('seo.description')} />
      <PageWrapper disableCard>
        <Box
          component="form"
          onSubmit={handleSubmit}
          sx={{
            maxWidth: 400,
            mx: 'auto',
            mt: { xs: 0, sm: 1, md: 1 },
            p: 4,
            borderRadius: 2,
            boxShadow: 3,
            backgroundColor: 'background.paper',
            border: (theme) => `1px solid ${theme.palette.divider}`,
          }}
        >
          {/* Logo */}
          <Box sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
            <Box
              component="img"
              src={logoImg}
              alt={t('signup.logoAlt')}
              sx={{ height: 150, width: 'auto' }}
            />
          </Box>
 
          <Typography variant="h4" gutterBottom align="center">
            {t('signup.pageTitle')}
          </Typography>
 
          {/* Messages */}
          {errorMsg && <AlertMessage message={errorMsg} severity="error" />}
          {successMsg && (
            <>
              <AlertMessage message={successMsg} severity="success" />
              <Box sx={{ textAlign: 'center', my: 2 }}>
                <Button component={Link} href="/login" variant="outlined">
                  {t('signup.goToLogin')}
                </Button>
              </Box>
            </>
          )}
 
          <Stack spacing={2}>
            <TextField
              required
              fullWidth
              id="firstname"
              label={t('signup.firstnameLabel')}
              value={firstname}
              onChange={(e) => setFirstname(e.target.value)}
              onBlur={() => setFirstnameTouched(true)}
              autoComplete="given-name"
              error={firstnameError}
              helperText={firstnameError ? t('errors.firstnameRequired') : ''}
            />
            <TextField
              required
              fullWidth
              id="lastname"
              label={t('signup.lastnameLabel')}
              value={lastname}
              onChange={(e) => setLastname(e.target.value)}
              onBlur={() => setLastnameTouched(true)}
              autoComplete="family-name"
              error={lastnameError}
              helperText={lastnameError ? t('errors.lastnameRequired') : ''}
            />
            <TextField
              required
              fullWidth
              id="email"
              label={t('signup.emailLabel')}
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onBlur={() => setEmailTouched(true)}
              autoComplete="email"
              error={emailError}
              helperText={emailError ? t('errors.invalidEmail') : ''}
            />
            <PasswordWithConfirmation
              password={password}
              onPasswordChange={setPassword}
              confirmPassword={confirmPassword}
              onConfirmChange={setConfirmPassword}
              touched={pwdTouched}
              onBlur={() => setPwdTouched(true)}
            />
 
            {/* Accept Terms */}
            <FormControlLabel
              control={
                <Checkbox
                  checked={acceptTerms}
                  onChange={(e) => setAcceptTerms(e.target.checked)}
                />
              }
              label={
                <Typography variant="body2" sx={{ fontSize: '0.875rem' }}>
                  {t('signup.agreeTOS')}{' '}
                  <Link href="/privacy-policy" target="_blank" underline="hover">
                    {t('signup.termsLink')}
                  </Link>
                </Typography>
              }
            />
 
            {/* ReCAPTCHA */}
            <Box sx={{ display: 'flex', justifyContent: 'center', mt: 1 }}>
              <ReCAPTCHA
                key={widgetKey}
                ref={captchaRef}
                sitekey={RECAPTCHA_SITE_KEY}
                size={isMobile ? 'compact' : 'normal'}
                theme={isDarkMode ? 'dark' : 'light'} 
                hl={lang}
                onChange={setCaptchaToken}
                onExpired={() => setCaptchaToken(null)}
                onErrored={() => setCaptchaToken(null)}
              />
            </Box>
 
            <Button
              type="submit"
              variant="contained"
              fullWidth
              disabled={loading || !captchaToken || !acceptTerms || !pwsMatch || !pwStrong || !isFirstnameValid || !isLastnameValid || !isEmailValid}
              sx={{ mt: 2 }}
              startIcon={
                loading
                  ? <CircularProgress color="inherit" size={16} />
                  : undefined
              }
            >
              {loading
                ? `${t('signup.signupButtonLoad')}…`
                : t('signup.signupButton')}
            </Button>
 
            {!loading && (!captchaToken || !acceptTerms) && (
              <Typography
                variant="caption"
                color="text.secondary"
                sx={{ display: 'block', mt: 1, textAlign: 'center' }}
              >
                {!captchaToken && t('signup.hintCaptchaRequired')}
                {!acceptTerms && t('signup.hintMustAgreeTOS')}
              </Typography>
            )}
 
            <Box sx={{ mt: 1, textAlign: 'center' }}>
              <Typography variant="body2" sx={{ fontSize: '0.8rem' }}>
                {t('signup.alreadyHaveAccount')}{' '}
                <Link href="/login" underline="hover" variant="body2">
                  {t('signup.loginLink')}
                </Link>
              </Typography>
            </Box>
          </Stack>
        </Box>
      </PageWrapper>
    </>
  );
}