All files / src/components/organizer/PartnerManagement PartnerNotesTab.tsx

94.82% Statements 55/58
79.41% Branches 27/34
88.23% Functions 15/17
94.82% Lines 55/58

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                                                                                          5x 38x 38x               5x 38x 38x 38x 38x     5x 23x 23x 23x 23x             23x     23x 23x 23x   23x 1x 1x 1x     23x 1x 1x 1x     23x 2x     23x 1x 1x 1x       23x 1x     23x 1x     1x   1x 1x 1x     23x 1x 1x 1x     23x 1x             22x 1x               21x 2x                                                                                                                                     19x                                       38x                   1x             2x                                                                                                                                     1x             1x                                                  
import React, { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Stack,
  Chip,
  Alert,
  IconButton,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { Add, Edit, Delete, Note as NoteIcon } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { BATbernLoader } from '@components/shared/BATbernLoader';
import { usePartnerNotes } from '@/hooks/usePartnerNotes';
import { usePartnerDetailStore } from '@/stores/partnerDetailStore';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import type { PartnerNoteDTO } from '@/services/api/partnerNotesApi';
 
type UserRole = 'ORGANIZER' | 'PARTNER' | 'SPEAKER' | 'ATTENDEE';
 
interface PartnerNotesTabProps {
  companyName: string;
  role?: UserRole; // Story 8.0: read-only for PARTNER
}
 
interface NoteFormData {
  title: string;
  content: string;
}
 
interface DeleteConfirmState {
  noteId: string;
  noteTitle: string;
}
 
type Note = PartnerNoteDTO;
 
// Format date for display
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
};
 
// Extract plain text preview from HTML content
const getContentPreview = (htmlContent: string, maxLength: number = 100): string => {
  const div = document.createElement('div');
  div.innerHTML = htmlContent;
  const text = div.textContent || div.innerText || '';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
};
 
