All files / src/components/organizer TopicStatusPanel.tsx

54.66% Statements 41/75
51.42% Branches 36/70
35.29% Functions 12/34
57.14% Lines 40/70

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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495                                                                                                                                          4x   4x         4x           1x 8x 8x 8x 8x 8x 8x             8x                 8x 8x       8x                     8x   8x 12x 8x                 8x                 8x                             8x                                 8x               8x             8x                     8x 8x                                 8x 8x                         8x 8x                     8x 8x                                                                                           8x 4x               4x                   4x                     4x 4x                                                                                                                                                                                                                                   4x 4x                                                                                                                  
/**
 * TopicStatusPanel
 * Story 8.2: AC4, AC5, AC7 — Task 9
 *
 * Organizer view of partner topic suggestions.
 * Sortable table with company logos, edit/delete for any topic, and
 * status dropdown + planned-event text input per row.
 * Only rendered for ORGANIZER role.
 */
 
import React, { useMemo, useState } from 'react';
import {
  Alert,
  Box,
  Card,
  CardActions,
  CardContent,
  Chip,
  Container,
  IconButton,
  MenuItem,
  Paper,
  Select,
  Skeleton,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableSortLabel,
  TextField,
  Tooltip,
  Typography,
} from '@mui/material';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import SaveIcon from '@mui/icons-material/Save';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { format, parseISO } from 'date-fns';
import CompanyLogo from '@/components/shared/Company/CompanyLogo';
import { TopicSuggestionForm } from '@/components/partner/TopicSuggestionForm';
import {
  deleteTopic,
  getTopics,
  updateTopic,
  updateTopicStatus,
  type TopicDTO,
} from '@/services/api/partnerTopicsApi';
 
// ─── Types ────────────────────────────────────────────────────────────────────
 
type SortKey = 'title' | 'suggestedByCompany' | 'voteCount' | 'createdAt';
type SortDir = 'asc' | 'desc';
 
// ─── Per-row local state ──────────────────────────────────────────────────────
 
interface RowState {
  status: 'PROPOSED' | 'SELECTED' | 'DECLINED';
  plannedEvent: string;
  saving: boolean;
}
 
// ─── Sorting helper ───────────────────────────────────────────────────────────
 
function sortTopics(topics: TopicDTO[], key: SortKey, dir: SortDir): TopicDTO[] {
  return [...topics].sort((a, b) => {
    const cmp =
      key === 'voteCount'
        ? a.voteCount - b.voteCount
        : key === 'createdAt'
          ? a.createdAt.localeCompare(b.createdAt) // ISO strings sort lexicographically
          : (a[key] ?? '').localeCompare(b[key] ?? '');
    return dir === 'asc' ? cmp : -cmp;
  });
}
 
// ─── Main component ───────────────────────────────────────────────────────────
 
