Admin: Berichten-scherm met formulierschakelaar, lijst, detail en opnieuw mailen (CMS-U6)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 22:42:33 +01:00
co-authored by Claude Sonnet 5.5
parent 0d729b6413
commit fd13647139
22 changed files with 1675 additions and 10 deletions
@@ -5,7 +5,7 @@
- **Feature Slug**: contact-forms-module
- **Project Type**: Brownfield
- **Start Date**: 2026-11-09
- **Current Stage**: PHASE 2 - CMS-U7 and CMS-U5 built and committed; next CMS-U6, then plan CMS-U8
- **Current Stage**: PHASE 2 - CMS-U7, CMS-U5 and CMS-U6 built and committed; next plan CMS-U8
- **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it)
## Workspace State
@@ -0,0 +1,11 @@
# CMS-U6 — Admin UI "Berichten" (summary)
Frontend only. New feature folder `frontend/src/features/contact` (services, components, page, msw mocks, tests).
- Route `/messages` (Owner/Administrator, `ModuleGuard Contact`, plus `ContactAvailabilityGuard`: a 404 on `GET /contact-settings` means the host switch is off and the usual not-found page is shown). Sidebar entry "Berichten" only when capabilities list `Contact` and the settings call did not answer 404.
- Form switch card (`role=switch`, state from the server response, first-time hint, translated errors).
- List: chips Inbox/Nieuw/Gelezen/Gearchiveerd/Spam (Nieuw shows `unreadCount`), 25 per page, pager, empty states, spam only under its chip, mail status icons with text alternatives.
- Detail dialog: line breaks kept, mailto link, status select, "Geen spam", delete with confirmation, resend (sent / not sent / 409 / 429 with Retry-After seconds / disabled with hint when mail is off), translated mail error code and next attempt time. Opening an unread message marks it read (decision approved).
- Texts nl/en under `contact.*` and `nav.messages`; no API titles are shown.
- Shared files touched (additive): `lib/api-client.ts` (new `patch` method), `Sidebar.tsx` (one entry), `router.tsx` (one route), `mocks/index.ts`, both translation files.
- Verification: `pnpm lint` clean, `npx tsc -b` clean, vitest 58 files / 458 tests (26 new). Not touched: backend, auth/refresh, users, theme assets.
@@ -17,12 +17,12 @@ Phase 2, frontend only (`frontend/src/features/contact`, `router.tsx`, `Sidebar.
7. All user-facing texts Dutch with English counterparts (`contact.*`); errors and 4xx/5xx mapped to translated messages, never the API's English titles. Accessibility: switch with accessible name and state, focus management in dialogs, status icons with text alternatives.
## Steps
- [ ] **Step 1 — Types, services and msw mocks** (settings get/put incl. 404 = unavailable, messages list/detail/patch/delete/resend with the real status codes and shapes).
- [ ] **Step 2 — Components**: `FormSwitchCard`, `MessagesFilterChips`, `MessagesTable` + pager, `MessageDialog`, `DeleteMessageDialog`.
- [ ] **Step 3 — Page, route, sidebar entry, guards, translations (nl/en)**.
- [ ] **Step 4 — Tests (Vitest + Testing Library + msw)**: sidebar entry visible/hidden (module missing, 404 on settings, role); direct route when unavailable; switch card off→on→off with server response, error path, first-time hint; list default shows no spam, each chip sends the right query, counter from `unreadCount`, paging; detail opens, marks unread as read, line breaks preserved, status change, un-spam moves the row, delete confirm/cancel, resend (`mailed` true/false, 409, 429 with seconds, email disabled), empty states, translated error codes; no raw API titles shown.
- [ ] **Step 5 — Verification (automatic)**: `pnpm lint`, `npx tsc -b`, full `pnpm test`; new files formatted with prettier (the 15 old prettier warnings in offerings stay); real output reported.
- [ ] **Step 6 — Docs/commit**: summary; one commit; no push.
- [x] **Step 1 — Types, services and msw mocks** (settings get/put incl. 404 = unavailable, messages list/detail/patch/delete/resend with the real status codes and shapes).
- [x] **Step 2 — Components**: `FormSwitchCard`, `MessagesFilterChips`, `MessagesTable` + pager, `MessageDialog`, `DeleteMessageDialog`.
- [x] **Step 3 — Page, route, sidebar entry, guards, translations (nl/en)**.
- [x] **Step 4 — Tests (Vitest + Testing Library + msw)**: sidebar entry visible/hidden (module missing, 404 on settings, role); direct route when unavailable; switch card off→on→off with server response, error path, first-time hint; list default shows no spam, each chip sends the right query, counter from `unreadCount`, paging; detail opens, marks unread as read, line breaks preserved, status change, un-spam moves the row, delete confirm/cancel, resend (`mailed` true/false, 409, 429 with seconds, email disabled), empty states, translated error codes; no raw API titles shown.
- [x] **Step 5 — Verification (automatic)**: `pnpm lint`, `npx tsc -b`, full `pnpm test`; new files formatted with prettier (the 15 old prettier warnings in offerings stay); real output reported.
- [x] **Step 6 — Docs/commit**: summary; one commit; no push.
## Explicitly NOT touched
Backend, auth/refresh, users, theme assets, existing features except the one entry in `Sidebar.tsx` and the route in `router.tsx`, shared UI primitives (used, not edited; a switch is built from the existing button/checkbox primitives unless a primitive is missing, then added as a new file).
+16 -2
View File
@@ -1,11 +1,12 @@
import { Link } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import { LayoutDashboard, Users, FileText, Package, Settings, X } from 'lucide-react';
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/features/auth/context/auth-context';
import { useAvailabilityStatus } from '@/features/availability/services/useAvailability';
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
import { useContactSettings } from '@/features/contact/services/useContactSettings';
import { LanguageSwitcher } from '@/i18n/LanguageSwitcher';
import { BrandLogo } from './BrandLogo';
import { ThemeToggle } from './ThemeToggle';
@@ -36,6 +37,14 @@ const NAV_ITEMS: NavItem[] = [
roles: ['Owner', 'Administrator'],
requiredModule: 'Offerings',
},
{
to: '/messages',
labelKey: 'nav.messages',
icon: Mail,
testId: 'nav-messages',
roles: ['Owner', 'Administrator'],
requiredModule: 'Contact',
},
];
const SETTINGS_ITEM: NavItem = {
@@ -53,11 +62,16 @@ export function Sidebar({ onClose }: SidebarProps = {}) {
const { data: capabilities } = useSystemCapabilities();
const role = user?.role as Role | undefined;
// The Berichten entry also needs the management API to exist on this host (a loaded module is not enough:
// while the host switch is off its routes answer 404). Only asked for roles that may see the entry.
const mayManageContact = (role === 'Owner' || role === 'Administrator') && !!capabilities?.modules.includes('Contact');
const { data: contactSettings } = useContactSettings({ enabled: mayManageContact });
const systemUnavailable = availability?.status === 'NotAvailable';
const visibleItems = NAV_ITEMS.filter(
(item) =>
(!item.roles || (role && item.roles.includes(role))) &&
(!item.requiredModule || capabilities?.modules.includes(item.requiredModule))
(!item.requiredModule || capabilities?.modules.includes(item.requiredModule)) &&
(item.requiredModule !== 'Contact' || !!contactSettings)
);
const showSettings = !SETTINGS_ITEM.roles || (role && SETTINGS_ITEM.roles.includes(role));
@@ -0,0 +1,22 @@
import type { ReactNode } from 'react';
import { NotFoundPage } from '@/pages/NotFoundPage';
import { useContactSettings } from '../services/useContactSettings';
/**
* The module can be loaded while the management routes are closed (host switch off: every route answers 404 with an
* empty body). In that case the screen does not exist: the usual "not found" page is shown.
*/
export function ContactAvailabilityGuard({ children }: { children: ReactNode }) {
const { data, isPending, isError } = useContactSettings();
if (isPending) {
return (
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
<span className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
if (isError || data === null) return <NotFoundPage />;
return <>{children}</>;
}
@@ -0,0 +1,52 @@
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
interface Props {
open: boolean;
isDeleting: boolean;
error: string | null;
onConfirm: () => void;
onCancel: () => void;
}
export function DeleteMessageDialog({ open, isDeleting, error, onConfirm, onCancel }: Props) {
const { t } = useTranslation();
return (
<Dialog
open={open}
onOpenChange={(next) => {
if (!next) onCancel();
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('contact.deleteDialog.title')}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">{t('contact.deleteDialog.message')}</p>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<div className="flex justify-end gap-2">
<Button
variant="outline"
onClick={onCancel}
data-testid="delete-message-cancel"
>
{t('common.cancel')}
</Button>
<Button
variant="destructive"
disabled={isDeleting}
onClick={onConfirm}
data-testid="delete-message-confirm"
>
{isDeleting ? '…' : t('contact.deleteDialog.confirm')}
</Button>
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,75 @@
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { useContactSettings, useUpdateContactSettings } from '../services/useContactSettings';
import { contactErrorMessage } from '../errors';
/** The form switch: whether the contact form on the website is open. The state shown is the server's. */
export function FormSwitchCard() {
const { t } = useTranslation();
const { data: settings } = useContactSettings();
const update = useUpdateContactSettings();
if (!settings) return null;
const open = settings.enabled;
const toggle = () =>
update.mutate(!open, {
onSuccess: (saved) =>
toast.success(
saved.enabled ? t('contact.switch.nowOn') : t('contact.switch.nowOff'),
),
});
return (
<Card data-testid="contact-switch-card">
<CardContent className="space-y-3 p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h2 className="font-semibold">{t('contact.switch.title')}</h2>
<p className="text-sm" data-testid="contact-switch-state">
{open ? t('contact.switch.stateOn') : t('contact.switch.stateOff')}
</p>
</div>
{settings.hostEnabled ? (
<Button
type="button"
role="switch"
aria-checked={open}
aria-label={t('contact.switch.title')}
variant={open ? 'default' : 'outline'}
disabled={update.isPending}
onClick={toggle}
data-testid="contact-switch-toggle"
>
{open ? t('contact.switch.turnOff') : t('contact.switch.turnOn')}
</Button>
) : (
<p
className="text-sm text-muted-foreground"
data-testid="contact-switch-host-off"
>
{t('contact.switch.hostOff')}
</p>
)}
</div>
<p className="text-sm text-muted-foreground">{t('contact.switch.explanation')}</p>
{!open && settings.hostEnabled && (
<p className="text-sm text-muted-foreground" data-testid="contact-switch-hint">
{t('contact.switch.firstTimeHint')}
</p>
)}
{update.isError && (
<p
role="alert"
className="text-sm text-destructive"
data-testid="contact-switch-error"
>
{contactErrorMessage(update.error, t)}
</p>
)}
</CardContent>
</Card>
);
}
@@ -0,0 +1,247 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
import {
useContactMessage,
useResendContactMessage,
useUpdateContactMessageStatus,
} from '../services/useContactMessages';
import type { SettableStatus } from '../services/types';
import { contactErrorMessage, mailErrorLabel } from '../errors';
import { MailStatusIcon } from './MessagesTable';
interface Props {
id: string | null;
onClose: () => void;
onDeleteRequested: (id: string) => void;
}
const SETTABLE: SettableStatus[] = ['new', 'read', 'archived'];
export function MessageDialog({ id, onClose, onDeleteRequested }: Props) {
const { t, i18n } = useTranslation();
const { data: message, isPending, isError } = useContactMessage(id);
const { data: capabilities } = useSystemCapabilities();
const setStatus = useUpdateContactMessageStatus();
const resend = useResendContactMessage();
const [resendNote, setResendNote] = useState<string | null>(null);
const markedRead = useRef<string | null>(null);
// Opening an unread message marks it as read, once per message.
useEffect(() => {
if (message && message.status === 'new' && markedRead.current !== message.id) {
markedRead.current = message.id;
setStatus.mutate({ id: message.id, status: 'read' });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [message?.id, message?.status]);
const format = new Intl.DateTimeFormat(i18n.language, {
dateStyle: 'medium',
timeStyle: 'short',
});
const emailEnabled = capabilities?.emailEnabled ?? false;
const isSpam = message?.status === 'spam';
const doResend = () => {
if (!message) return;
setResendNote(null);
resend.mutate(message.id, {
onSuccess: (result) =>
setResendNote(
result.mailed ? t('contact.resend.sent') : t('contact.resend.notSent'),
),
onError: (error) => setResendNote(contactErrorMessage(error, t)),
});
};
const errorLabel = mailErrorLabel(message?.mailError, t);
return (
<Dialog
open={id !== null}
onOpenChange={(open) => {
if (!open) onClose();
}}
>
<DialogContent className="sm:max-w-xl" data-testid="contact-message-dialog">
<DialogHeader>
<DialogTitle>
{message ? message.subject : t('contact.detail.title')}
</DialogTitle>
<DialogDescription>{t('contact.detail.title')}</DialogDescription>
</DialogHeader>
{isPending && (
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
)}
{isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.generic')}
</p>
)}
{message && (
<div className="space-y-4">
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
<dt className="text-muted-foreground">{t('contact.table.name')}</dt>
<dd>{message.name}</dd>
<dt className="text-muted-foreground">{t('contact.table.email')}</dt>
<dd>
<a
className="text-primary underline-offset-4 hover:underline"
href={`mailto:${message.email}`}
>
{message.email}
</a>
</dd>
<dt className="text-muted-foreground">{t('contact.table.received')}</dt>
<dd>{format.format(new Date(message.receivedAt))}</dd>
<dt className="text-muted-foreground">
{t('contact.detail.retention')}
</dt>
<dd>{format.format(new Date(message.retentionUntil))}</dd>
</dl>
<p
className="max-h-60 overflow-y-auto whitespace-pre-wrap break-words rounded-md border bg-muted/30 p-3 text-sm"
data-testid="contact-message-body"
>
{message.message}
</p>
<div className="flex items-center gap-2 text-sm">
<label
htmlFor="contact-status-select"
className="text-muted-foreground"
>
{t('contact.table.status')}
</label>
{isSpam ? (
<>
<span>{t('contact.status.spam')}</span>
<Button
type="button"
size="sm"
variant="outline"
disabled={setStatus.isPending}
onClick={() =>
setStatus.mutate(
{ id: message.id, status: 'read' },
{ onSuccess: onClose },
)
}
data-testid="contact-not-spam"
>
{t('contact.detail.notSpam')}
</Button>
</>
) : (
<select
id="contact-status-select"
value={message.status}
disabled={setStatus.isPending}
onChange={(e) =>
setStatus.mutate({
id: message.id,
status: e.target.value as SettableStatus,
})
}
className="h-9 rounded-md border border-input bg-background px-2"
data-testid="contact-status-select"
>
{SETTABLE.map((s) => (
<option key={s} value={s}>
{t(`contact.status.${s}`)}
</option>
))}
</select>
)}
</div>
{setStatus.isError && (
<p role="alert" className="text-sm text-destructive">
{contactErrorMessage(setStatus.error, t)}
</p>
)}
{!isSpam && (
<div
className="space-y-1 rounded-md border p-3 text-sm"
data-testid="contact-mail-info"
>
<div className="flex items-center gap-2">
<MailStatusIcon status={message.mailStatus} />
<span>{t(`contact.mailStatus.${message.mailStatus}`)}</span>
<span className="text-muted-foreground">
{t('contact.detail.attempts', {
count: message.mailAttempts,
})}
</span>
</div>
{errorLabel && <p data-testid="contact-mail-error">{errorLabel}</p>}
{message.nextMailAttemptAt && message.mailStatus !== 'sent' && (
<p
className="text-muted-foreground"
data-testid="contact-next-attempt"
>
{t('contact.detail.nextAttempt', {
time: format.format(
new Date(message.nextMailAttemptAt),
),
})}
</p>
)}
</div>
)}
{resendNote && (
<p role="status" className="text-sm" data-testid="contact-resend-note">
{resendNote}
</p>
)}
<div className="flex flex-wrap justify-between gap-2">
<Button
type="button"
variant="destructive"
onClick={() => onDeleteRequested(message.id)}
data-testid="contact-delete-button"
>
{t('contact.detail.delete')}
</Button>
{!isSpam && (
<div className="flex flex-col items-end gap-1">
<Button
type="button"
variant="outline"
disabled={!emailEnabled || resend.isPending}
onClick={doResend}
data-testid="contact-resend-button"
>
{t('contact.detail.resend')}
</Button>
{!emailEnabled && (
<span
className="text-xs text-muted-foreground"
data-testid="contact-resend-hint"
>
{t('contact.resend.mailOff')}
</span>
)}
</div>
)}
</div>
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,47 @@
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import type { ContactFilter } from '../services/types';
const FILTERS: ContactFilter[] = ['inbox', 'new', 'read', 'archived', 'spam'];
interface Props {
value: ContactFilter;
unreadCount: number | undefined;
onChange: (filter: ContactFilter) => void;
}
export function MessagesFilterChips({ value, unreadCount, onChange }: Props) {
const { t } = useTranslation();
return (
<div role="group" aria-label={t('contact.filter.label')} className="flex flex-wrap gap-2">
{FILTERS.map((filter) => {
const active = filter === value;
return (
<button
key={filter}
type="button"
aria-pressed={active}
data-testid={`contact-filter-${filter}`}
onClick={() => onChange(filter)}
className={cn(
'rounded-full border px-3 py-1 text-sm transition-colors',
active
? 'border-primary bg-primary text-primary-foreground'
: 'hover:bg-accent',
)}
>
{t(`contact.filter.${filter}`)}
{filter === 'new' && unreadCount !== undefined && (
<span
className="ml-1.5 font-semibold"
data-testid="contact-unread-count"
>
({unreadCount})
</span>
)}
</button>
);
})}
</div>
);
}
@@ -0,0 +1,100 @@
import { useTranslation } from 'react-i18next';
import { CheckCircle2, Clock, MinusCircle, XCircle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type { ContactMailStatus, ContactMessageListItem } from '../services/types';
export function MailStatusIcon({ status }: { status: ContactMailStatus }) {
const { t } = useTranslation();
const common = {
'aria-label': t(`contact.mailStatus.${status}`),
role: 'img',
'data-testid': `mail-status-${status}`,
};
switch (status) {
case 'sent':
return <CheckCircle2 {...common} className="size-4 text-green-600" />;
case 'failed':
return <XCircle {...common} className="size-4 text-destructive" />;
case 'pending':
return <Clock {...common} className="size-4 text-amber-600" />;
default:
return <MinusCircle {...common} className="size-4 text-muted-foreground" />;
}
}
interface Props {
items: ContactMessageListItem[];
onOpen: (id: string) => void;
}
export function MessagesTable({ items, onOpen }: Props) {
const { t, i18n } = useTranslation();
const format = new Intl.DateTimeFormat(i18n.language, {
dateStyle: 'short',
timeStyle: 'short',
});
return (
<div className="overflow-x-auto rounded-md border">
<table className="w-full text-sm" data-testid="contact-messages-table">
<thead className="bg-muted/50 text-left">
<tr>
<th className="p-2">{t('contact.table.received')}</th>
<th className="p-2">{t('contact.table.name')}</th>
<th className="p-2">{t('contact.table.email')}</th>
<th className="p-2">{t('contact.table.subject')}</th>
<th className="p-2">{t('contact.table.status')}</th>
<th className="p-2">{t('contact.table.mail')}</th>
</tr>
</thead>
<tbody>
{items.map((m) => (
<tr
key={m.id}
data-testid={`contact-row-${m.id}`}
className={
m.status === 'spam'
? 'bg-destructive/5'
: m.status === 'new'
? 'font-semibold'
: ''
}
>
<td className="p-2 whitespace-nowrap">
{format.format(new Date(m.receivedAt))}
</td>
<td className="p-2">
<button
type="button"
className="text-left text-primary underline-offset-4 hover:underline"
onClick={() => onOpen(m.id)}
data-testid={`contact-open-${m.id}`}
>
{m.name}
</button>
</td>
<td className="p-2">{m.email}</td>
<td className="p-2">{m.subject}</td>
<td className="p-2">
<Badge
variant={
m.status === 'spam'
? 'destructive'
: m.status === 'new'
? 'default'
: 'secondary'
}
>
{t(`contact.status.${m.status}`)}
</Badge>
</td>
<td className="p-2">
<MailStatusIcon status={m.mailStatus} />
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
import type { TFunction } from 'i18next';
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
/** Maps any failure to a translated text; the API's own (English) titles are never shown. */
export function contactErrorMessage(error: unknown, t: TFunction): string {
if (error instanceof NetworkError) return t('errors.network');
if (error instanceof ProblemDetailsError) {
if (error.status === 429) {
const seconds = Math.max(1, Math.ceil((error.retryAfterMs ?? 60000) / 1000));
return t('contact.errors.rateLimited', { seconds });
}
if (error.status === 409) return t('contact.errors.spamResend');
if (error.status === 404) return t('contact.errors.notFound');
}
return t('errors.generic');
}
const KNOWN_MAIL_ERRORS = [
'disabled',
'recipient_not_configured',
'not_configured',
'timeout',
'timeout_connect',
'timeout_auth',
'timeout_send',
'auth_failed',
'rejected',
'rejected_sender',
'rejected_recipient',
'tls_failed',
'connection_failed',
'unknown',
];
/** Short mail error codes (from the mail sender) to translated reasons; unknown codes fall back to a generic text. */
export function mailErrorLabel(code: string | null | undefined, t: TFunction): string | null {
if (!code) return null;
return KNOWN_MAIL_ERRORS.includes(code)
? t(`contact.mailError.${code}`)
: t('contact.mailError.unknown');
}
@@ -0,0 +1,142 @@
import { http, HttpResponse } from 'msw';
import type {
ContactMessageDetail,
ContactMessageListItem,
ContactSettings,
ContactStatus,
} from '@/features/contact/services/types';
const BASE = '*/api/v1/contact-messages';
const SETTINGS = '*/api/v1/contact-settings';
export const MSG_NEW = '11111111-1111-1111-1111-111111111111';
export const MSG_READ = '22222222-2222-2222-2222-222222222222';
export const MSG_SPAM = '33333333-3333-3333-3333-333333333333';
function seed(): ContactMessageDetail[] {
const base = {
retentionUntil: '2027-11-01T10:00:00Z',
mailAttempts: 1,
mailError: null,
nextMailAttemptAt: null,
};
return [
{
...base,
id: MSG_NEW,
receivedAt: '2026-11-09T10:00:00Z',
name: 'Jan Jansen',
email: 'jan@example.nl',
subject: 'website',
message: 'Eerste regel\nTweede regel',
status: 'new',
mailStatus: 'sent',
},
{
...base,
id: MSG_READ,
receivedAt: '2026-11-08T10:00:00Z',
name: 'Marieke',
email: 'marieke@example.nl',
subject: 'onderhoud',
message: 'Hallo',
status: 'read',
mailStatus: 'failed',
mailAttempts: 2,
mailError: 'auth_failed',
nextMailAttemptAt: '2026-11-09T12:00:00Z',
},
{
...base,
id: MSG_SPAM,
receivedAt: '2026-11-07T10:00:00Z',
name: 'Bot',
email: 'bot@example.nl',
subject: 'website',
message: 'buy',
status: 'spam',
mailStatus: 'notApplicable',
mailAttempts: 0,
},
];
}
let messages = seed();
let settings: ContactSettings = { enabled: false, hostEnabled: true };
export function resetMockContact(): void {
messages = seed();
settings = { enabled: false, hostEnabled: true };
}
export function getMockContactMessages(): ContactMessageDetail[] {
return messages;
}
function toItem(m: ContactMessageDetail): ContactMessageListItem {
return {
id: m.id,
receivedAt: m.receivedAt,
name: m.name,
email: m.email,
subject: m.subject,
status: m.status,
mailStatus: m.mailStatus,
};
}
export const contactHandlers = [
http.get(SETTINGS, () => HttpResponse.json(settings)),
http.put(SETTINGS, async ({ request }) => {
const body = (await request.json()) as { enabled: boolean };
settings = { ...settings, enabled: body.enabled };
return HttpResponse.json(settings);
}),
http.get(BASE, ({ request }) => {
const url = new URL(request.url);
const status = url.searchParams.get('status');
const page = Number(url.searchParams.get('page') ?? '1');
const pageSize = Number(url.searchParams.get('pageSize') ?? '25');
const wanted: ContactStatus[] = status
? [status as ContactStatus]
: ['new', 'read', 'archived'];
const all = messages.filter((m) => wanted.includes(m.status));
const items = all.slice((page - 1) * pageSize, page * pageSize).map(toItem);
return HttpResponse.json({
items,
page,
pageSize,
totalCount: all.length,
unreadCount: messages.filter((m) => m.status === 'new').length,
});
}),
http.get(`${BASE}/:id`, ({ params }) => {
const m = messages.find((x) => x.id === params.id);
return m ? HttpResponse.json(m) : new HttpResponse(null, { status: 404 });
}),
http.patch(`${BASE}/:id`, async ({ params, request }) => {
const m = messages.find((x) => x.id === params.id);
if (!m) return new HttpResponse(null, { status: 404 });
const body = (await request.json()) as { status: ContactStatus };
m.status = body.status;
return HttpResponse.json(m);
}),
http.delete(`${BASE}/:id`, ({ params }) => {
const before = messages.length;
messages = messages.filter((x) => x.id !== params.id);
return messages.length === before
? new HttpResponse(null, { status: 404 })
: new HttpResponse(null, { status: 204 });
}),
http.post(`${BASE}/:id/resend`, ({ params }) => {
const m = messages.find((x) => x.id === params.id);
if (!m) return new HttpResponse(null, { status: 404 });
if (m.status === 'spam')
return HttpResponse.json({ status: 409, title: 'Conflict' }, { status: 409 });
return HttpResponse.json({
mailStatus: 'sent',
mailAttempts: m.mailAttempts + 1,
mailed: true,
});
}),
];
@@ -0,0 +1,418 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { server } from '@/mocks/server';
import { API_BASE } from '@/features/auth/mocks/fixtures';
import {
MSG_NEW,
MSG_READ,
MSG_SPAM,
getMockContactMessages,
resetMockContact,
} from '@/features/contact/mocks/handlers';
import { _resetSetupStatusCache } from '@/router';
const LONG = { timeout: 10000 };
function capabilities(modules: string[], emailEnabled = true) {
server.use(
http.get(`${API_BASE}/api/v1/System/capabilities`, () =>
HttpResponse.json({ modules, emailEnabled, defaultLanguage: 'nl' }),
),
);
}
const WITH_CONTACT = ['Availability', 'Identity', 'Master', 'Offerings', 'Contact'];
beforeEach(() => {
_resetSetupStatusCache();
resetMockContact();
mockAuthenticated();
});
async function openPage() {
capabilities(WITH_CONTACT);
renderApp('/messages');
await screen.findByTestId('messages-title', {}, LONG);
}
describe('Berichten navigation', () => {
it('shows the sidebar entry when the module is loaded and the API answers', async () => {
capabilities(WITH_CONTACT);
renderApp('/dashboard');
expect(await screen.findByTestId('nav-messages', {}, LONG)).toBeInTheDocument();
});
it('hides the entry when the module is not loaded', async () => {
capabilities(['Availability', 'Identity', 'Offerings']);
renderApp('/dashboard');
await screen.findByTestId('nav-offerings', {}, LONG);
expect(screen.queryByTestId('nav-messages')).not.toBeInTheDocument();
});
it('hides the entry when the settings answer 404 (host switch off)', async () => {
capabilities(WITH_CONTACT);
server.use(
http.get(
`${API_BASE}/api/v1/contact-settings`,
() => new HttpResponse(null, { status: 404 }),
),
);
renderApp('/dashboard');
await screen.findByTestId('nav-offerings', {}, LONG);
await new Promise((r) => setTimeout(r, 200));
expect(screen.queryByTestId('nav-messages')).not.toBeInTheDocument();
});
it('shows the not-found page on a direct visit while unavailable', async () => {
capabilities(WITH_CONTACT);
server.use(
http.get(
`${API_BASE}/api/v1/contact-settings`,
() => new HttpResponse(null, { status: 404 }),
),
);
renderApp('/messages');
expect(await screen.findByTestId('not-found-title', {}, LONG)).toBeInTheDocument();
});
it('shows the feature-unavailable message when the module is missing', async () => {
capabilities(['Availability', 'Identity']);
renderApp('/messages');
expect(
await screen.findByTestId('feature-unavailable-message', {}, LONG),
).toBeInTheDocument();
});
});
describe('Form switch', () => {
it('shows the first-time hint while off and switches on and off with the server answer', async () => {
await openPage();
expect(await screen.findByTestId('contact-switch-hint')).toBeInTheDocument();
const toggle = screen.getByTestId('contact-switch-toggle');
expect(toggle).toHaveAttribute('aria-checked', 'false');
await userEvent.click(toggle);
await waitFor(() =>
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
'aria-checked',
'true',
),
);
expect(screen.getByTestId('contact-switch-state')).toHaveTextContent('The form is on');
expect(screen.queryByTestId('contact-switch-hint')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('contact-switch-toggle'));
await waitFor(() =>
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
'aria-checked',
'false',
),
);
});
it('shows a translated error and keeps the state when the switch fails', async () => {
await openPage();
server.use(
http.put(`${API_BASE}/api/v1/contact-settings`, () =>
HttpResponse.json({ status: 500, title: 'Internal Server Error' }, { status: 500 }),
),
);
await userEvent.click(await screen.findByTestId('contact-switch-toggle'));
const error = await screen.findByTestId('contact-switch-error');
expect(error).toHaveTextContent('Something went wrong');
expect(error).not.toHaveTextContent('Internal Server Error');
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
'aria-checked',
'false',
);
});
});
describe('Message list', () => {
it('shows the inbox without spam and the unread counter', async () => {
await openPage();
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
expect(screen.getByTestId(`contact-row-${MSG_READ}`)).toBeInTheDocument();
expect(screen.queryByTestId(`contact-row-${MSG_SPAM}`)).not.toBeInTheDocument();
expect(screen.getByTestId('contact-unread-count')).toHaveTextContent('(1)');
expect(screen.getByTestId('messages-range')).toHaveTextContent('1–2 of 2');
});
it('sends the right status for each chip and shows spam apart', async () => {
await openPage();
await screen.findByTestId(`contact-row-${MSG_NEW}`);
await userEvent.click(screen.getByTestId('contact-filter-spam'));
expect(await screen.findByTestId(`contact-row-${MSG_SPAM}`)).toBeInTheDocument();
expect(screen.queryByTestId(`contact-row-${MSG_NEW}`)).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('contact-filter-new'));
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
expect(screen.queryByTestId(`contact-row-${MSG_READ}`)).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('contact-filter-archived'));
expect(await screen.findByTestId('messages-empty-state')).toHaveTextContent(
'No archived messages',
);
});
it('requests the status query parameter only for a specific chip, 25 per page', async () => {
const urls: string[] = [];
server.use(
http.get(`${API_BASE}/api/v1/contact-messages`, ({ request }) => {
urls.push(new URL(request.url).search);
return HttpResponse.json({
items: [],
page: 1,
pageSize: 25,
totalCount: 0,
unreadCount: 0,
});
}),
);
await openPage();
await screen.findByTestId('messages-empty-state');
await userEvent.click(screen.getByTestId('contact-filter-read'));
await waitFor(() => expect(urls.some((u) => u.includes('status=read'))).toBe(true));
expect(urls[0]).not.toContain('status=');
expect(urls[0]).toContain('pageSize=25');
});
it('pages through more than 25 messages', async () => {
const many = Array.from({ length: 30 }, (_, i) => ({
id: `00000000-0000-0000-0000-${String(i).padStart(12, '0')}`,
receivedAt: '2026-11-09T10:00:00Z',
name: `Naam ${i}`,
email: 'x@example.nl',
subject: 's',
status: 'read',
mailStatus: 'sent',
}));
server.use(
http.get(`${API_BASE}/api/v1/contact-messages`, ({ request }) => {
const page = Number(new URL(request.url).searchParams.get('page'));
return HttpResponse.json({
items: many.slice((page - 1) * 25, page * 25),
page,
pageSize: 25,
totalCount: 30,
unreadCount: 0,
});
}),
);
await openPage();
expect(await screen.findByTestId('messages-range')).toHaveTextContent('1–25 of 30');
expect(screen.getByTestId('messages-prev')).toBeDisabled();
await userEvent.click(screen.getByTestId('messages-next'));
await waitFor(() =>
expect(screen.getByTestId('messages-range')).toHaveTextContent('26–30 of 30'),
);
expect(screen.getByTestId('messages-next')).toBeDisabled();
});
it('shows an empty state for the inbox', async () => {
server.use(
http.get(`${API_BASE}/api/v1/contact-messages`, () =>
HttpResponse.json({
items: [],
page: 1,
pageSize: 25,
totalCount: 0,
unreadCount: 0,
}),
),
);
await openPage();
expect(await screen.findByTestId('messages-empty-state')).toHaveTextContent(
'No messages yet',
);
});
it('gives the mail icons a text alternative', async () => {
await openPage();
await screen.findByTestId(`contact-row-${MSG_NEW}`);
expect(
within(screen.getByTestId(`contact-row-${MSG_NEW}`)).getByRole('img'),
).toHaveAccessibleName('Mail sent');
expect(
within(screen.getByTestId(`contact-row-${MSG_READ}`)).getByRole('img'),
).toHaveAccessibleName('Mail failed');
});
});
describe('Message detail', () => {
it('opens, keeps line breaks, links the address and marks an unread message as read', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_NEW}`));
const body = await screen.findByTestId('contact-message-body');
expect(body.textContent).toBe('Eerste regel\nTweede regel');
expect(body.className).toContain('whitespace-pre-wrap');
expect(screen.getByRole('link', { name: 'jan@example.nl' })).toHaveAttribute(
'href',
'mailto:jan@example.nl',
);
await waitFor(() =>
expect(getMockContactMessages().find((m) => m.id === MSG_NEW)?.status).toBe('read'),
);
await waitFor(() =>
expect(screen.getByTestId('contact-unread-count')).toHaveTextContent('(0)'),
);
});
it('does not change an already read message when it is opened', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await screen.findByTestId('contact-message-body');
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read');
});
it('changes the status through the select', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await userEvent.selectOptions(
await screen.findByTestId('contact-status-select'),
'archived',
);
await waitFor(() =>
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe(
'archived',
),
);
});
it('shows the translated mail error and the next attempt, never the raw code', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
expect(await screen.findByTestId('contact-mail-error')).toHaveTextContent(
'Logging in to the mail server failed.',
);
expect(screen.getByTestId('contact-mail-error')).not.toHaveTextContent('auth_failed');
expect(screen.getByTestId('contact-next-attempt')).toBeInTheDocument();
});
it('moves a spam message to the inbox with "Geen spam"', async () => {
await openPage();
await userEvent.click(await screen.findByTestId('contact-filter-spam'));
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_SPAM}`));
await userEvent.click(await screen.findByTestId('contact-not-spam'));
await waitFor(() =>
expect(getMockContactMessages().find((m) => m.id === MSG_SPAM)?.status).toBe('read'),
);
await waitFor(() =>
expect(screen.queryByTestId(`contact-row-${MSG_SPAM}`)).not.toBeInTheDocument(),
);
await userEvent.click(screen.getByTestId('contact-filter-inbox'));
expect(await screen.findByTestId(`contact-row-${MSG_SPAM}`)).toBeInTheDocument();
});
it('does not offer resend on a spam message', async () => {
await openPage();
await userEvent.click(await screen.findByTestId('contact-filter-spam'));
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_SPAM}`));
await screen.findByTestId('contact-not-spam');
expect(screen.queryByTestId('contact-resend-button')).not.toBeInTheDocument();
});
});
describe('Delete', () => {
it('deletes after confirmation', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await userEvent.click(await screen.findByTestId('contact-delete-button'));
await userEvent.click(await screen.findByTestId('delete-message-confirm'));
await waitFor(() =>
expect(screen.queryByTestId(`contact-row-${MSG_READ}`)).not.toBeInTheDocument(),
);
expect(getMockContactMessages().some((m) => m.id === MSG_READ)).toBe(false);
});
it('keeps the message when the confirmation is cancelled', async () => {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
await userEvent.click(await screen.findByTestId('contact-delete-button'));
await userEvent.click(await screen.findByTestId('delete-message-cancel'));
expect(getMockContactMessages().some((m) => m.id === MSG_READ)).toBe(true);
});
});
describe('Resend', () => {
async function openRead() {
await openPage();
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
return screen.findByTestId('contact-resend-button');
}
it('says "Verstuurd" when the mail went out', async () => {
await userEvent.click(await openRead());
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent('Sent.');
});
it('says "Niet verstuurd" when the server could not send', async () => {
const button = await openRead();
server.use(
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
HttpResponse.json({
mailStatus: 'pending',
mailAttempts: 0,
mailed: false,
mailError: 'disabled',
}),
),
);
await userEvent.click(button);
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent(
'Not sent (mail is off).',
);
});
it('shows the retry delay from Retry-After on 429', async () => {
const button = await openRead();
server.use(
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
HttpResponse.json(
{ status: 429, title: 'Too Many Requests' },
{ status: 429, headers: { 'Retry-After': '42' } },
),
),
);
await userEvent.click(button);
const note = await screen.findByTestId('contact-resend-note');
expect(note).toHaveTextContent('Try again in 42 seconds.');
expect(note).not.toHaveTextContent('Too Many Requests');
});
it('explains a 409 on a spam message', async () => {
const button = await openRead();
server.use(
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
HttpResponse.json({ status: 409, title: 'Conflict' }, { status: 409 }),
),
);
await userEvent.click(button);
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent(
'Mark the message as not spam first.',
);
});
it('disables resend with a hint when e-mail is off for the site', async () => {
capabilities(WITH_CONTACT, false);
renderApp('/messages');
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`, {}, LONG));
expect(await screen.findByTestId('contact-resend-button')).toBeDisabled();
expect(screen.getByTestId('contact-resend-hint')).toBeInTheDocument();
});
});
@@ -0,0 +1,123 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Mail } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FormSwitchCard } from '../components/FormSwitchCard';
import { MessagesFilterChips } from '../components/MessagesFilterChips';
import { MessagesTable } from '../components/MessagesTable';
import { MessageDialog } from '../components/MessageDialog';
import { DeleteMessageDialog } from '../components/DeleteMessageDialog';
import { useContactMessages, useDeleteContactMessage } from '../services/useContactMessages';
import { contactErrorMessage } from '../errors';
import type { ContactFilter } from '../services/types';
export function MessagesPage() {
const { t } = useTranslation();
const [filter, setFilter] = useState<ContactFilter>('inbox');
const [page, setPage] = useState(1);
const [openId, setOpenId] = useState<string | null>(null);
const [deleteId, setDeleteId] = useState<string | null>(null);
const { data, isPending, isError } = useContactMessages(filter, page);
const remove = useDeleteContactMessage();
const changeFilter = (next: ContactFilter) => {
setFilter(next);
setPage(1);
};
const from = data && data.totalCount > 0 ? (data.page - 1) * data.pageSize + 1 : 0;
const to = data ? Math.min(data.page * data.pageSize, data.totalCount) : 0;
const hasPrevious = page > 1;
const hasNext = data ? to < data.totalCount : false;
return (
<div className="space-y-4 p-4">
<h1 className="text-2xl font-semibold" data-testid="messages-title">
{t('contact.title')}
</h1>
<FormSwitchCard />
<MessagesFilterChips
value={filter}
unreadCount={data?.unreadCount}
onChange={changeFilter}
/>
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
{isError && (
<p role="alert" className="text-sm text-destructive">
{t('errors.generic')}
</p>
)}
{data && data.items.length === 0 && (
<div
className="flex flex-col items-center gap-3 py-12 text-center"
data-testid="messages-empty-state"
>
<Mail className="size-10 text-muted-foreground" />
<p className="text-muted-foreground">{t(`contact.empty.${filter}`)}</p>
</div>
)}
{data && data.items.length > 0 && (
<>
<MessagesTable items={data.items} onOpen={setOpenId} />
<div className="flex items-center justify-between text-sm">
<span data-testid="messages-range">
{t('contact.pager.range', { from, to, total: data.totalCount })}
</span>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
disabled={!hasPrevious}
onClick={() => setPage(page - 1)}
data-testid="messages-prev"
>
{t('contact.pager.previous')}
</Button>
<Button
variant="outline"
size="sm"
disabled={!hasNext}
onClick={() => setPage(page + 1)}
data-testid="messages-next"
>
{t('contact.pager.next')}
</Button>
</div>
</div>
</>
)}
<MessageDialog
key={openId ?? 'closed'}
id={openId}
onClose={() => setOpenId(null)}
onDeleteRequested={setDeleteId}
/>
<DeleteMessageDialog
open={deleteId !== null}
isDeleting={remove.isPending}
error={remove.isError ? contactErrorMessage(remove.error, t) : null}
onCancel={() => {
setDeleteId(null);
remove.reset();
}}
onConfirm={() => {
if (deleteId) {
remove.mutate(deleteId, {
onSuccess: () => {
setDeleteId(null);
setOpenId(null);
},
});
}
}}
/>
</div>
);
}
@@ -0,0 +1,47 @@
export type ContactStatus = 'new' | 'read' | 'archived' | 'spam' | 'converted';
export type ContactMailStatus = 'pending' | 'sent' | 'failed' | 'notApplicable';
/** The status filters of the list; 'inbox' sends no status (the server then leaves out spam). */
export type ContactFilter = 'inbox' | 'new' | 'read' | 'archived' | 'spam';
/** The statuses an administrator may set from the detail dialog. */
export type SettableStatus = 'new' | 'read' | 'archived';
export interface ContactMessageListItem {
id: string;
receivedAt: string;
name: string;
email: string;
subject: string;
status: ContactStatus;
mailStatus: ContactMailStatus;
}
export interface ContactMessageList {
items: ContactMessageListItem[];
page: number;
pageSize: number;
totalCount: number;
unreadCount: number;
}
export interface ContactMessageDetail extends ContactMessageListItem {
message: string;
mailAttempts: number;
mailError: string | null;
retentionUntil: string;
nextMailAttemptAt?: string | null;
}
export interface ContactResendResult {
mailStatus: ContactMailStatus;
mailAttempts: number;
mailed: boolean;
mailError?: string | null;
}
export interface ContactSettings {
/** The CMS switch: whether the form on the website is open. */
enabled: boolean;
hostEnabled: boolean;
}
export const PAGE_SIZE = 25;
@@ -0,0 +1,75 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api-client';
import {
PAGE_SIZE,
type ContactFilter,
type ContactMessageDetail,
type ContactMessageList,
type ContactResendResult,
type SettableStatus,
} from './types';
const BASE = '/api/v1/contact-messages';
export function useContactMessages(filter: ContactFilter, page: number) {
return useQuery<ContactMessageList, Error>({
queryKey: ['contact', 'messages', filter, page],
queryFn: () => {
const params = new URLSearchParams({ page: String(page), pageSize: String(PAGE_SIZE) });
if (filter !== 'inbox') params.set('status', filter);
return api.get<ContactMessageList>(`${BASE}?${params.toString()}`);
},
});
}
export function useContactMessage(id: string | null) {
return useQuery<ContactMessageDetail, Error>({
queryKey: ['contact', 'message', id],
enabled: id !== null,
queryFn: () => api.get<ContactMessageDetail>(`${BASE}/${id}`),
});
}
function useInvalidateMessages() {
const queryClient = useQueryClient();
return () => {
void queryClient.invalidateQueries({ queryKey: ['contact', 'messages'] });
};
}
export function useUpdateContactMessageStatus() {
const queryClient = useQueryClient();
const invalidate = useInvalidateMessages();
return useMutation<ContactMessageDetail, Error, { id: string; status: SettableStatus }>({
mutationFn: ({ id, status }) =>
api.patch<ContactMessageDetail>(`${BASE}/${id}`, { status }),
onSuccess: (detail) => {
queryClient.setQueryData(['contact', 'message', detail.id], detail);
invalidate();
},
});
}
export function useDeleteContactMessage() {
const queryClient = useQueryClient();
const invalidate = useInvalidateMessages();
return useMutation<void, Error, string>({
mutationFn: (id) => api.delete<void>(`${BASE}/${id}`),
onSuccess: (_data, id) => {
queryClient.removeQueries({ queryKey: ['contact', 'message', id] });
invalidate();
},
});
}
export function useResendContactMessage() {
const queryClient = useQueryClient();
const invalidate = useInvalidateMessages();
return useMutation<ContactResendResult, Error, string>({
mutationFn: (id) => api.post<ContactResendResult>(`${BASE}/${id}/resend`),
onSuccess: (_result, id) => {
void queryClient.invalidateQueries({ queryKey: ['contact', 'message', id] });
invalidate();
},
});
}
@@ -0,0 +1,35 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { api, ProblemDetailsError } from '@/lib/api-client';
import type { ContactSettings } from './types';
export const CONTACT_SETTINGS_KEY = ['contact', 'settings'] as const;
/**
* The form switch. `data === null` means "not available on this host": while the host switch is off every
* management route answers 404 with an empty body, although the module is loaded.
*/
export function useContactSettings(options?: { enabled?: boolean }) {
return useQuery<ContactSettings | null, Error>({
queryKey: CONTACT_SETTINGS_KEY,
enabled: options?.enabled ?? true,
// Fixed for the lifetime of the host process; the switch itself is updated from the PUT response.
staleTime: Infinity,
queryFn: async () => {
try {
return await api.get<ContactSettings>('/api/v1/contact-settings');
} catch (error) {
if (error instanceof ProblemDetailsError && error.status === 404) return null;
throw error;
}
},
});
}
export function useUpdateContactSettings() {
const queryClient = useQueryClient();
return useMutation<ContactSettings, Error, boolean>({
mutationFn: (enabled) => api.put<ContactSettings>('/api/v1/contact-settings', { enabled }),
// The state shown is the one the server answered with.
onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings),
});
}
@@ -11,6 +11,7 @@
"users": "Users",
"cms": "CMS",
"offerings": "Offerings",
"messages": "Messages",
"profile": "Profile",
"settings": "Settings",
"openMenu": "Open navigation",
@@ -415,5 +416,101 @@
"invalidInvitationToken": "Invalid or expired invitation token.",
"featureUnavailableTitle": "Not available on this instance",
"featureUnavailable": "This feature is only available on a Master CMS instance."
},
"contact": {
"title": "Messages",
"switch": {
"title": "Contact form on the website",
"stateOn": "The form is on: visitors can send you a message.",
"stateOff": "The form is off: visitors only see your e-mail address.",
"turnOn": "Turn on",
"turnOff": "Turn off",
"nowOn": "The contact form is now on.",
"nowOff": "The contact form is now off.",
"explanation": "While the form is off, visitors only see your e-mail address. Turning it off helps against spam or during maintenance.",
"firstTimeHint": "The form stays closed until you turn it on.",
"hostOff": "The form is switched off at server level."
},
"filter": {
"label": "Filter messages",
"inbox": "Inbox",
"new": "New",
"read": "Read",
"archived": "Archived",
"spam": "Spam"
},
"table": {
"received": "Received",
"name": "Name",
"email": "E-mail address",
"subject": "Subject",
"status": "Status",
"mail": "Mail"
},
"status": {
"new": "New",
"read": "Read",
"archived": "Archived",
"spam": "Spam",
"converted": "Converted"
},
"mailStatus": {
"pending": "Mail waiting to be sent",
"sent": "Mail sent",
"failed": "Mail failed",
"notApplicable": "No mail applicable"
},
"empty": {
"inbox": "No messages yet.",
"new": "No new messages.",
"read": "No read messages.",
"archived": "No archived messages.",
"spam": "No spam."
},
"pager": {
"range": "{{from}}–{{to}} of {{total}}",
"previous": "Previous",
"next": "Next"
},
"detail": {
"title": "Message",
"retention": "Kept until",
"attempts": "({{count}} attempts)",
"nextAttempt": "Next attempt: {{time}}",
"delete": "Delete",
"resend": "Send mail again",
"notSpam": "Not spam"
},
"resend": {
"sent": "Sent.",
"notSent": "Not sent (mail is off).",
"mailOff": "Mail is off on this site."
},
"deleteDialog": {
"title": "Delete message?",
"message": "The message is deleted permanently. This cannot be undone.",
"confirm": "Delete"
},
"errors": {
"rateLimited": "Try again in {{seconds}} seconds.",
"spamResend": "Mark the message as not spam first.",
"notFound": "This message no longer exists."
},
"mailError": {
"disabled": "Mail is off.",
"recipient_not_configured": "No recipient is configured.",
"not_configured": "Mail is not configured.",
"timeout": "The mail server was too slow.",
"timeout_connect": "Connecting to the mail server took too long.",
"timeout_auth": "Logging in to the mail server took too long.",
"timeout_send": "Sending took too long.",
"auth_failed": "Logging in to the mail server failed.",
"rejected": "The mail server refused the message.",
"rejected_sender": "The mail server refused the sender address.",
"rejected_recipient": "The mail server refused the recipient.",
"tls_failed": "The secure connection to the mail server failed.",
"connection_failed": "Cannot reach the mail server.",
"unknown": "Unknown error while sending."
}
}
}
@@ -11,6 +11,7 @@
"users": "Gebruikers",
"cms": "CMS",
"offerings": "Aanbiedingen",
"messages": "Berichten",
"profile": "Profiel",
"settings": "Instellingen",
"openMenu": "Navigatie openen",
@@ -415,5 +416,101 @@
"invalidInvitationToken": "Ongeldig of verlopen uitnodigingstoken.",
"featureUnavailableTitle": "Niet beschikbaar op deze instantie",
"featureUnavailable": "Deze functie is alleen beschikbaar op een Master-CMS-instantie."
},
"contact": {
"title": "Berichten",
"switch": {
"title": "Contactformulier op de website",
"stateOn": "Het formulier staat aan: bezoekers kunnen je een bericht sturen.",
"stateOff": "Het formulier staat uit: bezoekers zien alleen je e-mailadres.",
"turnOn": "Aanzetten",
"turnOff": "Uitzetten",
"nowOn": "Het contactformulier staat nu aan.",
"nowOff": "Het contactformulier staat nu uit.",
"explanation": "Als het formulier uit staat, ziet de bezoeker alleen je e-mailadres. Uitzetten helpt bij spam of onderhoud.",
"firstTimeHint": "Het formulier is nog gesloten tot je het aanzet.",
"hostOff": "Het formulier is op serverniveau uitgeschakeld."
},
"filter": {
"label": "Filter berichten",
"inbox": "Inbox",
"new": "Nieuw",
"read": "Gelezen",
"archived": "Gearchiveerd",
"spam": "Spam"
},
"table": {
"received": "Ontvangen",
"name": "Naam",
"email": "E-mailadres",
"subject": "Onderwerp",
"status": "Status",
"mail": "Mail"
},
"status": {
"new": "Nieuw",
"read": "Gelezen",
"archived": "Gearchiveerd",
"spam": "Spam",
"converted": "Omgezet"
},
"mailStatus": {
"pending": "Mail wacht op verzending",
"sent": "Mail verstuurd",
"failed": "Mail mislukt",
"notApplicable": "Geen mail van toepassing"
},
"empty": {
"inbox": "Nog geen berichten.",
"new": "Geen nieuwe berichten.",
"read": "Geen gelezen berichten.",
"archived": "Geen gearchiveerde berichten.",
"spam": "Geen spam."
},
"pager": {
"range": "{{from}}–{{to}} van {{total}}",
"previous": "Vorige",
"next": "Volgende"
},
"detail": {
"title": "Bericht",
"retention": "Bewaard tot",
"attempts": "({{count}} pogingen)",
"nextAttempt": "Volgende poging: {{time}}",
"delete": "Verwijderen",
"resend": "Opnieuw mailen",
"notSpam": "Geen spam"
},
"resend": {
"sent": "Verstuurd.",
"notSent": "Niet verstuurd (mail staat uit).",
"mailOff": "Mail staat uit op deze site."
},
"deleteDialog": {
"title": "Bericht verwijderen?",
"message": "Het bericht wordt definitief verwijderd. Dit kan niet ongedaan worden gemaakt.",
"confirm": "Verwijderen"
},
"errors": {
"rateLimited": "Probeer het over {{seconds}} seconden opnieuw.",
"spamResend": "Markeer het bericht eerst als geen spam.",
"notFound": "Dit bericht bestaat niet meer."
},
"mailError": {
"disabled": "Mail staat uit.",
"recipient_not_configured": "Er is geen ontvanger ingesteld.",
"not_configured": "Mail is niet ingesteld.",
"timeout": "De mailserver reageerde te langzaam.",
"timeout_connect": "Verbinden met de mailserver duurde te lang.",
"timeout_auth": "Inloggen bij de mailserver duurde te lang.",
"timeout_send": "Versturen duurde te lang.",
"auth_failed": "Inloggen bij de mailserver is mislukt.",
"rejected": "De mailserver weigerde het bericht.",
"rejected_sender": "De mailserver weigerde het afzenderadres.",
"rejected_recipient": "De mailserver weigerde de ontvanger.",
"tls_failed": "De beveiligde verbinding met de mailserver is mislukt.",
"connection_failed": "Geen verbinding met de mailserver.",
"unknown": "Onbekende fout bij het versturen."
}
}
}
+4
View File
@@ -93,6 +93,10 @@ export class ApiClient {
return this.request<T>(path, { ...options, method: 'PUT', body });
}
patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'PATCH', body });
}
delete<T>(path: string, options?: RequestOptions): Promise<T> {
return this.request<T>(path, { ...options, method: 'DELETE' });
}
+3 -1
View File
@@ -6,9 +6,10 @@ import { availabilityHandlers } from '@/features/availability/mocks/handlers';
import { cmsHandlers } from '@/features/cms/mocks/handlers';
import { systemHandlers } from '@/features/system/mocks/handlers';
import { offeringsHandlers } from '@/features/offerings/mocks/handlers';
import { contactHandlers } from '@/features/contact/mocks/handlers';
/** All default MSW handlers, composed from feature folders (Q3-B). */
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers];
export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...invitationHandlers, ...availabilityHandlers, ...cmsHandlers, ...systemHandlers, ...offeringsHandlers, ...contactHandlers];
export { authHandlers } from '@/features/auth/mocks/handlers';
export { userHandlers } from '@/features/users/mocks/handlers';
@@ -18,4 +19,5 @@ export { availabilityHandlers } from '@/features/availability/mocks/handlers';
export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/features/cms/mocks/handlers';
export { systemHandlers } from '@/features/system/mocks/handlers';
export { offeringsHandlers, resetMockOfferings, getMockOfferings } from '@/features/offerings/mocks/handlers';
export { contactHandlers, resetMockContact, getMockContactMessages } from '@/features/contact/mocks/handlers';
export * from '@/features/auth/mocks/fixtures';
+16
View File
@@ -14,6 +14,7 @@ import { LoginPage } from '@/features/auth/pages/LoginPage';
import { NotFoundPage } from '@/pages/NotFoundPage';
import { RoleGuard } from '@/features/auth/components/RoleGuard';
import { ModuleGuard } from '@/features/system/components/ModuleGuard';
import { ContactAvailabilityGuard } from '@/features/contact/components/ContactAvailabilityGuard';
export interface RouterContext {
auth: AuthContextValue;
@@ -268,6 +269,20 @@ const offeringsEditRoute = createRoute({
),
});
const messagesRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/messages',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Contact">
<ContactAvailabilityGuard>
{lazyPage(() => import('@/features/contact/pages/MessagesPage'), 'MessagesPage')()}
</ContactAvailabilityGuard>
</ModuleGuard>
</RoleGuard>
),
});
const settingsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/settings',
@@ -305,6 +320,7 @@ export const routeTree = rootRoute.addChildren([
offeringsRoute,
offeringsNewRoute,
offeringsEditRoute,
messagesRoute,
settingsRoute,
profileRoute,
]),