CMS: één bannerlijst met Locatie, SLP-thema, thema-schakelaar, documentatie

- Banner-admin: één lijst met Locatie-badge (Boven/Onder), Locatie-keuzeveld in het formulier, "Live" en "Wordt niet getoond" per locatie, aan/uit per rij
- Thema slpsoftware: Archivo, bordeaux #7A1414 (WCAG AA licht en donker), <SLP/>-logo, favicon, mail-logo; VITE_THEME in de SLP-builds (test en productie-config)
- Thema-schakelaar: eerste klik wisselt altijd het getoonde thema (klasse op <html> als bron van waarheid, gedeelde status, startscript valideert opslag) + tests
- Docs: README, docs/cms-themas.md, docs/deploy-en-testomgevingen.md, docs/privacy-gegevens-contactformulier.md, aidlc-docs (offering-banners, bug theme-toggle-first-click)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 00:14:10 +01:00
co-authored by Claude Sonnet 5.5
parent 4b09089ffb
commit 321234dfa6
28 changed files with 1081 additions and 242 deletions
@@ -413,6 +413,8 @@ jobs:
working-directory: frontend
env:
VITE_APP_ENV: test
VITE_APP_TITLE: SLP Software
VITE_THEME: slpsoftware
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_TEST }}
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
@@ -482,6 +484,8 @@ jobs:
working-directory: frontend
env:
VITE_APP_ENV: production
VITE_APP_TITLE: SLP Software
VITE_THEME: slpsoftware
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_PRODUCTION }}
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
+35 -4
View File
@@ -5,8 +5,8 @@ Een modulaire monolith CMS gebouwd met .NET 10.
## Projectstructuur
- `src/SlpModularCms.Api`: De host applicatie en API shell (lokale ontwikkeling / dev-host).
- `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project.
- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host alleen de modules `Identity` en `Availability` (geen `Master`, geen `Offerings`) en serveert de voorgerenderde website uit `wwwroot/web/` (`WebsiteMode.PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Bijbehorende tests: `SlpModularCms.Api.AndreaSlopFotografie.Tests` (de pipelinetests daarin hebben net als `Api.Tests` een bereikbare MariaDB nodig).
- `src/SlpModularCms.Api.SlpSoftware`: Tweede Client-project, de daadwerkelijk gedeployde API voor `test.slpsoftware.nl`/`slpsoftware.nl` (CI/CD-cutover vanaf `SlpModularCms.Api`). Host dezelfde modules als `SlpModularCms.Api` via dezelfde gedeelde `CmsHost`-compositie (zie hieronder), plus de `Offerings`- en `Contact`-module. Heeft een eigen, geïsoleerde lokale ontwikkeldatabase — zie `appsettings.Development.json` in dat project.
- `src/SlpModularCms.Api.AndreaSlopFotografie`: Derde Client-project voor Andrea Slop Fotografie (testomgeving `test.andreaslop.nl`). Host de modules `Identity`, `Availability`, `Offerings` en `Contact` (geen `Master`) en serveert de voorgerenderde website uit `wwwroot/web/` (`WebsiteMode.PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Bijbehorende tests: `SlpModularCms.Api.AndreaSlopFotografie.Tests` (de pipelinetests daarin hebben net als `Api.Tests` een bereikbare MariaDB nodig).
- `src/SlpModularCms.Core`: Kern functionaliteiten, data modellen en interfaces. Bevat ook `Core/Hosting/CmsHost.cs` — de gedeelde service- en pipeline-compositie die elk Client-project (`Api`, `Api.SlpSoftware`) vanuit zijn eigen dunne `Program.cs` aanroept, zodat beide projecten niet uit elkaar kunnen groeien.
- `src/SlpModularCms.Modules.*`: Onafhankelijke functionele modules.
- `frontend/`: De CMS admin web-UI (Vite + React + TypeScript). Bewust buiten `src/` gehouden om de .NET solution schoon te houden.
@@ -105,7 +105,7 @@ De frontend leest de API-basis-URL uit een environment-variabele (zie `frontend/
```
VITE_API_BASE_URL=http://localhost:5000
```
Per site kan de admin bij het bouwen een thema en standaardtaal krijgen: `VITE_THEME=asf` kiest `frontend/themes/asf/theme.css` (alleen CSS-variabelen, zelf gehoste lettertypen via `@fontsource`, plus een eigen favicon; een onbekende themanaam laat de build falen, leeg of afwezig = het standaardthema) en `VITE_DEFAULT_LANGUAGE=nl` (of `en`) bepaalt de taal zolang de gebruiker nog niets koos; een opgeslagen keuze wint altijd.
Per site kan de admin bij het bouwen een thema en standaardtaal krijgen (beschikbare thema's: `asf` en `slpsoftware`, zie [docs/cms-themas.md](docs/cms-themas.md)): `VITE_THEME=asf` kiest `frontend/themes/asf/theme.css` (alleen CSS-variabelen, zelf gehoste lettertypen via `@fontsource`, plus een eigen favicon; een onbekende themanaam laat de build falen, leeg of afwezig = het standaardthema) en `VITE_DEFAULT_LANGUAGE=nl` (of `en`) bepaalt de taal zolang de gebruiker nog niets koos; een opgeslagen keuze wint altijd.
Kopieer `.env.example` naar `.env.local` en pas de waarde aan indien nodig. Optioneel kan met `VITE_ENABLE_MSW=true` de MSW-mockbackend in de browser worden ingeschakeld voor frontend-ontwikkeling zonder draaiende API.
@@ -250,6 +250,37 @@ Zolang de master-gate een slave op `NotAvailable` heeft gezet (via push of pull)
- Een lokale poging om de status alsnog te wijzigen (bijv. via een directe API-call) wordt door de backend geweigerd met `409 Conflict` (`MasterControlledAvailabilityException` in `PersistentAvailabilityService.UpdateStatusAsync`) — de master-gate kan dus niet per ongeluk of expres lokaal worden omzeild.
- `GET /api/v1/Availability/status` geeft dit door via het veld `isMasterControlled`.
## Offerings: aanbiedingen en banner
De module `SlpModularCms.Modules.Offerings` (gehost door `Api.SlpSoftware` en `Api.AndreaSlopFotografie`) beheert de aanbiedingen (pakketten, met categorieën) en de banner van de website. Hieronder alleen de banner; details en beslissingen staan in `aidlc-docs/features/offering-banners/overview.md`.
Een banner heeft een **positie**: `top` (smalle balk boven de pagina, één regel) of `bottom` (grote banner; bestaande banners zijn via migratie `20261114100000_AddOfferingBannerPosition` `bottom` geworden).
**Publiek:** `GET /api/v1/offerings/banner?position=top|bottom`
- Zonder `position` geldt `bottom`; een andere waarde geeft `400`.
- `204` zonder actieve banner; anders `200` met `title`, `text`, `linkLabel`, `linkUrl`, `position` (geen planning).
- Anoniem, rate limit `offerings-public` (standaard 120 per 60 s per clientadres, `RateLimiting:OfferingsPublic`), antwoord met `Cache-Control: public, max-age=60`.
**Beheer:** `/api/v1/offerings/banners` (`GET`, `POST`, `PUT {id}`, `DELETE {id}`), alleen voor beheerders (`AdminOnly`).
**Velden en validatie:** `top`: tekst max 120 tekens, titel optioneel. `bottom`: titel verplicht (max 100), tekst max 300. Knoptekst (max 50) en link (max 500) alleen samen; een link is `https://…` of een pad dat met één `/` begint. `endsAt` moet na `startsAt` liggen. `isActive` en de planning (`startsAt`/`endsAt`) bepalen of een banner meetelt.
**"Maximaal één per positie"** geldt bij het uitlezen: je kunt meer banners opslaan en aanzetten; per positie wint de laatst gewijzigde actieve banner die binnen zijn van/tot valt. Een boven- en een onderbanner kunnen dus tegelijk getoond worden.
**Admin** (tabblad Banner bij Aanbiedingen): één lijst met een badge Locatie (Boven/Onder), de status (Actief, Gepland, Verlopen, Uit), de markeringen "Live" (wordt getoond) en "Wordt niet getoond" (actief, maar een nieuwere banner op dezelfde locatie wint), en een aan/uit-knop per rij. Het formulier heeft een keuzeveld Locatie dat de tekstlimiet en de titelplicht aanpast.
## Contactformulier-module
De module `SlpModularCms.Modules.Contact` (gehost door `Api.SlpSoftware` en `Api.AndreaSlopFotografie`; tests in `SlpModularCms.Modules.Contact.Tests`) ontvangt berichten van het contactformulier van een website, slaat ze op, mailt een melding naar de eigenaar en laat beheerders ze in de admin (Berichten) beheren. Plan en beslissingen: `aidlc-docs/features/contact-forms-module/`. Welke gegevens worden bewaard, hoe lang en wat in logs en Sentry terechtkomt: [`docs/privacy-gegevens-contactformulier.md`](docs/privacy-gegevens-contactformulier.md).
- **Uit tenzij beide schakelaars aan staan:** de hostschakelaar `Contact:Enabled` (standaard `false` in beide `appsettings.json`) én de CMS-schakelaar bij Berichten. Is het formulier niet open, dan bestaan de publieke routes niet (404). De migraties van de module worden pas bij het opstarten toegepast als `Contact:Enabled` aan staat.
- **Publiek:** `GET /api/v1/contact-messages/token` (tijdtoken, plus eventuele captcha-gegevens) en `POST /api/v1/contact-messages` (JSON, header `Idempotency-Key` met een GUID; antwoord `202`; fouten `400` in `ProblemDetails`-vorm met veldcodes `required`, `tooLong`, `invalid`, `expired`).
- **Beheer** (`AdminOnly`): `GET /api/v1/contact-messages`, `GET`/`PATCH`/`DELETE …/{id}`, `POST …/{id}/resend`, en `GET`/`PUT /api/v1/contact-settings` (schakelaar) met `PUT …/contact-settings/recipient` (ontvangstadres).
- **Anti-spam:** honeypot, minimumtijd tussen token en verzenden, optioneel Friendly Captcha, rate limiting per clientadres (`RateLimiting:ContactForm`, `ContactToken`, `ContactResend`). Achter een reverse proxy moet `ForwardedHeaders__KnownProxies__0` gezet zijn, anders delen alle bezoekers één limiet.
- **Configuratie (sectie `Contact`):** `Enabled`, `SiteId`, `MinSeconds` (3), `TokenLifetimeMinutes` (120), `RetentionMonths` (12), `SpamRetentionDays` (30), `MaxSpamRowsPerDay` (200), `MaxBodyBytes` (16384), `ProblemTypeBase`, `RecipientEmail` (alleen via omgevingsvariabele `Contact__RecipientEmail`), `Mail:SweepSeconds`/`MaxAttempts`/`BackoffMinutes`/`ClaimMinutes`/`BatchSize`, en `Captcha:Enabled`/`Provider` (`friendlycaptcha`)/`SiteKey`/`Secret` (alleen via `Contact__Captcha__Secret`)/`Region` (`global` of `eu`)/`VerifyUrl`/`TimeoutSeconds`. Een aangezet captcha met ontbrekende of ongeldige instellingen laat de host bij opstarten falen.
- **Opschonen:** een dagelijkse achtergrondtaak verwijdert berichten na hun bewaartermijn en idempotentie-gegevens na 24 uur.
- **Mail:** vereist werkende e-mailconfiguratie (zie "E-mail" hierboven) en een ontvangstadres; anders blijft het bericht bewaard met de reden bij het bericht.
## Lokaal Master + Slave Draaien (Dev)
Om de master↔slave-connectie (zie "Master CMS Module" hierboven) lokaal te kunnen testen, kun je twee backend-instanties tegelijk draaien: een volledige "master" (met de `SlpModularCms.Modules.Master`-module) en een "slave"-instantie zonder die module. Dit is puur een lokale ontwikkel-/testopstelling — er is geen nieuwe functionaliteit aan de master/slave-protocol zelf toegevoegd.
@@ -324,7 +355,7 @@ Ontbreekt `wwwroot/web/` nog (een verse deployment vóórdat een website-workspa
Voor lokale ontwikkeling verandert er niets: `pnpm dev` blijft op `http://localhost:5173` draaien zonder `/admin`-prefix.
### 1. Build & Publish
Publiceren gebeurt via de Gitea Actions-pipeline (`.gitea/workflows/continuous_integration.yaml` → `deploy-scp.yaml`), niet met een losse handmatige `dotnet publish`-stap: elke push naar `master` deployt automatisch naar test, productie alleen via een expliciete `workflow_dispatch` met de `deploy_production`-vlag aan. De pipeline publiceert framework-dependent voor `linux-arm64` en bouwt daarbij automatisch ook de admin-frontend mee naar `wwwroot/admin/`.
Publiceren gebeurt via de Gitea Actions-pipeline (`.gitea/workflows/continuous_integration.yaml` → `deploy-scp.yaml`), niet met een losse handmatige `dotnet publish`-stap: elke push naar `master` deployt automatisch naar de SlpSoftware-testomgeving (en naar de ASF-testomgeving als de Gitea-variabele `ASF_TEST_DEPLOY_ENABLED` op `true` staat), productie alleen via een expliciete `workflow_dispatch` met de `deploy_production`-vlag aan. Een branch naar test deployen kan met een handmatige run (`deploy_test` en/of `deploy_asf_test`). Zie [`docs/deploy-en-testomgevingen.md`](docs/deploy-en-testomgevingen.md) voor invoer, testhosts, vereiste variabelen en secrets (alleen namen) en rollback. De pipeline publiceert framework-dependent voor `linux-arm64` en bouwt daarbij automatisch ook de admin-frontend mee naar `wwwroot/admin/`.
Elke deploy plaatst de nieuwe release in een verse map en wisselt pas daarna atomisch over naar `current` — er is dus nooit een moment waarop de applicatie een halfklare release serveert, en `wwwroot/web/` (de klantsite) staat structureel buiten die verwisselde map, zodat een deploy hem nooit kan raken. Volledige host-setup, rollback-procedure en de exacte deploy-stappen staan in de Operations-documentatie van deze feature, niet hier — dit README beschrijft alleen wat er gebouwd is, niet hoe je het voor het eerst inricht.
+2
View File
@@ -17,3 +17,5 @@
| Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | 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 (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Frontend (router guard, login), Identity (Setup limiter) | 2026-11-09 |
| Feature | Contact Forms Module (contact-forms-module) | 🟡 Construction fase 2 (CMS-U7 en U5 klaar; U6, U8 volgen; niets gepusht) | feature/contact-forms-module | Modules (new Contact + Tests, Offerings category), Core (OnRejected, availability gate marker), Frontend (admin Berichten) | 2026-11-09 |
| Feature | [Offering banners (offering-banners)](features/offering-banners/overview.md) | 🟡 Op test (buiten AI-DLC gebouwd en achteraf gedocumenteerd; admin-lijst met Locatie-badge op test sinds 2026-11-15) | feature/contact-forms-module | Modules.Offerings (banner met positie top/bottom), openapi, Frontend (admin Aanbiedingen > Banner) | 2026-11-12 |
| Bug | [theme-toggle-first-click](bugs/theme-toggle-first-click/bug-fix.md) | ✅ Complete (niet gecommit/gemerged; buiten AI-DLC gebouwd; oorzaak niet in een echte browser nagebootst) | feature/contact-forms-module | Frontend (useTheme, index.html) | 2026-11-15 |
@@ -0,0 +1,43 @@
# Bug Fix: the first click on the theme toggle does nothing
- **Slug**: theme-toggle-first-click
- **Status**: Complete (pending deploy; built outside the AI-DLC flow, documented afterwards)
- **Issue**: None (reported by Bryan)
- **Branch**: feature/contact-forms-module
- **Started**: unknown
- **Documentation Language**: English
- **Conversation Language**: Dutch (user language)
## Report
In the admin, the first click on the light/dark toggle sometimes changed nothing visible; only the second click switched the theme.
## Root Cause
The `useTheme` hook (`frontend/src/hooks/useTheme.ts`) kept its own state, initialised from `localStorage` (`cms-theme`) or else from the OS preference (`prefers-color-scheme`). What is actually shown is decided by the class (`light` / `dark`) on `<html>`, which the start script in `frontend/index.html` sets before React runs. The two were not the same source: when the hook's state and the class on `<html>` differed, the first click flipped the hook's state and applied *that* theme, which could be the theme already shown, so nothing visible happened.
Two ways they could differ, both visible in the old code:
1. The start script in `index.html` took any stored value as a class name (`s ? s : ...`), while the hook only accepted `light` or `dark`. A stored value such as `system` put the class `system` on `<html>` (no theme at all) while the hook fell back to the OS preference.
2. Every toggle (desktop sidebar, mobile overlay) called `useTheme()` and so had its own state; flipping one left the others stale, so the next click on another toggle could re-apply the theme already shown.
**Not reproduced in a real browser.** The cause was derived from reading the old code; the only evidence is that the new tests fail against the old hook (reported by the developer; not re-run for this document). Which of the two cases (or another) happened in the browser session that was reported is not known.
## The Fix
- `useTheme.ts`: one source of truth, the class on `<html>`, read through `useSyncExternalStore`. If the page carries neither class, the stored value or OS preference is applied right away, so the reported state and what is shown cannot differ. `toggleTheme` flips what is shown now, stores it (inside `try/catch`, since storage can be unavailable), applies it and notifies every subscriber, so all toggles on the page share one state.
- `index.html`: the start script accepts only `light` or `dark` from storage; anything else falls back to the OS preference.
## Verification
**Path used**: Automated test framework (`frontend/src/hooks/useTheme.test.ts`, new block `first click`, 4 tests): with the OS preferring light and with it preferring dark and nothing stored or applied, the first click flips the shown theme; an unusable stored value (`system`) with class `system` on `<html>` still flips from what is shown; when the shown theme differs from the stored one the toggle follows the shown one and stores the new value; two toggles on one page stay in step.
**Before the fix**: according to the developer, the new tests fail against the old hook. Not re-run for this document. **After the fix**: not re-run for this document either.
**Not verified**: behaviour in a real browser (no manual reproduction before or after the fix).
## Result
- **PR(s)**: None
- **Commit(s)**: commit "CMS: één bannerlijst met Locatie, SLP-thema, thema-schakelaar" on feature/contact-forms-module (2026-11-15)
- **Completed**: 2026-11-15 (documentation)
@@ -510,6 +510,7 @@ change:
| `PI_MAIN_PORT` | secret | SSH port |
| `PI_MAIN_USERNAME` | secret | `gitea-workflow` — the generic, host-wide deploy account (§ 1.2), **not** `webadmin`; reuse the reference project's if it already has one |
| `PI_MAIN_PASSWORD` | secret | `gitea-workflow`'s password |
| `PI_MAIN_SSH_KEY` | secret | Optional: private key of the deploy account. When set and accepted, `deploy-scp.yaml` uses it instead of the password (needed for runners the host does not allow password login from) |
| `DEPLOY_PATH_TEST` | variable | `/home/gitea-workflow/apps/slpsoftware/test` |
| `DEPLOY_PATH_PRODUCTION` | variable | `/home/gitea-workflow/apps/slpsoftware/production` |
| `SERVICE_NAME_TEST` | variable | `slpsoftware-test.service` |
@@ -525,11 +526,13 @@ change:
## 2. Deploy Sequence (What Actually Happens on a Run)
Current compact overview, including the ASF test jobs and deploying a branch: `docs/deploy-en-testomgevingen.md` (checked against the workflows on 2026-11-15).
Already built (U5/U6) — this is the read-only walkthrough for whoever operates it:
1. Push to `master`, or a manual `workflow_dispatch` → the six gates run
2. `publish-test` runs (and `publish-production`, only if `workflow_dispatch` with the flag)
3. `deploy-test` (always, if gates pass) calls `deploy-scp.yaml`, which uploads into a new
1. Push to `master`, or a manual `workflow_dispatch` (inputs `deploy_test`, `deploy_production`, `deploy_asf_test`, all off by default) → the gates run (`changes`, `backend-build`, `backend-test`, `vulnerability-scan`, `frontend-prepare`, `frontend-build`, `frontend-test`, `frontend-lint`)
2. `publish-test` runs on a push to `master`, on pull requests (build only, no deploy) and on a dispatch with `deploy_test`; `publish-production` only on a dispatch with `deploy_production`
3. `deploy-test` (on a push to `master`, or a dispatch with `deploy_test`; not on pull requests) calls `deploy-scp.yaml`, which uploads into a new
`releases/{timestamp}/`, links `shared/wwwroot-web` and any `shared/modules/*.dll` in, switches
`current`, restarts `slpsoftware-test.service`, verifies `https://test.slpsoftware.nl/health`,
then prunes old releases (only test — `run_db_backup: false`)
@@ -0,0 +1,83 @@
# Offering Banners (offering-banners)
- **Slug**: offering-banners
- **Type**: Feature (small), built outside the AI-DLC flow and documented afterwards
- **Status**: On test (not merged, not pushed)
- **Branch**: feature/contact-forms-module
- **Affected components**: `SlpModularCms.Modules.Offerings` (+ Tests), openapi/slpsoftware.v1.json, frontend admin (`frontend/src/features/offerings`)
- **Documented**: 2026-11-15
- **Documentation Language**: English
- **Conversation Language**: Dutch (user language)
> This feature was **not** run through the AI-DLC stages (no requirements, design or audit trail). This file records what the code does, checked against the code on 2026-11-15. There are no `requirements`, `plans` or `audit.md` for it.
## Purpose
A site-wide, schedulable announcement ("banner") for offers and campaigns, managed by administrators in the CMS and fetched by the website through one public endpoint. A banner has a **position**: `top` (a narrow one-line bar above the page) or `bottom` (the large banner, which is also what every banner was before positions existed).
## History
| Commit | What |
|---|---|
| a2f4513 (2026-11-12) | `OfferingBanner` entity, `GET /offerings/banner`, banner layout removed (backend) |
| 5386abb (2026-11-12) | Banner tab in the admin (list, form, schedule); layout removed from the frontend |
| 4b09089 (2026-11-14) | Position `top`/`bottom` (backend, migration, admin tab, OpenAPI) |
| 2026-11-15 (commit "CMS: één bannerlijst met Locatie, SLP-thema, thema-schakelaar", on test) | Admin list: one list with a Location badge, "Live" / "Not shown" markers, on/off toggle per row; Location field in the form (`OfferingBannersTab.tsx`, `OfferingBannerDialog.tsx`, translations) |
## Contract
Routes are served under `/api/v1` (like all module routes).
### Public: `GET /api/v1/offerings/banner?position=top|bottom`
Source: `Controllers/OfferingBannersController.cs` (`PublicOfferingBannerController`).
| Aspect | Behaviour |
|---|---|
| Authentication | Anonymous (`[AllowAnonymous]`, `[PublicSiteEndpoint]`: stays reachable through the availability gate) |
| `position` | Optional. Absent or empty = `bottom`. Any other value than `top` / `bottom` (case sensitive) = `400` with `{ "error": "Position must be 'top' or 'bottom'." }` |
| No active banner at that position | `204 No Content` |
| Active banner | `200` with `{ title, text, linkLabel, linkUrl, position }` (no scheduling fields, no id) |
| Caching | `Cache-Control: public, max-age=60` is set on every answer that gets past the position check (so 200 and 204; not on the 400) |
| Rate limit | Policy `offerings-public`: fixed window per client address, `RateLimiting:OfferingsPublic:PermitLimit` / `WindowSeconds`, default 120 per 60 s (`ServiceCollectionExtensions.cs`); beyond it `429` |
### Management: `/api/v1/offerings/banners` (policy `AdminOnly`, i.e. role Administrator or higher)
| Method and route | Result |
|---|---|
| `GET /offerings/banners` | `200` list of all banners, most recently changed first (`id, position, title, text, linkLabel, linkUrl, isActive, startsAt, endsAt, updatedAt`) |
| `POST /offerings/banners` | `201` with the banner |
| `PUT /offerings/banners/{id}` | `200` with the banner (full replace), `404` if unknown |
| `DELETE /offerings/banners/{id}` | `204`, `404` if unknown |
### Fields and validation (`Models/OfferingBannerModels.cs`, `Data/Entities/OfferingBanner.cs`)
| Field | Rule |
|---|---|
| `position` | `top` or `bottom`; default `bottom` |
| `title` | Max 100 characters. **Required for `bottom`**, optional for `top` (may be empty) |
| `text` | Required, max 300 characters (`MaxLength`). For `top` the trimmed text is max **120** characters |
| `linkLabel` (max 50) and `linkUrl` (max 500) | Both or neither. Empty values are stored as null |
| `linkUrl` form | An `https://` URL with a host, or a site path starting with a single `/`. Not allowed: `//host`, backslashes, whitespace or control characters |
| `isActive` | Default `true` |
| `startsAt`, `endsAt` | Optional; if both are given, `endsAt` must be after `startsAt` |
Text fields are trimmed before storage. Every change logs `Offering banner {id} {Created|Updated|Deleted} by user {id}` and invalidates the `IIndexHtmlCache` when one is registered (`OfferingBannersService.Changed`). Whether a banner is injected into any HTML through that cache is not verified (no reference to banners was found in `Core/Hosting/Website`).
### Database
Table `OfferingsBanners`. Migration `20261114100000_AddOfferingBannerPosition` adds `Position varchar(10) NOT NULL DEFAULT 'bottom'`, so **every banner that existed before becomes `bottom`**. (Earlier migration `20261112100000_AddOfferingBannerRemoveLayout` created the table and dropped the `Layout` column of `OfferingsOfferings`.)
## Decisions (as implemented)
1. **"At most one per position" is enforced when reading, not when saving.** Any number of banners can be stored and switched on. `GetActiveAsync(position)` takes the banners that are switched on, at that position, inside their schedule (`StartsAt <= now` and `now < EndsAt`, either may be empty), and returns the one with the latest `UpdatedAt`. A top and a bottom banner can therefore be shown at the same time.
2. **The schedule is evaluated on the server at request time** (UTC, via `TimeProvider`); the browser's time zone only matters in the admin form (datetime-local, converted to UTC).
3. **The admin shows one list for both positions**, not one tab per position: a Location badge on each row (Top / Bottom), a status badge (Active / Planned / Expired / Off), and a "Live" badge on the banner visitors see now. An active banner shadowed by a more recently changed one at the same position gets "Not shown" plus a hint. `shownBannerIds` in `OfferingBannersTab.tsx` is a client-side copy of the server rule, not a server field. Each row has an on/off button (re-sends the banner through `PUT` with `isActive` flipped).
4. **The form follows the position**: changing Location changes the text limit (120 / 300) and whether the title is optional; the limits are mirrored in `schemas/offeringBanner.ts`.
5. **Links are restricted to `https://` or own-site paths**, which excludes `javascript:` and protocol-relative links.
## Known gaps and notes
- The OpenAPI document (`openapi/slpsoftware.v1.json`) describes the public endpoint with only a `200` answer: no `204`, `400` or `429`, no response body schema, no allowed values for `position`. The request schema has no length limits and no enum for `position`; `POST` is documented as `200` while the code returns `201`. The controllers carry no `[ProducesResponseType]` annotations. Not changed here.
- The website that shows the banner is not in this repository; how it fetches and renders the banner is not verified. The admin hint says that for Andrea's website the schedule applies at the next (nightly) build; that build is not in this repository either (not verified).
- Hosts that expose the module: `Api.SlpSoftware` and `Api.AndreaSlopFotografie` reference `Modules.Offerings` (csproj); the dev host `Api` does not.
+40
View File
@@ -0,0 +1,40 @@
# CMS-thema's per site
De admin (frontend) kan bij het bouwen een eigen uiterlijk krijgen. De standaardadmin blijft ongewijzigd als er geen thema is gekozen.
## Hoe het werkt
| Onderdeel | Waar | Gedrag |
|---|---|---|
| Keuze | omgevingsvariabele `VITE_THEME` bij `pnpm build` | Leeg of afwezig = standaardadmin. Een onbekende naam laat de build falen (geen stille terugval). |
| Beschikbare thema's | mappen in `frontend/themes/` met een `theme.css` | `asf`, `slpsoftware` |
| Kleuren, radius, lettertype | `themes/<naam>/theme.css` | Alleen design-tokens (CSS-variabelen), geen layout- of componentwijzigingen. Lettertypen zelf gehost via `@fontsource` (de admin-CSP staat alleen `font-src 'self'` toe). |
| Favicon | `themes/<naam>/favicon.png` | Wordt als `favicon-theme.png` uitgeleverd en in de pagina gelinkt. |
| Logo | `themes/<naam>/logo-on-light.png` en `logo-on-dark.png` | Beide of geen. Getoond via `BrandLogo` (licht/donker). Zonder logo valt de admin terug op de applicatienaam. |
| Mail-logo | `themes/<naam>/logo-mail.png` (optioneel) | Logo op een witte afgeronde badge voor e-mailkoppen. |
| Titel | `VITE_APP_TITLE` | Zet alleen `document.title`. |
| Taal | `VITE_DEFAULT_LANGUAGE` (`nl`/`en`) | Standaardtaal zolang de gebruiker nog niets koos. |
Code: `frontend/themes/resolveTheme.ts` (met tests), `frontend/vite.config.ts`, `frontend/src/lib/brand.ts`, `frontend/src/components/layout/BrandLogo.tsx`.
## Welke site gebruikt welk thema (CI)
| Site | Build | Thema |
|---|---|---|
| SLP Software | publish-test en publish-production in `.gitea/workflows/continuous_integration.yaml` | `slpsoftware`, titel `SLP Software` |
| Andrea Slop Fotografie | stap "Build admin frontend (ASF theme)" | `asf`, taal `nl` |
| Andere hosts | geen `VITE_THEME` | standaardadmin |
## Thema `slpsoftware`
- **Merk:** tekst `<SLP/>` in Archivo, bordeaux `#7A1414` (website-variant B).
- **Bestanden:** `theme.css` (tokens licht en donker), `logo-on-light.png`, `logo-on-dark.png`, `logo-mail.png`, `logo.svg` (alleen bron/archief), `favicon.png` (kopie van `icon-192.png` van de SLP-website; dat toont "/S" op bordeaux, niet `<SLP/>`).
- **Contrast (WCAG AA):** alle paren in `theme.css` halen AA in licht en donker; de uitkomsten staan in het commentaarblok bovenin het bestand en zijn te herberekenen met `contrast.py`. Laagste waarde: primary op card in donker, 4,93.
- **Logo opnieuw maken:** `python make-logo.py` in `frontend/themes/slpsoftware/` (Pillow en fonttools; lettertype uit `node_modules/@fontsource/archivo`, gewicht 800).
- **Donker:** lichter bordeaux als primary (`#e0646c`) zodat tekst en randen AA houden.
## Nieuw thema toevoegen
1. Map `frontend/themes/<naam>/` met minstens `theme.css`; optioneel favicon en logo-paar.
2. Tests in `frontend/themes/resolveTheme.test.ts` uitbreiden.
3. `VITE_THEME: <naam>` zetten in de build-stap van de betreffende site in de CI.
+96
View File
@@ -0,0 +1,96 @@
# Deploy en testomgevingen
Compact overzicht van hoe code op de testomgevingen en productie komt. Bron: `.gitea/workflows/continuous_integration.yaml` (hierna `ci`) en `.gitea/workflows/deploy-scp.yaml` (hierna `deploy`), gecontroleerd op 2026-11-15. De installatie van de host zelf staat niet hier maar in `aidlc-docs/features/gitea-deployment-workflow/operations/deployment/deployment-instructions.md` en `aidlc-docs/features/andreaslop-site-hosting/operations/deployment/deployment-instructions.md`.
## Omgevingen
| Omgeving | Wat | Publieke URL en health | Deploy-job |
|---|---|---|---|
| SlpSoftware test | `SlpModularCms.Api.SlpSoftware` | `https://test.slpsoftware.nl`, health `https://test.slpsoftware.nl/health` | `deploy-test` |
| SlpSoftware productie | `SlpModularCms.Api.SlpSoftware` | `https://slpsoftware.nl`, health `https://slpsoftware.nl/health` | `deploy-production` |
| ASF test (Andrea Slop Fotografie) | `SlpModularCms.Api.AndreaSlopFotografie` (website + admin met thema `asf`) | `https://test.andreaslop.nl`, health `https://test.andreaslop.nl/health` | `deploy-asf-test` |
De werkelijke health-URL's komen uit de Gitea-variabelen `HEALTH_CHECK_URL_TEST`, `HEALTH_CHECK_URL_PRODUCTION` en `HEALTH_CHECK_URL_ASF_TEST`; de waarden staan niet in de repository. De hostnamen hierboven komen uit de feature-documentatie (`deployment-instructions.md` van `gitea-deployment-workflow` en `andreaslop-site-hosting`) en zijn niet uit de workflows zelf af te leiden. Er is geen productie-deploy voor ASF in deze pipeline (de ASF-productie draait apart op IIS, zie `aidlc-docs/active-features.md`).
## Wanneer draait wat
| Trigger | Wat er gebeurt |
|---|---|
| `pull_request` (opened, synchronize, reopened) | De poorten (build, tests, kwetsbaarheidscontrole, frontend build/test/lint) en daarna `publish-test`: bouwt een testartefact. Er wordt **niet** gedeployed. Een nieuwe push naar dezelfde PR annuleert de lopende run (alleen bij PR's). |
| `push` op `master` | Dezelfde poorten, daarna automatisch `deploy-test` (SlpSoftware test) en, als `ASF_TEST_DEPLOY_ENABLED` op `true` staat, ook `deploy-asf-test`. Nooit productie. |
| `workflow_dispatch` (handmatig, op elke gekozen branch) | Alle poorten draaien altijd volledig (het pad-filter meldt dan backend en frontend als gewijzigd). Deployen gebeurt alleen voor de aangevinkte invoer, zie hieronder. |
Poorten (jobs): `changes` (pad-filter), `backend-build`, `backend-test` (met een MariaDB-servicecontainer op poort 3308), `vulnerability-scan`, `frontend-prepare`, `frontend-build`, `frontend-test`, `frontend-lint`. Een poort die overgeslagen is (omdat die kant van de repo niet wijzigde) blokkeert niet; een poort die faalt of wordt geannuleerd blokkeert elke publish. Pad-filter bij push/PR: backend = `src/**`, `tests/**`, `*.sln`, `**/*.csproj` en de workflowbestanden; frontend = `frontend/**` en de workflowbestanden. Een run die geen van beide raakt publiceert niets.
### Invoer van `workflow_dispatch`
| Invoer | Standaard | Effect |
|---|---|---|
| `deploy_test` | uit | Bouwt (`publish-test`) en deployt naar SlpSoftware test |
| `deploy_production` | uit | Bouwt (`publish-production`) en deployt naar SlpSoftware productie, met databaseback-up vooraf |
| `deploy_asf_test` | uit | Bouwt (`publish-asf-test`) en deployt naar ASF test; alleen als ook `ASF_TEST_DEPLOY_ENABLED` op `true` staat |
Zonder een van de drie aangevinkt draaien alleen de poorten (handig als losse CI-run). Meerdere tegelijk aanvinken kan. Let op: `deploy_production` is aan de `master`-branch niet gebonden in de workflow: de conditie van `deploy-production` controleert alleen de gebeurtenis en de invoer, niet de branch (zie `ci`, job `deploy-production`).
## Een branch naar test deployen
1. Gitea, repository, Actions, workflow "Continuous Integration", "Run workflow".
2. Kies de branch (de workflow bouwt en deployt de code van de gekozen ref; `actions/checkout` zonder `ref`).
3. Vink `deploy_test` aan (SlpSoftware test) en/of `deploy_asf_test` (ASF test). Laat `deploy_production` uit.
4. Na een groene run controleert de deploy zelf `/health`; kijk daarna zelf op de testhost.
Aandachtspunten:
- De selectie van een branch in de Gitea-interface en het uitvoeren op een andere branch dan `master` is door mij niet in de interface uitgeprobeerd (niet geverifieerd); de workflow zelf kent geen beperking tot `master` voor de testdeploys.
- Naar verwachting gebruikt Gitea het workflowbestand van de gekozen branch; dan moet de invoer `deploy_asf_test` daar in de workflow staan (niet geverifieerd).
- De testdatabase blijft bestaan. Bij het opstarten past de applicatie migraties toe (`MigrateCoreDatabase()` voor Identity/Core, en per module `Database.Migrate()`, zie README). Deploy je later weer `master`, dan staan de migraties van de branch nog in die database; dat gaat alleen goed als migraties voorwaarts-compatibel zijn (zo beschreven in `rollback-plan.md`).
- Een volgende push naar `master` overschrijft wat er op test staat.
- De testdeploys maken geen databaseback-up (`run_db_backup: false`).
## Wat `deploy` doet (per release)
1. Controleert dat `deploy_path`, `service_name` en `health_check_url` niet leeg zijn; anders stopt de deploy voordat de host wordt aangeraakt.
2. Zet SSH klaar: met de sleutel in `PI_MAIN_SSH_KEY` als die is ingesteld en werkt, anders met wachtwoord (`sshpass`).
3. Alleen productie: `bash ~/scripts/backup-slpsoftware-db.sh <omgeving>` op de host (het script staat niet in deze repository).
4. Uploadt het artefact naar `<deploy_path>/releases/<UTC-tijdstempel>`.
5. Koppelt de blijvende websitemap `shared/wwwroot-web` als `wwwroot/web` in de release, en eventuele `shared/modules/*.dll`.
6. Zet de symlink `<deploy_path>/current` in één stap om naar de nieuwe release en herstart de `systemd --user`-service (`service_name`).
7. Controleert `health_check_url` met `curl -f`, 10 pogingen met 3 seconden pauze. Slaagt dat niet, dan faalt de job.
8. Alleen na een geslaagde health-check: verwijdert oude releases, zodat `current` en één vorige release overblijven (`ls -1t | tail -n +3`).
9. Verwijdert de tijdelijke sleutel (ook bij falen).
## Rollback voor zover in de workflows beschreven
- Er is **geen automatische rollback**. Faalt de health-check, dan blijft `current` naar de nieuwe release wijzen en wordt er niet opgeruimd; de vorige release staat dan nog op schijf (opmerkingen in `deploy`).
- Handmatig terug: op de host `current` naar de vorige release in `releases/` zetten en de service herstarten. De exacte stappen staan in `aidlc-docs/features/gitea-deployment-workflow/operations/deployment/rollback-plan.md`.
- Verder terug dan de vorige release: een eerdere commit opnieuw deployen via de pijplijn (push naar `master`, of dispatch). Of de databasemigraties dat toelaten hangt af van die migraties (zie hierboven).
- Productie heeft een databaseback-up vooraf; terugzetten staat in dezelfde `rollback-plan.md`.
## Vereiste Gitea-secrets en -variabelen (alleen namen)
Secrets (SSH naar de host):
| Naam | Gebruik |
|---|---|
| `PI_MAIN_ADDRESS`, `PI_MAIN_PORT`, `PI_MAIN_USERNAME` | Adres, poort en deploy-account |
| `PI_MAIN_PASSWORD` | Wachtwoord (terugval; werkt vanaf de runner die op de host mag inloggen met wachtwoord) |
| `PI_MAIN_SSH_KEY` | Optioneel: privésleutel van het deploy-account, nodig voor runners die niet met wachtwoord mogen |
Variabelen:
| Naam | Voor |
|---|---|
| `DEPLOY_PATH_TEST`, `SERVICE_NAME_TEST`, `HEALTH_CHECK_URL_TEST` | SlpSoftware test. De `config`-job faalt als een van deze drie leeg is (dat geldt voor elke run, ook een PR) |
| `DEPLOY_PATH_PRODUCTION`, `SERVICE_NAME_PRODUCTION`, `HEALTH_CHECK_URL_PRODUCTION` | SlpSoftware productie |
| `ASF_TEST_DEPLOY_ENABLED` | Schakelaar voor alle ASF-jobs; alleen de waarde `true` zet ze aan |
| `DEPLOY_PATH_ASF_TEST`, `SERVICE_NAME_ASF_TEST`, `HEALTH_CHECK_URL_ASF_TEST` | ASF test; `config-asf` faalt als er een leeg is (terwijl de schakelaar aan staat) |
| `VITE_SENTRY_DSN` | Sentry-DSN voor de SlpSoftware-adminbuild (test en productie) |
| `VITE_SENTRY_DSN_ASF` | Sentry-DSN voor de ASF-adminbuild |
| `VITE_UMAMI_SCRIPT_URL`, `VITE_UMAMI_WEBSITE_ID_TEST`, `VITE_UMAMI_WEBSITE_ID_PRODUCTION` | Umami voor de SlpSoftware-adminbuild (ASF gebruikt geen Umami) |
| `SECURITY_ALLOWED_SCRIPT_ORIGINS_TEST`, `SECURITY_ALLOWED_SCRIPT_ORIGINS_PRODUCTION` | Alleen gebruikt als controle in `publish-test`/`publish-production` wanneer `VITE_UMAMI_SCRIPT_URL` gevuld is: de Umami-origin moet in deze lijst staan, en de lijst moet overeenkomen met `SecurityHeaders__AllowedScriptOrigins__0` op de host |
Runtime-instellingen van de applicatie (verbindingsstring, JWT, mail, `Contact__*`, Sentry) zitten niet in de workflow maar in het omgevingsbestand op de host (`shared/env`, zie README en de hostdocumentatie).
## Runners
Alle jobs draaien op het label `linux`, zodat elke runner (de Pi en de desktop-runner) ze kan oppakken. Gebouwd wordt voor `linux-arm64` (`PUBLISH_RID`), framework-dependent. Artefacten worden 1 dag bewaard.
+127
View File
@@ -0,0 +1,127 @@
# Privacy-gegevens van het contactformulier
Doel: feitelijke invoer voor de privacyverklaring van een website die de contactmodule gebruikt. Alles hieronder is gecontroleerd tegen de code op 2026-11-15 (branch `feature/contact-forms-module`, nog niet gemerged). Per feit staat het bronbestand; paden zijn relatief aan `src/`. Wat in de code niet te zien is (hostconfiguratie, mailserver, de website zelf) staat apart onder "Niet geverifieerd".
Dit is geen juridisch advies; het beschrijft alleen wat de software doet.
## 1. Wanneer is het formulier actief
| Feit | Bron |
|---|---|
| Het formulier werkt alleen als twee schakelaars aan staan: de hostschakelaar `Contact:Enabled` (omgevingsvariabele `Contact__Enabled`) en de CMS-schakelaar die een beheerder bij Berichten zet. Standaard staan beide uit. | `SlpModularCms.Modules.Contact/Services/ContactSettingsAndGates.cs`, `Controllers/ContactRouteFilter.cs`, `ContactModule.cs` |
| Is het formulier niet open, dan bestaan de routes niet (404). | `Controllers/ContactRouteFilter.cs` |
| In de meegeleverde `appsettings.json` staat `Contact:Enabled` op `false` voor `Api.SlpSoftware` (`SiteId` `slpsoftware`) en `Api.AndreaSlopFotografie` (`SiteId` `andreaslop`). Of het op een echte host aan staat, volgt uit de omgevingsvariabelen daar. | `SlpModularCms.Api.SlpSoftware/appsettings.json`, `SlpModularCms.Api.AndreaSlopFotografie/appsettings.json` |
## 2. Welke gegevens worden bij een bericht opgeslagen
Tabel `ContactMessages` (entiteit `ContactMessage`). Een bericht wordt alleen opgeslagen als alle velden geldig zijn (anders `400` en niets opgeslagen).
| Gegeven | Kolom | Grenzen | Opmerking |
|---|---|---|---|
| Naam | `Name` | max 100 tekens | Ingevuld door bezoeker, getrimd |
| E-mailadres | `Email` | max 254 tekens | Ingevuld door bezoeker; alleen een vormcontrole (`x@y.zz`) |
| Onderwerp | `Subject` | max 100 tekens | Bedoeld als door de website gekozen waarde (pakket-id, slug of `other`, zo staat het in de code); de API controleert alleen lengte en tekens, dus ook een vrije tekst wordt geaccepteerd |
| Bericht | `Message` | max 2000 tekens | Vrije tekst |
| Tijdstip van ontvangst | `ReceivedAt` | | Server-tijd (UTC) |
| Site | `SiteId` | | Uit configuratie (`Contact:SiteId`), nooit uit het verzoek |
| Status | `Status` | | `New`, `Read`, `Archived`, `Spam`, `Converted` |
| Mailstatus | `MailStatus`, `MailAttempts`, `NextMailAttemptAt`, `MailError` | `MailError` max 100 | Alleen een korte foutcode (bijv. `auth_failed`, `disabled`, `recipient_not_configured`), nooit een adres of tekst |
| Bewaren tot | `RetentionUntil` | | Zie hoofdstuk 3 |
Bron: `SlpModularCms.Modules.Contact/Data/Entities/ContactMessage.cs`, `Data/ContactDbContext.cs`, `Services/ContactValidator.cs`, `Services/ContactSubmissionService.cs`, `Services/ContactSeams.cs`.
**Wat niet wordt opgeslagen** (gecontroleerd: deze velden komen niet in `ContactMessage` of een andere tabel van de module voor):
- Geen IP-adres, geen hash van een IP-adres, geen user agent, geen referrer, geen cookies. (Ook de handoff-notitie zegt dit: `aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md`, regel "Privacy".)
- De honeypot-waarde en het captcha-antwoord worden niet bewaard; ze beslissen alleen of een bericht als spam wordt gemarkeerd.
- Het tijdtoken wordt niet opgeslagen (zie hoofdstuk 5).
- Er is in `ContactDbContext` geen veldversleuteling te zien: de velden staan als gewone tekst in de database.
Overige tabellen van de module:
| Tabel | Inhoud | Bron |
|---|---|---|
| `ContactIdempotency` | `SiteId`, `Key` (een door de website gegenereerde GUID uit de header `Idempotency-Key`), `CreatedAt`, `StatusCode`. Geen inhoud van het bericht. Voorkomt dubbele verwerking bij herhaald verzenden; wordt na 24 uur verwijderd. | `Data/Entities/ContactMessage.cs` (`IdempotencyRecord`), `Services/ContactRetentionService.cs` |
| `ContactSettings` | Eén rij: CMS-schakelaar, het door een beheerder ingestelde ontvangstadres voor meldingen (`RecipientEmail`), `UpdatedAt`, `UpdatedByUserId` | `Data/Entities/ContactMessage.cs` (`ContactSettings`) |
## 3. Bewaartermijnen en opschonen
| Onderwerp | Waarde | Configuratiesleutel | Bron |
|---|---|---|---|
| Bewaartermijn echt bericht | 12 maanden na ontvangst (vast per rij op het moment van opslaan; een latere wijziging van de instelling geldt niet met terugwerkende kracht) | `Contact:RetentionMonths` (standaard 12) | `Config/ContactOptions.cs`, `Services/ContactSubmissionService.cs` |
| Bewaartermijn spam | 30 dagen | `Contact:SpamRetentionDays` (standaard 30) | idem |
| Maximum spamrijen | 200 per site per UTC-dag; daarboven wordt spam beantwoord als normaal, maar niet opgeslagen | `Contact:MaxSpamRowsPerDay` (standaard 200) | idem |
| Idempotentie-gegevens | 24 uur | niet instelbaar | `Services/ContactRetentionService.cs`, `Services/ContactSubmissionService.cs` |
| Spam alsnog als echt markeren (status naar nieuw/gelezen/gearchiveerd) | de bewaartermijn start opnieuw: nu + `RetentionMonths` | | `Services/ContactAdminService.cs` (`SetStatusAsync`) |
Opschoon-job (`ContactRetentionService`, een achtergrondservice):
- Draait bij het opstarten van de applicatie en daarna elke 24 uur.
- Verwijdert alle berichten waarvan `RetentionUntil` verstreken is, **ongeacht status** (ook gelezen, gearchiveerd of geconverteerd), in batches van 500, en idempotentie-rijen ouder dan 24 uur. Het aantal verwijderde rijen wordt gelogd, geen inhoud.
- Doet niets (en raakt de database niet aan) zolang `Contact:Enabled` uit staat. Gevolg: zet je de hostschakelaar later uit, dan blijven opgeslagen berichten staan tot je hem weer aanzet.
- Een beheerder kan een bericht ook direct en definitief verwijderen (`DELETE /api/v1/contact-messages/{id}`).
- Er is in de code geen functie om berichten van één persoon te exporteren of op e-mailadres te zoeken; verwijderen gaat per bericht via de beheerlijst.
Bron: `Services/ContactRetentionService.cs`, `Repositories/ContactRepository.cs`, `Controllers/ContactAdminControllers.cs`.
**Back-ups:** vóór elke productie-deploy maakt de pipeline een databaseback-up via een script op de host (`backup-slpsoftware-db.sh`, `run_db_backup: true` in `.gitea/workflows/continuous_integration.yaml`). Volgens de feature-documentatie bewaart dat script de 7 meest recente back-ups per omgeving (`aidlc-docs/features/gitea-deployment-workflow/operations/deployment/deployment-instructions.md`, § 4). Het script zelf staat niet in deze repository: niet geverifieerd. Een verwijderd bericht kan dus nog in een back-up staan tot die roteert. Test-deploys (`test`) maken geen back-up in de pipeline.
## 4. Rate limiting (gegevens per bezoeker)
| Feit | Bron |
|---|---|
| Er zijn drie limieten: `ContactForm` (bericht versturen) 5 per 600 s, `ContactToken` (token ophalen) 20 per 600 s, `ContactResend` (opnieuw mailen door beheerder) 5 per 600 s. Instelbaar met `RateLimiting:ContactForm`, `RateLimiting:ContactToken`, `RateLimiting:ContactResend` (`PermitLimit`, `WindowSeconds`). | `ContactModule.cs`, `SlpModularCms.Api.SlpSoftware/appsettings.json` |
| De teller is per clientadres: het IP-adres zoals de applicatie het ziet (`ClientPartitionKey`). Dat is het echte bezoekersadres als `ForwardedHeaders:KnownProxies` is ingesteld; zonder die instelling deelt iedereen het adres van de proxy. | `SlpModularCms.Core/Hosting/Proxy/ClientPartitionKey.cs`, `Services/ContactSeams.cs` |
| De tellers staan alleen in het geheugen van het proces (ASP.NET Core `RateLimiter`, vast venster). Ze worden niet in de database opgeslagen en verdwijnen bij een herstart. | `ContactModule.cs` (`RateLimitPartition.GetFixedWindowLimiter`) |
| Bij een geweigerd verzoek (429) wordt in het log alleen de naam van de limiet en het pad vastgelegd, niet het IP-adres. | `SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs` (`OnRejected`), `Observability/SecurityEvents.cs` |
## 5. Anti-spam
| Maatregel | Werking | Bron |
|---|---|---|
| Honeypot | Een verborgen veld `hpCheck`; is het ingevuld, dan geldt het bericht als spam. | `Services/ContactSubmissionService.cs` |
| Minimumtijd | De bezoeker haalt eerst een token op (`GET /api/v1/contact-messages/token`); een bericht binnen `Contact:MinSeconds` (standaard 3 s) na dat token geldt als spam. Het token is geldig `Contact:TokenLifetimeMinutes` (standaard 120). Het token is een met ASP.NET Data Protection versleutelde tijdstempel, gebonden aan de `SiteId`; er wordt niets over bewaard. | `Services/ContactTokenService.cs`, `Config/ContactOptions.cs` |
| Captcha (optioneel) | Friendly Captcha v2, aan met `Contact:Captcha:Enabled`. De server stuurt alleen het captcha-antwoord en de site key naar de verificatie-URL (`global.frcapi.com` of, met `Contact:Captcha:Region=eu`, `eu.frcapi.com`), met de API-sleutel in een header; het IP-adres van de bezoeker en de berichtinhoud worden door de server niet meegestuurd. Ontbreekt het captcha-antwoord terwijl het captcha aan staat, dan geldt het bericht als spam. Bereikt de server de aanbieder niet (time-out, netwerkfout, 5xx, eigen verkeerde sleutel), dan wordt de bezoeker doorgelaten. | `Services/FriendlyCaptchaVerifier.cs`, `Config/ContactOptions.cs` |
| Spam wordt stil afgehandeld | Echt, spam en herhaling krijgen dezelfde `202`; spam wordt 30 dagen bewaard (zie hoofdstuk 3) en niet gemaild. | `Services/ContactSubmissionService.cs` |
| Maximale grootte verzoek | `Contact:MaxBodyBytes` (standaard 16384), anders `413`. | `Controllers/ContactRouteFilter.cs` |
Captcha en privacy: de widget in de browser van de bezoeker praat rechtstreeks met Friendly Captcha. Volgens de aantekening in de handoff-notitie (verwijzend naar de verklaringen van de aanbieder, niet door ons geverifieerd) kan bij regio `global` het IP-adres buiten de EU worden verwerkt en blijft het bij regio `eu` (betaald plan) binnen de EU; de privacyverklaring moet de aanbieder en de gebruikte regio noemen (`aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md`). De widget zelf zit in de website, niet in deze repository: niet geverifieerd.
## 6. E-mailmeldingen
| Feit | Bron |
|---|---|
| Voor elk echt bericht (niet voor spam) wordt een melding gemaild naar één ontvangstadres. Dat is het door een beheerder ingestelde adres (admin, Berichten), anders `Contact:RecipientEmail` (omgevingsvariabele `Contact__RecipientEmail`), anders niets. Zonder geldig adres of zonder werkende mailconfiguratie wordt niet gemaild; het bericht blijft bewaard en toont de reden. | `Services/ContactSettingsAndGates.cs`, `Services/ContactMailSender.cs` |
| De mail bevat naam, e-mailadres, onderwerp en bericht van de bezoeker. Het adres van de bezoeker staat als Reply-To (en de naam, als die geldig is als weergavenaam). In het mailonderwerp en andere headers staat niets dat de bezoeker typte. | `Services/ContactMailSender.cs` |
| Verzending gebeurt op de achtergrond (`ContactMailService`): direct na opslaan en daarnaast elke 120 s (`Contact:Mail:SweepSeconds`). Bij een fout nieuwe pogingen na 5 min, 15 min, 1 u, 6 u en 24 u (`Contact:Mail:BackoffMinutes`), maximaal 6 pogingen (`Contact:Mail:MaxAttempts`); daarna blijft het mislukt tot een beheerder het opnieuw verstuurt (maximaal 5 per 10 minuten). Alleen berichten met status Nieuw worden automatisch gemaild. | `Config/ContactOptions.cs`, `Services/ContactMailService.cs`, `Controllers/ContactAdminControllers.cs` |
| De mail gaat via de SMTP-instellingen van de host (`Email__Smtp__*`). Wat de mailserver en de mailbox van de ontvanger zelf bewaren valt buiten de applicatie: niet geverifieerd. | `README.md` (E-mail), `Services/ContactMailSender.cs` |
## 7. Logs en foutrapportage (Sentry)
| Feit | Bron |
|---|---|
| De contactmodule logt geen persoonsgegevens: bij een verzending alleen `Contact submission handled: {Outcome} for site {SiteId}` (uitkomst Genuine, Spam, SpamNotStored of Replay). De mailservice logt het bericht-id en een foutcode; fouten alleen met het exceptietype. Ook de Idempotency-Key en het token worden niet gelogd. Een test controleert dit met herkenbare markeringen in alle velden. | `Services/ContactSubmissionService.cs`, `Services/ContactMailSender.cs`, `Services/ContactMailService.cs`, `SlpModularCms.Modules.Contact.Tests/ContactNoPersonalDataInLogsTests.cs` |
| Het beheer logt alleen id's en uitkomsten (`Contact message {id} set to ...`, `deleted`, `resent`). | `Services/ContactAdminService.cs` |
| Sentry staat alleen aan als `Observability:SentryDsn` is gevuld (omgevingsvariabele `Observability__SentryDsn`); leeg = geen Sentry. | `SlpModularCms.Core/Hosting/Observability/SentryExtensions.cs` |
| Naar Sentry gaan gebeurtenissen vanaf niveau Warning; berichten vanaf Information gaan als breadcrumbs mee. `SendDefaultPii` staat aan: bij een gebeurtenis gaan het IP-adres, de user agent, de querystring, het pad en de ingelogde gebruikersnaam mee. | `Observability/SentryExtensions.cs`, `Observability/SentryEventScrubber.cs` (opmerking "retained") |
| Vóór verzending worden de headers `Cookie`, `Set-Cookie`, `Authorization` en `X-Master-Api-Key` verwijderd en de request-body wordt nooit meegestuurd (`MaxRequestBodySize = None`, daarnaast `request.Data = null`). De inhoud van het formulier komt daardoor niet via het verzoek in Sentry. De scrub-lijst is bewust niet configureerbaar. | `Observability/SentryEventScrubber.cs`, `Observability/SentryExtensions.cs` |
| Sentry kan dus het IP-adres van een bezoeker bevatten als er tijdens zijn verzoek een fout (Warning of hoger) optreedt. Het Sentry-project en de bewaartermijn daar zijn instellingen buiten de repository: niet geverifieerd. | idem |
| Logs van de reverse proxy / IIS / systemd-journal (bijv. IP-adressen in toegangslogs) vallen buiten de applicatie: niet geverifieerd. | n.v.t. |
## 8. Wie heeft toegang
| Wie | Toegang | Bron |
|---|---|---|
| Bezoeker | Kan alleen een token ophalen en een bericht versturen; kan niets uitlezen. | `Controllers/ContactMessagesController.cs` |
| Beheerders in het CMS | Lijst, detail (naam, e-mail, onderwerp, bericht, mailstatus, bewaren-tot), status wijzigen, verwijderen, opnieuw mailen, ontvangstadres en schakelaar instellen. Beleid `AdminOnly`: rol Administrator of hoger (Owner is hoger). Het ontvangstadres uit de omgeving wordt nooit aan de beheer-UI getoond, alleen de bron (`setting`/`config`). | `Controllers/ContactAdminControllers.cs`, `SlpModularCms.Core/Hosting/ServiceCollectionExtensions.cs` (`AdminOnly`), `SlpModularCms.Core/Identity/Authorization/HierarchicalRoleHandler.cs`, `Models/ContactAdminModels.cs` |
| Ontvanger van de meldingsmail | Ziet de inhoud in zijn mailbox (zie hoofdstuk 6). | `Services/ContactMailSender.cs` |
| Wie toegang heeft tot de database of host | Alles in dit document; niet af te dwingen vanuit de code. | n.v.t. |
## Niet geverifieerd (buiten de code)
- Of `Contact__Enabled` en het captcha op de testhosts of productie werkelijk aan staan.
- Retentie van back-ups en de inhoud van het back-upscript op de host.
- Mailserver, mailbox van de ontvanger, reverse proxy- en toegangslogs.
- Het Sentry-account (project, bewaartermijn, wie toegang heeft).
- De website zelf: de widget (captcha), het formulier en de tekst die bezoekers zien staan niet in deze repository.
- Of de bijbehorende frontend in `frontend/src` (beheer, Berichten) aanvullende gegevens toont of opslaat; alleen de API is hierboven nagelopen.
+1 -1
View File
@@ -8,7 +8,7 @@
<script>
(function () {
var s = localStorage.getItem('cms-theme');
var t = s ? s : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
var t = s === 'light' || s === 'dark' ? s : (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
document.documentElement.classList.add(t);
})();
</script>
+1
View File
@@ -22,6 +22,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource/archivo": "5.3.0",
"@fontsource/jost": "5.3.0",
"@fontsource/marcellus": "5.3.0",
"@hookform/resolvers": "^5.4.0",
+8
View File
@@ -17,6 +17,9 @@ importers:
'@dnd-kit/utilities':
specifier: ^3.2.2
version: 3.2.2(react@19.2.7)
'@fontsource/archivo':
specifier: 5.3.0
version: 5.3.0
'@fontsource/jost':
specifier: 5.3.0
version: 5.3.0
@@ -386,6 +389,9 @@ packages:
'@floating-ui/utils@0.2.11':
resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}
'@fontsource/archivo@5.3.0':
resolution: {integrity: sha512-5DIMgPVJRi62OqdOVoogCFxP73EkNM/E0YVTSDIQlDEJfDbxqZduwM/YoNZwC9Sx1CDgpKinqf8ckRY1QNIecw==}
'@fontsource/jost@5.3.0':
resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==}
@@ -2638,6 +2644,8 @@ snapshots:
'@floating-ui/utils@0.2.11': {}
'@fontsource/archivo@5.3.0': {}
'@fontsource/jost@5.3.0': {}
'@fontsource/marcellus@5.3.0': {}
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useTranslation } from 'react-i18next';
@@ -21,9 +21,9 @@ import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
interface OfferingBannerDialogProps {
/** Open for editing this banner (its own position applies); null with `creatingPosition` = a new one there. */
/** Open for editing this banner; null with `creating` = a new one. */
banner: OfferingBannerDto | null;
creatingPosition: BannerPosition | null;
creating: boolean;
onClose: () => void;
}
@@ -52,21 +52,20 @@ function toForm(banner: OfferingBannerDto | null, position: BannerPosition): Off
};
}
export function OfferingBannerDialog({ banner, creatingPosition, onClose }: OfferingBannerDialogProps) {
export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) {
const { t } = useTranslation();
const open = creatingPosition !== null || banner !== null;
const position: BannerPosition = banner?.position ?? creatingPosition ?? 'bottom';
const open = creating || banner !== null;
return (
<Dialog open={open} onOpenChange={(next) => { if (!next) onClose(); }}>
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle data-testid="banner-dialog-title">
{banner ? t(`offerings.banners.editTitle_${position}`) : t(`offerings.banners.createTitle_${position}`)}
{banner ? t('offerings.banners.editTitle') : t('offerings.banners.createTitle')}
</DialogTitle>
</DialogHeader>
{/* Content is unmounted while closed, so every opening starts from fresh form state. */}
<OfferingBannerForm banner={banner} position={position} onClose={onClose} />
<OfferingBannerForm banner={banner} onClose={onClose} />
</DialogContent>
</Dialog>
);
@@ -74,11 +73,9 @@ export function OfferingBannerDialog({ banner, creatingPosition, onClose }: Offe
function OfferingBannerForm({
banner,
position,
onClose,
}: {
banner: OfferingBannerDto | null;
position: BannerPosition;
onClose: () => void;
}) {
const { t } = useTranslation();
@@ -89,14 +86,22 @@ function OfferingBannerForm({
register,
handleSubmit,
control,
formState: { errors },
trigger,
formState: { errors, isSubmitted },
} = useForm<OfferingBannerFormData>({
resolver: zodResolver(offeringBannerFormSchema),
mode: 'onTouched',
defaultValues: toForm(banner, position),
defaultValues: toForm(banner, 'bottom'),
});
const position: BannerPosition = useWatch({ control, name: 'position' }) ?? 'bottom';
const textMax = bannerTextMaxLength(position);
const textLength = (useWatch({ control, name: 'text' }) ?? '').length;
const textTooLong = textLength > textMax;
// After a failed submit, switching location re-validates so stale title/text errors follow the new rules.
useEffect(() => {
if (isSubmitted) void trigger(['title', 'text']);
}, [position, isSubmitted, trigger]);
const onSubmit = async (values: OfferingBannerFormData) => {
setServerError(null);
@@ -129,6 +134,19 @@ function OfferingBannerForm({
/>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate data-testid="banner-form">
<div className="space-y-2">
<Label htmlFor="banner-position">{t('offerings.banners.position.label')}</Label>
<select
id="banner-position"
data-testid="banner-position"
className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
{...register('position')}
>
<option value="top">{t('offerings.banners.position.top')}</option>
<option value="bottom">{t('offerings.banners.position.bottom')}</option>
</select>
</div>
<div className="space-y-2">
<Label htmlFor="banner-title">{t(position === 'top' ? 'offerings.banners.titleLabelOptional' : 'offerings.banners.titleLabel')}</Label>
<Input id="banner-title" data-testid="banner-title" maxLength={100} {...register('title')} />
@@ -152,6 +170,11 @@ function OfferingBannerForm({
{textLength}/{textMax}
{position === 'top' && ` · ${t('offerings.banners.textHintTop')}`}
</p>
{textTooLong && !errors.text && (
<p className="text-sm text-destructive" role="alert" data-testid="banner-text-toolong">
{t('offerings.banners.textTooLong', { length: textLength, max: textMax })}
</p>
)}
<FieldError message={errors.text?.message} testId="banner-text-error" />
</div>
@@ -10,30 +10,34 @@ import { useDeleteOfferingBanner } from '../services/useDeleteOfferingBanner';
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
import { bannerStatus } from '../schemas/offeringBanner';
import { OfferingBannerDialog } from './OfferingBannerDialog';
import type { BannerPosition, OfferingBannerDto } from '../services/types';
import type { OfferingBannerDto } from '../services/types';
const fmt = (iso: string | null) =>
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
const POSITIONS: BannerPosition[] = ['top', 'bottom'];
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
/** The banner shown now for one position: among the live ones, the most recently changed wins. */
function liveBannerOf(banners: OfferingBannerDto[], now = new Date()): OfferingBannerDto | null {
const live = banners.filter((b) => bannerStatus(b, now) === 'live');
if (live.length === 0) return null;
return live.reduce((a, b) => (new Date(b.updatedAt) > new Date(a.updatedAt) ? b : a));
/** Ids of the banners actually shown now: per position, among the live ones the most recently changed wins. */
function shownBannerIds(banners: OfferingBannerDto[], now = new Date()): Set<string> {
const winners = new Map<string, OfferingBannerDto>();
for (const b of banners) {
if (bannerStatus(b, now) !== 'live') continue;
const current = winners.get(b.position);
if (!current || new Date(b.updatedAt) > new Date(current.updatedAt)) winners.set(b.position, b);
}
return new Set([...winners.values()].map((b) => b.id));
}
export function OfferingBannersTab() {
const { t } = useTranslation();
const { data: banners, isPending, isError } = useOfferingBanners();
const [editing, setEditing] = useState<OfferingBannerDto | null>(null);
const [creating, setCreating] = useState<BannerPosition | null>(null);
const [creating, setCreating] = useState(false);
const [pendingDelete, setPendingDelete] = useState<OfferingBannerDto | null>(null);
const remove = useDeleteOfferingBanner();
const save = useSaveOfferingBanner();
const items = banners ?? [];
const shownIds = shownBannerIds(items);
const toggleActive = (b: OfferingBannerDto) =>
save.mutate(
@@ -63,120 +67,119 @@ export function OfferingBannersTab() {
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
{isError && <p className="text-sm text-destructive">{t('errors.generic')}</p>}
{!isPending &&
!isError &&
POSITIONS.map((position) => {
const items = (banners ?? []).filter((b) => b.position === position);
const live = liveBannerOf(items);
return (
<section key={position} className="space-y-3" data-testid={`banners-section-${position}`}>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="space-y-1">
<h2 className="text-base font-semibold">{t(`offerings.banners.section.${position}.title`)}</h2>
<p className="text-sm text-muted-foreground">
{t(`offerings.banners.section.${position}.description`)}
</p>
<p className="text-xs text-muted-foreground" data-testid={`banner-live-hint-${position}`}>
{live
? t('offerings.banners.liveNow', { title: live.title || live.text })
: t('offerings.banners.nothingActive')}
</p>
</div>
<Button type="button" onClick={() => setCreating(position)} data-testid={`banner-add-${position}`}>
<Plus className="mr-1 size-4" aria-hidden="true" />
{t(`offerings.banners.section.${position}.addButton`)}
</Button>
</div>
{!isPending && !isError && (
<>
<div className="flex justify-end">
<Button type="button" onClick={() => setCreating(true)} data-testid="banner-add">
<Plus className="mr-1 size-4" aria-hidden="true" />
{t('offerings.banners.addButton')}
</Button>
</div>
{items.length === 0 ? (
<div
className="flex flex-col items-center space-y-2 py-8 text-center"
data-testid={`banners-empty-${position}`}
>
<Megaphone className="size-8 text-muted-foreground" aria-hidden="true" />
<p className="text-muted-foreground">{t('offerings.banners.empty')}</p>
</div>
) : (
<ul className="space-y-2" data-testid={`banners-list-${position}`}>
{items.map((b) => {
const status = bannerStatus(b);
const toggleLabel = t(
b.isActive ? 'offerings.banners.turnOffButton' : 'offerings.banners.turnOnButton',
);
return (
<li
key={b.id}
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
data-testid={`banner-row-${b.id}`}
{items.length === 0 ? (
<div className="flex flex-col items-center space-y-2 py-8 text-center" data-testid="banners-empty">
<Megaphone className="size-8 text-muted-foreground" aria-hidden="true" />
<p className="text-muted-foreground">{t('offerings.banners.empty')}</p>
</div>
) : (
<ul className="space-y-2" data-testid="banners-list">
{items.map((b) => {
const status = bannerStatus(b);
const shown = shownIds.has(b.id);
const hidden = status === 'live' && !shown;
const toggleLabel = t(
b.isActive ? 'offerings.banners.turnOffButton' : 'offerings.banners.turnOnButton',
);
return (
<li
key={b.id}
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
data-testid={`banner-row-${b.id}`}
>
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
{b.title && <span className="font-medium">{b.title}</span>}
<Badge variant="outline" data-testid={`banner-position-${b.id}`}>
{t(`offerings.banners.position.${b.position}`)}
</Badge>
<Badge variant={statusVariant[status]} data-testid={`banner-status-${b.id}`}>
{t(`offerings.banners.status.${status}`)}
</Badge>
{shown && (
<Badge data-testid={`banner-shown-${b.id}`}>{t('offerings.banners.shownBadge')}</Badge>
)}
{hidden && (
<Badge variant="destructive" data-testid={`banner-not-shown-${b.id}`}>
{t('offerings.banners.notShownBadge')}
</Badge>
)}
</div>
<p className="truncate text-sm text-muted-foreground">{b.text}</p>
{hidden && (
<p className="text-xs text-destructive" data-testid={`banner-not-shown-hint-${b.id}`}>
{t('offerings.banners.notShownHint')}
</p>
)}
{(b.startsAt || b.endsAt) && (
<p className="text-xs text-muted-foreground">
{fmt(b.startsAt) ?? '…'} – {fmt(b.endsAt) ?? '…'}
</p>
)}
</div>
<div className="flex shrink-0 gap-2">
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={toggleLabel}
title={toggleLabel}
disabled={save.isPending}
data-testid={`banner-toggle-${b.id}`}
onClick={() => toggleActive(b)}
>
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
{b.title && <span className="font-medium">{b.title}</span>}
<Badge variant={statusVariant[status]} data-testid={`banner-status-${b.id}`}>
{t(`offerings.banners.status.${status}`)}
</Badge>
</div>
<p className="truncate text-sm text-muted-foreground">{b.text}</p>
{(b.startsAt || b.endsAt) && (
<p className="text-xs text-muted-foreground">
{fmt(b.startsAt) ?? '…'} – {fmt(b.endsAt) ?? '…'}
</p>
)}
</div>
<div className="flex shrink-0 gap-2">
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={toggleLabel}
title={toggleLabel}
disabled={save.isPending}
data-testid={`banner-toggle-${b.id}`}
onClick={() => toggleActive(b)}
>
<Power className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.editButton')}
title={t('offerings.banners.editButton')}
data-testid={`banner-edit-${b.id}`}
onClick={() => setEditing(b)}
>
<Pencil className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.deleteButton')}
title={t('offerings.banners.deleteButton')}
data-testid={`banner-delete-${b.id}`}
onClick={() => setPendingDelete(b)}
>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
);
})}
</ul>
)}
</section>
);
})}
<Power className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.editButton')}
title={t('offerings.banners.editButton')}
data-testid={`banner-edit-${b.id}`}
onClick={() => setEditing(b)}
>
<Pencil className="size-4" aria-hidden="true" />
</Button>
<Button
type="button"
variant="outline"
size="icon"
className="size-11"
aria-label={t('offerings.banners.deleteButton')}
title={t('offerings.banners.deleteButton')}
data-testid={`banner-delete-${b.id}`}
onClick={() => setPendingDelete(b)}
>
<Trash2 className="size-4" aria-hidden="true" />
</Button>
</div>
</li>
);
})}
</ul>
)}
</>
)}
<OfferingBannerDialog
banner={editing}
creatingPosition={creating}
creating={creating}
onClose={() => {
setEditing(null);
setCreating(null);
setCreating(false);
}}
/>
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockAuthenticated } from '@/test/utils';
import { getMockBanners, resetMockOfferings, setMockBanners } from '@/features/offerings/mocks/handlers';
@@ -55,24 +55,19 @@ describe('Banner tab', () => {
expect(await screen.findByTestId('offerings-add-button')).toBeInTheDocument();
});
it('shows two sections (top and bottom), each with its own empty state and "nothing active" hint', async () => {
it('shows one list with an empty state and a single add button', async () => {
await openBannerTab();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banners-empty-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banners-empty-bottom')).toBeInTheDocument();
expect(within(top).getByTestId('banner-add-top')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-add-bottom')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/niets actief|Nothing is active/);
expect(await screen.findByTestId('banners-empty', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('banner-add')).toBeInTheDocument();
expect(screen.queryByTestId('banners-section-top')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-add-top')).not.toBeInTheDocument();
});
it('creates a bottom banner with a link and a schedule, sending position bottom', async () => {
it('creates a banner defaulting to location bottom, with a link and a schedule', async () => {
await openBannerTab();
expect(await screen.findByTestId('banners-empty-bottom', {}, T)).toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-add-bottom'));
await userEvent.type(await screen.findByTestId('banner-title'), 'Zomeractie');
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
expect(await screen.findByTestId('banner-position')).toHaveValue('bottom');
await userEvent.type(screen.getByTestId('banner-title'), 'Zomeractie');
await userEvent.type(screen.getByTestId('banner-text'), '10% korting in juli');
await userEvent.type(screen.getByTestId('banner-link-label'), 'Bekijk');
await userEvent.type(screen.getByTestId('banner-link-url'), '/privacy');
@@ -91,41 +86,67 @@ describe('Banner tab', () => {
});
expect(saved.startsAt).toBe(fromLocalInput('2030-07-01T09:00'));
expect(await screen.findByText('Zomeractie')).toBeInTheDocument();
expect(within(screen.getByTestId('banners-section-bottom')).getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(
/Gepland|Scheduled/,
);
expect(screen.getByTestId('banners-empty-top')).toBeInTheDocument();
expect(screen.getByTestId(`banner-position-${saved.id}`)).toHaveTextContent(/Onder|Bottom/);
expect(screen.getByTestId(`banner-status-${saved.id}`)).toHaveTextContent(/Gepland|Scheduled/);
});
it('requires a title for a bottom banner', async () => {
it('requires a title at location bottom', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-text'), 'Alleen tekst');
await userEvent.click(screen.getByTestId('banner-submit'));
expect(await screen.findByTestId('banner-title-error')).toBeInTheDocument();
expect(getMockBanners()).toHaveLength(0);
});
it('creates a top banner without a title, limited to 120 characters with a counter', async () => {
it('creates a top banner without a title; the text limit follows the chosen location live', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-top', {}, T));
expect(await screen.findByTestId('banner-text')).toHaveAttribute('maxlength', '120');
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
const text = await screen.findByTestId('banner-text');
expect(text).toHaveAttribute('maxlength', '300');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('0/300');
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(text).toHaveAttribute('maxlength', '120');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('0/120');
await userEvent.type(screen.getByTestId('banner-text'), 'Gratis verzending deze week');
await userEvent.type(text, 'Gratis verzending deze week');
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('27/120');
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
expect(getMockBanners()[0]).toMatchObject({ position: 'top', title: '', text: 'Gratis verzending deze week' });
const top = screen.getByTestId('banners-section-top');
expect(await within(top).findByText('Gratis verzending deze week')).toBeInTheDocument();
expect(screen.getByTestId('banners-empty-bottom')).toBeInTheDocument();
const saved = getMockBanners()[0];
expect(saved).toMatchObject({ position: 'top', title: '', text: 'Gratis verzending deze week' });
expect(await screen.findByTestId(`banner-position-${saved.id}`)).toHaveTextContent(/Boven|Top/);
});
it('does not silently truncate: switching to top with too long text shows a visible error and blocks saving', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-title'), 'Titel');
fireEvent.change(screen.getByTestId('banner-text'), { target: { value: 'x'.repeat(200) } });
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('200/300');
expect(screen.queryByTestId('banner-text-toolong')).not.toBeInTheDocument();
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(screen.getByTestId('banner-text')).toHaveValue('x'.repeat(200));
expect(screen.getByTestId('banner-text-counter')).toHaveTextContent('200/120');
expect(await screen.findByTestId('banner-text-toolong')).toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-submit'));
expect(await screen.findByTestId('banner-text-error')).toBeInTheDocument();
expect(getMockBanners()).toHaveLength(0);
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'bottom');
await waitFor(() => expect(screen.queryByTestId('banner-text-error')).not.toBeInTheDocument());
expect(screen.queryByTestId('banner-text-toolong')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
});
it('rejects an unsafe link and a link without button text, and an end before the start', async () => {
await openBannerTab();
await userEvent.click(await screen.findByTestId('banner-add-bottom', {}, T));
await userEvent.click(await screen.findByTestId('banner-add', {}, T));
await userEvent.type(await screen.findByTestId('banner-title'), 'X');
await userEvent.type(screen.getByTestId('banner-text'), 'Y');
@@ -148,41 +169,58 @@ describe('Banner tab', () => {
expect(getMockBanners()).toHaveLength(0);
});
it('lists banners under their own position and shows which one is live (most recently changed wins)', async () => {
it('lists all banners in one list in API order with a location badge per row', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
]);
await openBannerTab();
const top = await screen.findByTestId('banners-section-top', {}, T);
const bottom = screen.getByTestId('banners-section-bottom');
expect(within(top).getByTestId('banner-row-t1')).toBeInTheDocument();
expect(within(top).queryByTestId('banner-row-b-new')).not.toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-old')).toBeInTheDocument();
expect(within(bottom).getByTestId('banner-row-b-new')).toBeInTheDocument();
expect(screen.getByTestId('banner-live-hint-bottom')).toHaveTextContent(/Nu live: Nieuw|Live now: Nieuw/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/Balktekst/);
const list = await screen.findByTestId('banners-list', {}, T);
const rows = within(list).getAllByTestId(/^banner-row-/);
expect(rows.map((r) => r.getAttribute('data-testid'))).toEqual(['banner-row-b-new', 'banner-row-t1']);
expect(screen.getByTestId('banner-position-b-new')).toHaveTextContent(/Onder|Bottom/);
expect(screen.getByTestId('banner-position-t1')).toHaveTextContent(/Boven|Top/);
});
it('turns a banner off and on from its section', async () => {
setMockBanners([banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' })]);
it('marks the shown banner per location and flags older live banners on the same location as not shown', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
banner({ id: 'b-off', title: 'Uit', isActive: false, updatedAt: '2026-03-01T00:00:00Z' }),
]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-t1', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(false));
expect(getMockBanners()[0].position).toBe('top');
expect(await screen.findByTestId('banner-status-t1')).toHaveTextContent(/Uit|Off/);
expect(screen.getByTestId('banner-live-hint-top')).toHaveTextContent(/niets actief|Nothing is active/);
await userEvent.click(screen.getByTestId('banner-toggle-t1'));
await waitFor(() => expect(getMockBanners()[0].isActive).toBe(true));
expect(await screen.findByTestId('banner-shown-b-new', {}, T)).toBeInTheDocument();
expect(screen.getByTestId('banner-shown-t1')).toBeInTheDocument();
expect(screen.getByTestId('banner-not-shown-b-old')).toBeInTheDocument();
expect(screen.getByTestId('banner-not-shown-hint-b-old')).toHaveTextContent(/niet getoond|Not shown/);
expect(screen.queryByTestId('banner-shown-b-old')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-new')).not.toBeInTheDocument();
// An inactive banner is neither shown nor flagged.
expect(screen.queryByTestId('banner-shown-b-off')).not.toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-off')).not.toBeInTheDocument();
});
it('edits and deletes an existing banner, keeping its position', async () => {
it('turns a banner off and on, moving the shown mark to the next live banner', async () => {
setMockBanners([
banner({ id: 'b-old', title: 'Oud', updatedAt: '2026-01-01T00:00:00Z' }),
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-b-new', {}, T)).toHaveTextContent(/Actief|Active/);
await userEvent.click(screen.getByTestId('banner-toggle-b-new'));
await waitFor(() => expect(getMockBanners().find((b) => b.id === 'b-new')?.isActive).toBe(false));
expect(getMockBanners().find((b) => b.id === 'b-new')?.position).toBe('bottom');
expect(await screen.findByTestId('banner-status-b-new')).toHaveTextContent(/Uit|Off/);
expect(await screen.findByTestId('banner-shown-b-old')).toBeInTheDocument();
expect(screen.queryByTestId('banner-not-shown-b-old')).not.toBeInTheDocument();
await userEvent.click(screen.getByTestId('banner-toggle-b-new'));
await waitFor(() => expect(getMockBanners().find((b) => b.id === 'b-new')?.isActive).toBe(true));
});
it('edits a banner including its location (top keeps title optional), then deletes it', async () => {
setMockBanners([banner({ id: 'b1', title: 'Oud' })]);
await openBannerTab();
expect(await screen.findByTestId('banner-status-b1', {}, T)).toHaveTextContent(/Actief|Active/);
@@ -190,18 +228,21 @@ describe('Banner tab', () => {
await userEvent.click(screen.getByTestId('banner-edit-b1'));
const title = await screen.findByTestId('banner-title');
expect(title).toHaveValue('Oud');
expect(screen.getByTestId('banner-position')).toHaveValue('bottom');
await userEvent.clear(title);
await userEvent.type(title, 'Nieuw');
await userEvent.selectOptions(screen.getByTestId('banner-position'), 'top');
expect(screen.getByTestId('banner-text')).toHaveAttribute('maxlength', '120');
await userEvent.click(screen.getByTestId('banner-active'));
await userEvent.click(screen.getByTestId('banner-submit'));
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: 'Nieuw', isActive: false, position: 'bottom' }));
await waitFor(() => expect(getMockBanners()[0]).toMatchObject({ title: '', isActive: false, position: 'top' }));
expect(await screen.findByTestId('banner-status-b1')).toHaveTextContent(/Uit|Off/);
expect(screen.getByTestId('banner-position-b1')).toHaveTextContent(/Boven|Top/);
await userEvent.click(screen.getByTestId('banner-delete-b1'));
expect(await screen.findByTestId('banner-delete-message')).toHaveTextContent('Nieuw');
expect(await screen.findByTestId('banner-delete-message')).toHaveTextContent('Tekst');
await userEvent.click(screen.getByTestId('banner-delete-confirm'));
await waitFor(() => expect(getMockBanners()).toHaveLength(0));
expect(await screen.findByTestId('banners-empty-bottom')).toBeInTheDocument();
expect(await screen.findByTestId('banners-empty')).toBeInTheDocument();
});
});
+54
View File
@@ -48,3 +48,57 @@ describe('useTheme', () => {
expect(document.documentElement.classList.contains('light')).toBe(true);
});
});
describe('first click', () => {
const media = (dark: boolean) => vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: dark } as MediaQueryList);
const shown = () => (document.documentElement.classList.contains('dark') ? 'dark' : 'light');
it.each([
['light', 'dark'],
['dark', 'light'],
])('flips the shown theme straight away when the OS prefers %s and nothing is stored or applied', (os, expected) => {
media(os === 'dark');
const { result } = renderHook(() => useTheme());
expect(shown()).toBe(os);
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe(expected);
expect(result.current.theme).toBe(expected);
});
it('flips from what is shown even when the stored value is unusable', () => {
localStorage.setItem('cms-theme', 'system');
media(true);
document.documentElement.className = 'system';
const { result } = renderHook(() => useTheme());
expect(shown()).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
});
it('follows the shown theme when it differs from the stored one', () => {
localStorage.setItem('cms-theme', 'light');
document.documentElement.className = 'dark';
const { result } = renderHook(() => useTheme());
expect(result.current.theme).toBe('dark');
act(() => { result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(localStorage.getItem('cms-theme')).toBe('light');
});
it('keeps two toggles on the page in step', () => {
localStorage.setItem('cms-theme', 'light');
const a = renderHook(() => useTheme());
const b = renderHook(() => useTheme());
act(() => { a.result.current.toggleTheme(); });
expect(b.result.current.theme).toBe('dark');
act(() => { b.result.current.toggleTheme(); });
expect(shown()).toBe('light');
expect(a.result.current.theme).toBe('light');
});
});
+46 -10
View File
@@ -1,26 +1,62 @@
import { useState, useCallback } from 'react';
import { useCallback, useSyncExternalStore } from 'react';
type Theme = 'light' | 'dark';
const STORAGE_KEY = 'cms-theme';
function getInitialTheme(): Theme {
const listeners = new Set<() => void>();
function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
}
function preferredTheme(): Theme {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'light' || stored === 'dark') return stored;
if (isTheme(stored)) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function apply(theme: Theme) {
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(theme);
}
/**
* The theme that is actually shown, which is what the <html> class says: the stylesheet only
* knows that class. The stored value and the OS preference are only the way to pick a theme when
* the page carries none (or an unusable one); in that case it is applied right away, so the state
* we report and what the user sees can never differ. A first click then always flips what is shown.
*/
function currentTheme(): Theme {
const classes = document.documentElement.classList;
if (classes.contains('dark')) return 'dark';
if (classes.contains('light')) return 'light';
const theme = preferredTheme();
apply(theme);
return theme;
}
function subscribe(listener: () => void) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function useTheme() {
const [theme, setTheme] = useState<Theme>(getInitialTheme);
// One source of truth shared by every toggle on the page (desktop sidebar, mobile overlay).
const theme = useSyncExternalStore(subscribe, currentTheme, () => 'light' as Theme);
const toggleTheme = useCallback(() => {
setTheme((current) => {
const next: Theme = current === 'dark' ? 'light' : 'dark';
const next: Theme = currentTheme() === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem(STORAGE_KEY, next);
document.documentElement.classList.remove('light', 'dark');
document.documentElement.classList.add(next);
return next;
});
} catch {
// Storage can be unavailable (private mode); the switch itself still works.
}
apply(next);
listeners.forEach((notify) => notify());
}, []);
return { theme, isDark: theme === 'dark', toggleTheme };
+9 -18
View File
@@ -325,28 +325,19 @@
"title": "Offerings",
"addButton": "Add Offering",
"banners": {
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per spot (top and bottom) at any time: the most recently changed active one.",
"section": {
"top": {
"title": "Top",
"description": "Narrow bar at the top of the website, one line of text.",
"addButton": "Add top banner"
},
"bottom": {
"title": "Bottom",
"description": "Large banner at the bottom of the page with title, text and button.",
"addButton": "Add bottom banner"
}
"intro": "A banner is a wide announcement or promotion on the website. Plan ahead with a start and end time. At most one banner is shown per location (top and bottom) at any time: the most recently changed active one.",
"position": {
"label": "Location",
"top": "Top",
"bottom": "Bottom"
},
"liveNow": "Live now: {{title}}",
"nothingActive": "Nothing is active in this spot right now.",
"shownBadge": "Live",
"notShownBadge": "Not shown",
"notShownHint": "Not shown: a newer banner at this location",
"turnOffButton": "Turn banner off",
"turnOnButton": "Turn banner on",
"createTitle_top": "New banner (top)",
"createTitle_bottom": "New banner (bottom)",
"editTitle_top": "Edit banner (top)",
"editTitle_bottom": "Edit banner (bottom)",
"titleLabelOptional": "Title (optional)",
"textTooLong": "The text is {{length}} characters; this location allows at most {{max}}. Shorten the text or pick another location.",
"textHintTop": "One short line, up to 120 characters.",
"addButton": "Add banner",
"empty": "No banners yet.",
+9 -18
View File
@@ -325,28 +325,19 @@
"title": "Aanbiedingen",
"addButton": "Aanbieding toevoegen",
"banners": {
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per plek (boven en onder) wordt altijd maximaal één banner getoond: de laatst gewijzigde actieve.",
"section": {
"top": {
"title": "Boven",
"description": "Smalle balk bovenaan de website, één regel tekst.",
"addButton": "Banner boven toevoegen"
},
"bottom": {
"title": "Onder",
"description": "Grote banner onderaan de pagina met titel, tekst en knop.",
"addButton": "Banner onder toevoegen"
}
"intro": "Een banner is een brede mededeling of actie op de website. Plan vooruit met een begin- en eindtijd. Per locatie (boven en onder) wordt maximaal één banner getoond: de laatst gewijzigde actieve.",
"position": {
"label": "Locatie",
"top": "Boven",
"bottom": "Onder"
},
"liveNow": "Nu live: {{title}}",
"nothingActive": "Er is nu niets actief op deze plek.",
"shownBadge": "Live",
"notShownBadge": "Wordt niet getoond",
"notShownHint": "Wordt niet getoond: nieuwere banner op deze locatie",
"turnOffButton": "Banner uitzetten",
"turnOnButton": "Banner aanzetten",
"createTitle_top": "Nieuwe banner (boven)",
"createTitle_bottom": "Nieuwe banner (onder)",
"editTitle_top": "Banner bewerken (boven)",
"editTitle_bottom": "Banner bewerken (onder)",
"titleLabelOptional": "Titel (optioneel)",
"textTooLong": "De tekst is {{length}} tekens; voor deze locatie zijn maximaal {{max}} tekens toegestaan. Kort de tekst in of kies een andere locatie.",
"textHintTop": "Eén korte regel, maximaal 120 tekens.",
"addButton": "Banner toevoegen",
"empty": "Nog geen banners.",
+33 -1
View File
@@ -50,7 +50,7 @@ describe('resolveTheme', () => {
});
it('lists the available themes', () => {
expect(availableThemes()).toContain('asf');
expect(availableThemes()).toEqual(expect.arrayContaining(['asf', 'slpsoftware']));
});
it.each(['nope', '../asf', 'asf/../asf', '..', 'ASF', 'asf asf'])('rejects %j loudly, naming the real themes', (name) => {
@@ -99,3 +99,35 @@ describe('asf theme tokens', () => {
expect(theme).toContain('@fontsource/marcellus');
});
});
describe('slpsoftware theme', () => {
it('resolves stylesheet, favicon, logo pair and e-mail logo', () => {
const theme = resolveTheme('slpsoftware');
expect(theme.css.replaceAll('\\', '/')).toMatch(/themes\/slpsoftware\/theme\.css$/);
expect(fs.existsSync(theme.css)).toBe(true);
expect(theme.favicon !== null && fs.existsSync(theme.favicon)).toBe(true);
expect(theme.logo).not.toBeNull();
for (const f of [theme.logo!.onLight, theme.logo!.onDark, theme.logo!.mail!]) {
expect(fs.readFileSync(f).subarray(1, 4).toString()).toBe('PNG');
}
});
it('self-hosts Archivo and invents no structural token', () => {
const css = fs.readFileSync(path.resolve(__dirname, 'slpsoftware/theme.css'), 'utf-8');
const base = fs.readFileSync(path.resolve(__dirname, '../src/index.css'), 'utf-8');
const names = (src: string, block: string) => {
const m = src.match(new RegExp(`${block}\\s*\\{([^}]*)\\}`));
return new Set([...(m?.[1] ?? '').matchAll(/(--[a-z-]+)\s*:/g)].map((x) => x[1]));
};
expect(css).not.toMatch(/https?:\/\//);
expect(css).toContain('@fontsource/archivo');
for (const block of ['\\:root', '\\.dark']) {
const existing = names(base, block);
const themed = names(css, block);
for (const t of existing) expect(themed, `${block} ${t}`).toContain(t);
for (const t of themed) if (!existing.has(t)) expect(t).toMatch(/^--(slp-|font-sans$)/);
}
});
});
+12
View File
@@ -0,0 +1,12 @@
def lum(h):
h=h.lstrip('#'); c=[int(h[i:i+2],16)/255 for i in (0,2,4)]
c=[x/12.92 if x<=0.03928 else ((x+0.055)/1.055)**2.4 for x in c]
return .2126*c[0]+.7152*c[1]+.0722*c[2]
def cr(a,b):
la,lb=sorted([lum(a),lum(b)],reverse=True); return (la+.05)/(lb+.05)
L=dict(bg='#ffffff',fg='#1a1a1a',card='#f7f7f7',primary='#7a1414',pf='#ffffff',muted='#f4f4f5',mfg='#5c5c5c',accent='#f6e9e9',afg='#7a1414',destr='#c62828',dfg='#ffffff',ring='#7a1414')
D=dict(bg='#141414',fg='#f5f5f5',card='#1e1e1e',primary='#e0646c',pf='#141414',muted='#2a2a2a',mfg='#b0b0b0',accent='#3a1f21',afg='#f0a0a6',destr='#ff7b72',dfg='#141414',ring='#e0646c')
for n,t in (('light',L),('dark',D)):
print(n)
for lab,a,b,m in [('foreground/background','fg','bg',4.5),('card-foreground/card','fg','card',4.5),('primary-foreground/primary','pf','primary',4.5),('primary(link)/background','primary','bg',4.5),('primary/card','primary','card',4.5),('muted-foreground/background','mfg','bg',4.5),('muted-foreground/card','mfg','card',4.5),('muted-foreground/muted','mfg','muted',4.5),('accent-foreground/accent','afg','accent',4.5),('destructive-foreground/destructive','dfg','destr',4.5),('destructive/background','destr','bg',4.5),('ring/background','ring','bg',3),('ring/card','ring','card',3)]:
r=cr(t[a],t[b]); print(f' {lab:38s}{r:6.2f} {"OK" if r>=m else "FAIL"} (min {m})')
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-20 0 3658 824" role="img" aria-label="SLP Software">
<path fill="#7a1414" transform="translate(0 756) scale(1 -1)" d="M565 -6 63 194V327L565 527V399L197 260L565 121Z"/>
<path fill="#1a1a1a" transform="translate(649 756) scale(1 -1)" d="M360 -12Q295 -12 238.0 -0.5Q181 11 137.5 37.0Q94 63 69.0 105.5Q44 148 44 210Q44 214 44.0 219.0Q44 224 45 227H218Q218 224 217.5 219.5Q217 215 217 212Q217 180 233.5 160.5Q250 141 280.0 132.5Q310 124 350 124Q372 124 391.0 126.0Q410 128 425.0 133.0Q440 138 451.5 145.5Q463 153 468.5 163.5Q474 174 474 188Q474 211 456.5 226.0Q439 241 409.5 251.0Q380 261 343.0 270.0Q306 279 266.0 289.0Q226 299 189.0 314.0Q152 329 122.5 352.0Q93 375 75.5 409.5Q58 444 58 493Q58 547 81.0 586.5Q104 626 144.5 651.0Q185 676 238.0 687.5Q291 699 351 699Q410 699 461.5 687.0Q513 675 553.0 649.5Q593 624 615.5 585.5Q638 547 639 493V481H467V488Q467 511 454.5 528.5Q442 546 417.0 556.5Q392 567 355 567Q318 567 292.5 560.0Q267 553 253.5 540.0Q240 527 240 509Q240 487 257.5 473.0Q275 459 305.0 449.0Q335 439 372.0 430.5Q409 422 448.5 412.5Q488 403 525.0 388.5Q562 374 592.0 351.5Q622 329 639.5 296.0Q657 263 657 216Q657 134 618.5 84.0Q580 34 512.5 11.0Q445 -12 360 -12Z"/>
<path fill="#1a1a1a" transform="translate(1346 756) scale(1 -1)" d="M75 0V687H254V147H603V0Z"/>
<path fill="#1a1a1a" transform="translate(1969 756) scale(1 -1)" d="M75 0V687H453Q523 687 572.5 658.5Q622 630 648.5 579.5Q675 529 675 461Q675 391 647.5 340.0Q620 289 569.5 260.5Q519 232 449 232H254V0ZM254 370H407Q449 370 471.0 393.5Q493 417 493 459Q493 489 483.5 508.0Q474 527 455.0 537.5Q436 548 407 548H254Z"/>
<path fill="#7a1414" transform="translate(2667 756) scale(1 -1)" d="M0 -48 196 736H302L106 -48Z"/>
<path fill="#7a1414" transform="translate(2969 756) scale(1 -1)" d="M84 -6V121L452 260L84 399V527L586 327V194Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+100
View File
@@ -0,0 +1,100 @@
"""
Builds the SLP Software brand logo: logo-on-light.png, logo-on-dark.png, logo-mail.png and logo.svg.
The mark is the text <SLP/> in Archivo ExtraBold; the angle brackets and slash are bordeaux accents,
"SLP" is ink. Displayed 40 px high in the admin; PNGs are rendered at 3x (about 120 px high).
Needs: pip install pillow fonttools brotli; and `pnpm install` in frontend/ (font comes from @fontsource/archivo).
Run from this folder: python make-logo.py
"""
import io
import os
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
from PIL import Image, ImageDraw, ImageFont
SCALE = 3
H = 40 * SCALE
PAD = 2 * SCALE
FONT_WOFF2 = "../../node_modules/@fontsource/archivo/files/archivo-latin-800-normal.woff2"
TTF = "archivo-800.tmp.ttf"
PARTS = [("<", "accent"), ("SLP", "ink"), ("/>", "accent")]
VARIANTS = {
"logo-on-light.png": {"ink": (26, 26, 26), "accent": (122, 20, 20)},
"logo-on-dark.png": {"ink": (245, 245, 245), "accent": (224, 100, 108)},
}
f = TTFont(FONT_WOFF2)
f.flavor = None
f.save(TTF)
# Pick the pixel size so that the ink bounding box of the whole text is about H - 2*PAD high.
size = 100
probe = ImageFont.truetype(TTF, size)
text = "".join(p for p, _ in PARTS)
b = probe.getbbox(text)
size = round(size * (H - 2 * PAD) / (b[3] - b[1]))
font = ImageFont.truetype(TTF, size)
full = font.getbbox(text)
asc_top, asc_bot = full[1], full[3]
def render(colors):
# Draw the parts one after another using advance widths (keeps the font's own kerning-free spacing).
width = round(font.getlength(text)) + 2 * PAD + 4
img = Image.new("RGBA", (width, 2 * H), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
x = PAD
for part, role in PARTS:
d.text((x, PAD - asc_top), part, font=font, fill=colors[role] + (255,))
x += font.getlength(part)
img = img.crop(img.getchannel("A").getbbox())
out = Image.new("RGBA", (img.width + 2 * PAD, img.height + 2 * PAD), (0, 0, 0, 0))
out.alpha_composite(img, (PAD, PAD))
return out
for name, colors in VARIANTS.items():
im = render(colors)
im.save(name, optimize=True)
print(f"{name} {im.width}x{im.height}")
# logo-mail.png: the light variant on a white rounded badge (same approach as themes/asf/make-mail-logo.py).
src = Image.open("logo-on-light.png").convert("RGBA")
src = src.crop(src.getchannel("A").getbbox())
CONTENT_H, MPAD, RADIUS = 40 * SCALE, 8 * SCALE, 8 * SCALE
logo = src.resize((round(src.width * CONTENT_H / src.height), CONTENT_H), Image.LANCZOS)
w, h = logo.width + 2 * MPAD, CONTENT_H + 2 * MPAD
badge = Image.new("RGBA", (w, h), (0, 0, 0, 0))
ImageDraw.Draw(badge).rounded_rectangle((0, 0, w - 1, h - 1), radius=RADIUS, fill=(255, 255, 255, 255))
badge.alpha_composite(logo, (MPAD, MPAD))
badge.save("logo-mail.png", optimize=True)
print(f"logo-mail.png {w}x{h}")
# logo.svg: text converted to paths (archive/source; the build uses the PNGs).
gs = f.getGlyphSet()
cmap = f.getBestCmap()
upm = f["head"].unitsPerEm
hmtx = f["hmtx"]
paths, x = [], 0
ymin, ymax = 10**9, -10**9
from fontTools.pens.boundsPen import BoundsPen
for part, role in PARTS:
for ch in part:
g = cmap[ord(ch)]
pen = SVGPathPen(gs)
gs[g].draw(pen)
bp = BoundsPen(gs)
gs[g].draw(bp)
if bp.bounds:
ymin, ymax = min(ymin, bp.bounds[1]), max(ymax, bp.bounds[3])
paths.append((pen.getCommands(), x, role))
x += hmtx[g][0]
pad = 20
vb_h = ymax - ymin + 2 * pad
fill = {"ink": "#1a1a1a", "accent": "#7a1414"}
body = "\n".join(
f' <path fill="{fill[r]}" transform="translate({px} {ymax + pad}) scale(1 -1)" d="{d}"/>' for d, px, r in paths
)
svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{-pad} 0 {x + 2 * pad} {vb_h}" role="img" aria-label="SLP Software">\n{body}\n</svg>\n'
open("logo.svg", "w", encoding="utf-8", newline="\n").write(svg)
print("logo.svg", len(svg), "bytes")
os.remove(TTF)
+110
View File
@@ -0,0 +1,110 @@
/*
* Theme "slpsoftware" - SLP Software.
*
* Re-declares the admin design tokens only (colours, radius, font); no layout or component changes.
* Brand: bordeaux #7A1414 (website variant B) as primary/ring/accent basis on a white, neutral surface.
* Font: Archivo, self-hosted through @fontsource (the admin CSP is font-src 'self').
* Selected at build time with VITE_THEME=slpsoftware.
*
* Contrast (WCAG 2.x, computed by contrast.py next to this file; AA = 4.5:1 text, 3:1 UI/large):
*
* Pair Light Dark
* foreground / background 17.40 16.90
* card-foreground / card 16.25 15.29
* primary-foreground / primary 10.84 5.45
* primary (links) / background 10.84 5.45
* primary / card 10.12 4.93
* muted-foreground / background 6.69 8.49
* muted-foreground / card 6.24 7.69
* muted-foreground / muted 6.08 6.62
* accent-foreground / accent 9.16 7.36
* destructive-foreground / destructive 5.62 7.31
* destructive / background 5.62 7.31
* ring / background (min 3.0) 10.84 5.45
* ring / card (min 3.0) 10.12 4.93
*
* All pairs pass AA in both modes. Dark mode has no website counterpart: its primary is a lighter,
* derived bordeaux (#e0646c) so button text and links stay above 4.5:1 on the dark surfaces.
*/
@import '@fontsource/archivo/latin-400.css';
@import '@fontsource/archivo/latin-500.css';
@import '@fontsource/archivo/latin-600.css';
@import '@fontsource/archivo/latin-700.css';
:root {
--slp-bordeaux: #7a1414;
--slp-ink: #1a1a1a;
--slp-ink-2: #5c5c5c;
--slp-surface: #f7f7f7;
--slp-tint: #f6e9e9;
--slp-error: #c62828;
--slp-line: #e4e4e7;
--slp-font-body: 'Archivo', system-ui, 'Segoe UI', Roboto, sans-serif;
--background: #ffffff;
--foreground: var(--slp-ink);
--card: var(--slp-surface);
--card-foreground: var(--slp-ink);
--popover: #ffffff;
--popover-foreground: var(--slp-ink);
--primary: var(--slp-bordeaux);
--primary-foreground: #ffffff;
--secondary: #f4f4f5;
--secondary-foreground: var(--slp-ink);
--muted: #f4f4f5;
--muted-foreground: var(--slp-ink-2);
--accent: var(--slp-tint);
--accent-foreground: var(--slp-bordeaux);
--destructive: var(--slp-error);
--destructive-foreground: #ffffff;
--border: var(--slp-line);
--input: var(--slp-line);
--ring: var(--slp-bordeaux);
--radius: 0.375rem;
--font-sans: var(--slp-font-body);
}
.dark {
--background: #141414;
--foreground: #f5f5f5;
--card: #1e1e1e;
--card-foreground: #f5f5f5;
--popover: #1e1e1e;
--popover-foreground: #f5f5f5;
--primary: #e0646c;
--primary-foreground: #141414;
--secondary: #2a2a2a;
--secondary-foreground: #f5f5f5;
--muted: #2a2a2a;
--muted-foreground: #b0b0b0;
--accent: #3a1f21;
--accent-foreground: #f0a0a6;
--destructive: #ff7b72;
--destructive-foreground: #141414;
--border: #333333;
--input: #333333;
--ring: #e0646c;
}
body {
font-family: var(--slp-font-body);
}