Contactbeheer: berichten, schakelaar en tweelaagse poort voor het formulier

Beheerroutes zonder /admin-segment op contact-messages (lijst met spam apart en ongelezen-teller zonder spam, detail, status, verwijderen, opnieuw versturen met eigen limiet) en contact-settings voor de CMS-schakelaar, allemaal AdminOnly. Het formulier is alleen open als de hostvlag EN de CMS-schakelaar (standaard uit) aan staan; de hostvlag wordt eerst gecontroleerd zodat de database niet wordt aangeraakt. Bij uitgeschakelde host antwoorden de beheerroutes 404. OpenAPI-document bijgewerkt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:07:28 +01:00
co-authored by Claude Sonnet 5.5
parent f8d45eef54
commit e53b318c31
23 changed files with 2704 additions and 10 deletions
@@ -5,7 +5,7 @@
- **Feature Slug**: contact-forms-module
- **Project Type**: Brownfield
- **Start Date**: 2026-11-09
- **Current Stage**: CONSTRUCTION - CMS-U3b built and committed; CMS-U4 in progress
- **Current Stage**: CONSTRUCTION - CMS-U4 built and committed (awaiting review); next phase 2 after the ASF merge (CMS-U5, U6, U7)
- **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
@@ -119,3 +119,15 @@
**Context**: Code Generation Part 1.
---
## CMS-U3b and CMS-U4 built
**Timestamp**: 2026-11-09
**User Input**: "CMS-U3b en CMS-U4 goedgekeurd ... bestandsnaam per host ... hervat CMS-U4 na onderbreking" (via Redesign - SLS)
**AI Response**: U3b committed (0813656); U4 finished and committed after resuming: Scratch.cs removed, list query fixed, tests green.
**Context**: Construction phase 1 complete.
---
@@ -0,0 +1,73 @@
# CMS-U4 contact-admin-api: code summary
## IMPORTANT: the contact form is OFF by default, on two layers
1. **Host switch** `Contact:Enabled` (appsettings/environment of the host), default `false`. Release condition: only switch on after the per-client rate limiting from the ASF branch is on the base branch (see the CMS-U3 rebase checklist).
2. **CMS switch** (data, this unit): `PUT /api/v1/contact-settings` `{ "enabled": true }`, default **off** (no row = off). **Bryan has to switch the form on himself**, in the "Berichten" screen (CMS-U6) or through the API, before the public routes work. The form is open only when BOTH are on; otherwise `GET /contact-messages/token` and `POST /contact-messages` answer `404` with an empty body and the website shows its mailto fallback. A change of the CMS switch takes effect at once in the process that handled the change (other instances within 5 seconds).
## Routes (all `AdminOnly`: Owner or Administrator; anonymous = 401, role `User` = 403)
Same resource names as the public routes, no `/admin` segment. All sit behind the availability gate (no `[PublicSiteEndpoint]`): for visitors they answer 503 while the CMS is off/in maintenance; a verified administrator always gets through (by design, so the CMS can be switched back on).
**While the host switch is off every management route answers `404` with an empty body** (the contact tables do not exist then). The UI must read `404` on `GET /contact-settings` as "not available on this host" and hide the menu entry. The CMS switch never closes the management routes.
### JSON shapes (camelCase; enums are lower-camel strings)
`status`: `new | read | archived | spam | converted`; `mailStatus`: `pending | sent | failed | notApplicable`.
**`GET /api/v1/contact-messages?status=&page=1&pageSize=25`** -> `200`
```json
{
"items": [
{ "id": "3f2c...-guid", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen",
"email": "jan@example.nl", "subject": "website", "status": "new", "mailStatus": "pending" }
],
"page": 1, "pageSize": 25, "totalCount": 1, "unreadCount": 1
}
```
`status` (optional, one value `new|read|archived|spam`, case-insensitive): without it the list shows `new`, `read` and `archived` — **spam is never in the default list**; `status=spam` shows spam apart. Newest first. `page` >= 1, `pageSize` 1-100. `unreadCount` = number of `new` messages, **never counting spam, independent of the filter**. The list has no message text.
**`GET /api/v1/contact-messages/{id}`** -> `200`
```json
{
"id": "3f2c...", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen", "email": "jan@example.nl",
"subject": "website", "message": "Ik wil graag een offerte.", "status": "new", "mailStatus": "pending",
"mailAttempts": 0, "mailError": null, "retentionUntil": "2027-11-09T12:00:00+00:00"
}
```
`404` unknown id.
**`PATCH /api/v1/contact-messages/{id}`** body `{ "status": "new" | "read" | "archived" }` -> `200` with the detail shape above. Setting one of these on a spam message means "not spam": it then follows the normal retention (`retentionUntil` = now + `Contact:RetentionMonths`) and appears in the default list; its `mailStatus` stays `notApplicable` until resent. Anything else (`spam`, `converted`, unknown, missing, unreadable body) -> `400`. `404` unknown id.
**`DELETE /api/v1/contact-messages/{id}`** -> `204` (hard delete, erasure request); `404` unknown id.
**`POST /api/v1/contact-messages/{id}/resend`** (rate limit `contact-resend`, default 5 per 600 s) -> `200`
```json
{ "mailStatus": "pending", "mailAttempts": 0, "mailed": false }
```
`mailed=true` only when a mail was really sent. Until the mail unit (CMS-U5) there is no mail sender, so the answer is `mailed:false` and nothing changes. A spam message -> `409` (problem+json; "mark it as not spam first"). `404` unknown id. `429` with `Retry-After` after the limit.
**`GET /api/v1/contact-settings`** -> `200`
```json
{ "enabled": false, "hostEnabled": true }
```
`enabled` = the CMS switch (default `false`); `hostEnabled` = the host switch, read-only, so the UI can explain why the form is closed.
**`PUT /api/v1/contact-settings`** body `{ "enabled": true | false }` -> `200`, same shape as GET. Anything that is not a JSON boolean (missing, null, string, number, unreadable body) -> `400`.
### Error shape (`400`, `application/problem+json`)
```json
{ "type": "about:blank", "title": "Validation failed", "status": 400, "errors": { "status": ["invalid"] } }
```
Field names used: `status` (PATCH), `enabled` (PUT settings), `page`, `pageSize`, `status` (list query). Code is always `invalid`.
## Design notes
- Separate controllers for the management side (`ContactMessagesAdminController`, `ContactSettingsController`) next to the public `ContactMessagesController`; routes cannot clash (`{id:guid}`).
- Gate: `CompositeContactFormGate` = host flag first, then `CmsFlagContactFormGate` (singleton row in table `ContactSettings`, migration `AddContactSettings`, 5-second in-process cache invalidated on every change). The public `ContactRouteFilter` was not touched. With the host flag off the database is not touched at all.
- Statuses and mail statuses are stored as strings; the list uses one flag per status in its query because a parameterized collection loses the value-converter mapping in the SQL translation (found by the pipeline test).
- Nothing personal is logged by the admin services (ids and outcomes only; tested).
- Management routes appear in `openapi/slpsoftware.v1.json` (regenerated).
## Verification (real output)
Build 0 errors. Contact.Tests **223 passed** (unit + pipeline), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4, against a temporary MariaDB (removed afterwards). Explicit tests requested by SLS:
- Route table: exactly the seven management routes exist; every one is under class-level `AdminOnly`, none is `[AllowAnonymous]`, none is `[PublicSiteEndpoint]`, no route contains `admin`; the only `[PublicSiteEndpoint]` actions in the whole module are `GetToken` and `Submit`; the Availability route-table test (everything except `GetOfferings`, `GetToken`, `Submit` is blocked by a closed gate) covers the new routes without change.
- `PUT /contact-settings` by a non-admin -> `403` and nothing changes; by a regular user also for every other management route; anonymous -> `401` on all of them.
- Invalid body (`"yes"`, `1`, `null`, `{}`, `not json`, empty) -> `400` with `errors.enabled=["invalid"]` (and only that field).
- Real host: switch default off and reported with `hostEnabled`; PUT opens/closes the public routes at once while the management routes keep working; the changing user is recorded; full message flow (list without spam, `status=spam`, detail, status change, spam refused for resend, un-spam, delete); bad list queries -> `400`; resend `429` with `Retry-After`; host switch off -> management routes `404` (empty), anonymous still `401`; CMS disabled (availability) -> visitors `503` on the management routes, an administrator still `200`.
@@ -29,12 +29,12 @@ The admin routes need the Contact tables, which exist only when the host switch
All new routes require `AdminOnly` (Owner/Administrator). They are **not** marked `[PublicSiteEndpoint]`, so the availability gate blocks them when the CMS is off or in maintenance (verified by the route-table test).
## Steps
- [ ] **Step 1 — Settings model + migration** `AddContactSettings` (generated; applied to a real MariaDB for verification).
- [ ] **Step 2 — Repositories/services**: list/detail/patch/delete/resend (`IContactMessageAdminService`), settings (`IContactSettingsService`), gates (`CmsFlagContactFormGate`, `CompositeContactFormGate`), cache with invalidation. Resend uses the existing `IContactMailSender` seam.
- [ ] **Step 3 — Controllers + filter + rate-limit policy `contact-resend`** (registered in `ContactModule`, config `RateLimiting:ContactResend`, default 5/600; same single partition function as the other contact policies, so the rebase checklist still has one line).
- [ ] **Step 4 — Tests**: services (default list excludes spam; each status filter; ordering and paging bounds; `unreadCount` ignores spam and filters; detail fields; patch transitions incl. un-spam extending retention; invalid statuses; delete; resend rules incl. spam -> 409 and `Skipped`/`Sent`/`Failed`; settings default false, PUT/GET round trip, cache invalidated on PUT); gates (host off -> closed without calling the database gate; host on + CMS off -> closed; both on -> open; unit test with substitutes proving short-circuit order); controllers (status codes, response shapes, lower-camel enum strings); **route-table test (explicit, as requested)**: every action of `ContactMessagesAdminController` is under class-level `AdminOnly`, none has `[AllowAnonymous]` or `[PublicSiteEndpoint]`, no route contains `admin`; the set of public contact actions stays exactly `{GetToken, Submit}` and `AllowedPublicActions` in the Availability route-table test is unchanged (the new routes are covered by its "everything else answers 503" check); pipeline tests on the real host and MariaDB: anonymous -> 401, authenticated without admin role -> 403 (minted JWT with the host's development JWT settings), administrator -> 200 flows (list/detail/patch/delete/resend), host switch off -> admin routes 404 empty, CMS switch off -> public routes 404 but admin routes still 200, switching it on through `PUT /contact-settings` makes the public routes work within the cache window, the CMS being disabled (availability) blocks admin routes with 503, `contact-resend` returns 429 with `Retry-After` after its limit, no personal data in any log entry written by the admin services.
- [ ] **Step 5 — Verification (automatic)**: build; all test projects; pipeline tests against a temporary MariaDB (removed afterwards); real output.
- [ ] **Step 6 — Docs/commit**: summary with the JSON shapes for the frontend handoff and the rebase notes (none new); one commit; no push.
- [x] **Step 1 — Settings model + migration** `AddContactSettings` (generated; applied to a real MariaDB for verification).
- [x] **Step 2 — Repositories/services**: list/detail/patch/delete/resend (`IContactMessageAdminService`), settings (`IContactSettingsService`), gates (`CmsFlagContactFormGate`, `CompositeContactFormGate`), cache with invalidation. Resend uses the existing `IContactMailSender` seam.
- [x] **Step 3 — Controllers + filter + rate-limit policy `contact-resend`** (registered in `ContactModule`, config `RateLimiting:ContactResend`, default 5/600; same single partition function as the other contact policies, so the rebase checklist still has one line).
- [x] **Step 4 — Tests**: services (default list excludes spam; each status filter; ordering and paging bounds; `unreadCount` ignores spam and filters; detail fields; patch transitions incl. un-spam extending retention; invalid statuses; delete; resend rules incl. spam -> 409 and `Skipped`/`Sent`/`Failed`; settings default false, PUT/GET round trip, cache invalidated on PUT); gates (host off -> closed without calling the database gate; host on + CMS off -> closed; both on -> open; unit test with substitutes proving short-circuit order); controllers (status codes, response shapes, lower-camel enum strings); **route-table test (explicit, as requested)**: every action of `ContactMessagesAdminController` is under class-level `AdminOnly`, none has `[AllowAnonymous]` or `[PublicSiteEndpoint]`, no route contains `admin`; the set of public contact actions stays exactly `{GetToken, Submit}` and `AllowedPublicActions` in the Availability route-table test is unchanged (the new routes are covered by its "everything else answers 503" check); pipeline tests on the real host and MariaDB: anonymous -> 401, authenticated without admin role -> 403 (minted JWT with the host's development JWT settings), administrator -> 200 flows (list/detail/patch/delete/resend), host switch off -> admin routes 404 empty, CMS switch off -> public routes 404 but admin routes still 200, switching it on through `PUT /contact-settings` makes the public routes work within the cache window, the CMS being disabled (availability) blocks admin routes with 503, `contact-resend` returns 429 with `Retry-After` after its limit, no personal data in any log entry written by the admin services.
- [x] **Step 5 — Verification (automatic)**: build; all test projects; pipeline tests against a temporary MariaDB (removed afterwards); real output.
- [x] **Step 6 — Docs/commit**: summary with the JSON shapes for the frontend handoff and the rebase notes (none new); one commit; no push.
## Explicitly NOT touched
`ContactRouteFilter` (the public filter), the public controller, the public validation/submission logic, Core/Availability, Email, Identity, the frontend.