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

50% Statements 38/76
51.72% Branches 30/58
33.33% Functions 4/12
50.68% Lines 37/73

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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376                                                                                                                    2x         3x 3x 3x   3x 3x 3x     3x   3x                 3x 2x 2x 2x 2x 2x 1x 1x 1x                 1x         1x 1x 1x 1x   1x             2x     3x         3x                                   3x           3x                             3x                                                                 3x 3x 3x   3x                                                               3x 3x                 3x                                                                                                                                                                                                                                                                        
/**
 * Promote-to-READY sub-view (Epic 11 bug fix 2026-05-18 — replaces PromoteSpeakerDialog).
 *
 * Slides in over the SpeakerDetailDrawer body when an organizer presses "Promote to
 * speaker" on a CONTACTED-state card. Mirrors `ContentSubmissionSubView`'s structure:
 *
 *   - UserAutocomplete pre-filled with `speaker.speakerName` so existing SPEAKER users
 *     surface immediately.
 *   - "Create new speaker" button → UserCreateEditModal for the case where the real
 *     speaker doesn't exist yet (autoselects them on success).
 *   - "Promote" submits the resolved email/firstName/lastName via
 *     `usePromoteSpeakerToReady`. On success the drawer flips to the normal READY view
 *     because the cache invalidation pulls in the new state.
 *
 * Replaces the prior plain-text-fields PromoteSpeakerDialog modal — the dialog and the
 * Content sub-view used to ship two different speaker-resolution UXes; this consolidates
 * onto one.
 */
