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 | 1x 1x 1x 1x 1x 54x 54x 1x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 40x 20x 2x 2x 2x 2x 20x 20x 20x 2x 1x 1x 1x 20x 1x 19x 1x 18x 18x 1x 1x 6x 102x 36x 1x 2x | /**
* EmailTemplatesTab (Story 10.2)
*
* Tab 3 of the Admin page.
* - Layout Templates section (top): editable with Monaco Editor
* - Content Templates section: filterable by category/locale, editable with TinyMCE
*/
import React, { Suspense, useState } from 'react';
import {
Alert,
Box,
Button,
Chip,
Divider,
FormControl,
IconButton,
InputLabel,
List,
ListItem,
ListItemSecondaryAction,
ListItemText,
MenuItem,
Select,
Snackbar,
ToggleButton,
ToggleButtonGroup,
Tooltip,
Typography,
} from '@mui/material';
import {
Add as AddIcon,
ContentCopy as DuplicateIcon,
Delete as DeleteIcon,
Edit as EditIcon,
InfoOutlined as InfoIcon,
Visibility as PreviewIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { format } from 'date-fns';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import {
useDeleteEmailTemplate,
useEmailTemplates,
useLayoutTemplates,
} from '@/hooks/useEmailTemplates';
import type { EmailTemplateResponse } from '@/hooks/useEmailTemplates';
import { BATbernLoader } from '@components/shared/BATbernLoader';
// Lazy-load the edit modal because it statically imports TinyMCE + Monaco,
// which run side-effectful init at module load. Keeping this eager would make
// TinyMCE initialize on every admin page visit (even when the user never opens
// the Email Templates tab), which can crash the whole admin page if TinyMCE
// self-init fails (e.g. chunk load / CSP / peer-dep issues). Loading it only
// when the modal actually opens keeps the rest of the admin page resilient.
const EmailTemplateEditModal = React.lazy(() =>
import('./EmailTemplateEditModal').then((m) => ({ default: m.EmailTemplateEditModal }))
);
const EmailTemplatePreviewModal = React.lazy(() =>
import('./EmailTemplatePreviewModal').then((m) => ({ default: m.EmailTemplatePreviewModal }))
);
type Category =
| 'SPEAKER'
| 'REGISTRATION'
| 'TASK_REMINDER'
| 'NEWSLETTER'
| 'VENUE_COORDINATION'
| 'REGISTRANT_NOTICE';
const formatDate = (dateStr: string) => {
try {
return format(new Date(dateStr), 'dd.MM.yyyy');
} catch {
return dateStr;
}
};
const CATEGORY_OPTIONS: Category[] = [
'SPEAKER',
'REGISTRATION',
'TASK_REMINDER',
'NEWSLETTER',
'VENUE_COORDINATION',
'REGISTRANT_NOTICE',
];
const CATEGORY_LABEL_KEYS: Record<Category, [string, string]> = {
SPEAKER: ['emailTemplates.categories.SPEAKER', 'Speakers'],
REGISTRATION: ['emailTemplates.categories.REGISTRATION', 'Registration'],
TASK_REMINDER: ['emailTemplates.categories.TASK_REMINDER', 'Task Reminders'],
NEWSLETTER: ['emailTemplates.categories.NEWSLETTER', 'Newsletter'],
VENUE_COORDINATION: ['emailTemplates.categories.VENUE_COORDINATION', 'Venue & Catering'],
REGISTRANT_NOTICE: ['emailTemplates.categories.REGISTRANT_NOTICE', 'Registrant Notices'],
};
export const EmailTemplatesTab: React.FC = () => {
const { t } = useTranslation();
const { isMobile } = useBreakpoints();
const { data: layoutTemplates = [], isLoading: loadingLayouts } = useLayoutTemplates();
const {
data: allContentTemplates = [],
isLoading: loadingContent,
error: contentError,
} = useEmailTemplates({ isLayout: false });
const deleteMutation = useDeleteEmailTemplate();
const [categoryFilter, setCategoryFilter] = useState<Category>('SPEAKER');
const [localeFilter, setLocaleFilter] = useState<'de' | 'en'>('de');
const [editTemplate, setEditTemplate] = useState<EmailTemplateResponse | undefined>(undefined);
const [cloneFromTemplate, setCloneFromTemplate] = useState<EmailTemplateResponse | undefined>(
undefined
);
const [createCategory, setCreateCategory] = useState<Category>('SPEAKER');
const [isLayoutEdit, setIsLayoutEdit] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const [previewTemplate, setPreviewTemplate] = useState<EmailTemplateResponse | null>(null);
const [snackbar, setSnackbar] = useState<string | null>(null);
const filteredContent = allContentTemplates.filter(
(tmpl) => tmpl.category === categoryFilter && tmpl.locale === localeFilter
);
const handleEdit = (tmpl: EmailTemplateResponse, layoutMode: boolean) => {
setEditTemplate(tmpl);
setCloneFromTemplate(undefined);
setIsLayoutEdit(layoutMode);
setEditOpen(true);
};
const handleCreate = () => {
setEditTemplate(undefined);
setCloneFromTemplate(undefined);
setCreateCategory(categoryFilter);
setIsLayoutEdit(false);
setEditOpen(true);
};
const handleDuplicate = (tmpl: EmailTemplateResponse) => {
setEditTemplate(undefined);
setCloneFromTemplate(tmpl);
setCreateCategory(tmpl.category as Category);
setIsLayoutEdit(false);
setEditOpen(true);
};
const handleDelete = async (tmpl: EmailTemplateResponse) => {
if (!window.confirm(`Delete template "${tmpl.templateKey}" (${tmpl.locale})?`)) {
return;
}
try {
await deleteMutation.mutateAsync({ templateKey: tmpl.templateKey, locale: tmpl.locale });
} catch {
setSnackbar(t('emailTemplates.deleteFailed', 'Failed to delete template.'));
}
};
if (loadingLayouts || loadingContent) {
return (
<Box sx={{ textAlign: 'center', mt: 4 }}>
<BATbernLoader size={96} />
</Box>
);
}
if (contentError) {
return <Alert severity="error">{t('errors.loadFailed', 'Failed to load templates.')}</Alert>;
}
return (
<Box data-testid="email-templates-tab">
{/* ── Layout Templates ── */}
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
<Typography variant="h6">
{t('emailTemplates.layoutTemplates', 'Layout Templates')}
</Typography>
<Tooltip
title={t(
'emailTemplates.layoutTemplatesInfo',
'Defines the BATbern look & feel for all emails. Changes here affect all templates using this layout.'
)}
>
<InfoIcon fontSize="small" color="action" />
</Tooltip>
</Box>
<Box sx={{ bgcolor: 'action.hover', borderRadius: 1, px: 2, py: 1, mb: 1 }}>
<List dense disablePadding>
{layoutTemplates.map((tmpl) => (
<ListItem key={`${tmpl.templateKey}-${tmpl.locale}`} divider>
<ListItemText
primary={
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
<Typography variant="body2" fontWeight={600}>
{tmpl.templateKey}
</Typography>
<Chip label={tmpl.locale.toUpperCase()} size="small" color="primary" />
</Box>
}
secondary={`Updated: ${formatDate(tmpl.updatedAt)}`}
/>
<ListItemSecondaryAction sx={{ display: 'flex', gap: 0.5 }}>
<IconButton
size="small"
onClick={() => setPreviewTemplate(tmpl)}
aria-label={`Preview ${tmpl.templateKey}`}
>
<PreviewIcon fontSize="small" />
</IconButton>
<IconButton
size="small"
onClick={() => handleEdit(tmpl, true)}
aria-label={`Edit ${tmpl.templateKey}`}
data-testid={`edit-layout-${tmpl.templateKey}-${tmpl.locale}`}
>
<EditIcon fontSize="small" />
</IconButton>
</ListItemSecondaryAction>
</ListItem>
))}
{layoutTemplates.length === 0 && (
<ListItem>
<ListItemText
secondary={t('emailTemplates.noLayouts', 'No layout templates found.')}
/>
</ListItem>
)}
</List>
</Box>
<Divider sx={{ my: 3 }} />
{/* ── Content Templates ── */}
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
<Typography variant="h6">
{t('emailTemplates.contentTemplates', 'Email Content')}
</Typography>
<Button
size="small"
variant="outlined"
startIcon={<AddIcon />}
onClick={handleCreate}
data-testid="new-template-button"
>
{t('emailTemplates.newTemplate', '+ New Template')}
</Button>
</Box>
<Box sx={{ display: 'flex', gap: 2, mb: 2, flexWrap: 'wrap' }}>
{isMobile ? (
<FormControl size="small" sx={{ minWidth: 200, flex: 1 }}>
<InputLabel id="email-template-category-label">
{t('common:filters.categoryFilter')}
</InputLabel>
<Select
labelId="email-template-category-label"
value={categoryFilter}
label={t('common:filters.categoryFilter')}
onChange={(e) => setCategoryFilter(e.target.value as Category)}
data-testid="email-template-category-select"
>
{CATEGORY_OPTIONS.map((cat) => (
<MenuItem key={cat} value={cat}>
{t(CATEGORY_LABEL_KEYS[cat][0], CATEGORY_LABEL_KEYS[cat][1])}
</MenuItem>
))}
</Select>
</FormControl>
) : (
<ToggleButtonGroup
value={categoryFilter}
exclusive
onChange={(_, v) => {
if (v) setCategoryFilter(v);
}}
size="small"
aria-label={t('common:filters.categoryFilter')}
>
{CATEGORY_OPTIONS.map((cat) => (
<ToggleButton key={cat} value={cat}>
{t(CATEGORY_LABEL_KEYS[cat][0], CATEGORY_LABEL_KEYS[cat][1])}
</ToggleButton>
))}
</ToggleButtonGroup>
)}
<ToggleButtonGroup
value={localeFilter}
exclusive
onChange={(_, v) => {
if (v) setLocaleFilter(v);
}}
size="small"
aria-label={t('common:filters.languageFilter')}
>
<ToggleButton value="de">DE</ToggleButton>
<ToggleButton value="en">EN</ToggleButton>
</ToggleButtonGroup>
</Box>
<List dense data-testid="content-templates-list">
{filteredContent.map((tmpl) => (
<ListItem key={`${tmpl.templateKey}-${tmpl.locale}`} divider>
<ListItemText
primary={
<Box sx={{ display: 'flex', gap: 1, alignItems: 'center', flexWrap: 'wrap' }}>
<Typography variant="body2" fontWeight={600}>
{tmpl.templateKey}
</Typography>
{tmpl.isSystemTemplate ? (
<Chip
label={t('emailTemplates.systemTemplate', 'system')}
size="small"
color="warning"
variant="outlined"
/>
) : tmpl.layoutKey ? (
<Chip
label={tmpl.layoutKey}
size="small"
color="secondary"
variant="outlined"
/>
) : (
<Chip
label={t('emailTemplates.standalone', 'standalone')}
size="small"
variant="outlined"
/>
)}
</Box>
}
secondary={
<Box component="span">
{tmpl.subject && (
<Typography
variant="caption"
component="span"
display="block"
noWrap
sx={{ maxWidth: 400 }}
>
{tmpl.subject}
</Typography>
)}
<Typography variant="caption" component="span" color="text.secondary">
Updated: {formatDate(tmpl.updatedAt)}
</Typography>
</Box>
}
/>
<ListItemSecondaryAction sx={{ display: 'flex', gap: 0.5 }}>
<Tooltip title={t('emailTemplates.preview', 'Preview')}>
<IconButton
size="small"
onClick={() => setPreviewTemplate(tmpl)}
aria-label={`Preview ${tmpl.templateKey}`}
>
<PreviewIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title={t('emailTemplates.duplicateTemplate', 'Duplicate')}>
<IconButton
size="small"
onClick={() => handleDuplicate(tmpl)}
aria-label={`Duplicate ${tmpl.templateKey}`}
data-testid={`duplicate-email-template-${tmpl.templateKey}`}
>
<DuplicateIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title={t('emailTemplates.editTitle', 'Edit')}>
<IconButton
size="small"
onClick={() => handleEdit(tmpl, false)}
aria-label={`Edit ${tmpl.templateKey}`}
data-testid={`edit-email-template-${tmpl.templateKey}`}
>
<EditIcon fontSize="small" />
</IconButton>
</Tooltip>
{!tmpl.isSystemTemplate && (
<Tooltip title={t('common:actions.delete', 'Delete')}>
<IconButton
size="small"
onClick={() => handleDelete(tmpl)}
aria-label={`Delete ${tmpl.templateKey}`}
data-testid={`delete-email-template-${tmpl.templateKey}`}
>
<DeleteIcon fontSize="small" />
</IconButton>
</Tooltip>
)}
</ListItemSecondaryAction>
</ListItem>
))}
{filteredContent.length === 0 && (
<ListItem>
<ListItemText
secondary={t('emailTemplates.noTemplates', 'No templates found for this filter.')}
/>
</ListItem>
)}
</List>
{/* Edit Modal (lazy — loads TinyMCE/Monaco only when opened) */}
{editOpen && (
<Suspense fallback={null}>
<EmailTemplateEditModal
template={editTemplate}
isLayoutMode={isLayoutEdit}
initialCategory={createCategory}
cloneFrom={cloneFromTemplate}
onClose={() => {
setEditOpen(false);
setCloneFromTemplate(undefined);
}}
/>
</Suspense>
)}
{/* Preview Modal */}
{previewTemplate && (
<Suspense fallback={null}>
<EmailTemplatePreviewModal
template={previewTemplate}
onClose={() => setPreviewTemplate(null)}
/>
</Suspense>
)}
<Snackbar
open={Boolean(snackbar)}
autoHideDuration={4000}
onClose={() => setSnackbar(null)}
message={snackbar}
/>
</Box>
);
};
|