From fd136471390284a5635e43e90146a4b6deedcba3 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 22:42:33 +0100 Subject: [PATCH] Admin: Berichten-scherm met formulierschakelaar, lijst, detail en opnieuw mailen (CMS-U6) Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u6-admin-ui-berichten/code/summary.md | 11 + ...admin-ui-berichten-code-generation-plan.md | 12 +- frontend/src/components/layout/Sidebar.tsx | 18 +- .../components/ContactAvailabilityGuard.tsx | 22 + .../components/DeleteMessageDialog.tsx | 52 +++ .../contact/components/FormSwitchCard.tsx | 75 ++++ .../contact/components/MessageDialog.tsx | 247 +++++++++++ .../components/MessagesFilterChips.tsx | 47 ++ .../contact/components/MessagesTable.tsx | 100 +++++ frontend/src/features/contact/errors.ts | 41 ++ .../src/features/contact/mocks/handlers.ts | 142 ++++++ .../contact/pages/MessagesPage.test.tsx | 418 ++++++++++++++++++ .../features/contact/pages/MessagesPage.tsx | 123 ++++++ .../src/features/contact/services/types.ts | 47 ++ .../contact/services/useContactMessages.ts | 75 ++++ .../contact/services/useContactSettings.ts | 35 ++ frontend/src/i18n/locales/en/translation.json | 97 ++++ frontend/src/i18n/locales/nl/translation.json | 97 ++++ frontend/src/lib/api-client.ts | 4 + frontend/src/mocks/index.ts | 4 +- frontend/src/router.tsx | 16 + 22 files changed, 1675 insertions(+), 10 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u6-admin-ui-berichten/code/summary.md create mode 100644 frontend/src/features/contact/components/ContactAvailabilityGuard.tsx create mode 100644 frontend/src/features/contact/components/DeleteMessageDialog.tsx create mode 100644 frontend/src/features/contact/components/FormSwitchCard.tsx create mode 100644 frontend/src/features/contact/components/MessageDialog.tsx create mode 100644 frontend/src/features/contact/components/MessagesFilterChips.tsx create mode 100644 frontend/src/features/contact/components/MessagesTable.tsx create mode 100644 frontend/src/features/contact/errors.ts create mode 100644 frontend/src/features/contact/mocks/handlers.ts create mode 100644 frontend/src/features/contact/pages/MessagesPage.test.tsx create mode 100644 frontend/src/features/contact/pages/MessagesPage.tsx create mode 100644 frontend/src/features/contact/services/types.ts create mode 100644 frontend/src/features/contact/services/useContactMessages.ts create mode 100644 frontend/src/features/contact/services/useContactSettings.ts diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 3e0cabc..6322392 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -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 diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u6-admin-ui-berichten/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u6-admin-ui-berichten/code/summary.md new file mode 100644 index 0000000..15a54f0 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u6-admin-ui-berichten/code/summary.md @@ -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. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md index 6777e5b..b25637b 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md @@ -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). diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index 37f72bf..f1680f3 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -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)); diff --git a/frontend/src/features/contact/components/ContactAvailabilityGuard.tsx b/frontend/src/features/contact/components/ContactAvailabilityGuard.tsx new file mode 100644 index 0000000..4b453e5 --- /dev/null +++ b/frontend/src/features/contact/components/ContactAvailabilityGuard.tsx @@ -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 ( +
+ +
+ ); + } + + if (isError || data === null) return ; + return <>{children}; +} diff --git a/frontend/src/features/contact/components/DeleteMessageDialog.tsx b/frontend/src/features/contact/components/DeleteMessageDialog.tsx new file mode 100644 index 0000000..8b41f2f --- /dev/null +++ b/frontend/src/features/contact/components/DeleteMessageDialog.tsx @@ -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 ( + { + if (!next) onCancel(); + }} + > + + + {t('contact.deleteDialog.title')} + +

{t('contact.deleteDialog.message')}

