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,