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

85.29% Statements 29/34
56.52% Branches 13/23
100% Functions 7/7
84.84% Lines 28/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                                                                                  1x 6x 6x 6x 6x 6x   6x 3x 3x 3x 3x     3x         4x                         3x                 3x       3x       6x 3x             3x               3x 1x     2x 4x   2x 1x     2x                                                   1x                         2x                                        
/**
 * Table showing events a user has participated in
 * Story BAT-15: Integration - Participant Batch Import
 */
 
import React, { useEffect, useState } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Alert,
  Box,
  Card,
  CardContent,
  Stack,
  Typography,
} from '@mui/material';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { useTranslation } from 'react-i18next';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import axios from 'axios';
import apiClient from '@/services/api/apiClient';
import type { components } from '@/types/generated/event-registrations-api.types';
 
type Registration = components['schemas']['Registration'];
 
interface EventParticipation {
  eventCode: string;
  title: string;
  date: string;
  status: string;
}
 
interface EventsParticipatedTableProps {
  userId: string;
}
 
export const EventsParticipatedTable: React.FC<EventsParticipatedTableProps> = ({ userId }) => {
  const { t } = useTranslation('userManagement');
  const { isMobile } = useBreakpoints();
  const [events, setEvents] = useState<EventParticipation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    const fetchEventParticipations = async () => {
      try {
        setIsLoading(true);
        setError(null);
 
        // Fetch registrations for this user using the new endpoint
        const response = await apiClient.get<Registration[]>(`/events/registrations`, {
          headers: { 'X-Attendee-Username': userId },
        });
 
        // Transform response to table data with Swiss date format (de-CH)
        const participations: EventParticipation[] = response.data.map((reg) => ({
          eventCode: reg.eventCode || 'N/A',
          title: reg.eventTitle || reg.eventCode || t('userDetail.eventsTable.untitledEvent'),
          date: reg.eventDate
            ? new Date(reg.eventDate).toLocaleDateString('de-CH', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric',
              })
            : t('userDetail.eventsTable.dateTBD'),
          status: reg.status || 'REGISTERED',
        }));
 
        setEvents(participations);
      } catch (err) {
        console.error('Failed to fetch event participations:', err);
        if (axios.isAxiosError(err)) {
          setError(err.response?.data?.message || 'Failed to load event participations');
        } else {
          setError('Failed to load event participations');
        }
      } finally {
        setIsLoading(false);
      }
    };
 
    fetchEventParticipations();
    // eslint-disable-next-line react-hooks/exhaustive-deps -- t is stable from useTranslation
  }, [userId]);
 
  if (isLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight={200}>
        <BATbernLoader size={80} />
      </Box>
    );
  }
 
  Iif (error) {
    return (
      <Alert severity="error" sx={{ mb: 2 }}>
        {t('userDetail.eventsTable.loadError')}
      </Alert>
    );
  }
 
  if (events.length === 0) {
    return <Alert severity="info">{t('userDetail.eventsTable.noEvents')}</Alert>;
  }
 
  const statusColor = (status: string) =>
    status === 'ATTENDED' ? 'success.main' : 'text.secondary';
 
  if (isMobile) {
    return (
      <Box data-testid="events-participated-cards">
        {events.map((event, index) => (
          <Card
            key={`${event.eventCode}-${index}`}
            variant="outlined"
            sx={{ mb: 2 }}
            data-testid="event-participation-card"
          >
            <CardContent>
              <Stack spacing={0.5}>
                <Typography variant="subtitle1" fontWeight="bold">
                  {event.eventCode}
                </Typography>
                <Typography variant="body2">{event.title}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {event.date}
                </Typography>
                <Typography variant="body2" color={statusColor(event.status)}>
                  {t(`userDetail.eventsTable.statusValues.${event.status}`, event.status)}
                </Typography>
              </Stack>
            </CardContent>
          </Card>
        ))}
      </Box>
    );
  }
 
  return (
    <TableContainer component={Paper}>
      <Table aria-label={t('userDetail.eventsTable.ariaLabel')}>
        <TableHead>
          <TableRow>
            <TableCell>{t('userDetail.eventsTable.eventCode')}</TableCell>
            <TableCell>{t('common:labels.title')}</TableCell>
            <TableCell>{t('common:labels.date')}</TableCell>
            <TableCell>{t('common:labels.status')}</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {events.map((event, index) => (
            <TableRow key={`${event.eventCode}-${index}`}>
              <TableCell>
                <Typography variant="body2" fontWeight="medium">
                  {event.eventCode}
                </Typography>
              </TableCell>
              <TableCell>{event.title}</TableCell>
              <TableCell>{event.date}</TableCell>
              <TableCell>
                <Typography variant="body2" color={statusColor(event.status)}>
                  {t(`userDetail.eventsTable.statusValues.${event.status}`, event.status)}
                </Typography>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
};