All files / src/pages UserDashboardPage.tsx

100% Statements 50/50
100% Branches 24/24
100% Functions 12/12
100% Lines 44/44

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                                                      34x 34x     34x 34x 34x   34x   27x 4x 4x 4x     23x 23x   23x 23x 23x 23x   23x 14x 8x 8x 4x             4x     9x 8x 4x 4x 4x   4x     23x 16x       23x 23x 23x       34x 20x                   14x 8x               1x                 6x 4x     2x                       1x 1x   1x              
import { useState, useEffect, type JSX } from 'react';
import { useTranslation } from 'react-i18next';
import Seo from '../components/Seo';
import { PageWrapper } from '../components/PageWrapper';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import axios from 'axios';
import { fetchUser } from '../services/userService';
import { useAuthStore } from '../stores/useAuthStore';
import { getErrorMessage } from '../utils/errorUtils';
import OlympicLoader from './../components/OlympicLoader';
import { Navigate } from 'react-router-dom';
import { ErrorDisplay } from '../components/ErrorDisplay';
import { NameSection } from '../components/NameSection';
import { EmailSection } from '../components/EmailSection';
import { PasswordSection } from '../components/PasswordSection';
import { TwoFASection } from '../components/TwoFASection';
 
export interface UserProfile {
  firstname: string;
  lastname: string;
  email: string;
  twoFAEnabled: boolean;
}
 
export default function UserDashboardPage(): JSX.Element {
  const { t } = useTranslation('userDashboard');
  const token = useAuthStore((state) => state.authToken);
 
  // États initiaux: charger les données utilisateur existantes
  const [user, setUser] = useState<UserProfile | null>(null);
  const [loadingUser, setLoadingUser] = useState<boolean>(true);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
 
  useEffect(() => {
    // Si pas de token, on réinitialise et on stoppe le chargement
    if (!token) {
      setUser(null);
      setLoadingUser(false);
      return;
    }
 
    const controller = new AbortController();
    const signal = controller.signal;
 
    const loadUser = async () => {
      setLoadingUser(true);
      setErrorMsg(null);
      try {
        // Passer le signal à fetchUser afin que la requête puisse être annulée
        const response = await fetchUser(token, { signal });
        if (signal.aborted) return;
        const { status, data } = response;
        if (status === 200 && data.user) {
          setUser({
            firstname: data.user.firstname,
            lastname: data.user.lastname,
            email: data.user.email,
            twoFAEnabled: data.user.twofa_enabled,
          });
        } else {
          setErrorMsg(t('errors.fetchProfile'));
        }
      } catch (err: any) {
        if (signal.aborted) return;
        if (axios.isAxiosError(err) && err.response) {
          const respData = err.response.data;
          const code = respData?.code;
          setErrorMsg(getErrorMessage(t, code ?? 'generic_error'));
        } else {
          setErrorMsg(getErrorMessage(t, 'network_error'));
        }
      } finally {
        if (!signal.aborted) {
          setLoadingUser(false);
        }
      }
    };
    loadUser();
    return () => {
      controller.abort();
    };
  }, [token, t]);
 
  if (loadingUser) {
    return (
      <>
        <Seo title={t('seo.title')} description={t('seo.description')} />
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <OlympicLoader />
        </Box>
      </>
    );
  }
 
  if (errorMsg) {
    return (
      <PageWrapper>
        <ErrorDisplay
          title={t('errors.genericErrorTitle')}
          message={errorMsg}
          showRetry={true}
          retryButtonText={t('errors.retry')}
          onRetry={() => {
            window.location.reload();
          }}
          showHome={true}
          homeButtonText={t('errors.home')}
        />
      </PageWrapper>
    );
  }
 
  if (!user) {
    return <Navigate to="/login" replace />;
  }
 
  return (
    <>
      <Seo title={t('seo.title')} description={t('seo.description')} />
      <PageWrapper>
        <Box sx={{ maxWidth: 600, mx: 'auto', mt: 4, mb: 4 }}>
          <Typography variant="h4" gutterBottom align="center">
            {t('dashboard.title')}
          </Typography>
          <Typography variant="body1" gutterBottom align="center" sx={{ mb: 4 }}>
            {t('dashboard.subtitle')}
          </Typography>
          <Stack spacing={2}>
            <NameSection user={user} onUpdate={(vals) => setUser(prev => ({ ...prev!, ...vals }))}/>
            <EmailSection currentEmail={user.email} onUpdate={(newEmail) => setUser(prev => ({ ...prev!, email: newEmail }))}/>
            <PasswordSection />
            <TwoFASection enabled={user.twoFAEnabled} onToggle={(enabled) => setUser(prev => ({ ...prev!, twoFAEnabled: enabled }))} />
          </Stack>
        </Box>
      </PageWrapper>
    </>
  );
}