Aanbod: RESTful routes zonder /admin, één OfferingDto en herordenen via PUT /offerings/order

Admin en bezoeker gebruiken dezelfde resource; alleen GET is anoniem, de rest vereist AdminOnly. OfferingAdminDto vervalt (displayOrder zit nu in OfferingDto), move-up/move-down zijn vervangen door de order-route die een onbekende of onvolledige lijst met 400 afwijst. De admin-frontend en alle tests zijn mee aangepast.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:06:08 +01:00
co-authored by Claude Sonnet 5.5
parent e6710781e5
commit bc763c8ef6
39 changed files with 968 additions and 395 deletions
+1
View File
@@ -16,3 +16,4 @@
| Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (wacht op ASF test deploy) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 |
| Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (wacht op deploy) | feature/identity-email-notifications | Availability (middleware) | 2026-11-09 |
| Bug | [setup-page-after-failed-status-read](bugs/setup-page-after-failed-status-read/bug-fix.md) | ✅ Complete (wacht op deploy) | feature/identity-email-notifications | Frontend (router guard, login), Identity (Setup limiter) | 2026-11-09 |
| Feature | Contact Forms Module (contact-forms-module) | 🔵 Inception (wacht op antwoorden) | feature/contact-forms-module | Modules (new Contact + Tests, Offerings category), Core (OnRejected, availability gate marker), Frontend (admin Berichten) | 2026-11-09 |
@@ -0,0 +1,54 @@
# AI-DLC State Tracking
## Project Information
- **Feature Name**: Contact Forms Module (contact messages API + admin, offerings category)
- **Feature Slug**: contact-forms-module
- **Project Type**: Brownfield
- **Start Date**: 2026-11-09
- **Current Stage**: CONSTRUCTION - CMS-U0 built and committed (awaiting review); next CMS-U1 v2
- **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
- **Existing Code**: Yes
- **Reverse Engineering Needed**: No full rerun (July 2026 artifacts exist in `_shared/`; targeted code review of the touched areas instead — see requirements)
- **Workspace Root**: K:\Development\Projects\SlpModularCms
## Code Location Rules
- **Application Code**: Workspace root `src/` (NEVER in aidlc-docs/)
- **Feature Documentation**: aidlc-docs/features/contact-forms-module/ only
- **Shared Artifacts**: aidlc-docs/_shared/
## Language Configuration
- **Documentation Language**: English
- **Conversation Language**: User Language (Dutch)
- **Note**: Inherited from the other features in this workspace.
## Source Of Truth / Coordination
- Input contract: `K:\Development\SlpSoftware\Projects\SlpSoftware\aidlc-docs\features\redesign-modern-timetravel\inception\application-design\contact-api-contract.md` (v0.3.1-draft, incl. § 10a and § 11)
- Also: that feature's `inception\requirements\requirements.md` (FR-7, FR-8, FR-13..FR-19, NFR-4, NFR-5) and `application-design\*`
- Coordinator/approver of stages: session "Redesign - SLS" (approves within Bryan's decisions, otherwise asks Bryan). Stage status is reported to it.
- Do not touch files/behaviour the session "AndreaSlopFotografie" is still working on (AvailabilityMiddleware, rate limiter, host config, ForwardedHeaders, ASF settings) without coordination.
- No push/merge/PR without explicit instruction. No ASF addresses in code or committed config (env-only). No PII in logs.
## Extension Configuration
| Extension | Enabled | Decided At |
|---|---|---|
| Security Baseline | Yes | Requirements Analysis |
| Property-Based Testing | Partial | Requirements Analysis |
## Stage Progress
### 🔵 INCEPTION PHASE
- [x] Workspace Detection (classification: Feature)
- [x] Reverse Engineering (skipped by decision D10: targeted review in requirements)
- [x] Requirements Analysis (awaiting approval)
- [x] Workflow Planning (approved)
- [x] Application Design - EXECUTE (minimal; awaiting approval)
- [x] Units Generation - EXECUTE (awaiting approval)
### 🟢 CONSTRUCTION PHASE
- [ ] Functional Design - EXECUTE (U3, U4, U5)
- [ ] NFR Requirements/Design - EXECUTE (U2, U3)
- [ ] Infrastructure Design - SKIP
- [ ] Code Generation - EXECUTE per unit (plan approval first)
- [ ] Build and Test - EXECUTE
### 🟡 OPERATIONS PHASE
- [ ] UNDECIDED (resolve at Build and Test)
@@ -0,0 +1,73 @@
# Audit Log — contact-forms-module
## Initial Request (bootstrap, English)
**Timestamp**: 2026-11-09T00:00:00Z
**User Input**: "Opdracht van Bryan voor jou als bouwer van de CMS/API-kant (SlpModularCms). [...] gebruik de aidlc-workflow (Feature-lane) voor deze bouw, in jouw repo, met eigen aidlc-docs. Neem als input: contract v0.3.1 [...]. Bouwvolgorde (§ 11): (a) category op Offerings, (b) OnRejected/Retry-After/ProblemDetails, (c) contactmodule, (d) mail + retry, (e) admin-API, (f) admin-UI. Per unit build+test. Nieuwe feature-branch vanaf master. [...] Begin NIET met Code Generation vóór je plan door mij is goedgekeurd. [...] Niet doen: niets pushen/mergen/PR'en naar master zonder expliciete opdracht; geen ASF-adressen in code of committed config (env-only); geen PII in logs. Terugmelden: na elke aidlc-stage een korte status aan 'Redesign - SLS'." (relayed by cross-session message from session "Redesign - SLS")
**AI Response**: Confirmed; feature slug `contact-forms-module`; Feature lane; Inception only until the plan is approved.
**Context**: Workspace Detection — brownfield, classified Feature.
---
## Requirements Answers
**Timestamp**: 2026-11-09
**User Input**: "Antwoorden op requirement-verification-questions.md: 1 A, 2 B, 3 C, 4 A, 5 A, 6 A, 7 A, 8 A ... Schrijf de antwoorden zelf in het bestand en ga door met Requirements." (via Redesign - SLS)
**AI Response**: Answers recorded; requirements.md written with targeted review findings.
**Context**: Requirements Analysis, awaiting approval by Redesign - SLS.
---
## Workflow Planning
**Timestamp**: 2026-11-09
**User Input**: "Requirements goedgekeurd ... R1 beslist: bouw (a),(b),(c),(e) op master-basis, mail achter IContactMailSender; (d),(f) na merge en rebase. Doe nu GEEN rebase. Ga door met Workflow Planning en stuur me het execution plan ter goedkeuring. Nog geen Code Generation." (via Redesign - SLS)
**AI Response**: execution-plan.md written (6 units, phase split at the ASF merge).
**Context**: Workflow Planning, awaiting approval.
---
## Application Design and Units Generation
**Timestamp**: 2026-11-09
**User Input**: "Workflow Planning goedgekeurd ... Application Design (minimaal) en Units Generation mag je samen in een bericht sturen" (via Redesign - SLS)
**AI Response**: application-design.md and unit-of-work.md written; one deviation flagged (admin route shape) and one correction (Data Protection already host-level).
**Context**: awaiting approval.
---
## CMS-U1 Code Generation plan
**Timestamp**: 2026-11-09
**User Input**: "Application Design en Units Generation goedgekeurd ... stuur je Code Generation-plan voor CMS-U1 (category) ter goedkeuring." (via Redesign - SLS)
**AI Response**: plan written at construction/plans/cms-u1-offerings-category-code-generation-plan.md; approval requested.
**Context**: Code Generation Part 1.
---
## Plan revisions (U0, U1 v2)
**Timestamp**: 2026-11-09
**User Input**: "Beslissing van Bryan: de bestaande routes met een /admin-segment worden NU ook RESTful ... Nieuwe unit CMS-U0 ... Wijziging van Bryan op category: categorieen zijn data in het CMS ... Stuur me een samengevoegd plan."
**AI Response**: U1 v1 build stashed (not committed); U0 plan written; U1 plan rewritten (v2); order revised.
**Context**: awaiting approval.
---
@@ -0,0 +1,17 @@
# CMS-U0 offerings-restful-routes: code summary
## Routes (all under /api/v1/offerings)
GET (anonymous, rate limit offerings-public), POST (201 + Location), PUT {id:guid}, DELETE {id:guid}, PUT order {orderedIds}. All except GET are AdminOnly. No /admin segment; move-up/move-down removed. Order route returns 400 (ProblemDetails) unless the list holds every existing offering exactly once.
## DTO (decision A)
One OfferingDto for everybody, now including displayOrder; OfferingAdminDto removed. Handoff for the SLP site: displayOrder is an additive field on the public response and is ignored by the site (as is categoryId later); array order is still the display order.
## Backend files
Modules.Offerings: OfferingsController, IOfferingsService/OfferingsService (GetOfferingsAsync, validated ReorderAsync), OfferingOrderInvalidException, OfferingDto, repository (GetPrevious/GetNext removed).
Tests: route-table test (only GET anonymous, class AdminOnly, no admin segment, exact route set), 201+Location, order 400 (controller and service: unknown, incomplete, duplicate ids), displayOrder in DTO.
## Frontend (frontend/src/features/offerings)
Services use the new URLs; OfferingAdminDto renamed OfferingDto; useMoveOffering computes the new order from the cached list and calls PUT /offerings/order; msw handlers and tests updated, plus a test that move-down sends the full new order.
## Verification (real output)
dotnet build SlpModularCms.sln: 0 errors. Offerings.Tests 52 passed; Core.Tests 196 passed; Availability.Tests 82 passed; Identity.Tests 37 passed; Master.Tests 57 passed; Api.Tests 4 passed (with a local MariaDB container; without a database 4 fail with connection refused, also on clean master d9cc539). Frontend: vitest 41 files / 260 tests passed; eslint clean; tsc -b clean. prettier --check reports pre-existing style warnings on untouched files (not addressed).
@@ -0,0 +1,46 @@
# Code Generation Plan — CMS-U0 offerings-restful-routes
Decision (Bryan via Redesign - SLS): no `/admin` segment in API routes; admin uses the same resource with the same verbs, access via authorization (`AdminOnly`), public endpoints via `[PublicSiteEndpoint]` (CMS-U2). Applies now to Offerings, in this feature, before the category units. API and admin frontend are deployed together, so **no old routes are kept**.
## Unit context
- **Phase 1**, base master `d9cc539`, first unit. No data model change, no migration.
- **Touches**: `Modules.Offerings` (controller, service, DTOs, tests) and `frontend/src/features/offerings` (api calls, mocks, tests). Does **not** touch Core, Availability, Identity, ASF-owned areas (auth/refresh, users, theme assets).
## Route mapping
| Today | New | Auth |
|---|---|---|
| `GET /offerings` (public DTO) | `GET /offerings` (single DTO, see below) | anonymous (rate limit `offerings-public` unchanged; `[PublicSiteEndpoint]` added in CMS-U2) |
| `GET /offerings/admin` | removed (same `GET /offerings`) | |
| `POST /offerings/admin` | `POST /offerings` | AdminOnly, 201 + `Location: /api/v1/offerings/{id}` |
| `PUT /offerings/admin/{id}` | `PUT /offerings/{id:guid}` | AdminOnly |
| `DELETE /offerings/admin/{id}` | `DELETE /offerings/{id:guid}` | AdminOnly (soft delete unchanged) |
| `PUT /offerings/admin/reorder` | `PUT /offerings/order` body `{ "orderedIds": [...] }` | AdminOnly (collection action, `order` cannot clash with `{id:guid}`) |
| `POST .../{id}/move-up`, `.../move-down` | removed | UI computes the new order and calls `PUT /offerings/order` |
`PATCH` is not introduced (no partial-update use case); `PUT` keeps its current full-replace semantics.
## Design question: public vs admin DTO on one URL
Today the admin DTO differs from the public DTO by exactly one field: `displayOrder`.
- **Recommended (A)**: one URL, **one DTO for everybody**, `OfferingDto` gains `displayOrder` (additive, harmless to the SLS frontend which already relies on array order). No auth-dependent response => no `Vary: Authorization`, no cache split, a single OpenAPI schema, `OfferingAdminDto` is deleted.
- Alternative (B): auth-dependent DTO on the same URL: needs `Vary: Authorization`/no shared caching, an OpenAPI `oneOf`, and hides nothing sensitive. Alternative (C): `?view=admin` query switch: not RESTful-pure, adds a parameter for one integer.
- Other side effects of (A): the `offerings-public` limiter (120/min) now also covers admin list calls (fine).
Needs your OK; default is A.
## Steps
- [x] **Step 1 — DTO**: `OfferingDto` gets `int DisplayOrder` (appended); delete `OfferingAdminDto`; service `GetPublicOfferingsAsync`/`GetAllForAdminAsync` collapse into `GetOfferingsAsync`.
- [x] **Step 2 — Controller routes**: rewrite `OfferingsController` per the table; class stays `[Authorize(Policy = "AdminOnly")]` with `[AllowAnonymous]` only on `GET`; `Create` returns `Created("/api/v1/offerings/{id}", dto)`; remove `MoveUp`/`MoveDown` actions and `IOfferingsService.MoveUpAsync/MoveDownAsync` (+ repository `GetPreviousAsync/GetNextAsync` if unused elsewhere); reorder route `order`.
- [x] **Step 3 — Backend tests**: update `OfferingsControllerTests`, `OfferingsServiceTests`, repository tests (removed methods); add a route-table test (reflection over `OfferingsController` action routes + auth attributes: only `GET` is anonymous, all other actions inherit `AdminOnly`, no route contains `admin`).
- [x] **Step 4 — Frontend**: change URLs in `useOfferings`, `useCreateOffering`, `useUpdateOffering`, `useDeleteOffering`, `useReorderOfferings`; `useMoveOffering` computes the new id order client-side and calls `PUT /offerings/order` (keeps the UI buttons); `types.ts`: `OfferingAdminDto` becomes `OfferingDto` incl. `displayOrder` (or alias); update `mocks/handlers.ts` and tests (`OfferingsListPage.test.tsx`, `OfferingFormPage.test.tsx`, any others that assert URLs).
- [x] **Step 5 — Build + test (automatic)**: `dotnet build` solution; `dotnet test` Offerings.Tests (and Core.Tests/Availability.Tests as regression); `Api.Tests` need a local MySQL (they fail here with "connection refused" independent of this change; will be reported as such); frontend: lint + type-check + unit tests (`npm`/`pnpm` scripts as in `frontend/package.json`). Report real output.
- [x] **Step 6 — Docs**: summary in `construction/cms-u0-offerings-restful-routes/code/summary.md`, incl. the handoff note for the SLS site: `GET /api/v1/offerings` unchanged except the additive `displayOrder`.
- [x] **Step 7 — Commit** (one commit, Dutch message, Co-Authored-By line). No push.
## Explicitly NOT touched
Core, Availability (incl. `POST admin/status`, see below), Identity, Master, host config, `[PublicSiteEndpoint]` (CMS-U2), OpenAPI export (CMS-U3), category work (CMS-U1), ASF-owned frontend areas.
## Findings for other controllers (report only)
- Only `AvailabilityController` has another `admin` segment: `POST /availability/admin/status`. Per your instruction it becomes `PUT /availability/status` (AdminOnly; `GET /availability/status` stays public) **in Phase 2, after the ASF merge**, checking callers: Master/SlaveStatus, poll client, frontend.
- No other controller has an `admin` segment. Several are verb-style RPC routes (`Auth/login`, `Auth/revoke`, `Master/register`, `Master/status` POST, `CmsInstance/{id}/status` PUT) — not changed; flagged for your later RESTful review.
## Traceability
Bryan's route decision (SLS message), contract § 6/§ 7 (to be aligned by SLS); Security: authorization unchanged in effect (only `GET` anonymous), covered by the route-table test.
@@ -0,0 +1,42 @@
# Code Generation Plan — CMS-U1 offerings-category (REVISED v2: categories are CMS data)
Supersedes v1 (appsettings list, `OfferingsOptions`, `offerings/admin/categories`). Decision (Bryan via Redesign - SLS): categories are data managed in the CMS as part of Offerings (sub-section/dialog, not a new page); Bryan creates "Websites" and "Onderhoud" himself — **nothing is seeded in code**. Contract § 7 updated by SLS. Builds on CMS-U0 (RESTful routes, single `OfferingDto`).
## What v1 had already been done (now stashed, not committed)
Built and green (74 Offerings tests) but based on `offerings/admin` routes and the appsettings list: `Offering.Category` string column + migration `AddOfferingCategory`, `OfferingsOptions`, `Offerings:Categories` in `Api.SlpSoftware/appsettings.json`, service validation + legacy-value rule, tests. Parked in `git stash` ("cms-u1-v1-…"). Reused: test scaffolding patterns only. Dropped: `OfferingsOptions`, appsettings key, legacy-value rule, string column and its migration.
## Data model
- `OfferingCategory`: `Id` (Guid), `Name` (varchar 100, required, trimmed), `SortOrder` (int), `CreatedAt`, `UpdatedAt`. Unique index on `Name` (MySQL default collation is case-insensitive; the service also checks case-insensitively because InMemory tests do not enforce the index).
- `Offering.CategoryId` (Guid?, nullable) FK -> `OfferingCategory`, `DeleteBehavior.Restrict`.
- Migration `AddOfferingCategories` (Offerings context): new table + nullable column + FK + index. Additive; `Down` drops them. Generated with `dotnet ef` (the tool worked in v1: 9.0.19 produced a clean EF 10 migration).
## Routes (`/api/v1/offerings/categories`, all AdminOnly, no `/admin`)
| Route | Behaviour |
|---|---|
| `GET /offerings/categories` | list ordered by `SortOrder`, `Name`; each item `{ id, name, sortOrder, offeringCount }` (count of non-deleted offerings, for the UI) |
| `POST /offerings/categories` | body `{ name }`; 201 + Location; duplicate name (case-insensitive) => 409 ProblemDetails; blank/too long => 400 |
| `PUT /offerings/categories/{id:guid}` | rename (`{ name }`); duplicate => 409; unknown id => 404; offerings follow automatically (FK) |
| `DELETE /offerings/categories/{id:guid}` | 409 ProblemDetails while non-deleted offerings use it ("move the offerings first"); otherwise deleted (soft-deleted offerings that still point to it get `CategoryId = null` in the same transaction); unknown id => 404 |
Route `categories` cannot clash with `{id:guid}` on `/offerings`. Ordering/reordering of categories: **not in this unit** (order = creation order via `SortOrder`; reorder endpoint can be added cheaply later: `PUT /offerings/categories/order`).
## Offering changes
- `CreateOfferingRequest`/`UpdateOfferingRequest` gain `Guid? CategoryId`; if given it must exist => else `400` ValidationProblemDetails `errors.categoryId = ["invalid"]`; `null` clears the category.
- Single `OfferingDto` (from CMS-U0) gains `CategoryId` (Guid?, string in JSON like `Id`) and `Category` (name | null). Public JSON therefore carries `category` as the name or `null` (unchanged shape for the SLS frontend) plus the additive `categoryId`/`displayOrder`.
## Steps
- [ ] **Step 1 — Revert v1 leftovers**: confirm the working tree only contains CMS-U0 (stash holds v1); delete nothing committed.
- [ ] **Step 2 — Entities + DbContext**: `OfferingCategory`, `Offering.CategoryId` + navigation, mapping, unique index, FK Restrict; `Include` the category in `OfferingRepository` reads.
- [ ] **Step 3 — Repository**: `IOfferingCategoryRepository` (list with usage counts, get, add, remove, exists-by-name case-insensitive, clear category on soft-deleted offerings); transaction support as in `OfferingRepository`.
- [ ] **Step 4 — Services**: `IOfferingCategoriesService` (list/create/rename/delete with the rules above; exceptions `OfferingCategoryNameConflictException`, `OfferingCategoryInUseException`); `OfferingsService` validates `CategoryId` exists and maps `CategoryId`/`Category` into `OfferingDto`.
- [ ] **Step 5 — Controllers**: `OfferingCategoriesController` (route `offerings/categories`, class-level `AdminOnly`) with ProblemDetails mapping (409 conflict, 409 in-use, 404, 400); `OfferingsController` handles invalid `categoryId` as 400.
- [ ] **Step 6 — Migration** `AddOfferingCategories`.
- [ ] **Step 7 — Tests (Offerings.Tests)**: category service (create trims, duplicate case-insensitive => conflict, rename conflict, rename unknown, delete in use => in-use, delete unused ok, delete clears soft-deleted references, list with counts and order); offering service (unknown `categoryId` => invalid, null clears, DTO carries id+name, rename visible through DTO); controller mapping (201/404/409/400); repository (FK round trip, case-insensitive exists); route-table test from CMS-U0 extended (all `categories` actions AdminOnly, none anonymous).
- [ ] **Step 8 — Build + test (automatic)**: solution build; Offerings.Tests, Core.Tests, Availability.Tests; `Api.Tests` needs a local MySQL (fails here with "connection refused" regardless of the change). Report real output.
- [ ] **Step 9 — Docs/handoff**: summary + handoff note for the SLS frontend (public `category` = name|null; additive `categoryId`) and for CMS-U1b (route list above).
- [ ] **Step 10 — Commit** (one commit, no push).
## Explicitly NOT touched
Core, Availability, Identity, host config/appsettings (no `Offerings:Categories` anymore), the marker (CMS-U2), OpenAPI export (CMS-U3), frontend (CMS-U1b).
## CMS-U1b outline (own plan after U1 is done)
Categorieën sub-section/dialog inside the Offerings admin (list with offering counts, add, rename, delete with the 409 message), plus a select in `OfferingForm` (`categoryId`, "geen categorie" option); services/hooks/mocks/tests under `frontend/src/features/offerings` only; ASF-owned frontend areas untouched.
@@ -0,0 +1,65 @@
# Application Design (minimal) — contact-forms-module
Scope: component names, boundaries, configuration keys, and the few design points the contract leaves open. Behaviour and field-level detail stay in contract v0.3.1.
## 1. Repo findings that shape the design (master `d9cc539`)
- Modules are `IModule` classes discovered via the host's project references (`orchestrator.DiscoverModules()`); a host gets a module by a `ProjectReference` in its `.csproj`. Phase 1 registers Contact in `Api.SlpSoftware` only; `Api.AndreaSlopFotografie` does not exist on master and gets the reference after the ASF merge (Phase 2).
- **Data Protection is already host-level**: `AddCmsDataProtection()` (CmsHost) persists keys in the database (`ApplicationDbContext`) with a fixed application discriminator. Contact therefore does **not** own a key ring; it only asks `IDataProtectionProvider` for a protector with a per-site purpose string. (This replaces the plan wording "keyring in own DbContext".)
- Controller convention: `[Route("offerings")]` under the global `/api/v1` prefix, class-level `[Authorize(Policy = "AdminOnly")]`, public actions `[AllowAnonymous]` + `[EnableRateLimiting("<policy>")]`, admin actions under `offerings/admin`. Existing public limiter policy: `offerings-public`.
- `/System/capabilities` lists `ModuleOrchestrator.ModuleNames`: a module named `Contact` appears automatically.
- `AvailabilityMiddleware` is prefix-bypass based, with verified-admin-token bypass. Existing admin routes are **not** under a common `/api/v1/admin/` prefix (they are `.../admin` suffixes or controllers such as `Users`).
## 2. Deviation to confirm (admin route shape)
Contract § 6 writes `/api/v1/admin/contact-messages`. Repo convention is `contact-messages/admin...` (as `offerings/admin`). **Proposal**: follow the repo convention: `GET /api/v1/contact-messages/admin`, `GET .../admin/{id}`, `PATCH .../admin/{id}`, `DELETE .../admin/{id}`, `POST .../admin/{id}/resend`. The 503-regression test then iterates over all endpoints without `[PublicSiteEndpoint]` instead of relying on a prefix. Redesign - SLS to update the contract (or veto).
## 3. Components
| Component | Project | Responsibility |
|---|---|---|
| `PublicSiteEndpointAttribute` | Core (`Availability`) | marker, `AttributeTargets.Method`; read via endpoint metadata |
| Availability check | Modules.Availability `AvailabilityMiddleware` | minimal change: after the prefix bypass, `context.GetEndpoint()?.Metadata.GetMetadata<PublicSiteEndpointAttribute>()` != null => `next` (deny-by-default otherwise) |
| 429 handling | Core `AddCmsRateLimiting` `OnRejected` | set `Retry-After` (from `MetadataName.RetryAfter` when available, else window), write `application/problem+json`; keep the security-event call |
| Offering category | Modules.Offerings | `Offering.Category` (nullable, max 100), DTOs/requests, `ICategoryOptions` (reads `Offerings:Categories`), validation in service |
| `ContactModule` | Modules.Contact | `IModule` "Contact"; registers DbContext (MySQL, same pattern), services, hosted services; `Migrate()` in `UseModule` |
| `ContactDbContext` | Modules.Contact | `ContactMessages`, `IdempotencyRecords` |
| `ContactMessagesController` | Modules.Contact | public token + submit (`[PublicSiteEndpoint]`, `[AllowAnonymous]`, limiter policies); admin actions `AdminOnly` (U4) |
| `ContactSubmissionService` | Modules.Contact | validate, classify (genuine/spam), idempotency, store, trigger mail |
| `ContactValidator` | Modules.Contact | pure function: input => `{field: [codes]}`; shared rules (trim, length, regex, control chars) |
| `ContactTokenService` | Modules.Contact | issue/verify via `IDataProtector` (purpose `SlpModularCms.Contact.Token.{siteId}`), `ITimeProvider`; verify result: valid / tooYoung / expired-or-invalid |
| `ICaptchaVerifier` (+`NullCaptchaVerifier`, later Friendly Captcha impl) | Modules.Contact | fail-open on provider failure, log without PII |
| `IContactMailSender` (+`NoOpContactMailSender`) | Modules.Contact | seam for mail; real implementation in Phase 2 (CMS-U5) |
| `ContactRetentionService` | Modules.Contact | daily `BackgroundService`: delete rows past `retentionUntil` and idempotency records > 24 h |
| `ContactSiteOptions` | Modules.Contact | `Contact:*` binding (validated on start; recipient/sender not required until mail is wired) |
| Log scrubbing | Core Observability | extra rule in `SecurityEventProcessor`/Sentry `BeforeSend` for the contact routes |
## 4. Configuration keys
| Key | Default | Notes |
|---|---|---|
| `Offerings:Categories` | `[]` | per host; empty list => category must be null |
| `Contact:SiteId` | host name | derived from host config, never from the request; used in the token purpose and stored on rows |
| `Contact:MinSeconds` | 3 | |
| `Contact:TokenLifetimeMinutes` | 120 | |
| `Contact:RetentionMonths` | 12 | per row at insert |
| `Contact:SpamRetentionDays` | 30 | |
| `Contact:MaxSpamRowsPerDay` | 200 | cap per site per day, then 202 without storing |
| `Contact:MaxBodyBytes` | 16384 | |
| `Contact:HoneypotField` | `hpCheck` | |
| `Contact:RecipientEmail`, `Contact:SenderEmail` | none | env-only for ASF; not committed (Phase 2) |
| `Contact:Captcha:Enabled/Provider/SiteKey/Secret` | false | secret via env/secrets |
| `RateLimiting:ContactForm` | 5 / 600 s | per client IP |
| `RateLimiting:ContactToken` | 20 / 600 s | per client IP |
| `RateLimiting:ContactResend` | 5 / 600 s | admin resend |
## 5. Data
- `ContactMessage`: `Id` (Guid), `SiteId`, `ReceivedAt`, `Name`, `Email`, `Subject`, `Message`, `Status` (`New|Read|Archived|Spam|Converted`), `MailStatus` (`Pending|Sent|Failed|NotApplicable`), `MailError` (code only), `MailAttempts`, `NextMailAttemptAt`, `RetentionUntil`. Indexes: `(SiteId, Status, ReceivedAt)`, `RetentionUntil`. No IP.
- `IdempotencyRecord`: `Key` (Guid), `SiteId`, `CreatedAt`, `StatusCode`; unique index `(SiteId, Key)`. No request content.
- `Offering.Category`: `varchar(100)` NULL.
## 6. OpenAPI export
- Committed file `openapi/cms-api.v1.json` in the repo root. A test builds the document from the SlpSoftware host (`AddOpenApi`) and compares it to the file; set `UPDATE_OPENAPI=1` to rewrite it. Drift fails the build, so `cms-client` always generates from a current file.
- The contract's response components (`Validation`, `TooLarge`, `RateLimited`, `Problem`) are declared through an `IOpenApiDocumentTransformer` so the exported shape matches contract § 8.
## 7. Cross-cutting decisions
- Identical 202 for genuine and spam: same code path up to the store step; spam differs only by `Status=Spam` and `RetentionUntil=+30d`, and never triggers mail.
- Invalid/forged/other-site/expired token => `errors.token = ["expired"]`; too-young token => silent spam path.
- Logging: only status code, site id and outcome enum for these routes; request logging for them is disabled; a test asserts that a thrown exception's log entry holds no body or field value.
- Security Baseline is checked at each stage (anonymous endpoint, input limits, no oracle, secrets only via env, generic 5xx, headers).
@@ -0,0 +1,34 @@
# Units of Work — contact-forms-module
Naming: CMS-U1..CMS-U6 (the SLS frontend plan has its own U1..U5). One feature branch `feature/contact-forms-module`, one commit minimum per unit, sequential. Each unit: Code Generation plan => approval by Redesign - SLS => code + tests + automatic build/test => status.
| Unit | Name | Phase | Depends on | New/changed projects | Migration |
|---|---|---|---|---|---|
| CMS-U1 | offerings-category | 1 | none | Modules.Offerings (+Tests) | `AddOfferingCategory` (Offerings context) |
| CMS-U2 | gate-and-limiter | 1 | none (marks offerings GET from U1's controller) | Core, Modules.Availability (+Tests), Core.Tests/Api.Tests | none |
| CMS-U3 | contact-core | 1 | U2 | NEW Modules.Contact, NEW Modules.Contact.Tests, Api.SlpSoftware (reference), solution file | `InitialCreate` (Contact context) |
| CMS-U4 | contact-admin-api | 1 | U3 | Modules.Contact (+Tests) | none (maybe an index) |
| CMS-U5 | contact-mail | 2 | ASF merge + rebase; U3, U4 | Modules.Contact, Core/Email use (new `MailKind`), Api.AndreaSlopFotografie reference | `AddContactMailFields` only if not already in InitialCreate (preferred: fields exist from U3) |
| CMS-U6 | admin-ui | 2 | ASF merge + rebase; U4 | `frontend/` (new files + menu entry) | none |
## Per-unit boundaries (what is NOT touched)
- **U1**: no Core, no Availability, no Email; only Offerings files and its migration/tests.
- **U2**: only `AddCmsRateLimiting`/`OnRejected` in Core, the marker attribute file, and `AvailabilityMiddleware` (minimal diff); no policy numbers changed; no Email, Identity, host config.
- **U3**: no changes to existing modules except the `.csproj` reference in Api.SlpSoftware, the `.sln`, and appsettings sample keys; no Core/Email; no Identity.
- **U4**: only Modules.Contact.
- **U5/U6**: after merge; Email code of the ASF session is used, never edited (new `MailKind` only).
## Test projects
- `SlpModularCms.Modules.Contact.Tests` mirrors the module (xUnit as the other test projects). Solution layout: module under Application/Modules, tests under Tests/Modules (per CLAUDE.md).
- PBT (partial): validator and token round-trips, using the repo's available property-testing library if present, otherwise parameterised generators; decided in Functional Design of U3.
## Order and gates
U1 -> U2 -> U3 -> U4 (each approved before start). After Bryan merges the ASF branch: rebase, regenerate migrations only if snapshots conflict, then U5 -> U6.
## Revision 2026-11-09 (Bryan via Redesign - SLS)
- New **CMS-U0 offerings-restful-routes** (Phase 1, first): no `/admin` segments; plan in `construction/plans/cms-u0-...`.
- **CMS-U1 offerings-category** revised: categories are CMS data (table + FK + CRUD routes), no `Offerings:Categories` config, no seeding.
- New **CMS-U1b offerings-categories-ui**: categories sub-section + select in OfferingForm (after U1).
- Availability `POST admin/status` -> `PUT /availability/status`: Phase 2 (after the ASF merge), new unit **CMS-U7 availability-restful-status**.
- Admin routes of Contact follow the RESTful scheme (no `/admin`): `GET/PATCH/DELETE /contact-messages[/{id:guid}]`, `POST /contact-messages/{id:guid}/resend`. Application-design § 2 is superseded accordingly.
- Order: U0 -> U1 -> U1b -> U2 -> U3 -> U4 | merge | U5 -> U6 -> U7.
@@ -0,0 +1,137 @@
# Execution Plan — contact-forms-module
## Detailed Analysis Summary
### Transformation Scope
- **Transformation Type**: Multiple components (new module + targeted changes in existing ones). No infrastructure/deployment model change.
- **Primary Changes**: new `Modules.Contact` (+ Tests); `category` on `Modules.Offerings`; `OnRejected` and a public-route marker in Core/Availability; later mail integration (Core/Email) and admin UI (frontend).
- **Related Components**: Core (rate limiting, hosting, observability), Modules.Availability (middleware), Modules.Offerings, Api.SlpSoftware (+ Api.AndreaSlopFotografie after the ASF merge), frontend (admin).
### Change Impact Assessment
- **User-facing changes**: Yes: public contact endpoints (consumed by `cms-client`), admin "Berichten" screen (unit 6).
- **Structural changes**: Yes: one new module, one new marker attribute in Core.
- **Data model changes**: Yes: new tables (`ContactMessage`, idempotency record, DataProtection key ring), new `Offering.Category` column. All additive.
- **API changes**: Yes: new endpoints + `category` on offerings; 429 body/header change on existing rate-limited endpoints.
- **NFR impact**: Yes: security baseline (anonymous PII endpoint), privacy (retention, logging), reliability (mail retry).
### Component Relationships
```mermaid
flowchart LR
FE["cms-client (SLP site)"] --> API["Api.SlpSoftware / Api.AndreaSlopFotografie"]
API --> CONTACT["Modules.Contact (NEW)"]
API --> OFF["Modules.Offerings (+category)"]
API --> AVAIL["Modules.Availability (middleware)"]
CONTACT --> CORE["Core (marker, rate limiter, observability)"]
AVAIL --> CORE
CONTACT -. "after ASF merge" .-> MAIL["Core/Email (ASF branch)"]
ADMIN["frontend admin: Berichten"] -. "after ASF merge" .-> CONTACT
classDef new fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef changed fill:#f6e05e,stroke:#c05621,color:#000;
classDef ext fill:#bee3f8,stroke:#2b6cb0,color:#000;
classDef later fill:#e2e8f0,stroke:#4a5568,stroke-dasharray: 5 5,color:#000;
class CONTACT new;
class OFF,AVAIL,CORE,API changed;
class FE ext;
class MAIL,ADMIN later;
```
Text alternative: the Contact module (new, green) hangs off the API hosts and uses Core; Offerings, Availability, Core and the hosts change (yellow); mail and the admin UI (grey, dashed) wait for the ASF merge.
### Risk Assessment
- **Risk Level**: Medium (anonymous endpoint with PII; shared files with the ASF session).
- **Rollback Complexity**: Easy to Moderate (additive migrations; new module can be left unregistered per host).
- **Testing Complexity**: Moderate (gate regression, rate limiter behaviour, token/idempotency, background jobs).
## Workflow Visualization
```mermaid
flowchart TD
Start(["Request via Redesign - SLS"])
subgraph INCEPTION["🔵 INCEPTION"]
WD["Workspace Detection<br/><b>COMPLETED</b>"]
RE["Reverse Engineering<br/><b>SKIP (targeted review)</b>"]
RA["Requirements Analysis<br/><b>COMPLETED</b>"]
US["User Stories<br/><b>SKIP</b>"]
WP["Workflow Planning<br/><b>IN PROGRESS</b>"]
AD["Application Design<br/><b>EXECUTE (minimal)</b>"]
UG["Units Generation<br/><b>EXECUTE</b>"]
end
subgraph CONSTRUCTION["🟢 CONSTRUCTION (per unit)"]
FD["Functional Design<br/><b>EXECUTE (U3, U4, U5)</b>"]
NFR["NFR Requirements + Design<br/><b>EXECUTE (U2, U3)</b>"]
ID["Infrastructure Design<br/><b>SKIP (config noted in design)</b>"]
CG["Code Generation<br/><b>EXECUTE</b>"]
BT["Build and Test<br/><b>EXECUTE</b>"]
end
OPS["Operations<br/><b>UNDECIDED (at Build and Test)</b>"]
Start --> WD --> RA --> WP --> AD --> UG --> FD --> NFR --> CG --> BT --> OPS
style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style UG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style NFR fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style ID fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style OPS fill:#FFF59D,stroke:#F9A825,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000
linkStyle default stroke:#333,stroke-width:2px
```
Text alternative: Inception runs Application Design and Units Generation, then each unit goes through design (where needed), Code Generation and Build and Test; Operations is undecided.
## Phases to Execute
### 🔵 INCEPTION
- [x] Workspace Detection (COMPLETED)
- [x] Reverse Engineering (SKIPPED by D10: targeted review recorded in requirements)
- [x] Requirements Analysis (COMPLETED, approved by Redesign - SLS)
- [x] User Stories (SKIPPED: contract-driven backend work; acceptance criteria live in the contract and the SLS requirements FR-13..19)
- [ ] Workflow Planning (IN PROGRESS)
- [ ] Application Design - EXECUTE (minimal depth)
- **Rationale**: new module, new Core marker attribute; must fix component/service names, config keys (`Offerings:Categories`, `Contact:*`, `RateLimiting:ContactForm`), OpenAPI export path, DataProtection key-ring storage, purpose strings.
- [ ] Units Generation - EXECUTE
- **Rationale**: six units with an ordering constraint and a split at the ASF merge.
### 🟢 CONSTRUCTION
- [ ] Functional Design - EXECUTE for U3, U4, U5 (validation rules, state/status machine, idempotency, spam cap, retry/backoff); SKIP for U1, U2, U6 (covered by contract/design)
- [ ] NFR Requirements + NFR Design - EXECUTE for U2 and U3 (security baseline: PII logging, token oracle, size limits, rate limiting); SKIP for the others (covered by baseline checks in code generation)
- [ ] Infrastructure Design - SKIP (no new infrastructure; key-ring storage and config keys are recorded in Application Design)
- [ ] Code Generation - EXECUTE per unit (plan approved by Redesign - SLS before any code); automatic build+test per unit
- [ ] Build and Test - EXECUTE (after U1-U4, again after U5-U6)
### 🟡 OPERATIONS
- [ ] UNDECIDED: resolved at Build and Test (D7)
## Units (execution order)
Phase 1: now, on the master base. Phase 2: only after Bryan merges `feature/identity-email-notifications` and the branch is rebased (not before; no rebase now).
| Unit | Scope | Delivers | Tests | Depends on |
|---|---|---|---|---|
| **U1 offerings-category** (a) | `Category` on Offering entity, public + admin DTOs, create/update requests; validation against `Offerings:Categories` (per host appsettings); null/empty allowed | additive migration `AddOfferingCategory` in Offerings; config key documented; handoff note for the frontend (field name and semantics) | Offerings.Tests: mapping, validation (in list / not in list / null), repository; migration builds | none |
| **U2 gate-and-limiter** (b) | `OnRejected`: `429 application/problem+json` + `Retry-After` for all policies; `[PublicSiteEndpoint]` marker in Core; `AvailabilityMiddleware` lets marked endpoints through (deny-by-default); mark `GET /api/v1/offerings`. Minimal diffs in these two files (R3) | marker attribute, middleware check, updated 429 response, security-event kept | Core.Tests/Api.Tests: 429 body + header for existing policies (adjust existing tests); Availability.Tests: marked route open while disabled/maintenance/master-down; **every `/api/v1/admin/*` route still 503**; `/api/v1/Availability/status` open; ~6-10 existing tests touched | none (U1 for the offerings route mark) |
| **U3 contact-core** (c) | new `Modules.Contact` (+Tests): entities `ContactMessage`, `IdempotencyRecord`; DbContext + migration; token endpoint (DataProtection, per-site purpose, persistent key ring in DB); submit endpoint (validation codes, 413 ProblemDetails, `Idempotency-Key`, honeypot `hpCheck`, min-time, `ICaptchaVerifier` + Null, identical 202, spam stored with daily cap and 30-day retention, site id from config); `ContactForm` rate-limit policies; both routes `[PublicSiteEndpoint]`; `IContactMailSender` interface with no-op implementation (mail is wired in U5); retention `BackgroundService`; log/Sentry scrubbing for the routes | module registered in Api.SlpSoftware (Andrea host later), additive migration `InitialCreate`, config section `Contact:*`, exported OpenAPI document (path fixed in design) | Contact.Tests: validation rules incl. PBT (partial: round-trips, trim/length invariants), token sign/verify/expiry/foreign-site, idempotency replay, spam paths identical response, spam cap, retention job, no-PII-in-log test, endpoint tests via WebApplicationFactory | U2 |
| **U4 contact-admin-api** (e) | AdminOnly endpoints: list (paging, unread count, spam separate), detail, PATCH status (new/read/archived), DELETE (hard), `POST resend` (rate-limited; calls `IContactMailSender`, so a no-op until U5); capabilities entry is automatic from the module name | admin controller + DTOs, OpenAPI updated | Contact.Tests: authorization (non-admin 403/401), paging, counts exclude spam, status transitions, hard delete, resend rate-limit | U3 |
| **U5 contact-mail** (d) | PHASE 2. Implement `IContactMailSender` on `Core/Email` with a **new `MailKind`**, dark-mode contrast kept; From/Reply-To rules, header-injection and HTML-encoding protections; `mailStatus`/`mailAttempts`; `BackgroundService` sweeping `pending` (minutes) and retrying `failed` with backoff/max attempts; "no SMTP host = store only + admin notice" | mail path + retry job; Andrea host registration via env-only addresses | Contact.Tests: sender with fake `IEmailSender`, retry/backoff, header injection, encoding, failure never fails the request | merge of ASF branch + rebase; U3, U4 |
| **U6 admin-ui** (f) | PHASE 2. "Berichten" in `frontend/`: list+paging+unread count, detail, status, delete, mail status + resend; menu entry via capabilities; only new files + menu entry | UI + tests | frontend unit tests (Vitest as in repo) | merge of ASF branch + rebase; U4 |
## Migration Approach
- Contact and Offerings have their **own DbContext and migration history**, applied with `Database.Migrate()` at startup (D8). All migrations are additive (new tables, one nullable column).
- ASF changes live in `Core/Migrations` and the Identity/Availability contexts, so snapshot conflicts with U1/U3 are not expected. If the rebase still produces conflicts in any snapshot, delete and regenerate my own migration after the rebase (R2).
- DataProtection key ring: table owned by the Contact module's context (persistent per host; per-site purpose string).
## Branch and Process
- Worktree `..\SlpModularCms-contact-forms`, branch `feature/contact-forms-module` from master `d9cc539`. The main checkout is never switched.
- One commit per unit minimum; no push, merge or PR without explicit instruction. Per unit: Code Generation plan -> approval by Redesign - SLS -> code + automatic build+test -> status message.
- Stage status reports to Redesign - SLS after each stage; contract deviations reported immediately.
## Estimated Timeline
- **Total units**: 6 (4 now, 2 after the ASF merge). Rough effort: U1 small, U2 small-medium, U3 large, U4 medium, U5 medium, U6 medium. No calendar estimate (depends on approval turnaround and the ASF merge).
## Success Criteria
- **Primary Goal**: contract v0.3.1 implemented on the CMS side without breaking ASF-owned behaviour.
- **Key Deliverables**: category on offerings; public contact endpoints; admin API; mail + retry; admin UI; exported OpenAPI.
- **Quality Gates**: per-unit build+test green; Security Baseline checked per stage; no PII in logs (tested); `/api/v1/admin/*` stays gated (tested); no ASF addresses in committed config.
@@ -0,0 +1,77 @@
# Requirements Verification Questions — contact-forms-module
Input: contact-api-contract v0.3.1-draft (decisions by Bryan are not asked again). Only repo-specific or still-open points below. Answers may be given by "Redesign - SLS" (within Bryan's decisions) or by Bryan.
## Question 1: Security Extensions
Should security extension rules be enforced for this feature?
- A) Yes — enforce all SECURITY rules as blocking constraints (recommended: public anonymous endpoint, PII, mail)
- B) No — skip all SECURITY rules
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (Security Baseline enabled, per Bryan for the whole work) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 2: Property-Based Testing Extension
Should property-based testing rules be enforced?
- A) Yes — all PBT rules
- B) Partial — only pure functions and serialization round-trips (validation rules, token/idempotency logic)
- C) No — skip all PBT rules
- X) Other (please describe after [Answer]: tag below)
[Answer]: B (partial: pure functions and serialization round-trips) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 3: Operations phase
Should the Operations phase (deployment/monitoring/readiness) run for this feature? (Deployment already exists via the Gitea workflow.)
- A) No — closes after Build and Test; deployment follows existing workflow
- B) Yes — run the Operations phase
- C) Not sure yet — decide at Build and Test
- X) Other (please describe after [Answer]: tag below)
[Answer]: C (decide at Build and Test) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 4: Module layout
Where does the new module live?
- A) New projects `SlpModularCms.Modules.Contact` + `SlpModularCms.Modules.Contact.Tests` (own DbContext + migration, like Offerings), referenced by Api.SlpSoftware and Api.AndreaSlopFotografie (recommended)
- B) Inside Modules.Offerings
- X) Other (please describe after [Answer]: tag below)
[Answer]: A - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 5: Database and migrations per host
Offerings uses MySQL with `Database.Migrate()` at startup. For the Contact module:
- A) Same approach: own DbContext, MySQL, additive migration applied at startup; migration regenerated after the rebase on identity-email-notifications (recommended)
- B) Reuse an existing DbContext (e.g. Core)
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (migration regenerated after rebase) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 6: Availability gate marker
Peer advice (ASF session): a `[PublicSiteEndpoint]` marker attribute in Core, read via endpoint metadata in `AvailabilityMiddleware`, deny-by-default, admin routes never exempt, `/api/v1/Availability/status` stays open. Own unit together with (b).
- A) Marker attribute (recommended)
- B) Prefix list next to the existing bypass list
- X) Other (please describe after [Answer]: tag below)
[Answer]: A ([PublicSiteEndpoint] marker, deny-by-default) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 7: Reverse engineering
The `_shared/reverse-engineering` artifacts date from July 2026 (before Offerings, SlpSoftware and ASF hosts).
- A) Skip a full rerun; do a targeted review of the touched areas (Offerings, Email, rate limiter, Availability, capabilities, SecurityEvents) and record findings in the requirements (recommended)
- B) Full rerun
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (targeted review; new MailKind, existing mail code untouched) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 8: Admin UI scope
Unit (f) admin UI ("Berichten") is in the existing React admin (`frontend/`). The ASF session is still changing auth/refresh, users and theme assets there.
- A) Build (f) last, on the rebased branch after their merge, only touching new files plus the menu entry (recommended)
- B) Build it in parallel on the current base
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (admin UI last, after ASF merge; report if the merge takes too long) - answered by Redesign - SLS (technical lead) 2026-11-09
@@ -0,0 +1,60 @@
# Requirements — contact-forms-module
## 1. Intent Analysis
- **Request**: Build the CMS/API side of the contact form and related contract items: (a) `category` on Offerings, (b) rate-limit `Retry-After` + own ProblemDetails, public-route marker for the availability gate, (c) Contact module (token + submit), (d) mail + retry, (e) admin API, (f) admin UI "Berichten".
- **Source of truth**: `contact-api-contract.md` v0.3.1-draft (in the SlpSoftware repo, feature `redesign-modern-timetravel`). This document does not restate its field-level detail; it records scope, decisions, repo findings and deviations. Where they disagree, the contract wins unless listed under § 6.
- **Type**: New feature (multi-component). **Scope**: multiple components. **Complexity**: Complex. **Depth**: Standard (decisions already made by Bryan / technical lead).
- **Coordination**: stages approved by "Redesign - SLS" (leads the build; Bryan's permission runs through it).
## 2. Decisions (all recorded, not re-asked)
| # | Decision | Source |
|---|---|---|
| D1 | Admin "Berichten" view in scope, full version (list+paging+unread count, detail, status new/read/archived, delete, mail status + resend; AdminOnly; capabilities entry) | Bryan |
| D2 | Honeypot/too-fast submissions stored as `spam` (30 days, never mailed, per-site daily cap, outside unread count and default list), visitor sees normal 202 | Bryan |
| D3 | Captcha disabled by default; provider failure = fail-open | Bryan |
| D4 | Category list = fixed list per site in appsettings; admin only picks from it (no free text) | Bryan |
| D5 | Retention 12 months (per row, fixed at insert), daily cleanup job | Bryan |
| D6 | Availability gate blocks only CMS/admin routes; public routes stay open; deny-by-default; admin routes never exempt | Bryan |
| D7 | Security Baseline extension **enabled**; Property-Based Testing **partial** (pure functions + serialization round-trips: validation rules, token/idempotency logic); Operations phase **undecided** (decide at Build and Test) | Bryan via Redesign - SLS |
| D8 | New projects `SlpModularCms.Modules.Contact` + `.Contact.Tests`; own DbContext, MySQL, `Database.Migrate()` at startup, additive migration (like Offerings); migration regenerated after rebase | Redesign - SLS |
| D9 | Availability marker attribute `[PublicSiteEndpoint]` in Core, read from endpoint metadata in `AvailabilityMiddleware`; own unit together with (b); test that every `/api/v1/admin/*` route still returns 503; `/api/v1/Availability/status` stays open | Redesign - SLS |
| D10 | No full reverse-engineering rerun; targeted review (§ 3). Contact mail = **new `MailKind`**, existing mail code untouched, keep dark-mode contrast | Redesign - SLS |
| D11 | Admin UI (f) last, on rebased branch after the ASF merge, only new files + menu entry; report to SLS if the merge takes long | Redesign - SLS |
| D12 | No push/merge/PR; no ASF addresses in code/committed config (env-only); no PII in logs; no deploy to production | Bryan / SLS |
## 3. Targeted review findings (master `d9cc539`)
- **Module pattern**: `Modules.Offerings` = `IModule` (`RegisterServices` + `UseModule`), own `DbContext` (MySQL, `NonLockingMySQLHistoryRepository`), `Database.Migrate()` in `UseModule`. Contact follows this exactly.
- **Capabilities**: `SystemController` returns `ModuleOrchestrator.ModuleNames`; a registered module named "Contact" appears automatically. The frontend menu entry keys off it.
- **Availability**: `AvailabilityMiddleware` (Modules.Availability) blocks everything not on a prefix bypass list (`/api/v1/Availability/status`, `/Auth/`, `/Setup/status`, `/master/`, `/SlaveStatus`, `/health`) except verified Owner/Administrator tokens. The marker-attribute check slots in before the master/local gate.
- **Mail**: `Core/Email` (`IEmailSender`, `MailSendResult`, SMTP, templates) **does not exist on master**; it lives on the unmerged ASF branch `feature/identity-email-notifications`. `Api.AndreaSlopFotografie` is also not on master. Unit (d) therefore depends on that merge (or a rebase on their branch); see § 5.
- **Rate limiting**: `AddCmsRateLimiting` with named per-client policies; `OnRejected` currently logs a security event only (no body, no `Retry-After`). To be extended (unit b) for all policies, with existing tests adjusted. ForwardedHeaders/KnownProxies are env-configured (no code change).
- **Observability**: `SecurityEvents` / `SecurityEventProcessor` (Sentry): extra scrub rule for the contact routes; test that a logged exception holds no body.
- **Offerings**: has no `category` field; additive migration + DTO + admin DTO/requests + validation against the per-site configured list.
- **ASF-owned areas (do not touch without SLS)**: Email (MailTemplateRenderer, MailColours, EmailOptions, IdentityMailService), Identity, Core Hosting/Website/Proxy, Core migrations, frontend auth/users/theme. Expected rebase conflicts: appsettings, Program.cs/host config, AvailabilityMiddleware, EF snapshots.
## 4. Functional Requirements (summary; detail in contract)
- **FR-A Offerings category**: optional `category` string|null on offering (public + admin DTOs); value must be in the per-site configured list (`Offerings:Categories`); null/empty = no chip. Additive migration.
- **FR-B1 Rate limiter**: `OnRejected` writes `429 application/problem+json` with `Retry-After`; existing policies keep their numbers; new policy `ContactForm` (5/10 min per client IP, config `RateLimiting:ContactForm`) and token policy (20/10 min).
- **FR-B2 Gate**: `[PublicSiteEndpoint]` marker; applied to `GET /api/v1/offerings`, `GET /api/v1/contact-messages/token`, `POST /api/v1/contact-messages`.
- **FR-C Contact module**: `GET .../token` (DataProtection token, per-site purpose, persistent key ring); `POST .../contact-messages` with validation + error codes per contract § 3, own 413 ProblemDetails (16 KB), `Idempotency-Key` table (no PII), honeypot `hpCheck`, min-time, optional captcha behind `ICaptchaVerifier` (Null default, fail-open), identical 202, spam stored with daily cap, site id from host/config, retention fields.
- **FR-D Mail**: after commit, send via `IEmailSender` with a new `MailKind`; `From` fixed site sender (allow-list), `Reply-To` visitor, header-injection and HTML-encoding protections; `BackgroundService` sweeps `pending` frequently and retries `failed` with backoff and max attempts; no SMTP host = store only + admin notice.
- **FR-E Admin API**: `GET list/detail`, `PATCH status`, `DELETE` (hard), `POST resend` (rate-limited); AdminOnly; spam shown separately; unread count excludes spam.
- **FR-F Admin UI**: "Berichten" screen per D1 (last unit, after ASF merge).
- **FR-G Retention job**: daily deletion of rows past `retentionUntil` and idempotency records older than 24 h.
- **FR-H OpenAPI**: exported definitive OpenAPI document committed in the repo (path fixed in design) for `cms-client` type generation.
## 5. Non-Functional Requirements and risks
- **Security (baseline enabled)**: anonymous endpoint, so input validation, size limits, no oracle on token errors, no PII in logs/Sentry, secrets only via env/secrets manager, deny-by-default gate, generic 5xx, baseline rules checked at each stage.
- **Privacy**: IP not stored; retention per row; hard delete on erasure; privacy statement must mention backups and the captcha provider (site side).
- **Reliability**: mail failure never fails the request; at-least-once mail with attempt counter; idempotent submit.
- **Testability**: per-unit build + tests (xUnit); PBT partial per D7; `/admin/*` 503 regression test; token/validation round-trip tests.
- **Risk R1**: mail unit (d) depends on `Core/Email` being on the base branch. Options: wait for the ASF merge, or rebase the feature branch onto `feature/identity-email-notifications`. To be decided by SLS in the plan.
- **Risk R2**: EF migration snapshot conflicts after rebase; regenerate own migration (D8).
- **Risk R3**: `AvailabilityMiddleware` and rate-limiter edits overlap ASF-touched files; keep diffs minimal, coordinate via SLS.
## 6. Deviations / additions vs. contract v0.3.1
- None blocking. Additions: OpenAPI export path; `Offerings:Categories` config key name; Contact module named `Contact` (capabilities entry).
## 7. Open points for the plan stage (not blockers for requirements)
- Base for unit (d): wait for ASF merge vs. rebase now (R1).
- Exact config key names and OpenAPI export location (decide in Application Design).