All files / src/components/shared/Navigation UserMenuDropdown.tsx

96.77% Statements 30/31
83.33% Branches 10/12
100% Functions 9/9
96.77% Lines 30/31

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                                                                  10x               147x 147x   147x 1x 1x     147x 1x 1x     147x 1x 1x     147x 1x 1x     147x 1x 1x     147x 2x     2x 2x 2x     2x 2x 2x             2x     147x                                     147x                                                                                                 784x                                                                
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  Menu,
  MenuItem,
  Divider,
  Box,
  Typography,
  Select,
  SelectChangeEvent,
  ListItemIcon,
  ListItemText,
} from '@mui/material';
import PersonIcon from '@mui/icons-material/Person';
import SettingsIcon from '@mui/icons-material/Settings';
import HelpIcon from '@mui/icons-material/Help';
import LogoutIcon from '@mui/icons-material/Logout';
import LanguageIcon from '@mui/icons-material/Language';
import AdminPanelSettingsIcon from '@mui/icons-material/AdminPanelSettings';
import { UserContext } from '../../../types/auth';
import { updateUserPreferences } from '../../../services/api/userApi';
import type { UpdatePreferencesRequest } from '../../../types/user';
 
interface UserMenuDropdownProps {
  user: UserContext;
  anchorEl: HTMLElement | null;
  open: boolean;
  onClose: () => void;
  onLogout: () => void;
  onLanguageChange: (language: string) => void;
}
 
const UserMenuDropdown: React.FC<UserMenuDropdownProps> = ({
  user,
  anchorEl,
  open,
  onClose,
  onLogout,
  onLanguageChange,
}) => {
  const navigate = useNavigate();
  const { t, i18n } = useTranslation();
 
  const handleProfileClick = () => {
    navigate('/account/profile');
    onClose();
  };
 
  const handleAdministrationClick = () => {
    navigate('/organizer/admin');
    onClose();
  };
 
  const handleSettingsClick = () => {
    navigate('/account/settings');
    onClose();
  };
 
  const handleHelpClick = () => {
    navigate('/help');
    onClose();
  };
 
  const handleLogoutClick = () => {
    onLogout();
    onClose();
  };
 
  const handleLanguageChange = async (event: SelectChangeEvent<string>) => {
    const newLang = event.target.value;
 
    // Update i18n
    await i18n.changeLanguage(newLang);
    document.documentElement.lang = newLang;
    localStorage.setItem('batbern-language', newLang);
 
    // Persist to API (backend is ready, Story 2.6)
    try {
      await updateUserPreferences({ language: newLang as UpdatePreferencesRequest['language'] });
      console.log('[UserMenuDropdown] Language preference persisted to backend:', newLang);
    } catch (error) {
      console.error('[UserMenuDropdown] Failed to persist language preference:', error);
      // Continue anyway - localStorage update was successful
    }
 
    // Notify parent
    onLanguageChange(newLang);
  };
 
  return (
    <Menu
      anchorEl={anchorEl}
      open={open}
      onClose={onClose}
      role="menu"
      aria-label={t('navigation.userMenu')}
      MenuListProps={{
        'aria-labelledby': 'user-menu-button',
      }}
    >
      {/* User Info Section */}
      <Box sx={{ px: 2, py: 1 }}>
        <Typography variant="body2" fontWeight="medium">
          {user.email}
        </Typography>
        <Typography variant="caption" color="text.secondary" data-testid="user-menu-roles">
          {/* Story 11.E.3 (cherry-pick 73d94688 + 396a9045): list every role the user holds,
              null-safe in case a legacy auth shape predates the multi-role array. */}
          {(user.roles ?? (user.role ? [user.role] : [])).map((r) => t(`role.${r}`)).join(', ')}
        </Typography>
      </Box>
 
      <Divider />
 
      {/* Profile Menu Item */}
      <MenuItem onClick={handleProfileClick} role="menuitem" data-testid="my-account-link">
        <ListItemIcon>
          <PersonIcon fontSize="small" />
        </ListItemIcon>
        <ListItemText>{t('menu.profile')}</ListItemText>
      </MenuItem>
 
      {/* Settings Menu Item */}
      <MenuItem onClick={handleSettingsClick} role="menuitem">
        <ListItemIcon>
          <SettingsIcon fontSize="small" />
        </ListItemIcon>
        <ListItemText>{t('menu.settings')}</ListItemText>
      </MenuItem>
 
      {/* Administration Menu Item - organizer only (Story 10.1; Story 11.E.3 multi-role aware) */}
      {(user.roles ?? (user.role ? [user.role] : [])).includes('organizer') && (
        <MenuItem
          onClick={handleAdministrationClick}
          role="menuitem"
          data-testid="administration-link"
        >
          <ListItemIcon>
            <AdminPanelSettingsIcon fontSize="small" />
          </ListItemIcon>
          <ListItemText>{t('menu.administration')}</ListItemText>
        </MenuItem>
      )}
 
      {/* Language Switcher */}
      <Box sx={{ px: 2, py: 1.5 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <LanguageIcon fontSize="small" />
          <Select
            value={i18n.language}
            onChange={handleLanguageChange}
            size="small"
            sx={{ minWidth: 160 }}
            aria-label={t('language.select')}
            data-testid="language-select"
          >
            {Object.keys(i18n.options?.resources ?? {}).map((code) => (
              <MenuItem key={code} value={code} data-testid={`language-option-${code}`}>
                {code.toUpperCase()} — {t(`language.${code}`)}
              </MenuItem>
            ))}
          </Select>
        </Box>
      </Box>
 
      <Divider />
 
      {/* Help Menu Item */}
      <MenuItem onClick={handleHelpClick} role="menuitem">
        <ListItemIcon>
          <HelpIcon fontSize="small" />
        </ListItemIcon>
        <ListItemText>{t('menu.help')}</ListItemText>
      </MenuItem>
 
      <Divider />
 
      {/* Logout Menu Item */}
      <MenuItem onClick={handleLogoutClick} role="menuitem">
        <ListItemIcon>
          <LogoutIcon fontSize="small" />
        </ListItemIcon>
        <ListItemText>{t('menu.logout')}</ListItemText>
      </MenuItem>
    </Menu>
  );
};
 
export default UserMenuDropdown;