All files / src/components/organizer/EventPage SpeakerBulkComms.tsx

81.81% Statements 36/44
87.5% Branches 21/24
58.33% Functions 7/12
81.39% Lines 35/43

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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                                                                                                        1x         1x 15x 15x 15x 15x   15x 15x 15x 15x   15x 16x         15x                 3x       3x 3x 3x 3x 3x 3x 6x 6x 4x   1x     2x     2x       15x               15x 1x                             14x   14x                                                             1x 1x                                                                                 3x                                                                                                                                           3x                              
/**
 * SpeakerBulkComms (Epic 14, Phase E โ€” Story 14.E.3)
 *
 * The ๐ŸŽค Speakers audience of the Communications tab. Surfaces the previously
 * unwired `useSendReminder` hook as a bulk, confirm-gated reminder send.
 *
 * Scope note (NFR9 โ€” frontend-only, no backend): `useSendReminder` is 1:1
 * (per speakerPoolId) and supports only the RESPONSE and CONTENT reminder
 * types. So this surface offers exactly two reminders, sent by looping the 1:1
 * hook over the matching speakers client-side:
 *   - Response deadline โ†’ speakers still INVITED (awaiting a yes/no)
 *   - Content  deadline โ†’ speakers ACCEPTED   (awaiting their materials)
 * "Logistics & arrival" and "thank-you" speaker comms (FR32) would need a new
 * backend reminder type + bulk endpoint and are deferred (see deferred-work.md).
 *
 * NFR1: a send opens a confirm dialog FIRST and the Send button is disabled
 * while in flight, so a drag/double-click can never silently double-send.
 */
 
import React, { useMemo, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  FormControl,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  Stack,
  Typography,
} from '@mui/material';
import { NotificationsActive as ReminderIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useSpeakerPool, useSendReminder } from '@/hooks/useSpeakerPool';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import type { SpeakerPoolEntry } from '@/types/speakerPool.types';
 
interface SpeakerBulkCommsProps {
  eventCode: string;
  eventTitle: string;
}
 
type ReminderType = 'RESPONSE' | 'CONTENT';
 
/** Which speaker state each reminder targets. */
const TARGET_STATUS: Record<ReminderType, SpeakerPoolEntry['status']> = {
  RESPONSE: 'INVITED',
  CONTENT: 'ACCEPTED',
};
 
