diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u11-recipient-from-site-settings/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u11-recipient-from-site-settings/code/summary.md new file mode 100644 index 0000000..08711ef --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u11-recipient-from-site-settings/code/summary.md @@ -0,0 +1,6 @@ +# CMS-U11 — Recipient address from the site settings (summary) + +- Backend: nullable `RecipientEmail` on `ContactSettings` (migration `ContactSettingsRecipient`); `IContactSettingsService.GetEffectiveRecipientAsync` (setting > env > none) and `SetRecipientAsync` (wakes the mail sender); `ContactMailSender` reads the recipient per send (`NotReadyReasonAsync`); `GET /contact-settings` + `recipientEmail`/`recipientSource` (the env address is never returned); `PUT /contact-settings/recipient`; OpenAPI regenerated. +- Frontend: `RecipientCard` next to the form switch (field, save, back to the server setting, source text, client + server validation, translated), warning banner on the switch card while there is no address (no blocking). nl/en. +- Tests (new/changed): resolution order, invalid stored value ignored, admin view never shows the env address, set/clear, signal, sender uses the setting without a restart, no address = not ready + nothing sent, controller (valid/trimmed/blank/invalid/CRLF/too long/missing body), pipeline on the real host (login/role, view, set/invalid/clear, no leak in the public token response, a stored-but-pending message goes out after the address is set), route-table test, OpenAPI snapshot; frontend (field, save, invalid client/server, clear, banner without blocking). The existing outgoing contact mail tests keep their intent (only their construction and the async `NotReadyReasonAsync` signature were adapted). +- Decisions (approved): warn instead of block; the env address is not shown; the field sits on the Berichten page. diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md index 60122b9..f704832 100644 --- a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -109,7 +109,7 @@ CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings` Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifications + andreaslop-site-hosting). Conflicts: `aidlc-docs/active-features.md` (kept master's table, appended our row), `AvailabilityMiddleware` (kept their `CheckAdmin` / expired-token 401 behaviour, our marker block before it), `AddCmsRateLimiting.OnRejected` (kept their Retry-After logic for sliding windows, added the `60 s` fallback for policies without a wait and the problem+json body), `SlpModularCms.sln` (took master's, re-added the two Contact projects). No EF snapshot conflict (own contexts). Checklist steps 1 and 2 are DONE: `ContactRateLimitPartition.KeyFor` now returns `ClientPartitionKey.For(context)` and its test asserts different buckets per address. Still open: step 3 (`ForwardedHeaders:KnownProxies` per host), step 5 (`Contact:Enabled=true`), step 6 (CMS switch). `GET /System/capabilities` now carries `[PublicSiteEndpoint]` (never 503; separate commit). The pipeline tests for the management routes log in with a real user (the host validates every access token against its user and security stamp). ## 7. CMS-U5 additions (contact mail) -- Env var `Contact__RecipientEmail` (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`. +- Recipient address: since CMS-U11 the **site setting wins over** the env var `Contact__RecipientEmail` (see section 9); the env var stays the default/fallback (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`. - Mail itself needs the host's normal `Email:*` configuration; without it messages stay `pending` with `mailError: "disabled"`. - Detail: `nextMailAttemptAt`; resend: `mailError`. New migration `ContactMailClaim`. @@ -144,3 +144,15 @@ With `Contact:Enabled=true` and `Captcha:Enabled=true` the host **refuses to sta - References `Modules.Contact`; section `Contact` in its `appsettings.json` (`Enabled:false`, `SiteId: andreaslop`), the three contact rate-limit policies. Capabilities now list `Contact`; the module does nothing and touches no database while `Contact:Enabled=false`. - Release conditions (also in the comment of that section): `ForwardedHeaders__KnownProxies__0` = reverse proxy (IIS) address first (otherwise the whole site shares one bucket); `Contact__RecipientEmail` (env only); mail via `Email__Smtp__*`, `App__PublicBaseUrl`; sender = `Email:FromAddress` or the address chosen in the site settings from `Email:AllowedFromAddresses` (set by environment for ASF); captcha settings above; then `Contact__Enabled=true` and the admin switch (Berichten). - Host tests (`Api.AndreaSlopFotografie.Tests/ContactHostTests.cs`, real MariaDB): closed by default; public routes stay reachable (200/202) while the availability gate is "not available" and the management routes answer 503; per-client buckets with a known proxy vs one shared bucket without. + +## 9. CMS-U11 additions (recipient address from the site settings) + +Order of precedence for the address contact mails are sent to: **site setting (CMS admin, Berichten) > `Contact__RecipientEmail` (environment) > none.** The setting changes without a restart (read on every send); an invalid stored value is ignored (falls back). Table `ContactSettings` gets a nullable `RecipientEmail` (migration `ContactSettingsRecipient`, additive). + +| Method + path | Auth | Notes | +|---|---|---| +| `GET /contact-settings` | AdminOnly | now `{ enabled, hostEnabled, recipientEmail: string\|null, recipientSource: "setting"\|"config"\|"none" }`. `recipientEmail` is only the CMS setting; **the address from the environment is never returned** (source `config` = "set by the server configuration"). | +| `PUT /contact-settings/recipient` `{ "recipientEmail": string\|null }` | AdminOnly | `200` same shape as GET; `null`/blank clears the setting (back to the environment default); trimmed; `EmailAddressRules`; `400` problem+json `errors.recipientEmail = ["invalid"]` or `["tooLong"]` (> 254), never echoing the value; `401/403/404/503` as the other management routes. Not part of any public route or OpenAPI example. | +| `PUT /contact-settings` `{ enabled }` | AdminOnly | unchanged. | + +Without any address (`recipientSource: "none"`) the host still starts and the form can still be switched on (warn, not block): messages are stored, the mail stays `pending` with `mailError: "recipient_not_configured"` (not counted as an attempt) and goes out by itself within seconds once an address is set (setting the address wakes the mail sender). The admin shows a warning banner on the switch card. Release condition for SLP/ASF: the address no longer has to be in the environment when it is set in the admin. diff --git a/frontend/src/features/contact/components/FormSwitchCard.tsx b/frontend/src/features/contact/components/FormSwitchCard.tsx index 934074f..6324c44 100644 --- a/frontend/src/features/contact/components/FormSwitchCard.tsx +++ b/frontend/src/features/contact/components/FormSwitchCard.tsx @@ -51,6 +51,15 @@ export function FormSwitchCard() { )}

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

