All files / src/components/EmailSection EmailSection.tsx

100% Statements 59/59
100% Branches 32/32
100% Functions 10/10
100% Lines 56/56

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                                                      62x 62x 62x 62x   62x 62x 62x   62x 62x 62x   62x   62x 12x 12x 12x     62x 12x 1x 1x 1x 1x   12x     62x 8x 8x 8x   8x 1x 1x     7x 1x 1x     6x 1x 1x     5x 5x 5x   2x 1x 1x   1x     3x 2x 2x 1x   1x     1x     5x       62x                                             10x 3x               1x 1x 1x 1x                                                  
import Accordion from "@mui/material/Accordion";
import AccordionDetails from "@mui/material/AccordionDetails";
import AccordionSummary from "@mui/material/AccordionSummary";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import CircularProgress from "@mui/material/CircularProgress";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useEffect, useState, type JSX } from "react";
import { useTranslation } from "react-i18next";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { useAuthStore } from "../../stores/useAuthStore";
import { isEmailValid } from '../../utils/validation';
import { useNavigate } from "react-router-dom";
import { updateUserEmail } from "../../services/userService";
import axios from "axios";
import { getErrorMessage } from "../../utils/errorUtils";
import AlertMessage from "../AlertMessage";
import { useLanguageStore } from "../../stores/useLanguageStore";
 
interface EmailSectionProps {
  currentEmail: string;
  onUpdate: (newEmail: string) => void;
}
 
export function EmailSection({ currentEmail, onUpdate }: EmailSectionProps): JSX.Element {
  const { t } = useTranslation('userDashboard');
  const token = useAuthStore((state) => state.authToken);
  const navigate = useNavigate();
  const lang = useLanguageStore(state => state.lang);
 
  const [expanded, setExpanded] = useState<boolean>(false);
  const [newEmail, setNewEmail] = useState<string>(currentEmail);
  const [newEmailTouched, setNewEmailTouched] = useState(false);
  
  const [loading, setLoading] = useState<boolean>(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
 
  const emailError = newEmailTouched && !isEmailValid(newEmail);
 
  useEffect(() => {
    setNewEmail(currentEmail);
    setNewEmailTouched(false);
    setErrorMsg(null);
  }, [currentEmail]);
 
  const handleAccordionChange = () => {
    if (expanded) {
      setErrorMsg(null);
      setSuccessMsg(null);
      setNewEmailTouched(false);
      setNewEmail(currentEmail);
    }
    setExpanded(prev => !prev);
  };
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);
 
    if (!isEmailValid(newEmail)) {
      setErrorMsg(t('errors.emailRequired'));
      return;
    }
 
    if (newEmail === currentEmail) {
      setErrorMsg(t('errors.emailUnchanged'));
      return;
    }
 
    if (!token) {
      navigate('/login', { replace: true });
      return;
    }
 
    setLoading(true);
    try {
      const { status } = await updateUserEmail(token, newEmail, lang);
 
      if (status === 204 || status === 200) {
        onUpdate(newEmail);
        setSuccessMsg(t('dashboard.successMessageEmailUpdate'));
      } else {
        setErrorMsg(t('errors.emailUpdate'));
      }
    } catch (err: any) {
      if (axios.isAxiosError(err) && err.response) {
        const { data } = err.response;
        if (data.code) {
          setErrorMsg(getErrorMessage(t, data.code));
        } else {
          setErrorMsg(getErrorMessage(t, 'generic_error'));
        }
      } else {
        setErrorMsg(getErrorMessage(t, 'network_error'));
      }
    } finally {
      setLoading(false);
    }
  };
 
  return (
    <Accordion expanded={expanded} onChange={handleAccordionChange}>
      <AccordionSummary expandIcon={<ExpandMoreIcon />}> 
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', gap: { xs: 1, sm: 0 } }}>
          <Typography sx={{ fontSize: { xs: '0.85rem', sm: '1.2rem' } }}>
            {t('dashboard.email')}
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ fontSize: { xs: '0.8rem', sm: '1rem' } }}>
            {currentEmail}
          </Typography>
        </Box>
      </AccordionSummary>
      <AccordionDetails>
        <Stack component="form" onSubmit={handleSubmit} spacing={2} sx={{ width: '100%' }}>
          {errorMsg && <AlertMessage message={errorMsg} severity="error" />}
          {successMsg && <AlertMessage message={successMsg} severity="success" />}
          <TextField
            required
            fullWidth
            id="email"
            label={t('dashboard.email')}
            type="email"
            value={newEmail}
            onChange={(e) => setNewEmail(e.target.value)}
            onBlur={() => setNewEmailTouched(true)}
            autoComplete="email"
            error={emailError}
            helperText={emailError ? t('errors.emailInvalid') : ''}
          />
          <Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
            <Button 
              onClick={() => { 
                setNewEmail(currentEmail); 
                setNewEmailTouched(false);
                setErrorMsg(null);
                setSuccessMsg(null); 
              }} 
              disabled={loading}
            >
              {t('dashboard.cancel')}
            </Button>
            <Button
              type="submit"
              variant="contained"
              disabled={loading || !isEmailValid(newEmail)}
              startIcon={
                loading
                  ? <CircularProgress color="inherit" size={16} />
                  : undefined
              }
            >
              {loading
                ? `${t('dashboard.saveLoad')}…`
                : t('dashboard.save')}
            </Button>
          </Box>
        </Stack>
      </AccordionDetails>
    </Accordion>
  );
}