import React, { useEffect, useRef, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  Divider,
  IconButton,
  Paper,
  Stack,
  Typography,
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import type { AxiosError } from 'axios';
import { UserAutocomplete } from '@/components/shared/UserAutocomplete';
import { UserAvatar } from '@/components/shared/UserAvatar';
import UserCreateEditModal from '@/components/organizer/UserManagement/UserCreateEditModal';
import { getUserByUsername, searchUsers } from '@/services/api/userManagementApi';
import { usePromoteSpeakerToReady } from '@/hooks/useSpeakerPool';
import type { SpeakerPoolEntry } from '@/types/speakerPool.types';
import type { UserSearchResponse, User } from '@/types/user.types';
 
interface PromoteSpeakerSubViewProps {
  speaker: SpeakerPoolEntry;
  eventCode: string;
  onBack: () => void;
}
 
interface PromotionConflictDetails {
  code?: string;
  currentState?: string;
}
 
interface PromotionErrorBody {
  message?: string;
  details?: PromotionConflictDetails;
}
 
export const PromoteSpeakerSubView: React.FC<PromoteSpeakerSubViewProps> = ({
  speaker,
  eventCode,
  onBack,
}) => {
  const { t } = useTranslation(['organizer', 'common']);
  const queryClient = useQueryClient();
  const promoteMutation = usePromoteSpeakerToReady();
 
  const [selectedUser, setSelectedUser] = useState<UserSearchResponse | null>(null);
  const [userPickerError, setUserPickerError] = useState<string | undefined>(undefined);
  const [userModalOpen, setUserModalOpen] = useState(false);
  // Holds the FULL `User` (UserResponse) shape — UserSearchResponse omits `bio` and
  // other user-level fields, which would surface as an empty bio in the modal.
  const [editingUser, setEditingUser] = useState<User | null>(null);
 
  const lastPrefilledSpeakerIdRef = useRef<string | null>(null);
 
  // Prefill the autocomplete with the existing user to promote.
  //
  // Story 7.2 / ADR-012: a self-nomination already names the exact attendee, so resolve them
  // directly by username rather than guessing by name — and crucially WITHOUT a SPEAKER-role
  // filter, because a self-nominee is an ATTENDEE (not yet a SPEAKER). The promote grants SPEAKER
  // to whichever existing user is selected (provisionUserWithRole is idempotent by email — no
  // duplicate user), so all users are eligible here, not only existing speakers.
  useEffect(() => {
    const prefill = async () => {
      Iif (lastPrefilledSpeakerIdRef.current === speaker.id) return;
      lastPrefilledSpeakerIdRef.current = speaker.id;
      try {
        if (speaker.source === 'self_nomination' && speaker.proposedByUsername) {
          const user = await getUserByUsername(speaker.proposedByUsername);
          Eif (user) {
            setSelectedUser({
              id: user.id,
              email: user.email,
              firstName: user.firstName,
              lastName: user.lastName,
              roles: user.roles,
              profilePictureUrl: user.profilePictureUrl,
              companyId: user.companyId,
            });
            return;
          }
        }
        // Organizer-sourced candidate: best-effort match by the brainstorm name. No SPEAKER-role
        // filter (see above) — the first match is offered and the organizer can change it.
        let users = await searchUsers(speaker.speakerName, 20);
        Eif (users.length === 0 && speaker.speakerName.includes(' ')) {
          const firstName = speaker.speakerName.split(' ')[0];
          users = await searchUsers(firstName, 20);
        }
        Iif (users.length > 0) {
          setSelectedUser(users[0]);
        }
      } catch (error) {
        console.error('PromoteSpeakerSubView: failed to prefill speaker', error);
      }
    };
    prefill();
  }, [speaker.id, speaker.speakerName, speaker.source, speaker.proposedByUsername]);
 
  const handleCreateSpeaker = () => {
    setEditingUser(null);
    setUserModalOpen(true);
  };
 
  const handleEditSpeaker = async () => {
    if (!selectedUser) return;
    // Epic 11 bug fix 2026-05-19 — fetch the full UserResponse before opening the
    // modal so the bio + other user-level fields are populated. The narrow
    // UserSearchResponse omits them; passing it to the modal surfaces an empty bio
    // (mirrors the bug fixed in ContentSubmissionSubView).
    setEditingUser(selectedUser as unknown as User);
    setUserModalOpen(true);
    try {
      const fullUser = await getUserByUsername(selectedUser.id);
      if (fullUser) {
        setEditingUser(fullUser);
      }
    } catch (error) {
      console.error('Failed to fetch full user for edit:', error);
    }
  };
 
  const handleUserModalClose = () => {
    setUserModalOpen(false);
    setEditingUser(null);
    queryClient.invalidateQueries({ queryKey: ['users', 'search'] });
  };
 
  const handleUserModalSuccess = (createdOrUpdatedUser?: User) => {
    if (createdOrUpdatedUser) {
      setSelectedUser({
        id: createdOrUpdatedUser.id,
        email: createdOrUpdatedUser.email,
        firstName: createdOrUpdatedUser.firstName,
        lastName: createdOrUpdatedUser.lastName,
        roles: createdOrUpdatedUser.roles,
        profilePictureUrl: createdOrUpdatedUser.profilePictureUrl,
        companyId: createdOrUpdatedUser.companyId,
      });
    }
    handleUserModalClose();
  };
 
  const handlePromote = () => {
    if (!selectedUser) {
      setUserPickerError(
        t(
          'organizer:speakerBrainstorm.promoteDialog.errorEmailRequired',
          'Select a speaker to promote'
        )
      );
      return;
    }
    setUserPickerError(undefined);
    promoteMutation.mutate(
      {
        eventCode,
        speakerId: speaker.id,
        request: {
          email: selectedUser.email,
          firstName: selectedUser.firstName ?? '',
          lastName: selectedUser.lastName ?? '',
        },
      },
      {
        onSuccess: () => {
          // The cache invalidation in usePromoteSpeakerToReady flips the drawer's
          // speaker.status to READY; the parent's selectedSpeaker also refreshes via
          // useSpeakerPool. onBack returns to the now-READY drawer body.
          onBack();
        },
      }
    );
  };
 
  const errorBody =
    (promoteMutation.error as AxiosError<PromotionErrorBody> | null)?.response?.data ?? null;
  const errorAlert = (() => {
    Eif (!promoteMutation.isError) return null;
    const currentState = errorBody?.details?.currentState;
    Iif (errorBody?.details?.code === 'INVALID_PROMOTION_STATE' && currentState) {
      const stateMessageKey = (() => {
        switch (currentState) {
          case 'IDENTIFIED':
            return 'speakerBrainstorm.promoteDialog.errorStillIdentified';
          case 'DECLINED':
            return 'speakerBrainstorm.promoteDialog.errorDeclined';
          case 'READY':
            return 'speakerBrainstorm.promoteDialog.errorAlreadyReady';
          default:
            return 'speakerBrainstorm.promoteDialog.errorAlreadyPromoted';
        }
      })();
      const localizedState = t(
        `organizer:speakerBrainstorm.workflowState.${currentState}`,
        currentState
      );
      return (
        <Alert severity="warning" data-testid="promote-error-state">
          {t(`organizer:${stateMessageKey}`, { currentState: localizedState })}
        </Alert>
      );
    }
    return (
      <Alert severity="error" data-testid="promote-error-generic">
        {errorBody?.message ||
          t('organizer:speakerBrainstorm.promoteDialog.errorTitle', 'Could not promote speaker')}
      </Alert>
    );
  })();
 
  const canPromote =
    !!selectedUser && !!selectedUser.email && !!selectedUser.firstName && !!selectedUser.lastName;
  const incompleteUserBanner = selectedUser && !canPromote && (
    <Alert severity="info" data-testid="promote-incomplete-user">
      {t(
        'organizer:speakerBrainstorm.promoteSubView.incompleteUser',
        'Selected user is missing required fields (email / first name / last name). Edit the profile to complete it before promoting.'
      )}
    </Alert>
  );
 
  return (
    <>
      <Box sx={{ p: 1, display: 'flex', alignItems: 'center', gap: 1 }}>
        <IconButton
          onClick={onBack}
          size="small"
          aria-label={t('organizer:speakers.drawer.back')}
          data-testid="promote-subview-back"
        >
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h6">
          {t('organizer:speakerBrainstorm.promoteDialog.title', 'Promote to speaker')}
        </Typography>
      </Box>
      <Divider />
 
      <Box sx={{ flex: 1, overflow: 'auto', p: 2 }}>
        <Stack spacing={2}>
          <Typography variant="body2" color="text.secondary">
            {t(
              'organizer:speakerBrainstorm.promoteDialog.description',
              'The speaker moves to the READY lane and a user account is provisioned. No invitation email is sent yet — send the invitation from the READY lane when you are ready.'
            )}
          </Typography>
 
          <Paper variant="outlined" sx={{ p: 2 }}>
            <Typography variant="subtitle2" gutterBottom>
              {t('organizer:speakerContent.speakerInformation', 'Speaker')}
            </Typography>
            <UserAutocomplete
              value={selectedUser}
              onChange={(u) => {
                setSelectedUser(u);
                setUserPickerError(undefined);
              }}
              error={userPickerError}
              label={t('organizer:speakerContent.form.username', 'Find existing user')}
              // Story 7.2 / ADR-012: no role filter — a self-nominee is an ATTENDEE, not yet a
              // SPEAKER, and the promote grants SPEAKER on the way to READY. All users are eligible.
              disabled={promoteMutation.isPending}
              data-testid="promote-speaker-search-field"
            />
 
            {selectedUser && (
              <Box sx={{ mt: 2, p: 2, bgcolor: 'action.hover', borderRadius: 1 }}>
                <UserAvatar
                  firstName={selectedUser.firstName}
                  lastName={selectedUser.lastName}
                  company={selectedUser.companyId}
                  profilePictureUrl={selectedUser.profilePictureUrl}
                  size={40}
                  showCompany={true}
                />
                <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                  {selectedUser.email}
                </Typography>
                {selectedUser.roles && selectedUser.roles.length > 0 && (
                  <Typography variant="caption" color="text.secondary">
                    {t('organizer:speakerContent.form.roleLabel', 'Role')}:{' '}
                    {selectedUser.roles.join(', ')}
                  </Typography>
                )}
                <Box sx={{ mt: 2 }}>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={handleEditSpeaker}
                    disabled={promoteMutation.isPending}
                    fullWidth
                    data-testid="promote-edit-speaker-button"
                  >
                    {t('organizer:speakerContent.editSpeakerProfile', 'Edit speaker profile')}
                  </Button>
                </Box>
              </Box>
            )}
 
            <Box sx={{ mt: 2 }}>
              <Button
                variant="outlined"
                size="small"
                onClick={handleCreateSpeaker}
                disabled={promoteMutation.isPending}
                fullWidth
                data-testid="promote-create-new-speaker-button"
              >
                {t('organizer:speakerContent.createNewSpeaker', 'Create new speaker')}
              </Button>
            </Box>
          </Paper>
 
          {incompleteUserBanner}
          {errorAlert}
        </Stack>
      </Box>
 
      <Box
        sx={{
          p: 2,
          display: 'flex',
          justifyContent: 'flex-end',
          gap: 2,
          borderTop: 1,
          borderColor: 'divider',
        }}
      >
        <Button variant="outlined" onClick={onBack} disabled={promoteMutation.isPending}>
          {t('common:actions.cancel', 'Cancel')}
        </Button>
        <Button
          variant="contained"
          onClick={handlePromote}
          disabled={!canPromote || promoteMutation.isPending}
          startIcon={promoteMutation.isPending ? <CircularProgress size={16} /> : null}
          data-testid="promote-submit-button"
        >
          {promoteMutation.isPending
            ? t('organizer:speakerBrainstorm.promoteDialog.submitting', 'Promoting…')
            : t('organizer:speakerBrainstorm.promoteDialog.submitButton', 'Promote')}
        </Button>
      </Box>
 
      <UserCreateEditModal
        open={userModalOpen}
        onClose={handleUserModalClose}
        onSuccess={handleUserModalSuccess}
        user={editingUser}
      />
    </>
  );
};