+ {settings.recipientSource === 'none' && ( +

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

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

{t('contact.switch.firstTimeHint')} diff --git a/frontend/src/features/contact/components/RecipientCard.tsx b/frontend/src/features/contact/components/RecipientCard.tsx new file mode 100644 index 0000000..544ae6d --- /dev/null +++ b/frontend/src/features/contact/components/RecipientCard.tsx @@ -0,0 +1,148 @@ +import { useState, type FormEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent } from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { ProblemDetailsError } from '@/lib/api-client'; +import { useContactSettings, useUpdateContactRecipient } from '../services/useContactSettings'; +import { contactErrorMessage } from '../errors'; + +// Same shape the server accepts: something@domain.tld, no spaces. The server decides; this only saves a round trip. +const LOOKS_LIKE_AN_ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; + +function RecipientForm({ saved }: { saved: string }) { + const { t } = useTranslation(); + const { data: settings } = useContactSettings(); + const update = useUpdateContactRecipient(); + const [draft, setDraft] = useState(saved); + const [touched, setTouched] = useState(false); + + const trimmed = draft.trim(); + const clientInvalid = trimmed.length > 0 && !LOOKS_LIKE_AN_ADDRESS.test(trimmed); + const canSave = trimmed.length > 0 && !clientInvalid && trimmed !== saved && !update.isPending; + const source = settings?.recipientSource ?? 'none'; + + const save = (event: FormEvent) => { + event.preventDefault(); + setTouched(true); + if (!canSave) return; + update.mutate(trimmed, { onSuccess: () => toast.success(t('contact.recipient.saved')) }); + }; + + const reset = () => + update.mutate(null, { + onSuccess: () => { + setDraft(''); + toast.success(t('contact.recipient.cleared')); + }, + }); + + const serverMessage = update.isError + ? update.error instanceof ProblemDetailsError && update.error.status === 400 + ? t('contact.recipient.invalid') + : contactErrorMessage(update.error, t) + : null; + + return ( +

+
+ + { + setDraft(e.target.value); + setTouched(false); + update.reset(); + }} + data-testid="contact-recipient-input" + /> + {touched && clientInvalid && ( +

+ {t('contact.recipient.invalid')} +

+ )} +
+ +

+ {t(`contact.recipient.source.${source}`)} +

+ + {serverMessage && ( +

+ {serverMessage} +

+ )} + +
+ + {saved && ( + + )} +
+
+ ); +} + +/** The address contact messages are mailed to: the site setting, with the server configuration as the default. */ +export function RecipientCard() { + const { t } = useTranslation(); + const { data: settings } = useContactSettings(); + + if (!settings) return null; + + return ( + + +
+

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

+

+ {t('contact.recipient.description')} +

+
+ {/* Keyed by the saved value, so the field follows what the server answered. */} + +
+
+ ); +} diff --git a/frontend/src/features/contact/mocks/handlers.ts b/frontend/src/features/contact/mocks/handlers.ts index 3330e11..7ef6079 100644 --- a/frontend/src/features/contact/mocks/handlers.ts +++ b/frontend/src/features/contact/mocks/handlers.ts @@ -62,11 +62,21 @@ function seed(): ContactMessageDetail[] { } let messages = seed(); -let settings: ContactSettings = { enabled: false, hostEnabled: true }; +let settings: ContactSettings = { + enabled: false, + hostEnabled: true, + recipientEmail: null, + recipientSource: 'config', +}; export function resetMockContact(): void { messages = seed(); - settings = { enabled: false, hostEnabled: true }; + settings = { + enabled: false, + hostEnabled: true, + recipientEmail: null, + recipientSource: 'config', + }; } export function getMockContactMessages(): ContactMessageDetail[] { @@ -87,6 +97,26 @@ function toItem(m: ContactMessageDetail): ContactMessageListItem { export const contactHandlers = [ http.get(SETTINGS, () => HttpResponse.json(settings)), + http.put(`${SETTINGS}/recipient`, async ({ request }) => { + const body = (await request.json()) as { recipientEmail: string | null }; + const address = body.recipientEmail?.trim() || null; + if (address && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(address)) { + return HttpResponse.json( + { + status: 400, + title: 'Validation failed', + errors: { recipientEmail: ['invalid'] }, + }, + { status: 400 }, + ); + } + settings = { + ...settings, + recipientEmail: address, + recipientSource: address ? 'setting' : 'config', + }; + return HttpResponse.json(settings); + }), http.put(SETTINGS, async ({ request }) => { const body = (await request.json()) as { enabled: boolean }; settings = { ...settings, enabled: body.enabled }; diff --git a/frontend/src/features/contact/pages/MessagesPage.test.tsx b/frontend/src/features/contact/pages/MessagesPage.test.tsx index 5da1e7a..faa6c16 100644 --- a/frontend/src/features/contact/pages/MessagesPage.test.tsx +++ b/frontend/src/features/contact/pages/MessagesPage.test.tsx @@ -165,6 +165,112 @@ describe('Form switch', () => { }); }); +describe('Recipient address', () => { + it('shows the field, says that the server setting applies, and never an address it was not given', async () => { + await openPage(); + + expect(await screen.findByTestId('contact-recipient-card')).toBeInTheDocument(); + expect(screen.getByTestId('contact-recipient-input')).toHaveValue(''); + expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent( + 'server setting applies', + ); + expect(screen.queryByTestId('contact-recipient-reset')).not.toBeInTheDocument(); + expect(screen.queryByTestId('contact-no-recipient-banner')).not.toBeInTheDocument(); + }); + + it('saves a valid address, shows where it comes from and offers to go back', async () => { + await openPage(); + const input = await screen.findByTestId('contact-recipient-input'); + + await userEvent.type(input, ' inbox@example.org '); + await userEvent.click(screen.getByTestId('contact-recipient-save')); + + await waitFor(() => + expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent( + 'Messages go to this address', + ), + ); + expect(screen.getByTestId('contact-recipient-input')).toHaveValue('inbox@example.org'); + expect(screen.getByTestId('contact-recipient-reset')).toBeInTheDocument(); + }); + + it('does not save an invalid address (client side), and says so', async () => { + await openPage(); + const input = await screen.findByTestId('contact-recipient-input'); + + await userEvent.type(input, 'not-an-address'); + await userEvent.click(screen.getByTestId('contact-recipient-save')); + + expect(await screen.findByTestId('contact-recipient-invalid')).toHaveTextContent( + 'valid e-mail address', + ); + }); + + it('shows a translated message when the server refuses the address', async () => { + await openPage(); + server.use( + http.put(`${API_BASE}/api/v1/contact-settings/recipient`, () => + HttpResponse.json( + { + status: 400, + title: 'Validation failed', + errors: { recipientEmail: ['invalid'] }, + }, + { status: 400 }, + ), + ), + ); + await userEvent.type( + await screen.findByTestId('contact-recipient-input'), + 'jan@example.org', + ); + await userEvent.click(screen.getByTestId('contact-recipient-save')); + + const error = await screen.findByTestId('contact-recipient-error'); + expect(error).toHaveTextContent('valid e-mail address'); + expect(error).not.toHaveTextContent('Validation failed'); + }); + + it('goes back to the server setting when cleared', async () => { + await openPage(); + await userEvent.type( + await screen.findByTestId('contact-recipient-input'), + 'inbox@example.org', + ); + await userEvent.click(screen.getByTestId('contact-recipient-save')); + await userEvent.click(await screen.findByTestId('contact-recipient-reset')); + + await waitFor(() => + expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent( + 'server setting applies', + ), + ); + expect(screen.getByTestId('contact-recipient-input')).toHaveValue(''); + }); + + it('warns (but does not block the switch) while there is no address at all', async () => { + server.use( + http.get(`${API_BASE}/api/v1/contact-settings`, () => + HttpResponse.json({ + enabled: false, + hostEnabled: true, + recipientEmail: null, + recipientSource: 'none', + }), + ), + ); + await openPage(); + + expect(await screen.findByTestId('contact-no-recipient-banner')).toHaveTextContent( + 'No recipient address is set', + ); + expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent( + 'no recipient address yet', + ); + expect(screen.getByTestId('contact-switch-toggle')).not.toBeDisabled(); + }); +}); + describe('Message list', () => { it('shows the inbox without spam and the unread counter', async () => { await openPage(); diff --git a/frontend/src/features/contact/pages/MessagesPage.tsx b/frontend/src/features/contact/pages/MessagesPage.tsx index e6e8597..7ecee42 100644 --- a/frontend/src/features/contact/pages/MessagesPage.tsx +++ b/frontend/src/features/contact/pages/MessagesPage.tsx @@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next'; import { Mail } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { FormSwitchCard } from '../components/FormSwitchCard'; +import { RecipientCard } from '../components/RecipientCard'; import { MessagesFilterChips } from '../components/MessagesFilterChips'; import { MessagesTable } from '../components/MessagesTable'; import { MessageDialog } from '../components/MessageDialog'; @@ -38,6 +39,8 @@ export function MessagesPage() { + + ({ + mutationFn: (recipientEmail) => + api.put('/api/v1/contact-settings/recipient', { recipientEmail }), + onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings), + }); +} + export function useUpdateContactSettings() { const queryClient = useQueryClient(); return useMutation({ diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index a6861e4..f174414 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -431,7 +431,8 @@ "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." + "hostOff": "The form is switched off at server level.", + "noRecipientBanner": "No recipient address is set: messages are kept but not mailed. Enter an address below." }, "filter": { "label": "Filter messages", @@ -515,6 +516,22 @@ "tls_failed": "The secure connection to the mail server failed.", "connection_failed": "Cannot reach the mail server.", "unknown": "Unknown error while sending." + }, + "recipient": { + "title": "Recipient address for contact messages", + "description": "We mail every new message to this address. You can reply to that mail directly: the reply goes to the visitor.", + "label": "E-mail address", + "placeholder": "name@example.com", + "save": "Save", + "reset": "Back to the server setting", + "saved": "Recipient address saved.", + "cleared": "The server setting applies again.", + "invalid": "Enter a valid e-mail address.", + "source": { + "setting": "Messages go to this address.", + "config": "No address of your own is set: the server setting applies.", + "none": "There is no recipient address yet: messages are kept but not mailed." + } } } } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index 5055ec1..9918eed 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -431,7 +431,8 @@ "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." + "hostOff": "Het formulier is op serverniveau uitgeschakeld.", + "noRecipientBanner": "Er is geen ontvangstadres ingesteld: berichten worden bewaard maar niet gemaild. Vul hieronder een adres in." }, "filter": { "label": "Filter berichten", @@ -515,6 +516,22 @@ "tls_failed": "De beveiligde verbinding met de mailserver is mislukt.", "connection_failed": "Geen verbinding met de mailserver.", "unknown": "Onbekende fout bij het versturen." + }, + "recipient": { + "title": "Ontvangstadres contactberichten", + "description": "Hierheen sturen we een mail bij elk nieuw bericht. Je kunt direct op die mail antwoorden: het antwoord gaat naar de bezoeker.", + "label": "E-mailadres", + "placeholder": "naam@voorbeeld.nl", + "save": "Opslaan", + "reset": "Terug naar serverinstelling", + "saved": "Ontvangstadres opgeslagen.", + "cleared": "De serverinstelling geldt weer.", + "invalid": "Voer een geldig e-mailadres in.", + "source": { + "setting": "Berichten gaan naar dit adres.", + "config": "Er is geen eigen adres ingesteld: de serverinstelling geldt.", + "none": "Er is nog geen ontvangstadres: berichten worden bewaard maar niet gemaild." + } } } } diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 9d9b3c2..99f28da 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -344,6 +344,16 @@ }, "hostEnabled": { "type": "boolean" + }, + "recipientEmail": { + "type": [ + "null", + "string" + ] + }, + "recipientSource": { + "default": "none", + "type": "string" } }, "required": [ @@ -693,6 +703,20 @@ ], "type": "object" }, + "UpdateContactRecipientRequest": { + "properties": { + "recipientEmail": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "recipientEmail" + ], + "type": "object" + }, "UpdateContactSettingsRequest": { "properties": { "enabled": { @@ -2088,6 +2112,63 @@ ] } }, + "/api/v1/contact-settings/recipient": { + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactRecipientRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactRecipientRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactSettingsDto" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "ContactSettings" + ] + } + }, "/api/v1/offerings": { "get": { "responses": { diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs index c2030cd..8a24dcd 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs @@ -248,6 +248,7 @@ public class ContactAdminControllerTests "POST contact-messages/{id:guid}/resend", "GET contact-settings", "PUT contact-settings", + "PUT contact-settings/recipient", ]); } diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs index 8e01f68..4060ec7 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs @@ -45,6 +45,14 @@ public class ContactMailSenderTests public CapturingLoggerProvider Logs { get; } = new(); public OutgoingMail? Sent; + private readonly ContactDbContext _db = new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); + + /// The real settings service on an in-memory database: the administrator's setting and the environment. + public IContactSettingsService ContactSettings => new ContactSettingsService( + new ContactRepository(_db), new ContactSettingsCache(TimeProvider.System), Options.Create(Contact), + TimeProvider.System, Substitute.For()); + public Rig() { Availability.IsEnabled.Returns(true); @@ -62,7 +70,7 @@ public class ContactMailSenderTests var settings = Substitute.For(); settings.GetEffectiveSenderAsync(Arg.Any()).Returns(("noreply@example.org", "De Site")); return new ContactMailSender( - Email, new MailTemplateRenderer(), languages, settings, Availability, + Email, new MailTemplateRenderer(), languages, settings, ContactSettings, Availability, Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }), Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger()); } @@ -179,7 +187,7 @@ public class ContactMailSenderTests var result = await sut.SendAsync(Message(), CancellationToken.None); result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "disabled")); - sut.NotReadyReason().Should().Be("disabled"); + (await sut.NotReadyReasonAsync(CancellationToken.None)).Should().Be("disabled"); await rig.Email.DidNotReceive().SendAsync(Arg.Any(), Arg.Any()); } @@ -212,7 +220,7 @@ public class ContactMailServiceTests : IDisposable public ContactMailServiceTests() { - _sender.NotReadyReason().Returns((string?)null); + _sender.NotReadyReasonAsync(Arg.Any()).Returns((string?)null); _sender.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Sent); var services = new ServiceCollection(); @@ -330,7 +338,7 @@ public class ContactMailServiceTests : IDisposable [Fact] public async Task WhenMailCannotBeSent_NothingIsAttemptedOrCounted_AndTheReasonIsShown() { - _sender.NotReadyReason().Returns("disabled"); + _sender.NotReadyReasonAsync(Arg.Any()).Returns("disabled"); var id = Add(); (await Sut().SweepAsync(CancellationToken.None)).Should().Be(0); @@ -342,7 +350,7 @@ public class ContactMailServiceTests : IDisposable await _sender.DidNotReceive().SendAsync(Arg.Any(), Arg.Any()); // Once mail works again the same message goes out without any lost attempts. - _sender.NotReadyReason().Returns((string?)null); + _sender.NotReadyReasonAsync(Arg.Any()).Returns((string?)null); (await Sut().SweepAsync(CancellationToken.None)).Should().Be(1); Get(id).MailAttempts.Should().Be(1); } diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactRecipientTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactRecipientTests.cs new file mode 100644 index 0000000..c6bcf6e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactRecipientTests.cs @@ -0,0 +1,241 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Core.Email; +using SlpModularCms.Core.SiteSettings; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +/// The recipient of contact mails: the administrator's setting wins over the environment, which stays the default. +public class ContactRecipientTests : IDisposable +{ + private const string FromEnvironment = "env-inbox@example.org"; + private const string FromSetting = "setting-inbox@example.org"; + + private readonly ContactOptions _options = new() { Enabled = true, RecipientEmail = FromEnvironment }; + private readonly ContactDbContext _db = new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); + private readonly IContactMailSignal _signal = Substitute.For(); + private readonly FakeTimeProvider _time = new(new DateTimeOffset(2026, 11, 10, 12, 0, 0, TimeSpan.Zero)); + + public void Dispose() => _db.Dispose(); + + private ContactSettingsService Settings() => new( + new ContactRepository(_db), new ContactSettingsCache(_time), Options.Create(_options), _time, _signal); + + [Fact] + public async Task WithoutASetting_TheEnvironmentIsTheDefault() + { + (await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config")); + } + + [Fact] + public async Task AFilledSetting_Wins_AndTheEnvironmentIsTheFallbackAgainAfterClearing() + { + var sut = Settings(); + + await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None); + (await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromSetting, "setting")); + + await sut.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None); + (await sut.GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config")); + + await sut.SetRecipientAsync(" ", Guid.NewGuid(), CancellationToken.None); + (await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Source.Should().Be("config"); + } + + [Fact] + public async Task WithNeitherOfThem_ThereIsNoRecipient() + { + _options.RecipientEmail = null; + + (await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be(((string?)null, "none")); + } + + [Fact] + public async Task AnInvalidStoredAddress_IsIgnored_NotUsed() + { + _db.ContactSettings.Add(new ContactSettings { Enabled = true, RecipientEmail = "not an address\r\nBcc: x@y.z", UpdatedAt = _time.GetUtcNow() }); + await _db.SaveChangesAsync(); + + (await Settings().GetEffectiveRecipientAsync(CancellationToken.None)).Should().Be((FromEnvironment, "config")); + } + + [Fact] + public async Task TheAdminView_ShowsTheSettingAndTheSource_ButNeverTheEnvironmentAddress() + { + var sut = Settings(); + + var onlyEnvironment = await sut.GetAsync(CancellationToken.None); + onlyEnvironment.RecipientEmail.Should().BeNull(); + onlyEnvironment.RecipientSource.Should().Be("config"); + + var withSetting = await sut.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None); + withSetting.RecipientEmail.Should().Be(FromSetting); + withSetting.RecipientSource.Should().Be("setting"); + System.Text.Json.JsonSerializer.Serialize(onlyEnvironment).Should().NotContain(FromEnvironment); + + _options.RecipientEmail = null; + (await Settings().SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None)).RecipientSource.Should().Be("none"); + } + + [Fact] + public async Task SettingTheAddress_KeepsTheSwitch_RemembersWho_AndWakesTheMailSender() + { + var sut = Settings(); + var user = Guid.NewGuid(); + await sut.SetEnabledAsync(true, user, CancellationToken.None); + + var saved = await sut.SetRecipientAsync(FromSetting, user, CancellationToken.None); + + saved.Enabled.Should().BeTrue("setting the address does not touch the switch"); + (await _db.ContactSettings.SingleAsync()).UpdatedByUserId.Should().Be(user); + _signal.Received(1).Notify(); + } + + [Fact] + public async Task SettingTheAddressFirst_CreatesTheRowWithTheSwitchOff() + { + var saved = await Settings().SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None); + + saved.Enabled.Should().BeFalse(); + saved.RecipientEmail.Should().Be(FromSetting); + } + + [Fact] + public async Task TheMailSender_UsesTheSettingAtOnce_WithoutRestart_AndFallsBackToTheEnvironment() + { + var email = Substitute.For(); + OutgoingMail? sent = null; + email.SendAsync(Arg.Any(), Arg.Any()).Returns(call => + { + sent = call.Arg(); + return MailSendResult.Ok; + }); + var availability = Substitute.For(); + availability.IsEnabled.Returns(true); + var languages = Substitute.For(); + languages.Resolve(Arg.Any()).Returns("nl"); + var siteSettings = Substitute.For(); + siteSettings.GetEffectiveSenderAsync(Arg.Any()).Returns(("noreply@example.org", "De Site")); + var settings = Settings(); + var sender = new ContactMailSender( + email, new MailTemplateRenderer(), languages, siteSettings, settings, availability, + Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }), + Options.Create(_options), LoggerFactory.Create(_ => { }).CreateLogger()); + var message = new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "Jan", Email = "jan@example.nl", Subject = "Website", Message = "Hallo" }; + + await sender.SendAsync(message, CancellationToken.None); + sent!.ToAddress.Should().Be(FromEnvironment); + + await settings.SetRecipientAsync(FromSetting, Guid.NewGuid(), CancellationToken.None); + await sender.SendAsync(message, CancellationToken.None); + sent.ToAddress.Should().Be(FromSetting); + + await settings.SetRecipientAsync(null, Guid.NewGuid(), CancellationToken.None); + await sender.SendAsync(message, CancellationToken.None); + sent.ToAddress.Should().Be(FromEnvironment); + } + + [Fact] + public async Task WithoutAnyAddress_TheSenderIsNotReady_WithAClearReason_AndNothingIsSent() + { + _options.RecipientEmail = null; + var email = Substitute.For(); + var availability = Substitute.For(); + availability.IsEnabled.Returns(true); + var sender = new ContactMailSender( + email, new MailTemplateRenderer(), Substitute.For(), Substitute.For(), Settings(), availability, + Options.Create(new EmailOptions()), Options.Create(new AppMailOptions()), Options.Create(_options), + LoggerFactory.Create(_ => { }).CreateLogger()); + + (await sender.NotReadyReasonAsync(CancellationToken.None)).Should().Be("recipient_not_configured"); + var result = await sender.SendAsync(new ContactMessage { Id = Guid.NewGuid(), SiteId = "s", Name = "J", Email = "j@example.nl", Subject = "S", Message = "M" }, CancellationToken.None); + + result.Should().Be(new ContactMailResult(ContactMailOutcome.Skipped, "recipient_not_configured")); + await email.DidNotReceive().SendAsync(Arg.Any(), Arg.Any()); + } +} + +public class ContactRecipientControllerTests +{ + private readonly IContactSettingsService _settings = Substitute.For(); + private readonly ContactSettingsController _sut; + + public ContactRecipientControllerTests() + { + _sut = new ContactSettingsController(_settings, Options.Create(new ContactOptions())) + { + ControllerContext = new ControllerContext { HttpContext = new Microsoft.AspNetCore.Http.DefaultHttpContext() }, + }; + _settings.SetRecipientAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => new ContactSettingsDto(false, true, call.Arg(), call.Arg() is null ? "config" : "setting")); + } + + [Theory] + [InlineData("jan@example.nl")] + [InlineData(" jan@example.nl ")] + public async Task AValidAddress_IsSavedTrimmed(string address) + { + var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None); + + result.Should().BeOfType(); + await _settings.Received(1).SetRecipientAsync("jan@example.nl", Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task NullOrBlank_ClearsTheSetting(string? address) + { + var result = await _sut.PutRecipient(new UpdateContactRecipientRequest(address), CancellationToken.None); + + result.Should().BeOfType(); + await _settings.Received(1).SetRecipientAsync(null, Arg.Any(), Arg.Any()); + } + + [Theory] + [InlineData("not-an-address")] + [InlineData("a@b")] + [InlineData("jan@example.nl\r\nBcc: evil@example.com")] + [InlineData("jan@example.nl, other@example.nl")] + [InlineData("