All files / src/components/partner TopicListPage.tsx

67.5% Statements 54/80
60.56% Branches 43/71
50% Functions 19/38
70.27% Lines 52/74

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                                                                                                                1x                 11x   20x         20x           1x 25x 25x 25x 25x 25x 25x 25x             25x                 25x 22x       25x                     25x                   25x               25x             25x             25x 1x   1x 1x 1x   3x     1x           1x       25x 1x   1x 1x 1x   3x         1x           1x       25x 2x 1x   1x       25x           25x 11x       33x               14x 1x                     13x             2x                                                                                                     36x       36x 36x                                                                                                                                                                                                   2x                                                                                                    
/**
 * TopicListPage
 * Story 8.2: AC1, AC2, AC5, AC7, AC8 — Task 7
 *
 * Displays all topic suggestions as a sortable table.
 * Columns: Topic (title + description + status), Company, Actions (vote + edit/delete).
 * Partner can vote/unvote and submit new topics.
 */
 
import React, { useMemo, useState } from 'react';
import {
  Alert,
  Box,
  Button,
  Chip,
  Container,
  IconButton,
  Paper,
  Skeleton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TableSortLabel,
  Tooltip,
  Typography,
} from '@mui/material';
import ThumbUpIcon from '@mui/icons-material/ThumbUp';
import ThumbUpOutlinedIcon from '@mui/icons-material/ThumbUpOutlined';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import { format, parseISO } from 'date-fns';
import { useAuth } from '@/hooks/useAuth/useAuth';
import CompanyLogo from '@/components/shared/Company/CompanyLogo';
import { TopicSuggestionForm } from './TopicSuggestionForm';
import {
  castVote,
  deleteTopic,
  getTopics,
  removeVote,
  suggestTopic,
  updateTopic,
  type TopicDTO,
} from '@/services/api/partnerTopicsApi';
 
// ─── Types ────────────────────────────────────────────────────────────────────
 
type SortKey = 'title' | 'suggestedByCompany' | 'voteCount' | 'createdAt';
type SortDir = 'asc' | 'desc';
 
// ─── Status badge colours ─────────────────────────────────────────────────────
 
const STATUS_COLOR: Record<string, 'default' | 'success' | 'error'> = {
  PROPOSED: 'default',
  SELECTED: 'success',
  DECLINED: 'error',
};
 
