All files / src/components/organizer/EventManagement EventManagementDashboard.tsx

56.75% Statements 21/37
66.66% Branches 22/33
15.38% Functions 2/13
56.75% Lines 21/37

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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246                                                                      2x 15x 15x 15x 15x                         15x                 15x             15x                   15x     15x 15x 15x                       15x       15x       15x       15x         15x 1x               14x 1x                 13x                                                                                                                                                                                                                                    
/**
 * EventManagementDashboard Component
 *
 * Story 2.5.3 - Task 8b (GREEN Phase)
 * AC: 1 (Event Dashboard Display), 2 (Event List & Filters)
 * Wireframe: docs/wireframes/story-1.16-event-management-dashboard.md v1.0
 *
 * Main organizer dashboard with:
 * - Active events pipeline
 * - Critical tasks
 * - Team activity feed
 * - Quick actions sidebar
 */
 
import React, { useEffect } from 'react';
import { Paper, Typography, Box, Stack, Alert, Container } from '@mui/material';
import Grid from '@mui/material/Grid';
import { useTranslation } from 'react-i18next';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { useEvents } from '@/hooks/useEvents';
import { useNotifications } from '@/hooks/useNotifications';
import { useAuth } from '@/hooks/useAuth';
import { useEventStore } from '@/stores/eventStore';
import { useNotificationWebSocket } from '@/hooks/useNotificationWebSocket';
import { EventList } from './EventList';
import { EventSearch } from './EventSearch';
import { TaskWidget } from '../Tasks/TaskWidget';
import { TeamActivityFeed } from './TeamActivityFeed';
import { EventForm } from './EventForm';
import { EventPagination } from './EventPagination';
import { QuickActions } from './QuickActions';
import type { EventFilters } from '@/types/event.types';
 
