All files / src/components/organizer/Admin EmailTemplateEditModal.tsx

76.11% Statements 51/67
81.25% Branches 65/80
57.14% Functions 8/14
76.11% Lines 51/67

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                                                                                                            27x 27x   27x 16x   27x     1x             27x 27x 27x 27x     27x 27x         27x 27x 27x     27x       27x   27x       27x 27x 27x   27x   27x 16x 14x 14x 14x       27x 27x             27x 5x     5x 5x 4x     5x       5x 1x     1x     4x 4x 3x                   1x 1x 1x                                                       3x                               27x           27x                                                                                                                   8x                                                                                   11x                                                                     22x                           12x                                                              
/**
 * EmailTemplateEditModal (Story 10.2)
 *
 * Two modes:
 * - Edit mode (template prop provided): edit existing template
 * - Create mode (template undefined): create new content template
 *
 * Two editor modes:
 * - Layout mode (isLayoutMode=true): Monaco Editor, no subject field
 * - Content mode (isLayoutMode=false): TinyMCE WYSIWYG, subject field, layoutKey selector
 */
 
import React, { useCallback, useEffect, useRef, useState } from 'react';
import Editor from '@monaco-editor/react';
import { Editor as TinyMCEEditor } from '@tinymce/tinymce-react';
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
  Typography,
  useMediaQuery,
  useTheme,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import {
  useCreateEmailTemplate,
  useLayoutTemplates,
  useUpdateEmailTemplate,
} from '@/hooks/useEmailTemplates';
import type { EmailTemplateResponse } from '@/hooks/useEmailTemplates';
 
interface Props {
  /** When provided: edit mode. When undefined: create mode. */
  template?: EmailTemplateResponse;
  isLayoutMode: boolean;
  /** Category to assign when creating a new template (defaults to 'SPEAKER'). */
  initialCategory?: string;
  /** When set, pre-fills content/subject/layout from this template (create mode only). */
  cloneFrom?: EmailTemplateResponse;
  onClose: () => void;
}
 
function extractVariables(html: string): string[] {
  const matches = new Set<string>();
  const re = /\{\{(\w+)\}\}/g;
  let m;
  while ((m = re.exec(html)) !== null) {
    matches.add(m[1]);
  }
  return Array.from(matches);
}
 