+ {error && ( +

+ {error} +

+ )} +
+ + +
+
+
+ ); +} diff --git a/frontend/src/features/contact/components/FormSwitchCard.tsx b/frontend/src/features/contact/components/FormSwitchCard.tsx new file mode 100644 index 0000000..d47ea56 --- /dev/null +++ b/frontend/src/features/contact/components/FormSwitchCard.tsx @@ -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 ( + + +
+
+

{t('contact.switch.title')}

+

+ {open ? t('contact.switch.stateOn') : t('contact.switch.stateOff')} +

+
+ {settings.hostEnabled ? ( + + ) : ( +

+ {t('contact.switch.hostOff')} +

+ )} +
+

{t('contact.switch.explanation')}

+ {!open && settings.hostEnabled && ( +

+ {t('contact.switch.firstTimeHint')} +

+ )} + {update.isError && ( +

+ {contactErrorMessage(update.error, t)} +

+ )} +
+
+ ); +} diff --git a/frontend/src/features/contact/components/MessageDialog.tsx b/frontend/src/features/contact/components/MessageDialog.tsx new file mode 100644 index 0000000..dd4cdfc --- /dev/null +++ b/frontend/src/features/contact/components/MessageDialog.tsx @@ -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(null); + const markedRead = useRef(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 ( + { + if (!open) onClose(); + }} + > + + + + {message ? message.subject : t('contact.detail.title')} + + {t('contact.detail.title')} + + + {isPending && ( +

{t('common.loading')}

+ )} + {isError && ( +

+ {t('errors.generic')} +

+ )} + + {message && ( +
+
+
{t('contact.table.name')}
+
{message.name}
+
{t('contact.table.email')}
+
+ + {message.email} + +
+
{t('contact.table.received')}
+
{format.format(new Date(message.receivedAt))}
+
+ {t('contact.detail.retention')} +
+
{format.format(new Date(message.retentionUntil))}
+
+ +

+ {message.message} +

+ +
+ + {isSpam ? ( + <> + {t('contact.status.spam')} + + + ) : ( + + )} +
+ {setStatus.isError && ( +

+ {contactErrorMessage(setStatus.error, t)} +

+ )} + + {!isSpam && ( +
+
+ + {t(`contact.mailStatus.${message.mailStatus}`)} + + {t('contact.detail.attempts', { + count: message.mailAttempts, + })} + +
+ {errorLabel &&

{errorLabel}

} + {message.nextMailAttemptAt && message.mailStatus !== 'sent' && ( +

+ {t('contact.detail.nextAttempt', { + time: format.format( + new Date(message.nextMailAttemptAt), + ), + })} +

+ )} +
+ )} + + {resendNote && ( +

+ {resendNote} +

+ )} + +
+ + {!isSpam && ( +
+ + {!emailEnabled && ( + + {t('contact.resend.mailOff')} + + )} +
+ )} +
+
+ )} +
+
+ ); +} diff --git a/frontend/src/features/contact/components/MessagesFilterChips.tsx b/frontend/src/features/contact/components/MessagesFilterChips.tsx new file mode 100644 index 0000000..6fa28d6 --- /dev/null +++ b/frontend/src/features/contact/components/MessagesFilterChips.tsx @@ -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 ( +
+ {FILTERS.map((filter) => { + const active = filter === value; + return ( + + ); + })} +
+ ); +} diff --git a/frontend/src/features/contact/components/MessagesTable.tsx b/frontend/src/features/contact/components/MessagesTable.tsx new file mode 100644 index 0000000..07d5957 --- /dev/null +++ b/frontend/src/features/contact/components/MessagesTable.tsx @@ -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 ; + case 'failed': + return ; + case 'pending': + return ; + default: + return ; + } +} + +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 ( +
+ + + + + + + + + + + + + {items.map((m) => ( + + + + + + + + + ))} + +
{t('contact.table.received')}{t('contact.table.name')}{t('contact.table.email')}{t('contact.table.subject')}{t('contact.table.status')}{t('contact.table.mail')}
+ {format.format(new Date(m.receivedAt))} + + + {m.email}{m.subject} + + {t(`contact.status.${m.status}`)} + + + +
+
+ ); +} diff --git a/frontend/src/features/contact/errors.ts b/frontend/src/features/contact/errors.ts new file mode 100644 index 0000000..43ea751 --- /dev/null +++ b/frontend/src/features/contact/errors.ts @@ -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'); +} diff --git a/frontend/src/features/contact/mocks/handlers.ts b/frontend/src/features/contact/mocks/handlers.ts new file mode 100644 index 0000000..c44290c --- /dev/null +++ b/frontend/src/features/contact/mocks/handlers.ts @@ -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, + }); + }), +]; diff --git a/frontend/src/features/contact/pages/MessagesPage.test.tsx b/frontend/src/features/contact/pages/MessagesPage.test.tsx new file mode 100644 index 0000000..c40c733 --- /dev/null +++ b/frontend/src/features/contact/pages/MessagesPage.test.tsx @@ -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(); + }); +}); diff --git a/frontend/src/features/contact/pages/MessagesPage.tsx b/frontend/src/features/contact/pages/MessagesPage.tsx new file mode 100644 index 0000000..e6e8597 --- /dev/null +++ b/frontend/src/features/contact/pages/MessagesPage.tsx @@ -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('inbox'); + const [page, setPage] = useState(1); + const [openId, setOpenId] = useState(null); + const [deleteId, setDeleteId] = useState(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 ( +
+