export const EventManagementDashboard: React.FC = () => {
  const { t } = useTranslation('events');
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const {
    filters,
    setFilters,
    pagination,
    setPage,
    setLimit,
    isCreateModalOpen,
    openCreateModal,
    closeCreateModal,
    isEditModalOpen,
    selectedEventCode,
    openEditModal,
    closeEditModal,
  } = useEventStore();
 
  // Fetch data with React Query hooks
  // Include registrations to get actual registration counts from database
  const {
    data: eventsData,
    isLoading: isLoadingEvents,
    isError: isErrorEvents,
    error: eventsError,
  } = useEvents(pagination, filters, { expand: ['registrations'] });
 
  // Fetch notifications for current organizer (unread notifications)
  const {
    data: notificationsData,
    isLoading: isLoadingNotifications,
    refetch: refetchNotifications,
  } = useNotifications(
    {
      username: user?.username || '',
      status: 'UNREAD', // UNREAD status = in-app unread notifications
    },
    { page: 1, limit: 10 }
  );
 
  // Real-time WebSocket notifications (Story BAT-7)
  const { onNotification, isConnected } = useNotificationWebSocket(user?.username);
 
  // Subscribe to real-time notification updates
  useEffect(() => {
    Eif (!isConnected) {
      return;
    }
 
    const unsubscribe = onNotification((notification) => {
      console.log('Real-time notification received:', notification);
      // Invalidate notifications query to refetch with new notification
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
    });
 
    return unsubscribe;
  }, [isConnected, onNotification, queryClient]);
 
  const handleFiltersChange = (newFilters: EventFilters) => {
    setFilters(newFilters);
  };
 
  const handleEventEdit = (eventCode: string) => {
    openEditModal(eventCode);
  };
 
  const handleEventClick = (eventCode: string) => {
    navigate(`/organizer/events/${eventCode}`);
  };
 
  const handleNewEvent = () => {
    openCreateModal();
  };
 
  // Loading state
  if (isLoadingEvents && isLoadingNotifications) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <BATbernLoader size={96} />
      </Box>
    );
  }
 
  // Error state
  if (isErrorEvents) {
    return (
      <Box p={3}>
        <Alert severity="error">
          {t('dashboard.errors.failedToLoadEvents')}: {eventsError?.message}
        </Alert>
      </Box>
    );
  }
 
  return (
    <Box sx={{ flexGrow: 1, p: 3 }} data-testid="dashboard-container">
      <Container maxWidth="xl">
        {/* Header */}
        <Box mb={3}>
          <Typography variant="h4" component="h1">
            {t('dashboard.title')}
          </Typography>
        </Box>
 
        {/* Search and Filters */}
        <Paper sx={{ p: 3, mb: 3 }}>
          <EventSearch onFiltersChange={handleFiltersChange} filters={filters} />
        </Paper>
 
        {/* Main Content Grid */}
        <Grid container spacing={3}>
          {/* Active Events (Main Column - 8/12) */}
          <Grid size={{ xs: 12, md: 8 }}>
            <Paper sx={{ p: 3 }}>
              <Stack
                direction={{ xs: 'column', sm: 'row' }}
                justifyContent="space-between"
                alignItems={{ xs: 'flex-start', sm: 'center' }}
                spacing={{ xs: 0.5, sm: 0 }}
                mb={2}
              >
                <Typography variant="h5">{t('dashboard.activeEvents')}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {eventsData?.data?.length || 0}/{eventsData?.pagination?.totalItems || 0}{' '}
                  {(eventsData?.pagination?.totalItems || 0) === 1
                    ? t('dashboard.eventWord')
                    : t('dashboard.eventWord_plural')}
                </Typography>
              </Stack>
              <EventList
                events={eventsData?.data || []}
                isLoading={isLoadingEvents}
                onEventEdit={handleEventEdit}
                onEventClick={handleEventClick}
              />
 
              {/* Pagination */}
              {eventsData?.pagination && (
                <EventPagination
                  page={eventsData.pagination.page}
                  totalPages={eventsData.pagination.totalPages}
                  limit={eventsData.pagination.limit}
                  onPageChange={(newPage) => setPage(newPage)}
                  onLimitChange={(newLimit) => setLimit(newLimit)}
                />
              )}
            </Paper>
          </Grid>
 
          {/* Sidebar (4/12) */}
          <Grid size={{ xs: 12, md: 4 }}>
            <Stack spacing={3}>
              {/* Quick Actions - Story 5.1 */}
              <QuickActions onNewEvent={handleNewEvent} />
 
              {/* Critical Tasks - Story 5.5 Phase 6 */}
              <Paper sx={{ p: 3 }} data-testid="critical-tasks-section">
                <TaskWidget organizerUsername={user?.username || ''} />
              </Paper>
 
              {/* Notifications Feed - EventBridge Integration */}
              <Paper sx={{ p: 3 }} data-testid="team-activity-section">
                <TeamActivityFeed
                  notifications={notificationsData?.data || []}
                  totalNotifications={notificationsData?.pagination?.totalItems}
                  isLoading={isLoadingNotifications}
                  onReload={() => refetchNotifications()}
                  limit={5}
                />
              </Paper>
            </Stack>
          </Grid>
        </Grid>
 
        {/* Create Event Modal */}
        <EventForm
          open={isCreateModalOpen}
          mode="create"
          onClose={closeCreateModal}
          onSuccess={() => {
            closeCreateModal();
            // Refetch events after successful creation
            // The useEvents hook will automatically refetch due to query invalidation
          }}
        />
 
        {/* Edit Event Modal */}
        {isEditModalOpen && selectedEventCode && (
          <EventForm
            open={isEditModalOpen}
            mode="edit"
            event={eventsData?.data?.find((e) => e.eventCode === selectedEventCode)}
            onClose={closeEditModal}
            onSuccess={(updatedEvent) => {
              closeEditModal();
              // Redirect to event detail page if eventCode changed (e.g., eventNumber updated)
              if (updatedEvent && updatedEvent.eventCode !== selectedEventCode) {
                navigate(`/organizer/events/${updatedEvent.eventCode}`);
              }
              // Otherwise, refetch events to show updated data in list
              // The useEvents hook will automatically refetch due to query invalidation
            }}
          />
        )}
      </Container>
    </Box>
  );
};