const TopicStatusPanel: React.FC = () => {
  const { t } = useTranslation('partners');
  const { isMobile } = useBreakpoints();
  const queryClient = useQueryClient();
  const [sortKey, setSortKey] = useState<SortKey>('voteCount');
  const [sortDir, setSortDir] = useState<SortDir>('desc');
  const [editingTopic, setEditingTopic] = useState<TopicDTO | null>(null);
 
  // ─── Query ─────────────────────────────────────────────────────────────────
 
  const {
    data: topics,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['partnerTopics'],
    queryFn: getTopics,
    staleTime: 2 * 60 * 1000,
  });
 
  // ─── Sorted data ───────────────────────────────────────────────────────────
 
  const sortedTopics = useMemo(
    () => (topics ? sortTopics(topics, sortKey, sortDir) : []),
    [topics, sortKey, sortDir]
  );
 
  const handleSort = (key: SortKey) => {
    if (key === sortKey) {
      setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    } else {
      setSortKey(key);
      setSortDir(key === 'voteCount' || key === 'createdAt' ? 'desc' : 'asc');
    }
  };
 
  // ─── Per-row local state ───────────────────────────────────────────────────
 
  const [rowStates, setRowStates] = useState<Record<string, RowState>>({});
 
  const getRowStateById = (id: string, tList?: TopicDTO[]): RowState => {
    const topic = (tList ?? []).find((t) => t.id === id);
    return (
      rowStates[id] ?? {
        status: (topic?.status ?? 'PROPOSED') as RowState['status'],
        plannedEvent: topic?.plannedEvent ?? '',
        saving: false,
      }
    );
  };
 
  const setRowField = <K extends keyof RowState>(topicId: string, field: K, value: RowState[K]) => {
    setRowStates((prev) => ({
      ...prev,
      [topicId]: { ...getRowStateById(topicId, topics), ...prev[topicId], [field]: value },
    }));
  };
 
  // ─── Status update mutation ────────────────────────────────────────────────
 
  const statusMutation = useMutation({
    mutationFn: ({
      topicId,
      status,
      plannedEvent,
    }: {
      topicId: string;
      status: 'SELECTED' | 'DECLINED';
      plannedEvent?: string;
    }) => updateTopicStatus(topicId, { status, plannedEvent: plannedEvent || null }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const handleSave = async (topicId: string) => {
    const row = getRowStateById(topicId, topics);
    if (row.status === 'PROPOSED') return;
    setRowField(topicId, 'saving', true);
    try {
      await statusMutation.mutateAsync({
        topicId,
        status: row.status as 'SELECTED' | 'DECLINED',
        plannedEvent: row.plannedEvent || undefined,
      });
    } finally {
      setRowField(topicId, 'saving', false);
    }
  };
 
  // ─── Edit mutation ─────────────────────────────────────────────────────────
 
  const editMutation = useMutation({
    mutationFn: ({ id, title, description }: { id: string; title: string; description: string }) =>
      updateTopic(id, { title, description }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const handleEdit = async (title: string, description: string) => {
    if (!editingTopic) return;
    await editMutation.mutateAsync({ id: editingTopic.id, title, description });
  };
 
  // ─── Delete mutation ───────────────────────────────────────────────────────
 
  const deleteMutation = useMutation({
    mutationFn: (topicId: string) => deleteTopic(topicId),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  // ─── Shared per-row controls (used by both table rows and mobile cards) ──────
 
  // Story 7.1: COMMUNITY (attendee) suggestions have no company — show an origin badge
  // instead of a (null) company logo so organizers can distinguish them at a glance.
  const renderOrigin = (topic: TopicDTO) =>
    topic.source === 'COMMUNITY' ? (
      <Chip
        size="small"
        color="info"
        variant="outlined"
        label={t('portal.topics.source.community')}
        data-testid={`topic-source-community-${topic.id}`}
      />
    ) : (
      <CompanyLogo
        companyName={topic.suggestedByCompany ?? ''}
        variant="full"
        maxWidth={80}
        maxHeight={40}
      />
    );
 
  const renderStatusSelect = (topic: TopicDTO, row: RowState) => (
    <Select
      size="small"
      value={row.status}
      onChange={(e) => setRowField(topic.id, 'status', e.target.value as RowState['status'])}
      sx={{ minWidth: 120 }}
      data-testid={`status-select-${topic.id}`}
    >
      <MenuItem value="PROPOSED">{t('portal.topics.status.proposed')}</MenuItem>
      <MenuItem value="SELECTED">{t('portal.topics.status.selected')}</MenuItem>
      <MenuItem value="DECLINED">{t('portal.topics.status.declined')}</MenuItem>
    </Select>
  );
 
  const renderPlannedEventField = (topic: TopicDTO, row: RowState) =>
    row.status === 'SELECTED' ? (
      <TextField
        size="small"
        placeholder={t('topicStatus.eventCodePlaceholder')}
        value={row.plannedEvent}
        onChange={(e) => setRowField(topic.id, 'plannedEvent', e.target.value)}
        inputProps={{ maxLength: 100 }}
        data-testid={`planned-event-${topic.id}`}
      />
    ) : null;
 
  const renderActions = (topic: TopicDTO, row: RowState) => (
    <Box
      sx={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-end',
        gap: 0.5,
      }}
    >
      <Tooltip title={t('common:actions.save')}>
        <span>
          <IconButton
            size="small"
            color="primary"
            onClick={() => handleSave(topic.id)}
            disabled={row.saving || row.status === 'PROPOSED'}
            data-testid={`save-status-${topic.id}`}
          >
            <SaveIcon fontSize="small" />
          </IconButton>
        </span>
      </Tooltip>
      <Tooltip title={t('common:actions.edit')}>
        <IconButton
          size="small"
          onClick={() => setEditingTopic(topic)}
          data-testid={`edit-topic-${topic.id}`}
        >
          <EditIcon fontSize="small" />
        </IconButton>
      </Tooltip>
      <Tooltip title={t('common:actions.delete')}>
        <IconButton
          size="small"
          color="error"
          onClick={() => deleteMutation.mutate(topic.id)}
          disabled={deleteMutation.isPending}
          data-testid={`delete-topic-${topic.id}`}
        >
          <DeleteIcon fontSize="small" />
        </IconButton>
      </Tooltip>
    </Box>
  );
 
  // ─── Loading state ─────────────────────────────────────────────────────────
 
  if (isLoading) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }} data-testid="topics-status-panel-loading">
        <Skeleton variant="text" width={300} height={40} sx={{ mb: 2 }} />
        <Skeleton variant="rectangular" height={300} />
      </Container>
    );
  }
 
  Iif (isError) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Alert severity="error">{t('portal.topics.error')}</Alert>
      </Container>
    );
  }
 
  // ─── Main render ───────────────────────────────────────────────────────────
 
  return (
    <Container maxWidth="xl" sx={{ py: 4 }} data-testid="topic-status-panel">
      <Typography variant="h5" sx={{ mb: 3 }}>
        {t('portal.topics.organizer.title')}
      </Typography>
 
      {!topics || topics.length === 0 ? (
        <Typography color="text.secondary">{t('portal.topics.empty')}</Typography>
      ) : isMobile ? (
        <Box data-testid="organizer-topics-cards">
          {sortedTopics.map((topic) => {
            const row = getRowStateById(topic.id, topics);
            return (
              <Card
                key={topic.id}
                variant="outlined"
                sx={{ mb: 2 }}
                data-testid={`organizer-topic-card-${topic.id}`}
              >
                <CardContent>
                  <Stack spacing={1.5}>
                    {/* Title + description */}
                    <Box>
                      <Typography variant="subtitle1" fontWeight={600}>
                        {topic.title}
                      </Typography>
                      {topic.description && (
                        <Typography variant="caption" color="text.secondary">
                          {topic.description}
                        </Typography>
                      )}
                    </Box>
 
                    {/* Company + votes */}
                    <Box
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        gap: 1,
                      }}
                    >
                      {renderOrigin(topic)}
                      <Typography variant="body2" color="text.secondary">
                        {t('portal.topics.organizer.col.votes')}: {topic.voteCount}
                      </Typography>
                    </Box>
 
                    {/* Created date (parity with table Date column) */}
                    <Typography variant="caption" color="text.secondary">
                      {format(parseISO(topic.createdAt), 'd MMM yyyy')}
                    </Typography>
 
                    {/* Status select */}
                    {renderStatusSelect(topic, row)}
 
                    {/* Planned event (only when SELECTED) */}
                    {renderPlannedEventField(topic, row)}
                  </Stack>
                </CardContent>
                <CardActions sx={{ justifyContent: 'flex-end' }}>
                  {renderActions(topic, row)}
                </CardActions>
              </Card>
            );
          })}
        </Box>
      ) : (
        <TableContainer
          component={Paper}
          variant="outlined"
          data-testid="organizer-topics-table"
          sx={{ overflowX: 'auto' }}
        >
          <Table size="small" sx={{ minWidth: 800 }}>
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 700, width: '30%' }}>
                  <TableSortLabel
                    active={sortKey === 'title'}
                    direction={sortKey === 'title' ? sortDir : 'asc'}
                    onClick={() => handleSort('title')}
                  >
                    {t('common:labels.title')}
                  </TableSortLabel>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '15%' }}>
                  <TableSortLabel
                    active={sortKey === 'suggestedByCompany'}
                    direction={sortKey === 'suggestedByCompany' ? sortDir : 'asc'}
                    onClick={() => handleSort('suggestedByCompany')}
                  >
                    {t('portal.topics.organizer.col.company')}
                  </TableSortLabel>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '6%' }} align="right">
                  <TableSortLabel
                    active={sortKey === 'voteCount'}
                    direction={sortKey === 'voteCount' ? sortDir : 'desc'}
                    onClick={() => handleSort('voteCount')}
                  >
                    {t('portal.topics.organizer.col.votes')}
                  </TableSortLabel>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '10%' }}>
                  <TableSortLabel
                    active={sortKey === 'createdAt'}
                    direction={sortKey === 'createdAt' ? sortDir : 'desc'}
                    onClick={() => handleSort('createdAt')}
                  >
                    {t('common:labels.date')}
                  </TableSortLabel>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '14%' }}>
                  {t('common:labels.status')}
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '16%' }}>
                  {t('portal.topics.organizer.plannedEvent')}
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '15%' }} align="right">
                  {t('common:labels.actions')}
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {sortedTopics.map((topic) => {
                const row = getRowStateById(topic.id, topics);
                return (
                  <TableRow key={topic.id} hover data-testid={`organizer-topic-row-${topic.id}`}>
                    {/* Title + description */}
                    <TableCell>
                      <Typography variant="body2" fontWeight={600}>
                        {topic.title}
                      </Typography>
                      {topic.description && (
                        <Typography variant="caption" color="text.secondary">
                          {topic.description}
                        </Typography>
                      )}
                    </TableCell>
 
                    {/* Company logo, or Community badge for attendee-sourced topics */}
                    <TableCell>{renderOrigin(topic)}</TableCell>
 
                    {/* Vote count */}
                    <TableCell align="right">{topic.voteCount}</TableCell>
 
                    {/* Date column */}
                    <TableCell>
                      <Typography variant="body2" color="text.secondary" noWrap>
                        {format(parseISO(topic.createdAt), 'd MMM yyyy')}
                      </Typography>
                    </TableCell>
 
                    {/* Status select */}
                    <TableCell>{renderStatusSelect(topic, row)}</TableCell>
 
                    {/* Planned event */}
                    <TableCell>{renderPlannedEventField(topic, row)}</TableCell>
 
                    {/* Actions: save + edit + delete */}
                    <TableCell align="right">{renderActions(topic, row)}</TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      )}
 
      {/* Edit dialog */}
      <TopicSuggestionForm
        open={editingTopic !== null}
        onClose={() => setEditingTopic(null)}
        onSubmit={handleEdit}
        initialTitle={editingTopic?.title ?? ''}
        initialDescription={editingTopic?.description ?? ''}
        editMode
      />
    </Container>
  );
};
 
export default TopicStatusPanel;