+ {t('contact.title')} +

+ + + + + + {isPending &&

{t('common.loading')}

} + {isError && ( +

+ {t('errors.generic')} +

+ )} + + {data && data.items.length === 0 && ( +
+ +

{t(`contact.empty.${filter}`)}

+
+ )} + + {data && data.items.length > 0 && ( + <> + +
+ + {t('contact.pager.range', { from, to, total: data.totalCount })} + +
+ + +
+
+ + )} + + setOpenId(null)} + onDeleteRequested={setDeleteId} + /> + + { + setDeleteId(null); + remove.reset(); + }} + onConfirm={() => { + if (deleteId) { + remove.mutate(deleteId, { + onSuccess: () => { + setDeleteId(null); + setOpenId(null); + }, + }); + } + }} + /> +
+ ); +} diff --git a/frontend/src/features/contact/services/types.ts b/frontend/src/features/contact/services/types.ts new file mode 100644 index 0000000..68f1d6f --- /dev/null +++ b/frontend/src/features/contact/services/types.ts @@ -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; diff --git a/frontend/src/features/contact/services/useContactMessages.ts b/frontend/src/features/contact/services/useContactMessages.ts new file mode 100644 index 0000000..5e6b1e5 --- /dev/null +++ b/frontend/src/features/contact/services/useContactMessages.ts @@ -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({ + 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(`${BASE}?${params.toString()}`); + }, + }); +} + +export function useContactMessage(id: string | null) { + return useQuery({ + queryKey: ['contact', 'message', id], + enabled: id !== null, + queryFn: () => api.get(`${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({ + mutationFn: ({ id, status }) => + api.patch(`${BASE}/${id}`, { status }), + onSuccess: (detail) => { + queryClient.setQueryData(['contact', 'message', detail.id], detail); + invalidate(); + }, + }); +} + +export function useDeleteContactMessage() { + const queryClient = useQueryClient(); + const invalidate = useInvalidateMessages(); + return useMutation({ + mutationFn: (id) => api.delete(`${BASE}/${id}`), + onSuccess: (_data, id) => { + queryClient.removeQueries({ queryKey: ['contact', 'message', id] }); + invalidate(); + }, + }); +} + +export function useResendContactMessage() { + const queryClient = useQueryClient(); + const invalidate = useInvalidateMessages(); + return useMutation({ + mutationFn: (id) => api.post(`${BASE}/${id}/resend`), + onSuccess: (_result, id) => { + void queryClient.invalidateQueries({ queryKey: ['contact', 'message', id] }); + invalidate(); + }, + }); +} diff --git a/frontend/src/features/contact/services/useContactSettings.ts b/frontend/src/features/contact/services/useContactSettings.ts new file mode 100644 index 0000000..544144c --- /dev/null +++ b/frontend/src/features/contact/services/useContactSettings.ts @@ -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({ + 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('/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({ + mutationFn: (enabled) => api.put('/api/v1/contact-settings', { enabled }), + // The state shown is the one the server answered with. + onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings), + }); +} diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 4f86ac9..e6e1da3 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -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." + } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 3edb0eb..258b3a9 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -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." + } } } diff --git a/frontend/src/lib/api-client.ts b/frontend/src/lib/api-client.ts index 2522a62..c975018 100644 --- a/frontend/src/lib/api-client.ts +++ b/frontend/src/lib/api-client.ts @@ -93,6 +93,10 @@ export class ApiClient { return this.request(path, { ...options, method: 'PUT', body }); } + patch(path: string, body?: unknown, options?: RequestOptions): Promise { + return this.request(path, { ...options, method: 'PATCH', body }); + } + delete(path: string, options?: RequestOptions): Promise { return this.request(path, { ...options, method: 'DELETE' }); } diff --git a/frontend/src/mocks/index.ts b/frontend/src/mocks/index.ts index 846d606..213db9f 100644 --- a/frontend/src/mocks/index.ts +++ b/frontend/src/mocks/index.ts @@ -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'; diff --git a/frontend/src/router.tsx b/frontend/src/router.tsx index 8d89b12..a4c6751 100644 --- a/frontend/src/router.tsx +++ b/frontend/src/router.tsx @@ -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: () => ( + + + + {lazyPage(() => import('@/features/contact/pages/MessagesPage'), 'MessagesPage')()} + + + + ), +}); + const settingsRoute = createRoute({ getParentRoute: () => authenticatedRoute, path: '/settings', @@ -305,6 +320,7 @@ export const routeTree = rootRoute.addChildren([ offeringsRoute, offeringsNewRoute, offeringsEditRoute, + messagesRoute, settingsRoute, profileRoute, ]),