All files / src/components/organizer/UserManagement RoleManagerModal.tsx

88.88% Statements 32/36
72.72% Branches 16/22
100% Functions 8/8
93.93% Lines 31/33

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                                                        1x 18x 18x 18x   18x 18x     18x 8x 7x 7x       18x 2x 2x 2x 1x   1x         2x         18x   2x 1x 1x     1x   1x 1x         1x 2x             18x             18x   18x                                                                                     72x             2x                                                                                    
import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  FormGroup,
  FormControlLabel,
  Checkbox,
  Box,
  Typography,
  IconButton,
  Alert,
} from '@mui/material';
import { Close as CloseIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import { useUpdateUserRoles } from '../../../hooks/useUserManagement';
import type { User, Role } from '../../../types/user.types';
 
interface RoleManagerModalProps {
  user: User | null;
  open: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}
 
const RoleManagerModal: React.FC<RoleManagerModalProps> = ({ user, open, onClose, onSuccess }) => {
  const { t } = useTranslation('userManagement');
  const { isMobile } = useBreakpoints();
  const updateRolesMutation = useUpdateUserRoles();
 
  const [selectedRoles, setSelectedRoles] = useState<Role[]>([]);
  const [error, setError] = useState<string>('');
 
  // Initialize selected roles when modal opens or user changes
  useEffect(() => {
    if (open && user) {
      setSelectedRoles(user.roles as Role[]);
      setError('');
    }
  }, [open, user]);
 
  const handleRoleToggle = (role: Role) => {
    setSelectedRoles((prev) => {
      const isSelected = prev.includes(role);
      if (isSelected) {
        return prev.filter((r) => r !== role);
      } else {
        return [...prev, role];
      }
    });
 
    // Clear error when user makes changes
    Iif (error) {
      setError('');
    }
  };
 
  const handleSave = async () => {
    // Validation: At least one role must be selected
    if (selectedRoles.length === 0) {
      setError(t('error.minOneRole') || 'At least one role must be selected');
      return;
    }
 
    Iif (!user) return;
 
    try {
      await updateRolesMutation.mutateAsync({
        id: user.id,
        roles: selectedRoles,
      });
 
      onSuccess?.();
      onClose();
    } catch (error) {
      console.error('Failed to update user roles:', error);
      // Error is handled by React Query mutation error state
    }
  };
 
  const roleOptions: { value: Role; label: string }[] = [
    { value: 'ORGANIZER', label: t('common:role.organizer') },
    { value: 'SPEAKER', label: t('common:role.speaker') },
    { value: 'PARTNER', label: t('common:role.partner') },
    { value: 'ATTENDEE', label: t('common:role.attendee') },
  ];
 
  Iif (!user) return null;
 
  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      fullScreen={isMobile}
      aria-labelledby="role-manager-dialog-title"
      data-testid="role-manager-dialog"
    >
      <DialogTitle id="role-manager-dialog-title">
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h6">{t('modal.editRoles.title')}</Typography>
          <IconButton
            edge="end"
            color="inherit"
            onClick={onClose}
            aria-label={t('common:actions.close')}
          >
            <CloseIcon />
          </IconButton>
        </Box>
      </DialogTitle>
 
      <DialogContent dividers>
        <Box sx={{ mb: 2 }}>
          <Typography variant="body1" gutterBottom>
            {t('modal.editRoles.user')}:{' '}
            <strong>
              {user.firstName} {user.lastName}
            </strong>
          </Typography>
          <Typography variant="body2" color="text.secondary">
            {user.email}
          </Typography>
        </Box>
 
        <Typography variant="subtitle2" gutterBottom>
          {t('modal.editRoles.selectRoles')}:
        </Typography>
 
        <FormGroup data-testid="role-manager-checkboxes">
          {roleOptions.map((role) => (
            <FormControlLabel
              key={role.value}
              control={
                <Checkbox
                  data-testid={`role-manager-role-${role.value}`}
                  value={role.value}
                  checked={selectedRoles.includes(role.value)}
                  onChange={() => handleRoleToggle(role.value)}
                />
              }
              label={role.label}
            />
          ))}
        </FormGroup>
 
        {/* Validation Error */}
        {error && (
          <Alert severity="error" sx={{ mt: 2 }} data-testid="role-manager-error">
            {error}
          </Alert>
        )}
 
        {/* Mutation Error */}
        {updateRolesMutation.isError && (
          <Alert severity="error" sx={{ mt: 2 }}>
            {t('error.updateFailed')}
          </Alert>
        )}
      </DialogContent>
 
      <DialogActions>
        <Button onClick={onClose} variant="outlined" data-testid="role-manager-cancel">
          {t('common:actions.cancel')}
        </Button>
        <Button
          onClick={handleSave}
          variant="contained"
          color="primary"
          disabled={updateRolesMutation.isPending}
          data-testid="role-manager-save"
        >
          {updateRolesMutation.isPending ? t('common:actions.saving') : t('common:actions.save')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};
 
export default RoleManagerModal;