All files / src/components/Publishing/PublishingControls PublishingControls.tsx

84.48% Statements 49/58
70.76% Branches 46/65
100% Functions 11/11
87.5% Lines 49/56

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                                      1x       15x 15x   15x 15x   15x     15x     15x 105x         15x 45x   45x   15x   15x   15x             15x 45x   45x   15x     15x   15x 13x   2x         2x   15x 15x                     17x     15x 2x 2x 2x   2x 1x 1x       15x 43x   13x   15x   15x       15x 90x     15x                                       4x                     45x 45x 45x 45x   45x                         2x                                                              
import React, { useState } from 'react';
import { Box, Button, Alert, Typography, CircularProgress, Stack, Tooltip } from '@mui/material';
import {
  Error as ErrorIcon,
  CheckCircle as CheckIcon,
  Topic as TopicIcon,
  People as PeopleIcon,
  EventNote as AgendaIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { usePublishing } from '@/hooks/usePublishing/usePublishing';
import { PublishingPhase } from '@/types/event.types';
 
export interface PublishingControlsProps {
  eventCode: string;
  currentPhase: PublishingPhase;
  validationErrors?: Array<{ field: string; message: string; requirement: string }>;
}
 
export const PublishingControls: React.FC<PublishingControlsProps> = ({
  eventCode,
  validationErrors = [],
}) => {
  const { t } = useTranslation('events');
  const { publishPhase, isPublishing, publishingStatus } = usePublishing(eventCode);
 
  const [isAnnouncingPublish, setIsAnnouncingPublish] = useState(false);
  const [publishingPhase, setPublishingPhase] = useState<PublishingPhase | null>(null);
 
  const hasValidationErrors = validationErrors.length > 0;
 
  // Get published phases from status
  const publishedPhases = publishingStatus?.publishedPhases || [];
 
  // Check if a phase is already published
  const isPhasePublished = (phase: PublishingPhase): boolean => {
    return publishedPhases.includes(phase);
  };
 
  // Check if a phase can be published (validation passes and prerequisites met)
  // Always uses progressive ordering: topic → speakers → agenda
  const canPublishPhase = (phase: PublishingPhase): boolean => {
    Iif (!publishingStatus) return false;
 
    switch (phase) {
      case 'topic':
        return publishingStatus.topic?.isValid === true;
      case 'speakers':
        return publishingStatus.speakers?.isValid === true && isPhasePublished('topic');
      case 'agenda':
        return publishingStatus.sessions?.isValid === true && isPhasePublished('speakers');
      default:
        return false;
    }
  };
 
  // Get validation message for a phase
  const getPhaseValidationMessage = (phase: PublishingPhase): string | null => {
    Iif (!publishingStatus) return null;
 
    switch (phase) {
      case 'topic':
        Iif (!publishingStatus.topic?.isValid) {
          return publishingStatus.topic?.errors?.[0] || t('publishing.controls.topicNotReady');
        }
        break;
      case 'speakers':
        if (!isPhasePublished('topic')) {
          return t('publishing.controls.publishTopicFirst');
        }
        Iif (!publishingStatus.speakers?.isValid) {
          return (
            publishingStatus.speakers?.errors?.[0] || t('publishing.controls.speakersNotReady')
          );
        }
        break;
      case 'agenda':
        Eif (!isPhasePublished('speakers')) {
          return t('publishing.controls.publishSpeakersFirst');
        }
        if (!publishingStatus.sessions?.isValid) {
          const { assignedCount = 0, totalCount = 0 } = publishingStatus.sessions || {};
          return t('publishing.controls.agendaNotReady', {
            assigned: assignedCount,
            total: totalCount,
          });
        }
        break;
    }
    return null;
  };
 
  const handlePublish = async (phase: PublishingPhase) => {
    setIsAnnouncingPublish(true);
    setPublishingPhase(phase);
    await publishPhase(phase);
    // Reset announcement after a brief delay
    setTimeout(() => {
      setIsAnnouncingPublish(false);
      setPublishingPhase(null);
    }, 100);
  };
 
  const getPhaseIcon = (phase: PublishingPhase) => {
    switch (phase) {
      case 'topic':
        return <TopicIcon />;
      case 'speakers':
        return <PeopleIcon />;
      case 'agenda':
        return <AgendaIcon />;
    }
  };
 
  const getPhaseLabel = (phase: PublishingPhase): string => {
    return t(`publishing.controls.phase.${phase}`);
  };
 
  return (
    <Box>
      {/* Screen reader announcement for publish action */}
      {isAnnouncingPublish && publishingPhase && (
        <div role="status" aria-live="polite" style={{ position: 'absolute', left: '-10000px' }}>
          {t('publishing.controls.accessibility.publishingPhase', { phase: publishingPhase })}
        </div>
      )}
 
      {/* Validation Errors from API */}
      {hasValidationErrors && (
        <Alert
          severity="error"
          icon={<ErrorIcon data-testid="validation-error-icon" />}
          sx={{ mb: 2 }}
        >
          <Typography variant="subtitle2" gutterBottom>
            {t('publishing.controls.validationErrors')}
          </Typography>
          {validationErrors.map((error, index) => (
            <Typography key={index} variant="body2">
              • {error.message}
            </Typography>
          ))}
        </Alert>
      )}
 
      {/* Phase Publishing Buttons (the column title is provided by the parent
          EventPublishingTab — "Publish next phase" — so no heading here). */}
      <Stack direction="column" spacing={1} sx={{ mb: 3 }} alignItems="stretch">
        {(['topic', 'speakers', 'agenda'] as PublishingPhase[]).map((phase) => {
          const isPublished = isPhasePublished(phase);
          const canPublish = canPublishPhase(phase);
          const validationMessage = getPhaseValidationMessage(phase);
          const isCurrentlyPublishing = isPublishing && publishingPhase === phase;
 
          return (
            <Tooltip
              key={phase}
              title={
                isPublished ? t('publishing.controls.alreadyPublished') : validationMessage || ''
              }
              arrow
            >
              <span style={{ display: 'block', width: '100%' }}>
                <Button
                  variant={isPublished ? 'outlined' : 'contained'}
                  color={isPublished ? 'success' : 'primary'}
                  size="small"
                  onClick={() => handlePublish(phase)}
                  disabled={isPublishing || isPublished || !canPublish}
                  startIcon={
                    isCurrentlyPublishing ? (
                      <CircularProgress size={20} />
                    ) : isPublished ? (
                      <CheckIcon />
                    ) : (
                      getPhaseIcon(phase)
                    )
                  }
                  data-testid={`publish-${phase}-button`}
                  aria-label={t('publishing.controls.publishPhase', {
                    phase: getPhaseLabel(phase),
                  })}
                  sx={{ width: '100%', justifyContent: 'flex-start' }}
                >
                  {isPublished
                    ? t('publishing.controls.published', { phase: getPhaseLabel(phase) })
                    : isCurrentlyPublishing
                      ? t('publishing.controls.publishing')
                      : t('publishing.controls.publishPhase', { phase: getPhaseLabel(phase) })}
                </Button>
              </span>
            </Tooltip>
          );
        })}
      </Stack>
    </Box>
  );
};