// ─── 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 TopicListPage: React.FC = () => {
  const { t } = useTranslation('partners');
  const queryClient = useQueryClient();
  const { user } = useAuth();
  const [formOpen, setFormOpen] = useState(false);
  const [editingTopic, setEditingTopic] = useState<TopicDTO | null>(null);
  const [sortKey, setSortKey] = useState<SortKey>('voteCount');
  const [sortDir, setSortDir] = useState<SortDir>('desc');
 
  // ─── 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');
    }
  };
 
  // ─── Suggest mutation ──────────────────────────────────────────────────────
 
  const suggestMutation = useMutation({
    mutationFn: ({ title, description }: { title: string; description: string }) =>
      suggestTopic({ title, description }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  // ─── Edit / Delete mutations ───────────────────────────────────────────────
 
  const editMutation = useMutation({
    mutationFn: ({ id, title, description }: { id: string; title: string; description: string }) =>
      updateTopic(id, { title, description }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const deleteMutation = useMutation({
    mutationFn: (topicId: string) => deleteTopic(topicId),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const handleEdit = async (title: string, description: string) => {
    if (!editingTopic) return;
    await editMutation.mutateAsync({ id: editingTopic.id, title, description });
  };
 
  // ─── Vote mutations (optimistic) ───────────────────────────────────────────
 
  const castVoteMutation = useMutation({
    mutationFn: (topicId: string) => castVote(topicId),
    onMutate: async (topicId) => {
      await queryClient.cancelQueries({ queryKey: ['partnerTopics'] });
      const prev = queryClient.getQueryData<TopicDTO[]>(['partnerTopics']);
      queryClient.setQueryData<TopicDTO[]>(['partnerTopics'], (old) =>
        (old ?? []).map((t) =>
          t.id === topicId ? { ...t, voteCount: t.voteCount + 1, currentPartnerHasVoted: true } : t
        )
      );
      return { prev };
    },
    onError: (_err, _topicId, ctx) => {
      if (ctx?.prev) queryClient.setQueryData(['partnerTopics'], ctx.prev);
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const removeVoteMutation = useMutation({
    mutationFn: (topicId: string) => removeVote(topicId),
    onMutate: async (topicId) => {
      await queryClient.cancelQueries({ queryKey: ['partnerTopics'] });
      const prev = queryClient.getQueryData<TopicDTO[]>(['partnerTopics']);
      queryClient.setQueryData<TopicDTO[]>(['partnerTopics'], (old) =>
        (old ?? []).map((t) =>
          t.id === topicId
            ? { ...t, voteCount: Math.max(0, t.voteCount - 1), currentPartnerHasVoted: false }
            : t
        )
      );
      return { prev };
    },
    onError: (_err, _topicId, ctx) => {
      if (ctx?.prev) queryClient.setQueryData(['partnerTopics'], ctx.prev);
    },
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ['partnerTopics'] });
    },
  });
 
  const handleVoteToggle = (topic: TopicDTO) => {
    if (topic.currentPartnerHasVoted) {
      removeVoteMutation.mutate(topic.id);
    } else {
      castVoteMutation.mutate(topic.id);
    }
  };
 
  const handleSuggest = async (title: string, description: string) => {
    await suggestMutation.mutateAsync({ title, description });
  };
 
  // ─── Loading state ─────────────────────────────────────────────────────────
 
  if (isLoading) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }} data-testid="topics-loading">
        <Skeleton variant="text" width={300} height={40} sx={{ mb: 2 }} />
        {[1, 2, 3].map((i) => (
          <Skeleton key={i} variant="rectangular" height={72} sx={{ mb: 1, borderRadius: 1 }} />
        ))}
      </Container>
    );
  }
 
  // ─── Error state ───────────────────────────────────────────────────────────
 
  if (isError) {
    return (
      <Container maxWidth="xl" sx={{ py: 4 }}>
        <Alert severity="error" data-testid="topics-error">
          {t('portal.topics.error')}
        </Alert>
      </Container>
    );
  }
 
  // ─── Main render ───────────────────────────────────────────────────────────
 
  return (
    <Container maxWidth="xl" sx={{ py: 4 }} data-testid="topic-list-page">
      {/* Header row */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h5">{t('portal.topics.title')}</Typography>
        <Button
          variant="contained"
          onClick={() => setFormOpen(true)}
          data-testid="suggest-topic-button"
        >
          {t('portal.topics.suggest')}
        </Button>
      </Box>
 
      {/* Empty state */}
      {!topics || topics.length === 0 ? (
        <Typography color="text.secondary" data-testid="topics-empty">
          {t('portal.topics.empty')}
        </Typography>
      ) : (
        <TableContainer component={Paper} variant="outlined" data-testid="topics-list">
          <Table size="medium">
            <TableHead>
              <TableRow>
                <TableCell sx={{ fontWeight: 700, width: '55%' }}>
                  <TableSortLabel
                    active={sortKey === 'title'}
                    direction={sortKey === 'title' ? sortDir : 'asc'}
                    onClick={() => handleSort('title')}
                  >
                    {t('portal.topics.col.topic')}
                  </TableSortLabel>
                </TableCell>
                <TableCell sx={{ fontWeight: 700, width: '15%' }}>
                  <TableSortLabel
                    active={sortKey === 'suggestedByCompany'}
                    direction={sortKey === 'suggestedByCompany' ? sortDir : 'asc'}
                    onClick={() => handleSort('suggestedByCompany')}
                  >
                    {t('portal.topics.col.company')}
                  </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: '20%' }} align="right">
                  {t('common:labels.actions')}
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {sortedTopics.map((topic) => {
                const statusKey = topic.status.toLowerCase() as
                  | 'proposed'
                  | 'selected'
                  | 'declined';
                const isOwn = topic.suggestedByCompany === user?.companyName;
                return (
                  <TableRow key={topic.id} hover data-testid={`topic-item-${topic.id}`}>
                    {/* Topic column */}
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                        <Typography variant="subtitle2" fontWeight={600}>
                          {topic.title}
                        </Typography>
                        <Chip
                          label={t(`portal.topics.status.${statusKey}`)}
                          color={STATUS_COLOR[topic.status]}
                          size="small"
                          data-testid={`topic-status-${topic.id}`}
                        />
                        {topic.status === 'SELECTED' && topic.plannedEvent && (
                          <Typography
                            variant="caption"
                            color="text.secondary"
                            data-testid={`topic-planned-event-${topic.id}`}
                          >
                            {t('portal.topics.plannedFor')}: {topic.plannedEvent}
                          </Typography>
                        )}
                      </Box>
                      {topic.description && (
                        <Typography variant="body2" color="text.secondary" sx={{ mt: 0.5 }}>
                          {topic.description}
                        </Typography>
                      )}
                    </TableCell>
 
                    {/* Company column */}
                    <TableCell>
                      <CompanyLogo
                        companyName={topic.suggestedByCompany ?? ''}
                        variant="full"
                        maxWidth={80}
                        maxHeight={48}
                      />
                    </TableCell>
 
                    {/* Date column */}
                    <TableCell>
                      <Typography variant="body2" color="text.secondary" noWrap>
                        {format(parseISO(topic.createdAt), 'd MMM yyyy')}
                      </Typography>
                    </TableCell>
 
                    {/* Actions column */}
                    <TableCell align="right">
                      <Box
                        sx={{
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'flex-end',
                          gap: 1,
                        }}
                      >
                        {/* Edit / Delete — own company only */}
                        {isOwn && (
                          <>
                            <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>
                          </>
                        )}
 
                        {/* Vote button + count */}
                        <Box
                          sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}
                        >
                          <Tooltip
                            title={
                              topic.currentPartnerHasVoted
                                ? t('portal.topics.unvote')
                                : t('portal.topics.vote')
                            }
                          >
                            <IconButton
                              size="small"
                              color={topic.currentPartnerHasVoted ? 'primary' : 'default'}
                              onClick={() => handleVoteToggle(topic)}
                              aria-label={
                                topic.currentPartnerHasVoted
                                  ? t('portal.topics.unvote')
                                  : t('portal.topics.vote')
                              }
                              data-testid={`vote-button-${topic.id}`}
                            >
                              {topic.currentPartnerHasVoted ? (
                                <ThumbUpIcon fontSize="small" />
                              ) : (
                                <ThumbUpOutlinedIcon fontSize="small" />
                              )}
                            </IconButton>
                          </Tooltip>
                          <Typography variant="caption" data-testid={`vote-count-${topic.id}`}>
                            {topic.voteCount}
                          </Typography>
                        </Box>
                      </Box>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </TableContainer>
      )}
 
      {/* Suggestion form dialog */}
      <TopicSuggestionForm
        open={formOpen}
        onClose={() => setFormOpen(false)}
        onSubmit={handleSuggest}
      />
 
      {/* Edit form dialog */}
      <TopicSuggestionForm
        open={editingTopic !== null}
        onClose={() => setEditingTopic(null)}
        onSubmit={handleEdit}
        initialTitle={editingTopic?.title ?? ''}
        initialDescription={editingTopic?.description ?? ''}
        editMode
      />
    </Container>
  );
};
 
export default TopicListPage;