All files / src/components/organizer/SpeakerDrawer UnifiedHistoryPanel.tsx

2.38% Statements 1/42
0% Branches 0/48
0% Functions 0/10
2.5% Lines 1/40

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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261                                                                                                                                        1x                                                                                                                                                                                                                                                                                                                                                                                                
/**
 * Unified history panel for the speaker detail drawer (Story 11.D.4 — AC7.3).
 *
 * Merges the status-change feed (`GET /events/{code}/speakers/{id}/status/history`,
 * `speakerStatusService.getStatusHistory`) and the outreach feed (`useSpeakerOutreachHistory`)
 * into a single chronologically-ordered list, newest first. Replaces the legacy
 * 3-tab drawer's separate "Activity" tab + the status timeline that lived elsewhere.
 *
 * Per plan §8.5 "unified History — status changes (with reason) + outreach attempts in
 * one chronological feed".
 */
import React, { useMemo } from 'react';
import {
  Alert,
  Avatar,
  Box,
  Chip,
  List,
  ListItem,
  Stack,
  Tooltip,
  Typography,
} from '@mui/material';
import {
  SwapHoriz as StatusIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  Person as PersonIcon,
  HelpOutline as UnknownIcon,
  EditNote as RevisionIcon,
} from '@mui/icons-material';
import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { formatDateTime } from '@/utils/date';
import { speakerStatusService } from '@/services/speakerStatusService';
import { useSpeakerOutreachHistory } from '@/hooks/useSpeakerOutreach';
import type { SpeakerPoolEntry } from '@/types/speakerPool.types';
import type { components } from '@/types/generated/speakers-api.types';
 
type StatusHistoryItem = components['schemas']['StatusHistoryItem'];
type OutreachHistoryItem = components['schemas']['OutreachHistory'];
type ContactMethod = components['schemas']['ContactMethod'];
 
interface UnifiedHistoryPanelProps {
  speaker: SpeakerPoolEntry;
  eventCode: string;
}
 
interface InterleavedEntry {
  kind: 'status' | 'outreach';
  timestamp: string;
  payload: StatusHistoryItem | OutreachHistoryItem;
}
 
function contactMethodIcon(method: ContactMethod | string | undefined): React.ReactElement {
  switch (method) {
    case 'email':
      return <EmailIcon fontSize="small" />;
    case 'phone':
      return <PhoneIcon fontSize="small" />;
    case 'in_person':
      return <PersonIcon fontSize="small" />;
    default:
      return <UnknownIcon fontSize="small" />;
  }
}
 