export const SpeakerBulkComms: React.FC<SpeakerBulkCommsProps> = ({ eventCode, eventTitle }) => {
  const { t } = useTranslation(['events', 'common']);
  const { isMobile } = useBreakpoints();
  const poolQuery = useSpeakerPool(eventCode);
  const sendReminder = useSendReminder(eventCode);
 
  const [reminderType, setReminderType] = useState<ReminderType>('RESPONSE');
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [sending, setSending] = useState(false);
  const [result, setResult] = useState<{ sent: number; failed: SpeakerPoolEntry[] } | null>(null);
 
  const recipients = useMemo<SpeakerPoolEntry[]>(
    () => (poolQuery.data ?? []).filter((s) => s.status === TARGET_STATUS[reminderType]),
    [poolQuery.data, reminderType]
  );
 
  const typeLabel =
    reminderType === 'RESPONSE'
      ? t('eventPage.speakerComms.typeResponse', 'Response deadline (invited speakers)')
      : t('eventPage.speakerComms.typeContent', 'Content deadline (accepted speakers)');
 
  // Loop the 1:1 reminder over the chosen speakers, collecting per-speaker outcomes
  // so a partial failure is reported (and retryable) rather than swallowed.
  async function runSend(targets: SpeakerPoolEntry[]) {
    // The recipient set can refetch to empty while the confirm dialog is open;
    // never report a misleading "sent 0" success for a no-op confirm.
    Iif (targets.length === 0) {
      setConfirmOpen(false);
      return;
    }
    setSending(true);
    setConfirmOpen(false);
    let sent = 0;
    const failed: SpeakerPoolEntry[] = [];
    try {
      for (const s of targets) {
        try {
          await sendReminder.mutateAsync({ speakerPoolId: s.id, request: { reminderType } });
          sent += 1;
        } catch {
          failed.push(s);
        }
      }
      setResult({ sent, failed });
    } finally {
      // Guarantee the button is re-enabled even if something throws outside the per-item catch.
      setSending(false);
    }
  }
 
  Iif (poolQuery.isLoading) {
    return (
      <Box display="flex" justifyContent="center" py={6}>
        <CircularProgress />
      </Box>
    );
  }
 
  if (poolQuery.isError) {
    return (
      <Alert
        severity="error"
        data-testid="speaker-comms-load-error"
        action={
          <Button color="inherit" size="small" onClick={() => poolQuery.refetch()}>
            {t('eventPage.speakerComms.retry', 'Retry')}
          </Button>
        }
      >
        {t('eventPage.speakerComms.loadError', 'Could not load the speaker pool.')}
      </Alert>
    );
  }
 
  const noRecipients = recipients.length === 0;
 
  return (
    <Stack spacing={3} data-testid="speaker-comms">
      <Box>
        <Typography variant="h6" gutterBottom>
          {t('eventPage.speakerComms.title', 'Speaker reminders')}
        </Typography>
        <Typography variant="body2" color="text.secondary">
          {t(
            'eventPage.speakerComms.description',
            'Send a deadline reminder to the speakers who still owe a response or their content. Each speaker is emailed individually โ€” invitations and one-off nudges stay on the speaker card.'
          )}
        </Typography>
      </Box>
 
      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: { xs: '1fr', md: 'minmax(300px, 34%) 1fr' },
          gap: 3,
          alignItems: 'start',
        }}
      >
        <Paper variant="outlined" sx={{ p: 2 }}>
          <Stack spacing={2}>
            <FormControl size="small">
              <InputLabel>{t('eventPage.speakerComms.reminderType', 'Reminder type')}</InputLabel>
              <Select
                value={reminderType}
                label={t('eventPage.speakerComms.reminderType', 'Reminder type')}
                disabled={sending}
                onChange={(e) => {
                  setReminderType(e.target.value as ReminderType);
                  setResult(null);
                }}
                SelectDisplayProps={
                  {
                    'data-testid': 'speaker-comms-type-select',
                  } as React.HTMLAttributes<HTMLDivElement>
                }
              >
                <MenuItem value="RESPONSE">
                  {t('eventPage.speakerComms.typeResponse', 'Response deadline (invited speakers)')}
                </MenuItem>
                <MenuItem value="CONTENT">
                  {t('eventPage.speakerComms.typeContent', 'Content deadline (accepted speakers)')}
                </MenuItem>
              </Select>
            </FormControl>
 
            <Typography
              variant="caption"
              color="text.secondary"
              data-testid="speaker-comms-recipient-count"
            >
              {t('eventPage.speakerComms.recipientCount', {
                count: recipients.length,
                defaultValue: `${recipients.length} speaker(s) will be reminded`,
              })}
            </Typography>
 
            {noRecipients && (
              <Alert severity="info" data-testid="speaker-comms-empty">
                {t(
                  'eventPage.speakerComms.empty',
                  'No speakers are currently awaiting this reminder.'
                )}
              </Alert>
            )}
 
            <Box>
              <Button
                variant="contained"
                startIcon={sending ? <CircularProgress size={16} /> : <ReminderIcon />}
                onClick={() => setConfirmOpen(true)}
                disabled={noRecipients || sending}
                data-testid="speaker-comms-send-button"
              >
                {t('eventPage.speakerComms.send', 'Send reminders')}
              </Button>
            </Box>
 
            {result && (
              <Alert
                severity={result.failed.length === 0 ? 'success' : 'warning'}
                onClose={() => setResult(null)}
                data-testid="speaker-comms-result"
                action={
                  result.failed.length > 0 ? (
                    <Button
                      color="inherit"
                      size="small"
                      disabled={sending}
                      onClick={() => runSend(result.failed)}
                      data-testid="speaker-comms-retry-failed"
                    >
                      {t('eventPage.speakerComms.retryFailed', {
                        count: result.failed.length,
                        defaultValue: `Retry the ${result.failed.length} that failed`,
                      })}
                    </Button>
                  ) : undefined
                }
              >
                {t('eventPage.speakerComms.result', {
                  sent: result.sent,
                  failed: result.failed.length,
                  defaultValue: `Sent ${result.sent}, failed ${result.failed.length}.`,
                })}
              </Alert>
            )}
          </Stack>
        </Paper>
 
        <Paper variant="outlined" sx={{ p: 2 }}>
          <Typography variant="body2" color="text.secondary">
            {t(
              'eventPage.speakerComms.noPreview',
              "Reminders are sent with the standard speaker templates in each speaker's language โ€” no preview to show."
            )}
          </Typography>
        </Paper>
      </Box>
 
      {/* Confirmation dialog (NFR1 โ€” opens before any send call). */}
      <Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)} fullScreen={isMobile}>
        <DialogTitle>
          {t('eventPage.speakerComms.confirmTitle', 'Send speaker reminders?')}
        </DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t('eventPage.speakerComms.confirmBody', {
              type: typeLabel,
              count: recipients.length,
              eventTitle,
              defaultValue: `Send a โ€œ${typeLabel}โ€ reminder to ${recipients.length} speaker(s) of ยซ${eventTitle}ยป? Each is emailed individually.`,
            })}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setConfirmOpen(false)} disabled={sending}>
            {t('common:actions.cancel', 'Cancel')}
          </Button>
          <Button
            onClick={() => runSend(recipients)}
            variant="contained"
            disabled={sending}
            autoFocus
            data-testid="speaker-comms-confirm-send"
          >
            {sending ? <CircularProgress size={20} /> : t('common.confirm', 'Confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    </Stack>
  );
};
 
export default SpeakerBulkComms;