export const EmailTemplateEditModal: React.FC<Props> = ({
  template,
  isLayoutMode,
  initialCategory,
  cloneFrom,
  onClose,
}) => {
  const { t } = useTranslation();
  const theme = useTheme();
  const isFullScreen = useMediaQuery(theme.breakpoints.down('md'));
  const isEdit = Boolean(template);
 
  // Create-mode fields
  const [newTemplateKey, setNewTemplateKey] = useState('');
  const [newLocale, setNewLocale] = useState<'de' | 'en'>(
    (cloneFrom?.locale as 'de' | 'en') ?? 'de'
  );
 
  // Shared fields (pre-fill from cloneFrom in create mode)
  const [subject, setSubject] = useState(template?.subject ?? cloneFrom?.subject ?? '');
  const [htmlBody, setHtmlBody] = useState(template?.htmlBody ?? cloneFrom?.htmlBody ?? '');
  const [layoutKey, setLayoutKey] = useState(
    template?.layoutKey ?? cloneFrom?.layoutKey ?? 'batbern-default'
  );
  const [error, setError] = useState<string | null>(null);
 
  // Track TinyMCE content in a ref to avoid re-renders on every keystroke
  // (re-renders cause cursor to jump to top). Sync to state on blur for validation.
  const tinymceContentRef = useRef(htmlBody);
 
  const syncHtmlBodyFromEditor = useCallback(() => {
    setHtmlBody(tinymceContentRef.current);
  }, []);
 
  const { data: layouts = [] } = useLayoutTemplates();
  const createMutation = useCreateEmailTemplate();
  const updateMutation = useUpdateEmailTemplate();
 
  const isSaving = createMutation.isPending || updateMutation.isPending;
 
  useEffect(() => {
    if (template) {
      setSubject(template.subject ?? '');
      setHtmlBody(template.htmlBody);
      setLayoutKey(template.layoutKey ?? 'batbern-default');
    }
  }, [template]);
 
  const missingContentPlaceholder = isLayoutMode && !htmlBody.includes('{{content}}');
  const detectedVars = [
    ...new Set([
      ...(template?.variables ? Object.keys(template.variables) : []),
      ...extractVariables(htmlBody),
    ]),
  ];
 
  const handleSave = async () => {
    setError(null);
 
    // Sync latest TinyMCE content before validation (ref may be ahead of state)
    const currentHtmlBody = isLayoutMode ? htmlBody : tinymceContentRef.current;
    if (!isLayoutMode) {
      setHtmlBody(currentHtmlBody);
    }
 
    Iif (!currentHtmlBody.trim()) {
      setError(t('emailTemplates.validation.htmlBodyRequired', 'HTML body is required.'));
      return;
    }
    if (!isLayoutMode && !subject.trim()) {
      setError(
        t('emailTemplates.validation.subjectRequired', 'Subject is required for content templates.')
      );
      return;
    }
 
    try {
      if (isEdit && template) {
        await updateMutation.mutateAsync({
          templateKey: template.templateKey,
          locale: template.locale,
          req: {
            subject: isLayoutMode ? undefined : subject,
            htmlBody: currentHtmlBody,
            layoutKey: isLayoutMode ? undefined : layoutKey || undefined,
          },
        });
      } else {
        Eif (!newTemplateKey.trim()) {
          setError(t('emailTemplates.validation.templateKeyRequired', 'Template key is required.'));
          return;
        }
        if (/\s/.test(newTemplateKey)) {
          setError(
            t(
              'emailTemplates.validation.templateKeyNoSpaces',
              'Template key must not contain spaces.'
            )
          );
          return;
        }
        await createMutation.mutateAsync({
          templateKey: newTemplateKey.trim(),
          locale: newLocale,
          category: (initialCategory ?? 'SPEAKER') as
            | 'SPEAKER'
            | 'REGISTRATION'
            | 'TASK_REMINDER'
            | 'LAYOUT'
            | 'NEWSLETTER'
            | 'VENUE_COORDINATION'
            | 'REGISTRANT_NOTICE',
          isLayout: false,
          subject,
          htmlBody: currentHtmlBody,
          layoutKey: layoutKey || undefined,
        });
      }
      onClose();
    } catch (err: unknown) {
      const status = (err as { response?: { status?: number } })?.response?.status;
      if (status === 409) {
        setError(
          t(
            'emailTemplates.validation.duplicateKey',
            'A template with this key already exists for this locale. Please choose a different key.'
          )
        );
      } else {
        setError(t('emailTemplates.saveFailed', 'Failed to save template. Please try again.'));
      }
    }
  };
 
  const title = isEdit
    ? t('emailTemplates.editTitle', 'Edit Template')
    : cloneFrom
      ? t('emailTemplates.duplicateTitle', 'Duplicate Template')
      : t('emailTemplates.createTitle', 'New Template');
 
  return (
    <Dialog
      open
      onClose={onClose}
      maxWidth="lg"
      fullWidth
      fullScreen={isFullScreen}
      data-testid="email-template-modal"
    >
      <DialogTitle>{title}</DialogTitle>
      <DialogContent dividers>
        {/* Metadata chips (edit mode) */}
        {template && (
          <Box sx={{ mb: 2, display: 'flex', gap: 1, flexWrap: 'wrap' }}>
            <Chip label={template.templateKey} size="small" variant="outlined" />
            <Chip label={template.locale.toUpperCase()} size="small" color="primary" />
            <Chip label={template.category} size="small" />
            {template.isSystemTemplate && (
              <Chip
                label={t('emailTemplates.systemTemplate', 'System Template')}
                size="small"
                color="warning"
              />
            )}
          </Box>
        )}
 
        {/* Create-mode: templateKey + locale */}
        {!isEdit && (
          <Box sx={{ display: 'flex', gap: 2, mb: 2 }}>
            <TextField
              label={t('emailTemplates.templateKey', 'Template Key')}
              value={newTemplateKey}
              onChange={(e) => setNewTemplateKey(e.target.value)}
              fullWidth
              required
              helperText="e.g. my-custom-invitation"
              inputProps={{ 'data-testid': 'email-template-key-input' }}
            />
            <FormControl sx={{ minWidth: 100 }}>
              <InputLabel>{t('emailTemplates.locale', 'Locale')}</InputLabel>
              <Select
                value={newLocale}
                label={t('emailTemplates.locale', 'Locale')}
                onChange={(e) => setNewLocale(e.target.value as 'de' | 'en')}
              >
                <MenuItem value="de">DE</MenuItem>
                <MenuItem value="en">EN</MenuItem>
              </Select>
            </FormControl>
          </Box>
        )}
 
        {/* Subject (content mode only) */}
        {!isLayoutMode && (
          <TextField
            label={t('emailTemplates.subject', 'Subject')}
            value={subject}
            onChange={(e) => setSubject(e.target.value)}
            fullWidth
            required
            inputProps={{ maxLength: 500, 'data-testid': 'email-template-subject-input' }}
            sx={{ mb: 2 }}
          />
        )}
 
        <Typography variant="subtitle2" gutterBottom>
          {t('emailTemplates.htmlBody', 'HTML Content')}
        </Typography>
 
        {missingContentPlaceholder && (
          <Alert severity="warning" sx={{ mb: 1 }}>
            {t(
              'emailTemplates.missingContentPlaceholder',
              '{{content}} placeholder missing — email body will be empty'
            )}
          </Alert>
        )}
 
        {/* Editor */}
        {isLayoutMode ? (
          <Box sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
            <Editor
              height="500px"
              language="html"
              value={htmlBody}
              onChange={(val) => setHtmlBody(val ?? '')}
              options={{
                wordWrap: 'on',
                minimap: { enabled: false },
                fontSize: 13,
              }}
            />
          </Box>
        ) : (
          <Box sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 1 }}>
            <TinyMCEEditor
              tinymceScriptSrc="/tinymce/tinymce.min.js"
              initialValue={htmlBody}
              onEditorChange={(val: string) => {
                tinymceContentRef.current = val;
              }}
              licenseKey="gpl"
              init={{
                height: 400,
                menubar: false,
                z_index: 1400, // Must exceed MUI Dialog z-index (1300) so source code dialog is clickable
                plugins: 'code table lists link',
                toolbar:
                  'code | blocks | bold italic underline' +
                  ' | alignleft aligncenter alignright' +
                  ' | bullist numlist | outdent indent | hr | link | table',
                entity_encoding: 'raw',
                valid_elements: '*[*]',
                branding: false,
                setup: (editor) => {
                  editor.on('blur', syncHtmlBodyFromEditor);
                },
              }}
            />
          </Box>
        )}
 
        {/* Layout key + variable chips (content mode only) */}
        {!isLayoutMode && (
          <Box sx={{ mt: 2 }}>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel>{t('emailTemplates.layoutKey', 'Layout')}</InputLabel>
              <Select
                value={layoutKey}
                label={t('emailTemplates.layoutKey', 'Layout')}
                onChange={(e) => setLayoutKey(e.target.value)}
              >
                <MenuItem value="">{t('emailTemplates.standalone', 'None (standalone)')}</MenuItem>
                {layouts.map((l) => (
                  <MenuItem key={`${l.templateKey}-${l.locale}`} value={l.templateKey}>
                    {l.templateKey} ({l.locale})
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
 
            {detectedVars.length > 0 && (
              <Box>
                <Typography variant="caption" color="text.secondary">
                  {t('emailTemplates.variables', 'Available Variables')}:
                </Typography>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 0.5 }}>
                  {detectedVars.map((v) => (
                    <Chip key={v} label={`{{${v}}}`} size="small" variant="outlined" />
                  ))}
                </Box>
              </Box>
            )}
          </Box>
        )}
 
        {error && (
          <Alert severity="error" sx={{ mt: 2 }}>
            {error}
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={isSaving}>
          {t('actions.cancel', 'Cancel')}
        </Button>
        <Button
          onClick={handleSave}
          variant="contained"
          disabled={isSaving}
          startIcon={isSaving ? <CircularProgress size={16} /> : undefined}
          data-testid="email-template-save"
        >
          {t('actions.save', 'Save')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};