export const UnifiedHistoryPanel: React.FC<UnifiedHistoryPanelProps> = ({ speaker, eventCode }) => {
  const { t, i18n } = useTranslation(['organizer', 'common']);
  const fmt = (iso: string) => formatDateTime(new Date(iso), i18n.language);
 
  const statusQuery = useQuery({
    queryKey: ['speakerStatusHistory', eventCode, speaker.id],
    queryFn: () => speakerStatusService.getStatusHistory(eventCode, speaker.id),
    enabled: !!speaker.id,
  });
 
  const outreachQuery = useSpeakerOutreachHistory(eventCode, speaker.id);
 
  const isLoading = statusQuery.isLoading || outreachQuery.isLoading;
  const isError = statusQuery.isError || outreachQuery.isError;
 
  const entries: InterleavedEntry[] = useMemo(() => {
    const statusItems: InterleavedEntry[] = (statusQuery.data ?? [])
      .filter((it): it is StatusHistoryItem & { changedAt: string } => !!it.changedAt)
      .map((it) => ({ kind: 'status', timestamp: it.changedAt, payload: it }));
    const outreachItems: InterleavedEntry[] = (outreachQuery.data ?? []).map((it) => ({
      kind: 'outreach',
      timestamp: it.contactDate,
      payload: it,
    }));
    return [...statusItems, ...outreachItems].sort((a, b) => {
      // Newest first; tolerate unparseable timestamps by treating them as oldest.
      const ta = new Date(a.timestamp).getTime();
      const tb = new Date(b.timestamp).getTime();
      const safeA = Number.isNaN(ta) ? 0 : ta;
      const safeB = Number.isNaN(tb) ? 0 : tb;
      return safeB - safeA;
    });
  }, [statusQuery.data, outreachQuery.data]);
 
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <BATbernLoader size={64} />
      </Box>
    );
  }
 
  if (isError) {
    return (
      <Box sx={{ p: 2 }}>
        <Alert severity="error">{t('organizer:speakerDrawer.history.loadError')}</Alert>
      </Box>
    );
  }
 
  if (entries.length === 0) {
    return (
      <Box sx={{ textAlign: 'center', py: 4, px: 2 }}>
        <Typography variant="body2" color="text.secondary">
          {t('organizer:speakerDrawer.history.noEntries')}
        </Typography>
      </Box>
    );
  }
 
  return (
    <Box sx={{ p: 2, overflow: 'auto' }} data-testid="unified-history-panel">
      <List dense disablePadding>
        {entries.map((entry, idx) => {
          const key = `${entry.kind}-${idx}-${entry.timestamp}`;
          if (entry.kind === 'status') {
            const it = entry.payload as StatusHistoryItem;
            // ADR-009: rejecting an abstract is not a state transition, so the backend
            // surfaces it here as a synthetic entry with kind=CONTENT_REJECTED and no
            // previous/newStatus. Render those with a revision icon + dedicated copy
            // so the organizer sees the feedback and timestamp.
            const isContentRejection = it.kind === 'CONTENT_REJECTED';
            const fromLabel = it.previousStatus
              ? t(`organizer:speakerStatus.${it.previousStatus}`)
              : '—';
            const toLabel = it.newStatus ? t(`organizer:speakerStatus.${it.newStatus}`) : '—';
            return (
              <ListItem
                key={key}
                disableGutters
                data-testid={
                  isContentRejection ? 'history-entry-content-rejected' : 'history-entry-status'
                }
                sx={{
                  flexDirection: 'column',
                  alignItems: 'flex-start',
                  border: 1,
                  borderColor: 'divider',
                  borderRadius: 1,
                  p: 1.5,
                  mb: 1,
                }}
              >
                <Stack direction="row" spacing={1} alignItems="center" sx={{ width: '100%' }}>
                  <Avatar
                    sx={{
                      width: 24,
                      height: 24,
                      bgcolor: isContentRejection ? 'warning.main' : 'primary.main',
                    }}
                  >
                    {isContentRejection ? (
                      <RevisionIcon sx={{ fontSize: 16 }} />
                    ) : (
                      <StatusIcon sx={{ fontSize: 16 }} />
                    )}
                  </Avatar>
                  <Typography variant="body2" sx={{ flex: 1 }}>
                    {isContentRejection
                      ? t('organizer:speakerDrawer.history.contentRejectedEntry', {
                          actor: it.changedByUsername ?? t('common:labels.unknown', 'unknown'),
                          defaultValue: 'Abstract revision requested by {{actor}}',
                        })
                      : t('organizer:speakerDrawer.history.statusEntry', {
                          from: fromLabel,
                          to: toLabel,
                          actor: it.changedByUsername ?? t('common:labels.unknown', 'unknown'),
                        })}
                  </Typography>
                  <Tooltip title={fmt(entry.timestamp)}>
                    <Typography variant="caption" color="text.secondary">
                      {fmt(entry.timestamp)}
                    </Typography>
                  </Tooltip>
                </Stack>
                {it.changeReason && (
                  <Typography
                    variant="body2"
                    sx={{ mt: 0.5, ml: 4, color: 'text.secondary', whiteSpace: 'pre-wrap' }}
                  >
                    {it.changeReason}
                  </Typography>
                )}
              </ListItem>
            );
          }
 
          const it = entry.payload as OutreachHistoryItem;
          return (
            <ListItem
              key={key}
              disableGutters
              data-testid="history-entry-outreach"
              sx={{
                flexDirection: 'column',
                alignItems: 'flex-start',
                border: 1,
                borderColor: 'divider',
                borderRadius: 1,
                p: 1.5,
                mb: 1,
              }}
            >
              <Stack direction="row" spacing={1} alignItems="center" sx={{ width: '100%' }}>
                <Avatar sx={{ width: 24, height: 24, bgcolor: 'info.main' }}>
                  {contactMethodIcon(it.contactMethod)}
                </Avatar>
                <Typography variant="body2" sx={{ flex: 1 }}>
                  {t('organizer:speakerDrawer.history.outreachEntry', {
                    actor: it.organizerUsername ?? t('common:labels.unknown', 'unknown'),
                  })}
                </Typography>
                <Chip
                  size="small"
                  variant="outlined"
                  label={t(
                    `organizer:speakerOutreach.markContactedModal.method.${
                      it.contactMethod === 'in_person' ? 'inPerson' : it.contactMethod
                    }`
                  )}
                />
                <Tooltip title={fmt(entry.timestamp)}>
                  <Typography variant="caption" color="text.secondary">
                    {fmt(entry.timestamp)}
                  </Typography>
                </Tooltip>
              </Stack>
              {it.notes && (
                <Typography
                  variant="body2"
                  sx={{ mt: 0.5, ml: 4, color: 'text.secondary', whiteSpace: 'pre-wrap' }}
                >
                  {it.notes}
                </Typography>
              )}
            </ListItem>
          );
        })}
      </List>
    </Box>
  );
};