From bc763c8ef6f35f1ca3ea1f459f6a997628579f69 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:23:04 +0100 Subject: [PATCH 01/83] =?UTF-8?q?Aanbod:=20RESTful=20routes=20zonder=20/ad?= =?UTF-8?q?min,=20=C3=A9=C3=A9n=20OfferingDto=20en=20herordenen=20via=20PU?= =?UTF-8?q?T=20/offerings/order?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- aidlc-docs/active-features.md | 1 + .../contact-forms-module/aidlc-state.md | 54 +++++++ .../features/contact-forms-module/audit.md | 73 ++++++++++ .../code/summary.md | 17 +++ ...ngs-restful-routes-code-generation-plan.md | 46 ++++++ ...offerings-category-code-generation-plan.md | 42 ++++++ .../application-design/application-design.md | 65 +++++++++ .../application-design/unit-of-work.md | 34 +++++ .../inception/plans/execution-plan.md | 137 ++++++++++++++++++ .../requirement-verification-questions.md | 77 ++++++++++ .../inception/requirements/requirements.md | 60 ++++++++ .../components/DeleteOfferingDialog.tsx | 4 +- .../offerings/components/OfferingForm.tsx | 4 +- .../offerings/components/OfferingRow.tsx | 4 +- .../offerings/components/OfferingsList.tsx | 6 +- .../offerings/hooks/useOfferingsDnd.ts | 4 +- .../src/features/offerings/mocks/handlers.ts | 49 ++----- .../pages/OfferingsListPage.test.tsx | 30 +++- .../offerings/pages/OfferingsListPage.tsx | 4 +- .../src/features/offerings/services/types.ts | 2 +- .../offerings/services/useCreateOffering.ts | 8 +- .../offerings/services/useDeleteOffering.ts | 2 +- .../offerings/services/useMoveOffering.ts | 22 ++- .../offerings/services/useOfferings.ts | 6 +- .../offerings/services/useReorderOfferings.ts | 2 +- .../offerings/services/useUpdateOffering.ts | 8 +- .../Controllers/OfferingsControllerTests.cs | 52 +------ .../Controllers/OfferingsRoutesTests.cs | 106 ++++++++++++++ .../Repositories/OfferingRepositoryTests.cs | 47 ------ .../Services/OfferingsServiceOrderTests.cs | 99 +++++++++++++ .../Services/OfferingsServiceTests.cs | 92 ------------ .../Controllers/OfferingsController.cs | 53 +++---- .../Models/OfferingAdminDto.cs | 17 --- .../Models/OfferingDto.cs | 7 +- .../Repositories/IOfferingRepository.cs | 2 - .../Repositories/OfferingRepository.cs | 12 -- .../Services/IOfferingsService.cs | 14 +- .../Services/OfferingOrderInvalidException.cs | 7 + .../Services/OfferingsService.cs | 94 +++--------- 39 files changed, 968 insertions(+), 395 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/aidlc-state.md create mode 100644 aidlc-docs/features/contact-forms-module/audit.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u0-offerings-restful-routes/code/summary.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u0-offerings-restful-routes-code-generation-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/inception/application-design/application-design.md create mode 100644 aidlc-docs/features/contact-forms-module/inception/application-design/unit-of-work.md create mode 100644 aidlc-docs/features/contact-forms-module/inception/plans/execution-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/inception/requirements/requirement-verification-questions.md create mode 100644 aidlc-docs/features/contact-forms-module/inception/requirements/requirements.md create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsRoutesTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs delete mode 100644 src/SlpModularCms.Modules.Offerings/Models/OfferingAdminDto.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingOrderInvalidException.cs diff --git a/aidlc-docs/active-features.md b/aidlc-docs/active-features.md index 412a9c8..ca89252 100644 --- a/aidlc-docs/active-features.md +++ b/aidlc-docs/active-features.md @@ -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 | diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md new file mode 100644 index 0000000..e5dab64 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -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) diff --git a/aidlc-docs/features/contact-forms-module/audit.md b/aidlc-docs/features/contact-forms-module/audit.md new file mode 100644 index 0000000..f113d36 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -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. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u0-offerings-restful-routes/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u0-offerings-restful-routes/code/summary.md new file mode 100644 index 0000000..a4539ef --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u0-offerings-restful-routes/code/summary.md @@ -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). diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u0-offerings-restful-routes-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u0-offerings-restful-routes-code-generation-plan.md new file mode 100644 index 0000000..a41cd9f --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u0-offerings-restful-routes-code-generation-plan.md @@ -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. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md new file mode 100644 index 0000000..0985249 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md @@ -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. diff --git a/aidlc-docs/features/contact-forms-module/inception/application-design/application-design.md b/aidlc-docs/features/contact-forms-module/inception/application-design/application-design.md new file mode 100644 index 0000000..d909423 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/inception/application-design/application-design.md @@ -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("")]`, 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()` != 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). diff --git a/aidlc-docs/features/contact-forms-module/inception/application-design/unit-of-work.md b/aidlc-docs/features/contact-forms-module/inception/application-design/unit-of-work.md new file mode 100644 index 0000000..4e8290c --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/inception/application-design/unit-of-work.md @@ -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. diff --git a/aidlc-docs/features/contact-forms-module/inception/plans/execution-plan.md b/aidlc-docs/features/contact-forms-module/inception/plans/execution-plan.md new file mode 100644 index 0000000..1be99fc --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/inception/plans/execution-plan.md @@ -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
COMPLETED"] + RE["Reverse Engineering
SKIP (targeted review)"] + RA["Requirements Analysis
COMPLETED"] + US["User Stories
SKIP"] + WP["Workflow Planning
IN PROGRESS"] + AD["Application Design
EXECUTE (minimal)"] + UG["Units Generation
EXECUTE"] + end + subgraph CONSTRUCTION["🟒 CONSTRUCTION (per unit)"] + FD["Functional Design
EXECUTE (U3, U4, U5)"] + NFR["NFR Requirements + Design
EXECUTE (U2, U3)"] + ID["Infrastructure Design
SKIP (config noted in design)"] + CG["Code Generation
EXECUTE"] + BT["Build and Test
EXECUTE"] + end + OPS["Operations
UNDECIDED (at Build and Test)"] + 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. diff --git a/aidlc-docs/features/contact-forms-module/inception/requirements/requirement-verification-questions.md b/aidlc-docs/features/contact-forms-module/inception/requirements/requirement-verification-questions.md new file mode 100644 index 0000000..b43a6ad --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/inception/requirements/requirement-verification-questions.md @@ -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 diff --git a/aidlc-docs/features/contact-forms-module/inception/requirements/requirements.md b/aidlc-docs/features/contact-forms-module/inception/requirements/requirements.md new file mode 100644 index 0000000..ce317f9 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/inception/requirements/requirements.md @@ -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). diff --git a/frontend/src/features/offerings/components/DeleteOfferingDialog.tsx b/frontend/src/features/offerings/components/DeleteOfferingDialog.tsx index c15a9ce..ce1e7d2 100644 --- a/frontend/src/features/offerings/components/DeleteOfferingDialog.tsx +++ b/frontend/src/features/offerings/components/DeleteOfferingDialog.tsx @@ -1,10 +1,10 @@ import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; interface DeleteOfferingDialogProps { - offering: OfferingAdminDto | null; + offering: OfferingDto | null; isDeleting: boolean; onConfirm: () => void; onCancel: () => void; diff --git a/frontend/src/features/offerings/components/OfferingForm.tsx b/frontend/src/features/offerings/components/OfferingForm.tsx index 11d8124..0064855 100644 --- a/frontend/src/features/offerings/components/OfferingForm.tsx +++ b/frontend/src/features/offerings/components/OfferingForm.tsx @@ -9,10 +9,10 @@ import { Label } from '@/components/ui/label'; import { FieldError } from '@/components/ui/FieldError'; import { slugifyPreview } from '@/lib/slugify'; import { offeringFormSchema, type OfferingFormData } from '../schemas/offering'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; interface OfferingFormProps { - initialValues?: OfferingAdminDto; + initialValues?: OfferingDto; onSubmit: (values: OfferingFormData) => void; isSubmitting: boolean; } diff --git a/frontend/src/features/offerings/components/OfferingRow.tsx b/frontend/src/features/offerings/components/OfferingRow.tsx index 4ee92f3..abe39ff 100644 --- a/frontend/src/features/offerings/components/OfferingRow.tsx +++ b/frontend/src/features/offerings/components/OfferingRow.tsx @@ -7,10 +7,10 @@ import { Button } from '@/components/ui/button'; import { TableCell, TableRow } from '@/components/ui/table'; import { useUpdateOffering } from '../services/useUpdateOffering'; import { useMoveOffering } from '../services/useMoveOffering'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; interface OfferingRowProps { - offering: OfferingAdminDto; + offering: OfferingDto; isFirst: boolean; isLast: boolean; onDeleteRequested: () => void; diff --git a/frontend/src/features/offerings/components/OfferingsList.tsx b/frontend/src/features/offerings/components/OfferingsList.tsx index 3b823ea..b302c3d 100644 --- a/frontend/src/features/offerings/components/OfferingsList.tsx +++ b/frontend/src/features/offerings/components/OfferingsList.tsx @@ -5,11 +5,11 @@ import { GripVertical } from 'lucide-react'; import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { OfferingRow } from './OfferingRow'; import { useOfferingsDnd } from '../hooks/useOfferingsDnd'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; interface OfferingsListProps { - offerings: OfferingAdminDto[]; - onDeleteRequested: (offering: OfferingAdminDto) => void; + offerings: OfferingDto[]; + onDeleteRequested: (offering: OfferingDto) => void; } export function OfferingsList({ offerings, onDeleteRequested }: OfferingsListProps) { diff --git a/frontend/src/features/offerings/hooks/useOfferingsDnd.ts b/frontend/src/features/offerings/hooks/useOfferingsDnd.ts index 932339a..78fd1d1 100644 --- a/frontend/src/features/offerings/hooks/useOfferingsDnd.ts +++ b/frontend/src/features/offerings/hooks/useOfferingsDnd.ts @@ -9,9 +9,9 @@ import { } from '@dnd-kit/core'; import { arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable'; import { useReorderOfferings } from '../services/useReorderOfferings'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; -export function useOfferingsDnd(offerings: OfferingAdminDto[]) { +export function useOfferingsDnd(offerings: OfferingDto[]) { const [items, setItems] = useState(offerings); const [syncedOfferings, setSyncedOfferings] = useState(offerings); const [activeId, setActiveId] = useState(null); diff --git a/frontend/src/features/offerings/mocks/handlers.ts b/frontend/src/features/offerings/mocks/handlers.ts index dcecfb8..c07dbae 100644 --- a/frontend/src/features/offerings/mocks/handlers.ts +++ b/frontend/src/features/offerings/mocks/handlers.ts @@ -1,5 +1,5 @@ import { http, HttpResponse } from 'msw'; -import type { OfferingAdminDto, CreateOfferingRequest, UpdateOfferingRequest } from '@/features/offerings/services/types'; +import type { OfferingDto, CreateOfferingRequest, UpdateOfferingRequest } from '@/features/offerings/services/types'; import { API_BASE } from '@/features/auth/mocks/fixtures'; function slugify(value: string): string { @@ -11,7 +11,7 @@ function slugify(value: string): string { .replace(/^-+|-+$/g, ''); } -const seed: OfferingAdminDto[] = [ +const seed: OfferingDto[] = [ { id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', slug: 'starter', @@ -38,7 +38,7 @@ const seed: OfferingAdminDto[] = [ }, ]; -let mockOfferings: OfferingAdminDto[] = [...seed]; +let mockOfferings: OfferingDto[] = [...seed]; export const resetMockOfferings = () => { mockOfferings = [...seed]; @@ -47,13 +47,9 @@ export const resetMockOfferings = () => { export const getMockOfferings = () => mockOfferings; export const offeringsHandlers = [ - http.get(`${API_BASE}/api/v1/offerings`, () => - HttpResponse.json(mockOfferings.map(({ displayOrder: _displayOrder, ...dto }) => dto)), - ), + http.get(`${API_BASE}/api/v1/offerings`, () => HttpResponse.json(mockOfferings)), - http.get(`${API_BASE}/api/v1/offerings/admin`, () => HttpResponse.json(mockOfferings)), - - http.post(`${API_BASE}/api/v1/offerings/admin`, async ({ request }) => { + http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => { const body = (await request.json()) as CreateOfferingRequest; const slug = body.slug && body.slug.length > 0 ? slugify(body.slug) : slugify(body.title); if (mockOfferings.some((o) => o.slug === slug)) { @@ -63,7 +59,7 @@ export const offeringsHandlers = [ ); } - const newOffering: OfferingAdminDto = { + const newOffering: OfferingDto = { id: crypto.randomUUID(), ...body, slug, @@ -73,7 +69,7 @@ export const offeringsHandlers = [ return HttpResponse.json(newOffering, { status: 201 }); }), - http.put(`${API_BASE}/api/v1/offerings/admin/:id`, async ({ params, request }) => { + http.put(`${API_BASE}/api/v1/offerings/:id`, async ({ params, request }) => { const { id } = params as { id: string }; const body = (await request.json()) as UpdateOfferingRequest; const existing = mockOfferings.find((o) => o.id === id); @@ -92,48 +88,25 @@ export const offeringsHandlers = [ ); } - const updated: OfferingAdminDto = { ...existing, ...body, slug }; + const updated: OfferingDto = { ...existing, ...body, slug }; mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o)); return HttpResponse.json(updated); }), - http.delete(`${API_BASE}/api/v1/offerings/admin/:id`, ({ params }) => { + http.delete(`${API_BASE}/api/v1/offerings/:id`, ({ params }) => { const { id } = params as { id: string }; mockOfferings = mockOfferings.filter((o) => o.id !== id); return new HttpResponse(null, { status: 204 }); }), - http.put(`${API_BASE}/api/v1/offerings/admin/reorder`, async ({ request }) => { + http.put(`${API_BASE}/api/v1/offerings/order`, async ({ request }) => { const body = (await request.json()) as { orderedIds: string[] }; mockOfferings = body.orderedIds .map((id, index) => { const offering = mockOfferings.find((o) => o.id === id); return offering ? { ...offering, displayOrder: index } : null; }) - .filter((o): o is OfferingAdminDto => o !== null); - return new HttpResponse(null, { status: 204 }); - }), - - http.post(`${API_BASE}/api/v1/offerings/admin/:id/move-up`, ({ params }) => { - const { id } = params as { id: string }; - moveAdjacent(id, -1); - return new HttpResponse(null, { status: 204 }); - }), - - http.post(`${API_BASE}/api/v1/offerings/admin/:id/move-down`, ({ params }) => { - const { id } = params as { id: string }; - moveAdjacent(id, 1); + .filter((o): o is OfferingDto => o !== null); return new HttpResponse(null, { status: 204 }); }), ]; - -function moveAdjacent(id: string, delta: number) { - const sorted = [...mockOfferings].sort((a, b) => a.displayOrder - b.displayOrder); - const index = sorted.findIndex((o) => o.id === id); - const swapIndex = index + delta; - if (index === -1 || swapIndex < 0 || swapIndex >= sorted.length) return; - - const a = sorted[index]; - const b = sorted[swapIndex]; - [a.displayOrder, b.displayOrder] = [b.displayOrder, a.displayOrder]; -} diff --git a/frontend/src/features/offerings/pages/OfferingsListPage.test.tsx b/frontend/src/features/offerings/pages/OfferingsListPage.test.tsx index 760fd08..6205f88 100644 --- a/frontend/src/features/offerings/pages/OfferingsListPage.test.tsx +++ b/frontend/src/features/offerings/pages/OfferingsListPage.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; @@ -13,7 +13,7 @@ beforeEach(() => { resetMockOfferings(); }); -const OFFERINGS_URL = `${API_BASE}/api/v1/offerings/admin`; +const OFFERINGS_URL = `${API_BASE}/api/v1/offerings`; describe('OfferingsListPage', () => { it('renders the page title and Add button', async () => { @@ -86,6 +86,32 @@ describe('OfferingsListPage', () => { ).toBeDisabled(); }); + it('moves a row down by sending the full new order to PUT /offerings/order', async () => { + mockAuthenticated(); + let sentBody: { orderedIds: string[] } | undefined; + server.use( + http.put(`${OFFERINGS_URL}/order`, async ({ request }) => { + sentBody = (await request.json()) as { orderedIds: string[] }; + return new HttpResponse(null, { status: 204 }); + }), + ); + renderApp('/offerings'); + + await userEvent.click( + await screen.findByTestId( + 'offering-row-aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa-move-down-button', + {}, + { timeout: 10000 }, + ), + ); + + await vi.waitFor(() => + expect(sentBody).toEqual({ + orderedIds: ['bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'], + }), + ); + }); + it('redirects unauthenticated users to login', async () => { mockGuest(); renderApp('/offerings'); diff --git a/frontend/src/features/offerings/pages/OfferingsListPage.tsx b/frontend/src/features/offerings/pages/OfferingsListPage.tsx index 8ffeb64..8756524 100644 --- a/frontend/src/features/offerings/pages/OfferingsListPage.tsx +++ b/frontend/src/features/offerings/pages/OfferingsListPage.tsx @@ -7,11 +7,11 @@ import { OfferingsList } from '../components/OfferingsList'; import { DeleteOfferingDialog } from '../components/DeleteOfferingDialog'; import { useOfferings } from '../services/useOfferings'; import { useDeleteOffering } from '../services/useDeleteOffering'; -import type { OfferingAdminDto } from '../services/types'; +import type { OfferingDto } from '../services/types'; export function OfferingsListPage() { const { t } = useTranslation(); - const [offeringPendingDelete, setOfferingPendingDelete] = useState(null); + const [offeringPendingDelete, setOfferingPendingDelete] = useState(null); const { data: offerings, isPending, isError } = useOfferings(); const deleteOffering = useDeleteOffering({ onSuccess: () => setOfferingPendingDelete(null), diff --git a/frontend/src/features/offerings/services/types.ts b/frontend/src/features/offerings/services/types.ts index 00daed0..8cea23d 100644 --- a/frontend/src/features/offerings/services/types.ts +++ b/frontend/src/features/offerings/services/types.ts @@ -1,4 +1,4 @@ -export interface OfferingAdminDto { +export interface OfferingDto { id: string; slug: string; title: string; diff --git a/frontend/src/features/offerings/services/useCreateOffering.ts b/frontend/src/features/offerings/services/useCreateOffering.ts index 722cf64..5a3908a 100644 --- a/frontend/src/features/offerings/services/useCreateOffering.ts +++ b/frontend/src/features/offerings/services/useCreateOffering.ts @@ -1,13 +1,13 @@ import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { CreateOfferingRequest, OfferingAdminDto } from './types'; +import type { CreateOfferingRequest, OfferingDto } from './types'; export function useCreateOffering( - options?: Pick, 'onSuccess' | 'onError'>, + options?: Pick, 'onSuccess' | 'onError'>, ) { const queryClient = useQueryClient(); - return useMutation({ - mutationFn: (data) => api.post('/api/v1/offerings/admin', data), + return useMutation({ + mutationFn: (data) => api.post('/api/v1/offerings', data), onSuccess: (data, variables, ...rest) => { queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); options?.onSuccess?.(data, variables, ...rest); diff --git a/frontend/src/features/offerings/services/useDeleteOffering.ts b/frontend/src/features/offerings/services/useDeleteOffering.ts index c3001be..4e2fc09 100644 --- a/frontend/src/features/offerings/services/useDeleteOffering.ts +++ b/frontend/src/features/offerings/services/useDeleteOffering.ts @@ -6,7 +6,7 @@ export function useDeleteOffering( ) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: (id) => api.delete(`/api/v1/offerings/admin/${id}`), + mutationFn: (id) => api.delete(`/api/v1/offerings/${id}`), onSuccess: (data, variables, ...rest) => { queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); options?.onSuccess?.(data, variables, ...rest); diff --git a/frontend/src/features/offerings/services/useMoveOffering.ts b/frontend/src/features/offerings/services/useMoveOffering.ts index eb73568..62d0e9f 100644 --- a/frontend/src/features/offerings/services/useMoveOffering.ts +++ b/frontend/src/features/offerings/services/useMoveOffering.ts @@ -1,16 +1,32 @@ import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { MoveDirection } from './types'; +import type { MoveDirection, OfferingDto } from './types'; +const OFFERINGS_KEY = ['offerings', 'admin']; + +/** + * Moves one offering a step up or down. The API has no move endpoint (the collection is reordered + * as a whole via `PUT /api/v1/offerings/order`), so the new order is computed from the cached list. + * Moving past either end is a no-op. + */ export function useMoveOffering( direction: MoveDirection, options?: Pick, 'onSuccess' | 'onError'>, ) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: (id) => api.post(`/api/v1/offerings/admin/${id}/move-${direction}`), + mutationFn: async (id) => { + const offerings = queryClient.getQueryData(OFFERINGS_KEY) ?? []; + const ids = [...offerings].sort((a, b) => a.displayOrder - b.displayOrder).map((o) => o.id); + const index = ids.indexOf(id); + const target = direction === 'up' ? index - 1 : index + 1; + if (index === -1 || target < 0 || target >= ids.length) return; + + [ids[index], ids[target]] = [ids[target], ids[index]]; + await api.put('/api/v1/offerings/order', { orderedIds: ids }); + }, onSuccess: (data, variables, ...rest) => { - queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); + queryClient.invalidateQueries({ queryKey: OFFERINGS_KEY }); options?.onSuccess?.(data, variables, ...rest); }, onError: options?.onError, diff --git a/frontend/src/features/offerings/services/useOfferings.ts b/frontend/src/features/offerings/services/useOfferings.ts index 73de56b..5fee1e9 100644 --- a/frontend/src/features/offerings/services/useOfferings.ts +++ b/frontend/src/features/offerings/services/useOfferings.ts @@ -1,10 +1,10 @@ import { useQuery } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { OfferingAdminDto } from './types'; +import type { OfferingDto } from './types'; export function useOfferings() { - return useQuery({ + return useQuery({ queryKey: ['offerings', 'admin'], - queryFn: () => api.get('/api/v1/offerings/admin'), + queryFn: () => api.get('/api/v1/offerings'), }); } diff --git a/frontend/src/features/offerings/services/useReorderOfferings.ts b/frontend/src/features/offerings/services/useReorderOfferings.ts index 0343e19..6e92f74 100644 --- a/frontend/src/features/offerings/services/useReorderOfferings.ts +++ b/frontend/src/features/offerings/services/useReorderOfferings.ts @@ -6,7 +6,7 @@ export function useReorderOfferings( ) { const queryClient = useQueryClient(); return useMutation({ - mutationFn: (orderedIds) => api.put('/api/v1/offerings/admin/reorder', { orderedIds }), + mutationFn: (orderedIds) => api.put('/api/v1/offerings/order', { orderedIds }), onSuccess: (data, variables, ...rest) => { queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); options?.onSuccess?.(data, variables, ...rest); diff --git a/frontend/src/features/offerings/services/useUpdateOffering.ts b/frontend/src/features/offerings/services/useUpdateOffering.ts index 5f1b1f3..e3b0245 100644 --- a/frontend/src/features/offerings/services/useUpdateOffering.ts +++ b/frontend/src/features/offerings/services/useUpdateOffering.ts @@ -1,15 +1,15 @@ import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/react-query'; import { api } from '@/lib/api-client'; -import type { OfferingAdminDto, UpdateOfferingRequest } from './types'; +import type { OfferingDto, UpdateOfferingRequest } from './types'; type UpdateVariables = { id: string } & UpdateOfferingRequest; export function useUpdateOffering( - options?: Pick, 'onSuccess' | 'onError'>, + options?: Pick, 'onSuccess' | 'onError'>, ) { const queryClient = useQueryClient(); - return useMutation({ - mutationFn: ({ id, ...body }) => api.put(`/api/v1/offerings/admin/${id}`, body), + return useMutation({ + mutationFn: ({ id, ...body }) => api.put(`/api/v1/offerings/${id}`, body), onSuccess: (data, variables, ...rest) => { queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); options?.onSuccess?.(data, variables, ...rest); diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerTests.cs index b830e20..0d734b4 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerTests.cs @@ -24,10 +24,7 @@ public class OfferingsControllerTests return new OfferingsController(_service) { ControllerContext = new ControllerContext { HttpContext = httpContext } }; } - private static OfferingDto PublicDto() => new( - Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false); - - private static OfferingAdminDto AdminDto(int displayOrder = 0) => new( + private static OfferingDto Dto(int displayOrder = 0) => new( Guid.NewGuid().ToString(), "title", "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", false, displayOrder); private static CreateOfferingRequest CreateRequest() => new( @@ -41,35 +38,23 @@ public class OfferingsControllerTests [Fact] public async Task GetOfferings_Returns200_WithList() { - _service.GetPublicOfferingsAsync().Returns([PublicDto()]); + _service.GetOfferingsAsync().Returns([Dto()]); var result = await CreateSut().GetOfferings(); result.Should().BeOfType().Which.StatusCode.Should().Be(200); } - // --- GetAllForAdmin --- - - [Fact] - public async Task GetAllForAdmin_Returns200_WithList() - { - _service.GetAllForAdminAsync().Returns([AdminDto()]); - - var result = await CreateSut().GetAllForAdmin(); - - result.Should().BeOfType().Which.StatusCode.Should().Be(200); - } - // --- Create --- [Fact] public async Task Create_Returns201Created() { - _service.CreateAsync(Arg.Any(), Arg.Any()).Returns(AdminDto()); + _service.CreateAsync(Arg.Any(), Arg.Any()).Returns(Dto()); var result = await CreateSut().Create(CreateRequest()); - result.Should().BeOfType().Which.StatusCode.Should().Be(201); + result.Should().BeOfType().Which.StatusCode.Should().Be(201); } [Fact] @@ -88,7 +73,7 @@ public class OfferingsControllerTests [Fact] public async Task Update_Returns200_WhenFound() { - _service.UpdateAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(AdminDto()); + _service.UpdateAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns(Dto()); var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest()); @@ -99,7 +84,7 @@ public class OfferingsControllerTests public async Task Update_Returns404_WhenNotFound() { _service.UpdateAsync(Arg.Any(), Arg.Any(), Arg.Any()) - .Returns((OfferingAdminDto?)null); + .Returns((OfferingDto?)null); var result = await CreateSut().Update(Guid.NewGuid(), UpdateRequest()); @@ -139,29 +124,4 @@ public class OfferingsControllerTests result.Should().BeOfType(); } - // --- Reorder / MoveUp / MoveDown --- - - [Fact] - public async Task Reorder_Returns204() - { - var result = await CreateSut().Reorder(new ReorderOfferingsRequest([Guid.NewGuid()])); - - result.Should().BeOfType(); - } - - [Fact] - public async Task MoveUp_Returns204() - { - var result = await CreateSut().MoveUp(Guid.NewGuid()); - - result.Should().BeOfType(); - } - - [Fact] - public async Task MoveDown_Returns204() - { - var result = await CreateSut().MoveDown(Guid.NewGuid()); - - result.Should().BeOfType(); - } } diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsRoutesTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsRoutesTests.cs new file mode 100644 index 0000000..b0a19f7 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsRoutesTests.cs @@ -0,0 +1,106 @@ +using System.Reflection; +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Offerings.Controllers; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingsRoutesTests +{ + private readonly IOfferingsService _service = Substitute.For(); + + private OfferingsController CreateSut() => new(_service) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuth")), + }, + }, + }; + + private static IEnumerable<(MethodInfo Action, HttpMethodAttribute Http)> Actions() => + typeof(OfferingsController) + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(m => (Action: m, Http: m.GetCustomAttributes().SingleOrDefault())) + .Where(x => x.Http is not null) + .Select(x => (x.Action, x.Http!)); + + [Fact] + public void OnlyGet_IsAnonymous_AndTheClassRequiresAdminOnly() + { + var classPolicy = typeof(OfferingsController).GetCustomAttribute(); + classPolicy.Should().NotBeNull(); + classPolicy!.Policy.Should().Be("AdminOnly"); + + foreach (var (action, http) in Actions()) + { + var anonymous = action.GetCustomAttribute() is not null; + anonymous.Should().Be( + http.HttpMethods.Single() == "GET", + $"{http.HttpMethods.Single()} {http.Template} must be anonymous only when it is a GET"); + } + } + + [Fact] + public void NoRouteContainsAnAdminSegment_AndTheMoveActionsAreGone() + { + foreach (var (_, http) in Actions()) + { + (http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin"); + } + + typeof(OfferingsController).GetMethods().Select(m => m.Name) + .Should().NotContain(["MoveUp", "MoveDown", "GetAllForAdmin"]); + } + + [Fact] + public void RouteTable_IsTheRestfulSet() + { + Actions().Select(a => $"{a.Http.HttpMethods.Single()} {a.Http.Template}".Trim()) + .Should().BeEquivalentTo( + [ + "GET", + "POST", + "PUT {id:guid}", + "DELETE {id:guid}", + "PUT order", + ]); + } + + [Fact] + public async Task Create_Returns201_WithLocationOfTheNewResource() + { + var dto = new OfferingDto(Guid.NewGuid().ToString(), "t", "T", "D", "p", "n", ["f"], "c", false, 0); + _service.CreateAsync(Arg.Any(), Arg.Any()).Returns(dto); + + var result = await CreateSut().Create(new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c")); + + var created = result.Should().BeOfType().Subject; + created.StatusCode.Should().Be(201); + created.Location.Should().Be($"/api/v1/offerings/{dto.Id}"); + created.Value.Should().Be(dto); + } + + [Fact] + public async Task Reorder_Returns400_WhenTheListIsUnknownOrIncomplete() + { + _service.ReorderAsync(Arg.Any>(), Arg.Any()) + .ThrowsAsync(new OfferingOrderInvalidException()); + + var result = await CreateSut().Reorder(new ReorderOfferingsRequest([Guid.NewGuid()])); + + var bad = result.Should().BeOfType().Subject; + bad.Value.Should().BeOfType().Which.Status.Should().Be(400); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingRepositoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingRepositoryTests.cs index 6661169..842486a 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingRepositoryTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingRepositoryTests.cs @@ -105,53 +105,6 @@ public class OfferingRepositoryTests : IDisposable result.Should().BeNull(); } - [Fact] - public async Task GetPreviousAsync_ReturnsClosestLowerDisplayOrder() - { - await _sut.AddAsync(Offering("First", displayOrder: 0)); - await _sut.AddAsync(Offering("Second", displayOrder: 1)); - await _sut.AddAsync(Offering("Third", displayOrder: 2)); - await _sut.SaveChangesAsync(); - - var result = await _sut.GetPreviousAsync(2); - - result!.Title.Should().Be("Second"); - } - - [Fact] - public async Task GetPreviousAsync_ReturnsNull_WhenFirst() - { - await _sut.AddAsync(Offering("First", displayOrder: 0)); - await _sut.SaveChangesAsync(); - - var result = await _sut.GetPreviousAsync(0); - - result.Should().BeNull(); - } - - [Fact] - public async Task GetNextAsync_ReturnsClosestHigherDisplayOrder() - { - await _sut.AddAsync(Offering("First", displayOrder: 0)); - await _sut.AddAsync(Offering("Second", displayOrder: 1)); - await _sut.SaveChangesAsync(); - - var result = await _sut.GetNextAsync(0); - - result!.Title.Should().Be("Second"); - } - - [Fact] - public async Task GetNextAsync_ReturnsNull_WhenLast() - { - await _sut.AddAsync(Offering("Last", displayOrder: 0)); - await _sut.SaveChangesAsync(); - - var result = await _sut.GetNextAsync(0); - - result.Should().BeNull(); - } - [Fact] public async Task ExistsBySlugAsync_ReturnsTrue_WhenSlugTaken() { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs new file mode 100644 index 0000000..9fc2d87 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs @@ -0,0 +1,99 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingsServiceOrderTests +{ + private readonly IOfferingRepository _repo = Substitute.For(); + + public OfferingsServiceOrderTests() + { + _repo.BeginTransactionAsync().Returns(Substitute.For()); + } + + private OfferingsService CreateSut() => new(_repo, Substitute.For>()); + + private static Offering New(int order) => new() + { + Id = Guid.NewGuid(), + Slug = $"s{order}", + Title = $"T{order}", + Description = "d", + Price = "p", + PriceNote = "n", + Features = ["f"], + CtaLabel = "c", + DisplayOrder = order, + }; + + [Fact] + public async Task ReorderAsync_AssignsSequentialOrder_FromTheGivenList() + { + var a = New(0); + var b = New(1); + var c = New(2); + _repo.GetAllAsync().Returns([a, b, c]); + + await CreateSut().ReorderAsync([c.Id, a.Id, b.Id], Guid.NewGuid()); + + c.DisplayOrder.Should().Be(0); + a.DisplayOrder.Should().Be(1); + b.DisplayOrder.Should().Be(2); + await _repo.Received(1).SaveChangesAsync(); + } + + [Fact] + public async Task ReorderAsync_Throws_AndChangesNothing_WhenAnIdIsUnknown() + { + var a = New(0); + var b = New(1); + _repo.GetAllAsync().Returns([a, b]); + + var act = () => CreateSut().ReorderAsync([a.Id, Guid.NewGuid()], Guid.NewGuid()); + + await act.Should().ThrowAsync(); + a.DisplayOrder.Should().Be(0); + b.DisplayOrder.Should().Be(1); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task ReorderAsync_Throws_WhenTheListIsIncomplete() + { + var a = New(0); + var b = New(1); + _repo.GetAllAsync().Returns([a, b]); + + var act = () => CreateSut().ReorderAsync([a.Id], Guid.NewGuid()); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task ReorderAsync_Throws_WhenTheListHoldsADuplicate() + { + var a = New(0); + var b = New(1); + _repo.GetAllAsync().Returns([a, b]); + + var act = () => CreateSut().ReorderAsync([a.Id, a.Id], Guid.NewGuid()); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task GetOfferingsAsync_IncludesDisplayOrder_ForEveryone() + { + _repo.GetAllAsync().Returns([New(3)]); + + var result = await CreateSut().GetOfferingsAsync(); + + result.Should().ContainSingle().Which.DisplayOrder.Should().Be(3); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index aecf8ec..2046fce 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -267,96 +267,4 @@ public class OfferingsServiceTests offering.DeletedAt.Should().NotBeNull(); } - // --- ReorderAsync / BR-OFF-03 --- - - [Fact] - public async Task ReorderAsync_ReassignsDisplayOrderSequentially() - { - var first = ExistingOffering(displayOrder: 5); - var second = ExistingOffering(displayOrder: 2); - _repo.GetByIdAsync(first.Id).Returns(first); - _repo.GetByIdAsync(second.Id).Returns(second); - - await CreateSut().ReorderAsync([first.Id, second.Id], Guid.NewGuid()); - - first.DisplayOrder.Should().Be(0); - second.DisplayOrder.Should().Be(1); - } - - // --- MoveUpAsync / MoveDownAsync / BR-OFF-03 boundaries --- - - [Fact] - public async Task MoveUpAsync_IsNoOp_WhenAlreadyFirst() - { - var offering = ExistingOffering(displayOrder: 0); - _repo.GetByIdAsync(offering.Id).Returns(offering); - _repo.GetPreviousAsync(0).Returns((Offering?)null); - - await CreateSut().MoveUpAsync(offering.Id, Guid.NewGuid()); - - await _repo.DidNotReceive().BeginTransactionAsync(); - } - - [Fact] - public async Task MoveUpAsync_SwapsDisplayOrder_WithPrevious() - { - var offering = ExistingOffering(displayOrder: 1); - var previous = ExistingOffering(displayOrder: 0); - _repo.GetByIdAsync(offering.Id).Returns(offering); - _repo.GetPreviousAsync(1).Returns(previous); - - await CreateSut().MoveUpAsync(offering.Id, Guid.NewGuid()); - - offering.DisplayOrder.Should().Be(0); - previous.DisplayOrder.Should().Be(1); - } - - [Fact] - public async Task MoveDownAsync_IsNoOp_WhenAlreadyLast() - { - var offering = ExistingOffering(displayOrder: 0); - _repo.GetByIdAsync(offering.Id).Returns(offering); - _repo.GetNextAsync(0).Returns((Offering?)null); - - await CreateSut().MoveDownAsync(offering.Id, Guid.NewGuid()); - - await _repo.DidNotReceive().BeginTransactionAsync(); - } - - [Fact] - public async Task MoveDownAsync_SwapsDisplayOrder_WithNext() - { - var offering = ExistingOffering(displayOrder: 0); - var next = ExistingOffering(displayOrder: 1); - _repo.GetByIdAsync(offering.Id).Returns(offering); - _repo.GetNextAsync(0).Returns(next); - - await CreateSut().MoveDownAsync(offering.Id, Guid.NewGuid()); - - offering.DisplayOrder.Should().Be(1); - next.DisplayOrder.Should().Be(0); - } - - // --- GetPublicOfferingsAsync / GetAllForAdminAsync --- - - [Fact] - public async Task GetPublicOfferingsAsync_MapsToPublicDto() - { - _repo.GetAllAsync().Returns([ExistingOffering()]); - - var result = await CreateSut().GetPublicOfferingsAsync(); - - result.Should().ContainSingle(); - } - - [Fact] - public async Task GetAllForAdminAsync_IncludesDisplayOrder() - { - var offering = ExistingOffering(displayOrder: 3); - _repo.GetAllAsync().Returns([offering]); - - var result = await CreateSut().GetAllForAdminAsync(); - - result[0].DisplayOrder.Should().Be(3); - } } diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs index e6dced8..a9750ed 100644 --- a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs @@ -8,6 +8,11 @@ using SlpModularCms.Modules.Offerings.Services; namespace SlpModularCms.Modules.Offerings.Controllers; +/// +/// The offerings resource. Reading is public; every write requires the AdminOnly policy. +/// There is deliberately no separate "admin" route: an administrator uses the same resource +/// and verbs, and access is decided by authorization alone. +/// [ApiController] [Route("offerings")] [Authorize(Policy = "AdminOnly")] @@ -18,24 +23,17 @@ public class OfferingsController(IOfferingsService service) : ControllerBase [EnableRateLimiting("offerings-public")] public async Task GetOfferings() { - var offerings = await service.GetPublicOfferingsAsync(); + var offerings = await service.GetOfferingsAsync(); return Ok(offerings); } - [HttpGet("admin")] - public async Task GetAllForAdmin() - { - var offerings = await service.GetAllForAdminAsync(); - return Ok(offerings); - } - - [HttpPost("admin")] + [HttpPost] public async Task Create([FromBody] CreateOfferingRequest request) { try { var dto = await service.CreateAsync(request, GetCallerId()); - return CreatedAtAction(nameof(GetAllForAdmin), null, dto); + return Created($"/api/v1/offerings/{dto.Id}", dto); } catch (OfferingSlugConflictException ex) { @@ -43,7 +41,7 @@ public class OfferingsController(IOfferingsService service) : ControllerBase } } - [HttpPut("admin/{id:guid}")] + [HttpPut("{id:guid}")] public async Task Update(Guid id, [FromBody] UpdateOfferingRequest request) { try @@ -57,32 +55,29 @@ public class OfferingsController(IOfferingsService service) : ControllerBase } } - [HttpDelete("admin/{id:guid}")] + [HttpDelete("{id:guid}")] public async Task Delete(Guid id) { var deleted = await service.DeleteAsync(id, GetCallerId()); return deleted ? NoContent() : NotFound(); } - [HttpPut("admin/reorder")] + /// + /// Sets the display order of the whole collection. The list must contain every existing + /// offering exactly once. + /// + [HttpPut("order")] public async Task Reorder([FromBody] ReorderOfferingsRequest request) { - await service.ReorderAsync(request.OrderedIds, GetCallerId()); - return NoContent(); - } - - [HttpPost("admin/{id:guid}/move-up")] - public async Task MoveUp(Guid id) - { - await service.MoveUpAsync(id, GetCallerId()); - return NoContent(); - } - - [HttpPost("admin/{id:guid}/move-down")] - public async Task MoveDown(Guid id) - { - await service.MoveDownAsync(id, GetCallerId()); - return NoContent(); + try + { + await service.ReorderAsync(request.OrderedIds, GetCallerId()); + return NoContent(); + } + catch (OfferingOrderInvalidException ex) + { + return BadRequest(new ProblemDetails { Status = StatusCodes.Status400BadRequest, Title = ex.Message }); + } } private Guid GetCallerId() diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingAdminDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingAdminDto.cs deleted file mode 100644 index dc8bc67..0000000 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingAdminDto.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace SlpModularCms.Modules.Offerings.Models; - -[ExcludeFromCodeCoverage] -public record OfferingAdminDto( - string Id, - string Slug, - string Title, - string Description, - string Price, - string PriceNote, - IReadOnlyList Features, - string CtaLabel, - bool Featured, - int DisplayOrder -); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs index ac3a640..13e170b 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs @@ -2,6 +2,10 @@ using System.Diagnostics.CodeAnalysis; namespace SlpModularCms.Modules.Offerings.Models; +/// +/// The one representation of an offering, for anonymous visitors and administrators alike. +/// DisplayOrder is informational (the array order already is the display order). +/// [ExcludeFromCodeCoverage] public record OfferingDto( string Id, @@ -12,5 +16,6 @@ public record OfferingDto( string PriceNote, IReadOnlyList Features, string CtaLabel, - bool Featured + bool Featured, + int DisplayOrder ); diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs index 1b636cb..28cc5a3 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs @@ -12,8 +12,6 @@ public interface IOfferingRepository void Update(Offering offering); Task GetMaxDisplayOrderAsync(); Task GetFeaturedAsync(); - Task GetPreviousAsync(int displayOrder); - Task GetNextAsync(int displayOrder); Task SaveChangesAsync(); Task BeginTransactionAsync(); } diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs index 7796c2f..d6de447 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs @@ -28,18 +28,6 @@ public class OfferingRepository(OfferingsDbContext context) : IOfferingRepositor public async Task GetFeaturedAsync() => await context.Offerings.FirstOrDefaultAsync(o => o.Featured); - public async Task GetPreviousAsync(int displayOrder) - => await context.Offerings - .Where(o => o.DisplayOrder < displayOrder) - .OrderByDescending(o => o.DisplayOrder) - .FirstOrDefaultAsync(); - - public async Task GetNextAsync(int displayOrder) - => await context.Offerings - .Where(o => o.DisplayOrder > displayOrder) - .OrderBy(o => o.DisplayOrder) - .FirstOrDefaultAsync(); - public async Task SaveChangesAsync() => await context.SaveChangesAsync(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/IOfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/IOfferingsService.cs index f33ed34..416369e 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/IOfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/IOfferingsService.cs @@ -4,12 +4,14 @@ namespace SlpModularCms.Modules.Offerings.Services; public interface IOfferingsService { - Task> GetPublicOfferingsAsync(); - Task> GetAllForAdminAsync(); - Task CreateAsync(CreateOfferingRequest request, Guid callerId); - Task UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId); + Task> GetOfferingsAsync(); + Task CreateAsync(CreateOfferingRequest request, Guid callerId); + Task UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId); Task DeleteAsync(Guid id, Guid callerId); + + /// + /// Sets the display order of all offerings. must contain every + /// existing offering exactly once; otherwise . + /// Task ReorderAsync(IReadOnlyList orderedIds, Guid callerId); - Task MoveUpAsync(Guid id, Guid callerId); - Task MoveDownAsync(Guid id, Guid callerId); } diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingOrderInvalidException.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingOrderInvalidException.cs new file mode 100644 index 0000000..c64f7d3 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingOrderInvalidException.cs @@ -0,0 +1,7 @@ +namespace SlpModularCms.Modules.Offerings.Services; + +/// +/// Thrown when a reorder request does not list every existing offering exactly once. +/// +public class OfferingOrderInvalidException() + : Exception("The order must list every existing offering exactly once."); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index 7d4fb1a..d1df084 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -7,19 +7,13 @@ namespace SlpModularCms.Modules.Offerings.Services; public class OfferingsService(IOfferingRepository repository, ILogger logger) : IOfferingsService { - public async Task> GetPublicOfferingsAsync() + public async Task> GetOfferingsAsync() { var offerings = await repository.GetAllAsync(); - return offerings.Select(ToPublicDto).ToList(); + return offerings.Select(ToDto).ToList(); } - public async Task> GetAllForAdminAsync() - { - var offerings = await repository.GetAllAsync(); - return offerings.Select(ToAdminDto).ToList(); - } - - public async Task CreateAsync(CreateOfferingRequest request, Guid callerId) + public async Task CreateAsync(CreateOfferingRequest request, Guid callerId) { var now = DateTimeOffset.UtcNow; var offering = new Offering @@ -61,10 +55,10 @@ public class OfferingsService(IOfferingRepository repository, ILogger UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId) + public async Task UpdateAsync(Guid id, UpdateOfferingRequest request, Guid callerId) { var offering = await repository.GetByIdAsync(id); if (offering is null) @@ -107,7 +101,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger DeleteAsync(Guid id, Guid callerId) @@ -134,15 +128,25 @@ public class OfferingsService(IOfferingRepository repository, ILogger orderedIds, Guid callerId) { + var offerings = await repository.GetAllAsync(); + + // The list must be a permutation of the existing offerings: no unknown ids, no duplicates, + // none missing. Silently skipping mismatches would leave the display order half-applied. + var existingIds = offerings.Select(o => o.Id).ToHashSet(); + if (orderedIds.Count != existingIds.Count + || orderedIds.Distinct().Count() != orderedIds.Count + || !orderedIds.All(existingIds.Contains)) + { + throw new OfferingOrderInvalidException(); + } + await using var transaction = await repository.BeginTransactionAsync(); + var byId = offerings.ToDictionary(o => o.Id); var now = DateTimeOffset.UtcNow; for (var i = 0; i < orderedIds.Count; i++) { - var offering = await repository.GetByIdAsync(orderedIds[i]); - if (offering is null) - continue; - + var offering = byId[orderedIds[i]]; offering.DisplayOrder = i; offering.UpdatedAt = now; offering.LastModifiedByUserId = callerId; @@ -157,50 +161,6 @@ public class OfferingsService(IOfferingRepository repository, ILogger new( - o.Id.ToString(), - o.Slug, - o.Title, - o.Description, - o.Price, - o.PriceNote, - o.Features, - o.CtaLabel, - o.Featured - ); - - private static OfferingAdminDto ToAdminDto(Offering o) => new( + private static OfferingDto ToDto(Offering o) => new( o.Id.ToString(), o.Slug, o.Title, -- 2.39.5 From 8bda5629ff17d9ce34655989f061f0b47626f08f Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:36:02 +0100 Subject: [PATCH 02/83] =?UTF-8?q?Aanbod:=20categorie=C3=ABn=20als=20CMS-da?= =?UTF-8?q?ta=20met=20CRUD-routes=20en=20categoryId=20op=20het=20aanbod?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nieuwe tabel OfferingsCategories (unieke naam, case-insensitief) en nullable Offering.CategoryId met FK Restrict (migratie AddOfferingCategories). Routes onder /offerings/categories zijn AdminOnly; verwijderen van een gebruikte categorie geeft 409. Het aanbod neemt categoryId (moet bestaan, anders 400) en geeft category (naam) en categoryId terug; niets wordt geseed. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u1-offerings-category/code/summary.md | 23 +++ ...offerings-category-code-generation-plan.md | 20 +-- .../OfferingCategoriesControllerTests.cs | 110 +++++++++++++ .../OfferingsControllerCategoryTests.cs | 60 +++++++ .../OfferingCategoryRepositoryTests.cs | 133 ++++++++++++++++ .../OfferingCategoriesServiceTests.cs | 148 ++++++++++++++++++ .../Services/OfferingsServiceCategoryTests.cs | 139 ++++++++++++++++ .../Services/OfferingsServiceOrderTests.cs | 2 +- .../Services/OfferingsServiceTests.cs | 2 +- .../OfferingCategoriesController.cs | 64 ++++++++ .../Controllers/OfferingsController.cs | 15 ++ .../Data/Entities/Offering.cs | 2 + .../Data/Entities/OfferingCategory.cs | 16 ++ .../Data/OfferingsDbContext.cs | 23 +++ ...09193305_AddOfferingCategories.Designer.cs | 136 ++++++++++++++++ .../20261109193305_AddOfferingCategories.cs | 75 +++++++++ .../OfferingsDbContextModelSnapshot.cs | 43 +++++ .../Models/CreateOfferingRequest.cs | 3 +- .../Models/OfferingCategoryModels.cs | 9 ++ .../Models/OfferingDto.cs | 4 +- .../Models/UpdateOfferingRequest.cs | 3 +- .../OfferingsModule.cs | 2 + .../IOfferingCategoryRepository.cs | 28 ++++ .../OfferingCategoryRepository.cs | 69 ++++++++ .../Repositories/OfferingRepository.cs | 4 +- .../Services/OfferingCategoriesService.cs | 91 +++++++++++ .../Services/OfferingCategoryExceptions.cs | 12 ++ .../Services/OfferingsService.cs | 25 ++- 29 files changed, 1243 insertions(+), 20 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index e5dab64..dca1ade 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-U0 built and committed (awaiting review); next CMS-U1 v2 +- **Current Stage**: CONSTRUCTION - CMS-U1 built and committed (awaiting review); next CMS-U1b - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md new file mode 100644 index 0000000..2c6e7f6 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u1-offerings-category/code/summary.md @@ -0,0 +1,23 @@ +# CMS-U1 offerings-category (v2, categories are CMS data): code summary + +## Data +OfferingCategory (Id, Name unique case-insensitive, SortOrder, CreatedAt, UpdatedAt) in table OfferingsCategories; Offering.CategoryId (nullable, FK Restrict) + navigation. Migration 20261109193305_AddOfferingCategories (Offerings context). Verified on a real MariaDB: applies after InitialCreate and AddOfferingSlug, unique index rejects 'websites' when 'Websites' exists, FK delete rule RESTRICT. Nothing is seeded. + +## Routes (/api/v1/offerings/categories, class AdminOnly, no anonymous action, no admin segment) +GET list {id,name,sortOrder,offeringCount}; POST {name} 201+Location (409 duplicate name); PUT {id:guid} rename (404 unknown, 409 duplicate); DELETE {id:guid} (404 unknown, 409 ProblemDetails while live offerings use it; soft-deleted offerings are released in the same transaction). +Offerings: create/update take categoryId (Guid?, must exist, else 400 errors.categoryId=["invalid"], null clears). OfferingDto gains categoryId (string|null) and category (name|null). + +## Handoff for the SLP site +GET /api/v1/offerings: category is the name or null (shape unchanged for the site); categoryId and displayOrder are additive fields that the site ignores. A rename is visible on the next request: the name is read through the FK on every query, and the code has no response or output caching. A reverse proxy cache (nginx/IIS) is outside this repo and must not cache /api/v1/offerings for longer than acceptable for renames. + +## Handoff for CMS-U1b (admin UI) +Use the four category routes above plus categoryId on offering create/update; offeringCount is in the list for the delete dialog; the 409 delete message is the ProblemDetails title. + +## Dropped from v1 +Offerings:Categories, OfferingsOptions, appsettings values, legacy-value rule, string column and its migration (v1 stays in git stash until this commit exists). + +## Verification (real output) +Build 0 errors. Offerings.Tests 84 passed; Core.Tests 196; Availability.Tests 82; Identity.Tests 37; Master.Tests 57; Api.Tests 4 passed (MariaDB container, removed afterwards). Note: Api.Tests host (SlpModularCms.Api) does not load the Offerings module; the migration was therefore verified separately with dotnet ef database update against the container. + +## Tech debt note +prettier --check reports style warnings on 15 pre-existing files in frontend/src/features/offerings (untouched, probably line endings). Not addressed in this feature. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md index 0985249..da80be9 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1-offerings-category-code-generation-plan.md @@ -24,16 +24,16 @@ Route `categories` cannot clash with `{id:guid}` on `/offerings`. Ordering/reord - 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). +- [x] **Step 1 β€” Revert v1 leftovers**: confirm the working tree only contains CMS-U0 (stash holds v1); delete nothing committed. +- [x] **Step 2 β€” Entities + DbContext**: `OfferingCategory`, `Offering.CategoryId` + navigation, mapping, unique index, FK Restrict; `Include` the category in `OfferingRepository` reads. +- [x] **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`. +- [x] **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`. +- [x] **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. +- [x] **Step 6 β€” Migration** `AddOfferingCategories`. +- [x] **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). +- [x] **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. +- [x] **Step 9 β€” Docs/handoff**: summary + handoff note for the SLS frontend (public `category` = name|null; additive `categoryId`) and for CMS-U1b (route list above). +- [x] **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). diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs new file mode 100644 index 0000000..45f51a6 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingCategoriesControllerTests.cs @@ -0,0 +1,110 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Offerings.Controllers; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingCategoriesControllerTests +{ + private readonly IOfferingCategoriesService _service = Substitute.For(); + + private OfferingCategoriesController CreateSut() => new(_service); + + private static OfferingCategoryDto Dto(string name = "Websites") + => new(Guid.NewGuid().ToString(), name, 0, 0); + + [Fact] + public async Task List_Returns200() + { + _service.ListAsync().Returns([Dto()]); + + var result = await CreateSut().List(); + + result.Should().BeOfType().Which.StatusCode.Should().Be(200); + } + + [Fact] + public async Task Create_Returns201_WithLocation() + { + var dto = Dto(); + _service.CreateAsync("Websites").Returns(dto); + + var result = await CreateSut().Create(new OfferingCategoryRequest("Websites")); + + var created = result.Should().BeOfType().Subject; + created.Location.Should().Be($"/api/v1/offerings/categories/{dto.Id}"); + } + + [Fact] + public async Task Create_Returns409_WhenTheNameIsTaken() + { + _service.CreateAsync(Arg.Any()).ThrowsAsync(new OfferingCategoryNameConflictException("Websites")); + + var result = await CreateSut().Create(new OfferingCategoryRequest("Websites")); + + result.Should().BeOfType().Which.StatusCode.Should().Be(409); + } + + [Fact] + public async Task Rename_Returns200_404_And409() + { + var id = Guid.NewGuid(); + _service.RenameAsync(id, "Nieuw").Returns(Dto("Nieuw")); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + + _service.RenameAsync(id, "Nieuw").Returns((OfferingCategoryDto?)null); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + + _service.RenameAsync(id, "Nieuw").ThrowsAsync(new OfferingCategoryNameConflictException("Nieuw")); + (await CreateSut().Rename(id, new OfferingCategoryRequest("Nieuw"))) + .Should().BeOfType(); + } + + [Fact] + public async Task Delete_Returns204_404_And409WhenInUse() + { + var id = Guid.NewGuid(); + _service.DeleteAsync(id).Returns(true); + (await CreateSut().Delete(id)).Should().BeOfType(); + + _service.DeleteAsync(id).Returns(false); + (await CreateSut().Delete(id)).Should().BeOfType(); + + _service.DeleteAsync(id).ThrowsAsync(new OfferingCategoryInUseException(2)); + var conflict = await CreateSut().Delete(id); + var problem = conflict.Should().BeOfType().Subject.Value + .Should().BeOfType().Subject; + problem.Status.Should().Be(409); + problem.Title.Should().Contain("2"); + } + + [Fact] + public void EveryAction_RequiresAdminOnly_IsNeverAnonymous_AndHasNoAdminSegment() + { + var type = typeof(OfferingCategoriesController); + type.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + type.GetCustomAttribute()!.Template.Should().Be("offerings/categories"); + + var actions = type + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(m => m.GetCustomAttributes().Any()) + .ToList(); + + actions.Should().HaveCount(4); + foreach (var action in actions) + { + action.GetCustomAttribute().Should().BeNull(action.Name); + (action.GetCustomAttribute()!.Template ?? string.Empty) + .Should().NotContainEquivalentOf("admin"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs new file mode 100644 index 0000000..d0fb1ef --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsControllerCategoryTests.cs @@ -0,0 +1,60 @@ +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Offerings.Controllers; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingsControllerCategoryTests +{ + private readonly IOfferingsService _service = Substitute.For(); + + private OfferingsController CreateSut() => new(_service) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString())], "TestAuth")), + }, + }, + }; + + private static void AssertInvalidCategoryId(IActionResult result) + { + var bad = result.Should().BeOfType().Subject; + var problem = bad.Value.Should().BeOfType().Subject; + problem.Status.Should().Be(400); + problem.Errors["categoryId"].Should().Equal("invalid"); + } + + [Fact] + public async Task Create_Returns400_WithCategoryIdError_WhenTheCategoryDoesNotExist() + { + _service.CreateAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new OfferingCategoryInvalidException()); + + var result = await CreateSut().Create( + new CreateOfferingRequest("T", "D", "p", "n", ["f"], "c", CategoryId: Guid.NewGuid())); + + AssertInvalidCategoryId(result); + } + + [Fact] + public async Task Update_Returns400_WithCategoryIdError_WhenTheCategoryDoesNotExist() + { + _service.UpdateAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .ThrowsAsync(new OfferingCategoryInvalidException()); + + var result = await CreateSut().Update( + Guid.NewGuid(), new UpdateOfferingRequest("T", "D", "p", "n", ["f"], "c", CategoryId: Guid.NewGuid())); + + AssertInvalidCategoryId(result); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs new file mode 100644 index 0000000..e8052b8 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Repositories/OfferingCategoryRepositoryTests.cs @@ -0,0 +1,133 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Offerings.Data; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Repositories; + +namespace SlpModularCms.Modules.Offerings.Tests.Repositories; + +public class OfferingCategoryRepositoryTests : IDisposable +{ + private readonly OfferingsDbContext _context; + private readonly OfferingCategoryRepository _sut; + + public OfferingCategoryRepositoryTests() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options; + _context = new OfferingsDbContext(options); + _sut = new OfferingCategoryRepository(_context); + } + + public void Dispose() => _context.Dispose(); + + private static OfferingCategory Category(string name, int order) => new() + { + Id = Guid.NewGuid(), + Name = name, + SortOrder = order, + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + + private static Offering Offering(string title, Guid? categoryId, bool deleted = false) => new() + { + Id = Guid.NewGuid(), + Slug = title.ToLowerInvariant(), + Title = title, + Description = "d", + Price = "p", + PriceNote = "n", + Features = ["f"], + CtaLabel = "c", + CategoryId = categoryId, + IsDeleted = deleted, + CreatedAt = DateTimeOffset.UtcNow, + UpdatedAt = DateTimeOffset.UtcNow, + }; + + [Fact] + public async Task ListAsync_OrdersBySortOrderThenName_AndCountsOnlyLiveOfferings() + { + var onderhoud = Category("Onderhoud", 1); + var websites = Category("Websites", 0); + await _sut.AddAsync(onderhoud); + await _sut.AddAsync(websites); + _context.Offerings.AddRange( + Offering("A", websites.Id), + Offering("B", websites.Id), + Offering("Gone", websites.Id, deleted: true), + Offering("C", null)); + await _context.SaveChangesAsync(); + + var result = await _sut.ListAsync(); + + result.Select(r => (r.Category.Name, r.OfferingCount)).Should().Equal(("Websites", 2), ("Onderhoud", 0)); + } + + [Theory] + [InlineData("websites")] + [InlineData("WEBSITES")] + [InlineData("Websites")] + public async Task ExistsByNameAsync_IsCaseInsensitive(string probe) + { + await _sut.AddAsync(Category("Websites", 0)); + await _sut.SaveChangesAsync(); + + (await _sut.ExistsByNameAsync(probe)).Should().BeTrue(); + } + + [Fact] + public async Task ExistsByNameAsync_IgnoresTheCategoryBeingRenamed() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + await _sut.SaveChangesAsync(); + + (await _sut.ExistsByNameAsync("websites", excludeId: websites.Id)).Should().BeFalse(); + (await _sut.ExistsByNameAsync("Onderhoud")).Should().BeFalse(); + } + + [Fact] + public async Task GetMaxSortOrderAsync_ReturnsMinusOne_WhenEmpty_ElseTheHighest() + { + (await _sut.GetMaxSortOrderAsync()).Should().Be(-1); + + await _sut.AddAsync(Category("A", 3)); + await _sut.AddAsync(Category("B", 7)); + await _sut.SaveChangesAsync(); + + (await _sut.GetMaxSortOrderAsync()).Should().Be(7); + } + + [Fact] + public async Task ClearCategoryOnDeletedOfferingsAsync_OnlyReleasesSoftDeletedOfferings() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + var live = Offering("Live", websites.Id); + var gone = Offering("Gone", websites.Id, deleted: true); + _context.Offerings.AddRange(live, gone); + await _context.SaveChangesAsync(); + + await _sut.ClearCategoryOnDeletedOfferingsAsync(websites.Id); + await _context.SaveChangesAsync(); + _context.ChangeTracker.Clear(); + + var all = await _context.Offerings.IgnoreQueryFilters().ToListAsync(); + all.Single(o => o.Title == "Live").CategoryId.Should().Be(websites.Id); + all.Single(o => o.Title == "Gone").CategoryId.Should().BeNull(); + } + + [Fact] + public async Task CountOfferingsAsync_IgnoresSoftDeletedOfferings() + { + var websites = Category("Websites", 0); + await _sut.AddAsync(websites); + _context.Offerings.AddRange(Offering("Live", websites.Id), Offering("Gone", websites.Id, deleted: true)); + await _context.SaveChangesAsync(); + + (await _sut.CountOfferingsAsync(websites.Id)).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs new file mode 100644 index 0000000..d8a9b10 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingCategoriesServiceTests.cs @@ -0,0 +1,148 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingCategoriesServiceTests +{ + private readonly IOfferingCategoryRepository _repo = Substitute.For(); + + public OfferingCategoriesServiceTests() + { + _repo.BeginTransactionAsync().Returns(Substitute.For()); + _repo.GetMaxSortOrderAsync().Returns(-1); + } + + private OfferingCategoriesService CreateSut() + => new(_repo, Substitute.For>()); + + private static OfferingCategory Category(string name, int order = 0) => new() + { + Id = Guid.NewGuid(), + Name = name, + SortOrder = order, + }; + + [Fact] + public async Task ListAsync_ReturnsNamesInRepositoryOrder_WithCounts() + { + _repo.ListAsync().Returns([ + new CategoryWithCount(Category("Websites", 0), 2), + new CategoryWithCount(Category("Onderhoud", 1), 0), + ]); + + var result = await CreateSut().ListAsync(); + + result.Select(c => (c.Name, c.OfferingCount)).Should().Equal(("Websites", 2), ("Onderhoud", 0)); + } + + [Fact] + public async Task CreateAsync_TrimsTheName_AppendsToTheEnd_AndSaves() + { + _repo.GetMaxSortOrderAsync().Returns(4); + + var dto = await CreateSut().CreateAsync(" Websites "); + + dto.Name.Should().Be("Websites"); + dto.SortOrder.Should().Be(5); + dto.OfferingCount.Should().Be(0); + await _repo.Received(1).AddAsync(Arg.Is(c => c.Name == "Websites")); + await _repo.Received(1).SaveChangesAsync(); + } + + [Fact] + public async Task CreateAsync_Throws_AndSavesNothing_WhenTheNameIsTaken() + { + _repo.ExistsByNameAsync("Websites").Returns(true); + + var act = () => CreateSut().CreateAsync("Websites"); + + await act.Should().ThrowAsync(); + await _repo.DidNotReceive().AddAsync(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task RenameAsync_ReturnsNull_WhenUnknown() + { + _repo.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var result = await CreateSut().RenameAsync(Guid.NewGuid(), "Nieuw"); + + result.Should().BeNull(); + } + + [Fact] + public async Task RenameAsync_ChangesTheName_AndReportsTheUsage() + { + var category = Category("Oud"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(3); + + var dto = await CreateSut().RenameAsync(category.Id, " Nieuw "); + + category.Name.Should().Be("Nieuw"); + dto!.Name.Should().Be("Nieuw"); + dto.OfferingCount.Should().Be(3); + await _repo.Received(1).SaveChangesAsync(); + } + + [Fact] + public async Task RenameAsync_Throws_WhenAnotherCategoryHasTheName() + { + var category = Category("Oud"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.ExistsByNameAsync("Websites", category.Id).Returns(true); + + var act = () => CreateSut().RenameAsync(category.Id, "Websites"); + + await act.Should().ThrowAsync(); + category.Name.Should().Be("Oud"); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task DeleteAsync_ReturnsFalse_WhenUnknown() + { + _repo.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + (await CreateSut().DeleteAsync(Guid.NewGuid())).Should().BeFalse(); + } + + [Fact] + public async Task DeleteAsync_Throws_AndDeletesNothing_WhileOfferingsUseTheCategory() + { + var category = Category("Websites"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(2); + + var act = () => CreateSut().DeleteAsync(category.Id); + + await act.Should().ThrowAsync(); + _repo.DidNotReceive().Remove(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task DeleteAsync_ReleasesSoftDeletedOfferings_ThenRemovesTheCategory() + { + var category = Category("Websites"); + _repo.GetByIdAsync(category.Id).Returns(category); + _repo.CountOfferingsAsync(category.Id).Returns(0); + + var deleted = await CreateSut().DeleteAsync(category.Id); + + deleted.Should().BeTrue(); + Received.InOrder(() => + { + _repo.ClearCategoryOnDeletedOfferingsAsync(category.Id); + _repo.Remove(category); + _repo.SaveChangesAsync(); + }); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs new file mode 100644 index 0000000..8411677 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceCategoryTests.cs @@ -0,0 +1,139 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingsServiceCategoryTests +{ + private readonly IOfferingRepository _repo = Substitute.For(); + private readonly IOfferingCategoryRepository _categories = Substitute.For(); + + public OfferingsServiceCategoryTests() + { + _repo.BeginTransactionAsync().Returns(Substitute.For()); + _repo.GetMaxDisplayOrderAsync().Returns(-1); + } + + private OfferingsService CreateSut() + => new(_repo, _categories, Substitute.For>()); + + private static OfferingCategory Category(string name) => new() { Id = Guid.NewGuid(), Name = name }; + + private static CreateOfferingRequest Create(Guid? categoryId) => new( + "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", CategoryId: categoryId); + + private static UpdateOfferingRequest Update(Guid? categoryId) => new( + "Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact", CategoryId: categoryId); + + private static Offering Existing(OfferingCategory? category) => new() + { + Id = Guid.NewGuid(), + Slug = "existing", + Title = "Existing", + Description = "Description", + Price = "€ 100", + PriceNote = "per month", + Features = ["Feature 1"], + CtaLabel = "Contact", + CategoryId = category?.Id, + Category = category, + }; + + [Fact] + public async Task CreateAsync_StoresTheCategory_AndReturnsIdAndName() + { + var websites = Category("Websites"); + _categories.GetByIdAsync(websites.Id).Returns(websites); + + var dto = await CreateSut().CreateAsync(Create(websites.Id), Guid.NewGuid()); + + dto.CategoryId.Should().Be(websites.Id.ToString()); + dto.Category.Should().Be("Websites"); + await _repo.Received(1).AddAsync(Arg.Is(o => o.CategoryId == websites.Id)); + } + + [Fact] + public async Task CreateAsync_WithoutCategory_HasNullCategoryFields() + { + var dto = await CreateSut().CreateAsync(Create(null), Guid.NewGuid()); + + dto.CategoryId.Should().BeNull(); + dto.Category.Should().BeNull(); + await _categories.DidNotReceive().GetByIdAsync(Arg.Any()); + } + + [Fact] + public async Task CreateAsync_Throws_AndSavesNothing_WhenTheCategoryDoesNotExist() + { + _categories.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var act = () => CreateSut().CreateAsync(Create(Guid.NewGuid()), Guid.NewGuid()); + + await act.Should().ThrowAsync(); + await _repo.DidNotReceive().AddAsync(Arg.Any()); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task UpdateAsync_MovesTheOfferingToAnotherCategory() + { + var websites = Category("Websites"); + var onderhoud = Category("Onderhoud"); + var target = Existing(websites); + _repo.GetByIdAsync(target.Id).Returns(target); + _categories.GetByIdAsync(onderhoud.Id).Returns(onderhoud); + + var dto = await CreateSut().UpdateAsync(target.Id, Update(onderhoud.Id), Guid.NewGuid()); + + dto!.Category.Should().Be("Onderhoud"); + target.CategoryId.Should().Be(onderhoud.Id); + } + + [Fact] + public async Task UpdateAsync_ClearsTheCategory_WhenNull() + { + var target = Existing(Category("Websites")); + _repo.GetByIdAsync(target.Id).Returns(target); + + var dto = await CreateSut().UpdateAsync(target.Id, Update(null), Guid.NewGuid()); + + dto!.CategoryId.Should().BeNull(); + dto.Category.Should().BeNull(); + target.CategoryId.Should().BeNull(); + } + + [Fact] + public async Task UpdateAsync_Throws_AndChangesNothing_WhenTheCategoryDoesNotExist() + { + var websites = Category("Websites"); + var target = Existing(websites); + _repo.GetByIdAsync(target.Id).Returns(target); + _categories.GetByIdAsync(Arg.Any()).Returns((OfferingCategory?)null); + + var act = () => CreateSut().UpdateAsync(target.Id, Update(Guid.NewGuid()), Guid.NewGuid()); + + await act.Should().ThrowAsync(); + target.CategoryId.Should().Be(websites.Id); + await _repo.DidNotReceive().SaveChangesAsync(); + } + + [Fact] + public async Task GetOfferingsAsync_CarriesTheCategoryName_SoARenameShowsUpImmediately() + { + var websites = Category("Websites"); + _repo.GetAllAsync().Returns([Existing(websites)]); + var sut = CreateSut(); + + (await sut.GetOfferingsAsync())[0].Category.Should().Be("Websites"); + + websites.Name = "Webdesign"; + + (await sut.GetOfferingsAsync())[0].Category.Should().Be("Webdesign"); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs index 9fc2d87..1140bd2 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceOrderTests.cs @@ -17,7 +17,7 @@ public class OfferingsServiceOrderTests _repo.BeginTransactionAsync().Returns(Substitute.For()); } - private OfferingsService CreateSut() => new(_repo, Substitute.For>()); + private OfferingsService CreateSut() => new(_repo, Substitute.For(), Substitute.For>()); private static Offering New(int order) => new() { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index 2046fce..68689b8 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -19,7 +19,7 @@ public class OfferingsServiceTests _repo.BeginTransactionAsync().Returns(Substitute.For()); } - private OfferingsService CreateSut() => new(_repo, _logger); + private OfferingsService CreateSut() => new(_repo, Substitute.For(), _logger); private static CreateOfferingRequest CreateRequest(bool featured = false) => new( "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", featured); diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs new file mode 100644 index 0000000..1a363de --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingCategoriesController.cs @@ -0,0 +1,64 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Controllers; + +/// +/// Categories offerings can be placed in. Managed by administrators only; visitors see the +/// category name on the offerings themselves. +/// +[ApiController] +[Route("offerings/categories")] +[Authorize(Policy = "AdminOnly")] +public class OfferingCategoriesController(IOfferingCategoriesService service) : ControllerBase +{ + [HttpGet] + public async Task List() => Ok(await service.ListAsync()); + + [HttpPost] + public async Task Create([FromBody] OfferingCategoryRequest request) + { + try + { + var dto = await service.CreateAsync(request.Name); + return Created($"/api/v1/offerings/categories/{dto.Id}", dto); + } + catch (OfferingCategoryNameConflictException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + [HttpPut("{id:guid}")] + public async Task Rename(Guid id, [FromBody] OfferingCategoryRequest request) + { + try + { + var dto = await service.RenameAsync(id, request.Name); + return dto is null ? NotFound() : Ok(dto); + } + catch (OfferingCategoryNameConflictException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + { + try + { + return await service.DeleteAsync(id) ? NoContent() : NotFound(); + } + catch (OfferingCategoryInUseException ex) + { + return Conflict(Problem409(ex.Message)); + } + } + + private static ProblemDetails Problem409(string title) + => new() { Status = StatusCodes.Status409Conflict, Title = title }; +} diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs index a9750ed..8d170d4 100644 --- a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs @@ -35,6 +35,10 @@ public class OfferingsController(IOfferingsService service) : ControllerBase var dto = await service.CreateAsync(request, GetCallerId()); return Created($"/api/v1/offerings/{dto.Id}", dto); } + catch (OfferingCategoryInvalidException) + { + return InvalidCategory(); + } catch (OfferingSlugConflictException ex) { return Conflict(new ProblemDetails { Status = StatusCodes.Status409Conflict, Title = ex.Message }); @@ -49,6 +53,10 @@ public class OfferingsController(IOfferingsService service) : ControllerBase var dto = await service.UpdateAsync(id, request, GetCallerId()); return dto is null ? NotFound() : Ok(dto); } + catch (OfferingCategoryInvalidException) + { + return InvalidCategory(); + } catch (OfferingSlugConflictException ex) { return Conflict(new ProblemDetails { Status = StatusCodes.Status409Conflict, Title = ex.Message }); @@ -80,6 +88,13 @@ public class OfferingsController(IOfferingsService service) : ControllerBase } } + private IActionResult InvalidCategory() => BadRequest(new ValidationProblemDetails( + new Dictionary { ["categoryId"] = ["invalid"] }) + { + Status = StatusCodes.Status400BadRequest, + Title = "Invalid category", + }); + private Guid GetCallerId() { var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs index 0825584..12f87eb 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs @@ -11,6 +11,8 @@ public class Offering public List Features { get; set; } = []; public string CtaLabel { get; set; } = string.Empty; public bool Featured { get; set; } + public Guid? CategoryId { get; set; } + public OfferingCategory? Category { get; set; } public int DisplayOrder { get; set; } public bool IsDeleted { get; set; } public DateTimeOffset? DeletedAt { get; set; } diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs new file mode 100644 index 0000000..5052b28 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingCategory.cs @@ -0,0 +1,16 @@ +namespace SlpModularCms.Modules.Offerings.Data.Entities; + +/// +/// A category an offering can be placed in. Managed in the CMS (never seeded in code). +/// +public class OfferingCategory +{ + public Guid Id { get; set; } + + /// Display name; unique, compared case-insensitively. + public string Name { get; set; } = string.Empty; + + public int SortOrder { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs index 84444d0..d4a959e 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs @@ -8,6 +8,7 @@ namespace SlpModularCms.Modules.Offerings.Data; public class OfferingsDbContext(DbContextOptions options) : DbContext(options) { public DbSet Offerings => Set(); + public DbSet OfferingCategories => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -41,7 +42,29 @@ public class OfferingsDbContext(DbContextOptions options) : v => v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())), v => v.ToList())); + // Restrict: a category cannot be deleted while any offering still points at it. The + // service releases soft-deleted offerings first and rejects deletion while live + // offerings use the category. + entity.HasOne(e => e.Category) + .WithMany() + .HasForeignKey(e => e.CategoryId) + .OnDelete(DeleteBehavior.Restrict); + entity.HasQueryFilter(e => !e.IsDeleted); }); + + modelBuilder.Entity(entity => + { + entity.ToTable("OfferingsCategories"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.SortOrder).IsRequired(); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + + // MySQL's default collation is case-insensitive, so this also enforces + // case-insensitive uniqueness; the service checks it explicitly as well. + entity.HasIndex(e => e.Name).IsUnique(); + }); } } diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs new file mode 100644 index 0000000..9941931 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.Designer.cs @@ -0,0 +1,136 @@ +ο»Ώ// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Offerings.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + [DbContext(typeof(OfferingsDbContext))] + [Migration("20261109193305_AddOfferingCategories")] + partial class AddOfferingCategories + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CategoryId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CtaLabel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Featured") + .HasColumnType("tinyint(1)"); + + b.Property("Features") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Price") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("PriceNote") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(130) + .HasColumnType("varchar(130)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.ToTable("OfferingsOfferings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs new file mode 100644 index 0000000..b8dd6cc --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261109193305_AddOfferingCategories.cs @@ -0,0 +1,75 @@ +ο»Ώusing System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + /// + public partial class AddOfferingCategories : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "CategoryId", + table: "OfferingsOfferings", + type: "char(36)", + nullable: true); + + migrationBuilder.CreateTable( + name: "OfferingsCategories", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Name = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + SortOrder = table.Column(type: "int", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OfferingsCategories", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_OfferingsOfferings_CategoryId", + table: "OfferingsOfferings", + column: "CategoryId"); + + migrationBuilder.CreateIndex( + name: "IX_OfferingsCategories_Name", + table: "OfferingsCategories", + column: "Name", + unique: true); + + migrationBuilder.AddForeignKey( + name: "FK_OfferingsOfferings_OfferingsCategories_CategoryId", + table: "OfferingsOfferings", + column: "CategoryId", + principalTable: "OfferingsCategories", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_OfferingsOfferings_OfferingsCategories_CategoryId", + table: "OfferingsOfferings"); + + migrationBuilder.DropTable( + name: "OfferingsCategories"); + + migrationBuilder.DropIndex( + name: "IX_OfferingsOfferings_CategoryId", + table: "OfferingsOfferings"); + + migrationBuilder.DropColumn( + name: "CategoryId", + table: "OfferingsOfferings"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs index 9484838..48b2e91 100644 --- a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs @@ -25,6 +25,9 @@ namespace SlpModularCms.Modules.Offerings.Migrations .ValueGeneratedOnAdd() .HasColumnType("char(36)"); + b.Property("CategoryId") + .HasColumnType("char(36)"); + b.Property("CreatedAt") .HasColumnType("datetime"); @@ -82,8 +85,48 @@ namespace SlpModularCms.Modules.Offerings.Migrations b.HasKey("Id"); + b.HasIndex("CategoryId"); + b.ToTable("OfferingsOfferings", (string)null); }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); #pragma warning restore 612, 618 } } diff --git a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs index fcaf2e6..05d0a63 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs @@ -10,5 +10,6 @@ public record CreateOfferingRequest( [Required, FeaturesValidation] List Features, [Required, MaxLength(50)] string CtaLabel, bool Featured = false, - [MaxLength(130)] string? Slug = null + [MaxLength(130)] string? Slug = null, + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs new file mode 100644 index 0000000..3edf5f7 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingCategoryModels.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Offerings.Models; + +[ExcludeFromCodeCoverage] +public record OfferingCategoryDto(string Id, string Name, int SortOrder, int OfferingCount); + +public record OfferingCategoryRequest([Required, MaxLength(100)] string Name); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs index 13e170b..ecabd11 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs @@ -17,5 +17,7 @@ public record OfferingDto( IReadOnlyList Features, string CtaLabel, bool Featured, - int DisplayOrder + int DisplayOrder, + string? CategoryId = null, + string? Category = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs index 542d025..1daf976 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs @@ -10,5 +10,6 @@ public record UpdateOfferingRequest( [Required, FeaturesValidation] List Features, [Required, MaxLength(50)] string CtaLabel, bool Featured = false, - [MaxLength(130)] string? Slug = null + [MaxLength(130)] string? Slug = null, + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index 058975d..649b6db 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -29,6 +29,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddHttpContextAccessor(); } diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs new file mode 100644 index 0000000..ef155ee --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingCategoryRepository.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Storage; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Repositories; + +public record CategoryWithCount(OfferingCategory Category, int OfferingCount); + +public interface IOfferingCategoryRepository +{ + /// All categories ordered by sort order then name, with the number of non-deleted offerings in each. + Task> ListAsync(); + + Task GetByIdAsync(Guid id); + + /// Case-insensitive name check; skips the category being renamed. + Task ExistsByNameAsync(string name, Guid? excludeId = null); + + Task GetMaxSortOrderAsync(); + Task CountOfferingsAsync(Guid categoryId); + + /// Clears the category on soft-deleted offerings that still point to it (so the FK no longer blocks deletion). + Task ClearCategoryOnDeletedOfferingsAsync(Guid categoryId); + + Task AddAsync(OfferingCategory category); + void Remove(OfferingCategory category); + Task SaveChangesAsync(); + Task BeginTransactionAsync(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs new file mode 100644 index 0000000..6bfda37 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingCategoryRepository.cs @@ -0,0 +1,69 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using SlpModularCms.Modules.Offerings.Data; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Repositories; + +public class OfferingCategoryRepository(OfferingsDbContext context) : IOfferingCategoryRepository +{ + public async Task> ListAsync() + { + var categories = await context.OfferingCategories + .OrderBy(c => c.SortOrder) + .ThenBy(c => c.Name) + .ToListAsync(); + + // The Offering query filter already excludes soft-deleted offerings. + var counts = await context.Offerings + .Where(o => o.CategoryId != null) + .GroupBy(o => o.CategoryId!.Value) + .Select(g => new { CategoryId = g.Key, Count = g.Count() }) + .ToDictionaryAsync(x => x.CategoryId, x => x.Count); + + return categories + .Select(c => new CategoryWithCount(c, counts.GetValueOrDefault(c.Id))) + .ToList(); + } + + public async Task GetByIdAsync(Guid id) + => await context.OfferingCategories.FirstOrDefaultAsync(c => c.Id == id); + + public async Task ExistsByNameAsync(string name, Guid? excludeId = null) + { + var lowered = name.ToLower(); + return await context.OfferingCategories + .AnyAsync(c => c.Name.ToLower() == lowered && c.Id != (excludeId ?? Guid.Empty)); + } + + public async Task GetMaxSortOrderAsync() + => await context.OfferingCategories.Select(c => (int?)c.SortOrder).MaxAsync() ?? -1; + + public async Task CountOfferingsAsync(Guid categoryId) + => await context.Offerings.CountAsync(o => o.CategoryId == categoryId); + + public async Task ClearCategoryOnDeletedOfferingsAsync(Guid categoryId) + { + var deleted = await context.Offerings + .IgnoreQueryFilters() + .Where(o => o.IsDeleted && o.CategoryId == categoryId) + .ToListAsync(); + + foreach (var offering in deleted) + { + offering.CategoryId = null; + } + } + + public async Task AddAsync(OfferingCategory category) + => await context.OfferingCategories.AddAsync(category); + + public void Remove(OfferingCategory category) + => context.OfferingCategories.Remove(category); + + public async Task SaveChangesAsync() + => await context.SaveChangesAsync(); + + public async Task BeginTransactionAsync() + => await context.Database.BeginTransactionAsync(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs index d6de447..7a18382 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs @@ -8,10 +8,10 @@ namespace SlpModularCms.Modules.Offerings.Repositories; public class OfferingRepository(OfferingsDbContext context) : IOfferingRepository { public async Task> GetAllAsync() - => await context.Offerings.OrderBy(o => o.DisplayOrder).ToListAsync(); + => await context.Offerings.Include(o => o.Category).OrderBy(o => o.DisplayOrder).ToListAsync(); public async Task GetByIdAsync(Guid id) - => await context.Offerings.FirstOrDefaultAsync(o => o.Id == id); + => await context.Offerings.Include(o => o.Category).FirstOrDefaultAsync(o => o.Id == id); public async Task ExistsBySlugAsync(string slug, Guid? excludeId = null) => await context.Offerings.AnyAsync(o => o.Slug == slug && o.Id != (excludeId ?? Guid.Empty)); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs new file mode 100644 index 0000000..a5df0d2 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoriesService.cs @@ -0,0 +1,91 @@ +using Microsoft.Extensions.Logging; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; + +namespace SlpModularCms.Modules.Offerings.Services; + +public interface IOfferingCategoriesService +{ + Task> ListAsync(); + Task CreateAsync(string name); + Task RenameAsync(Guid id, string name); + Task DeleteAsync(Guid id); +} + +public class OfferingCategoriesService( + IOfferingCategoryRepository repository, + ILogger logger) : IOfferingCategoriesService +{ + public async Task> ListAsync() + { + var categories = await repository.ListAsync(); + return categories.Select(c => ToDto(c.Category, c.OfferingCount)).ToList(); + } + + public async Task CreateAsync(string name) + { + var trimmed = name.Trim(); + if (await repository.ExistsByNameAsync(trimmed)) + throw new OfferingCategoryNameConflictException(trimmed); + + var now = DateTimeOffset.UtcNow; + var category = new OfferingCategory + { + Id = Guid.NewGuid(), + Name = trimmed, + SortOrder = await repository.GetMaxSortOrderAsync() + 1, + CreatedAt = now, + UpdatedAt = now, + }; + + await repository.AddAsync(category); + await repository.SaveChangesAsync(); + + logger.LogInformation("Offering category {CategoryId} created", category.Id); + return ToDto(category, 0); + } + + public async Task RenameAsync(Guid id, string name) + { + var category = await repository.GetByIdAsync(id); + if (category is null) + return null; + + var trimmed = name.Trim(); + if (await repository.ExistsByNameAsync(trimmed, excludeId: id)) + throw new OfferingCategoryNameConflictException(trimmed); + + category.Name = trimmed; + category.UpdatedAt = DateTimeOffset.UtcNow; + await repository.SaveChangesAsync(); + + logger.LogInformation("Offering category {CategoryId} renamed", category.Id); + return ToDto(category, await repository.CountOfferingsAsync(id)); + } + + public async Task DeleteAsync(Guid id) + { + var category = await repository.GetByIdAsync(id); + if (category is null) + return false; + + var inUse = await repository.CountOfferingsAsync(id); + if (inUse > 0) + throw new OfferingCategoryInUseException(inUse); + + // Soft-deleted offerings may still point at the category; release them so the FK + // (Restrict) no longer blocks the deletion. Both steps succeed or fail together. + await using var transaction = await repository.BeginTransactionAsync(); + await repository.ClearCategoryOnDeletedOfferingsAsync(id); + repository.Remove(category); + await repository.SaveChangesAsync(); + await transaction.CommitAsync(); + + logger.LogInformation("Offering category {CategoryId} deleted", id); + return true; + } + + private static OfferingCategoryDto ToDto(OfferingCategory c, int offeringCount) + => new(c.Id.ToString(), c.Name, c.SortOrder, offeringCount); +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs new file mode 100644 index 0000000..bcfbb5a --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingCategoryExceptions.cs @@ -0,0 +1,12 @@ +namespace SlpModularCms.Modules.Offerings.Services; + +/// Thrown when an offering refers to a category that does not exist. +public class OfferingCategoryInvalidException() : Exception("The category does not exist."); + +/// Thrown when a category name is already taken (case-insensitive). +public class OfferingCategoryNameConflictException(string name) + : Exception($"A category named '{name}' already exists."); + +/// Thrown when a category that is still used by offerings is deleted. +public class OfferingCategoryInUseException(int offeringCount) + : Exception($"The category is still used by {offeringCount} offering(s). Move them to another category first."); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index d1df084..bcb5196 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -5,7 +5,10 @@ using SlpModularCms.Modules.Offerings.Repositories; namespace SlpModularCms.Modules.Offerings.Services; -public class OfferingsService(IOfferingRepository repository, ILogger logger) : IOfferingsService +public class OfferingsService( + IOfferingRepository repository, + IOfferingCategoryRepository categories, + ILogger logger) : IOfferingsService { public async Task> GetOfferingsAsync() { @@ -15,6 +18,7 @@ public class OfferingsService(IOfferingRepository repository, ILogger CreateAsync(CreateOfferingRequest request, Guid callerId) { + var category = await ResolveCategoryAsync(request.CategoryId); var now = DateTimeOffset.UtcNow; var offering = new Offering { @@ -26,6 +30,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger ResolveCategoryAsync(Guid? categoryId) + { + if (categoryId is null) + return null; + + return await categories.GetByIdAsync(categoryId.Value) + ?? throw new OfferingCategoryInvalidException(); + } + private async Task ResolveSlugAsync(string? explicitSlug, string title) => !string.IsNullOrWhiteSpace(explicitSlug) ? await ResolveExplicitSlugAsync(explicitSlug, excludeId: null) @@ -216,6 +235,8 @@ public class OfferingsService(IOfferingRepository repository, ILogger Date: Mon, 9 Nov 2026 20:45:45 +0100 Subject: [PATCH 03/83] =?UTF-8?q?Aanbod:=20categorie=C3=ABn=20beheren=20in?= =?UTF-8?q?=20een=20dialoog=20en=20categorie=20kiezen=20in=20het=20aanbodf?= =?UTF-8?q?ormulier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Knop 'CategorieΓ«n beheren' op de aanbodlijst opent een dialoog om categorieΓ«n toe te voegen, te hernoemen en te verwijderen, met Nederlandse meldingen voor een dubbele naam en een categorie die nog in gebruik is. Het formulier krijgt een keuzelijst met 'Geen categorie', de lijst toont de categorie als badge en de querykey ['offerings','list'] vervangt de oude admin-key zodat een hernoeming direct zichtbaar is. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 + .../code/summary.md | 15 + ...ings-categories-ui-code-generation-plan.md | 27 ++ .../offerings/components/CategoriesDialog.tsx | 320 ++++++++++++++++++ .../offerings/components/OfferingForm.tsx | 58 +++- .../offerings/components/OfferingRow.tsx | 12 +- .../src/features/offerings/mocks/handlers.ts | 122 ++++++- .../pages/OfferingCategories.test.tsx | 304 +++++++++++++++++ .../offerings/pages/OfferingsListPage.tsx | 20 +- .../features/offerings/schemas/offering.ts | 5 + .../src/features/offerings/services/types.ts | 13 + .../offerings/services/useCreateOffering.ts | 2 +- .../services/useCreateOfferingCategory.ts | 15 + .../offerings/services/useDeleteOffering.ts | 2 +- .../services/useDeleteOfferingCategory.ts | 14 + .../offerings/services/useMoveOffering.ts | 2 +- .../services/useOfferingCategories.ts | 12 + .../offerings/services/useOfferings.ts | 2 +- .../services/useRenameOfferingCategory.ts | 19 ++ .../offerings/services/useReorderOfferings.ts | 2 +- .../offerings/services/useUpdateOffering.ts | 2 +- frontend/src/i18n/locales/en/translation.json | 23 ++ frontend/src/i18n/locales/nl/translation.json | 23 ++ 24 files changed, 1000 insertions(+), 28 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u1b-offerings-categories-ui-code-generation-plan.md create mode 100644 frontend/src/features/offerings/components/CategoriesDialog.tsx create mode 100644 frontend/src/features/offerings/pages/OfferingCategories.test.tsx create mode 100644 frontend/src/features/offerings/services/useCreateOfferingCategory.ts create mode 100644 frontend/src/features/offerings/services/useDeleteOfferingCategory.ts create mode 100644 frontend/src/features/offerings/services/useOfferingCategories.ts create mode 100644 frontend/src/features/offerings/services/useRenameOfferingCategory.ts diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index dca1ade..6b6ddae 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-U1 built and committed (awaiting review); next CMS-U1b +- **Current Stage**: CONSTRUCTION - CMS-U1b built and committed (awaiting review); next CMS-U2 - **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 f113d36..5d8428e 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -71,3 +71,15 @@ **Context**: awaiting approval. --- + +## CMS-U1b plan + +**Timestamp**: 2026-11-09 + +**User Input**: "CMS-U1 v2 geaccepteerd ... stash mag verwijderd ... stuur het plan voor CMS-U1b" (via Redesign - SLS) + +**AI Response**: stash dropped (e5e3652); U1b plan written; approval requested. + +**Context**: Code Generation Part 1. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md new file mode 100644 index 0000000..56f1889 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md @@ -0,0 +1,15 @@ +# CMS-U1b offerings-categories-ui: code summary + +## What changed (frontend/src/features/offerings + nl/en translations only) +- Offerings list page: button "CategorieΓ«n beheren" opens CategoriesDialog (no new route). The dialog lists categories with their offering count, adds, renames (inline; Enter confirms, Escape cancels the rename and keeps the dialog open) and deletes (inline confirmation). Errors are shown in Dutch from i18n, not from the API's English titles: duplicate name (409), category in use (409, count from the list), blank/too long name (client side), network, generic. +- OfferingForm: "Categorie" select with "Geen categorie" first. Create sends categoryId or null; edit preselects; a category that no longer exists falls back to none (only judged on fresh data). +- OfferingRow: category badge; the featured toggle now sends categoryId too (PUT replaces the whole offering, so omitting it would have cleared the category). +- Query keys: ['offerings','admin'] renamed to ['offerings','list'] (there is no admin endpoint anymore); category mutations invalidate ['offerings','categories'] and, for rename/delete, ['offerings','list'], so a rename shows up in the list and form without a reload (tested). +- Mocks follow the backend (409 duplicate/in use, 404, counts, 400 invalid categoryId); no seed. The mock `PUT /offerings/order` handler is registered before `/:id` (it was shadowed by `/:id` before). + +## Notes +- Radix Select reports an empty value while its options load; the form ignores that (otherwise it wiped the preselected category). Covered by the preselect test. +- Escape during a rename is handled via DialogContent onEscapeKeyDown (Radix closes dialogs on a document listener). + +## Verification (real output) +pnpm lint: clean. npx tsc -b: clean. vitest: 42 test files, 278 tests passed (new: 18 in OfferingCategories.test.tsx: dialog 9, list 2, form 5 + schema 1... plus 1 earlier move test). New files formatted with prettier; the 15 pre-existing prettier warnings in this feature folder remain (tech debt, unchanged). diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1b-offerings-categories-ui-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1b-offerings-categories-ui-code-generation-plan.md new file mode 100644 index 0000000..5f939e7 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u1b-offerings-categories-ui-code-generation-plan.md @@ -0,0 +1,27 @@ +# Code Generation Plan β€” CMS-U1b offerings-categories-ui + +Frontend only, `frontend/src/features/offerings` (plus the two locale files). Backend routes come from CMS-U1 (commit f2ac377). Wishes from Bryan (via Redesign - SLS): no new page, part of Offerings management; a "CategorieΓ«n beheren" button opening a dialog/panel with list + add + rename + delete (409 in understandable Dutch); a "geen categorie" option in the select in the offering form. + +## Behaviour +1. **Offerings list page**: a secondary button "CategorieΓ«n beheren" next to "Aanbieding toevoegen" opens a dialog. No route change. +2. **Categories dialog** (`CategoriesDialog`): lists categories in API order with the number of offerings (e.g. "Websites Β· 2 aanbiedingen"); an input + "Toevoegen" at the bottom; each row has rename (pencil: inline input with confirm/cancel, Enter confirms, Escape cancels) and delete (trash: inline "Weet je het zeker? Verwijderen / Annuleren"). Empty state: "Nog geen categorieΓ«n. Voeg de eerste toe." Mutation errors show as an inline `role="alert"` message in the dialog. +3. **Error messages (Dutch, not taken from the English API titles)**: create/rename `409` => "Er bestaat al een categorie met de naam '{{name}}'." ; delete `409` => "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." (count from the list data); network => existing `errors.network`; other => `errors.generic`. Blank name is rejected client-side ("Vul een naam in.", max 100 characters). +4. **Offering form**: a "Categorie" select with the categories and a first option "Geen categorie" (internal value `none`, because Radix Select forbids an empty value). Create sends `categoryId: null` or the id; edit preselects the current category; if the category list is empty the select still shows only "Geen categorie". A stale/unknown `categoryId` from the server falls back to "Geen categorie". +5. **Offering row** shows the category name as a small badge when present. +6. Everything stays consistent through query invalidation: category mutations invalidate `['offerings','categories']` and `['offerings','admin']` (a rename shows in the list and form immediately). + +## Steps +- [x] **Step 1 β€” Types and schema**: `services/types.ts`: `OfferingDto` gains `categoryId?: string | null` and `category?: string | null`; `CreateOfferingRequest` gains `categoryId?: string | null`; new `OfferingCategoryDto { id, name, sortOrder, offeringCount }`. `schemas/offering.ts`: `categoryId: z.string().nullable().optional()`; new `categoryNameSchema` (trimmed, 1..100). +- [x] **Step 2 β€” Services**: `useOfferingCategories` (GET `/api/v1/offerings/categories`), `useCreateOfferingCategory` (POST), `useRenameOfferingCategory` (PUT `/{id}`), `useDeleteOfferingCategory` (DELETE `/{id}`), same pattern as the existing hooks. +- [x] **Step 3 β€” Components**: `components/CategoriesDialog.tsx` (state: editing id, delete-pending id, new name, error), reuse `Dialog`, `Button`, `Input`, `FieldError`; `OfferingForm.tsx`: category select (Radix `Select` from `components/ui/select.tsx`); `OfferingRow.tsx`: badge; `OfferingsListPage.tsx`: the button + dialog. +- [x] **Step 4 β€” i18n**: add `offerings.categories.*` and `offerings.form.categoryLabel/noCategory` to `nl` and `en` translation files (Dutch is the primary wording above; English counterparts provided). +- [x] **Step 5 β€” Mocks**: `mocks/handlers.ts`: category endpoints with the real behaviours (409 duplicate case-insensitive, 409 in use with counts from the mock offerings, 404 unknown) and offering POST/PUT accepting `categoryId` and returning `categoryId`/`category`. Seed: no categories (nothing is seeded in the real system either); tests add their own. +- [x] **Step 6 β€” Tests (Vitest + Testing Library + msw)**: dialog (empty state; add; blank name rejected; duplicate name shows the Dutch message; rename; delete unused; delete in-use shows the count message and keeps the row), form (select lists categories and "Geen categorie"; submit sends the chosen `categoryId` or `null`; edit preselects; unknown id falls back), list page (button opens the dialog; the category badge renders), schema test. +- [x] **Step 7 β€” Verification (automatic)**: `pnpm lint`, `npx tsc -b`, `pnpm test` (full suite). New files are formatted with prettier; the 15 pre-existing prettier warnings are left alone (tech debt, already reported). +- [x] **Step 8 β€” Docs and commit**: `construction/cms-u1b-offerings-categories-ui/code/summary.md`; one commit; no push. + +## Explicitly NOT touched +Backend, ASF-owned frontend areas (auth/refresh, users, theme assets), router, other features, shared UI primitives except by using them (no edits to `components/ui`). + +## Traceability +Bryan's category decision, contract Β§ 7 (v2), CMS-U1 handoff (routes, 409 semantics, `offeringCount`). diff --git a/frontend/src/features/offerings/components/CategoriesDialog.tsx b/frontend/src/features/offerings/components/CategoriesDialog.tsx new file mode 100644 index 0000000..2ebefc1 --- /dev/null +++ b/frontend/src/features/offerings/components/CategoriesDialog.tsx @@ -0,0 +1,320 @@ +import { useState, type FormEvent } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Check, Pencil, Trash2, X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; +import { categoryNameSchema } from '../schemas/offering'; +import { useOfferingCategories } from '../services/useOfferingCategories'; +import { useCreateOfferingCategory } from '../services/useCreateOfferingCategory'; +import { useRenameOfferingCategory } from '../services/useRenameOfferingCategory'; +import { useDeleteOfferingCategory } from '../services/useDeleteOfferingCategory'; +import type { OfferingCategoryDto } from '../services/types'; + +interface CategoriesDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; +} + +/** + * Manages the categories offerings can be placed in. Lives inside the Offerings management + * (opened from the list page) rather than on a page of its own. + */ +export function CategoriesDialog({ open, onOpenChange }: CategoriesDialogProps) { + const { t } = useTranslation(); + const { data: categories, isPending, isError } = useOfferingCategories(); + const createCategory = useCreateOfferingCategory(); + const renameCategory = useRenameOfferingCategory(); + const deleteCategory = useDeleteOfferingCategory(); + + const [newName, setNewName] = useState(''); + const [editingId, setEditingId] = useState(null); + const [editName, setEditName] = useState(''); + const [deletePendingId, setDeletePendingId] = useState(null); + const [error, setError] = useState(null); + + function validate(name: string): string | null { + const result = categoryNameSchema.safeParse(name); + if (result.success) return null; + return result.error.issues[0].code === 'too_big' + ? t('offerings.categories.errors.nameTooLong') + : t('offerings.categories.errors.nameRequired'); + } + + // Server rejections are translated here instead of showing the API's English titles. + function describeError(err: unknown, context: { name?: string; usedBy?: number }): string { + if (err instanceof NetworkError) return t('errors.network'); + if (err instanceof ProblemDetailsError && err.status === 409) { + return context.usedBy !== undefined + ? t('offerings.categories.errors.inUse', { count: context.usedBy }) + : t('offerings.categories.errors.duplicate', { name: context.name ?? '' }); + } + return t('errors.generic'); + } + + async function handleAdd(event: FormEvent) { + event.preventDefault(); + const trimmed = newName.trim(); + const problem = validate(trimmed); + if (problem) { + setError(problem); + return; + } + setError(null); + try { + await createCategory.mutateAsync(trimmed); + setNewName(''); + } catch (err) { + setError(describeError(err, { name: trimmed })); + } + } + + function startEdit(category: OfferingCategoryDto) { + setError(null); + setDeletePendingId(null); + setEditingId(category.id); + setEditName(category.name); + } + + function cancelEdit() { + setEditingId(null); + setError(null); + } + + async function confirmEdit(category: OfferingCategoryDto) { + const trimmed = editName.trim(); + const problem = validate(trimmed); + if (problem) { + setError(problem); + return; + } + if (trimmed === category.name) { + cancelEdit(); + return; + } + setError(null); + try { + await renameCategory.mutateAsync({ id: category.id, name: trimmed }); + setEditingId(null); + } catch (err) { + setError(describeError(err, { name: trimmed })); + } + } + + function startDelete(category: OfferingCategoryDto) { + setError(null); + setEditingId(null); + setDeletePendingId(category.id); + } + + async function confirmDelete(category: OfferingCategoryDto) { + setError(null); + try { + await deleteCategory.mutateAsync(category.id); + setDeletePendingId(null); + } catch (err) { + setDeletePendingId(null); + setError(describeError(err, { usedBy: category.offeringCount })); + } + } + + function handleOpenChange(next: boolean) { + if (!next) { + setEditingId(null); + setDeletePendingId(null); + setError(null); + setNewName(''); + } + onOpenChange(next); + } + + return ( + + { + // Escape while renaming only cancels the rename, it does not close the dialog. + if (editingId !== null) { + event.preventDefault(); + cancelEdit(); + } + }} + > + + {t('offerings.categories.title')} + + + {error !== null && ( +

+ {error} +

+ )} + + {isPending && ( +

{t('common.loading')}

+ )} + {isError &&

{t('errors.generic')}

} + + {!isPending && !isError && categories.length === 0 && ( +

+ {t('offerings.categories.emptyState')} +

+ )} + + {!isPending && !isError && categories.length > 0 && ( +
    + {categories.map((category) => ( +
  • + {editingId === category.id ? ( + <> + setEditName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault(); + void confirmEdit(category); + } else if (e.key === 'Escape') { + e.stopPropagation(); + cancelEdit(); + } + }} + /> +
    + + +
    + + ) : ( + <> +
    + + {category.name} + + + {t('offerings.categories.offeringCount', { + count: category.offeringCount, + })} + +
    + + {deletePendingId === category.id ? ( +
    + + {t('offerings.categories.deleteConfirm')} + + + +
    + ) : ( +
    + + +
    + )} + + )} +
  • + ))} +
+ )} + +
+ setNewName(e.target.value)} + /> + +
+
+
+ ); +} diff --git a/frontend/src/features/offerings/components/OfferingForm.tsx b/frontend/src/features/offerings/components/OfferingForm.tsx index 0064855..15c2a2c 100644 --- a/frontend/src/features/offerings/components/OfferingForm.tsx +++ b/frontend/src/features/offerings/components/OfferingForm.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useEffect, useState } from 'react'; import { useForm, useWatch } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { useTranslation } from 'react-i18next'; @@ -7,6 +7,8 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { FieldError } from '@/components/ui/FieldError'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { useOfferingCategories } from '../services/useOfferingCategories'; import { slugifyPreview } from '@/lib/slugify'; import { offeringFormSchema, type OfferingFormData } from '../schemas/offering'; import type { OfferingDto } from '../services/types'; @@ -39,9 +41,32 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering ctaLabel: '', featured: false, slug: '', + categoryId: null, }, }); + // Radix Select does not allow an empty value, so "no category" is the sentinel 'none' here + // and is mapped back to null for the form value. + const NO_CATEGORY = 'none'; + const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories(); + const categoryId = useWatch({ control, name: 'categoryId' }); + const selectedCategory = + categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY; + + // A category that no longer exists (deleted meanwhile) falls back to "no category" so the + // form never submits an id the API would reject. Only judged on fresh data: a cached list + // that is being refetched may still be missing a category that does exist. + useEffect(() => { + if ( + categories !== undefined && + !isFetchingCategories && + categoryId != null && + !categories.some((c) => c.id === categoryId) + ) { + setValue('categoryId', null); + } + }, [categories, isFetchingCategories, categoryId, setValue]); + // useFieldArray requires object-shaped array items β€” features is a plain string[], // so add/remove are handled directly via setValue instead. const features = useWatch({ control, name: 'features' }); @@ -177,6 +202,37 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering +
+ + +
+
{features.map((_, index) => ( diff --git a/frontend/src/features/offerings/components/OfferingRow.tsx b/frontend/src/features/offerings/components/OfferingRow.tsx index abe39ff..e620c4a 100644 --- a/frontend/src/features/offerings/components/OfferingRow.tsx +++ b/frontend/src/features/offerings/components/OfferingRow.tsx @@ -3,6 +3,7 @@ import { CSS } from '@dnd-kit/utilities'; import { useTranslation } from 'react-i18next'; import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Trash2 } from 'lucide-react'; import { Link } from '@tanstack/react-router'; +import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { TableCell, TableRow } from '@/components/ui/table'; import { useUpdateOffering } from '../services/useUpdateOffering'; @@ -45,7 +46,14 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of - {offering.title} + + {offering.title} + {offering.category && ( + + {offering.category} + + )} + {offering.price} +
+ + +
{isPending &&

{t('common.loading')}

} @@ -50,6 +62,8 @@ export function OfferingsListPage() { )} + + ; + +/** A category name as typed by an admin (already trimmed by the caller). */ +export const categoryNameSchema = z.string().min(1).max(100); diff --git a/frontend/src/features/offerings/services/types.ts b/frontend/src/features/offerings/services/types.ts index 8cea23d..c647eca 100644 --- a/frontend/src/features/offerings/services/types.ts +++ b/frontend/src/features/offerings/services/types.ts @@ -9,6 +9,10 @@ export interface OfferingDto { ctaLabel: string; featured: boolean; displayOrder: number; + /** Id of the category, or null/absent when the offering has none. */ + categoryId?: string | null; + /** Name of the category (renames show up here automatically). */ + category?: string | null; } export interface CreateOfferingRequest { @@ -21,8 +25,17 @@ export interface CreateOfferingRequest { featured: boolean; /** Omit to auto-generate from title; set to explicitly override. */ slug?: string; + /** Category id; null clears the category. */ + categoryId?: string | null; } export type UpdateOfferingRequest = CreateOfferingRequest; +export interface OfferingCategoryDto { + id: string; + name: string; + sortOrder: number; + offeringCount: number; +} + export type MoveDirection = 'up' | 'down'; diff --git a/frontend/src/features/offerings/services/useCreateOffering.ts b/frontend/src/features/offerings/services/useCreateOffering.ts index 5a3908a..049557a 100644 --- a/frontend/src/features/offerings/services/useCreateOffering.ts +++ b/frontend/src/features/offerings/services/useCreateOffering.ts @@ -9,7 +9,7 @@ export function useCreateOffering( return useMutation({ mutationFn: (data) => api.post('/api/v1/offerings', data), onSuccess: (data, variables, ...rest) => { - queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); options?.onSuccess?.(data, variables, ...rest); }, onError: options?.onError, diff --git a/frontend/src/features/offerings/services/useCreateOfferingCategory.ts b/frontend/src/features/offerings/services/useCreateOfferingCategory.ts new file mode 100644 index 0000000..7a286e5 --- /dev/null +++ b/frontend/src/features/offerings/services/useCreateOfferingCategory.ts @@ -0,0 +1,15 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/lib/api-client'; +import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories'; +import type { OfferingCategoryDto } from './types'; + +export function useCreateOfferingCategory() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (name) => + api.post('/api/v1/offerings/categories', { name }), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY }); + }, + }); +} diff --git a/frontend/src/features/offerings/services/useDeleteOffering.ts b/frontend/src/features/offerings/services/useDeleteOffering.ts index 4e2fc09..10d92d2 100644 --- a/frontend/src/features/offerings/services/useDeleteOffering.ts +++ b/frontend/src/features/offerings/services/useDeleteOffering.ts @@ -8,7 +8,7 @@ export function useDeleteOffering( return useMutation({ mutationFn: (id) => api.delete(`/api/v1/offerings/${id}`), onSuccess: (data, variables, ...rest) => { - queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); options?.onSuccess?.(data, variables, ...rest); }, onError: options?.onError, diff --git a/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts b/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts new file mode 100644 index 0000000..9d81c42 --- /dev/null +++ b/frontend/src/features/offerings/services/useDeleteOfferingCategory.ts @@ -0,0 +1,14 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/lib/api-client'; +import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories'; + +export function useDeleteOfferingCategory() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (id) => api.delete(`/api/v1/offerings/categories/${id}`), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); + }, + }); +} diff --git a/frontend/src/features/offerings/services/useMoveOffering.ts b/frontend/src/features/offerings/services/useMoveOffering.ts index 62d0e9f..642c4a5 100644 --- a/frontend/src/features/offerings/services/useMoveOffering.ts +++ b/frontend/src/features/offerings/services/useMoveOffering.ts @@ -2,7 +2,7 @@ import { useMutation, useQueryClient, type UseMutationOptions } from '@tanstack/ import { api } from '@/lib/api-client'; import type { MoveDirection, OfferingDto } from './types'; -const OFFERINGS_KEY = ['offerings', 'admin']; +const OFFERINGS_KEY = ['offerings', 'list']; /** * Moves one offering a step up or down. The API has no move endpoint (the collection is reordered diff --git a/frontend/src/features/offerings/services/useOfferingCategories.ts b/frontend/src/features/offerings/services/useOfferingCategories.ts new file mode 100644 index 0000000..1194542 --- /dev/null +++ b/frontend/src/features/offerings/services/useOfferingCategories.ts @@ -0,0 +1,12 @@ +import { useQuery } from '@tanstack/react-query'; +import { api } from '@/lib/api-client'; +import type { OfferingCategoryDto } from './types'; + +export const OFFERING_CATEGORIES_KEY = ['offerings', 'categories']; + +export function useOfferingCategories() { + return useQuery({ + queryKey: OFFERING_CATEGORIES_KEY, + queryFn: () => api.get('/api/v1/offerings/categories'), + }); +} diff --git a/frontend/src/features/offerings/services/useOfferings.ts b/frontend/src/features/offerings/services/useOfferings.ts index 5fee1e9..0a1a13b 100644 --- a/frontend/src/features/offerings/services/useOfferings.ts +++ b/frontend/src/features/offerings/services/useOfferings.ts @@ -4,7 +4,7 @@ import type { OfferingDto } from './types'; export function useOfferings() { return useQuery({ - queryKey: ['offerings', 'admin'], + queryKey: ['offerings', 'list'], queryFn: () => api.get('/api/v1/offerings'), }); } diff --git a/frontend/src/features/offerings/services/useRenameOfferingCategory.ts b/frontend/src/features/offerings/services/useRenameOfferingCategory.ts new file mode 100644 index 0000000..66d3b4c --- /dev/null +++ b/frontend/src/features/offerings/services/useRenameOfferingCategory.ts @@ -0,0 +1,19 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { api } from '@/lib/api-client'; +import { OFFERING_CATEGORIES_KEY } from './useOfferingCategories'; +import type { OfferingCategoryDto } from './types'; + +type RenameVariables = { id: string; name: string }; + +export function useRenameOfferingCategory() { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: ({ id, name }) => + api.put(`/api/v1/offerings/categories/${id}`, { name }), + onSuccess: () => { + // The category name is part of every offering that uses it, so refresh both lists. + queryClient.invalidateQueries({ queryKey: OFFERING_CATEGORIES_KEY }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); + }, + }); +} diff --git a/frontend/src/features/offerings/services/useReorderOfferings.ts b/frontend/src/features/offerings/services/useReorderOfferings.ts index 6e92f74..fa9d473 100644 --- a/frontend/src/features/offerings/services/useReorderOfferings.ts +++ b/frontend/src/features/offerings/services/useReorderOfferings.ts @@ -8,7 +8,7 @@ export function useReorderOfferings( return useMutation({ mutationFn: (orderedIds) => api.put('/api/v1/offerings/order', { orderedIds }), onSuccess: (data, variables, ...rest) => { - queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); options?.onSuccess?.(data, variables, ...rest); }, onError: options?.onError, diff --git a/frontend/src/features/offerings/services/useUpdateOffering.ts b/frontend/src/features/offerings/services/useUpdateOffering.ts index e3b0245..28690b5 100644 --- a/frontend/src/features/offerings/services/useUpdateOffering.ts +++ b/frontend/src/features/offerings/services/useUpdateOffering.ts @@ -11,7 +11,7 @@ export function useUpdateOffering( return useMutation({ mutationFn: ({ id, ...body }) => api.put(`/api/v1/offerings/${id}`, body), onSuccess: (data, variables, ...rest) => { - queryClient.invalidateQueries({ queryKey: ['offerings', 'admin'] }); + queryClient.invalidateQueries({ queryKey: ['offerings', 'list'] }); options?.onSuccess?.(data, variables, ...rest); }, onError: options?.onError, diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json index 98db0ae..4f86ac9 100644 --- a/frontend/src/i18n/locales/en/translation.json +++ b/frontend/src/i18n/locales/en/translation.json @@ -323,6 +323,27 @@ "offerings": { "title": "Offerings", "addButton": "Add Offering", + "categories": { + "manageButton": "Manage categories", + "title": "Manage categories", + "emptyState": "No categories yet. Add the first one.", + "offeringCount_one": "{{count}} offering", + "offeringCount_other": "{{count}} offerings", + "newLabel": "New category", + "addButton": "Add", + "editButton": "Rename category", + "confirmEditButton": "Confirm name", + "cancelButton": "Cancel", + "deleteButton": "Delete category", + "deleteConfirm": "Are you sure?", + "deleteConfirmButton": "Delete", + "errors": { + "nameRequired": "Enter a name.", + "nameTooLong": "The name can be at most 100 characters.", + "duplicate": "A category named '{{name}}' already exists.", + "inUse": "This category is still used by {{count}} offering(s). Move them to another category first." + } + }, "emptyState": { "heading": "No offerings yet", "description": "Add your first offering to get started." @@ -365,6 +386,8 @@ "removeFeatureButton": "Remove", "ctaLabelLabel": "Button text", "featuredLabel": "Featured", + "categoryLabel": "Category", + "noCategory": "No category", "submitButton": "Save", "successToast": "Offering saved successfully" } diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json index fa2c9df..3edb0eb 100644 --- a/frontend/src/i18n/locales/nl/translation.json +++ b/frontend/src/i18n/locales/nl/translation.json @@ -323,6 +323,27 @@ "offerings": { "title": "Aanbiedingen", "addButton": "Aanbieding toevoegen", + "categories": { + "manageButton": "CategorieΓ«n beheren", + "title": "CategorieΓ«n beheren", + "emptyState": "Nog geen categorieΓ«n. Voeg de eerste toe.", + "offeringCount_one": "{{count}} aanbieding", + "offeringCount_other": "{{count}} aanbiedingen", + "newLabel": "Nieuwe categorie", + "addButton": "Toevoegen", + "editButton": "Categorie hernoemen", + "confirmEditButton": "Naam bevestigen", + "cancelButton": "Annuleren", + "deleteButton": "Categorie verwijderen", + "deleteConfirm": "Weet je het zeker?", + "deleteConfirmButton": "Verwijderen", + "errors": { + "nameRequired": "Vul een naam in.", + "nameTooLong": "De naam mag maximaal 100 tekens bevatten.", + "duplicate": "Er bestaat al een categorie met de naam '{{name}}'.", + "inUse": "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." + } + }, "emptyState": { "heading": "Nog geen aanbiedingen", "description": "Voeg je eerste aanbieding toe om te beginnen." @@ -365,6 +386,8 @@ "removeFeatureButton": "Verwijderen", "ctaLabelLabel": "Knoptekst", "featuredLabel": "Uitgelicht", + "categoryLabel": "Categorie", + "noCategory": "Geen categorie", "submitButton": "Opslaan", "successToast": "Aanbieding succesvol opgeslagen" } -- 2.39.5 From c3c8bcfd5e76010eacc389ed71e35605f24ceed3 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:47:19 +0100 Subject: [PATCH 04/83] Docs: plan CMS-U2 en correctie testtelling in samenvatting CMS-U1b Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 +++++++ .../code/summary.md | 2 +- ...2-gate-and-limiter-code-generation-plan.md | 36 +++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 6b6ddae..e7a7b23 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-U1b built and committed (awaiting review); next CMS-U2 +- **Current Stage**: CONSTRUCTION - CMS-U2 Code Generation Part 1 (plan 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 5d8428e..6d15f96 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -83,3 +83,15 @@ **Context**: Code Generation Part 1. --- + +## CMS-U1b done, CMS-U2 plan + +**Timestamp**: 2026-11-09 + +**User Input**: "CMS-U1b goedgekeurd ... Daarna: CMS-U2; stuur het plan." (via Redesign - SLS) + +**AI Response**: U1b committed (20f4c3c); U2 plan written; approval requested. + +**Context**: Code Generation Part 1. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md index 56f1889..0d8c57f 100644 --- a/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u1b-offerings-categories-ui/code/summary.md @@ -12,4 +12,4 @@ - Escape during a rename is handled via DialogContent onEscapeKeyDown (Radix closes dialogs on a document listener). ## Verification (real output) -pnpm lint: clean. npx tsc -b: clean. vitest: 42 test files, 278 tests passed (new: 18 in OfferingCategories.test.tsx: dialog 9, list 2, form 5 + schema 1... plus 1 earlier move test). New files formatted with prettier; the 15 pre-existing prettier warnings in this feature folder remain (tech debt, unchanged). +pnpm lint: clean. npx tsc -b: clean. vitest: 42 test files, 278 tests passed (new: 18 in OfferingCategories.test.tsx = dialog 10, list 2, form 5, schema 1). New files formatted with prettier; the 15 pre-existing prettier warnings in this feature folder remain (tech debt, unchanged). diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md new file mode 100644 index 0000000..3ad4fc0 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md @@ -0,0 +1,36 @@ +# Code Generation Plan β€” CMS-U2 gate-and-limiter + +Phase 1, base: current branch (master `d9cc539` + CMS-U0/U1/U1b). Decisions: D6 (the availability gate blocks only the CMS/admin; public site endpoints stay reachable), D9 (marker attribute, deny-by-default), FR-B1 (429 with `Retry-After` and ProblemDetails), SLS remarks (route-table style test: the marker only on the three allowed public routes; every other endpoint stays behind the gate). Keep the diffs in `AvailabilityMiddleware` and the rate-limiter file minimal (R3: both are files the ASF session also changes). + +## Findings on master that shape the plan +- `AddCmsRateLimiting` (Core/Hosting/ServiceCollectionExtensions.cs): `OnRejected` currently only logs a security event; no body, no `Retry-After`. Policies are plain `AddFixedWindowLimiter/AddSlidingWindowLimiter` (login, refresh, Sentry tunnel, offerings-public). `UseRateLimiter` runs before `UseCors` and the module middleware. +- `AvailabilityMiddleware` is registered by the module via `UseMiddleware` after the implicit `UseRouting`, so `context.GetEndpoint()` is available there (the rate limiter already relies on endpoint metadata the same way). +- Master has no `ClientPartitionKey` and no `Contact` module yet; the contact routes join the allowlist in CMS-U3. The 3 public routes of the decision are: `GET /offerings` (exists now), `GET /contact-messages/token` and `POST /contact-messages` (CMS-U3). + +## Behaviour +1. **429 response (all existing and future policies)**: status 429, header `Retry-After: ` taken from the limiter lease (`MetadataName.RetryAfter`), falling back to 60 s when the lease does not report one; body `application/problem+json` `{ type: "https://www.rfc-editor.org/rfc/rfc6585#section-4", title: "Too many requests", status: 429 }`. The security event call stays exactly as it is. Policy numbers are not changed. +2. **Marker** `[PublicSiteEndpoint]` (sealed attribute, `AttributeTargets.Method`, in `SlpModularCms.Core.Availability`): an endpoint carrying it is let through `AvailabilityMiddleware` before the master/local gate is evaluated. Everything else stays deny-by-default, including all admin routes. Existing prefix bypasses (`/api/v1/Availability/status`, Auth, Setup/status, master, SlaveStatus, `/health`) and the verified-admin-token bypass are untouched. +3. **Marked now**: only `OfferingsController.GetOfferings`. (U3 adds the two contact routes.) + +## Steps +- [ ] **Step 1 β€” Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`. +- [ ] **Step 2 β€” Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change. +- [ ] **Step 3 β€” OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON. +- [ ] **Step 4 β€” Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module). +- [ ] **Step 5 β€” Tests**: + - Core.Tests: `OnRejected` (resolved from `IOptions` after `AddCmsRateLimiting`, called with a fake lease): sets `Retry-After` rounded up from the lease value (e.g. 0.2 s -> 1, 61.5 s -> 62), falls back to 60 without lease metadata, writes `application/problem+json` with status 429, still logs the security event with policy name and path, status code is 429. + - Api.Tests (existing real-pipeline test `Sentry_tunnel_rate_limiter_engages_after_the_configured_permit_limit`): additionally assert the `Retry-After` header and the problem+json content type on the 429 (needs the local database; run with the container). + - Availability.Tests (middleware): marked endpoint passes while the system is disabled, in maintenance, and with the master gate closed; an unmarked endpoint with the same state still gets 503; a marked endpoint does not bypass anything else (a request without endpoint metadata is still blocked); `/api/v1/Availability/status` stays open. + - Availability.Tests (route-table style, SLS request): reflection over the controllers of the referenced modules (Availability, Identity, Master, Offerings; test-only project references): (a) the set of actions carrying the marker is exactly `{ OfferingsController.GetOfferings }` (the test names the allowlist so CMS-U3 extends it deliberately); (b) for every other controller action the middleware, given an endpoint with that action's attributes and a closed gate, answers 503 β€” which covers all admin routes, and the marker is never on an `AdminOnly`/`[Authorize]` action. + - Offerings.Tests: `GetOfferings` has the marker and `[AllowAnonymous]`; no other action of the controller has the marker. +- [ ] **Step 6 β€” Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output. +- [ ] **Step 7 β€” Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push. + +## Explicitly NOT touched +Policy numbers and partitioning (no `ClientPartitionKey` here; that is the ASF branch), ForwardedHeaders, host config, Email, Identity, Master, bypass-prefix list, other controllers' routes, `POST admin/status` (CMS-U7, phase 2). + +## Rebase notes (for after the ASF merge) +Expected conflicts: `AvailabilityMiddleware.cs` and `AddCmsRateLimiting`; both edits are small and isolated (one block each), so they should merge by hand without redesign. Re-run the marker/route-table tests after the rebase. + +## Traceability +D6, D9, FR-B1/B2, requirements R3; Security Baseline: deny-by-default, no information leak in the 429 body, no PII. -- 2.39.5 From a58374abeba96fb1b6aea108aad1471377903e57 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:53:15 +0100 Subject: [PATCH 05/83] Beschikbaarheidspoort laat publieke site-endpoints door en 429 geeft Retry-After met ProblemDetails Nieuwe marker [PublicSiteEndpoint] (deny-by-default): alleen GET /offerings blijft bereikbaar als het CMS uit staat of in onderhoud is; alle andere acties, adminroutes inbegrepen, blijven 503. OnRejected zet Retry-After en schrijft application/problem+json met alleen type, title en status. Op master zijn de limiet-policies nog globale buckets: de contactroutes mogen pas live na de per-client-partitionering van de ASF-branch. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u2-gate-and-limiter/code/summary.md | 18 ++ ...2-gate-and-limiter-code-generation-plan.md | 14 +- src/SlpModularCms.Api.Tests/PipelineTests.cs | 10 + .../Hosting/RateLimiterOnRejectedTests.cs | 152 +++++++++++ .../PublicSiteEndpointAttribute.cs | 15 ++ .../Hosting/ServiceCollectionExtensions.cs | 17 +- .../PublicSiteEndpointGateTests.cs | 241 ++++++++++++++++++ ...dularCms.Modules.Availability.Tests.csproj | 8 + .../Middleware/AvailabilityMiddleware.cs | 9 + .../Controllers/OfferingsPublicMarkerTests.cs | 32 +++ .../Controllers/OfferingsController.cs | 2 + 12 files changed, 510 insertions(+), 10 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md create mode 100644 src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs create mode 100644 src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs create mode 100644 src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index e7a7b23..674a488 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-U2 Code Generation Part 1 (plan awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U2 built and committed (awaiting review); next CMS-U3 plan - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md new file mode 100644 index 0000000..024ca54 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u2-gate-and-limiter/code/summary.md @@ -0,0 +1,18 @@ +# CMS-U2 gate-and-limiter: code summary + +## What changed +- `Core/Availability/PublicSiteEndpointAttribute` (sealed, methods only). `AvailabilityMiddleware`: right after the prefix bypass, an endpoint whose metadata carries the marker is let through before the master/local gate (deny-by-default; prefix bypasses and the verified-admin bypass untouched). Marked now: `OfferingsController.GetOfferings` only. +- `AddCmsRateLimiting.OnRejected`: still logs the security event, now also sets `Retry-After` (whole seconds, rounded up, minimum 1, from the limiter lease; 60 when the lease reports none) and writes `application/problem+json` with only `type`, `title`, `status`. Policy numbers and bucket behaviour are unchanged. + +## RELEASE CONDITION (must be met before the contact routes go live) +On the base branch (master) the rate-limit policies are **global buckets**: there is no per-client partition key and no ForwardedHeaders handling (both exist only on the ASF branch `feature/identity-email-notifications`). Any per-IP policy added in CMS-U3 (ContactForm 5 per 10 minutes, ContactToken 20 per 10 minutes, ContactResend) would therefore be shared by all visitors: after five submissions the whole site would be blocked. **The contact routes must not be enabled on a public host before the per-client partitioning from the ASF branch is on the base branch (after the ASF merge and the rebase).** Also required on that host: `ForwardedHeaders:KnownProxies` (env). Recorded in contract Β§ 4.5 and repeated in the CMS-U3 plan. + +## Verification (real output) +- Build: 0 errors. Tests: Core.Tests 205 passed (9 new in RateLimiterOnRejectedTests: Retry-After rounding, fallback 60, problem+json with exactly type/title/status, no leak of policy name/path/limiter terms, only `Retry-After` and `Content-Type` headers, security event logged once, 429 status), Availability.Tests 95 passed (13 new in PublicSiteEndpointGateTests: marked endpoint passes for CMS disabled / maintenance / master blocks; unmarked, and no endpoint, still 503; Availability/status open; route table: marker on exactly `OfferingsController.GetOfferings`, marked actions are anonymous and never `[Authorize]`, every other action of the Availability/Identity/Master/Offerings/System controllers answers 503 at a closed gate, and the only action that passes is `GetOfferings`), Offerings.Tests 86 passed (2 new marker tests), Identity.Tests 37, Master.Tests 57, Api.Tests 4 passed with a temporary MariaDB (the existing Sentry-tunnel limiter test now also asserts Retry-After, `application/problem+json` and the three-field body). +- Real pipeline smoke (SlpSoftware host against the temporary MariaDB, CMS state set via the AvailabilityState table): with the CMS **disabled** `GET /api/v1/offerings` 200, `GET /api/v1/offerings/categories` 503, `GET /api/v1/System/capabilities` 503, `GET /api/v1/Availability/status` 200, unauthenticated `PUT /api/v1/offerings/order` 503; in **maintenance** offerings 200 and capabilities 503. The host was stopped and the container removed afterwards. + +## Handoff +Public site endpoints stay reachable when the CMS is off or in maintenance; the frontend 503 fallback now only applies to admin calls. Extending the public set is deliberate: add the action to `AllowedPublicActions` in `PublicSiteEndpointGateTests` in the same change (CMS-U3 adds the contact token GET and POST). + +## Rebase notes (after the ASF merge) +Expected conflicts: `AvailabilityMiddleware.cs` (one block) and `AddCmsRateLimiting` (`OnRejected`). Re-run the Core, Availability and Offerings tests and the Api.Tests after the rebase. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md index 3ad4fc0..86b92ea 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u2-gate-and-limiter-code-generation-plan.md @@ -13,18 +13,18 @@ Phase 1, base: current branch (master `d9cc539` + CMS-U0/U1/U1b). Decisions: D6 3. **Marked now**: only `OfferingsController.GetOfferings`. (U3 adds the two contact routes.) ## Steps -- [ ] **Step 1 β€” Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`. -- [ ] **Step 2 β€” Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change. -- [ ] **Step 3 β€” OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON. -- [ ] **Step 4 β€” Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module). -- [ ] **Step 5 β€” Tests**: +- [x] **Step 1 β€” Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`. +- [x] **Step 2 β€” Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change. +- [x] **Step 3 β€” OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON. +- [x] **Step 4 β€” Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module). +- [x] **Step 5 β€” Tests**: - Core.Tests: `OnRejected` (resolved from `IOptions` after `AddCmsRateLimiting`, called with a fake lease): sets `Retry-After` rounded up from the lease value (e.g. 0.2 s -> 1, 61.5 s -> 62), falls back to 60 without lease metadata, writes `application/problem+json` with status 429, still logs the security event with policy name and path, status code is 429. - Api.Tests (existing real-pipeline test `Sentry_tunnel_rate_limiter_engages_after_the_configured_permit_limit`): additionally assert the `Retry-After` header and the problem+json content type on the 429 (needs the local database; run with the container). - Availability.Tests (middleware): marked endpoint passes while the system is disabled, in maintenance, and with the master gate closed; an unmarked endpoint with the same state still gets 503; a marked endpoint does not bypass anything else (a request without endpoint metadata is still blocked); `/api/v1/Availability/status` stays open. - Availability.Tests (route-table style, SLS request): reflection over the controllers of the referenced modules (Availability, Identity, Master, Offerings; test-only project references): (a) the set of actions carrying the marker is exactly `{ OfferingsController.GetOfferings }` (the test names the allowlist so CMS-U3 extends it deliberately); (b) for every other controller action the middleware, given an endpoint with that action's attributes and a closed gate, answers 503 β€” which covers all admin routes, and the marker is never on an `AdminOnly`/`[Authorize]` action. - Offerings.Tests: `GetOfferings` has the marker and `[AllowAnonymous]`; no other action of the controller has the marker. -- [ ] **Step 6 β€” Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output. -- [ ] **Step 7 β€” Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push. +- [x] **Step 6 β€” Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output. +- [x] **Step 7 β€” Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push. ## Explicitly NOT touched Policy numbers and partitioning (no `ClientPartitionKey` here; that is the ASF branch), ForwardedHeaders, host config, Email, Identity, Master, bypass-prefix list, other controllers' routes, `POST admin/status` (CMS-U7, phase 2). diff --git a/src/SlpModularCms.Api.Tests/PipelineTests.cs b/src/SlpModularCms.Api.Tests/PipelineTests.cs index 5b9e182..ddeb709 100644 --- a/src/SlpModularCms.Api.Tests/PipelineTests.cs +++ b/src/SlpModularCms.Api.Tests/PipelineTests.cs @@ -102,5 +102,15 @@ public class PipelineTests : IClassFixture // request instead, which would otherwise mask a rate limiter that silently stopped // engaging). last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + + // The rejection tells the client when to retry and carries a machine-readable body with + // only the standard fields (nothing about the limiter, the policy or the caller). + last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); + int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1); + last.Content.Headers.ContentType?.MediaType.Should().Be("application/problem+json"); + var body = await last.Content.ReadAsStringAsync(); + using var json = System.Text.Json.JsonDocument.Parse(body); + json.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]); + json.RootElement.GetProperty("status").GetInt32().Should().Be(429); } } diff --git a/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs b/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs new file mode 100644 index 0000000..db6c6f0 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Hosting/RateLimiterOnRejectedTests.cs @@ -0,0 +1,152 @@ +using System.Text.Json; +using System.Threading.RateLimiting; +using FluentAssertions; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Observability; +using Xunit; + +namespace SlpModularCms.Core.Tests.Hosting; + +/// +/// The 429 response of every rate-limit policy: a retry hint and a machine-readable body, and +/// nothing about the limiter or the caller. +/// +public class RateLimiterOnRejectedTests +{ + private sealed class TestLease(TimeSpan? retryAfter) : RateLimitLease + { + public override bool IsAcquired => false; + public override IEnumerable MetadataNames => + retryAfter is null ? [] : [MetadataName.RetryAfter.Name]; + + public override bool TryGetMetadata(string metadataName, out object? metadata) + { + if (retryAfter is not null && metadataName == MetadataName.RetryAfter.Name) + { + metadata = retryAfter.Value; + return true; + } + + metadata = null; + return false; + } + } + + private sealed class CapturingLoggerProvider : ILoggerProvider + { + public List<(EventId EventId, string Message)> Entries { get; } = []; + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(Entries); + public void Dispose() { } + + private sealed class CapturingLogger(List<(EventId, string)> entries) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) => entries.Add((eventId, formatter(state, exception))); + } + } + + private static async Task<(HttpContext Context, string Body, CapturingLoggerProvider Logs)> RejectAsync( + TimeSpan? retryAfter, string policy = "login") + { + var logs = new CapturingLoggerProvider(); + var services = new ServiceCollection(); + services.AddLogging(b => b.AddProvider(logs)); + services.AddCmsRateLimiting(new ConfigurationBuilder().Build()); + var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().Value; + + var context = new DefaultHttpContext { RequestServices = provider }; + context.Request.Path = "/api/v1/Auth/login"; + context.Response.Body = new MemoryStream(); + context.SetEndpoint(new Endpoint( + _ => Task.CompletedTask, + new EndpointMetadataCollection(new EnableRateLimitingAttribute(policy)), + "test")); + + await options.OnRejected!( + new OnRejectedContext { HttpContext = context, Lease = new TestLease(retryAfter) }, + CancellationToken.None); + + context.Response.Body.Position = 0; + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + return (context, body, logs); + } + + [Fact] + public void RejectionStatusCode_Is429() + { + var provider = new ServiceCollection() + .AddLogging() + .AddCmsRateLimiting(new ConfigurationBuilder().Build()) + .BuildServiceProvider(); + + provider.GetRequiredService>().Value.RejectionStatusCode + .Should().Be(StatusCodes.Status429TooManyRequests); + } + + [Theory] + [InlineData(0.2, "1")] + [InlineData(1.0, "1")] + [InlineData(59.01, "60")] + [InlineData(61.5, "62")] + public async Task OnRejected_SetsRetryAfter_InWholeSecondsRoundedUp(double seconds, string expected) + { + var (context, _, _) = await RejectAsync(TimeSpan.FromSeconds(seconds)); + + context.Response.Headers.RetryAfter.ToString().Should().Be(expected); + } + + [Fact] + public async Task OnRejected_FallsBackTo60Seconds_WhenTheLeaseReportsNoWait() + { + var (context, _, _) = await RejectAsync(retryAfter: null); + + context.Response.Headers.RetryAfter.ToString().Should().Be("60"); + } + + [Fact] + public async Task OnRejected_WritesProblemJson_WithOnlyTypeTitleAndStatus() + { + var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30)); + + context.Response.ContentType.Should().StartWith("application/problem+json"); + using var json = JsonDocument.Parse(body); + json.RootElement.EnumerateObject().Select(p => p.Name) + .Should().BeEquivalentTo(["type", "title", "status"]); + json.RootElement.GetProperty("status").GetInt32().Should().Be(429); + json.RootElement.GetProperty("title").GetString().Should().Be("Too many requests"); + } + + [Fact] + public async Task OnRejected_DoesNotLeakThePolicyPathOrTheLimiterInTheResponse() + { + var (context, body, _) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "super-secret-policy"); + + body.Should().NotContain("super-secret-policy"); + body.Should().NotContain("/api/v1/Auth/login"); + body.ToLowerInvariant().Should().NotContain("permit").And.NotContain("window").And.NotContain("lease"); + context.Response.Headers.Keys.Should().BeEquivalentTo(["Retry-After", "Content-Type"]); + } + + [Fact] + public async Task OnRejected_StillLogsTheRateLimitSecurityEvent_ExactlyOnce() + { + // The message template is deliberately constant (see SecurityEventsTests); the policy and + // path travel as structured properties, so only the event id is asserted here. + var (_, _, logs) = await RejectAsync(TimeSpan.FromSeconds(30), policy: "login"); + + logs.Entries.Count(e => e.EventId.Id == SecurityEvents.RateLimitTriggeredEventId).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs new file mode 100644 index 0000000..b63669a --- /dev/null +++ b/src/SlpModularCms.Core/Availability/PublicSiteEndpointAttribute.cs @@ -0,0 +1,15 @@ +namespace SlpModularCms.Core.Availability; + +/// +/// Marks an endpoint as public site functionality that stays reachable while the CMS is +/// switched off, in maintenance or blocked by the master. +/// +/// +/// The availability statuses exist to stop the CMS (changing data and settings through the +/// admin). Visitors of the public website must keep working, so the few endpoints the website +/// itself calls carry this marker. The gate is deny-by-default: an endpoint without the marker +/// is blocked, and the marker must never be placed on an endpoint that requires authorization. +/// It is read from the endpoint metadata by AvailabilityMiddleware. +/// +[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] +public sealed class PublicSiteEndpointAttribute : Attribute; diff --git a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs index ee4b76b..6f82dc7 100644 --- a/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs @@ -171,7 +171,7 @@ public static class ServiceCollectionExtensions // Without this callback a brute-force attempt against /api/v1/Auth/login returns 429 // and leaves NO trace anywhere β€” the one rate limiter this application has would be // entirely unobservable, and the alert rule for it could never fire. - options.OnRejected = (context, _) => + options.OnRejected = async (context, cancellationToken) => { var logger = context.HttpContext.RequestServices .GetRequiredService() @@ -202,11 +202,24 @@ public static class ServiceCollectionExtensions var window = configuration.GetValue($"RateLimiting:{section}:WindowSeconds", 60); waitSeconds = policyName == "refresh" ? window / 4.0 : window; } + // Every 429 carries a retry hint, also for policies that report no wait (the contact and offerings policies). + waitSeconds ??= 60; if (waitSeconds is not null) context.HttpContext.Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(waitSeconds.Value)).ToString(System.Globalization.CultureInfo.InvariantCulture); - return ValueTask.CompletedTask; + + // Machine-readable body with only the standard type/title/status: nothing about the limiter, the policy or the caller. + await context.HttpContext.Response.WriteAsJsonAsync( + new Microsoft.AspNetCore.Mvc.ProblemDetails + { + Type = "https://www.rfc-editor.org/rfc/rfc6585#section-4", + Title = "Too many requests", + Status = StatusCodes.Status429TooManyRequests, + }, + options: null, + contentType: "application/problem+json", + cancellationToken: cancellationToken); }; // Every named policy is partitioned per client address (ClientPartitionKey). Behind a diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs new file mode 100644 index 0000000..851d37c --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -0,0 +1,241 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Security; +using SlpModularCms.Core.Observability; +using SlpModularCms.Modules.Availability.Controllers; +using SlpModularCms.Modules.Availability.Middleware; +using SlpModularCms.Modules.Availability.Services; +using SlpModularCms.Modules.Identity.Controllers; +using SlpModularCms.Modules.Master.Controllers; +using SlpModularCms.Modules.Offerings.Controllers; +using Xunit; + +namespace SlpModularCms.Modules.Availability.Tests; + +/// +/// The availability statuses stop the CMS only. These tests pin down which endpoints stay +/// reachable behind a closed gate (deny-by-default, marker per action) and prove that every +/// other endpoint, admin routes included, is still blocked. +/// +public class PublicSiteEndpointGateTests +{ + private readonly IAvailabilityService _service = Substitute.For(); + private readonly IMasterAvailabilityService _masterService = Substitute.For(); + private readonly IAdminTokenValidator _adminTokenValidator = Substitute.For(); + private readonly RequestDelegate _next = Substitute.For(); + private readonly AvailabilityMiddleware _middleware; + + public PublicSiteEndpointGateTests() + { + _middleware = new AvailabilityMiddleware( + _next, NullLogger.Instance, _adminTokenValidator); + + // No admin token on any request in these tests. + _adminTokenValidator.Validate(Arg.Any()) + .Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); + _masterService.GetMasterStatus().Returns(new MasterGateStatus(true, null)); + } + + public enum ClosedGate + { + CmsDisabled, + Maintenance, + MasterBlocks, + } + + private void CloseGate(ClosedGate gate) + { + switch (gate) + { + case ClosedGate.CmsDisabled: + _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); + break; + case ClosedGate.Maintenance: + _service.IsAvailableAsync().Returns(AvailabilityStatus.Maintenance); + break; + case ClosedGate.MasterBlocks: + _service.IsAvailableAsync().Returns(AvailabilityStatus.Available); + _masterService.GetMasterStatus().Returns(new MasterGateStatus(false, "Geblokkeerd door master")); + break; + } + } + + private async Task StatusFor(Endpoint? endpoint) + { + var context = new DefaultHttpContext(); + context.Request.Path = "/api/v1/some-resource"; + context.Response.Body = new MemoryStream(); + if (endpoint is not null) + { + context.SetEndpoint(endpoint); + } + + _next.ClearReceivedCalls(); + await _middleware.InvokeAsync(context, _service, _masterService); + + return _next.ReceivedCalls().Any() ? StatusCodes.Status200OK : context.Response.StatusCode; + } + + private static Endpoint EndpointWith(params object[] metadata) + => new(_ => Task.CompletedTask, new EndpointMetadataCollection(metadata), "test"); + + /// The metadata MVC would attach to an action: the controller's attributes, then the action's. + private static Endpoint EndpointOf(MethodInfo action) + { + var metadata = action.DeclaringType!.GetCustomAttributes(inherit: true) + .Concat(action.GetCustomAttributes(inherit: true)) + .ToArray(); + return new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(metadata), action.Name); + } + + [Theory] + [InlineData(ClosedGate.CmsDisabled)] + [InlineData(ClosedGate.Maintenance)] + [InlineData(ClosedGate.MasterBlocks)] + public async Task AMarkedEndpoint_StaysReachable_WhateverTheClosedGate(ClosedGate gate) + { + CloseGate(gate); + + (await StatusFor(EndpointWith(new PublicSiteEndpointAttribute()))).Should().Be(200); + } + + [Theory] + [InlineData(ClosedGate.CmsDisabled)] + [InlineData(ClosedGate.Maintenance)] + [InlineData(ClosedGate.MasterBlocks)] + public async Task AnUnmarkedEndpoint_IsStillBlocked(ClosedGate gate) + { + CloseGate(gate); + + (await StatusFor(EndpointWith(new AuthorizeAttribute("AdminOnly")))).Should().Be(503); + } + + [Fact] + public async Task ARequestWithoutEndpointMetadata_IsStillBlocked() + { + CloseGate(ClosedGate.CmsDisabled); + + (await StatusFor(endpoint: null)).Should().Be(503); + } + + [Fact] + public async Task TheMarkerDoesNotBlockAnything_WhenTheCmsIsAvailable() + { + _service.IsAvailableAsync().Returns(AvailabilityStatus.Available); + + (await StatusFor(EndpointWith(new PublicSiteEndpointAttribute()))).Should().Be(200); + (await StatusFor(endpoint: null)).Should().Be(200); + } + + [Fact] + public async Task TheAvailabilityStatusEndpoint_StaysOpen_BecauseOfItsPathBypass() + { + CloseGate(ClosedGate.CmsDisabled); + var context = new DefaultHttpContext(); + context.Request.Path = "/api/v1/Availability/status"; + context.Response.Body = new MemoryStream(); + + await _middleware.InvokeAsync(context, _service, _masterService); + + await _next.Received(1).Invoke(context); + } + + // ---- Route table: which actions of all modules carry the marker ---- + + /// + /// The complete list of actions that stay reachable when the CMS is off. Extending it is a + /// deliberate act: add the action here and in the code in the same change. (CMS-U3 adds the two + /// public contact routes.) + /// + private static readonly string[] AllowedPublicActions = + [ + $"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}", + ]; + + private static IReadOnlyList AllActions() => + new[] + { + typeof(AvailabilityController).Assembly, + typeof(UsersController).Assembly, + typeof(CmsInstanceController).Assembly, + typeof(OfferingsController).Assembly, + typeof(SystemController).Assembly, + } + .Distinct() + .SelectMany(a => a.GetTypes()) + .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract) + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + .Where(m => m.GetCustomAttributes().Any()) + .ToList(); + + private static string Name(MethodInfo m) => $"{m.DeclaringType!.Name}.{m.Name}"; + + [Fact] + public void TheMarkerIsOnExactlyTheAllowedPublicActions() + { + var actions = AllActions(); + actions.Count.Should().BeGreaterThan(20, "the reflection must actually find the controllers of the modules"); + + actions.Where(m => m.GetCustomAttribute() is not null) + .Select(Name) + .Should().BeEquivalentTo(AllowedPublicActions); + } + + [Fact] + public void AMarkedActionIsAnonymous_AndNeverAnAuthorizedOne() + { + foreach (var action in AllActions().Where(m => m.GetCustomAttribute() is not null)) + { + action.GetCustomAttribute() + .Should().NotBeNull($"{Name(action)} is public so it must be explicitly anonymous"); + action.GetCustomAttributes() + .Should().BeEmpty($"{Name(action)} must not require authorization"); + } + } + + [Fact] + public async Task EveryOtherAction_IncludingAllAdminRoutes_IsBlockedByAClosedGate() + { + CloseGate(ClosedGate.CmsDisabled); + var others = AllActions() + .Where(m => m.GetCustomAttribute() is null) + .ToList(); + others.Should().NotBeEmpty(); + + var reachable = new List(); + foreach (var action in others) + { + if (await StatusFor(EndpointOf(action)) != 503) + { + reachable.Add(Name(action)); + } + } + + reachable.Should().BeEmpty("only marked actions may pass a closed gate"); + } + + [Fact] + public async Task TheMarkedActions_AreTheOnlyOnesThatPassAClosedGate() + { + CloseGate(ClosedGate.Maintenance); + + var passing = new List(); + foreach (var action in AllActions()) + { + if (await StatusFor(EndpointOf(action)) == 200) + { + passing.Add(Name(action)); + } + } + + passing.Should().BeEquivalentTo(AllowedPublicActions); + } +} diff --git a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj index 9767b63..112f182 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj +++ b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj @@ -31,4 +31,12 @@ + + + + + + + \ No newline at end of file diff --git a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs index ef816d2..162e356 100644 --- a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs +++ b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs @@ -69,6 +69,15 @@ public class AvailabilityMiddleware return; } + // Public site functionality (e.g. the offerings list the website shows) stays reachable + // whatever the status: the statuses only stop the CMS. Deny-by-default: only an endpoint + // that explicitly carries the marker passes here. + if (context.GetEndpoint()?.Metadata.GetMetadata() is not null) + { + await _next(context); + return; + } + var admin = CheckAdmin(context); if (admin.IsVerifiedAdmin) { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs new file mode 100644 index 0000000..78aed46 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs @@ -0,0 +1,32 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Offerings.Controllers; + +namespace SlpModularCms.Modules.Offerings.Tests.Controllers; + +public class OfferingsPublicMarkerTests +{ + private static IEnumerable Actions() => + new[] { typeof(OfferingsController), typeof(OfferingCategoriesController) } + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)); + + [Fact] + public void GetOfferings_IsMarkedAsPublicSiteEndpoint_AndAnonymous() + { + var action = typeof(OfferingsController).GetMethod(nameof(OfferingsController.GetOfferings))!; + + action.GetCustomAttribute().Should().NotBeNull(); + action.GetCustomAttribute().Should().NotBeNull(); + } + + [Fact] + public void NoOtherOfferingsAction_CarriesTheMarker() + { + Actions() + .Where(m => m.Name != nameof(OfferingsController.GetOfferings)) + .Where(m => m.GetCustomAttribute() is not null) + .Should().BeEmpty("writes and the category management stay behind the availability gate"); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs index 8d170d4..5005b6c 100644 --- a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingsController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; +using SlpModularCms.Core.Availability; using SlpModularCms.Modules.Offerings.Models; using SlpModularCms.Modules.Offerings.Services; @@ -20,6 +21,7 @@ public class OfferingsController(IOfferingsService service) : ControllerBase { [HttpGet] [AllowAnonymous] + [PublicSiteEndpoint] [EnableRateLimiting("offerings-public")] public async Task GetOfferings() { -- 2.39.5 From 0f6f5475a1f86e127dad753b57f15337c6cf9a2c Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 20:54:29 +0100 Subject: [PATCH 06/83] Docs: plan CMS-U3 (contact-core) met release-voorwaarde en partitioneringsaanpak Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 ++++ ...ms-u3-contact-core-code-generation-plan.md | 57 +++++++++++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 674a488..6671b79 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-U2 built and committed (awaiting review); next CMS-U3 plan +- **Current Stage**: CONSTRUCTION - CMS-U3 Code Generation Part 1 (plan 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 6d15f96..390924f 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -95,3 +95,15 @@ **Context**: Code Generation Part 1. --- + +## CMS-U2 done, CMS-U3 plan + +**Timestamp**: 2026-11-09 + +**User Input**: "CMS-U2 goedgekeurd ... release-voorwaarde in summary en U3-plan; leg uit hoe ContactForm/ContactToken zich op master gedraagt en hoe dit na de rebase naar per-client schakelt; controleer dat 429 geen interne details lekt." (via Redesign - SLS) + +**AI Response**: U2 committed (9e8e8ef); U3 plan written with Contact:Enabled switch and single partition-key function; approval requested. + +**Context**: Code Generation Part 1. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md new file mode 100644 index 0000000..011584f --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md @@ -0,0 +1,57 @@ +# Code Generation Plan β€” CMS-U3 contact-core + +Phase 1, base: current branch (master + CMS-U0/U1/U1b/U2). Inputs: contract v0.3.x (Β§ 2-5), requirements D2/D3/D5, application-design Β§ 3-7 (admin routes superseded by unit-of-work: RESTful, no `/admin`), functional-design decisions below. Scope: the **public** contact endpoints and everything they need. Admin endpoints are CMS-U4, real mail is CMS-U5, OpenAPI export is split off as **CMS-U3b** (see end) to keep this unit reviewable. + +## RELEASE CONDITION (explicit, as agreed) +On master the rate-limit policies are global buckets (no per-client partition key, no ForwardedHeaders; both exist only on the ASF branch). A per-IP contact policy would then be one bucket for the whole site: five submissions would block everybody. **The contact routes must not be enabled on a public host until the per-client partitioning from the ASF branch is on the base branch.** This is enforced in code, not only documented: see `Contact:Enabled` below. + +## Rate limiting: how it behaves on master and how it switches after the rebase +- Policies `contact-form` (5 per 600 s), `contact-token` (20 per 600 s) and (CMS-U4) `contact-resend` (5 per 600 s) are registered **inside the Contact module** through `services.Configure(...)`, so the shared `AddCmsRateLimiting` file (also edited by the ASF branch) is not touched in this unit. +- Each policy is built with `RateLimitPartition.GetFixedWindowLimiter(partitionKey, ...)`, and the key comes from exactly one function in the module: `ContactRateLimitPartition.KeyFor(HttpContext)`. **On master it returns the constant `"global"`**, so the policies behave as one shared bucket per policy (the documented, known state β€” safe, because the routes are disabled by default on any host). +- **After the ASF merge and rebase**, switching to per-client is a one-line change in that single function: `return ClientPartitionKey.For(context);` (the ASF helper). No policy, controller or test is rewritten. A test pins the function: it currently asserts the constant, and the rebase commit changes that one assertion to "two different client addresses give two different keys". +- No own partitioning, forwarded-header parsing or IP handling is built here (would clash with the ASF implementation). + +## Safety switch +`Contact:Enabled` (default **false**). While false the module registers nothing active: the two contact routes answer **404** (an endpoint filter on the controller short-circuits before any work), no database access, no hosted service work (the retention job starts but does nothing), no key-ring use. Enabling is an explicit act per host (appsettings of the host or environment) and belongs to the release step after the rebase. Tests run with it enabled. The 404 body is empty (nothing revealed). The two routes still carry `[PublicSiteEndpoint]` so the gate behaviour is the same once enabled. + +## Components (see application-design Β§ 3) +`Modules.Contact` + `Modules.Contact.Tests` (solution folders Application/Modules and Tests/Modules), referenced by `Api.SlpSoftware` only (the Andrea host is not on master; the reference follows in phase 2). +- `ContactModule : IModule` ("Contact"): options, DbContext (MySQL, `NonLockingMySQLHistoryRepository`, `Database.Migrate()` in `UseModule`, same as Offerings), services, rate-limit policies, hosted service. +- `ContactDbContext`: `ContactMessage`, `IdempotencyRecord`. Migration `InitialCreate`. Tables `ContactMessages`, `ContactIdempotency`. +- `ContactMessagesController` (`[Route("contact-messages")]`, class `[AllowAnonymous]` for the two public actions only; admin actions arrive in U4 with `AdminOnly`): `GET token` (`[PublicSiteEndpoint]`, policy `contact-token`), `POST` (`[PublicSiteEndpoint]`, policy `contact-form`, `RequestSizeLimit` from `Contact:MaxBodyBytes`). +- `ContactValidator` (pure), `ContactTokenService` (`IDataProtectionProvider`, purpose `SlpModularCms.Contact.Token.{siteId}`; keys already persist in the database via `AddCmsDataProtection`), `ContactSubmissionService`, `ICaptchaVerifier` + `NullCaptchaVerifier` (Friendly Captcha implementation comes later behind the same interface; fail-open), `IContactMailSender` + `NoOpContactMailSender` (real implementation in U5), `ContactRetentionService` (daily `BackgroundService`, pattern of `IntegrityCheckBackgroundService`), `ContactOptions` (`Contact:*`, validated), `ContactRateLimitPartition`. + +## Functional design decisions (fills the contract's gaps) +1. **Validation** (pure function, trims first): name 1-100, email 1-254 + regex `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`, subject 1-100 (opaque, never checked against offerings), message 1-2000; control characters rejected in name, email, subject (newlines are allowed in message); `hpCheck` key present; `token` required. Error codes `required|tooLong|invalid|expired`; field names as in the JSON; ProblemDetails with `errors` and status 400; the `type` URI is configurable (`Contact:ProblemTypeBase`, default none => `about:blank`) so no site domain is hard-coded in a module that two sites use (open point 2). +2. **Idempotency**: header `Idempotency-Key` required, GUID (`errors.idempotencyKey: required|invalid`). Key + site id unique. A replay within 24 h returns the stored status code (always 202 for accepted requests) without a second row. A replay of a request that was *rejected* with 400 is not stored (so the client can correct and resend with the same key). The record holds only key, site, created-at, status code. +3. **Token**: `GET token` returns `{ token, minSeconds, captcha }`; token payload = issue time + site id, protected with the purpose string, lifetime `Contact:TokenLifetimeMinutes` (120). Verification outcomes: valid / too young (below `MinSeconds`) / expired-or-invalid (forged, other site, garbage, too old). +4. **Submission pipeline**: size limit -> idempotency header -> validation -> token: invalid/expired => 400 `errors.token=["expired"]` (no oracle); too young or honeypot filled or captcha rejected => **spam path**; otherwise genuine path. Spam path: store with `Status=Spam`, `RetentionUntil=now+SpamRetentionDays`, never mailed, unless the per-site daily cap (`Contact:MaxSpamRowsPerDay`, default 200) is reached (then not stored); response is the identical 202 `{ "status": "received" }`. Genuine path: store `Status=New`, `MailStatus=Pending`, `RetentionUntil=now+RetentionMonths`, then call `IContactMailSender` **after commit** and only record the outcome (U3: no-op => stays `Pending`/`NotApplicable`; U5 adds sweep + retry). +5. **Captcha**: disabled by default; when enabled and the token is missing or rejected => spam path; verifier failure (timeout/5xx) => fail-open with a log line without PII. +6. **Retention job**: daily; deletes `ContactMessages` where `RetentionUntil < now` and `IdempotencyRecords` older than 24 h; logs counts only. +7. **Site id**: `Contact:SiteId`, default = host name from `Contact:SiteId` fallback `Environment.ApplicationName`; never from the request. +8. **Privacy/logging**: no IP stored; no name/email/message/body in any log, exception or Sentry event. Findings: Sentry is configured with `MaxRequestBodySize = None` and the `SentryEventScrubber`; the plan adds (a) request logging for these routes is off, (b) a log-capture test that submits a request carrying marker strings in all fields, forces an exception in the service and asserts none of the marker strings appears in any log entry or exception message, (c) a scrubber test that a Sentry event built from such an exception has no body/field values. Model-binding errors use the custom problem shape, never echo values. +9. **Security Baseline**: allow-list validation, bounded sizes, deny-by-default gate, generic 5xx (`UseExceptionHandler` already returns ProblemDetails), no secrets in config (captcha secret via env), no oracle on token errors. + +## Configuration (`Contact:` section; defaults as in application-design Β§ 4) +`Enabled=false`, `SiteId`, `MinSeconds=3`, `TokenLifetimeMinutes=120`, `RetentionMonths=12`, `SpamRetentionDays=30`, `MaxSpamRowsPerDay=200`, `MaxBodyBytes=16384`, `HoneypotField=hpCheck`, `Captcha:{Enabled=false,Provider,SiteKey,Secret}`; `RateLimiting:ContactForm` (5/600), `RateLimiting:ContactToken` (20/600). Recipient/sender e-mail addresses are not part of U3 (U5, env-only for ASF). `appsettings.json` of `Api.SlpSoftware` gets the section with `Enabled=false`; no addresses, no secrets. + +## Steps +- [ ] **Step 1 β€” Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes. +- [ ] **Step 2 β€” Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification). +- [ ] **Step 3 β€” Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation. +- [ ] **Step 4 β€” Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service. +- [ ] **Step 5 β€” Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list). +- [ ] **Step 6 β€” Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency). +- [ ] **Step 7 β€” Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported. +- [ ] **Step 8 β€” Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push. + +## Explicitly NOT touched +`AddCmsRateLimiting`/Core hosting files, `AvailabilityMiddleware`, Email, Identity, ASF-owned areas, host Program.cs, frontend, the Andrea host. No admin endpoints (CMS-U4), no mail sending (CMS-U5), no OpenAPI export (CMS-U3b). + +## CMS-U3b (proposed separate small unit, right after U3) +Exported OpenAPI document committed as `openapi/cms-api.v1.json` with a snapshot test (`UPDATE_OPENAPI=1` rewrites; drift fails the build) and an `IOpenApiDocumentTransformer` adding the contract's reusable responses (Validation/TooLarge/RateLimited). Separate because it needs the host-level test harness and touches how the document is produced, which is unrelated to the contact logic. + +## Open points for approval +1. `Contact:Enabled=false` default with 404 (my proposal to enforce the release condition in code). OK? +2. Validation problem `type`: configurable, default `about:blank` (instead of the contract's `https://slpsoftware.nl/problems/validation`, to avoid hard-coding a site domain in a module used by two sites). The frontend maps on `errors`, not on `type`. OK? +3. Split OpenAPI export into CMS-U3b. OK? -- 2.39.5 From 7748bbe9c97c54b19b9c0ae958be8276faf1febd Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 21:08:49 +0100 Subject: [PATCH 07/83] Contactmodule: token- en inzendroute met spamafhandeling, idempotentie en retentietaak Nieuwe module SlpModularCms.Modules.Contact met eigen DbContext en migratie InitialCreate. GET contact-messages/token en POST contact-messages zijn publiek ([PublicSiteEndpoint]), geven bij echte inzendingen, spam en herhalingen hetzelfde 202 en slaan spam apart op (30 dagen, dagplafond). Standaard staat de module uit (Contact:Enabled=false, 404 met lege body, geen databasetoegang) totdat de rate limiting per client op de basisbranch staat; de rate-limit-sleutel zit in een enkele functie zodat dat later een regel wijzigen is. Mail zit achter een seam (nog een no-op). Co-Authored-By: Claude Sonnet 5.5 --- SlpModularCms.sln | 30 ++ .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u3-contact-core/code/summary.md | 55 +++ ...ms-u3-contact-core-code-generation-plan.md | 16 +- .../Program.Coverage.cs | 3 + .../SlpModularCms.Api.SlpSoftware.csproj | 1 + .../appsettings.json | 24 ++ .../PublicSiteEndpointGateTests.cs | 4 + ...dularCms.Modules.Availability.Tests.csproj | 1 + .../ContactControllerTests.cs | 292 +++++++++++++++ .../ContactNoPersonalDataInLogsTests.cs | 92 +++++ .../ContactRetentionAndPartitionTests.cs | 144 ++++++++ .../ContactSubmissionServiceTests.cs | 344 ++++++++++++++++++ .../ContactTokenServiceTests.cs | 144 ++++++++ .../ContactValidatorTests.cs | 185 ++++++++++ .../Pipeline/ContactHostFactory.cs | 113 ++++++ .../Pipeline/ContactPipelineTests.cs | 318 ++++++++++++++++ ...SlpModularCms.Modules.Contact.Tests.csproj | 39 ++ .../SubmissionHarness.cs | 97 +++++ .../Config/ContactOptions.cs | 52 +++ .../ContactModule.cs | 89 +++++ .../Controllers/ContactMessagesController.cs | 71 ++++ .../Controllers/ContactRouteFilter.cs | 63 ++++ .../Data/ContactDbContext.cs | 44 +++ .../Data/Entities/ContactMessage.cs | 58 +++ .../20261109200014_InitialCreate.Designer.cs | 115 ++++++ .../20261109200014_InitialCreate.cs | 82 +++++ .../ContactDbContextModelSnapshot.cs | 112 ++++++ .../Models/ContactModels.cs | 44 +++ .../Repositories/ContactRepository.cs | 75 ++++ .../Services/ContactFormGate.cs | 25 ++ .../Services/ContactRetentionService.cs | 58 +++ .../Services/ContactSeams.cs | 61 ++++ .../Services/ContactSubmissionService.cs | 205 +++++++++++ .../Services/ContactTokenService.cs | 83 +++++ .../Services/ContactValidator.cs | 115 ++++++ .../SlpModularCms.Modules.Contact.csproj | 19 + 37 files changed, 3266 insertions(+), 9 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md create mode 100644 src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj create mode 100644 src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs create mode 100644 src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs create mode 100644 src/SlpModularCms.Modules.Contact/ContactModule.cs create mode 100644 src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs create mode 100644 src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs create mode 100644 src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs create mode 100644 src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs create mode 100644 src/SlpModularCms.Modules.Contact/Models/ContactModels.cs create mode 100644 src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs create mode 100644 src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj diff --git a/SlpModularCms.sln b/SlpModularCms.sln index aa999db..8ca0860 100644 --- a/SlpModularCms.sln +++ b/SlpModularCms.sln @@ -42,6 +42,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlo EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -244,6 +248,30 @@ Global {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.ActiveCfg = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.Build.0 = Debug|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.Build.0 = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.ActiveCfg = Release|Any CPU + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.ActiveCfg = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.Build.0 = Debug|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.Build.0 = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.ActiveCfg = Release|Any CPU + {06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -267,5 +295,7 @@ Global {BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894} {759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899} {DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3} + {59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C} + {06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894} EndGlobalSection EndGlobal diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 6671b79..cfdeda6 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-U3 Code Generation Part 1 (plan awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U3 built and committed (awaiting review); next CMS-U3b plan, then CMS-U4 - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md new file mode 100644 index 0000000..3dd97e4 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md @@ -0,0 +1,55 @@ +# CMS-U3 contact-core: code summary + +## What it delivers +New module `SlpModularCms.Modules.Contact` (+ `.Contact.Tests`), referenced by `Api.SlpSoftware` only. + +Public routes (both anonymous, `[PublicSiteEndpoint]`, reachable while the CMS is off): +- `GET /api/v1/contact-messages/token` -> `{ token, minSeconds, captcha }` (`captcha` is null unless enabled; the secret is never returned). Rate limit policy `contact-token`. +- `POST /api/v1/contact-messages` with header `Idempotency-Key: ` and body `{ name, email, subject, message, hpCheck, token, captchaToken? }` -> `202 { "status": "received" }` for genuine messages, spam and replays alike. Policy `contact-form`. Errors: `400` (`errors` per field with codes `required|tooLong|invalid|expired`, also `idempotencyKey` and `body`), `413` (problem+json), `429` (Retry-After, problem+json), `404` empty body while the form is closed. + +Behaviour: validation (limits 100/254/100/2000, e-mail regex, control characters rejected, fields trimmed) -> replay check (same key within 24 h answers 202 without a second row; a rejected request does not use up its key) -> token (forged, other-site, garbage and expired all answer `errors.token=["expired"]`: no oracle) -> classification: too-young token (< `MinSeconds`), filled `hpCheck`, or a rejected captcha is spam -> store (genuine: `New`, mail `Pending`, retention 12 months; spam: `Spam`, mail `NotApplicable`, 30 days, per-site daily cap 200 beyond which it is answered but not stored) -> after commit the mail seam `IContactMailSender` (no-op until the mail unit: result `Skipped`, message stays `Pending`). A mail problem never fails the request. Daily retention job removes expired messages and idempotency records older than 24 h. Site id comes from configuration, never from the request; no IP address is stored. + +## RELEASE CONDITION (unchanged, now enforced in code) +On the base branch the rate-limit policies are shared buckets (no per-client key, no forwarded-header handling). The contact routes therefore stay **closed** (`Contact:Enabled=false`, 404 with empty body, no database access, retention job idle) until the per-client partitioning from the ASF branch is on the base branch. Do not enable on a public host before that. + +## Gate design (two layers, per the later decision) +Route filter `ContactRouteFilter` asks `IContactFormGate.IsOpenAsync`. Today the only layer is `HostFlagContactFormGate` (`Contact:Enabled`). CMS-U4 adds the CMS-controlled switch (`/api/v1/contact-settings`) as a second layer by replacing the registration with a composite gate; the filter is not touched. The form is active only if every layer is open; otherwise 404 empty body (the website shows its mailto fallback). + +## REBASE CHECKLIST (after the ASF merge) +1. `src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs`, class `ContactRateLimitPartition`: change the single line `public static string KeyFor(HttpContext context) => GlobalKey;` to `public static string KeyFor(HttpContext context) => ClientPartitionKey.For(context);` (add the ASF `using`). Remove the `GlobalKey` constant if it is no longer used. +2. `src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs`, test `OnTheBaseBranch_EveryCallerSharesOneBucket`: replace it with "two different client addresses give two different keys" (the same two addresses are already in the test). +3. Make sure `ForwardedHeaders:KnownProxies` is configured on the host (environment). +4. Regenerate/verify migrations only if a snapshot conflicts (Contact has its own context and history, so none is expected). Re-run all test projects. +5. Only then set `Contact:Enabled=true` on the host (environment or appsettings of that host). + +## `Contact:*` configuration (keys and defaults; `Api.SlpSoftware/appsettings.json` carries them) +| Key | Default | Notes | +|---|---|---| +| `Contact:Enabled` | `false` | host switch / release condition | +| `Contact:SiteId` | `slpsoftware` in appsettings; `default` if unset | stored on rows, bound into the token purpose; never from a request | +| `Contact:MinSeconds` | `3` | returned to the client as `minSeconds`; faster = spam | +| `Contact:TokenLifetimeMinutes` | `120` | | +| `Contact:RetentionMonths` | `12` | per row at insert; no retroactive change | +| `Contact:SpamRetentionDays` | `30` | | +| `Contact:MaxSpamRowsPerDay` | `200` | per site per UTC day | +| `Contact:MaxBodyBytes` | `16384` | 413 beyond | +| `Contact:ProblemTypeBase` | none -> `about:blank` | base for the validation problem `type` (`{base}/validation`) | +| `Contact:Captcha:Enabled` | `false` | | +| `Contact:Captcha:Provider` / `SiteKey` | none | returned in the token response when enabled | +| `Contact:Captcha:Secret` | none | env / secrets manager only, never committed | +| `RateLimiting:ContactForm:PermitLimit` / `WindowSeconds` | `5` / `600` | | +| `RateLimiting:ContactToken:PermitLimit` / `WindowSeconds` | `20` / `600` | | + +## Deviations from the contract / design (for SLS to adopt) +- The honeypot JSON name is fixed `hpCheck` (no `Contact:HoneypotField`): the payload shape is a contract matter; the site's DOM name is free. A missing `hpCheck` key counts as empty (lenient) instead of a `required` error, so a real client that omits it is not rejected and a bot learns no field name from an error. +- Unbindable bodies (malformed JSON, wrong types) answer `400` with `errors.body=["invalid"]` in the same problem shape (the controller is deliberately not an `[ApiController]`). +- Validation problem `type` is configurable (`Contact:ProblemTypeBase`), default `about:blank` (approved). + +## Privacy / logging +Only the outcome (`Genuine|Spam|SpamNotStored|Replay`) and the site id are logged; mail failures are logged by exception type only. Tests prove that no name, e-mail, subject, message, captcha token, Idempotency-Key or token appears in any log entry (genuine, spam, replay, invalid, forged token, mail exception with personal data in its message, database exception). Sentry: request bodies are never captured (`MaxRequestBodySize=None`) and the existing scrubber nulls `Request.Data`. Note: like for every endpoint, a Sentry error event carries the caller's IP address (`SendDefaultPii`); nothing from the form body is in it. + +## Verification (real output) +Build 0 errors. Contact.Tests 113 passed (unit and pipeline), Core 205, Availability 95 (route table now allows exactly GetOfferings + GetToken + Submit), Offerings 86, Identity 37, Master 57, Api.Tests 4 β€” all against a temporary MariaDB (removed afterwards). Pipeline tests start the real SlpSoftware host: disabled -> both routes 404 empty and the contact tables do not even exist (the module never touched the database; the retention tick changes nothing); enabled -> token 200, valid POST 202 stored once, replay 202 without a second row, honeypot 202 identical body but stored as Spam, 400 shapes, 413, malformed bodies without echo, 429 with Retry-After for both policies, routes reachable while the CMS is disabled (and `/offerings/categories` 503), migration applied on a real MariaDB with a unique (site, key) constraint, retention job deletes expired rows. Each pipeline fixture creates and drops its own database. + +## Running the tests +The `Pipeline` tests need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (same requirement as `Api.Tests`). Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md index 011584f..88c8226 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3-contact-core-code-generation-plan.md @@ -36,14 +36,14 @@ On master the rate-limit policies are global buckets (no per-client partition ke `Enabled=false`, `SiteId`, `MinSeconds=3`, `TokenLifetimeMinutes=120`, `RetentionMonths=12`, `SpamRetentionDays=30`, `MaxSpamRowsPerDay=200`, `MaxBodyBytes=16384`, `HoneypotField=hpCheck`, `Captcha:{Enabled=false,Provider,SiteKey,Secret}`; `RateLimiting:ContactForm` (5/600), `RateLimiting:ContactToken` (20/600). Recipient/sender e-mail addresses are not part of U3 (U5, env-only for ASF). `appsettings.json` of `Api.SlpSoftware` gets the section with `Enabled=false`; no addresses, no secrets. ## Steps -- [ ] **Step 1 β€” Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes. -- [ ] **Step 2 β€” Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification). -- [ ] **Step 3 β€” Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation. -- [ ] **Step 4 β€” Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service. -- [ ] **Step 5 β€” Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list). -- [ ] **Step 6 β€” Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency). -- [ ] **Step 7 β€” Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported. -- [ ] **Step 8 β€” Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push. +- [x] **Step 1 β€” Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes. +- [x] **Step 2 β€” Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification). +- [x] **Step 3 β€” Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation. +- [x] **Step 4 β€” Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service. +- [x] **Step 5 β€” Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list). +- [x] **Step 6 β€” Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency). +- [x] **Step 7 β€” Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported. +- [x] **Step 8 β€” Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push. ## Explicitly NOT touched `AddCmsRateLimiting`/Core hosting files, `AvailabilityMiddleware`, Email, Identity, ASF-owned areas, host Program.cs, frontend, the Andrea host. No admin endpoints (CMS-U4), no mail sending (CMS-U5), no OpenAPI export (CMS-U3b). diff --git a/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs new file mode 100644 index 0000000..5d379c2 --- /dev/null +++ b/src/SlpModularCms.Api.SlpSoftware/Program.Coverage.cs @@ -0,0 +1,3 @@ +// Exposes the top-level-statements Program class so WebApplicationFactory can start the +// composed host in tests (same approach as SlpModularCms.Api/Program.Coverage.cs). +public partial class Program { } diff --git a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj index 3f43383..bad6be2 100644 --- a/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj +++ b/src/SlpModularCms.Api.SlpSoftware/SlpModularCms.Api.SlpSoftware.csproj @@ -20,6 +20,7 @@ + diff --git a/src/SlpModularCms.Api.SlpSoftware/appsettings.json b/src/SlpModularCms.Api.SlpSoftware/appsettings.json index f4dbb4b..8f96bf6 100644 --- a/src/SlpModularCms.Api.SlpSoftware/appsettings.json +++ b/src/SlpModularCms.Api.SlpSoftware/appsettings.json @@ -61,6 +61,22 @@ "Cors": { "AllowedOrigins": [] }, + "Contact": { + // OFF by default. Do not enable on a public host until per-client rate limiting is on the + // base branch (see ContactRateLimitPartition): until then the contact rate limits are one + // bucket shared by all visitors. + "Enabled": false, + "SiteId": "slpsoftware", + "MinSeconds": 3, + "TokenLifetimeMinutes": 120, + "RetentionMonths": 12, + "SpamRetentionDays": 30, + "MaxSpamRowsPerDay": 200, + "MaxBodyBytes": 16384, + "Captcha": { + "Enabled": false + } + }, "RateLimiting": { "Login": { "PermitLimit": 5, @@ -77,6 +93,14 @@ "OfferingsPublic": { "PermitLimit": 120, "WindowSeconds": 60 + }, + "ContactForm": { + "PermitLimit": 5, + "WindowSeconds": 600 + }, + "ContactToken": { + "PermitLimit": 20, + "WindowSeconds": 600 } }, "SecurityHeaders": { diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs index 851d37c..a2e2a84 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -13,6 +13,7 @@ using SlpModularCms.Core.Observability; using SlpModularCms.Modules.Availability.Controllers; using SlpModularCms.Modules.Availability.Middleware; using SlpModularCms.Modules.Availability.Services; +using SlpModularCms.Modules.Contact.Controllers; using SlpModularCms.Modules.Identity.Controllers; using SlpModularCms.Modules.Master.Controllers; using SlpModularCms.Modules.Offerings.Controllers; @@ -158,6 +159,8 @@ public class PublicSiteEndpointGateTests private static readonly string[] AllowedPublicActions = [ $"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}", ]; private static IReadOnlyList AllActions() => @@ -167,6 +170,7 @@ public class PublicSiteEndpointGateTests typeof(UsersController).Assembly, typeof(CmsInstanceController).Assembly, typeof(OfferingsController).Assembly, + typeof(ContactMessagesController).Assembly, typeof(SystemController).Assembly, } .Distinct() diff --git a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj index 112f182..cefb9db 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj +++ b/src/SlpModularCms.Modules.Availability.Tests/SlpModularCms.Modules.Availability.Tests.csproj @@ -34,6 +34,7 @@ + diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs new file mode 100644 index 0000000..05d2831 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs @@ -0,0 +1,292 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.AspNetCore.Routing; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactMessagesControllerTests +{ + private readonly IContactTokenService _tokens = Substitute.For(); + private readonly IContactSubmissionService _submissions = Substitute.For(); + + private ContactMessagesController Create(ContactOptions? options = null, string? idempotencyKey = null) + { + var controller = new ContactMessagesController(_tokens, _submissions, Options.Create(options ?? new ContactOptions { Enabled = true })) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + if (idempotencyKey is not null) + { + controller.Request.Headers[ContactMessagesController.IdempotencyKeyHeader] = idempotencyKey; + } + + return controller; + } + + [Fact] + public void GetToken_ReturnsTheTokenTheMinimumTime_AndNoCaptchaByDefault() + { + _tokens.Issue().Returns("tok"); + + var result = Create(new ContactOptions { Enabled = true, MinSeconds = 5 }).GetToken(); + + var body = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + body.Should().Be(new ContactTokenResponse("tok", 5, null)); + } + + [Fact] + public void GetToken_ReportsTheCaptchaProviderAndSiteKey_WhenEnabled_ButNeverTheSecret() + { + _tokens.Issue().Returns("tok"); + var options = new ContactOptions + { + Enabled = true, + Captcha = new ContactCaptchaOptions { Enabled = true, Provider = "friendlycaptcha", SiteKey = "pub", Secret = "very-secret" }, + }; + + var result = Create(options).GetToken(); + + var body = (ContactTokenResponse)((OkObjectResult)result).Value!; + body.Captcha.Should().Be(new ContactCaptchaInfo("friendlycaptcha", "pub")); + System.Text.Json.JsonSerializer.Serialize(body).Should().NotContain("very-secret"); + } + + [Fact] + public async Task Submit_Returns202_WithTheFixedBody_WhenReceived() + { + _submissions.SubmitAsync(Arg.Any(), "key", Arg.Any()) + .Returns(new SubmissionResult.Received()); + + var result = await Create(idempotencyKey: "key").Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None); + + var obj = result.Should().BeOfType().Subject; + obj.StatusCode.Should().Be(202); + obj.Value.Should().Be(new ReceivedResponse("received")); + } + + [Fact] + public async Task Submit_Returns400_WithTheErrorsShape_AndTheConfiguredTypeBase() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["email"] = ["invalid"] })); + + var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" }) + .Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None); + + var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + problem.Status.Should().Be(400); + problem.Type.Should().Be("https://example.test/problems/validation"); + problem.Errors["email"].Should().Equal("invalid"); + } + + [Fact] + public async Task Submit_UsesAboutBlank_WhenNoTypeBaseIsConfigured() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["name"] = ["required"] })); + + var result = await Create().Submit(null, CancellationToken.None); + + ((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank"); + } + + [Fact] + public async Task Submit_PassesNull_WhenTheBodyCouldNotBeBound() + { + _submissions.SubmitAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new SubmissionResult.Invalid(new Dictionary { ["body"] = ["invalid"] })); + var controller = Create(); + controller.ModelState.AddModelError("$.name", "The JSON value could not be converted"); + + await controller.Submit(new ContactMessageRequest("a", "b", "c", "d", "", "t", null), CancellationToken.None); + + await _submissions.Received(1).SubmitAsync(null, Arg.Any(), Arg.Any()); + } + + [Fact] + public void TheRouteTable_HasTwoPublicRoutes_BothMarkedAnonymousAndRateLimited_AndNoAdminSegment() + { + var type = typeof(ContactMessagesController); + type.GetCustomAttribute()!.Template.Should().Be("contact-messages"); + type.GetCustomAttribute().Should().BeNull(); + type.GetCustomAttribute().Should().BeNull("the management routes arrive with the admin unit"); + + var actions = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Where(m => m.GetCustomAttributes().Any()) + .ToDictionary(m => $"{m.GetCustomAttribute()!.HttpMethods.Single()} {m.GetCustomAttribute()!.Template}".Trim()); + + actions.Keys.Should().BeEquivalentTo(["GET token", "POST"]); + foreach (var action in actions.Values) + { + action.GetCustomAttribute().Should().NotBeNull(); + action.GetCustomAttribute().Should().NotBeNull(); + } + + actions["GET token"].GetCustomAttribute()!.PolicyName.Should().Be("contact-token"); + actions["POST"].GetCustomAttribute()!.PolicyName.Should().Be("contact-form"); + type.GetCustomAttribute()!.ServiceType.Should().Be(typeof(ContactRouteFilter)); + } +} + +public class ContactRouteFilterTests +{ + private static ResourceExecutingContext Context(string method, long? contentLength = null, IHttpMaxRequestBodySizeFeature? feature = null) + { + var http = new DefaultHttpContext(); + http.Request.Method = method; + http.Request.ContentLength = contentLength; + if (feature is not null) + { + http.Features.Set(feature); + } + + return new ResourceExecutingContext( + new ActionContext(http, new RouteData(), new ActionDescriptor()), + new List(), + new List()); + } + + private static ContactRouteFilter Create(bool enabled, int max = 1000) + { + var options = Options.Create(new ContactOptions { Enabled = enabled, MaxBodyBytes = max }); + return new ContactRouteFilter(new HostFlagContactFormGate(options), options); + } + + private static ContactRouteFilter CreateWithGate(bool open, int max = 1000) + { + var gate = Substitute.For(); + gate.IsOpenAsync(Arg.Any()).Returns(open); + return new ContactRouteFilter(gate, Options.Create(new ContactOptions { Enabled = true, MaxBodyBytes = max })); + } + + [Theory] + [InlineData("GET", false)] + [InlineData("POST", false)] + [InlineData("GET", true)] + [InlineData("POST", true)] + public async Task TheFilter_FollowsTheGateOnly_SoAnotherLayerCanBeAddedWithoutTouchingIt(string method, bool open) + { + var context = Context(method); + var nextCalled = false; + + await CreateWithGate(open).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Next(context)(); + }); + + nextCalled.Should().Be(open); + (context.Result is NotFoundResult).Should().Be(!open); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task TheHostFlagGate_ReflectsContactEnabled(bool enabled) + { + var gate = new HostFlagContactFormGate(Options.Create(new ContactOptions { Enabled = enabled })); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().Be(enabled); + } + + private static ResourceExecutionDelegate Next(ResourceExecutingContext context, Exception? exception = null) + => () => Task.FromResult(new ResourceExecutedContext(context, new List()) { Exception = exception }); + + [Theory] + [InlineData("GET")] + [InlineData("POST")] + public async Task WhileDisabled_BothRoutesAre404_AndNothingFurtherRuns(string method) + { + var context = Context(method); + var nextCalled = false; + + await Create(enabled: false).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Task.FromResult(null!); + }); + + context.Result.Should().BeOfType(); + nextCalled.Should().BeFalse(); + } + + [Fact] + public async Task APostBeyondTheLimit_Gets413_AsProblemJson() + { + var context = Context("POST", contentLength: 1001); + + await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, Next(context)); + + var result = context.Result.Should().BeOfType().Subject; + result.StatusCode.Should().Be(413); + result.ContentTypes.Should().Contain("application/problem+json"); + result.Value.Should().BeOfType().Which.Status.Should().Be(413); + } + + [Fact] + public async Task APostWithinTheLimit_PassesThrough_AndLimitsChunkedBodies() + { + var feature = Substitute.For(); + feature.IsReadOnly.Returns(false); + var context = Context("POST", contentLength: 1000, feature: feature); + var nextCalled = false; + + await Create(enabled: true, max: 1000).OnResourceExecutionAsync(context, () => + { + nextCalled = true; + return Next(context)(); + }); + + nextCalled.Should().BeTrue(); + context.Result.Should().BeNull(); + feature.MaxRequestBodySize.Should().Be(1000); + } + + [Fact] + public async Task ABodyThatTurnsOutTooLargeWhileReading_BecomesA413() + { + var context = Context("POST"); + ResourceExecutedContext? executed = null; + + await Create(enabled: true).OnResourceExecutionAsync(context, async () => + { + executed = await Next( + context, + new BadHttpRequestException("too large", StatusCodes.Status413PayloadTooLarge))(); + return executed; + }); + + executed!.ExceptionHandled.Should().BeTrue(); + executed.Result.Should().BeOfType().Which.StatusCode.Should().Be(413); + } + + [Fact] + public async Task OtherExceptions_AreLeftAlone() + { + var context = Context("POST"); + ResourceExecutedContext? executed = null; + + await Create(enabled: true).OnResourceExecutionAsync(context, async () => + { + executed = await Next(context, new InvalidOperationException("boom"))(); + return executed; + }); + + executed!.ExceptionHandled.Should().BeFalse(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs new file mode 100644 index 0000000..8e0a352 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs @@ -0,0 +1,92 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +/// +/// Nothing a visitor typed, and nothing that identifies a request (the Idempotency-Key and the +/// token are no personal data, but there is no reason to log them either), may ever appear in a log. +/// +public class ContactNoPersonalDataInLogsTests +{ + private const string MarkerName = "ZXQ-Name-Marker"; + private const string MarkerEmail = "zxq-marker@example.test"; + private const string MarkerSubject = "ZXQ-Subject-Marker"; + private const string MarkerMessage = "ZXQ-Message-Marker"; + + private static ContactMessageRequest Marked(string token, string hp = "") => + new(MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, hp, token, "ZXQ-Captcha-Marker"); + + private static void AssertClean(SubmissionHarness h, params string[] extraForbidden) + { + var forbidden = new[] { MarkerName, MarkerEmail, MarkerSubject, MarkerMessage, "ZXQ-Captcha-Marker", "ZXQ-" } + .Concat(extraForbidden).ToArray(); + + h.Logs.Messages.Should().NotBeEmpty("outcomes are logged"); + foreach (var message in h.Logs.Messages) + { + foreach (var marker in forbidden) + { + message.Should().NotContain(marker); + } + } + } + + [Fact] + public async Task GenuineSpamReplayAndInvalid_LogNothingPersonal_NoKeyAndNoToken() + { + using var h = new SubmissionHarness(o => o.Captcha.Enabled = true); + var key = Guid.NewGuid().ToString(); + var token = h.MatureToken(); + + await h.Submit(Marked(token), key); // genuine + await h.Submit(Marked(token), key); // replay + await h.Submit(Marked(h.MatureToken(), hp: "ZXQ-Honeypot")); // spam + await h.Submit(Marked(token) with { Email = "ZXQ-not-an-address" }); // invalid fields + await h.Submit(Marked("ZXQ-forged-token")); // forged token + + AssertClean(h, key, token, "ZXQ-Honeypot"); + } + + [Fact] + public async Task AMailFailureWithPersonalDataInItsMessage_IsLoggedByTypeOnly() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException($"cannot deliver to {MarkerEmail}: {MarkerMessage}")); + + await h.Submit(Marked(h.MatureToken())); + + AssertClean(h); + h.Logs.Messages.Should().Contain(m => m.Contains(nameof(InvalidOperationException))); + } + + [Fact] + public async Task ADatabaseFailureWithPersonalDataInItsMessage_DoesNotLeakThroughTheServiceLogs() + { + var repository = Substitute.For(); + repository.SaveChangesAsync(Arg.Any()).ThrowsAsync(new DbUpdateException("duplicate")); + using var h = new SubmissionHarness(repositoryOverride: repository); + + await h.Submit(Marked(h.MatureToken())); + + AssertClean(h); + } + + [Fact] + public async Task TheOutcomeLogLines_CarryOnlyTheOutcomeAndTheSiteId() + { + using var h = new SubmissionHarness(); + + await h.Submit(Marked(h.MatureToken())); + + h.Logs.Messages.Should().ContainSingle() + .Which.Should().Be("Contact submission handled: Genuine for site site-a"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs new file mode 100644 index 0000000..915781e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs @@ -0,0 +1,144 @@ +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactRetentionServiceTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + private static ContactMessage Message(string name, DateTimeOffset retentionUntil) => new() + { + Id = Guid.NewGuid(), SiteId = "s", ReceivedAt = Now.AddDays(-1), Name = name, Email = "a@b.nl", + Subject = "x", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = retentionUntil, + }; + + private static (ContactRetentionService Sut, ServiceProvider Provider, string Db) Create(bool enabled) + { + var databaseName = Guid.NewGuid().ToString(); + var services = new ServiceCollection(); + services.AddDbContext(o => o.UseInMemoryDatabase(databaseName)); + services.AddScoped(); + var provider = services.BuildServiceProvider(); + + var sut = new ContactRetentionService( + provider.GetRequiredService(), + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = enabled }), + new FakeTimeProvider(Now), + NullLogger.Instance); + return (Sut: sut, Provider: provider, Db: databaseName); + } + + [Fact] + public async Task DeletesExpiredMessagesAndOldIdempotencyRecords_AndKeepsTheRest() + { + var (sut, provider, _) = Create(enabled: true); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.ContactMessages.AddRange( + Message("expired", Now.AddSeconds(-1)), + Message("expired too", Now.AddDays(-30)), + Message("kept", Now.AddDays(1)), + Message("kept long", Now.AddMonths(11))); + db.IdempotencyRecords.AddRange( + new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-25), StatusCode = 202 }, + new IdempotencyRecord { SiteId = "s", Key = Guid.NewGuid(), CreatedAt = Now.AddHours(-23), StatusCode = 202 }); + await db.SaveChangesAsync(); + } + + await sut.ExecuteTickAsync(CancellationToken.None); + + await using var check = provider.CreateAsyncScope(); + var after = check.ServiceProvider.GetRequiredService(); + after.ContactMessages.Select(m => m.Name).Should().BeEquivalentTo("kept", "kept long"); + after.IdempotencyRecords.Count().Should().Be(1); + } + + [Fact] + public async Task HandlesMoreRowsThanOneBatch() + { + var (sut, provider, _) = Create(enabled: true); + await using (var scope = provider.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.ContactMessages.AddRange(Enumerable.Range(0, 1200).Select(i => Message($"old{i}", Now.AddDays(-1)))); + await db.SaveChangesAsync(); + } + + await sut.ExecuteTickAsync(CancellationToken.None); + + await using var check = provider.CreateAsyncScope(); + check.ServiceProvider.GetRequiredService().ContactMessages.Should().BeEmpty(); + } + + [Fact] + public async Task WhileDisabled_ItDoesNothing_AndNeverEvenOpensAScope() + { + var scopeFactory = Substitute.For(); + var sut = new ContactRetentionService( + scopeFactory, + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = false }), + new FakeTimeProvider(Now), + NullLogger.Instance); + + await sut.ExecuteTickAsync(CancellationToken.None); + + scopeFactory.ReceivedCalls().Should().BeEmpty("a disabled module must not touch the database or anything else"); + } + + [Fact] + public async Task ADatabaseProblem_DoesNotCrashTheJob() + { + var scopeFactory = Substitute.For(); + scopeFactory.CreateScope().Returns(_ => throw new InvalidOperationException("db down")); + var sut = new ContactRetentionService( + scopeFactory, + Microsoft.Extensions.Options.Options.Create(new ContactOptions { Enabled = true }), + new FakeTimeProvider(Now), + NullLogger.Instance); + + var act = () => sut.ExecuteTickAsync(CancellationToken.None); + + await act.Should().NotThrowAsync(); + } + + [Fact] + public void TheJobRunsDaily() + { + ContactRetentionService.Interval.Should().Be(TimeSpan.FromHours(24)); + } +} + +public class ContactRateLimitPartitionTests +{ + /// + /// REBASE CHECKLIST: on master there is no per-client partitioning, so every caller shares one + /// bucket and this test pins the constant. After the ASF merge the body of + /// ContactRateLimitPartition.KeyFor becomes return ClientPartitionKey.For(context); + /// and this test changes to "two different client addresses give two different keys". + /// + [Fact] + public void OnTheBaseBranch_EveryCallerSharesOneBucket() + { + var first = new DefaultHttpContext(); + first.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10"); + var second = new DefaultHttpContext(); + second.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("198.51.100.20"); + + ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.GlobalKey); + ContactRateLimitPartition.KeyFor(second).Should().Be(ContactRateLimitPartition.GlobalKey); + ContactRateLimitPartition.GlobalKey.Should().Be("global"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs new file mode 100644 index 0000000..6b8a5f4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactSubmissionServiceTests.cs @@ -0,0 +1,344 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; +using SlpModularCms.Modules.Contact.Models; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactSubmissionServiceTests +{ + private static async Task> Messages(SubmissionHarness h) + => await h.Db.ContactMessages.AsNoTracking().ToListAsync(); + + [Fact] + public async Task AGenuineMessage_IsStored_AsNew_WithTwelveMonthsRetention_AndMailPending() + { + using var h = new SubmissionHarness(); + var token = h.MatureToken(); + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType(); + var stored = (await Messages(h)).Single(); + stored.Status.Should().Be(ContactMessageStatus.New); + stored.MailStatus.Should().Be(ContactMailStatus.Pending); + stored.SiteId.Should().Be("site-a"); + stored.Name.Should().Be("Jan Jansen"); + stored.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12)); + } + + [Fact] + public async Task TextFieldsAreStoredTrimmed() + { + using var h = new SubmissionHarness(); + var request = SubmissionHarness.Request(h.MatureToken()) with { Name = " Jan ", Message = "\n hallo \n" }; + + await h.Submit(request); + + var stored = (await Messages(h)).Single(); + stored.Name.Should().Be("Jan"); + stored.Message.Should().Be("hallo"); + } + + [Fact] + public async Task TheMailSender_IsCalledAfterTheMessageIsStored_AndOnlyForGenuineMessages() + { + using var h = new SubmissionHarness(); + var storedWhenMailWasCalled = false; + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(call => + { + storedWhenMailWasCalled = h.Db.ContactMessages.AsNoTracking().Any(m => m.Id == call.Arg().Id); + return ContactMailOutcome.Skipped; + }); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + + storedWhenMailWasCalled.Should().BeTrue(); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ASentMail_IsRecorded_WithOneAttempt() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Sent); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + var stored = (await Messages(h)).Single(); + stored.MailStatus.Should().Be(ContactMailStatus.Sent); + stored.MailAttempts.Should().Be(1); + } + + [Fact] + public async Task AMailFailure_NeverFailsTheRequest_AndLeavesTheMessageStored() + { + using var h = new SubmissionHarness(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException("smtp said no to jan@example.nl")); + + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + result.Should().BeOfType(); + (await Messages(h)).Single().MailStatus.Should().Be(ContactMailStatus.Pending); + } + + [Fact] + public async Task AFilledHoneypot_IsStoredAsSpam_ForThirtyDays_NeverMailed_WithTheSameAnswer() + { + using var h = new SubmissionHarness(); + + var spam = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "http://spam")); + var genuine = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + spam.Should().Be(genuine, "a bot must not be able to tell the difference"); + var stored = (await Messages(h)).Single(m => m.Status == ContactMessageStatus.Spam); + stored.MailStatus.Should().Be(ContactMailStatus.NotApplicable); + stored.RetentionUntil.Should().Be(stored.ReceivedAt.AddDays(30)); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task ATooFastSubmission_IsSpam() + { + using var h = new SubmissionHarness(); + var token = h.Tokens.Issue(); // no waiting + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType(); + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam); + } + + [Fact] + public async Task ARejectedCaptcha_IsSpam_WhenCaptchaIsEnabled() + { + using var h = new SubmissionHarness(o => o.Captcha.Enabled = true); + h.Captcha.VerifyAsync(Arg.Any(), Arg.Any()).Returns(false); + + await h.Submit(SubmissionHarness.Request(h.MatureToken(), captcha: "bad")); + + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.Spam); + } + + [Fact] + public async Task TheCaptchaIsNotConsulted_WhenItIsDisabled() + { + using var h = new SubmissionHarness(); + + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + await h.Captcha.DidNotReceive().VerifyAsync(Arg.Any(), Arg.Any()); + (await Messages(h)).Single().Status.Should().Be(ContactMessageStatus.New); + } + + [Fact] + public async Task SpamIsNotStored_OnceTheDailyCapIsReached_ButTheAnswerStaysTheSame() + { + using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 2); + + for (var i = 0; i < 4; i++) + { + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + result.Should().BeOfType(); + } + + (await Messages(h)).Count(m => m.Status == ContactMessageStatus.Spam).Should().Be(2); + h.Db.IdempotencyRecords.Count().Should().Be(4, "dropped spam still gets a replay record"); + } + + [Fact] + public async Task TheSpamCap_StartsAgainOnTheNextDay() + { + using var h = new SubmissionHarness(o => o.MaxSpamRowsPerDay = 1); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + (await Messages(h)).Should().HaveCount(1); + + h.Time.Advance(TimeSpan.FromDays(1)); + await h.Submit(SubmissionHarness.Request(h.MatureToken(), hp: "bot")); + + (await Messages(h)).Should().HaveCount(2); + } + + [Fact] + public async Task AReplayWithTheSameKey_ReturnsTheSameAnswer_WithoutASecondRowOrMail() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var request = SubmissionHarness.Request(h.MatureToken()); + + var first = await h.Submit(request, key); + var second = await h.Submit(request, key); + + second.Should().Be(first); + (await Messages(h)).Should().HaveCount(1); + await h.Mail.Received(1).SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task AReplay_StillWorks_WhenTheTokenHasExpiredInTheMeantime() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var request = SubmissionHarness.Request(h.MatureToken()); + await h.Submit(request, key); + + h.Time.Advance(TimeSpan.FromHours(3)); + var replay = await h.Submit(request, key); + + replay.Should().BeOfType(); + (await Messages(h)).Should().HaveCount(1); + } + + [Fact] + public async Task AKeyOlderThan24Hours_CanBeUsedAgain() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + await h.Submit(SubmissionHarness.Request(h.MatureToken()), key); + + h.Time.Advance(TimeSpan.FromHours(25)); + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken()), key); + + result.Should().BeOfType(); + (await Messages(h)).Should().HaveCount(2); + h.Db.IdempotencyRecords.Count().Should().Be(1, "the old record is reused, not duplicated"); + } + + [Fact] + public async Task TheIdempotencyRecord_HoldsNoRequestContent() + { + using var h = new SubmissionHarness(); + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + var record = h.Db.IdempotencyRecords.AsNoTracking().Single(); + record.SiteId.Should().Be("site-a"); + record.StatusCode.Should().Be(202); + typeof(IdempotencyRecord).GetProperties().Select(p => p.Name) + .Should().BeEquivalentTo(["SiteId", "Key", "CreatedAt", "StatusCode"]); + } + + [Fact] + public async Task InvalidFields_AreRejected_WithEveryProblemListed_AndNothingIsStored() + { + using var h = new SubmissionHarness(); + var request = SubmissionHarness.Request(h.MatureToken()) with { Name = "", Email = "nope", Message = new string('a', 2001) }; + + var result = await h.Submit(request); + + var invalid = result.Should().BeOfType().Subject; + invalid.Errors["name"].Should().Equal("required"); + invalid.Errors["email"].Should().Equal("invalid"); + invalid.Errors["message"].Should().Equal("tooLong"); + (await Messages(h)).Should().BeEmpty(); + h.Db.IdempotencyRecords.Should().BeEmpty("a rejected request must not use up its key"); + } + + [Fact] + public async Task ACorrectedRequest_CanReuseTheKeyOfARejectedOne() + { + using var h = new SubmissionHarness(); + var key = Guid.NewGuid().ToString(); + var token = h.MatureToken(); + + (await h.Submit(SubmissionHarness.Request(token) with { Email = "nope" }, key)).Should().BeOfType(); + (await h.Submit(SubmissionHarness.Request(token), key)).Should().BeOfType(); + + (await Messages(h)).Should().HaveCount(1); + } + + [Theory] + [InlineData(null, "required")] + [InlineData("", "required")] + [InlineData("not-a-guid", "invalid")] + public async Task ABadIdempotencyKey_IsRejected(string? key, string code) + { + using var h = new SubmissionHarness(); + + var result = await h.Sut.SubmitAsync(SubmissionHarness.Request(h.MatureToken()), key, CancellationToken.None); + + result.Should().BeOfType().Which.Errors["idempotencyKey"].Should().Equal(code); + (await Messages(h)).Should().BeEmpty(); + } + + [Fact] + public async Task ANullBody_IsRejected_AsAnInvalidBody() + { + using var h = new SubmissionHarness(); + + var result = await h.Submit(null); + + result.Should().BeOfType().Which.Errors["body"].Should().Equal("invalid"); + } + + [Theory] + [InlineData("garbage")] + [InlineData("CfDJ8-forged")] + public async Task AForgedToken_IsReportedAsExpired_AndNothingIsStored(string token) + { + using var h = new SubmissionHarness(); + + var result = await h.Submit(SubmissionHarness.Request(token)); + + result.Should().BeOfType().Which.Errors["token"].Should().Equal("expired"); + (await Messages(h)).Should().BeEmpty(); + h.Db.IdempotencyRecords.Should().BeEmpty(); + } + + [Fact] + public async Task AnExpiredToken_IsReportedAsExpired_ExactlyLikeAForgedOne() + { + using var h = new SubmissionHarness(); + var token = h.Tokens.Issue(); + h.Time.Advance(TimeSpan.FromHours(3)); + + var expired = await h.Submit(SubmissionHarness.Request(token)); + var forged = await h.Submit(SubmissionHarness.Request("forged")); + + expired.Should().BeOfType(); + ((SubmissionResult.Invalid)expired).Errors.Should().BeEquivalentTo(((SubmissionResult.Invalid)forged).Errors); + } + + [Fact] + public async Task ARaceOnTheSameKey_IsAnsweredAsAReplay() + { + var repository = Substitute.For(); + repository.GetIdempotencyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns((IdempotencyRecord?)null); + repository.SaveChangesAsync(Arg.Any()).ThrowsAsync(new DbUpdateException("duplicate")); + using var h = new SubmissionHarness(repositoryOverride: repository); + + var result = await h.Submit(SubmissionHarness.Request(h.MatureToken())); + + result.Should().BeOfType(); + } + + [Fact] + public async Task TheSiteId_ComesFromConfiguration_NeverFromTheRequest() + { + using var h = new SubmissionHarness(o => o.SiteId = "configured-site"); + var request = SubmissionHarness.Request(h.MatureToken()) with { Subject = "other-site" }; + + await h.Submit(request); + + (await Messages(h)).Single().SiteId.Should().Be("configured-site"); + } + + [Fact] + public async Task ARetentionConfigChange_DoesNotChangeStoredRows() + { + using var h = new SubmissionHarness(); + await h.Submit(SubmissionHarness.Request(h.MatureToken())); + var before = (await Messages(h)).Single().RetentionUntil; + + h.Options.RetentionMonths = 1; + + (await Messages(h)).Single().RetentionUntil.Should().Be(before); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs new file mode 100644 index 0000000..d333ac2 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactTokenServiceTests.cs @@ -0,0 +1,144 @@ +using FluentAssertions; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Time.Testing; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactTokenServiceTests +{ + private static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + private static ContactTokenService Create( + FakeTimeProvider time, string siteId = "site-a", IDataProtectionProvider? provider = null, + int minSeconds = 3, int lifetimeMinutes = 120) + => new( + provider ?? DataProtectionProvider.Create("contact-token-tests"), + Options.Create(new ContactOptions { SiteId = siteId, MinSeconds = minSeconds, TokenLifetimeMinutes = lifetimeMinutes }), + time); + + [Fact] + public void ATokenIsValid_AfterTheMinimumTime_AndBeforeItExpires() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromSeconds(3)); + sut.Check(token).Should().Be(TokenCheck.Valid); + + time.Advance(TimeSpan.FromMinutes(119)); + sut.Check(token).Should().Be(TokenCheck.Valid); + } + + [Fact] + public void ATokenIsTooYoung_BeforeTheMinimumTime() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromSeconds(2)); + + sut.Check(token).Should().Be(TokenCheck.TooYoung); + } + + [Fact] + public void ATokenExpires_AfterItsLifetime() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + + time.Advance(TimeSpan.FromMinutes(120) + TimeSpan.FromSeconds(1)); + + sut.Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATokenFromTheFuture_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var provider = DataProtectionProvider.Create("contact-token-tests"); + var later = Create(new FakeTimeProvider(Start.AddHours(1)), provider: provider); + var token = later.Issue(); + + Create(time, provider: provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATokenOfAnotherSite_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var provider = DataProtectionProvider.Create("contact-token-tests"); + var token = Create(time, "site-a", provider).Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + Create(time, "site-b", provider).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + Create(time, "site-a", provider).Check(token).Should().Be(TokenCheck.Valid); + } + + [Fact] + public void ATokenFromAnotherKeyRing_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var token = Create(time, provider: DataProtectionProvider.Create("one")).Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + Create(time, provider: DataProtectionProvider.Create("two")).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("garbage")] + [InlineData("CfDJ8-not-a-real-token")] + public void BlankOrGarbage_IsInvalid(string? token) + { + Create(new FakeTimeProvider(Start)).Check(token).Should().Be(TokenCheck.InvalidOrExpired); + } + + [Fact] + public void ATamperedToken_IsInvalid() + { + var time = new FakeTimeProvider(Start); + var sut = Create(time); + var token = sut.Issue(); + time.Advance(TimeSpan.FromSeconds(10)); + + for (var i = 0; i < token.Length; i += 7) + { + var chars = token.ToCharArray(); + chars[i] = chars[i] == 'A' ? 'B' : 'A'; + sut.Check(new string(chars)).Should().Be(TokenCheck.InvalidOrExpired, $"changing character {i} must break the token"); + } + } + + [Fact] + public void RoundTrip_ClassifiesEveryAgeAsExpected_ForManyRandomAges() + { + var random = new Random(4242); + for (var i = 0; i < 200; i++) + { + var time = new FakeTimeProvider(Start); + var sut = Create(time, minSeconds: 3, lifetimeMinutes: 120); + var token = sut.Issue(); + + var ageSeconds = random.Next(0, 3 * 60 * 60); + time.Advance(TimeSpan.FromSeconds(ageSeconds)); + + var expected = ageSeconds > 120 * 60 ? TokenCheck.InvalidOrExpired + : ageSeconds < 3 ? TokenCheck.TooYoung + : TokenCheck.Valid; + sut.Check(token).Should().Be(expected, $"age {ageSeconds} s"); + } + } + + [Fact] + public void ThePurposeStringIsBoundToTheSite() + { + ContactTokenService.PurposeFor("slpsoftware").Should().Be("SlpModularCms.Contact.Token.slpsoftware"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs new file mode 100644 index 0000000..95170ee --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactValidatorTests.cs @@ -0,0 +1,185 @@ +using FluentAssertions; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactValidatorTests +{ + private static ContactMessageRequest Valid() => new( + "Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", "", "token", null); + + private static Dictionary Check(ContactMessageRequest request) + => ContactValidator.Validate(ContactValidator.Normalize(request)); + + [Fact] + public void AValidRequest_HasNoErrors() + { + Check(Valid()).Should().BeEmpty(); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void RequiredFields_AreReported_WhenMissingOrBlank(string? blank) + { + var errors = Check(new ContactMessageRequest(blank, blank, blank, blank, null, blank, null)); + + errors.Keys.Should().BeEquivalentTo("name", "email", "subject", "message", "token"); + errors.Values.Should().OnlyContain(v => v.Single() == "required"); + } + + [Theory] + [InlineData(100, true)] + [InlineData(101, false)] + public void Name_AllowsAtMost100Characters(int length, bool valid) + { + var errors = Check(Valid() with { Name = new string('a', length) }); + + (errors.ContainsKey("name") ? errors["name"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData(254, true)] + [InlineData(255, false)] + public void Email_AllowsAtMost254Characters(int length, bool valid) + { + var email = new string('a', length - "@example.nl".Length) + "@example.nl"; + var errors = Check(Valid() with { Email = email }); + + (errors.ContainsKey("email") ? errors["email"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData(2000, true)] + [InlineData(2001, false)] + public void Message_AllowsAtMost2000Characters(int length, bool valid) + { + var errors = Check(Valid() with { Message = new string('a', length) }); + + (errors.ContainsKey("message") ? errors["message"].Single() : "ok").Should().Be(valid ? "ok" : "tooLong"); + } + + [Theory] + [InlineData("jan@example.nl", true)] + [InlineData("a@b.co", true)] + [InlineData("jan.jansen+tag@sub.example.nl", true)] + [InlineData("jan@example", false)] + [InlineData("jan@example.n", false)] + [InlineData("@example.nl", false)] + [InlineData("jan example@example.nl", false)] + [InlineData("jan@@example.nl", false)] + public void Email_MustLookLikeAnAddress(string email, bool valid) + { + var errors = Check(Valid() with { Email = email }); + + errors.ContainsKey("email").Should().Be(!valid); + if (!valid) + { + errors["email"].Single().Should().Be("invalid"); + } + } + + [Fact] + public void Trimming_HappensBeforeTheLengthCheck() + { + var errors = Check(Valid() with { Name = " " + new string('a', 100) + " " }); + + errors.Should().BeEmpty(); + } + + [Fact] + public void Normalize_IsIdempotent_ForManyRandomInputs() + { + var random = new Random(20261109); + for (var i = 0; i < 300; i++) + { + var request = new ContactMessageRequest( + Noise(random, 120), Noise(random, 40), Noise(random, 120), Noise(random, 300), Noise(random, 3), Noise(random, 50), null); + + var once = ContactValidator.Normalize(request); + ContactValidator.Normalize(once).Should().Be(once); + } + } + + [Fact] + public void Validation_NeverChangesBetweenARequestAndItsNormalizedForm() + { + // Validating twice (before and after another trim) must give the same answer. + var random = new Random(7); + for (var i = 0; i < 300; i++) + { + var request = new ContactMessageRequest( + Noise(random, 130), Noise(random, 300), Noise(random, 130), Noise(random, 2100), "", Noise(random, 20), null); + + var normalized = ContactValidator.Normalize(request); + ContactValidator.Validate(normalized).Should().BeEquivalentTo(ContactValidator.Validate(ContactValidator.Normalize(normalized))); + } + } + + [Theory] + [InlineData("name")] + [InlineData("email")] + [InlineData("subject")] + public void AnyControlCharacter_IsInvalid_InSingleLineFields(string field) + { + for (var code = 0; code < 32; code++) + { + var bad = $"a{(char)code}b"; + var request = field switch + { + "name" => Valid() with { Name = bad }, + "email" => Valid() with { Email = $"a{(char)code}b@example.nl" }, + _ => Valid() with { Subject = bad }, + }; + + var errors = ContactValidator.Validate(request); // not trimmed: control characters inside stay + errors.Should().ContainKey(field, $"control character U+{code:X4} must be rejected"); + errors[field].Single().Should().Be("invalid"); + } + + var del = field switch + { + "name" => Valid() with { Name = "a\u007Fb" }, + "email" => Valid() with { Email = "a\u007Fb@example.nl" }, + _ => Valid() with { Subject = "a\u007Fb" }, + }; + ContactValidator.Validate(del).Should().ContainKey(field); + } + + [Fact] + public void Message_AllowsLineBreaksAndTabs_ButNoOtherControlCharacters() + { + ContactValidator.Validate(Valid() with { Message = "regel 1\r\nregel 2\n\tingesprongen" }).Should().BeEmpty(); + + for (var code = 0; code < 32; code++) + { + if (code is '\n' or '\r' or '\t') + { + continue; + } + + var errors = ContactValidator.Validate(Valid() with { Message = $"a{(char)code}b" }); + errors.Should().ContainKey("message", $"control character U+{code:X4} must be rejected"); + } + } + + [Fact] + public void ErrorCodes_AreExactlyTheContractedOnes() + { + var codes = new[] + { + ContactErrorCodes.Required, ContactErrorCodes.TooLong, ContactErrorCodes.Invalid, ContactErrorCodes.Expired, + }; + + codes.Should().Equal("required", "tooLong", "invalid", "expired"); + } + + private static string Noise(Random random, int maxLength) + { + const string alphabet = "abcXYZ019 @.+-_\t\né€"; + var length = random.Next(0, maxLength + 1); + return new string(Enumerable.Range(0, length).Select(_ => alphabet[random.Next(alphabet.Length)]).ToArray()); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs new file mode 100644 index 0000000..0dd3cb1 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs @@ -0,0 +1,113 @@ +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Modules.Contact.Data; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// +/// Starts the real, composed SlpSoftware host (all modules, the real pipeline) against a real +/// MariaDB/MySQL. Like SlpModularCms.Api.Tests this needs a reachable database: set the +/// environment variable ConnectionStrings__DefaultConnection to a server you may create +/// databases on. Every factory uses its own freshly created database and drops it again. +/// To run only the pure unit tests use --filter "FullyQualifiedName!~Pipeline". +/// +public class ContactHostFactory : WebApplicationFactory +{ + private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection"; + + private readonly Dictionary _settings; + private readonly string _databaseName = "SlpContactPipeline_" + Guid.NewGuid().ToString("N")[..12]; + + public ContactHostFactory(Dictionary? settings = null) + { + _settings = settings ?? []; + } + + public static string BaseConnectionString => + Environment.GetEnvironmentVariable(EnvironmentVariable) + ?? throw new InvalidOperationException( + $"Set {EnvironmentVariable} to a MariaDB/MySQL server for the contact pipeline tests " + + "(or run the unit tests only with --filter \"FullyQualifiedName!~Pipeline\")."); + + public string ConnectionString => + Regex.IsMatch(BaseConnectionString, "Database=[^;]*", RegexOptions.IgnoreCase) + ? Regex.Replace(BaseConnectionString, "Database=[^;]*", $"Database={_databaseName}", RegexOptions.IgnoreCase) + : $"{BaseConnectionString};Database={_databaseName}"; + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + builder.ConfigureAppConfiguration((_, config) => + { + var all = new Dictionary + { + ["ConnectionStrings:DefaultConnection"] = ConnectionString, + // Fresh availability answers instead of a cached one. + ["Availability:StatusCacheSeconds"] = "0", + }; + foreach (var (key, value) in _settings) + { + all[key] = value; + } + + config.AddInMemoryCollection(all); + }); + } + + public async Task WithDb(Func> action) + { + await using var scope = Services.CreateAsyncScope(); + return await action(scope.ServiceProvider.GetRequiredService()); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + try + { + using var scope = Services.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.EnsureDeleted(); + } + catch + { + // Best effort clean-up of the throwaway database. + } + } + + base.Dispose(disposing); + } +} + +public sealed class EnabledContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:SiteId"] = "pipeline-site", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}); + +public sealed class DisabledContactHostFactory() : ContactHostFactory; + +/// Only the form policy is tight, so a token can still be fetched freely. +public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "2", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}); + +/// Only the token policy is tight. +public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "2", +}); diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs new file mode 100644 index 0000000..890b297 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs @@ -0,0 +1,318 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +internal static class Http +{ + public const string Route = "/api/v1/contact-messages"; + + public static async Task GetTokenAsync(HttpClient client) + { + var response = await client.GetAsync($"{Route}/token"); + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return json.RootElement.GetProperty("token").GetString()!; + } + + public static Task PostAsync( + HttpClient client, string json, string? key = "new", bool useKey = true) + { + var request = new HttpRequestMessage(HttpMethod.Post, Route) + { + Content = new StringContent(json, Encoding.UTF8, "application/json"), + }; + if (useKey) + { + request.Headers.Add("Idempotency-Key", key == "new" ? Guid.NewGuid().ToString() : key); + } + + return client.SendAsync(request); + } + + public static string Body(string token, string name = "Jan Jansen", string hp = "") => + JsonSerializer.Serialize(new + { + name, + email = "jan@example.nl", + subject = "website", + message = "Ik wil graag een offerte.", + hpCheck = hp, + token, + }); +} + +public class ContactPipelineEnabledTests(EnabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheTokenRoute_ReturnsATokenTheMinimumTime_AndNoCaptcha() + { + var response = await factory.CreateClient().GetAsync($"{Http.Route}/token"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + json.RootElement.GetProperty("token").GetString().Should().NotBeNullOrWhiteSpace(); + json.RootElement.GetProperty("minSeconds").GetInt32().Should().Be(0); + json.RootElement.GetProperty("captcha").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task AValidSubmission_Returns202_IsStoredOnce_AndAReplayDoesNotStoreAgain() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + var key = Guid.NewGuid().ToString(); + var body = Http.Body(token, name: "Pipeline Genuine"); + + var first = await Http.PostAsync(client, body, key); + var second = await Http.PostAsync(client, body, key); + + first.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await first.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + second.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await second.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + + var rows = await factory.WithDb(db => db.ContactMessages.AsNoTracking().Where(m => m.Name == "Pipeline Genuine").ToListAsync()); + rows.Should().ContainSingle(); + rows[0].Status.Should().Be(ContactMessageStatus.New); + rows[0].SiteId.Should().Be("pipeline-site"); + rows[0].RetentionUntil.Should().BeAfter(DateTimeOffset.UtcNow.AddMonths(11)); + } + + [Fact] + public async Task AFilledHoneypot_GetsTheIdenticalAnswer_ButIsStoredAsSpam() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + var response = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Bot", hp: "http://spam")); + + response.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await response.Content.ReadAsStringAsync()).Should().Be("""{"status":"received"}"""); + var row = await factory.WithDb(db => db.ContactMessages.AsNoTracking().SingleAsync(m => m.Name == "Pipeline Bot")); + row.Status.Should().Be(ContactMessageStatus.Spam); + row.MailStatus.Should().Be(ContactMailStatus.NotApplicable); + row.RetentionUntil.Should().BeBefore(DateTimeOffset.UtcNow.AddDays(31)); + } + + [Fact] + public async Task InvalidFields_Return400_WithTheContractedShape() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + var json = JsonSerializer.Serialize(new { name = "", email = "nope", subject = "s", message = "m", hpCheck = "", token }); + + var response = await Http.PostAsync(client, json); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = doc.RootElement; + root.GetProperty("status").GetInt32().Should().Be(400); + root.GetProperty("type").GetString().Should().Be("about:blank"); + root.GetProperty("errors").GetProperty("name")[0].GetString().Should().Be("required"); + root.GetProperty("errors").GetProperty("email")[0].GetString().Should().Be("invalid"); + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Subject == "s"))).Should().Be(0); + } + + [Fact] + public async Task AMissingIdempotencyKey_Returns400() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + var response = await Http.PostAsync(client, Http.Body(token), useKey: false); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("idempotencyKey")[0].GetString().Should().Be("required"); + } + + [Fact] + public async Task AForgedToken_IsReportedAsExpired() + { + var response = await Http.PostAsync(factory.CreateClient(), Http.Body("forged-token")); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("token")[0].GetString().Should().Be("expired"); + } + + [Theory] + [InlineData("{ this is not json")] + [InlineData("""{"name": 123, "email": "a@b.nl"}""")] + [InlineData("")] + public async Task AnUnbindableBody_Returns400_InOurShape_WithoutEchoingTheInput(string body) + { + var response = await Http.PostAsync(factory.CreateClient(), body); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var doc = JsonDocument.Parse(text); + doc.RootElement.GetProperty("errors").GetProperty("body")[0].GetString().Should().Be("invalid"); + text.Should().NotContain("this is not json").And.NotContain("a@b.nl"); + } + + [Fact] + public async Task ABodyBeyondTheLimit_Returns413_AsProblemJson() + { + var client = factory.CreateClient(); + var huge = new string('x', 20_000); + + var response = await Http.PostAsync(client, JsonSerializer.Serialize(new { message = huge })); + + response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("status").GetInt32().Should().Be(413); + } + + [Fact] + public async Task TheMigration_CreatedBothTables_AndTheIdempotencyKeyIsUnique() + { + var count = await factory.WithDb(async db => + { + var key = Guid.NewGuid(); + db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); + await db.SaveChangesAsync(); + db.ChangeTracker.Clear(); + + db.IdempotencyRecords.Add(new IdempotencyRecord { SiteId = "dup", Key = key, CreatedAt = DateTimeOffset.UtcNow, StatusCode = 202 }); + var act = () => db.SaveChangesAsync(); + await act.Should().ThrowAsync("the same site cannot use a key twice"); + + return await db.ContactMessages.CountAsync(); + }); + + count.Should().BeGreaterThanOrEqualTo(0); + } + + [Fact] + public async Task TheRetentionJob_RemovesExpiredRows_InTheRealDatabase() + { + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = Guid.NewGuid(), SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddYears(-2), + Name = "Pipeline Expired", Email = "a@b.nl", Subject = "s", Message = "m", + Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddDays(-1), + }); + await db.SaveChangesAsync(); + return 0; + }); + + var job = factory.Services.GetServices().OfType().Single(); + await job.ExecuteTickAsync(CancellationToken.None); + + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Expired"))).Should().Be(0); + } +} + +public class ContactPipelineDisabledTests(DisabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task WhileDisabled_BothRoutesAre404_WithAnEmptyBody() + { + var client = factory.CreateClient(); + + var token = await client.GetAsync($"{Http.Route}/token"); + var post = await Http.PostAsync(client, Http.Body("anything")); + + token.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await token.Content.ReadAsStringAsync()).Should().BeEmpty(); + post.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await post.Content.ReadAsStringAsync()).Should().BeEmpty(); + } + + [Fact] + public async Task WhileDisabled_TheModuleNeverTouchedTheDatabase_AndTheRetentionJobDoesNothing() + { + // The host has started (other modules migrated their tables), but the contact tables do + // not exist: the module neither migrated nor queried anything. + await using var connection = new MySql.Data.MySqlClient.MySqlConnection(factory.ConnectionString); + await connection.OpenAsync(); + await using var command = connection.CreateCommand(); + command.CommandText = + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name IN ('ContactMessages','ContactIdempotency')"; + Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0); + + _ = factory.CreateClient(); // make sure the host is up + var job = factory.Services.GetServices().OfType().Single(); + await job.ExecuteTickAsync(CancellationToken.None); + + Convert.ToInt32(await command.ExecuteScalarAsync()).Should().Be(0, "the disabled job must not create or touch anything"); + } +} + +public class ContactPipelineFormRateLimitTests(TightFormLimitContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheFormPolicy_Answers429_WithRetryAfter_AndOnlyTheStandardFields() + { + var client = factory.CreateClient(); + var token = await Http.GetTokenAsync(client); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await Http.PostAsync(client, Http.Body(token, name: $"Pipeline Limit {i}")); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); + int.Parse(retryAfter!.Single()).Should().BeInRange(1, 600); + last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await last.Content.ReadAsStringAsync()); + doc.RootElement.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["type", "title", "status"]); + } + +} + +public class ContactPipelineTokenRateLimitTests(TightTokenLimitContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheTokenPolicy_AnswersAfterItsOwnLimit_With429AndRetryAfter() + { + var client = factory.CreateClient(); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await client.GetAsync($"{Http.Route}/token"); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + last.Headers.Contains("Retry-After").Should().BeTrue(); + } +} + +public class ContactPipelineGateTests(EnabledContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task TheContactRoutes_StayReachable_WhileTheCmsIsDisabled_ButAdminRoutesAreBlocked() + { + // Switch the CMS off through the availability state of the real database. + await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( + "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')")); + var client = factory.CreateClient(); + + (await client.GetAsync("/api/v1/offerings/categories")).StatusCode + .Should().Be(HttpStatusCode.ServiceUnavailable, "the gate really is closed"); + + var token = await Http.GetTokenAsync(client); + var post = await Http.PostAsync(client, Http.Body(token, name: "Pipeline Gate")); + + post.StatusCode.Should().Be(HttpStatusCode.Accepted); + (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Gate"))).Should().Be(1); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj b/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj new file mode 100644 index 0000000..08c6e9f --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/SlpModularCms.Modules.Contact.Tests.csproj @@ -0,0 +1,39 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs b/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs new file mode 100644 index 0000000..afe9db2 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/SubmissionHarness.cs @@ -0,0 +1,97 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +/// Captures every log entry so tests can prove nothing personal is ever logged. +public sealed class CapturingLoggerProvider : ILoggerProvider +{ + public List Messages { get; } = []; + + public ILogger CreateLogger(string categoryName) => new CapturingLogger(Messages); + public void Dispose() { } + + private sealed class CapturingLogger(List messages) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + lock (messages) + { + messages.Add(formatter(state, exception)); + if (exception is not null) + { + messages.Add(exception.ToString()); + } + } + } + } +} + +/// +/// The submission service wired to a real in-memory database, a real token service and a fake +/// clock; only the captcha and the mail sender are substitutes. +/// +public sealed class SubmissionHarness : IDisposable +{ + public static readonly DateTimeOffset Start = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + public FakeTimeProvider Time { get; } = new(Start); + public ContactOptions Options { get; } + public ContactDbContext Db { get; } + public IContactRepository Repository { get; } + public IContactTokenService Tokens { get; } + public ICaptchaVerifier Captcha { get; } = Substitute.For(); + public IContactMailSender Mail { get; } = Substitute.For(); + public CapturingLoggerProvider Logs { get; } = new(); + public ContactSubmissionService Sut { get; } + + public SubmissionHarness(Action? configure = null, IContactRepository? repositoryOverride = null) + { + Options = new ContactOptions { Enabled = true, SiteId = "site-a", MinSeconds = 3 }; + configure?.Invoke(Options); + + Db = new ContactDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options); + Repository = repositoryOverride ?? new ContactRepository(Db); + + var wrapped = Microsoft.Extensions.Options.Options.Create(Options); + Tokens = new ContactTokenService(DataProtectionProvider.Create("submission-tests"), wrapped, Time); + + Captcha.VerifyAsync(Arg.Any(), Arg.Any()).Returns(true); + Mail.SendAsync(Arg.Any(), Arg.Any()) + .Returns(ContactMailOutcome.Skipped); + + var loggerFactory = LoggerFactory.Create(b => b.AddProvider(Logs)); + Sut = new ContactSubmissionService( + Repository, Tokens, Captcha, Mail, wrapped, Time, loggerFactory.CreateLogger()); + } + + /// A token that is old enough to pass the minimum-time check. + public string MatureToken() + { + var token = Tokens.Issue(); + Time.Advance(TimeSpan.FromSeconds(Options.MinSeconds + 1)); + return token; + } + + public static ContactMessageRequest Request(string token, string hp = "", string? captcha = null) => new( + "Jan Jansen", "jan@example.nl", "website", "Ik wil graag een offerte.", hp, token, captcha); + + public Task Submit(ContactMessageRequest? request, string? key = null) + => Sut.SubmitAsync(request, key ?? Guid.NewGuid().ToString(), CancellationToken.None); + + public void Dispose() => Db.Dispose(); +} diff --git a/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs b/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs new file mode 100644 index 0000000..1d122b4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Config/ContactOptions.cs @@ -0,0 +1,52 @@ +namespace SlpModularCms.Modules.Contact.Config; + +/// +/// Per-host configuration of the contact module (section Contact). +/// +public class ContactOptions +{ + public const string SectionName = "Contact"; + + /// + /// Master switch. While false the contact routes answer 404 and the module touches nothing. + /// It must only be switched on for a public host once per-client rate limiting is in place + /// (see ). + /// + public bool Enabled { get; set; } + + /// Identifies the site on stored rows and in the token purpose. Never taken from a request. + public string? SiteId { get; set; } + + /// Minimum seconds between issuing the token and submitting; faster submissions are treated as spam. + public int MinSeconds { get; set; } = 3; + + public int TokenLifetimeMinutes { get; set; } = 120; + + /// Months a genuine message is kept (fixed per row at insert). + public int RetentionMonths { get; set; } = 12; + + /// Days a message classified as spam is kept. + public int SpamRetentionDays { get; set; } = 30; + + /// Per site and UTC day; beyond it spam is answered normally but not stored. + public int MaxSpamRowsPerDay { get; set; } = 200; + + public int MaxBodyBytes { get; set; } = 16384; + + /// Base of the validation problem type URI. When empty the type is about:blank. + public string? ProblemTypeBase { get; set; } + + public ContactCaptchaOptions Captcha { get; set; } = new(); + + public string EffectiveSiteId => string.IsNullOrWhiteSpace(SiteId) ? "default" : SiteId.Trim(); +} + +public class ContactCaptchaOptions +{ + public bool Enabled { get; set; } + public string? Provider { get; set; } + public string? SiteKey { get; set; } + + /// Server-side secret; supply it through the environment or a secrets manager, never committed. + public string? Secret { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs new file mode 100644 index 0000000..06ac096 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -0,0 +1,89 @@ +using System.Diagnostics.CodeAnalysis; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Modules; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact; + +[ExcludeFromCodeCoverage] +public class ContactModule : IModule +{ + public string Name => "Contact"; + public string Version => "1.0.0"; + + public void RegisterServices(IServiceCollection services) + { + services.AddOptions() + .Configure((options, config) => + config.GetSection(ContactOptions.SectionName).Bind(options)); + + services.AddDbContext((serviceProvider, options) => + { + var config = serviceProvider.GetRequiredService(); + options.UseMySQL(config.GetConnectionString("DefaultConnection")!); + options.ReplaceService(); + }); + + services.TryAddSingleton(TimeProvider.System); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); + + // Rate-limit policies live in this module so the shared limiter setup stays untouched. + // The bucket key comes from one function; see ContactRateLimitPartition. + services.AddOptions() + .Configure((limiter, config) => + { + limiter.AddPolicy(ContactMessagesController.FormPolicy, context => + Window(config, "ContactForm", 5, 600, context)); + limiter.AddPolicy(ContactMessagesController.TokenPolicy, context => + Window(config, "ContactToken", 20, 600, context)); + }); + } + + public void UseModule(IApplicationBuilder app) + { + // Nothing is touched while the module is switched off: not even the database. + var enabled = app.ApplicationServices.GetRequiredService>().Value.Enabled; + if (!enabled) + { + return; + } + + using var scope = app.ApplicationServices.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.Migrate(); + } + + private static RateLimitPartition Window( + IConfiguration config, string name, int defaultPermits, int defaultSeconds, Microsoft.AspNetCore.Http.HttpContext context) + { + var section = config.GetSection($"RateLimiting:{name}"); + return RateLimitPartition.GetFixedWindowLimiter( + ContactRateLimitPartition.KeyFor(context), + _ => new FixedWindowRateLimiterOptions + { + PermitLimit = section.GetValue("PermitLimit", defaultPermits), + Window = TimeSpan.FromSeconds(section.GetValue("WindowSeconds", defaultSeconds)), + QueueLimit = 0, + }); + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs new file mode 100644 index 0000000..246199d --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs @@ -0,0 +1,71 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// The public contact routes. Deliberately not an [ApiController]: a body that cannot be +/// bound must produce our own problem shape, never the framework's, and must not echo values. +/// The management routes (list, read, delete, resend) are added with the admin unit. +/// +[Route("contact-messages")] +[ServiceFilter(typeof(ContactRouteFilter))] +public class ContactMessagesController( + IContactTokenService tokens, + IContactSubmissionService submissions, + IOptions options) : ControllerBase +{ + public const string IdempotencyKeyHeader = "Idempotency-Key"; + public const string TokenPolicy = "contact-token"; + public const string FormPolicy = "contact-form"; + + [HttpGet("token")] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting(TokenPolicy)] + public IActionResult GetToken() + { + var settings = options.Value; + var captcha = settings.Captcha is { Enabled: true } c && !string.IsNullOrWhiteSpace(c.Provider) + ? new ContactCaptchaInfo(c.Provider!, c.SiteKey ?? string.Empty) + : null; + + return Ok(new ContactTokenResponse(tokens.Issue(), settings.MinSeconds, captcha)); + } + + [HttpPost] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting(FormPolicy)] + public async Task Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken) + { + var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault(); + + // An unbindable body (malformed JSON, wrong types) arrives as null. + var result = await submissions.SubmitAsync(ModelState.IsValid ? request : null, key, cancellationToken); + + return result switch + { + SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)), + _ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted }, + }; + } + + private ValidationProblemDetails Problem(IReadOnlyDictionary errors) + { + var baseUri = options.Value.ProblemTypeBase?.TrimEnd('/'); + return new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value)) + { + Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation", + Title = "Validation failed", + Status = StatusCodes.Status400BadRequest, + }; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs new file mode 100644 index 0000000..aada5a8 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactRouteFilter.cs @@ -0,0 +1,63 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// Runs before model binding on the public contact routes: +/// 1. While the form is not open (see ) the route does not exist +/// (404, empty body). +/// 2. Caps the request body (413 as problem+json), also when the size is only known while reading. +/// +public sealed class ContactRouteFilter(IContactFormGate gate, IOptions options) : IAsyncResourceFilter +{ + public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) + { + var settings = options.Value; + if (!await gate.IsOpenAsync(context.HttpContext.RequestAborted)) + { + context.Result = new NotFoundResult(); + return; + } + + var request = context.HttpContext.Request; + if (HttpMethods.IsPost(request.Method)) + { + if (request.ContentLength > settings.MaxBodyBytes) + { + context.Result = TooLarge(); + return; + } + + // For chunked bodies the length is unknown up front; Kestrel enforces the cap while reading. + var feature = context.HttpContext.Features.Get(); + if (feature is { IsReadOnly: false }) + { + feature.MaxRequestBodySize = settings.MaxBodyBytes; + } + } + + var executed = await next(); + + if (executed.Exception is BadHttpRequestException { StatusCode: StatusCodes.Status413PayloadTooLarge }) + { + executed.ExceptionHandled = true; + executed.Result = TooLarge(); + } + } + + private static ObjectResult TooLarge() => new(new ProblemDetails + { + Status = StatusCodes.Status413PayloadTooLarge, + Title = "Payload too large", + }) + { + StatusCode = StatusCodes.Status413PayloadTooLarge, + ContentTypes = { "application/problem+json" }, + }; +} diff --git a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs new file mode 100644 index 0000000..cbb12e4 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs @@ -0,0 +1,44 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Data; + +public class ContactDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet ContactMessages => Set(); + public DbSet IdempotencyRecords => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(entity => + { + entity.ToTable("ContactMessages"); + entity.HasKey(e => e.Id); + entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100); + entity.Property(e => e.ReceivedAt).IsRequired(); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.Email).IsRequired().HasMaxLength(254); + entity.Property(e => e.Subject).IsRequired().HasMaxLength(100); + entity.Property(e => e.Message).IsRequired().HasMaxLength(2000); + entity.Property(e => e.Status).IsRequired().HasConversion().HasMaxLength(20); + entity.Property(e => e.MailStatus).IsRequired().HasConversion().HasMaxLength(20); + entity.Property(e => e.MailError).HasMaxLength(100); + entity.Property(e => e.RetentionUntil).IsRequired(); + + entity.HasIndex(e => new { e.SiteId, e.Status, e.ReceivedAt }); + entity.HasIndex(e => e.RetentionUntil); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("ContactIdempotency"); + entity.HasKey(e => new { e.SiteId, e.Key }); + entity.Property(e => e.SiteId).IsRequired().HasMaxLength(100); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.StatusCode).IsRequired(); + entity.HasIndex(e => e.CreatedAt); + }); + } +} diff --git a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs new file mode 100644 index 0000000..82ac5ae --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs @@ -0,0 +1,58 @@ +namespace SlpModularCms.Modules.Contact.Data.Entities; + +public enum ContactMessageStatus +{ + New, + Read, + Archived, + Spam, + Converted, +} + +public enum ContactMailStatus +{ + /// Waiting to be mailed (also the state while no mail sender is available). + Pending, + Sent, + Failed, + /// Never mailed on purpose (spam). + NotApplicable, +} + +/// +/// A message sent through the website's contact form. Has its own id and status so that it can +/// later be turned into an assignment (quotes, invoices); that is not built yet. +/// +public class ContactMessage +{ + public Guid Id { get; set; } + public string SiteId { get; set; } = string.Empty; + public DateTimeOffset ReceivedAt { get; set; } + public string Name { get; set; } = string.Empty; + public string Email { get; set; } = string.Empty; + + /// Opaque value chosen by the site (a package id, a slug, or 'other'). + public string Subject { get; set; } = string.Empty; + + public string Message { get; set; } = string.Empty; + public ContactMessageStatus Status { get; set; } + public ContactMailStatus MailStatus { get; set; } + + /// Short error code of the last failed mail attempt (never an address or content). + public string? MailError { get; set; } + + public int MailAttempts { get; set; } + public DateTimeOffset? NextMailAttemptAt { get; set; } + + /// Fixed at insert: a later configuration change does not apply retroactively. + public DateTimeOffset RetentionUntil { get; set; } +} + +/// Remembers an Idempotency-Key for 24 hours. Holds no request content. +public class IdempotencyRecord +{ + public string SiteId { get; set; } = string.Empty; + public Guid Key { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public int StatusCode { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs new file mode 100644 index 0000000..f95d4d6 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.Designer.cs @@ -0,0 +1,115 @@ +ο»Ώ// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Contact.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + [DbContext(typeof(ContactDbContext))] + [Migration("20261109200014_InitialCreate")] + partial class InitialCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("varchar(254)"); + + b.Property("MailAttempts") + .HasColumnType("int"); + + b.Property("MailError") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("MailStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("varchar(2000)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NextMailAttemptAt") + .HasColumnType("datetime"); + + b.Property("ReceivedAt") + .HasColumnType("datetime"); + + b.Property("RetentionUntil") + .HasColumnType("datetime"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("RetentionUntil"); + + b.HasIndex("SiteId", "Status", "ReceivedAt"); + + b.ToTable("ContactMessages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => + { + b.Property("SiteId") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Key") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.HasKey("SiteId", "Key"); + + b.HasIndex("CreatedAt"); + + b.ToTable("ContactIdempotency", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs new file mode 100644 index 0000000..1c2d26c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109200014_InitialCreate.cs @@ -0,0 +1,82 @@ +ο»Ώusing System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + /// + public partial class InitialCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ContactIdempotency", + columns: table => new + { + SiteId = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Key = table.Column(type: "char(36)", nullable: false), + CreatedAt = table.Column(type: "datetime", nullable: false), + StatusCode = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactIdempotency", x => new { x.SiteId, x.Key }); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "ContactMessages", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + SiteId = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + ReceivedAt = table.Column(type: "datetime", nullable: false), + Name = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Email = table.Column(type: "varchar(254)", maxLength: 254, nullable: false), + Subject = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Message = table.Column(type: "varchar(2000)", maxLength: 2000, nullable: false), + Status = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + MailStatus = table.Column(type: "varchar(20)", maxLength: 20, nullable: false), + MailError = table.Column(type: "varchar(100)", maxLength: 100, nullable: true), + MailAttempts = table.Column(type: "int", nullable: false), + NextMailAttemptAt = table.Column(type: "datetime", nullable: true), + RetentionUntil = table.Column(type: "datetime", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactMessages", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_ContactIdempotency_CreatedAt", + table: "ContactIdempotency", + column: "CreatedAt"); + + migrationBuilder.CreateIndex( + name: "IX_ContactMessages_RetentionUntil", + table: "ContactMessages", + column: "RetentionUntil"); + + migrationBuilder.CreateIndex( + name: "IX_ContactMessages_SiteId_Status_ReceivedAt", + table: "ContactMessages", + columns: new[] { "SiteId", "Status", "ReceivedAt" }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ContactIdempotency"); + + migrationBuilder.DropTable( + name: "ContactMessages"); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs new file mode 100644 index 0000000..52b5f28 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs @@ -0,0 +1,112 @@ +ο»Ώ// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Contact.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + [DbContext(typeof(ContactDbContext))] + partial class ContactDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("varchar(254)"); + + b.Property("MailAttempts") + .HasColumnType("int"); + + b.Property("MailError") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("MailStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("varchar(2000)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NextMailAttemptAt") + .HasColumnType("datetime"); + + b.Property("ReceivedAt") + .HasColumnType("datetime"); + + b.Property("RetentionUntil") + .HasColumnType("datetime"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("RetentionUntil"); + + b.HasIndex("SiteId", "Status", "ReceivedAt"); + + b.ToTable("ContactMessages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => + { + b.Property("SiteId") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Key") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.HasKey("SiteId", "Key"); + + b.HasIndex("CreatedAt"); + + b.ToTable("ContactIdempotency", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Models/ContactModels.cs b/src/SlpModularCms.Modules.Contact/Models/ContactModels.cs new file mode 100644 index 0000000..6f0367c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Models/ContactModels.cs @@ -0,0 +1,44 @@ +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Contact.Models; + +/// +/// The body of POST /contact-messages. Everything is nullable on purpose: a missing field is +/// reported as the validation code required in our own problem shape instead of a +/// framework binding error. HpCheck is the honeypot (JSON name hpCheck). +/// +public record ContactMessageRequest( + string? Name, + string? Email, + string? Subject, + string? Message, + string? HpCheck, + string? Token, + string? CaptchaToken); + +[ExcludeFromCodeCoverage] +public record ContactCaptchaInfo(string Provider, string SiteKey); + +[ExcludeFromCodeCoverage] +public record ContactTokenResponse(string Token, int MinSeconds, ContactCaptchaInfo? Captcha); + +[ExcludeFromCodeCoverage] +public record ReceivedResponse(string Status); + +/// Validation error codes, as the client maps them to texts. +public static class ContactErrorCodes +{ + public const string Required = "required"; + public const string TooLong = "tooLong"; + public const string Invalid = "invalid"; + public const string Expired = "expired"; +} + +/// Outcome of handling one submission. +public abstract record SubmissionResult +{ + /// Accepted: genuine, spam and replays all look the same to the caller. + public sealed record Received : SubmissionResult; + + public sealed record Invalid(IReadOnlyDictionary Errors) : SubmissionResult; +} diff --git a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs new file mode 100644 index 0000000..fb26df7 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs @@ -0,0 +1,75 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Repositories; + +public interface IContactRepository +{ + Task GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken); + Task CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken); + void Add(ContactMessage message); + void Add(IdempotencyRecord record); + Task SaveChangesAsync(CancellationToken cancellationToken); + Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken); + Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); +} + +public class ContactRepository(ContactDbContext context) : IContactRepository +{ + private const int BatchSize = 500; + + public Task GetIdempotencyAsync(string siteId, Guid key, CancellationToken cancellationToken) + => context.IdempotencyRecords.FirstOrDefaultAsync(r => r.SiteId == siteId && r.Key == key, cancellationToken); + + public Task CountSpamSinceAsync(string siteId, DateTimeOffset since, CancellationToken cancellationToken) + => context.ContactMessages.CountAsync( + m => m.SiteId == siteId && m.Status == ContactMessageStatus.Spam && m.ReceivedAt >= since, + cancellationToken); + + public void Add(ContactMessage message) => context.ContactMessages.Add(message); + + public void Add(IdempotencyRecord record) => context.IdempotencyRecords.Add(record); + + public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken); + + public async Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken) + { + var total = 0; + while (true) + { + var batch = await context.ContactMessages + .Where(m => m.RetentionUntil < now) + .Take(BatchSize) + .ToListAsync(cancellationToken); + if (batch.Count == 0) + { + return total; + } + + context.ContactMessages.RemoveRange(batch); + await context.SaveChangesAsync(cancellationToken); + total += batch.Count; + } + } + + public async Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken) + { + var total = 0; + while (true) + { + var batch = await context.IdempotencyRecords + .Where(r => r.CreatedAt < cutoff) + .Take(BatchSize) + .ToListAsync(cancellationToken); + if (batch.Count == 0) + { + return total; + } + + context.IdempotencyRecords.RemoveRange(batch); + await context.SaveChangesAsync(cancellationToken); + total += batch.Count; + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs b/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs new file mode 100644 index 0000000..7676c17 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactFormGate.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Decides whether the public contact form is active. The form is active only when every layer +/// says so; if any layer is off the public routes answer 404 with an empty body (the website +/// then shows its mailto fallback). +/// +/// +/// Layers: (1) the host switch Contact:Enabled (release condition, default off) and, +/// from the admin unit on, (2) a switch an administrator controls in the CMS. The route filter +/// only knows this interface, so adding the second layer does not touch the filter. +/// +public interface IContactFormGate +{ + Task IsOpenAsync(CancellationToken cancellationToken); +} + +/// Layer 1: the host configuration. +public sealed class HostFlagContactFormGate(IOptions options) : IContactFormGate +{ + public Task IsOpenAsync(CancellationToken cancellationToken) => Task.FromResult(options.Value.Enabled); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs new file mode 100644 index 0000000..3b3a0a8 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactRetentionService.cs @@ -0,0 +1,58 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Daily clean-up: deletes messages past their retention date and idempotency records older +/// than 24 hours. While the module is disabled it does nothing at all (no database access). +/// +public class ContactRetentionService( + IServiceScopeFactory scopeFactory, + IOptions options, + TimeProvider time, + ILogger logger) : BackgroundService +{ + internal static readonly TimeSpan Interval = TimeSpan.FromHours(24); + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await ExecuteTickAsync(stoppingToken); + + using var timer = new PeriodicTimer(Interval); + while (await timer.WaitForNextTickAsync(stoppingToken)) + { + await ExecuteTickAsync(stoppingToken); + } + } + + internal async Task ExecuteTickAsync(CancellationToken stoppingToken) + { + if (!options.Value.Enabled) + { + return; + } + + try + { + await using var scope = scopeFactory.CreateAsyncScope(); + var repository = scope.ServiceProvider.GetRequiredService(); + var now = time.GetUtcNow(); + + var messages = await repository.DeleteExpiredMessagesAsync(now, stoppingToken); + var records = await repository.DeleteIdempotencyOlderThanAsync(now - TimeSpan.FromHours(24), stoppingToken); + + logger.LogInformation( + "Contact retention: removed {Messages} expired message(s) and {Records} idempotency record(s)", + messages, records); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError("Contact retention run failed ({ExceptionType})", ex.GetType().Name); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs new file mode 100644 index 0000000..c68ea7a --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Http; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Verifies a captcha token server-side. Implementations must fail open: when the provider +/// itself is unreachable they return true (and log without personal data), so real +/// visitors are never locked out by a provider outage. +/// +public interface ICaptchaVerifier +{ + Task VerifyAsync(string? captchaToken, CancellationToken cancellationToken); +} + +/// Used while no captcha is configured: everything passes. +public sealed class NullCaptchaVerifier : ICaptchaVerifier +{ + public Task VerifyAsync(string? captchaToken, CancellationToken cancellationToken) => Task.FromResult(true); +} + +public enum ContactMailOutcome +{ + /// No mail was attempted (no sender available yet); the message stays pending. + Skipped, + Sent, + Failed, +} + +/// +/// Sends the notification mail for a genuine message. Called after the message is stored; a +/// failure must never fail the request. The real implementation arrives with the mail unit. +/// +public interface IContactMailSender +{ + Task SendAsync(ContactMessage message, CancellationToken cancellationToken); +} + +public sealed class NoOpContactMailSender : IContactMailSender +{ + public Task SendAsync(ContactMessage message, CancellationToken cancellationToken) + => Task.FromResult(ContactMailOutcome.Skipped); +} + +/// +/// The single place that decides which rate-limit bucket a request belongs to. +/// +/// +/// On the base branch the rate limiter has no per-client partitioning (no forwarded-header +/// handling, no client key): every visitor is the same caller. This returns a constant, so the +/// contact policies behave as ONE shared bucket per policy, which is why the contact routes are +/// disabled (Contact:Enabled=false) until the per-client partitioning from the ASF branch +/// has been merged. Switching to per-client is the one-line change documented in the rebase +/// checklist: replace the body with ClientPartitionKey.For(context). +/// +public static class ContactRateLimitPartition +{ + public const string GlobalKey = "global"; + + public static string KeyFor(HttpContext context) => GlobalKey; +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs new file mode 100644 index 0000000..1b47483 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSubmissionService.cs @@ -0,0 +1,205 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +public interface IContactSubmissionService +{ + Task SubmitAsync(ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken); +} + +/// +/// Handles one submission: validate, de-duplicate, classify (genuine or spam), store, mail. +/// Genuine messages, spam and replays are indistinguishable to the caller (the same 202), so +/// bots learn nothing. Nothing personal is ever logged: only the outcome and the site id. +/// +public sealed class ContactSubmissionService( + IContactRepository repository, + IContactTokenService tokens, + ICaptchaVerifier captcha, + IContactMailSender mailSender, + IOptions options, + TimeProvider time, + ILogger logger) : IContactSubmissionService +{ + private static readonly TimeSpan IdempotencyWindow = TimeSpan.FromHours(24); + + private enum Outcome { Genuine, Spam, SpamNotStored, Replay } + + public async Task SubmitAsync( + ContactMessageRequest? request, string? idempotencyKey, CancellationToken cancellationToken) + { + var o = options.Value; + var siteId = o.EffectiveSiteId; + + // 1. Header and fields (one response lists every problem). + var errors = new Dictionary(); + Guid key = default; + if (string.IsNullOrWhiteSpace(idempotencyKey)) + { + errors["idempotencyKey"] = [ContactErrorCodes.Required]; + } + else if (!Guid.TryParse(idempotencyKey, out key)) + { + errors["idempotencyKey"] = [ContactErrorCodes.Invalid]; + } + + if (request is null) + { + errors["body"] = [ContactErrorCodes.Invalid]; + } + else + { + request = ContactValidator.Normalize(request); + foreach (var (field, codes) in ContactValidator.Validate(request)) + { + errors[field] = codes; + } + } + + if (errors.Count > 0) + { + return new SubmissionResult.Invalid(errors); + } + + var now = time.GetUtcNow(); + + // 2. Replay within 24 hours: the same answer, nothing stored twice. + var existing = await repository.GetIdempotencyAsync(siteId, key, cancellationToken); + if (existing is not null && now - existing.CreatedAt < IdempotencyWindow) + { + Log(Outcome.Replay, siteId); + return new SubmissionResult.Received(); + } + + // 3. Token. Forged, other-site and expired tokens all look the same ('expired'): no oracle. + var tokenCheck = tokens.Check(request!.Token); + if (tokenCheck == TokenCheck.InvalidOrExpired) + { + return new SubmissionResult.Invalid(new Dictionary + { + ["token"] = [ContactErrorCodes.Expired], + }); + } + + // 4. Classify. A filled honeypot, a too-fast submission or a rejected captcha is spam. + var isSpam = tokenCheck == TokenCheck.TooYoung + || !string.IsNullOrEmpty(request.HpCheck) + || (o.Captcha.Enabled && !await captcha.VerifyAsync(request.CaptchaToken, cancellationToken)); + + // 5. Store. Spam is kept for a short time (a real visitor may have tripped a check) but + // capped per day so a flood cannot fill the table. + ContactMessage? message = null; + var outcome = Outcome.Genuine; + if (isSpam) + { + var startOfDay = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero); + var spamToday = await repository.CountSpamSinceAsync(siteId, startOfDay, cancellationToken); + if (spamToday < o.MaxSpamRowsPerDay) + { + message = NewMessage(request, siteId, now, ContactMessageStatus.Spam, ContactMailStatus.NotApplicable, + now.AddDays(o.SpamRetentionDays)); + outcome = Outcome.Spam; + } + else + { + outcome = Outcome.SpamNotStored; + } + } + else + { + message = NewMessage(request, siteId, now, ContactMessageStatus.New, ContactMailStatus.Pending, + now.AddMonths(o.RetentionMonths)); + } + + if (message is not null) + { + repository.Add(message); + } + + if (existing is null) + { + repository.Add(new IdempotencyRecord + { + SiteId = siteId, + Key = key, + CreatedAt = now, + StatusCode = StatusCodes202, + }); + } + else + { + // An expired record that the daily job has not removed yet: reuse its row. + existing.CreatedAt = now; + existing.StatusCode = StatusCodes202; + } + + try + { + await repository.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + // Two requests with the same key raced; the other one won. Same answer, nothing twice. + Log(Outcome.Replay, siteId); + return new SubmissionResult.Received(); + } + + // 6. Mail, only for genuine messages and only after the message is safely stored. A mail + // problem never fails the request. + if (outcome == Outcome.Genuine && message is not null) + { + await TryMailAsync(message, cancellationToken); + } + + Log(outcome, siteId); + return new SubmissionResult.Received(); + } + + private const int StatusCodes202 = 202; + + private async Task TryMailAsync(ContactMessage message, CancellationToken cancellationToken) + { + try + { + var result = await mailSender.SendAsync(message, cancellationToken); + if (result == ContactMailOutcome.Skipped) + { + return; + } + + message.MailAttempts++; + message.MailStatus = result == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed; + await repository.SaveChangesAsync(cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Type only: the exception message could carry addresses or content. + logger.LogError("Notification mail for a contact message failed ({ExceptionType})", ex.GetType().Name); + } + } + + private static ContactMessage NewMessage( + ContactMessageRequest request, string siteId, DateTimeOffset now, + ContactMessageStatus status, ContactMailStatus mailStatus, DateTimeOffset retentionUntil) => new() + { + Id = Guid.NewGuid(), + SiteId = siteId, + ReceivedAt = now, + Name = request.Name!, + Email = request.Email!, + Subject = request.Subject!, + Message = request.Message!, + Status = status, + MailStatus = mailStatus, + RetentionUntil = retentionUntil, + }; + + private void Log(Outcome outcome, string siteId) + => logger.LogInformation("Contact submission handled: {Outcome} for site {SiteId}", outcome, siteId); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs new file mode 100644 index 0000000..ed167ed --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactTokenService.cs @@ -0,0 +1,83 @@ +using System.Globalization; +using System.Security.Cryptography; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; + +namespace SlpModularCms.Modules.Contact.Services; + +public enum TokenCheck +{ + Valid, + + /// Issued less than MinSeconds ago: the form was filled in faster than a person can. + TooYoung, + + /// Forged, garbage, from another site, or older than its lifetime. Never distinguished to the caller. + InvalidOrExpired, +} + +public interface IContactTokenService +{ + string Issue(); + TokenCheck Check(string? token); +} + +/// +/// Server-signed token for the minimum-time check. Protected with ASP.NET Data Protection (the +/// host stores the key ring in the database), bound to the site by the purpose string, so a token +/// of one site is garbage to another. Nothing is stored. +/// +public sealed class ContactTokenService : IContactTokenService +{ + private const string Version = "v1"; + + private readonly IDataProtector _protector; + private readonly ContactOptions _options; + private readonly TimeProvider _time; + + public ContactTokenService(IDataProtectionProvider provider, IOptions options, TimeProvider time) + { + _options = options.Value; + _time = time; + _protector = provider.CreateProtector(PurposeFor(_options.EffectiveSiteId)); + } + + public static string PurposeFor(string siteId) => $"SlpModularCms.Contact.Token.{siteId}"; + + public string Issue() + => _protector.Protect($"{Version}|{_time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}"); + + public TokenCheck Check(string? token) + { + if (string.IsNullOrWhiteSpace(token)) + { + return TokenCheck.InvalidOrExpired; + } + + string payload; + try + { + payload = _protector.Unprotect(token); + } + catch (CryptographicException) + { + return TokenCheck.InvalidOrExpired; + } + + var parts = payload.Split('|'); + if (parts.Length != 2 || parts[0] != Version + || !long.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var issuedAt)) + { + return TokenCheck.InvalidOrExpired; + } + + var age = _time.GetUtcNow().ToUnixTimeSeconds() - issuedAt; + if (age < 0 || age > TimeSpan.FromMinutes(_options.TokenLifetimeMinutes).TotalSeconds) + { + return TokenCheck.InvalidOrExpired; + } + + return age < _options.MinSeconds ? TokenCheck.TooYoung : TokenCheck.Valid; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs b/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs new file mode 100644 index 0000000..2392e2c --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactValidator.cs @@ -0,0 +1,115 @@ +using System.Text.RegularExpressions; +using SlpModularCms.Modules.Contact.Models; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// Field rules of the contact form. Pure: no I/O, no clock. The same limits and codes are used +/// by the client so the two can never disagree silently. +/// +public static class ContactValidator +{ + public const int NameMax = 100; + public const int EmailMax = 254; + public const int SubjectMax = 100; + public const int MessageMax = 2000; + + private static readonly Regex EmailPattern = + new(@"^[^\s@]+@[^\s@]+\.[^\s@]{2,}$", RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(250)); + + /// The request with all text fields trimmed (null stays null). + public static ContactMessageRequest Normalize(ContactMessageRequest request) => request with + { + Name = request.Name?.Trim(), + Email = request.Email?.Trim(), + Subject = request.Subject?.Trim(), + Message = request.Message?.Trim(), + Token = request.Token?.Trim(), + }; + + /// Validates an already normalized request. Keys are the JSON field names. + public static Dictionary Validate(ContactMessageRequest request) + { + var errors = new Dictionary(); + + Check(errors, "name", request.Name, NameMax, allowLineBreaks: false); + CheckEmail(errors, request.Email); + Check(errors, "subject", request.Subject, SubjectMax, allowLineBreaks: false); + Check(errors, "message", request.Message, MessageMax, allowLineBreaks: true); + + if (string.IsNullOrWhiteSpace(request.Token)) + { + errors["token"] = [ContactErrorCodes.Required]; + } + + return errors; + } + + private static void Check(Dictionary errors, string field, string? value, int max, bool allowLineBreaks) + { + if (string.IsNullOrEmpty(value)) + { + errors[field] = [ContactErrorCodes.Required]; + } + else if (value.Length > max) + { + errors[field] = [ContactErrorCodes.TooLong]; + } + else if (HasControlCharacters(value, allowLineBreaks)) + { + errors[field] = [ContactErrorCodes.Invalid]; + } + } + + private static void CheckEmail(Dictionary errors, string? value) + { + if (string.IsNullOrEmpty(value)) + { + errors["email"] = [ContactErrorCodes.Required]; + } + else if (value.Length > EmailMax) + { + errors["email"] = [ContactErrorCodes.TooLong]; + } + else if (HasControlCharacters(value, allowLineBreaks: false) || !IsEmailShaped(value)) + { + errors["email"] = [ContactErrorCodes.Invalid]; + } + } + + private static bool IsEmailShaped(string value) + { + try + { + return EmailPattern.IsMatch(value); + } + catch (RegexMatchTimeoutException) + { + return false; + } + } + + /// + /// Control characters would end up in mail headers (header injection) or break displays. + /// In the message, tabs and line breaks are normal text and allowed. + /// + internal static bool HasControlCharacters(string value, bool allowLineBreaks) + { + foreach (var c in value) + { + if (!char.IsControl(c)) + { + continue; + } + + if (allowLineBreaks && (c is '\n' or '\r' or '\t')) + { + continue; + } + + return true; + } + + return false; + } +} diff --git a/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj b/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj new file mode 100644 index 0000000..c323c4e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/SlpModularCms.Modules.Contact.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + + + + + <_Parameter1>SlpModularCms.Modules.Contact.Tests + + + + + + + + -- 2.39.5 From ce06fad727beeb0dbc0096514c3e94958ae69bf0 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 21:11:39 +0100 Subject: [PATCH 08/83] Docs: plannen CMS-U3b en CMS-U4 en privacy-aandachtspunt Sentry/IP Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 +++++ .../cms-u3-contact-core/code/summary.md | 3 ++ ...u3b-openapi-export-code-generation-plan.md | 34 ++++++++++++++ ...-contact-admin-api-code-generation-plan.md | 46 +++++++++++++++++++ 5 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index cfdeda6..a7ddf1b 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-U3 built and committed (awaiting review); next CMS-U3b plan, then CMS-U4 +- **Current Stage**: CONSTRUCTION - CMS-U3b and CMS-U4 Code Generation Part 1 (plans 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 390924f..3f0ac40 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -107,3 +107,15 @@ **Context**: Code Generation Part 1. --- + +## CMS-U3 done, CMS-U3b and CMS-U4 plans + +**Timestamp**: 2026-11-09 + +**User Input**: "CMS-U3 geaccepteerd ... Stuur het U3b-plan en het U4-plan in een bericht ... contact-settings-routes, lijst/detail/status/verwijderen/resend, spam apart, ongelezen-teller zonder spam, route-table-test als AdminOnly." (via Redesign - SLS) + +**AI Response**: U3 committed (b9af7df); plans for U3b and U4 written; Sentry/IP privacy note added to the U3 summary. + +**Context**: Code Generation Part 1. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md index 3dd97e4..f4b6856 100644 --- a/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u3-contact-core/code/summary.md @@ -53,3 +53,6 @@ Build 0 errors. Contact.Tests 113 passed (unit and pipeline), Core 205, Availabi ## Running the tests The `Pipeline` tests need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (same requirement as `Api.Tests`). Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`. + +## Attention point for the privacy statement (SLS request) +Sentry runs with `SendDefaultPii = true`: an error event for ANY request, including the contact routes, carries the caller's IP address. Nothing from the form (name, e-mail, subject, message) is ever in a Sentry event, and no IP address is stored in the contact database. The privacy statement should mention error reporting with IP addresses as a processing activity (and the Sentry data location/retention); no code action now. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md new file mode 100644 index 0000000..ca129a4 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md @@ -0,0 +1,34 @@ +# Code Generation Plan β€” CMS-U3b openapi-export + +Phase 1, right after CMS-U3. Contract: "the definitive OpenAPI document is generated by the CMS and committed, so `cms-client` generates its types from it" (Β§ 8, FR-H). Scope: the SlpSoftware host's API document as a committed file plus a test that keeps it current, and the contact contract details in it (reusable problem responses, required header, required request fields). No behaviour change of any endpoint. + +## Findings +- The host already registers `services.AddOpenApi()` (Core, document `v1`) and, in Development only, `app.MapOpenApi()` which serves `/openapi/v1.json`; the pipeline test host runs in Development, so the document can be fetched over HTTP from the real composed host (no internal API needed). +- The shared registration lives in a Core file the ASF branch also changes. Everything contact-specific is therefore added **from the Contact module** through named options (`services.Configure("v1", ...)`), leaving Core untouched. +- `.NET 10`'s OpenAPI uses `Microsoft.OpenApi` 2.x types; the transformers are written against that model (risk noted below). + +## Behaviour +1. **Committed file** `openapi/cms-api.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline. +2. **Snapshot test** (pipeline test, needs the database like the other pipeline tests): fetches `/openapi/v1.json` from the real host, normalizes it the same way, and compares it with the committed file; any drift fails the test with a message that names `UPDATE_OPENAPI=1`. With `UPDATE_OPENAPI=1` the test rewrites the file instead (and still passes), so regenerating is one command: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`. +3. **Contact contract details in the document** (module-level transformers): + - Reusable `components.responses`: `Validation` (400, `application/problem+json`, `ValidationProblem` with `errors` map of arrays of the codes `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header, `Problem`), plus schemas `Problem` and `ValidationProblem`; referenced by the contact operations. + - `POST /api/v1/contact-messages`: required header parameter `Idempotency-Key` (uuid); request body schema marks `name, email, subject, message, hpCheck, token` as required with the contract's `maxLength` values (100, 254, 100, 2000, 0 for `hpCheck`), `captchaToken` nullable; responses 202/400/413/429 (404 is documented as "form closed"). + - `GET /api/v1/contact-messages/token`: 200 (`ContactToken`: `token`, `minSeconds`, `captcha` nullable object) and 429; 404 "form closed". + - Attributes (`[ProducesResponseType]`) on the public contact actions drive the operations; the transformers only add what attributes cannot express (components, header, required/maxLength). +4. **cms-client note**: the file is the single source for generated types; the Andrea host will get its own file when it exists on the base branch (name per host, e.g. `openapi/andrea.v1.json`); this unit documents the convention in the file's README line in the summary. + +## Steps +- [ ] **Step 1 β€” Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched). +- [ ] **Step 2 β€” Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure("v1", ...)`. +- [ ] **Step 3 β€” Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them. +- [ ] **Step 4 β€” Generate and commit** `openapi/cms-api.v1.json`; review it (no PII, no secrets, no host names, no example addresses). +- [ ] **Step 5 β€” Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged). +- [ ] **Step 6 β€” Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push. + +## Explicitly NOT touched +Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' controllers (their operations simply appear in the document as generated), the Andrea host (not on the base branch), frontend. + +## Risks / open points +- The Microsoft.OpenApi 2.x model differs from 1.x examples found online; if a detail cannot be expressed through the transformer API, the unit documents it in the summary instead of faking it, and the test asserts what the document really contains. +- The file will be large (the whole host API). It is committed as is; reviewers diff it like code. +- Needs SLS confirmation: file name `openapi/cms-api.v1.json` for the SlpSoftware host (per-host naming convention proposed above). diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md new file mode 100644 index 0000000..b4cd929 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md @@ -0,0 +1,46 @@ +# Code Generation Plan β€” CMS-U4 contact-admin-api + +Phase 1, after CMS-U3b. Inputs: requirements D1/D2, contract Β§ 6 (RESTful, no `/admin` segment), Bryan's two-layer switch (SLS message), CMS-U3 gate design (`IContactFormGate`). Scope: everything an administrator does with contact messages through the API, plus the CMS-controlled on/off switch. The UI is CMS-U6; the real mail sender is CMS-U5. + +## Routes (all AdminOnly, same resource names as the public routes, no `/admin`) +New controller `ContactMessagesAdminController` (class-level `[Authorize(Policy = "AdminOnly")]`, route `contact-messages`; no action is anonymous or marked `[PublicSiteEndpoint]`), so public and admin actions are separated and the route-table tests stay trivial. Routes cannot clash with the public ones (`GET token`, `POST ""`) because of the `{id:guid}` constraint. + +| Route | Behaviour | +|---|---| +| `GET /contact-messages?status=&page=&pageSize=` | list, newest first. `status` = `new|read|archived|spam` (a single value). **Default (no status) = `new`, `read`, `archived` β€” spam is never in the default list.** `page` from 1, `pageSize` 1-100 (default 25), out-of-range values -> 400 `errors.page/pageSize=["invalid"]`. Response `{ items:[{id, receivedAt, name, email, subject, status, mailStatus}], page, pageSize, totalCount, unreadCount }`. `unreadCount` = messages with status `new`, **never counting spam**, independent of the chosen filter. Message text is not in the list. | +| `GET /contact-messages/{id:guid}` | full message: all list fields plus `message`, `mailAttempts`, `mailError` (code only), `retentionUntil`. 404 unknown. | +| `PATCH /contact-messages/{id:guid}` | body `{ "status": "new"|"read"|"archived" }`. Setting one of these on a spam row "un-spams" it (a real visitor tripped a check); its `retentionUntil` is then extended to the normal retention (now + `RetentionMonths`) so it is not deleted in 30 days; `mailStatus` stays `notApplicable` until it is resent. Other values (`spam`, `converted`, unknown) -> 400 `errors.status=["invalid"]`. 404 unknown. | +| `DELETE /contact-messages/{id:guid}` | hard delete (erasure request), 204; 404 unknown. | +| `POST /contact-messages/{id:guid}/resend` | policy `contact-resend` (5 per 600 s). Spam rows -> 409 ProblemDetails ("mark it as not spam first"). Otherwise calls `IContactMailSender`, records the outcome (`attempts+1`, status `sent|failed`; `Skipped` leaves the status and reports it) and returns `200 { mailStatus, mailAttempts, mailed: true|false }`. Until the mail unit the sender is the no-op, so `mailed=false`. 404 unknown. | +| `GET /contact-settings` | singleton: `{ "enabled": bool, "hostEnabled": bool }`. `enabled` = the CMS switch (data, default **false** when no row exists); `hostEnabled` = the host switch `Contact:Enabled` (read-only, so the UI can explain why the form is closed). | +| `PUT /contact-settings` | body `{ "enabled": true|false }`; replaces the singleton, returns the same shape as GET. Stores who changed it and when. | + +Statuses and mail statuses are serialized as lower-camel strings (`new`, `read`, `archived`, `spam`, `converted`; `pending`, `sent`, `failed`, `notApplicable`). + +## Two-layer gate (the CMS switch) +- New table `ContactSettings` (singleton row: `Id` fixed, `Enabled`, `UpdatedAt`, `UpdatedByUserId`), migration `AddContactSettings` (additive). +- `CmsFlagContactFormGate` (layer 2) reads the row (absent = closed) through a short in-process cache (5 s absolute) that `PUT /contact-settings` invalidates immediately, so the public routes do not hit the database on every request. `CompositeContactFormGate` is registered as the `IContactFormGate`: the form is open only if **both** layers are open; layers are evaluated in order **host flag first** and short-circuit, so with the host switch off the database (and its not-yet-existing tables) is never touched. +- `ContactRouteFilter` is not modified (it only knows the interface), as agreed. + +## Admin routes and the host switch +The admin routes need the Contact tables, which exist only when the host switch is on (the module migrates only then β€” the CMS-U3 requirement that a disabled module touches nothing). So when `Contact:Enabled=false` every admin route (including `contact-settings`) answers **404 with an empty body** via a small `ContactAdminRouteFilter` (host flag only; the CMS switch deliberately does not close the admin routes, otherwise nobody could switch the form back on). The UI (CMS-U6) treats a 404 on `GET /contact-settings` as "feature not available on this host" and hides the menu entry. `/System/capabilities` lists the module whenever it is loaded, so it is not enough on its own. + +## Authorization and gate +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. + +## Explicitly NOT touched +`ContactRouteFilter` (the public filter), the public controller, the public validation/submission logic, Core/Availability, Email, Identity, the frontend. + +## Notes / assumptions to confirm +1. `hostEnabled` in `GET /contact-settings` is an addition to the agreed `{ enabled }` shape (read-only, lets the UI explain a closed form). OK? +2. Un-spamming extends retention to the normal period (otherwise the row would be deleted after the remaining spam days). OK? +3. Resend of a spam row = 409 instead of mailing it silently. OK? +4. Admin routes answer 404 when the host switch is off (tables do not exist then). OK? -- 2.39.5 From f8d45eef54de810f2e58dd378236b7bff70239f3 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 21:20:45 +0100 Subject: [PATCH 09/83] OpenAPI-document van de SlpSoftware-host vastgelegd met snapshot-test en contactcontract openapi/slpsoftware.v1.json is de bron voor de gegenereerde frontend-types; een test haalt het document van de echte host op en faalt bij afwijking (UPDATE_OPENAPI=1 herschrijft het bestand). De contactmodule voegt de herbruikbare foutresponses, de verplichte Idempotency-Key en de verplichte velden met maximale lengtes toe via een documenttransformer, zodat Core ongemoeid blijft. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../cms-u3b-openapi-export/code/summary.md | 25 + ...u3b-openapi-export-code-generation-plan.md | 18 +- openapi/slpsoftware.v1.json | 1573 +++++++++++++++++ .../ContactControllerTests.cs | 4 +- .../Pipeline/OpenApiSnapshotTests.cs | 160 ++ .../ContactModule.cs | 6 + .../Controllers/ContactMessagesController.cs | 17 +- .../ContactOpenApiDocumentTransformer.cs | 176 ++ 9 files changed, 1968 insertions(+), 13 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md create mode 100644 openapi/slpsoftware.v1.json create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs create mode 100644 src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index a7ddf1b..d62d076 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-U3b and CMS-U4 Code Generation Part 1 (plans awaiting approval by Redesign - SLS) +- **Current Stage**: CONSTRUCTION - CMS-U3b built and committed; CMS-U4 in progress - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md new file mode 100644 index 0000000..0d981bb --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u3b-openapi-export/code/summary.md @@ -0,0 +1,25 @@ +# CMS-U3b openapi-export: code summary + +## Result +Committed `openapi/slpsoftware.v1.json`: the OpenAPI 3.1 document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). **Convention: one file per host, named after the host** (`openapi/slpsoftware.v1.json` now, `openapi/andreaslopfotografie.v1.json` when that host exists on the base branch). It is the single source from which the frontend client (`cms-client`) generates its types. + +Regenerate after an intended API change: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot` (needs the database like the other pipeline tests). Without the variable the same test fails when the served document differs from the file, with that command in its message (drift detection was verified by changing one value in the file). + +Normalized form (so the diff is meaningful): no `servers` (derived from the request host), object keys in ordinal order everywhere, 2-space indentation, LF, trailing newline. Reviewed for hosts, addresses and secrets; the tests assert there are none. + +## Contact contract in the document (module-level, Core untouched) +`ContactOpenApiDocumentTransformer`, registered from `ContactModule` through the named options of document `v1`: +- Reusable `components.responses`: `Validation` (400, problem+json, schema `ValidationProblem` with `errors` = map of field name -> array of `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header); schemas `Problem`, `ValidationProblem`. +- `POST /api/v1/contact-messages`: required header `Idempotency-Key` (uuid); request body required, exactly one `ContactMessageRequest` (`required`: name, email, subject, message, hpCheck, token; `maxLength` 100/254/100/2000/0, plain `string` types; `captchaToken` nullable); responses 202, 400, 404 (form closed), 413, 429. +- `GET /api/v1/contact-messages/token`: 200 (`ContactTokenResponse`), 404 (form closed), 429. +- The contact controller is not an `[ApiController]` (own error shape), so it carries `[ApiExplorerSettings(IgnoreApi = false)]` to appear in the document; `[ProducesResponseType]` attributes (with explicit content types) drive its operations. + +## Notes +- Microsoft.OpenApi 2.x model: everything above could be expressed through the document transformer; nothing had to be faked. Minor generator quirks kept as generated (e.g. nullable unions elsewhere in the document). +- The document is of the host as composed: operations of every loaded module appear. Routes that are closed at runtime (`Contact:Enabled=false`) are still documented; the 404 "form closed" response says so. + +## Side fix found while doing this +Problem details of the 400 answer are explicitly `application/problem+json` again after a class-level `[Produces]` experiment was rejected (it overrides the content type); covered by the existing pipeline test and a new controller assertion. + +## Verification (real output) +Build 0 errors. Contact.Tests 117 passed (4 new OpenApiSnapshot tests: equality with the committed file, contract content incl. header/required/maxLength/reusable responses/error codes, no hosts/addresses/secrets, deterministic normalization), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4; temporary MariaDB used and removed afterwards. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md index ca129a4..75e646e 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u3b-openapi-export-code-generation-plan.md @@ -8,22 +8,22 @@ Phase 1, right after CMS-U3. Contract: "the definitive OpenAPI document is gener - `.NET 10`'s OpenAPI uses `Microsoft.OpenApi` 2.x types; the transformers are written against that model (risk noted below). ## Behaviour -1. **Committed file** `openapi/cms-api.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline. +1. **Committed file** `openapi/slpsoftware.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline. 2. **Snapshot test** (pipeline test, needs the database like the other pipeline tests): fetches `/openapi/v1.json` from the real host, normalizes it the same way, and compares it with the committed file; any drift fails the test with a message that names `UPDATE_OPENAPI=1`. With `UPDATE_OPENAPI=1` the test rewrites the file instead (and still passes), so regenerating is one command: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`. 3. **Contact contract details in the document** (module-level transformers): - Reusable `components.responses`: `Validation` (400, `application/problem+json`, `ValidationProblem` with `errors` map of arrays of the codes `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header, `Problem`), plus schemas `Problem` and `ValidationProblem`; referenced by the contact operations. - `POST /api/v1/contact-messages`: required header parameter `Idempotency-Key` (uuid); request body schema marks `name, email, subject, message, hpCheck, token` as required with the contract's `maxLength` values (100, 254, 100, 2000, 0 for `hpCheck`), `captchaToken` nullable; responses 202/400/413/429 (404 is documented as "form closed"). - `GET /api/v1/contact-messages/token`: 200 (`ContactToken`: `token`, `minSeconds`, `captcha` nullable object) and 429; 404 "form closed". - Attributes (`[ProducesResponseType]`) on the public contact actions drive the operations; the transformers only add what attributes cannot express (components, header, required/maxLength). -4. **cms-client note**: the file is the single source for generated types; the Andrea host will get its own file when it exists on the base branch (name per host, e.g. `openapi/andrea.v1.json`); this unit documents the convention in the file's README line in the summary. +4. **cms-client note**: the file is the single source for generated types; the Andrea host will get `openapi/andreaslopfotografie.v1.json` when it exists on the base branch (name = host name); this unit documents the convention in the file's README line in the summary. ## Steps -- [ ] **Step 1 β€” Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched). -- [ ] **Step 2 β€” Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure("v1", ...)`. -- [ ] **Step 3 β€” Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them. -- [ ] **Step 4 β€” Generate and commit** `openapi/cms-api.v1.json`; review it (no PII, no secrets, no host names, no example addresses). -- [ ] **Step 5 β€” Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged). -- [ ] **Step 6 β€” Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push. +- [x] **Step 1 β€” Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched). +- [x] **Step 2 β€” Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure("v1", ...)`. +- [x] **Step 3 β€” Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them. +- [x] **Step 4 β€” Generate and commit** `openapi/slpsoftware.v1.json`; review it (no PII, no secrets, no host names, no example addresses). +- [x] **Step 5 β€” Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged). +- [x] **Step 6 β€” Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push. ## Explicitly NOT touched Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' controllers (their operations simply appear in the document as generated), the Andrea host (not on the base branch), frontend. @@ -31,4 +31,4 @@ Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' contro ## Risks / open points - The Microsoft.OpenApi 2.x model differs from 1.x examples found online; if a detail cannot be expressed through the transformer API, the unit documents it in the summary instead of faking it, and the test asserts what the document really contains. - The file will be large (the whole host API). It is committed as is; reviewers diff it like code. -- Needs SLS confirmation: file name `openapi/cms-api.v1.json` for the SlpSoftware host (per-host naming convention proposed above). +- Needs SLS confirmation: file name per host: `openapi/slpsoftware.v1.json` (approved). diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json new file mode 100644 index 0000000..b6b6248 --- /dev/null +++ b/openapi/slpsoftware.v1.json @@ -0,0 +1,1573 @@ +{ + "components": { + "responses": { + "RateLimited": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too many requests. Retry after the number of seconds in the Retry-After header.", + "headers": { + "Retry-After": { + "description": "Seconds to wait before retrying.", + "schema": { + "format": "int32", + "type": "integer" + } + } + } + }, + "TooLarge": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "The request body is too large." + }, + "Validation": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblem" + } + } + }, + "description": "Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"])." + } + }, + "schemas": { + "AvailabilityStatus": { + "type": "integer" + }, + "ChangePasswordRequest": { + "properties": { + "currentPassword": { + "type": "string" + }, + "newPassword": { + "type": "string" + } + }, + "required": [ + "currentPassword", + "newPassword" + ], + "type": "object" + }, + "ChangeRoleRequest": { + "properties": { + "newRole": { + "type": "string" + } + }, + "required": [ + "newRole" + ], + "type": "object" + }, + "CompleteSetupRequest": { + "properties": { + "password": { + "type": "string" + }, + "token": { + "type": "string" + } + }, + "required": [ + "token", + "password" + ], + "type": "object" + }, + "ContactCaptchaInfo": { + "properties": { + "provider": { + "type": "string" + }, + "siteKey": { + "type": "string" + } + }, + "required": [ + "provider", + "siteKey" + ], + "type": "object" + }, + "ContactMessageRequest": { + "properties": { + "captchaToken": { + "type": [ + "null", + "string" + ] + }, + "email": { + "maxLength": 254, + "type": "string" + }, + "hpCheck": { + "maxLength": 0, + "type": "string" + }, + "message": { + "maxLength": 2000, + "type": "string" + }, + "name": { + "maxLength": 100, + "type": "string" + }, + "subject": { + "maxLength": 100, + "type": "string" + }, + "token": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "subject", + "message", + "hpCheck", + "token" + ], + "type": "object" + }, + "ContactTokenResponse": { + "properties": { + "captcha": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ContactCaptchaInfo" + } + ] + }, + "minSeconds": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "token": { + "type": "string" + } + }, + "required": [ + "token", + "minSeconds", + "captcha" + ], + "type": "object" + }, + "CreateCmsInstanceRequest": { + "properties": { + "apiKey": { + "type": "string" + }, + "name": { + "type": "string" + }, + "url": { + "type": "string" + } + }, + "required": [ + "name", + "url", + "apiKey" + ], + "type": "object" + }, + "CreateOfferingRequest": { + "properties": { + "categoryId": { + "format": "uuid", + "type": [ + "null", + "string" + ] + }, + "ctaLabel": { + "type": "string" + }, + "description": { + "type": "string" + }, + "featured": { + "default": false, + "type": "boolean" + }, + "features": { + "items": { + "type": "string" + }, + "type": "array" + }, + "price": { + "type": "string" + }, + "priceNote": { + "type": "string" + }, + "slug": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "description", + "price", + "priceNote", + "features", + "ctaLabel" + ], + "type": "object" + }, + "CreateOwnerRequest": { + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "password": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "password" + ], + "type": "object" + }, + "InviteUserRequest": { + "properties": { + "email": { + "type": "string" + }, + "role": { + "type": "string" + } + }, + "required": [ + "email", + "role" + ], + "type": "object" + }, + "LoginRequest": { + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string" + } + }, + "required": [ + "email", + "password" + ], + "type": "object" + }, + "OfferingCategoryRequest": { + "properties": { + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "Problem": { + "description": "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.", + "properties": { + "status": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "type": "object" + }, + "ProblemDetails": { + "properties": { + "detail": { + "type": [ + "null", + "string" + ] + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "status": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "type": { + "type": [ + "null", + "string" + ] + } + }, + "type": "object" + }, + "PushStatusRequest": { + "properties": { + "disableMessage": { + "type": [ + "null", + "string" + ] + }, + "isAvailable": { + "type": "boolean" + } + }, + "required": [ + "isAvailable", + "disableMessage" + ], + "type": "object" + }, + "ReceivedResponse": { + "properties": { + "status": { + "type": "string" + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "RegisterMasterRequest": { + "properties": { + "masterUrl": { + "type": "string" + } + }, + "required": [ + "masterUrl" + ], + "type": "object" + }, + "ReorderOfferingsRequest": { + "properties": { + "orderedIds": { + "items": { + "format": "uuid", + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "orderedIds" + ], + "type": "object" + }, + "SetUserActiveRequest": { + "properties": { + "isActive": { + "type": "boolean" + } + }, + "required": [ + "isActive" + ], + "type": "object" + }, + "UpdateOfferingRequest": { + "properties": { + "categoryId": { + "format": "uuid", + "type": [ + "null", + "string" + ] + }, + "ctaLabel": { + "type": "string" + }, + "description": { + "type": "string" + }, + "featured": { + "default": false, + "type": "boolean" + }, + "features": { + "items": { + "type": "string" + }, + "type": "array" + }, + "price": { + "type": "string" + }, + "priceNote": { + "type": "string" + }, + "slug": { + "type": [ + "null", + "string" + ] + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "description", + "price", + "priceNote", + "features", + "ctaLabel" + ], + "type": "object" + }, + "UpdateProfileRequest": { + "properties": { + "email": { + "type": "string" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name", + "email" + ], + "type": "object" + }, + "UpdateStatusRequest": { + "properties": { + "newStatus": { + "$ref": "#/components/schemas/AvailabilityStatus" + }, + "reason": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "newStatus", + "reason" + ], + "type": "object" + }, + "ValidationProblem": { + "description": "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.", + "properties": { + "errors": { + "additionalProperties": { + "items": { + "enum": [ + "required", + "tooLong", + "invalid", + "expired" + ], + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "status": { + "format": "int32", + "type": "integer" + }, + "title": { + "type": "string" + }, + "type": { + "type": "string" + } + }, + "type": "object" + }, + "ValidationProblemDetails": { + "properties": { + "detail": { + "type": [ + "null", + "string" + ] + }, + "errors": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "type": "object" + }, + "instance": { + "type": [ + "null", + "string" + ] + }, + "status": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "null", + "integer", + "string" + ] + }, + "title": { + "type": [ + "null", + "string" + ] + }, + "type": { + "type": [ + "null", + "string" + ] + } + }, + "type": "object" + } + } + }, + "info": { + "title": "SlpModularCms.Api.SlpSoftware | v1", + "version": "1.0.0" + }, + "openapi": "3.1.1", + "paths": { + "/api/v1/Availability/admin/status": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + } + }, + "/api/v1/Availability/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + } + }, + "/api/v1/CmsInstances": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateCmsInstanceRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + } + }, + "/api/v1/CmsInstances/{id}/status": { + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "CmsInstance" + ] + } + }, + "/api/v1/Invitation/complete": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CompleteSetupRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Invitation" + ] + } + }, + "/api/v1/Invitation/validate": { + "get": { + "parameters": [ + { + "in": "query", + "name": "token", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Invitation" + ] + } + }, + "/api/v1/Master/register": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/RegisterMasterRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Master/registered-url": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Master/status": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/PushStatusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Master" + ] + } + }, + "/api/v1/Setup/owner": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateOwnerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Setup" + ] + } + }, + "/api/v1/Setup/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Setup" + ] + } + }, + "/api/v1/SlaveStatus": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SlaveStatus" + ] + } + }, + "/api/v1/System/capabilities": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "System" + ] + } + }, + "/api/v1/Users": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/invite": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/InviteUserRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/me": { + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateProfileRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}/active": { + "put": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/SetUserActiveRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{userId}/role": { + "put": { + "parameters": [ + { + "in": "path", + "name": "userId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ChangeRoleRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/auth/change-password": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ChangePasswordRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/login": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/refresh": { + "post": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/auth/revoke": { + "post": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, + "/api/v1/contact-messages": { + "post": { + "parameters": [ + { + "description": "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.", + "in": "header", + "name": "Idempotency-Key", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageRequest" + } + } + }, + "required": true + }, + "responses": { + "202": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReceivedResponse" + } + } + }, + "description": "Accepted" + }, + "400": { + "$ref": "#/components/responses/Validation" + }, + "404": { + "description": "The contact form is closed on this site (the website shows its mailto fallback)." + }, + "413": { + "$ref": "#/components/responses/TooLarge" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + } + }, + "tags": [ + "ContactMessages" + ] + } + }, + "/api/v1/contact-messages/token": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactTokenResponse" + } + } + }, + "description": "OK" + }, + "404": { + "description": "The contact form is closed on this site (the website shows its mailto fallback)." + }, + "429": { + "$ref": "#/components/responses/RateLimited" + } + }, + "tags": [ + "ContactMessages" + ] + } + }, + "/api/v1/offerings": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/CreateOfferingRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/api/v1/offerings/categories": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + } + }, + "/api/v1/offerings/categories/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingCategoryRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingCategories" + ] + } + }, + "/api/v1/offerings/order": { + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ReorderOfferingsRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/api/v1/offerings/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateOfferingRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Offerings" + ] + } + }, + "/health": { + "get": { + "operationId": "HealthCheck", + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SlpModularCms.Api.SlpSoftware" + ] + } + } + }, + "tags": [ + { + "name": "SlpModularCms.Api.SlpSoftware" + }, + { + "name": "System" + }, + { + "name": "Availability" + }, + { + "name": "Master" + }, + { + "name": "ContactMessages" + }, + { + "name": "Auth" + }, + { + "name": "Invitation" + }, + { + "name": "Setup" + }, + { + "name": "Users" + }, + { + "name": "CmsInstance" + }, + { + "name": "SlaveStatus" + }, + { + "name": "OfferingCategories" + }, + { + "name": "Offerings" + } + ] +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs index 05d2831..fcca3b1 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactControllerTests.cs @@ -88,7 +88,7 @@ public class ContactMessagesControllerTests var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" }) .Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None); - var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; + var problem = result.Should().BeOfType().Subject.Value.Should().BeOfType().Subject; problem.Status.Should().Be(400); problem.Type.Should().Be("https://example.test/problems/validation"); problem.Errors["email"].Should().Equal("invalid"); @@ -102,7 +102,7 @@ public class ContactMessagesControllerTests var result = await Create().Submit(null, CancellationToken.None); - ((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank"); + ((ValidationProblemDetails)((ObjectResult)result).Value!).Type.Should().Be("about:blank"); } [Fact] diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs new file mode 100644 index 0000000..1658e75 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/OpenApiSnapshotTests.cs @@ -0,0 +1,160 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// +/// Keeps the committed OpenAPI document of the SlpSoftware host (openapi/slpsoftware.v1.json) +/// equal to what the real, composed host serves, and checks the contact contract inside it. +/// +/// +/// The document is the single source from which the frontend client (cms-client) +/// generates its types. To regenerate after an intended API change run: +/// UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot. +/// +public class OpenApiSnapshotTests(DisabledContactHostFactory factory) : IClassFixture +{ + private const string FileName = "slpsoftware.v1.json"; + + private static string RepositoryRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "SlpModularCms.sln"))) + { + directory = directory.Parent; + } + + return directory?.FullName ?? throw new InvalidOperationException("SlpModularCms.sln not found above the test output."); + } + + private static string SnapshotPath() => Path.Combine(RepositoryRoot(), "openapi", FileName); + + private async Task FetchAsync() + { + var response = await factory.CreateClient().GetAsync("/openapi/v1.json"); + response.IsSuccessStatusCode.Should().BeTrue(); + return await response.Content.ReadAsStringAsync(); + } + + /// + /// A stable form: no request-derived servers, every object's keys in ordinal order (the + /// generator's order depends on assembly discovery), 2-space indentation, LF, trailing newline. + /// + internal static string Normalize(string json) + { + var root = JsonNode.Parse(json)!.AsObject(); + root.Remove("servers"); + + var text = Sort(root)!.ToJsonString(new JsonSerializerOptions + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }); + + return text.Replace("\r\n", "\n") + "\n"; + } + + private static JsonNode? Sort(JsonNode? node) => node switch + { + JsonObject obj => new JsonObject(obj + .OrderBy(p => p.Key, StringComparer.Ordinal) + .Select(p => new KeyValuePair(p.Key, Sort(p.Value)))), + JsonArray array => new JsonArray(array.Select(Sort).ToArray()), + _ => node?.DeepClone(), + }; + + [Fact] + public async Task TheCommittedDocument_EqualsWhatTheHostServes() + { + var current = Normalize(await FetchAsync()); + var path = SnapshotPath(); + + if (Environment.GetEnvironmentVariable("UPDATE_OPENAPI") == "1") + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + await File.WriteAllTextAsync(path, current, new System.Text.UTF8Encoding(false)); + return; + } + + File.Exists(path).Should().BeTrue($"{path} is missing. Generate it with: UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot"); + var committed = (await File.ReadAllTextAsync(path)).Replace("\r\n", "\n"); + + committed.Should().Be( + current, + "the OpenAPI document changed. If that is intended, regenerate the committed file with: " + + "UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot"); + } + + [Fact] + public async Task TheDocument_ContainsTheContactContract() + { + var doc = JsonNode.Parse(Normalize(await FetchAsync()))!; + var paths = doc["paths"]!.AsObject(); + + paths.Select(p => p.Key).Should().Contain(["/api/v1/contact-messages", "/api/v1/contact-messages/token"]); + + // POST /contact-messages + var post = doc["paths"]!["/api/v1/contact-messages"]!["post"]!; + var header = post["parameters"]!.AsArray().Single(p => p!["name"]!.GetValue() == "Idempotency-Key")!; + header["in"]!.GetValue().Should().Be("header"); + header["required"]!.GetValue().Should().BeTrue(); + header["schema"]!["format"]!.GetValue().Should().Be("uuid"); + + post["requestBody"]!["required"]!.GetValue().Should().BeTrue(); + post["requestBody"]!["content"]!["application/json"]!["schema"]!["$ref"]!.GetValue() + .Should().EndWith("/ContactMessageRequest"); + + post["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["202", "400", "404", "413", "429"]); + post["responses"]!["400"]!["$ref"]!.GetValue().Should().EndWith("/Validation"); + post["responses"]!["413"]!["$ref"]!.GetValue().Should().EndWith("/TooLarge"); + post["responses"]!["429"]!["$ref"]!.GetValue().Should().EndWith("/RateLimited"); + + // GET /contact-messages/token + var token = doc["paths"]!["/api/v1/contact-messages/token"]!["get"]!; + token["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["200", "404", "429"]); + + // Request schema: the contract's required fields and limits. + var request = doc["components"]!["schemas"]!["ContactMessageRequest"]!; + request["required"]!.AsArray().Select(n => n!.GetValue()) + .Should().BeEquivalentTo(["name", "email", "subject", "message", "hpCheck", "token"]); + var properties = request["properties"]!; + properties["name"]!["maxLength"]!.GetValue().Should().Be(100); + properties["email"]!["maxLength"]!.GetValue().Should().Be(254); + properties["subject"]!["maxLength"]!.GetValue().Should().Be(100); + properties["message"]!["maxLength"]!.GetValue().Should().Be(2000); + properties["hpCheck"]!["maxLength"]!.GetValue().Should().Be(0); + + // Reusable responses. + var responses = doc["components"]!["responses"]!; + responses["RateLimited"]!["headers"]!["Retry-After"].Should().NotBeNull(); + responses["Validation"]!["content"]!["application/problem+json"].Should().NotBeNull(); + responses["TooLarge"]!["content"]!["application/problem+json"].Should().NotBeNull(); + + var codes = doc["components"]!["schemas"]!["ValidationProblem"]!["properties"]!["errors"]!["additionalProperties"]!["items"]!["enum"]! + .AsArray().Select(n => n!.GetValue()); + codes.Should().BeEquivalentTo(["required", "tooLong", "invalid", "expired"]); + } + + [Fact] + public async Task TheDocument_HoldsNoHostNamesAddressesOrSecrets() + { + var text = Normalize(await FetchAsync()); + + text.Should().NotContain("127.0.0.1").And.NotContain("localhost"); + text.Should().NotContain("@", "no e-mail addresses (not even examples)"); + text.ToLowerInvariant().Should().NotContain("secret\":").And.NotContain("password\":\""); + JsonNode.Parse(text)!.AsObject().ContainsKey("servers").Should().BeFalse(); + } + + [Fact] + public void Normalize_IsDeterministic_RegardlessOfKeyOrder() + { + const string a = """{"servers":[{"url":"http://x"}],"b":1,"a":{"z":1,"y":[{"d":1,"c":2}]}}"""; + const string b = """{"a":{"y":[{"c":2,"d":1}],"z":1},"b":1}"""; + + Normalize(a).Should().Be(Normalize(b)); + Normalize(a).Should().EndWith("\n").And.NotContain("\r"); + } +} diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs index 06ac096..dc8312a 100644 --- a/src/SlpModularCms.Modules.Contact/ContactModule.cs +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -1,6 +1,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading.RateLimiting; using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.OpenApi; using Microsoft.AspNetCore.RateLimiting; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; @@ -13,6 +14,7 @@ using SlpModularCms.Core.Modules; using SlpModularCms.Modules.Contact.Config; using SlpModularCms.Modules.Contact.Controllers; using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.OpenApi; using SlpModularCms.Modules.Contact.Repositories; using SlpModularCms.Modules.Contact.Services; @@ -47,6 +49,10 @@ public class ContactModule : IModule services.AddScoped(); services.AddHostedService(); + // The contact details of the OpenAPI document (named options of document 'v1', so the shared + // AddOpenApi() call in Core stays untouched). + services.Configure("v1", openApi => openApi.AddDocumentTransformer()); + // Rate-limit policies live in this module so the shared limiter setup stays untouched. // The bucket key comes from one function; see ContactRateLimitPartition. services.AddOptions() diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs index 246199d..f0306bf 100644 --- a/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactMessagesController.cs @@ -15,6 +15,7 @@ namespace SlpModularCms.Modules.Contact.Controllers; /// bound must produce our own problem shape, never the framework's, and must not echo values. /// The management routes (list, read, delete, resend) are added with the admin unit. /// +[ApiExplorerSettings(IgnoreApi = false)] // not an [ApiController], so visibility must be explicit for the OpenAPI document [Route("contact-messages")] [ServiceFilter(typeof(ContactRouteFilter))] public class ContactMessagesController( @@ -30,6 +31,9 @@ public class ContactMessagesController( [AllowAnonymous] [PublicSiteEndpoint] [EnableRateLimiting(TokenPolicy)] + [ProducesResponseType(typeof(ContactTokenResponse), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] public IActionResult GetToken() { var settings = options.Value; @@ -44,6 +48,12 @@ public class ContactMessagesController( [AllowAnonymous] [PublicSiteEndpoint] [EnableRateLimiting(FormPolicy)] + [Consumes("application/json")] + [ProducesResponseType(typeof(ReceivedResponse), StatusCodes.Status202Accepted, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status413PayloadTooLarge, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")] public async Task Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken) { var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault(); @@ -53,7 +63,12 @@ public class ContactMessagesController( return result switch { - SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)), + SubmissionResult.Invalid invalid => new ObjectResult(Problem(invalid.Errors)) + { + StatusCode = StatusCodes.Status400BadRequest, + // Explicit content type: problem details are served as problem+json, not as plain json. + ContentTypes = { "application/problem+json" }, + }, _ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted }, }; } diff --git a/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs b/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs new file mode 100644 index 0000000..7b89045 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/OpenApi/ContactOpenApiDocumentTransformer.cs @@ -0,0 +1,176 @@ +using System.Net.Http; +using Microsoft.AspNetCore.OpenApi; +using Microsoft.OpenApi; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.OpenApi; + +/// +/// Adds what attributes cannot express to the generated OpenAPI document: the reusable problem +/// responses of the contact contract, the required Idempotency-Key header, and the +/// required fields / maximum lengths of the request body. It only touches the contact +/// operations and schemas; everything else in the document is left as generated. +/// +public sealed class ContactOpenApiDocumentTransformer : IOpenApiDocumentTransformer +{ + public const string RoutePath = "/api/v1/contact-messages"; + public const string TokenPath = "/api/v1/contact-messages/token"; + + private static readonly string[] Codes = ["required", "tooLong", "invalid", "expired"]; + + public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken) + { + AddComponents(document); + + if (document.Paths.TryGetValue(RoutePath, out var route) && route.Operations is not null + && route.Operations.TryGetValue(HttpMethod.Post, out var submit)) + { + DescribeSubmit(document, submit); + } + + if (document.Paths.TryGetValue(TokenPath, out var token) && token.Operations is not null + && token.Operations.TryGetValue(HttpMethod.Get, out var getToken)) + { + getToken.Responses ??= []; + getToken.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." }; + getToken.Responses["429"] = new OpenApiResponseReference("RateLimited", document); + } + + return Task.CompletedTask; + } + + private static void AddComponents(OpenApiDocument document) + { + document.Components ??= new OpenApiComponents(); + document.Components.Schemas ??= new Dictionary(); + document.Components.Responses ??= new Dictionary(); + + document.Components.Schemas["Problem"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + Description = "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.", + Properties = new Dictionary + { + ["type"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["title"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + }, + }; + + document.Components.Schemas["ValidationProblem"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + Description = "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.", + Properties = new Dictionary + { + ["type"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["title"] = new OpenApiSchema { Type = JsonSchemaType.String }, + ["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + ["errors"] = new OpenApiSchema + { + Type = JsonSchemaType.Object, + AdditionalProperties = new OpenApiSchema + { + Type = JsonSchemaType.Array, + Items = new OpenApiSchema + { + Type = JsonSchemaType.String, + Enum = Codes.Select(c => (System.Text.Json.Nodes.JsonNode)System.Text.Json.Nodes.JsonValue.Create(c)!).ToList(), + }, + }, + }, + }, + }; + + document.Components.Responses["Validation"] = ProblemResponse( + "Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"]).", + "ValidationProblem", document); + document.Components.Responses["TooLarge"] = ProblemResponse("The request body is too large.", "Problem", document); + document.Components.Responses["RateLimited"] = new OpenApiResponse + { + Description = "Too many requests. Retry after the number of seconds in the Retry-After header.", + Headers = new Dictionary + { + ["Retry-After"] = new OpenApiHeader + { + Description = "Seconds to wait before retrying.", + Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" }, + }, + }, + Content = new Dictionary + { + ["application/problem+json"] = new() { Schema = new OpenApiSchemaReference("Problem", document) }, + }, + }; + } + + private static OpenApiResponse ProblemResponse(string description, string schema, OpenApiDocument document) => new() + { + Description = description, + Content = new Dictionary + { + ["application/problem+json"] = new() { Schema = new OpenApiSchemaReference(schema, document) }, + }, + }; + + private static void DescribeSubmit(OpenApiDocument document, OpenApiOperation submit) + { + submit.Parameters ??= []; + submit.Parameters.Add(new OpenApiParameter + { + Name = ContactMessagesController.IdempotencyKeyHeader, + In = ParameterLocation.Header, + Required = true, + Description = "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.", + Schema = new OpenApiSchema { Type = JsonSchemaType.String, Format = "uuid" }, + }); + + submit.Responses ??= []; + submit.Responses["400"] = new OpenApiResponseReference("Validation", document); + submit.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." }; + submit.Responses["413"] = new OpenApiResponseReference("TooLarge", document); + submit.Responses["429"] = new OpenApiResponseReference("RateLimited", document); + + // The body is required and is exactly one JSON object. (The action parameter is nullable + // on purpose, which the generator would otherwise show as 'null or object'.) + submit.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = new Dictionary + { + ["application/json"] = new() { Schema = new OpenApiSchemaReference(nameof(Models.ContactMessageRequest), document) }, + }, + }; + + // The body schema: our model is nullable on purpose (a missing field is reported as the + // code 'required' in our own shape), so the contract's requirements are documented here. + if (document.Components?.Schemas is { } schemas + && schemas.TryGetValue(nameof(Models.ContactMessageRequest), out var schemaRef) + && schemaRef is OpenApiSchema request) + { + request.Required = new HashSet { "name", "email", "subject", "message", "hpCheck", "token" }; + SetMax(request, "name", ContactValidator.NameMax); + SetMax(request, "email", ContactValidator.EmailMax); + SetMax(request, "subject", ContactValidator.SubjectMax); + SetMax(request, "message", ContactValidator.MessageMax); + SetMax(request, "hpCheck", 0); + if (request.Properties is not null && request.Properties.TryGetValue("token", out var tokenProperty) + && tokenProperty is OpenApiSchema tokenSchema) + { + tokenSchema.Type = JsonSchemaType.String; + } + } + } + + private static void SetMax(OpenApiSchema request, string property, int max) + { + if (request.Properties is not null && request.Properties.TryGetValue(property, out var p) && p is OpenApiSchema schema) + { + // Required by the contract, so a plain string for generated client types (the C# model + // is nullable only so that a missing field can be reported in our own error shape). + schema.Type = JsonSchemaType.String; + schema.MaxLength = max; + } + } +} -- 2.39.5 From e53b318c317437c0ac7afa99be40f9ec587d1194 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 23:19:42 +0100 Subject: [PATCH 10/83] 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 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 + .../cms-u4-contact-admin-api/code/summary.md | 73 +++ ...-contact-admin-api-code-generation-plan.md | 12 +- openapi/slpsoftware.v1.json | 535 ++++++++++++++++++ .../appsettings.json | 4 + .../ContactAdminControllerTests.cs | 313 ++++++++++ .../ContactAdminServiceTests.cs | 321 +++++++++++ .../ContactSettingsAndGatesTests.cs | 175 ++++++ .../Pipeline/ContactAdminPipelineTests.cs | 343 +++++++++++ .../Pipeline/ContactHostFactory.cs | 55 +- .../ContactModule.cs | 16 +- .../Controllers/ContactAdminControllers.cs | 164 ++++++ .../Controllers/ContactProblems.cs | 42 ++ .../Data/ContactDbContext.cs | 11 + .../Data/Entities/ContactMessage.cs | 15 + ...61109202158_AddContactSettings.Designer.cs | 134 +++++ .../20261109202158_AddContactSettings.cs | 37 ++ .../ContactDbContextModelSnapshot.cs | 19 + .../Models/ContactAdminModels.cs | 93 +++ .../Repositories/ContactRepository.cs | 61 ++ .../Services/ContactAdminService.cs | 151 +++++ .../Services/ContactSettingsAndGates.cs | 126 +++++ 23 files changed, 2704 insertions(+), 10 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs create mode 100644 src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs create mode 100644 src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs create mode 100644 src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index d62d076..f6d42b1 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-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 diff --git a/aidlc-docs/features/contact-forms-module/audit.md b/aidlc-docs/features/contact-forms-module/audit.md index 3f0ac40..d02d6ea 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -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. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md new file mode 100644 index 0000000..7bb0526 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u4-contact-admin-api/code/summary.md @@ -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`. diff --git a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md index b4cd929..24fa36f 100644 --- a/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md +++ b/aidlc-docs/features/contact-forms-module/construction/plans/cms-u4-contact-admin-api-code-generation-plan.md @@ -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. diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index b6b6248..61a5189 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -101,6 +101,153 @@ ], "type": "object" }, + "ContactMessageDetail": { + "properties": { + "email": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mailAttempts": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "mailError": { + "type": [ + "null", + "string" + ] + }, + "mailStatus": { + "type": "string" + }, + "message": { + "type": "string" + }, + "name": { + "type": "string" + }, + "receivedAt": { + "format": "date-time", + "type": "string" + }, + "retentionUntil": { + "format": "date-time", + "type": "string" + }, + "status": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "id", + "receivedAt", + "name", + "email", + "subject", + "message", + "status", + "mailStatus", + "mailAttempts", + "mailError", + "retentionUntil" + ], + "type": "object" + }, + "ContactMessageList": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/ContactMessageListItem" + }, + "type": "array" + }, + "page": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "pageSize": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "totalCount": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "unreadCount": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + "required": [ + "items", + "page", + "pageSize", + "totalCount", + "unreadCount" + ], + "type": "object" + }, + "ContactMessageListItem": { + "properties": { + "email": { + "type": "string" + }, + "id": { + "type": "string" + }, + "mailStatus": { + "type": "string" + }, + "name": { + "type": "string" + }, + "receivedAt": { + "format": "date-time", + "type": "string" + }, + "status": { + "type": "string" + }, + "subject": { + "type": "string" + } + }, + "required": [ + "id", + "receivedAt", + "name", + "email", + "subject", + "status", + "mailStatus" + ], + "type": "object" + }, "ContactMessageRequest": { "properties": { "captchaToken": { @@ -143,6 +290,45 @@ ], "type": "object" }, + "ContactResendResult": { + "properties": { + "mailAttempts": { + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + }, + "mailStatus": { + "type": "string" + }, + "mailed": { + "type": "boolean" + } + }, + "required": [ + "mailStatus", + "mailAttempts", + "mailed" + ], + "type": "object" + }, + "ContactSettingsDto": { + "properties": { + "enabled": { + "type": "boolean" + }, + "hostEnabled": { + "type": "boolean" + } + }, + "required": [ + "enabled", + "hostEnabled" + ], + "type": "object" + }, "ContactTokenResponse": { "properties": { "captcha": { @@ -424,6 +610,34 @@ ], "type": "object" }, + "UpdateContactMessageStatusRequest": { + "properties": { + "status": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "status" + ], + "type": "object" + }, + "UpdateContactSettingsRequest": { + "properties": { + "enabled": { + "type": [ + "null", + "boolean" + ] + } + }, + "required": [ + "enabled" + ], + "type": "object" + }, "UpdateOfferingRequest": { "properties": { "categoryId": { @@ -1194,6 +1408,68 @@ } }, "/api/v1/contact-messages": { + "get": { + "parameters": [ + { + "in": "query", + "name": "status", + "schema": { + "type": "string" + } + }, + { + "in": "query", + "name": "page", + "schema": { + "default": 1, + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + }, + { + "in": "query", + "name": "pageSize", + "schema": { + "default": 25, + "format": "int32", + "pattern": "^-?(?:0|[1-9]\\d*)$", + "type": [ + "integer", + "string" + ] + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageList" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, "post": { "parameters": [ { @@ -1271,6 +1547,259 @@ ] } }, + "/api/v1/contact-messages/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No Content" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, + "get": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageDetail" + } + } + }, + "description": "OK" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + }, + "patch": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactMessageStatusRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactMessageStatusRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactMessageDetail" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + }, + "404": { + "description": "Not Found" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + } + }, + "/api/v1/contact-messages/{id}/resend": { + "post": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactResendResult" + } + } + }, + "description": "OK" + }, + "404": { + "description": "Not Found" + }, + "409": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Conflict" + }, + "429": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Too Many Requests" + } + }, + "tags": [ + "ContactMessagesAdmin" + ] + } + }, + "/api/v1/contact-settings": { + "get": { + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactSettingsDto" + } + } + }, + "description": "OK" + } + }, + "tags": [ + "ContactSettings" + ] + }, + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactSettingsRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/UpdateContactSettingsRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContactSettingsDto" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/ValidationProblemDetails" + } + } + }, + "description": "Bad Request" + } + }, + "tags": [ + "ContactSettings" + ] + } + }, "/api/v1/offerings": { "get": { "responses": { @@ -1542,9 +2071,15 @@ { "name": "Master" }, + { + "name": "ContactMessagesAdmin" + }, { "name": "ContactMessages" }, + { + "name": "ContactSettings" + }, { "name": "Auth" }, diff --git a/src/SlpModularCms.Api.SlpSoftware/appsettings.json b/src/SlpModularCms.Api.SlpSoftware/appsettings.json index 8f96bf6..7bb6fd1 100644 --- a/src/SlpModularCms.Api.SlpSoftware/appsettings.json +++ b/src/SlpModularCms.Api.SlpSoftware/appsettings.json @@ -101,6 +101,10 @@ "ContactToken": { "PermitLimit": 20, "WindowSeconds": 600 + }, + "ContactResend": { + "PermitLimit": 5, + "WindowSeconds": 600 } }, "SecurityHeaders": { diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs new file mode 100644 index 0000000..c2030cd --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminControllerTests.cs @@ -0,0 +1,313 @@ +using System.Reflection; +using System.Security.Claims; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.AspNetCore.Routing; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Controllers; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactAdminControllerTests +{ + private readonly IContactAdminService _service = Substitute.For(); + private readonly IContactSettingsService _settings = Substitute.For(); + + private ContactMessagesAdminController Messages(string? typeBase = null) => new(_service, Options.Create(new ContactOptions { Enabled = true, ProblemTypeBase = typeBase })) + { + ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }, + }; + + private ContactSettingsController Settings(Guid? userId = null) + { + var http = new DefaultHttpContext(); + if (userId is not null) + { + http.User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString())], "TestAuth")); + } + + return new ContactSettingsController(_settings, Options.Create(new ContactOptions { Enabled = true })) + { + ControllerContext = new ControllerContext { HttpContext = http }, + }; + } + + private static void AssertInvalid(IActionResult result, params string[] fields) + { + var obj = result.Should().BeOfType().Subject; + obj.StatusCode.Should().Be(400); + obj.ContentTypes.Should().Contain("application/problem+json"); + var problem = obj.Value.Should().BeOfType().Subject; + problem.Errors.Keys.Should().BeEquivalentTo(fields); + problem.Errors.Values.Should().OnlyContain(v => v.Length == 1 && v[0] == "invalid"); + } + + // ---- list ---- + + [Fact] + public async Task List_Returns200_WithTheServiceResult() + { + var list = new ContactMessageList([], 1, 25, 0, 0); + _service.ListAsync(null, 1, 25, Arg.Any()).Returns(list); + + var result = await Messages().List(null, 1, 25); + + result.Should().BeOfType().Which.Value.Should().Be(list); + } + + [Theory] + [InlineData(0, 25, null, "page")] + [InlineData(-3, 25, null, "page")] + [InlineData(1, 0, null, "pageSize")] + [InlineData(1, 101, null, "pageSize")] + [InlineData(1, 25, "bogus", "status")] + [InlineData(1, 25, "converted", "status")] + public async Task List_Returns400_NamingTheBadParameter(int page, int pageSize, string? status, string field) + { + var result = await Messages().List(status, page, pageSize); + + AssertInvalid(result, field); + await _service.DidNotReceive().ListAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task List_Returns400_ForAnUnparsablePageNumber() + { + var controller = Messages(); + controller.ModelState.AddModelError("page", "The value 'abc' is not valid."); + + var result = await controller.List(null); + + AssertInvalid(result, "page"); + } + + // ---- detail, status, delete, resend ---- + + [Fact] + public async Task Get_Returns200_Or404() + { + var id = Guid.NewGuid(); + _service.GetAsync(id, Arg.Any()).Returns((ContactMessageDetail?)null); + (await Messages().Get(id, CancellationToken.None)).Should().BeOfType(); + + var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", "new", "pending", 0, null, DateTimeOffset.UtcNow); + _service.GetAsync(id, Arg.Any()).Returns(detail); + (await Messages().Get(id, CancellationToken.None)).Should().BeOfType().Which.Value.Should().Be(detail); + } + + [Theory] + [InlineData("new", ContactMessageStatus.New)] + [InlineData("read", ContactMessageStatus.Read)] + [InlineData("archived", ContactMessageStatus.Archived)] + [InlineData("ARCHIVED", ContactMessageStatus.Archived)] + public async Task SetStatus_AcceptsNewReadArchived(string value, ContactMessageStatus expected) + { + var id = Guid.NewGuid(); + var detail = new ContactMessageDetail(id.ToString(), DateTimeOffset.UtcNow, "n", "e", "s", "m", value.ToLowerInvariant(), "pending", 0, null, DateTimeOffset.UtcNow); + _service.SetStatusAsync(id, expected, Arg.Any()).Returns(detail); + + var result = await Messages().SetStatus(id, new UpdateContactMessageStatusRequest(value), CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(detail); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("spam")] + [InlineData("converted")] + [InlineData("deleted")] + public async Task SetStatus_RejectsEverythingElse_WithErrorsStatus(string? value) + { + var result = await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest(value), CancellationToken.None); + + AssertInvalid(result, "status"); + await _service.DidNotReceive().SetStatusAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task SetStatus_RejectsAnUnreadableBody() + { + var controller = Messages(); + controller.ModelState.AddModelError("$.status", "bad"); + + AssertInvalid(await controller.SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status"); + AssertInvalid(await Messages().SetStatus(Guid.NewGuid(), null, CancellationToken.None), "status"); + } + + [Fact] + public async Task SetStatus_Returns404_ForAnUnknownMessage() + { + _service.SetStatusAsync(Arg.Any(), Arg.Any(), Arg.Any()).Returns((ContactMessageDetail?)null); + + (await Messages().SetStatus(Guid.NewGuid(), new UpdateContactMessageStatusRequest("read"), CancellationToken.None)) + .Should().BeOfType(); + } + + [Fact] + public async Task Delete_Returns204_Or404() + { + var id = Guid.NewGuid(); + _service.DeleteAsync(id, Arg.Any()).Returns(true, false); + + (await Messages().Delete(id, CancellationToken.None)).Should().BeOfType(); + (await Messages().Delete(id, CancellationToken.None)).Should().BeOfType(); + } + + [Fact] + public async Task Resend_Returns200_404_Or409ForSpam() + { + var id = Guid.NewGuid(); + var result = new ContactResendResult("sent", 1, true); + _service.ResendAsync(id, Arg.Any()).Returns(result); + (await Messages().Resend(id, CancellationToken.None)).Should().BeOfType().Which.Value.Should().Be(result); + + _service.ResendAsync(id, Arg.Any()).Returns((ContactResendResult?)null); + (await Messages().Resend(id, CancellationToken.None)).Should().BeOfType(); + + _service.ResendAsync(id, Arg.Any()).Returns>(_ => throw new ContactResendNotAllowedException()); + var conflict = (ObjectResult)await Messages().Resend(id, CancellationToken.None); + conflict.StatusCode.Should().Be(409); + conflict.ContentTypes.Should().Contain("application/problem+json"); + conflict.Value.Should().BeOfType().Which.Status.Should().Be(409); + } + + // ---- settings ---- + + [Fact] + public async Task GetSettings_ReturnsTheSingleton() + { + _settings.GetAsync(Arg.Any()).Returns(new ContactSettingsDto(false, true)); + + var result = await Settings().Get(CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(new ContactSettingsDto(false, true)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task PutSettings_StoresTheBoolean_RecordingWhoDidIt(bool enabled) + { + var user = Guid.NewGuid(); + _settings.SetEnabledAsync(enabled, user, Arg.Any()).Returns(new ContactSettingsDto(enabled, true)); + + var result = await Settings(user).Put(new UpdateContactSettingsRequest(enabled), CancellationToken.None); + + result.Should().BeOfType().Which.Value.Should().Be(new ContactSettingsDto(enabled, true)); + } + + [Fact] + public async Task PutSettings_RejectsAMissingNullOrNonBooleanValue_WithErrorsEnabled() + { + AssertInvalid(await Settings().Put(null, CancellationToken.None), "enabled"); + AssertInvalid(await Settings().Put(new UpdateContactSettingsRequest(null), CancellationToken.None), "enabled"); + + var controller = Settings(); + controller.ModelState.AddModelError("$.enabled", "The JSON value could not be converted to System.Boolean."); + AssertInvalid(await controller.Put(new UpdateContactSettingsRequest(true), CancellationToken.None), "enabled"); + + await _settings.DidNotReceive().SetEnabledAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + // ---- route table (every route of the management side) ---- + + private static readonly Type[] AdminControllers = [typeof(ContactMessagesAdminController), typeof(ContactSettingsController)]; + + private static IEnumerable<(Type Controller, MethodInfo Action, HttpMethodAttribute Http)> AdminActions() => + AdminControllers.SelectMany(c => c + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(m => (Controller: c, Action: m, Http: m.GetCustomAttributes().SingleOrDefault())) + .Where(x => x.Http is not null) + .Select(x => (x.Controller, x.Action, x.Http!))); + + [Fact] + public void RouteTable_TheManagementRoutesAreExactlyTheAgreedSet() + { + AdminActions().Select(a => + $"{a.Http.HttpMethods.Single()} {a.Controller.GetCustomAttribute()!.Template}/{a.Http.Template}".TrimEnd('/')) + .Should().BeEquivalentTo( + [ + "GET contact-messages", + "GET contact-messages/{id:guid}", + "PATCH contact-messages/{id:guid}", + "DELETE contact-messages/{id:guid}", + "POST contact-messages/{id:guid}/resend", + "GET contact-settings", + "PUT contact-settings", + ]); + } + + [Fact] + public void RouteTable_EveryManagementRoute_IsAdminOnly_NeverAnonymous_NeverPublic_AndHasNoAdminSegment() + { + foreach (var controller in AdminControllers) + { + controller.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + controller.GetCustomAttribute()!.ServiceType.Should().Be(typeof(ContactAdminRouteFilter)); + controller.GetCustomAttribute()!.Template.Should().NotContainEquivalentOf("admin"); + } + + foreach (var (controller, action, http) in AdminActions()) + { + var name = $"{controller.Name}.{action.Name}"; + action.GetCustomAttribute().Should().BeNull($"{name} must not be anonymous"); + action.GetCustomAttribute().Should().BeNull($"{name} must stay behind the availability gate"); + action.GetCustomAttributes().Where(a => a.Policy != "AdminOnly").Should().BeEmpty(); + (http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin"); + } + } + + [Fact] + public void RouteTable_OnlyTwoActionsOfTheWholeContactModuleArePublic() + { + var publicActions = typeof(ContactModule).Assembly.GetTypes() + .Where(t => typeof(ControllerBase).IsAssignableFrom(t) && !t.IsAbstract) + .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) + .Where(m => m.GetCustomAttribute() is not null) + .Select(m => $"{m.DeclaringType!.Name}.{m.Name}"); + + publicActions.Should().BeEquivalentTo( + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}", + $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}"); + } + + [Fact] + public void ResendHasItsOwnRateLimitPolicy() + { + typeof(ContactMessagesAdminController).GetMethod(nameof(ContactMessagesAdminController.Resend))! + .GetCustomAttribute()!.PolicyName.Should().Be("contact-resend"); + } + + // ---- the host switch on the management side ---- + + private static ResourceExecutingContext ResourceContext() => new( + new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), + new List(), + new List()); + + [Fact] + public void AdminRouteFilter_Answers404_WhileTheHostSwitchIsOff_AndPassesWhenItIsOn() + { + var off = ResourceContext(); + new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = false })).OnResourceExecuting(off); + off.Result.Should().BeOfType(); + + var on = ResourceContext(); + new ContactAdminRouteFilter(Options.Create(new ContactOptions { Enabled = true })).OnResourceExecuting(on); + on.Result.Should().BeNull(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs new file mode 100644 index 0000000..19c8daf --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactAdminServiceTests.cs @@ -0,0 +1,321 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public sealed class AdminHarness : IDisposable +{ + public static readonly DateTimeOffset Now = new(2026, 11, 9, 12, 0, 0, TimeSpan.Zero); + + public FakeTimeProvider Time { get; } = new(Now); + public ContactOptions Options { get; } = new() { Enabled = true, SiteId = "site-a", RetentionMonths = 12 }; + public ContactDbContext Db { get; } + public IContactMailSender Mail { get; } = Substitute.For(); + public CapturingLoggerProvider Logs { get; } = new(); + public ContactAdminService Sut { get; } + + public AdminHarness() + { + Db = new ContactDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options); + Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Skipped); + + Sut = new ContactAdminService( + new ContactRepository(Db), + Mail, + Microsoft.Extensions.Options.Options.Create(Options), + Time, + LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger()); + } + + public ContactMessage Add( + ContactMessageStatus status = ContactMessageStatus.New, int minutesAgo = 0, string site = "site-a", + string name = "Jan", ContactMailStatus mail = ContactMailStatus.Pending) + { + var message = new ContactMessage + { + Id = Guid.NewGuid(), + SiteId = site, + ReceivedAt = Now.AddMinutes(-minutesAgo), + Name = name, + Email = "jan@example.nl", + Subject = "website", + Message = "Hallo", + Status = status, + MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : mail, + RetentionUntil = status == ContactMessageStatus.Spam ? Now.AddDays(10) : Now.AddMonths(11), + }; + Db.ContactMessages.Add(message); + Db.SaveChanges(); + return message; + } + + public void Dispose() => Db.Dispose(); +} + +public class ContactAdminServiceTests +{ + [Fact] + public async Task TheDefaultList_ExcludesSpam_ShowsTheRest_NewestFirst() + { + using var h = new AdminHarness(); + var oldest = h.Add(ContactMessageStatus.Archived, minutesAgo: 30); + var newest = h.Add(ContactMessageStatus.New, minutesAgo: 1); + var middle = h.Add(ContactMessageStatus.Read, minutesAgo: 10); + h.Add(ContactMessageStatus.Spam, minutesAgo: 0); + + var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + + list!.Items.Select(i => i.Id).Should().Equal(newest.Id.ToString(), middle.Id.ToString(), oldest.Id.ToString()); + list.TotalCount.Should().Be(3); + list.Items.Should().NotContain(i => i.Status == "spam"); + } + + [Theory] + [InlineData("new", "new")] + [InlineData("read", "read")] + [InlineData("archived", "archived")] + [InlineData("spam", "spam")] + [InlineData("SPAM", "spam")] + public async Task AStatusFilter_ShowsOnlyThatStatus(string filter, string expected) + { + using var h = new AdminHarness(); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.Read); + h.Add(ContactMessageStatus.Archived); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + + var list = await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None); + + list!.Items.Should().OnlyContain(i => i.Status == expected); + list.TotalCount.Should().Be(expected == "spam" ? 2 : 1); + } + + [Theory] + [InlineData("converted")] + [InlineData("nonsense")] + public async Task AnUnknownOrUnlistableStatus_IsRejected(string filter) + { + using var h = new AdminHarness(); + + (await h.Sut.ListAsync(filter, 1, 25, CancellationToken.None)).Should().BeNull(); + } + + [Theory] + [InlineData(0, 25)] + [InlineData(-1, 25)] + [InlineData(1, 0)] + [InlineData(1, 101)] + public async Task PageAndPageSize_MustBeInRange(int page, int pageSize) + { + using var h = new AdminHarness(); + + (await h.Sut.ListAsync(null, page, pageSize, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task Paging_ReturnsTheRequestedSliceAndTheTotal() + { + using var h = new AdminHarness(); + for (var i = 0; i < 30; i++) + { + h.Add(ContactMessageStatus.Read, minutesAgo: i); + } + + var third = await h.Sut.ListAsync(null, 3, 10, CancellationToken.None); + var fourth = await h.Sut.ListAsync(null, 4, 10, CancellationToken.None); + + third!.Items.Should().HaveCount(10); + third.Page.Should().Be(3); + third.PageSize.Should().Be(10); + third.TotalCount.Should().Be(30); + fourth!.Items.Should().BeEmpty(); + fourth.TotalCount.Should().Be(30); + third.Items.Select(i => i.ReceivedAt).Should().BeInDescendingOrder(); + } + + [Fact] + public async Task TheUnreadCount_CountsOnlyNew_NeverSpam_AndIgnoresTheFilter() + { + using var h = new AdminHarness(); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.New); + h.Add(ContactMessageStatus.Read); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.Spam); + h.Add(ContactMessageStatus.New, site: "another-site"); + + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2); + (await h.Sut.ListAsync("spam", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2, "spam does not count and the filter does not matter"); + (await h.Sut.ListAsync("read", 1, 25, CancellationToken.None))!.UnreadCount.Should().Be(2); + } + + [Fact] + public async Task OtherSitesMessages_AreInvisible() + { + using var h = new AdminHarness(); + var foreign = h.Add(site: "another-site"); + + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.TotalCount.Should().Be(0); + (await h.Sut.GetAsync(foreign.Id, CancellationToken.None)).Should().BeNull(); + (await h.Sut.DeleteAsync(foreign.Id, CancellationToken.None)).Should().BeFalse(); + (await h.Sut.SetStatusAsync(foreign.Id, ContactMessageStatus.Read, CancellationToken.None)).Should().BeNull(); + (await h.Sut.ResendAsync(foreign.Id, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task TheListItems_DoNotCarryTheMessageText_ButTheDetailDoes() + { + using var h = new AdminHarness(); + var message = h.Add(); + + var list = await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + var detail = await h.Sut.GetAsync(message.Id, CancellationToken.None); + + typeof(SlpModularCms.Modules.Contact.Models.ContactMessageListItem).GetProperties().Select(p => p.Name) + .Should().NotContain("Message"); + list!.Items.Single().Name.Should().Be("Jan"); + detail!.Message.Should().Be("Hallo"); + detail.MailAttempts.Should().Be(0); + detail.RetentionUntil.Should().Be(message.RetentionUntil); + detail.Status.Should().Be("new"); + detail.MailStatus.Should().Be("pending"); + } + + [Fact] + public async Task AnUnknownId_GivesNull() + { + using var h = new AdminHarness(); + + (await h.Sut.GetAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull(); + } + + [Theory] + [InlineData(ContactMessageStatus.New)] + [InlineData(ContactMessageStatus.Read)] + [InlineData(ContactMessageStatus.Archived)] + public async Task TheStatusOfARegularMessage_CanBeChanged_WithoutTouchingItsRetention(ContactMessageStatus target) + { + using var h = new AdminHarness(); + var message = h.Add(ContactMessageStatus.Read); + var retention = message.RetentionUntil; + + var result = await h.Sut.SetStatusAsync(message.Id, target, CancellationToken.None); + + result!.Status.Should().Be(target.ToString().ToLowerInvariant()); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).RetentionUntil.Should().Be(retention); + } + + [Fact] + public async Task MarkingSpamAsNotSpam_FollowsTheNormalRetention_AndKeepsMailNotApplicable() + { + using var h = new AdminHarness(); + var spam = h.Add(ContactMessageStatus.Spam); + h.Options.RetentionMonths = 12; + + var result = await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.Read, CancellationToken.None); + + result!.Status.Should().Be("read"); + result.MailStatus.Should().Be("notApplicable"); + result.RetentionUntil.Should().Be(h.Time.GetUtcNow().AddMonths(12)); + (await h.Sut.ListAsync(null, 1, 25, CancellationToken.None))!.Items.Should().ContainSingle(i => i.Id == spam.Id.ToString()); + } + + [Fact] + public async Task Delete_RemovesTheMessageForGood() + { + using var h = new AdminHarness(); + var message = h.Add(); + + (await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeTrue(); + + h.Db.ContactMessages.Should().BeEmpty(); + (await h.Sut.DeleteAsync(message.Id, CancellationToken.None)).Should().BeFalse(); + } + + [Fact] + public async Task Resend_OfASpamMessage_IsNotAllowed_AndNothingIsSent() + { + using var h = new AdminHarness(); + var spam = h.Add(ContactMessageStatus.Spam); + + var act = () => h.Sut.ResendAsync(spam.Id, CancellationToken.None); + + await act.Should().ThrowAsync(); + await h.Mail.DidNotReceive().SendAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Resend_RecordsASentMail() + { + using var h = new AdminHarness(); + var message = h.Add(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Sent); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("sent", 1, true)); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailStatus.Should().Be(ContactMailStatus.Sent); + } + + [Fact] + public async Task Resend_RecordsAFailedMail() + { + using var h = new AdminHarness(); + var message = h.Add(); + h.Mail.SendAsync(Arg.Any(), Arg.Any()).Returns(ContactMailOutcome.Failed); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("failed", 1, false)); + } + + [Fact] + public async Task Resend_WhenNoMailCanBeSent_ChangesNothing_AndSaysSo() + { + using var h = new AdminHarness(); + var message = h.Add(); + + var result = await h.Sut.ResendAsync(message.Id, CancellationToken.None); + + result.Should().Be(new SlpModularCms.Modules.Contact.Models.ContactResendResult("pending", 0, false)); + (await h.Db.ContactMessages.AsNoTracking().SingleAsync()).MailAttempts.Should().Be(0); + } + + [Fact] + public async Task Resend_OfAnUnknownMessage_GivesNull() + { + using var h = new AdminHarness(); + + (await h.Sut.ResendAsync(Guid.NewGuid(), CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task NoPersonalDataIsLogged_ByAnyAdminAction() + { + using var h = new AdminHarness(); + var message = h.Add(name: "ZXQ-Admin-Marker"); + var spam = h.Add(ContactMessageStatus.Spam, name: "ZXQ-Spam-Marker"); + + await h.Sut.ListAsync(null, 1, 25, CancellationToken.None); + await h.Sut.GetAsync(message.Id, CancellationToken.None); + await h.Sut.SetStatusAsync(message.Id, ContactMessageStatus.Read, CancellationToken.None); + await h.Sut.SetStatusAsync(spam.Id, ContactMessageStatus.New, CancellationToken.None); + await h.Sut.ResendAsync(message.Id, CancellationToken.None); + await h.Sut.DeleteAsync(message.Id, CancellationToken.None); + + h.Logs.Messages.Should().NotBeEmpty(); + h.Logs.Messages.Should().NotContain(m => m.Contains("ZXQ") || m.Contains("example.nl") || m.Contains("Hallo")); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs new file mode 100644 index 0000000..8a87e4b --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactSettingsAndGatesTests.cs @@ -0,0 +1,175 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Time.Testing; +using NSubstitute; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Tests; + +public class ContactSettingsServiceTests +{ + private sealed class Setup : IDisposable + { + public FakeTimeProvider Time { get; } = new(new DateTimeOffset(2026, 11, 9, 12, 0, 0, TimeSpan.Zero)); + public ContactOptions Options { get; } = new() { Enabled = true }; + public ContactDbContext Db { get; } = new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options); + public ContactSettingsCache Cache { get; } + public ContactSettingsService Sut { get; } + + public Setup() + { + Cache = new ContactSettingsCache(Time); + Sut = new ContactSettingsService( + new ContactRepository(Db), Cache, Microsoft.Extensions.Options.Options.Create(Options), Time); + } + + public void Dispose() => Db.Dispose(); + } + + [Fact] + public async Task WithoutARow_TheSwitchIsOff() + { + using var s = new Setup(); + + (await s.Sut.GetAsync(CancellationToken.None)).Should().Be(new ContactSettingsDto(false, true)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse(); + } + + [Fact] + public async Task HostEnabled_ReflectsTheHostSwitch_ReadOnly() + { + using var s = new Setup(); + s.Options.Enabled = false; + + (await s.Sut.GetAsync(CancellationToken.None)).HostEnabled.Should().BeFalse(); + } + + [Fact] + public async Task SettingTheSwitch_CreatesTheSingletonRow_ThenUpdatesIt_AndRemembersWhoAndWhen() + { + using var s = new Setup(); + var user = Guid.NewGuid(); + + var on = await s.Sut.SetEnabledAsync(true, user, CancellationToken.None); + s.Time.Advance(TimeSpan.FromMinutes(5)); + var off = await s.Sut.SetEnabledAsync(false, Guid.NewGuid(), CancellationToken.None); + + on.Should().Be(new ContactSettingsDto(true, true)); + off.Should().Be(new ContactSettingsDto(false, true)); + var rows = await s.Db.ContactSettings.AsNoTracking().ToListAsync(); + rows.Should().ContainSingle().Which.Id.Should().Be(ContactSettings.SingletonId); + rows[0].Enabled.Should().BeFalse(); + rows[0].UpdatedAt.Should().Be(s.Time.GetUtcNow()); + } + + [Fact] + public async Task TheUserWhoChangedItIsStored() + { + using var s = new Setup(); + var user = Guid.NewGuid(); + + await s.Sut.SetEnabledAsync(true, user, CancellationToken.None); + + (await s.Db.ContactSettings.AsNoTracking().SingleAsync()).UpdatedByUserId.Should().Be(user); + } + + [Fact] + public async Task ThePublicCheck_IsCachedBriefly_AndRefreshedAfterwards() + { + using var s = new Setup(); + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue(); // fills the cache + + // Another instance flips the row behind this one's back. + var row = await s.Db.ContactSettings.SingleAsync(); + row.Enabled = false; + await s.Db.SaveChangesAsync(); + + s.Time.Advance(TimeSpan.FromSeconds(4)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue("still within the cache lifetime"); + + s.Time.Advance(TimeSpan.FromSeconds(2)); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse("the cache expired"); + } + + [Fact] + public async Task ChangingTheSwitch_TakesEffectAtOnceInThisProcess() + { + using var s = new Setup(); + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeFalse(); // cached: off + + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + + (await s.Sut.IsEnabledAsync(CancellationToken.None)).Should().BeTrue(); + } + + [Fact] + public async Task TheAdministratorsOwnView_IsNeverServedFromTheCache() + { + using var s = new Setup(); + await s.Sut.SetEnabledAsync(true, Guid.NewGuid(), CancellationToken.None); + await s.Sut.IsEnabledAsync(CancellationToken.None); + var row = await s.Db.ContactSettings.SingleAsync(); + row.Enabled = false; + await s.Db.SaveChangesAsync(); + + (await s.Sut.GetAsync(CancellationToken.None)).Enabled.Should().BeFalse(); + } + + [Fact] + public void TheCacheLifetime_IsFiveSeconds() + { + ContactSettingsCache.Lifetime.Should().Be(TimeSpan.FromSeconds(5)); + } +} + +public class ContactFormGateTests +{ + private static IContactFormGate Layer(bool open) + { + var gate = Substitute.For(); + gate.IsOpenAsync(Arg.Any()).Returns(open); + return gate; + } + + [Theory] + [InlineData(true, true, true)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, false)] + public async Task TheFormIsOpen_OnlyWhenEveryLayerIsOpen(bool host, bool cms, bool expected) + { + var gate = new CompositeContactFormGate([Layer(host), Layer(cms)]); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().Be(expected); + } + + [Fact] + public async Task WhenTheFirstLayerIsClosed_TheSecondIsNeverAsked_SoTheDatabaseIsNotTouched() + { + var host = Layer(false); + var cms = Layer(true); + + await new CompositeContactFormGate([host, cms]).IsOpenAsync(CancellationToken.None); + + await host.Received(1).IsOpenAsync(Arg.Any()); + await cms.DidNotReceive().IsOpenAsync(Arg.Any()); + } + + [Fact] + public async Task TheCmsLayer_FollowsTheSettingsService() + { + var settings = Substitute.For(); + settings.IsEnabledAsync(Arg.Any()).Returns(true, false); + var gate = new CmsFlagContactFormGate(settings); + + (await gate.IsOpenAsync(CancellationToken.None)).Should().BeTrue(); + (await gate.IsOpenAsync(CancellationToken.None)).Should().BeFalse(); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs new file mode 100644 index 0000000..5e24fdc --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs @@ -0,0 +1,343 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.Tokens; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// Mints access tokens the way the host itself does (same settings, same claims). +internal static class Jwt +{ + public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null) + { + var settings = factory.Services.GetRequiredService().GetSection("JwtSettings"); + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings["Secret"]!)); + var token = new JwtSecurityToken( + issuer: settings["Issuer"], + audience: settings["Audience"], + claims: + [ + new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()), + new Claim(ClaimTypes.Role, role), + ], + expires: DateTime.UtcNow.AddHours(1), + signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); + + var client = factory.CreateClient(); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token)); + return client; + } + + public static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json"); +} + +public class ContactAdminPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture +{ + private const string Messages = "/api/v1/contact-messages"; + private const string Settings = "/api/v1/contact-settings"; + + private async Task SeedAsync(ContactMessageStatus status, string name, int minutesAgo = 0) + { + var id = Guid.NewGuid(); + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = id, SiteId = "pipeline-site", ReceivedAt = DateTimeOffset.UtcNow.AddMinutes(-minutesAgo), + Name = name, Email = "x@example.nl", Subject = "website", Message = "Hallo", + Status = status, + MailStatus = status == ContactMessageStatus.Spam ? ContactMailStatus.NotApplicable : ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11), + }); + await db.SaveChangesAsync(); + return 0; + }); + return id; + } + + // ---- authentication and authorization ---- + + [Theory] + [InlineData("GET", Messages)] + [InlineData("GET", Settings)] + [InlineData("PUT", Settings)] + [InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")] + public async Task EveryManagementRoute_RequiresLogin(string method, string url) + { + var request = new HttpRequestMessage(new HttpMethod(method), url); + if (method is "PUT" or "PATCH") + { + request.Content = Jwt.Json("{}"); + } + + var response = await factory.CreateClient().SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Theory] + [InlineData("GET", Messages)] + [InlineData("GET", Settings)] + [InlineData("PUT", Settings)] + [InlineData("PATCH", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("DELETE", Messages + "/00000000-0000-0000-0000-000000000001")] + [InlineData("POST", Messages + "/00000000-0000-0000-0000-000000000001/resend")] + public async Task EveryManagementRoute_IsForbidden_ForARegularUser(string method, string url) + { + var request = new HttpRequestMessage(new HttpMethod(method), url); + if (method is "PUT" or "PATCH") + { + request.Content = Jwt.Json("""{"enabled":true,"status":"read"}"""); + } + + var response = await Jwt.ClientWithRole(factory, "User").SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task APutOnTheSwitchByANonAdmin_Is403_AndChangesNothing() + { + // The other tests in this class may have created the row; what matters is that this call changes nothing. + var before = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync()); + + var response = await Jwt.ClientWithRole(factory, "User").PutAsync(Settings, Jwt.Json("""{"enabled":true}""")); + + response.StatusCode.Should().Be(HttpStatusCode.Forbidden); + var after = await factory.WithDb(db => db.ContactSettings.AsNoTracking().Select(s => new { s.Enabled, s.UpdatedAt }).ToListAsync()); + after.Should().BeEquivalentTo(before); + (await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK); + } + + // ---- the switch ---- + + [Fact] + public async Task TheCmsSwitch_IsOffByDefault_AndTheStateIsReportedWithTheHostSwitch() + { + var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Settings); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).Should().Be("""{"enabled":false,"hostEnabled":true}"""); + } + + [Theory] + [InlineData("""{"enabled":"yes"}""")] + [InlineData("""{"enabled":1}""")] + [InlineData("""{"enabled":null}""")] + [InlineData("{}")] + [InlineData("not json")] + [InlineData("")] + public async Task APutWithoutABoolean_Is400_WithErrorsEnabled(string body) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").PutAsync(Settings, Jwt.Json(body)); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("enabled")[0].GetString().Should().Be("invalid"); + doc.RootElement.GetProperty("errors").EnumerateObject().Should().ContainSingle(); + } + + [Fact] + public async Task TheSwitch_OpensAndClosesThePublicRoutes_AtOnce_WhileTheManagementRoutesKeepWorking() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + var visitor = factory.CreateClient(); + + // Default: closed. 404 with an empty body, the website shows its mailto fallback. + var closed = await visitor.GetAsync($"{Messages}/token"); + closed.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await closed.Content.ReadAsStringAsync()).Should().BeEmpty(); + + var on = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":true}""")); + on.StatusCode.Should().Be(HttpStatusCode.OK); + (await on.Content.ReadAsStringAsync()).Should().Be("""{"enabled":true,"hostEnabled":true}"""); + (await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.OK); + + var off = await admin.PutAsync(Settings, Jwt.Json("""{"enabled":false}""")); + off.StatusCode.Should().Be(HttpStatusCode.OK); + (await visitor.GetAsync($"{Messages}/token")).StatusCode.Should().Be(HttpStatusCode.NotFound); + var post = await visitor.PostAsync(Messages, Jwt.Json("{}")); + post.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await post.Content.ReadAsStringAsync()).Should().BeEmpty(); + + // The management side is never closed by the CMS switch. + (await admin.GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK); + (await admin.GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.OK); + } + + [Fact] + public async Task TheUserWhoChangedTheSwitch_IsRecorded() + { + var user = Guid.NewGuid(); + + await Jwt.ClientWithRole(factory, "Owner", user).PutAsync(Settings, Jwt.Json("""{"enabled":false}""")); + + (await factory.WithDb(db => db.ContactSettings.AsNoTracking().SingleAsync())).UpdatedByUserId.Should().Be(user); + } + + // ---- messages ---- + + [Fact] + public async Task TheMessageFlow_ListDetailStatusSpamDeleteResend() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + var first = await SeedAsync(ContactMessageStatus.New, "Flow Eerste", minutesAgo: 10); + var second = await SeedAsync(ContactMessageStatus.New, "Flow Tweede", minutesAgo: 5); + var spam = await SeedAsync(ContactMessageStatus.Spam, "Flow Spam", minutesAgo: 1); + + // Default list: no spam; unread counts only the new ones. + using (var list = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync())) + { + var names = list.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()).ToList(); + names.Should().Contain(["Flow Eerste", "Flow Tweede"]).And.NotContain("Flow Spam"); + list.RootElement.GetProperty("unreadCount").GetInt32().Should().BeGreaterThanOrEqualTo(2); + list.RootElement.GetProperty("items")[0].TryGetProperty("message", out _).Should().BeFalse("the list has no message text"); + } + + // Spam apart. + using (var spamList = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?status=spam")).Content.ReadAsStringAsync())) + { + spamList.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()) + .Should().Equal("Flow Spam"); + } + + // Detail. + using (var detail = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}/{first}")).Content.ReadAsStringAsync())) + { + detail.RootElement.GetProperty("message").GetString().Should().Be("Hallo"); + detail.RootElement.GetProperty("status").GetString().Should().Be("new"); + detail.RootElement.GetProperty("mailStatus").GetString().Should().Be("pending"); + } + + // Status change. + var patch = await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"read"}""")); + patch.StatusCode.Should().Be(HttpStatusCode.OK); + (await patch.Content.ReadAsStringAsync()).Should().Contain("\"status\":\"read\""); + (await admin.PatchAsync($"{Messages}/{first}", Jwt.Json("""{"status":"spam"}"""))).StatusCode.Should().Be(HttpStatusCode.BadRequest); + + // Resend: spam is refused, a regular message answers (no mail sender yet: mailed=false). + (await admin.PostAsync($"{Messages}/{spam}/resend", null)).StatusCode.Should().Be(HttpStatusCode.Conflict); + var resend = await admin.PostAsync($"{Messages}/{second}/resend", null); + resend.StatusCode.Should().Be(HttpStatusCode.OK); + (await resend.Content.ReadAsStringAsync()).Should().Be("""{"mailStatus":"pending","mailAttempts":0,"mailed":false}"""); + + // Not spam after all: now in the default list. + (await admin.PatchAsync($"{Messages}/{spam}", Jwt.Json("""{"status":"archived"}"""))).StatusCode.Should().Be(HttpStatusCode.OK); + using (var again = JsonDocument.Parse(await (await admin.GetAsync($"{Messages}?pageSize=100")).Content.ReadAsStringAsync())) + { + again.RootElement.GetProperty("items").EnumerateArray().Select(i => i.GetProperty("name").GetString()) + .Should().Contain("Flow Spam"); + } + + // Delete. + (await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NoContent); + (await admin.GetAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound); + (await admin.DeleteAsync($"{Messages}/{second}")).StatusCode.Should().Be(HttpStatusCode.NotFound); + } + + [Theory] + [InlineData("?page=0")] + [InlineData("?pageSize=101")] + [InlineData("?status=bogus")] + [InlineData("?page=abc")] + public async Task ABadListQuery_Is400_InTheContractShape(string query) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages + query); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + } + + [Fact] + public async Task ABadStatusBody_Is400_WithErrorsStatus() + { + var id = await SeedAsync(ContactMessageStatus.New, "Pipeline Patch"); + + var response = await Jwt.ClientWithRole(factory, "Administrator").PatchAsync($"{Messages}/{id}", Jwt.Json("""{"status":"nope"}""")); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + doc.RootElement.GetProperty("errors").GetProperty("status")[0].GetString().Should().Be("invalid"); + } + + // ---- the availability gate ---- + + [Fact] + public async Task WhenTheCmsIsDisabled_TheManagementRoutesAreBlockedForVisitors_ButNotForAnAdministrator() + { + await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( + "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 1, 'pipeline test', NOW(), 'pipeline test')")); + + // No marker on the management routes: anonymous callers meet the gate (503), not even a 401. + (await factory.CreateClient().GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await factory.CreateClient().GetAsync(Settings)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await Jwt.ClientWithRole(factory, "User").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + + // By design a verified administrator can always reach a disabled CMS (to switch it back on). + (await Jwt.ClientWithRole(factory, "Administrator").GetAsync(Messages)).StatusCode.Should().Be(HttpStatusCode.OK); + } +} + +public class ContactAdminHostSwitchPipelineTests(DisabledContactHostFactory factory) : IClassFixture +{ + [Theory] + [InlineData("GET", "/api/v1/contact-messages")] + [InlineData("GET", "/api/v1/contact-settings")] + public async Task WhileTheHostSwitchIsOff_TheManagementRoutesAre404_WithAnEmptyBody(string method, string url) + { + var response = await Jwt.ClientWithRole(factory, "Administrator").SendAsync(new HttpRequestMessage(new HttpMethod(method), url)); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + (await response.Content.ReadAsStringAsync()).Should().BeEmpty(); + } + + [Fact] + public async Task WhileTheHostSwitchIsOff_AnonymousCallersStillMeetAuthenticationFirst() + { + (await factory.CreateClient().GetAsync("/api/v1/contact-settings")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } +} + +public class ContactResendRateLimitPipelineTests(TightResendContactHostFactory factory) : IClassFixture +{ + [Fact] + public async Task Resend_Answers429_WithRetryAfter_AfterItsOwnLimit() + { + var id = Guid.NewGuid(); + await factory.WithDb(async db => + { + db.ContactMessages.Add(new ContactMessage + { + Id = id, SiteId = "default", ReceivedAt = DateTimeOffset.UtcNow, Name = "n", Email = "e@example.nl", + Subject = "s", Message = "m", Status = ContactMessageStatus.New, MailStatus = ContactMailStatus.Pending, + RetentionUntil = DateTimeOffset.UtcNow.AddMonths(11), + }); + await db.SaveChangesAsync(); + return 0; + }); + var admin = Jwt.ClientWithRole(factory, "Administrator"); + + HttpResponseMessage? last = null; + for (var i = 0; i < 3; i++) + { + last = await admin.PostAsync($"/api/v1/contact-messages/{id}/resend", null); + } + + last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + last.Headers.TryGetValues("Retry-After", out var retryAfter).Should().BeTrue(); + int.Parse(retryAfter!.Single()).Should().BeGreaterThanOrEqualTo(1); + last.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); + } +} diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs index 0dd3cb1..f26baf0 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactHostFactory.cs @@ -15,8 +15,31 @@ namespace SlpModularCms.Modules.Contact.Tests.Pipeline; /// databases on. Every factory uses its own freshly created database and drops it again. /// To run only the pure unit tests use --filter "FullyQualifiedName!~Pipeline". /// -public class ContactHostFactory : WebApplicationFactory +public class ContactHostFactory : WebApplicationFactory, IAsyncLifetime { + /// Whether the CMS switch (layer 2 of the gate) is turned on right after start-up. + protected virtual bool OpenCmsSwitch => false; + + Task IAsyncLifetime.InitializeAsync() => OpenCmsSwitch ? OpenCmsSwitchAsync() : Task.CompletedTask; + + Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask; + + private async Task OpenCmsSwitchAsync() + { + _ = CreateClient(); // starts the host (migrates the contact tables) + await WithDb(async db => + { + db.ContactSettings.Add(new Data.Entities.ContactSettings + { + Enabled = true, + UpdatedAt = DateTimeOffset.UtcNow, + UpdatedByUserId = Guid.NewGuid(), + }); + await db.SaveChangesAsync(); + return 0; + }); + } + private const string EnvironmentVariable = "ConnectionStrings__DefaultConnection"; private readonly Dictionary _settings; @@ -83,7 +106,21 @@ public class ContactHostFactory : WebApplicationFactory } } +/// Host switch on, CMS switch ON: the contact form is fully open. public sealed class EnabledContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["Contact:SiteId"] = "pipeline-site", + ["Contact:MinSeconds"] = "0", + ["RateLimiting:ContactForm:PermitLimit"] = "1000", + ["RateLimiting:ContactToken:PermitLimit"] = "1000", +}) +{ + protected override bool OpenCmsSwitch => true; +} + +/// Host switch on, CMS switch OFF (its default): the public routes are closed, the admin routes work. +public sealed class ClosedCmsSwitchContactHostFactory() : ContactHostFactory(new() { ["Contact:Enabled"] = "true", ["Contact:SiteId"] = "pipeline-site", @@ -92,6 +129,7 @@ public sealed class EnabledContactHostFactory() : ContactHostFactory(new() ["RateLimiting:ContactToken:PermitLimit"] = "1000", }); +/// Host switch OFF (the default): the whole module is inactive. public sealed class DisabledContactHostFactory() : ContactHostFactory; /// Only the form policy is tight, so a token can still be fetched freely. @@ -101,7 +139,10 @@ public sealed class TightFormLimitContactHostFactory() : ContactHostFactory(new( ["Contact:MinSeconds"] = "0", ["RateLimiting:ContactForm:PermitLimit"] = "2", ["RateLimiting:ContactToken:PermitLimit"] = "1000", -}); +}) +{ + protected override bool OpenCmsSwitch => true; +} /// Only the token policy is tight. public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new() @@ -110,4 +151,14 @@ public sealed class TightTokenLimitContactHostFactory() : ContactHostFactory(new ["Contact:MinSeconds"] = "0", ["RateLimiting:ContactForm:PermitLimit"] = "1000", ["RateLimiting:ContactToken:PermitLimit"] = "2", +}) +{ + protected override bool OpenCmsSwitch => true; +} + +/// Only the resend policy is tight; the CMS switch is off. +public sealed class TightResendContactHostFactory() : ContactHostFactory(new() +{ + ["Contact:Enabled"] = "true", + ["RateLimiting:ContactResend:PermitLimit"] = "2", }); diff --git a/src/SlpModularCms.Modules.Contact/ContactModule.cs b/src/SlpModularCms.Modules.Contact/ContactModule.cs index dc8312a..07787c3 100644 --- a/src/SlpModularCms.Modules.Contact/ContactModule.cs +++ b/src/SlpModularCms.Modules.Contact/ContactModule.cs @@ -45,8 +45,20 @@ public class ContactModule : IModule services.AddSingleton(); services.AddSingleton(); services.AddScoped(); - services.AddScoped(); + // Gate: the form is open only if the host switch AND the CMS switch are on. The host switch + // is asked first, so with it off the database is never touched. + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(sp => new CompositeContactFormGate( + [ + sp.GetRequiredService(), + sp.GetRequiredService(), + ])); + services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddHostedService(); // The contact details of the OpenAPI document (named options of document 'v1', so the shared @@ -62,6 +74,8 @@ public class ContactModule : IModule Window(config, "ContactForm", 5, 600, context)); limiter.AddPolicy(ContactMessagesController.TokenPolicy, context => Window(config, "ContactToken", 20, 600, context)); + limiter.AddPolicy(ContactMessagesAdminController.ResendPolicy, context => + Window(config, "ContactResend", 5, 600, context)); }); } diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs new file mode 100644 index 0000000..781d903 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactAdminControllers.cs @@ -0,0 +1,164 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Services; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// +/// The management routes need the contact tables, which exist only while the host switch +/// (Contact:Enabled) is on. While it is off they answer 404 with an empty body. The CMS +/// switch deliberately does NOT close them: otherwise nobody could switch the form back on. +/// +public sealed class ContactAdminRouteFilter(IOptions options) : IResourceFilter +{ + public void OnResourceExecuting(ResourceExecutingContext context) + { + if (!options.Value.Enabled) + { + context.Result = new NotFoundResult(); + } + } + + public void OnResourceExecuted(ResourceExecutedContext context) + { + } +} + +/// +/// Management of the stored messages. Same resource name as the public routes, no admin segment: +/// access is decided by authorization alone (AdminOnly). Not an [ApiController], like the +/// public controller, so every 400 is in our own problem shape. +/// +[ApiExplorerSettings(IgnoreApi = false)] +[Route("contact-messages")] +[Authorize(Policy = "AdminOnly")] +[ServiceFilter(typeof(ContactAdminRouteFilter))] +public class ContactMessagesAdminController(IContactAdminService service, IOptions options) : ControllerBase +{ + public const string ResendPolicy = "contact-resend"; + + [HttpGet] + [ProducesResponseType(typeof(ContactMessageList), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + public async Task List( + [FromQuery] string? status, [FromQuery] int page = 1, [FromQuery] int pageSize = ContactAdminService.DefaultPageSize, + CancellationToken cancellationToken = default) + { + var invalid = new List(); + foreach (var (key, entry) in ModelState) + { + if (entry.Errors.Count > 0) + { + invalid.Add(key is "page" or "pageSize" or "status" ? key : "query"); + } + } + + if (page < 1 && !invalid.Contains("page")) invalid.Add("page"); + if ((pageSize < 1 || pageSize > ContactAdminService.MaxPageSize) && !invalid.Contains("pageSize")) invalid.Add("pageSize"); + if (!string.IsNullOrWhiteSpace(status) && !ContactStatusNames.TryParseListable(status, out _) && !invalid.Contains("status")) invalid.Add("status"); + + if (invalid.Count > 0) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, invalid.Distinct().ToArray()); + } + + var result = await service.ListAsync(status, page, pageSize, cancellationToken); + return result is null ? ContactProblems.Invalid(options.Value.ProblemTypeBase, "query") : Ok(result); + } + + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Get(Guid id, CancellationToken cancellationToken) + { + var message = await service.GetAsync(id, cancellationToken); + return message is null ? NotFound() : Ok(message); + } + + [HttpPatch("{id:guid}")] + [Consumes("application/json")] + [ProducesResponseType(typeof(ContactMessageDetail), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task SetStatus( + Guid id, [FromBody] UpdateContactMessageStatusRequest? request, CancellationToken cancellationToken) + { + if (!ModelState.IsValid || request is null || !ContactStatusNames.TryParseSettable(request.Status, out var status)) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, "status"); + } + + var message = await service.SetStatusAsync(id, status, cancellationToken); + return message is null ? NotFound() : Ok(message); + } + + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Delete(Guid id, CancellationToken cancellationToken) + => await service.DeleteAsync(id, cancellationToken) ? NoContent() : NotFound(); + + [HttpPost("{id:guid}/resend")] + [EnableRateLimiting(ResendPolicy)] + [ProducesResponseType(typeof(ContactResendResult), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict, "application/problem+json")] + [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")] + public async Task Resend(Guid id, CancellationToken cancellationToken) + { + try + { + var result = await service.ResendAsync(id, cancellationToken); + return result is null ? NotFound() : Ok(result); + } + catch (ContactResendNotAllowedException ex) + { + return ContactProblems.Conflict(ex.Message); + } + } +} + +/// +/// The CMS switch of the contact form: a singleton resource. The form is open only when this +/// switch AND the host switch are on. Default: off. +/// +[ApiExplorerSettings(IgnoreApi = false)] +[Route("contact-settings")] +[Authorize(Policy = "AdminOnly")] +[ServiceFilter(typeof(ContactAdminRouteFilter))] +public class ContactSettingsController(IContactSettingsService service, IOptions options) : ControllerBase +{ + [HttpGet] + [ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")] + public async Task Get(CancellationToken cancellationToken) + => Ok(await service.GetAsync(cancellationToken)); + + [HttpPut] + [Consumes("application/json")] + [ProducesResponseType(typeof(ContactSettingsDto), StatusCodes.Status200OK, "application/json")] + [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")] + public async Task Put([FromBody] UpdateContactSettingsRequest? request, CancellationToken cancellationToken) + { + // A missing or non-boolean 'enabled' (or an unreadable body) is reported as errors.enabled. + if (!ModelState.IsValid || request?.Enabled is not { } enabled) + { + return ContactProblems.Invalid(options.Value.ProblemTypeBase, "enabled"); + } + + return Ok(await service.SetEnabledAsync(enabled, CallerId(), cancellationToken)); + } + + private Guid CallerId() + { + var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); + return Guid.TryParse(claim, out var id) ? id : Guid.Empty; + } +} diff --git a/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs b/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs new file mode 100644 index 0000000..8438bdb --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Controllers/ContactProblems.cs @@ -0,0 +1,42 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace SlpModularCms.Modules.Contact.Controllers; + +/// The problem+json answers of the contact routes, in one place. +internal static class ContactProblems +{ + public const string ContentType = "application/problem+json"; + + /// A 400 with the contract's errors map (field name -> codes). + public static ObjectResult Validation(IReadOnlyDictionary errors, string? typeBase) + { + var baseUri = typeBase?.TrimEnd('/'); + var problem = new ValidationProblemDetails(errors.ToDictionary(e => e.Key, e => e.Value)) + { + Type = string.IsNullOrWhiteSpace(baseUri) ? "about:blank" : $"{baseUri}/validation", + Title = "Validation failed", + Status = StatusCodes.Status400BadRequest, + }; + + return new ObjectResult(problem) + { + StatusCode = StatusCodes.Status400BadRequest, + ContentTypes = { ContentType }, + }; + } + + /// A 400 that names the given fields as invalid. + public static ObjectResult Invalid(string? typeBase, params string[] fields) + => Validation(fields.ToDictionary(f => f, _ => new[] { "invalid" }), typeBase); + + public static ObjectResult Conflict(string title) => new(new ProblemDetails + { + Status = StatusCodes.Status409Conflict, + Title = title, + }) + { + StatusCode = StatusCodes.Status409Conflict, + ContentTypes = { ContentType }, + }; +} diff --git a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs index cbb12e4..96930e8 100644 --- a/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs +++ b/src/SlpModularCms.Modules.Contact/Data/ContactDbContext.cs @@ -7,6 +7,7 @@ public class ContactDbContext(DbContextOptions options) : DbCo { public DbSet ContactMessages => Set(); public DbSet IdempotencyRecords => Set(); + public DbSet ContactSettings => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -31,6 +32,16 @@ public class ContactDbContext(DbContextOptions options) : DbCo entity.HasIndex(e => e.RetentionUntil); }); + modelBuilder.Entity(entity => + { + entity.ToTable("ContactSettings"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Id).ValueGeneratedNever(); + entity.Property(e => e.Enabled).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + entity.Property(e => e.UpdatedByUserId).IsRequired(); + }); + modelBuilder.Entity(entity => { entity.ToTable("ContactIdempotency"); diff --git a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs index 82ac5ae..7ae138e 100644 --- a/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs +++ b/src/SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs @@ -56,3 +56,18 @@ public class IdempotencyRecord public DateTimeOffset CreatedAt { get; set; } public int StatusCode { get; set; } } + +/// +/// The CMS-controlled on/off switch of the contact form (a singleton row, id 1). While no row +/// exists the switch is off. It is the second layer of the gate; the host switch +/// (Contact:Enabled) is the first. +/// +public class ContactSettings +{ + public const int SingletonId = 1; + + public int Id { get; set; } = SingletonId; + public bool Enabled { get; set; } + public DateTimeOffset UpdatedAt { get; set; } + public Guid UpdatedByUserId { get; set; } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs new file mode 100644 index 0000000..a1c1891 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.Designer.cs @@ -0,0 +1,134 @@ +ο»Ώ// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Contact.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + [DbContext(typeof(ContactDbContext))] + [Migration("20261109202158_AddContactSettings")] + partial class AddContactSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("varchar(254)"); + + b.Property("MailAttempts") + .HasColumnType("int"); + + b.Property("MailError") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("MailStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(2000) + .HasColumnType("varchar(2000)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("NextMailAttemptAt") + .HasColumnType("datetime"); + + b.Property("ReceivedAt") + .HasColumnType("datetime"); + + b.Property("RetentionUntil") + .HasColumnType("datetime"); + + b.Property("SiteId") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.HasKey("Id"); + + b.HasIndex("RetentionUntil"); + + b.HasIndex("SiteId", "Status", "ReceivedAt"); + + b.ToTable("ContactMessages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.Property("UpdatedByUserId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ContactSettings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => + { + b.Property("SiteId") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Key") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("StatusCode") + .HasColumnType("int"); + + b.HasKey("SiteId", "Key"); + + b.HasIndex("CreatedAt"); + + b.ToTable("ContactIdempotency", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs new file mode 100644 index 0000000..eed495e --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Migrations/20261109202158_AddContactSettings.cs @@ -0,0 +1,37 @@ +ο»Ώusing System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Contact.Migrations +{ + /// + public partial class AddContactSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ContactSettings", + columns: table => new + { + Id = table.Column(type: "int", nullable: false), + Enabled = table.Column(type: "tinyint(1)", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false), + UpdatedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ContactSettings", x => x.Id); + }) + .Annotation("MySQL:Charset", "utf8mb4"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ContactSettings"); + } + } +} diff --git a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs index 52b5f28..d56a9cb 100644 --- a/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Contact/Migrations/ContactDbContextModelSnapshot.cs @@ -85,6 +85,25 @@ namespace SlpModularCms.Modules.Contact.Migrations b.ToTable("ContactMessages", (string)null); }); + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.ContactSettings", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Enabled") + .HasColumnType("tinyint(1)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.Property("UpdatedByUserId") + .HasColumnType("char(36)"); + + b.HasKey("Id"); + + b.ToTable("ContactSettings", (string)null); + }); + modelBuilder.Entity("SlpModularCms.Modules.Contact.Data.Entities.IdempotencyRecord", b => { b.Property("SiteId") diff --git a/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs b/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs new file mode 100644 index 0000000..9e778d0 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Models/ContactAdminModels.cs @@ -0,0 +1,93 @@ +using System.Diagnostics.CodeAnalysis; +using SlpModularCms.Modules.Contact.Data.Entities; + +namespace SlpModularCms.Modules.Contact.Models; + +// JSON shapes of the management routes. Statuses are lower-camel strings: +// status: new | read | archived | spam | converted +// mailStatus: pending | sent | failed | notApplicable + +[ExcludeFromCodeCoverage] +public record ContactMessageListItem( + string Id, + DateTimeOffset ReceivedAt, + string Name, + string Email, + string Subject, + string Status, + string MailStatus); + +[ExcludeFromCodeCoverage] +public record ContactMessageList( + IReadOnlyList Items, + int Page, + int PageSize, + int TotalCount, + int UnreadCount); + +[ExcludeFromCodeCoverage] +public record ContactMessageDetail( + string Id, + DateTimeOffset ReceivedAt, + string Name, + string Email, + string Subject, + string Message, + string Status, + string MailStatus, + int MailAttempts, + string? MailError, + DateTimeOffset RetentionUntil); + +/// Body of PATCH /contact-messages/{id}. Nullable so a missing field is reported in our own shape. +public record UpdateContactMessageStatusRequest(string? Status); + +[ExcludeFromCodeCoverage] +public record ContactResendResult(string MailStatus, int MailAttempts, bool Mailed); + +[ExcludeFromCodeCoverage] +public record ContactSettingsDto(bool Enabled, bool HostEnabled); + +/// Body of PUT /contact-settings. Nullable so a missing or non-boolean value is reported as errors.enabled. +public record UpdateContactSettingsRequest(bool? Enabled); + +/// The wire names of the statuses. +public static class ContactStatusNames +{ + public static string Of(ContactMessageStatus status) => status switch + { + ContactMessageStatus.New => "new", + ContactMessageStatus.Read => "read", + ContactMessageStatus.Archived => "archived", + ContactMessageStatus.Spam => "spam", + ContactMessageStatus.Converted => "converted", + _ => throw new ArgumentOutOfRangeException(nameof(status)), + }; + + public static string Of(ContactMailStatus status) => status switch + { + ContactMailStatus.Pending => "pending", + ContactMailStatus.Sent => "sent", + ContactMailStatus.Failed => "failed", + ContactMailStatus.NotApplicable => "notApplicable", + _ => throw new ArgumentOutOfRangeException(nameof(status)), + }; + + /// Parses a filter value (case-insensitive); only the statuses that can be listed. + public static bool TryParseListable(string? value, out ContactMessageStatus status) + { + status = default; + switch (value?.Trim().ToLowerInvariant()) + { + case "new": status = ContactMessageStatus.New; return true; + case "read": status = ContactMessageStatus.Read; return true; + case "archived": status = ContactMessageStatus.Archived; return true; + case "spam": status = ContactMessageStatus.Spam; return true; + default: return false; + } + } + + /// Parses a value an administrator may set: new, read or archived. + public static bool TryParseSettable(string? value, out ContactMessageStatus status) + => TryParseListable(value, out status) && status != ContactMessageStatus.Spam; +} diff --git a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs index fb26df7..c63ad3f 100644 --- a/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs +++ b/src/SlpModularCms.Modules.Contact/Repositories/ContactRepository.cs @@ -13,6 +13,21 @@ public interface IContactRepository Task SaveChangesAsync(CancellationToken cancellationToken); Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken); Task DeleteIdempotencyOlderThanAsync(DateTimeOffset cutoff, CancellationToken cancellationToken); + + // ---- management (admin) ---- + + /// One page of messages of the given statuses, newest first, plus the total count of that selection. + Task<(IReadOnlyList Items, int TotalCount)> ListAsync( + string siteId, IReadOnlyCollection statuses, int skip, int take, CancellationToken cancellationToken); + + /// Messages with status New. Spam is never counted. + Task CountUnreadAsync(string siteId, CancellationToken cancellationToken); + + Task GetAsync(string siteId, Guid id, CancellationToken cancellationToken); + void Remove(ContactMessage message); + + Task GetSettingsAsync(CancellationToken cancellationToken); + void Add(ContactSettings settings); } public class ContactRepository(ContactDbContext context) : IContactRepository @@ -33,6 +48,52 @@ public class ContactRepository(ContactDbContext context) : IContactRepository public Task SaveChangesAsync(CancellationToken cancellationToken) => context.SaveChangesAsync(cancellationToken); + public async Task<(IReadOnlyList Items, int TotalCount)> ListAsync( + string siteId, IReadOnlyCollection statuses, int skip, int take, CancellationToken cancellationToken) + { + // One flag per status instead of 'statuses.Contains(m.Status)': the status is stored as a + // string through a value converter, and a parameterized collection loses that mapping in + // the SQL translation. + var wantNew = statuses.Contains(ContactMessageStatus.New); + var wantRead = statuses.Contains(ContactMessageStatus.Read); + var wantArchived = statuses.Contains(ContactMessageStatus.Archived); + var wantSpam = statuses.Contains(ContactMessageStatus.Spam); + var wantConverted = statuses.Contains(ContactMessageStatus.Converted); + + var query = context.ContactMessages + .AsNoTracking() + .Where(m => m.SiteId == siteId + && ((wantNew && m.Status == ContactMessageStatus.New) + || (wantRead && m.Status == ContactMessageStatus.Read) + || (wantArchived && m.Status == ContactMessageStatus.Archived) + || (wantSpam && m.Status == ContactMessageStatus.Spam) + || (wantConverted && m.Status == ContactMessageStatus.Converted))); + + var total = await query.CountAsync(cancellationToken); + var items = await query + .OrderByDescending(m => m.ReceivedAt) + .ThenBy(m => m.Id) + .Skip(skip) + .Take(take) + .ToListAsync(cancellationToken); + + return (items, total); + } + + public Task CountUnreadAsync(string siteId, CancellationToken cancellationToken) + => context.ContactMessages.CountAsync( + m => m.SiteId == siteId && m.Status == ContactMessageStatus.New, cancellationToken); + + public Task GetAsync(string siteId, Guid id, CancellationToken cancellationToken) + => context.ContactMessages.FirstOrDefaultAsync(m => m.SiteId == siteId && m.Id == id, cancellationToken); + + public void Remove(ContactMessage message) => context.ContactMessages.Remove(message); + + public Task GetSettingsAsync(CancellationToken cancellationToken) + => context.ContactSettings.FirstOrDefaultAsync(s => s.Id == ContactSettings.SingletonId, cancellationToken); + + public void Add(ContactSettings settings) => context.ContactSettings.Add(settings); + public async Task DeleteExpiredMessagesAsync(DateTimeOffset now, CancellationToken cancellationToken) { var total = 0; diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs b/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs new file mode 100644 index 0000000..7cc1c55 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactAdminService.cs @@ -0,0 +1,151 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// Thrown when a spam message is resent; it must be marked as not spam first. +public sealed class ContactResendNotAllowedException() : Exception("A spam message cannot be resent; mark it as not spam first."); + +public interface IContactAdminService +{ + /// Null when page or pageSize is out of range or the status filter is unknown (the caller reports 400). + Task ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken); + + Task GetAsync(Guid id, CancellationToken cancellationToken); + + /// Null when the message does not exist. + Task SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken); + + Task DeleteAsync(Guid id, CancellationToken cancellationToken); + + /// Null when the message does not exist. Throws for spam. + Task ResendAsync(Guid id, CancellationToken cancellationToken); +} + +/// +/// Everything an administrator does with the stored messages. Spam is kept apart: it is never in +/// the default list and never counted as unread. Nothing personal is logged, only ids and outcomes. +/// +public sealed class ContactAdminService( + IContactRepository repository, + IContactMailSender mailSender, + IOptions options, + TimeProvider time, + ILogger logger) : IContactAdminService +{ + public const int DefaultPageSize = 25; + public const int MaxPageSize = 100; + + private static readonly ContactMessageStatus[] DefaultStatuses = + [ContactMessageStatus.New, ContactMessageStatus.Read, ContactMessageStatus.Archived]; + + public async Task ListAsync(string? status, int page, int pageSize, CancellationToken cancellationToken) + { + if (page < 1 || pageSize < 1 || pageSize > MaxPageSize) + { + return null; + } + + ContactMessageStatus[] statuses; + if (string.IsNullOrWhiteSpace(status)) + { + statuses = DefaultStatuses; + } + else if (ContactStatusNames.TryParseListable(status, out var parsed)) + { + statuses = [parsed]; + } + else + { + return null; + } + + var siteId = options.Value.EffectiveSiteId; + var (items, total) = await repository.ListAsync(siteId, statuses, (page - 1) * pageSize, pageSize, cancellationToken); + var unread = await repository.CountUnreadAsync(siteId, cancellationToken); + + return new ContactMessageList( + items.Select(m => new ContactMessageListItem( + m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, + ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus))).ToList(), + page, pageSize, total, unread); + } + + public async Task GetAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + return message is null ? null : ToDetail(message); + } + + public async Task SetStatusAsync(Guid id, ContactMessageStatus status, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return null; + } + + // Marking a spam message as read/new/archived means "this was a real person": it then + // follows the normal retention instead of being deleted after the short spam period. + if (message.Status == ContactMessageStatus.Spam) + { + message.RetentionUntil = time.GetUtcNow().AddMonths(options.Value.RetentionMonths); + } + + message.Status = status; + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Contact message {MessageId} set to {Status}", message.Id, status); + return ToDetail(message); + } + + public async Task DeleteAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return false; + } + + repository.Remove(message); + await repository.SaveChangesAsync(cancellationToken); + + logger.LogInformation("Contact message {MessageId} deleted", id); + return true; + } + + public async Task ResendAsync(Guid id, CancellationToken cancellationToken) + { + var message = await repository.GetAsync(options.Value.EffectiveSiteId, id, cancellationToken); + if (message is null) + { + return null; + } + + if (message.Status == ContactMessageStatus.Spam) + { + throw new ContactResendNotAllowedException(); + } + + var outcome = await mailSender.SendAsync(message, cancellationToken); + if (outcome != ContactMailOutcome.Skipped) + { + message.MailAttempts++; + message.MailStatus = outcome == ContactMailOutcome.Sent ? ContactMailStatus.Sent : ContactMailStatus.Failed; + await repository.SaveChangesAsync(cancellationToken); + } + + logger.LogInformation("Contact message {MessageId} resent: {Outcome}", id, outcome); + return new ContactResendResult( + ContactStatusNames.Of(message.MailStatus), message.MailAttempts, outcome == ContactMailOutcome.Sent); + } + + private static ContactMessageDetail ToDetail(ContactMessage m) => new( + m.Id.ToString(), m.ReceivedAt, m.Name, m.Email, m.Subject, m.Message, + ContactStatusNames.Of(m.Status), ContactStatusNames.Of(m.MailStatus), + m.MailAttempts, m.MailError, m.RetentionUntil); +} diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs new file mode 100644 index 0000000..f458337 --- /dev/null +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs @@ -0,0 +1,126 @@ +using Microsoft.Extensions.Options; +using SlpModularCms.Modules.Contact.Config; +using SlpModularCms.Modules.Contact.Data.Entities; +using SlpModularCms.Modules.Contact.Models; +using SlpModularCms.Modules.Contact.Repositories; + +namespace SlpModularCms.Modules.Contact.Services; + +/// +/// The latest known value of the CMS switch, shared by all requests of this process. Short-lived +/// so the public routes do not query the database on every request, and dropped immediately when +/// the switch is changed here (other instances see a change after at most ). +/// +public sealed class ContactSettingsCache(TimeProvider time) +{ + public static readonly TimeSpan Lifetime = TimeSpan.FromSeconds(5); + + private readonly object _lock = new(); + private bool _value; + private DateTimeOffset _expires = DateTimeOffset.MinValue; + + public bool TryGet(out bool enabled) + { + lock (_lock) + { + enabled = _value; + return time.GetUtcNow() < _expires; + } + } + + public void Set(bool enabled) + { + lock (_lock) + { + _value = enabled; + _expires = time.GetUtcNow() + Lifetime; + } + } + + public void Invalidate() + { + lock (_lock) + { + _expires = DateTimeOffset.MinValue; + } + } +} + +public interface IContactSettingsService +{ + /// The CMS switch (a missing row means off). + Task IsEnabledAsync(CancellationToken cancellationToken); + + Task GetAsync(CancellationToken cancellationToken); + Task SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken); +} + +public sealed class ContactSettingsService( + IContactRepository repository, + ContactSettingsCache cache, + IOptions options, + TimeProvider time) : IContactSettingsService +{ + public async Task IsEnabledAsync(CancellationToken cancellationToken) + { + if (cache.TryGet(out var cached)) + { + return cached; + } + + var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false; + cache.Set(enabled); + return enabled; + } + + public async Task GetAsync(CancellationToken cancellationToken) + { + // The administrator's own view is never served from the cache. + var enabled = (await repository.GetSettingsAsync(cancellationToken))?.Enabled ?? false; + return new ContactSettingsDto(enabled, options.Value.Enabled); + } + + public async Task SetEnabledAsync(bool enabled, Guid userId, CancellationToken cancellationToken) + { + var settings = await repository.GetSettingsAsync(cancellationToken); + if (settings is null) + { + settings = new ContactSettings(); + repository.Add(settings); + } + + settings.Enabled = enabled; + settings.UpdatedAt = time.GetUtcNow(); + settings.UpdatedByUserId = userId; + await repository.SaveChangesAsync(cancellationToken); + + cache.Invalidate(); + return new ContactSettingsDto(enabled, options.Value.Enabled); + } +} + +/// Layer 2: the switch an administrator controls in the CMS. +public sealed class CmsFlagContactFormGate(IContactSettingsService settings) : IContactFormGate +{ + public Task IsOpenAsync(CancellationToken cancellationToken) => settings.IsEnabledAsync(cancellationToken); +} + +/// +/// The form is open only if every layer is open. Layers are asked in order and the first closed +/// one ends the check, so with the host switch off the database is never touched. +/// +public sealed class CompositeContactFormGate(IReadOnlyList layers) : IContactFormGate +{ + public async Task IsOpenAsync(CancellationToken cancellationToken) + { + foreach (var layer in layers) + { + if (!await layer.IsOpenAsync(cancellationToken)) + { + return false; + } + } + + return true; + } +} -- 2.39.5 From c3dceb203b709ce69312e2966b7a04fc1cbee536 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 9 Nov 2026 23:20:53 +0100 Subject: [PATCH 11/83] Docs: overdracht fase 1 voor de frontend (routes, configuratie, rebase-checklist, afwijkingen) Co-Authored-By: Claude Sonnet 5.5 --- .../construction/phase-1-handoff.md | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md new file mode 100644 index 0000000..5d17898 --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -0,0 +1,106 @@ +# Phase 1 handoff (CMS side) β€” for the frontend work + +Branch `feature/contact-forms-module` (worktree `..\SlpModularCms-contact-forms`), base master `d9cc539`, phase 1 units CMS-U0, U1, U1b, U2, U3, U3b, U4 all committed (last commit `44f161a`). Nothing pushed, merged or deployed. Phase 2 (CMS-U5 mail + retry, CMS-U6 "Berichten" UI, CMS-U7 `PUT /availability/status`) waits for the merge of `feature/identity-email-notifications` and a rebase. + +The machine-readable source for types is **`openapi/slpsoftware.v1.json`** (one file per host, named after the host; regenerate with `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`). Per-unit details: `construction/cms-u*/code/summary.md`. + +All paths are under `/api/v1`. "Gate" = the availability gate: routes without the public marker answer 503 to visitors while the CMS is off or in maintenance; a verified Owner/Administrator always gets through. `401` = no/invalid login, `403` = logged in without `Administrator`/`Owner`. JSON is camelCase. + +## 1. Routes + +### Offerings (module `Offerings`) +| Method + path | Auth | Success | Other status codes | +|---|---|---|---| +| `GET /offerings` | public (marker, survives a closed gate); limiter `offerings-public` 120/60 s | `200` array of offerings | `429` | +| `POST /offerings` | AdminOnly | `201` + `Location: /api/v1/offerings/{id}` + offering | `400` (framework validation shape; bad `categoryId` = `errors.categoryId=["invalid"]`), `409` slug taken, `401`, `403`, `503` | +| `PUT /offerings/{id:guid}` | AdminOnly | `200` offering (full replace; omitting `categoryId` clears the category) | `400`, `404`, `409`, `401`, `403`, `503` | +| `DELETE /offerings/{id:guid}` | AdminOnly | `204` (soft delete) | `404`, `401`, `403`, `503` | +| `PUT /offerings/order` body `{ "orderedIds": [guid,...] }` | AdminOnly | `204` | `400` problem unless the list holds every existing offering exactly once, `401`, `403`, `503` | + +Offering JSON: `{ id, slug, title, description, price, priceNote, features[], ctaLabel, featured, displayOrder, categoryId|null, category|null }`. `category` = the category **name** (a rename shows up at once; no response caching in the code); `categoryId` and `displayOrder` are additive fields the SLP site can ignore. Create/update body: `title, description, price, priceNote, features[], ctaLabel, featured, slug?, categoryId?` (`categoryId` must exist; `null` clears). + +### Offering categories (CMS data, nothing seeded) +| Method + path | Auth | Success | Other | +|---|---|---|---| +| `GET /offerings/categories` | AdminOnly | `200` `[{ id, name, sortOrder, offeringCount }]` | `401`, `403`, `503` | +| `POST /offerings/categories` `{ name }` (1-100) | AdminOnly | `201` + Location + category | `400`, `409` name taken (case-insensitive) | +| `PUT /offerings/categories/{id:guid}` `{ name }` | AdminOnly | `200` category | `400`, `404`, `409` | +| `DELETE /offerings/categories/{id:guid}` | AdminOnly | `204` | `404`, `409` while live offerings use it | + +### Contact β€” public (module `Contact`) +Both answer `404` with an **empty body** while the form is closed (host switch OR CMS switch off); the website then shows its mailto fallback. Both stay reachable when the CMS is disabled. +| Method + path | Auth | Success | Other | +|---|---|---|---| +| `GET /contact-messages/token` | public (marker); limiter `contact-token` 20/600 s | `200` `{ token, minSeconds, captcha: null \| { provider, siteKey } }` | `404` closed, `429` | +| `POST /contact-messages` headers `Idempotency-Key: ` (required), body `{ name, email, subject, message, hpCheck, token, captchaToken? }` | public (marker); limiter `contact-form` 5/600 s | `202` `{ "status": "received" }` β€” identical for genuine, spam and replay | `400` problem+json (`errors` per field), `404` closed, `413` problem (> 16384 bytes), `429` | + +Limits: name 1-100, email 1-254 (regex `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`), subject 1-100 (opaque value chosen by the site), message 1-2000; all trimmed; control characters rejected (line breaks and tabs allowed in `message`). `hpCheck` is the honeypot, must be empty. `400` shape: `{ type, title, status, errors: { : [code] } }`, codes `required | tooLong | invalid | expired`; fields `name, email, subject, message, token, idempotencyKey, body`. A forged, other-site or expired token is always `errors.token=["expired"]` (fetch a fresh token and retry once). Replays with the same key within 24 h get the same `202` without a second message; a `400` does not use up the key. + +### Contact β€” management (AdminOnly; not public; behind the gate) +All answer `404` with an empty body while the **host** switch `Contact:Enabled` is off (the tables do not exist then). The CMS switch never closes them. +| Method + path | Success | Other | +|---|---|---| +| `GET /contact-messages?status=&page=&pageSize=` | `200` `{ items[{id,receivedAt,name,email,subject,status,mailStatus}], page, pageSize, totalCount, unreadCount }`; default list = `new`,`read`,`archived` (**no spam**), `status=spam` shows spam apart; `pageSize` 1-100 (default 25); `unreadCount` = `new` only, never spam | `400` (`errors.page/pageSize/status`), `401`, `403`, `404`, `503` | +| `GET /contact-messages/{id:guid}` | `200` detail (list fields + `message, mailAttempts, mailError, retentionUntil`) | `404` | +| `PATCH /contact-messages/{id:guid}` `{ "status": "new"\|"read"\|"archived" }` | `200` detail (on a spam message = "not spam": normal retention from now) | `400 errors.status=["invalid"]`, `404` | +| `DELETE /contact-messages/{id:guid}` | `204` (hard delete) | `404` | +| `POST /contact-messages/{id:guid}/resend` (limiter `contact-resend` 5/600 s) | `200` `{ mailStatus, mailAttempts, mailed }` (`mailed:false` until CMS-U5) | `404`, `409` spam message, `429` | +| `GET /contact-settings` | `200` `{ enabled, hostEnabled }` (`enabled` = CMS switch, default **false**) | `401`, `403`, `404`, `503` | +| `PUT /contact-settings` `{ "enabled": true\|false }` | `200` same shape | `400 errors.enabled=["invalid"]` for anything that is not a JSON boolean, `401`, `403`, `404`, `503` | + +`status`: `new|read|archived|spam|converted`; `mailStatus`: `pending|sent|failed|notApplicable`. + +### Unchanged but relevant +`POST /availability/admin/status` still has its `admin` segment; it becomes `PUT /availability/status` in phase 2 (CMS-U7, after the ASF merge; callers to check then: master/slave status, poll client, frontend). `GET /availability/status` stays public. + +## 2. `Contact:*` and related configuration keys (Api.SlpSoftware `appsettings.json`) +| Key | Default | Notes | +|---|---|---| +| `Contact:Enabled` | `false` | host switch; **release condition**, see Β§ 3 | +| `Contact:SiteId` | `slpsoftware` (code default `default`) | stored on rows, in the token purpose; never from a request | +| `Contact:MinSeconds` | `3` | returned as `minSeconds`; faster = spam | +| `Contact:TokenLifetimeMinutes` | `120` | | +| `Contact:RetentionMonths` | `12` | fixed per row at insert | +| `Contact:SpamRetentionDays` | `30` | | +| `Contact:MaxSpamRowsPerDay` | `200` | per site per UTC day; beyond it spam is answered but not stored | +| `Contact:MaxBodyBytes` | `16384` | `413` beyond | +| `Contact:ProblemTypeBase` | none -> `about:blank` | `{base}/validation` when set | +| `Contact:Captcha:Enabled` | `false` | | +| `Contact:Captcha:Provider`, `:SiteKey` | none | returned in the token response when enabled | +| `Contact:Captcha:Secret` | none | environment / secrets manager only, never committed | +| `RateLimiting:ContactForm` | `5` / `600` | `PermitLimit` / `WindowSeconds` | +| `RateLimiting:ContactToken` | `20` / `600` | | +| `RateLimiting:ContactResend` | `5` / `600` | | +| (removed) | | `Offerings:Categories` no longer exists; categories are data | + +CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings`, default off. Mail recipient/sender settings arrive with CMS-U5 (environment only, no addresses in committed config). + +## 3. Release / rebase checklist (do in this order, after Bryan merges `feature/identity-email-notifications`) +1. Rebase `feature/contact-forms-module` onto the merged base. Expected conflicts: `AvailabilityMiddleware.cs` (one block), `AddCmsRateLimiting` (`OnRejected`), `appsettings` files, host composition, maybe EF snapshots (own contexts, so none expected; regenerate our migration only if a snapshot conflicts). Re-run all test projects. +2. **Per-client rate limiting**: in `Modules.Contact/Services/ContactSeams.cs`, class `ContactRateLimitPartition`, change `public static string KeyFor(HttpContext context) => GlobalKey;` to `=> ClientPartitionKey.For(context);` (add the ASF `using`; drop `GlobalKey` if unused). In `Contact.Tests/ContactRetentionAndPartitionTests.cs`, test `OnTheBaseBranch_EveryCallerSharesOneBucket` becomes "two different client addresses give two different keys". Until this is done every visitor shares one bucket per policy (5 form submissions per 10 minutes for the whole site), which is why the module is off by default. +3. `ForwardedHeaders:KnownProxies` configured on the host (environment). +4. Phase 2 units (CMS-U5 mail + retry job, CMS-U6 UI, CMS-U7) on the rebased branch; give the Andrea host the Contact module reference and its own `openapi/andreaslopfotografie.v1.json` when it is in scope. +5. Only then set **`Contact:Enabled=true`** on the host (environment or its appsettings). +6. Switch the **CMS switch** on: it is OFF by default, so Bryan must open the form himself (screen "Berichten" in CMS-U6, or `PUT /api/v1/contact-settings {"enabled":true}`). Until both switches are on the website shows its mailto fallback. +7. Nothing is deployed to production without Bryan; no push/merge/PR happened. + +## 4. Known deviations from contract v0.3.x and design decisions to adopt +- **Admin routes** are RESTful on the resource (`/contact-messages`, `/offerings`, `/contact-settings`), no `admin` segment, per Bryan's decision; old `offerings/admin...` routes and move-up/move-down are gone (reorder via `PUT /offerings/order`). +- **One offering DTO** for everybody (`OfferingAdminDto` removed): adds `displayOrder`, `categoryId`; `category` is the name. +- **Categories are CMS data** (table + CRUD), not `Offerings:Categories`. +- **Honeypot** JSON name is fixed `hpCheck` (no configurable name); a **missing `hpCheck` counts as empty**. +- **Unbindable body** (malformed JSON, wrong types) -> `400` with `errors.body=["invalid"]` in the same problem shape (the contact controllers are deliberately not `[ApiController]`). +- **`Contact:ProblemTypeBase`** configurable, default `about:blank` (instead of a fixed URL). +- **Two-layer switch**: host `Contact:Enabled` and the CMS switch; both default off; `404` empty body when closed. +- **`GET /contact-settings`** returns the extra read-only `hostEnabled`. +- **Un-spam** (PATCH spam -> new/read/archived) extends retention to the normal period; **resend of spam = 409**. +- **Management routes answer `404`** while the host switch is off; **an Owner/Administrator passes the availability gate** while the CMS is disabled (existing design), visitors get `503`. +- **Mail**: stored first; the mail seam (`IContactMailSender`) is a no-op until CMS-U5, so messages stay `pending` and resend reports `mailed:false`. +- **Rate limits** are global buckets on this base until the checklist step 2 (documented, enforced by the default-off switches). +- **Privacy**: no IP address is stored; Sentry error events carry the caller's IP (`SendDefaultPii`) but never form content β€” mention error reporting in the privacy statement. Backups may keep deleted messages longer than the retention period β€” mention or shorten backup retention. + +## 5. Tests and tooling worth knowing +- Pipeline tests (`Contact.Tests/Pipeline`, `Api.Tests`) need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (CI provides it: `.gitea/workflows/continuous_integration.yaml`). Each fixture creates and drops its own database. Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`. +- Frontend (`frontend/`): `pnpm lint`, `npx tsc -b`, `pnpm test` (278 tests at CMS-U1b). 15 pre-existing files under `features/offerings` fail `prettier --check` (tech debt, not touched). +- The admin frontend work of phase 1 is only the offerings part (new routes, `useMoveOffering` via `PUT /offerings/order`, categories dialog + select, query key `['offerings','list']`). +- Last test run (CMS-U4): Contact.Tests 223, Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4 β€” all green. -- 2.39.5 From 99066f7ed6caff8336345bfb54714e348ebd352d Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:25:43 +0100 Subject: [PATCH 12/83] Contactroutes: rate limiting per client met de ClientPartitionKey van de host ContactRateLimitPartition.KeyFor gebruikt nu ClientPartitionKey.For(context) in plaats van een vaste sleutel; de test controleert dat verschillende clientadressen verschillende buckets krijgen. ForwardedHeaders:KnownProxies moet op elke host staan die de contactroutes inschakelt. Co-Authored-By: Claude Sonnet 5.5 --- .../ContactRetentionAndPartitionTests.cs | 26 +++++++++++++------ .../Services/ContactSeams.cs | 17 ++++++------ 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs index 915781e..3f89d0c 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs @@ -124,21 +124,31 @@ public class ContactRetentionServiceTests public class ContactRateLimitPartitionTests { /// - /// REBASE CHECKLIST: on master there is no per-client partitioning, so every caller shares one - /// bucket and this test pins the constant. After the ASF merge the body of - /// ContactRateLimitPartition.KeyFor becomes return ClientPartitionKey.For(context); - /// and this test changes to "two different client addresses give two different keys". + /// Every contact policy is partitioned per client with the host's own key + /// (ClientPartitionKey): different client addresses never share a bucket. /// [Fact] - public void OnTheBaseBranch_EveryCallerSharesOneBucket() + public void DifferentClientAddresses_GetDifferentBuckets_AndTheSameAddressTheSameBucket() { var first = new DefaultHttpContext(); first.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10"); + var again = new DefaultHttpContext(); + again.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("203.0.113.10"); var second = new DefaultHttpContext(); second.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("198.51.100.20"); - ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.GlobalKey); - ContactRateLimitPartition.KeyFor(second).Should().Be(ContactRateLimitPartition.GlobalKey); - ContactRateLimitPartition.GlobalKey.Should().Be("global"); + ContactRateLimitPartition.KeyFor(first).Should().NotBe(ContactRateLimitPartition.KeyFor(second)); + ContactRateLimitPartition.KeyFor(first).Should().Be(ContactRateLimitPartition.KeyFor(again)); + ContactRateLimitPartition.KeyFor(first).Should().Be("203.0.113.10"); + } + + [Fact] + public void TheKeyIsTheHostsOwnClientKey() + { + var context = new DefaultHttpContext(); + context.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("::ffff:192.0.2.7"); + + ContactRateLimitPartition.KeyFor(context).Should().Be(SlpModularCms.Core.Hosting.Proxy.ClientPartitionKey.For(context)); + ContactRateLimitPartition.KeyFor(new DefaultHttpContext()).Should().Be(SlpModularCms.Core.Hosting.Proxy.ClientPartitionKey.Unknown); } } diff --git a/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs index c68ea7a..bb55c42 100644 --- a/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs +++ b/src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Http; +using SlpModularCms.Core.Hosting.Proxy; using SlpModularCms.Modules.Contact.Data.Entities; namespace SlpModularCms.Modules.Contact.Services; @@ -46,16 +47,14 @@ public sealed class NoOpContactMailSender : IContactMailSender /// The single place that decides which rate-limit bucket a request belongs to. /// /// -/// On the base branch the rate limiter has no per-client partitioning (no forwarded-header -/// handling, no client key): every visitor is the same caller. This returns a constant, so the -/// contact policies behave as ONE shared bucket per policy, which is why the contact routes are -/// disabled (Contact:Enabled=false) until the per-client partitioning from the ASF branch -/// has been merged. Switching to per-client is the one-line change documented in the rebase -/// checklist: replace the body with ClientPartitionKey.For(context). +/// Every contact policy is partitioned per client, with the same key as the other policies of the +/// host (: the remote address as seen by the pipeline, the real +/// visitor once ForwardedHeaders:KnownProxies is configured). That setting is required on +/// every host that enables the contact routes: without it all visitors share the proxy's address, +/// i.e. one bucket for the whole site. The routes stay disabled by default +/// (Contact:Enabled=false) until that has been checked on the host. /// public static class ContactRateLimitPartition { - public const string GlobalKey = "global"; - - public static string KeyFor(HttpContext context) => GlobalKey; + public static string KeyFor(HttpContext context) => ClientPartitionKey.For(context); } -- 2.39.5 From b39fc5b6ea1853726ee62cd49474d05454836373 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:25:57 +0100 Subject: [PATCH 13/83] GET System/capabilities blijft bereikbaar als het CMS uit staat of in onderhoud is De actie krijgt [PublicSiteEndpoint] (en [AllowAnonymous]), zodat een gast op de loginpagina geen 503 meer krijgt; de lijst van publieke acties in de route-table-test en een pipelinetest (CMS in onderhoud) zijn bijgewerkt. Besluit van Bryan: de beschikbaarheidsstatussen blokkeren alleen het CMS, nooit de publieke site. Co-Authored-By: Claude Sonnet 5.5 --- src/SlpModularCms.Core/Hosting/SystemController.cs | 4 ++++ .../PublicSiteEndpointGateTests.cs | 1 + .../Pipeline/ContactPipelineTests.cs | 14 ++++++++++++++ 3 files changed, 19 insertions(+) diff --git a/src/SlpModularCms.Core/Hosting/SystemController.cs b/src/SlpModularCms.Core/Hosting/SystemController.cs index 600065f..a8ad817 100644 --- a/src/SlpModularCms.Core/Hosting/SystemController.cs +++ b/src/SlpModularCms.Core/Hosting/SystemController.cs @@ -1,5 +1,7 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; +using SlpModularCms.Core.Availability; using SlpModularCms.Core.Email; namespace SlpModularCms.Core.Hosting; @@ -25,6 +27,8 @@ public class SystemController : ControllerBase } [HttpGet("capabilities")] + [AllowAnonymous] + [PublicSiteEndpoint] public IActionResult GetCapabilities() { // EmailEnabled tells the UI whether mail actions exist on this site; DefaultLanguage is the diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs index a2e2a84..96a7ae7 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -161,6 +161,7 @@ public class PublicSiteEndpointGateTests $"{nameof(OfferingsController)}.{nameof(OfferingsController.GetOfferings)}", $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.GetToken)}", $"{nameof(ContactMessagesController)}.{nameof(ContactMessagesController.Submit)}", + $"{nameof(SystemController)}.{nameof(SystemController.GetCapabilities)}", ]; private static IReadOnlyList AllActions() => diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs index 890b297..4b713c6 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactPipelineTests.cs @@ -315,4 +315,18 @@ public class ContactPipelineGateTests(EnabledContactHostFactory factory) : IClas post.StatusCode.Should().Be(HttpStatusCode.Accepted); (await factory.WithDb(db => db.ContactMessages.CountAsync(m => m.Name == "Pipeline Gate"))).Should().Be(1); } + + [Fact] + public async Task TheLoginPageRoutes_NeverAnswer503_WhileTheCmsIsDisabled() + { + await factory.WithDb(db => db.Database.ExecuteSqlRawAsync( + "INSERT INTO AvailabilityState (Id, Status, Message, LastUpdatedAt, UpdatedBy) VALUES (UUID(), 2, 'maintenance pipeline test', NOW(), 'pipeline test')")); + var client = factory.CreateClient(); + + // A guest on a disabled or maintenance CMS must still be able to read what the login page needs. + (await client.GetAsync("/api/v1/System/capabilities")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/Availability/status")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/contact-messages")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, "the management routes stay behind the gate"); + } } -- 2.39.5 From daa1bac312c3ea89f7a5c9dad3edd99de4fe0721 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:25:57 +0100 Subject: [PATCH 14/83] Tests na de rebase: echte login voor de beheer-pipelinetests en OpenAPI-document bijgewerkt De host controleert nu elk toegangstoken tegen een bestaande, actieve gebruiker met dezelfde security stamp, dus de pipelinetests maken een echte gebruiker met rol aan en loggen in via de authenticatieservice. Het OpenAPI-document is opnieuw gegenereerd met de routes van de gemergede master. Co-Authored-By: Claude Sonnet 5.5 --- openapi/slpsoftware.v1.json | 274 ++++++++++++++++++ .../Pipeline/ContactAdminPipelineTests.cs | 58 ++-- 2 files changed, 313 insertions(+), 19 deletions(-) diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 61a5189..b64ad04 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -73,6 +73,12 @@ }, "CompleteSetupRequest": { "properties": { + "name": { + "type": [ + "null", + "string" + ] + }, "password": { "type": "string" }, @@ -449,11 +455,28 @@ ], "type": "object" }, + "ForgotPasswordRequest": { + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ], + "type": "object" + }, "InviteUserRequest": { "properties": { "email": { "type": "string" }, + "language": { + "type": [ + "null", + "string" + ] + }, "role": { "type": "string" } @@ -573,6 +596,15 @@ ], "type": "object" }, + "RegenerateInviteRequest": { + "properties": { + "sendEmail": { + "default": false, + "type": "boolean" + } + }, + "type": "object" + }, "RegisterMasterRequest": { "properties": { "masterUrl": { @@ -599,6 +631,26 @@ ], "type": "object" }, + "ResetPasswordRequest": { + "properties": { + "newPassword": { + "type": "string" + }, + "token": { + "type": "string" + }, + "userId": { + "format": "uuid", + "type": "string" + } + }, + "required": [ + "userId", + "token", + "newPassword" + ], + "type": "object" + }, "SetUserActiveRequest": { "properties": { "isActive": { @@ -638,6 +690,27 @@ ], "type": "object" }, + "UpdateMailSettingsRequest": { + "properties": { + "fromAddress": { + "type": [ + "null", + "string" + ] + }, + "fromName": { + "type": [ + "null", + "string" + ] + } + }, + "required": [ + "fromAddress", + "fromName" + ], + "type": "object" + }, "UpdateOfferingRequest": { "properties": { "categoryId": { @@ -694,6 +767,12 @@ "email": { "type": "string" }, + "language": { + "type": [ + "null", + "string" + ] + }, "name": { "type": "string" } @@ -1110,6 +1189,48 @@ ] } }, + "/api/v1/SiteSettings/mail": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SiteSettings" + ] + }, + "put": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/UpdateMailSettingsRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateMailSettingsRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UpdateMailSettingsRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "SiteSettings" + ] + } + }, "/api/v1/SlaveStatus": { "get": { "responses": { @@ -1210,6 +1331,92 @@ ] } }, + "/api/v1/Users/{invitationId}/regenerate-invite": { + "post": { + "parameters": [ + { + "in": "path", + "name": "invitationId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RegenerateInviteRequest" + } + ] + } + }, + "application/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RegenerateInviteRequest" + } + ] + } + }, + "text/json": { + "schema": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/RegenerateInviteRequest" + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, + "/api/v1/Users/{invitationId}/resend-invite": { + "post": { + "parameters": [ + { + "in": "path", + "name": "invitationId", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Users" + ] + } + }, "/api/v1/Users/{userId}": { "delete": { "parameters": [ @@ -1351,6 +1558,38 @@ ] } }, + "/api/v1/auth/forgot-password": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ForgotPasswordRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForgotPasswordRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ForgotPasswordRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, "/api/v1/auth/login": { "post": { "requestBody": { @@ -1395,6 +1634,38 @@ ] } }, + "/api/v1/auth/reset-password": { + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/ResetPasswordRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResetPasswordRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ResetPasswordRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Auth" + ] + } + }, "/api/v1/auth/revoke": { "post": { "responses": { @@ -2089,6 +2360,9 @@ { "name": "Setup" }, + { + "name": "SiteSettings" + }, { "name": "Users" }, diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs index 5e24fdc..522718d 100644 --- a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactAdminPipelineTests.cs @@ -1,39 +1,59 @@ -using System.IdentityModel.Tokens.Jwt; + using System.Net; using System.Net.Http.Headers; -using System.Security.Claims; + using System.Text; using System.Text.Json; using FluentAssertions; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; -using Microsoft.IdentityModel.Tokens; +using SlpModularCms.Core.Identity.Entities; +using SlpModularCms.Core.Identity.Services; using SlpModularCms.Modules.Contact.Data.Entities; namespace SlpModularCms.Modules.Contact.Tests.Pipeline; -/// Mints access tokens the way the host itself does (same settings, same claims). +/// +/// Logs in the way the host itself does: a real, active user with the given role is created and +/// the host's own authentication service issues the access token. (The host checks every access +/// token against its user, so a hand-made token for a user that does not exist is refused.) +/// internal static class Jwt { + private const string Password = "Password1!"; + public static HttpClient ClientWithRole(ContactHostFactory factory, string role, Guid? userId = null) + => ClientWithRoleAsync(factory, role, userId).GetAwaiter().GetResult(); + + public static async Task ClientWithRoleAsync(ContactHostFactory factory, string role, Guid? userId = null) { - var settings = factory.Services.GetRequiredService().GetSection("JwtSettings"); - var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings["Secret"]!)); - var token = new JwtSecurityToken( - issuer: settings["Issuer"], - audience: settings["Audience"], - claims: - [ - new Claim(ClaimTypes.NameIdentifier, (userId ?? Guid.NewGuid()).ToString()), - new Claim(ClaimTypes.Role, role), - ], - expires: DateTime.UtcNow.AddHours(1), - signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); + var id = userId ?? Guid.NewGuid(); + var email = $"pipeline-{id:N}@example.test"; + + string accessToken; + await using (var scope = factory.Services.CreateAsyncScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + var roles = scope.ServiceProvider.GetRequiredService>(); + if (!await roles.RoleExistsAsync(role)) + { + // Roles normally appear with the first-run setup; a test host starts without one. + (await roles.CreateAsync(new ApplicationRole { Name = role })).Succeeded.Should().BeTrue(); + } + + if (await users.FindByIdAsync(id.ToString()) is null) + { + var user = new ApplicationUser { Id = id, UserName = email, Email = email, IsActive = true, DisplayName = email }; + (await users.CreateAsync(user, Password)).Succeeded.Should().BeTrue(); + (await users.AddToRoleAsync(user, role)).Succeeded.Should().BeTrue(); + } + + accessToken = (await scope.ServiceProvider.GetRequiredService().AuthenticateAsync(email, Password)).AccessToken; + } var client = factory.CreateClient(); - client.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token)); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return client; } -- 2.39.5 From ecdc46cb942d74870867a02db128d289193d3123 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:26:27 +0100 Subject: [PATCH 15/83] Docs: rebase-resultaat in de fase-1-overdracht Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/construction/phase-1-handoff.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md index 5d17898..135cefb 100644 --- a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -104,3 +104,6 @@ CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings` - Frontend (`frontend/`): `pnpm lint`, `npx tsc -b`, `pnpm test` (278 tests at CMS-U1b). 15 pre-existing files under `features/offerings` fail `prettier --check` (tech debt, not touched). - The admin frontend work of phase 1 is only the offerings part (new routes, `useMoveOffering` via `PUT /offerings/order`, categories dialog + select, query key `['offerings','list']`). - Last test run (CMS-U4): Contact.Tests 223, Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4 β€” all green. + +## 6. Rebase result (2026-11-10) +Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifications + andreaslop-site-hosting). Conflicts: `aidlc-docs/active-features.md` (kept master's table, appended our row), `AvailabilityMiddleware` (kept their `CheckAdmin` / expired-token 401 behaviour, our marker block before it), `AddCmsRateLimiting.OnRejected` (kept their Retry-After logic for sliding windows, added the `60 s` fallback for policies without a wait and the problem+json body), `SlpModularCms.sln` (took master's, re-added the two Contact projects). No EF snapshot conflict (own contexts). Checklist steps 1 and 2 are DONE: `ContactRateLimitPartition.KeyFor` now returns `ClientPartitionKey.For(context)` and its test asserts different buckets per address. Still open: step 3 (`ForwardedHeaders:KnownProxies` per host), step 5 (`Contact:Enabled=true`), step 6 (CMS switch). `GET /System/capabilities` now carries `[PublicSiteEndpoint]` (never 503; separate commit). The pipeline tests for the management routes log in with a real user (the host validates every access token against its user and security stamp). -- 2.39.5 From a3b67b6a361a26f5c9ebc3216eb7325f85e35db6 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:30:17 +0100 Subject: [PATCH 16/83] Docs: plannen CMS-U5 (mail en retry), CMS-U6 (beheer-UI Berichten) en CMS-U7 (PUT /availability/status) Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 +++++++ ...ms-u5-contact-mail-code-generation-plan.md | 36 +++++++++++++++++++ ...admin-ui-berichten-code-generation-plan.md | 33 +++++++++++++++++ ...ity-restful-status-code-generation-plan.md | 31 ++++++++++++++++ 5 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u5-contact-mail-code-generation-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u6-admin-ui-berichten-code-generation-plan.md create mode 100644 aidlc-docs/features/contact-forms-module/construction/plans/cms-u7-availability-restful-status-code-generation-plan.md 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. -- 2.39.5 From 728fc08db8677230c71210e566b9f829a0a1acbb Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 13:39:40 +0100 Subject: [PATCH 17/83] PUT /availability/status vervangt POST /availability/admin/status; de poort sluit alleen het lezen van de status vrij MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit De status is één resource: de publieke GET en de PUT van de beheerder delen het pad; de PUT geeft de bijgewerkte resource terug. De vrijstelling van de poort geldt nu alleen voor GET en HEAD, zodat de PUT als beheerroute gewoon achter de poort blijft. De oude route verdwijnt zonder alias, dus API en admin-app moeten als één release uit. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../code/summary.md | 20 +++ .../construction/phase-1-handoff.md | 2 +- ...ity-restful-status-code-generation-plan.md | 14 +- .../features/availability/mocks/handlers.ts | 9 +- .../availability/services/useAvailability.ts | 10 +- .../settings/pages/SettingsPage.test.tsx | 37 ++++- openapi/slpsoftware.v1.json | 26 ++-- .../AvailabilityGateScopeTests.cs | 1 + .../AvailabilityStatusRouteTests.cs | 140 ++++++++++++++++++ .../AvailabilityControllerTests.cs | 7 +- .../PublicSiteEndpointGateTests.cs | 1 + .../TestContexts.cs | 1 + .../Controllers/AvailabilityController.cs | 27 ++-- .../Middleware/AvailabilityMiddleware.cs | 9 +- .../AvailabilityStatusPipelineTests.cs | 83 +++++++++++ 16 files changed, 344 insertions(+), 45 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md create mode 100644 src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index 0b79319..de74d2f 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: contact-forms-module - **Project Type**: Brownfield - **Start Date**: 2026-11-09 -- **Current Stage**: PHASE 2 planning - rebased on master e671078; plans CMS-U5, U6, U7 awaiting approval by Redesign - SLS +- **Current Stage**: PHASE 2 - CMS-U7 built and committed; next CMS-U5, then CMS-U6 - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md new file mode 100644 index 0000000..ac4872f --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u7-availability-restful-status/code/summary.md @@ -0,0 +1,20 @@ +# CMS-U7 availability-restful-status: code summary + +## RELEASE NOTE: this unit must go out as ONE release together with the admin app +`POST /api/v1/Availability/admin/status` is removed (no alias) and replaced by `PUT /api/v1/Availability/status`. The API and the admin app (`frontend/`) change together. Deploying only one half breaks the status change in Settings: a new API with an old admin bundle gets a non-JSON fallback page on the old route; a new bundle on an old API gets 405/404. During a deploy window a still-open old browser tab fails until its next page load. + +## Result +- `PUT /api/v1/Availability/status` (AdminOnly), body unchanged `{ "newStatus": "Available"|"Maintenance"|"NotAvailable", "reason": string|null }`. `200` with the **updated resource**, same JSON as `GET /api/v1/Availability/status` (`{ status, checkedAt, message, isMasterControlled }`); `409` problem+json when the status is master-controlled (unchanged); `400` for an invalid status or a service that cannot persist; `401`/`403` like every admin route. +- `GET /api/v1/Availability/status` is unchanged (public, open for everyone, also while the CMS is off). +- Old route removed; `openapi/slpsoftware.v1.json` regenerated. +- **Gate** (`AvailabilityMiddleware`, small isolated diff): the exemption for `/api/v1/Availability/status` now applies to `GET`/`HEAD` only. `PUT` (and any other method) follows the normal gate: a verified Owner/Administrator passes, an expired token gets `401`, everyone else `503`. Before, the prefix exemption let any method through. +- Frontend: `useUpdateAvailability` uses `PUT` and writes the answer into the status cache; msw default handler and the two failure handlers in `SettingsPage.test.tsx` moved to `PUT`; a new test asserts method, path (no `admin`) and body. + +## Callers of the old route (checked repository-wide: code, docs, CI, configs) +Only the admin frontend: `features/availability/services/useAvailability.ts`, `features/availability/mocks/handlers.ts`, two handlers in `features/settings/pages/SettingsPage.test.tsx`. No server-side caller: the master pushes with `POST /Master/status`, slaves read `GET /SlaveStatus`; no proxy, deploy script or workflow mentions it; the README names only the GET. Historic `aidlc-docs` mentions are history and unchanged. + +## Changes to existing tests (for the record) +Three existing tests built a request without an HTTP method (the default is empty) and relied on the old method-less prefix exemption. They now set `GET` like a real request does: `TestContexts.Api()` and `AvailabilityGateScopeTests.RunAsync` (shared helpers) and `PublicSiteEndpointGateTests.TheAvailabilityStatusEndpoint_StaysOpen...`. `AvailabilityControllerTests.UpdateStatus_ReturnsOk...` now asserts the body (`OkObjectResult`, same four fields as the GET) instead of `OkResult`. No assertion about gate behaviour was weakened. + +## Verification (real output) +Build 0 errors. Availability.Tests 165 passed (11 new in `AvailabilityStatusRouteTests`: GET/HEAD stay open; PUT/POST/DELETE/PATCH are gated; a verified administrator passes while the CMS is disabled; an expired token on PUT = 401; case-insensitive path; route table = exactly `GET status` + `PUT status`, PUT is AdminOnly and not public-marked, no `admin` in any route). Contact.Tests 228 passed (3 new pipeline tests on the real host: anonymous PUT 401, user 403, administrator PUT Maintenance -> body is the updated resource -> anonymous GET shows it -> visitor gets 503 on a gated route and on the PUT itself -> administrator switches it back; invalid status 400 and unchanged state; the old route behaves like a route that never existed and changes nothing). Api.AndreaSlopFotografie 11, Api 4, Core 625, Identity 145, Master 61, Offerings 86. Frontend: `pnpm lint` clean, `npx tsc -b` clean, vitest 57 files / 432 tests passed (1 new). diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md index 135cefb..1cd8103 100644 --- a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -51,7 +51,7 @@ All answer `404` with an empty body while the **host** switch `Contact:Enabled` `status`: `new|read|archived|spam|converted`; `mailStatus`: `pending|sent|failed|notApplicable`. ### Unchanged but relevant -`POST /availability/admin/status` still has its `admin` segment; it becomes `PUT /availability/status` in phase 2 (CMS-U7, after the ASF merge; callers to check then: master/slave status, poll client, frontend). `GET /availability/status` stays public. +`PUT /availability/status` (AdminOnly; body `{ newStatus, reason }`; `200` with the updated resource in the GET shape, `409` master-controlled) replaced `POST /availability/admin/status` (CMS-U7, no alias; API and admin app must be released together). `GET /availability/status` stays public; the gate exempts it for GET/HEAD only. ## 2. `Contact:*` and related configuration keys (Api.SlpSoftware `appsettings.json`) | Key | Default | Notes | 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 index ffe8669..f58bbef 100644 --- 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 @@ -15,13 +15,13 @@ Phase 2, on the rebased branch. Decision (Bryan via SLS): no `/admin` segment in 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. +- [x] **Step 1 β€” Controller**: `[HttpPut("status")]` replaces `admin/status`; returns the updated status object (shared builder with GET); remove the old route. +- [x] **Step 2 β€” Middleware**: method-aware bypass for `Availability/status` (small, isolated diff); comment explains why. +- [x] **Step 3 β€” Frontend**: `useAvailability.ts` mutation (PUT + cache update), `availability/mocks/handlers.ts`, `SettingsPage.test.tsx` (2 handlers); no other change. +- [x] **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). +- [x] **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. +- [x] **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. +- [x] **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. diff --git a/frontend/src/features/availability/mocks/handlers.ts b/frontend/src/features/availability/mocks/handlers.ts index c09c7ad..397c8d8 100644 --- a/frontend/src/features/availability/mocks/handlers.ts +++ b/frontend/src/features/availability/mocks/handlers.ts @@ -10,5 +10,12 @@ export const availabilityHandlers = [ }), ), - http.post('*/Availability/admin/status', () => new HttpResponse(null, { status: 200 })), + http.put('*/Availability/status', () => + HttpResponse.json({ + status: 'Available', + checkedAt: new Date().toISOString(), + message: '', + isMasterControlled: false, + }), + ), ]; diff --git a/frontend/src/features/availability/services/useAvailability.ts b/frontend/src/features/availability/services/useAvailability.ts index bf5f876..988e5e7 100644 --- a/frontend/src/features/availability/services/useAvailability.ts +++ b/frontend/src/features/availability/services/useAvailability.ts @@ -17,8 +17,12 @@ export function useAvailabilityStatus() { export function useUpdateAvailability() { const queryClient = useQueryClient(); - return useMutation({ - mutationFn: (data) => api.post('/api/v1/Availability/admin/status', data), - onSuccess: () => queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }), + return useMutation({ + mutationFn: (data) => api.put('/api/v1/Availability/status', data), + onSuccess: (updated) => { + // The PUT answers with the updated resource (same shape as the GET): use it at once. + queryClient.setQueryData(['availability', 'status'], updated); + return queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }); + }, }); } diff --git a/frontend/src/features/settings/pages/SettingsPage.test.tsx b/frontend/src/features/settings/pages/SettingsPage.test.tsx index 960c179..3941579 100644 --- a/frontend/src/features/settings/pages/SettingsPage.test.tsx +++ b/frontend/src/features/settings/pages/SettingsPage.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; @@ -60,6 +60,37 @@ describe('SettingsPage', () => { expect(maintenanceBtn.className).toContain('bg-primary'); }); + it('changes the status with PUT on the status resource (no admin route), sending the chosen status', async () => { + let sent: { method: string; url: string; body: { newStatus: string } } | undefined; + server.use( + http.put(`${API_BASE}/api/v1/Availability/status`, async ({ request }) => { + sent = { + method: request.method, + url: new URL(request.url).pathname, + body: (await request.json()) as { newStatus: string }, + }; + return HttpResponse.json({ + status: 'Maintenance', + checkedAt: new Date().toISOString(), + message: '', + isMasterControlled: false, + }); + }), + ); + mockAuthenticated(); + renderApp('/settings'); + + await screen.findByTestId('availability-mode-selector', {}, { timeout: 10000 }); + await userEvent.click(screen.getByTestId('mode-option-Maintenance')); + await userEvent.click(screen.getByTestId('availability-save-button')); + + await vi.waitFor(() => expect(sent).toBeDefined()); + expect(sent!.method).toBe('PUT'); + expect(sent!.url).toBe('/api/v1/Availability/status'); + expect(sent!.url).not.toContain('admin'); + expect(sent!.body.newStatus).toBe('Maintenance'); + }); + it('saves availability and shows success toast', async () => { mockAuthenticated(); renderApp('/settings'); @@ -72,7 +103,7 @@ describe('SettingsPage', () => { it('shows error toast when save fails', async () => { server.use( - http.post(`${API_BASE}/api/v1/Availability/admin/status`, () => + http.put(`${API_BASE}/api/v1/Availability/status`, () => HttpResponse.json({ title: 'Error' }, { status: 500 }), ), ); @@ -118,7 +149,7 @@ describe('SettingsPage', () => { it('shows a master-controlled error toast on a 409 conflict from the server', async () => { server.use( - http.post(`${API_BASE}/api/v1/Availability/admin/status`, () => + http.put(`${API_BASE}/api/v1/Availability/status`, () => HttpResponse.json({ title: 'Conflict' }, { status: 409 }), ), ); diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index b64ad04..e9ae40b 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -887,8 +887,18 @@ }, "openapi": "3.1.1", "paths": { - "/api/v1/Availability/admin/status": { - "post": { + "/api/v1/Availability/status": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "Availability" + ] + }, + "put": { "requestBody": { "content": { "application/*+json": { @@ -919,18 +929,6 @@ ] } }, - "/api/v1/Availability/status": { - "get": { - "responses": { - "200": { - "description": "OK" - } - }, - "tags": [ - "Availability" - ] - } - }, "/api/v1/CmsInstances": { "get": { "responses": { diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs index 75fb60a..f26865b 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityGateScopeTests.cs @@ -39,6 +39,7 @@ public class AvailabilityGateScopeTests var middleware = new AvailabilityMiddleware(next, NullLogger.Instance, validator); var context = new DefaultHttpContext(); context.Request.Path = path; + context.Request.Method = HttpMethods.Get; // reading: the status path is open for GET only context.Response.Body = new MemoryStream(); await middleware.InvokeAsync(context, localSvc, masterSvc); diff --git a/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs new file mode 100644 index 0000000..6a3243e --- /dev/null +++ b/src/SlpModularCms.Modules.Availability.Tests/AvailabilityStatusRouteTests.cs @@ -0,0 +1,140 @@ +using System.Reflection; +using FluentAssertions; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Routing; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using SlpModularCms.Core.Availability; +using SlpModularCms.Core.Hosting.Security; +using SlpModularCms.Core.Observability; +using SlpModularCms.Modules.Availability.Controllers; +using SlpModularCms.Modules.Availability.Middleware; +using SlpModularCms.Modules.Availability.Services; +using Xunit; + +namespace SlpModularCms.Modules.Availability.Tests; + +/// +/// The availability status is one resource: the public GET and the administrator's PUT share the +/// path. There is no separate admin route, and the gate must not exempt the PUT. +/// +public class AvailabilityStatusRouteTests +{ + private readonly IAvailabilityService _service = Substitute.For(); + private readonly IMasterAvailabilityService _master = Substitute.For(); + private readonly IAdminTokenValidator _validator = Substitute.For(); + private readonly RequestDelegate _next = Substitute.For(); + private readonly AvailabilityMiddleware _middleware; + + public AvailabilityStatusRouteTests() + { + _middleware = new AvailabilityMiddleware(_next, NullLogger.Instance, _validator); + _master.GetMasterStatus().Returns(new MasterGateStatus(true, null)); + _service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable); + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Absent)); + } + + private async Task Call(string method, string path = "/api/v1/Availability/status") + { + var context = new DefaultHttpContext(); + context.Request.Method = method; + context.Request.Path = path; + context.Response.Body = new MemoryStream(); + _next.ClearReceivedCalls(); + await _middleware.InvokeAsync(context, _service, _master); + return context; + } + + [Theory] + [InlineData("GET")] + [InlineData("HEAD")] + public async Task ReadingTheStatus_StaysOpen_WhateverTheState(string method) + { + await Call(method); + + await _next.Received(1).Invoke(Arg.Any()); + } + + [Theory] + [InlineData("PUT")] + [InlineData("POST")] + [InlineData("DELETE")] + [InlineData("PATCH")] + public async Task ChangingTheStatus_IsNotExempted_ItMeetsTheGateLikeEveryAdminRoute(string method) + { + var context = await Call(method); + + await _next.DidNotReceive().Invoke(Arg.Any()); + context.Response.StatusCode.Should().Be(503); + } + + [Fact] + public async Task AVerifiedAdministrator_CanStillChangeTheStatus_WhileTheCmsIsDisabled() + { + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(true, default)); + + await Call("PUT"); + + await _next.Received(1).Invoke(Arg.Any()); + } + + [Fact] + public async Task AnExpiredAdministratorToken_OnThePut_Gets401_SoTheAppRefreshesItsSession() + { + _validator.Validate(Arg.Any()).Returns(new AdminTokenResult(false, BypassRejectionReason.Expired)); + + var context = await Call("PUT"); + + context.Response.StatusCode.Should().Be(401); + await _next.DidNotReceive().Invoke(Arg.Any()); + } + + [Fact] + public async Task ThePathMatchIsCaseInsensitive_ForReadingToo() + { + await Call("GET", "/api/v1/availability/STATUS"); + + await _next.Received(1).Invoke(Arg.Any()); + } + + // ---- route table of the controller ---- + + private static IEnumerable<(MethodInfo Action, HttpMethodAttribute Http)> Actions() => + typeof(AvailabilityController) + .GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(m => (Action: m, Http: m.GetCustomAttributes().SingleOrDefault())) + .Where(x => x.Http is not null) + .Select(x => (x.Action, x.Http!)); + + [Fact] + public void RouteTable_StatusIsOneResource_GetIsPublic_PutIsAdminOnly_AndNoRouteHasAnAdminSegment() + { + Actions().Select(a => $"{a.Http.HttpMethods.Single()} {a.Http.Template}") + .Should().BeEquivalentTo(["GET status", "PUT status"]); + + var get = Actions().Single(a => a.Http.HttpMethods.Single() == "GET").Action; + var put = Actions().Single(a => a.Http.HttpMethods.Single() == "PUT").Action; + + get.GetCustomAttribute().Should().NotBeNull(); + put.GetCustomAttribute().Should().BeNull(); + put.GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + put.GetCustomAttribute().Should().BeNull("changing the status must stay behind the gate"); + + foreach (var (_, http) in Actions()) + { + (http.Template ?? string.Empty).Should().NotContainEquivalentOf("admin"); + } + } + + [Fact] + public async Task TheOldAdminRoute_IsGone_AndAnswersLikeAnyUnknownRoute() + { + // Not exempted by the gate and not a route of the controller. + var context = await Call("POST", "/api/v1/Availability/admin/status"); + + context.Response.StatusCode.Should().Be(503, "an unknown admin-looking path is gated like every other non-exempted path"); + Actions().Should().NotContain(a => (a.Http.Template ?? "").Contains("admin")); + } +} diff --git a/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs b/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs index 259667a..236dbd7 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/Controllers/AvailabilityControllerTests.cs @@ -95,7 +95,12 @@ public class AvailabilityControllerTests var result = await controller.UpdateStatus( new UpdateStatusRequest(AvailabilityStatus.Maintenance, "Test maintenance")); - result.Should().BeOfType(); + // The answer is the updated resource, in the same shape as GET /Availability/status. + var ok = result.Should().BeOfType().Subject; + ok.Value!.GetType().GetProperty("Status")!.GetValue(ok.Value).Should().Be("Maintenance"); + ok.Value.GetType().GetProperty("Message")!.GetValue(ok.Value).Should().Be("Test maintenance"); + ok.Value.GetType().GetProperties().Select(p => p.Name) + .Should().BeEquivalentTo(["Status", "CheckedAt", "Message", "IsMasterControlled"]); } [Fact] diff --git a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs index 96a7ae7..5f22a89 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/PublicSiteEndpointGateTests.cs @@ -142,6 +142,7 @@ public class PublicSiteEndpointGateTests CloseGate(ClosedGate.CmsDisabled); var context = new DefaultHttpContext(); context.Request.Path = "/api/v1/Availability/status"; + context.Request.Method = HttpMethods.Get; context.Response.Body = new MemoryStream(); await _middleware.InvokeAsync(context, _service, _masterService); diff --git a/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs index 5179246..e5ed3a2 100644 --- a/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs +++ b/src/SlpModularCms.Modules.Availability.Tests/TestContexts.cs @@ -9,6 +9,7 @@ internal static class TestContexts { var context = new DefaultHttpContext(); context.Request.Path = path; + context.Request.Method = HttpMethods.Get; // a real request always has a method; the status path is open for reads only return context; } } diff --git a/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs b/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs index 4da4318..cde9127 100644 --- a/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs +++ b/src/SlpModularCms.Modules.Availability/Controllers/AvailabilityController.cs @@ -20,18 +20,21 @@ public class AvailabilityController : ControllerBase [HttpGet("status")] [AllowAnonymous] public async Task GetStatus() - { - var details = await _availabilityService.GetStatusDetailsAsync(); - return Ok(new - { - Status = details.Status.ToString(), - CheckedAt = DateTimeOffset.UtcNow, - Message = details.Message ?? string.Empty, - details.IsMasterControlled, - }); - } + => Ok(ToResponse(await _availabilityService.GetStatusDetailsAsync())); - [HttpPost("admin/status")] + private static object ToResponse(AvailabilityStatusDetails details) => new + { + Status = details.Status.ToString(), + CheckedAt = DateTimeOffset.UtcNow, + Message = details.Message ?? string.Empty, + details.IsMasterControlled, + }; + + /// + /// Changes the status. Same resource as the public GET (no separate admin route); the answer is the + /// updated resource, in the same shape as the GET. + /// + [HttpPut("status")] [Authorize(Policy = "AdminOnly")] public async Task UpdateStatus([FromBody] UpdateStatusRequest request) { @@ -47,7 +50,7 @@ public class AvailabilityController : ControllerBase request.Reason, User.Identity?.Name); - return Ok(); + return Ok(ToResponse(await _availabilityService.GetStatusDetailsAsync())); } catch (MasterControlledAvailabilityException ex) { diff --git a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs index 162e356..30d1324 100644 --- a/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs +++ b/src/SlpModularCms.Modules.Availability/Middleware/AvailabilityMiddleware.cs @@ -40,9 +40,12 @@ public class AvailabilityMiddleware // on the bypass list, which only went unnoticed while another server (nginx) served the website and the SPA. private const string GatedPrefix = "/api/"; + // Reading the status stays open for everyone (GET/HEAD only). Changing it (PUT, same path) is an admin route and + // is NOT exempted: it follows the normal gate (a verified Owner/Administrator passes). + private const string StatusPath = "/api/v1/Availability/status"; + private static readonly string[] _bypassPrefixes = [ - "/api/v1/Availability/status", "/api/v1/Auth/", "/api/v1/Setup/status", "/api/v1/master/", @@ -63,7 +66,9 @@ public class AvailabilityMiddleware return; } - if (_bypassPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))) + var readsStatus = path.StartsWith(StatusPath, StringComparison.OrdinalIgnoreCase) + && (HttpMethods.IsGet(context.Request.Method) || HttpMethods.IsHead(context.Request.Method)); + if (readsStatus || _bypassPrefixes.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase))) { await _next(context); return; diff --git a/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs new file mode 100644 index 0000000..26fef6a --- /dev/null +++ b/src/SlpModularCms.Modules.Contact.Tests/Pipeline/AvailabilityStatusPipelineTests.cs @@ -0,0 +1,83 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; + +namespace SlpModularCms.Modules.Contact.Tests.Pipeline; + +/// The availability status as one RESTful resource, on the real composed host. +public class AvailabilityStatusPipelineTests(ClosedCmsSwitchContactHostFactory factory) : IClassFixture +{ + private const string Status = "/api/v1/Availability/status"; + + private static async Task Read(HttpResponseMessage response) + { + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return doc.RootElement.Clone(); + } + + [Fact] + public async Task TheWholeStory_PutMaintenance_VisitorsAreBlocked_PutAvailableAgain() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + var visitor = factory.CreateClient(); + + // Anonymous change: meets authentication while the CMS is available. + (await visitor.PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"x"}"""))) + .StatusCode.Should().Be(HttpStatusCode.Unauthorized); + // A regular user is refused. + (await Jwt.ClientWithRole(factory, "User").PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"x"}"""))) + .StatusCode.Should().Be(HttpStatusCode.Forbidden); + + // The administrator changes it; the answer is the updated resource, same shape as the GET. + var put = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Maintenance","reason":"Gepland onderhoud"}""")); + put.StatusCode.Should().Be(HttpStatusCode.OK); + var body = await Read(put); + body.GetProperty("status").GetString().Should().Be("Maintenance"); + body.GetProperty("message").GetString().Should().Be("Gepland onderhoud"); + body.EnumerateObject().Select(p => p.Name).Should().BeEquivalentTo(["status", "checkedAt", "message", "isMasterControlled"]); + + // Reading stays open for everyone and shows the new state. + var read = await visitor.GetAsync(Status); + read.StatusCode.Should().Be(HttpStatusCode.OK); + (await Read(read)).GetProperty("status").GetString().Should().Be("Maintenance"); + + // Visitors meet the gate on a CMS route, and ALSO on the PUT itself (it is not exempted). + (await visitor.GetAsync("/api/v1/offerings/categories")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await visitor.PutAsync(Status, Jwt.Json("""{"newStatus":"Available","reason":null}"""))).StatusCode + .Should().Be(HttpStatusCode.ServiceUnavailable); + + // The administrator can always switch it back on. + var back = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Available","reason":null}""")); + back.StatusCode.Should().Be(HttpStatusCode.OK); + (await Read(back)).GetProperty("status").GetString().Should().Be("Available"); + (await visitor.GetAsync("/api/v1/offerings/categories")).StatusCode.Should().NotBe(HttpStatusCode.ServiceUnavailable); + } + + [Fact] + public async Task TheOldAdminRoute_IsGone() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + + // The host answers a path that no controller owns with the site's fallback page, so the proof is + // behavioural: the old route behaves exactly like a route that never existed, and it changes nothing. + var old = await admin.PostAsync("/api/v1/Availability/admin/status", Jwt.Json("""{"newStatus":"Maintenance","reason":"old route"}""")); + var neverExisted = await admin.PostAsync("/api/v1/Availability/no-such-route", Jwt.Json("""{"newStatus":"Maintenance","reason":"old route"}""")); + + old.StatusCode.Should().Be(neverExisted.StatusCode); + old.Content.Headers.ContentType?.MediaType.Should().Be(neverExisted.Content.Headers.ContentType?.MediaType); + old.Content.Headers.ContentType?.MediaType.Should().NotBe("application/json"); + (await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("status").GetString().Should().Be("Available"); + (await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("message").GetString().Should().NotContain("old route"); + } + + [Fact] + public async Task AnInvalidStatus_IsRejected_AndTheStateDoesNotChange() + { + var admin = Jwt.ClientWithRole(factory, "Administrator"); + + var response = await admin.PutAsync(Status, Jwt.Json("""{"newStatus":"Exploded","reason":null}""")); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await Read(await factory.CreateClient().GetAsync(Status))).GetProperty("status").GetString().Should().Be("Available"); + } +} -- 2.39.5 From bc7936034ce81397fbe1df16e70eb7b2d9ffd4a1 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 15:28:24 +0100 Subject: [PATCH 18/83] Contact: mail via achtergrondservice met claim, backoff en maximum (CMS-U5) Co-Authored-By: Claude Sonnet 5.5 --- .../contact-forms-module/aidlc-state.md | 2 +- .../features/contact-forms-module/audit.md | 12 + .../cms-u5-contact-mail/code/summary.md | 23 + .../construction/phase-1-handoff.md | 5 + ...ms-u5-contact-mail-code-generation-plan.md | 16 +- openapi/slpsoftware.v1.json | 13 + .../Email/MailTemplateRenderer.cs | 49 +- src/SlpModularCms.Core/Email/MailTypes.cs | 14 +- .../Email/SmtpEmailSender.cs | 8 + .../ContactMailTests.cs | 422 ++++++++++++++++++ .../ContactNoPersonalDataInLogsTests.cs | 13 - .../ContactSubmissionServiceTests.cs | 42 +- .../Pipeline/ContactAdminPipelineTests.cs | 4 +- .../Pipeline/ContactMailPipelineTests.cs | 142 ++++++ .../SubmissionHarness.cs | 6 +- .../Config/ContactOptions.cs | 32 ++ .../ContactModule.cs | 5 +- .../Data/ContactDbContext.cs | 4 + ...0261110141855_ContactMailClaim.Designer.cs | 135 ++++++ .../20261110141855_ContactMailClaim.cs | 22 + .../ContactDbContextModelSnapshot.cs | 1 + .../Models/ContactAdminModels.cs | 5 +- .../Repositories/ContactRepository.cs | 22 + .../Services/ContactAdminService.cs | 39 +- .../Services/ContactMailSender.cs | 97 ++++ .../Services/ContactMailService.cs | 159 +++++++ .../Services/ContactSeams.cs | 56 ++- .../Services/ContactSubmissionService.cs | 32 +- 28 files changed, 1273 insertions(+), 107 deletions(-) create mode 100644 aidlc-docs/features/contact-forms-module/construction/cms-u5-contact-mail/code/summary.md create mode 100644 src/SlpModularCms.Modules.Contact.Tests/ContactMailTests.cs create mode 100644 src/SlpModularCms.Modules.Contact.Tests/Pipeline/ContactMailPipelineTests.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261110141855_ContactMailClaim.Designer.cs create mode 100644 src/SlpModularCms.Modules.Contact/Migrations/20261110141855_ContactMailClaim.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactMailSender.cs create mode 100644 src/SlpModularCms.Modules.Contact/Services/ContactMailService.cs diff --git a/aidlc-docs/features/contact-forms-module/aidlc-state.md b/aidlc-docs/features/contact-forms-module/aidlc-state.md index de74d2f..3e0cabc 100644 --- a/aidlc-docs/features/contact-forms-module/aidlc-state.md +++ b/aidlc-docs/features/contact-forms-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: contact-forms-module - **Project Type**: Brownfield - **Start Date**: 2026-11-09 -- **Current Stage**: PHASE 2 - CMS-U7 built and committed; next CMS-U5, then CMS-U6 +- **Current Stage**: PHASE 2 - CMS-U7 and CMS-U5 built and committed; next CMS-U6, then plan CMS-U8 - **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications β€” never switch it) ## Workspace State diff --git a/aidlc-docs/features/contact-forms-module/audit.md b/aidlc-docs/features/contact-forms-module/audit.md index dd29407..fa43bb4 100644 --- a/aidlc-docs/features/contact-forms-module/audit.md +++ b/aidlc-docs/features/contact-forms-module/audit.md @@ -143,3 +143,15 @@ **Context**: Phase 2 planning. --- + +## CMS-U5 contact mail built + +**Timestamp**: 2026-11-10 + +**User Input**: Approval of plan CMS-U5 incl. the three additive shared mail changes (via Redesign - SLS). + +**AI Response**: Store + signal + background sender with claim, backoff and maximum; real sender; admin resend and detail; tests (unit and pipeline with a capturing sender); OpenAPI regenerated; all test projects green. + +**Context**: Phase 2, one commit. + +--- diff --git a/aidlc-docs/features/contact-forms-module/construction/cms-u5-contact-mail/code/summary.md b/aidlc-docs/features/contact-forms-module/construction/cms-u5-contact-mail/code/summary.md new file mode 100644 index 0000000..d80dfdc --- /dev/null +++ b/aidlc-docs/features/contact-forms-module/construction/cms-u5-contact-mail/code/summary.md @@ -0,0 +1,23 @@ +# CMS-U5 β€” Contact mail + retry (summary) + +## Behaviour +- A submission only stores the message (status `new`, mail `pending`, `NextMailAttemptAt = now`) and signals the background sender. The visitor never waits for SMTP. +- `ContactMailService` (BackgroundService) wakes on the signal and every `Contact:Mail:SweepSeconds`; it picks unread (`new`) messages with mail `pending`/`failed`, fewer than `MaxAttempts` attempts and a due `NextMailAttemptAt`, oldest first, `BatchSize` at a time. +- Claim: `NextMailAttemptAt` is a concurrency token; the sender first sets it to now + `ClaimMinutes` (whole seconds, the column is `datetime`), a second instance fails to save and skips the message. +- Failure: `failed` + short error code, attempts + 1, next attempt after 5 min / 15 min / 1 h / 6 h / 24 h; after `MaxAttempts` (6) no automatic attempt; an administrator can still resend (ignores backoff and maximum). +- Mail off or no valid recipient: nothing attempted or counted; the reason (`disabled` / `recipient_not_configured`) is shown as `mailError`. +- Spam, read, archived messages are never auto-mailed. Module disabled: the service does nothing and never touches the database. +- Mail: To = `Contact:RecipientEmail`, From = site sender, Reply-To = visitor (address validated, name only if valid), fixed subject "Nieuw bericht via {site}" / "New message via {site}"; details (name, e-mail, subject, message) HTML-encoded, line breaks kept, text part included. Logs: message id and short codes only. + +## Configuration (env-only for the address) +- `Contact__RecipientEmail` (environment variable; no address in repo config). +- `Contact:Mail:SweepSeconds` 120, `MaxAttempts` 6, `BackoffMinutes` [5,15,60,360,1440], `ClaimMinutes` 5, `BatchSize` 20. + +## API +- Detail has `nextMailAttemptAt`; resend result has `mailError`. Migration `ContactMailClaim` (schema unchanged, concurrency token only). OpenAPI regenerated. + +## Shared files changed (additive only) +`Core/Email/MailTypes.cs`, `MailTemplateRenderer.cs`, `SmtpEmailSender.cs` (+66/-5). Existing Core tests untouched: 625 green. + +## Found by the real-database pipeline test +`datetime` drops fractions, which made the claim's concurrency check fail on the outcome save; claim time is now truncated to whole seconds. diff --git a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md index 1cd8103..4921fca 100644 --- a/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md +++ b/aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md @@ -107,3 +107,8 @@ CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings` ## 6. Rebase result (2026-11-10) Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifications + andreaslop-site-hosting). Conflicts: `aidlc-docs/active-features.md` (kept master's table, appended our row), `AvailabilityMiddleware` (kept their `CheckAdmin` / expired-token 401 behaviour, our marker block before it), `AddCmsRateLimiting.OnRejected` (kept their Retry-After logic for sliding windows, added the `60 s` fallback for policies without a wait and the problem+json body), `SlpModularCms.sln` (took master's, re-added the two Contact projects). No EF snapshot conflict (own contexts). Checklist steps 1 and 2 are DONE: `ContactRateLimitPartition.KeyFor` now returns `ClientPartitionKey.For(context)` and its test asserts different buckets per address. Still open: step 3 (`ForwardedHeaders:KnownProxies` per host), step 5 (`Contact:Enabled=true`), step 6 (CMS switch). `GET /System/capabilities` now carries `[PublicSiteEndpoint]` (never 503; separate commit). The pipeline tests for the management routes log in with a real user (the host validates every access token against its user and security stamp). + +## 7. CMS-U5 additions (contact mail) +- Env var `Contact__RecipientEmail` (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`. +- Mail itself needs the host's normal `Email:*` configuration; without it messages stay `pending` with `mailError: "disabled"`. +- Detail: `nextMailAttemptAt`; resend: `mailError`. New migration `ContactMailClaim`. 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 index af1121c..0e89893 100644 --- 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 @@ -18,14 +18,14 @@ Phase 2, on the rebased branch (base `origin/master` `e671078`). Inputs: contrac 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. +- [x] **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. +- [x] **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"). +- [x] **Step 3 β€” Pipeline change**: `ContactSubmissionService` stops sending inline, sets `NextMailAttemptAt`, signals `IContactMailSignal`. +- [x] **Step 4 β€” Retry/background service** `ContactMailService` (claim, backoff, max attempts, signal, disabled handling) and options `Contact:Mail:*` (`SweepSeconds`, `MaxAttempts`, `BackoffMinutes`), `Contact:RecipientEmail`. +- [x] **Step 5 β€” Admin**: detail gets `nextMailAttemptAt`; resend uses the real sender; OpenAPI regenerated. +- [x] **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. +- [x] **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). +- [x] **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. diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index e9ae40b..f4dbeb3 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -138,6 +138,13 @@ "name": { "type": "string" }, + "nextMailAttemptAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, "receivedAt": { "format": "date-time", "type": "string" @@ -306,6 +313,12 @@ "string" ] }, + "mailError": { + "type": [ + "null", + "string" + ] + }, "mailStatus": { "type": "string" }, diff --git a/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs b/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs index cbeab6f..cd602a0 100644 --- a/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs +++ b/src/SlpModularCms.Core/Email/MailTemplateRenderer.cs @@ -101,6 +101,19 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer "An administrator has changed your role at {0} to: {1}.", null, "Think this is a mistake? Please contact the administrator.", "This message was sent automatically by {0}.") + }, + // The details (name, e-mail address, subject, message) come from MailModel.Details; nothing the visitor + // typed is part of the subject, which stays fixed text. + [MailKind.ContactMessage] = new() + { + ["nl"] = new("Nieuw bericht via {0}", "Nieuw bericht via het contactformulier", + "Er is een bericht verstuurd via het contactformulier van {0}.", + null, "Je kunt direct op deze mail antwoorden: het antwoord gaat naar het e-mailadres van de afzender.", + "Deze mail is automatisch verstuurd door {0}."), + ["en"] = new("New message via {0}", "New message from the contact form", + "A message was sent through the contact form of {0}.", + null, "You can reply to this message directly: the reply goes to the sender's e-mail address.", + "This message was sent automatically by {0}.") } }; @@ -135,7 +148,7 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl); return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer), - BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer)); + BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer, model.Details)); } private static string RoleName(string lang, string? key) => @@ -224,6 +237,7 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer sb.Append($"

{E(heading)}

"); if (greeting is not null) sb.Append($"

{E(greeting)}

"); sb.Append($"

{E(intro)}

"); + AppendDetails(sb, model.Details); if (button is not null && !string.IsNullOrEmpty(model.ActionUrl)) { // 'Bulletproof' button: a table cell with bgcolor + style, a visible border, and the link filling the cell. @@ -240,12 +254,43 @@ public sealed class MailTemplateRenderer : IMailTemplateRenderer return sb.ToString(); } - private static string BuildText(string? greeting, string heading, string intro, string? url, string? note, string footer) + /// + /// Labelled values (label on its own line in the muted colour, value below it). Only classes the dark block already + /// overrides carry an inline colour (.mail-muted, .mail-rule); the values inherit the card's text colour, so they + /// read in light and dark. Every value is HTML-encoded; line breaks in a value become <br>. + /// + private static void AppendDetails(StringBuilder sb, IReadOnlyList? details) + { + if (details is null || details.Count == 0) return; + + sb.Append(""); + foreach (var detail in details) + { + var value = E(detail.Value.Replace("\r\n", "\n").Replace('\r', '\n')).Replace("\n", "
"); + sb.Append(""); + } + sb.Append("
"); + sb.Append($"
{E(detail.Label)}
"); + sb.Append($"
{value}
"); + sb.Append("
"); + } + + private static string BuildText( + string? greeting, string heading, string intro, string? url, string? note, string footer, + IReadOnlyList? details = null) { var sb = new StringBuilder(); sb.AppendLine(heading).AppendLine(); if (greeting is not null) sb.AppendLine(greeting).AppendLine(); sb.AppendLine(intro).AppendLine(); + if (details is { Count: > 0 }) + { + foreach (var detail in details) + { + // Plain text: a label line, then the value as written (the message keeps its own line breaks). + sb.Append(detail.Label).AppendLine(":").AppendLine(detail.Value.Replace("\r\n", "\n").Replace('\r', '\n')).AppendLine(); + } + } if (url is not null) sb.AppendLine(url).AppendLine(); if (note is not null) sb.AppendLine(note).AppendLine(); sb.AppendLine("--").AppendLine(footer); diff --git a/src/SlpModularCms.Core/Email/MailTypes.cs b/src/SlpModularCms.Core/Email/MailTypes.cs index 7ad0759..f9a899e 100644 --- a/src/SlpModularCms.Core/Email/MailTypes.cs +++ b/src/SlpModularCms.Core/Email/MailTypes.cs @@ -33,7 +33,9 @@ public sealed record OutgoingMail( string HtmlBody, string? TextBody = null, string? FromAddress = null, - string? FromName = null); + string? FromName = null, + string? ReplyToAddress = null, + string? ReplyToName = null); public enum MailKind { @@ -42,9 +44,14 @@ public enum MailKind PasswordReset, AccountDeactivated, AccountReactivated, - RoleChanged + RoleChanged, + /// A visitor's message from the contact form, mailed to the site owner (details + Reply-To). + ContactMessage } +/// One labelled value in the details block of a mail (for example the visitor's name). Always encoded in HTML. +public sealed record MailDetail(string Label, string Value); + /// Values the template needs. carries the role key for . public sealed record MailModel( string SiteName, @@ -54,7 +61,8 @@ public sealed record MailModel( string? Detail = null, string? LogoUrl = null, string? BrandColor = null, - string? LogoDarkUrl = null); + string? LogoDarkUrl = null, + IReadOnlyList? Details = null); public sealed record RenderedMail(string Subject, string Html, string Text); diff --git a/src/SlpModularCms.Core/Email/SmtpEmailSender.cs b/src/SlpModularCms.Core/Email/SmtpEmailSender.cs index f24012e..56b06b2 100644 --- a/src/SlpModularCms.Core/Email/SmtpEmailSender.cs +++ b/src/SlpModularCms.Core/Email/SmtpEmailSender.cs @@ -40,6 +40,14 @@ public sealed class SmtpEmailSender(IOptions options, ILogger new ContactMailOptions().BackoffAfter(attempts).Should().Be(TimeSpan.FromMinutes(minutes)); + + [Fact] + public void TheDefaults_AreSixAttempts() + => new ContactMailOptions().MaxAttempts.Should().Be(6); +} + +public class ContactMailSenderTests +{ + private const string Visitor = "jan@example.nl"; + + private sealed class Rig + { + public IEmailSender Email { get; } = Substitute.For(); + public IMailAvailability Availability { get; } = Substitute.For(); + public ContactOptions Contact { get; } = new() { Enabled = true, RecipientEmail = "owner@example.org" }; + public CapturingLoggerProvider Logs { get; } = new(); + public OutgoingMail? Sent; + + public Rig() + { + Availability.IsEnabled.Returns(true); + Email.SendAsync(Arg.Any(), Arg.Any()).Returns(call => + { + Sent = call.Arg(); + return MailSendResult.Ok; + }); + } + + public ContactMailSender Build(string language = "nl") + { + var languages = Substitute.For(); + languages.Resolve(Arg.Any()).Returns(language); + var settings = Substitute.For(); + settings.GetEffectiveSenderAsync(Arg.Any()).Returns(("noreply@example.org", "De Site")); + return new ContactMailSender( + Email, new MailTemplateRenderer(), languages, settings, Availability, + Options.Create(new EmailOptions()), Options.Create(new AppMailOptions { PublicBaseUrl = "https://example.org" }), + Options.Create(Contact), LoggerFactory.Create(b => b.AddProvider(Logs)).CreateLogger()); + } + } + + private static ContactMessage Message(string name = "Jan Jansen", string subject = "website", string body = "Hallo\nwereld") + => new() { Id = Guid.NewGuid(), SiteId = "s", Name = name, Email = Visitor, Subject = subject, Message = body }; + + [Fact] + public async Task ASend_GoesToTheRecipient_FromTheSiteSender_WithTheVisitorAsReplyTo() + { + var rig = new Rig(); + + var result = await rig.Build().SendAsync(Message(), CancellationToken.None); + + result.Outcome.Should().Be(ContactMailOutcome.Sent); + rig.Sent!.ToAddress.Should().Be("owner@example.org"); + rig.Sent.FromAddress.Should().Be("noreply@example.org"); + rig.Sent.ReplyToAddress.Should().Be(Visitor); + rig.Sent.ReplyToName.Should().Be("Jan Jansen"); + } + + [Fact] + public async Task TheSubject_NeverContainsAnythingTheVisitorTyped() + { + var rig = new Rig(); + + await rig.Build().SendAsync(Message(name: "ZXQ-Name", subject: "ZXQ-Subject\r\nBcc: x@y.z", body: "ZXQ-Body"), CancellationToken.None); + + rig.Sent!.Subject.Should().NotContain("ZXQ").And.NotContain("\r").And.NotContain("\n"); + rig.Sent.Subject.Should().Be("Nieuw bericht via De Site"); + } + + [Fact] + public async Task TheBody_EncodesHtml_AndKeepsLineBreaks_AndHasATextPart() + { + var rig = new Rig(); + + await rig.Build().SendAsync(Message(body: "\nregel2"), CancellationToken.None); + + rig.Sent!.HtmlBody.Should().NotContain(" & 'q'\r\nregel2\nregel3"))); + + mail.Html.Should().NotContain(""); + var doc = JsonDocument.Parse(json["".Length]).RootElement; + doc.GetProperty("@context").GetString().Should().Be("https://schema.org"); + doc.GetProperty("@type").GetString().Should().Be("ItemList"); + var items = doc.GetProperty("itemListElement").EnumerateArray().ToList(); + items.Should().HaveCount(2); + items[1].GetProperty("position").GetInt32().Should().Be(2); + var offer = items[0].GetProperty("item"); + offer.GetProperty("@type").GetString().Should().Be("Offer"); + offer.GetProperty("name").GetString().Should().Be("Start"); + offer.GetProperty("url").GetString().Should().Be("https://slpsoftware.nl/#pakketten"); + offer.GetProperty("price").GetString().Should().Be("300"); + offer.GetProperty("priceCurrency").GetString().Should().Be("EUR"); + } + + [Fact] + public void JsonLd_OmitsPriceAndCurrency_WhenTheLabelIsNotParseable() + { + var json = OfferingsIndexMarkers.JsonLd([Dto("Maatwerk", price: "Op aanvraag")], "https://x.nl"); + + json.Should().NotContain("\"price\"").And.NotContain("priceCurrency"); + } + + [Fact] + public void JsonLd_CannotCloseTheScriptElement() + { + var json = OfferingsIndexMarkers.JsonLd([Dto("x & y")], "https://x.nl"); + + json.Substring("", string.Empty, StringComparison.Ordinal) + .Should().NotContain("<"); + } + + [Fact] + public void Html_IsASemanticList_WithEverythingEncoded() + { + var html = OfferingsIndexMarkers.Html([Dto("A & B", price: "€ 300", note: "eenmalig")]); + + html.Should().Be( + "
  • A <b>& B</b>

    " + + "

    Beschrijving

    € 300 eenmalig

"); + } + + [Fact] + public async Task WithoutOfferings_BothMarkersAreEmpty() + { + var service = Substitute.For(); + service.GetOfferingsAsync().Returns([]); + + var markers = await new OfferingsIndexMarkers(service).RenderAsync("https://x.nl", CancellationToken.None); + + markers[OfferingsIndexMarkers.JsonLdMarker].Should().BeEmpty(); + markers[OfferingsIndexMarkers.HtmlMarker].Should().BeEmpty(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index c142f5f..53b9101 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -267,6 +267,23 @@ public class OfferingsServiceTests offering.DeletedAt.Should().NotBeNull(); } + [Fact] + public async Task EveryChange_InvalidatesTheWebsitePageCache() + { + var cache = Substitute.For(); + var sut = new OfferingsService(_repo, Substitute.For(), _logger, cache); + var offering = ExistingOffering(); + _repo.GetByIdAsync(offering.Id).Returns(offering); + _repo.GetAllAsync().Returns([offering]); + + await sut.CreateAsync(CreateRequest(), Guid.NewGuid()); + await sut.UpdateAsync(offering.Id, UpdateRequestWithLayout(null), Guid.NewGuid()); + await sut.ReorderAsync([offering.Id], Guid.NewGuid()); + await sut.DeleteAsync(offering.Id, Guid.NewGuid()); + + cache.Received(4).Invalidate(); + } + // --- Layout (card/banner), at most one banner --- private static CreateOfferingRequest CreateRequestWithLayout(string? layout) => new( diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index 649b6db..e5188c6 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Modules; using SlpModularCms.Modules.Offerings.Data; using SlpModularCms.Modules.Offerings.Repositories; @@ -29,6 +30,7 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddHttpContextAccessor(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsIndexMarkers.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsIndexMarkers.cs new file mode 100644 index 0000000..0c60aab --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsIndexMarkers.cs @@ -0,0 +1,114 @@ +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Models; + +namespace SlpModularCms.Modules.Offerings.Services; + +/// +/// Fills the website's <!--SLP:OFFERINGS-JSON-LD--> and <!--SLP:OFFERINGS-HTML--> markers with the +/// current offerings (banner included): a schema.org ItemList of Offers for search engines and a plain, semantic, +/// non-hydrated list that the React app removes at start-up. Both are empty when there are no offerings. +/// The contract (markers + the JSON of GET /api/v1/offerings) is host-independent: a build-time variant fills +/// the same markers from the same JSON. +/// +public sealed partial class OfferingsIndexMarkers(IOfferingsService offerings) : IIndexHtmlMarkerProvider +{ + public const string JsonLdMarker = "SLP:OFFERINGS-JSON-LD"; + public const string HtmlMarker = "SLP:OFFERINGS-HTML"; + + public async Task> RenderAsync(string publicBaseUrl, CancellationToken cancellationToken) + { + var list = await offerings.GetOfferingsAsync(); + return new Dictionary + { + [JsonLdMarker] = JsonLd(list, publicBaseUrl), + [HtmlMarker] = Html(list), + }; + } + + [GeneratedRegex(@"€ ?([0-9.,]+)")] + private static partial Regex EuroPrice(); + + /// + /// The numeric price of a label like "€ 1.500,50" (Dutch notation: dot = thousands, comma = decimals), as + /// "1500.50"; null when the label is not parseable. Never guessed. + /// + internal static string? ParsePrice(string label) + { + var match = EuroPrice().Match(label ?? string.Empty); + if (!match.Success) + { + return null; + } + + var digits = match.Groups[1].Value.Trim('.', ',').Replace(".", string.Empty).Replace(',', '.'); + return decimal.TryParse(digits, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value) + ? value.ToString(CultureInfo.InvariantCulture) + : null; + } + + internal static string JsonLd(IReadOnlyList list, string baseUrl) + { + if (list.Count == 0) + { + return string.Empty; + } + + var items = list.Select((o, index) => + { + var offer = new Dictionary + { + ["@type"] = "Offer", + ["name"] = o.Title, + ["description"] = o.Description, + ["url"] = baseUrl + "/#pakketten", + }; + + if (ParsePrice(o.Price) is { } price) + { + offer["price"] = price; + offer["priceCurrency"] = "EUR"; + } + + return new Dictionary + { + ["@type"] = "ListItem", + ["position"] = index + 1, + ["item"] = offer, + }; + }).ToList(); + + var document = new Dictionary + { + ["@context"] = "https://schema.org", + ["@type"] = "ItemList", + ["itemListElement"] = items, + }; + + // The default encoder escapes <, > and &, so the JSON can never close the script element. + return ""; + } + + internal static string Html(IReadOnlyList list) + { + if (list.Count == 0) + { + return string.Empty; + } + + var html = new StringBuilder("
    "); + foreach (var o in list) + { + var priceLine = string.Join(' ', new[] { o.Price, o.PriceNote }.Where(part => !string.IsNullOrWhiteSpace(part))); + html.Append("
  • ").Append(WebUtility.HtmlEncode(o.Title)).Append("

    ") + .Append(WebUtility.HtmlEncode(o.Description)).Append("

    ") + .Append(WebUtility.HtmlEncode(priceLine)).Append("

  • "); + } + + return html.Append("
").ToString(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index d415f78..426f35b 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Modules.Offerings.Data.Entities; using SlpModularCms.Modules.Offerings.Models; using SlpModularCms.Modules.Offerings.Repositories; @@ -8,7 +9,8 @@ namespace SlpModularCms.Modules.Offerings.Services; public class OfferingsService( IOfferingRepository repository, IOfferingCategoryRepository categories, - ILogger logger) : IOfferingsService + ILogger logger, + IIndexHtmlCache? indexCache = null) : IOfferingsService { public async Task> GetOfferingsAsync() { @@ -59,6 +61,7 @@ public class OfferingsService( await repository.SaveChangesAsync(); } + indexCache?.Invalidate(); logger.LogInformation( "Offering {OfferingId} {Action} by user {LastModifiedByUserId}", offering.Id, "Created", callerId); @@ -112,6 +115,7 @@ public class OfferingsService( await repository.SaveChangesAsync(); } + indexCache?.Invalidate(); logger.LogInformation( "Offering {OfferingId} {Action} by user {LastModifiedByUserId}", offering.Id, "Updated", callerId); @@ -134,6 +138,7 @@ public class OfferingsService( repository.Update(offering); await repository.SaveChangesAsync(); + indexCache?.Invalidate(); logger.LogInformation( "Offering {OfferingId} {Action} by user {LastModifiedByUserId}", offering.Id, "Deleted", callerId); @@ -171,6 +176,7 @@ public class OfferingsService( await repository.SaveChangesAsync(); await transaction.CommitAsync(); + indexCache?.Invalidate(); logger.LogInformation( "Offerings reordered ({Count} items) by user {LastModifiedByUserId}", orderedIds.Count, callerId); -- 2.39.5 From ad71a2cc0d8d9d7bbfa4ed0ec4a31b1d26da0f67 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 08:08:40 +0100 Subject: [PATCH 47/83] ASF-host: Offerings-module aan (pakketten voor de website, build-time fetch) Host verwijst nu naar SlpModularCms.Modules.Offerings; capabilities- en referentietests omgekeerd. De index.html-injectie blijft SpaFallback-only. Co-Authored-By: Claude Sonnet 5.5 --- .../HostConfigurationTests.cs | 4 ++-- .../HostPipelineTests.cs | 6 +++--- .../SlpModularCms.Api.AndreaSlopFotografie.csproj | 13 ++++++++----- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs index 9b91f04..7f33718 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs @@ -80,11 +80,11 @@ public class HostConfigurationTests } [Fact] - public void Host_DoesNotReferenceMasterOrOfferingsModules() + public void Host_ReferencesOfferings_ButNotTheMasterModule() { var referenced = typeof(Program).Assembly.GetReferencedAssemblies().Select(a => a.Name); - referenced.Should().NotContain("SlpModularCms.Modules.Offerings") + referenced.Should().Contain("SlpModularCms.Modules.Offerings") .And.NotContain("SlpModularCms.Modules.Master"); } diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs index fdb2cc2..41b42b3 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs @@ -27,15 +27,15 @@ public class HostPipelineTests : IClassFixture public HostPipelineTests(AsfWebApplicationFactory factory) => _factory = factory; [Fact] - public async Task Capabilities_ListIdentityAndAvailability_ButNotOfferingsOrMaster() + public async Task Capabilities_ListIdentityAvailabilityAndOfferings_ButNotMaster() { var response = await _factory.CreateClient().GetAsync("/api/v1/System/capabilities"); response.StatusCode.Should().Be(HttpStatusCode.OK); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); var modules = doc.RootElement.GetProperty("modules").EnumerateArray().Select(e => e.GetString()).ToList(); - modules.Should().Contain("Identity").And.Contain("Availability"); - modules.Should().NotContain("Offerings").And.NotContain("Master"); + modules.Should().Contain("Identity").And.Contain("Availability").And.Contain("Offerings"); + modules.Should().NotContain("Master"); } [Fact] diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj index 1b978b4..9d89f19 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj +++ b/src/SlpModularCms.Api.AndreaSlopFotografie/SlpModularCms.Api.AndreaSlopFotografie.csproj @@ -18,15 +18,18 @@
+ -- 2.39.5 From f2a32b26c917f9876fe4c08bb88de358bd227d9d Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 09:10:58 +0100 Subject: [PATCH 48/83] Script: Seed-Offerings.ps1 (idempotente pakketten-seed via admin-API, wachtwoord interactief) Co-Authored-By: Claude Sonnet 5.5 --- scripts/Seed-Offerings.ps1 | 97 ++++++++++++++++++++++++++++++++++++++ scripts/offerings-asf.json | 32 +++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 scripts/Seed-Offerings.ps1 create mode 100644 scripts/offerings-asf.json diff --git a/scripts/Seed-Offerings.ps1 b/scripts/Seed-Offerings.ps1 new file mode 100644 index 0000000..db7b607 --- /dev/null +++ b/scripts/Seed-Offerings.ps1 @@ -0,0 +1,97 @@ +<# +.SYNOPSIS + Creates offerings (packages) in a CMS through the admin API. Idempotent: a slug that already exists is skipped. + +.DESCRIPTION + Logs in with an admin account (the password is asked interactively, as a secure string; it is never + written to disk, to the console or to a log), then creates the offerings from -PackagesFile in file + order with an explicit slug. DisplayOrder is assigned by the server in creation order (0, 1, 2, ...). + Test hosts only unless you deliberately point it somewhere else. + +.PARAMETER BaseUrl + Root of the host, e.g. https://test.andreaslop.nl (no trailing /api). + +.PARAMETER Email + Admin e-mail address. Asked when omitted. + +.PARAMETER PackagesFile + JSON array; default: offerings-asf.json next to this script. Each item: slug, title, description, + price, priceNote, features (array), ctaLabel, layout (card|banner, default card), featured (default false). + +.PARAMETER WhatIf + Shows what would be created without logging in or writing anything. + +.EXAMPLE + ./scripts/Seed-Offerings.ps1 -BaseUrl https://test.andreaslop.nl +#> +[CmdletBinding(SupportsShouldProcess)] +param( + [Parameter(Mandatory)] [string] $BaseUrl, + [string] $Email, + [string] $PackagesFile = (Join-Path $PSScriptRoot 'offerings-asf.json') +) + +$ErrorActionPreference = 'Stop' +$BaseUrl = $BaseUrl.TrimEnd('/') +$api = "$BaseUrl/api/v1" + +$packages = Get-Content -LiteralPath $PackagesFile -Raw -Encoding UTF8 | ConvertFrom-Json +if (-not $packages -or $packages.Count -eq 0) { throw "No packages in $PackagesFile." } + +# Refuse unfinished templates: no guessed copy ends up in a CMS. +foreach ($p in $packages) { + foreach ($field in 'slug', 'title', 'description', 'price', 'priceNote', 'ctaLabel') { + $v = $p.$field + if ([string]::IsNullOrWhiteSpace($v) -or $v -like 'TODO*') { throw "Package '$($p.slug)': '$field' is empty or still TODO." } + } + if (-not $p.features -or $p.features.Count -eq 0 -or ($p.features | Where-Object { $_ -like 'TODO*' })) { + throw "Package '$($p.slug)': 'features' is empty or still TODO." + } +} + +if ($WhatIfPreference) { + $packages | ForEach-Object { Write-Host "Would create '$($_.slug)' ($($_.title), $($_.price)) on $BaseUrl" } + return +} + +if (-not $Email) { $Email = Read-Host 'Admin e-mail' } +$secure = Read-Host "Password for $Email" -AsSecureString +$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) +try { + $plain = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) + $body = @{ email = $Email; password = $plain } | ConvertTo-Json -Compress + $login = Invoke-RestMethod -Method Post -Uri "$api/auth/login" -ContentType 'application/json' -Body $body +} +finally { + [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) + $plain = $null; $body = $null +} +$headers = @{ Authorization = "Bearer $($login.accessToken)" } + +# The public list tells which slugs exist already. +$existing = @(Invoke-RestMethod -Method Get -Uri "$api/offerings" -Headers $headers | ForEach-Object { $_.slug }) + +foreach ($p in $packages) { + if ($existing -contains $p.slug) { Write-Host "skip $($p.slug) (exists)"; continue } + $payload = [ordered]@{ + slug = $p.slug + title = $p.title + description = $p.description + price = $p.price + priceNote = $p.priceNote + features = @($p.features) + ctaLabel = $p.ctaLabel + featured = [bool]$p.featured + layout = if ($p.layout) { $p.layout } else { 'card' } + } | ConvertTo-Json -Depth 5 + try { + $created = Invoke-RestMethod -Method Post -Uri "$api/offerings" -Headers $headers -ContentType 'application/json; charset=utf-8' -Body ([Text.Encoding]::UTF8.GetBytes($payload)) + Write-Host "create $($created.slug) (displayOrder $($created.displayOrder))" + } + catch { + Write-Error "Creating '$($p.slug)' failed: $($_.Exception.Message) $($_.ErrorDetails.Message)" + } +} + +Write-Host 'Result:' +Invoke-RestMethod -Method Get -Uri "$api/offerings" | ForEach-Object { Write-Host (" {0,2} {1} {2} [{3}]" -f $_.displayOrder, $_.slug, $_.price, $_.layout) } diff --git a/scripts/offerings-asf.json b/scripts/offerings-asf.json new file mode 100644 index 0000000..1797f2d --- /dev/null +++ b/scripts/offerings-asf.json @@ -0,0 +1,32 @@ +[ + { + "slug": "zwangerschap", + "title": "Zwangerschap", + "description": "TODO (uit web/src/content/packages.ts)", + "price": "€ 175", + "priceNote": "TODO", + "features": ["TODO", "TODO", "TODO"], + "ctaLabel": "TODO", + "layout": "card" + }, + { + "slug": "newborn", + "title": "Newborn", + "description": "TODO (uit web/src/content/packages.ts)", + "price": "€ 185", + "priceNote": "TODO", + "features": ["TODO", "TODO", "TODO"], + "ctaLabel": "TODO", + "layout": "card" + }, + { + "slug": "gezin", + "title": "Gezin", + "description": "TODO (uit web/src/content/packages.ts)", + "price": "€ 175", + "priceNote": "TODO", + "features": ["TODO", "TODO", "TODO"], + "ctaLabel": "TODO", + "layout": "card" + } +] -- 2.39.5 From b94245fc122a9e325e6eb19a52cc84bf0a57c831 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 09:19:23 +0100 Subject: [PATCH 49/83] Offerings: lege description/priceNote/ctaLabel toegestaan; ASF-pakketten-seed gevuld; ASF-referentietest gerepareerd De hosttest op GetReferencedAssemblies faalde in CI (module wordt runtime gevonden, geen compile-referentie); Offerings-aanwezigheid via capabilities. Co-Authored-By: Claude Sonnet 5.5 --- scripts/Seed-Offerings.ps1 | 6 +++- scripts/offerings-asf.json | 36 ++++++++++++------- .../HostConfigurationTests.cs | 7 ++-- .../Services/OfferingsServiceTests.cs | 19 ++++++++++ .../Models/CreateOfferingRequest.cs | 6 ++-- .../Models/UpdateOfferingRequest.cs | 6 ++-- 6 files changed, 58 insertions(+), 22 deletions(-) diff --git a/scripts/Seed-Offerings.ps1 b/scripts/Seed-Offerings.ps1 index db7b607..124855a 100644 --- a/scripts/Seed-Offerings.ps1 +++ b/scripts/Seed-Offerings.ps1 @@ -40,10 +40,14 @@ if (-not $packages -or $packages.Count -eq 0) { throw "No packages in $PackagesF # Refuse unfinished templates: no guessed copy ends up in a CMS. foreach ($p in $packages) { - foreach ($field in 'slug', 'title', 'description', 'price', 'priceNote', 'ctaLabel') { + foreach ($field in 'slug', 'title', 'price') { $v = $p.$field if ([string]::IsNullOrWhiteSpace($v) -or $v -like 'TODO*') { throw "Package '$($p.slug)': '$field' is empty or still TODO." } } + # description, priceNote and ctaLabel may be empty (the API accepts empty strings), but never TODO. + foreach ($field in 'description', 'priceNote', 'ctaLabel') { + if ("$($p.$field)" -like 'TODO*') { throw "Package '$($p.slug)': '$field' is still TODO." } + } if (-not $p.features -or $p.features.Count -eq 0 -or ($p.features | Where-Object { $_ -like 'TODO*' })) { throw "Package '$($p.slug)': 'features' is empty or still TODO." } diff --git a/scripts/offerings-asf.json b/scripts/offerings-asf.json index 1797f2d..2fa2133 100644 --- a/scripts/offerings-asf.json +++ b/scripts/offerings-asf.json @@ -2,31 +2,43 @@ { "slug": "zwangerschap", "title": "Zwangerschap", - "description": "TODO (uit web/src/content/packages.ts)", + "description": "", "price": "€ 175", - "priceNote": "TODO", - "features": ["TODO", "TODO", "TODO"], - "ctaLabel": "TODO", + "priceNote": "", + "features": [ + "1 uur fotografie", + "Minstens 30 zorgvuldig nabewerkte foto's", + "Persoonlijke online fotogalerij" + ], + "ctaLabel": "", "layout": "card" }, { "slug": "newborn", "title": "Newborn", - "description": "TODO (uit web/src/content/packages.ts)", + "description": "", "price": "€ 185", - "priceNote": "TODO", - "features": ["TODO", "TODO", "TODO"], - "ctaLabel": "TODO", + "priceNote": "", + "features": [ + "1-2 uur fotografie", + "Minstens 40 zorgvuldig nabewerkte foto's", + "Persoonlijke online fotogalerij" + ], + "ctaLabel": "", "layout": "card" }, { "slug": "gezin", "title": "Gezin", - "description": "TODO (uit web/src/content/packages.ts)", + "description": "", "price": "€ 175", - "priceNote": "TODO", - "features": ["TODO", "TODO", "TODO"], - "ctaLabel": "TODO", + "priceNote": "", + "features": [ + "1 uur fotografie", + "Minstens 30 zorgvuldig nabewerkte foto's", + "Persoonlijke online fotogalerij" + ], + "ctaLabel": "", "layout": "card" } ] diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs index 7f33718..8c8cee1 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostConfigurationTests.cs @@ -80,12 +80,13 @@ public class HostConfigurationTests } [Fact] - public void Host_ReferencesOfferings_ButNotTheMasterModule() + public void Host_DoesNotReferenceTheMasterModule() { + // Offerings has no compile-time reference from the host (modules are discovered at runtime), so its + // presence is asserted through /System/capabilities in HostPipelineTests instead. var referenced = typeof(Program).Assembly.GetReferencedAssemblies().Select(a => a.Name); - referenced.Should().Contain("SlpModularCms.Modules.Offerings") - .And.NotContain("SlpModularCms.Modules.Master"); + referenced.Should().NotContain("SlpModularCms.Modules.Master"); } [Fact] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index 53b9101..659ca5a 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -375,4 +375,23 @@ public class OfferingsServiceTests ok.Should().Be(valid); } + + [Theory] + [InlineData(typeof(CreateOfferingRequest), "Description", true)] + [InlineData(typeof(CreateOfferingRequest), "PriceNote", true)] + [InlineData(typeof(CreateOfferingRequest), "CtaLabel", true)] + [InlineData(typeof(UpdateOfferingRequest), "Description", true)] + [InlineData(typeof(UpdateOfferingRequest), "PriceNote", true)] + [InlineData(typeof(UpdateOfferingRequest), "CtaLabel", true)] + [InlineData(typeof(CreateOfferingRequest), "Title", false)] + [InlineData(typeof(CreateOfferingRequest), "Price", false)] + public void Request_accepts_empty_text_only_for_description_pricenote_and_cta(Type request, string name, bool emptyAllowed) + { + var parameter = request.GetConstructors()[0].GetParameters().Single(p => p.Name == name); + var required = (System.ComponentModel.DataAnnotations.RequiredAttribute)parameter + .GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.RequiredAttribute), false).Single(); + + required.IsValid(string.Empty).Should().Be(emptyAllowed); + required.IsValid(null).Should().BeFalse(); + } } diff --git a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs index 9ba7a28..556ccee 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs @@ -4,11 +4,11 @@ namespace SlpModularCms.Modules.Offerings.Models; public record CreateOfferingRequest( [Required, MaxLength(100)] string Title, - [Required, MaxLength(500)] string Description, + [Required(AllowEmptyStrings = true), MaxLength(500)] string Description, [Required, MaxLength(50)] string Price, - [Required, MaxLength(100)] string PriceNote, + [Required(AllowEmptyStrings = true), MaxLength(100)] string PriceNote, [Required, FeaturesValidation] List Features, - [Required, MaxLength(50)] string CtaLabel, + [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, bool Featured = false, [MaxLength(130)] string? Slug = null, Guid? CategoryId = null, diff --git a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs index 2feeca7..c359c18 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs @@ -4,11 +4,11 @@ namespace SlpModularCms.Modules.Offerings.Models; public record UpdateOfferingRequest( [Required, MaxLength(100)] string Title, - [Required, MaxLength(500)] string Description, + [Required(AllowEmptyStrings = true), MaxLength(500)] string Description, [Required, MaxLength(50)] string Price, - [Required, MaxLength(100)] string PriceNote, + [Required(AllowEmptyStrings = true), MaxLength(100)] string PriceNote, [Required, FeaturesValidation] List Features, - [Required, MaxLength(50)] string CtaLabel, + [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, bool Featured = false, [MaxLength(130)] string? Slug = null, Guid? CategoryId = null, -- 2.39.5 From 6349d99f16d3b1165292e46e3f28ad59ee5fd145 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 10:09:41 +0100 Subject: [PATCH 50/83] Seed-Offerings.ps1: JSON-array expliciet opsommen (PowerShell 5.1) Co-Authored-By: Claude Sonnet 5.5 --- scripts/Seed-Offerings.ps1 | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/scripts/Seed-Offerings.ps1 b/scripts/Seed-Offerings.ps1 index 124855a..f2131cb 100644 --- a/scripts/Seed-Offerings.ps1 +++ b/scripts/Seed-Offerings.ps1 @@ -73,7 +73,9 @@ finally { $headers = @{ Authorization = "Bearer $($login.accessToken)" } # The public list tells which slugs exist already. -$existing = @(Invoke-RestMethod -Method Get -Uri "$api/offerings" -Headers $headers | ForEach-Object { $_.slug }) +# Windows PowerShell 5.1 hands a JSON array over as ONE object; wrap it so every item is enumerated. +$list = @(Invoke-RestMethod -Method Get -Uri "$api/offerings" -Headers $headers) +$existing = @(foreach ($o in $list) { $o.slug }) foreach ($p in $packages) { if ($existing -contains $p.slug) { Write-Host "skip $($p.slug) (exists)"; continue } @@ -98,4 +100,5 @@ foreach ($p in $packages) { } Write-Host 'Result:' -Invoke-RestMethod -Method Get -Uri "$api/offerings" | ForEach-Object { Write-Host (" {0,2} {1} {2} [{3}]" -f $_.displayOrder, $_.slug, $_.price, $_.layout) } +$final = @(Invoke-RestMethod -Method Get -Uri "$api/offerings") +foreach ($o in $final) { Write-Host (" {0,2} {1} {2} [{3}]" -f $o.displayOrder, $o.slug, $o.price, $o.layout) } -- 2.39.5 From a2f4513205180b53837ab037be56bfd850f083c8 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 10:47:44 +0100 Subject: [PATCH 51/83] Offerings: OfferingBanner (planbare banner, GET /offerings/banner) en layout verwijderd (backend) Co-Authored-By: Claude Sonnet 5.5 --- openapi/slpsoftware.v1.json | 181 +++++++++++++++-- .../HostPipelineTests.cs | 24 +++ .../Controllers/OfferingsPublicMarkerTests.cs | 13 +- .../Services/OfferingBannersServiceTests.cs | 190 ++++++++++++++++++ .../Services/OfferingsIndexMarkersTests.cs | 8 +- .../Services/OfferingsServiceTests.cs | 97 +-------- .../Controllers/OfferingBannersController.cs | 60 ++++++ .../Data/Entities/Offering.cs | 3 - .../Data/Entities/OfferingBanner.cs | 25 +++ .../Data/Entities/OfferingLayouts.cs | 7 - .../Data/OfferingsDbContext.cs | 16 +- ..._AddOfferingBannerRemoveLayout.Designer.cs | 182 +++++++++++++++++ ...112100000_AddOfferingBannerRemoveLayout.cs | 55 +++++ .../OfferingsDbContextModelSnapshot.cs | 54 ++++- .../Models/CreateOfferingRequest.cs | 3 +- .../Models/OfferingBannerModels.cs | 62 ++++++ .../Models/OfferingDto.cs | 3 +- .../Models/UpdateOfferingRequest.cs | 3 +- .../OfferingsModule.cs | 2 + .../Repositories/IOfferingRepository.cs | 1 - .../Repositories/OfferingBannerRepository.cs | 41 ++++ .../Repositories/OfferingRepository.cs | 3 - .../Services/OfferingBannersService.cs | 105 ++++++++++ .../Services/OfferingsService.cs | 28 +-- 24 files changed, 1005 insertions(+), 161 deletions(-) create mode 100644 src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs delete mode 100644 src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index 1427866..83236be 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -437,12 +437,6 @@ }, "type": "array" }, - "layout": { - "type": [ - "null", - "string" - ] - }, "price": { "type": "string" }, @@ -535,6 +529,51 @@ ], "type": "object" }, + "OfferingBannerRequest": { + "properties": { + "endsAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, + "isActive": { + "default": true, + "type": "boolean" + }, + "linkLabel": { + "type": [ + "null", + "string" + ] + }, + "linkUrl": { + "type": [ + "null", + "string" + ] + }, + "startsAt": { + "format": "date-time", + "type": [ + "null", + "string" + ] + }, + "text": { + "type": "string" + }, + "title": { + "type": "string" + } + }, + "required": [ + "title", + "text" + ], + "type": "object" + }, "OfferingCategoryRequest": { "properties": { "name": { @@ -783,12 +822,6 @@ }, "type": "array" }, - "layout": { - "type": [ - "null", - "string" - ] - }, "price": { "type": "string" }, @@ -2223,6 +2256,124 @@ ] } }, + "/api/v1/offerings/banner": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "PublicOfferingBanner" + ] + } + }, + "/api/v1/offerings/banners": { + "get": { + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + }, + "post": { + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + } + }, + "/api/v1/offerings/banners/{id}": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/OfferingBannerRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + }, + "tags": [ + "OfferingBanners" + ] + } + }, "/api/v1/offerings/categories": { "get": { "responses": { @@ -2482,6 +2633,12 @@ { "name": "SlaveStatus" }, + { + "name": "OfferingBanners" + }, + { + "name": "PublicOfferingBanner" + }, { "name": "OfferingCategories" }, diff --git a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs index 41b42b3..a9fcb19 100644 --- a/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs +++ b/src/SlpModularCms.Api.AndreaSlopFotografie.Tests/HostPipelineTests.cs @@ -3,6 +3,8 @@ using System.Text.Json; using FluentAssertions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; namespace SlpModularCms.Api.AndreaSlopFotografie.Tests; @@ -38,6 +40,28 @@ public class HostPipelineTests : IClassFixture modules.Should().NotContain("Master"); } + [Fact] + public async Task OfferingBanner_Is204_WhenNoneIsActive_AndOfferingsAreListed_OnAMigratedDatabase() + { + var client = _factory.CreateClient(); + + var banner = await client.GetAsync("/api/v1/offerings/banner"); + banner.StatusCode.Should().Be(HttpStatusCode.NoContent); + + (await client.GetAsync("/api/v1/offerings")).StatusCode.Should().Be(HttpStatusCode.OK); + (await client.GetAsync("/api/v1/offerings/banners")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + } + + [Fact] + public void OfferingsMigrations_MatchTheModel() + { + _ = _factory.CreateClient(); // starts the host and migrates + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + db.Database.HasPendingModelChanges().Should().BeFalse("every model change needs its migration and snapshot"); + } + [Fact] public async Task Health_IsReachable() { diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs index 78aed46..d26339f 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Controllers/OfferingsPublicMarkerTests.cs @@ -9,7 +9,7 @@ namespace SlpModularCms.Modules.Offerings.Tests.Controllers; public class OfferingsPublicMarkerTests { private static IEnumerable Actions() => - new[] { typeof(OfferingsController), typeof(OfferingCategoriesController) } + new[] { typeof(OfferingsController), typeof(OfferingCategoriesController), typeof(OfferingBannersController), typeof(PublicOfferingBannerController) } .SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)); [Fact] @@ -26,7 +26,18 @@ public class OfferingsPublicMarkerTests { Actions() .Where(m => m.Name != nameof(OfferingsController.GetOfferings)) + .Where(m => !(m.DeclaringType == typeof(PublicOfferingBannerController) && m.Name == nameof(PublicOfferingBannerController.Get))) .Where(m => m.GetCustomAttribute() is not null) .Should().BeEmpty("writes and the category management stay behind the availability gate"); } + + [Fact] + public void TheBannerGet_IsPublicAndMarked_WhileBannerManagementIsNot() + { + var get = typeof(PublicOfferingBannerController).GetMethod(nameof(PublicOfferingBannerController.Get))!; + + get.GetCustomAttribute().Should().NotBeNull(); + get.GetCustomAttribute().Should().NotBeNull(); + typeof(OfferingBannersController).GetCustomAttribute()!.Policy.Should().Be("AdminOnly"); + } } diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs new file mode 100644 index 0000000..423318c --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingBannersServiceTests.cs @@ -0,0 +1,190 @@ +using System.ComponentModel.DataAnnotations; +using FluentAssertions; +using Microsoft.Extensions.Logging; +using NSubstitute; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +public class OfferingBannersServiceTests +{ + private sealed class FakeTimeProvider(DateTimeOffset start) : TimeProvider + { + private DateTimeOffset _now = start; + public override DateTimeOffset GetUtcNow() => _now; + public void Advance(TimeSpan by) => _now += by; + } + + private static readonly DateTimeOffset Now = new(2026, 11, 12, 12, 0, 0, TimeSpan.Zero); + private readonly IOfferingBannerRepository _repo = Substitute.For(); + private readonly FakeTimeProvider _time = new(Now); + private readonly IIndexHtmlCache _cache = Substitute.For(); + + private OfferingBannersService Sut() => + new(_repo, Substitute.For>(), _time, _cache); + + private static OfferingBanner Banner(string title, bool active = true, DateTimeOffset? from = null, DateTimeOffset? to = null, + DateTimeOffset? updated = null) => new() + { + Id = Guid.NewGuid(), Title = title, Text = "Tekst", IsActive = active, StartsAt = from, EndsAt = to, + UpdatedAt = updated ?? Now.AddDays(-1), + }; + + private void Switched(params OfferingBanner[] banners) => _repo.GetSwitchedOnAsync().Returns(banners); + + [Fact] + public async Task GetActive_ReturnsNull_WhenNothingIsSwitchedOn() + { + Switched(); + (await Sut().GetActiveAsync()).Should().BeNull(); + } + + [Fact] + public async Task GetActive_ReturnsOnlyTheContent_ForABannerWithoutSchedule() + { + var banner = Banner("Actie"); + banner.LinkLabel = "Bekijk"; + banner.LinkUrl = "/aanbieding"; + Switched(banner); + + var result = await Sut().GetActiveAsync(); + + result.Should().Be(new PublicOfferingBannerDto("Actie", "Tekst", "Bekijk", "/aanbieding")); + } + + [Fact] + public async Task GetActive_AppliesTheScheduleAtShowTime() + { + Switched( + Banner("future", from: Now.AddHours(1)), + Banner("past", to: Now.AddHours(-1)), + Banner("ended-exactly-now", to: Now)); + + (await Sut().GetActiveAsync()).Should().BeNull(); + + _time.Advance(TimeSpan.FromHours(2)); + (await Sut().GetActiveAsync())!.Title.Should().Be("future"); + } + + [Fact] + public async Task GetActive_StartsInclusive() + { + Switched(Banner("now", from: Now)); + (await Sut().GetActiveAsync())!.Title.Should().Be("now"); + } + + [Fact] + public async Task GetActive_PicksTheMostRecentlyChanged_WhenSeveralQualify() + { + Switched(Banner("old", updated: Now.AddDays(-5)), Banner("new", updated: Now.AddDays(-1))); + (await Sut().GetActiveAsync())!.Title.Should().Be("new"); + } + + [Fact] + public async Task Create_TrimsText_StoresLinkOnlyWhenComplete_AndInvalidatesTheCache() + { + OfferingBanner? saved = null; + await _repo.AddAsync(Arg.Do(b => saved = b)); + + var dto = await Sut().CreateAsync(new OfferingBannerRequest(" Actie ", " Tekst ", " ", null), Guid.NewGuid()); + + saved!.Title.Should().Be("Actie"); + saved.Text.Should().Be("Tekst"); + saved.LinkLabel.Should().BeNull(); + saved.LinkUrl.Should().BeNull(); + dto.IsActive.Should().BeTrue(); + await _repo.Received(1).SaveChangesAsync(); + _cache.Received(1).Invalidate(); + } + + [Fact] + public async Task Update_ReplacesEverything_ReturnsNullForUnknown_AndDeleteRemoves() + { + var banner = Banner("Oud"); + _repo.GetByIdAsync(banner.Id).Returns(banner); + _repo.GetByIdAsync(Arg.Is(g => g != banner.Id)).Returns((OfferingBanner?)null); + + var updated = await Sut().UpdateAsync(banner.Id, new OfferingBannerRequest("Nieuw", "T2", "Ga", "https://x.nl/a", false, Now, Now.AddDays(1)), Guid.NewGuid()); + updated!.Title.Should().Be("Nieuw"); + updated.LinkUrl.Should().Be("https://x.nl/a"); + updated.IsActive.Should().BeFalse(); + banner.UpdatedAt.Should().Be(Now); + + (await Sut().UpdateAsync(Guid.NewGuid(), new OfferingBannerRequest("a", "b"), Guid.NewGuid())).Should().BeNull(); + + (await Sut().DeleteAsync(banner.Id)).Should().BeTrue(); + _repo.Received(1).Remove(banner); + (await Sut().DeleteAsync(Guid.NewGuid())).Should().BeFalse(); + } + + private static List Validate(OfferingBannerRequest r) + { + var results = new List(); + Validator.TryValidateObject(r, new ValidationContext(r), results, validateAllProperties: true); + return results; + } + + [Theory] + [InlineData("https://slpsoftware.nl/actie", true)] + [InlineData("/aanbieding", true)] + [InlineData("/", true)] + [InlineData("http://slpsoftware.nl", false)] + [InlineData("//evil.example", false)] + [InlineData("/\evil", false)] + [InlineData("javascript:alert(1)", false)] + [InlineData("mailto:a@b.nl", false)] + [InlineData("actie", false)] + [InlineData("https://", false)] + [InlineData("/with space", false)] + public void Link_AllowsOnlyHttpsOrSiteRelativePaths(string url, bool valid) + { + var errors = Validate(new OfferingBannerRequest("T", "X", "Ga", url)); + errors.Count.Should().Be(valid ? 0 : 1); + } + + [Fact] + public void Link_LabelAndUrlComeTogether() + { + Validate(new OfferingBannerRequest("T", "X", "Ga", null)).Should().HaveCount(1); + Validate(new OfferingBannerRequest("T", "X", null, "/x")).Should().HaveCount(1); + Validate(new OfferingBannerRequest("T", "X")).Should().BeEmpty(); + } + + [Fact] + public void Schedule_EndMustBeAfterStart() + { + Validate(new OfferingBannerRequest("T", "X", StartsAt: Now, EndsAt: Now)).Should().HaveCount(1); + Validate(new OfferingBannerRequest("T", "X", StartsAt: Now, EndsAt: Now.AddMinutes(1))).Should().BeEmpty(); + Validate(new OfferingBannerRequest("T", "X", EndsAt: Now)).Should().BeEmpty(); + } + + [Theory] + [InlineData("Title", 100)] + [InlineData("Text", 300)] + [InlineData("LinkLabel", 50)] + [InlineData("LinkUrl", 500)] + public void Fields_AreLimited(string name, int max) + { + // MVC validates record constructor parameters; the attributes sit on the parameter itself. + var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == name); + var maxLength = (MaxLengthAttribute)parameter.GetCustomAttributes(typeof(MaxLengthAttribute), false).Single(); + + maxLength.Length.Should().Be(max); + } + + [Theory] + [InlineData("Title")] + [InlineData("Text")] + public void TitleAndText_AreRequired(string name) + { + var parameter = typeof(OfferingBannerRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == name); + var required = (RequiredAttribute)parameter.GetCustomAttributes(typeof(RequiredAttribute), false).Single(); + + required.IsValid("").Should().BeFalse(); + required.IsValid("x").Should().BeTrue(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs index 49595b3..9bfa942 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsIndexMarkersTests.cs @@ -8,8 +8,8 @@ namespace SlpModularCms.Modules.Offerings.Tests.Services; public class OfferingsIndexMarkersTests { - private static OfferingDto Dto(string title, string price = "€ 300", string note = "eenmalig", string layout = "card") => new( - Guid.NewGuid().ToString(), "slug", title, "Beschrijving", price, note, ["a"], "Start", false, 0, null, null, layout); + private static OfferingDto Dto(string title, string price = "€ 300", string note = "eenmalig") => new( + Guid.NewGuid().ToString(), "slug", title, "Beschrijving", price, note, ["a"], "Start", false, 0, null, null); [Theory] [InlineData("€ 300", "300")] @@ -25,9 +25,9 @@ public class OfferingsIndexMarkersTests => OfferingsIndexMarkers.ParsePrice(label).Should().Be(expected); [Fact] - public void JsonLd_IsAnItemListOfOffers_WithPositions_AndTheBannerIncluded() + public void JsonLd_IsAnItemListOfOffers_WithPositions() { - var json = OfferingsIndexMarkers.JsonLd([Dto("Start"), Dto("Banner", layout: "banner")], "https://slpsoftware.nl"); + var json = OfferingsIndexMarkers.JsonLd([Dto("Start"), Dto("Pro")], "https://slpsoftware.nl"); json.Should().StartWith(""); var doc = JsonDocument.Parse(json["".Length]).RootElement; diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs index 659ca5a..9f968c2 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsServiceTests.cs @@ -267,6 +267,9 @@ public class OfferingsServiceTests offering.DeletedAt.Should().NotBeNull(); } + private static UpdateOfferingRequest UpdateRequest() => new( + "Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact"); + [Fact] public async Task EveryChange_InvalidatesTheWebsitePageCache() { @@ -277,105 +280,13 @@ public class OfferingsServiceTests _repo.GetAllAsync().Returns([offering]); await sut.CreateAsync(CreateRequest(), Guid.NewGuid()); - await sut.UpdateAsync(offering.Id, UpdateRequestWithLayout(null), Guid.NewGuid()); + await sut.UpdateAsync(offering.Id, UpdateRequest(), Guid.NewGuid()); await sut.ReorderAsync([offering.Id], Guid.NewGuid()); await sut.DeleteAsync(offering.Id, Guid.NewGuid()); cache.Received(4).Invalidate(); } - // --- Layout (card/banner), at most one banner --- - - private static CreateOfferingRequest CreateRequestWithLayout(string? layout) => new( - "Title", "Description", "€ 100", "per month", ["Feature 1"], "Contact", Layout: layout); - - private static UpdateOfferingRequest UpdateRequestWithLayout(string? layout) => new( - "Existing", "Description", "€ 100", "per month", ["Feature 1"], "Contact", Layout: layout); - - [Fact] - public async Task CreateAsync_DefaultsLayoutToCard_WhenOmitted() - { - var result = await CreateSut().CreateAsync(CreateRequestWithLayout(null), Guid.NewGuid()); - - result.Layout.Should().Be("card"); - await _repo.DidNotReceive().GetBannerAsync(); - } - - [Fact] - public async Task CreateAsync_DemotesCurrentBanner_WhenNewOneIsBanner() - { - var current = ExistingOffering(); - current.Layout = "banner"; - _repo.GetBannerAsync().Returns(current); - - var result = await CreateSut().CreateAsync(CreateRequestWithLayout("banner"), Guid.NewGuid()); - - result.Layout.Should().Be("banner"); - current.Layout.Should().Be("card"); - } - - [Fact] - public async Task UpdateAsync_KeepsLayout_WhenOmitted() - { - var target = ExistingOffering(); - target.Layout = "banner"; - _repo.GetByIdAsync(target.Id).Returns(target); - _repo.GetBannerAsync().Returns(target); - - var result = await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout(null), Guid.NewGuid()); - - result!.Layout.Should().Be("banner"); - } - - [Fact] - public async Task UpdateAsync_DemotesOtherBanner_ButNotItself() - { - var target = ExistingOffering(); - var other = ExistingOffering(); - other.Layout = "banner"; - _repo.GetByIdAsync(target.Id).Returns(target); - _repo.GetBannerAsync().Returns(other); - - await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("banner"), Guid.NewGuid()); - - target.Layout.Should().Be("banner"); - other.Layout.Should().Be("card"); - - // already the banner: stays one - _repo.GetBannerAsync().Returns(target); - await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("banner"), Guid.NewGuid()); - target.Layout.Should().Be("banner"); - } - - [Fact] - public async Task UpdateAsync_CanReturnBannerToCard() - { - var target = ExistingOffering(); - target.Layout = "banner"; - _repo.GetByIdAsync(target.Id).Returns(target); - - var result = await CreateSut().UpdateAsync(target.Id, UpdateRequestWithLayout("card"), Guid.NewGuid()); - - result!.Layout.Should().Be("card"); - } - - [Theory] - [InlineData("card", true)] - [InlineData("banner", true)] - [InlineData(null, true)] - [InlineData("hero", false)] - [InlineData("Card", false)] - public void Request_validates_layout_values(string? layout, bool valid) - { - // MVC validates record constructor parameters; check the attribute declared on the parameter itself. - var parameter = typeof(CreateOfferingRequest).GetConstructors()[0].GetParameters().Single(p => p.Name == "Layout"); - var attribute = (System.ComponentModel.DataAnnotations.ValidationAttribute)parameter - .GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.RegularExpressionAttribute), false).Single(); - var ok = attribute.IsValid(layout); - - ok.Should().Be(valid); - } - [Theory] [InlineData(typeof(CreateOfferingRequest), "Description", true)] [InlineData(typeof(CreateOfferingRequest), "PriceNote", true)] diff --git a/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs new file mode 100644 index 0000000..767804e --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Controllers/OfferingBannersController.cs @@ -0,0 +1,60 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.RateLimiting; +using SlpModularCms.Core.Availability; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Controllers; + +/// Management of offering banners. Administrators only; visitors use GET /offerings/banner. +[ApiController] +[Route("offerings/banners")] +[Authorize(Policy = "AdminOnly")] +public class OfferingBannersController(IOfferingBannersService service) : ControllerBase +{ + [HttpGet] + public async Task List() => Ok(await service.ListAsync()); + + [HttpPost] + public async Task Create([FromBody] OfferingBannerRequest request) + { + var dto = await service.CreateAsync(request, GetCallerId()); + return Created($"/api/v1/offerings/banners/{dto.Id}", dto); + } + + [HttpPut("{id:guid}")] + public async Task Update(Guid id, [FromBody] OfferingBannerRequest request) + { + var dto = await service.UpdateAsync(id, request, GetCallerId()); + return dto is null ? NotFound() : Ok(dto); + } + + [HttpDelete("{id:guid}")] + public async Task Delete(Guid id) + => await service.DeleteAsync(id) ? NoContent() : NotFound(); + + private Guid GetCallerId() + { + var claim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"); + return Guid.TryParse(claim, out var id) ? id : Guid.Empty; + } +} + +/// The banner visitors see: 200 with the one active banner, otherwise 204. +[ApiController] +[Route("offerings/banner")] +public class PublicOfferingBannerController(IOfferingBannersService service) : ControllerBase +{ + [HttpGet] + [AllowAnonymous] + [PublicSiteEndpoint] + [EnableRateLimiting("offerings-public")] + public async Task Get() + { + Response.Headers.CacheControl = "public, max-age=60"; + var current = await service.GetActiveAsync(); + return current is null ? NoContent() : Ok(current); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs index 1bc0383..12f87eb 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/Offering.cs @@ -11,9 +11,6 @@ public class Offering public List Features { get; set; } = []; public string CtaLabel { get; set; } = string.Empty; public bool Featured { get; set; } - - /// Presentation on the website: "card" (default) or "banner" (at most one per site). - public string Layout { get; set; } = OfferingLayouts.Card; public Guid? CategoryId { get; set; } public OfferingCategory? Category { get; set; } public int DisplayOrder { get; set; } diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs new file mode 100644 index 0000000..11d6544 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingBanner.cs @@ -0,0 +1,25 @@ +namespace SlpModularCms.Modules.Offerings.Data.Entities; + +/// +/// A site-wide banner for offers and campaigns. Several can be stored (for example +/// planned ones with a start and end); the public API shows the one that is active right now. +/// +public class OfferingBanner +{ + public Guid Id { get; set; } + public string Title { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; + + /// Optional button; and are both set or both null. + public string? LinkLabel { get; set; } + + /// An absolute https:// URL or a site-relative path starting with a single "/". + public string? LinkUrl { get; set; } + + public bool IsActive { get; set; } + public DateTimeOffset? StartsAt { get; set; } + public DateTimeOffset? EndsAt { get; set; } + public DateTimeOffset CreatedAt { get; set; } + public DateTimeOffset UpdatedAt { get; set; } + public Guid LastModifiedByUserId { get; set; } +} diff --git a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs b/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs deleted file mode 100644 index 75fc3eb..0000000 --- a/src/SlpModularCms.Modules.Offerings/Data/Entities/OfferingLayouts.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace SlpModularCms.Modules.Offerings.Data.Entities; - -public static class OfferingLayouts -{ - public const string Card = "card"; - public const string Banner = "banner"; -} diff --git a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs index 5cab2c0..61ce8d3 100644 --- a/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs +++ b/src/SlpModularCms.Modules.Offerings/Data/OfferingsDbContext.cs @@ -9,6 +9,7 @@ public class OfferingsDbContext(DbContextOptions options) : { public DbSet Offerings => Set(); public DbSet OfferingCategories => Set(); + public DbSet OfferingBanners => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -24,7 +25,6 @@ public class OfferingsDbContext(DbContextOptions options) : entity.Property(e => e.Price).IsRequired().HasMaxLength(50); entity.Property(e => e.PriceNote).IsRequired().HasMaxLength(100); entity.Property(e => e.CtaLabel).IsRequired().HasMaxLength(50); - entity.Property(e => e.Layout).IsRequired().HasMaxLength(10).HasDefaultValue(OfferingLayouts.Card); entity.Property(e => e.DisplayOrder).IsRequired(); entity.Property(e => e.IsDeleted).IsRequired(); entity.Property(e => e.CreatedAt).IsRequired(); @@ -54,6 +54,20 @@ public class OfferingsDbContext(DbContextOptions options) : entity.HasQueryFilter(e => !e.IsDeleted); }); + modelBuilder.Entity(entity => + { + entity.ToTable("OfferingsBanners"); + entity.HasKey(e => e.Id); + entity.Property(e => e.Title).IsRequired().HasMaxLength(100); + entity.Property(e => e.Text).IsRequired().HasMaxLength(300); + entity.Property(e => e.LinkLabel).HasMaxLength(50); + entity.Property(e => e.LinkUrl).HasMaxLength(500); + entity.Property(e => e.IsActive).IsRequired(); + entity.Property(e => e.CreatedAt).IsRequired(); + entity.Property(e => e.UpdatedAt).IsRequired(); + entity.Property(e => e.LastModifiedByUserId).IsRequired(); + }); + modelBuilder.Entity(entity => { entity.ToTable("OfferingsCategories"); diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs new file mode 100644 index 0000000..d20ab2b --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.Designer.cs @@ -0,0 +1,182 @@ +ο»Ώ// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Offerings.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + [DbContext(typeof(OfferingsDbContext))] + [Migration("20261112100000_AddOfferingBannerRemoveLayout")] + partial class AddOfferingBannerRemoveLayout + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingBanner", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("LinkLabel") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("LinkUrl") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("varchar(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("OfferingsBanners", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CategoryId") + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CtaLabel") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("DisplayOrder") + .HasColumnType("int"); + + b.Property("Featured") + .HasColumnType("tinyint(1)"); + + b.Property("Features") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("IsDeleted") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Price") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("PriceNote") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Slug") + .IsRequired() + .HasMaxLength(130) + .HasColumnType("varchar(130)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.ToTable("OfferingsOfferings", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("OfferingsCategories", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => + { + b.HasOne("SlpModularCms.Modules.Offerings.Data.Entities.OfferingCategory", "Category") + .WithMany() + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Category"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs new file mode 100644 index 0000000..dfc9823 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Migrations/20261112100000_AddOfferingBannerRemoveLayout.cs @@ -0,0 +1,55 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Offerings.Migrations +{ + /// + public partial class AddOfferingBannerRemoveLayout : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "Layout", + table: "OfferingsOfferings"); + + migrationBuilder.CreateTable( + name: "OfferingsBanners", + columns: table => new + { + Id = table.Column(type: "char(36)", nullable: false), + Title = table.Column(type: "varchar(100)", maxLength: 100, nullable: false), + Text = table.Column(type: "varchar(300)", maxLength: 300, nullable: false), + LinkLabel = table.Column(type: "varchar(50)", maxLength: 50, nullable: true), + LinkUrl = table.Column(type: "varchar(500)", maxLength: 500, nullable: true), + IsActive = table.Column(type: "tinyint(1)", nullable: false), + StartsAt = table.Column(type: "datetime", nullable: true), + EndsAt = table.Column(type: "datetime", nullable: true), + CreatedAt = table.Column(type: "datetime", nullable: false), + UpdatedAt = table.Column(type: "datetime", nullable: false), + LastModifiedByUserId = table.Column(type: "char(36)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_OfferingsBanners", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "OfferingsBanners"); + + migrationBuilder.AddColumn( + name: "Layout", + table: "OfferingsOfferings", + type: "varchar(10)", + maxLength: 10, + nullable: false, + defaultValue: "card"); + } + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs index e5043b0..6fdf5a2 100644 --- a/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Offerings/Migrations/OfferingsDbContextModelSnapshot.cs @@ -19,6 +19,53 @@ namespace SlpModularCms.Modules.Offerings.Migrations .HasAnnotation("ProductVersion", "10.0.9") .HasAnnotation("Relational:MaxIdentifierLength", 64); + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.OfferingBanner", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("EndsAt") + .HasColumnType("datetime"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("LinkLabel") + .HasMaxLength(50) + .HasColumnType("varchar(50)"); + + b.Property("LinkUrl") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("StartsAt") + .HasColumnType("datetime"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(300) + .HasColumnType("varchar(300)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("OfferingsBanners", (string)null); + }); + modelBuilder.Entity("SlpModularCms.Modules.Offerings.Data.Entities.Offering", b => { b.Property("Id") @@ -57,13 +104,6 @@ namespace SlpModularCms.Modules.Offerings.Migrations b.Property("IsDeleted") .HasColumnType("tinyint(1)"); - b.Property("Layout") - .IsRequired() - .ValueGeneratedOnAdd() - .HasMaxLength(10) - .HasColumnType("varchar(10)") - .HasDefaultValue("card"); - b.Property("LastModifiedByUserId") .HasColumnType("char(36)"); diff --git a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs index 556ccee..c1a6805 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/CreateOfferingRequest.cs @@ -11,6 +11,5 @@ public record CreateOfferingRequest( [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, bool Featured = false, [MaxLength(130)] string? Slug = null, - Guid? CategoryId = null, - [RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs new file mode 100644 index 0000000..facb64f --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingBannerModels.cs @@ -0,0 +1,62 @@ +using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; + +namespace SlpModularCms.Modules.Offerings.Models; + +/// Administrator view of a banner. +[ExcludeFromCodeCoverage] +public record OfferingBannerDto( + string Id, + string Title, + string Text, + string? LinkLabel, + string? LinkUrl, + bool IsActive, + DateTimeOffset? StartsAt, + DateTimeOffset? EndsAt, + DateTimeOffset UpdatedAt); + +/// What visitors get: only the content to show, never the scheduling. +[ExcludeFromCodeCoverage] +public record PublicOfferingBannerDto(string Title, string Text, string? LinkLabel, string? LinkUrl); + +/// Create and full-replace (PUT) body. Empty link fields are stored as null. +public record OfferingBannerRequest( + [Required, MaxLength(100)] string Title, + [Required, MaxLength(300)] string Text, + [MaxLength(50)] string? LinkLabel = null, + [MaxLength(500)] string? LinkUrl = null, + bool IsActive = true, + DateTimeOffset? StartsAt = null, + DateTimeOffset? EndsAt = null) : IValidatableObject +{ + public IEnumerable Validate(ValidationContext validationContext) + { + var hasLabel = !string.IsNullOrWhiteSpace(LinkLabel); + var hasUrl = !string.IsNullOrWhiteSpace(LinkUrl); + + if (hasLabel != hasUrl) + yield return new ValidationResult("Link label and link URL must be given together.", [nameof(LinkLabel), nameof(LinkUrl)]); + else if (hasUrl && !OfferingBannerLinks.IsAllowed(LinkUrl!.Trim())) + yield return new ValidationResult("Link URL must be an https:// address or a site path starting with '/'.", [nameof(LinkUrl)]); + + if (StartsAt is not null && EndsAt is not null && EndsAt <= StartsAt) + yield return new ValidationResult("EndsAt must be after StartsAt.", [nameof(EndsAt)]); + } +} + +public static class OfferingBannerLinks +{ + /// https:// with a host, or a site-relative path with a single leading "/" (never "//host" or "/\"). + public static bool IsAllowed(string url) + { + if (url.Any(c => char.IsWhiteSpace(c) || char.IsControl(c) || c == '\\')) return false; + + if (url.StartsWith('/')) + return !url.StartsWith("//", StringComparison.Ordinal); + + return Uri.TryCreate(url, UriKind.Absolute, out var uri) + && uri.Scheme == Uri.UriSchemeHttps + && !string.IsNullOrEmpty(uri.Host); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs index 7676147..ecabd11 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/OfferingDto.cs @@ -19,6 +19,5 @@ public record OfferingDto( bool Featured, int DisplayOrder, string? CategoryId = null, - string? Category = null, - string Layout = "card" + string? Category = null ); diff --git a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs index c359c18..846ed1f 100644 --- a/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs +++ b/src/SlpModularCms.Modules.Offerings/Models/UpdateOfferingRequest.cs @@ -11,6 +11,5 @@ public record UpdateOfferingRequest( [Required(AllowEmptyStrings = true), MaxLength(50)] string CtaLabel, bool Featured = false, [MaxLength(130)] string? Slug = null, - Guid? CategoryId = null, - [RegularExpression("^(card|banner)$", ErrorMessage = "Layout must be 'card' or 'banner'.")] string? Layout = null + Guid? CategoryId = null ); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index e5188c6..8396372 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -31,6 +31,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddHttpContextAccessor(); diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs index 49c190e..28cc5a3 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/IOfferingRepository.cs @@ -12,7 +12,6 @@ public interface IOfferingRepository void Update(Offering offering); Task GetMaxDisplayOrderAsync(); Task GetFeaturedAsync(); - Task GetBannerAsync(); Task SaveChangesAsync(); Task BeginTransactionAsync(); } diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs new file mode 100644 index 0000000..f39183d --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingBannerRepository.cs @@ -0,0 +1,41 @@ +using Microsoft.EntityFrameworkCore; +using SlpModularCms.Modules.Offerings.Data; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Repositories; + +public interface IOfferingBannerRepository +{ + /// All banners, most recently changed first. + Task> GetAllAsync(); + + Task GetByIdAsync(Guid id); + + /// Banners switched on (IsActive); the schedule is applied by the caller. + Task> GetSwitchedOnAsync(); + + Task AddAsync(OfferingBanner banner); + void Update(OfferingBanner banner); + void Remove(OfferingBanner banner); + Task SaveChangesAsync(); +} + +public class OfferingBannerRepository(OfferingsDbContext context) : IOfferingBannerRepository +{ + public async Task> GetAllAsync() + => (await context.OfferingBanners.ToListAsync()).OrderByDescending(b => b.UpdatedAt).ToList(); + + public async Task GetByIdAsync(Guid id) + => await context.OfferingBanners.FirstOrDefaultAsync(b => b.Id == id); + + public async Task> GetSwitchedOnAsync() + => await context.OfferingBanners.Where(b => b.IsActive).ToListAsync(); + + public async Task AddAsync(OfferingBanner banner) => await context.OfferingBanners.AddAsync(banner); + + public void Update(OfferingBanner banner) => context.OfferingBanners.Update(banner); + + public void Remove(OfferingBanner banner) => context.OfferingBanners.Remove(banner); + + public async Task SaveChangesAsync() => await context.SaveChangesAsync(); +} diff --git a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs index 16aeb92..7a18382 100644 --- a/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs +++ b/src/SlpModularCms.Modules.Offerings/Repositories/OfferingRepository.cs @@ -28,9 +28,6 @@ public class OfferingRepository(OfferingsDbContext context) : IOfferingRepositor public async Task GetFeaturedAsync() => await context.Offerings.FirstOrDefaultAsync(o => o.Featured); - public async Task GetBannerAsync() - => await context.Offerings.FirstOrDefaultAsync(o => o.Layout == OfferingLayouts.Banner); - public async Task SaveChangesAsync() => await context.SaveChangesAsync(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs new file mode 100644 index 0000000..74f7685 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingBannersService.cs @@ -0,0 +1,105 @@ +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Repositories; + +namespace SlpModularCms.Modules.Offerings.Services; + +public interface IOfferingBannersService +{ + Task> ListAsync(); + + /// The one banner that is switched on and inside its schedule right now, or null. + Task GetActiveAsync(); + + Task CreateAsync(OfferingBannerRequest request, Guid callerId); + Task UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId); + Task DeleteAsync(Guid id); +} + +public class OfferingBannersService( + IOfferingBannerRepository repository, + ILogger logger, + TimeProvider? time = null, + IIndexHtmlCache? indexCache = null) : IOfferingBannersService +{ + private readonly TimeProvider _time = time ?? TimeProvider.System; + + public async Task> ListAsync() + => (await repository.GetAllAsync()).Select(ToDto).ToList(); + + public async Task GetActiveAsync() + { + var now = _time.GetUtcNow(); + + // Several can be switched on (planned ones, overlaps); the most recently changed wins. + var current = (await repository.GetSwitchedOnAsync()) + .Where(b => (b.StartsAt is null || b.StartsAt <= now) && (b.EndsAt is null || now < b.EndsAt)) + .OrderByDescending(b => b.UpdatedAt) + .FirstOrDefault(); + + return current is null ? null : new PublicOfferingBannerDto(current.Title, current.Text, current.LinkLabel, current.LinkUrl); + } + + public async Task CreateAsync(OfferingBannerRequest request, Guid callerId) + { + var now = _time.GetUtcNow(); + var banner = new OfferingBanner { Id = Guid.NewGuid(), CreatedAt = now }; + Apply(banner, request, now, callerId); + + await repository.AddAsync(banner); + await repository.SaveChangesAsync(); + + Changed(banner.Id, "Created", callerId); + return ToDto(banner); + } + + public async Task UpdateAsync(Guid id, OfferingBannerRequest request, Guid callerId) + { + var banner = await repository.GetByIdAsync(id); + if (banner is null) return null; + + Apply(banner, request, _time.GetUtcNow(), callerId); + repository.Update(banner); + await repository.SaveChangesAsync(); + + Changed(id, "Updated", callerId); + return ToDto(banner); + } + + public async Task DeleteAsync(Guid id) + { + var banner = await repository.GetByIdAsync(id); + if (banner is null) return false; + + repository.Remove(banner); + await repository.SaveChangesAsync(); + + Changed(id, "Deleted", null); + return true; + } + + private static void Apply(OfferingBanner b, OfferingBannerRequest r, DateTimeOffset now, Guid callerId) + { + var hasLink = !string.IsNullOrWhiteSpace(r.LinkUrl) && !string.IsNullOrWhiteSpace(r.LinkLabel); + b.Title = r.Title.Trim(); + b.Text = r.Text.Trim(); + b.LinkLabel = hasLink ? r.LinkLabel!.Trim() : null; + b.LinkUrl = hasLink ? r.LinkUrl!.Trim() : null; + b.IsActive = r.IsActive; + b.StartsAt = r.StartsAt; + b.EndsAt = r.EndsAt; + b.UpdatedAt = now; + b.LastModifiedByUserId = callerId; + } + + private void Changed(Guid id, string action, Guid? callerId) + { + indexCache?.Invalidate(); + logger.LogInformation("Offering banner {BannerId} {Action} by user {LastModifiedByUserId}", id, action, callerId); + } + + private static OfferingBannerDto ToDto(OfferingBanner b) => new( + b.Id.ToString(), b.Title, b.Text, b.LinkLabel, b.LinkUrl, b.IsActive, b.StartsAt, b.EndsAt, b.UpdatedAt); +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs index 426f35b..166a0e2 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsService.cs @@ -35,7 +35,6 @@ public class OfferingsService( CategoryId = category?.Id, Category = category, Featured = request.Featured, - Layout = request.Layout ?? OfferingLayouts.Card, DisplayOrder = await repository.GetMaxDisplayOrderAsync() + 1, CreatedAt = now, UpdatedAt = now, @@ -46,11 +45,10 @@ public class OfferingsService( // transactional per NFR Design Pattern 1 so a mid-operation failure can never // leave two offerings both featured or the new one unsaved after the old one // was already un-featured. - if (request.Featured || offering.Layout == OfferingLayouts.Banner) + if (request.Featured) { await using var transaction = await repository.BeginTransactionAsync(); - if (request.Featured) await UnfeatureCurrentAsync(); - if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync(); + await UnfeatureCurrentAsync(); await repository.AddAsync(offering); await repository.SaveChangesAsync(); await transaction.CommitAsync(); @@ -95,16 +93,13 @@ public class OfferingsService( offering.CategoryId = category?.Id; offering.Category = category; offering.Featured = request.Featured; - // Layout is additive: older clients omit it, which keeps the stored value. - if (request.Layout is not null) offering.Layout = request.Layout; offering.UpdatedAt = DateTimeOffset.UtcNow; offering.LastModifiedByUserId = callerId; - if (request.Featured || offering.Layout == OfferingLayouts.Banner) + if (request.Featured) { await using var transaction = await repository.BeginTransactionAsync(); - if (request.Featured) await UnfeatureCurrentAsync(exceptId: offering.Id); - if (offering.Layout == OfferingLayouts.Banner) await DemoteCurrentBannerAsync(exceptId: offering.Id); + await UnfeatureCurrentAsync(exceptId: offering.Id); repository.Update(offering); await repository.SaveChangesAsync(); await transaction.CommitAsync(); @@ -193,18 +188,6 @@ public class OfferingsService( repository.Update(current); } - // At most one banner per site: promoting another offering demotes the current one to a card. - private async Task DemoteCurrentBannerAsync(Guid? exceptId = null) - { - var current = await repository.GetBannerAsync(); - if (current is null || current.Id == exceptId) - return; - - current.Layout = OfferingLayouts.Card; - current.UpdatedAt = DateTimeOffset.UtcNow; - repository.Update(current); - } - private async Task ResolveCategoryAsync(Guid? categoryId) { if (categoryId is null) @@ -260,7 +243,6 @@ public class OfferingsService( o.Featured, o.DisplayOrder, o.CategoryId?.ToString(), - o.Category?.Name, - o.Layout + o.Category?.Name ); } -- 2.39.5 From 5386abb9efaa2aaa84ad1e946f5cd3271a6c2cc8 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Thu, 12 Nov 2026 11:04:50 +0100 Subject: [PATCH 52/83] Offerings: banner-tabblad in de admin (lijst, formulier, planning), layout uit de frontend; gate-test bijgewerkt Co-Authored-By: Claude Sonnet 5.5 --- .../components/OfferingBannerDialog.tsx | 190 +++ .../components/OfferingBannersTab.tsx | 146 +++ .../offerings/components/OfferingForm.tsx | 20 - .../src/features/offerings/mocks/handlers.ts | 46 +- .../offerings/pages/OfferingBanners.test.tsx | 141 ++ .../offerings/pages/OfferingFormPage.test.tsx | 34 +- .../offerings/pages/OfferingsListPage.tsx | 39 + .../features/offerings/schemas/offering.ts | 2 - .../offerings/schemas/offeringBanner.ts | 73 ++ .../src/features/offerings/services/types.ts | 30 +- .../services/useDeleteOfferingBanner.ts | 13 + .../offerings/services/useOfferingBanners.ts | 12 + .../services/useSaveOfferingBanner.ts | 18 + frontend/src/i18n/locales/en/translation.json | 1140 +++++++++-------- frontend/src/i18n/locales/nl/translation.json | 1140 +++++++++-------- .../PublicSiteEndpointGateTests.cs | 1 + 16 files changed, 1867 insertions(+), 1178 deletions(-) create mode 100644 frontend/src/features/offerings/components/OfferingBannerDialog.tsx create mode 100644 frontend/src/features/offerings/components/OfferingBannersTab.tsx create mode 100644 frontend/src/features/offerings/pages/OfferingBanners.test.tsx create mode 100644 frontend/src/features/offerings/schemas/offeringBanner.ts create mode 100644 frontend/src/features/offerings/services/useDeleteOfferingBanner.ts create mode 100644 frontend/src/features/offerings/services/useOfferingBanners.ts create mode 100644 frontend/src/features/offerings/services/useSaveOfferingBanner.ts diff --git a/frontend/src/features/offerings/components/OfferingBannerDialog.tsx b/frontend/src/features/offerings/components/OfferingBannerDialog.tsx new file mode 100644 index 0000000..34a94a6 --- /dev/null +++ b/frontend/src/features/offerings/components/OfferingBannerDialog.tsx @@ -0,0 +1,190 @@ +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { useTranslation } from 'react-i18next'; +import { toast } from 'sonner'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { FieldError } from '@/components/ui/FieldError'; +import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { NetworkError } from '@/lib/api-client'; +import { + fromLocalInput, + offeringBannerFormSchema, + toLocalInput, + type OfferingBannerFormData, +} from '../schemas/offeringBanner'; +import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner'; +import type { OfferingBannerDto } from '../services/types'; + +interface OfferingBannerDialogProps { + /** Open for editing this banner; null with `creating` = a new one. */ + banner: OfferingBannerDto | null; + creating: boolean; + onClose: () => void; +} + +const EMPTY: OfferingBannerFormData = { + title: '', + text: '', + linkLabel: '', + linkUrl: '', + isActive: true, + startsAt: '', + endsAt: '', +}; + +function toForm(banner: OfferingBannerDto | null): OfferingBannerFormData { + if (!banner) return EMPTY; + return { + title: banner.title, + text: banner.text, + linkLabel: banner.linkLabel ?? '', + linkUrl: banner.linkUrl ?? '', + isActive: banner.isActive, + startsAt: toLocalInput(banner.startsAt), + endsAt: toLocalInput(banner.endsAt), + }; +} + +export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) { + const { t } = useTranslation(); + const open = creating || banner !== null; + + return ( + { if (!next) onClose(); }}> + + + + {banner ? t('offerings.banners.editTitle') : t('offerings.banners.createTitle')} + + + {/* Content is unmounted while closed, so every opening starts from fresh form state. */} + + + + ); +} + +function OfferingBannerForm({ banner, onClose }: { banner: OfferingBannerDto | null; onClose: () => void }) { + const { t } = useTranslation(); + const [serverError, setServerError] = useState(null); + const save = useSaveOfferingBanner(); + + const { + register, + handleSubmit, + formState: { errors }, + } = useForm({ + resolver: zodResolver(offeringBannerFormSchema), + mode: 'onTouched', + defaultValues: toForm(banner), + }); + + const onSubmit = async (values: OfferingBannerFormData) => { + setServerError(null); + try { + await save.mutateAsync({ + id: banner?.id, + body: { + title: values.title, + text: values.text, + linkLabel: values.linkLabel || null, + linkUrl: values.linkUrl || null, + isActive: values.isActive, + startsAt: fromLocalInput(values.startsAt), + endsAt: fromLocalInput(values.endsAt), + }, + }); + toast.success(t('offerings.banners.savedToast')); + onClose(); + } catch (err) { + setServerError(err instanceof NetworkError ? t('errors.network') : t('errors.generic')); + } + }; + + return ( + <> + setServerError(null)} + /> + +
+
+ + + +
+ +
+ +