const PartnerNotesTab: React.FC<PartnerNotesTabProps> = ({ companyName, role }) => {
  const { t } = useTranslation('partners');
  const { isMobile } = useBreakpoints();
  const { showNoteModal, setShowNoteModal } = usePartnerDetailStore();
  const isPartner = role === 'PARTNER';
  const {
    data: notes,
    isLoading,
    error,
    createNote,
    updateNote,
    deleteNote,
  } = usePartnerNotes(companyName);
 
  const [editingNote, setEditingNote] = useState<Note | null>(null);
  const [formData, setFormData] = useState<NoteFormData>({ title: '', content: '' });
  const [deleteConfirm, setDeleteConfirm] = useState<DeleteConfirmState | null>(null);
 
  const handleAddNote = () => {
    setEditingNote(null);
    setFormData({ title: '', content: '' });
    setShowNoteModal(true);
  };
 
  const handleEditNote = (note: Note) => {
    setEditingNote(note);
    setFormData({ title: note.title, content: note.content });
    setShowNoteModal(true);
  };
 
  const handleDeleteNote = (noteId: string, noteTitle: string) => {
    setDeleteConfirm({ noteId, noteTitle });
  };
 
  const handleConfirmDelete = () => {
    Eif (deleteConfirm) {
      deleteNote(deleteConfirm.noteId);
      setDeleteConfirm(null);
    }
  };
 
  const handleCancelDelete = () => {
    setDeleteConfirm(null);
  };
 
  const handleSaveNote = () => {
    Iif (editingNote) {
      updateNote({ noteId: editingNote.id, ...formData });
    } else {
      createNote(formData);
    }
    setShowNoteModal(false);
    setFormData({ title: '', content: '' });
    setEditingNote(null);
  };
 
  const handleCloseModal = () => {
    setShowNoteModal(false);
    setFormData({ title: '', content: '' });
    setEditingNote(null);
  };
 
  if (isLoading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="300px">
        <BATbernLoader size={96} />
      </Box>
    );
  }
 
  if (error) {
    return (
      <Alert severity="error">
        <Typography variant="h6">{t('detail.notesTab.failedToLoadNotes')}</Typography>
        <Typography variant="body2">{(error as Error).message}</Typography>
      </Alert>
    );
  }
 
  if (!notes || notes.length === 0) {
    return (
      <Box textAlign="center" py={6}>
        <NoteIcon sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
        <Typography variant="h6" color="text.secondary" gutterBottom>
          {t('detail.notesTab.noNotes')}
        </Typography>
        {!isPartner && (
          <>
            <Typography variant="body2" color="text.secondary" mb={3}>
              Add your first note to track important information about this partner
            </Typography>
            <Button
              variant="contained"
              startIcon={<Add />}
              onClick={handleAddNote}
              data-testid="add-note-button"
            >
              {t('detail.notesTab.addNote')}
            </Button>
          </>
        )}
 
        {/* Note Modal — must be present in empty state too (showNoteModal set in store) */}
        <Dialog
          open={showNoteModal}
          onClose={handleCloseModal}
          maxWidth="md"
          fullWidth
          fullScreen={isMobile}
        >
          <DialogTitle>{t('detail.notesTab.addNote')}</DialogTitle>
          <DialogContent>
            <Stack spacing={3} mt={1}>
              <TextField
                label={t('common:labels.title')}
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                fullWidth
                required
              />
              <TextField
                label={t('detail.notesTab.contentLabel')}
                value={formData.content}
                onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                multiline
                rows={8}
                fullWidth
                required
                helperText={t('detail.notesTab.htmlSupported')}
              />
            </Stack>
          </DialogContent>
          <DialogActions>
            <Button onClick={handleCloseModal}>{t('common:actions.cancel')}</Button>
            <Button
              variant="contained"
              onClick={handleSaveNote}
              disabled={!formData.title || !formData.content}
            >
              {t('common:actions.save')}
            </Button>
          </DialogActions>
        </Dialog>
      </Box>
    );
  }
 
  return (
    <Box>
      {/* Header with add button — hidden for PARTNER */}
      <Stack direction="row" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h6">{t('detail.notesTab.title')}</Typography>
        {!isPartner && (
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={handleAddNote}
            data-testid="add-note-button"
          >
            {t('detail.notesTab.addNote')}
          </Button>
        )}
      </Stack>
 
      {/* Notes list */}
      <Stack spacing={2}>
        {notes.map((note) => (
          <Card key={note.id} data-testid={`note-item-${note.id}`}>
            <CardContent>
              <Stack direction="row" justifyContent="space-between" alignItems="flex-start" mb={2}>
                <Typography variant="h6" fontWeight="medium">
                  {note.title}
                </Typography>
                {!isPartner && (
                  <Stack direction="row" spacing={1}>
                    <IconButton
                      size="small"
                      onClick={() => handleEditNote(note)}
                      aria-label={t('detail.notesTab.editNote')}
                    >
                      <Edit fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDeleteNote(note.id, note.title)}
                      aria-label={t('detail.notesTab.deleteNote')}
                      color="error"
                    >
                      <Delete fontSize="small" />
                    </IconButton>
                  </Stack>
                )}
              </Stack>
 
              {/* Content preview */}
              <Typography variant="body2" color="text.secondary" mb={2}>
                {getContentPreview(note.content)}
              </Typography>
 
              {/* Author and timestamp */}
              <Stack direction="row" spacing={2} alignItems="center">
                <Chip label={note.authorUsername} size="small" variant="outlined" />
                <Typography variant="caption" color="text.secondary">
                  {formatDate(note.createdAt)}
                  {note.updatedAt !== note.createdAt && ' (edited)'}
                </Typography>
              </Stack>
            </CardContent>
          </Card>
        ))}
      </Stack>
 
      {/* Delete Confirmation Dialog */}
      <Dialog open={!!deleteConfirm} onClose={handleCancelDelete} fullScreen={isMobile}>
        <DialogTitle>{t('detail.notesTab.deleteNoteConfirmTitle')}</DialogTitle>
        <DialogContent>
          <Typography>
            {t('detail.notesTab.deleteNoteConfirmMessage', {
              title: deleteConfirm?.noteTitle ?? '',
            })}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete}>{t('common:actions.cancel')}</Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleConfirmDelete}
            data-testid="confirm-delete-note"
          >
            {t('common:actions.delete')}
          </Button>
        </DialogActions>
      </Dialog>
 
      {/* Note Modal */}
      <Dialog
        open={showNoteModal}
        onClose={handleCloseModal}
        maxWidth="md"
        fullWidth
        fullScreen={isMobile}
      >
        <DialogTitle>
          {editingNote ? t('detail.notesTab.editNote') : t('detail.notesTab.addNote')}
        </DialogTitle>
        <DialogContent>
          <Stack spacing={3} mt={1}>
            <TextField
              label={t('common:labels.title')}
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              fullWidth
              required
            />
            <TextField
              label={t('detail.notesTab.contentLabel')}
              value={formData.content}
              onChange={(e) => setFormData({ ...formData, content: e.target.value })}
              multiline
              rows={8}
              fullWidth
              required
              helperText={t('detail.notesTab.htmlSupported')}
            />
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseModal}>{t('common:actions.cancel')}</Button>
          <Button
            variant="contained"
            onClick={handleSaveNote}
            disabled={!formData.title || !formData.content}
          >
            {t('common:actions.save')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};
 
export default PartnerNotesTab;