diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index f6d42b1..0b79319 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**: CONSTRUCTION - CMS-U4 built and committed (awaiting review); next phase 2 after the ASF merge (CMS-U5, U6, U7) +- **Current Stage**: PHASE 2 planning - rebased on master e671078; plans CMS-U5, U6, U7 awaiting approval by Redesign - SLS - **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/audit.md b/aidlc-docs/features/contact-forms-module/audit.md index d02d6ea..dd29407 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -131,3 +131,15 @@ **Context**: Construction phase 1 complete. --- + +## Rebase onto master e671078 and phase 2 plans + +**Timestamp**: 2026-11-10 + +**User Input**: "De ASF-merge is klaar: PR #11 ... merge-commit e671078 ... rebase feature/contact-forms-module, KeyFor -> ClientPartitionKey.For + de ene testassertie, System/capabilities-marker als aparte commit, alle tests incl. pipelinetests. Stuur daarna het rebase-resultaat plus de plannen voor CMS-U5, U6, U7." (via Redesign - SLS) + +**AI Response**: Rebase done (conflicts: active-features, AvailabilityMiddleware, OnRejected, sln); three follow-up commits; all tests green; plans for U5, U6, U7 written. + +**Context**: Phase 2 planning. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u5-contact-mail-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u5-contact-mail-code-generation-plan.md new file mode 100644 index 0000000..af1121c --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u5-contact-mail-code-generation-plan.md @@ -0,0 +1,36 @@ +# Code Generation Plan — CMS-U5 contact-mail (mail + retry) + +Phase 2, on the rebased branch (base `origin/master` `e671078`). Inputs: contract § 4 (store first, mail after commit, no personal data in logs, From = fixed site sender, Reply-To = visitor), requirements FR-D, SLS decision "new MailKind, do not change existing mail code", CMS-U3/U4 seams (`IContactMailSender`, `ContactMessage.MailStatus/MailAttempts/MailError/NextMailAttemptAt`, resend endpoint). Nothing is deployed; `Contact:Enabled` stays off. + +## Findings on the merged master (Core/Email) +- `IEmailSender.SendAsync(OutgoingMail)` returns a `MailSendResult(Sent, ErrorCode)`; never throws. `IMailAvailability.IsEnabled` is the single answer to "can this host send mail" (SMTP host set and configuration valid). `ISiteSettingsService.GetEffectiveSenderAsync` gives the effective From address/name (already checked against `Email:AllowedFromAddresses`). `ILanguageResolver` + `IMailTemplateRenderer` render subject/HTML/text from a static catalog per `MailKind` (nl/en), with dark-mode classes (`DarkPage`/`DarkCard`). +- The renderer's layout has a heading, a greeting, one intro paragraph, an optional button and a note. A contact mail also needs a block with the visitor's name, e-mail address, subject and message, and the mail needs a `Reply-To`. `OutgoingMail` has no reply-to member and `MailModel` has no list of details. +- `SmtpEmailSender` already classifies failures into short codes (`auth_failed`, `rejected_recipient`, `timeout_*`, ...); those codes are what `ContactMessage.MailError` stores. + +## Decisions +1. **Additive changes in the shared mail code (needs ASF/SLS consent, nothing existing changes behaviour)**: `MailKind.ContactMessage` (+ nl/en catalog entry); `MailModel` gets an optional `IReadOnlyList? Details` (label/value pairs; values HTML-encoded, line breaks kept as `
` in HTML and plain lines in text, rendered inside the existing card with the existing muted/dark classes so the dark-mode contrast is kept); `OutgoingMail` gets optional `ReplyToAddress`/`ReplyToName`, applied by `SmtpEmailSender` (control characters stripped, address validated with `EmailAddressRules`). No other change to those files. +2. **The visitor never waits for SMTP.** The submit request no longer sends mail inline (U3 did a no-op call there). It stores the message with `MailStatus=Pending` and `NextMailAttemptAt=now` and wakes the sender in-process (a `Channel` signal); the mail goes out within seconds in the background. Resend (admin request) still sends inline, as U4 does. +3. **Retry job** `ContactMailService : BackgroundService` — wakes on the signal and every `Contact:Mail:SweepSeconds` (default 120). Selects rows with `Status != Spam`, `MailStatus in (Pending, Failed)`, `MailAttempts < MaxAttempts` and `NextMailAttemptAt <= now` (or null), oldest first, batches of 20. Each row is **claimed** first (`NextMailAttemptAt = now + 5 min`, saved) so two instances never mail the same message; then sent. Success: `Sent`, error cleared. Failure: `Failed`, `MailError` = the short code, `MailAttempts++`, `NextMailAttemptAt = now + backoff[attempts]` with backoff 5 min, 15 min, 1 h, 6 h, 24 h (configurable list); after `Contact:Mail:MaxAttempts` (default 6) it stays `Failed` until an administrator resends (resend ignores backoff and the maximum). +4. **When mail cannot be sent at all** (`IMailAvailability.IsEnabled` false or no valid `Contact:RecipientEmail`): rows stay `Pending`, no attempt is counted, nothing is retried in a loop; the admin detail shows why (`mailError` = `disabled` / `recipient_not_configured`). They are picked up automatically once mail is configured. +5. **Addresses**: recipient `Contact:RecipientEmail` is **environment only** for the Andrea site (no address in committed config); the SLP host may keep it in its own appsettings (SLS to confirm). From = `ISiteSettingsService.GetEffectiveSenderAsync` (allow-listed); Reply-To = visitor address and display name. Mail subject is fixed text from the catalog ("Nieuw bericht via {site}"); no visitor-supplied text goes into the subject or any header except Reply-To. +6. **Privacy**: no address, name or message in any log line, exception or Sentry event; only message id, attempt number and the short error code. `SmtpFailure.Describe` output stays out of the contact logs (it may quote reply text). +7. Admin API additive field: the message detail gets `nextMailAttemptAt` (nullable) so the UI can show "next attempt at ...". +8. The Andrea host gets the Contact module reference only when SLS/Bryan decide the ASF website uses the form (out of scope here); the module works there unchanged. + +## Steps +- [ ] **Step 1 — Shared mail code, additive**: `MailKind.ContactMessage`, catalog texts (nl/en), `MailModel.Details`, `OutgoingMail.ReplyTo*`, `SmtpEmailSender` reply-to; renderer tests (see below). Show the diff of the three shared files to SLS before moving on. +- [ ] **Step 2 — Contact mail sender**: `ContactMailSender : IContactMailSender` (replaces the no-op; renders, builds the Reply-To, calls `IEmailSender`, maps the `MailSendResult` to `Sent/Failed` + code; returns `Skipped` for "disabled"/"no recipient"). +- [ ] **Step 3 — Pipeline change**: `ContactSubmissionService` stops sending inline, sets `NextMailAttemptAt`, signals `IContactMailSignal`. +- [ ] **Step 4 — Retry/background service** `ContactMailService` (claim, backoff, max attempts, signal, disabled handling) and options `Contact:Mail:*` (`SweepSeconds`, `MaxAttempts`, `BackoffMinutes`), `Contact:RecipientEmail`. +- [ ] **Step 5 — Admin**: detail gets `nextMailAttemptAt`; resend uses the real sender; OpenAPI regenerated. +- [ ] **Step 6 — Tests**: renderer (every visitor value HTML-encoded, newline handling, subject contains no visitor text, nl/en, dark-mode classes present, text part); sender with a fake `IEmailSender` (To/From/Reply-To/subject, control characters in the display name never reach a header, result codes mapped, disabled and missing recipient give `Skipped`); retry service (only due rows, spam never, backoff schedule exactly as configured, max attempts, claim prevents a second sender, signal wakes it, disabled mail leaves rows untouched and uncounted, resend ignores backoff); submission service no longer calls the sender and signals; no personal data in any log (extends the existing log-capture tests); **pipeline** on the real host with a capturing `IEmailSender` registered in the test host: submit -> mail captured within seconds and row `sent`; failing sender -> `failed` + code + next attempt; resend `mailed:true`; mail disabled -> rows pending. +- [ ] **Step 7 — Verification (automatic)**: build; all test projects incl. pipeline tests on a temporary MariaDB (removed afterwards). Optionally one manual end-to-end against smtp4dev if it is available locally (not a gate). +- [ ] **Step 8 — Docs/commit**: summary (config keys, behaviour table, shared-file diff), update `phase-1-handoff.md` routes/keys; one commit; no push. + +## Explicitly NOT touched +Existing mail kinds and their texts/behaviour, identity mail flow, `IMailAvailability`, site settings, SMTP credentials handling, the public routes' contract (still `202` immediately), the availability gate. + +## Risks / questions for approval +1. OK to make the three **additive** changes in shared mail code (`MailTypes.cs`, `MailTemplateRenderer.cs`, `SmtpEmailSender.cs`)? Alternative without touching them: a plain-text-only contact mail built in the Contact module with no Reply-To header (worse: no one can reply by pressing Reply). I recommend the additive change. +2. `Contact:RecipientEmail` for the SLP host: committed in its appsettings or environment only? +3. Backoff 5 min / 15 min / 1 h / 6 h / 24 h and 6 attempts: acceptable? 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 new file mode 100644 index 0000000..6777e5b --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md @@ -0,0 +1,33 @@ +# Code Generation Plan — CMS-U6 admin-ui-berichten + +Phase 2, frontend only (`frontend/src/features/contact`, `router.tsx`, `Sidebar.tsx`, locales). Backend routes exist (CMS-U4); the JSON shapes are in `construction/phase-1-handoff.md` and `openapi/slpsoftware.v1.json`. Decisions: D1 (admin view in scope, full version), Bryan: the form switch must be visible and switchable in the "Berichten" screen (spam attack, maintenance). Areas the ASF session touched in the frontend (auth/refresh, users, theme assets) are not changed; Sidebar/router get one added entry each. + +## Findings on the merged master +- Sidebar items are declared in `NAV_ITEMS` with `roles` and `requiredModule`; routes use `RoleGuard` + `ModuleGuard`. `useSystemCapabilities` lists loaded modules (cached for the session) and `emailEnabled`. +- A loaded `Contact` module does **not** mean the API is usable: while the host switch is off every management route answers 404 with an empty body. The UI therefore treats `404` on `GET /contact-settings` as "not available on this host". +- Offerings (CMS-U0/U1b) set the pattern: feature folder with `services/`, `components/`, `pages/`, `mocks/`, msw handlers, `['feature','list']` query keys, nl/en translations, Vitest + Testing Library. + +## Behaviour +1. **Navigation**: menu entry "Berichten" (icon: mail) for Owner and Administrator, shown only when capabilities list `Contact` **and** `GET /contact-settings` did not answer 404 (loaded once per session, cached). Route `/messages`, guarded by role and the same availability check; a direct visit while unavailable shows the existing "not found" page. +2. **Form switch card** at the top: "Contactformulier op de website — Aan/Uit" with a clear state text, one toggle button, an explanation line ("Als het formulier uit staat ziet de bezoeker alleen je e-mailadres") and, when `hostEnabled` is false, no toggle but the host-level explanation (cannot occur while the screen is reachable; handled defensively). Switching uses `PUT /contact-settings`; success toast, error banner with the Dutch generic/network messages; the state comes from the server response. **First-time hint**: the switch is off by default, so a short note tells Bryan that the form is closed until he switches it on. +3. **List**: filter chips "Inbox" (default: new+read+archived), "Nieuw", "Gelezen", "Gearchiveerd", "Spam" (each calls `GET /contact-messages?status=` — "Inbox" sends no status); the chip "Nieuw" shows `unreadCount`; paging 25 per page with previous/next and "x–y van z"; newest first; columns: received (locale date and time), name, e-mail, subject (the opaque site value, shown as is), status badge, mail icon (sent / pending / failed / n.v.t.). Empty states per filter. Spam rows are visually separate (only visible under "Spam"). +4. **Detail** (dialog, not a new page): full message with preserved line breaks, e-mail as `mailto:` link, received time, status select (Nieuw/Gelezen/Gearchiveerd → `PATCH`), mail status with attempts, error code (translated: disabled, not configured, auth, rejected, timeout...), next attempt time, retention date. Buttons: **Verwijderen** (confirm dialog, `DELETE`), **Opnieuw mailen** (`POST .../resend`; disabled with hint when `emailEnabled` is false; shows "Verstuurd" when `mailed:true`, "Niet verstuurd (mail staat uit)" when `mailed:false`; `409` for spam → "Markeer het bericht eerst als geen spam."; `429` → "Probeer het over {n} seconden opnieuw." from `Retry-After`), **Geen spam** on spam rows (`PATCH status=read`, then it moves to the Inbox). +5. **Opening an unread message marks it as read** (`PATCH read`), so the counter drops. (Decision to confirm.) +6. Cache: keys `['contact','messages',filter,page]` and `['contact','settings']`; mutations invalidate messages (and the counter); the switch updates the settings cache from the response. +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. + +## 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). + +## Questions for approval +1. Auto-mark as read when a message is opened: OK? +2. Sidebar badge with the unread count (extra request per page load for admins): wanted, or only the chip counter? (I propose chip counter only.) +3. Keep the filter as chips (above) or a select? (Chips proposed.) diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md new file mode 100644 index 0000000..ffe8669 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md @@ -0,0 +1,31 @@ +# Code Generation Plan — CMS-U7 availability-restful-status + +Phase 2, on the rebased branch. Decision (Bryan via SLS): no `/admin` segment in API routes; `POST /api/v1/Availability/admin/status` becomes `PUT /api/v1/Availability/status` (AdminOnly), same resource as the public `GET .../status`. The last open admin-segment route (checked in CMS-U0: it was the only one left). + +## Findings (merged master, all callers checked) +- Backend: `AvailabilityController` — `[HttpGet("status")] [AllowAnonymous]` and `[HttpPost("admin/status")] [Authorize(Policy="AdminOnly")]` with body `UpdateStatusRequest { NewStatus, Reason }`; answers `200` (empty), `400` (unsupported service), `409` ProblemDetails when the status is master-controlled. +- **Callers of the old route** (repository-wide search for `admin/status`, code, docs, CI, configs): only the admin frontend — `frontend/src/features/availability/services/useAvailability.ts` (mutation), `frontend/src/features/availability/mocks/handlers.ts`, and two msw handlers in `frontend/src/features/settings/pages/SettingsPage.test.tsx`. No server-side caller: the master pushes status to slaves with `POST /Master/status`, slaves read `GET /SlaveStatus`, instances poll the master — none of them uses `Availability/admin/status`. No proxy (nginx/IIS), deploy script, workflow or README references the old route (the README mentions only `GET .../status`). Historic `aidlc-docs` entries are history and stay as they are. +- **Gate**: `AvailabilityMiddleware` lets `/api/v1/Availability/status` through for **every method** (path-prefix bypass). After the change that would also exempt `PUT`, an admin route, from the gate for callers without a token (they would get `401` instead of `503`) — harmless in effect but contrary to "admin routes are never exempted". The bypass must therefore apply to `GET` (and `HEAD`) only. +- The frontend `Settings` page changes the status; `useAvailabilityStatus` (GET) is used on login, sidebar, dashboard. + +## Behaviour +1. `PUT /api/v1/Availability/status`, body `{ "newStatus": "Available"|"Maintenance"|"NotAvailable", "reason": string|null }` (unchanged), AdminOnly. Success: `200` with the **same JSON as `GET /Availability/status`** (the updated resource), so the UI can refresh its cache from the response. `409` problem+json when the status is master-controlled (unchanged); `400` for an invalid `newStatus` (framework validation); `401`/`403` as for all admin routes. +2. The old route `POST /Availability/admin/status` is **removed**, no alias: API and admin app are deployed together (decision of Bryan for the other routes too). Consequence to accept: during a deploy window an old browser bundle calling the old route gets `404`; the next page load fixes it. +3. `AvailabilityMiddleware`: the `Availability/status` bypass is limited to `GET`/`HEAD`; every other method follows the normal gate (a verified Owner/Administrator passes, expired token = `401`, others `503`). Minimal change in that file (ASF-owned file, small diff). +4. Frontend: `useUpdateAvailability` uses `PUT` and updates the cached status from the response; mocks and the two Settings tests change to `PUT`. + +## Steps +- [ ] **Step 1 — Controller**: `[HttpPut("status")]` replaces `admin/status`; returns the updated status object (shared builder with GET); remove the old route. +- [ ] **Step 2 — Middleware**: method-aware bypass for `Availability/status` (small, isolated diff); comment explains why. +- [ ] **Step 3 — Frontend**: `useAvailability.ts` mutation (PUT + cache update), `availability/mocks/handlers.ts`, `SettingsPage.test.tsx` (2 handlers); no other change. +- [ ] **Step 4 — Docs/contract**: regenerate `openapi/slpsoftware.v1.json`; update `phase-1-handoff.md`; README mention only if it names the route (it does not). +- [ ] **Step 5 — Tests**: controller (PUT 200 body equals GET shape, 409 master-controlled, 400 invalid status, GET unchanged and anonymous); route-table test: the only anonymous action on the controller is `GetStatus`, `UpdateStatus` is `AdminOnly`, no route contains `admin`, old route absent; middleware: `PUT /api/v1/Availability/status` without token is blocked by the gate while the CMS is off (not bypassed), `GET` still open, a verified administrator can `PUT` while the CMS is disabled (existing guarantee), expired token on PUT = `401`; pipeline on the real host: login as administrator, `PUT` Maintenance → `GET` shows it, visitors get `503` on a gated route, `PUT` back to Available; old `POST admin/status` = `404`; frontend: Settings page test uses PUT and shows the new status. +- [ ] **Step 6 — Verification (automatic)**: build; all test projects incl. pipeline tests (temporary MariaDB, removed afterwards); `pnpm lint`, `npx tsc -b`, `pnpm test`; real output reported. +- [ ] **Step 7 — Commit**: one commit; no push. + +## Explicitly NOT touched +Master/slave endpoints (`Master/*`, `SlaveStatus`, `CmsInstances/{id}/status`), the gate logic for any other route, `GET /Availability/status` behaviour, polling/circuit-breaker code. + +## Risk / notes +- **Order of deploy** with the SLP production release: this unit changes an API route and the admin app together; it must go out as one release (no alias). Do not deploy only one half. +- `CmsInstances/{id}/status` (`PUT`, master-side, per instance) is unrelated and stays.