Contactformulier-module, banners, thema's, taalbestanden en CI-herstructurering #15
@@ -3,12 +3,12 @@ name: Continuous Integration
|
|||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
deploy_test:
|
deploy_sls_test:
|
||||||
description: 'Deploy to Test'
|
description: 'Deploy SLS test (SlpSoftware)'
|
||||||
type: boolean
|
type: boolean
|
||||||
default: false
|
default: false
|
||||||
deploy_production:
|
deploy_sls_production:
|
||||||
description: 'Deploy to Production'
|
description: 'Deploy SLS production (SlpSoftware)'
|
||||||
type: boolean
|
type: boolean
|
||||||
default: false
|
default: false
|
||||||
deploy_asf_test:
|
deploy_asf_test:
|
||||||
@@ -22,7 +22,7 @@ on:
|
|||||||
|
|
||||||
# A new push to the same PR does not cancel an already-running CI attempt by default (each
|
# A new push to the same PR does not cancel an already-running CI attempt by default (each
|
||||||
# `synchronize` event starts an independent run) — this opts in to cancelling the superseded one,
|
# `synchronize` event starts an independent run) — this opts in to cancelling the superseded one,
|
||||||
# but ONLY for pull_request events. `deploy-test`/`deploy-production` never run on a pull_request
|
# but ONLY for pull_request events. `deploy-sls-test`/`deploy-sls-production` never run on a pull_request
|
||||||
# (they require a push to master or a workflow_dispatch, see those jobs' `if:` conditions), so
|
# (they require a push to master or a workflow_dispatch, see those jobs' `if:` conditions), so
|
||||||
# scoping cancel-in-progress to pull_request here can never abort a live deploy mid-flight.
|
# scoping cancel-in-progress to pull_request here can never abort a live deploy mid-flight.
|
||||||
concurrency:
|
concurrency:
|
||||||
@@ -31,17 +31,17 @@ concurrency:
|
|||||||
|
|
||||||
# Reusable settings for this workflow. Change these in one place if the .NET/Node/pnpm version,
|
# Reusable settings for this workflow. Change these in one place if the .NET/Node/pnpm version,
|
||||||
# artifact names, or deploy destinations change. The env context is NOT available inside a called
|
# artifact names, or deploy destinations change. The env context is NOT available inside a called
|
||||||
# reusable workflow's `with:` inputs (see the `config` job below, which works around this by passing
|
# reusable workflow's `with:` inputs (see the `config-sls` job below, which works around this by passing
|
||||||
# these values through as job outputs to the `deploy-test` / `deploy-production` jobs).
|
# these values through as job outputs to the `deploy-sls-test` / `deploy-sls-production` jobs).
|
||||||
env:
|
env:
|
||||||
DOTNET_VERSION: '10.0.x'
|
DOTNET_VERSION: '10.0.x'
|
||||||
NODE_VERSION: '20'
|
NODE_VERSION: '20'
|
||||||
PNPM_VERSION: '9'
|
PNPM_VERSION: '9'
|
||||||
PUBLISH_RID: linux-arm64
|
PUBLISH_RID: linux-arm64
|
||||||
ARTIFACT_NAME_TEST: app-test
|
ARTIFACT_NAME_SLS_TEST: app-sls-test
|
||||||
ARTIFACT_NAME_PRODUCTION: app-production
|
ARTIFACT_NAME_SLS_PRODUCTION: app-sls-production
|
||||||
DEPLOY_ENVIRONMENT_TEST: test
|
DEPLOY_ENVIRONMENT_SLS_TEST: test
|
||||||
DEPLOY_ENVIRONMENT_PRODUCTION: production
|
DEPLOY_ENVIRONMENT_SLS_PRODUCTION: production
|
||||||
DEPLOY_PATH_TEST: ${{ vars.DEPLOY_PATH_TEST }}
|
DEPLOY_PATH_TEST: ${{ vars.DEPLOY_PATH_TEST }}
|
||||||
DEPLOY_PATH_PRODUCTION: ${{ vars.DEPLOY_PATH_PRODUCTION }}
|
DEPLOY_PATH_PRODUCTION: ${{ vars.DEPLOY_PATH_PRODUCTION }}
|
||||||
SERVICE_NAME_TEST: ${{ vars.SERVICE_NAME_TEST }}
|
SERVICE_NAME_TEST: ${{ vars.SERVICE_NAME_TEST }}
|
||||||
@@ -51,40 +51,56 @@ env:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Passes the env: values above through as job outputs, since the env context is unavailable in
|
# Passes the env: values above through as job outputs, since the env context is unavailable in
|
||||||
# the `with:` block of a job that calls a reusable workflow (see deploy-test / deploy-production).
|
# the `with:` block of a job that calls a reusable workflow (see deploy-sls-test / deploy-sls-production).
|
||||||
config:
|
config-sls:
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
outputs:
|
outputs:
|
||||||
artifact_name_test: ${{ steps.set.outputs.artifact_name_test }}
|
artifact_name_sls_test: ${{ steps.set.outputs.artifact_name_sls_test }}
|
||||||
artifact_name_production: ${{ steps.set.outputs.artifact_name_production }}
|
artifact_name_sls_production: ${{ steps.set.outputs.artifact_name_sls_production }}
|
||||||
deploy_environment_test: ${{ steps.set.outputs.deploy_environment_test }}
|
deploy_environment_sls_test: ${{ steps.set.outputs.deploy_environment_sls_test }}
|
||||||
deploy_environment_production: ${{ steps.set.outputs.deploy_environment_production }}
|
deploy_environment_sls_production: ${{ steps.set.outputs.deploy_environment_sls_production }}
|
||||||
deploy_path_test: ${{ steps.set.outputs.deploy_path_test }}
|
deploy_path_sls_test: ${{ steps.set.outputs.deploy_path_sls_test }}
|
||||||
deploy_path_production: ${{ steps.set.outputs.deploy_path_production }}
|
deploy_path_sls_production: ${{ steps.set.outputs.deploy_path_sls_production }}
|
||||||
service_name_test: ${{ steps.set.outputs.service_name_test }}
|
service_name_sls_test: ${{ steps.set.outputs.service_name_sls_test }}
|
||||||
service_name_production: ${{ steps.set.outputs.service_name_production }}
|
service_name_sls_production: ${{ steps.set.outputs.service_name_sls_production }}
|
||||||
health_check_url_test: ${{ steps.set.outputs.health_check_url_test }}
|
health_check_url_sls_test: ${{ steps.set.outputs.health_check_url_sls_test }}
|
||||||
health_check_url_production: ${{ steps.set.outputs.health_check_url_production }}
|
health_check_url_sls_production: ${{ steps.set.outputs.health_check_url_sls_production }}
|
||||||
steps:
|
steps:
|
||||||
# Gitea has no reliable way to see a past run's workflow_dispatch input values from the UI, so
|
# Gitea has no reliable way to see a past run's workflow_dispatch input values from the UI, so
|
||||||
# this logs them explicitly — the only durable record of what was actually checked for a run.
|
# this logs them explicitly — the only durable record of what was actually checked for a run.
|
||||||
- name: Log dispatch inputs
|
- name: Log dispatch inputs
|
||||||
if: github.event_name == 'workflow_dispatch'
|
if: github.event_name == 'workflow_dispatch'
|
||||||
run: |
|
run: |
|
||||||
echo "Deploy to Test: ${{ github.event.inputs.deploy_test }}"
|
echo "Deploy SLS test: ${{ github.event.inputs.deploy_sls_test }}"
|
||||||
echo "Deploy to Production: ${{ github.event.inputs.deploy_production }}"
|
echo "Deploy SLS production: ${{ github.event.inputs.deploy_sls_production }}"
|
||||||
|
# The Gitea variables are read at STEP level (like config-asf), not through the workflow-level env block: on the PC
|
||||||
|
# runner the workflow-level `${{ vars.* }}` values came through empty (deploy path "" -> mkdir /releases), while
|
||||||
|
# step-level env works on both runners. The test trio must be set, otherwise fail here instead of in the deploy.
|
||||||
- id: set
|
- id: set
|
||||||
|
env:
|
||||||
|
DEPLOY_PATH_TEST: ${{ vars.DEPLOY_PATH_TEST }}
|
||||||
|
DEPLOY_PATH_PRODUCTION: ${{ vars.DEPLOY_PATH_PRODUCTION }}
|
||||||
|
SERVICE_NAME_TEST: ${{ vars.SERVICE_NAME_TEST }}
|
||||||
|
SERVICE_NAME_PRODUCTION: ${{ vars.SERVICE_NAME_PRODUCTION }}
|
||||||
|
HEALTH_CHECK_URL_TEST: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||||
|
HEALTH_CHECK_URL_PRODUCTION: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
|
||||||
run: |
|
run: |
|
||||||
echo "artifact_name_test=${{ env.ARTIFACT_NAME_TEST }}" >> "$GITHUB_OUTPUT"
|
for v in DEPLOY_PATH_TEST SERVICE_NAME_TEST HEALTH_CHECK_URL_TEST; do
|
||||||
echo "artifact_name_production=${{ env.ARTIFACT_NAME_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
if [ -z "${!v}" ]; then
|
||||||
echo "deploy_environment_test=${{ env.DEPLOY_ENVIRONMENT_TEST }}" >> "$GITHUB_OUTPUT"
|
echo "The Gitea variable $v is empty or not set on this runner; the deploy would use an empty path."
|
||||||
echo "deploy_environment_production=${{ env.DEPLOY_ENVIRONMENT_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
exit 1
|
||||||
echo "deploy_path_test=${{ env.DEPLOY_PATH_TEST }}" >> "$GITHUB_OUTPUT"
|
fi
|
||||||
echo "deploy_path_production=${{ env.DEPLOY_PATH_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
done
|
||||||
echo "service_name_test=${{ env.SERVICE_NAME_TEST }}" >> "$GITHUB_OUTPUT"
|
echo "artifact_name_sls_test=${{ env.ARTIFACT_NAME_SLS_TEST }}" >> "$GITHUB_OUTPUT"
|
||||||
echo "service_name_production=${{ env.SERVICE_NAME_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
echo "artifact_name_sls_production=${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
||||||
echo "health_check_url_test=${{ env.HEALTH_CHECK_URL_TEST }}" >> "$GITHUB_OUTPUT"
|
echo "deploy_environment_sls_test=${{ env.DEPLOY_ENVIRONMENT_SLS_TEST }}" >> "$GITHUB_OUTPUT"
|
||||||
echo "health_check_url_production=${{ env.HEALTH_CHECK_URL_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
echo "deploy_environment_sls_production=${{ env.DEPLOY_ENVIRONMENT_SLS_PRODUCTION }}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "deploy_path_sls_test=$DEPLOY_PATH_TEST" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "deploy_path_sls_production=$DEPLOY_PATH_PRODUCTION" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "service_name_sls_test=$SERVICE_NAME_TEST" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "service_name_sls_production=$SERVICE_NAME_PRODUCTION" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "health_check_url_sls_test=$HEALTH_CHECK_URL_TEST" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "health_check_url_sls_production=$HEALTH_CHECK_URL_PRODUCTION" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
# Path-based skip: keeps the pipeline short when a change only touches one side of the repo.
|
# Path-based skip: keeps the pipeline short when a change only touches one side of the repo.
|
||||||
# fetch-depth: 0 gives paths-filter full local git history to diff against, rather than relying
|
# fetch-depth: 0 gives paths-filter full local git history to diff against, rather than relying
|
||||||
@@ -94,7 +110,7 @@ jobs:
|
|||||||
# workflow_dispatch run has no `before` commit to diff against and is always an explicit request
|
# workflow_dispatch run has no `before` commit to diff against and is always an explicit request
|
||||||
# to run everything, so it force-reports both sides as changed rather than trusting the filter.
|
# to run everything, so it force-reports both sides as changed rather than trusting the filter.
|
||||||
changes:
|
changes:
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
outputs:
|
outputs:
|
||||||
backend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.backend == 'true' }}
|
backend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.backend == 'true' }}
|
||||||
frontend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.frontend == 'true' }}
|
frontend: ${{ github.event_name == 'workflow_dispatch' || steps.filter.outputs.frontend == 'true' }}
|
||||||
@@ -118,6 +134,7 @@ jobs:
|
|||||||
- 'src/**'
|
- 'src/**'
|
||||||
- 'tests/**'
|
- 'tests/**'
|
||||||
- '*.sln'
|
- '*.sln'
|
||||||
|
- '*.slnf'
|
||||||
- '**/*.csproj'
|
- '**/*.csproj'
|
||||||
frontend:
|
frontend:
|
||||||
- *workflow
|
- *workflow
|
||||||
@@ -127,20 +144,44 @@ jobs:
|
|||||||
backend-build:
|
backend-build:
|
||||||
needs: changes
|
needs: changes
|
||||||
if: needs.changes.outputs.backend == 'true'
|
if: needs.changes.outputs.backend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-dotnet@v4
|
- uses: actions/setup-dotnet@v4
|
||||||
with:
|
with:
|
||||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||||
|
# The CI builds and tests the master CMS only (SlpModularCms.Api with every module, Core and all test
|
||||||
|
# projects), listed in SlpModularCms.Ci.slnf. The site projects (Api.SlpSoftware, Api.AndreaSlopFotografie,
|
||||||
|
# Api.Slave) are thin compositions: they are compiled by compile-sites below and built/published only when a
|
||||||
|
# deploy needs them. Their behaviour is covered by the tests on the master host (see SiteContractTests).
|
||||||
- name: Restore and build (Release)
|
- name: Restore and build (Release)
|
||||||
run: dotnet build SlpModularCms.sln -c Release
|
run: dotnet build SlpModularCms.Ci.slnf -c Release
|
||||||
|
|
||||||
|
# --- Not required: the thin site projects still compile ---
|
||||||
|
# Compile only (no tests, a few seconds): catches a broken reference or a renamed type in a site project on the
|
||||||
|
# pull request instead of at deploy time. Deliberately not a required check; the smoke tests after the test
|
||||||
|
# deploys catch composition errors that compile fine.
|
||||||
|
compile-sites:
|
||||||
|
needs: changes
|
||||||
|
if: needs.changes.outputs.backend == 'true'
|
||||||
|
runs-on: linux
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||||
|
- name: Compile the site projects (Release)
|
||||||
|
run: |
|
||||||
|
for project in SlpSoftware AndreaSlopFotografie Slave; do
|
||||||
|
echo "== SlpModularCms.Api.$project"
|
||||||
|
dotnet build "src/SlpModularCms.Api.$project/SlpModularCms.Api.$project.csproj" -c Release
|
||||||
|
done
|
||||||
|
|
||||||
# --- Gate 2: backend tests ---
|
# --- Gate 2: backend tests ---
|
||||||
backend-test:
|
backend-test:
|
||||||
needs: [changes, backend-build]
|
needs: [changes, backend-build]
|
||||||
if: needs.changes.outputs.backend == 'true'
|
if: needs.changes.outputs.backend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
# Added for SlpModularCms.Api.Tests (slpsoftware-api feature, NFR-CS-01): its pipeline
|
# Added for SlpModularCms.Api.Tests (slpsoftware-api feature, NFR-CS-01): its pipeline
|
||||||
# regression tests boot the real Api host via WebApplicationFactory, which unconditionally
|
# regression tests boot the real Api host via WebApplicationFactory, which unconditionally
|
||||||
# runs CmsHost.ConfigurePipeline's startup migration (MigrateCoreDatabase) -- unlike every
|
# runs CmsHost.ConfigurePipeline's startup migration (MigrateCoreDatabase) -- unlike every
|
||||||
@@ -148,56 +189,54 @@ jobs:
|
|||||||
# database. Without a real, reachable MariaDB, those tests fail on the connection itself
|
# database. Without a real, reachable MariaDB, those tests fail on the connection itself
|
||||||
# before any assertion runs.
|
# before any assertion runs.
|
||||||
#
|
#
|
||||||
# A `services:` block was tried first and rejected: this runner uses host networking for
|
# The database is a job-level `services:` container, so the job needs no container-engine socket (the PC
|
||||||
# job AND service containers ("--network and --net in the options will be ignored" in the
|
# runner has no /var/run/docker.sock in its job containers; a manual `docker run` failed there). The server
|
||||||
# job log), so the `ports:` mapping was silently ignored, and the mariadb:11 service ended
|
# listens on 3308 (MYSQL_TCP_PORT) instead of 3306: on the Pi runner job and service containers share the
|
||||||
# up sharing the host's network namespace directly on port 3306 -- which something else on
|
# host's network namespace (host networking), where the host's own database already answers on 3306 -- the
|
||||||
# this runner already answers on (root auth was rejected by a server that was clearly NOT
|
# reason the first `services:` attempt there failed. On a runner with a separate job network the service is
|
||||||
# the freshly-initialized container: "Access denied ... using password: YES" against a
|
# reached by its name `mariadb`; with host networking it is reached on 127.0.0.1 (resolved in the test step).
|
||||||
# password nothing but this job ever set). An explicitly `docker run` container below,
|
services:
|
||||||
# published on host port 3307 instead of 3306, avoids that collision entirely.
|
mariadb:
|
||||||
|
image: mariadb:11
|
||||||
|
env:
|
||||||
|
MARIADB_ROOT_PASSWORD: ci_test_password
|
||||||
|
MARIADB_DATABASE: SlpModularCms
|
||||||
|
MYSQL_TCP_PORT: '3308'
|
||||||
|
options: >-
|
||||||
|
--health-cmd="mariadb-admin ping -uroot -pci_test_password --silent"
|
||||||
|
--health-interval=3s --health-timeout=3s --health-retries=40
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-dotnet@v4
|
- uses: actions/setup-dotnet@v4
|
||||||
with:
|
with:
|
||||||
dotnet-version: ${{ env.DOTNET_VERSION }}
|
dotnet-version: ${{ env.DOTNET_VERSION }}
|
||||||
- name: Start MariaDB for SlpModularCms.Api.Tests
|
- name: Test (Release)
|
||||||
|
shell: bash
|
||||||
|
# ConnectionStrings__DefaultConnection overrides the placeholder in appsettings.Development.json for this CI
|
||||||
|
# run only (environment variables are applied after appsettings.*.json), so it reaches
|
||||||
|
# SlpModularCms.Api.Tests' WebApplicationFactory without touching a committed appsettings file.
|
||||||
run: |
|
run: |
|
||||||
docker run -d --name ci-mariadb \
|
HOST=127.0.0.1
|
||||||
-e MARIADB_ROOT_PASSWORD=ci_test_password \
|
if getent hosts mariadb >/dev/null 2>&1; then HOST=mariadb; fi
|
||||||
-e MARIADB_DATABASE=SlpModularCms \
|
echo "Waiting for MariaDB on $HOST:3308"
|
||||||
-p 3307:3306 \
|
for i in $(seq 1 60); do
|
||||||
mariadb:11
|
if (echo > "/dev/tcp/$HOST/3308") 2>/dev/null; then echo "MariaDB is accepting connections."; break; fi
|
||||||
for i in $(seq 1 30); do
|
|
||||||
# mariadb:11 does not provide a `mysqladmin` alias -- verified locally against this
|
|
||||||
# exact image; the correct binary here is `mariadb-admin`.
|
|
||||||
if docker exec ci-mariadb mariadb-admin ping -uroot -pci_test_password --silent 2>/dev/null; then
|
|
||||||
echo "MariaDB is ready."
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
echo "Waiting for MariaDB... ($i/30)"
|
|
||||||
sleep 2
|
sleep 2
|
||||||
done
|
done
|
||||||
- name: Test (Release)
|
export ConnectionStrings__DefaultConnection="Server=$HOST;Port=3308;Database=SlpModularCms;Uid=root;Pwd=ci_test_password"
|
||||||
env:
|
dotnet test SlpModularCms.Ci.slnf -c Release
|
||||||
# Overrides the placeholder in SlpModularCms.Api/appsettings.Development.json for this
|
|
||||||
# CI run only -- ASP.NET Core's configuration layering applies environment variables
|
|
||||||
# after appsettings.*.json, so this reaches SlpModularCms.Api.Tests' WebApplicationFactory
|
|
||||||
# without touching any committed appsettings file. Port 3307, not 3306 -- see above.
|
|
||||||
ConnectionStrings__DefaultConnection: "Server=127.0.0.1;Port=3307;Database=SlpModularCms;Uid=root;Pwd=ci_test_password"
|
|
||||||
run: dotnet test SlpModularCms.sln -c Release
|
|
||||||
- name: Stop MariaDB for SlpModularCms.Api.Tests
|
|
||||||
if: always()
|
|
||||||
run: docker rm -f ci-mariadb || true
|
|
||||||
|
|
||||||
# --- Gate 3: vulnerability scan ---
|
# --- Gate 3: vulnerability scan ---
|
||||||
# `dotnet list package --vulnerable` always exits 0, even when it reports vulnerabilities, so the
|
# `dotnet list package --vulnerable` always exits 0, even when it reports vulnerabilities, so the
|
||||||
# step greps its own output and fails deliberately (FR-22, D-12, OPEN-03 — closed by pinning
|
# step greps its own output and fails deliberately (FR-22, D-12, OPEN-03 — closed by pinning
|
||||||
# Microsoft.OpenApi and System.Security.Cryptography.Xml in the relevant .csproj files).
|
# Microsoft.OpenApi and System.Security.Cryptography.Xml in the relevant .csproj files).
|
||||||
# Runner labels: `ubuntu-latest` exists only on the Pi (linux-arm64). The independent jobs below (vulnerability-scan,
|
# Runner labels: a job runs on a runner that has ALL of its runs-on labels.
|
||||||
# frontend-*) use `linux`, which the Pi and the desktop runner (x64) both carry, so they can run in parallel. They need no
|
# Pi runner: linux-arm64, ubuntu-latest, global, linux, arm64, podman, raspberry-pi
|
||||||
# arm64 artefact and each does its own `pnpm install`. NOT moved: backend-test (docker mariadb), publish-* (linux-arm64
|
# PC runner: global, linux, x64, podman, bryan-desktop
|
||||||
# artefacts for the Pi) and deploy-* (reusable deploy workflow).
|
# Every job uses `linux` so that any runner (PC, Pi, future ones) can pick it up; no job assumes the host
|
||||||
|
# architecture or a specific user: publish-* cross-publishes with an explicit `-r linux-arm64`, deploy-scp.yaml only
|
||||||
|
# installs missing tools and only uses sudo when needed, backend-test uses a services: container (no engine socket needed).
|
||||||
|
# Use `raspberry-pi` only for a job that demonstrably cannot run elsewhere, and say why in a comment.
|
||||||
vulnerability-scan:
|
vulnerability-scan:
|
||||||
needs: changes
|
needs: changes
|
||||||
if: needs.changes.outputs.backend == 'true'
|
if: needs.changes.outputs.backend == 'true'
|
||||||
@@ -244,7 +283,7 @@ jobs:
|
|||||||
# --- Gate 4: frontend build ---
|
# --- Gate 4: frontend build ---
|
||||||
# Validates the frontend compiles on its own, independent of any environment. The actual
|
# Validates the frontend compiles on its own, independent of any environment. The actual
|
||||||
# per-environment deployable artifact is produced later by each publish job's own "Build admin
|
# per-environment deployable artifact is produced later by each publish job's own "Build admin
|
||||||
# frontend" step (publish-test / publish-production, below), which builds frontend/ again with
|
# frontend" step (publish-sls-test / publish-sls-production, below), which builds frontend/ again with
|
||||||
# that environment's Vite variables set and copies the result into wwwroot/admin before
|
# that environment's Vite variables set and copies the result into wwwroot/admin before
|
||||||
# `dotnet publish` runs — see that step's comment for why this isn't an MSBuild target instead.
|
# `dotnet publish` runs — see that step's comment for why this isn't an MSBuild target instead.
|
||||||
frontend-build:
|
frontend-build:
|
||||||
@@ -342,7 +381,7 @@ jobs:
|
|||||||
# kept in sync with the host's real SecurityHeaders__AllowedScriptOrigins__0 env var (D-16). This
|
# kept in sync with the host's real SecurityHeaders__AllowedScriptOrigins__0 env var (D-16). This
|
||||||
# gate cannot see the actual runtime CSP configuration; it only catches drift between the frontend
|
# gate cannot see the actual runtime CSP configuration; it only catches drift between the frontend
|
||||||
# build and what this variable claims the CSP allows.
|
# build and what this variable claims the CSP allows.
|
||||||
publish-test:
|
publish-sls-test:
|
||||||
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
||||||
# always() bypasses the automatic skip-cascade from a gate job that was itself skipped (because
|
# always() bypasses the automatic skip-cascade from a gate job that was itself skipped (because
|
||||||
# its side of the repo didn't change). Gitea Actions only implements always() from the GitHub
|
# its side of the repo didn't change). Gitea Actions only implements always() from the GitHub
|
||||||
@@ -350,9 +389,9 @@ jobs:
|
|||||||
# gate's outcome is checked explicitly via needs.<job>.result instead: a skipped gate is fine,
|
# gate's outcome is checked explicitly via needs.<job>.result instead: a skipped gate is fine,
|
||||||
# but a gate that actually ran and failed or was cancelled still blocks the publish. The
|
# but a gate that actually ran and failed or was cancelled still blocks the publish. The
|
||||||
# changes.outputs check makes sure there's something to publish at all: a run that touched
|
# changes.outputs check makes sure there's something to publish at all: a run that touched
|
||||||
# neither backend nor frontend has nothing new to deploy. The final line skips this build on a
|
# neither backend nor frontend has nothing new to deploy. The last two lines build this site only when a
|
||||||
# manual workflow_dispatch run that didn't check deploy_test — building and uploading a test
|
# deploy will use it: never on a pull_request (the pull request builds and tests the master CMS only) and, on a
|
||||||
# artifact nobody is going to deploy is wasted work; push/PR runs are unaffected.
|
# manual workflow_dispatch run, only when deploy_sls_test is checked.
|
||||||
if: |
|
if: |
|
||||||
always() &&
|
always() &&
|
||||||
needs.changes.result == 'success' &&
|
needs.changes.result == 'success' &&
|
||||||
@@ -363,8 +402,9 @@ jobs:
|
|||||||
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
|
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
|
||||||
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
|
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
|
||||||
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
|
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
|
||||||
(github.event_name != 'workflow_dispatch' || github.event.inputs.deploy_test == 'true')
|
github.event_name != 'pull_request' &&
|
||||||
runs-on: ubuntu-latest
|
(github.event_name != 'workflow_dispatch' || github.event.inputs.deploy_sls_test == 'true')
|
||||||
|
runs-on: linux
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-dotnet@v4
|
- uses: actions/setup-dotnet@v4
|
||||||
@@ -399,6 +439,8 @@ jobs:
|
|||||||
working-directory: frontend
|
working-directory: frontend
|
||||||
env:
|
env:
|
||||||
VITE_APP_ENV: test
|
VITE_APP_ENV: test
|
||||||
|
VITE_APP_TITLE: SLP Software
|
||||||
|
VITE_THEME: slpsoftware
|
||||||
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
|
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
|
||||||
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_TEST }}
|
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_TEST }}
|
||||||
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
|
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
|
||||||
@@ -412,21 +454,21 @@ jobs:
|
|||||||
working-directory: src/SlpModularCms.Api.SlpSoftware
|
working-directory: src/SlpModularCms.Api.SlpSoftware
|
||||||
run: >
|
run: >
|
||||||
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
|
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
|
||||||
-o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_TEST }}
|
-o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_SLS_TEST }}
|
||||||
|
|
||||||
- name: Upload publish artifact
|
- name: Upload publish artifact
|
||||||
uses: actions/upload-artifact@v3
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: ${{ env.ARTIFACT_NAME_TEST }}
|
name: ${{ env.ARTIFACT_NAME_SLS_TEST }}
|
||||||
path: ${{ env.ARTIFACT_NAME_TEST }}
|
path: ${{ env.ARTIFACT_NAME_SLS_TEST }}
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
|
|
||||||
# Same as publish-test, but only for a manual workflow_dispatch run with deploy_production set —
|
# Same as publish-sls-test, but only for a manual workflow_dispatch run with deploy_sls_production set —
|
||||||
# a distinct job rather than a parameterized reuse of publish-test, because VITE_APP_ENV is a
|
# a distinct job rather than a parameterized reuse of publish-sls-test, because VITE_APP_ENV is a
|
||||||
# Vite build-time value: one dist/ bundle cannot be tagged as both 'test' and 'production' (FR-05).
|
# Vite build-time value: one dist/ bundle cannot be tagged as both 'test' and 'production' (FR-05).
|
||||||
publish-production:
|
publish-sls-production:
|
||||||
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
||||||
# See publish-test's comment above on why this checks needs.<job>.result explicitly instead of
|
# See publish-sls-test's comment above on why this checks needs.<job>.result explicitly instead of
|
||||||
# failure()/cancelled(), which Gitea Actions doesn't support.
|
# failure()/cancelled(), which Gitea Actions doesn't support.
|
||||||
if: |
|
if: |
|
||||||
always() &&
|
always() &&
|
||||||
@@ -437,9 +479,9 @@ jobs:
|
|||||||
needs.frontend-build.result != 'failure' && needs.frontend-build.result != 'cancelled' &&
|
needs.frontend-build.result != 'failure' && needs.frontend-build.result != 'cancelled' &&
|
||||||
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
|
needs.frontend-test.result != 'failure' && needs.frontend-test.result != 'cancelled' &&
|
||||||
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
|
needs.frontend-lint.result != 'failure' && needs.frontend-lint.result != 'cancelled' &&
|
||||||
github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_production == 'true' &&
|
github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_production == 'true' &&
|
||||||
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true')
|
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true')
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-dotnet@v4
|
- uses: actions/setup-dotnet@v4
|
||||||
@@ -462,12 +504,14 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# See publish-test's "Build admin frontend" step for why this runs as its own step ahead of
|
# See publish-sls-test's "Build admin frontend" step for why this runs as its own step ahead of
|
||||||
# dotnet publish rather than an MSBuild target.
|
# dotnet publish rather than an MSBuild target.
|
||||||
- name: Build admin frontend
|
- name: Build admin frontend
|
||||||
working-directory: frontend
|
working-directory: frontend
|
||||||
env:
|
env:
|
||||||
VITE_APP_ENV: production
|
VITE_APP_ENV: production
|
||||||
|
VITE_APP_TITLE: SLP Software
|
||||||
|
VITE_THEME: slpsoftware
|
||||||
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
|
VITE_UMAMI_SCRIPT_URL: ${{ vars.VITE_UMAMI_SCRIPT_URL }}
|
||||||
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_PRODUCTION }}
|
VITE_UMAMI_WEBSITE_ID: ${{ vars.VITE_UMAMI_WEBSITE_ID_PRODUCTION }}
|
||||||
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
|
VITE_SENTRY_DSN: ${{ vars.VITE_SENTRY_DSN }}
|
||||||
@@ -481,46 +525,50 @@ jobs:
|
|||||||
working-directory: src/SlpModularCms.Api.SlpSoftware
|
working-directory: src/SlpModularCms.Api.SlpSoftware
|
||||||
run: >
|
run: >
|
||||||
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
|
dotnet publish -c Release -r ${{ env.PUBLISH_RID }} --self-contained false
|
||||||
-o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_PRODUCTION }}
|
-o ${{ github.workspace }}/${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
|
||||||
|
|
||||||
- name: Upload publish artifact
|
- name: Upload publish artifact
|
||||||
uses: actions/upload-artifact@v3
|
uses: actions/upload-artifact@v3
|
||||||
with:
|
with:
|
||||||
name: ${{ env.ARTIFACT_NAME_PRODUCTION }}
|
name: ${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
|
||||||
path: ${{ env.ARTIFACT_NAME_PRODUCTION }}
|
path: ${{ env.ARTIFACT_NAME_SLS_PRODUCTION }}
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
|
|
||||||
# Automatic test deploy on every push to master (unchanged — a merge should reach test without
|
# Automatic test deploy on every push to master (unchanged — a merge should reach test without
|
||||||
# extra steps). A manual workflow_dispatch run only deploys to test when deploy_test is checked,
|
# extra steps). A manual workflow_dispatch run only deploys to test when deploy_sls_test is checked,
|
||||||
# since a dispatch run is often just re-running CI/production, not a new test build (FR-03, D-01,
|
# since a dispatch run is often just re-running CI/production, not a new test build (FR-03, D-01,
|
||||||
# D-09).
|
# D-09).
|
||||||
deploy-test:
|
# deploy_path / service_name / health_check_url come straight from the Gitea variables, NOT from the `config-sls` job
|
||||||
needs: [publish-test, config]
|
# outputs: a job output whose value contains a secret value (here most likely the deploy account name inside the
|
||||||
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
|
# path) is dropped by the runner, so the reusable workflow received an empty deploy_path ("/releases"). The
|
||||||
|
# `config-sls` outputs are still used for the artifact and environment names.
|
||||||
|
deploy-sls-test:
|
||||||
|
needs: [publish-sls-test, config-sls]
|
||||||
|
if: (github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master')
|
||||||
uses: ./.gitea/workflows/deploy-scp.yaml
|
uses: ./.gitea/workflows/deploy-scp.yaml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
with:
|
with:
|
||||||
artifact_name: ${{ needs.config.outputs.artifact_name_test }}
|
artifact_name: ${{ needs.config-sls.outputs.artifact_name_sls_test }}
|
||||||
environment: ${{ needs.config.outputs.deploy_environment_test }}
|
environment: ${{ needs.config-sls.outputs.deploy_environment_sls_test }}
|
||||||
deploy_path: ${{ needs.config.outputs.deploy_path_test }}
|
deploy_path: ${{ vars.DEPLOY_PATH_TEST }}
|
||||||
service_name: ${{ needs.config.outputs.service_name_test }}
|
service_name: ${{ vars.SERVICE_NAME_TEST }}
|
||||||
health_check_url: ${{ needs.config.outputs.health_check_url_test }}
|
health_check_url: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||||
run_db_backup: false
|
run_db_backup: false
|
||||||
|
|
||||||
# Production deploy ONLY on an explicit workflow_dispatch run with deploy_production checked
|
# Production deploy ONLY on an explicit workflow_dispatch run with deploy_sls_production checked
|
||||||
# (FR-04, D-09) — never reachable from a plain push to master, so pushing cannot deploy production
|
# (FR-04, D-09) — never reachable from a plain push to master, so pushing cannot deploy production
|
||||||
# under any circumstance.
|
# under any circumstance.
|
||||||
deploy-production:
|
deploy-sls-production:
|
||||||
needs: [publish-production, config]
|
needs: [publish-sls-production, config-sls]
|
||||||
if: github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_production == 'true'
|
if: github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_sls_production == 'true'
|
||||||
uses: ./.gitea/workflows/deploy-scp.yaml
|
uses: ./.gitea/workflows/deploy-scp.yaml
|
||||||
secrets: inherit
|
secrets: inherit
|
||||||
with:
|
with:
|
||||||
artifact_name: ${{ needs.config.outputs.artifact_name_production }}
|
artifact_name: ${{ needs.config-sls.outputs.artifact_name_sls_production }}
|
||||||
environment: ${{ needs.config.outputs.deploy_environment_production }}
|
environment: ${{ needs.config-sls.outputs.deploy_environment_sls_production }}
|
||||||
deploy_path: ${{ needs.config.outputs.deploy_path_production }}
|
deploy_path: ${{ vars.DEPLOY_PATH_PRODUCTION }}
|
||||||
service_name: ${{ needs.config.outputs.service_name_production }}
|
service_name: ${{ vars.SERVICE_NAME_PRODUCTION }}
|
||||||
health_check_url: ${{ needs.config.outputs.health_check_url_production }}
|
health_check_url: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
|
||||||
run_db_backup: true
|
run_db_backup: true
|
||||||
|
|
||||||
# ==========================================================================================
|
# ==========================================================================================
|
||||||
@@ -537,7 +585,7 @@ jobs:
|
|||||||
# ==========================================================================================
|
# ==========================================================================================
|
||||||
config-asf:
|
config-asf:
|
||||||
if: ${{ vars.ASF_TEST_DEPLOY_ENABLED == 'true' }}
|
if: ${{ vars.ASF_TEST_DEPLOY_ENABLED == 'true' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
outputs:
|
outputs:
|
||||||
deploy_path: ${{ steps.set.outputs.deploy_path }}
|
deploy_path: ${{ steps.set.outputs.deploy_path }}
|
||||||
service_name: ${{ steps.set.outputs.service_name }}
|
service_name: ${{ steps.set.outputs.service_name }}
|
||||||
@@ -561,7 +609,7 @@ jobs:
|
|||||||
|
|
||||||
publish-asf-test:
|
publish-asf-test:
|
||||||
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
needs: [changes, backend-build, backend-test, vulnerability-scan, frontend-build, frontend-test, frontend-lint]
|
||||||
# Same gate handling as publish-test (see there for why always() and explicit results), plus the
|
# Same gate handling as publish-sls-test (see there for why always() and explicit results), plus the
|
||||||
# ASF switch, and built only when it will actually be deployed.
|
# ASF switch, and built only when it will actually be deployed.
|
||||||
if: |
|
if: |
|
||||||
always() &&
|
always() &&
|
||||||
@@ -576,7 +624,7 @@ jobs:
|
|||||||
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
|
(needs.changes.outputs.backend == 'true' || needs.changes.outputs.frontend == 'true') &&
|
||||||
((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') ||
|
((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') ||
|
||||||
(github.event_name == 'push' && github.ref == 'refs/heads/master'))
|
(github.event_name == 'push' && github.ref == 'refs/heads/master'))
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-dotnet@v4
|
- uses: actions/setup-dotnet@v4
|
||||||
@@ -590,7 +638,7 @@ jobs:
|
|||||||
version: ${{ env.PNPM_VERSION }}
|
version: ${{ env.PNPM_VERSION }}
|
||||||
|
|
||||||
# Admin SPA with the ASF theme and Dutch as the default language. Lands in wwwroot/admin
|
# Admin SPA with the ASF theme and Dutch as the default language. Lands in wwwroot/admin
|
||||||
# BEFORE dotnet publish, for the same reason as in publish-test. No Umami for the admin.
|
# BEFORE dotnet publish, for the same reason as in publish-sls-test. No Umami for the admin.
|
||||||
- name: Build admin frontend (ASF theme)
|
- name: Build admin frontend (ASF theme)
|
||||||
working-directory: frontend
|
working-directory: frontend
|
||||||
env:
|
env:
|
||||||
@@ -618,6 +666,8 @@ jobs:
|
|||||||
path: app-asf-test
|
path: app-asf-test
|
||||||
retention-days: 1
|
retention-days: 1
|
||||||
|
|
||||||
|
# Path/service/health straight from the Gitea variables, like deploy-sls-test (a job output containing a secret value,
|
||||||
|
# here the deploy account name in the path, arrives empty). config-asf still validates that they are set.
|
||||||
deploy-asf-test:
|
deploy-asf-test:
|
||||||
needs: [publish-asf-test, config-asf]
|
needs: [publish-asf-test, config-asf]
|
||||||
if: vars.ASF_TEST_DEPLOY_ENABLED == 'true' && ((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master'))
|
if: vars.ASF_TEST_DEPLOY_ENABLED == 'true' && ((github.event_name == 'workflow_dispatch' && github.event.inputs.deploy_asf_test == 'true') || (github.event_name == 'push' && github.ref == 'refs/heads/master'))
|
||||||
@@ -626,7 +676,32 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
artifact_name: app-asf-test
|
artifact_name: app-asf-test
|
||||||
environment: test
|
environment: test
|
||||||
deploy_path: ${{ needs.config-asf.outputs.deploy_path }}
|
deploy_path: ${{ vars.DEPLOY_PATH_ASF_TEST }}
|
||||||
service_name: ${{ needs.config-asf.outputs.service_name }}
|
service_name: ${{ vars.SERVICE_NAME_ASF_TEST }}
|
||||||
health_check_url: ${{ needs.config-asf.outputs.health_check_url }}
|
health_check_url: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
|
||||||
run_db_backup: false
|
run_db_backup: false
|
||||||
|
|
||||||
|
# --- Smoke tests of the deployed compositions (anonymous requests, see scripts/smoke-site.sh) ---
|
||||||
|
# The CI tests the master CMS; this is the check that the composition of each site that was just deployed to test
|
||||||
|
# is the intended one (modules, website mode, noindex, protected admin routes). A failing smoke test fails the run.
|
||||||
|
smoke-sls-test:
|
||||||
|
needs: [deploy-sls-test]
|
||||||
|
if: always() && needs.deploy-sls-test.result == 'success'
|
||||||
|
runs-on: linux
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Smoke test SLS test
|
||||||
|
env:
|
||||||
|
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||||
|
run: bash scripts/smoke-site.sh "$HEALTH_URL" sls-test
|
||||||
|
|
||||||
|
smoke-asf-test:
|
||||||
|
needs: [deploy-asf-test]
|
||||||
|
if: always() && needs.deploy-asf-test.result == 'success'
|
||||||
|
runs-on: linux
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Smoke test ASF test
|
||||||
|
env:
|
||||||
|
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
|
||||||
|
run: bash scripts/smoke-site.sh "$HEALTH_URL" asf-test
|
||||||
|
|||||||
@@ -40,8 +40,75 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: linux
|
||||||
steps:
|
steps:
|
||||||
|
# Runner-independent: only installs what is missing, and only uses sudo when not already root and sudo exists
|
||||||
|
# (a container on the PC runner has neither sudo nor a need for it; the Pi runner may need it).
|
||||||
|
#
|
||||||
|
# Authentication: the Pi-Main host only allows password login from the Pi runner's address, so every runner other
|
||||||
|
# than that one needs a key. If the secret PI_MAIN_SSH_KEY (private key of the deploy account) is set and works,
|
||||||
|
# the wrappers `rssh` / `rscp` below use it (-i, IdentitiesOnly, BatchMode); otherwise they fall back to sshpass
|
||||||
|
# with the password, which keeps working from the Pi runner. The key lives in a temp directory that is removed
|
||||||
|
# at the end of the job; it is never printed.
|
||||||
|
- name: Ensure ssh tooling and authentication
|
||||||
|
env:
|
||||||
|
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||||
|
SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||||
|
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||||
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
|
SSH_KEY: ${{ secrets.PI_MAIN_SSH_KEY }}
|
||||||
|
IN_DEPLOY_PATH: ${{ inputs.deploy_path }}
|
||||||
|
IN_SERVICE_NAME: ${{ inputs.service_name }}
|
||||||
|
IN_HEALTH_URL: ${{ inputs.health_check_url }}
|
||||||
|
run: |
|
||||||
|
# Inputs are not secret: print them so an empty one is visible, and stop before anything touches the host.
|
||||||
|
echo "Inputs: deploy_path='$IN_DEPLOY_PATH' service_name='$IN_SERVICE_NAME' health_check_url='$IN_HEALTH_URL'"
|
||||||
|
for v in IN_DEPLOY_PATH IN_SERVICE_NAME IN_HEALTH_URL; do
|
||||||
|
if [ -z "${!v}" ]; then echo "Input $v is empty; refusing to deploy."; exit 1; fi
|
||||||
|
done
|
||||||
|
SUDO=""
|
||||||
|
if [ "$(id -u)" != "0" ] && command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
|
||||||
|
if ! command -v sshpass >/dev/null 2>&1 || ! command -v ssh >/dev/null 2>&1 || ! command -v scp >/dev/null 2>&1; then
|
||||||
|
$SUDO apt-get update && $SUDO apt-get install -y sshpass openssh-client
|
||||||
|
fi
|
||||||
|
|
||||||
|
D=$(mktemp -d)
|
||||||
|
mkdir -p "$D/bin"
|
||||||
|
echo "DEPLOY_TMP=$D" >> "$GITHUB_ENV"
|
||||||
|
echo "$D/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
|
if [ -n "$SSH_KEY" ]; then
|
||||||
|
printf '%s\n' "$SSH_KEY" > "$D/key"
|
||||||
|
chmod 600 "$D/key"
|
||||||
|
if ssh -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -o ConnectTimeout=15 \
|
||||||
|
-p "$SSH_PORT" "$SSH_USER@$SSH_HOST" true; then
|
||||||
|
touch "$D/key_ok"
|
||||||
|
echo "Authentication: deploy key"
|
||||||
|
else
|
||||||
|
echo "Deploy key rejected or host unreachable with it; falling back to password"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "No deploy key set; using password"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat > "$D/bin/rssh" <<'WRAP'
|
||||||
|
#!/bin/sh
|
||||||
|
D="$(dirname "$0")/.."
|
||||||
|
if [ -f "$D/key_ok" ]; then
|
||||||
|
exec ssh -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" "$@"
|
||||||
|
fi
|
||||||
|
exec sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no -p "$SSH_PORT" "$SSH_USER@$SSH_HOST" "$@"
|
||||||
|
WRAP
|
||||||
|
cat > "$D/bin/rscp" <<'WRAP'
|
||||||
|
#!/bin/sh
|
||||||
|
D="$(dirname "$0")/.."
|
||||||
|
if [ -f "$D/key_ok" ]; then
|
||||||
|
exec scp -i "$D/key" -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=no -P "$SSH_PORT" "$@"
|
||||||
|
fi
|
||||||
|
exec sshpass -p "$SSH_PASS" scp -o StrictHostKeyChecking=no -P "$SSH_PORT" "$@"
|
||||||
|
WRAP
|
||||||
|
chmod +x "$D/bin/rssh" "$D/bin/rscp"
|
||||||
|
|
||||||
- name: Compute release timestamp
|
- name: Compute release timestamp
|
||||||
id: release
|
id: release
|
||||||
run: echo "timestamp=$(date -u +%Y%m%d%H%M%S)" >> "$GITHUB_OUTPUT"
|
run: echo "timestamp=$(date -u +%Y%m%d%H%M%S)" >> "$GITHUB_OUTPUT"
|
||||||
@@ -68,11 +135,7 @@ jobs:
|
|||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
echo "Environment: ${{ inputs.environment }}"
|
echo "Environment: ${{ inputs.environment }}"
|
||||||
sudo apt-get update && sudo apt-get install -y sshpass
|
rssh \
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"bash ~/scripts/backup-slpsoftware-db.sh ${{ inputs.environment }}"
|
"bash ~/scripts/backup-slpsoftware-db.sh ${{ inputs.environment }}"
|
||||||
|
|
||||||
# Uploads the published output to a fresh, timestamped release directory rather than
|
# Uploads the published output to a fresh, timestamped release directory rather than
|
||||||
@@ -92,16 +155,10 @@ jobs:
|
|||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
echo "Environment: ${{ inputs.environment }}, transport: ${{ inputs.transport }}"
|
echo "Environment: ${{ inputs.environment }}, transport: ${{ inputs.transport }}"
|
||||||
sudo apt-get update && sudo apt-get install -y sshpass
|
|
||||||
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
rssh \
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"mkdir -p $RELEASE_DIR"
|
"mkdir -p $RELEASE_DIR"
|
||||||
sshpass -p "$SSH_PASS" scp \
|
rscp \
|
||||||
-P "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
-r ${{ inputs.artifact_name }}/* \
|
-r ${{ inputs.artifact_name }}/* \
|
||||||
"$SSH_USER@$SSH_HOST:$RELEASE_DIR/"
|
"$SSH_USER@$SSH_HOST:$RELEASE_DIR/"
|
||||||
|
|
||||||
@@ -123,10 +180,7 @@ jobs:
|
|||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
rssh \
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"mkdir -p ${{ inputs.deploy_path }}/shared/wwwroot-web && \
|
"mkdir -p ${{ inputs.deploy_path }}/shared/wwwroot-web && \
|
||||||
mkdir -p $RELEASE_DIR/wwwroot && \
|
mkdir -p $RELEASE_DIR/wwwroot && \
|
||||||
rm -rf $RELEASE_DIR/wwwroot/web && \
|
rm -rf $RELEASE_DIR/wwwroot/web && \
|
||||||
@@ -150,10 +204,7 @@ jobs:
|
|||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
rssh \
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"mkdir -p ${{ inputs.deploy_path }}/shared/modules && \
|
"mkdir -p ${{ inputs.deploy_path }}/shared/modules && \
|
||||||
ls ${{ inputs.deploy_path }}/shared/modules/*.dll 2>/dev/null | while read -r f; do \
|
ls ${{ inputs.deploy_path }}/shared/modules/*.dll 2>/dev/null | while read -r f; do \
|
||||||
name=\$(basename \"\$f\"); \
|
name=\$(basename \"\$f\"); \
|
||||||
@@ -172,10 +223,7 @@ jobs:
|
|||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
RELEASE_DIR="${{ inputs.deploy_path }}/releases/${{ steps.release.outputs.timestamp }}"
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
rssh \
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \
|
"ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \
|
||||||
systemctl --user restart ${{ inputs.service_name }}"
|
systemctl --user restart ${{ inputs.service_name }}"
|
||||||
|
|
||||||
@@ -206,8 +254,9 @@ jobs:
|
|||||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||||
run: |
|
run: |
|
||||||
sshpass -p "$SSH_PASS" ssh \
|
rssh \
|
||||||
-p "$SSH_PORT" \
|
|
||||||
-o StrictHostKeyChecking=no \
|
|
||||||
"$SSH_USER@$SSH_HOST" \
|
|
||||||
"cd ${{ inputs.deploy_path }}/releases && ls -1t | tail -n +3 | xargs -r rm -rf"
|
"cd ${{ inputs.deploy_path }}/releases && ls -1t | tail -n +3 | xargs -r rm -rf"
|
||||||
|
|
||||||
|
- name: Remove deploy key
|
||||||
|
if: always()
|
||||||
|
run: rm -rf "${DEPLOY_TMP:-/nonexistent}"
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ Een modulaire monolith CMS gebouwd met .NET 10.
|
|||||||
## Projectstructuur
|
## Projectstructuur
|
||||||
|
|
||||||
- `src/SlpModularCms.Api`: De host applicatie en API shell (lokale ontwikkeling / dev-host).
|
- `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.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 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.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/` (`Website:Mode=PrerenderedPages`) plus de admin met het thema `asf` op `/admin`. Lokaal op poort `5200`, eigen database (`appsettings.Development.json`). Geen eigen testproject: het gedrag zit in Core en de modules en wordt getest op de master-`SlpModularCms.Api` (alle modules); de samenstelling en standaardwaarden van deze site worden getest in `SlpModularCms.Api.Tests` (`SiteContractTests`, `AsfVariantPipelineTests`) en `SlpModularCms.Modules.Contact.Tests` (`SiteVariantContactTests`). `Website:Mode=PrerenderedPages` staat in de eigen `appsettings.json`.
|
||||||
- `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.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.
|
- `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.
|
- `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
|
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.
|
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.
|
- 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`.
|
- `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)
|
## 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.
|
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.
|
Voor lokale ontwikkeling verandert er niets: `pnpm dev` blijft op `http://localhost:5173` draaien zonder `/admin`-prefix.
|
||||||
|
|
||||||
### 1. Build & Publish
|
### 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.
|
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.
|
||||||
|
|
||||||
@@ -345,7 +376,7 @@ In productie moeten gevoelige instellingen worden doorgegeven via Environment Va
|
|||||||
- `Observability__SentryDsn` — leeg is een normale, ondersteunde staat: Sentry wordt dan overgeslagen en alleen console-logging blijft actief
|
- `Observability__SentryDsn` — leeg is een normale, ondersteunde staat: Sentry wordt dan overgeslagen en alleen console-logging blijft actief
|
||||||
- `SecurityHeaders__AllowedScriptOrigins__0`, `SecurityHeaders__AllowedConnectOrigins__0`, ... — externe origins die de CSP van `/admin` en `/api/v1` mag toestaan (bijv. de Umami-scripthost en Sentry's ingest-endpoint). Zie `appsettings.json → SecurityHeaders` voor de volledige optiesvorm; een onbekende `PathPolicies`-policy-naam laat de applicatie bij **opstarten** falen, niet pas bij de eerste request
|
- `SecurityHeaders__AllowedScriptOrigins__0`, `SecurityHeaders__AllowedConnectOrigins__0`, ... — externe origins die de CSP van `/admin` en `/api/v1` mag toestaan (bijv. de Umami-scripthost en Sentry's ingest-endpoint). Zie `appsettings.json → SecurityHeaders` voor de volledige optiesvorm; een onbekende `PathPolicies`-policy-naam laat de applicatie bij **opstarten** falen, niet pas bij de eerste request
|
||||||
|
|
||||||
- **Voorgerenderde website (`WebsiteMode.PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md).
|
- **Voorgerenderde website (`Website:Mode=PrerenderedPages`)** — een client kiest dit in zijn `Program.cs` via `CmsHostOptions` (standaard `SpaFallback`: alles blijft zoals het was). Instellingen voor deze modus: `Website__NoIndex=true` (testinstantie: `X-Robots-Tag` plus `robots.txt` met `Disallow: /`), `SecurityHeaders__DefaultPolicy=StrictSite` met `SecurityHeaders__AllowedSiteScriptOrigins__0`, `SecurityHeaders__AllowedSiteConnectOrigins__0`, ... (alleen gebruikt door `StrictSite`). Logging van de website (301's en 404's op `Information`) gaat via de logger-categorie `SlpModularCms.Website`: zet per omgeving `Website__LogLevel` (test `Information`, standaard en productie `Warning`; leeg = `Logging:LogLevel` beslist). Gebruik niet `Logging__LogLevel__SlpModularCms.Website` in een systemd-`EnvironmentFile`: een variabelenaam met een punt wordt daar genegeerd. Gedrag per pad staat in [`WEBSITE_WORKSPACE.md`](WEBSITE_WORKSPACE.md).
|
||||||
|
|
||||||
### 2a. Data Protection key ring (Master CMS Module)
|
### 2a. Data Protection key ring (Master CMS Module)
|
||||||
De API keys van geregistreerde slaves worden versleuteld opgeslagen met ASP.NET Core Data Protection. De key ring wordt **automatisch** persistent opgeslagen in de database (`PersistKeysToDbContext`, met een expliciete, stabiele applicatie-discriminator) — dit hoeft niet meer apart geconfigureerd te worden. Dit is bewust zo gebouwd omdat de atomische release-switch (zie hierboven) bij elke deploy een nieuwe content-root-map gebruikt: zonder een database-backed key ring zou dat elke keer de key ring weggooien en alle opgeslagen slave-API-keys onleesbaar maken.
|
De API keys van geregistreerde slaves worden versleuteld opgeslagen met ASP.NET Core Data Protection. De key ring wordt **automatisch** persistent opgeslagen in de database (`PersistKeysToDbContext`, met een expliciete, stabiele applicatie-discriminator) — dit hoeft niet meer apart geconfigureerd te worden. Dit is bewust zo gebouwd omdat de atomische release-switch (zie hierboven) bij elke deploy een nieuwe content-root-map gebruikt: zonder een database-backed key ring zou dat elke keer de key ring weggooien en alle opgeslagen slave-API-keys onleesbaar maken.
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"solution": {
|
||||||
|
"path": "SlpModularCms.sln",
|
||||||
|
"projects": [
|
||||||
|
"src\\SlpModularCms.Api\\SlpModularCms.Api.csproj",
|
||||||
|
"src\\SlpModularCms.Core\\SlpModularCms.Core.csproj",
|
||||||
|
"src\\SlpModularCms.Core.Tests\\SlpModularCms.Core.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Availability\\SlpModularCms.Modules.Availability.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Availability.Tests\\SlpModularCms.Modules.Availability.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Identity\\SlpModularCms.Modules.Identity.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Identity.Tests\\SlpModularCms.Modules.Identity.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Master\\SlpModularCms.Modules.Master.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Master.Tests\\SlpModularCms.Modules.Master.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Api.Tests\\SlpModularCms.Api.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Offerings\\SlpModularCms.Modules.Offerings.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Offerings.Tests\\SlpModularCms.Modules.Offerings.Tests.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Contact\\SlpModularCms.Modules.Contact.csproj",
|
||||||
|
"src\\SlpModularCms.Modules.Contact.Tests\\SlpModularCms.Modules.Contact.Tests.csproj"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
-14
@@ -40,7 +40,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Offer
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie", "src\SlpModularCms.Api.AndreaSlopFotografie\SlpModularCms.Api.AndreaSlopFotografie.csproj", "{759EE53D-EECA-4054-A17F-4172B0EC2015}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Api.AndreaSlopFotografie.Tests", "src\SlpModularCms.Api.AndreaSlopFotografie.Tests\SlpModularCms.Api.AndreaSlopFotografie.Tests.csproj", "{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact", "src\SlpModularCms.Modules.Contact\SlpModularCms.Modules.Contact.csproj", "{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlpModularCms.Modules.Contact.Tests", "src\SlpModularCms.Modules.Contact.Tests\SlpModularCms.Modules.Contact.Tests.csproj", "{06C25AF5-D63F-4007-8796-C4BA27940EBA}"
|
||||||
EndProject
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
@@ -232,18 +234,30 @@ Global
|
|||||||
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.Build.0 = Release|Any CPU
|
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = Release|Any CPU
|
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.Build.0 = Release|Any CPU
|
{759EE53D-EECA-4054-A17F-4172B0EC2015}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x64.Build.0 = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.ActiveCfg = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Debug|x86.Build.0 = Debug|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|Any CPU.Build.0 = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.ActiveCfg = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x64.Build.0 = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.ActiveCfg = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B}.Release|x86.Build.0 = Release|Any CPU
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
@@ -266,6 +280,7 @@ Global
|
|||||||
{43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
{43DE02A5-DD13-42D1-9BF9-434E706B8500} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
||||||
{BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
{BF1054BD-DBD7-4D78-B99A-73FDC1362EA5} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
||||||
{759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899}
|
{759EE53D-EECA-4054-A17F-4172B0EC2015} = {D72703E6-B021-4360-B1EE-0E99999B5899}
|
||||||
{DF0FDCFD-2601-4D60-A7F5-198D39DBE57B} = {2F43D186-C7D5-4AB1-B821-4D595CA2ECB3}
|
{59F64DD2-DF30-4F78-A3B7-2AB6A769ED6C} = {30D8F44D-4B6E-4980-8D1F-29D1A64F438C}
|
||||||
|
{06C25AF5-D63F-4007-8796-C4BA27940EBA} = {77DF6642-7863-4D67-BAEE-217EC2D99894}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
EndGlobal
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
| Type | Name | Status | Branch | Affected Components | Session Start |
|
| Type | Name | Status | Branch | Affected Components | Session Start |
|
||||||
|------|------|--------|--------|---------------------|---------------|
|
|------|------|--------|--------|---------------------|---------------|
|
||||||
| Feature | SlpModularCms.Api Implementation (slp-modular-cms-api) | ✅ Complete | unknown | Core, Identity, Availability, Shell | 2026-06-07 |
|
| Feature | SlpModularCms.Api Implementation (slp-modular-cms-api) | ✅ Complete | unknown | Core, Identity, Availability, Shell | 2026-06-07 |
|
||||||
| Feature | CMS Frontend (cms-frontend) | ✅ Complete | unknown | Frontend, Identity (Auth), Availability | 2026-06-16 |
|
| Feature | CMS Frontend (cms-frontend) | ✅ Complete (Build and Test en Operations gesloten 2026-11-16) | unknown | Frontend, Identity (Auth), Availability | 2026-06-16 |
|
||||||
| Feature | Master CMS Module (master-cms-module) | ✅ Complete | unknown | Modules, Availability | 2026-06-26 |
|
| Feature | Master CMS Module (master-cms-module) | ✅ Complete | unknown | Modules, Availability | 2026-06-26 |
|
||||||
| Feature | Tech Debt Backlog (tech-debt-backlog) | 🔵 Inception | unknown | Modules.Master, Frontend | 2026-07-01 |
|
| Feature | Tech Debt Backlog (tech-debt-backlog) | 🔵 Doorlopende backlog (bewust open) | unknown | Modules.Master, Frontend | 2026-07-01 |
|
||||||
| Feature | Local Dev Master/Slave Setup (local-dev-master-slave-setup) | ✅ Complete | unknown | Modules.Master, Api, Frontend | 2026-07-02 |
|
| Feature | Local Dev Master/Slave Setup (local-dev-master-slave-setup) | ✅ Complete | unknown | Modules.Master, Api, Frontend | 2026-07-02 |
|
||||||
| Feature | Gitea Deployment Workflow (gitea-deployment-workflow) | 🟡 Operations (wacht op CI-proef en eerste test-deploy) | feature/gitea-deployment-workflow | CI/CD, Api (hosting/config), Core, Modules, Frontend (build), Docs | 2026-07-27 |
|
| Feature | Gitea Deployment Workflow (gitea-deployment-workflow) | ✅ Complete (CI en test-deploys draaien; productiecontrole in de gezamenlijke checklist, 2026-11-16) | feature/gitea-deployment-workflow | CI/CD, Api (hosting/config), Core, Modules, Frontend (build), Docs | 2026-07-27 |
|
||||||
| Feature | SlpSoftware Production API (slpsoftware-api) | ✅ Complete | feature/slpsoftware-api | Clients (new Api.SlpSoftware), Modules (new Offerings module + Tests), Core (CmsHost), CI/CD (retargeted to Api.SlpSoftware) | 2026-08-02 |
|
| Feature | SlpSoftware Production API (slpsoftware-api) | ✅ Complete | feature/slpsoftware-api | Clients (new Api.SlpSoftware), Modules (new Offerings module + Tests), Core (CmsHost), CI/CD (retargeted to Api.SlpSoftware) | 2026-08-02 |
|
||||||
| Feature | Andrea's site hosting (andreaslop-site-hosting) | ✅ Complete (gemerged naar master via PR #11, 2026-11-10; ASF-productie op IIS apart) | feature/andreaslop-site-hosting | Core (CmsHost, CSP, static content), Clients (new Api.AndreaSlopFotografie), Frontend (theme), CI/CD | 2026-11-06 |
|
| Feature | Andrea's site hosting (andreaslop-site-hosting) | ✅ Complete (gemerged naar master via PR #11, 2026-11-10; ASF-productie op IIS apart) | feature/andreaslop-site-hosting | Core (CmsHost, CSP, static content), Clients (new Api.AndreaSlopFotografie), Frontend (theme), CI/CD | 2026-11-06 |
|
||||||
| Bug | [cms-admin-nine-points](bugs/cms-admin-nine-points/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/andreaslop-site-hosting | Core (auth, invitations), Identity, Availability, Frontend | 2026-11-08 |
|
| Bug | [cms-admin-nine-points](bugs/cms-admin-nine-points/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/andreaslop-site-hosting | Core (auth, invitations), Identity, Availability, Frontend | 2026-11-08 |
|
||||||
@@ -16,3 +16,11 @@
|
|||||||
| Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 |
|
| Bug | [owner-cannot-promote-requester-identity](bugs/owner-cannot-promote-requester-identity/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Identity (UsersController) | 2026-11-08 |
|
||||||
| Bug | [availability-gate-blocks-website-and-admin](bugs/availability-gate-blocks-website-and-admin/bug-fix.md) | ✅ Complete (gemerged via PR #11, 2026-11-10) | feature/identity-email-notifications | Availability (middleware) | 2026-11-09 |
|
| 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 |
|
| 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) | ✅ Afgesloten 2026-11-16 (U1 t/m U12 gebouwd, Build and Test gesloten, Operations in de [gezamenlijke productie-checklist](../docs/release-checklist-productie.md); contactformulier door Bryan op test geaccepteerd; productie wacht op Bryans go) | 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) | ✅ Afgesloten 2026-11-16 (op test; buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | Modules.Offerings (banner met positie top/bottom), openapi, Frontend (admin Aanbiedingen > Banner) | 2026-11-12 |
|
||||||
|
| Feature | [Offering schedule (offering-schedule)](features/offering-schedule/overview.md) | ✅ Afgesloten 2026-11-16 (op test; buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | Modules.Offerings (aan/uit en van/tot per pakket, `/offerings/all`), openapi, Frontend (admin pakketformulier en -lijst) | 2026-11-15 |
|
||||||
|
| Feature | [Website SEO (website-seo)](features/website-seo/overview.md) | ✅ Afgesloten 2026-11-16 (op SLP-test; productie vraagt `Website__NoIndex=false` en `Website__PublicBaseUrl`, zie de productie-checklist) | feature/contact-forms-module | Core (Hosting/Website), Modules.Offerings (index-markers), Api.SlpSoftware (appsettings) | 2026-11-11 |
|
||||||
|
| Feature | [CI bouwt en test alleen het master-CMS (ci-master-pipeline)](features/ci-master-pipeline/overview.md) | ✅ Afgesloten 2026-11-16 (buiten AI-DLC gebouwd en achteraf gedocumenteerd) | feature/contact-forms-module | CI/CD (workflow, slnf, rooktest), Core (Website:Mode), Api (alle modules), Tests (ASF-testproject opgeheven) | 2026-11-15 |
|
||||||
|
| Feature | [ASF: host injecteert in voorgerenderde pagina's (asf-host-injection)](features/asf-host-injection/plan.md) | ✅ Gebouwd en op test (afgesloten 2026-11-16; ASF-productie op IIS is een apart, later plan) | feature/contact-forms-module | Core (Hosting/Website), Modules.Offerings, docs | 2026-11-15 |
|
||||||
|
| Feature | [Vertaalbestanden backend (translation-files)](../docs/translation-files.md) | ✅ Afgesloten 2026-11-16 (stappen 1-8, docs; buiten AI-DLC gebouwd; goedgekeurd door Bryan via SLS-Main; productie via de checklist) | feature/contact-forms-module | Core (Texts, Email, Identity, Hosting), Modules.Availability, Modules.Offerings | 2026-11-15 |
|
||||||
|
| 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)
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Host injection into ASF's prerendered pages (asf-host-injection)
|
||||||
|
|
||||||
|
- **Slug**: asf-host-injection
|
||||||
|
- **Type**: Feature, **proposal; not approved, build not started**
|
||||||
|
- **Status**: **Built** on `feature/contact-forms-module` (commits 7d66944, a136615, ef4fb9d, 4baadf3 and the one after it; tests green locally), **not yet deployed**: needs the website build with the markers and `Website__PublicBaseUrl=https://test.andreaslop.nl` in the ASF-test env file. Before: plan agreed with the ASF session (their counterpart: `AndreaSlopFotografie-packages/aidlc-docs/features/asf-cms-host-injection/plan.md`, section "Host contract"). Bryan accepted the approach (neutral list first, styled cards after hydration; the host writes the list HTML) on 2026-11-15 but said **not to start building yet**: he first reads the plan and finds out whether .NET 10 can run on the hosting package (hosting bundle or self-contained).
|
||||||
|
- **Affected components (planned)**: `SlpModularCms.Core` (`Hosting/Website`: generalise `IndexHtmlInjector`, hook in `PrerenderedSiteMiddleware`), `SlpModularCms.Modules.Offerings` (marker providers), `scripts/smoke-site.sh`, docs
|
||||||
|
- **Documented**: 2026-11-15
|
||||||
|
- **Documentation Language**: English
|
||||||
|
- **Conversation Language**: Dutch (user language)
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Bryan's hosting package has one entry per website: the CMS host is that entry and serves the website, the prerendered pages and `/admin`. So ASF in production also runs entirely through Kestrel (IIS passes every request on, serves no static files and caches no HTML). Packages, banners and (later) gallery data can therefore be written into the prerendered HTML by the host: visible to crawlers within about a minute of a CMS change, without a nightly build. A rebuild webhook stays an option only for build-processed gallery images.
|
||||||
|
|
||||||
|
## Host contract (agreed with ASF)
|
||||||
|
|
||||||
|
All markers are found in one pass; a page without markers and without the authored address is still served as a plain static file. **Fail-open everywhere**: missing marker = nothing; invalid data or a provider failure = the baked page is served.
|
||||||
|
|
||||||
|
| Marker | Host behaviour |
|
||||||
|
|---|---|
|
||||||
|
| `<!--CMS:OFFERINGS-HTML-->…<!--/CMS:OFFERINGS-HTML-->` | Replace the content between the markers by a simple crawlable list from the live offerings (C# template following ASF's "Neutral HTML spec" and their golden files; everything HTML-encoded). The markers stay. |
|
||||||
|
| `<!--CMS:BANNER-TOP-HTML-->…<!--/…-->`, `<!--CMS:BANNER-BOTTOM-HTML-->…<!--/…-->` | Same, from the live banner of that position as `<aside><strong/><span/><a/>`; empty (204) empties the region, so an ended banner disappears at once. |
|
||||||
|
| `<!--CMS:DATA-->` directly followed by the baked `<script type="application/json" id="cms-data">` | Replace the pair by the live block `{"siteUrl":…,"offerings":[…],"banners":{"top":…\|null,"bottom":…\|null}}`, the same shapes as the public GETs, `< > &` and U+2028/9 as `\uXXXX`. `siteUrl` = `Website:PublicBaseUrl`, otherwise `Website:AuthoredBaseUrl`, without a trailing slash. |
|
||||||
|
| `<!--CMS:OFFER-JSON-LD slug="x"-->` directly before `<script type="application/ld+json">` | Parse that block and set `offers.price` (whole euros) from the live offering; no live offering or no price derivable (free text) = remove `offers`. A provider failure leaves the baked block. Invalid JSON is left alone. |
|
||||||
|
| `<span data-cms-price="slug">€ 185</span>` | Replace the text by `€` + U+00A0 + whole euros; unknown slug or no price = unchanged. |
|
||||||
|
|
||||||
|
## One artifact for test and production
|
||||||
|
|
||||||
|
`Website:AuthoredBaseUrl` (`https://andreaslop.nl`, the address ASF's build writes) is replaced by `Website:PublicBaseUrl` in html, `sitemap.xml` and `robots.txt` when the host has a `PublicBaseUrl` that differs (test: `Website__PublicBaseUrl=https://test.andreaslop.nl` in the host's env file). Where the host answers `robots.txt` itself (a `NoIndex` test host) that goes first.
|
||||||
|
|
||||||
|
## Serving and caching
|
||||||
|
|
||||||
|
Injected pages: `Cache-Control: no-cache`, strong ETag from the final body, 304 on `If-None-Match`, no `Last-Modified`; behind the 60-second cache with direct invalidation on every CMS change (offering, banner). The proxy must not cache HTML, must pass `ETag`/`If-None-Match`/304 and `Vary`, and must forward `Host` and `X-Forwarded-*`. Measured on test-ASF (2026-11-15): HTML and `robots.txt` already come from the host (host headers, no `Age`/`X-Cache`), gzip is applied on the way. `/assets/` stays immutable.
|
||||||
|
|
||||||
|
## Open before the build starts
|
||||||
|
|
||||||
|
1. Bryan approves the plan; the ASF golden files (input JSON + expected HTML, with a README and commit) are delivered after that.
|
||||||
|
2. Can .NET 10 run on the hosting package (hosting bundle or self-contained)? Decided by Bryan with the hosting provider.
|
||||||
|
3. IIS production: one pass-through entry (ASP.NET Core Module, no static-file handler or HTML caching in IIS; in-process or out-of-process with `ForwardedHeaders:KnownProxies`), a Windows publish artifact and its own publish job. To be written down once the environment is known and tested against test-ASF.
|
||||||
|
4. Hero and gallery: a separate plan (same-origin images with content-hash URLs, variants and dimensions, preload for LCP); the data model keeps room for it.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
Markers stripped by a build (confirmed not the case for ASF's Vite/TanStack prerender); proxy or IIS caching of HTML; .NET 10 unavailable on the package; the per-base-URL cache keyed from the Host header when no `PublicBaseUrl` is configured (to be capped in this unit); several app instances (invalidation is per process; the 60-second TTL bounds the lag). Estimated effort: about 1.5 days for the host side, plus ASF's front-end rework.
|
||||||
|
|
||||||
|
## As built (2026-11-15)
|
||||||
|
|
||||||
|
| Piece | Where |
|
||||||
|
|---|---|
|
||||||
|
| Marker edits (regions, data block, JSON-LD, inline values, script escaping) | `Core/Hosting/Website/HtmlMarkerEditor.cs` |
|
||||||
|
| Injector for every html/xml/txt file of the prerendered host and for the SpaFallback index.html; caching (60 s, direct invalidation, capped at 256 entries), ETag/304, address replacement, per-part fail-open | `Core/Hosting/Website/HtmlMarkerInjector.cs`; hook in `PrerenderedSiteMiddleware` (`ServeFile`); registered by `AddCmsWebsite` |
|
||||||
|
| Neutral list and banner HTML, price rules (whole euros, `1.250`) | `Offerings/Services/CmsPageHtml.cs`; golden files of the website repo (ASF commit 16027f5) in `Offerings.Tests/Golden/host-injection`, `GoldenHtmlTests` |
|
||||||
|
| Marker transform (regions, `#cms-data` with `siteUrl`, JSON-LD price, `data-cms-price`) | `Offerings/Services/OfferingsHtmlTransform.cs` (`IHtmlPageTransform`) |
|
||||||
|
| Settings | ASF `appsettings.json`: `Website:AuthoredBaseUrl=https://andreaslop.nl`, `Website:PublicBaseUrl` empty (env `Website__PublicBaseUrl`) |
|
||||||
|
| End-to-end test (real database, ASF settings, temporary web root) | `Api.Tests/AsfInjectionPipelineTests` |
|
||||||
|
| Smoke test | `scripts/smoke-site.sh`: unprocessed `CMS:DATA` / `CMS:OFFER-JSON-LD` markers on `/` fail; a data block must carry this host's `siteUrl`; ETag and no-cache on the injected home page |
|
||||||
|
|
||||||
|
Behaviour choices: a successful empty answer empties a region (no live package, no active banner); a failing service leaves the baked content; a package without a derivable price removes `offers` from the JSON-LD (a failing service does not); a file without markers and without the authored address stays a plain static file; 404.html is not injected.
|
||||||
|
|
||||||
|
**Deploy order matters**: set `Website__PublicBaseUrl=https://test.andreaslop.nl` on ASF-test before the first website build with markers is deployed, otherwise the data block's `siteUrl` is the production address and the smoke test fails on purpose.
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# CI builds and tests the master CMS only (ci-master-pipeline)
|
||||||
|
|
||||||
|
- **Slug**: ci-master-pipeline
|
||||||
|
- **Type**: Feature (small, infrastructure), built outside the AI-DLC flow and documented afterwards
|
||||||
|
- **Status**: Pushed on `feature/contact-forms-module` (commits 24168c6, ca46ce2, 612263e, ad8841a); first CI run with the new workflow pending
|
||||||
|
- **Affected components**: `.gitea/workflows/continuous_integration.yaml`, `SlpModularCms.Ci.slnf`, `scripts/smoke-site.sh`, `SlpModularCms.Api` (+ Tests), `SlpModularCms.Core` (`CmsHost`, `CmsHostOptions`), site projects, `SlpModularCms.Modules.Contact.Tests`
|
||||||
|
- **Documented**: 2026-11-15
|
||||||
|
- **Documentation Language**: English
|
||||||
|
- **Conversation Language**: Dutch (user language)
|
||||||
|
|
||||||
|
> Not run through the AI-DLC stages; this file records what the code does. Decision by Bryan (relayed by SLS-Main): the CI builds and tests the master CMS only; sites are thin compositions.
|
||||||
|
|
||||||
|
## Idea
|
||||||
|
|
||||||
|
`SlpModularCms.Api` is the master CMS: Core plus **every** module (Availability, Contact, Identity, Master, Offerings). The site projects (`Api.SlpSoftware`, `Api.AndreaSlopFotografie`, `Api.Slave`) only compose: a `Program.cs`, a list of module references and an `appsettings.json`. All behaviour lives in Core and the modules and is tested once, on the master host.
|
||||||
|
|
||||||
|
## What changed
|
||||||
|
|
||||||
|
| Area | Change |
|
||||||
|
|---|---|
|
||||||
|
| Website mode | `Website:Mode` (`SpaFallback` default, `PrerenderedPages`) from configuration (`CmsHostOptions.ResolveWebsiteMode`, decided once as `WebsiteModeSelection`). An unknown value stops the host. ASF sets `PrerenderedPages` in its own `appsettings.json`; no site chooses a mode in code. |
|
||||||
|
| Master host | `SlpModularCms.Api` references all modules and has generic defaults for Website, Email, App, Contact and RateLimiting. |
|
||||||
|
| Tests | The ASF test project is gone (18 tests moved, none lost). Site composition and committed defaults: `Api.Tests/SiteContractTests` (reads each site's csproj and appsettings.json, no build of the site). Site behaviour: the master host run with a site's committed settings on top (`AsfVariantPipelineTests`, `SiteVariantContactTests`). Contact pipeline tests and the OpenAPI snapshot run on the master `Api` (`Contact.Tests` references `SlpModularCms.Api`, not a site project). The snapshot changed in exactly three lines: the document title and two tag/assembly names went from `SlpModularCms.Api.SlpSoftware` to `SlpModularCms.Api` (the names come from the host assembly); no path or schema changed. |
|
||||||
|
| CI | `backend-build`/`backend-test` use `SlpModularCms.Ci.slnf` (no site projects). `publish-sls-test` no longer runs on pull requests. `compile-sites` (not required) compiles the three site projects. After each test deploy `smoke-sls-test` / `smoke-asf-test` run `scripts/smoke-site.sh`. |
|
||||||
|
| Branch protection | Required checks on `master`: `backend-test (pull_request)` and `frontend-test (pull_request)` only; the old `publish-test (pull_request)` requirement must be removed before the merge (see `docs/deploy-en-testomgevingen.md`). |
|
||||||
|
|
||||||
|
## Smoke test (`scripts/smoke-site.sh <url> <sls-test|asf-test>`)
|
||||||
|
|
||||||
|
Anonymous requests only: `/health`, public offerings, public banner (200 or 204), `/offerings/all` is 401, `X-Robots-Tag: noindex` and `robots.txt` disallow on a test host, the module list from `/api/v1/System/capabilities` (SLS: all five; ASF: without Master), SLS `/sitemap.xml` 404, ASF unknown path 404 (prerendered mode). A failing check fails the run.
|
||||||
|
|
||||||
|
## Safety net for composition errors
|
||||||
|
|
||||||
|
1. `SiteContractTests`: module references and committed defaults per site. 2. `compile-sites` on pull requests. 3. The smoke test after every test deploy. 4. Policy: production only for a commit that was green on that site's test host.
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
- **Feature Slug**: cms-frontend
|
- **Feature Slug**: cms-frontend
|
||||||
- **Project Type**: Brownfield
|
- **Project Type**: Brownfield
|
||||||
- **Start Date**: 2026-06-16T20:27:00Z
|
- **Start Date**: 2026-06-16T20:27:00Z
|
||||||
- **Current Stage**: CONSTRUCTION - Unit 6: Code Generation (Complete)
|
- **Current Stage**: CLOSED 2026-11-16 - all units built; Build and Test closed (frontend suite in CI); Operations folded into the joint production checklist
|
||||||
- **Branch**: unknown
|
- **Branch**: unknown
|
||||||
|
|
||||||
## Workspace State
|
## Workspace State
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
- [x] Unit 4 — Dashboard — COMPLETED 2026-06-22 (55/55 tests pass, build ✅)
|
- [x] Unit 4 — Dashboard — COMPLETED 2026-06-22 (55/55 tests pass, build ✅)
|
||||||
- [x] Unit 5 — User Management — COMPLETED 2026-06-22 (all 21 steps done, tests written)
|
- [x] Unit 5 — User Management — COMPLETED 2026-06-22 (all 21 steps done, tests written)
|
||||||
- [x] Unit 6 — Profile, Settings & CMS Placeholder — COMPLETED 2026-06-22 (all 25 steps done, tests written)
|
- [x] Unit 6 — Profile, Settings & CMS Placeholder — COMPLETED 2026-06-22 (all 25 steps done, tests written)
|
||||||
- [ ] Build and Test — Not Started
|
- [x] Build and Test — Closed 2026-11-16 (frontend vitest 531/531, lint and build run in CI as `frontend-test`; the admin has been in use on the test hosts)
|
||||||
|
|
||||||
### 🟡 OPERATIONS PHASE
|
### 🟡 OPERATIONS PHASE
|
||||||
- [ ] Operations — Placeholder
|
- [x] Operations — Included in the joint production checklist (`docs/release-checklist-productie.md`)
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# AI-DLC State Tracking
|
||||||
|
|
||||||
|
## Project Information
|
||||||
|
- **Feature Name**: Contact Forms Module (contact messages API + admin, offerings category)
|
||||||
|
- **Feature Slug**: contact-forms-module
|
||||||
|
- **Project Type**: Brownfield
|
||||||
|
- **Start Date**: 2026-11-09
|
||||||
|
- **Current Stage**: CLOSED 2026-11-16 - all units built, Build and Test closed, Operations folded into the joint production checklist (`docs/release-checklist-productie.md`)
|
||||||
|
- **Branch**: feature/contact-forms-module (worktree ..SlpModularCms-contact-forms, from master d9cc539; main checkout stays on feature/identity-email-notifications — never switch it)
|
||||||
|
|
||||||
|
## Workspace State
|
||||||
|
- **Existing Code**: Yes
|
||||||
|
- **Reverse Engineering Needed**: No full rerun (July 2026 artifacts exist in `_shared/`; targeted code review of the touched areas instead — see requirements)
|
||||||
|
- **Workspace Root**: K:\Development\Projects\SlpModularCms
|
||||||
|
|
||||||
|
## Code Location Rules
|
||||||
|
- **Application Code**: Workspace root `src/` (NEVER in aidlc-docs/)
|
||||||
|
- **Feature Documentation**: aidlc-docs/features/contact-forms-module/ only
|
||||||
|
- **Shared Artifacts**: aidlc-docs/_shared/
|
||||||
|
|
||||||
|
## Language Configuration
|
||||||
|
- **Documentation Language**: English
|
||||||
|
- **Conversation Language**: User Language (Dutch)
|
||||||
|
- **Note**: Inherited from the other features in this workspace.
|
||||||
|
|
||||||
|
## Source Of Truth / Coordination
|
||||||
|
- Input contract: `K:\Development\SlpSoftware\Projects\SlpSoftware\aidlc-docs\features\redesign-modern-timetravel\inception\application-design\contact-api-contract.md` (v0.3.1-draft, incl. § 10a and § 11)
|
||||||
|
- Also: that feature's `inception\requirements\requirements.md` (FR-7, FR-8, FR-13..FR-19, NFR-4, NFR-5) and `application-design\*`
|
||||||
|
- Coordinator/approver of stages: session "Redesign - SLS" (approves within Bryan's decisions, otherwise asks Bryan). Stage status is reported to it.
|
||||||
|
- Do not touch files/behaviour the session "AndreaSlopFotografie" is still working on (AvailabilityMiddleware, rate limiter, host config, ForwardedHeaders, ASF settings) without coordination.
|
||||||
|
- No push/merge/PR without explicit instruction. No ASF addresses in code or committed config (env-only). No PII in logs.
|
||||||
|
|
||||||
|
## Extension Configuration
|
||||||
|
| Extension | Enabled | Decided At |
|
||||||
|
|---|---|---|
|
||||||
|
| Security Baseline | Yes | Requirements Analysis |
|
||||||
|
| Property-Based Testing | Partial | Requirements Analysis |
|
||||||
|
|
||||||
|
## Stage Progress
|
||||||
|
### 🔵 INCEPTION PHASE
|
||||||
|
- [x] Workspace Detection (classification: Feature)
|
||||||
|
- [x] Reverse Engineering (skipped by decision D10: targeted review in requirements)
|
||||||
|
- [x] Requirements Analysis (awaiting approval)
|
||||||
|
- [x] Workflow Planning (approved)
|
||||||
|
- [x] Application Design - EXECUTE (minimal; awaiting approval)
|
||||||
|
- [x] Units Generation - EXECUTE (awaiting approval)
|
||||||
|
### 🟢 CONSTRUCTION PHASE
|
||||||
|
- [x] Functional Design - done per unit where needed
|
||||||
|
- [x] NFR Requirements/Design - done where needed (U2, U3)
|
||||||
|
- [x] Infrastructure Design - SKIP
|
||||||
|
- [x] Code Generation - complete (CMS-U0 to U12, plus banners, schedule, SEO, CI, host injection and translation files, documented under their own features)
|
||||||
|
- [x] Build and Test - closed 2026-11-16: `construction/build-and-test/build-and-test-summary.md`
|
||||||
|
### 🟡 OPERATIONS PHASE
|
||||||
|
- [x] Included in the joint production checklist (`docs/release-checklist-productie.md`), not run as separate stages. The production release waits for the owner's explicit go.
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
# Audit Log — contact-forms-module
|
||||||
|
|
||||||
|
## Initial Request (bootstrap, English)
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09T00:00:00Z
|
||||||
|
|
||||||
|
**User Input**: "Opdracht van Bryan voor jou als bouwer van de CMS/API-kant (SlpModularCms). [...] gebruik de aidlc-workflow (Feature-lane) voor deze bouw, in jouw repo, met eigen aidlc-docs. Neem als input: contract v0.3.1 [...]. Bouwvolgorde (§ 11): (a) category op Offerings, (b) OnRejected/Retry-After/ProblemDetails, (c) contactmodule, (d) mail + retry, (e) admin-API, (f) admin-UI. Per unit build+test. Nieuwe feature-branch vanaf master. [...] Begin NIET met Code Generation vóór je plan door mij is goedgekeurd. [...] Niet doen: niets pushen/mergen/PR'en naar master zonder expliciete opdracht; geen ASF-adressen in code of committed config (env-only); geen PII in logs. Terugmelden: na elke aidlc-stage een korte status aan 'Redesign - SLS'." (relayed by cross-session message from session "Redesign - SLS")
|
||||||
|
|
||||||
|
**AI Response**: Confirmed; feature slug `contact-forms-module`; Feature lane; Inception only until the plan is approved.
|
||||||
|
|
||||||
|
**Context**: Workspace Detection — brownfield, classified Feature.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Requirements Answers
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "Antwoorden op requirement-verification-questions.md: 1 A, 2 B, 3 C, 4 A, 5 A, 6 A, 7 A, 8 A ... Schrijf de antwoorden zelf in het bestand en ga door met Requirements." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: Answers recorded; requirements.md written with targeted review findings.
|
||||||
|
|
||||||
|
**Context**: Requirements Analysis, awaiting approval by Redesign - SLS.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Workflow Planning
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "Requirements goedgekeurd ... R1 beslist: bouw (a),(b),(c),(e) op master-basis, mail achter IContactMailSender; (d),(f) na merge en rebase. Doe nu GEEN rebase. Ga door met Workflow Planning en stuur me het execution plan ter goedkeuring. Nog geen Code Generation." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: execution-plan.md written (6 units, phase split at the ASF merge).
|
||||||
|
|
||||||
|
**Context**: Workflow Planning, awaiting approval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Application Design and Units Generation
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "Workflow Planning goedgekeurd ... Application Design (minimaal) en Units Generation mag je samen in een bericht sturen" (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: application-design.md and unit-of-work.md written; one deviation flagged (admin route shape) and one correction (Data Protection already host-level).
|
||||||
|
|
||||||
|
**Context**: awaiting approval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U1 Code Generation plan
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "Application Design en Units Generation goedgekeurd ... stuur je Code Generation-plan voor CMS-U1 (category) ter goedkeuring." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: plan written at construction/plans/cms-u1-offerings-category-code-generation-plan.md; approval requested.
|
||||||
|
|
||||||
|
**Context**: Code Generation Part 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Plan revisions (U0, U1 v2)
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "Beslissing van Bryan: de bestaande routes met een /admin-segment worden NU ook RESTful ... Nieuwe unit CMS-U0 ... Wijziging van Bryan op category: categorieen zijn data in het CMS ... Stuur me een samengevoegd plan."
|
||||||
|
|
||||||
|
**AI Response**: U1 v1 build stashed (not committed); U0 plan written; U1 plan rewritten (v2); order revised.
|
||||||
|
|
||||||
|
**Context**: awaiting approval.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U1b plan
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "CMS-U1 v2 geaccepteerd ... stash mag verwijderd ... stuur het plan voor CMS-U1b" (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: stash dropped (e5e3652); U1b plan written; approval requested.
|
||||||
|
|
||||||
|
**Context**: Code Generation Part 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U1b done, CMS-U2 plan
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "CMS-U1b goedgekeurd ... Daarna: CMS-U2; stuur het plan." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: U1b committed (20f4c3c); U2 plan written; approval requested.
|
||||||
|
|
||||||
|
**Context**: Code Generation Part 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U2 done, CMS-U3 plan
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "CMS-U2 goedgekeurd ... release-voorwaarde in summary en U3-plan; leg uit hoe ContactForm/ContactToken zich op master gedraagt en hoe dit na de rebase naar per-client schakelt; controleer dat 429 geen interne details lekt." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: U2 committed (9e8e8ef); U3 plan written with Contact:Enabled switch and single partition-key function; approval requested.
|
||||||
|
|
||||||
|
**Context**: Code Generation Part 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U3 done, CMS-U3b and CMS-U4 plans
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "CMS-U3 geaccepteerd ... Stuur het U3b-plan en het U4-plan in een bericht ... contact-settings-routes, lijst/detail/status/verwijderen/resend, spam apart, ongelezen-teller zonder spam, route-table-test als AdminOnly." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: U3 committed (b9af7df); plans for U3b and U4 written; Sentry/IP privacy note added to the U3 summary.
|
||||||
|
|
||||||
|
**Context**: Code Generation Part 1.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U3b and CMS-U4 built
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-09
|
||||||
|
|
||||||
|
**User Input**: "CMS-U3b en CMS-U4 goedgekeurd ... bestandsnaam per host ... hervat CMS-U4 na onderbreking" (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: U3b committed (0813656); U4 finished and committed after resuming: Scratch.cs removed, list query fixed, tests green.
|
||||||
|
|
||||||
|
**Context**: Construction phase 1 complete.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Rebase onto master e671078 and phase 2 plans
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-10
|
||||||
|
|
||||||
|
**User Input**: "De ASF-merge is klaar: PR #11 ... merge-commit e671078 ... rebase feature/contact-forms-module, KeyFor -> ClientPartitionKey.For + de ene testassertie, System/capabilities-marker als aparte commit, alle tests incl. pipelinetests. Stuur daarna het rebase-resultaat plus de plannen voor CMS-U5, U6, U7." (via Redesign - SLS)
|
||||||
|
|
||||||
|
**AI Response**: Rebase done (conflicts: active-features, AvailabilityMiddleware, OnRejected, sln); three follow-up commits; all tests green; plans for U5, U6, U7 written.
|
||||||
|
|
||||||
|
**Context**: Phase 2 planning.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U5 contact mail built
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-10
|
||||||
|
|
||||||
|
**User Input**: Approval of plan CMS-U5 incl. the three additive shared mail changes (via Redesign - SLS).
|
||||||
|
|
||||||
|
**AI Response**: Store + signal + background sender with claim, backoff and maximum; real sender; admin resend and detail; tests (unit and pipeline with a capturing sender); OpenAPI regenerated; all test projects green.
|
||||||
|
|
||||||
|
**Context**: Phase 2, one commit.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
|
||||||
|
## CMS-U9 built
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-10
|
||||||
|
|
||||||
|
**User Input**: Approval of plan CMS-U9 with the owner's answers (Friendly Captcha v2; missing token = spam 202; provider 401/sitekey_invalid = fail-open + error log; in-page widget) and the instruction to postpone the frame-src catalogue change until the owner decides (via SLP Software - SLS - Main).
|
||||||
|
|
||||||
|
**AI Response**: Verifier, config, start-up validation, ASF host reference and tests built; docs checked against the provider's v2 documentation; found that the v2 widget needs frame-src (reported, step 6 postponed, patch parked).
|
||||||
|
|
||||||
|
**Context**: Phase 2, one commit, nothing pushed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CMS-U12 built (unread UX)
|
||||||
|
|
||||||
|
**Timestamp**: 2026-11-11
|
||||||
|
|
||||||
|
**User Input**: Request via the lead session (owner's wish): status above the message in the detail, a visual unread indication in the list, a dashboard tile with the unread count (only when the contact module is on); first find out what "unread" means in the model.
|
||||||
|
|
||||||
|
**AI Response**: Model already has New/Read and marks read on open, so no backend change; added the dot, status placement, mark-as-unread button and dashboard tile with tests (frontend 482/482).
|
||||||
|
|
||||||
|
**Context**: Compact change, one commit.
|
||||||
|
|
||||||
|
---
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
# Build and Test summary — contact-forms-module (and the features built on the same branch)
|
||||||
|
|
||||||
|
- **Closed**: 2026-11-16 (on Bryan's go, relayed by SLP Software - SLS - Main)
|
||||||
|
- **Branch**: `feature/contact-forms-module` (last code commit 8ec7ddd before the closing docs)
|
||||||
|
- **Scope**: Contact module (CMS-U0..U12), offering banners, offering schedule, website SEO, CI master pipeline, ASF host injection, translation files.
|
||||||
|
|
||||||
|
## Result
|
||||||
|
|
||||||
|
| Suite | Tests | Result |
|
||||||
|
|---|---|---|
|
||||||
|
| SlpModularCms.Core.Tests | 797 | pass |
|
||||||
|
| SlpModularCms.Modules.Offerings.Tests | 212 | pass |
|
||||||
|
| SlpModularCms.Modules.Availability.Tests | 171 | pass |
|
||||||
|
| SlpModularCms.Modules.Identity.Tests | 145 | pass |
|
||||||
|
| SlpModularCms.Api.Tests | 35 | pass |
|
||||||
|
| SlpModularCms.Modules.Contact.Tests (incl. OpenAPI snapshot, needs MariaDB) | 349 | pass |
|
||||||
|
| SlpModularCms.Modules.Master.Tests | 61 | pass |
|
||||||
|
| Frontend (vitest) | 531 | pass |
|
||||||
|
|
||||||
|
Also verified: the golden files for mails (42), the placeholder page and the website host injection (ASF golden files); end-to-end on the test hosts (anonymous smoke test `scripts/smoke-site.sh` on SLP-test and ASF-test, ETag/304, JSON-LD prices, sitemap address); Bryan accepted the contact form on the test host.
|
||||||
|
|
||||||
|
## Not verified here (carried into the production checklist)
|
||||||
|
|
||||||
|
- Live propagation of an admin change into the injected pages (needs an admin login on test-ASF).
|
||||||
|
- A real win-x64 self-contained publish (text resources verified as embedded in the assemblies only).
|
||||||
|
- Behaviour on production settings (`Website__NoIndex=false`, `Website__PublicBaseUrl`, retention).
|
||||||
|
|
||||||
|
## Operations
|
||||||
|
|
||||||
|
Not run as separate stages. Operations for all features on this branch is **included in the joint production checklist**: [docs/release-checklist-productie.md](../../../../../docs/release-checklist-productie.md).
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
# CMS-U0 offerings-restful-routes: code summary
|
||||||
|
|
||||||
|
## Routes (all under /api/v1/offerings)
|
||||||
|
GET (anonymous, rate limit offerings-public), POST (201 + Location), PUT {id:guid}, DELETE {id:guid}, PUT order {orderedIds}. All except GET are AdminOnly. No /admin segment; move-up/move-down removed. Order route returns 400 (ProblemDetails) unless the list holds every existing offering exactly once.
|
||||||
|
|
||||||
|
## DTO (decision A)
|
||||||
|
One OfferingDto for everybody, now including displayOrder; OfferingAdminDto removed. Handoff for the SLP site: displayOrder is an additive field on the public response and is ignored by the site (as is categoryId later); array order is still the display order.
|
||||||
|
|
||||||
|
## Backend files
|
||||||
|
Modules.Offerings: OfferingsController, IOfferingsService/OfferingsService (GetOfferingsAsync, validated ReorderAsync), OfferingOrderInvalidException, OfferingDto, repository (GetPrevious/GetNext removed).
|
||||||
|
Tests: route-table test (only GET anonymous, class AdminOnly, no admin segment, exact route set), 201+Location, order 400 (controller and service: unknown, incomplete, duplicate ids), displayOrder in DTO.
|
||||||
|
|
||||||
|
## Frontend (frontend/src/features/offerings)
|
||||||
|
Services use the new URLs; OfferingAdminDto renamed OfferingDto; useMoveOffering computes the new order from the cached list and calls PUT /offerings/order; msw handlers and tests updated, plus a test that move-down sends the full new order.
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
dotnet build SlpModularCms.sln: 0 errors. Offerings.Tests 52 passed; Core.Tests 196 passed; Availability.Tests 82 passed; Identity.Tests 37 passed; Master.Tests 57 passed; Api.Tests 4 passed (with a local MariaDB container; without a database 4 fail with connection refused, also on clean master d9cc539). Frontend: vitest 41 files / 260 tests passed; eslint clean; tsc -b clean. prettier --check reports pre-existing style warnings on untouched files (not addressed).
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
# CMS-U1 offerings-category (v2, categories are CMS data): code summary
|
||||||
|
|
||||||
|
## Data
|
||||||
|
OfferingCategory (Id, Name unique case-insensitive, SortOrder, CreatedAt, UpdatedAt) in table OfferingsCategories; Offering.CategoryId (nullable, FK Restrict) + navigation. Migration 20261109193305_AddOfferingCategories (Offerings context). Verified on a real MariaDB: applies after InitialCreate and AddOfferingSlug, unique index rejects 'websites' when 'Websites' exists, FK delete rule RESTRICT. Nothing is seeded.
|
||||||
|
|
||||||
|
## Routes (/api/v1/offerings/categories, class AdminOnly, no anonymous action, no admin segment)
|
||||||
|
GET list {id,name,sortOrder,offeringCount}; POST {name} 201+Location (409 duplicate name); PUT {id:guid} rename (404 unknown, 409 duplicate); DELETE {id:guid} (404 unknown, 409 ProblemDetails while live offerings use it; soft-deleted offerings are released in the same transaction).
|
||||||
|
Offerings: create/update take categoryId (Guid?, must exist, else 400 errors.categoryId=["invalid"], null clears). OfferingDto gains categoryId (string|null) and category (name|null).
|
||||||
|
|
||||||
|
## Handoff for the SLP site
|
||||||
|
GET /api/v1/offerings: category is the name or null (shape unchanged for the site); categoryId and displayOrder are additive fields that the site ignores. A rename is visible on the next request: the name is read through the FK on every query, and the code has no response or output caching. A reverse proxy cache (nginx/IIS) is outside this repo and must not cache /api/v1/offerings for longer than acceptable for renames.
|
||||||
|
|
||||||
|
## Handoff for CMS-U1b (admin UI)
|
||||||
|
Use the four category routes above plus categoryId on offering create/update; offeringCount is in the list for the delete dialog; the 409 delete message is the ProblemDetails title.
|
||||||
|
|
||||||
|
## Dropped from v1
|
||||||
|
Offerings:Categories, OfferingsOptions, appsettings values, legacy-value rule, string column and its migration (v1 stays in git stash until this commit exists).
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
Build 0 errors. Offerings.Tests 84 passed; Core.Tests 196; Availability.Tests 82; Identity.Tests 37; Master.Tests 57; Api.Tests 4 passed (MariaDB container, removed afterwards). Note: Api.Tests host (SlpModularCms.Api) does not load the Offerings module; the migration was therefore verified separately with dotnet ef database update against the container.
|
||||||
|
|
||||||
|
## Tech debt note
|
||||||
|
prettier --check reports style warnings on 15 pre-existing files in frontend/src/features/offerings (untouched, probably line endings). Not addressed in this feature.
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# CMS-U10 — Berichten UX (summary)
|
||||||
|
|
||||||
|
Frontend only, `frontend/src/features/contact` + nl/en texts (`contact.switch.on|off`, `contact.detail.archive|restore`).
|
||||||
|
|
||||||
|
- **Form switch**: new `ToggleSwitch` (native button, `role="switch"`, `aria-checked`, label as accessible name, state as visible text "Aan"/"Uit", `min-h-11 min-w-11` target, Space/Enter, disabled while saving). Existing error handling, toast and first-time hint unchanged.
|
||||||
|
- **Status**: new `StatusIcon` (envelope = new, open envelope = read, archive box = archived, shield = spam) with the name as visible text and `title`; the same component in the list and the detail dialog. The status select is gone.
|
||||||
|
- **Detail actions**: opening an unread message still marks it read automatically (no button). Buttons: Archiveren (new/read), Terugzetten (archived -> read), Geen spam (spam), Verwijderen, Opnieuw mailen.
|
||||||
|
- **Subject**: shown literally as the site sent it (no transformation); mock data now uses capitalised labels ('Website', 'Onderhoudspakket', 'Overig'). The local dev database was re-seeded with such labels (not part of the repo).
|
||||||
|
- Tests: switch (role, name, state text, 44px classes, Space/Enter, disabled while saving), no select, status icon with text in list and detail, archive/restore flow, literal subject. Lint and `tsc -b` clean, vitest 59 files / 470 tests.
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
# CMS-U11 — Recipient address from the site settings (summary)
|
||||||
|
|
||||||
|
- Backend: nullable `RecipientEmail` on `ContactSettings` (migration `ContactSettingsRecipient`); `IContactSettingsService.GetEffectiveRecipientAsync` (setting > env > none) and `SetRecipientAsync` (wakes the mail sender); `ContactMailSender` reads the recipient per send (`NotReadyReasonAsync`); `GET /contact-settings` + `recipientEmail`/`recipientSource` (the env address is never returned); `PUT /contact-settings/recipient`; OpenAPI regenerated.
|
||||||
|
- Frontend: `RecipientCard` next to the form switch (field, save, back to the server setting, source text, client + server validation, translated), warning banner on the switch card while there is no address (no blocking). nl/en.
|
||||||
|
- Tests (new/changed): resolution order, invalid stored value ignored, admin view never shows the env address, set/clear, signal, sender uses the setting without a restart, no address = not ready + nothing sent, controller (valid/trimmed/blank/invalid/CRLF/too long/missing body), pipeline on the real host (login/role, view, set/invalid/clear, no leak in the public token response, a stored-but-pending message goes out after the address is set), route-table test, OpenAPI snapshot; frontend (field, save, invalid client/server, clear, banner without blocking). The existing outgoing contact mail tests keep their intent (only their construction and the async `NotReadyReasonAsync` signature were adapted).
|
||||||
|
- Decisions (approved): warn instead of block; the env address is not shown; the field sits on the Berichten page.
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
# CMS-U12 — Unread indication, status placement and dashboard tile (summary)
|
||||||
|
|
||||||
|
- Model (unchanged, no backend work): `ContactMessageStatus` New/Read/Archived/Spam. New = unread; the detail dialog already marks a new message read when opened; `unreadCount` (status New, spam excluded) is part of every list answer; `PATCH /contact-messages/{id}` already accepts `new`.
|
||||||
|
- Frontend: status row moved above the message text in the detail; "Mark as unread" button for read messages (closes the dialog, so it is not marked read again); dot before the name for unread rows (`role="img"`, accessible name "Unread", plus the existing bold row and status badge); `MessagesTile` on the dashboard (unread count, link to /messages), shown only where the sidebar entry is shown (module loaded, role Owner/Administrator, management API answers); nl/en.
|
||||||
|
- Tests: dot with accessible name only for unread, status above body, mark-as-unread round trip (counter + dot), tile count + link, tile hidden without module and on 404. Full frontend suite 482/482, eslint and tsc clean.
|
||||||
|
- Decisions (small, within the request): dot before the name; the dashboard reads the counter from `GET /contact-messages?page=1&pageSize=1`.
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
# CMS-U1b offerings-categories-ui: code summary
|
||||||
|
|
||||||
|
## What changed (frontend/src/features/offerings + nl/en translations only)
|
||||||
|
- Offerings list page: button "Categorieën beheren" opens CategoriesDialog (no new route). The dialog lists categories with their offering count, adds, renames (inline; Enter confirms, Escape cancels the rename and keeps the dialog open) and deletes (inline confirmation). Errors are shown in Dutch from i18n, not from the API's English titles: duplicate name (409), category in use (409, count from the list), blank/too long name (client side), network, generic.
|
||||||
|
- OfferingForm: "Categorie" select with "Geen categorie" first. Create sends categoryId or null; edit preselects; a category that no longer exists falls back to none (only judged on fresh data).
|
||||||
|
- OfferingRow: category badge; the featured toggle now sends categoryId too (PUT replaces the whole offering, so omitting it would have cleared the category).
|
||||||
|
- Query keys: ['offerings','admin'] renamed to ['offerings','list'] (there is no admin endpoint anymore); category mutations invalidate ['offerings','categories'] and, for rename/delete, ['offerings','list'], so a rename shows up in the list and form without a reload (tested).
|
||||||
|
- Mocks follow the backend (409 duplicate/in use, 404, counts, 400 invalid categoryId); no seed. The mock `PUT /offerings/order` handler is registered before `/:id` (it was shadowed by `/:id` before).
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Radix Select reports an empty value while its options load; the form ignores that (otherwise it wiped the preselected category). Covered by the preselect test.
|
||||||
|
- Escape during a rename is handled via DialogContent onEscapeKeyDown (Radix closes dialogs on a document listener).
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
pnpm lint: clean. npx tsc -b: clean. vitest: 42 test files, 278 tests passed (new: 18 in OfferingCategories.test.tsx = dialog 10, list 2, form 5, schema 1). New files formatted with prettier; the 15 pre-existing prettier warnings in this feature folder remain (tech debt, unchanged).
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
# CMS-U2 gate-and-limiter: code summary
|
||||||
|
|
||||||
|
## What changed
|
||||||
|
- `Core/Availability/PublicSiteEndpointAttribute` (sealed, methods only). `AvailabilityMiddleware`: right after the prefix bypass, an endpoint whose metadata carries the marker is let through before the master/local gate (deny-by-default; prefix bypasses and the verified-admin bypass untouched). Marked now: `OfferingsController.GetOfferings` only.
|
||||||
|
- `AddCmsRateLimiting.OnRejected`: still logs the security event, now also sets `Retry-After` (whole seconds, rounded up, minimum 1, from the limiter lease; 60 when the lease reports none) and writes `application/problem+json` with only `type`, `title`, `status`. Policy numbers and bucket behaviour are unchanged.
|
||||||
|
|
||||||
|
## RELEASE CONDITION (must be met before the contact routes go live)
|
||||||
|
On the base branch (master) the rate-limit policies are **global buckets**: there is no per-client partition key and no ForwardedHeaders handling (both exist only on the ASF branch `feature/identity-email-notifications`). Any per-IP policy added in CMS-U3 (ContactForm 5 per 10 minutes, ContactToken 20 per 10 minutes, ContactResend) would therefore be shared by all visitors: after five submissions the whole site would be blocked. **The contact routes must not be enabled on a public host before the per-client partitioning from the ASF branch is on the base branch (after the ASF merge and the rebase).** Also required on that host: `ForwardedHeaders:KnownProxies` (env). Recorded in contract § 4.5 and repeated in the CMS-U3 plan.
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
- Build: 0 errors. Tests: Core.Tests 205 passed (9 new in RateLimiterOnRejectedTests: Retry-After rounding, fallback 60, problem+json with exactly type/title/status, no leak of policy name/path/limiter terms, only `Retry-After` and `Content-Type` headers, security event logged once, 429 status), Availability.Tests 95 passed (13 new in PublicSiteEndpointGateTests: marked endpoint passes for CMS disabled / maintenance / master blocks; unmarked, and no endpoint, still 503; Availability/status open; route table: marker on exactly `OfferingsController.GetOfferings`, marked actions are anonymous and never `[Authorize]`, every other action of the Availability/Identity/Master/Offerings/System controllers answers 503 at a closed gate, and the only action that passes is `GetOfferings`), Offerings.Tests 86 passed (2 new marker tests), Identity.Tests 37, Master.Tests 57, Api.Tests 4 passed with a temporary MariaDB (the existing Sentry-tunnel limiter test now also asserts Retry-After, `application/problem+json` and the three-field body).
|
||||||
|
- Real pipeline smoke (SlpSoftware host against the temporary MariaDB, CMS state set via the AvailabilityState table): with the CMS **disabled** `GET /api/v1/offerings` 200, `GET /api/v1/offerings/categories` 503, `GET /api/v1/System/capabilities` 503, `GET /api/v1/Availability/status` 200, unauthenticated `PUT /api/v1/offerings/order` 503; in **maintenance** offerings 200 and capabilities 503. The host was stopped and the container removed afterwards.
|
||||||
|
|
||||||
|
## Handoff
|
||||||
|
Public site endpoints stay reachable when the CMS is off or in maintenance; the frontend 503 fallback now only applies to admin calls. Extending the public set is deliberate: add the action to `AllowedPublicActions` in `PublicSiteEndpointGateTests` in the same change (CMS-U3 adds the contact token GET and POST).
|
||||||
|
|
||||||
|
## Rebase notes (after the ASF merge)
|
||||||
|
Expected conflicts: `AvailabilityMiddleware.cs` (one block) and `AddCmsRateLimiting` (`OnRejected`). Re-run the Core, Availability and Offerings tests and the Api.Tests after the rebase.
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
# CMS-U3 contact-core: code summary
|
||||||
|
|
||||||
|
## What it delivers
|
||||||
|
New module `SlpModularCms.Modules.Contact` (+ `.Contact.Tests`), referenced by `Api.SlpSoftware` only.
|
||||||
|
|
||||||
|
Public routes (both anonymous, `[PublicSiteEndpoint]`, reachable while the CMS is off):
|
||||||
|
- `GET /api/v1/contact-messages/token` -> `{ token, minSeconds, captcha }` (`captcha` is null unless enabled; the secret is never returned). Rate limit policy `contact-token`.
|
||||||
|
- `POST /api/v1/contact-messages` with header `Idempotency-Key: <guid>` and body `{ name, email, subject, message, hpCheck, token, captchaToken? }` -> `202 { "status": "received" }` for genuine messages, spam and replays alike. Policy `contact-form`. Errors: `400` (`errors` per field with codes `required|tooLong|invalid|expired`, also `idempotencyKey` and `body`), `413` (problem+json), `429` (Retry-After, problem+json), `404` empty body while the form is closed.
|
||||||
|
|
||||||
|
Behaviour: validation (limits 100/254/100/2000, e-mail regex, control characters rejected, fields trimmed) -> replay check (same key within 24 h answers 202 without a second row; a rejected request does not use up its key) -> token (forged, other-site, garbage and expired all answer `errors.token=["expired"]`: no oracle) -> classification: too-young token (< `MinSeconds`), filled `hpCheck`, or a rejected captcha is spam -> store (genuine: `New`, mail `Pending`, retention 12 months; spam: `Spam`, mail `NotApplicable`, 30 days, per-site daily cap 200 beyond which it is answered but not stored) -> after commit the mail seam `IContactMailSender` (no-op until the mail unit: result `Skipped`, message stays `Pending`). A mail problem never fails the request. Daily retention job removes expired messages and idempotency records older than 24 h. Site id comes from configuration, never from the request; no IP address is stored.
|
||||||
|
|
||||||
|
## RELEASE CONDITION (unchanged, now enforced in code)
|
||||||
|
On the base branch the rate-limit policies are shared buckets (no per-client key, no forwarded-header handling). The contact routes therefore stay **closed** (`Contact:Enabled=false`, 404 with empty body, no database access, retention job idle) until the per-client partitioning from the ASF branch is on the base branch. Do not enable on a public host before that.
|
||||||
|
|
||||||
|
## Gate design (two layers, per the later decision)
|
||||||
|
Route filter `ContactRouteFilter` asks `IContactFormGate.IsOpenAsync`. Today the only layer is `HostFlagContactFormGate` (`Contact:Enabled`). CMS-U4 adds the CMS-controlled switch (`/api/v1/contact-settings`) as a second layer by replacing the registration with a composite gate; the filter is not touched. The form is active only if every layer is open; otherwise 404 empty body (the website shows its mailto fallback).
|
||||||
|
|
||||||
|
## REBASE CHECKLIST (after the ASF merge)
|
||||||
|
1. `src/SlpModularCms.Modules.Contact/Services/ContactSeams.cs`, class `ContactRateLimitPartition`: change the single line `public static string KeyFor(HttpContext context) => GlobalKey;` to `public static string KeyFor(HttpContext context) => ClientPartitionKey.For(context);` (add the ASF `using`). Remove the `GlobalKey` constant if it is no longer used.
|
||||||
|
2. `src/SlpModularCms.Modules.Contact.Tests/ContactRetentionAndPartitionTests.cs`, test `OnTheBaseBranch_EveryCallerSharesOneBucket`: replace it with "two different client addresses give two different keys" (the same two addresses are already in the test).
|
||||||
|
3. Make sure `ForwardedHeaders:KnownProxies` is configured on the host (environment).
|
||||||
|
4. Regenerate/verify migrations only if a snapshot conflicts (Contact has its own context and history, so none is expected). Re-run all test projects.
|
||||||
|
5. Only then set `Contact:Enabled=true` on the host (environment or appsettings of that host).
|
||||||
|
|
||||||
|
## `Contact:*` configuration (keys and defaults; `Api.SlpSoftware/appsettings.json` carries them)
|
||||||
|
| Key | Default | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `Contact:Enabled` | `false` | host switch / release condition |
|
||||||
|
| `Contact:SiteId` | `slpsoftware` in appsettings; `default` if unset | stored on rows, bound into the token purpose; never from a request |
|
||||||
|
| `Contact:MinSeconds` | `3` | returned to the client as `minSeconds`; faster = spam |
|
||||||
|
| `Contact:TokenLifetimeMinutes` | `120` | |
|
||||||
|
| `Contact:RetentionMonths` | `12` | per row at insert; no retroactive change |
|
||||||
|
| `Contact:SpamRetentionDays` | `30` | |
|
||||||
|
| `Contact:MaxSpamRowsPerDay` | `200` | per site per UTC day |
|
||||||
|
| `Contact:MaxBodyBytes` | `16384` | 413 beyond |
|
||||||
|
| `Contact:ProblemTypeBase` | none -> `about:blank` | base for the validation problem `type` (`{base}/validation`) |
|
||||||
|
| `Contact:Captcha:Enabled` | `false` | |
|
||||||
|
| `Contact:Captcha:Provider` / `SiteKey` | none | returned in the token response when enabled |
|
||||||
|
| `Contact:Captcha:Secret` | none | env / secrets manager only, never committed |
|
||||||
|
| `RateLimiting:ContactForm:PermitLimit` / `WindowSeconds` | `5` / `600` | |
|
||||||
|
| `RateLimiting:ContactToken:PermitLimit` / `WindowSeconds` | `20` / `600` | |
|
||||||
|
|
||||||
|
## Deviations from the contract / design (for SLS to adopt)
|
||||||
|
- The honeypot JSON name is fixed `hpCheck` (no `Contact:HoneypotField`): the payload shape is a contract matter; the site's DOM name is free. A missing `hpCheck` key counts as empty (lenient) instead of a `required` error, so a real client that omits it is not rejected and a bot learns no field name from an error.
|
||||||
|
- Unbindable bodies (malformed JSON, wrong types) answer `400` with `errors.body=["invalid"]` in the same problem shape (the controller is deliberately not an `[ApiController]`).
|
||||||
|
- Validation problem `type` is configurable (`Contact:ProblemTypeBase`), default `about:blank` (approved).
|
||||||
|
|
||||||
|
## Privacy / logging
|
||||||
|
Only the outcome (`Genuine|Spam|SpamNotStored|Replay`) and the site id are logged; mail failures are logged by exception type only. Tests prove that no name, e-mail, subject, message, captcha token, Idempotency-Key or token appears in any log entry (genuine, spam, replay, invalid, forged token, mail exception with personal data in its message, database exception). Sentry: request bodies are never captured (`MaxRequestBodySize=None`) and the existing scrubber nulls `Request.Data`. Note: like for every endpoint, a Sentry error event carries the caller's IP address (`SendDefaultPii`); nothing from the form body is in it.
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
Build 0 errors. Contact.Tests 113 passed (unit and pipeline), Core 205, Availability 95 (route table now allows exactly GetOfferings + GetToken + Submit), Offerings 86, Identity 37, Master 57, Api.Tests 4 — all against a temporary MariaDB (removed afterwards). Pipeline tests start the real SlpSoftware host: disabled -> both routes 404 empty and the contact tables do not even exist (the module never touched the database; the retention tick changes nothing); enabled -> token 200, valid POST 202 stored once, replay 202 without a second row, honeypot 202 identical body but stored as Spam, 400 shapes, 413, malformed bodies without echo, 429 with Retry-After for both policies, routes reachable while the CMS is disabled (and `/offerings/categories` 503), migration applied on a real MariaDB with a unique (site, key) constraint, retention job deletes expired rows. Each pipeline fixture creates and drops its own database.
|
||||||
|
|
||||||
|
## Running the tests
|
||||||
|
The `Pipeline` tests need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (same requirement as `Api.Tests`). Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`.
|
||||||
|
|
||||||
|
## Attention point for the privacy statement (SLS request)
|
||||||
|
Sentry runs with `SendDefaultPii = true`: an error event for ANY request, including the contact routes, carries the caller's IP address. Nothing from the form (name, e-mail, subject, message) is ever in a Sentry event, and no IP address is stored in the contact database. The privacy statement should mention error reporting with IP addresses as a processing activity (and the Sentry data location/retention); no code action now.
|
||||||
+25
@@ -0,0 +1,25 @@
|
|||||||
|
# CMS-U3b openapi-export: code summary
|
||||||
|
|
||||||
|
## Result
|
||||||
|
Committed `openapi/slpsoftware.v1.json`: the OpenAPI 3.1 document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). **Convention: one file per host, named after the host** (`openapi/slpsoftware.v1.json` now, `openapi/andreaslopfotografie.v1.json` when that host exists on the base branch). It is the single source from which the frontend client (`cms-client`) generates its types.
|
||||||
|
|
||||||
|
Regenerate after an intended API change: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot` (needs the database like the other pipeline tests). Without the variable the same test fails when the served document differs from the file, with that command in its message (drift detection was verified by changing one value in the file).
|
||||||
|
|
||||||
|
Normalized form (so the diff is meaningful): no `servers` (derived from the request host), object keys in ordinal order everywhere, 2-space indentation, LF, trailing newline. Reviewed for hosts, addresses and secrets; the tests assert there are none.
|
||||||
|
|
||||||
|
## Contact contract in the document (module-level, Core untouched)
|
||||||
|
`ContactOpenApiDocumentTransformer`, registered from `ContactModule` through the named options of document `v1`:
|
||||||
|
- Reusable `components.responses`: `Validation` (400, problem+json, schema `ValidationProblem` with `errors` = map of field name -> array of `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header); schemas `Problem`, `ValidationProblem`.
|
||||||
|
- `POST /api/v1/contact-messages`: required header `Idempotency-Key` (uuid); request body required, exactly one `ContactMessageRequest` (`required`: name, email, subject, message, hpCheck, token; `maxLength` 100/254/100/2000/0, plain `string` types; `captchaToken` nullable); responses 202, 400, 404 (form closed), 413, 429.
|
||||||
|
- `GET /api/v1/contact-messages/token`: 200 (`ContactTokenResponse`), 404 (form closed), 429.
|
||||||
|
- The contact controller is not an `[ApiController]` (own error shape), so it carries `[ApiExplorerSettings(IgnoreApi = false)]` to appear in the document; `[ProducesResponseType]` attributes (with explicit content types) drive its operations.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- Microsoft.OpenApi 2.x model: everything above could be expressed through the document transformer; nothing had to be faked. Minor generator quirks kept as generated (e.g. nullable unions elsewhere in the document).
|
||||||
|
- The document is of the host as composed: operations of every loaded module appear. Routes that are closed at runtime (`Contact:Enabled=false`) are still documented; the 404 "form closed" response says so.
|
||||||
|
|
||||||
|
## Side fix found while doing this
|
||||||
|
Problem details of the 400 answer are explicitly `application/problem+json` again after a class-level `[Produces]` experiment was rejected (it overrides the content type); covered by the existing pipeline test and a new controller assertion.
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
Build 0 errors. Contact.Tests 117 passed (4 new OpenApiSnapshot tests: equality with the committed file, contract content incl. header/required/maxLength/reusable responses/error codes, no hosts/addresses/secrets, deterministic normalization), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4; temporary MariaDB used and removed afterwards.
|
||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
# CMS-U4 contact-admin-api: code summary
|
||||||
|
|
||||||
|
## IMPORTANT: the contact form is OFF by default, on two layers
|
||||||
|
1. **Host switch** `Contact:Enabled` (appsettings/environment of the host), default `false`. Release condition: only switch on after the per-client rate limiting from the ASF branch is on the base branch (see the CMS-U3 rebase checklist).
|
||||||
|
2. **CMS switch** (data, this unit): `PUT /api/v1/contact-settings` `{ "enabled": true }`, default **off** (no row = off). **Bryan has to switch the form on himself**, in the "Berichten" screen (CMS-U6) or through the API, before the public routes work. The form is open only when BOTH are on; otherwise `GET /contact-messages/token` and `POST /contact-messages` answer `404` with an empty body and the website shows its mailto fallback. A change of the CMS switch takes effect at once in the process that handled the change (other instances within 5 seconds).
|
||||||
|
|
||||||
|
## Routes (all `AdminOnly`: Owner or Administrator; anonymous = 401, role `User` = 403)
|
||||||
|
Same resource names as the public routes, no `/admin` segment. All sit behind the availability gate (no `[PublicSiteEndpoint]`): for visitors they answer 503 while the CMS is off/in maintenance; a verified administrator always gets through (by design, so the CMS can be switched back on).
|
||||||
|
|
||||||
|
**While the host switch is off every management route answers `404` with an empty body** (the contact tables do not exist then). The UI must read `404` on `GET /contact-settings` as "not available on this host" and hide the menu entry. The CMS switch never closes the management routes.
|
||||||
|
|
||||||
|
### JSON shapes (camelCase; enums are lower-camel strings)
|
||||||
|
`status`: `new | read | archived | spam | converted`; `mailStatus`: `pending | sent | failed | notApplicable`.
|
||||||
|
|
||||||
|
**`GET /api/v1/contact-messages?status=&page=1&pageSize=25`** -> `200`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"items": [
|
||||||
|
{ "id": "3f2c...-guid", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen",
|
||||||
|
"email": "jan@example.nl", "subject": "website", "status": "new", "mailStatus": "pending" }
|
||||||
|
],
|
||||||
|
"page": 1, "pageSize": 25, "totalCount": 1, "unreadCount": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
`status` (optional, one value `new|read|archived|spam`, case-insensitive): without it the list shows `new`, `read` and `archived` — **spam is never in the default list**; `status=spam` shows spam apart. Newest first. `page` >= 1, `pageSize` 1-100. `unreadCount` = number of `new` messages, **never counting spam, independent of the filter**. The list has no message text.
|
||||||
|
|
||||||
|
**`GET /api/v1/contact-messages/{id}`** -> `200`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": "3f2c...", "receivedAt": "2026-11-09T12:00:00+00:00", "name": "Jan Jansen", "email": "jan@example.nl",
|
||||||
|
"subject": "website", "message": "Ik wil graag een offerte.", "status": "new", "mailStatus": "pending",
|
||||||
|
"mailAttempts": 0, "mailError": null, "retentionUntil": "2027-11-09T12:00:00+00:00"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
`404` unknown id.
|
||||||
|
|
||||||
|
**`PATCH /api/v1/contact-messages/{id}`** body `{ "status": "new" | "read" | "archived" }` -> `200` with the detail shape above. Setting one of these on a spam message means "not spam": it then follows the normal retention (`retentionUntil` = now + `Contact:RetentionMonths`) and appears in the default list; its `mailStatus` stays `notApplicable` until resent. Anything else (`spam`, `converted`, unknown, missing, unreadable body) -> `400`. `404` unknown id.
|
||||||
|
|
||||||
|
**`DELETE /api/v1/contact-messages/{id}`** -> `204` (hard delete, erasure request); `404` unknown id.
|
||||||
|
|
||||||
|
**`POST /api/v1/contact-messages/{id}/resend`** (rate limit `contact-resend`, default 5 per 600 s) -> `200`
|
||||||
|
```json
|
||||||
|
{ "mailStatus": "pending", "mailAttempts": 0, "mailed": false }
|
||||||
|
```
|
||||||
|
`mailed=true` only when a mail was really sent. Until the mail unit (CMS-U5) there is no mail sender, so the answer is `mailed:false` and nothing changes. A spam message -> `409` (problem+json; "mark it as not spam first"). `404` unknown id. `429` with `Retry-After` after the limit.
|
||||||
|
|
||||||
|
**`GET /api/v1/contact-settings`** -> `200`
|
||||||
|
```json
|
||||||
|
{ "enabled": false, "hostEnabled": true }
|
||||||
|
```
|
||||||
|
`enabled` = the CMS switch (default `false`); `hostEnabled` = the host switch, read-only, so the UI can explain why the form is closed.
|
||||||
|
|
||||||
|
**`PUT /api/v1/contact-settings`** body `{ "enabled": true | false }` -> `200`, same shape as GET. Anything that is not a JSON boolean (missing, null, string, number, unreadable body) -> `400`.
|
||||||
|
|
||||||
|
### Error shape (`400`, `application/problem+json`)
|
||||||
|
```json
|
||||||
|
{ "type": "about:blank", "title": "Validation failed", "status": 400, "errors": { "status": ["invalid"] } }
|
||||||
|
```
|
||||||
|
Field names used: `status` (PATCH), `enabled` (PUT settings), `page`, `pageSize`, `status` (list query). Code is always `invalid`.
|
||||||
|
|
||||||
|
## Design notes
|
||||||
|
- Separate controllers for the management side (`ContactMessagesAdminController`, `ContactSettingsController`) next to the public `ContactMessagesController`; routes cannot clash (`{id:guid}`).
|
||||||
|
- Gate: `CompositeContactFormGate` = host flag first, then `CmsFlagContactFormGate` (singleton row in table `ContactSettings`, migration `AddContactSettings`, 5-second in-process cache invalidated on every change). The public `ContactRouteFilter` was not touched. With the host flag off the database is not touched at all.
|
||||||
|
- Statuses and mail statuses are stored as strings; the list uses one flag per status in its query because a parameterized collection loses the value-converter mapping in the SQL translation (found by the pipeline test).
|
||||||
|
- Nothing personal is logged by the admin services (ids and outcomes only; tested).
|
||||||
|
- Management routes appear in `openapi/slpsoftware.v1.json` (regenerated).
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
Build 0 errors. Contact.Tests **223 passed** (unit + pipeline), Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4, against a temporary MariaDB (removed afterwards). Explicit tests requested by SLS:
|
||||||
|
- Route table: exactly the seven management routes exist; every one is under class-level `AdminOnly`, none is `[AllowAnonymous]`, none is `[PublicSiteEndpoint]`, no route contains `admin`; the only `[PublicSiteEndpoint]` actions in the whole module are `GetToken` and `Submit`; the Availability route-table test (everything except `GetOfferings`, `GetToken`, `Submit` is blocked by a closed gate) covers the new routes without change.
|
||||||
|
- `PUT /contact-settings` by a non-admin -> `403` and nothing changes; by a regular user also for every other management route; anonymous -> `401` on all of them.
|
||||||
|
- Invalid body (`"yes"`, `1`, `null`, `{}`, `not json`, empty) -> `400` with `errors.enabled=["invalid"]` (and only that field).
|
||||||
|
- Real host: switch default off and reported with `hostEnabled`; PUT opens/closes the public routes at once while the management routes keep working; the changing user is recorded; full message flow (list without spam, `status=spam`, detail, status change, spam refused for resend, un-spam, delete); bad list queries -> `400`; resend `429` with `Retry-After`; host switch off -> management routes `404` (empty), anonymous still `401`; CMS disabled (availability) -> visitors `503` on the management routes, an administrator still `200`.
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
# CMS-U5 — Contact mail + retry (summary)
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
- A submission only stores the message (status `new`, mail `pending`, `NextMailAttemptAt = now`) and signals the background sender. The visitor never waits for SMTP.
|
||||||
|
- `ContactMailService` (BackgroundService) wakes on the signal and every `Contact:Mail:SweepSeconds`; it picks unread (`new`) messages with mail `pending`/`failed`, fewer than `MaxAttempts` attempts and a due `NextMailAttemptAt`, oldest first, `BatchSize` at a time.
|
||||||
|
- Claim: `NextMailAttemptAt` is a concurrency token; the sender first sets it to now + `ClaimMinutes` (whole seconds, the column is `datetime`), a second instance fails to save and skips the message.
|
||||||
|
- Failure: `failed` + short error code, attempts + 1, next attempt after 5 min / 15 min / 1 h / 6 h / 24 h; after `MaxAttempts` (6) no automatic attempt; an administrator can still resend (ignores backoff and maximum).
|
||||||
|
- Mail off or no valid recipient: nothing attempted or counted; the reason (`disabled` / `recipient_not_configured`) is shown as `mailError`.
|
||||||
|
- Spam, read, archived messages are never auto-mailed. Module disabled: the service does nothing and never touches the database.
|
||||||
|
- Mail: To = `Contact:RecipientEmail`, From = site sender, Reply-To = visitor (address validated, name only if valid), fixed subject "Nieuw bericht via {site}" / "New message via {site}"; details (name, e-mail, subject, message) HTML-encoded, line breaks kept, text part included. Logs: message id and short codes only.
|
||||||
|
|
||||||
|
## Configuration (env-only for the address)
|
||||||
|
- `Contact__RecipientEmail` (environment variable; no address in repo config).
|
||||||
|
- `Contact:Mail:SweepSeconds` 120, `MaxAttempts` 6, `BackoffMinutes` [5,15,60,360,1440], `ClaimMinutes` 5, `BatchSize` 20.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- Detail has `nextMailAttemptAt`; resend result has `mailError`. Migration `ContactMailClaim` (schema unchanged, concurrency token only). OpenAPI regenerated.
|
||||||
|
|
||||||
|
## Shared files changed (additive only)
|
||||||
|
`Core/Email/MailTypes.cs`, `MailTemplateRenderer.cs`, `SmtpEmailSender.cs` (+66/-5). Existing Core tests untouched: 625 green.
|
||||||
|
|
||||||
|
## Found by the real-database pipeline test
|
||||||
|
`datetime` drops fractions, which made the claim's concurrency check fail on the outcome save; claim time is now truncated to whole seconds.
|
||||||
|
|
||||||
|
## Follow-up (review by AndreaSlopFotografie)
|
||||||
|
- The "you can reply directly" note is removed from the ContactMessage catalog (Reply-To may be left out when the visitor address is invalid).
|
||||||
|
- Plain text: every line of a visitor value is indented two spaces, so a visitor's own `--` line or fake headings cannot imitate the layout.
|
||||||
|
- NEW Core tests (next to the unchanged existing ones): `ContactMessageMailRenderingTests` (encoding of script/quotes/line breaks, labels encoded, null/empty Details give no block, fixed subject, text indent, no reply hint) and `SmtpReplyToTests` (valid Reply-To with name, invalid/CRLF address left out, control characters in the name dropped, none when absent), using the existing in-process stub SMTP server. Core: 639 green (625 existing + 14 new).
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# CMS-U6 — Admin UI "Berichten" (summary)
|
||||||
|
|
||||||
|
Frontend only. New feature folder `frontend/src/features/contact` (services, components, page, msw mocks, tests).
|
||||||
|
|
||||||
|
- Route `/messages` (Owner/Administrator, `ModuleGuard Contact`, plus `ContactAvailabilityGuard`: a 404 on `GET /contact-settings` means the host switch is off and the usual not-found page is shown). Sidebar entry "Berichten" only when capabilities list `Contact` and the settings call did not answer 404.
|
||||||
|
- Form switch card (`role=switch`, state from the server response, first-time hint, translated errors).
|
||||||
|
- List: chips Inbox/Nieuw/Gelezen/Gearchiveerd/Spam (Nieuw shows `unreadCount`), 25 per page, pager, empty states, spam only under its chip, mail status icons with text alternatives.
|
||||||
|
- Detail dialog: line breaks kept, mailto link, status select, "Geen spam", delete with confirmation, resend (sent / not sent / 409 / 429 with Retry-After seconds / disabled with hint when mail is off), translated mail error code and next attempt time. Opening an unread message marks it read (decision approved).
|
||||||
|
- Texts nl/en under `contact.*` and `nav.messages`; no API titles are shown.
|
||||||
|
- Shared files touched (additive): `lib/api-client.ts` (new `patch` method), `Sidebar.tsx` (one entry), `router.tsx` (one route), `mocks/index.ts`, both translation files.
|
||||||
|
- Verification: `pnpm lint` clean, `npx tsc -b` clean, vitest 58 files / 458 tests (26 new). Not touched: backend, auth/refresh, users, theme assets.
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# CMS-U7 availability-restful-status: code summary
|
||||||
|
|
||||||
|
## RELEASE NOTE: this unit must go out as ONE release together with the admin app
|
||||||
|
`POST /api/v1/Availability/admin/status` is removed (no alias) and replaced by `PUT /api/v1/Availability/status`. The API and the admin app (`frontend/`) change together. Deploying only one half breaks the status change in Settings: a new API with an old admin bundle gets a non-JSON fallback page on the old route; a new bundle on an old API gets 405/404. During a deploy window a still-open old browser tab fails until its next page load.
|
||||||
|
|
||||||
|
## Result
|
||||||
|
- `PUT /api/v1/Availability/status` (AdminOnly), body unchanged `{ "newStatus": "Available"|"Maintenance"|"NotAvailable", "reason": string|null }`. `200` with the **updated resource**, same JSON as `GET /api/v1/Availability/status` (`{ status, checkedAt, message, isMasterControlled }`); `409` problem+json when the status is master-controlled (unchanged); `400` for an invalid status or a service that cannot persist; `401`/`403` like every admin route.
|
||||||
|
- `GET /api/v1/Availability/status` is unchanged (public, open for everyone, also while the CMS is off).
|
||||||
|
- Old route removed; `openapi/slpsoftware.v1.json` regenerated.
|
||||||
|
- **Gate** (`AvailabilityMiddleware`, small isolated diff): the exemption for `/api/v1/Availability/status` now applies to `GET`/`HEAD` only. `PUT` (and any other method) follows the normal gate: a verified Owner/Administrator passes, an expired token gets `401`, everyone else `503`. Before, the prefix exemption let any method through.
|
||||||
|
- Frontend: `useUpdateAvailability` uses `PUT` and writes the answer into the status cache; msw default handler and the two failure handlers in `SettingsPage.test.tsx` moved to `PUT`; a new test asserts method, path (no `admin`) and body.
|
||||||
|
|
||||||
|
## Callers of the old route (checked repository-wide: code, docs, CI, configs)
|
||||||
|
Only the admin frontend: `features/availability/services/useAvailability.ts`, `features/availability/mocks/handlers.ts`, two handlers in `features/settings/pages/SettingsPage.test.tsx`. No server-side caller: the master pushes with `POST /Master/status`, slaves read `GET /SlaveStatus`; no proxy, deploy script or workflow mentions it; the README names only the GET. Historic `aidlc-docs` mentions are history and unchanged.
|
||||||
|
|
||||||
|
## Changes to existing tests (for the record)
|
||||||
|
Three existing tests built a request without an HTTP method (the default is empty) and relied on the old method-less prefix exemption. They now set `GET` like a real request does: `TestContexts.Api()` and `AvailabilityGateScopeTests.RunAsync` (shared helpers) and `PublicSiteEndpointGateTests.TheAvailabilityStatusEndpoint_StaysOpen...`. `AvailabilityControllerTests.UpdateStatus_ReturnsOk...` now asserts the body (`OkObjectResult`, same four fields as the GET) instead of `OkResult`. No assertion about gate behaviour was weakened.
|
||||||
|
|
||||||
|
## Verification (real output)
|
||||||
|
Build 0 errors. Availability.Tests 165 passed (11 new in `AvailabilityStatusRouteTests`: GET/HEAD stay open; PUT/POST/DELETE/PATCH are gated; a verified administrator passes while the CMS is disabled; an expired token on PUT = 401; case-insensitive path; route table = exactly `GET status` + `PUT status`, PUT is AdminOnly and not public-marked, no `admin` in any route). Contact.Tests 228 passed (3 new pipeline tests on the real host: anonymous PUT 401, user 403, administrator PUT Maintenance -> body is the updated resource -> anonymous GET shows it -> visitor gets 503 on a gated route and on the PUT itself -> administrator switches it back; invalid status 400 and unchanged state; the old route behaves like a route that never existed and changes nothing). Api.AndreaSlopFotografie 11, Api 4, Core 625, Identity 145, Master 61, Offerings 86. Frontend: `pnpm lint` clean, `npx tsc -b` clean, vitest 57 files / 432 tests passed (1 new).
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
# CMS-U8 — Offerings page on small screens (summary)
|
||||||
|
|
||||||
|
Only `frontend/src/features/offerings/pages/OfferingsListPage.tsx` (+ new test file). No new translations needed: the existing `offerings.addButton` / `offerings.categories.manageButton` are used.
|
||||||
|
|
||||||
|
- Below `sm` (640px): "Aanbieding toevoegen" is a FAB (fixed, bottom-right, safe-area aware, plus icon, `aria-label` + `title`, 56px), "Categorieën beheren" is icon-only (44px, `aria-label` + `title`), the page has `pb-24` so the last row is not covered.
|
||||||
|
- From `sm` up: unchanged text buttons (`hidden sm:inline-flex`); FAB and icon button are `sm:hidden`. The existing test ids stay on the text buttons.
|
||||||
|
- Tests (`OfferingsResponsive.test.tsx`, 6): classes per breakpoint, accessible names nl/en, FAB link, icon button opens the dialog, bottom space. jsdom has no media queries, so breakpoints are asserted on Tailwind classes.
|
||||||
|
- Observations (not changed): UsersPage header is a plain `flex justify-between` with an action button (same pattern, no FAB, not changed); the Berichten table scrolls horizontally on narrow screens and its chips wrap. Not verified on a real narrow viewport.
|
||||||
|
- Verification: lint and `tsc -b` clean, vitest 59 files / 464 tests.
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
# CMS-U9 — Friendly Captcha v2 and the ASF host (summary)
|
||||||
|
|
||||||
|
- `FriendlyCaptchaVerifier` (v2 siteverify, X-API-Key, fail-open rules, no secrets/tokens in logs), `ContactCaptchaOptions` (+ VerifyUrl, TimeoutSeconds, `Problems()`), start-up validation (`ContactOptionsValidator`, ValidateOnStart: the host refuses to start with an incomplete captcha setup), module wiring (`NullCaptchaVerifier` while off), token response only announces a complete setup, missing/empty `captchaToken` while on = spam (202).
|
||||||
|
- OpenAPI: descriptions for token and submit operations regenerated.
|
||||||
|
- ASF host: `ProjectReference` + `Contact` config section (off), rate-limit policies, release conditions in the file and in the handoff (section 8).
|
||||||
|
- Tests (new): verifier (request shape, EU URL, all answers, timeout, network error, cancellation, empty token, no secrets in logs), options validation, submission rule, pipeline with a fake provider (token response shape, spam vs genuine identical 202, missing token, fail-open 500/503/401, label with `& ' " < >`, start-up refusal), mail label encoding, ASF host tests (closed by default, public routes reachable while the gate is closed, per-client vs shared bucket, committed defaults), frontend label test.
|
||||||
|
- NOT included (instruction): the `frame-src` CSP catalogue change (`AllowedSiteFrameOrigins`), parked as a patch; see handoff section 8 for the provider's CSP requirement.
|
||||||
|
- Deviation found against the plan: the v2 widget needs `frame-src` (iframes); the "no frame-src" assumption was wrong. Also `sitekey_invalid` is HTTP 400 (not 401/403).
|
||||||
|
|
||||||
|
## Follow-up (owner decisions)
|
||||||
|
- `frame-src` catalogue change committed: `SecurityHeaders:AllowedSiteFrameOrigins` (exact origins; StrictSite only; empty = byte-identical). 6 new Core tests (Core 645).
|
||||||
|
- Region: `Contact:Captcha:Region` = `global` (default) | `eu`; token response `captcha` gains `apiEndpoint` (additive); VerifyUrl derived from the region, an explicit VerifyUrl must match it, an unknown region or a mismatch stops the host at start-up. Tests: options (default, eu, mismatches, unknown), pipeline (default global, eu, mismatch refuses to start), OpenAPI regenerated. Contact tests 313.
|
||||||
|
- Privacy documented for both regions (handoff section 8).
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
# Phase 1 handoff (CMS side) — for the frontend work
|
||||||
|
|
||||||
|
Branch `feature/contact-forms-module` (worktree `..\SlpModularCms-contact-forms`), base master `d9cc539`, phase 1 units CMS-U0, U1, U1b, U2, U3, U3b, U4 all committed (last commit `44f161a`). Nothing pushed, merged or deployed. Phase 2 (CMS-U5 mail + retry, CMS-U6 "Berichten" UI, CMS-U7 `PUT /availability/status`) waits for the merge of `feature/identity-email-notifications` and a rebase.
|
||||||
|
|
||||||
|
The machine-readable source for types is **`openapi/slpsoftware.v1.json`** (one file per host, named after the host; regenerate with `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`). Per-unit details: `construction/cms-u*/code/summary.md`.
|
||||||
|
|
||||||
|
All paths are under `/api/v1`. "Gate" = the availability gate: routes without the public marker answer 503 to visitors while the CMS is off or in maintenance; a verified Owner/Administrator always gets through. `401` = no/invalid login, `403` = logged in without `Administrator`/`Owner`. JSON is camelCase.
|
||||||
|
|
||||||
|
## 1. Routes
|
||||||
|
|
||||||
|
### Offerings (module `Offerings`)
|
||||||
|
| Method + path | Auth | Success | Other status codes |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET /offerings` | public (marker, survives a closed gate); limiter `offerings-public` 120/60 s | `200` array of offerings | `429` |
|
||||||
|
| `POST /offerings` | AdminOnly | `201` + `Location: /api/v1/offerings/{id}` + offering | `400` (framework validation shape; bad `categoryId` = `errors.categoryId=["invalid"]`), `409` slug taken, `401`, `403`, `503` |
|
||||||
|
| `PUT /offerings/{id:guid}` | AdminOnly | `200` offering (full replace; omitting `categoryId` clears the category) | `400`, `404`, `409`, `401`, `403`, `503` |
|
||||||
|
| `DELETE /offerings/{id:guid}` | AdminOnly | `204` (soft delete) | `404`, `401`, `403`, `503` |
|
||||||
|
| `PUT /offerings/order` body `{ "orderedIds": [guid,...] }` | AdminOnly | `204` | `400` problem unless the list holds every existing offering exactly once, `401`, `403`, `503` |
|
||||||
|
|
||||||
|
Offering JSON: `{ id, slug, title, description, price, priceNote, features[], ctaLabel, featured, displayOrder, categoryId|null, category|null }`. `category` = the category **name** (a rename shows up at once; no response caching in the code); `categoryId` and `displayOrder` are additive fields the SLP site can ignore. Create/update body: `title, description, price, priceNote, features[], ctaLabel, featured, slug?, categoryId?` (`categoryId` must exist; `null` clears).
|
||||||
|
|
||||||
|
### Offering categories (CMS data, nothing seeded)
|
||||||
|
| Method + path | Auth | Success | Other |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET /offerings/categories` | AdminOnly | `200` `[{ id, name, sortOrder, offeringCount }]` | `401`, `403`, `503` |
|
||||||
|
| `POST /offerings/categories` `{ name }` (1-100) | AdminOnly | `201` + Location + category | `400`, `409` name taken (case-insensitive) |
|
||||||
|
| `PUT /offerings/categories/{id:guid}` `{ name }` | AdminOnly | `200` category | `400`, `404`, `409` |
|
||||||
|
| `DELETE /offerings/categories/{id:guid}` | AdminOnly | `204` | `404`, `409` while live offerings use it |
|
||||||
|
|
||||||
|
### Contact — public (module `Contact`)
|
||||||
|
Both answer `404` with an **empty body** while the form is closed (host switch OR CMS switch off); the website then shows its mailto fallback. Both stay reachable when the CMS is disabled.
|
||||||
|
| Method + path | Auth | Success | Other |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `GET /contact-messages/token` | public (marker); limiter `contact-token` 20/600 s | `200` `{ token, minSeconds, captcha: null \| { provider, siteKey } }` | `404` closed, `429` |
|
||||||
|
| `POST /contact-messages` headers `Idempotency-Key: <uuid>` (required), body `{ name, email, subject, message, hpCheck, token, captchaToken? }` | public (marker); limiter `contact-form` 5/600 s | `202` `{ "status": "received" }` — identical for genuine, spam and replay | `400` problem+json (`errors` per field), `404` closed, `413` problem (> 16384 bytes), `429` |
|
||||||
|
|
||||||
|
Limits: name 1-100, email 1-254 (regex `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`), subject 1-100 (opaque value chosen by the site), message 1-2000; all trimmed; control characters rejected (line breaks and tabs allowed in `message`). `hpCheck` is the honeypot, must be empty. `400` shape: `{ type, title, status, errors: { <field>: [code] } }`, codes `required | tooLong | invalid | expired`; fields `name, email, subject, message, token, idempotencyKey, body`. A forged, other-site or expired token is always `errors.token=["expired"]` (fetch a fresh token and retry once). Replays with the same key within 24 h get the same `202` without a second message; a `400` does not use up the key.
|
||||||
|
|
||||||
|
### Contact — management (AdminOnly; not public; behind the gate)
|
||||||
|
All answer `404` with an empty body while the **host** switch `Contact:Enabled` is off (the tables do not exist then). The CMS switch never closes them.
|
||||||
|
| Method + path | Success | Other |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET /contact-messages?status=&page=&pageSize=` | `200` `{ items[{id,receivedAt,name,email,subject,status,mailStatus}], page, pageSize, totalCount, unreadCount }`; default list = `new`,`read`,`archived` (**no spam**), `status=spam` shows spam apart; `pageSize` 1-100 (default 25); `unreadCount` = `new` only, never spam | `400` (`errors.page/pageSize/status`), `401`, `403`, `404`, `503` |
|
||||||
|
| `GET /contact-messages/{id:guid}` | `200` detail (list fields + `message, mailAttempts, mailError, retentionUntil`) | `404` |
|
||||||
|
| `PATCH /contact-messages/{id:guid}` `{ "status": "new"\|"read"\|"archived" }` | `200` detail (on a spam message = "not spam": normal retention from now) | `400 errors.status=["invalid"]`, `404` |
|
||||||
|
| `DELETE /contact-messages/{id:guid}` | `204` (hard delete) | `404` |
|
||||||
|
| `POST /contact-messages/{id:guid}/resend` (limiter `contact-resend` 5/600 s) | `200` `{ mailStatus, mailAttempts, mailed }` (`mailed:false` until CMS-U5) | `404`, `409` spam message, `429` |
|
||||||
|
| `GET /contact-settings` | `200` `{ enabled, hostEnabled }` (`enabled` = CMS switch, default **false**) | `401`, `403`, `404`, `503` |
|
||||||
|
| `PUT /contact-settings` `{ "enabled": true\|false }` | `200` same shape | `400 errors.enabled=["invalid"]` for anything that is not a JSON boolean, `401`, `403`, `404`, `503` |
|
||||||
|
|
||||||
|
`status`: `new|read|archived|spam|converted`; `mailStatus`: `pending|sent|failed|notApplicable`.
|
||||||
|
|
||||||
|
### Unchanged but relevant
|
||||||
|
`PUT /availability/status` (AdminOnly; body `{ newStatus, reason }`; `200` with the updated resource in the GET shape, `409` master-controlled) replaced `POST /availability/admin/status` (CMS-U7, no alias; API and admin app must be released together). `GET /availability/status` stays public; the gate exempts it for GET/HEAD only.
|
||||||
|
|
||||||
|
## 2. `Contact:*` and related configuration keys (Api.SlpSoftware `appsettings.json`)
|
||||||
|
| Key | Default | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `Contact:Enabled` | `false` | host switch; **release condition**, see § 3 |
|
||||||
|
| `Contact:SiteId` | `slpsoftware` (code default `default`) | stored on rows, in the token purpose; never from a request |
|
||||||
|
| `Contact:MinSeconds` | `3` | returned as `minSeconds`; faster = spam |
|
||||||
|
| `Contact:TokenLifetimeMinutes` | `120` | |
|
||||||
|
| `Contact:RetentionMonths` | `12` | fixed per row at insert |
|
||||||
|
| `Contact:SpamRetentionDays` | `30` | |
|
||||||
|
| `Contact:MaxSpamRowsPerDay` | `200` | per site per UTC day; beyond it spam is answered but not stored |
|
||||||
|
| `Contact:MaxBodyBytes` | `16384` | `413` beyond |
|
||||||
|
| `Contact:ProblemTypeBase` | none -> `about:blank` | `{base}/validation` when set |
|
||||||
|
| `Contact:Captcha:Enabled` | `false` | |
|
||||||
|
| `Contact:Captcha:Provider`, `:SiteKey` | none | returned in the token response when enabled |
|
||||||
|
| `Contact:Captcha:Secret` | none | environment / secrets manager only, never committed |
|
||||||
|
| `RateLimiting:ContactForm` | `5` / `600` | `PermitLimit` / `WindowSeconds` |
|
||||||
|
| `RateLimiting:ContactToken` | `20` / `600` | |
|
||||||
|
| `RateLimiting:ContactResend` | `5` / `600` | |
|
||||||
|
| (removed) | | `Offerings:Categories` no longer exists; categories are data |
|
||||||
|
|
||||||
|
CMS switch (not configuration): table `ContactSettings`, `PUT /contact-settings`, default off. Mail recipient/sender settings arrive with CMS-U5 (environment only, no addresses in committed config).
|
||||||
|
|
||||||
|
## 3. Release / rebase checklist (do in this order, after Bryan merges `feature/identity-email-notifications`)
|
||||||
|
1. Rebase `feature/contact-forms-module` onto the merged base. Expected conflicts: `AvailabilityMiddleware.cs` (one block), `AddCmsRateLimiting` (`OnRejected`), `appsettings` files, host composition, maybe EF snapshots (own contexts, so none expected; regenerate our migration only if a snapshot conflicts). Re-run all test projects.
|
||||||
|
2. **Per-client rate limiting**: in `Modules.Contact/Services/ContactSeams.cs`, class `ContactRateLimitPartition`, change `public static string KeyFor(HttpContext context) => GlobalKey;` to `=> ClientPartitionKey.For(context);` (add the ASF `using`; drop `GlobalKey` if unused). In `Contact.Tests/ContactRetentionAndPartitionTests.cs`, test `OnTheBaseBranch_EveryCallerSharesOneBucket` becomes "two different client addresses give two different keys". Until this is done every visitor shares one bucket per policy (5 form submissions per 10 minutes for the whole site), which is why the module is off by default.
|
||||||
|
3. `ForwardedHeaders:KnownProxies` configured on the host (environment).
|
||||||
|
4. Phase 2 units (CMS-U5 mail + retry job, CMS-U6 UI, CMS-U7) on the rebased branch; give the Andrea host the Contact module reference and its own `openapi/andreaslopfotografie.v1.json` when it is in scope.
|
||||||
|
5. Only then set **`Contact:Enabled=true`** on the host (environment or its appsettings).
|
||||||
|
6. Switch the **CMS switch** on: it is OFF by default, so Bryan must open the form himself (screen "Berichten" in CMS-U6, or `PUT /api/v1/contact-settings {"enabled":true}`). Until both switches are on the website shows its mailto fallback.
|
||||||
|
7. Nothing is deployed to production without Bryan; no push/merge/PR happened.
|
||||||
|
|
||||||
|
## 4. Known deviations from contract v0.3.x and design decisions to adopt
|
||||||
|
- **Admin routes** are RESTful on the resource (`/contact-messages`, `/offerings`, `/contact-settings`), no `admin` segment, per Bryan's decision; old `offerings/admin...` routes and move-up/move-down are gone (reorder via `PUT /offerings/order`).
|
||||||
|
- **One offering DTO** for everybody (`OfferingAdminDto` removed): adds `displayOrder`, `categoryId`; `category` is the name.
|
||||||
|
- **Categories are CMS data** (table + CRUD), not `Offerings:Categories`.
|
||||||
|
- **Honeypot** JSON name is fixed `hpCheck` (no configurable name); a **missing `hpCheck` counts as empty**.
|
||||||
|
- **Unbindable body** (malformed JSON, wrong types) -> `400` with `errors.body=["invalid"]` in the same problem shape (the contact controllers are deliberately not `[ApiController]`).
|
||||||
|
- **`Contact:ProblemTypeBase`** configurable, default `about:blank` (instead of a fixed URL).
|
||||||
|
- **Two-layer switch**: host `Contact:Enabled` and the CMS switch; both default off; `404` empty body when closed.
|
||||||
|
- **`GET /contact-settings`** returns the extra read-only `hostEnabled`.
|
||||||
|
- **Un-spam** (PATCH spam -> new/read/archived) extends retention to the normal period; **resend of spam = 409**.
|
||||||
|
- **Management routes answer `404`** while the host switch is off; **an Owner/Administrator passes the availability gate** while the CMS is disabled (existing design), visitors get `503`.
|
||||||
|
- **Mail**: stored first; the mail seam (`IContactMailSender`) is a no-op until CMS-U5, so messages stay `pending` and resend reports `mailed:false`.
|
||||||
|
- **Rate limits** are global buckets on this base until the checklist step 2 (documented, enforced by the default-off switches).
|
||||||
|
- **Privacy**: no IP address is stored; Sentry error events carry the caller's IP (`SendDefaultPii`) but never form content — mention error reporting in the privacy statement. Backups may keep deleted messages longer than the retention period — mention or shorten backup retention.
|
||||||
|
|
||||||
|
## 5. Tests and tooling worth knowing
|
||||||
|
- Pipeline tests (`Contact.Tests/Pipeline`, `Api.Tests`) need `ConnectionStrings__DefaultConnection` pointing at a MariaDB/MySQL server on which databases may be created (CI provides it: `.gitea/workflows/continuous_integration.yaml`). Each fixture creates and drops its own database. Unit tests only: `dotnet test --filter "FullyQualifiedName!~Pipeline"`.
|
||||||
|
- Frontend (`frontend/`): `pnpm lint`, `npx tsc -b`, `pnpm test` (278 tests at CMS-U1b). 15 pre-existing files under `features/offerings` fail `prettier --check` (tech debt, not touched).
|
||||||
|
- The admin frontend work of phase 1 is only the offerings part (new routes, `useMoveOffering` via `PUT /offerings/order`, categories dialog + select, query key `['offerings','list']`).
|
||||||
|
- Last test run (CMS-U4): Contact.Tests 223, Core 205, Availability 95, Offerings 86, Identity 37, Master 57, Api.Tests 4 — all green.
|
||||||
|
|
||||||
|
## 6. Rebase result (2026-11-10)
|
||||||
|
Rebased onto `origin/master` `e671078` (merge of PR #11: identity-email-notifications + andreaslop-site-hosting). Conflicts: `aidlc-docs/active-features.md` (kept master's table, appended our row), `AvailabilityMiddleware` (kept their `CheckAdmin` / expired-token 401 behaviour, our marker block before it), `AddCmsRateLimiting.OnRejected` (kept their Retry-After logic for sliding windows, added the `60 s` fallback for policies without a wait and the problem+json body), `SlpModularCms.sln` (took master's, re-added the two Contact projects). No EF snapshot conflict (own contexts). Checklist steps 1 and 2 are DONE: `ContactRateLimitPartition.KeyFor` now returns `ClientPartitionKey.For(context)` and its test asserts different buckets per address. Still open: step 3 (`ForwardedHeaders:KnownProxies` per host), step 5 (`Contact:Enabled=true`), step 6 (CMS switch). `GET /System/capabilities` now carries `[PublicSiteEndpoint]` (never 503; separate commit). The pipeline tests for the management routes log in with a real user (the host validates every access token against its user and security stamp).
|
||||||
|
|
||||||
|
## 7. CMS-U5 additions (contact mail)
|
||||||
|
- Recipient address: since CMS-U11 the **site setting wins over** the env var `Contact__RecipientEmail` (see section 9); the env var stays the default/fallback (SLP: environment only, like ASF). Optional `Contact__Mail__SweepSeconds|MaxAttempts|ClaimMinutes|BatchSize`, `Contact__Mail__BackoffMinutes__0..n`.
|
||||||
|
- Mail itself needs the host's normal `Email:*` configuration; without it messages stay `pending` with `mailError: "disabled"`.
|
||||||
|
- Detail: `nextMailAttemptAt`; resend: `mailError`. New migration `ContactMailClaim`.
|
||||||
|
|
||||||
|
|
||||||
|
## 8. CMS-U9 additions (Friendly Captcha v2 and the ASF host)
|
||||||
|
|
||||||
|
### Captcha contract (no wire change)
|
||||||
|
- `GET /contact-messages/token` -> `captcha: null` while off, otherwise `{ "provider": "friendlycaptcha", "siteKey": "<public site key>", "apiEndpoint": "global" | "eu" }`. `apiEndpoint` (additive, default `global`) is the widget's data region and follows `Contact:Captcha:Region`, so switching region needs no website rebuild. Nothing else about the captcha (API key, verify URL) is ever returned.
|
||||||
|
- `POST /contact-messages`: `captchaToken` = the widget's response string (the widget also puts it in the form field `frc-captcha-response`). While the captcha is on, a **missing, empty or rejected** value is treated as spam: answer `202 {"status":"received"}` identical to a genuine message, stored with status `spam` (never a 400, so a bot learns nothing). While the captcha is off the field is ignored.
|
||||||
|
- Verify (server side, Friendly Captcha **v2**): `POST https://global.frcapi.com/api/v2/captcha/siteverify` (EU-only: `https://eu.frcapi.com/api/v2/captcha/siteverify`), header `X-API-Key: <API key>`, JSON `{ "response": "...", "sitekey": "..." }`; `success:true` passes, `success:false` (HTTP 200 `response_invalid|response_timeout|response_duplicate`, or 400 `response_missing|bad_request`) = spam. Checked against developer.friendlycaptcha.com on 2026-11-10.
|
||||||
|
- **Fail-open**: timeout (default 3 s), network error and 5xx let the visitor through (warning `captcha_unavailable`, kind only). Our own wrong API key or site key (HTTP 401, or 400 with `error_code: sitekey_invalid`) also lets the visitor through but logs an **error** `captcha_misconfigured`. The response token, the API key and the site key are never logged.
|
||||||
|
|
||||||
|
### Configuration (per site)
|
||||||
|
| Key | Notes |
|
||||||
|
|---|---|
|
||||||
|
| `Contact:Captcha:Enabled` | default `false` |
|
||||||
|
| `Contact:Captcha:Provider` | `friendlycaptcha` (only supported value; case-insensitive) |
|
||||||
|
| `Contact:Captcha:SiteKey` | public; sent to the browser |
|
||||||
|
| `Contact__Captcha__Secret` | the API key; **environment variable / secrets manager only**, never committed |
|
||||||
|
| `Contact:Captcha:Region` | `global` (default) or `eu`; decides the verify host and the `apiEndpoint` announced to the widget. Unknown value = host refuses to start |
|
||||||
|
| `Contact:Captcha:VerifyUrl` | optional override, normally empty (derived from Region); if set it must be https **and match the Region's host** (`global.frcapi.com` / `eu.frcapi.com`), otherwise the host refuses to start |
|
||||||
|
| `Contact:Captcha:TimeoutSeconds` | default 3 (1-30) |
|
||||||
|
|
||||||
|
With `Contact:Enabled=true` and `Captcha:Enabled=true` the host **refuses to start** when provider, site key or secret is missing/invalid (the message names the setting only, never a value).
|
||||||
|
|
||||||
|
### Widget (website session) and CSP
|
||||||
|
- Widget: Friendly Captcha v2 SDK with `sitekey` = `siteKey` from the token response; for the EU endpoint the widget needs `apiEndpoint: "eu"` (`data-api-endpoint="eu"`). The response goes into `captchaToken`. Exact SDK package/events: to be verified by the website session against the SDK docs.
|
||||||
|
- **CSP** (decision: exact origins, no wildcard): the v2 widget renders in iframes and the provider's CSP guide requires `frame-src` for `*.frcapi.com`. New option `SecurityHeaders:AllowedSiteFrameOrigins` (StrictSite only; empty = header byte-identical to before; origins only, validated at start-up; the admin and relaxed policies never get it). ASF values (owner decision: main host plus two reserve hosts, exact, no wildcard): `SecurityHeaders__AllowedSiteFrameOrigins__0=https://global.frcapi.com`, `__1=https://global0.frcapi.com`, `__2=https://global1.frcapi.com`. On the switch to the EU region use `https://eu.frcapi.com`, `https://eu0.frcapi.com`, `https://eu1.frcapi.com` instead (together with `Contact__Captcha__Region=eu`). The resulting directive is `frame-src 'self' https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com`. No `connect-src`/`script-src` additions are documented by the provider; a browser test with the real widget is still needed.
|
||||||
|
- Privacy (provider statements, v2 docs): "Friendly Captcha does not rely on user tracking or cookies for its protection service". **Region `global`**: the visitor's IP address can be processed outside the EU. **Region `eu`** (dedicated endpoint "hosted in Germany"; paid Advanced/Enterprise plan): "personal information (i.e. visitor IP addresses) never leave the EU". The site's privacy page must name the captcha provider, the processing of the visitor's IP address for the challenge, and which region is in use; commercial use needs a paid plan with the provider. For a test or a launch without a paid plan keep `Contact:Captcha:Enabled=false`.
|
||||||
|
|
||||||
|
### ASF host (`Api.AndreaSlopFotografie`)
|
||||||
|
- References `Modules.Contact`; section `Contact` in its `appsettings.json` (`Enabled:false`, `SiteId: andreaslop`), the three contact rate-limit policies. Capabilities now list `Contact`; the module does nothing and touches no database while `Contact:Enabled=false`.
|
||||||
|
- Release conditions (also in the comment of that section): `ForwardedHeaders__KnownProxies__0` = reverse proxy (IIS) address first (otherwise the whole site shares one bucket); `Contact__RecipientEmail` (env only); mail via `Email__Smtp__*`, `App__PublicBaseUrl`; sender = `Email:FromAddress` or the address chosen in the site settings from `Email:AllowedFromAddresses` (set by environment for ASF); captcha settings above; then `Contact__Enabled=true` and the admin switch (Berichten).
|
||||||
|
- Host tests (`Api.AndreaSlopFotografie.Tests/ContactHostTests.cs`, real MariaDB): closed by default; public routes stay reachable (200/202) while the availability gate is "not available" and the management routes answer 503; per-client buckets with a known proxy vs one shared bucket without.
|
||||||
|
|
||||||
|
## 9. CMS-U11 additions (recipient address from the site settings)
|
||||||
|
|
||||||
|
Order of precedence for the address contact mails are sent to: **site setting (CMS admin, Berichten) > `Contact__RecipientEmail` (environment) > none.** The setting changes without a restart (read on every send); an invalid stored value is ignored (falls back). Table `ContactSettings` gets a nullable `RecipientEmail` (migration `ContactSettingsRecipient`, additive).
|
||||||
|
|
||||||
|
| Method + path | Auth | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET /contact-settings` | AdminOnly | now `{ enabled, hostEnabled, recipientEmail: string\|null, recipientSource: "setting"\|"config"\|"none" }`. `recipientEmail` is only the CMS setting; **the address from the environment is never returned** (source `config` = "set by the server configuration"). |
|
||||||
|
| `PUT /contact-settings/recipient` `{ "recipientEmail": string\|null }` | AdminOnly | `200` same shape as GET; `null`/blank clears the setting (back to the environment default); trimmed; `EmailAddressRules`; `400` problem+json `errors.recipientEmail = ["invalid"]` or `["tooLong"]` (> 254), never echoing the value; `401/403/404/503` as the other management routes. Not part of any public route or OpenAPI example. |
|
||||||
|
| `PUT /contact-settings` `{ enabled }` | AdminOnly | unchanged. |
|
||||||
|
|
||||||
|
Without any address (`recipientSource: "none"`) the host still starts and the form can still be switched on (warn, not block): messages are stored, the mail stays `pending` with `mailError: "recipient_not_configured"` (not counted as an attempt) and goes out by itself within seconds once an address is set (setting the address wakes the mail sender). The admin shows a warning banner on the switch card. Release condition for SLP/ASF: the address no longer has to be in the environment when it is set in the admin.
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
# Code Generation Plan — CMS-U0 offerings-restful-routes
|
||||||
|
|
||||||
|
Decision (Bryan via Redesign - SLS): no `/admin` segment in API routes; admin uses the same resource with the same verbs, access via authorization (`AdminOnly`), public endpoints via `[PublicSiteEndpoint]` (CMS-U2). Applies now to Offerings, in this feature, before the category units. API and admin frontend are deployed together, so **no old routes are kept**.
|
||||||
|
|
||||||
|
## Unit context
|
||||||
|
- **Phase 1**, base master `d9cc539`, first unit. No data model change, no migration.
|
||||||
|
- **Touches**: `Modules.Offerings` (controller, service, DTOs, tests) and `frontend/src/features/offerings` (api calls, mocks, tests). Does **not** touch Core, Availability, Identity, ASF-owned areas (auth/refresh, users, theme assets).
|
||||||
|
|
||||||
|
## Route mapping
|
||||||
|
| Today | New | Auth |
|
||||||
|
|---|---|---|
|
||||||
|
| `GET /offerings` (public DTO) | `GET /offerings` (single DTO, see below) | anonymous (rate limit `offerings-public` unchanged; `[PublicSiteEndpoint]` added in CMS-U2) |
|
||||||
|
| `GET /offerings/admin` | removed (same `GET /offerings`) | |
|
||||||
|
| `POST /offerings/admin` | `POST /offerings` | AdminOnly, 201 + `Location: /api/v1/offerings/{id}` |
|
||||||
|
| `PUT /offerings/admin/{id}` | `PUT /offerings/{id:guid}` | AdminOnly |
|
||||||
|
| `DELETE /offerings/admin/{id}` | `DELETE /offerings/{id:guid}` | AdminOnly (soft delete unchanged) |
|
||||||
|
| `PUT /offerings/admin/reorder` | `PUT /offerings/order` body `{ "orderedIds": [...] }` | AdminOnly (collection action, `order` cannot clash with `{id:guid}`) |
|
||||||
|
| `POST .../{id}/move-up`, `.../move-down` | removed | UI computes the new order and calls `PUT /offerings/order` |
|
||||||
|
|
||||||
|
`PATCH` is not introduced (no partial-update use case); `PUT` keeps its current full-replace semantics.
|
||||||
|
|
||||||
|
## Design question: public vs admin DTO on one URL
|
||||||
|
Today the admin DTO differs from the public DTO by exactly one field: `displayOrder`.
|
||||||
|
- **Recommended (A)**: one URL, **one DTO for everybody**, `OfferingDto` gains `displayOrder` (additive, harmless to the SLS frontend which already relies on array order). No auth-dependent response => no `Vary: Authorization`, no cache split, a single OpenAPI schema, `OfferingAdminDto` is deleted.
|
||||||
|
- Alternative (B): auth-dependent DTO on the same URL: needs `Vary: Authorization`/no shared caching, an OpenAPI `oneOf`, and hides nothing sensitive. Alternative (C): `?view=admin` query switch: not RESTful-pure, adds a parameter for one integer.
|
||||||
|
- Other side effects of (A): the `offerings-public` limiter (120/min) now also covers admin list calls (fine).
|
||||||
|
Needs your OK; default is A.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — DTO**: `OfferingDto` gets `int DisplayOrder` (appended); delete `OfferingAdminDto`; service `GetPublicOfferingsAsync`/`GetAllForAdminAsync` collapse into `GetOfferingsAsync`.
|
||||||
|
- [x] **Step 2 — Controller routes**: rewrite `OfferingsController` per the table; class stays `[Authorize(Policy = "AdminOnly")]` with `[AllowAnonymous]` only on `GET`; `Create` returns `Created("/api/v1/offerings/{id}", dto)`; remove `MoveUp`/`MoveDown` actions and `IOfferingsService.MoveUpAsync/MoveDownAsync` (+ repository `GetPreviousAsync/GetNextAsync` if unused elsewhere); reorder route `order`.
|
||||||
|
- [x] **Step 3 — Backend tests**: update `OfferingsControllerTests`, `OfferingsServiceTests`, repository tests (removed methods); add a route-table test (reflection over `OfferingsController` action routes + auth attributes: only `GET` is anonymous, all other actions inherit `AdminOnly`, no route contains `admin`).
|
||||||
|
- [x] **Step 4 — Frontend**: change URLs in `useOfferings`, `useCreateOffering`, `useUpdateOffering`, `useDeleteOffering`, `useReorderOfferings`; `useMoveOffering` computes the new id order client-side and calls `PUT /offerings/order` (keeps the UI buttons); `types.ts`: `OfferingAdminDto` becomes `OfferingDto` incl. `displayOrder` (or alias); update `mocks/handlers.ts` and tests (`OfferingsListPage.test.tsx`, `OfferingFormPage.test.tsx`, any others that assert URLs).
|
||||||
|
- [x] **Step 5 — Build + test (automatic)**: `dotnet build` solution; `dotnet test` Offerings.Tests (and Core.Tests/Availability.Tests as regression); `Api.Tests` need a local MySQL (they fail here with "connection refused" independent of this change; will be reported as such); frontend: lint + type-check + unit tests (`npm`/`pnpm` scripts as in `frontend/package.json`). Report real output.
|
||||||
|
- [x] **Step 6 — Docs**: summary in `construction/cms-u0-offerings-restful-routes/code/summary.md`, incl. the handoff note for the SLS site: `GET /api/v1/offerings` unchanged except the additive `displayOrder`.
|
||||||
|
- [x] **Step 7 — Commit** (one commit, Dutch message, Co-Authored-By line). No push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Core, Availability (incl. `POST admin/status`, see below), Identity, Master, host config, `[PublicSiteEndpoint]` (CMS-U2), OpenAPI export (CMS-U3), category work (CMS-U1), ASF-owned frontend areas.
|
||||||
|
|
||||||
|
## Findings for other controllers (report only)
|
||||||
|
- Only `AvailabilityController` has another `admin` segment: `POST /availability/admin/status`. Per your instruction it becomes `PUT /availability/status` (AdminOnly; `GET /availability/status` stays public) **in Phase 2, after the ASF merge**, checking callers: Master/SlaveStatus, poll client, frontend.
|
||||||
|
- No other controller has an `admin` segment. Several are verb-style RPC routes (`Auth/login`, `Auth/revoke`, `Master/register`, `Master/status` POST, `CmsInstance/{id}/status` PUT) — not changed; flagged for your later RESTful review.
|
||||||
|
|
||||||
|
## Traceability
|
||||||
|
Bryan's route decision (SLS message), contract § 6/§ 7 (to be aligned by SLS); Security: authorization unchanged in effect (only `GET` anonymous), covered by the route-table test.
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
# Code Generation Plan — CMS-U1 offerings-category (REVISED v2: categories are CMS data)
|
||||||
|
|
||||||
|
Supersedes v1 (appsettings list, `OfferingsOptions`, `offerings/admin/categories`). Decision (Bryan via Redesign - SLS): categories are data managed in the CMS as part of Offerings (sub-section/dialog, not a new page); Bryan creates "Websites" and "Onderhoud" himself — **nothing is seeded in code**. Contract § 7 updated by SLS. Builds on CMS-U0 (RESTful routes, single `OfferingDto`).
|
||||||
|
|
||||||
|
## What v1 had already been done (now stashed, not committed)
|
||||||
|
Built and green (74 Offerings tests) but based on `offerings/admin` routes and the appsettings list: `Offering.Category` string column + migration `AddOfferingCategory`, `OfferingsOptions`, `Offerings:Categories` in `Api.SlpSoftware/appsettings.json`, service validation + legacy-value rule, tests. Parked in `git stash` ("cms-u1-v1-…"). Reused: test scaffolding patterns only. Dropped: `OfferingsOptions`, appsettings key, legacy-value rule, string column and its migration.
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
- `OfferingCategory`: `Id` (Guid), `Name` (varchar 100, required, trimmed), `SortOrder` (int), `CreatedAt`, `UpdatedAt`. Unique index on `Name` (MySQL default collation is case-insensitive; the service also checks case-insensitively because InMemory tests do not enforce the index).
|
||||||
|
- `Offering.CategoryId` (Guid?, nullable) FK -> `OfferingCategory`, `DeleteBehavior.Restrict`.
|
||||||
|
- Migration `AddOfferingCategories` (Offerings context): new table + nullable column + FK + index. Additive; `Down` drops them. Generated with `dotnet ef` (the tool worked in v1: 9.0.19 produced a clean EF 10 migration).
|
||||||
|
|
||||||
|
## Routes (`/api/v1/offerings/categories`, all AdminOnly, no `/admin`)
|
||||||
|
| Route | Behaviour |
|
||||||
|
|---|---|
|
||||||
|
| `GET /offerings/categories` | list ordered by `SortOrder`, `Name`; each item `{ id, name, sortOrder, offeringCount }` (count of non-deleted offerings, for the UI) |
|
||||||
|
| `POST /offerings/categories` | body `{ name }`; 201 + Location; duplicate name (case-insensitive) => 409 ProblemDetails; blank/too long => 400 |
|
||||||
|
| `PUT /offerings/categories/{id:guid}` | rename (`{ name }`); duplicate => 409; unknown id => 404; offerings follow automatically (FK) |
|
||||||
|
| `DELETE /offerings/categories/{id:guid}` | 409 ProblemDetails while non-deleted offerings use it ("move the offerings first"); otherwise deleted (soft-deleted offerings that still point to it get `CategoryId = null` in the same transaction); unknown id => 404 |
|
||||||
|
Route `categories` cannot clash with `{id:guid}` on `/offerings`. Ordering/reordering of categories: **not in this unit** (order = creation order via `SortOrder`; reorder endpoint can be added cheaply later: `PUT /offerings/categories/order`).
|
||||||
|
|
||||||
|
## Offering changes
|
||||||
|
- `CreateOfferingRequest`/`UpdateOfferingRequest` gain `Guid? CategoryId`; if given it must exist => else `400` ValidationProblemDetails `errors.categoryId = ["invalid"]`; `null` clears the category.
|
||||||
|
- Single `OfferingDto` (from CMS-U0) gains `CategoryId` (Guid?, string in JSON like `Id`) and `Category` (name | null). Public JSON therefore carries `category` as the name or `null` (unchanged shape for the SLS frontend) plus the additive `categoryId`/`displayOrder`.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Revert v1 leftovers**: confirm the working tree only contains CMS-U0 (stash holds v1); delete nothing committed.
|
||||||
|
- [x] **Step 2 — Entities + DbContext**: `OfferingCategory`, `Offering.CategoryId` + navigation, mapping, unique index, FK Restrict; `Include` the category in `OfferingRepository` reads.
|
||||||
|
- [x] **Step 3 — Repository**: `IOfferingCategoryRepository` (list with usage counts, get, add, remove, exists-by-name case-insensitive, clear category on soft-deleted offerings); transaction support as in `OfferingRepository`.
|
||||||
|
- [x] **Step 4 — Services**: `IOfferingCategoriesService` (list/create/rename/delete with the rules above; exceptions `OfferingCategoryNameConflictException`, `OfferingCategoryInUseException`); `OfferingsService` validates `CategoryId` exists and maps `CategoryId`/`Category` into `OfferingDto`.
|
||||||
|
- [x] **Step 5 — Controllers**: `OfferingCategoriesController` (route `offerings/categories`, class-level `AdminOnly`) with ProblemDetails mapping (409 conflict, 409 in-use, 404, 400); `OfferingsController` handles invalid `categoryId` as 400.
|
||||||
|
- [x] **Step 6 — Migration** `AddOfferingCategories`.
|
||||||
|
- [x] **Step 7 — Tests (Offerings.Tests)**: category service (create trims, duplicate case-insensitive => conflict, rename conflict, rename unknown, delete in use => in-use, delete unused ok, delete clears soft-deleted references, list with counts and order); offering service (unknown `categoryId` => invalid, null clears, DTO carries id+name, rename visible through DTO); controller mapping (201/404/409/400); repository (FK round trip, case-insensitive exists); route-table test from CMS-U0 extended (all `categories` actions AdminOnly, none anonymous).
|
||||||
|
- [x] **Step 8 — Build + test (automatic)**: solution build; Offerings.Tests, Core.Tests, Availability.Tests; `Api.Tests` needs a local MySQL (fails here with "connection refused" regardless of the change). Report real output.
|
||||||
|
- [x] **Step 9 — Docs/handoff**: summary + handoff note for the SLS frontend (public `category` = name|null; additive `categoryId`) and for CMS-U1b (route list above).
|
||||||
|
- [x] **Step 10 — Commit** (one commit, no push).
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Core, Availability, Identity, host config/appsettings (no `Offerings:Categories` anymore), the marker (CMS-U2), OpenAPI export (CMS-U3), frontend (CMS-U1b).
|
||||||
|
|
||||||
|
## CMS-U1b outline (own plan after U1 is done)
|
||||||
|
Categorieën sub-section/dialog inside the Offerings admin (list with offering counts, add, rename, delete with the 409 message), plus a select in `OfferingForm` (`categoryId`, "geen categorie" option); services/hooks/mocks/tests under `frontend/src/features/offerings` only; ASF-owned frontend areas untouched.
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
# Code Generation Plan — CMS-U1b offerings-categories-ui
|
||||||
|
|
||||||
|
Frontend only, `frontend/src/features/offerings` (plus the two locale files). Backend routes come from CMS-U1 (commit f2ac377). Wishes from Bryan (via Redesign - SLS): no new page, part of Offerings management; a "Categorieën beheren" button opening a dialog/panel with list + add + rename + delete (409 in understandable Dutch); a "geen categorie" option in the select in the offering form.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
1. **Offerings list page**: a secondary button "Categorieën beheren" next to "Aanbieding toevoegen" opens a dialog. No route change.
|
||||||
|
2. **Categories dialog** (`CategoriesDialog`): lists categories in API order with the number of offerings (e.g. "Websites · 2 aanbiedingen"); an input + "Toevoegen" at the bottom; each row has rename (pencil: inline input with confirm/cancel, Enter confirms, Escape cancels) and delete (trash: inline "Weet je het zeker? Verwijderen / Annuleren"). Empty state: "Nog geen categorieën. Voeg de eerste toe." Mutation errors show as an inline `role="alert"` message in the dialog.
|
||||||
|
3. **Error messages (Dutch, not taken from the English API titles)**: create/rename `409` => "Er bestaat al een categorie met de naam '{{name}}'." ; delete `409` => "Deze categorie wordt nog gebruikt door {{count}} aanbieding(en). Verplaats die eerst naar een andere categorie." (count from the list data); network => existing `errors.network`; other => `errors.generic`. Blank name is rejected client-side ("Vul een naam in.", max 100 characters).
|
||||||
|
4. **Offering form**: a "Categorie" select with the categories and a first option "Geen categorie" (internal value `none`, because Radix Select forbids an empty value). Create sends `categoryId: null` or the id; edit preselects the current category; if the category list is empty the select still shows only "Geen categorie". A stale/unknown `categoryId` from the server falls back to "Geen categorie".
|
||||||
|
5. **Offering row** shows the category name as a small badge when present.
|
||||||
|
6. Everything stays consistent through query invalidation: category mutations invalidate `['offerings','categories']` and `['offerings','admin']` (a rename shows in the list and form immediately).
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Types and schema**: `services/types.ts`: `OfferingDto` gains `categoryId?: string | null` and `category?: string | null`; `CreateOfferingRequest` gains `categoryId?: string | null`; new `OfferingCategoryDto { id, name, sortOrder, offeringCount }`. `schemas/offering.ts`: `categoryId: z.string().nullable().optional()`; new `categoryNameSchema` (trimmed, 1..100).
|
||||||
|
- [x] **Step 2 — Services**: `useOfferingCategories` (GET `/api/v1/offerings/categories`), `useCreateOfferingCategory` (POST), `useRenameOfferingCategory` (PUT `/{id}`), `useDeleteOfferingCategory` (DELETE `/{id}`), same pattern as the existing hooks.
|
||||||
|
- [x] **Step 3 — Components**: `components/CategoriesDialog.tsx` (state: editing id, delete-pending id, new name, error), reuse `Dialog`, `Button`, `Input`, `FieldError`; `OfferingForm.tsx`: category select (Radix `Select` from `components/ui/select.tsx`); `OfferingRow.tsx`: badge; `OfferingsListPage.tsx`: the button + dialog.
|
||||||
|
- [x] **Step 4 — i18n**: add `offerings.categories.*` and `offerings.form.categoryLabel/noCategory` to `nl` and `en` translation files (Dutch is the primary wording above; English counterparts provided).
|
||||||
|
- [x] **Step 5 — Mocks**: `mocks/handlers.ts`: category endpoints with the real behaviours (409 duplicate case-insensitive, 409 in use with counts from the mock offerings, 404 unknown) and offering POST/PUT accepting `categoryId` and returning `categoryId`/`category`. Seed: no categories (nothing is seeded in the real system either); tests add their own.
|
||||||
|
- [x] **Step 6 — Tests (Vitest + Testing Library + msw)**: dialog (empty state; add; blank name rejected; duplicate name shows the Dutch message; rename; delete unused; delete in-use shows the count message and keeps the row), form (select lists categories and "Geen categorie"; submit sends the chosen `categoryId` or `null`; edit preselects; unknown id falls back), list page (button opens the dialog; the category badge renders), schema test.
|
||||||
|
- [x] **Step 7 — Verification (automatic)**: `pnpm lint`, `npx tsc -b`, `pnpm test` (full suite). New files are formatted with prettier; the 15 pre-existing prettier warnings are left alone (tech debt, already reported).
|
||||||
|
- [x] **Step 8 — Docs and commit**: `construction/cms-u1b-offerings-categories-ui/code/summary.md`; one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Backend, ASF-owned frontend areas (auth/refresh, users, theme assets), router, other features, shared UI primitives except by using them (no edits to `components/ui`).
|
||||||
|
|
||||||
|
## Traceability
|
||||||
|
Bryan's category decision, contract § 7 (v2), CMS-U1 handoff (routes, 409 semantics, `offeringCount`).
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Code Generation Plan — CMS-U2 gate-and-limiter
|
||||||
|
|
||||||
|
Phase 1, base: current branch (master `d9cc539` + CMS-U0/U1/U1b). Decisions: D6 (the availability gate blocks only the CMS/admin; public site endpoints stay reachable), D9 (marker attribute, deny-by-default), FR-B1 (429 with `Retry-After` and ProblemDetails), SLS remarks (route-table style test: the marker only on the three allowed public routes; every other endpoint stays behind the gate). Keep the diffs in `AvailabilityMiddleware` and the rate-limiter file minimal (R3: both are files the ASF session also changes).
|
||||||
|
|
||||||
|
## Findings on master that shape the plan
|
||||||
|
- `AddCmsRateLimiting` (Core/Hosting/ServiceCollectionExtensions.cs): `OnRejected` currently only logs a security event; no body, no `Retry-After`. Policies are plain `AddFixedWindowLimiter/AddSlidingWindowLimiter` (login, refresh, Sentry tunnel, offerings-public). `UseRateLimiter` runs before `UseCors` and the module middleware.
|
||||||
|
- `AvailabilityMiddleware` is registered by the module via `UseMiddleware` after the implicit `UseRouting`, so `context.GetEndpoint()` is available there (the rate limiter already relies on endpoint metadata the same way).
|
||||||
|
- Master has no `ClientPartitionKey` and no `Contact` module yet; the contact routes join the allowlist in CMS-U3. The 3 public routes of the decision are: `GET /offerings` (exists now), `GET /contact-messages/token` and `POST /contact-messages` (CMS-U3).
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
1. **429 response (all existing and future policies)**: status 429, header `Retry-After: <whole seconds, at least 1>` taken from the limiter lease (`MetadataName.RetryAfter`), falling back to 60 s when the lease does not report one; body `application/problem+json` `{ type: "https://www.rfc-editor.org/rfc/rfc6585#section-4", title: "Too many requests", status: 429 }`. The security event call stays exactly as it is. Policy numbers are not changed.
|
||||||
|
2. **Marker** `[PublicSiteEndpoint]` (sealed attribute, `AttributeTargets.Method`, in `SlpModularCms.Core.Availability`): an endpoint carrying it is let through `AvailabilityMiddleware` before the master/local gate is evaluated. Everything else stays deny-by-default, including all admin routes. Existing prefix bypasses (`/api/v1/Availability/status`, Auth, Setup/status, master, SlaveStatus, `/health`) and the verified-admin-token bypass are untouched.
|
||||||
|
3. **Marked now**: only `OfferingsController.GetOfferings`. (U3 adds the two contact routes.)
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Core**: add `Core/Availability/PublicSiteEndpointAttribute.cs`.
|
||||||
|
- [x] **Step 2 — Middleware (minimal diff)**: in `AvailabilityMiddleware.InvokeAsync`, right after the prefix-bypass block, add the endpoint-metadata check (4 lines + comment). No other change.
|
||||||
|
- [x] **Step 3 — OnRejected (minimal diff)**: make the lambda `async`, keep the security event call, then set `Retry-After` and write the ProblemDetails JSON.
|
||||||
|
- [x] **Step 4 — Mark** `GetOfferings` with `[PublicSiteEndpoint]` (Offerings module).
|
||||||
|
- [x] **Step 5 — Tests**:
|
||||||
|
- Core.Tests: `OnRejected` (resolved from `IOptions<RateLimiterOptions>` after `AddCmsRateLimiting`, called with a fake lease): sets `Retry-After` rounded up from the lease value (e.g. 0.2 s -> 1, 61.5 s -> 62), falls back to 60 without lease metadata, writes `application/problem+json` with status 429, still logs the security event with policy name and path, status code is 429.
|
||||||
|
- Api.Tests (existing real-pipeline test `Sentry_tunnel_rate_limiter_engages_after_the_configured_permit_limit`): additionally assert the `Retry-After` header and the problem+json content type on the 429 (needs the local database; run with the container).
|
||||||
|
- Availability.Tests (middleware): marked endpoint passes while the system is disabled, in maintenance, and with the master gate closed; an unmarked endpoint with the same state still gets 503; a marked endpoint does not bypass anything else (a request without endpoint metadata is still blocked); `/api/v1/Availability/status` stays open.
|
||||||
|
- Availability.Tests (route-table style, SLS request): reflection over the controllers of the referenced modules (Availability, Identity, Master, Offerings; test-only project references): (a) the set of actions carrying the marker is exactly `{ OfferingsController.GetOfferings }` (the test names the allowlist so CMS-U3 extends it deliberately); (b) for every other controller action the middleware, given an endpoint with that action's attributes and a closed gate, answers 503 — which covers all admin routes, and the marker is never on an `AdminOnly`/`[Authorize]` action.
|
||||||
|
- Offerings.Tests: `GetOfferings` has the marker and `[AllowAnonymous]`; no other action of the controller has the marker.
|
||||||
|
- [x] **Step 6 — Verification (automatic)**: build solution; Core, Availability, Offerings, Identity, Master tests; Api.Tests with a temporary MariaDB container (started for the run and removed afterwards, as agreed); report real output.
|
||||||
|
- [x] **Step 7 — Docs/commit**: `construction/cms-u2-gate-and-limiter/code/summary.md` incl. handoff note (public routes stay reachable when the CMS is disabled/maintenance; frontend 503 fallback now only applies to admin calls); one commit, no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Policy numbers and partitioning (no `ClientPartitionKey` here; that is the ASF branch), ForwardedHeaders, host config, Email, Identity, Master, bypass-prefix list, other controllers' routes, `POST admin/status` (CMS-U7, phase 2).
|
||||||
|
|
||||||
|
## Rebase notes (for after the ASF merge)
|
||||||
|
Expected conflicts: `AvailabilityMiddleware.cs` and `AddCmsRateLimiting`; both edits are small and isolated (one block each), so they should merge by hand without redesign. Re-run the marker/route-table tests after the rebase.
|
||||||
|
|
||||||
|
## Traceability
|
||||||
|
D6, D9, FR-B1/B2, requirements R3; Security Baseline: deny-by-default, no information leak in the 429 body, no PII.
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
# Code Generation Plan — CMS-U3 contact-core
|
||||||
|
|
||||||
|
Phase 1, base: current branch (master + CMS-U0/U1/U1b/U2). Inputs: contract v0.3.x (§ 2-5), requirements D2/D3/D5, application-design § 3-7 (admin routes superseded by unit-of-work: RESTful, no `/admin`), functional-design decisions below. Scope: the **public** contact endpoints and everything they need. Admin endpoints are CMS-U4, real mail is CMS-U5, OpenAPI export is split off as **CMS-U3b** (see end) to keep this unit reviewable.
|
||||||
|
|
||||||
|
## RELEASE CONDITION (explicit, as agreed)
|
||||||
|
On master the rate-limit policies are global buckets (no per-client partition key, no ForwardedHeaders; both exist only on the ASF branch). A per-IP contact policy would then be one bucket for the whole site: five submissions would block everybody. **The contact routes must not be enabled on a public host until the per-client partitioning from the ASF branch is on the base branch.** This is enforced in code, not only documented: see `Contact:Enabled` below.
|
||||||
|
|
||||||
|
## Rate limiting: how it behaves on master and how it switches after the rebase
|
||||||
|
- Policies `contact-form` (5 per 600 s), `contact-token` (20 per 600 s) and (CMS-U4) `contact-resend` (5 per 600 s) are registered **inside the Contact module** through `services.Configure<RateLimiterOptions>(...)`, so the shared `AddCmsRateLimiting` file (also edited by the ASF branch) is not touched in this unit.
|
||||||
|
- Each policy is built with `RateLimitPartition.GetFixedWindowLimiter(partitionKey, ...)`, and the key comes from exactly one function in the module: `ContactRateLimitPartition.KeyFor(HttpContext)`. **On master it returns the constant `"global"`**, so the policies behave as one shared bucket per policy (the documented, known state — safe, because the routes are disabled by default on any host).
|
||||||
|
- **After the ASF merge and rebase**, switching to per-client is a one-line change in that single function: `return ClientPartitionKey.For(context);` (the ASF helper). No policy, controller or test is rewritten. A test pins the function: it currently asserts the constant, and the rebase commit changes that one assertion to "two different client addresses give two different keys".
|
||||||
|
- No own partitioning, forwarded-header parsing or IP handling is built here (would clash with the ASF implementation).
|
||||||
|
|
||||||
|
## Safety switch
|
||||||
|
`Contact:Enabled` (default **false**). While false the module registers nothing active: the two contact routes answer **404** (an endpoint filter on the controller short-circuits before any work), no database access, no hosted service work (the retention job starts but does nothing), no key-ring use. Enabling is an explicit act per host (appsettings of the host or environment) and belongs to the release step after the rebase. Tests run with it enabled. The 404 body is empty (nothing revealed). The two routes still carry `[PublicSiteEndpoint]` so the gate behaviour is the same once enabled.
|
||||||
|
|
||||||
|
## Components (see application-design § 3)
|
||||||
|
`Modules.Contact` + `Modules.Contact.Tests` (solution folders Application/Modules and Tests/Modules), referenced by `Api.SlpSoftware` only (the Andrea host is not on master; the reference follows in phase 2).
|
||||||
|
- `ContactModule : IModule` ("Contact"): options, DbContext (MySQL, `NonLockingMySQLHistoryRepository`, `Database.Migrate()` in `UseModule`, same as Offerings), services, rate-limit policies, hosted service.
|
||||||
|
- `ContactDbContext`: `ContactMessage`, `IdempotencyRecord`. Migration `InitialCreate`. Tables `ContactMessages`, `ContactIdempotency`.
|
||||||
|
- `ContactMessagesController` (`[Route("contact-messages")]`, class `[AllowAnonymous]` for the two public actions only; admin actions arrive in U4 with `AdminOnly`): `GET token` (`[PublicSiteEndpoint]`, policy `contact-token`), `POST` (`[PublicSiteEndpoint]`, policy `contact-form`, `RequestSizeLimit` from `Contact:MaxBodyBytes`).
|
||||||
|
- `ContactValidator` (pure), `ContactTokenService` (`IDataProtectionProvider`, purpose `SlpModularCms.Contact.Token.{siteId}`; keys already persist in the database via `AddCmsDataProtection`), `ContactSubmissionService`, `ICaptchaVerifier` + `NullCaptchaVerifier` (Friendly Captcha implementation comes later behind the same interface; fail-open), `IContactMailSender` + `NoOpContactMailSender` (real implementation in U5), `ContactRetentionService` (daily `BackgroundService`, pattern of `IntegrityCheckBackgroundService`), `ContactOptions` (`Contact:*`, validated), `ContactRateLimitPartition`.
|
||||||
|
|
||||||
|
## Functional design decisions (fills the contract's gaps)
|
||||||
|
1. **Validation** (pure function, trims first): name 1-100, email 1-254 + regex `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`, subject 1-100 (opaque, never checked against offerings), message 1-2000; control characters rejected in name, email, subject (newlines are allowed in message); `hpCheck` key present; `token` required. Error codes `required|tooLong|invalid|expired`; field names as in the JSON; ProblemDetails with `errors` and status 400; the `type` URI is configurable (`Contact:ProblemTypeBase`, default none => `about:blank`) so no site domain is hard-coded in a module that two sites use (open point 2).
|
||||||
|
2. **Idempotency**: header `Idempotency-Key` required, GUID (`errors.idempotencyKey: required|invalid`). Key + site id unique. A replay within 24 h returns the stored status code (always 202 for accepted requests) without a second row. A replay of a request that was *rejected* with 400 is not stored (so the client can correct and resend with the same key). The record holds only key, site, created-at, status code.
|
||||||
|
3. **Token**: `GET token` returns `{ token, minSeconds, captcha }`; token payload = issue time + site id, protected with the purpose string, lifetime `Contact:TokenLifetimeMinutes` (120). Verification outcomes: valid / too young (below `MinSeconds`) / expired-or-invalid (forged, other site, garbage, too old).
|
||||||
|
4. **Submission pipeline**: size limit -> idempotency header -> validation -> token: invalid/expired => 400 `errors.token=["expired"]` (no oracle); too young or honeypot filled or captcha rejected => **spam path**; otherwise genuine path. Spam path: store with `Status=Spam`, `RetentionUntil=now+SpamRetentionDays`, never mailed, unless the per-site daily cap (`Contact:MaxSpamRowsPerDay`, default 200) is reached (then not stored); response is the identical 202 `{ "status": "received" }`. Genuine path: store `Status=New`, `MailStatus=Pending`, `RetentionUntil=now+RetentionMonths`, then call `IContactMailSender` **after commit** and only record the outcome (U3: no-op => stays `Pending`/`NotApplicable`; U5 adds sweep + retry).
|
||||||
|
5. **Captcha**: disabled by default; when enabled and the token is missing or rejected => spam path; verifier failure (timeout/5xx) => fail-open with a log line without PII.
|
||||||
|
6. **Retention job**: daily; deletes `ContactMessages` where `RetentionUntil < now` and `IdempotencyRecords` older than 24 h; logs counts only.
|
||||||
|
7. **Site id**: `Contact:SiteId`, default = host name from `Contact:SiteId` fallback `Environment.ApplicationName`; never from the request.
|
||||||
|
8. **Privacy/logging**: no IP stored; no name/email/message/body in any log, exception or Sentry event. Findings: Sentry is configured with `MaxRequestBodySize = None` and the `SentryEventScrubber`; the plan adds (a) request logging for these routes is off, (b) a log-capture test that submits a request carrying marker strings in all fields, forces an exception in the service and asserts none of the marker strings appears in any log entry or exception message, (c) a scrubber test that a Sentry event built from such an exception has no body/field values. Model-binding errors use the custom problem shape, never echo values.
|
||||||
|
9. **Security Baseline**: allow-list validation, bounded sizes, deny-by-default gate, generic 5xx (`UseExceptionHandler` already returns ProblemDetails), no secrets in config (captcha secret via env), no oracle on token errors.
|
||||||
|
|
||||||
|
## Configuration (`Contact:` section; defaults as in application-design § 4)
|
||||||
|
`Enabled=false`, `SiteId`, `MinSeconds=3`, `TokenLifetimeMinutes=120`, `RetentionMonths=12`, `SpamRetentionDays=30`, `MaxSpamRowsPerDay=200`, `MaxBodyBytes=16384`, `HoneypotField=hpCheck`, `Captcha:{Enabled=false,Provider,SiteKey,Secret}`; `RateLimiting:ContactForm` (5/600), `RateLimiting:ContactToken` (20/600). Recipient/sender e-mail addresses are not part of U3 (U5, env-only for ASF). `appsettings.json` of `Api.SlpSoftware` gets the section with `Enabled=false`; no addresses, no secrets.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Projects**: create `SlpModularCms.Modules.Contact` and `.Contact.Tests` (net10.0, same package set as Offerings/Offerings.Tests), add to `SlpModularCms.sln` (Application/Modules and Tests/Modules folders), reference from `Api.SlpSoftware`; no other project reference changes.
|
||||||
|
- [x] **Step 2 — Options, entities, DbContext, migration `InitialCreate`** (generated with dotnet ef; applied to a real MariaDB for verification).
|
||||||
|
- [x] **Step 3 — Pure logic**: `ContactValidator`, `ContactTokenService` (clock abstraction `TimeProvider`), spam classification, options validation.
|
||||||
|
- [x] **Step 4 — Services + repository**: submission pipeline, idempotency, spam cap, `ICaptchaVerifier`/`IContactMailSender` seams, retention service.
|
||||||
|
- [x] **Step 5 — Controller + wiring**: routes, `[PublicSiteEndpoint]`, rate-limit policies via `ContactRateLimitPartition`, size limit, `Contact:Enabled` 404 filter, module registration; add the two actions to `AllowedPublicActions` in `PublicSiteEndpointGateTests` (and the module assembly to its reflection list).
|
||||||
|
- [x] **Step 6 — Tests** (xUnit; PBT partial per D7): validator (examples + property tests: trimming idempotence, length boundaries 100/254/2000 inclusive, any control character in name/email/subject rejected, valid addresses accepted); token (round trip, expiry, too young, tampered, other site purpose) as properties/round-trips; submission service (genuine, honeypot, too fast, captcha reject, cap reached, idempotent replay, rejected-not-stored, mail seam called after commit only for genuine); retention service; endpoints via `WebApplicationFactory`-free controller + service tests plus a **real-pipeline test** (Api.SlpSoftware host against the temporary MariaDB) for: disabled => 404, enabled => token + POST 202, replay 202 without a second row, invalid => 400 shape, 413, 429 with Retry-After, and routes stay reachable with the CMS disabled; no-PII log test; route-table additions; `ContactRateLimitPartition` constant-key test (see above); migration applied on a real MariaDB (tables + unique index on idempotency).
|
||||||
|
- [x] **Step 7 — Verification (automatic)**: solution build; all test projects; Api.Tests and the new real-pipeline test with a temporary MariaDB container (removed afterwards); real output reported.
|
||||||
|
- [x] **Step 8 — Docs/commit**: summary incl. release condition and the rebase checklist (swap the partition function; set `Contact:Enabled` per host); one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
`AddCmsRateLimiting`/Core hosting files, `AvailabilityMiddleware`, Email, Identity, ASF-owned areas, host Program.cs, frontend, the Andrea host. No admin endpoints (CMS-U4), no mail sending (CMS-U5), no OpenAPI export (CMS-U3b).
|
||||||
|
|
||||||
|
## CMS-U3b (proposed separate small unit, right after U3)
|
||||||
|
Exported OpenAPI document committed as `openapi/cms-api.v1.json` with a snapshot test (`UPDATE_OPENAPI=1` rewrites; drift fails the build) and an `IOpenApiDocumentTransformer` adding the contract's reusable responses (Validation/TooLarge/RateLimited). Separate because it needs the host-level test harness and touches how the document is produced, which is unrelated to the contact logic.
|
||||||
|
|
||||||
|
## Open points for approval
|
||||||
|
1. `Contact:Enabled=false` default with 404 (my proposal to enforce the release condition in code). OK?
|
||||||
|
2. Validation problem `type`: configurable, default `about:blank` (instead of the contract's `https://slpsoftware.nl/problems/validation`, to avoid hard-coding a site domain in a module used by two sites). The frontend maps on `errors`, not on `type`. OK?
|
||||||
|
3. Split OpenAPI export into CMS-U3b. OK?
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
# Code Generation Plan — CMS-U3b openapi-export
|
||||||
|
|
||||||
|
Phase 1, right after CMS-U3. Contract: "the definitive OpenAPI document is generated by the CMS and committed, so `cms-client` generates its types from it" (§ 8, FR-H). Scope: the SlpSoftware host's API document as a committed file plus a test that keeps it current, and the contact contract details in it (reusable problem responses, required header, required request fields). No behaviour change of any endpoint.
|
||||||
|
|
||||||
|
## Findings
|
||||||
|
- The host already registers `services.AddOpenApi()` (Core, document `v1`) and, in Development only, `app.MapOpenApi()` which serves `/openapi/v1.json`; the pipeline test host runs in Development, so the document can be fetched over HTTP from the real composed host (no internal API needed).
|
||||||
|
- The shared registration lives in a Core file the ASF branch also changes. Everything contact-specific is therefore added **from the Contact module** through named options (`services.Configure<OpenApiOptions>("v1", ...)`), leaving Core untouched.
|
||||||
|
- `.NET 10`'s OpenAPI uses `Microsoft.OpenApi` 2.x types; the transformers are written against that model (risk noted below).
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
1. **Committed file** `openapi/slpsoftware.v1.json` (repo root), the OpenAPI document of the SlpSoftware host (Offerings, Contact, Identity, Availability, Master, System). Written deterministically: `servers` removed (it is derived from the request host), keys in the order the generator emits, 2-space indentation, LF line endings, trailing newline.
|
||||||
|
2. **Snapshot test** (pipeline test, needs the database like the other pipeline tests): fetches `/openapi/v1.json` from the real host, normalizes it the same way, and compares it with the committed file; any drift fails the test with a message that names `UPDATE_OPENAPI=1`. With `UPDATE_OPENAPI=1` the test rewrites the file instead (and still passes), so regenerating is one command: `UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot`.
|
||||||
|
3. **Contact contract details in the document** (module-level transformers):
|
||||||
|
- Reusable `components.responses`: `Validation` (400, `application/problem+json`, `ValidationProblem` with `errors` map of arrays of the codes `required|tooLong|invalid|expired`), `TooLarge` (413), `RateLimited` (429 with the `Retry-After` header, `Problem`), plus schemas `Problem` and `ValidationProblem`; referenced by the contact operations.
|
||||||
|
- `POST /api/v1/contact-messages`: required header parameter `Idempotency-Key` (uuid); request body schema marks `name, email, subject, message, hpCheck, token` as required with the contract's `maxLength` values (100, 254, 100, 2000, 0 for `hpCheck`), `captchaToken` nullable; responses 202/400/413/429 (404 is documented as "form closed").
|
||||||
|
- `GET /api/v1/contact-messages/token`: 200 (`ContactToken`: `token`, `minSeconds`, `captcha` nullable object) and 429; 404 "form closed".
|
||||||
|
- Attributes (`[ProducesResponseType]`) on the public contact actions drive the operations; the transformers only add what attributes cannot express (components, header, required/maxLength).
|
||||||
|
4. **cms-client note**: the file is the single source for generated types; the Andrea host will get `openapi/andreaslopfotografie.v1.json` when it exists on the base branch (name = host name); this unit documents the convention in the file's README line in the summary.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Attributes**: `[ProducesResponseType]` on `GetToken` and `Submit` (and `[ProducesResponseType<...>]` for the offerings list is already inferred by return types; nothing else is touched).
|
||||||
|
- [x] **Step 2 — Transformers** in `Modules.Contact/OpenApi/`: `ContactOpenApiDocumentTransformer` (components), `ContactOpenApiOperationTransformer` (header, response refs), `ContactOpenApiSchemaTransformer` (required/maxLength). Registered from `ContactModule.RegisterServices` via `services.Configure<OpenApiOptions>("v1", ...)`.
|
||||||
|
- [x] **Step 3 — Snapshot test + helper** in `Contact.Tests/Pipeline/OpenApiSnapshotTests.cs`: normalization (drop `servers`, stable formatting), repo-root lookup (walk up to `SlpModularCms.sln`), `UPDATE_OPENAPI=1` rewrite, a failing message with the exact regeneration command. Plus unit assertions on the fetched document (not only equality with the file): the contract details in item 3 exist (header required, reusable responses present, required fields and maxLength), so a regenerated file cannot silently lose them.
|
||||||
|
- [x] **Step 4 — Generate and commit** `openapi/slpsoftware.v1.json`; review it (no PII, no secrets, no host names, no example addresses).
|
||||||
|
- [x] **Step 5 — Verification (automatic)**: build; Contact.Tests (pipeline against a temporary MariaDB); full solution tests; real output. The test is run twice: once with `UPDATE_OPENAPI=1`, once without (must pass unchanged).
|
||||||
|
- [x] **Step 6 — Docs/commit**: summary (how to regenerate, how the frontend consumes it, convention per host); one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Core (`AddOpenApi`, `MapOpenApi`), any endpoint behaviour, other modules' controllers (their operations simply appear in the document as generated), the Andrea host (not on the base branch), frontend.
|
||||||
|
|
||||||
|
## Risks / open points
|
||||||
|
- The Microsoft.OpenApi 2.x model differs from 1.x examples found online; if a detail cannot be expressed through the transformer API, the unit documents it in the summary instead of faking it, and the test asserts what the document really contains.
|
||||||
|
- The file will be large (the whole host API). It is committed as is; reviewers diff it like code.
|
||||||
|
- Needs SLS confirmation: file name per host: `openapi/slpsoftware.v1.json` (approved).
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
# Code Generation Plan — CMS-U4 contact-admin-api
|
||||||
|
|
||||||
|
Phase 1, after CMS-U3b. Inputs: requirements D1/D2, contract § 6 (RESTful, no `/admin` segment), Bryan's two-layer switch (SLS message), CMS-U3 gate design (`IContactFormGate`). Scope: everything an administrator does with contact messages through the API, plus the CMS-controlled on/off switch. The UI is CMS-U6; the real mail sender is CMS-U5.
|
||||||
|
|
||||||
|
## Routes (all AdminOnly, same resource names as the public routes, no `/admin`)
|
||||||
|
New controller `ContactMessagesAdminController` (class-level `[Authorize(Policy = "AdminOnly")]`, route `contact-messages`; no action is anonymous or marked `[PublicSiteEndpoint]`), so public and admin actions are separated and the route-table tests stay trivial. Routes cannot clash with the public ones (`GET token`, `POST ""`) because of the `{id:guid}` constraint.
|
||||||
|
|
||||||
|
| Route | Behaviour |
|
||||||
|
|---|---|
|
||||||
|
| `GET /contact-messages?status=&page=&pageSize=` | list, newest first. `status` = `new|read|archived|spam` (a single value). **Default (no status) = `new`, `read`, `archived` — spam is never in the default list.** `page` from 1, `pageSize` 1-100 (default 25), out-of-range values -> 400 `errors.page/pageSize=["invalid"]`. Response `{ items:[{id, receivedAt, name, email, subject, status, mailStatus}], page, pageSize, totalCount, unreadCount }`. `unreadCount` = messages with status `new`, **never counting spam**, independent of the chosen filter. Message text is not in the list. |
|
||||||
|
| `GET /contact-messages/{id:guid}` | full message: all list fields plus `message`, `mailAttempts`, `mailError` (code only), `retentionUntil`. 404 unknown. |
|
||||||
|
| `PATCH /contact-messages/{id:guid}` | body `{ "status": "new"|"read"|"archived" }`. Setting one of these on a spam row "un-spams" it (a real visitor tripped a check); its `retentionUntil` is then extended to the normal retention (now + `RetentionMonths`) so it is not deleted in 30 days; `mailStatus` stays `notApplicable` until it is resent. Other values (`spam`, `converted`, unknown) -> 400 `errors.status=["invalid"]`. 404 unknown. |
|
||||||
|
| `DELETE /contact-messages/{id:guid}` | hard delete (erasure request), 204; 404 unknown. |
|
||||||
|
| `POST /contact-messages/{id:guid}/resend` | policy `contact-resend` (5 per 600 s). Spam rows -> 409 ProblemDetails ("mark it as not spam first"). Otherwise calls `IContactMailSender`, records the outcome (`attempts+1`, status `sent|failed`; `Skipped` leaves the status and reports it) and returns `200 { mailStatus, mailAttempts, mailed: true|false }`. Until the mail unit the sender is the no-op, so `mailed=false`. 404 unknown. |
|
||||||
|
| `GET /contact-settings` | singleton: `{ "enabled": bool, "hostEnabled": bool }`. `enabled` = the CMS switch (data, default **false** when no row exists); `hostEnabled` = the host switch `Contact:Enabled` (read-only, so the UI can explain why the form is closed). |
|
||||||
|
| `PUT /contact-settings` | body `{ "enabled": true|false }`; replaces the singleton, returns the same shape as GET. Stores who changed it and when. |
|
||||||
|
|
||||||
|
Statuses and mail statuses are serialized as lower-camel strings (`new`, `read`, `archived`, `spam`, `converted`; `pending`, `sent`, `failed`, `notApplicable`).
|
||||||
|
|
||||||
|
## Two-layer gate (the CMS switch)
|
||||||
|
- New table `ContactSettings` (singleton row: `Id` fixed, `Enabled`, `UpdatedAt`, `UpdatedByUserId`), migration `AddContactSettings` (additive).
|
||||||
|
- `CmsFlagContactFormGate` (layer 2) reads the row (absent = closed) through a short in-process cache (5 s absolute) that `PUT /contact-settings` invalidates immediately, so the public routes do not hit the database on every request. `CompositeContactFormGate` is registered as the `IContactFormGate`: the form is open only if **both** layers are open; layers are evaluated in order **host flag first** and short-circuit, so with the host switch off the database (and its not-yet-existing tables) is never touched.
|
||||||
|
- `ContactRouteFilter` is not modified (it only knows the interface), as agreed.
|
||||||
|
|
||||||
|
## Admin routes and the host switch
|
||||||
|
The admin routes need the Contact tables, which exist only when the host switch is on (the module migrates only then — the CMS-U3 requirement that a disabled module touches nothing). So when `Contact:Enabled=false` every admin route (including `contact-settings`) answers **404 with an empty body** via a small `ContactAdminRouteFilter` (host flag only; the CMS switch deliberately does not close the admin routes, otherwise nobody could switch the form back on). The UI (CMS-U6) treats a 404 on `GET /contact-settings` as "feature not available on this host" and hides the menu entry. `/System/capabilities` lists the module whenever it is loaded, so it is not enough on its own.
|
||||||
|
|
||||||
|
## Authorization and gate
|
||||||
|
All new routes require `AdminOnly` (Owner/Administrator). They are **not** marked `[PublicSiteEndpoint]`, so the availability gate blocks them when the CMS is off or in maintenance (verified by the route-table test).
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Settings model + migration** `AddContactSettings` (generated; applied to a real MariaDB for verification).
|
||||||
|
- [x] **Step 2 — Repositories/services**: list/detail/patch/delete/resend (`IContactMessageAdminService`), settings (`IContactSettingsService`), gates (`CmsFlagContactFormGate`, `CompositeContactFormGate`), cache with invalidation. Resend uses the existing `IContactMailSender` seam.
|
||||||
|
- [x] **Step 3 — Controllers + filter + rate-limit policy `contact-resend`** (registered in `ContactModule`, config `RateLimiting:ContactResend`, default 5/600; same single partition function as the other contact policies, so the rebase checklist still has one line).
|
||||||
|
- [x] **Step 4 — Tests**: services (default list excludes spam; each status filter; ordering and paging bounds; `unreadCount` ignores spam and filters; detail fields; patch transitions incl. un-spam extending retention; invalid statuses; delete; resend rules incl. spam -> 409 and `Skipped`/`Sent`/`Failed`; settings default false, PUT/GET round trip, cache invalidated on PUT); gates (host off -> closed without calling the database gate; host on + CMS off -> closed; both on -> open; unit test with substitutes proving short-circuit order); controllers (status codes, response shapes, lower-camel enum strings); **route-table test (explicit, as requested)**: every action of `ContactMessagesAdminController` is under class-level `AdminOnly`, none has `[AllowAnonymous]` or `[PublicSiteEndpoint]`, no route contains `admin`; the set of public contact actions stays exactly `{GetToken, Submit}` and `AllowedPublicActions` in the Availability route-table test is unchanged (the new routes are covered by its "everything else answers 503" check); pipeline tests on the real host and MariaDB: anonymous -> 401, authenticated without admin role -> 403 (minted JWT with the host's development JWT settings), administrator -> 200 flows (list/detail/patch/delete/resend), host switch off -> admin routes 404 empty, CMS switch off -> public routes 404 but admin routes still 200, switching it on through `PUT /contact-settings` makes the public routes work within the cache window, the CMS being disabled (availability) blocks admin routes with 503, `contact-resend` returns 429 with `Retry-After` after its limit, no personal data in any log entry written by the admin services.
|
||||||
|
- [x] **Step 5 — Verification (automatic)**: build; all test projects; pipeline tests against a temporary MariaDB (removed afterwards); real output.
|
||||||
|
- [x] **Step 6 — Docs/commit**: summary with the JSON shapes for the frontend handoff and the rebase notes (none new); one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
`ContactRouteFilter` (the public filter), the public controller, the public validation/submission logic, Core/Availability, Email, Identity, the frontend.
|
||||||
|
|
||||||
|
## Notes / assumptions to confirm
|
||||||
|
1. `hostEnabled` in `GET /contact-settings` is an addition to the agreed `{ enabled }` shape (read-only, lets the UI explain a closed form). OK?
|
||||||
|
2. Un-spamming extends retention to the normal period (otherwise the row would be deleted after the remaining spam days). OK?
|
||||||
|
3. Resend of a spam row = 409 instead of mailing it silently. OK?
|
||||||
|
4. Admin routes answer 404 when the host switch is off (tables do not exist then). OK?
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
# Code Generation Plan — CMS-U5 contact-mail (mail + retry)
|
||||||
|
|
||||||
|
Phase 2, on the rebased branch (base `origin/master` `e671078`). Inputs: contract § 4 (store first, mail after commit, no personal data in logs, From = fixed site sender, Reply-To = visitor), requirements FR-D, SLS decision "new MailKind, do not change existing mail code", CMS-U3/U4 seams (`IContactMailSender`, `ContactMessage.MailStatus/MailAttempts/MailError/NextMailAttemptAt`, resend endpoint). Nothing is deployed; `Contact:Enabled` stays off.
|
||||||
|
|
||||||
|
## Findings on the merged master (Core/Email)
|
||||||
|
- `IEmailSender.SendAsync(OutgoingMail)` returns a `MailSendResult(Sent, ErrorCode)`; never throws. `IMailAvailability.IsEnabled` is the single answer to "can this host send mail" (SMTP host set and configuration valid). `ISiteSettingsService.GetEffectiveSenderAsync` gives the effective From address/name (already checked against `Email:AllowedFromAddresses`). `ILanguageResolver` + `IMailTemplateRenderer` render subject/HTML/text from a static catalog per `MailKind` (nl/en), with dark-mode classes (`DarkPage`/`DarkCard`).
|
||||||
|
- The renderer's layout has a heading, a greeting, one intro paragraph, an optional button and a note. A contact mail also needs a block with the visitor's name, e-mail address, subject and message, and the mail needs a `Reply-To`. `OutgoingMail` has no reply-to member and `MailModel` has no list of details.
|
||||||
|
- `SmtpEmailSender` already classifies failures into short codes (`auth_failed`, `rejected_recipient`, `timeout_*`, ...); those codes are what `ContactMessage.MailError` stores.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
1. **Additive changes in the shared mail code (needs ASF/SLS consent, nothing existing changes behaviour)**: `MailKind.ContactMessage` (+ nl/en catalog entry); `MailModel` gets an optional `IReadOnlyList<MailDetail>? Details` (label/value pairs; values HTML-encoded, line breaks kept as `<br>` in HTML and plain lines in text, rendered inside the existing card with the existing muted/dark classes so the dark-mode contrast is kept); `OutgoingMail` gets optional `ReplyToAddress`/`ReplyToName`, applied by `SmtpEmailSender` (control characters stripped, address validated with `EmailAddressRules`). No other change to those files.
|
||||||
|
2. **The visitor never waits for SMTP.** The submit request no longer sends mail inline (U3 did a no-op call there). It stores the message with `MailStatus=Pending` and `NextMailAttemptAt=now` and wakes the sender in-process (a `Channel` signal); the mail goes out within seconds in the background. Resend (admin request) still sends inline, as U4 does.
|
||||||
|
3. **Retry job** `ContactMailService : BackgroundService` — wakes on the signal and every `Contact:Mail:SweepSeconds` (default 120). Selects rows with `Status != Spam`, `MailStatus in (Pending, Failed)`, `MailAttempts < MaxAttempts` and `NextMailAttemptAt <= now` (or null), oldest first, batches of 20. Each row is **claimed** first (`NextMailAttemptAt = now + 5 min`, saved) so two instances never mail the same message; then sent. Success: `Sent`, error cleared. Failure: `Failed`, `MailError` = the short code, `MailAttempts++`, `NextMailAttemptAt = now + backoff[attempts]` with backoff 5 min, 15 min, 1 h, 6 h, 24 h (configurable list); after `Contact:Mail:MaxAttempts` (default 6) it stays `Failed` until an administrator resends (resend ignores backoff and the maximum).
|
||||||
|
4. **When mail cannot be sent at all** (`IMailAvailability.IsEnabled` false or no valid `Contact:RecipientEmail`): rows stay `Pending`, no attempt is counted, nothing is retried in a loop; the admin detail shows why (`mailError` = `disabled` / `recipient_not_configured`). They are picked up automatically once mail is configured.
|
||||||
|
5. **Addresses**: recipient `Contact:RecipientEmail` is **environment only** for the Andrea site (no address in committed config); the SLP host may keep it in its own appsettings (SLS to confirm). From = `ISiteSettingsService.GetEffectiveSenderAsync` (allow-listed); Reply-To = visitor address and display name. Mail subject is fixed text from the catalog ("Nieuw bericht via {site}"); no visitor-supplied text goes into the subject or any header except Reply-To.
|
||||||
|
6. **Privacy**: no address, name or message in any log line, exception or Sentry event; only message id, attempt number and the short error code. `SmtpFailure.Describe` output stays out of the contact logs (it may quote reply text).
|
||||||
|
7. Admin API additive field: the message detail gets `nextMailAttemptAt` (nullable) so the UI can show "next attempt at ...".
|
||||||
|
8. The Andrea host gets the Contact module reference only when SLS/Bryan decide the ASF website uses the form (out of scope here); the module works there unchanged.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Shared mail code, additive**: `MailKind.ContactMessage`, catalog texts (nl/en), `MailModel.Details`, `OutgoingMail.ReplyTo*`, `SmtpEmailSender` reply-to; renderer tests (see below). Show the diff of the three shared files to SLS before moving on.
|
||||||
|
- [x] **Step 2 — Contact mail sender**: `ContactMailSender : IContactMailSender` (replaces the no-op; renders, builds the Reply-To, calls `IEmailSender`, maps the `MailSendResult` to `Sent/Failed` + code; returns `Skipped` for "disabled"/"no recipient").
|
||||||
|
- [x] **Step 3 — Pipeline change**: `ContactSubmissionService` stops sending inline, sets `NextMailAttemptAt`, signals `IContactMailSignal`.
|
||||||
|
- [x] **Step 4 — Retry/background service** `ContactMailService` (claim, backoff, max attempts, signal, disabled handling) and options `Contact:Mail:*` (`SweepSeconds`, `MaxAttempts`, `BackoffMinutes`), `Contact:RecipientEmail`.
|
||||||
|
- [x] **Step 5 — Admin**: detail gets `nextMailAttemptAt`; resend uses the real sender; OpenAPI regenerated.
|
||||||
|
- [x] **Step 6 — Tests**: renderer (every visitor value HTML-encoded, newline handling, subject contains no visitor text, nl/en, dark-mode classes present, text part); sender with a fake `IEmailSender` (To/From/Reply-To/subject, control characters in the display name never reach a header, result codes mapped, disabled and missing recipient give `Skipped`); retry service (only due rows, spam never, backoff schedule exactly as configured, max attempts, claim prevents a second sender, signal wakes it, disabled mail leaves rows untouched and uncounted, resend ignores backoff); submission service no longer calls the sender and signals; no personal data in any log (extends the existing log-capture tests); **pipeline** on the real host with a capturing `IEmailSender` registered in the test host: submit -> mail captured within seconds and row `sent`; failing sender -> `failed` + code + next attempt; resend `mailed:true`; mail disabled -> rows pending.
|
||||||
|
- [x] **Step 7 — Verification (automatic)**: build; all test projects incl. pipeline tests on a temporary MariaDB (removed afterwards). Optionally one manual end-to-end against smtp4dev if it is available locally (not a gate).
|
||||||
|
- [x] **Step 8 — Docs/commit**: summary (config keys, behaviour table, shared-file diff), update `phase-1-handoff.md` routes/keys; one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Existing mail kinds and their texts/behaviour, identity mail flow, `IMailAvailability`, site settings, SMTP credentials handling, the public routes' contract (still `202` immediately), the availability gate.
|
||||||
|
|
||||||
|
## Risks / questions for approval
|
||||||
|
1. OK to make the three **additive** changes in shared mail code (`MailTypes.cs`, `MailTemplateRenderer.cs`, `SmtpEmailSender.cs`)? Alternative without touching them: a plain-text-only contact mail built in the Contact module with no Reply-To header (worse: no one can reply by pressing Reply). I recommend the additive change.
|
||||||
|
2. `Contact:RecipientEmail` for the SLP host: committed in its appsettings or environment only?
|
||||||
|
3. Backoff 5 min / 15 min / 1 h / 6 h / 24 h and 6 attempts: acceptable?
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
# Code Generation Plan — CMS-U6 admin-ui-berichten
|
||||||
|
|
||||||
|
Phase 2, frontend only (`frontend/src/features/contact`, `router.tsx`, `Sidebar.tsx`, locales). Backend routes exist (CMS-U4); the JSON shapes are in `construction/phase-1-handoff.md` and `openapi/slpsoftware.v1.json`. Decisions: D1 (admin view in scope, full version), Bryan: the form switch must be visible and switchable in the "Berichten" screen (spam attack, maintenance). Areas the ASF session touched in the frontend (auth/refresh, users, theme assets) are not changed; Sidebar/router get one added entry each.
|
||||||
|
|
||||||
|
## Findings on the merged master
|
||||||
|
- Sidebar items are declared in `NAV_ITEMS` with `roles` and `requiredModule`; routes use `RoleGuard` + `ModuleGuard`. `useSystemCapabilities` lists loaded modules (cached for the session) and `emailEnabled`.
|
||||||
|
- A loaded `Contact` module does **not** mean the API is usable: while the host switch is off every management route answers 404 with an empty body. The UI therefore treats `404` on `GET /contact-settings` as "not available on this host".
|
||||||
|
- Offerings (CMS-U0/U1b) set the pattern: feature folder with `services/`, `components/`, `pages/`, `mocks/`, msw handlers, `['feature','list']` query keys, nl/en translations, Vitest + Testing Library.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
1. **Navigation**: menu entry "Berichten" (icon: mail) for Owner and Administrator, shown only when capabilities list `Contact` **and** `GET /contact-settings` did not answer 404 (loaded once per session, cached). Route `/messages`, guarded by role and the same availability check; a direct visit while unavailable shows the existing "not found" page.
|
||||||
|
2. **Form switch card** at the top: "Contactformulier op de website — Aan/Uit" with a clear state text, one toggle button, an explanation line ("Als het formulier uit staat ziet de bezoeker alleen je e-mailadres") and, when `hostEnabled` is false, no toggle but the host-level explanation (cannot occur while the screen is reachable; handled defensively). Switching uses `PUT /contact-settings`; success toast, error banner with the Dutch generic/network messages; the state comes from the server response. **First-time hint**: the switch is off by default, so a short note tells Bryan that the form is closed until he switches it on.
|
||||||
|
3. **List**: filter chips "Inbox" (default: new+read+archived), "Nieuw", "Gelezen", "Gearchiveerd", "Spam" (each calls `GET /contact-messages?status=` — "Inbox" sends no status); the chip "Nieuw" shows `unreadCount`; paging 25 per page with previous/next and "x–y van z"; newest first; columns: received (locale date and time), name, e-mail, subject (the opaque site value, shown as is), status badge, mail icon (sent / pending / failed / n.v.t.). Empty states per filter. Spam rows are visually separate (only visible under "Spam").
|
||||||
|
4. **Detail** (dialog, not a new page): full message with preserved line breaks, e-mail as `mailto:` link, received time, status select (Nieuw/Gelezen/Gearchiveerd → `PATCH`), mail status with attempts, error code (translated: disabled, not configured, auth, rejected, timeout...), next attempt time, retention date. Buttons: **Verwijderen** (confirm dialog, `DELETE`), **Opnieuw mailen** (`POST .../resend`; disabled with hint when `emailEnabled` is false; shows "Verstuurd" when `mailed:true`, "Niet verstuurd (mail staat uit)" when `mailed:false`; `409` for spam → "Markeer het bericht eerst als geen spam."; `429` → "Probeer het over {n} seconden opnieuw." from `Retry-After`), **Geen spam** on spam rows (`PATCH status=read`, then it moves to the Inbox).
|
||||||
|
5. **Opening an unread message marks it as read** (`PATCH read`), so the counter drops. (Decision to confirm.)
|
||||||
|
6. Cache: keys `['contact','messages',filter,page]` and `['contact','settings']`; mutations invalidate messages (and the counter); the switch updates the settings cache from the response.
|
||||||
|
7. All user-facing texts Dutch with English counterparts (`contact.*`); errors and 4xx/5xx mapped to translated messages, never the API's English titles. Accessibility: switch with accessible name and state, focus management in dialogs, status icons with text alternatives.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Types, services and msw mocks** (settings get/put incl. 404 = unavailable, messages list/detail/patch/delete/resend with the real status codes and shapes).
|
||||||
|
- [x] **Step 2 — Components**: `FormSwitchCard`, `MessagesFilterChips`, `MessagesTable` + pager, `MessageDialog`, `DeleteMessageDialog`.
|
||||||
|
- [x] **Step 3 — Page, route, sidebar entry, guards, translations (nl/en)**.
|
||||||
|
- [x] **Step 4 — Tests (Vitest + Testing Library + msw)**: sidebar entry visible/hidden (module missing, 404 on settings, role); direct route when unavailable; switch card off→on→off with server response, error path, first-time hint; list default shows no spam, each chip sends the right query, counter from `unreadCount`, paging; detail opens, marks unread as read, line breaks preserved, status change, un-spam moves the row, delete confirm/cancel, resend (`mailed` true/false, 409, 429 with seconds, email disabled), empty states, translated error codes; no raw API titles shown.
|
||||||
|
- [x] **Step 5 — Verification (automatic)**: `pnpm lint`, `npx tsc -b`, full `pnpm test`; new files formatted with prettier (the 15 old prettier warnings in offerings stay); real output reported.
|
||||||
|
- [x] **Step 6 — Docs/commit**: summary; one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Backend, auth/refresh, users, theme assets, existing features except the one entry in `Sidebar.tsx` and the route in `router.tsx`, shared UI primitives (used, not edited; a switch is built from the existing button/checkbox primitives unless a primitive is missing, then added as a new file).
|
||||||
|
|
||||||
|
## Questions for approval
|
||||||
|
1. Auto-mark as read when a message is opened: OK?
|
||||||
|
2. Sidebar badge with the unread count (extra request per page load for admins): wanted, or only the chip counter? (I propose chip counter only.)
|
||||||
|
3. Keep the filter as chips (above) or a select? (Chips proposed.)
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
# Code Generation Plan — CMS-U7 availability-restful-status
|
||||||
|
|
||||||
|
Phase 2, on the rebased branch. Decision (Bryan via SLS): no `/admin` segment in API routes; `POST /api/v1/Availability/admin/status` becomes `PUT /api/v1/Availability/status` (AdminOnly), same resource as the public `GET .../status`. The last open admin-segment route (checked in CMS-U0: it was the only one left).
|
||||||
|
|
||||||
|
## Findings (merged master, all callers checked)
|
||||||
|
- Backend: `AvailabilityController` — `[HttpGet("status")] [AllowAnonymous]` and `[HttpPost("admin/status")] [Authorize(Policy="AdminOnly")]` with body `UpdateStatusRequest { NewStatus, Reason }`; answers `200` (empty), `400` (unsupported service), `409` ProblemDetails when the status is master-controlled.
|
||||||
|
- **Callers of the old route** (repository-wide search for `admin/status`, code, docs, CI, configs): only the admin frontend — `frontend/src/features/availability/services/useAvailability.ts` (mutation), `frontend/src/features/availability/mocks/handlers.ts`, and two msw handlers in `frontend/src/features/settings/pages/SettingsPage.test.tsx`. No server-side caller: the master pushes status to slaves with `POST /Master/status`, slaves read `GET /SlaveStatus`, instances poll the master — none of them uses `Availability/admin/status`. No proxy (nginx/IIS), deploy script, workflow or README references the old route (the README mentions only `GET .../status`). Historic `aidlc-docs` entries are history and stay as they are.
|
||||||
|
- **Gate**: `AvailabilityMiddleware` lets `/api/v1/Availability/status` through for **every method** (path-prefix bypass). After the change that would also exempt `PUT`, an admin route, from the gate for callers without a token (they would get `401` instead of `503`) — harmless in effect but contrary to "admin routes are never exempted". The bypass must therefore apply to `GET` (and `HEAD`) only.
|
||||||
|
- The frontend `Settings` page changes the status; `useAvailabilityStatus` (GET) is used on login, sidebar, dashboard.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
1. `PUT /api/v1/Availability/status`, body `{ "newStatus": "Available"|"Maintenance"|"NotAvailable", "reason": string|null }` (unchanged), AdminOnly. Success: `200` with the **same JSON as `GET /Availability/status`** (the updated resource), so the UI can refresh its cache from the response. `409` problem+json when the status is master-controlled (unchanged); `400` for an invalid `newStatus` (framework validation); `401`/`403` as for all admin routes.
|
||||||
|
2. The old route `POST /Availability/admin/status` is **removed**, no alias: API and admin app are deployed together (decision of Bryan for the other routes too). Consequence to accept: during a deploy window an old browser bundle calling the old route gets `404`; the next page load fixes it.
|
||||||
|
3. `AvailabilityMiddleware`: the `Availability/status` bypass is limited to `GET`/`HEAD`; every other method follows the normal gate (a verified Owner/Administrator passes, expired token = `401`, others `503`). Minimal change in that file (ASF-owned file, small diff).
|
||||||
|
4. Frontend: `useUpdateAvailability` uses `PUT` and updates the cached status from the response; mocks and the two Settings tests change to `PUT`.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
- [x] **Step 1 — Controller**: `[HttpPut("status")]` replaces `admin/status`; returns the updated status object (shared builder with GET); remove the old route.
|
||||||
|
- [x] **Step 2 — Middleware**: method-aware bypass for `Availability/status` (small, isolated diff); comment explains why.
|
||||||
|
- [x] **Step 3 — Frontend**: `useAvailability.ts` mutation (PUT + cache update), `availability/mocks/handlers.ts`, `SettingsPage.test.tsx` (2 handlers); no other change.
|
||||||
|
- [x] **Step 4 — Docs/contract**: regenerate `openapi/slpsoftware.v1.json`; update `phase-1-handoff.md`; README mention only if it names the route (it does not).
|
||||||
|
- [x] **Step 5 — Tests**: controller (PUT 200 body equals GET shape, 409 master-controlled, 400 invalid status, GET unchanged and anonymous); route-table test: the only anonymous action on the controller is `GetStatus`, `UpdateStatus` is `AdminOnly`, no route contains `admin`, old route absent; middleware: `PUT /api/v1/Availability/status` without token is blocked by the gate while the CMS is off (not bypassed), `GET` still open, a verified administrator can `PUT` while the CMS is disabled (existing guarantee), expired token on PUT = `401`; pipeline on the real host: login as administrator, `PUT` Maintenance → `GET` shows it, visitors get `503` on a gated route, `PUT` back to Available; old `POST admin/status` = `404`; frontend: Settings page test uses PUT and shows the new status.
|
||||||
|
- [x] **Step 6 — Verification (automatic)**: build; all test projects incl. pipeline tests (temporary MariaDB, removed afterwards); `pnpm lint`, `npx tsc -b`, `pnpm test`; real output reported.
|
||||||
|
- [x] **Step 7 — Commit**: one commit; no push.
|
||||||
|
|
||||||
|
## Explicitly NOT touched
|
||||||
|
Master/slave endpoints (`Master/*`, `SlaveStatus`, `CmsInstances/{id}/status`), the gate logic for any other route, `GET /Availability/status` behaviour, polling/circuit-breaker code.
|
||||||
|
|
||||||
|
## Risk / notes
|
||||||
|
- **Order of deploy** with the SLP production release: this unit changes an API route and the admin app together; it must go out as one release (no alias). Do not deploy only one half.
|
||||||
|
- `CmsInstances/{id}/status` (`PUT`, master-side, per instance) is unrelated and stays.
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
# Code Generation Plan — CMS-U9 friendly-captcha-and-asf-host
|
||||||
|
|
||||||
|
Status: BUILT except step 6 (frame-src catalogue change, postponed on instruction). No push, no deploy.
|
||||||
|
|
||||||
|
## Starting point (already in the code)
|
||||||
|
- `ICaptchaVerifier` seam with `NullCaptchaVerifier` (always true); `ContactSubmissionService` calls it only when `Contact:Captcha:Enabled`; a `false` answer is classified as spam: **202 + status spam**, identical to today.
|
||||||
|
- Token response already has `captcha: null | { provider, siteKey }` (from `Contact:Captcha:Provider|SiteKey`); request already has optional `captchaToken`. So the wire contract needs **no change**; only the rule "captchaToken is required when captcha is on" gets a defined meaning (a missing/empty token counts as a failed check = spam, never a 400, so a bot learns nothing).
|
||||||
|
- Public routes carry `[PublicSiteEndpoint]` (gate exempt, also when the CMS/master is "not available").
|
||||||
|
|
||||||
|
## Decisions to confirm
|
||||||
|
1. **Friendly Captcha version: v2 (recommended).** Server verify: `POST https://global.frcapi.com/api/v2/captcha/siteverify` (EU-only alternative host `eu.frcapi.com`), JSON `{ "response": <captchaToken>, "sitekey": <siteKey> }`, header `X-API-Key: <secret>`; result `success: true|false`. Endpoint host is configurable (`Contact:Captcha:VerifyUrl`, default global v2). v1 (`api.friendlycaptcha.com/api/v1/siteverify`, form `solution` + `secret`, EU host `eu-api.friendlycaptcha.eu`) is the old API and is **not** built. I will re-check these URLs/field names against the provider's current documentation at build time and report any difference before coding on them.
|
||||||
|
2. Client-side (for the website session): the v2 widget (`@friendlycaptcha/sdk`) needs the **site key** (from the token response) and renders into the form; on solve it yields a response string that is sent as `captchaToken`. The widget loads its worker/script from the app bundle (or a script URL) and talks to the provider API at runtime.
|
||||||
|
3. **Fail-open** (decided): provider timeout (verify timeout default 3 s, configurable), network error or 5xx => treated as passed + a warning log with the failure kind only (never token, address or message text). A definite negative answer (`success:false`, or 4xx for a bad/expired token) => spam. A 4xx caused by our own config (bad secret/sitekey: 401/403) => fail-open too, but logged as **error** `captcha_misconfigured` so it is noticed; the token response never leaks it.
|
||||||
|
4. Config per site, secret only via environment: `Contact:Captcha:Enabled|Provider (friendlycaptcha)|SiteKey|VerifyUrl|TimeoutSeconds`, secret `Contact__Captcha__Secret` (env only, never in committed config; startup refuses `Enabled=true` + `Provider=friendlycaptcha` with an empty secret or sitekey, logging names only). Unknown provider => startup validation failure.
|
||||||
|
5. Privacy note (docs): Friendly Captcha does not use cookies or personal tracking; the visitor's IP address is processed for the challenge request by the provider (EU-hosted option exists; verify call from our server sends the response + sitekey only, **not** the visitor IP unless we choose to). Documented per provider/version in the contract doc; exact wording to be checked against the provider's own privacy statement at build time, and ASF's privacy page owner (Andrea) needs to mention it.
|
||||||
|
|
||||||
|
## Build steps
|
||||||
|
- [x] **Step 1 — Verifier**: `FriendlyCaptchaVerifier : ICaptchaVerifier` using `IHttpClientFactory` (named client, timeout from options), returns true/false per the rules above; `CaptchaProviderOptionsValidator`; provider selection in `ContactModule` (`NullCaptchaVerifier` stays for provider-less/disabled).
|
||||||
|
- [x] **Step 2 — Submission rule**: when enabled, an empty `captchaToken` = failed check (spam), without calling the provider.
|
||||||
|
- [x] **Step 3 — Token response**: unchanged shape; only returns `captcha` when enabled **and** provider/sitekey valid; test that no secret/verify URL ever appears in any response.
|
||||||
|
- [x] **Step 4 — Tests (no real network)**: fake `HttpMessageHandler`: success true/false, timeout, 5xx, 401/403 (misconfigured), malformed JSON, cancellation; empty token; request body/headers exact (`X-API-Key`, JSON fields); logs carry no token/secret/PII; pipeline test on the real host with the fake handler registered: spam => 202 + stored as spam, identical response body to genuine; fail-open => genuine stored; token response `captcha` shape; startup validation (missing secret/sitekey, unknown provider).
|
||||||
|
- [x] **Step 5 — Subject label check (decision a)**: tests with labels containing `& ' " < > ` and line-break/control characters through validator, mail (subject stays fixed; HTML body encodes the label; text part indents it), Reply-To, admin list/detail JSON (React escapes on display; verified by a frontend test with `<b>x</b> & "q"`).
|
||||||
|
- [ ] **Step 6 (POSTPONED on instruction until the frame-src decision; patch parked, not committed) — CSP proposal (not applied to ASF by me)**: add a catalogue option so a site can allow the captcha provider: for `StrictSite`: `connect-src 'self' https://global.frcapi.com` (and `https://eu.frcapi.com` when the EU host is used), `frame-src` is not needed for the v2 default widget (it runs in-page); if the widget is configured in iframe mode add `frame-src https://global.frcapi.com`; `script-src` additions only if the SDK is loaded from a CDN instead of the site bundle (avoid: bundle it). Delivered as: `SecurityHeaders:AllowedSiteConnectOrigins` entries (already supported by the catalogue) plus documented values; **no catalogue code change is needed for connect-src**, and I add a `frame-src` extension only if you want iframe mode. Documented in the contract doc.
|
||||||
|
- [x] **Step 7 — ASF host** (coordinate with session `AndreaSlopFotografie`; the host project is theirs, I only add):
|
||||||
|
- `ProjectReference` to `Modules.Contact` + module registration in `Api.AndreaSlopFotografie`; per-site `Contact:SiteId` (e.g. `andreaslop`), own database/connection as already used there.
|
||||||
|
- Host tests (new, in `Api.AndreaSlopFotografie.Tests`, real pipeline on MariaDB): (a) contact routes answer only when `Contact:Enabled` + CMS switch; (b) `[PublicSiteEndpoint]`: token/submit routes stay reachable (200/202/404-closed, never the gate's 503) while the availability gate is "not available"; admin routes remain gated; (c) rate limits are per client: with `ForwardedHeaders:KnownProxies` set, two client addresses get separate buckets; without it, one shared bucket (test documents the consequence).
|
||||||
|
- Docs: release conditions for ASF: `ForwardedHeaders__KnownProxies__0=<IIS proxy ip>` before `Contact__Enabled=true`; `Contact__RecipientEmail` env only; From: `Email:FromAddress` is the site address; contact mail uses `GetEffectiveSenderAsync`, so it follows `Email:AllowedFromAddresses`/the site settings (to be set for ASF to a real ASF address via env, not in repo); captcha secret via env.
|
||||||
|
- [x] **Step 8 — Docs**: contract doc (captcha shape, `captchaToken` rule, spam behaviour, fail-open, CSP values, privacy note), handoff section 8 (keys + env var names), OpenAPI regenerated (description of `captchaToken`/`captcha`), summary, state/audit.
|
||||||
|
- [x] **Step 9 — Verification**: all test projects incl. pipeline on a temporary MariaDB; one commit; no push; container removed.
|
||||||
|
|
||||||
|
## Answers to the ASF-host facts (short)
|
||||||
|
1. ASF csproj/registration: **to build in U9** (step 7).
|
||||||
|
2. KnownProxies empty ⇒ one shared bucket behind IIS: **to build in U9**: host test + documented release condition (`ForwardedHeaders__KnownProxies__0`); `ClientPartitionKey` already used by the contact limiter (**present**).
|
||||||
|
3. From / AllowedFromAddresses: **present in code** (contact mail uses the site's effective sender); ASF value is an env/config decision for their host (**U9 doc**, no repo address).
|
||||||
|
4. CSP: **U9 proposal** (step 6; connect-src only via the existing `AllowedSiteConnectOrigins`, nothing applied to ASF by me).
|
||||||
|
5. Gate: `[PublicSiteEndpoint]` on `GET /contact-messages/token` and `POST /contact-messages` is **present** and tested on the SlpSoftware host (pipeline tests with the gate off); a test on the **ASF host configuration** is **to build in U9** (step 7b). Management routes stay gated.
|
||||||
|
6. Mail renderer/branding reuse: **present**. The contact mail uses the core `MailTemplateRenderer` (logo, brand colour, dark mode, nl/en) and the site's effective sender.
|
||||||
|
|
||||||
|
## Not touched
|
||||||
|
Admin app (except possibly one test for escaped labels), auth/refresh, users, theme assets, `src/cms-client` (SLP Software - SLS - Main changes it), ASF host files other than the ProjectReference/registration agreed with the ASF session.
|
||||||
|
|
||||||
|
## Questions
|
||||||
|
1. Friendly Captcha **v2** (recommended) — OK?
|
||||||
|
2. Missing `captchaToken` while captcha is on = spam (202), not 400 — OK?
|
||||||
|
3. Misconfigured provider (401/403 from verify) = fail-open + error log — OK, or fail-closed (everything becomes spam) instead?
|
||||||
|
4. Widget mode: in-page SDK (no `frame-src`) — OK?
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
# Application Design (minimal) — contact-forms-module
|
||||||
|
|
||||||
|
Scope: component names, boundaries, configuration keys, and the few design points the contract leaves open. Behaviour and field-level detail stay in contract v0.3.1.
|
||||||
|
|
||||||
|
## 1. Repo findings that shape the design (master `d9cc539`)
|
||||||
|
- Modules are `IModule` classes discovered via the host's project references (`orchestrator.DiscoverModules()`); a host gets a module by a `ProjectReference` in its `.csproj`. Phase 1 registers Contact in `Api.SlpSoftware` only; `Api.AndreaSlopFotografie` does not exist on master and gets the reference after the ASF merge (Phase 2).
|
||||||
|
- **Data Protection is already host-level**: `AddCmsDataProtection()` (CmsHost) persists keys in the database (`ApplicationDbContext`) with a fixed application discriminator. Contact therefore does **not** own a key ring; it only asks `IDataProtectionProvider` for a protector with a per-site purpose string. (This replaces the plan wording "keyring in own DbContext".)
|
||||||
|
- Controller convention: `[Route("offerings")]` under the global `/api/v1` prefix, class-level `[Authorize(Policy = "AdminOnly")]`, public actions `[AllowAnonymous]` + `[EnableRateLimiting("<policy>")]`, admin actions under `offerings/admin`. Existing public limiter policy: `offerings-public`.
|
||||||
|
- `/System/capabilities` lists `ModuleOrchestrator.ModuleNames`: a module named `Contact` appears automatically.
|
||||||
|
- `AvailabilityMiddleware` is prefix-bypass based, with verified-admin-token bypass. Existing admin routes are **not** under a common `/api/v1/admin/` prefix (they are `.../admin` suffixes or controllers such as `Users`).
|
||||||
|
|
||||||
|
## 2. Deviation to confirm (admin route shape)
|
||||||
|
Contract § 6 writes `/api/v1/admin/contact-messages`. Repo convention is `contact-messages/admin...` (as `offerings/admin`). **Proposal**: follow the repo convention: `GET /api/v1/contact-messages/admin`, `GET .../admin/{id}`, `PATCH .../admin/{id}`, `DELETE .../admin/{id}`, `POST .../admin/{id}/resend`. The 503-regression test then iterates over all endpoints without `[PublicSiteEndpoint]` instead of relying on a prefix. Redesign - SLS to update the contract (or veto).
|
||||||
|
|
||||||
|
## 3. Components
|
||||||
|
| Component | Project | Responsibility |
|
||||||
|
|---|---|---|
|
||||||
|
| `PublicSiteEndpointAttribute` | Core (`Availability`) | marker, `AttributeTargets.Method`; read via endpoint metadata |
|
||||||
|
| Availability check | Modules.Availability `AvailabilityMiddleware` | minimal change: after the prefix bypass, `context.GetEndpoint()?.Metadata.GetMetadata<PublicSiteEndpointAttribute>()` != null => `next` (deny-by-default otherwise) |
|
||||||
|
| 429 handling | Core `AddCmsRateLimiting` `OnRejected` | set `Retry-After` (from `MetadataName.RetryAfter` when available, else window), write `application/problem+json`; keep the security-event call |
|
||||||
|
| Offering category | Modules.Offerings | `Offering.Category` (nullable, max 100), DTOs/requests, `ICategoryOptions` (reads `Offerings:Categories`), validation in service |
|
||||||
|
| `ContactModule` | Modules.Contact | `IModule` "Contact"; registers DbContext (MySQL, same pattern), services, hosted services; `Migrate()` in `UseModule` |
|
||||||
|
| `ContactDbContext` | Modules.Contact | `ContactMessages`, `IdempotencyRecords` |
|
||||||
|
| `ContactMessagesController` | Modules.Contact | public token + submit (`[PublicSiteEndpoint]`, `[AllowAnonymous]`, limiter policies); admin actions `AdminOnly` (U4) |
|
||||||
|
| `ContactSubmissionService` | Modules.Contact | validate, classify (genuine/spam), idempotency, store, trigger mail |
|
||||||
|
| `ContactValidator` | Modules.Contact | pure function: input => `{field: [codes]}`; shared rules (trim, length, regex, control chars) |
|
||||||
|
| `ContactTokenService` | Modules.Contact | issue/verify via `IDataProtector` (purpose `SlpModularCms.Contact.Token.{siteId}`), `ITimeProvider`; verify result: valid / tooYoung / expired-or-invalid |
|
||||||
|
| `ICaptchaVerifier` (+`NullCaptchaVerifier`, later Friendly Captcha impl) | Modules.Contact | fail-open on provider failure, log without PII |
|
||||||
|
| `IContactMailSender` (+`NoOpContactMailSender`) | Modules.Contact | seam for mail; real implementation in Phase 2 (CMS-U5) |
|
||||||
|
| `ContactRetentionService` | Modules.Contact | daily `BackgroundService`: delete rows past `retentionUntil` and idempotency records > 24 h |
|
||||||
|
| `ContactSiteOptions` | Modules.Contact | `Contact:*` binding (validated on start; recipient/sender not required until mail is wired) |
|
||||||
|
| Log scrubbing | Core Observability | extra rule in `SecurityEventProcessor`/Sentry `BeforeSend` for the contact routes |
|
||||||
|
|
||||||
|
## 4. Configuration keys
|
||||||
|
| Key | Default | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `Offerings:Categories` | `[]` | per host; empty list => category must be null |
|
||||||
|
| `Contact:SiteId` | host name | derived from host config, never from the request; used in the token purpose and stored on rows |
|
||||||
|
| `Contact:MinSeconds` | 3 | |
|
||||||
|
| `Contact:TokenLifetimeMinutes` | 120 | |
|
||||||
|
| `Contact:RetentionMonths` | 12 | per row at insert |
|
||||||
|
| `Contact:SpamRetentionDays` | 30 | |
|
||||||
|
| `Contact:MaxSpamRowsPerDay` | 200 | cap per site per day, then 202 without storing |
|
||||||
|
| `Contact:MaxBodyBytes` | 16384 | |
|
||||||
|
| `Contact:HoneypotField` | `hpCheck` | |
|
||||||
|
| `Contact:RecipientEmail`, `Contact:SenderEmail` | none | env-only for ASF; not committed (Phase 2) |
|
||||||
|
| `Contact:Captcha:Enabled/Provider/SiteKey/Secret` | false | secret via env/secrets |
|
||||||
|
| `RateLimiting:ContactForm` | 5 / 600 s | per client IP |
|
||||||
|
| `RateLimiting:ContactToken` | 20 / 600 s | per client IP |
|
||||||
|
| `RateLimiting:ContactResend` | 5 / 600 s | admin resend |
|
||||||
|
|
||||||
|
## 5. Data
|
||||||
|
- `ContactMessage`: `Id` (Guid), `SiteId`, `ReceivedAt`, `Name`, `Email`, `Subject`, `Message`, `Status` (`New|Read|Archived|Spam|Converted`), `MailStatus` (`Pending|Sent|Failed|NotApplicable`), `MailError` (code only), `MailAttempts`, `NextMailAttemptAt`, `RetentionUntil`. Indexes: `(SiteId, Status, ReceivedAt)`, `RetentionUntil`. No IP.
|
||||||
|
- `IdempotencyRecord`: `Key` (Guid), `SiteId`, `CreatedAt`, `StatusCode`; unique index `(SiteId, Key)`. No request content.
|
||||||
|
- `Offering.Category`: `varchar(100)` NULL.
|
||||||
|
|
||||||
|
## 6. OpenAPI export
|
||||||
|
- Committed file `openapi/cms-api.v1.json` in the repo root. A test builds the document from the SlpSoftware host (`AddOpenApi`) and compares it to the file; set `UPDATE_OPENAPI=1` to rewrite it. Drift fails the build, so `cms-client` always generates from a current file.
|
||||||
|
- The contract's response components (`Validation`, `TooLarge`, `RateLimited`, `Problem`) are declared through an `IOpenApiDocumentTransformer` so the exported shape matches contract § 8.
|
||||||
|
|
||||||
|
## 7. Cross-cutting decisions
|
||||||
|
- Identical 202 for genuine and spam: same code path up to the store step; spam differs only by `Status=Spam` and `RetentionUntil=+30d`, and never triggers mail.
|
||||||
|
- Invalid/forged/other-site/expired token => `errors.token = ["expired"]`; too-young token => silent spam path.
|
||||||
|
- Logging: only status code, site id and outcome enum for these routes; request logging for them is disabled; a test asserts that a thrown exception's log entry holds no body or field value.
|
||||||
|
- Security Baseline is checked at each stage (anonymous endpoint, input limits, no oracle, secrets only via env, generic 5xx, headers).
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Units of Work — contact-forms-module
|
||||||
|
|
||||||
|
Naming: CMS-U1..CMS-U6 (the SLS frontend plan has its own U1..U5). One feature branch `feature/contact-forms-module`, one commit minimum per unit, sequential. Each unit: Code Generation plan => approval by Redesign - SLS => code + tests + automatic build/test => status.
|
||||||
|
|
||||||
|
| Unit | Name | Phase | Depends on | New/changed projects | Migration |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| CMS-U1 | offerings-category | 1 | none | Modules.Offerings (+Tests) | `AddOfferingCategory` (Offerings context) |
|
||||||
|
| CMS-U2 | gate-and-limiter | 1 | none (marks offerings GET from U1's controller) | Core, Modules.Availability (+Tests), Core.Tests/Api.Tests | none |
|
||||||
|
| CMS-U3 | contact-core | 1 | U2 | NEW Modules.Contact, NEW Modules.Contact.Tests, Api.SlpSoftware (reference), solution file | `InitialCreate` (Contact context) |
|
||||||
|
| CMS-U4 | contact-admin-api | 1 | U3 | Modules.Contact (+Tests) | none (maybe an index) |
|
||||||
|
| CMS-U5 | contact-mail | 2 | ASF merge + rebase; U3, U4 | Modules.Contact, Core/Email use (new `MailKind`), Api.AndreaSlopFotografie reference | `AddContactMailFields` only if not already in InitialCreate (preferred: fields exist from U3) |
|
||||||
|
| CMS-U6 | admin-ui | 2 | ASF merge + rebase; U4 | `frontend/` (new files + menu entry) | none |
|
||||||
|
|
||||||
|
## Per-unit boundaries (what is NOT touched)
|
||||||
|
- **U1**: no Core, no Availability, no Email; only Offerings files and its migration/tests.
|
||||||
|
- **U2**: only `AddCmsRateLimiting`/`OnRejected` in Core, the marker attribute file, and `AvailabilityMiddleware` (minimal diff); no policy numbers changed; no Email, Identity, host config.
|
||||||
|
- **U3**: no changes to existing modules except the `.csproj` reference in Api.SlpSoftware, the `.sln`, and appsettings sample keys; no Core/Email; no Identity.
|
||||||
|
- **U4**: only Modules.Contact.
|
||||||
|
- **U5/U6**: after merge; Email code of the ASF session is used, never edited (new `MailKind` only).
|
||||||
|
|
||||||
|
## Test projects
|
||||||
|
- `SlpModularCms.Modules.Contact.Tests` mirrors the module (xUnit as the other test projects). Solution layout: module under Application/Modules, tests under Tests/Modules (per CLAUDE.md).
|
||||||
|
- PBT (partial): validator and token round-trips, using the repo's available property-testing library if present, otherwise parameterised generators; decided in Functional Design of U3.
|
||||||
|
|
||||||
|
## Order and gates
|
||||||
|
U1 -> U2 -> U3 -> U4 (each approved before start). After Bryan merges the ASF branch: rebase, regenerate migrations only if snapshots conflict, then U5 -> U6.
|
||||||
|
|
||||||
|
## Revision 2026-11-09 (Bryan via Redesign - SLS)
|
||||||
|
- New **CMS-U0 offerings-restful-routes** (Phase 1, first): no `/admin` segments; plan in `construction/plans/cms-u0-...`.
|
||||||
|
- **CMS-U1 offerings-category** revised: categories are CMS data (table + FK + CRUD routes), no `Offerings:Categories` config, no seeding.
|
||||||
|
- New **CMS-U1b offerings-categories-ui**: categories sub-section + select in OfferingForm (after U1).
|
||||||
|
- Availability `POST admin/status` -> `PUT /availability/status`: Phase 2 (after the ASF merge), new unit **CMS-U7 availability-restful-status**.
|
||||||
|
- Admin routes of Contact follow the RESTful scheme (no `/admin`): `GET/PATCH/DELETE /contact-messages[/{id:guid}]`, `POST /contact-messages/{id:guid}/resend`. Application-design § 2 is superseded accordingly.
|
||||||
|
- Order: U0 -> U1 -> U1b -> U2 -> U3 -> U4 | merge | U5 -> U6 -> U7.
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
# Execution Plan — contact-forms-module
|
||||||
|
|
||||||
|
## Detailed Analysis Summary
|
||||||
|
|
||||||
|
### Transformation Scope
|
||||||
|
- **Transformation Type**: Multiple components (new module + targeted changes in existing ones). No infrastructure/deployment model change.
|
||||||
|
- **Primary Changes**: new `Modules.Contact` (+ Tests); `category` on `Modules.Offerings`; `OnRejected` and a public-route marker in Core/Availability; later mail integration (Core/Email) and admin UI (frontend).
|
||||||
|
- **Related Components**: Core (rate limiting, hosting, observability), Modules.Availability (middleware), Modules.Offerings, Api.SlpSoftware (+ Api.AndreaSlopFotografie after the ASF merge), frontend (admin).
|
||||||
|
|
||||||
|
### Change Impact Assessment
|
||||||
|
- **User-facing changes**: Yes: public contact endpoints (consumed by `cms-client`), admin "Berichten" screen (unit 6).
|
||||||
|
- **Structural changes**: Yes: one new module, one new marker attribute in Core.
|
||||||
|
- **Data model changes**: Yes: new tables (`ContactMessage`, idempotency record, DataProtection key ring), new `Offering.Category` column. All additive.
|
||||||
|
- **API changes**: Yes: new endpoints + `category` on offerings; 429 body/header change on existing rate-limited endpoints.
|
||||||
|
- **NFR impact**: Yes: security baseline (anonymous PII endpoint), privacy (retention, logging), reliability (mail retry).
|
||||||
|
|
||||||
|
### Component Relationships
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
FE["cms-client (SLP site)"] --> API["Api.SlpSoftware / Api.AndreaSlopFotografie"]
|
||||||
|
API --> CONTACT["Modules.Contact (NEW)"]
|
||||||
|
API --> OFF["Modules.Offerings (+category)"]
|
||||||
|
API --> AVAIL["Modules.Availability (middleware)"]
|
||||||
|
CONTACT --> CORE["Core (marker, rate limiter, observability)"]
|
||||||
|
AVAIL --> CORE
|
||||||
|
CONTACT -. "after ASF merge" .-> MAIL["Core/Email (ASF branch)"]
|
||||||
|
ADMIN["frontend admin: Berichten"] -. "after ASF merge" .-> CONTACT
|
||||||
|
classDef new fill:#9ae6b4,stroke:#2f855a,color:#000;
|
||||||
|
classDef changed fill:#f6e05e,stroke:#c05621,color:#000;
|
||||||
|
classDef ext fill:#bee3f8,stroke:#2b6cb0,color:#000;
|
||||||
|
classDef later fill:#e2e8f0,stroke:#4a5568,stroke-dasharray: 5 5,color:#000;
|
||||||
|
class CONTACT new;
|
||||||
|
class OFF,AVAIL,CORE,API changed;
|
||||||
|
class FE ext;
|
||||||
|
class MAIL,ADMIN later;
|
||||||
|
```
|
||||||
|
Text alternative: the Contact module (new, green) hangs off the API hosts and uses Core; Offerings, Availability, Core and the hosts change (yellow); mail and the admin UI (grey, dashed) wait for the ASF merge.
|
||||||
|
|
||||||
|
### Risk Assessment
|
||||||
|
- **Risk Level**: Medium (anonymous endpoint with PII; shared files with the ASF session).
|
||||||
|
- **Rollback Complexity**: Easy to Moderate (additive migrations; new module can be left unregistered per host).
|
||||||
|
- **Testing Complexity**: Moderate (gate regression, rate limiter behaviour, token/idempotency, background jobs).
|
||||||
|
|
||||||
|
## Workflow Visualization
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
Start(["Request via Redesign - SLS"])
|
||||||
|
subgraph INCEPTION["🔵 INCEPTION"]
|
||||||
|
WD["Workspace Detection<br/><b>COMPLETED</b>"]
|
||||||
|
RE["Reverse Engineering<br/><b>SKIP (targeted review)</b>"]
|
||||||
|
RA["Requirements Analysis<br/><b>COMPLETED</b>"]
|
||||||
|
US["User Stories<br/><b>SKIP</b>"]
|
||||||
|
WP["Workflow Planning<br/><b>IN PROGRESS</b>"]
|
||||||
|
AD["Application Design<br/><b>EXECUTE (minimal)</b>"]
|
||||||
|
UG["Units Generation<br/><b>EXECUTE</b>"]
|
||||||
|
end
|
||||||
|
subgraph CONSTRUCTION["🟢 CONSTRUCTION (per unit)"]
|
||||||
|
FD["Functional Design<br/><b>EXECUTE (U3, U4, U5)</b>"]
|
||||||
|
NFR["NFR Requirements + Design<br/><b>EXECUTE (U2, U3)</b>"]
|
||||||
|
ID["Infrastructure Design<br/><b>SKIP (config noted in design)</b>"]
|
||||||
|
CG["Code Generation<br/><b>EXECUTE</b>"]
|
||||||
|
BT["Build and Test<br/><b>EXECUTE</b>"]
|
||||||
|
end
|
||||||
|
OPS["Operations<br/><b>UNDECIDED (at Build and Test)</b>"]
|
||||||
|
Start --> WD --> RA --> WP --> AD --> UG --> FD --> NFR --> CG --> BT --> OPS
|
||||||
|
style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
|
||||||
|
style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
|
||||||
|
style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
|
||||||
|
style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
|
||||||
|
style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
|
||||||
|
style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style UG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style NFR fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style ID fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style OPS fill:#FFF59D,stroke:#F9A825,stroke-width:2px,stroke-dasharray: 5 5,color:#000
|
||||||
|
style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000
|
||||||
|
linkStyle default stroke:#333,stroke-width:2px
|
||||||
|
```
|
||||||
|
Text alternative: Inception runs Application Design and Units Generation, then each unit goes through design (where needed), Code Generation and Build and Test; Operations is undecided.
|
||||||
|
|
||||||
|
## Phases to Execute
|
||||||
|
|
||||||
|
### 🔵 INCEPTION
|
||||||
|
- [x] Workspace Detection (COMPLETED)
|
||||||
|
- [x] Reverse Engineering (SKIPPED by D10: targeted review recorded in requirements)
|
||||||
|
- [x] Requirements Analysis (COMPLETED, approved by Redesign - SLS)
|
||||||
|
- [x] User Stories (SKIPPED: contract-driven backend work; acceptance criteria live in the contract and the SLS requirements FR-13..19)
|
||||||
|
- [ ] Workflow Planning (IN PROGRESS)
|
||||||
|
- [ ] Application Design - EXECUTE (minimal depth)
|
||||||
|
- **Rationale**: new module, new Core marker attribute; must fix component/service names, config keys (`Offerings:Categories`, `Contact:*`, `RateLimiting:ContactForm`), OpenAPI export path, DataProtection key-ring storage, purpose strings.
|
||||||
|
- [ ] Units Generation - EXECUTE
|
||||||
|
- **Rationale**: six units with an ordering constraint and a split at the ASF merge.
|
||||||
|
|
||||||
|
### 🟢 CONSTRUCTION
|
||||||
|
- [ ] Functional Design - EXECUTE for U3, U4, U5 (validation rules, state/status machine, idempotency, spam cap, retry/backoff); SKIP for U1, U2, U6 (covered by contract/design)
|
||||||
|
- [ ] NFR Requirements + NFR Design - EXECUTE for U2 and U3 (security baseline: PII logging, token oracle, size limits, rate limiting); SKIP for the others (covered by baseline checks in code generation)
|
||||||
|
- [ ] Infrastructure Design - SKIP (no new infrastructure; key-ring storage and config keys are recorded in Application Design)
|
||||||
|
- [ ] Code Generation - EXECUTE per unit (plan approved by Redesign - SLS before any code); automatic build+test per unit
|
||||||
|
- [ ] Build and Test - EXECUTE (after U1-U4, again after U5-U6)
|
||||||
|
|
||||||
|
### 🟡 OPERATIONS
|
||||||
|
- [ ] UNDECIDED: resolved at Build and Test (D7)
|
||||||
|
|
||||||
|
## Units (execution order)
|
||||||
|
|
||||||
|
Phase 1: now, on the master base. Phase 2: only after Bryan merges `feature/identity-email-notifications` and the branch is rebased (not before; no rebase now).
|
||||||
|
|
||||||
|
| Unit | Scope | Delivers | Tests | Depends on |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **U1 offerings-category** (a) | `Category` on Offering entity, public + admin DTOs, create/update requests; validation against `Offerings:Categories` (per host appsettings); null/empty allowed | additive migration `AddOfferingCategory` in Offerings; config key documented; handoff note for the frontend (field name and semantics) | Offerings.Tests: mapping, validation (in list / not in list / null), repository; migration builds | none |
|
||||||
|
| **U2 gate-and-limiter** (b) | `OnRejected`: `429 application/problem+json` + `Retry-After` for all policies; `[PublicSiteEndpoint]` marker in Core; `AvailabilityMiddleware` lets marked endpoints through (deny-by-default); mark `GET /api/v1/offerings`. Minimal diffs in these two files (R3) | marker attribute, middleware check, updated 429 response, security-event kept | Core.Tests/Api.Tests: 429 body + header for existing policies (adjust existing tests); Availability.Tests: marked route open while disabled/maintenance/master-down; **every `/api/v1/admin/*` route still 503**; `/api/v1/Availability/status` open; ~6-10 existing tests touched | none (U1 for the offerings route mark) |
|
||||||
|
| **U3 contact-core** (c) | new `Modules.Contact` (+Tests): entities `ContactMessage`, `IdempotencyRecord`; DbContext + migration; token endpoint (DataProtection, per-site purpose, persistent key ring in DB); submit endpoint (validation codes, 413 ProblemDetails, `Idempotency-Key`, honeypot `hpCheck`, min-time, `ICaptchaVerifier` + Null, identical 202, spam stored with daily cap and 30-day retention, site id from config); `ContactForm` rate-limit policies; both routes `[PublicSiteEndpoint]`; `IContactMailSender` interface with no-op implementation (mail is wired in U5); retention `BackgroundService`; log/Sentry scrubbing for the routes | module registered in Api.SlpSoftware (Andrea host later), additive migration `InitialCreate`, config section `Contact:*`, exported OpenAPI document (path fixed in design) | Contact.Tests: validation rules incl. PBT (partial: round-trips, trim/length invariants), token sign/verify/expiry/foreign-site, idempotency replay, spam paths identical response, spam cap, retention job, no-PII-in-log test, endpoint tests via WebApplicationFactory | U2 |
|
||||||
|
| **U4 contact-admin-api** (e) | AdminOnly endpoints: list (paging, unread count, spam separate), detail, PATCH status (new/read/archived), DELETE (hard), `POST resend` (rate-limited; calls `IContactMailSender`, so a no-op until U5); capabilities entry is automatic from the module name | admin controller + DTOs, OpenAPI updated | Contact.Tests: authorization (non-admin 403/401), paging, counts exclude spam, status transitions, hard delete, resend rate-limit | U3 |
|
||||||
|
| **U5 contact-mail** (d) | PHASE 2. Implement `IContactMailSender` on `Core/Email` with a **new `MailKind`**, dark-mode contrast kept; From/Reply-To rules, header-injection and HTML-encoding protections; `mailStatus`/`mailAttempts`; `BackgroundService` sweeping `pending` (minutes) and retrying `failed` with backoff/max attempts; "no SMTP host = store only + admin notice" | mail path + retry job; Andrea host registration via env-only addresses | Contact.Tests: sender with fake `IEmailSender`, retry/backoff, header injection, encoding, failure never fails the request | merge of ASF branch + rebase; U3, U4 |
|
||||||
|
| **U6 admin-ui** (f) | PHASE 2. "Berichten" in `frontend/`: list+paging+unread count, detail, status, delete, mail status + resend; menu entry via capabilities; only new files + menu entry | UI + tests | frontend unit tests (Vitest as in repo) | merge of ASF branch + rebase; U4 |
|
||||||
|
|
||||||
|
## Migration Approach
|
||||||
|
- Contact and Offerings have their **own DbContext and migration history**, applied with `Database.Migrate()` at startup (D8). All migrations are additive (new tables, one nullable column).
|
||||||
|
- ASF changes live in `Core/Migrations` and the Identity/Availability contexts, so snapshot conflicts with U1/U3 are not expected. If the rebase still produces conflicts in any snapshot, delete and regenerate my own migration after the rebase (R2).
|
||||||
|
- DataProtection key ring: table owned by the Contact module's context (persistent per host; per-site purpose string).
|
||||||
|
|
||||||
|
## Branch and Process
|
||||||
|
- Worktree `..\SlpModularCms-contact-forms`, branch `feature/contact-forms-module` from master `d9cc539`. The main checkout is never switched.
|
||||||
|
- One commit per unit minimum; no push, merge or PR without explicit instruction. Per unit: Code Generation plan -> approval by Redesign - SLS -> code + automatic build+test -> status message.
|
||||||
|
- Stage status reports to Redesign - SLS after each stage; contract deviations reported immediately.
|
||||||
|
|
||||||
|
## Estimated Timeline
|
||||||
|
- **Total units**: 6 (4 now, 2 after the ASF merge). Rough effort: U1 small, U2 small-medium, U3 large, U4 medium, U5 medium, U6 medium. No calendar estimate (depends on approval turnaround and the ASF merge).
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
- **Primary Goal**: contract v0.3.1 implemented on the CMS side without breaking ASF-owned behaviour.
|
||||||
|
- **Key Deliverables**: category on offerings; public contact endpoints; admin API; mail + retry; admin UI; exported OpenAPI.
|
||||||
|
- **Quality Gates**: per-unit build+test green; Security Baseline checked per stage; no PII in logs (tested); `/api/v1/admin/*` stays gated (tested); no ASF addresses in committed config.
|
||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
# Requirements Verification Questions — contact-forms-module
|
||||||
|
|
||||||
|
Input: contact-api-contract v0.3.1-draft (decisions by Bryan are not asked again). Only repo-specific or still-open points below. Answers may be given by "Redesign - SLS" (within Bryan's decisions) or by Bryan.
|
||||||
|
|
||||||
|
## Question 1: Security Extensions
|
||||||
|
Should security extension rules be enforced for this feature?
|
||||||
|
|
||||||
|
- A) Yes — enforce all SECURITY rules as blocking constraints (recommended: public anonymous endpoint, PII, mail)
|
||||||
|
- B) No — skip all SECURITY rules
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A (Security Baseline enabled, per Bryan for the whole work) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 2: Property-Based Testing Extension
|
||||||
|
Should property-based testing rules be enforced?
|
||||||
|
|
||||||
|
- A) Yes — all PBT rules
|
||||||
|
- B) Partial — only pure functions and serialization round-trips (validation rules, token/idempotency logic)
|
||||||
|
- C) No — skip all PBT rules
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: B (partial: pure functions and serialization round-trips) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 3: Operations phase
|
||||||
|
Should the Operations phase (deployment/monitoring/readiness) run for this feature? (Deployment already exists via the Gitea workflow.)
|
||||||
|
|
||||||
|
- A) No — closes after Build and Test; deployment follows existing workflow
|
||||||
|
- B) Yes — run the Operations phase
|
||||||
|
- C) Not sure yet — decide at Build and Test
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: C (decide at Build and Test) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 4: Module layout
|
||||||
|
Where does the new module live?
|
||||||
|
|
||||||
|
- A) New projects `SlpModularCms.Modules.Contact` + `SlpModularCms.Modules.Contact.Tests` (own DbContext + migration, like Offerings), referenced by Api.SlpSoftware and Api.AndreaSlopFotografie (recommended)
|
||||||
|
- B) Inside Modules.Offerings
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 5: Database and migrations per host
|
||||||
|
Offerings uses MySQL with `Database.Migrate()` at startup. For the Contact module:
|
||||||
|
|
||||||
|
- A) Same approach: own DbContext, MySQL, additive migration applied at startup; migration regenerated after the rebase on identity-email-notifications (recommended)
|
||||||
|
- B) Reuse an existing DbContext (e.g. Core)
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A (migration regenerated after rebase) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 6: Availability gate marker
|
||||||
|
Peer advice (ASF session): a `[PublicSiteEndpoint]` marker attribute in Core, read via endpoint metadata in `AvailabilityMiddleware`, deny-by-default, admin routes never exempt, `/api/v1/Availability/status` stays open. Own unit together with (b).
|
||||||
|
|
||||||
|
- A) Marker attribute (recommended)
|
||||||
|
- B) Prefix list next to the existing bypass list
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A ([PublicSiteEndpoint] marker, deny-by-default) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 7: Reverse engineering
|
||||||
|
The `_shared/reverse-engineering` artifacts date from July 2026 (before Offerings, SlpSoftware and ASF hosts).
|
||||||
|
|
||||||
|
- A) Skip a full rerun; do a targeted review of the touched areas (Offerings, Email, rate limiter, Availability, capabilities, SecurityEvents) and record findings in the requirements (recommended)
|
||||||
|
- B) Full rerun
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A (targeted review; new MailKind, existing mail code untouched) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
|
|
||||||
|
## Question 8: Admin UI scope
|
||||||
|
Unit (f) admin UI ("Berichten") is in the existing React admin (`frontend/`). The ASF session is still changing auth/refresh, users and theme assets there.
|
||||||
|
|
||||||
|
- A) Build (f) last, on the rebased branch after their merge, only touching new files plus the menu entry (recommended)
|
||||||
|
- B) Build it in parallel on the current base
|
||||||
|
- X) Other (please describe after [Answer]: tag below)
|
||||||
|
|
||||||
|
[Answer]: A (admin UI last, after ASF merge; report if the merge takes too long) - answered by Redesign - SLS (technical lead) 2026-11-09
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Requirements — contact-forms-module
|
||||||
|
|
||||||
|
## 1. Intent Analysis
|
||||||
|
- **Request**: Build the CMS/API side of the contact form and related contract items: (a) `category` on Offerings, (b) rate-limit `Retry-After` + own ProblemDetails, public-route marker for the availability gate, (c) Contact module (token + submit), (d) mail + retry, (e) admin API, (f) admin UI "Berichten".
|
||||||
|
- **Source of truth**: `contact-api-contract.md` v0.3.1-draft (in the SlpSoftware repo, feature `redesign-modern-timetravel`). This document does not restate its field-level detail; it records scope, decisions, repo findings and deviations. Where they disagree, the contract wins unless listed under § 6.
|
||||||
|
- **Type**: New feature (multi-component). **Scope**: multiple components. **Complexity**: Complex. **Depth**: Standard (decisions already made by Bryan / technical lead).
|
||||||
|
- **Coordination**: stages approved by "Redesign - SLS" (leads the build; Bryan's permission runs through it).
|
||||||
|
|
||||||
|
## 2. Decisions (all recorded, not re-asked)
|
||||||
|
| # | Decision | Source |
|
||||||
|
|---|---|---|
|
||||||
|
| D1 | Admin "Berichten" view in scope, full version (list+paging+unread count, detail, status new/read/archived, delete, mail status + resend; AdminOnly; capabilities entry) | Bryan |
|
||||||
|
| D2 | Honeypot/too-fast submissions stored as `spam` (30 days, never mailed, per-site daily cap, outside unread count and default list), visitor sees normal 202 | Bryan |
|
||||||
|
| D3 | Captcha disabled by default; provider failure = fail-open | Bryan |
|
||||||
|
| D4 | Category list = fixed list per site in appsettings; admin only picks from it (no free text) | Bryan |
|
||||||
|
| D5 | Retention 12 months (per row, fixed at insert), daily cleanup job | Bryan |
|
||||||
|
| D6 | Availability gate blocks only CMS/admin routes; public routes stay open; deny-by-default; admin routes never exempt | Bryan |
|
||||||
|
| D7 | Security Baseline extension **enabled**; Property-Based Testing **partial** (pure functions + serialization round-trips: validation rules, token/idempotency logic); Operations phase **undecided** (decide at Build and Test) | Bryan via Redesign - SLS |
|
||||||
|
| D8 | New projects `SlpModularCms.Modules.Contact` + `.Contact.Tests`; own DbContext, MySQL, `Database.Migrate()` at startup, additive migration (like Offerings); migration regenerated after rebase | Redesign - SLS |
|
||||||
|
| D9 | Availability marker attribute `[PublicSiteEndpoint]` in Core, read from endpoint metadata in `AvailabilityMiddleware`; own unit together with (b); test that every `/api/v1/admin/*` route still returns 503; `/api/v1/Availability/status` stays open | Redesign - SLS |
|
||||||
|
| D10 | No full reverse-engineering rerun; targeted review (§ 3). Contact mail = **new `MailKind`**, existing mail code untouched, keep dark-mode contrast | Redesign - SLS |
|
||||||
|
| D11 | Admin UI (f) last, on rebased branch after the ASF merge, only new files + menu entry; report to SLS if the merge takes long | Redesign - SLS |
|
||||||
|
| D12 | No push/merge/PR; no ASF addresses in code/committed config (env-only); no PII in logs; no deploy to production | Bryan / SLS |
|
||||||
|
|
||||||
|
## 3. Targeted review findings (master `d9cc539`)
|
||||||
|
- **Module pattern**: `Modules.Offerings` = `IModule` (`RegisterServices` + `UseModule`), own `DbContext` (MySQL, `NonLockingMySQLHistoryRepository`), `Database.Migrate()` in `UseModule`. Contact follows this exactly.
|
||||||
|
- **Capabilities**: `SystemController` returns `ModuleOrchestrator.ModuleNames`; a registered module named "Contact" appears automatically. The frontend menu entry keys off it.
|
||||||
|
- **Availability**: `AvailabilityMiddleware` (Modules.Availability) blocks everything not on a prefix bypass list (`/api/v1/Availability/status`, `/Auth/`, `/Setup/status`, `/master/`, `/SlaveStatus`, `/health`) except verified Owner/Administrator tokens. The marker-attribute check slots in before the master/local gate.
|
||||||
|
- **Mail**: `Core/Email` (`IEmailSender`, `MailSendResult`, SMTP, templates) **does not exist on master**; it lives on the unmerged ASF branch `feature/identity-email-notifications`. `Api.AndreaSlopFotografie` is also not on master. Unit (d) therefore depends on that merge (or a rebase on their branch); see § 5.
|
||||||
|
- **Rate limiting**: `AddCmsRateLimiting` with named per-client policies; `OnRejected` currently logs a security event only (no body, no `Retry-After`). To be extended (unit b) for all policies, with existing tests adjusted. ForwardedHeaders/KnownProxies are env-configured (no code change).
|
||||||
|
- **Observability**: `SecurityEvents` / `SecurityEventProcessor` (Sentry): extra scrub rule for the contact routes; test that a logged exception holds no body.
|
||||||
|
- **Offerings**: has no `category` field; additive migration + DTO + admin DTO/requests + validation against the per-site configured list.
|
||||||
|
- **ASF-owned areas (do not touch without SLS)**: Email (MailTemplateRenderer, MailColours, EmailOptions, IdentityMailService), Identity, Core Hosting/Website/Proxy, Core migrations, frontend auth/users/theme. Expected rebase conflicts: appsettings, Program.cs/host config, AvailabilityMiddleware, EF snapshots.
|
||||||
|
|
||||||
|
## 4. Functional Requirements (summary; detail in contract)
|
||||||
|
- **FR-A Offerings category**: optional `category` string|null on offering (public + admin DTOs); value must be in the per-site configured list (`Offerings:Categories`); null/empty = no chip. Additive migration.
|
||||||
|
- **FR-B1 Rate limiter**: `OnRejected` writes `429 application/problem+json` with `Retry-After`; existing policies keep their numbers; new policy `ContactForm` (5/10 min per client IP, config `RateLimiting:ContactForm`) and token policy (20/10 min).
|
||||||
|
- **FR-B2 Gate**: `[PublicSiteEndpoint]` marker; applied to `GET /api/v1/offerings`, `GET /api/v1/contact-messages/token`, `POST /api/v1/contact-messages`.
|
||||||
|
- **FR-C Contact module**: `GET .../token` (DataProtection token, per-site purpose, persistent key ring); `POST .../contact-messages` with validation + error codes per contract § 3, own 413 ProblemDetails (16 KB), `Idempotency-Key` table (no PII), honeypot `hpCheck`, min-time, optional captcha behind `ICaptchaVerifier` (Null default, fail-open), identical 202, spam stored with daily cap, site id from host/config, retention fields.
|
||||||
|
- **FR-D Mail**: after commit, send via `IEmailSender` with a new `MailKind`; `From` fixed site sender (allow-list), `Reply-To` visitor, header-injection and HTML-encoding protections; `BackgroundService` sweeps `pending` frequently and retries `failed` with backoff and max attempts; no SMTP host = store only + admin notice.
|
||||||
|
- **FR-E Admin API**: `GET list/detail`, `PATCH status`, `DELETE` (hard), `POST resend` (rate-limited); AdminOnly; spam shown separately; unread count excludes spam.
|
||||||
|
- **FR-F Admin UI**: "Berichten" screen per D1 (last unit, after ASF merge).
|
||||||
|
- **FR-G Retention job**: daily deletion of rows past `retentionUntil` and idempotency records older than 24 h.
|
||||||
|
- **FR-H OpenAPI**: exported definitive OpenAPI document committed in the repo (path fixed in design) for `cms-client` type generation.
|
||||||
|
|
||||||
|
## 5. Non-Functional Requirements and risks
|
||||||
|
- **Security (baseline enabled)**: anonymous endpoint, so input validation, size limits, no oracle on token errors, no PII in logs/Sentry, secrets only via env/secrets manager, deny-by-default gate, generic 5xx, baseline rules checked at each stage.
|
||||||
|
- **Privacy**: IP not stored; retention per row; hard delete on erasure; privacy statement must mention backups and the captcha provider (site side).
|
||||||
|
- **Reliability**: mail failure never fails the request; at-least-once mail with attempt counter; idempotent submit.
|
||||||
|
- **Testability**: per-unit build + tests (xUnit); PBT partial per D7; `/admin/*` 503 regression test; token/validation round-trip tests.
|
||||||
|
- **Risk R1**: mail unit (d) depends on `Core/Email` being on the base branch. Options: wait for the ASF merge, or rebase the feature branch onto `feature/identity-email-notifications`. To be decided by SLS in the plan.
|
||||||
|
- **Risk R2**: EF migration snapshot conflicts after rebase; regenerate own migration (D8).
|
||||||
|
- **Risk R3**: `AvailabilityMiddleware` and rate-limiter edits overlap ASF-touched files; keep diffs minimal, coordinate via SLS.
|
||||||
|
|
||||||
|
## 6. Deviations / additions vs. contract v0.3.1
|
||||||
|
- None blocking. Additions: OpenAPI export path; `Offerings:Categories` config key name; Contact module named `Contact` (capabilities entry).
|
||||||
|
|
||||||
|
## 7. Open points for the plan stage (not blockers for requirements)
|
||||||
|
- Base for unit (d): wait for ASF merge vs. rebase now (R1).
|
||||||
|
- Exact config key names and OpenAPI export location (decide in Application Design).
|
||||||
@@ -188,7 +188,7 @@ Execution rounds (Q4 = B): **R1** = U1 + U2 · **R2** = U3 + U4 · **R3** = U5 +
|
|||||||
(DSN, Umami website IDs, alert rules, 6 monitors) — not verified by execution from this session
|
(DSN, Umami website IDs, alert rules, 6 monitors) — not verified by execution from this session
|
||||||
(no access to those external accounts), taken on the user's report. Artifacts:
|
(no access to those external accounts), taken on the user's report. Artifacts:
|
||||||
`operations/plans/monitoring-setup-plan.md`, `operations/monitoring/monitoring-instructions.md`
|
`operations/plans/monitoring-setup-plan.md`, `operations/monitoring/monitoring-instructions.md`
|
||||||
- [ ] Production Readiness Validation — **EXECUTE** (includes the `dotnet-appsettings` compliance gate)
|
- [x] Production Readiness Validation — Included in the joint production checklist (`docs/release-checklist-productie.md`, 2026-11-16); the real production release waits for the owner's go
|
||||||
|
|
||||||
## Execution Plan Summary
|
## Execution Plan Summary
|
||||||
- **Risk Level**: High — three destructive-and-silent failure modes (customer website loss, Data Protection key-ring loss, automatic migration against production)
|
- **Risk Level**: High — three destructive-and-silent failure modes (customer website loss, Data Protection key-ring loss, automatic migration against production)
|
||||||
|
|||||||
+15
-12
@@ -402,14 +402,14 @@ server {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 1.7.3 Artifact Upload Body Size (413 on `publish-test`/`publish-production`)
|
#### 1.7.3 Artifact Upload Body Size (413 on `publish-sls-test`/`publish-sls-production`)
|
||||||
|
|
||||||
The Gitea instance itself (`gitea.slpsoftware.nl`) sits behind the same proxy Pi as every other
|
The Gitea instance itself (`gitea.slpsoftware.nl`) sits behind the same proxy Pi as every other
|
||||||
domain in § 1.7 — Actions' own web UI/API traffic is proxied through it exactly like
|
domain in § 1.7 — Actions' own web UI/API traffic is proxied through it exactly like
|
||||||
`test.slpsoftware.nl` and `slpsoftware.nl` are. Gitea Actions' artifact upload
|
`test.slpsoftware.nl` and `slpsoftware.nl` are. Gitea Actions' artifact upload
|
||||||
(`actions/upload-artifact`) sends the build output in chunks; if a chunk exceeds nginx's
|
(`actions/upload-artifact`) sends the build output in chunks; if a chunk exceeds nginx's
|
||||||
`client_max_body_size` (default 1m), nginx itself rejects it with `413 Request Entity Too Large`
|
`client_max_body_size` (default 1m), nginx itself rejects it with `413 Request Entity Too Large`
|
||||||
before the request ever reaches Gitea — surfacing in the `publish-test`/`publish-production` job log
|
before the request ever reaches Gitea — surfacing in the `publish-sls-test`/`publish-sls-production` job log
|
||||||
as repeated `A 413 status code has been received, will attempt to retry the upload` followed by
|
as repeated `A 413 status code has been received, will attempt to retry the upload` followed by
|
||||||
`Retry limit has been reached` on individual files once the action's retries are exhausted.
|
`Retry limit has been reached` on individual files once the action's retries are exhausted.
|
||||||
|
|
||||||
@@ -433,9 +433,9 @@ http {
|
|||||||
sudo nginx -t && sudo systemctl reload nginx
|
sudo nginx -t && sudo systemctl reload nginx
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 1.7.4 Never Re-Run `deploy-test`/`deploy-production` Alone — Gitea Platform Limitation
|
#### 1.7.4 Never Re-Run `deploy-sls-test`/`deploy-sls-production` Alone — Gitea Platform Limitation
|
||||||
|
|
||||||
`deploy-test` and `deploy-production` in `continuous_integration.yaml` are not ordinary jobs — each
|
`deploy-sls-test` and `deploy-sls-production` in `continuous_integration.yaml` are not ordinary jobs — each
|
||||||
one *calls* the reusable `deploy-scp.yaml` workflow (`uses: ./.gitea/workflows/deploy-scp.yaml`).
|
one *calls* the reusable `deploy-scp.yaml` workflow (`uses: ./.gitea/workflows/deploy-scp.yaml`).
|
||||||
Re-running **only** one of these two jobs after a failure (Gitea's per-job "re-run" action) is a
|
Re-running **only** one of these two jobs after a failure (Gitea's per-job "re-run" action) is a
|
||||||
known Gitea Actions limitation, not a bug in either workflow file here: Gitea does not cleanly resume
|
known Gitea Actions limitation, not a bug in either workflow file here: Gitea does not cleanly resume
|
||||||
@@ -446,7 +446,7 @@ List Artifacts - Error is not retryable
|
|||||||
Status Code: 404
|
Status Code: 404
|
||||||
Error: List Artifacts failed: Artifact service responded with 404
|
Error: List Artifacts failed: Artifact service responded with 404
|
||||||
```
|
```
|
||||||
even though `publish-test`/`publish-production` genuinely succeeded and uploaded the artifact
|
even though `publish-sls-test`/`publish-sls-production` genuinely succeeded and uploaded the artifact
|
||||||
moments earlier in the same run (retention had not expired — this is not the same failure mode as
|
moments earlier in the same run (retention had not expired — this is not the same failure mode as
|
||||||
§ 1.7.3, and not a retention issue at all).
|
§ 1.7.3, and not a retention issue at all).
|
||||||
|
|
||||||
@@ -466,13 +466,13 @@ This matches a documented behaviour of Actions-style re-run implementations, see
|
|||||||
GitHub's own tooling ([cli/cli#13522](https://github.com/cli/cli/issues/13522)): re-running an
|
GitHub's own tooling ([cli/cli#13522](https://github.com/cli/cli/issues/13522)): re-running an
|
||||||
*existing* run can replay against secrets/variables as they were **when that run was first created**,
|
*existing* run can replay against secrets/variables as they were **when that run was first created**,
|
||||||
not their current values — particularly for a job that calls a reusable workflow with
|
not their current values — particularly for a job that calls a reusable workflow with
|
||||||
`secrets: inherit` (exactly what `deploy-test`/`deploy-production` do here). The documented contract
|
`secrets: inherit` (exactly what `deploy-sls-test`/`deploy-sls-production` do here). The documented contract
|
||||||
("secrets are fetched at the time of the re-run") does not hold in practice for this case. A genuinely
|
("secrets are fetched at the time of the re-run") does not hold in practice for this case. A genuinely
|
||||||
**new** run (fresh push, or `workflow_dispatch`) always fetches current values correctly — only
|
**new** run (fresh push, or `workflow_dispatch`) always fetches current values correctly — only
|
||||||
re-running an existing run risks the stale snapshot.
|
re-running an existing run risks the stale snapshot.
|
||||||
|
|
||||||
**Net effect of § 1.7.4 + § 1.7.5 together**: neither of Gitea's two "re-run" options is fully safe
|
**Net effect of § 1.7.4 + § 1.7.5 together**: neither of Gitea's two "re-run" options is fully safe
|
||||||
for `deploy-test`/`deploy-production` — "re-run this job alone" loses the artifact, "re-run all jobs"
|
for `deploy-sls-test`/`deploy-sls-production` — "re-run this job alone" loses the artifact, "re-run all jobs"
|
||||||
can keep stale secrets. **The one reliable option is to trigger a brand new run** (an actual push, or
|
can keep stale secrets. **The one reliable option is to trigger a brand new run** (an actual push, or
|
||||||
`workflow_dispatch`'s "Run workflow" button) rather than using either re-run action on a failed run,
|
`workflow_dispatch`'s "Run workflow" button) rather than using either re-run action on a failed run,
|
||||||
whenever a secret or variable was just changed to fix that failure. Re-running an existing run is
|
whenever a secret or variable was just changed to fix that failure. Re-running an existing run is
|
||||||
@@ -510,6 +510,7 @@ change:
|
|||||||
| `PI_MAIN_PORT` | secret | SSH port |
|
| `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_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_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_TEST` | variable | `/home/gitea-workflow/apps/slpsoftware/test` |
|
||||||
| `DEPLOY_PATH_PRODUCTION` | variable | `/home/gitea-workflow/apps/slpsoftware/production` |
|
| `DEPLOY_PATH_PRODUCTION` | variable | `/home/gitea-workflow/apps/slpsoftware/production` |
|
||||||
| `SERVICE_NAME_TEST` | variable | `slpsoftware-test.service` |
|
| `SERVICE_NAME_TEST` | variable | `slpsoftware-test.service` |
|
||||||
@@ -525,15 +526,17 @@ change:
|
|||||||
|
|
||||||
## 2. Deploy Sequence (What Actually Happens on a Run)
|
## 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:
|
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
|
1. Push to `master`, or a manual `workflow_dispatch` (inputs `deploy_sls_test`, `deploy_sls_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 (and `publish-production`, only if `workflow_dispatch` with the flag)
|
2. `publish-sls-test` runs on a push to `master`, on pull requests (build only, no deploy) and on a dispatch with `deploy_sls_test`; `publish-sls-production` only on a dispatch with `deploy_sls_production`
|
||||||
3. `deploy-test` (always, if gates pass) calls `deploy-scp.yaml`, which uploads into a new
|
3. `deploy-sls-test` (on a push to `master`, or a dispatch with `deploy_sls_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
|
`releases/{timestamp}/`, links `shared/wwwroot-web` and any `shared/modules/*.dll` in, switches
|
||||||
`current`, restarts `slpsoftware-test.service`, verifies `https://test.slpsoftware.nl/health`,
|
`current`, restarts `slpsoftware-test.service`, verifies `https://test.slpsoftware.nl/health`,
|
||||||
then prunes old releases (only test — `run_db_backup: false`)
|
then prunes old releases (only test — `run_db_backup: false`)
|
||||||
4. `deploy-production` (only with the flag) does the same, plus a database backup first
|
4. `deploy-sls-production` (only with the flag) does the same, plus a database backup first
|
||||||
(`run_db_backup: true`) — see § 4
|
(`run_db_backup: true`) — see § 4
|
||||||
|
|
||||||
## 3. First-Ever Deploy Notes
|
## 3. First-Ever Deploy Notes
|
||||||
@@ -631,7 +634,7 @@ section documents what actually changes when that day comes (OPEN-04 — not sch
|
|||||||
per Q5 = B of the deployment setup plan).
|
per Q5 = B of the deployment setup plan).
|
||||||
|
|
||||||
### 5.1 What carries over unchanged
|
### 5.1 What carries over unchanged
|
||||||
- The CI workflow's gates, the two-build split, the `config` job pattern
|
- The CI workflow's gates, the two-build split, the `config-sls` job pattern
|
||||||
- The overall shape of the interface: `artifact_name`, `environment`, `deploy_path`
|
- The overall shape of the interface: `artifact_name`, `environment`, `deploy_path`
|
||||||
|
|
||||||
### 5.2 What does not carry over — read this before assuming it's a drop-in swap
|
### 5.2 What does not carry over — read this before assuming it's a drop-in swap
|
||||||
|
|||||||
+1
-1
@@ -20,7 +20,7 @@ procedure.
|
|||||||
| Environment | Host | Domain | Trigger |
|
| Environment | Host | Domain | Trigger |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Test | Raspberry Pi (`linux-arm64`) | `test.slpsoftware.nl` | Automatic on push to `master`, or any `workflow_dispatch` |
|
| Test | Raspberry Pi (`linux-arm64`) | `test.slpsoftware.nl` | Automatic on push to `master`, or any `workflow_dispatch` |
|
||||||
| Production | Same Pi, separate directory | `slpsoftware.nl` | Only `workflow_dispatch` with `deploy_production = true` |
|
| Production | Same Pi, separate directory | `slpsoftware.nl` | Only `workflow_dispatch` with `deploy_sls_production = true` |
|
||||||
|
|
||||||
Same physical host for both (per `infrastructure-design.md` § 1) — separated by directory,
|
Same physical host for both (per `infrastructure-design.md` § 1) — separated by directory,
|
||||||
`systemd --user` unit, and local port, never by anything the workflow manages directly.
|
`systemd --user` unit, and local port, never by anything the workflow manages directly.
|
||||||
|
|||||||
+1
-1
@@ -33,7 +33,7 @@ If the defect predates the retained previous release, redeploy an **earlier comm
|
|||||||
normal pipeline:
|
normal pipeline:
|
||||||
|
|
||||||
1. `git revert` or check out the last-known-good commit on a branch
|
1. `git revert` or check out the last-known-good commit on a branch
|
||||||
2. Push to `master` (test) or run `workflow_dispatch` with `deploy_production: true` (production) —
|
2. Push to `master` (test) or run `workflow_dispatch` with `deploy_sls_production: true` (production) —
|
||||||
the same gates and deploy sequence run as any other deploy
|
the same gates and deploy sequence run as any other deploy
|
||||||
3. This only works because migrations are required to be forward-compatible and non-destructive
|
3. This only works because migrations are required to be forward-compatible and non-destructive
|
||||||
(D-26) — redeploying an older commit's code against a database that has since had newer
|
(D-26) — redeploying an older commit's code against a database that has since had newer
|
||||||
|
|||||||
+1
-1
@@ -25,7 +25,7 @@ there is no separate DSN per environment.
|
|||||||
|
|
||||||
| Variable | Value |
|
| Variable | Value |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `VITE_SENTRY_DSN` | the project's DSN (same value used by both `publish-test` and `publish-production`) |
|
| `VITE_SENTRY_DSN` | the project's DSN (same value used by both `publish-sls-test` and `publish-sls-production`) |
|
||||||
|
|
||||||
### 1.2 Host configuration
|
### 1.2 Host configuration
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ producing the operational documentation around it, not re-deciding the method:
|
|||||||
services, no sudo (`infrastructure-design.md` §§ 2–3)
|
services, no sudo (`infrastructure-design.md` §§ 2–3)
|
||||||
- **Rollback mechanism**: re-point the `current` symlink to the previous release and restart the
|
- **Rollback mechanism**: re-point the `current` symlink to the previous release and restart the
|
||||||
service — already fully specified, this stage just needs to write it up as a runnable procedure
|
service — already fully specified, this stage just needs to write it up as a runnable procedure
|
||||||
- **Approval gate for production**: the `workflow_dispatch` + `deploy_production` flag itself is the
|
- **Approval gate for production**: the `workflow_dispatch` + `deploy_sls_production` flag itself is the
|
||||||
approval gate (D-09) — no additional gate is needed
|
approval gate (D-09) — no additional gate is needed
|
||||||
|
|
||||||
## Question 1: Include Deployment Setup?
|
## Question 1: Include Deployment Setup?
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Offering schedule (offering-schedule)
|
||||||
|
|
||||||
|
- **Slug**: offering-schedule
|
||||||
|
- **Type**: Feature (small), built outside the AI-DLC flow and documented afterwards
|
||||||
|
- **Status**: Commits 8af156c and 32b98fe on `feature/contact-forms-module`; on the test hosts once CI run 109 is deployed (not merged, nothing in production)
|
||||||
|
- **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)
|
||||||
|
|
||||||
|
> Not run through the AI-DLC stages; this file records what the code does. There are no `requirements`, `plans` or `audit.md`.
|
||||||
|
|
||||||
|
## Purpose
|
||||||
|
|
||||||
|
An offering (package) can be switched on or off and limited to a period, so it can be prepared in advance or retired without deleting it.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
|
||||||
|
| Item | Behaviour |
|
||||||
|
|---|---|
|
||||||
|
| Fields on `Offering` | `IsActive` (default true), `StartsAt?`, `EndsAt?` (UTC). Migration `20261115100000_AddOfferingSchedule`. |
|
||||||
|
| Live | An offering is live when it is switched on, `StartsAt` is empty or not in the future, and `EndsAt` is empty or still in the future (`OfferingSchedule.IsLive`). |
|
||||||
|
| Public list | `GET /api/v1/offerings` returns **only live offerings**, evaluated at request time. Consumers that fetch at build time (the ASF website) therefore get the schedule as it is at the build moment. |
|
||||||
|
| Administrator list | `GET /api/v1/offerings/all` (AdminOnly) returns every offering including switched-off, planned and expired ones, with `isActive`, `startsAt` and `endsAt`. |
|
||||||
|
| Create / update | `CreateOfferingRequest` / `UpdateOfferingRequest` accept `isActive`, `startsAt`, `endsAt`; the schedule is validated (`OfferingSchedule.Validate`, end must be after start). |
|
||||||
|
| Cache | Every change invalidates the host's index.html cache (SpaFallback hosts), so the SLP markers refresh at once. A schedule boundary that passes on its own is picked up when the cache entry expires (about 60 seconds). |
|
||||||
|
| Admin UI | The package form has the schedule fields and a Cancel button; the featured star keeps the schedule. The list loads `/offerings/all`. |
|
||||||
+1
-1
@@ -14,7 +14,7 @@ as the artifact built, tested, and deployed to `test.slpsoftware.nl` / `slpsoftw
|
|||||||
|
|
||||||
| File | Change |
|
| File | Change |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `.gitea/workflows/continuous_integration.yaml` | `publish-test`/`publish-production`'s "Build admin frontend" and "Publish" steps retargeted from `src/SlpModularCms.Api` to `src/SlpModularCms.Api.SlpSoftware` (6 lines). Everything else — the six CI gates, `deploy-scp.yaml` calls, Gitea variables/secrets, `SlpModularCms.Api.Tests` (Unit 1's own regression suite, scoped to `Api` per NFR-CS-01) — is unchanged. |
|
| `.gitea/workflows/continuous_integration.yaml` | `publish-sls-test`/`publish-sls-production`'s "Build admin frontend" and "Publish" steps retargeted from `src/SlpModularCms.Api` to `src/SlpModularCms.Api.SlpSoftware` (6 lines). Everything else — the six CI gates, `deploy-scp.yaml` calls, Gitea variables/secrets, `SlpModularCms.Api.Tests` (Unit 1's own regression suite, scoped to `Api` per NFR-CS-01) — is unchanged. |
|
||||||
| `deploy-scp.yaml` | **No change.** It never hardcodes an entry-point `.dll` name; it uploads whatever the artifact contains and restarts a `service_name` input string. |
|
| `deploy-scp.yaml` | **No change.** It never hardcodes an entry-point `.dll` name; it uploads whatever the artifact contains and restarts a `service_name` input string. |
|
||||||
| `gitea-deployment-workflow/operations/deployment/deployment-instructions.md` § 1.6 | systemd unit `ExecStart` documentation updated to `SlpModularCms.Api.SlpSoftware.dll`, with an explicit note that this is a manual, host-side edit for already-existing units — this session cannot reach the Pi to apply it. |
|
| `gitea-deployment-workflow/operations/deployment/deployment-instructions.md` § 1.6 | systemd unit `ExecStart` documentation updated to `SlpModularCms.Api.SlpSoftware.dll`, with an explicit note that this is a manual, host-side edit for already-existing units — this session cannot reach the Pi to apply it. |
|
||||||
| `rollback-plan.md` | **No change.** Operates on the release-directory/symlink level, not a specific `.dll` name. |
|
| `rollback-plan.md` | **No change.** Operates on the release-directory/symlink level, not a specific `.dll` name. |
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Website SEO on the CMS host (website-seo)
|
||||||
|
|
||||||
|
- **Slug**: website-seo
|
||||||
|
- **Type**: Feature (small), built outside the AI-DLC flow and documented afterwards
|
||||||
|
- **Status**: Commits a7460a0, 284ff1f (2026-11-11) and 32b98fe on `feature/contact-forms-module`; on the SLP test host (not merged, nothing in production)
|
||||||
|
- **Affected components**: `SlpModularCms.Core` (`Hosting/Website`), `SlpModularCms.Modules.Offerings` (index markers), `SlpModularCms.Api.SlpSoftware/appsettings.json`
|
||||||
|
- **Documented**: 2026-11-15
|
||||||
|
- **Documentation Language**: English
|
||||||
|
- **Conversation Language**: Dutch (user language)
|
||||||
|
|
||||||
|
> Not run through the AI-DLC stages; this file records what the code does. There are no `requirements`, `plans` or `audit.md`.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Only hosts in `WebsiteMode.SpaFallback` (SlpSoftware). The ASF host (`PrerenderedPages`) registers none of this: that site builds its own canonical, og, JSON-LD and sitemap.
|
||||||
|
|
||||||
|
## Behaviour (`Website` configuration section)
|
||||||
|
|
||||||
|
| Setting | Effect |
|
||||||
|
|---|---|
|
||||||
|
| `NoIndex` (default `true`, fail-safe) | `X-Robots-Tag: noindex, nofollow` on every response; `/robots.txt` is `Disallow: /`; no sitemap. **Production must set `Website__NoIndex=false`.** |
|
||||||
|
| `PublicBaseUrl` | Absolute address of the instance. With `NoIndex=false`: `/robots.txt` allows all and points to `{PublicBaseUrl}/sitemap.xml`; `/sitemap.xml` lists `Sitemap:Paths` (no `lastmod`). Production: `https://slpsoftware.nl`. |
|
||||||
|
| `AuthoredBaseUrl` | The address the static `index.html` is written with. On a test instance with its own `PublicBaseUrl`, the host replaces the authored address by `PublicBaseUrl` in the served HTML (canonical, og, JSON-LD). Equal on production, so nothing changes. Only the configured value is used, never the request's Host header. |
|
||||||
|
| `KnownPaths` | Only these paths are pages (200, the SPA shell); any other website path is a real 404 (still the shell). `/api`, `/admin` and assets keep working. |
|
||||||
|
| `Sitemap:Paths` | Paths listed in the sitemap. |
|
||||||
|
|
||||||
|
## Index markers (`HtmlMarkerInjector` (until 2026-11-15 `IndexHtmlInjector`; generalised for the prerendered host, see asf-host-injection))
|
||||||
|
|
||||||
|
The host fills markers in `index.html`: `<!--SLP:OFFERINGS-JSON-LD-->` (schema.org `ItemList` of `Offer`) and `<!--SLP:OFFERINGS-HTML-->` (a static `#packages-static` list), rendered by `OfferingsIndexMarkers` from the live offerings. 60-second cache, invalidated directly by every offering change, `ETag` with 304 support; if a provider fails the plain page is still served. The markers must stay in `<body>` above `#root`; the website removes `#packages-static` on start-up.
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# Captcha-aanbieders voor het contactformulier
|
||||||
|
|
||||||
|
Levend document. Laatst bijgewerkt: 2026-11-15. Bronnen zijn gecontroleerd op **2026-11-15** (zie "Bronnen"). Prijzen en limieten spreken elkaar in de bronnen vaak tegen (veel bronnen zijn concurrenten van de aanbieder over wie ze schrijven): **controleer ze bij de aanbieder zelf voordat er iets wordt afgenomen of gebouwd.**
|
||||||
|
|
||||||
|
## Doel en uitgangspunten
|
||||||
|
|
||||||
|
Het contactformulier van beide sites (SlpSoftware en Andrea Slop Fotografie) wordt beschermd tegen spam door de CMS-host (`SlpModularCms.Modules.Contact`). Nu: een honeypot-veld, een minimale wachttijd (`Contact:MinSeconds`), een eenmalig token (`/contact-messages/token`), idempotentie en rate limits per bezoeker. **Een captcha staat uit** (`Contact:Captcha:Enabled=false`) en is voor productie nog niet gekozen. Zie ook [privacy-gegevens-contactformulier.md](privacy-gegevens-contactformulier.md) en [deploy-en-testomgevingen.md](deploy-en-testomgevingen.md) (het captcha staat uit tot dit besluit).
|
||||||
|
|
||||||
|
Wensen van Bryan: **gratis of goedkoop**, voor **twee websites**, liefst **geen cookiebanner** nodig (past dus slecht bij aanbieders die cookies/tracking zetten).
|
||||||
|
|
||||||
|
## Beslisstatus
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| **Beslissing** | _nog niet gekozen_ |
|
||||||
|
| **Datum** | _(in te vullen door Bryan)_ |
|
||||||
|
| **Gekozen aanbieder** | _(in te vullen)_ |
|
||||||
|
| **Opmerkingen** | |
|
||||||
|
|
||||||
|
## Wat er nu is
|
||||||
|
|
||||||
|
- **Server (CMS):** `ICaptchaVerifier` in de Contact-module met één implementatie, `FriendlyCaptchaVerifier` (Friendly Captcha v2). Instellingen: `Contact:Captcha:Enabled`, `Provider` (nu alleen `friendlycaptcha`), `SiteKey`, `Secret` (alleen via omgeving: `Contact__Captcha__Secret`), `Region` (`global`|`eu`). Ontbreekt het antwoord terwijl het captcha aan staat, dan geldt het bericht als spam; bereikt de server de aanbieder niet, dan wordt de bezoeker doorgelaten (fail-open).
|
||||||
|
- **Contract met de site:** de site leest `{ provider, siteKey, apiEndpoint }` van de CMS-host. De **widget in de ASF-website kent alleen Friendly Captcha**; het formulier praat met de widget via `setCaptchaToken` / `onProblem` / `resetCount` (volgens de ASF-sessie).
|
||||||
|
- **CSP:** onder het `StrictSite`-beleid komen extra origins uit `SecurityHeaders:AllowedSiteScriptOrigins`, `AllowedSiteConnectOrigins` en `AllowedSiteFrameOrigins` (frame-src, bijvoorbeeld de Friendly Captcha-widget). Voor test/productie moet dat ook in de proxy (nginx) of IIS kloppen, als die eigen headers zetten.
|
||||||
|
|
||||||
|
## Overzicht
|
||||||
|
|
||||||
|
Bedragen zijn indicatief (zie de waarschuwing bovenaan).
|
||||||
|
|
||||||
|
| | 1. Niets extra | 2. Altcha (zelf gehost) | 3. Cloudflare Turnstile | 4. Google reCAPTCHA | 5. hCaptcha | 6. Friendly Captcha |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| **Kosten** | € 0 | € 0 (open source, MIT); betaalde cloud/support optioneel | gratis; gratis plan met max. 20 widgets; limiet van ca. 1 miljoen verificaties/maand genoemd (bronnen verschillen) | gratis tot 10.000 beoordelingen/maand; daarboven via Google Cloud (genoemd: vast $ 8/maand tot 100.000, daarna per beoordeling) | gratis Basic-laag (genoemd tot 10.000/maand, bronnen verschillen); passieve modus pas vanaf Pro (genoemd $ 99/maand) | gratis alleen niet-commercieel (ca. 1.000 verzoeken/maand); commercieel vanaf ca. € 9/maand per domein |
|
||||||
|
| **Dataplek** | n.v.t. | **eigen host (EU/eigen keuze)**; geen derde partij | VS-bedrijf, wereldwijd netwerk | VS-bedrijf (Google) | VS-bedrijf; EU-VS Data Privacy Framework en SCC's | **EU** (Duits bedrijf); `eu`-endpoint volgens één bron alleen in een duur plan, controleer |
|
||||||
|
| **Cookies / toestemming** | geen | geen, geen fingerprinting | "grotendeels zonder cookies"; `cf_clearance` bij pre-clearance; onduidelijk voor onze configuratie | cookies/tracking; in de EU meestal toestemming nodig | cookies; kritiek over doelen in de cookieverklaring; toestemming onzeker | geen cookies |
|
||||||
|
| **Toegankelijkheid** | geen last voor bezoekers | geen puzzel; werkt op proof-of-work; WCAG 2.2 AA volgens de aanbieder | meestal onzichtbaar/eenmalige checkbox | v2 plaatjes/checkbox is lastig; v3 onzichtbaar (score) | plaatjes in de gratis laag (geen passieve modus) | onzichtbaar proof-of-work |
|
||||||
|
| **CSP-gevolgen** | geen | **geen externe hosts**: `connect-src 'self'`, mogelijk `worker-src blob:` voor de rekenwerker | `script-src` + `frame-src` `https://challenges.cloudflare.com` (en connect) | `script-src`/`frame-src` `https://www.google.com`, `https://www.gstatic.com` | `script-src`/`frame-src`/`connect-src` `https://hcaptcha.com`, `https://*.hcaptcha.com` | `frame-src`/`connect-src` `https://global.frcapi.com` of `https://eu.frcapi.com` (bestaat al in de configuratie) |
|
||||||
|
| **Serverkant** | n.v.t. | CMS geeft de challenge uit en controleert de oplossing (geen externe call) | één `siteverify`-call naar Cloudflare | één `siteverify`-call naar Google | één `siteverify`-call | één verify-call (bestaat al: `FriendlyCaptchaVerifier`) |
|
||||||
|
| **Werk om te bouwen** | geen | **middel**: challenge-endpoint + verificatie (HMAC), nonce/vervaltijd tegen hergebruik, widget-adapter, tests | klein tot middel: verifier + widget-adapter | klein tot middel: verifier + widget-adapter | klein tot middel | **geen** (werkt al); enkel plan kiezen |
|
||||||
|
| **Aanbeveling** | basis, blijft altijd aan | **eerste keus** als er een captcha nodig is en niets bij derden mag landen | goede gratis tweede keus als een VS-partij en een extern script acceptabel zijn | **afgeraden** vanwege toestemming en tracking | minst aangeraden | goede keuze als de kosten (ca. € 9/maand per domein, dus voor twee sites ca. € 18) acceptabel zijn |
|
||||||
|
|
||||||
|
## Per aanbieder
|
||||||
|
|
||||||
|
### 1. Niets extra (huidige bescherming)
|
||||||
|
|
||||||
|
Honeypot, wachttijd, eenmalig token, idempotentiesleutel en rate limits per bezoeker (met `ForwardedHeaders:KnownProxies` correct gezet; zonder dat deelt de hele site één emmer). Geen kosten, geen privacygevolgen, geen werk. Beperking: geen bescherming tegen een gerichte bot die de wachttijd en het token respecteert en per bezoeker onder de rate limit blijft. **Is een volwaardige keuze zolang er in de praktijk weinig spam binnenkomt.**
|
||||||
|
|
||||||
|
### 2. Altcha (zelf gehost proof-of-work)
|
||||||
|
|
||||||
|
- **Kosten:** open source (MIT), gratis. De aanbieder verkoopt daarnaast een cloud/professioneel plan; bronnen noemen uiteenlopende bedragen (€ 9 voor 100.000 verificaties tegenover € 99 voor een ander pakket): niet nodig voor zelf hosten.
|
||||||
|
- **Data en privacy:** niets verlaat onze host; geen derde partij, geen cookies, geen fingerprinting (volgens de aanbieder en directories).
|
||||||
|
- **Toegankelijkheid:** geen puzzel; de browser rekent een korte proof-of-work uit. Aanbieder claimt WCAG 2.2 AA.
|
||||||
|
- **CSP:** geen externe origins. De widget laadt als script van de eigen host (of is meegebouwd); de verificatie gaat naar `'self'`. De rekenwerker kan `worker-src blob:` vragen.
|
||||||
|
- **Server:** de CMS-host geeft de challenge uit (met HMAC-sleutel in de omgeving) en controleert de oplossing zelf. Vraagt een nieuw endpoint, tijdsvenster, bescherming tegen hergebruik (nonce opslaan of kort token) en rate limit op de challenge.
|
||||||
|
- **Werk:** middel (ca. 1,5-2 dagen: server, adapter in de widget, CSP, tests, privacytekst).
|
||||||
|
- **Beperking:** proof-of-work vertraagt bots maar herkent ze niet; geen risicoscore of dashboard in de gratis versie.
|
||||||
|
|
||||||
|
### 3. Cloudflare Turnstile
|
||||||
|
|
||||||
|
- **Kosten:** gratis plan (maximaal 20 widgets; een limiet van ca. 1 miljoen verificaties per maand wordt genoemd, bronnen verschillen). Enterprise op aanvraag.
|
||||||
|
- **Data/cookies:** VS-bedrijf; "grotendeels zonder cookies", maar met pre-clearance kan `cf_clearance` worden gezet; Cloudflare verwijst voor details naar een privacy-addendum (niet door ons gelezen).
|
||||||
|
- **Toegankelijkheid:** meestal onzichtbaar, soms een enkele klik.
|
||||||
|
- **CSP:** extern script en frame van `https://challenges.cloudflare.com`.
|
||||||
|
- **Server:** één `siteverify`-call naar Cloudflare met het geheim in de omgeving.
|
||||||
|
- **Werk:** ca. ½-1 dag per site voor verifier + adapter in de widget (plus eenmalig de provider-neutrale widget, zie hieronder).
|
||||||
|
- **Let op:** extern script van een VS-bedrijf; in de privacytekst noemen.
|
||||||
|
|
||||||
|
### 4. Google reCAPTCHA (nieuw toegevoegd aan de vergelijking)
|
||||||
|
|
||||||
|
- **Kosten:** gratis tot 10.000 beoordelingen per maand per organisatie (over alle sites samen); boven die grens via Google Cloud met facturering (volgens de documentatie een vast bedrag tot 100.000 en daarna per beoordeling). De datum waarop de gratis grens van 1 miljoen naar 10.000 ging verschilt per bron (2024, 2025 of 2026): controleren bij Google.
|
||||||
|
- **Data/cookies:** VS-bedrijf; cookies en tracking; in de EU is meestal toestemming nodig. **Dat past slecht bij de keuze "geen cookiebanner".**
|
||||||
|
- **Versies:** v2 (checkbox, soms plaatjes: lastiger voor bezoekers) of v3 (onzichtbaar, score; vraagt een drempelwaarde en afhandeling van lage scores).
|
||||||
|
- **CSP:** scripts en frames van `https://www.google.com` en `https://www.gstatic.com`.
|
||||||
|
- **Server:** één `siteverify`-call (of de Enterprise-API).
|
||||||
|
- **Werk:** ½-1 dag.
|
||||||
|
- **Aanbeveling:** niet kiezen tenzij er een bijzondere reden is.
|
||||||
|
|
||||||
|
### 5. hCaptcha
|
||||||
|
|
||||||
|
- **Kosten:** gratis Basic-laag (bronnen noemen 10.000/maand of "onbeperkt"; de aanbieder zegt zelf niet wat er daarboven gebeurt); alleen zichtbare puzzels in de gratis laag, passieve modus pas vanaf Pro (genoemd $ 99/maand).
|
||||||
|
- **Data/cookies:** VS-bedrijf (EU-VS Data Privacy Framework, SCC's); cookies; kritiek in bronnen (meestal concurrenten) over doelen in het cookiebeleid; toestemming onzeker.
|
||||||
|
- **CSP:** `https://hcaptcha.com` en `https://*.hcaptcha.com` (script, frame, connect).
|
||||||
|
- **Server:** één `siteverify`-call.
|
||||||
|
- **Werk:** ½-1 dag.
|
||||||
|
- **Aanbeveling:** minst aangeraden voor onze wensen (puzzels voor bezoekers, cookies).
|
||||||
|
|
||||||
|
### 6. Friendly Captcha (nu de enige ondersteunde aanbieder in de widget)
|
||||||
|
|
||||||
|
- **Kosten:** het gratis plan is niet-commercieel en beperkt (genoemd 1.000 verzoeken per maand); commercieel gebruik vanaf ca. € 9/maand per domein (Starter); grotere plannen volgen (genoemd € 39 en € 200). Eén bron zegt dat er helemaal geen gratis plan is: controleer. **Voor twee sites: ca. € 18/maand.** Een proefperiode van 30 dagen wordt genoemd.
|
||||||
|
- **Data/cookies:** EU-bedrijf; geen cookies. Het `global`-endpoint kan IP-adressen buiten de EU verwerken; een `eu`-endpoint (`Contact:Captcha:Region=eu`) wordt volgens één bron alleen in een duur plan geleverd: controleer de dataplek vóór de privacytekst wordt vastgesteld.
|
||||||
|
- **Toegankelijkheid:** onzichtbaar proof-of-work.
|
||||||
|
- **CSP:** `frame-src`/`connect-src` voor `https://global.frcapi.com` of `https://eu.frcapi.com`.
|
||||||
|
- **Server:** gebouwd en getest (`FriendlyCaptchaVerifier`, fail-open bij een storing van de aanbieder).
|
||||||
|
- **Werk:** geen, enkel het plan en de sleutels.
|
||||||
|
|
||||||
|
## Werk voor een andere aanbieder dan Friendly Captcha
|
||||||
|
|
||||||
|
Volgens de ASF-sessie (website) en de code van de CMS-host:
|
||||||
|
|
||||||
|
| Onderdeel | Werk |
|
||||||
|
|---|---|
|
||||||
|
| Widget in de website | De widget kent alleen Friendly Captcha. Provider-neutraal maken (formulier praat al via `setCaptchaToken` / `onProblem` / `resetCount`) is ca. **1 dag** (eenmalig). Daarna per aanbieder een adapter van ca. **½-1 dag**. |
|
||||||
|
| Contract `{ provider, siteKey, apiEndpoint }` | Bestaat al en kan een andere `provider` melden. |
|
||||||
|
| CMS-host (server) | `ICaptchaVerifier` bestaat; per aanbieder een implementatie (Turnstile/reCAPTCHA/hCaptcha: ½-1 dag, Altcha: ca. 1,5-2 dagen), `Contact:Captcha:Provider` accepteert nu alleen `friendlycaptcha` (validatie uitbreiden), kiezen op basis van `Provider`, opties en tests. |
|
||||||
|
| CSP per aanbieder | `AllowedSiteScriptOrigins` / `AllowedSiteConnectOrigins` / `AllowedSiteFrameOrigins` in de CMS-host **en** de CSP van de proxy (nginx op de testhost) of IIS (productie); één bron van waarheid per site. |
|
||||||
|
| Privacytekst | Per aanbieder aanpassen (wie verwerkt, waar, welke cookies); zie [privacy-gegevens-contactformulier.md](privacy-gegevens-contactformulier.md). |
|
||||||
|
| Productie-instellingen | Sleutels en geheimen alleen via omgevingsvariabelen; `Contact:Captcha:Enabled=true` pas na besluit; test eerst op de testhosts. |
|
||||||
|
|
||||||
|
## Bronnen (gecontroleerd op 2026-11-15)
|
||||||
|
|
||||||
|
Dit zijn zoekresultaten en samenvattingen; niet alle pagina's van de aanbieders zelf konden worden gelezen. Bedragen en limieten vóór afname bij de aanbieder verifiëren.
|
||||||
|
|
||||||
|
- Altcha: [open source captcha](https://altcha.org/open-source-captcha/), [open source versus betaald](https://altcha.org/docs/open-source-vs-paid/), [cloud-prijzen](https://altcha.org/docs/v2/cloud/pricing). Vergelijking van een concurrent: [captcha.eu](https://www.captcha.eu/altcha-vs-captchaeu/). De prijzen in bronnen verschillen (€ 9 en € 99).
|
||||||
|
- Cloudflare Turnstile: [plannen](https://developers.cloudflare.com/turnstile/plans), [documentatie (volledige tekst)](https://developers.cloudflare.com/turnstile/llms-full.txt); derden: [Prosopo](https://prosopo.io/tools/cloudflare-turnstile-pricing/), [captcha.eu](https://www.captcha.eu/?p=3564), [Piano](https://docs.piano.io/en/subscriptions/cloudflare-turnstile). Genoemde limieten (20 widgets, 1 miljoen) verschillen per bron.
|
||||||
|
- Google reCAPTCHA: [facturering](https://docs.cloud.google.com/recaptcha/docs/billing-information), [lagen vergelijken](https://docs.cloud.google.com/recaptcha/docs/compare-tiers); derden over de datum van de wijziging: [phpcaptcha.org](https://www.phpcaptcha.org/recaptcha-pricing), [Prosopo](https://prosopo.io/tools/recaptcha-pricing-calculator/).
|
||||||
|
- hCaptcha: [Prosopo-vergelijking](https://prosopo.io/blog/procaptcha-vs-hcaptcha-comparison/), [phpcaptcha.org](https://www.phpcaptcha.org/hcaptcha-review), [splitforms](https://splitforms.com/blog/hcaptcha-pricing-free-plan-limits); privacykritiek van concurrenten: [captcha.eu](https://www.captcha.eu/?p=3413), [Friendly Captcha](https://friendlycaptcha.com/insights/hcaptcha-gdpr/).
|
||||||
|
- Friendly Captcha: [llms.txt van de aanbieder](https://friendlycaptcha.com/llms.txt), [Capterra](https://www.capterra.com/p/10034125/Friendly-Captcha/), [TrustComponent-vergelijking](https://www.trustcomponent.com/en/products/captcha/comparison/friendly-captcha-vs-trustcaptcha), [DreamHost](https://www.dreamhost.com/blog/captcha-alternative/).
|
||||||
|
- Eerder in de repository: de aantekening over regio's en plannen in `aidlc-docs/features/contact-forms-module/construction/phase-1-handoff.md`.
|
||||||
|
|
||||||
|
## Open vragen voor Bryan
|
||||||
|
|
||||||
|
1. Is een captcha nodig? Zo ja, hoeveel spam komt er nu binnen (geen captcha op test; productie nog niet live)?
|
||||||
|
2. Is een extern script van een VS-aanbieder (Turnstile) acceptabel, of is "alles op onze eigen host" (Altcha) of "EU, betaald" (Friendly Captcha) de wens?
|
||||||
|
3. Welk bedrag per maand is acceptabel (twee sites)?
|
||||||
@@ -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-sls-test en publish-sls-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.
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# 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-sls-test` |
|
||||||
|
| SlpSoftware productie | `SlpModularCms.Api.SlpSoftware` | `https://slpsoftware.nl`, health `https://slpsoftware.nl/health` | `deploy-sls-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 voor het master-CMS (`SlpModularCms.Api` met alle modules, Core, alle testprojecten via `SlpModularCms.Ci.slnf`; kwetsbaarheidscontrole; frontend build/test/lint) en de niet-verplichte `compile-sites` (alleen compileren van de dunne site-projecten). Er wordt **niet** gepubliceerd of gedeployed: een site wordt pas gebouwd bij een deploy. Een nieuwe push naar dezelfde PR annuleert de lopende run. |
|
||||||
|
| `push` op `master` | Dezelfde poorten, daarna automatisch `deploy-sls-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_sls_test` | uit | Bouwt (`publish-sls-test`) en deployt naar SlpSoftware test |
|
||||||
|
| `deploy_sls_production` | uit | Bouwt (`publish-sls-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_sls_production` is aan de `master`-branch niet gebonden in de workflow: de conditie van `deploy-sls-production` controleert alleen de gebeurtenis en de invoer, niet de branch (zie `ci`, job `deploy-sls-production`).
|
||||||
|
|
||||||
|
## Jobnamen en branch protection (merge-checklist)
|
||||||
|
|
||||||
|
Jobnamen volgen `{actie}-{site}-{omgeving}`: `config-sls`, `publish-sls-test`, `deploy-sls-test`, `publish-sls-production`, `deploy-sls-production` en voor Andrea `config-asf`, `publish-asf-test`, `deploy-asf-test`. Ook de invoeren van de handmatige run hebben de sitenaam: `deploy_sls_test`, `deploy_sls_production` en `deploy_asf_test` (vroeger `deploy_test` en `deploy_production`). De uitvoer van `config-sls` heet `artifact_name_sls_*`, `deploy_environment_sls_*`, `deploy_path_sls_*`, `service_name_sls_*` en `health_check_url_sls_*`, de artefacten `app-sls-test` en `app-sls-production` (ASF: `app-asf-test`). De Gitea-variabelen en -secrets (bijv. `DEPLOY_PATH_TEST`) zijn niet hernoemd.
|
||||||
|
|
||||||
|
Wat de CI per site doet: bij een pull request bouwt en test de CI alleen het master-CMS (alle modules, `SlpModularCms.Ci.slnf`). De sites (`Api.SlpSoftware`, `Api.AndreaSlopFotografie`, `Api.Slave`) zijn dunne composities zonder eigen logica; hun samenstelling en standaardwaarden worden getest op de master-host (`SiteContractTests`, `AsfVariantPipelineTests`, `SiteVariantContactTests`), `compile-sites` controleert dat ze nog compileren (niet verplicht) en `publish-*` bouwt een site pas bij een deploy (push naar `master` of een aangevinkte invoer). Na elke test-deploy draait een rooktest (`scripts/smoke-site.sh`, jobs `smoke-sls-test` en `smoke-asf-test`: health, modulelijst in `/System/capabilities`, noindex, beschermde beheerroutes, 404 op een onbekend pad bij ASF); faalt die, dan faalt de run.
|
||||||
|
|
||||||
|
Branch protection op `master`: verplicht zijn alleen `Continuous Integration / backend-test (pull_request)` en `frontend-test (pull_request)`. De eerdere verplichte check `publish-test (pull_request)` bestaat niet meer (er wordt bij een pull request niet meer gepubliceerd) en **moet vóór de merge uit de vereiste checks worden gehaald** (Gitea: repository, Instellingen, Branches, beschermde branch `master`, vereiste statuschecks), anders wacht de merge op een check die nooit meer draait. Pas dat vlak voor de merge aan, met Bryans go.
|
||||||
|
|
||||||
|
## 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_sls_test` aan (SlpSoftware test) en/of `deploy_asf_test` (ASF test). Laat `deploy_sls_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-sls`-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-sls-test`/`publish-sls-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.
|
||||||
|
|
||||||
|
## Captcha
|
||||||
|
|
||||||
|
Het captcha van het contactformulier staat uit (`Contact:Captcha:Enabled=false`) tot Bryan een aanbieder kiest. De vergelijking van de opties, de gevolgen voor CSP, privacy en werk en de beslisrij staan in [captcha-providers.md](captcha-providers.md). Zet het captcha pas aan na dat besluit, met de sleutels alleen via omgevingsvariabelen.
|
||||||
@@ -0,0 +1,413 @@
|
|||||||
|
# Teksten van de mails van het CMS
|
||||||
|
|
||||||
|
Gegenereerd door `scripts/Export-MailTexts.ps1` uit `src/SlpModularCms.Core/Texts/nl.json` en `en.json` (en de voorbeeldmails in `src/SlpModularCms.Core.Tests/Golden/mail`). Niet met de hand wijzigen: pas de tekstbestanden aan en draai het script opnieuw. Zie [translation-files.md](translation-files.md) voor de opzet.
|
||||||
|
|
||||||
|
In de teksten staan plaatshouders tussen accolades die bij het versturen worden ingevuld: `{site}` (naam van de site), `{validity}` (hoe lang een link geldig is, bijvoorbeeld "48 uur" of "30 minuten"), `{role}` (de nieuwe rol) en `{name}` (naam van de ontvanger). Elke mail heeft bovenaan een kop, optioneel een aanhef, de inleiding, eventueel een knop met de link, een opmerking en onderaan een vaste voettekst.
|
||||||
|
|
||||||
|
## Vaste onderdelen
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Aanhef (als de naam van de ontvanger bekend is) | Hallo {name}, | Hello {name}, |
|
||||||
|
| Voettekst onder elke mail | Deze mail is automatisch verstuurd door {site}. | This message was sent automatically by {site}. |
|
||||||
|
| Rol: eigenaar | Eigenaar | Owner |
|
||||||
|
| Rol: beheerder | Beheerder | Administrator |
|
||||||
|
| Rol: gebruiker | Gebruiker | User |
|
||||||
|
| Geldigheid, 1 uur | {count} uur | {count} hour |
|
||||||
|
| Geldigheid, meerdere uren | {count} uur | {count} hours |
|
||||||
|
| Geldigheid, minuten | {count} minuten | {count} minutes |
|
||||||
|
|
||||||
|
## Uitnodiging
|
||||||
|
|
||||||
|
Wanneer: Een beheerder nodigt iemand uit.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Uitnodiging voor {site} | Invitation to {site} |
|
||||||
|
| Kop | Je bent uitgenodigd | You have been invited |
|
||||||
|
| Inleiding | Je bent uitgenodigd om een account aan te maken voor {site}. Kies met de knop hieronder je wachtwoord om je account te activeren. | You have been invited to create an account for {site}. Use the button below to choose your password and activate your account. |
|
||||||
|
| Knop | Account activeren | Activate account |
|
||||||
|
| Opmerking onderaan | Deze link is {validity} geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging. | This link is valid for {validity}. If it has expired, ask the administrator for a new invitation. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Je bent uitgenodigd
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Je bent uitgenodigd om een account aan te maken voor Test <Site> & Co. Kies met de knop hieronder je wachtwoord om je account te activeren.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
Deze link is 48 uur geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging.
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
You have been invited
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
You have been invited to create an account for Test <Site> & Co. Use the button below to choose your password and activate your account.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
This link is valid for 48 hours. If it has expired, ask the administrator for a new invitation.
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Nieuwe uitnodigingslink
|
||||||
|
|
||||||
|
Wanneer: Een beheerder maakt een nieuwe uitnodigingslink aan.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Nieuwe uitnodigingslink voor {site} | New invitation link for {site} |
|
||||||
|
| Kop | Je hebt een nieuwe uitnodigingslink | You have a new invitation link |
|
||||||
|
| Inleiding | Er is een nieuwe uitnodigingslink voor je aangemaakt voor {site}. De vorige link werkt niet meer. | A new invitation link has been created for you for {site}. The previous link no longer works. |
|
||||||
|
| Knop | Account activeren | Activate account |
|
||||||
|
| Opmerking onderaan | Deze link is {validity} geldig. | This link is valid for {validity}. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Je hebt een nieuwe uitnodigingslink
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Er is een nieuwe uitnodigingslink voor je aangemaakt voor Test <Site> & Co. De vorige link werkt niet meer.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
Deze link is 1 uur geldig.
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
You have a new invitation link
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
A new invitation link has been created for you for Test <Site> & Co. The previous link no longer works.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
This link is valid for 1 hour.
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Wachtwoord opnieuw instellen
|
||||||
|
|
||||||
|
Wanneer: Iemand vraagt een nieuw wachtwoord aan.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Wachtwoord opnieuw instellen voor {site} | Reset your password for {site} |
|
||||||
|
| Kop | Wachtwoord opnieuw instellen | Reset your password |
|
||||||
|
| Inleiding | Er is gevraagd om het wachtwoord van je account bij {site} opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen. | A request was made to reset the password of your account at {site}. Use the button below to choose a new password. |
|
||||||
|
| Knop | Nieuw wachtwoord kiezen | Choose a new password |
|
||||||
|
| Opmerking onderaan | Deze link is {validity} geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd. | This link is valid for {validity} and works once. Did you not ask for this? Ignore this message: your password stays unchanged. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Wachtwoord opnieuw instellen
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Er is gevraagd om het wachtwoord van je account bij Test <Site> & Co opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
Deze link is 30 minuten geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd.
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Reset your password
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
A request was made to reset the password of your account at Test <Site> & Co. Use the button below to choose a new password.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
This link is valid for 30 minutes and works once. Did you not ask for this? Ignore this message: your password stays unchanged.
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Account gedeactiveerd
|
||||||
|
|
||||||
|
Wanneer: Een beheerder deactiveert een account.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Je account bij {site} is gedeactiveerd | Your account at {site} has been deactivated |
|
||||||
|
| Kop | Account gedeactiveerd | Account deactivated |
|
||||||
|
| Inleiding | Een beheerder heeft je account bij {site} gedeactiveerd. Je kunt niet meer inloggen. | An administrator has deactivated your account at {site}. You can no longer sign in. |
|
||||||
|
| Opmerking onderaan | Denk je dat dit niet klopt? Neem dan contact op met de beheerder. | Think this is a mistake? Please contact the administrator. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Account gedeactiveerd
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Een beheerder heeft je account bij Test <Site> & Co gedeactiveerd. Je kunt niet meer inloggen.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
Denk je dat dit niet klopt? Neem dan contact op met de beheerder.
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Account deactivated
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
An administrator has deactivated your account at Test <Site> & Co. You can no longer sign in.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
Think this is a mistake? Please contact the administrator.
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Account weer actief
|
||||||
|
|
||||||
|
Wanneer: Een beheerder activeert een account weer.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Je account bij {site} is weer actief | Your account at {site} is active again |
|
||||||
|
| Kop | Account weer actief | Account active again |
|
||||||
|
| Inleiding | Een beheerder heeft je account bij {site} weer geactiveerd. Je kunt weer inloggen. | An administrator has reactivated your account at {site}. You can sign in again. |
|
||||||
|
| Knop | Inloggen | Sign in |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Account weer actief
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Een beheerder heeft je account bij Test <Site> & Co weer geactiveerd. Je kunt weer inloggen.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Account active again
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
An administrator has reactivated your account at Test <Site> & Co. You can sign in again.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
https://test.example.nl/activate?token=a&b=c
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rol gewijzigd
|
||||||
|
|
||||||
|
Wanneer: Een beheerder wijzigt de rol van een gebruiker.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Je rol bij {site} is gewijzigd | Your role at {site} has changed |
|
||||||
|
| Kop | Rol gewijzigd | Role changed |
|
||||||
|
| Inleiding | Een beheerder heeft je rol bij {site} gewijzigd naar: {role}. | An administrator has changed your role at {site} to: {role}. |
|
||||||
|
| Opmerking onderaan | Denk je dat dit niet klopt? Neem dan contact op met de beheerder. | Think this is a mistake? Please contact the administrator. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Rol gewijzigd
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Een beheerder heeft je rol bij Test <Site> & Co gewijzigd naar: Beheerder.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
Denk je dat dit niet klopt? Neem dan contact op met de beheerder.
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Role changed
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
An administrator has changed your role at Test <Site> & Co to: Administrator.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
Think this is a mistake? Please contact the administrator.
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Nieuw contactbericht
|
||||||
|
|
||||||
|
Wanneer: Een bezoeker verstuurt het contactformulier; de mail gaat naar de eigenaar van de site.
|
||||||
|
|
||||||
|
| Onderdeel | Nederlands | Engels |
|
||||||
|
|---|---|---|
|
||||||
|
| Onderwerp | Nieuw bericht via {site} | New message via {site} |
|
||||||
|
| Kop | Nieuw bericht via het contactformulier | New message from the contact form |
|
||||||
|
| Inleiding | Er is een bericht verstuurd via het contactformulier van {site}. | A message was sent through the contact form of {site}. |
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Nederlands)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
Nieuw bericht via het contactformulier
|
||||||
|
|
||||||
|
Hallo Jan "de" Vries,
|
||||||
|
|
||||||
|
Er is een bericht verstuurd via het contactformulier van Test <Site> & Co.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
--
|
||||||
|
Deze mail is automatisch verstuurd door Test <Site> & Co.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Voorbeeld (tekstversie, Engels)**, met voorbeeldwaarden (site 'Test <Site> & Co', ontvanger 'Jan "de" Vries'):
|
||||||
|
|
||||||
|
```text
|
||||||
|
New message from the contact form
|
||||||
|
|
||||||
|
Hello Jan "de" Vries,
|
||||||
|
|
||||||
|
A message was sent through the contact form of Test <Site> & Co.
|
||||||
|
|
||||||
|
Naam:
|
||||||
|
Jan <script>
|
||||||
|
|
||||||
|
Bericht:
|
||||||
|
regel 1
|
||||||
|
regel 2 & meer
|
||||||
|
|
||||||
|
--
|
||||||
|
This message was sent automatically by Test <Site> & Co.
|
||||||
|
```
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
Welke aanbieder (of geen) uiteindelijk wordt gebruikt is nog niet besloten; de vergelijking en de beslisrij staan in [captcha-providers.md](captcha-providers.md). Deze privacytekst moet bij het besluit worden aangepast aan de gekozen aanbieder.
|
||||||
|
|
||||||
|
## 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.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# Gezamenlijke productie-checklist (CMS, SlpSoftware en Andrea Slop Fotografie)
|
||||||
|
|
||||||
|
Levend document (2026-11-16). Dit is de checklist voor het moment waarop Bryan de productie-release vrijgeeft. Operations van de features `contact-forms-module`, `offering-banners`, `offering-schedule`, `website-seo`, `ci-master-pipeline`, `asf-host-injection` en `translation-files` is **meegenomen in deze checklist**: er zijn geen aparte Operations-stappen per feature. Er wordt pas iets naar productie gezet na Bryans expliciete go; een push naar `master` deployt alleen naar de testomgevingen.
|
||||||
|
|
||||||
|
Achtergrond per onderwerp: [deploy-en-testomgevingen.md](deploy-en-testomgevingen.md), [captcha-providers.md](captcha-providers.md), [privacy-gegevens-contactformulier.md](privacy-gegevens-contactformulier.md), [translation-files.md](translation-files.md).
|
||||||
|
|
||||||
|
## 0. Voorwaarden
|
||||||
|
|
||||||
|
- [ ] Bryan heeft de release vrijgegeven (per site: SLP en ASF kunnen apart).
|
||||||
|
- [ ] De commit die naar productie gaat, is eerder groen geweest op de testhost van die site (CI-run met rooktest `smoke-sls-test` / `smoke-asf-test`).
|
||||||
|
- [ ] Er is een recente databaseback-up van productie. De migraties draaien bij het opstarten van de host.
|
||||||
|
|
||||||
|
## 1. Volgorde
|
||||||
|
|
||||||
|
1. **CMS eerst**: PR `feature/contact-forms-module` naar `master`, na de aanpassing van de branch protection (zie 2). Een push naar `master` deployt alleen naar TEST.
|
||||||
|
2. **Daarna ASF**: de website-PR van Andrea Slop Fotografie pas na de CMS-merge, en pas nadat het testcommit **d449e76 is verwijderd** (zie 3).
|
||||||
|
3. **Productie**: pas daarna, per site, met een handmatige dispatch (`deploy_sls_production` voor SLP). Nooit als bijproduct van een merge.
|
||||||
|
|
||||||
|
## 2. Branch protection (Gitea)
|
||||||
|
|
||||||
|
- [ ] Verplichte checks op `master`: alleen `backend-test (pull_request)` en `frontend-test (pull_request)`.
|
||||||
|
- [ ] `publish-test (pull_request)` is verwijderd uit de verplichte checks (de job draait niet meer op pull requests). Pas dit vlak vóór de merge aan, niet eerder.
|
||||||
|
- [ ] `compile-sites` is bedoeld als informatieve check en niet verplicht.
|
||||||
|
|
||||||
|
## 3. ASF
|
||||||
|
|
||||||
|
- [ ] Het testcommit **d449e76** (ASF-testconfiguratie) staat niet in wat naar productie gaat.
|
||||||
|
- [ ] ASF draait met `Website:Mode=PrerenderedPages` (staat in de eigen `appsettings.json`) en `Website__PublicBaseUrl` op het productieadres.
|
||||||
|
- [ ] De ASF-productiepipeline (self-contained win-x64 naar IIS) is een apart, nog niet gestart plan; zie het voorstel `iis-publish-pipeline` zodra dat bestaat.
|
||||||
|
|
||||||
|
## 4. SLP-productie: instellingen
|
||||||
|
|
||||||
|
| Instelling | Waarde in productie | Waarom |
|
||||||
|
|---|---|---|
|
||||||
|
| `Website__NoIndex` | `false` | Testhosts staan op `noindex`; zonder deze wijziging blijft productie voor zoekmachines dicht. Pas pas aan op het release-moment, niet eerder. |
|
||||||
|
| `Website__PublicBaseUrl` | het publieke productieadres, zonder slash achteraan | Canonical, `og:image`, sitemap, robots en `siteUrl` in de pagina-data volgen dit adres. |
|
||||||
|
| `Contact__Captcha__Enabled` | `false` | Er is nog geen captcha-aanbieder gekozen (zie captcha-providers.md). Sleutels komen anders alleen via omgevingsvariabelen. |
|
||||||
|
| `Contact__Enabled` | pas `true` als het formulier live moet | Het contactformulier staat standaard uit. |
|
||||||
|
| `Texts__DefaultLanguage` | `nl` (standaard) | De vaste teksten van de backend zijn Nederlands. |
|
||||||
|
|
||||||
|
## 5. Contact-retentie en privacy
|
||||||
|
|
||||||
|
- [ ] `Contact:RetentionMonths` (standaard 12) en `Contact:SpamRetentionDays` (standaard 30) kloppen met de privacyverklaring van de site.
|
||||||
|
- [ ] De opschoon-job (`ContactRetentionService`) draait na de eerste start en logt aantallen, geen inhoud.
|
||||||
|
- [ ] De privacytekst op de website komt overeen met [privacy-gegevens-contactformulier.md](privacy-gegevens-contactformulier.md) (bewaartermijnen, ontvanger, mailkopie).
|
||||||
|
- [ ] Retentie van databaseback-ups: apart besluit van Bryan; staat nog open.
|
||||||
|
|
||||||
|
## 6. Na de release
|
||||||
|
|
||||||
|
- [ ] Rooktest op productie: `scripts/smoke-site.sh <url> sls-test` is bedoeld voor testhosts; voor productie handmatig `/health`, de openbare aanbiedingen, de modulelijst in `/api/v1/System/capabilities` en dat `X-Robots-Tag: noindex` er **niet** meer staat.
|
||||||
|
- [ ] **Sentry nalopen** (nieuwe issues sinds de release, het release-label, de alertregels) en UptimeRobot-monitors.
|
||||||
|
- [ ] Een testbericht via het contactformulier en de binnenkomst in de admin (Berichten) en in de mailbox van de eigenaar, daarna het testbericht verwijderen.
|
||||||
|
- [ ] Controleer in de admin dat banners en pakketten (planning aan/uit, positie) zichtbaar worden in de website.
|
||||||
|
- [ ] Rollback: zie het rollbackplan van de deploy (`aidlc-docs/features/gitea-deployment-workflow/operations/deployment/rollback-plan.md`). Een migratie wordt niet automatisch teruggedraaid.
|
||||||
|
|
||||||
|
## 7. Niet doen zonder nieuwe go van Bryan
|
||||||
|
|
||||||
|
Productie-deploys, variabelen voor productie zetten, `NoIndex` wijzigen, captcha aanzetten, `Contact__Enabled` op productie aanzetten.
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Vertaalbestanden van de backend
|
||||||
|
|
||||||
|
Levend document (2026-11-15). De vaste, voor gebruikers bedoelde teksten van de CMS-host staan niet meer in de C#-code maar in JSON-bestanden per taal. Dit document beschrijft de opzet, de sleutelstijl en hoe je een tekst of taal toevoegt. De beheerteksten van de admin staan in de frontend (`frontend/src/i18n/locales/nl|en/translation.json`) en zijn hier niet bij betrokken.
|
||||||
|
|
||||||
|
## Wat staat erin, wat niet
|
||||||
|
|
||||||
|
| In de bestanden | Blijft in code |
|
||||||
|
|---|---|
|
||||||
|
| Mails: uitnodigingen, wachtwoord resetten, accountwijzigingen, melding van een contactbericht (`core.mail.*`) | CMS-data: pakketten, banners, categorieën, berichten van bezoekers |
|
||||||
|
| De labels voor de gegevens van de bezoeker in de mail aan de eigenaar: Naam, E-mailadres, Onderwerp, Bericht (`contact.mail.label.*`) | |
|
||||||
|
| Meldingen aan de beheerder bij inloggen, uitnodigen en eerste inrichting (`core.identity.*`) | Technische ProblemDetails-titels (`Validation failed`, `Too many requests`, `Service Unavailable`, `Unauthorized`, `Payload too large`, `Invalid category`) |
|
||||||
|
| Beschikbaarheidsmeldingen (`availability.*`) | Foutcodes van het contactformulier (`required`, `too_long`, `invalid`, ...): dat is een contract met de websites |
|
||||||
|
| Validatiemeldingen van pakketten en banners (`offerings.validation.*`) | Interne uitzonderingen (Master), log- en SecurityEvent-teksten |
|
||||||
|
| De pagina als er geen website is geplaatst (`core.host.placeholder.*`) | De HTML-structuur van mails en pagina's (alleen de zinnen gaan naar de bestanden) |
|
||||||
|
| 'Boek {name}' in de gewone lijst die de host in de website schrijft (`offerings.injection.book`) | |
|
||||||
|
| De antwoorden van de wachtwoord- en gebruikersbeheer-endpoints (`core.identity.auth.*`, `core.identity.users.*`) | |
|
||||||
|
|
||||||
|
De golden files van de website (ASF) voor de lijst-HTML blijven leidend: de tekst 'Boek {name}' moet in het Nederlands exact zo blijven.
|
||||||
|
|
||||||
|
## Bestanden en lagen
|
||||||
|
|
||||||
|
- Per project dat teksten heeft: `Texts/nl.json` en `Texts/en.json`, ingebed in de assembly (`<EmbeddedResource Include="Texts\*.json" WithCulture="false" />`). **`WithCulture="false"` is nodig:** zonder die vlag maakt de SDK van bestanden als `X.Texts.en.json` een satellite-assembly en vindt de host ze niet.
|
||||||
|
- Genest JSON; de loader maakt er punt-sleutels van (`{"core":{"mail":{"footer":"..."}}}` is `core.mail.footer`). Opmerkingen en een komma aan het eind mogen.
|
||||||
|
- Plaatshouders heten `{naam}` (letters en cijfers, geen nummers). Waarden worden niet geëscaped door de catalogus: wie HTML schrijft, escaped de waarde zelf vóór het invullen.
|
||||||
|
- Een tekst die de host in HTML zet (placeholder-pagina) mag eenvoudige opmaak bevatten (`<code>`, `<a>`). Die bestanden schrijven wij zelf; er komt nooit bezoekersinvoer in.
|
||||||
|
- Lagen, de eerste die een sleutel kent wint: (1) een optionele database-override (`ITextOverrides`; nog geen implementatie, de catalogus kent de laag al), (2) een map naast de app (`Texts:Directory`) met `nl.json`, `en.json` of `*.nl.json`, zelfde vorm als de ingebedde bestanden, handig om een tekst bij een deploy te wijzigen zonder rebuild, (3) de ingebedde bestanden.
|
||||||
|
- Taal: `Texts:DefaultLanguage` (standaard `nl`). Een mail volgt de taal van de ontvanger (`nl`/`en`), anders de sitetaal. Een onbekende taal valt terug op de standaardtaal, daarna op `nl`, daarna `en`.
|
||||||
|
- Een ontbrekende sleutel breekt een request nooit: de sleutelnaam wordt de tekst en er komt één foutregel in het log (per sleutel en taal één keer). Een kapot override-bestand wordt genegeerd en gelogd.
|
||||||
|
|
||||||
|
## Sleutels in code
|
||||||
|
|
||||||
|
Elke tekst heeft een getypeerde sleutel: `CoreTexts.Mail.Invitation.Subject`, `AvailabilityTexts.Maintenance`, `OfferingsTexts.Validation.Banner.Position`, ... Een sleutel is een `TextKey(pad, plaatshouders...)`; de plaatshouders die erbij staan moeten in elke taal in de tekst staan. Gebruik de catalogus zo:
|
||||||
|
|
||||||
|
```csharp
|
||||||
|
texts.Get(CoreTexts.Mail.Footer, language, ("site", siteName));
|
||||||
|
```
|
||||||
|
|
||||||
|
- Services krijgen `ITextCatalog` (een optionele parameter, zonder waarde gebruikt de code de gedeelde Nederlandse standaardcatalogus `TextCatalog.Default`).
|
||||||
|
- Controllers en middleware: `HttpTexts.From(HttpContext)`.
|
||||||
|
- Validatie (`IValidatableObject`, `ValidationAttribute`): `ValidationContext.GetService(typeof(ITextCatalog))`, in de Offerings-module via `OfferingsTexts.From(context)`.
|
||||||
|
- Een module met eigen teksten registreert zijn assembly: `services.AddCmsTextsFrom(typeof(XModule).Assembly)`.
|
||||||
|
|
||||||
|
Sleutelstijl: kleine letters en camelCase per onderdeel, `module.onderwerp.onderdeel` (`core.mail.passwordReset.note`). De websites gebruiken dezelfde vorm (genest JSON per taal, punt-paden, `{naam}`), zodat later één gedeeld overzicht mogelijk is.
|
||||||
|
|
||||||
|
## Een tekst, sleutel of taal toevoegen
|
||||||
|
|
||||||
|
1. **Nieuwe tekst:** voeg de sleutel toe aan de sleutelklasse van de module (met de plaatshouders), en de tekst aan `nl.json` én `en.json`. Een test (`TextAudit`) faalt als een sleutel in een taal ontbreekt, als de plaatshouders afwijken, of als een bestand een tekst heeft die geen sleutel kent.
|
||||||
|
2. **Nieuwe taal:** een extra bestand `Texts/<taal>.json` per project (bijvoorbeeld `de.json`) met dezelfde sleutels en plaatshouders; voeg de taal toe aan de `Verify`-aanroepen in de tests. Zet `Texts:DefaultLanguage` als de site die taal als standaard moet hebben. Voor mails is de ondersteunde taalset nu nog `nl`/`en` (`MailLanguages`); die uitbreiden is een aparte stap.
|
||||||
|
3. **Een tekst voor één site aanpassen zonder rebuild:** zet `Texts__Directory` naar een map met een `nl.json` met alleen de sleutels die anders moeten zijn.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- `TextAudit.Verify(assembly, TextAudit.KeysOf(typeof(Sleutelklasse)), "nl", "en")` (per project dat teksten heeft): sleutels per taal, plaatshouders, wezen.
|
||||||
|
- Karakteriseringstests: alle mails (7 soorten × nl, en, een onbekende taal × volledig en kaal) zijn vastgelegd in `SlpModularCms.Core.Tests/Golden/mail` en moesten na de verhuizing byte-identiek blijven; de placeholder-pagina is vergeleken met het originele bestand (zonder witruimte-verschillen); de Nederlandse meldingen van Identity en Availability zijn per tekst vastgelegd; de golden files van de website staan in `SlpModularCms.Modules.Offerings.Tests/Golden/host-injection`.
|
||||||
|
- Regenereren van de mail-snapshots met opzet: `UPDATE_GOLDEN=1 dotnet test --filter MailGoldenTests`.
|
||||||
|
|
||||||
|
## Gedragswijzigingen bij de verhuizing
|
||||||
|
|
||||||
|
Twee bewuste wijzigingen, goedgekeurd door Bryan (via de leider): teksten die alleen in het Engels bestonden zijn nu Nederlands bij `Texts:DefaultLanguage=nl`; de Engelse bestandsversie bevat de oude teksten letterlijk.
|
||||||
|
|
||||||
|
1. De validatiemeldingen van pakketten en banners (`offerings.validation.*`, 9 teksten). Beheerders zijn Nederlandstalig en de admin toont de melding letterlijk.
|
||||||
|
2. De Engelse antwoorden van de endpoints voor wachtwoord vergeten/instellen en gebruikersbeheer (`core.identity.auth.invalidEmail`, `resetRequested`, `linkInvalid`, `passwordSet`, `passwordRejected` en `core.identity.users.*`, 13 teksten), zoals 'You cannot delete your own account.' De admin toont voor wachtwoord vergeten zijn eigen tekst (`forgotPassword.sentMessage`) en niet het antwoord van de server, dus er wordt niets dubbel getoond.
|
||||||
|
|
||||||
|
Verder is de uitvoer ongewijzigd; de uitzondering `MasterControlledAvailabilityException` heeft een technische Engelse melding gekregen, de zin voor de beheerder komt uit `availability.masterControlled`.
|
||||||
|
|
||||||
|
## Leesbaar overzicht van de mails
|
||||||
|
|
||||||
|
[mail-teksten.md](mail-teksten.md) toont alle mailteksten per soort in het Nederlands en Engels, plus de tekstversie van een voorbeeldmail. Het bestand wordt gegenereerd met `./scripts/Export-MailTexts.ps1` (niet met de hand wijzigen).
|
||||||
|
|
||||||
|
## Productie
|
||||||
|
|
||||||
|
De bestanden zitten als resource in de assemblies, dus in elke publish, ook de self-contained Windows-publish voor IIS: er is geen aparte map met bestanden om mee te leveren. Een override-map (`Texts:Directory`) is optioneel en staat naast de app.
|
||||||
+1
-1
@@ -8,7 +8,7 @@
|
|||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var s = localStorage.getItem('cms-theme');
|
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);
|
document.documentElement.classList.add(t);
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -22,6 +22,7 @@
|
|||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"@fontsource/archivo": "5.3.0",
|
||||||
"@fontsource/jost": "5.3.0",
|
"@fontsource/jost": "5.3.0",
|
||||||
"@fontsource/marcellus": "5.3.0",
|
"@fontsource/marcellus": "5.3.0",
|
||||||
"@hookform/resolvers": "^5.4.0",
|
"@hookform/resolvers": "^5.4.0",
|
||||||
|
|||||||
Generated
+8
@@ -17,6 +17,9 @@ importers:
|
|||||||
'@dnd-kit/utilities':
|
'@dnd-kit/utilities':
|
||||||
specifier: ^3.2.2
|
specifier: ^3.2.2
|
||||||
version: 3.2.2(react@19.2.7)
|
version: 3.2.2(react@19.2.7)
|
||||||
|
'@fontsource/archivo':
|
||||||
|
specifier: 5.3.0
|
||||||
|
version: 5.3.0
|
||||||
'@fontsource/jost':
|
'@fontsource/jost':
|
||||||
specifier: 5.3.0
|
specifier: 5.3.0
|
||||||
version: 5.3.0
|
version: 5.3.0
|
||||||
@@ -386,6 +389,9 @@ packages:
|
|||||||
'@floating-ui/utils@0.2.11':
|
'@floating-ui/utils@0.2.11':
|
||||||
resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}
|
resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}
|
||||||
|
|
||||||
|
'@fontsource/archivo@5.3.0':
|
||||||
|
resolution: {integrity: sha512-5DIMgPVJRi62OqdOVoogCFxP73EkNM/E0YVTSDIQlDEJfDbxqZduwM/YoNZwC9Sx1CDgpKinqf8ckRY1QNIecw==}
|
||||||
|
|
||||||
'@fontsource/jost@5.3.0':
|
'@fontsource/jost@5.3.0':
|
||||||
resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==}
|
resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==}
|
||||||
|
|
||||||
@@ -2638,6 +2644,8 @@ snapshots:
|
|||||||
|
|
||||||
'@floating-ui/utils@0.2.11': {}
|
'@floating-ui/utils@0.2.11': {}
|
||||||
|
|
||||||
|
'@fontsource/archivo@5.3.0': {}
|
||||||
|
|
||||||
'@fontsource/jost@5.3.0': {}
|
'@fontsource/jost@5.3.0': {}
|
||||||
|
|
||||||
'@fontsource/marcellus@5.3.0': {}
|
'@fontsource/marcellus@5.3.0': {}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Link } from '@tanstack/react-router';
|
import { Link } from '@tanstack/react-router';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { LayoutDashboard, Users, FileText, Package, Settings, X } from 'lucide-react';
|
import { LayoutDashboard, Users, FileText, Package, Mail, Settings, X } from 'lucide-react';
|
||||||
import type { LucideIcon } from 'lucide-react';
|
import type { LucideIcon } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useAuth } from '@/features/auth/context/auth-context';
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
import { useAvailabilityStatus } from '@/features/availability/services/useAvailability';
|
import { useAvailabilityStatus } from '@/features/availability/services/useAvailability';
|
||||||
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||||
|
import { useContactSettings } from '@/features/contact/services/useContactSettings';
|
||||||
import { LanguageSwitcher } from '@/i18n/LanguageSwitcher';
|
import { LanguageSwitcher } from '@/i18n/LanguageSwitcher';
|
||||||
import { BrandLogo } from './BrandLogo';
|
import { BrandLogo } from './BrandLogo';
|
||||||
import { ThemeToggle } from './ThemeToggle';
|
import { ThemeToggle } from './ThemeToggle';
|
||||||
@@ -36,6 +37,14 @@ const NAV_ITEMS: NavItem[] = [
|
|||||||
roles: ['Owner', 'Administrator'],
|
roles: ['Owner', 'Administrator'],
|
||||||
requiredModule: 'Offerings',
|
requiredModule: 'Offerings',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
to: '/messages',
|
||||||
|
labelKey: 'nav.messages',
|
||||||
|
icon: Mail,
|
||||||
|
testId: 'nav-messages',
|
||||||
|
roles: ['Owner', 'Administrator'],
|
||||||
|
requiredModule: 'Contact',
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const SETTINGS_ITEM: NavItem = {
|
const SETTINGS_ITEM: NavItem = {
|
||||||
@@ -53,11 +62,16 @@ export function Sidebar({ onClose }: SidebarProps = {}) {
|
|||||||
const { data: capabilities } = useSystemCapabilities();
|
const { data: capabilities } = useSystemCapabilities();
|
||||||
|
|
||||||
const role = user?.role as Role | undefined;
|
const role = user?.role as Role | undefined;
|
||||||
|
// The Berichten entry also needs the management API to exist on this host (a loaded module is not enough:
|
||||||
|
// while the host switch is off its routes answer 404). Only asked for roles that may see the entry.
|
||||||
|
const mayManageContact = (role === 'Owner' || role === 'Administrator') && !!capabilities?.modules.includes('Contact');
|
||||||
|
const { data: contactSettings } = useContactSettings({ enabled: mayManageContact });
|
||||||
const systemUnavailable = availability?.status === 'NotAvailable';
|
const systemUnavailable = availability?.status === 'NotAvailable';
|
||||||
const visibleItems = NAV_ITEMS.filter(
|
const visibleItems = NAV_ITEMS.filter(
|
||||||
(item) =>
|
(item) =>
|
||||||
(!item.roles || (role && item.roles.includes(role))) &&
|
(!item.roles || (role && item.roles.includes(role))) &&
|
||||||
(!item.requiredModule || capabilities?.modules.includes(item.requiredModule))
|
(!item.requiredModule || capabilities?.modules.includes(item.requiredModule)) &&
|
||||||
|
(item.requiredModule !== 'Contact' || !!contactSettings)
|
||||||
);
|
);
|
||||||
const showSettings = !SETTINGS_ITEM.roles || (role && SETTINGS_ITEM.roles.includes(role));
|
const showSettings = !SETTINGS_ITEM.roles || (role && SETTINGS_ITEM.roles.includes(role));
|
||||||
|
|
||||||
|
|||||||
@@ -10,5 +10,12 @@ export const availabilityHandlers = [
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
|
|
||||||
http.post('*/Availability/admin/status', () => new HttpResponse(null, { status: 200 })),
|
http.put('*/Availability/status', () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
status: 'Available',
|
||||||
|
checkedAt: new Date().toISOString(),
|
||||||
|
message: '',
|
||||||
|
isMasterControlled: false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -17,8 +17,12 @@ export function useAvailabilityStatus() {
|
|||||||
|
|
||||||
export function useUpdateAvailability() {
|
export function useUpdateAvailability() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation<void, Error, UpdateAvailabilityPayload>({
|
return useMutation<AvailabilityResponse, Error, UpdateAvailabilityPayload>({
|
||||||
mutationFn: (data) => api.post<void>('/api/v1/Availability/admin/status', data),
|
mutationFn: (data) => api.put<AvailabilityResponse>('/api/v1/Availability/status', data),
|
||||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['availability', 'status'] }),
|
onSuccess: (updated) => {
|
||||||
|
// The PUT answers with the updated resource (same shape as the GET): use it at once.
|
||||||
|
queryClient.setQueryData(['availability', 'status'], updated);
|
||||||
|
return queryClient.invalidateQueries({ queryKey: ['availability', 'status'] });
|
||||||
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { NotFoundPage } from '@/pages/NotFoundPage';
|
||||||
|
import { useContactSettings } from '../services/useContactSettings';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The module can be loaded while the management routes are closed (host switch off: every route answers 404 with an
|
||||||
|
* empty body). In that case the screen does not exist: the usual "not found" page is shown.
|
||||||
|
*/
|
||||||
|
export function ContactAvailabilityGuard({ children }: { children: ReactNode }) {
|
||||||
|
const { data, isPending, isError } = useContactSettings();
|
||||||
|
|
||||||
|
if (isPending) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
|
||||||
|
<span className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || data === null) return <NotFoundPage />;
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { useRef, type KeyboardEvent, type ReactNode } from 'react';
|
||||||
|
|
||||||
|
export interface ContactTab<T extends string> {
|
||||||
|
id: T;
|
||||||
|
label: string;
|
||||||
|
panel: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props<T extends string> {
|
||||||
|
tabs: ContactTab<T>[];
|
||||||
|
value: T;
|
||||||
|
onChange: (id: T) => void;
|
||||||
|
'aria-label': string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Accessible tabs (WAI-ARIA tabs pattern, automatic activation): role=tablist/tab/tabpanel, roving tabindex,
|
||||||
|
* Left/Right/Home/End move and select. Only the selected panel is rendered.
|
||||||
|
*/
|
||||||
|
export function ContactTabs<T extends string>({ tabs, value, onChange, ...rest }: Props<T>) {
|
||||||
|
const refs = useRef<Record<string, HTMLButtonElement | null>>({});
|
||||||
|
const index = tabs.findIndex((tab) => tab.id === value);
|
||||||
|
|
||||||
|
const move = (to: number) => {
|
||||||
|
const next = tabs[(to + tabs.length) % tabs.length];
|
||||||
|
onChange(next.id);
|
||||||
|
refs.current[next.id]?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKeyDown = (event: KeyboardEvent) => {
|
||||||
|
switch (event.key) {
|
||||||
|
case 'ArrowRight':
|
||||||
|
event.preventDefault();
|
||||||
|
move(index + 1);
|
||||||
|
break;
|
||||||
|
case 'ArrowLeft':
|
||||||
|
event.preventDefault();
|
||||||
|
move(index - 1);
|
||||||
|
break;
|
||||||
|
case 'Home':
|
||||||
|
event.preventDefault();
|
||||||
|
move(0);
|
||||||
|
break;
|
||||||
|
case 'End':
|
||||||
|
event.preventDefault();
|
||||||
|
move(tabs.length - 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div
|
||||||
|
role="tablist"
|
||||||
|
aria-label={rest['aria-label']}
|
||||||
|
className="flex gap-1 border-b"
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
>
|
||||||
|
{tabs.map((tab) => {
|
||||||
|
const selected = tab.id === value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
ref={(el) => {
|
||||||
|
refs.current[tab.id] = el;
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
id={`contact-tab-${tab.id}`}
|
||||||
|
aria-selected={selected}
|
||||||
|
aria-controls={`contact-panel-${tab.id}`}
|
||||||
|
tabIndex={selected ? 0 : -1}
|
||||||
|
onClick={() => onChange(tab.id)}
|
||||||
|
data-testid={`contact-tab-${tab.id}`}
|
||||||
|
className={`-mb-px min-h-11 border-b-2 px-4 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${
|
||||||
|
selected
|
||||||
|
? 'border-primary text-foreground'
|
||||||
|
: 'border-transparent text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{tabs.map(
|
||||||
|
(tab) =>
|
||||||
|
tab.id === value && (
|
||||||
|
<div
|
||||||
|
key={tab.id}
|
||||||
|
role="tabpanel"
|
||||||
|
id={`contact-panel-${tab.id}`}
|
||||||
|
aria-labelledby={`contact-tab-${tab.id}`}
|
||||||
|
tabIndex={0}
|
||||||
|
className="space-y-4 focus-visible:outline-none"
|
||||||
|
data-testid={`contact-panel-${tab.id}`}
|
||||||
|
>
|
||||||
|
{tab.panel}
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
isDeleting: boolean;
|
||||||
|
error: string | null;
|
||||||
|
onConfirm: () => void;
|
||||||
|
onCancel: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function DeleteMessageDialog({ open, isDeleting, error, onConfirm, onCancel }: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!next) onCancel();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t('contact.deleteDialog.title')}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<p className="text-sm text-muted-foreground">{t('contact.deleteDialog.message')}</p>
|
||||||
|
{error && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={onCancel}
|
||||||
|
data-testid="delete-message-cancel"
|
||||||
|
>
|
||||||
|
{t('common.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={isDeleting}
|
||||||
|
onClick={onConfirm}
|
||||||
|
data-testid="delete-message-confirm"
|
||||||
|
>
|
||||||
|
{isDeleting ? '…' : t('contact.deleteDialog.confirm')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { useContactSettings, useUpdateContactSettings } from '../services/useContactSettings';
|
||||||
|
import { contactErrorMessage } from '../errors';
|
||||||
|
import { ToggleSwitch } from './ToggleSwitch';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form switch in the page header, level with the title: the switch with its visible state (On/Off) and a short
|
||||||
|
* accessible name/tooltip. The state shown is the server's. Explanations live in the Settings tab (FormSwitchCard).
|
||||||
|
*/
|
||||||
|
export function FormSwitchHeader() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: settings } = useContactSettings();
|
||||||
|
const update = useUpdateContactSettings();
|
||||||
|
|
||||||
|
if (!settings) return null;
|
||||||
|
|
||||||
|
const open = settings.enabled;
|
||||||
|
const toggle = (next: boolean) =>
|
||||||
|
update.mutate(next, {
|
||||||
|
onSuccess: (saved) =>
|
||||||
|
toast.success(
|
||||||
|
saved.enabled ? t('contact.switch.nowOn') : t('contact.switch.nowOff'),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-end gap-1">
|
||||||
|
{settings.hostEnabled ? (
|
||||||
|
<ToggleSwitch
|
||||||
|
checked={open}
|
||||||
|
onCheckedChange={toggle}
|
||||||
|
label={t('contact.switch.shortLabel')}
|
||||||
|
title={t('contact.switch.shortLabel')}
|
||||||
|
stateText={open ? t('contact.switch.on') : t('contact.switch.off')}
|
||||||
|
disabled={update.isPending}
|
||||||
|
data-testid="contact-switch-toggle"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground" data-testid="contact-switch-host-off">
|
||||||
|
{t('contact.switch.hostOff')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{update.isError && (
|
||||||
|
<p
|
||||||
|
role="alert"
|
||||||
|
className="text-sm text-destructive"
|
||||||
|
data-testid="contact-switch-error"
|
||||||
|
>
|
||||||
|
{contactErrorMessage(update.error, t)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the switch means (state, explanation, hints), at the top of the Settings tab. */
|
||||||
|
export function FormSwitchCard() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: settings } = useContactSettings();
|
||||||
|
|
||||||
|
if (!settings) return null;
|
||||||
|
|
||||||
|
const open = settings.enabled;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card data-testid="contact-switch-card">
|
||||||
|
<CardContent className="space-y-3 p-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="font-semibold">{t('contact.switch.title')}</h2>
|
||||||
|
<p className="text-sm" data-testid="contact-switch-state">
|
||||||
|
{open ? t('contact.switch.stateOn') : t('contact.switch.stateOff')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">{t('contact.switch.explanation')}</p>
|
||||||
|
{settings.recipientSource === 'none' && (
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
className="rounded-md border border-amber-500/50 bg-amber-500/10 p-2 text-sm"
|
||||||
|
data-testid="contact-no-recipient-banner"
|
||||||
|
>
|
||||||
|
{t('contact.switch.noRecipientBanner')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!open && settings.hostEnabled && (
|
||||||
|
<p className="text-sm text-muted-foreground" data-testid="contact-switch-hint">
|
||||||
|
{t('contact.switch.firstTimeHint')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||||
|
import {
|
||||||
|
useContactMessage,
|
||||||
|
useResendContactMessage,
|
||||||
|
useUpdateContactMessageStatus,
|
||||||
|
} from '../services/useContactMessages';
|
||||||
|
import { StatusIcon } from './StatusIcon';
|
||||||
|
import { contactErrorMessage, mailErrorLabel } from '../errors';
|
||||||
|
import { MailStatusIcon } from './MessagesTable';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
id: string | null;
|
||||||
|
onClose: () => void;
|
||||||
|
onDeleteRequested: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MessageDialog({ id, onClose, onDeleteRequested }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const { data: message, isPending, isError } = useContactMessage(id);
|
||||||
|
const { data: capabilities } = useSystemCapabilities();
|
||||||
|
const setStatus = useUpdateContactMessageStatus();
|
||||||
|
const resend = useResendContactMessage();
|
||||||
|
const [resendNote, setResendNote] = useState<string | null>(null);
|
||||||
|
const markedRead = useRef<string | null>(null);
|
||||||
|
|
||||||
|
// Opening an unread message marks it as read, once per message.
|
||||||
|
useEffect(() => {
|
||||||
|
if (message && message.status === 'new' && markedRead.current !== message.id) {
|
||||||
|
markedRead.current = message.id;
|
||||||
|
setStatus.mutate({ id: message.id, status: 'read' });
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [message?.id, message?.status]);
|
||||||
|
|
||||||
|
const format = new Intl.DateTimeFormat(i18n.language, {
|
||||||
|
dateStyle: 'medium',
|
||||||
|
timeStyle: 'short',
|
||||||
|
});
|
||||||
|
const emailEnabled = capabilities?.emailEnabled ?? false;
|
||||||
|
const isSpam = message?.status === 'spam';
|
||||||
|
|
||||||
|
const doResend = () => {
|
||||||
|
if (!message) return;
|
||||||
|
setResendNote(null);
|
||||||
|
resend.mutate(message.id, {
|
||||||
|
onSuccess: (result) =>
|
||||||
|
setResendNote(
|
||||||
|
result.mailed ? t('contact.resend.sent') : t('contact.resend.notSent'),
|
||||||
|
),
|
||||||
|
onError: (error) => setResendNote(contactErrorMessage(error, t)),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const errorLabel = mailErrorLabel(message?.mailError, t);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog
|
||||||
|
open={id !== null}
|
||||||
|
onOpenChange={(open) => {
|
||||||
|
if (!open) onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogContent className="sm:max-w-xl" data-testid="contact-message-dialog">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{message ? message.subject : t('contact.detail.title')}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>{t('contact.detail.title')}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{isPending && (
|
||||||
|
<p className="text-sm text-muted-foreground">{t('common.loading')}</p>
|
||||||
|
)}
|
||||||
|
{isError && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{t('errors.generic')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-sm">
|
||||||
|
<dt className="text-muted-foreground">{t('contact.table.name')}</dt>
|
||||||
|
<dd>{message.name}</dd>
|
||||||
|
<dt className="text-muted-foreground">{t('contact.table.email')}</dt>
|
||||||
|
<dd>
|
||||||
|
<a
|
||||||
|
className="text-primary underline-offset-4 hover:underline"
|
||||||
|
href={`mailto:${message.email}`}
|
||||||
|
>
|
||||||
|
{message.email}
|
||||||
|
</a>
|
||||||
|
</dd>
|
||||||
|
<dt className="text-muted-foreground">{t('contact.table.received')}</dt>
|
||||||
|
<dd>{format.format(new Date(message.receivedAt))}</dd>
|
||||||
|
<dt className="text-muted-foreground">
|
||||||
|
{t('contact.detail.retention')}
|
||||||
|
</dt>
|
||||||
|
<dd>{format.format(new Date(message.retentionUntil))}</dd>
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{t('contact.table.status')}
|
||||||
|
</span>
|
||||||
|
<StatusIcon status={message.status} />
|
||||||
|
{isSpam && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={setStatus.isPending}
|
||||||
|
onClick={() =>
|
||||||
|
setStatus.mutate(
|
||||||
|
{ id: message.id, status: 'read' },
|
||||||
|
{ onSuccess: onClose },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
data-testid="contact-not-spam"
|
||||||
|
>
|
||||||
|
{t('contact.detail.notSpam')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{message.status === 'read' && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={setStatus.isPending}
|
||||||
|
onClick={() =>
|
||||||
|
setStatus.mutate(
|
||||||
|
{ id: message.id, status: 'new' },
|
||||||
|
{ onSuccess: onClose },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
data-testid="contact-mark-unread-button"
|
||||||
|
>
|
||||||
|
{t('contact.detail.markUnread')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{(message.status === 'new' || message.status === 'read') && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={setStatus.isPending}
|
||||||
|
onClick={() =>
|
||||||
|
setStatus.mutate({ id: message.id, status: 'archived' })
|
||||||
|
}
|
||||||
|
data-testid="contact-archive-button"
|
||||||
|
>
|
||||||
|
{t('contact.detail.archive')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{message.status === 'archived' && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
disabled={setStatus.isPending}
|
||||||
|
onClick={() =>
|
||||||
|
setStatus.mutate({ id: message.id, status: 'read' })
|
||||||
|
}
|
||||||
|
data-testid="contact-restore-button"
|
||||||
|
>
|
||||||
|
{t('contact.detail.restore')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{setStatus.isError && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{contactErrorMessage(setStatus.error, t)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p
|
||||||
|
className="max-h-60 overflow-y-auto whitespace-pre-wrap break-words rounded-md border bg-muted/30 p-3 text-sm"
|
||||||
|
data-testid="contact-message-body"
|
||||||
|
>
|
||||||
|
{message.message}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{!isSpam && (
|
||||||
|
<div
|
||||||
|
className="space-y-1 rounded-md border p-3 text-sm"
|
||||||
|
data-testid="contact-mail-info"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<MailStatusIcon status={message.mailStatus} />
|
||||||
|
<span>{t(`contact.mailStatus.${message.mailStatus}`)}</span>
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{t('contact.detail.attempts', {
|
||||||
|
count: message.mailAttempts,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{errorLabel && <p data-testid="contact-mail-error">{errorLabel}</p>}
|
||||||
|
{message.nextMailAttemptAt && message.mailStatus !== 'sent' && (
|
||||||
|
<p
|
||||||
|
className="text-muted-foreground"
|
||||||
|
data-testid="contact-next-attempt"
|
||||||
|
>
|
||||||
|
{t('contact.detail.nextAttempt', {
|
||||||
|
time: format.format(
|
||||||
|
new Date(message.nextMailAttemptAt),
|
||||||
|
),
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{resendNote && (
|
||||||
|
<p role="status" className="text-sm" data-testid="contact-resend-note">
|
||||||
|
{resendNote}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap justify-between gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
onClick={() => onDeleteRequested(message.id)}
|
||||||
|
data-testid="contact-delete-button"
|
||||||
|
>
|
||||||
|
{t('contact.detail.delete')}
|
||||||
|
</Button>
|
||||||
|
{!isSpam && (
|
||||||
|
<div className="flex flex-col items-end gap-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={!emailEnabled || resend.isPending}
|
||||||
|
onClick={doResend}
|
||||||
|
data-testid="contact-resend-button"
|
||||||
|
>
|
||||||
|
{t('contact.detail.resend')}
|
||||||
|
</Button>
|
||||||
|
{!emailEnabled && (
|
||||||
|
<span
|
||||||
|
className="text-xs text-muted-foreground"
|
||||||
|
data-testid="contact-resend-hint"
|
||||||
|
>
|
||||||
|
{t('contact.resend.mailOff')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import type { ContactFilter } from '../services/types';
|
||||||
|
|
||||||
|
const FILTERS: ContactFilter[] = ['inbox', 'new', 'read', 'archived', 'spam'];
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
value: ContactFilter;
|
||||||
|
unreadCount: number | undefined;
|
||||||
|
onChange: (filter: ContactFilter) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MessagesFilterChips({ value, unreadCount, onChange }: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div role="group" aria-label={t('contact.filter.label')} className="flex flex-wrap gap-2">
|
||||||
|
{FILTERS.map((filter) => {
|
||||||
|
const active = filter === value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={filter}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={active}
|
||||||
|
data-testid={`contact-filter-${filter}`}
|
||||||
|
onClick={() => onChange(filter)}
|
||||||
|
className={cn(
|
||||||
|
'rounded-full border px-3 py-1 text-sm transition-colors',
|
||||||
|
active
|
||||||
|
? 'border-primary bg-primary text-primary-foreground'
|
||||||
|
: 'hover:bg-accent',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{t(`contact.filter.${filter}`)}
|
||||||
|
{filter === 'new' && unreadCount !== undefined && (
|
||||||
|
<span
|
||||||
|
className="ml-1.5 font-semibold"
|
||||||
|
data-testid="contact-unread-count"
|
||||||
|
>
|
||||||
|
({unreadCount})
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { CheckCircle2, Clock, MinusCircle, XCircle } from 'lucide-react';
|
||||||
|
import { StatusIcon } from './StatusIcon';
|
||||||
|
import type { ContactMailStatus, ContactMessageListItem } from '../services/types';
|
||||||
|
|
||||||
|
export function MailStatusIcon({ status }: { status: ContactMailStatus }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const common = {
|
||||||
|
'aria-label': t(`contact.mailStatus.${status}`),
|
||||||
|
role: 'img',
|
||||||
|
'data-testid': `mail-status-${status}`,
|
||||||
|
};
|
||||||
|
switch (status) {
|
||||||
|
case 'sent':
|
||||||
|
return <CheckCircle2 {...common} className="size-4 text-green-600" />;
|
||||||
|
case 'failed':
|
||||||
|
return <XCircle {...common} className="size-4 text-destructive" />;
|
||||||
|
case 'pending':
|
||||||
|
return <Clock {...common} className="size-4 text-amber-600" />;
|
||||||
|
default:
|
||||||
|
return <MinusCircle {...common} className="size-4 text-muted-foreground" />;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
items: ContactMessageListItem[];
|
||||||
|
onOpen: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MessagesTable({ items, onOpen }: Props) {
|
||||||
|
const { t, i18n } = useTranslation();
|
||||||
|
const format = new Intl.DateTimeFormat(i18n.language, {
|
||||||
|
dateStyle: 'short',
|
||||||
|
timeStyle: 'short',
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="overflow-x-auto rounded-md border">
|
||||||
|
<table className="w-full text-sm" data-testid="contact-messages-table">
|
||||||
|
<thead className="bg-muted/50 text-left">
|
||||||
|
<tr>
|
||||||
|
<th className="p-2">{t('contact.table.received')}</th>
|
||||||
|
<th className="p-2">{t('contact.table.name')}</th>
|
||||||
|
<th className="p-2">{t('contact.table.email')}</th>
|
||||||
|
<th className="p-2">{t('contact.table.subject')}</th>
|
||||||
|
<th className="p-2">{t('contact.table.status')}</th>
|
||||||
|
<th className="p-2">{t('contact.table.mail')}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{items.map((m) => (
|
||||||
|
<tr
|
||||||
|
key={m.id}
|
||||||
|
data-testid={`contact-row-${m.id}`}
|
||||||
|
// The whole row opens the message; the name stays a real button for keyboard and screen readers.
|
||||||
|
onClick={() => onOpen(m.id)}
|
||||||
|
className={`cursor-pointer hover:bg-muted/50 ${
|
||||||
|
m.status === 'spam'
|
||||||
|
? 'bg-destructive/5'
|
||||||
|
: m.status === 'new'
|
||||||
|
? 'font-semibold'
|
||||||
|
: ''
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<td className="p-2 whitespace-nowrap">
|
||||||
|
{format.format(new Date(m.receivedAt))}
|
||||||
|
</td>
|
||||||
|
<td className="p-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-left text-primary underline-offset-4 hover:underline"
|
||||||
|
onClick={() => onOpen(m.id)}
|
||||||
|
data-testid={`contact-open-${m.id}`}
|
||||||
|
>
|
||||||
|
{m.status === 'new' && (
|
||||||
|
<span
|
||||||
|
className="mr-2 inline-block size-2.5 rounded-full bg-primary align-middle"
|
||||||
|
data-testid={`contact-unread-dot-${m.id}`}
|
||||||
|
role="img"
|
||||||
|
aria-label={t('contact.unread.label')}
|
||||||
|
title={t('contact.unread.label')}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{m.name}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
<td className="p-2">{m.email}</td>
|
||||||
|
<td className="p-2">{m.subject}</td>
|
||||||
|
<td className="p-2">
|
||||||
|
<StatusIcon status={m.status} />
|
||||||
|
</td>
|
||||||
|
<td className="p-2">
|
||||||
|
<MailStatusIcon status={m.mailStatus} />
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { Link } from '@tanstack/react-router';
|
||||||
|
import { Mail } from 'lucide-react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
|
import { useSystemCapabilities } from '@/features/system/services/useSystemCapabilities';
|
||||||
|
import { useContactSettings } from '../services/useContactSettings';
|
||||||
|
import { useUnreadContactCount } from '../services/useContactMessages';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dashboard tile for the Berichten: the number of unread messages, linking to the list. Shown only where the
|
||||||
|
* Berichten entry of the sidebar is shown (module loaded, management API answering, role may manage it).
|
||||||
|
*/
|
||||||
|
export function MessagesTile() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { data: capabilities } = useSystemCapabilities();
|
||||||
|
const mayManage =
|
||||||
|
(user?.role === 'Owner' || user?.role === 'Administrator') &&
|
||||||
|
!!capabilities?.modules.includes('Contact');
|
||||||
|
const { data: settings } = useContactSettings({ enabled: mayManage });
|
||||||
|
const available = mayManage && !!settings;
|
||||||
|
const { data: unread, isError } = useUnreadContactCount(available);
|
||||||
|
|
||||||
|
if (!available) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link to="/messages" className="block h-full" data-testid="messages-tile">
|
||||||
|
<Card className="h-full transition-colors hover:bg-accent/50">
|
||||||
|
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||||
|
<CardTitle>{t('contact.title')}</CardTitle>
|
||||||
|
<Mail className="size-5 text-muted-foreground" aria-hidden="true" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
{isError ? (
|
||||||
|
<p className="text-sm text-muted-foreground" data-testid="messages-tile-error">
|
||||||
|
{t('contact.tile.error')}
|
||||||
|
</p>
|
||||||
|
) : unread === undefined ? (
|
||||||
|
<div className="h-8 w-16 animate-pulse rounded bg-muted" />
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-3xl font-semibold" data-testid="messages-tile-count">
|
||||||
|
{unread}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{t('contact.tile.unread', { count: unread })}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { useState, type FormEvent } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { ProblemDetailsError } from '@/lib/api-client';
|
||||||
|
import { useContactSettings, useUpdateContactRecipient } from '../services/useContactSettings';
|
||||||
|
import { contactErrorMessage } from '../errors';
|
||||||
|
|
||||||
|
// Same shape the server accepts: something@domain.tld, no spaces. The server decides; this only saves a round trip.
|
||||||
|
const LOOKS_LIKE_AN_ADDRESS = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||||
|
|
||||||
|
function RecipientForm({ saved }: { saved: string }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: settings } = useContactSettings();
|
||||||
|
const update = useUpdateContactRecipient();
|
||||||
|
const [draft, setDraft] = useState(saved);
|
||||||
|
const [touched, setTouched] = useState(false);
|
||||||
|
|
||||||
|
const trimmed = draft.trim();
|
||||||
|
const clientInvalid = trimmed.length > 0 && !LOOKS_LIKE_AN_ADDRESS.test(trimmed);
|
||||||
|
const canSave = trimmed.length > 0 && !clientInvalid && trimmed !== saved && !update.isPending;
|
||||||
|
const source = settings?.recipientSource ?? 'none';
|
||||||
|
|
||||||
|
const save = (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setTouched(true);
|
||||||
|
if (!canSave) return;
|
||||||
|
update.mutate(trimmed, { onSuccess: () => toast.success(t('contact.recipient.saved')) });
|
||||||
|
};
|
||||||
|
|
||||||
|
const reset = () =>
|
||||||
|
update.mutate(null, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setDraft('');
|
||||||
|
toast.success(t('contact.recipient.cleared'));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const serverMessage = update.isError
|
||||||
|
? update.error instanceof ProblemDetailsError && update.error.status === 400
|
||||||
|
? t('contact.recipient.invalid')
|
||||||
|
: contactErrorMessage(update.error, t)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={save} noValidate className="space-y-3" data-testid="contact-recipient-form">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label htmlFor="contact-recipient-input" className="text-sm font-medium">
|
||||||
|
{t('contact.recipient.label')}
|
||||||
|
</label>
|
||||||
|
<Input
|
||||||
|
id="contact-recipient-input"
|
||||||
|
type="email"
|
||||||
|
inputMode="email"
|
||||||
|
autoComplete="off"
|
||||||
|
value={draft}
|
||||||
|
placeholder={t('contact.recipient.placeholder')}
|
||||||
|
aria-invalid={touched && clientInvalid}
|
||||||
|
aria-describedby="contact-recipient-source"
|
||||||
|
onChange={(e) => {
|
||||||
|
setDraft(e.target.value);
|
||||||
|
setTouched(false);
|
||||||
|
update.reset();
|
||||||
|
}}
|
||||||
|
data-testid="contact-recipient-input"
|
||||||
|
/>
|
||||||
|
{touched && clientInvalid && (
|
||||||
|
<p
|
||||||
|
role="alert"
|
||||||
|
className="text-sm text-destructive"
|
||||||
|
data-testid="contact-recipient-invalid"
|
||||||
|
>
|
||||||
|
{t('contact.recipient.invalid')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p
|
||||||
|
id="contact-recipient-source"
|
||||||
|
className="text-sm text-muted-foreground"
|
||||||
|
data-testid="contact-recipient-source"
|
||||||
|
>
|
||||||
|
{t(`contact.recipient.source.${source}`)}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{serverMessage && (
|
||||||
|
<p
|
||||||
|
role="alert"
|
||||||
|
className="text-sm text-destructive"
|
||||||
|
data-testid="contact-recipient-error"
|
||||||
|
>
|
||||||
|
{serverMessage}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
className="min-h-11"
|
||||||
|
disabled={update.isPending || trimmed.length === 0 || trimmed === saved}
|
||||||
|
data-testid="contact-recipient-save"
|
||||||
|
>
|
||||||
|
{t('contact.recipient.save')}
|
||||||
|
</Button>
|
||||||
|
{saved && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="min-h-11"
|
||||||
|
disabled={update.isPending}
|
||||||
|
onClick={reset}
|
||||||
|
data-testid="contact-recipient-reset"
|
||||||
|
>
|
||||||
|
{t('contact.recipient.reset')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The address contact messages are mailed to: the site setting, with the server configuration as the default. */
|
||||||
|
export function RecipientCard() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: settings } = useContactSettings();
|
||||||
|
|
||||||
|
if (!settings) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card data-testid="contact-recipient-card">
|
||||||
|
<CardContent className="space-y-3 p-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="font-semibold">{t('contact.recipient.title')}</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{t('contact.recipient.description')}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{/* Keyed by the saved value, so the field follows what the server answered. */}
|
||||||
|
<RecipientForm
|
||||||
|
key={settings.recipientEmail ?? ''}
|
||||||
|
saved={settings.recipientEmail ?? ''}
|
||||||
|
/>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Archive, Mail, MailOpen, ShieldAlert, type LucideIcon } from 'lucide-react';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import type { ContactStatus } from '../services/types';
|
||||||
|
|
||||||
|
const ICONS: Record<ContactStatus, LucideIcon> = {
|
||||||
|
new: Mail,
|
||||||
|
read: MailOpen,
|
||||||
|
archived: Archive,
|
||||||
|
spam: ShieldAlert,
|
||||||
|
// Not produced by the management screen (kept for completeness of the API's status set).
|
||||||
|
converted: MailOpen,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The status of a message as an icon plus its name as visible text (never colour alone): closed envelope = new,
|
||||||
|
* open envelope = read, archive box = archived, shield = spam. The same component is used in the list and the detail.
|
||||||
|
*/
|
||||||
|
export function StatusIcon({ status }: { status: ContactStatus }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const Icon = ICONS[status];
|
||||||
|
const label = t(`contact.status.${status}`);
|
||||||
|
return (
|
||||||
|
<Badge
|
||||||
|
variant={status === 'spam' ? 'destructive' : status === 'new' ? 'default' : 'secondary'}
|
||||||
|
className="gap-1.5"
|
||||||
|
title={label}
|
||||||
|
data-testid={`status-icon-${status}`}
|
||||||
|
>
|
||||||
|
<Icon className="size-3.5" aria-hidden="true" />
|
||||||
|
<span>{label}</span>
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface ToggleSwitchProps {
|
||||||
|
checked: boolean;
|
||||||
|
onCheckedChange: (checked: boolean) => void;
|
||||||
|
/** The visible label; it is also the accessible name of the switch. */
|
||||||
|
label: string;
|
||||||
|
/** Optional tooltip (native title). */
|
||||||
|
title?: string;
|
||||||
|
/** The state as text ("On"/"Off"), so the state is never conveyed by colour or position alone. */
|
||||||
|
stateText: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
'data-testid'?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A toggle switch: a native button with role="switch" (Space and Enter work out of the box), a 44px touch target,
|
||||||
|
* the label and the state as visible text.
|
||||||
|
*/
|
||||||
|
export function ToggleSwitch({
|
||||||
|
checked,
|
||||||
|
onCheckedChange,
|
||||||
|
label,
|
||||||
|
title,
|
||||||
|
stateText,
|
||||||
|
disabled = false,
|
||||||
|
'data-testid': testId,
|
||||||
|
}: ToggleSwitchProps) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={checked}
|
||||||
|
aria-label={label}
|
||||||
|
title={title}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onCheckedChange(!checked)}
|
||||||
|
data-testid={testId}
|
||||||
|
className="inline-flex min-h-11 min-w-11 items-center gap-3 rounded-md px-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className={cn(
|
||||||
|
'relative inline-flex h-7 w-12 shrink-0 items-center rounded-full border transition-colors',
|
||||||
|
checked ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
'inline-block size-5 rounded-full bg-background shadow transition-transform',
|
||||||
|
checked ? 'translate-x-6' : 'translate-x-1',
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
<span className="text-sm font-medium" data-testid="toggle-switch-state">
|
||||||
|
{stateText}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import type { TFunction } from 'i18next';
|
||||||
|
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||||
|
|
||||||
|
/** Maps any failure to a translated text; the API's own (English) titles are never shown. */
|
||||||
|
export function contactErrorMessage(error: unknown, t: TFunction): string {
|
||||||
|
if (error instanceof NetworkError) return t('errors.network');
|
||||||
|
if (error instanceof ProblemDetailsError) {
|
||||||
|
if (error.status === 429) {
|
||||||
|
const seconds = Math.max(1, Math.ceil((error.retryAfterMs ?? 60000) / 1000));
|
||||||
|
return t('contact.errors.rateLimited', { seconds });
|
||||||
|
}
|
||||||
|
if (error.status === 409) return t('contact.errors.spamResend');
|
||||||
|
if (error.status === 404) return t('contact.errors.notFound');
|
||||||
|
}
|
||||||
|
return t('errors.generic');
|
||||||
|
}
|
||||||
|
|
||||||
|
const KNOWN_MAIL_ERRORS = [
|
||||||
|
'disabled',
|
||||||
|
'recipient_not_configured',
|
||||||
|
'not_configured',
|
||||||
|
'timeout',
|
||||||
|
'timeout_connect',
|
||||||
|
'timeout_auth',
|
||||||
|
'timeout_send',
|
||||||
|
'auth_failed',
|
||||||
|
'rejected',
|
||||||
|
'rejected_sender',
|
||||||
|
'rejected_recipient',
|
||||||
|
'tls_failed',
|
||||||
|
'connection_failed',
|
||||||
|
'unknown',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Short mail error codes (from the mail sender) to translated reasons; unknown codes fall back to a generic text. */
|
||||||
|
export function mailErrorLabel(code: string | null | undefined, t: TFunction): string | null {
|
||||||
|
if (!code) return null;
|
||||||
|
return KNOWN_MAIL_ERRORS.includes(code)
|
||||||
|
? t(`contact.mailError.${code}`)
|
||||||
|
: t('contact.mailError.unknown');
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import { http, HttpResponse } from 'msw';
|
||||||
|
import type {
|
||||||
|
ContactMessageDetail,
|
||||||
|
ContactMessageListItem,
|
||||||
|
ContactSettings,
|
||||||
|
ContactStatus,
|
||||||
|
} from '@/features/contact/services/types';
|
||||||
|
|
||||||
|
const BASE = '*/api/v1/contact-messages';
|
||||||
|
const SETTINGS = '*/api/v1/contact-settings';
|
||||||
|
|
||||||
|
export const MSG_NEW = '11111111-1111-1111-1111-111111111111';
|
||||||
|
export const MSG_READ = '22222222-2222-2222-2222-222222222222';
|
||||||
|
export const MSG_SPAM = '33333333-3333-3333-3333-333333333333';
|
||||||
|
|
||||||
|
function seed(): ContactMessageDetail[] {
|
||||||
|
const base = {
|
||||||
|
retentionUntil: '2027-11-01T10:00:00Z',
|
||||||
|
mailAttempts: 1,
|
||||||
|
mailError: null,
|
||||||
|
nextMailAttemptAt: null,
|
||||||
|
};
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
...base,
|
||||||
|
id: MSG_NEW,
|
||||||
|
receivedAt: '2026-11-09T10:00:00Z',
|
||||||
|
name: 'Jan Jansen',
|
||||||
|
email: 'jan@example.nl',
|
||||||
|
subject: 'Website',
|
||||||
|
message: 'Eerste regel\nTweede regel',
|
||||||
|
status: 'new',
|
||||||
|
mailStatus: 'sent',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...base,
|
||||||
|
id: MSG_READ,
|
||||||
|
receivedAt: '2026-11-08T10:00:00Z',
|
||||||
|
name: 'Marieke',
|
||||||
|
email: 'marieke@example.nl',
|
||||||
|
subject: 'Onderhoudspakket',
|
||||||
|
message: 'Hallo',
|
||||||
|
status: 'read',
|
||||||
|
mailStatus: 'failed',
|
||||||
|
mailAttempts: 2,
|
||||||
|
mailError: 'auth_failed',
|
||||||
|
nextMailAttemptAt: '2026-11-09T12:00:00Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...base,
|
||||||
|
id: MSG_SPAM,
|
||||||
|
receivedAt: '2026-11-07T10:00:00Z',
|
||||||
|
name: 'Bot',
|
||||||
|
email: 'bot@example.nl',
|
||||||
|
subject: 'Overig',
|
||||||
|
message: 'buy',
|
||||||
|
status: 'spam',
|
||||||
|
mailStatus: 'notApplicable',
|
||||||
|
mailAttempts: 0,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
let messages = seed();
|
||||||
|
let settings: ContactSettings = {
|
||||||
|
enabled: false,
|
||||||
|
hostEnabled: true,
|
||||||
|
recipientEmail: null,
|
||||||
|
recipientSource: 'config',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resetMockContact(): void {
|
||||||
|
messages = seed();
|
||||||
|
settings = {
|
||||||
|
enabled: false,
|
||||||
|
hostEnabled: true,
|
||||||
|
recipientEmail: null,
|
||||||
|
recipientSource: 'config',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMockContactMessages(): ContactMessageDetail[] {
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toItem(m: ContactMessageDetail): ContactMessageListItem {
|
||||||
|
return {
|
||||||
|
id: m.id,
|
||||||
|
receivedAt: m.receivedAt,
|
||||||
|
name: m.name,
|
||||||
|
email: m.email,
|
||||||
|
subject: m.subject,
|
||||||
|
status: m.status,
|
||||||
|
mailStatus: m.mailStatus,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const contactHandlers = [
|
||||||
|
http.get(SETTINGS, () => HttpResponse.json(settings)),
|
||||||
|
http.put(`${SETTINGS}/recipient`, async ({ request }) => {
|
||||||
|
const body = (await request.json()) as { recipientEmail: string | null };
|
||||||
|
const address = body.recipientEmail?.trim() || null;
|
||||||
|
if (address && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(address)) {
|
||||||
|
return HttpResponse.json(
|
||||||
|
{
|
||||||
|
status: 400,
|
||||||
|
title: 'Validation failed',
|
||||||
|
errors: { recipientEmail: ['invalid'] },
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
settings = {
|
||||||
|
...settings,
|
||||||
|
recipientEmail: address,
|
||||||
|
recipientSource: address ? 'setting' : 'config',
|
||||||
|
};
|
||||||
|
return HttpResponse.json(settings);
|
||||||
|
}),
|
||||||
|
http.put(SETTINGS, async ({ request }) => {
|
||||||
|
const body = (await request.json()) as { enabled: boolean };
|
||||||
|
settings = { ...settings, enabled: body.enabled };
|
||||||
|
return HttpResponse.json(settings);
|
||||||
|
}),
|
||||||
|
http.get(BASE, ({ request }) => {
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const status = url.searchParams.get('status');
|
||||||
|
const page = Number(url.searchParams.get('page') ?? '1');
|
||||||
|
const pageSize = Number(url.searchParams.get('pageSize') ?? '25');
|
||||||
|
const wanted: ContactStatus[] = status
|
||||||
|
? [status as ContactStatus]
|
||||||
|
: ['new', 'read', 'archived'];
|
||||||
|
const all = messages.filter((m) => wanted.includes(m.status));
|
||||||
|
const items = all.slice((page - 1) * pageSize, page * pageSize).map(toItem);
|
||||||
|
return HttpResponse.json({
|
||||||
|
items,
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
totalCount: all.length,
|
||||||
|
unreadCount: messages.filter((m) => m.status === 'new').length,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
http.get(`${BASE}/:id`, ({ params }) => {
|
||||||
|
const m = messages.find((x) => x.id === params.id);
|
||||||
|
return m ? HttpResponse.json(m) : new HttpResponse(null, { status: 404 });
|
||||||
|
}),
|
||||||
|
http.patch(`${BASE}/:id`, async ({ params, request }) => {
|
||||||
|
const m = messages.find((x) => x.id === params.id);
|
||||||
|
if (!m) return new HttpResponse(null, { status: 404 });
|
||||||
|
const body = (await request.json()) as { status: ContactStatus };
|
||||||
|
m.status = body.status;
|
||||||
|
return HttpResponse.json(m);
|
||||||
|
}),
|
||||||
|
http.delete(`${BASE}/:id`, ({ params }) => {
|
||||||
|
const before = messages.length;
|
||||||
|
messages = messages.filter((x) => x.id !== params.id);
|
||||||
|
return messages.length === before
|
||||||
|
? new HttpResponse(null, { status: 404 })
|
||||||
|
: new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
http.post(`${BASE}/:id/resend`, ({ params }) => {
|
||||||
|
const m = messages.find((x) => x.id === params.id);
|
||||||
|
if (!m) return new HttpResponse(null, { status: 404 });
|
||||||
|
if (m.status === 'spam')
|
||||||
|
return HttpResponse.json({ status: 409, title: 'Conflict' }, { status: 409 });
|
||||||
|
return HttpResponse.json({
|
||||||
|
mailStatus: 'sent',
|
||||||
|
mailAttempts: m.mailAttempts + 1,
|
||||||
|
mailed: true,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
];
|
||||||
@@ -0,0 +1,778 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { screen, waitFor, within } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { http, HttpResponse } from 'msw';
|
||||||
|
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||||
|
import { server } from '@/mocks/server';
|
||||||
|
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||||
|
import {
|
||||||
|
MSG_NEW,
|
||||||
|
MSG_READ,
|
||||||
|
MSG_SPAM,
|
||||||
|
getMockContactMessages,
|
||||||
|
resetMockContact,
|
||||||
|
} from '@/features/contact/mocks/handlers';
|
||||||
|
import { _resetSetupStatusCache } from '@/router';
|
||||||
|
|
||||||
|
const LONG = { timeout: 10000 };
|
||||||
|
|
||||||
|
function capabilities(modules: string[], emailEnabled = true) {
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/System/capabilities`, () =>
|
||||||
|
HttpResponse.json({ modules, emailEnabled, defaultLanguage: 'nl' }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const WITH_CONTACT = ['Availability', 'Identity', 'Master', 'Offerings', 'Contact'];
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
_resetSetupStatusCache();
|
||||||
|
resetMockContact();
|
||||||
|
mockAuthenticated();
|
||||||
|
});
|
||||||
|
|
||||||
|
async function openPage() {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
renderApp('/messages');
|
||||||
|
await screen.findByTestId('messages-title', {}, LONG);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSettings() {
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-tab-settings'));
|
||||||
|
await screen.findByTestId('contact-panel-settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Berichten navigation', () => {
|
||||||
|
it('shows the sidebar entry when the module is loaded and the API answers', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
expect(await screen.findByTestId('nav-messages', {}, LONG)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides the entry when the module is not loaded', async () => {
|
||||||
|
capabilities(['Availability', 'Identity', 'Offerings']);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
await screen.findByTestId('nav-offerings', {}, LONG);
|
||||||
|
expect(screen.queryByTestId('nav-messages')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hides the entry when the settings answer 404 (host switch off)', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
server.use(
|
||||||
|
http.get(
|
||||||
|
`${API_BASE}/api/v1/contact-settings`,
|
||||||
|
() => new HttpResponse(null, { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
await screen.findByTestId('nav-offerings', {}, LONG);
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
expect(screen.queryByTestId('nav-messages')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the not-found page on a direct visit while unavailable', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
server.use(
|
||||||
|
http.get(
|
||||||
|
`${API_BASE}/api/v1/contact-settings`,
|
||||||
|
() => new HttpResponse(null, { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
renderApp('/messages');
|
||||||
|
expect(await screen.findByTestId('not-found-title', {}, LONG)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the feature-unavailable message when the module is missing', async () => {
|
||||||
|
capabilities(['Availability', 'Identity']);
|
||||||
|
renderApp('/messages');
|
||||||
|
expect(
|
||||||
|
await screen.findByTestId('feature-unavailable-message', {}, LONG),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Form switch', () => {
|
||||||
|
it('shows the first-time hint while off and switches on and off with the server answer', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
expect(await screen.findByTestId('contact-switch-hint')).toBeInTheDocument();
|
||||||
|
const toggle = screen.getByTestId('contact-switch-toggle');
|
||||||
|
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||||
|
|
||||||
|
await userEvent.click(toggle);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
|
||||||
|
'aria-checked',
|
||||||
|
'true',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-switch-state')).toHaveTextContent('The form is on');
|
||||||
|
expect(screen.queryByTestId('contact-switch-hint')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('contact-switch-toggle'));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
|
||||||
|
'aria-checked',
|
||||||
|
'false',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is a real switch: named, stateful, 44px, with the state as text, usable by keyboard', async () => {
|
||||||
|
await openPage();
|
||||||
|
const toggle = await screen.findByRole('switch', { name: 'Contact form on/off' });
|
||||||
|
|
||||||
|
expect(toggle).toHaveAttribute('aria-checked', 'false');
|
||||||
|
expect(toggle).toHaveTextContent('Off');
|
||||||
|
expect(toggle.className).toContain('min-h-11');
|
||||||
|
expect(toggle.className).toContain('min-w-11');
|
||||||
|
|
||||||
|
toggle.focus();
|
||||||
|
await userEvent.keyboard(' ');
|
||||||
|
await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'true'));
|
||||||
|
expect(toggle).toHaveTextContent('On');
|
||||||
|
|
||||||
|
await userEvent.keyboard('{Enter}');
|
||||||
|
await waitFor(() => expect(toggle).toHaveAttribute('aria-checked', 'false'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is disabled while saving', async () => {
|
||||||
|
await openPage();
|
||||||
|
server.use(
|
||||||
|
http.put(`${API_BASE}/api/v1/contact-settings`, async () => {
|
||||||
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
|
return HttpResponse.json({ enabled: true, hostEnabled: true });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const toggle = await screen.findByTestId('contact-switch-toggle');
|
||||||
|
await userEvent.click(toggle);
|
||||||
|
|
||||||
|
expect(toggle).toBeDisabled();
|
||||||
|
await waitFor(() => expect(toggle).not.toBeDisabled());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a translated error and keeps the state when the switch fails', async () => {
|
||||||
|
await openPage();
|
||||||
|
server.use(
|
||||||
|
http.put(`${API_BASE}/api/v1/contact-settings`, () =>
|
||||||
|
HttpResponse.json({ status: 500, title: 'Internal Server Error' }, { status: 500 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-switch-toggle'));
|
||||||
|
|
||||||
|
const error = await screen.findByTestId('contact-switch-error');
|
||||||
|
expect(error).toHaveTextContent('Something went wrong');
|
||||||
|
expect(error).not.toHaveTextContent('Internal Server Error');
|
||||||
|
expect(screen.getByTestId('contact-switch-toggle')).toHaveAttribute(
|
||||||
|
'aria-checked',
|
||||||
|
'false',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Recipient address', () => {
|
||||||
|
it('shows the field, says that the server setting applies, and never an address it was not given', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('contact-recipient-card')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('');
|
||||||
|
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||||
|
'server setting applies',
|
||||||
|
);
|
||||||
|
expect(screen.queryByTestId('contact-recipient-reset')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('contact-no-recipient-banner')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('saves a valid address, shows where it comes from and offers to go back', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
const input = await screen.findByTestId('contact-recipient-input');
|
||||||
|
|
||||||
|
await userEvent.type(input, ' inbox@example.org ');
|
||||||
|
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||||
|
'Messages go to this address',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('inbox@example.org');
|
||||||
|
expect(screen.getByTestId('contact-recipient-reset')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not save an invalid address (client side), and says so', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
const input = await screen.findByTestId('contact-recipient-input');
|
||||||
|
|
||||||
|
await userEvent.type(input, 'not-an-address');
|
||||||
|
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('contact-recipient-invalid')).toHaveTextContent(
|
||||||
|
'valid e-mail address',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a translated message when the server refuses the address', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
server.use(
|
||||||
|
http.put(`${API_BASE}/api/v1/contact-settings/recipient`, () =>
|
||||||
|
HttpResponse.json(
|
||||||
|
{
|
||||||
|
status: 400,
|
||||||
|
title: 'Validation failed',
|
||||||
|
errors: { recipientEmail: ['invalid'] },
|
||||||
|
},
|
||||||
|
{ status: 400 },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await userEvent.type(
|
||||||
|
await screen.findByTestId('contact-recipient-input'),
|
||||||
|
'jan@example.org',
|
||||||
|
);
|
||||||
|
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||||
|
|
||||||
|
const error = await screen.findByTestId('contact-recipient-error');
|
||||||
|
expect(error).toHaveTextContent('valid e-mail address');
|
||||||
|
expect(error).not.toHaveTextContent('Validation failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('goes back to the server setting when cleared', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
await userEvent.type(
|
||||||
|
await screen.findByTestId('contact-recipient-input'),
|
||||||
|
'inbox@example.org',
|
||||||
|
);
|
||||||
|
await userEvent.click(screen.getByTestId('contact-recipient-save'));
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-recipient-reset'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||||
|
'server setting applies',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-recipient-input')).toHaveValue('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns (but does not block the switch) while there is no address at all', async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/contact-settings`, () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
enabled: false,
|
||||||
|
hostEnabled: true,
|
||||||
|
recipientEmail: null,
|
||||||
|
recipientSource: 'none',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('contact-no-recipient-banner')).toHaveTextContent(
|
||||||
|
'No recipient address is set',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-recipient-source')).toHaveTextContent(
|
||||||
|
'no recipient address yet',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-switch-toggle')).not.toBeDisabled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Message list', () => {
|
||||||
|
it('shows the inbox without spam and the unread counter', async () => {
|
||||||
|
await openPage();
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId(`contact-row-${MSG_READ}`)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId(`contact-row-${MSG_SPAM}`)).not.toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('contact-unread-count')).toHaveTextContent('(1)');
|
||||||
|
expect(screen.getByTestId('messages-range')).toHaveTextContent('1–2 of 2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends the right status for each chip and shows spam apart', async () => {
|
||||||
|
await openPage();
|
||||||
|
await screen.findByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-spam'));
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_SPAM}`)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId(`contact-row-${MSG_NEW}`)).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-new'));
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId(`contact-row-${MSG_READ}`)).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-archived'));
|
||||||
|
expect(await screen.findByTestId('messages-empty-state')).toHaveTextContent(
|
||||||
|
'No archived messages',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requests the status query parameter only for a specific chip, 25 per page', async () => {
|
||||||
|
const urls: string[] = [];
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/contact-messages`, ({ request }) => {
|
||||||
|
urls.push(new URL(request.url).search);
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: [],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 25,
|
||||||
|
totalCount: 0,
|
||||||
|
unreadCount: 0,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await openPage();
|
||||||
|
await screen.findByTestId('messages-empty-state');
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-read'));
|
||||||
|
await waitFor(() => expect(urls.some((u) => u.includes('status=read'))).toBe(true));
|
||||||
|
|
||||||
|
expect(urls[0]).not.toContain('status=');
|
||||||
|
expect(urls[0]).toContain('pageSize=25');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pages through more than 25 messages', async () => {
|
||||||
|
const many = Array.from({ length: 30 }, (_, i) => ({
|
||||||
|
id: `00000000-0000-0000-0000-${String(i).padStart(12, '0')}`,
|
||||||
|
receivedAt: '2026-11-09T10:00:00Z',
|
||||||
|
name: `Naam ${i}`,
|
||||||
|
email: 'x@example.nl',
|
||||||
|
subject: 's',
|
||||||
|
status: 'read',
|
||||||
|
mailStatus: 'sent',
|
||||||
|
}));
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/contact-messages`, ({ request }) => {
|
||||||
|
const page = Number(new URL(request.url).searchParams.get('page'));
|
||||||
|
return HttpResponse.json({
|
||||||
|
items: many.slice((page - 1) * 25, page * 25),
|
||||||
|
page,
|
||||||
|
pageSize: 25,
|
||||||
|
totalCount: 30,
|
||||||
|
unreadCount: 0,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await openPage();
|
||||||
|
expect(await screen.findByTestId('messages-range')).toHaveTextContent('1–25 of 30');
|
||||||
|
expect(screen.getByTestId('messages-prev')).toBeDisabled();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('messages-next'));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('messages-range')).toHaveTextContent('26–30 of 30'),
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('messages-next')).toBeDisabled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows an empty state for the inbox', async () => {
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/contact-messages`, () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
items: [],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 25,
|
||||||
|
totalCount: 0,
|
||||||
|
unreadCount: 0,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await openPage();
|
||||||
|
expect(await screen.findByTestId('messages-empty-state')).toHaveTextContent(
|
||||||
|
'No messages yet',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a subject label with special characters as plain text', async () => {
|
||||||
|
const label = `Fotoshoot & <b>"bruiloft"</b> 'zomer'`;
|
||||||
|
server.use(
|
||||||
|
http.get(`${API_BASE}/api/v1/contact-messages`, () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: MSG_NEW,
|
||||||
|
receivedAt: '2026-11-09T10:00:00Z',
|
||||||
|
name: 'Jan',
|
||||||
|
email: 'jan@example.nl',
|
||||||
|
subject: label,
|
||||||
|
status: 'read',
|
||||||
|
mailStatus: 'sent',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 25,
|
||||||
|
totalCount: 1,
|
||||||
|
unreadCount: 0,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await openPage();
|
||||||
|
|
||||||
|
const row = await screen.findByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
expect(row).toHaveTextContent(label);
|
||||||
|
expect(row.querySelector('b')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives the mail icons a text alternative', async () => {
|
||||||
|
await openPage();
|
||||||
|
await screen.findByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
expect(
|
||||||
|
within(screen.getByTestId(`contact-row-${MSG_NEW}`)).getByTestId('mail-status-sent'),
|
||||||
|
).toHaveAccessibleName('Mail sent');
|
||||||
|
expect(
|
||||||
|
within(screen.getByTestId(`contact-row-${MSG_READ}`)).getByTestId('mail-status-failed'),
|
||||||
|
).toHaveAccessibleName('Mail failed');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Message detail', () => {
|
||||||
|
it('opens, keeps line breaks, links the address and marks an unread message as read', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_NEW}`));
|
||||||
|
|
||||||
|
const body = await screen.findByTestId('contact-message-body');
|
||||||
|
expect(body.textContent).toBe('Eerste regel\nTweede regel');
|
||||||
|
expect(body.className).toContain('whitespace-pre-wrap');
|
||||||
|
expect(screen.getByRole('link', { name: 'jan@example.nl' })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'mailto:jan@example.nl',
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_NEW)?.status).toBe('read'),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-unread-count')).toHaveTextContent('(0)'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not change an already read message when it is opened', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
await screen.findByTestId('contact-message-body');
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('has no status select; the status is an icon with its name as text', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
|
||||||
|
const dialog = await screen.findByTestId('contact-message-dialog');
|
||||||
|
expect(within(dialog).queryByTestId('contact-status-select')).not.toBeInTheDocument();
|
||||||
|
expect(within(dialog).queryByRole('combobox')).not.toBeInTheDocument();
|
||||||
|
const icon = within(dialog).getByTestId('status-icon-read');
|
||||||
|
expect(icon).toHaveTextContent('Read');
|
||||||
|
expect(icon).toHaveAttribute('title', 'Read');
|
||||||
|
expect(icon.querySelector('svg')).toHaveAttribute('aria-hidden', 'true');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('archives a message and restores it to read', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-archive-button'));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe(
|
||||||
|
'archived',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await within(screen.getByTestId('contact-message-dialog')).findByTestId(
|
||||||
|
'status-icon-archived',
|
||||||
|
),
|
||||||
|
).toHaveTextContent('Archived');
|
||||||
|
expect(screen.queryByTestId('contact-archive-button')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-restore-button'));
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('read'),
|
||||||
|
);
|
||||||
|
expect(await screen.findByTestId('contact-archive-button')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the same status icon and name in the list', async () => {
|
||||||
|
await openPage();
|
||||||
|
const readRow = await screen.findByTestId(`contact-row-${MSG_READ}`);
|
||||||
|
const newRow = screen.getByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
|
||||||
|
expect(within(readRow).getByTestId('status-icon-read')).toHaveTextContent('Read');
|
||||||
|
expect(within(newRow).getByTestId('status-icon-new')).toHaveTextContent('New');
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-spam'));
|
||||||
|
expect(await screen.findByTestId('status-icon-spam')).toHaveTextContent('Spam');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the subject exactly as the site sent it, capitals included', async () => {
|
||||||
|
await openPage();
|
||||||
|
const row = await screen.findByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
expect(row).toHaveTextContent('Website');
|
||||||
|
expect(row).not.toHaveTextContent('website'); // case-sensitive: no lower-case slug
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the translated mail error and the next attempt, never the raw code', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('contact-mail-error')).toHaveTextContent(
|
||||||
|
'Logging in to the mail server failed.',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('contact-mail-error')).not.toHaveTextContent('auth_failed');
|
||||||
|
expect(screen.getByTestId('contact-next-attempt')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves a spam message to the inbox with "Geen spam"', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-filter-spam'));
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_SPAM}`));
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-not-spam'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_SPAM)?.status).toBe('read'),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.queryByTestId(`contact-row-${MSG_SPAM}`)).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
await userEvent.click(screen.getByTestId('contact-filter-inbox'));
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_SPAM}`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not offer resend on a spam message', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-filter-spam'));
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_SPAM}`));
|
||||||
|
await screen.findByTestId('contact-not-spam');
|
||||||
|
expect(screen.queryByTestId('contact-resend-button')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Delete', () => {
|
||||||
|
it('deletes after confirmation', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-delete-button'));
|
||||||
|
await userEvent.click(await screen.findByTestId('delete-message-confirm'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.queryByTestId(`contact-row-${MSG_READ}`)).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(getMockContactMessages().some((m) => m.id === MSG_READ)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the message when the confirmation is cancelled', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-delete-button'));
|
||||||
|
await userEvent.click(await screen.findByTestId('delete-message-cancel'));
|
||||||
|
|
||||||
|
expect(getMockContactMessages().some((m) => m.id === MSG_READ)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Resend', () => {
|
||||||
|
async function openRead() {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
return screen.findByTestId('contact-resend-button');
|
||||||
|
}
|
||||||
|
|
||||||
|
it('says "Verstuurd" when the mail went out', async () => {
|
||||||
|
await userEvent.click(await openRead());
|
||||||
|
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent('Sent.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('says "Niet verstuurd" when the server could not send', async () => {
|
||||||
|
const button = await openRead();
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
|
||||||
|
HttpResponse.json({
|
||||||
|
mailStatus: 'pending',
|
||||||
|
mailAttempts: 0,
|
||||||
|
mailed: false,
|
||||||
|
mailError: 'disabled',
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await userEvent.click(button);
|
||||||
|
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent(
|
||||||
|
'Not sent (mail is off).',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the retry delay from Retry-After on 429', async () => {
|
||||||
|
const button = await openRead();
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
|
||||||
|
HttpResponse.json(
|
||||||
|
{ status: 429, title: 'Too Many Requests' },
|
||||||
|
{ status: 429, headers: { 'Retry-After': '42' } },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await userEvent.click(button);
|
||||||
|
const note = await screen.findByTestId('contact-resend-note');
|
||||||
|
expect(note).toHaveTextContent('Try again in 42 seconds.');
|
||||||
|
expect(note).not.toHaveTextContent('Too Many Requests');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains a 409 on a spam message', async () => {
|
||||||
|
const button = await openRead();
|
||||||
|
server.use(
|
||||||
|
http.post(`${API_BASE}/api/v1/contact-messages/:id/resend`, () =>
|
||||||
|
HttpResponse.json({ status: 409, title: 'Conflict' }, { status: 409 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await userEvent.click(button);
|
||||||
|
expect(await screen.findByTestId('contact-resend-note')).toHaveTextContent(
|
||||||
|
'Mark the message as not spam first.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables resend with a hint when e-mail is off for the site', async () => {
|
||||||
|
capabilities(WITH_CONTACT, false);
|
||||||
|
renderApp('/messages');
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`, {}, LONG));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('contact-resend-button')).toBeDisabled();
|
||||||
|
expect(screen.getByTestId('contact-resend-hint')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Unread indication and status placement', () => {
|
||||||
|
it('marks only unread messages with a dot that has an accessible name', async () => {
|
||||||
|
await openPage();
|
||||||
|
await screen.findByTestId(`contact-row-${MSG_NEW}`);
|
||||||
|
const dot = screen.getByTestId(`contact-unread-dot-${MSG_NEW}`);
|
||||||
|
expect(dot).toHaveAccessibleName('Unread');
|
||||||
|
expect(screen.queryByTestId(`contact-unread-dot-${MSG_READ}`)).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the status above the message text in the detail', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
const body = await screen.findByTestId('contact-message-body');
|
||||||
|
const status = await within(screen.getByTestId('contact-message-dialog')).findByTestId(
|
||||||
|
'status-icon-read',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
status.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING,
|
||||||
|
).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks a read message as unread again and does not re-mark it as read', async () => {
|
||||||
|
await openPage();
|
||||||
|
await userEvent.click(await screen.findByTestId(`contact-open-${MSG_READ}`));
|
||||||
|
await userEvent.click(await screen.findByTestId('contact-mark-unread-button'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockContactMessages().find((m) => m.id === MSG_READ)?.status).toBe('new'),
|
||||||
|
);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('contact-unread-count')).toHaveTextContent('(2)'),
|
||||||
|
);
|
||||||
|
expect(await screen.findByTestId(`contact-unread-dot-${MSG_READ}`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Dashboard tile', () => {
|
||||||
|
it('shows the number of unread messages and links to the list', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
const tile = await screen.findByTestId('messages-tile', {}, LONG);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId('messages-tile-count')).toHaveTextContent('1'),
|
||||||
|
);
|
||||||
|
expect(tile).toHaveAttribute('href', '/messages');
|
||||||
|
// Next to the system status tile in the same grid, not full width.
|
||||||
|
expect(tile.parentElement).toBe(screen.getByTestId('dashboard-tiles'));
|
||||||
|
expect(screen.getByTestId('availability-badge').closest('[data-testid="dashboard-tiles"]')).not.toBeNull();
|
||||||
|
expect(tile).toHaveTextContent('unread message');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is not shown when the module is not loaded', async () => {
|
||||||
|
capabilities(['Availability', 'Identity', 'Offerings']);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
await screen.findByTestId('dashboard-title', {}, LONG);
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
expect(screen.queryByTestId('messages-tile')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is not shown while the host switch is off (404)', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
server.use(
|
||||||
|
http.get(
|
||||||
|
`${API_BASE}/api/v1/contact-settings`,
|
||||||
|
() => new HttpResponse(null, { status: 404 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
renderApp('/dashboard');
|
||||||
|
await screen.findByTestId('dashboard-title', {}, LONG);
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
expect(screen.queryByTestId('messages-tile')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Clickable row', () => {
|
||||||
|
it('opens the message when any cell of the row is clicked', async () => {
|
||||||
|
await openPage();
|
||||||
|
const row = await screen.findByTestId(`contact-row-${MSG_READ}`);
|
||||||
|
await userEvent.click(within(row).getByText('Onderhoudspakket'));
|
||||||
|
expect(await screen.findByTestId('contact-message-dialog')).toBeInTheDocument();
|
||||||
|
expect(await screen.findByTestId('contact-message-body')).toHaveTextContent('Hallo');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Tabs and header switch', () => {
|
||||||
|
it('opens on the messages tab with the switch level with the title and no settings blocks', async () => {
|
||||||
|
await openPage();
|
||||||
|
expect(await screen.findByRole('tab', { name: 'Messages', selected: true })).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('tabpanel')).toHaveAttribute('id', 'contact-panel-messages');
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('contact-recipient-card')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('contact-switch-card')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
const header = screen.getByTestId('messages-title').parentElement as HTMLElement;
|
||||||
|
const toggle = within(header).getByRole('switch', { name: 'Contact form on/off' });
|
||||||
|
expect(toggle).toHaveAttribute('title', 'Contact form on/off');
|
||||||
|
expect(toggle).toHaveTextContent('Off');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('moves the explanation, hints and recipient to the Settings tab', async () => {
|
||||||
|
await openPage();
|
||||||
|
await openSettings();
|
||||||
|
expect(screen.getByRole('tab', { name: 'Settings', selected: true })).toBeInTheDocument();
|
||||||
|
const card = await screen.findByTestId('contact-switch-card');
|
||||||
|
expect(card).toHaveTextContent('While the form is off');
|
||||||
|
expect(screen.getByTestId('contact-switch-state')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('contact-recipient-card')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('messages-range')).not.toBeInTheDocument();
|
||||||
|
// the switch stays in the header
|
||||||
|
expect(screen.getAllByRole('switch')).toHaveLength(1);
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('contact-tab-messages'));
|
||||||
|
expect(await screen.findByTestId(`contact-row-${MSG_NEW}`)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('opens directly on the Settings tab from the URL', async () => {
|
||||||
|
capabilities(WITH_CONTACT);
|
||||||
|
renderApp('/messages?tab=settings');
|
||||||
|
expect(await screen.findByTestId('contact-recipient-card', {}, LONG)).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('tab', { name: 'Settings', selected: true })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports the arrow keys, Home and End on the tabs', async () => {
|
||||||
|
await openPage();
|
||||||
|
const messagesTab = await screen.findByRole('tab', { name: 'Messages' });
|
||||||
|
messagesTab.focus();
|
||||||
|
await userEvent.keyboard('{ArrowRight}');
|
||||||
|
expect(await screen.findByRole('tab', { name: 'Settings', selected: true })).toHaveFocus();
|
||||||
|
expect(screen.getByRole('tabpanel')).toHaveAttribute('aria-labelledby', 'contact-tab-settings');
|
||||||
|
await userEvent.keyboard('{ArrowRight}');
|
||||||
|
expect(await screen.findByRole('tab', { name: 'Messages', selected: true })).toHaveFocus();
|
||||||
|
await userEvent.keyboard('{End}');
|
||||||
|
expect(await screen.findByRole('tab', { name: 'Settings', selected: true })).toHaveFocus();
|
||||||
|
await userEvent.keyboard('{Home}');
|
||||||
|
expect(await screen.findByRole('tab', { name: 'Messages', selected: true })).toHaveFocus();
|
||||||
|
expect(screen.getByRole('tab', { name: 'Settings' })).toHaveAttribute('tabindex', '-1');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Mail } from 'lucide-react';
|
||||||
|
import { useNavigate, useSearch } from '@tanstack/react-router';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { FormSwitchCard, FormSwitchHeader } from '../components/FormSwitchCard';
|
||||||
|
import { ContactTabs } from '../components/ContactTabs';
|
||||||
|
import { RecipientCard } from '../components/RecipientCard';
|
||||||
|
import { MessagesFilterChips } from '../components/MessagesFilterChips';
|
||||||
|
import { MessagesTable } from '../components/MessagesTable';
|
||||||
|
import { MessageDialog } from '../components/MessageDialog';
|
||||||
|
import { DeleteMessageDialog } from '../components/DeleteMessageDialog';
|
||||||
|
import { useContactMessages, useDeleteContactMessage } from '../services/useContactMessages';
|
||||||
|
import { contactErrorMessage } from '../errors';
|
||||||
|
import type { ContactFilter } from '../services/types';
|
||||||
|
|
||||||
|
type TabId = 'messages' | 'settings';
|
||||||
|
|
||||||
|
export function MessagesPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const search = useSearch({ strict: false }) as { tab?: string };
|
||||||
|
const tab: TabId = search.tab === 'settings' ? 'settings' : 'messages';
|
||||||
|
const [filter, setFilter] = useState<ContactFilter>('inbox');
|
||||||
|
const [page, setPage] = useState(1);
|
||||||
|
const [openId, setOpenId] = useState<string | null>(null);
|
||||||
|
const [deleteId, setDeleteId] = useState<string | null>(null);
|
||||||
|
const { data, isPending, isError } = useContactMessages(filter, page);
|
||||||
|
const remove = useDeleteContactMessage();
|
||||||
|
|
||||||
|
const changeFilter = (next: ContactFilter) => {
|
||||||
|
setFilter(next);
|
||||||
|
setPage(1);
|
||||||
|
};
|
||||||
|
|
||||||
|
const from = data && data.totalCount > 0 ? (data.page - 1) * data.pageSize + 1 : 0;
|
||||||
|
const to = data ? Math.min(data.page * data.pageSize, data.totalCount) : 0;
|
||||||
|
const hasPrevious = page > 1;
|
||||||
|
const hasNext = data ? to < data.totalCount : false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4 p-4">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<h1 className="text-2xl font-semibold" data-testid="messages-title">
|
||||||
|
{t('contact.title')}
|
||||||
|
</h1>
|
||||||
|
<FormSwitchHeader />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ContactTabs<TabId>
|
||||||
|
aria-label={t('contact.tabs.label')}
|
||||||
|
value={tab}
|
||||||
|
onChange={(next) =>
|
||||||
|
void navigate({
|
||||||
|
to: '.',
|
||||||
|
search: { tab: next === 'settings' ? 'settings' : undefined },
|
||||||
|
replace: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
tabs={[
|
||||||
|
{
|
||||||
|
id: 'messages',
|
||||||
|
label: t('contact.tabs.messages'),
|
||||||
|
panel: (
|
||||||
|
<>
|
||||||
|
<MessagesFilterChips
|
||||||
|
value={filter}
|
||||||
|
unreadCount={data?.unreadCount}
|
||||||
|
onChange={changeFilter}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{isPending && <p className="text-sm text-muted-foreground">{t('common.loading')}</p>}
|
||||||
|
{isError && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{t('errors.generic')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{data && data.items.length === 0 && (
|
||||||
|
<div
|
||||||
|
className="flex flex-col items-center gap-3 py-12 text-center"
|
||||||
|
data-testid="messages-empty-state"
|
||||||
|
>
|
||||||
|
<Mail className="size-10 text-muted-foreground" />
|
||||||
|
<p className="text-muted-foreground">{t(`contact.empty.${filter}`)}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{data && data.items.length > 0 && (
|
||||||
|
<>
|
||||||
|
<MessagesTable items={data.items} onOpen={setOpenId} />
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<span data-testid="messages-range">
|
||||||
|
{t('contact.pager.range', { from, to, total: data.totalCount })}
|
||||||
|
</span>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={!hasPrevious}
|
||||||
|
onClick={() => setPage(page - 1)}
|
||||||
|
data-testid="messages-prev"
|
||||||
|
>
|
||||||
|
{t('contact.pager.previous')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={!hasNext}
|
||||||
|
onClick={() => setPage(page + 1)}
|
||||||
|
data-testid="messages-next"
|
||||||
|
>
|
||||||
|
{t('contact.pager.next')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'settings',
|
||||||
|
label: t('contact.tabs.settings'),
|
||||||
|
panel: (
|
||||||
|
<>
|
||||||
|
<FormSwitchCard />
|
||||||
|
<RecipientCard />
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<MessageDialog
|
||||||
|
key={openId ?? 'closed'}
|
||||||
|
id={openId}
|
||||||
|
onClose={() => setOpenId(null)}
|
||||||
|
onDeleteRequested={setDeleteId}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DeleteMessageDialog
|
||||||
|
open={deleteId !== null}
|
||||||
|
isDeleting={remove.isPending}
|
||||||
|
error={remove.isError ? contactErrorMessage(remove.error, t) : null}
|
||||||
|
onCancel={() => {
|
||||||
|
setDeleteId(null);
|
||||||
|
remove.reset();
|
||||||
|
}}
|
||||||
|
onConfirm={() => {
|
||||||
|
if (deleteId) {
|
||||||
|
remove.mutate(deleteId, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setDeleteId(null);
|
||||||
|
setOpenId(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
export type ContactStatus = 'new' | 'read' | 'archived' | 'spam' | 'converted';
|
||||||
|
export type ContactMailStatus = 'pending' | 'sent' | 'failed' | 'notApplicable';
|
||||||
|
/** The status filters of the list; 'inbox' sends no status (the server then leaves out spam). */
|
||||||
|
export type ContactFilter = 'inbox' | 'new' | 'read' | 'archived' | 'spam';
|
||||||
|
/** The statuses an administrator may set from the detail dialog. */
|
||||||
|
export type SettableStatus = 'new' | 'read' | 'archived';
|
||||||
|
|
||||||
|
export interface ContactMessageListItem {
|
||||||
|
id: string;
|
||||||
|
receivedAt: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
subject: string;
|
||||||
|
status: ContactStatus;
|
||||||
|
mailStatus: ContactMailStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContactMessageList {
|
||||||
|
items: ContactMessageListItem[];
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
totalCount: number;
|
||||||
|
unreadCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContactMessageDetail extends ContactMessageListItem {
|
||||||
|
message: string;
|
||||||
|
mailAttempts: number;
|
||||||
|
mailError: string | null;
|
||||||
|
retentionUntil: string;
|
||||||
|
nextMailAttemptAt?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContactResendResult {
|
||||||
|
mailStatus: ContactMailStatus;
|
||||||
|
mailAttempts: number;
|
||||||
|
mailed: boolean;
|
||||||
|
mailError?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContactSettings {
|
||||||
|
/** The CMS switch: whether the form on the website is open. */
|
||||||
|
enabled: boolean;
|
||||||
|
hostEnabled: boolean;
|
||||||
|
/** The address chosen in the CMS, or null. The address from the server configuration is never sent. */
|
||||||
|
recipientEmail?: string | null;
|
||||||
|
/** Where mail goes: the CMS setting, the server configuration (default) or nowhere. */
|
||||||
|
recipientSource?: 'setting' | 'config' | 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const PAGE_SIZE = 25;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { api } from '@/lib/api-client';
|
||||||
|
import {
|
||||||
|
PAGE_SIZE,
|
||||||
|
type ContactFilter,
|
||||||
|
type ContactMessageDetail,
|
||||||
|
type ContactMessageList,
|
||||||
|
type ContactResendResult,
|
||||||
|
type SettableStatus,
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
const BASE = '/api/v1/contact-messages';
|
||||||
|
|
||||||
|
export function useContactMessages(filter: ContactFilter, page: number) {
|
||||||
|
return useQuery<ContactMessageList, Error>({
|
||||||
|
queryKey: ['contact', 'messages', filter, page],
|
||||||
|
queryFn: () => {
|
||||||
|
const params = new URLSearchParams({ page: String(page), pageSize: String(PAGE_SIZE) });
|
||||||
|
if (filter !== 'inbox') params.set('status', filter);
|
||||||
|
return api.get<ContactMessageList>(`${BASE}?${params.toString()}`);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only the unread counter, for the dashboard tile (one item is enough: the counter is part of every list answer). */
|
||||||
|
export function useUnreadContactCount(enabled: boolean) {
|
||||||
|
return useQuery<number, Error>({
|
||||||
|
queryKey: ['contact', 'messages', 'unreadCount'],
|
||||||
|
enabled,
|
||||||
|
queryFn: async () =>
|
||||||
|
(await api.get<ContactMessageList>(`${BASE}?page=1&pageSize=1`)).unreadCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useContactMessage(id: string | null) {
|
||||||
|
return useQuery<ContactMessageDetail, Error>({
|
||||||
|
queryKey: ['contact', 'message', id],
|
||||||
|
enabled: id !== null,
|
||||||
|
queryFn: () => api.get<ContactMessageDetail>(`${BASE}/${id}`),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function useInvalidateMessages() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return () => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['contact', 'messages'] });
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateContactMessageStatus() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const invalidate = useInvalidateMessages();
|
||||||
|
return useMutation<ContactMessageDetail, Error, { id: string; status: SettableStatus }>({
|
||||||
|
mutationFn: ({ id, status }) =>
|
||||||
|
api.patch<ContactMessageDetail>(`${BASE}/${id}`, { status }),
|
||||||
|
onSuccess: (detail) => {
|
||||||
|
queryClient.setQueryData(['contact', 'message', detail.id], detail);
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useDeleteContactMessage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const invalidate = useInvalidateMessages();
|
||||||
|
return useMutation<void, Error, string>({
|
||||||
|
mutationFn: (id) => api.delete<void>(`${BASE}/${id}`),
|
||||||
|
onSuccess: (_data, id) => {
|
||||||
|
queryClient.removeQueries({ queryKey: ['contact', 'message', id] });
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useResendContactMessage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const invalidate = useInvalidateMessages();
|
||||||
|
return useMutation<ContactResendResult, Error, string>({
|
||||||
|
mutationFn: (id) => api.post<ContactResendResult>(`${BASE}/${id}/resend`),
|
||||||
|
onSuccess: (_result, id) => {
|
||||||
|
void queryClient.invalidateQueries({ queryKey: ['contact', 'message', id] });
|
||||||
|
invalidate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { api, ProblemDetailsError } from '@/lib/api-client';
|
||||||
|
import type { ContactSettings } from './types';
|
||||||
|
|
||||||
|
export const CONTACT_SETTINGS_KEY = ['contact', 'settings'] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The form switch. `data === null` means "not available on this host": while the host switch is off every
|
||||||
|
* management route answers 404 with an empty body, although the module is loaded.
|
||||||
|
*/
|
||||||
|
export function useContactSettings(options?: { enabled?: boolean }) {
|
||||||
|
return useQuery<ContactSettings | null, Error>({
|
||||||
|
queryKey: CONTACT_SETTINGS_KEY,
|
||||||
|
enabled: options?.enabled ?? true,
|
||||||
|
// Fixed for the lifetime of the host process; the switch itself is updated from the PUT response.
|
||||||
|
staleTime: Infinity,
|
||||||
|
queryFn: async () => {
|
||||||
|
try {
|
||||||
|
return await api.get<ContactSettings>('/api/v1/contact-settings');
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof ProblemDetailsError && error.status === 404) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sets the address contact mails go to; null clears it (back to the server configuration). */
|
||||||
|
export function useUpdateContactRecipient() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation<ContactSettings, Error, string | null>({
|
||||||
|
mutationFn: (recipientEmail) =>
|
||||||
|
api.put<ContactSettings>('/api/v1/contact-settings/recipient', { recipientEmail }),
|
||||||
|
onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUpdateContactSettings() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
return useMutation<ContactSettings, Error, boolean>({
|
||||||
|
mutationFn: (enabled) => api.put<ContactSettings>('/api/v1/contact-settings', { enabled }),
|
||||||
|
// The state shown is the one the server answered with.
|
||||||
|
onSuccess: (settings) => queryClient.setQueryData(CONTACT_SETTINGS_KEY, settings),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { useAuth } from '@/features/auth/context/auth-context';
|
import { useAuth } from '@/features/auth/context/auth-context';
|
||||||
import { useAvailabilityStatus } from '@/features/availability/services/useAvailability';
|
import { useAvailabilityStatus } from '@/features/availability/services/useAvailability';
|
||||||
|
import { MessagesTile } from '@/features/contact/components/MessagesTile';
|
||||||
import { AvailabilityStatusBadge } from '@/features/availability/components/AvailabilityStatusBadge';
|
import { AvailabilityStatusBadge } from '@/features/availability/components/AvailabilityStatusBadge';
|
||||||
|
|
||||||
export function DashboardPage() {
|
export function DashboardPage() {
|
||||||
@@ -21,46 +22,49 @@ export function DashboardPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Card>
|
<div className="grid gap-4 md:grid-cols-2" data-testid="dashboard-tiles">
|
||||||
<CardHeader>
|
<Card>
|
||||||
<CardTitle>{t('availability.title')}</CardTitle>
|
<CardHeader>
|
||||||
</CardHeader>
|
<CardTitle>{t('availability.title')}</CardTitle>
|
||||||
<CardContent>
|
</CardHeader>
|
||||||
{isLoading && (
|
<CardContent>
|
||||||
<div
|
{isLoading && (
|
||||||
data-testid="availability-skeleton"
|
<div
|
||||||
className="h-8 w-32 animate-pulse rounded-full bg-muted"
|
data-testid="availability-skeleton"
|
||||||
/>
|
className="h-8 w-32 animate-pulse rounded-full bg-muted"
|
||||||
)}
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isLoading && data && (
|
{!isLoading && data && (
|
||||||
<AvailabilityStatusBadge
|
<AvailabilityStatusBadge
|
||||||
status={data.status}
|
status={data.status}
|
||||||
message={data.message}
|
message={data.message}
|
||||||
stale={isError}
|
stale={isError}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isError && (
|
{isError && (
|
||||||
<div
|
<div
|
||||||
data-testid="availability-error"
|
data-testid="availability-error"
|
||||||
className="mt-3 flex items-center gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
|
className="mt-3 flex items-center gap-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm text-destructive"
|
||||||
>
|
|
||||||
<span>{t('availability.errorTitle')}</span>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
data-testid="availability-retry"
|
|
||||||
onClick={() => void refetch()}
|
|
||||||
>
|
>
|
||||||
{t('availability.retry')}
|
<span>{t('availability.errorTitle')}</span>
|
||||||
</Button>
|
<Button
|
||||||
</div>
|
variant="outline"
|
||||||
)}
|
size="sm"
|
||||||
|
data-testid="availability-retry"
|
||||||
|
onClick={() => void refetch()}
|
||||||
|
>
|
||||||
|
{t('availability.retry')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isLoading && !data && !isError && null}
|
{!isLoading && !data && !isError && null}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
<MessagesTile />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,320 @@
|
|||||||
|
import { useState, type FormEvent } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Check, Pencil, Trash2, X } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||||
|
import { categoryNameSchema } from '../schemas/offering';
|
||||||
|
import { useOfferingCategories } from '../services/useOfferingCategories';
|
||||||
|
import { useCreateOfferingCategory } from '../services/useCreateOfferingCategory';
|
||||||
|
import { useRenameOfferingCategory } from '../services/useRenameOfferingCategory';
|
||||||
|
import { useDeleteOfferingCategory } from '../services/useDeleteOfferingCategory';
|
||||||
|
import type { OfferingCategoryDto } from '../services/types';
|
||||||
|
|
||||||
|
interface CategoriesDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages the categories offerings can be placed in. Lives inside the Offerings management
|
||||||
|
* (opened from the list page) rather than on a page of its own.
|
||||||
|
*/
|
||||||
|
export function CategoriesDialog({ open, onOpenChange }: CategoriesDialogProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { data: categories, isPending, isError } = useOfferingCategories();
|
||||||
|
const createCategory = useCreateOfferingCategory();
|
||||||
|
const renameCategory = useRenameOfferingCategory();
|
||||||
|
const deleteCategory = useDeleteOfferingCategory();
|
||||||
|
|
||||||
|
const [newName, setNewName] = useState('');
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [editName, setEditName] = useState('');
|
||||||
|
const [deletePendingId, setDeletePendingId] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function validate(name: string): string | null {
|
||||||
|
const result = categoryNameSchema.safeParse(name);
|
||||||
|
if (result.success) return null;
|
||||||
|
return result.error.issues[0].code === 'too_big'
|
||||||
|
? t('offerings.categories.errors.nameTooLong')
|
||||||
|
: t('offerings.categories.errors.nameRequired');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server rejections are translated here instead of showing the API's English titles.
|
||||||
|
function describeError(err: unknown, context: { name?: string; usedBy?: number }): string {
|
||||||
|
if (err instanceof NetworkError) return t('errors.network');
|
||||||
|
if (err instanceof ProblemDetailsError && err.status === 409) {
|
||||||
|
return context.usedBy !== undefined
|
||||||
|
? t('offerings.categories.errors.inUse', { count: context.usedBy })
|
||||||
|
: t('offerings.categories.errors.duplicate', { name: context.name ?? '' });
|
||||||
|
}
|
||||||
|
return t('errors.generic');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAdd(event: FormEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
const trimmed = newName.trim();
|
||||||
|
const problem = validate(trimmed);
|
||||||
|
if (problem) {
|
||||||
|
setError(problem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await createCategory.mutateAsync(trimmed);
|
||||||
|
setNewName('');
|
||||||
|
} catch (err) {
|
||||||
|
setError(describeError(err, { name: trimmed }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startEdit(category: OfferingCategoryDto) {
|
||||||
|
setError(null);
|
||||||
|
setDeletePendingId(null);
|
||||||
|
setEditingId(category.id);
|
||||||
|
setEditName(category.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelEdit() {
|
||||||
|
setEditingId(null);
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmEdit(category: OfferingCategoryDto) {
|
||||||
|
const trimmed = editName.trim();
|
||||||
|
const problem = validate(trimmed);
|
||||||
|
if (problem) {
|
||||||
|
setError(problem);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (trimmed === category.name) {
|
||||||
|
cancelEdit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await renameCategory.mutateAsync({ id: category.id, name: trimmed });
|
||||||
|
setEditingId(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(describeError(err, { name: trimmed }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function startDelete(category: OfferingCategoryDto) {
|
||||||
|
setError(null);
|
||||||
|
setEditingId(null);
|
||||||
|
setDeletePendingId(category.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmDelete(category: OfferingCategoryDto) {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await deleteCategory.mutateAsync(category.id);
|
||||||
|
setDeletePendingId(null);
|
||||||
|
} catch (err) {
|
||||||
|
setDeletePendingId(null);
|
||||||
|
setError(describeError(err, { usedBy: category.offeringCount }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleOpenChange(next: boolean) {
|
||||||
|
if (!next) {
|
||||||
|
setEditingId(null);
|
||||||
|
setDeletePendingId(null);
|
||||||
|
setError(null);
|
||||||
|
setNewName('');
|
||||||
|
}
|
||||||
|
onOpenChange(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent
|
||||||
|
className="sm:max-w-lg"
|
||||||
|
data-testid="categories-dialog"
|
||||||
|
onEscapeKeyDown={(event) => {
|
||||||
|
// Escape while renaming only cancels the rename, it does not close the dialog.
|
||||||
|
if (editingId !== null) {
|
||||||
|
event.preventDefault();
|
||||||
|
cancelEdit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t('offerings.categories.title')}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{error !== null && (
|
||||||
|
<p
|
||||||
|
role="alert"
|
||||||
|
className="text-sm text-destructive"
|
||||||
|
data-testid="categories-error"
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{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 && categories.length === 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground" data-testid="categories-empty">
|
||||||
|
{t('offerings.categories.emptyState')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isPending && !isError && categories.length > 0 && (
|
||||||
|
<ul className="divide-y rounded-md border" data-testid="categories-list">
|
||||||
|
{categories.map((category) => (
|
||||||
|
<li
|
||||||
|
key={category.id}
|
||||||
|
className="flex items-center justify-between gap-2 px-3 py-2"
|
||||||
|
data-testid={`category-row-${category.id}`}
|
||||||
|
>
|
||||||
|
{editingId === category.id ? (
|
||||||
|
<>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
className="h-8"
|
||||||
|
value={editName}
|
||||||
|
aria-label={t('offerings.categories.editButton')}
|
||||||
|
data-testid={`category-edit-input-${category.id}`}
|
||||||
|
onChange={(e) => setEditName(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
void confirmEdit(category);
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.stopPropagation();
|
||||||
|
cancelEdit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={t(
|
||||||
|
'offerings.categories.confirmEditButton',
|
||||||
|
)}
|
||||||
|
data-testid={`category-edit-confirm-${category.id}`}
|
||||||
|
onClick={() => void confirmEdit(category)}
|
||||||
|
>
|
||||||
|
<Check className="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={t('offerings.categories.cancelButton')}
|
||||||
|
data-testid={`category-edit-cancel-${category.id}`}
|
||||||
|
onClick={cancelEdit}
|
||||||
|
>
|
||||||
|
<X className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<span
|
||||||
|
className="font-medium"
|
||||||
|
data-testid={`category-name-${category.id}`}
|
||||||
|
>
|
||||||
|
{category.name}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className="ml-2 text-sm text-muted-foreground"
|
||||||
|
data-testid={`category-count-${category.id}`}
|
||||||
|
>
|
||||||
|
{t('offerings.categories.offeringCount', {
|
||||||
|
count: category.offeringCount,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{deletePendingId === category.id ? (
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<span>
|
||||||
|
{t('offerings.categories.deleteConfirm')}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
size="sm"
|
||||||
|
disabled={deleteCategory.isPending}
|
||||||
|
data-testid={`category-delete-confirm-${category.id}`}
|
||||||
|
onClick={() => void confirmDelete(category)}
|
||||||
|
>
|
||||||
|
{t('offerings.categories.deleteConfirmButton')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
data-testid={`category-delete-cancel-${category.id}`}
|
||||||
|
onClick={() => setDeletePendingId(null)}
|
||||||
|
>
|
||||||
|
{t('offerings.categories.cancelButton')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={t(
|
||||||
|
'offerings.categories.editButton',
|
||||||
|
)}
|
||||||
|
data-testid={`category-edit-${category.id}`}
|
||||||
|
onClick={() => startEdit(category)}
|
||||||
|
>
|
||||||
|
<Pencil className="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
aria-label={t(
|
||||||
|
'offerings.categories.deleteButton',
|
||||||
|
)}
|
||||||
|
data-testid={`category-delete-${category.id}`}
|
||||||
|
onClick={() => startDelete(category)}
|
||||||
|
>
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleAdd} className="flex gap-2" noValidate>
|
||||||
|
<Input
|
||||||
|
value={newName}
|
||||||
|
placeholder={t('offerings.categories.newLabel')}
|
||||||
|
aria-label={t('offerings.categories.newLabel')}
|
||||||
|
data-testid="category-new-input"
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={createCategory.isPending}
|
||||||
|
data-testid="category-add-button"
|
||||||
|
>
|
||||||
|
{t('offerings.categories.addButton')}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
import type { OfferingAdminDto } from '../services/types';
|
import type { OfferingDto } from '../services/types';
|
||||||
|
|
||||||
interface DeleteOfferingDialogProps {
|
interface DeleteOfferingDialogProps {
|
||||||
offering: OfferingAdminDto | null;
|
offering: OfferingDto | null;
|
||||||
isDeleting: boolean;
|
isDeleting: boolean;
|
||||||
onConfirm: () => void;
|
onConfirm: () => void;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useForm, useWatch } from 'react-hook-form';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { FieldError } from '@/components/ui/FieldError';
|
||||||
|
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { NetworkError } from '@/lib/api-client';
|
||||||
|
import {
|
||||||
|
fromLocalInput,
|
||||||
|
bannerTextMaxLength,
|
||||||
|
offeringBannerFormSchema,
|
||||||
|
toLocalInput,
|
||||||
|
type OfferingBannerFormData,
|
||||||
|
} from '../schemas/offeringBanner';
|
||||||
|
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
|
||||||
|
import type { BannerPosition, OfferingBannerDto } from '../services/types';
|
||||||
|
|
||||||
|
interface OfferingBannerDialogProps {
|
||||||
|
/** Open for editing this banner; null with `creating` = a new one. */
|
||||||
|
banner: OfferingBannerDto | null;
|
||||||
|
creating: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyForm = (position: BannerPosition): OfferingBannerFormData => ({
|
||||||
|
position,
|
||||||
|
title: '',
|
||||||
|
text: '',
|
||||||
|
linkLabel: '',
|
||||||
|
linkUrl: '',
|
||||||
|
isActive: true,
|
||||||
|
startsAt: '',
|
||||||
|
endsAt: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
function toForm(banner: OfferingBannerDto | null, position: BannerPosition): OfferingBannerFormData {
|
||||||
|
if (!banner) return emptyForm(position);
|
||||||
|
return {
|
||||||
|
position: banner.position,
|
||||||
|
title: banner.title,
|
||||||
|
text: banner.text,
|
||||||
|
linkLabel: banner.linkLabel ?? '',
|
||||||
|
linkUrl: banner.linkUrl ?? '',
|
||||||
|
isActive: banner.isActive,
|
||||||
|
startsAt: toLocalInput(banner.startsAt),
|
||||||
|
endsAt: toLocalInput(banner.endsAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function OfferingBannerDialog({ banner, creating, onClose }: OfferingBannerDialogProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const open = creating || banner !== null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<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') : t('offerings.banners.createTitle')}
|
||||||
|
</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
{/* Content is unmounted while closed, so every opening starts from fresh form state. */}
|
||||||
|
<OfferingBannerForm banner={banner} onClose={onClose} />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function OfferingBannerForm({
|
||||||
|
banner,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
banner: OfferingBannerDto | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [serverError, setServerError] = useState<string | null>(null);
|
||||||
|
const save = useSaveOfferingBanner();
|
||||||
|
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
control,
|
||||||
|
trigger,
|
||||||
|
formState: { errors, isSubmitted },
|
||||||
|
} = useForm<OfferingBannerFormData>({
|
||||||
|
resolver: zodResolver(offeringBannerFormSchema),
|
||||||
|
mode: 'onTouched',
|
||||||
|
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);
|
||||||
|
try {
|
||||||
|
await save.mutateAsync({
|
||||||
|
id: banner?.id,
|
||||||
|
body: {
|
||||||
|
position: values.position,
|
||||||
|
title: values.title,
|
||||||
|
text: values.text,
|
||||||
|
linkLabel: values.linkLabel || null,
|
||||||
|
linkUrl: values.linkUrl || null,
|
||||||
|
isActive: values.isActive,
|
||||||
|
startsAt: fromLocalInput(values.startsAt),
|
||||||
|
endsAt: fromLocalInput(values.endsAt),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
toast.success(t('offerings.banners.savedToast'));
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
setServerError(err instanceof NetworkError ? t('errors.network') : t('errors.generic'));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<FormErrorBanner
|
||||||
|
error={serverError !== null ? { message: serverError } : null}
|
||||||
|
onDismiss={() => setServerError(null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<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')} />
|
||||||
|
<FieldError message={errors.title?.message} testId="banner-title-error" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="banner-text">{t('offerings.banners.textLabel')}</Label>
|
||||||
|
<textarea
|
||||||
|
id="banner-text"
|
||||||
|
data-testid="banner-text"
|
||||||
|
rows={position === 'top' ? 2 : 3}
|
||||||
|
maxLength={textMax}
|
||||||
|
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||||
|
{...register('text')}
|
||||||
|
/>
|
||||||
|
<p
|
||||||
|
className={`text-xs ${textLength >= textMax ? 'text-destructive' : 'text-muted-foreground'}`}
|
||||||
|
data-testid="banner-text-counter"
|
||||||
|
>
|
||||||
|
{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>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="banner-link-label">{t('offerings.banners.linkLabelLabel')}</Label>
|
||||||
|
<Input id="banner-link-label" data-testid="banner-link-label" maxLength={50} {...register('linkLabel')} />
|
||||||
|
<FieldError message={errors.linkLabel?.message} testId="banner-link-label-error" />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="banner-link-url">{t('offerings.banners.linkUrlLabel')}</Label>
|
||||||
|
<Input
|
||||||
|
id="banner-link-url"
|
||||||
|
data-testid="banner-link-url"
|
||||||
|
maxLength={500}
|
||||||
|
placeholder="https://… of /pad"
|
||||||
|
{...register('linkUrl')}
|
||||||
|
/>
|
||||||
|
<FieldError message={errors.linkUrl?.message} testId="banner-link-url-error" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{t('offerings.banners.linkHint')}</p>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="banner-starts">{t('offerings.banners.startsLabel')}</Label>
|
||||||
|
<Input id="banner-starts" type="datetime-local" data-testid="banner-starts" {...register('startsAt')} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="banner-ends">{t('offerings.banners.endsLabel')}</Label>
|
||||||
|
<Input id="banner-ends" type="datetime-local" data-testid="banner-ends" {...register('endsAt')} />
|
||||||
|
<FieldError message={errors.endsAt?.message} testId="banner-ends-error" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{t('offerings.banners.scheduleHint')}</p>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
id="banner-active"
|
||||||
|
type="checkbox"
|
||||||
|
data-testid="banner-active"
|
||||||
|
className="size-4 rounded border-input"
|
||||||
|
{...register('isActive')}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="banner-active">{t('offerings.banners.activeLabel')}</Label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button type="button" variant="outline" onClick={onClose} data-testid="banner-cancel">
|
||||||
|
{t('common.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={save.isPending} data-testid="banner-submit">
|
||||||
|
{save.isPending ? '…' : t('common.save')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Megaphone, Pencil, Plus, Power, Trash2 } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { useOfferingBanners } from '../services/useOfferingBanners';
|
||||||
|
import { useDeleteOfferingBanner } from '../services/useDeleteOfferingBanner';
|
||||||
|
import { useSaveOfferingBanner } from '../services/useSaveOfferingBanner';
|
||||||
|
import { bannerStatus } from '../schemas/offeringBanner';
|
||||||
|
import { OfferingBannerDialog } from './OfferingBannerDialog';
|
||||||
|
import type { OfferingBannerDto } from '../services/types';
|
||||||
|
|
||||||
|
const fmt = (iso: string | null) =>
|
||||||
|
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
|
||||||
|
|
||||||
|
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
|
||||||
|
|
||||||
|
/** 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(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(
|
||||||
|
{
|
||||||
|
id: b.id,
|
||||||
|
body: {
|
||||||
|
position: b.position,
|
||||||
|
title: b.title,
|
||||||
|
text: b.text,
|
||||||
|
linkLabel: b.linkLabel,
|
||||||
|
linkUrl: b.linkUrl,
|
||||||
|
isActive: !b.isActive,
|
||||||
|
startsAt: b.startsAt,
|
||||||
|
endsAt: b.endsAt,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => toast.success(t('offerings.banners.savedToast')),
|
||||||
|
onError: () => toast.error(t('errors.generic')),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6" data-testid="banners-tab">
|
||||||
|
<p className="text-sm text-muted-foreground">{t('offerings.banners.intro')}</p>
|
||||||
|
|
||||||
|
{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 && (
|
||||||
|
<>
|
||||||
|
<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">
|
||||||
|
<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)}
|
||||||
|
>
|
||||||
|
<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}
|
||||||
|
creating={creating}
|
||||||
|
onClose={() => {
|
||||||
|
setEditing(null);
|
||||||
|
setCreating(false);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Dialog open={pendingDelete !== null} onOpenChange={(open) => { if (!open) setPendingDelete(null); }}>
|
||||||
|
<DialogContent className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t('offerings.banners.deleteTitle')}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<p className="text-sm text-muted-foreground" data-testid="banner-delete-message">
|
||||||
|
{t('offerings.banners.deleteMessage', { title: pendingDelete?.title || pendingDelete?.text || '' })}
|
||||||
|
</p>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setPendingDelete(null)} data-testid="banner-delete-cancel">
|
||||||
|
{t('common.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
disabled={remove.isPending}
|
||||||
|
data-testid="banner-delete-confirm"
|
||||||
|
onClick={() => {
|
||||||
|
if (!pendingDelete) return;
|
||||||
|
remove.mutate(pendingDelete.id, {
|
||||||
|
onSuccess: () => {
|
||||||
|
setPendingDelete(null);
|
||||||
|
toast.success(t('offerings.banners.deletedToast'));
|
||||||
|
},
|
||||||
|
onError: () => toast.error(t('errors.generic')),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{remove.isPending ? '…' : t('offerings.banners.deleteConfirm')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useForm, useWatch } from 'react-hook-form';
|
import { useForm, useWatch } from 'react-hook-form';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
@@ -7,17 +7,22 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { FieldError } from '@/components/ui/FieldError';
|
import { FieldError } from '@/components/ui/FieldError';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { useOfferingCategories } from '../services/useOfferingCategories';
|
||||||
import { slugifyPreview } from '@/lib/slugify';
|
import { slugifyPreview } from '@/lib/slugify';
|
||||||
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
|
import { offeringFormSchema, type OfferingFormData } from '../schemas/offering';
|
||||||
import type { OfferingAdminDto } from '../services/types';
|
import { toLocalInput } from '../schemas/offeringBanner';
|
||||||
|
import type { OfferingDto } from '../services/types';
|
||||||
|
|
||||||
interface OfferingFormProps {
|
interface OfferingFormProps {
|
||||||
initialValues?: OfferingAdminDto;
|
initialValues?: OfferingDto;
|
||||||
onSubmit: (values: OfferingFormData) => void;
|
onSubmit: (values: OfferingFormData) => void;
|
||||||
|
/** Leaves the form without saving (back to the list). */
|
||||||
|
onCancel: () => void;
|
||||||
isSubmitting: boolean;
|
isSubmitting: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OfferingForm({ initialValues, onSubmit, isSubmitting }: OfferingFormProps) {
|
export function OfferingForm({ initialValues, onSubmit, onCancel, isSubmitting }: OfferingFormProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
const {
|
const {
|
||||||
@@ -30,7 +35,14 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
|||||||
} = useForm<OfferingFormData>({
|
} = useForm<OfferingFormData>({
|
||||||
resolver: zodResolver(offeringFormSchema),
|
resolver: zodResolver(offeringFormSchema),
|
||||||
mode: 'onTouched',
|
mode: 'onTouched',
|
||||||
defaultValues: initialValues ?? {
|
defaultValues: initialValues
|
||||||
|
? {
|
||||||
|
...initialValues,
|
||||||
|
isActive: initialValues.isActive ?? true,
|
||||||
|
startsAt: toLocalInput(initialValues.startsAt ?? null),
|
||||||
|
endsAt: toLocalInput(initialValues.endsAt ?? null),
|
||||||
|
}
|
||||||
|
: {
|
||||||
title: '',
|
title: '',
|
||||||
description: '',
|
description: '',
|
||||||
price: '',
|
price: '',
|
||||||
@@ -39,9 +51,35 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
|||||||
ctaLabel: '',
|
ctaLabel: '',
|
||||||
featured: false,
|
featured: false,
|
||||||
slug: '',
|
slug: '',
|
||||||
|
categoryId: null,
|
||||||
|
isActive: true,
|
||||||
|
startsAt: '',
|
||||||
|
endsAt: '',
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Radix Select does not allow an empty value, so "no category" is the sentinel 'none' here
|
||||||
|
// and is mapped back to null for the form value.
|
||||||
|
const NO_CATEGORY = 'none';
|
||||||
|
const { data: categories, isFetching: isFetchingCategories } = useOfferingCategories();
|
||||||
|
const categoryId = useWatch({ control, name: 'categoryId' });
|
||||||
|
const selectedCategory =
|
||||||
|
categoryId != null && categories?.some((c) => c.id === categoryId) ? categoryId : NO_CATEGORY;
|
||||||
|
|
||||||
|
// A category that no longer exists (deleted meanwhile) falls back to "no category" so the
|
||||||
|
// form never submits an id the API would reject. Only judged on fresh data: a cached list
|
||||||
|
// that is being refetched may still be missing a category that does exist.
|
||||||
|
useEffect(() => {
|
||||||
|
if (
|
||||||
|
categories !== undefined &&
|
||||||
|
!isFetchingCategories &&
|
||||||
|
categoryId != null &&
|
||||||
|
!categories.some((c) => c.id === categoryId)
|
||||||
|
) {
|
||||||
|
setValue('categoryId', null);
|
||||||
|
}
|
||||||
|
}, [categories, isFetchingCategories, categoryId, setValue]);
|
||||||
|
|
||||||
// useFieldArray requires object-shaped array items — features is a plain string[],
|
// useFieldArray requires object-shaped array items — features is a plain string[],
|
||||||
// so add/remove are handled directly via setValue instead.
|
// so add/remove are handled directly via setValue instead.
|
||||||
const features = useWatch({ control, name: 'features' });
|
const features = useWatch({ control, name: 'features' });
|
||||||
@@ -177,6 +215,37 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="offering-category">{t('offerings.form.categoryLabel')}</Label>
|
||||||
|
<Select
|
||||||
|
value={selectedCategory}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
// Radix reports an empty value while its options are still loading (the
|
||||||
|
// chosen category is not in the list yet); that is not a user choice.
|
||||||
|
if (value === '') return;
|
||||||
|
setValue('categoryId', value === NO_CATEGORY ? null : value, { shouldDirty: true });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="offering-category" data-testid="offering-category">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={NO_CATEGORY} data-testid="offering-category-none">
|
||||||
|
{t('offerings.form.noCategory')}
|
||||||
|
</SelectItem>
|
||||||
|
{categories?.map((category) => (
|
||||||
|
<SelectItem
|
||||||
|
key={category.id}
|
||||||
|
value={category.id}
|
||||||
|
data-testid={`offering-category-option-${category.id}`}
|
||||||
|
>
|
||||||
|
{category.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>{t('offerings.form.featuresLabel')}</Label>
|
<Label>{t('offerings.form.featuresLabel')}</Label>
|
||||||
{features.map((_, index) => (
|
{features.map((_, index) => (
|
||||||
@@ -235,9 +304,45 @@ export function OfferingForm({ initialValues, onSubmit, isSubmitting }: Offering
|
|||||||
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
|
<Label htmlFor="offering-featured">{t('offerings.form.featuredLabel')}</Label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
|
<div className="space-y-3 rounded-md border p-3" data-testid="offering-schedule">
|
||||||
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
<div className="flex items-center gap-2">
|
||||||
</Button>
|
<input
|
||||||
|
id="offering-active"
|
||||||
|
type="checkbox"
|
||||||
|
data-testid="offering-active"
|
||||||
|
className="size-4 rounded border-input"
|
||||||
|
{...register('isActive')}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="offering-active">{t('offerings.form.activeLabel')}</Label>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="offering-starts">{t('offerings.form.startsLabel')}</Label>
|
||||||
|
<Input id="offering-starts" type="datetime-local" data-testid="offering-starts" {...register('startsAt')} />
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="offering-ends">{t('offerings.form.endsLabel')}</Label>
|
||||||
|
<Input
|
||||||
|
id="offering-ends"
|
||||||
|
type="datetime-local"
|
||||||
|
data-testid="offering-ends"
|
||||||
|
aria-invalid={errors.endsAt !== undefined}
|
||||||
|
{...register('endsAt')}
|
||||||
|
/>
|
||||||
|
{errors.endsAt && <FieldError message={t('offerings.form.endBeforeStart')} testId="offering-ends-error" />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{t('offerings.form.scheduleHint')}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||||
|
<Button type="button" variant="outline" onClick={onCancel} disabled={isSubmitting} data-testid="offering-form-cancel">
|
||||||
|
{t('common.cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={isSubmitting} data-testid="offering-form-submit">
|
||||||
|
{isSubmitting ? '…' : t('offerings.form.submitButton')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,23 @@
|
|||||||
import { useSortable } from '@dnd-kit/sortable';
|
import { useSortable } from '@dnd-kit/sortable';
|
||||||
import { CSS } from '@dnd-kit/utilities';
|
import { CSS } from '@dnd-kit/utilities';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Trash2 } from 'lucide-react';
|
import { GripVertical, Star, ChevronUp, ChevronDown, Pencil, Power, Trash2 } from 'lucide-react';
|
||||||
import { Link } from '@tanstack/react-router';
|
import { Link } from '@tanstack/react-router';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { TableCell, TableRow } from '@/components/ui/table';
|
import { TableCell, TableRow } from '@/components/ui/table';
|
||||||
import { useUpdateOffering } from '../services/useUpdateOffering';
|
import { useUpdateOffering } from '../services/useUpdateOffering';
|
||||||
import { useMoveOffering } from '../services/useMoveOffering';
|
import { useMoveOffering } from '../services/useMoveOffering';
|
||||||
import type { OfferingAdminDto } from '../services/types';
|
import { scheduleStatus } from '../schemas/offeringBanner';
|
||||||
|
import type { OfferingDto } from '../services/types';
|
||||||
|
|
||||||
|
const fmt = (iso: string | null) =>
|
||||||
|
iso ? new Date(iso).toLocaleString('nl-NL', { dateStyle: 'short', timeStyle: 'short' }) : null;
|
||||||
|
|
||||||
|
const statusVariant = { live: 'default', scheduled: 'secondary', expired: 'outline', off: 'outline' } as const;
|
||||||
|
|
||||||
interface OfferingRowProps {
|
interface OfferingRowProps {
|
||||||
offering: OfferingAdminDto;
|
offering: OfferingDto;
|
||||||
isFirst: boolean;
|
isFirst: boolean;
|
||||||
isLast: boolean;
|
isLast: boolean;
|
||||||
onDeleteRequested: () => void;
|
onDeleteRequested: () => void;
|
||||||
@@ -22,6 +29,26 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
|||||||
const updateOffering = useUpdateOffering();
|
const updateOffering = useUpdateOffering();
|
||||||
const moveUp = useMoveOffering('up');
|
const moveUp = useMoveOffering('up');
|
||||||
const moveDown = useMoveOffering('down');
|
const moveDown = useMoveOffering('down');
|
||||||
|
const status = scheduleStatus(offering);
|
||||||
|
|
||||||
|
// PUT replaces the whole offering: everything that is not changed has to be sent along, the
|
||||||
|
// switch and the schedule included, or a click on the star or the power button would reset them.
|
||||||
|
const fullBody = {
|
||||||
|
id: offering.id,
|
||||||
|
title: offering.title,
|
||||||
|
description: offering.description,
|
||||||
|
price: offering.price,
|
||||||
|
priceNote: offering.priceNote,
|
||||||
|
features: offering.features,
|
||||||
|
ctaLabel: offering.ctaLabel,
|
||||||
|
// Leaving the category out would clear it.
|
||||||
|
categoryId: offering.categoryId ?? null,
|
||||||
|
featured: offering.featured,
|
||||||
|
isActive: offering.isActive,
|
||||||
|
startsAt: offering.startsAt,
|
||||||
|
endsAt: offering.endsAt,
|
||||||
|
};
|
||||||
|
const toggleLabel = t(offering.isActive ? 'offerings.actions.turnOff' : 'offerings.actions.turnOn');
|
||||||
|
|
||||||
// The moving visual is rendered by <DragOverlay> instead (see OfferingsList) — a portal
|
// The moving visual is rendered by <DragOverlay> instead (see OfferingsList) — a portal
|
||||||
// outside the document flow, so it can't grow the page's scrollable area the way
|
// outside the document flow, so it can't grow the page's scrollable area the way
|
||||||
@@ -45,7 +72,27 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
|||||||
<GripVertical className="size-4" />
|
<GripVertical className="size-4" />
|
||||||
</button>
|
</button>
|
||||||
</TableCell>
|
</TableCell>
|
||||||
<TableCell>{offering.title}</TableCell>
|
<TableCell>
|
||||||
|
{offering.title}
|
||||||
|
{offering.category && (
|
||||||
|
<Badge variant="secondary" className="ml-2" data-testid={`offering-row-${offering.id}-category`}>
|
||||||
|
{offering.category}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
<div className="mt-1 flex flex-wrap items-center gap-2">
|
||||||
|
<Badge variant={statusVariant[status]} data-testid={`offering-row-${offering.id}-status`}>
|
||||||
|
{t(`offerings.banners.status.${status}`)}
|
||||||
|
</Badge>
|
||||||
|
{status === 'live' && (
|
||||||
|
<Badge data-testid={`offering-row-${offering.id}-shown`}>{t('offerings.banners.shownBadge')}</Badge>
|
||||||
|
)}
|
||||||
|
{(offering.startsAt || offering.endsAt) && (
|
||||||
|
<span className="text-xs text-muted-foreground" data-testid={`offering-row-${offering.id}-period`}>
|
||||||
|
{fmt(offering.startsAt) ?? '…'} – {fmt(offering.endsAt) ?? '…'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
<TableCell>{offering.price}</TableCell>
|
<TableCell>{offering.price}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<Button
|
<Button
|
||||||
@@ -53,18 +100,7 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
|||||||
size="icon"
|
size="icon"
|
||||||
data-testid={`offering-row-${offering.id}-featured-toggle`}
|
data-testid={`offering-row-${offering.id}-featured-toggle`}
|
||||||
aria-label={offering.featured ? t('offerings.actions.unmarkFeatured') : t('offerings.actions.markFeatured')}
|
aria-label={offering.featured ? t('offerings.actions.unmarkFeatured') : t('offerings.actions.markFeatured')}
|
||||||
onClick={() =>
|
onClick={() => updateOffering.mutate({ ...fullBody, featured: !offering.featured })}
|
||||||
updateOffering.mutate({
|
|
||||||
id: offering.id,
|
|
||||||
title: offering.title,
|
|
||||||
description: offering.description,
|
|
||||||
price: offering.price,
|
|
||||||
priceNote: offering.priceNote,
|
|
||||||
features: offering.features,
|
|
||||||
ctaLabel: offering.ctaLabel,
|
|
||||||
featured: !offering.featured,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<Star className={`size-4 ${offering.featured ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
<Star className={`size-4 ${offering.featured ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
||||||
</Button>
|
</Button>
|
||||||
@@ -91,6 +127,17 @@ export function OfferingRow({ offering, isFirst, isLast, onDeleteRequested }: Of
|
|||||||
>
|
>
|
||||||
<ChevronDown className="size-4" />
|
<ChevronDown className="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
data-testid={`offering-row-${offering.id}-toggle-active`}
|
||||||
|
aria-label={toggleLabel}
|
||||||
|
title={toggleLabel}
|
||||||
|
disabled={updateOffering.isPending}
|
||||||
|
onClick={() => updateOffering.mutate({ ...fullBody, isActive: !offering.isActive })}
|
||||||
|
>
|
||||||
|
<Power className={`size-4 ${offering.isActive ? '' : 'text-muted-foreground'}`} aria-hidden="true" />
|
||||||
|
</Button>
|
||||||
<Button variant="ghost" size="icon" asChild data-testid={`offering-row-${offering.id}-edit-link`}>
|
<Button variant="ghost" size="icon" asChild data-testid={`offering-row-${offering.id}-edit-link`}>
|
||||||
<Link to="/offerings/$id/edit" params={{ id: offering.id }} aria-label={t('offerings.actions.edit')}>
|
<Link to="/offerings/$id/edit" params={{ id: offering.id }} aria-label={t('offerings.actions.edit')}>
|
||||||
<Pencil className="size-4" />
|
<Pencil className="size-4" />
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ import { GripVertical } from 'lucide-react';
|
|||||||
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||||
import { OfferingRow } from './OfferingRow';
|
import { OfferingRow } from './OfferingRow';
|
||||||
import { useOfferingsDnd } from '../hooks/useOfferingsDnd';
|
import { useOfferingsDnd } from '../hooks/useOfferingsDnd';
|
||||||
import type { OfferingAdminDto } from '../services/types';
|
import type { OfferingDto } from '../services/types';
|
||||||
|
|
||||||
interface OfferingsListProps {
|
interface OfferingsListProps {
|
||||||
offerings: OfferingAdminDto[];
|
offerings: OfferingDto[];
|
||||||
onDeleteRequested: (offering: OfferingAdminDto) => void;
|
onDeleteRequested: (offering: OfferingDto) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function OfferingsList({ offerings, onDeleteRequested }: OfferingsListProps) {
|
export function OfferingsList({ offerings, onDeleteRequested }: OfferingsListProps) {
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ import {
|
|||||||
} from '@dnd-kit/core';
|
} from '@dnd-kit/core';
|
||||||
import { arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
|
import { arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
|
||||||
import { useReorderOfferings } from '../services/useReorderOfferings';
|
import { useReorderOfferings } from '../services/useReorderOfferings';
|
||||||
import type { OfferingAdminDto } from '../services/types';
|
import type { OfferingDto } from '../services/types';
|
||||||
|
|
||||||
export function useOfferingsDnd(offerings: OfferingAdminDto[]) {
|
export function useOfferingsDnd(offerings: OfferingDto[]) {
|
||||||
const [items, setItems] = useState(offerings);
|
const [items, setItems] = useState(offerings);
|
||||||
const [syncedOfferings, setSyncedOfferings] = useState(offerings);
|
const [syncedOfferings, setSyncedOfferings] = useState(offerings);
|
||||||
const [activeId, setActiveId] = useState<string | null>(null);
|
const [activeId, setActiveId] = useState<string | null>(null);
|
||||||
|
|||||||
@@ -1,5 +1,12 @@
|
|||||||
import { http, HttpResponse } from 'msw';
|
import { http, HttpResponse } from 'msw';
|
||||||
import type { OfferingAdminDto, CreateOfferingRequest, UpdateOfferingRequest } from '@/features/offerings/services/types';
|
import type {
|
||||||
|
OfferingDto,
|
||||||
|
OfferingCategoryDto,
|
||||||
|
OfferingBannerDto,
|
||||||
|
OfferingBannerRequest,
|
||||||
|
CreateOfferingRequest,
|
||||||
|
UpdateOfferingRequest,
|
||||||
|
} from '@/features/offerings/services/types';
|
||||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||||
|
|
||||||
function slugify(value: string): string {
|
function slugify(value: string): string {
|
||||||
@@ -11,7 +18,7 @@ function slugify(value: string): string {
|
|||||||
.replace(/^-+|-+$/g, '');
|
.replace(/^-+|-+$/g, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
const seed: OfferingAdminDto[] = [
|
const seed: OfferingDto[] = [
|
||||||
{
|
{
|
||||||
id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
|
||||||
slug: 'starter',
|
slug: 'starter',
|
||||||
@@ -23,6 +30,9 @@ const seed: OfferingAdminDto[] = [
|
|||||||
ctaLabel: 'Get started',
|
ctaLabel: 'Get started',
|
||||||
featured: false,
|
featured: false,
|
||||||
displayOrder: 0,
|
displayOrder: 0,
|
||||||
|
isActive: true,
|
||||||
|
startsAt: null,
|
||||||
|
endsAt: null,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
|
id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
|
||||||
@@ -35,25 +45,105 @@ const seed: OfferingAdminDto[] = [
|
|||||||
ctaLabel: 'Get started',
|
ctaLabel: 'Get started',
|
||||||
featured: true,
|
featured: true,
|
||||||
displayOrder: 1,
|
displayOrder: 1,
|
||||||
|
isActive: true,
|
||||||
|
startsAt: null,
|
||||||
|
endsAt: null,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
let mockOfferings: OfferingAdminDto[] = [...seed];
|
let mockOfferings: OfferingDto[] = [...seed];
|
||||||
|
|
||||||
|
/** Categories (id, name, sortOrder). Nothing is seeded, like the real system; tests add their own. */
|
||||||
|
type MockCategory = Omit<OfferingCategoryDto, 'offeringCount'>;
|
||||||
|
let mockCategories: MockCategory[] = [];
|
||||||
|
|
||||||
|
/** Banners; nothing is seeded. Handlers are registered before the /:id routes so 'banners' is not read as an id. */
|
||||||
|
let mockBanners: OfferingBannerDto[] = [];
|
||||||
|
export const getMockBanners = () => mockBanners;
|
||||||
|
export const setMockBanners = (banners: OfferingBannerDto[]) => {
|
||||||
|
mockBanners = [...banners];
|
||||||
|
};
|
||||||
|
|
||||||
export const resetMockOfferings = () => {
|
export const resetMockOfferings = () => {
|
||||||
|
mockBanners = [];
|
||||||
mockOfferings = [...seed];
|
mockOfferings = [...seed];
|
||||||
|
mockCategories = [];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getMockOfferings = () => mockOfferings;
|
export const getMockOfferings = () => mockOfferings;
|
||||||
|
|
||||||
|
export const setMockCategories = (categories: MockCategory[]) => {
|
||||||
|
mockCategories = [...categories];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Assigns categories to mock offerings (id -> category id) without going through the API. */
|
||||||
|
export const assignMockCategories = (assignments: Record<string, string>) => {
|
||||||
|
mockOfferings = mockOfferings.map((o) =>
|
||||||
|
assignments[o.id] !== undefined ? { ...o, categoryId: assignments[o.id] } : o,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const withCategoryName = (o: OfferingDto): OfferingDto => ({
|
||||||
|
...o,
|
||||||
|
categoryId: o.categoryId ?? null,
|
||||||
|
category: mockCategories.find((c) => c.id === o.categoryId)?.name ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const countFor = (categoryId: string) => mockOfferings.filter((o) => o.categoryId === categoryId).length;
|
||||||
|
|
||||||
|
const nameTaken = (name: string, exceptId?: string) =>
|
||||||
|
mockCategories.some((c) => c.id !== exceptId && c.name.toLowerCase() === name.toLowerCase());
|
||||||
|
|
||||||
export const offeringsHandlers = [
|
export const offeringsHandlers = [
|
||||||
http.get(`${API_BASE}/api/v1/offerings`, () =>
|
http.get(`${API_BASE}/api/v1/offerings/banners`, () => HttpResponse.json(mockBanners)),
|
||||||
HttpResponse.json(mockOfferings.map(({ displayOrder: _displayOrder, ...dto }) => dto)),
|
|
||||||
),
|
|
||||||
|
|
||||||
http.get(`${API_BASE}/api/v1/offerings/admin`, () => HttpResponse.json(mockOfferings)),
|
http.post(`${API_BASE}/api/v1/offerings/banners`, async ({ request }) => {
|
||||||
|
const body = (await request.json()) as OfferingBannerRequest;
|
||||||
|
const created: OfferingBannerDto = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
...body,
|
||||||
|
position: body.position ?? 'bottom',
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
mockBanners = [created, ...mockBanners];
|
||||||
|
return HttpResponse.json(created, { status: 201 });
|
||||||
|
}),
|
||||||
|
|
||||||
http.post(`${API_BASE}/api/v1/offerings/admin`, async ({ request }) => {
|
http.put(`${API_BASE}/api/v1/offerings/banners/:id`, async ({ params, request }) => {
|
||||||
|
const { id } = params as { id: string };
|
||||||
|
const existing = mockBanners.find((b) => b.id === id);
|
||||||
|
if (!existing) return new HttpResponse(null, { status: 404 });
|
||||||
|
const body = (await request.json()) as OfferingBannerRequest;
|
||||||
|
const updated: OfferingBannerDto = { ...existing, ...body, updatedAt: new Date().toISOString() };
|
||||||
|
mockBanners = mockBanners.map((b) => (b.id === id ? updated : b));
|
||||||
|
return HttpResponse.json(updated);
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.delete(`${API_BASE}/api/v1/offerings/banners/:id`, ({ params }) => {
|
||||||
|
const { id } = params as { id: string };
|
||||||
|
mockBanners = mockBanners.filter((b) => b.id !== id);
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
|
||||||
|
// The administrator list: everything, including switched-off, planned and expired offerings.
|
||||||
|
http.get(`${API_BASE}/api/v1/offerings/all`, () => HttpResponse.json(mockOfferings.map(withCategoryName))),
|
||||||
|
|
||||||
|
// The public list: only what is switched on and inside its schedule.
|
||||||
|
http.get(`${API_BASE}/api/v1/offerings`, () => {
|
||||||
|
const now = Date.now();
|
||||||
|
return HttpResponse.json(
|
||||||
|
mockOfferings
|
||||||
|
.filter(
|
||||||
|
(o) =>
|
||||||
|
o.isActive &&
|
||||||
|
(!o.startsAt || new Date(o.startsAt).getTime() <= now) &&
|
||||||
|
(!o.endsAt || now < new Date(o.endsAt).getTime()),
|
||||||
|
)
|
||||||
|
.map(withCategoryName),
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.post(`${API_BASE}/api/v1/offerings`, async ({ request }) => {
|
||||||
const body = (await request.json()) as CreateOfferingRequest;
|
const body = (await request.json()) as CreateOfferingRequest;
|
||||||
const slug = body.slug && body.slug.length > 0 ? slugify(body.slug) : slugify(body.title);
|
const slug = body.slug && body.slug.length > 0 ? slugify(body.slug) : slugify(body.title);
|
||||||
if (mockOfferings.some((o) => o.slug === slug)) {
|
if (mockOfferings.some((o) => o.slug === slug)) {
|
||||||
@@ -62,18 +152,80 @@ export const offeringsHandlers = [
|
|||||||
{ status: 409 },
|
{ status: 409 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (body.categoryId && !mockCategories.some((c) => c.id === body.categoryId)) {
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ status: 400, title: 'Invalid category', errors: { categoryId: ['invalid'] } },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const newOffering: OfferingAdminDto = {
|
const newOffering: OfferingDto = {
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
...body,
|
...body,
|
||||||
slug,
|
slug,
|
||||||
displayOrder: mockOfferings.length,
|
displayOrder: mockOfferings.length,
|
||||||
};
|
};
|
||||||
mockOfferings = [...mockOfferings, newOffering];
|
mockOfferings = [...mockOfferings, newOffering];
|
||||||
return HttpResponse.json(newOffering, { status: 201 });
|
return HttpResponse.json(withCategoryName(newOffering), { status: 201 });
|
||||||
}),
|
}),
|
||||||
|
|
||||||
http.put(`${API_BASE}/api/v1/offerings/admin/:id`, async ({ params, request }) => {
|
// Registered before the `:id` routes: `order` would otherwise be matched as an id.
|
||||||
|
http.put(`${API_BASE}/api/v1/offerings/order`, async ({ request }) => {
|
||||||
|
const body = (await request.json()) as { orderedIds: string[] };
|
||||||
|
mockOfferings = body.orderedIds
|
||||||
|
.map((id, index) => {
|
||||||
|
const offering = mockOfferings.find((o) => o.id === id);
|
||||||
|
return offering ? { ...offering, displayOrder: index } : null;
|
||||||
|
})
|
||||||
|
.filter((o): o is OfferingDto => o !== null);
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.get(`${API_BASE}/api/v1/offerings/categories`, () =>
|
||||||
|
HttpResponse.json(
|
||||||
|
[...mockCategories]
|
||||||
|
.sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))
|
||||||
|
.map((c) => ({ ...c, offeringCount: countFor(c.id) })),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
|
||||||
|
http.post(`${API_BASE}/api/v1/offerings/categories`, async ({ request }) => {
|
||||||
|
const { name } = (await request.json()) as { name: string };
|
||||||
|
if (nameTaken(name)) {
|
||||||
|
return HttpResponse.json({ status: 409, title: `A category named '${name}' already exists.` }, { status: 409 });
|
||||||
|
}
|
||||||
|
const created: MockCategory = { id: crypto.randomUUID(), name, sortOrder: mockCategories.length };
|
||||||
|
mockCategories = [...mockCategories, created];
|
||||||
|
return HttpResponse.json({ ...created, offeringCount: 0 }, { status: 201 });
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.put(`${API_BASE}/api/v1/offerings/categories/:id`, async ({ params, request }) => {
|
||||||
|
const { id } = params as { id: string };
|
||||||
|
const { name } = (await request.json()) as { name: string };
|
||||||
|
const existing = mockCategories.find((c) => c.id === id);
|
||||||
|
if (!existing) return new HttpResponse(null, { status: 404 });
|
||||||
|
if (nameTaken(name, id)) {
|
||||||
|
return HttpResponse.json({ status: 409, title: `A category named '${name}' already exists.` }, { status: 409 });
|
||||||
|
}
|
||||||
|
const renamed = { ...existing, name };
|
||||||
|
mockCategories = mockCategories.map((c) => (c.id === id ? renamed : c));
|
||||||
|
return HttpResponse.json({ ...renamed, offeringCount: countFor(id) });
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.delete(`${API_BASE}/api/v1/offerings/categories/:id`, ({ params }) => {
|
||||||
|
const { id } = params as { id: string };
|
||||||
|
if (!mockCategories.some((c) => c.id === id)) return new HttpResponse(null, { status: 404 });
|
||||||
|
if (countFor(id) > 0) {
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ status: 409, title: 'The category is still used by offering(s). Move them first.' },
|
||||||
|
{ status: 409 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
mockCategories = mockCategories.filter((c) => c.id !== id);
|
||||||
|
return new HttpResponse(null, { status: 204 });
|
||||||
|
}),
|
||||||
|
|
||||||
|
http.put(`${API_BASE}/api/v1/offerings/:id`, async ({ params, request }) => {
|
||||||
const { id } = params as { id: string };
|
const { id } = params as { id: string };
|
||||||
const body = (await request.json()) as UpdateOfferingRequest;
|
const body = (await request.json()) as UpdateOfferingRequest;
|
||||||
const existing = mockOfferings.find((o) => o.id === id);
|
const existing = mockOfferings.find((o) => o.id === id);
|
||||||
@@ -91,49 +243,27 @@ export const offeringsHandlers = [
|
|||||||
{ status: 409 },
|
{ status: 409 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (body.categoryId && !mockCategories.some((c) => c.id === body.categoryId)) {
|
||||||
|
return HttpResponse.json(
|
||||||
|
{ status: 400, title: 'Invalid category', errors: { categoryId: ['invalid'] } },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const updated: OfferingAdminDto = { ...existing, ...body, slug };
|
// PUT replaces the offering: an absent categoryId clears the category, as in the real API.
|
||||||
|
const updated: OfferingDto = {
|
||||||
|
...existing,
|
||||||
|
...body,
|
||||||
|
slug,
|
||||||
|
categoryId: body.categoryId ?? null,
|
||||||
|
};
|
||||||
mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o));
|
mockOfferings = mockOfferings.map((o) => (o.id === id ? updated : o));
|
||||||
return HttpResponse.json(updated);
|
return HttpResponse.json(withCategoryName(updated));
|
||||||
}),
|
}),
|
||||||
|
|
||||||
http.delete(`${API_BASE}/api/v1/offerings/admin/:id`, ({ params }) => {
|
http.delete(`${API_BASE}/api/v1/offerings/:id`, ({ params }) => {
|
||||||
const { id } = params as { id: string };
|
const { id } = params as { id: string };
|
||||||
mockOfferings = mockOfferings.filter((o) => o.id !== id);
|
mockOfferings = mockOfferings.filter((o) => o.id !== id);
|
||||||
return new HttpResponse(null, { status: 204 });
|
return new HttpResponse(null, { status: 204 });
|
||||||
}),
|
}),
|
||||||
|
|
||||||
http.put(`${API_BASE}/api/v1/offerings/admin/reorder`, async ({ request }) => {
|
|
||||||
const body = (await request.json()) as { orderedIds: string[] };
|
|
||||||
mockOfferings = body.orderedIds
|
|
||||||
.map((id, index) => {
|
|
||||||
const offering = mockOfferings.find((o) => o.id === id);
|
|
||||||
return offering ? { ...offering, displayOrder: index } : null;
|
|
||||||
})
|
|
||||||
.filter((o): o is OfferingAdminDto => o !== null);
|
|
||||||
return new HttpResponse(null, { status: 204 });
|
|
||||||
}),
|
|
||||||
|
|
||||||
http.post(`${API_BASE}/api/v1/offerings/admin/:id/move-up`, ({ params }) => {
|
|
||||||
const { id } = params as { id: string };
|
|
||||||
moveAdjacent(id, -1);
|
|
||||||
return new HttpResponse(null, { status: 204 });
|
|
||||||
}),
|
|
||||||
|
|
||||||
http.post(`${API_BASE}/api/v1/offerings/admin/:id/move-down`, ({ params }) => {
|
|
||||||
const { id } = params as { id: string };
|
|
||||||
moveAdjacent(id, 1);
|
|
||||||
return new HttpResponse(null, { status: 204 });
|
|
||||||
}),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
function moveAdjacent(id: string, delta: number) {
|
|
||||||
const sorted = [...mockOfferings].sort((a, b) => a.displayOrder - b.displayOrder);
|
|
||||||
const index = sorted.findIndex((o) => o.id === id);
|
|
||||||
const swapIndex = index + delta;
|
|
||||||
if (index === -1 || swapIndex < 0 || swapIndex >= sorted.length) return;
|
|
||||||
|
|
||||||
const a = sorted[index];
|
|
||||||
const b = sorted[swapIndex];
|
|
||||||
[a.displayOrder, b.displayOrder] = [b.displayOrder, a.displayOrder];
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
import { beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
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';
|
||||||
|
import {
|
||||||
|
bannerStatus,
|
||||||
|
fromLocalInput,
|
||||||
|
isAllowedBannerLink,
|
||||||
|
offeringBannerFormSchema,
|
||||||
|
toLocalInput,
|
||||||
|
} from '@/features/offerings/schemas/offeringBanner';
|
||||||
|
import type { OfferingBannerDto } from '@/features/offerings/services/types';
|
||||||
|
import { _resetSetupStatusCache } from '@/router';
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
_resetSetupStatusCache();
|
||||||
|
resetMockOfferings();
|
||||||
|
});
|
||||||
|
|
||||||
|
const T = { timeout: 10000 };
|
||||||
|
|
||||||
|
async function openBannerTab() {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await userEvent.click(await screen.findByTestId('offerings-tab-banner', {}, T));
|
||||||
|
}
|
||||||
|
|
||||||
|
const banner = (over: Partial<OfferingBannerDto> & { id: string }): OfferingBannerDto => ({
|
||||||
|
position: 'bottom',
|
||||||
|
title: 'Titel',
|
||||||
|
text: 'Tekst',
|
||||||
|
linkLabel: null,
|
||||||
|
linkUrl: null,
|
||||||
|
isActive: true,
|
||||||
|
startsAt: null,
|
||||||
|
endsAt: null,
|
||||||
|
updatedAt: '2026-01-01T00:00:00Z',
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Banner tab', () => {
|
||||||
|
it('switches between the offerings and the banner tab, hiding the add-offering actions on the banner tab', async () => {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
expect(await screen.findByTestId('offerings-add-button', {}, T)).toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('offerings-tab-banner'));
|
||||||
|
expect(await screen.findByTestId('banners-tab')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('offerings-tab-banner')).toHaveAttribute('aria-selected', 'true');
|
||||||
|
expect(screen.queryByTestId('offerings-add-button')).not.toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('offerings-add-fab')).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('offerings-tab-offerings'));
|
||||||
|
expect(await screen.findByTestId('offerings-add-button')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows one list with an empty state and a single add button', async () => {
|
||||||
|
await openBannerTab();
|
||||||
|
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 banner defaulting to location bottom, with a link and a schedule', async () => {
|
||||||
|
await openBannerTab();
|
||||||
|
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');
|
||||||
|
await userEvent.type(screen.getByTestId('banner-starts'), '2030-07-01T09:00');
|
||||||
|
await userEvent.type(screen.getByTestId('banner-ends'), '2030-07-31T23:00');
|
||||||
|
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(getMockBanners()).toHaveLength(1));
|
||||||
|
const saved = getMockBanners()[0];
|
||||||
|
expect(saved).toMatchObject({
|
||||||
|
position: 'bottom',
|
||||||
|
title: 'Zomeractie',
|
||||||
|
linkLabel: 'Bekijk',
|
||||||
|
linkUrl: '/privacy',
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
expect(saved.startsAt).toBe(fromLocalInput('2030-07-01T09:00'));
|
||||||
|
expect(await screen.findByText('Zomeractie')).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 at location bottom', async () => {
|
||||||
|
await openBannerTab();
|
||||||
|
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; the text limit follows the chosen location live', async () => {
|
||||||
|
await openBannerTab();
|
||||||
|
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(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));
|
||||||
|
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', {}, T));
|
||||||
|
await userEvent.type(await screen.findByTestId('banner-title'), 'X');
|
||||||
|
await userEvent.type(screen.getByTestId('banner-text'), 'Y');
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByTestId('banner-link-label'), 'Go');
|
||||||
|
await userEvent.type(screen.getByTestId('banner-link-url'), 'javascript:alert(1)');
|
||||||
|
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||||
|
expect(await screen.findByTestId('banner-link-url-error')).toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.clear(screen.getByTestId('banner-link-label'));
|
||||||
|
await userEvent.clear(screen.getByTestId('banner-link-url'));
|
||||||
|
await userEvent.type(screen.getByTestId('banner-link-url'), '/ok');
|
||||||
|
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||||
|
expect(await screen.findByTestId('banner-link-label-error')).toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.clear(screen.getByTestId('banner-link-url'));
|
||||||
|
await userEvent.type(screen.getByTestId('banner-starts'), '2030-07-31T09:00');
|
||||||
|
await userEvent.type(screen.getByTestId('banner-ends'), '2030-07-01T09:00');
|
||||||
|
await userEvent.click(screen.getByTestId('banner-submit'));
|
||||||
|
expect(await screen.findByTestId('banner-ends-error')).toBeInTheDocument();
|
||||||
|
expect(getMockBanners()).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists all banners in one list in API order with a location badge per row', async () => {
|
||||||
|
setMockBanners([
|
||||||
|
banner({ id: 'b-new', title: 'Nieuw', updatedAt: '2026-02-01T00:00:00Z' }),
|
||||||
|
banner({ id: 't1', position: 'top', title: '', text: 'Balktekst' }),
|
||||||
|
]);
|
||||||
|
await openBannerTab();
|
||||||
|
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('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-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('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/);
|
||||||
|
|
||||||
|
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.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: '', 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('Tekst');
|
||||||
|
await userEvent.click(screen.getByTestId('banner-delete-confirm'));
|
||||||
|
await waitFor(() => expect(getMockBanners()).toHaveLength(0));
|
||||||
|
expect(await screen.findByTestId('banners-empty')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('banner form schema', () => {
|
||||||
|
const base = {
|
||||||
|
position: 'bottom' as const,
|
||||||
|
title: 'T',
|
||||||
|
text: 'X',
|
||||||
|
linkLabel: '',
|
||||||
|
linkUrl: '',
|
||||||
|
isActive: true,
|
||||||
|
startsAt: '',
|
||||||
|
endsAt: '',
|
||||||
|
};
|
||||||
|
const fieldErrors = (v: object) => {
|
||||||
|
const r = offeringBannerFormSchema.safeParse(v);
|
||||||
|
return r.success ? [] : r.error.issues.map((i) => i.path[0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('bottom: title required, text up to 300', () => {
|
||||||
|
expect(fieldErrors(base)).toEqual([]);
|
||||||
|
expect(fieldErrors({ ...base, title: '' })).toContain('title');
|
||||||
|
expect(fieldErrors({ ...base, text: 'x'.repeat(300) })).toEqual([]);
|
||||||
|
expect(fieldErrors({ ...base, text: 'x'.repeat(301) })).toContain('text');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('top: title optional, text up to 120', () => {
|
||||||
|
const top = { ...base, position: 'top' as const, title: '' };
|
||||||
|
expect(fieldErrors(top)).toEqual([]);
|
||||||
|
expect(fieldErrors({ ...top, text: 'x'.repeat(120) })).toEqual([]);
|
||||||
|
expect(fieldErrors({ ...top, text: 'x'.repeat(121) })).toContain('text');
|
||||||
|
expect(fieldErrors({ ...top, text: '' })).toContain('text');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('banner helpers', () => {
|
||||||
|
it.each([
|
||||||
|
['https://slpsoftware.nl/actie', true],
|
||||||
|
['/aanbieding', true],
|
||||||
|
['/', true],
|
||||||
|
['http://x.nl', false],
|
||||||
|
['//evil.example', false],
|
||||||
|
['/\\evil', false],
|
||||||
|
['javascript:alert(1)', false],
|
||||||
|
['mailto:a@b.nl', false],
|
||||||
|
['actie', false],
|
||||||
|
['/with space', false],
|
||||||
|
])('link %s → %s', (url, ok) => {
|
||||||
|
expect(isAllowedBannerLink(url)).toBe(ok);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('derives the status from switch and schedule', () => {
|
||||||
|
const now = new Date('2026-11-12T12:00:00Z');
|
||||||
|
expect(bannerStatus({ isActive: false, startsAt: null, endsAt: null }, now)).toBe('off');
|
||||||
|
expect(bannerStatus({ isActive: true, startsAt: '2026-11-13T00:00:00Z', endsAt: null }, now)).toBe('scheduled');
|
||||||
|
expect(bannerStatus({ isActive: true, startsAt: null, endsAt: '2026-11-12T12:00:00Z' }, now)).toBe('expired');
|
||||||
|
expect(bannerStatus({ isActive: true, startsAt: '2026-11-01T00:00:00Z', endsAt: '2026-12-01T00:00:00Z' }, now)).toBe('live');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('round-trips datetime-local values', () => {
|
||||||
|
expect(toLocalInput(fromLocalInput('2030-07-01T09:00'))).toBe('2030-07-01T09:00');
|
||||||
|
expect(fromLocalInput('')).toBeNull();
|
||||||
|
expect(toLocalInput(null)).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { screen, waitFor, within } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { renderApp, mockAuthenticated } from '@/test/utils';
|
||||||
|
import { changeLanguage } from '@/i18n/config';
|
||||||
|
import {
|
||||||
|
assignMockCategories,
|
||||||
|
getMockOfferings,
|
||||||
|
resetMockOfferings,
|
||||||
|
setMockCategories,
|
||||||
|
} from '@/features/offerings/mocks/handlers';
|
||||||
|
import { categoryNameSchema } from '@/features/offerings/schemas/offering';
|
||||||
|
import { _resetSetupStatusCache } from '@/router';
|
||||||
|
|
||||||
|
const STARTER = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
|
||||||
|
const PRO = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
|
||||||
|
const WEBSITES = { id: 'c1', name: 'Websites', sortOrder: 0 };
|
||||||
|
const ONDERHOUD = { id: 'c2', name: 'Onderhoud', sortOrder: 1 };
|
||||||
|
const LONG = { timeout: 10000 };
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
_resetSetupStatusCache();
|
||||||
|
resetMockOfferings();
|
||||||
|
await changeLanguage('nl');
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await changeLanguage('en');
|
||||||
|
});
|
||||||
|
|
||||||
|
async function openDialog() {
|
||||||
|
await userEvent.click(await screen.findByTestId('offerings-categories-button', {}, LONG));
|
||||||
|
return screen.findByTestId('categories-dialog');
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('categories dialog', () => {
|
||||||
|
it('opens from the list page without leaving it and shows the empty state', async () => {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
expect(screen.getByTestId('categories-empty')).toHaveTextContent(
|
||||||
|
'Nog geen categorieën. Voeg de eerste toe.',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('offerings-title')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists the categories with the number of offerings in each', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
assignMockCategories({ [STARTER]: 'c1', [PRO]: 'c1' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Websites');
|
||||||
|
expect(screen.getByTestId('category-count-c1')).toHaveTextContent('2 aanbiedingen');
|
||||||
|
expect(screen.getByTestId('category-count-c2')).toHaveTextContent('0 aanbiedingen');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds a category', async () => {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.type(await screen.findByTestId('category-new-input'), 'Websites');
|
||||||
|
await userEvent.click(screen.getByTestId('category-add-button'));
|
||||||
|
|
||||||
|
expect(await screen.findByText('Websites')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('category-new-input')).toHaveValue('');
|
||||||
|
expect(screen.queryByTestId('categories-empty')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a blank name before calling the API', async () => {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.type(await screen.findByTestId('category-new-input'), ' ');
|
||||||
|
await userEvent.click(screen.getByTestId('category-add-button'));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('categories-error')).toHaveTextContent('Vul een naam in.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows a Dutch message when the name is already taken', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.type(await screen.findByTestId('category-new-input'), 'websites');
|
||||||
|
await userEvent.click(screen.getByTestId('category-add-button'));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
|
||||||
|
"Er bestaat al een categorie met de naam 'websites'.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renames a category with Enter', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('category-edit-c1'));
|
||||||
|
const input = screen.getByTestId('category-edit-input-c1');
|
||||||
|
await userEvent.clear(input);
|
||||||
|
await userEvent.type(input, 'Webdesign{Enter}');
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Webdesign');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cancels a rename with Escape without closing the dialog', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('category-edit-c1'));
|
||||||
|
await userEvent.type(screen.getByTestId('category-edit-input-c1'), 'xyz{Escape}');
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('category-name-c1')).toHaveTextContent('Websites');
|
||||||
|
expect(screen.getByTestId('categories-dialog')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the duplicate-name message when renaming to an existing name', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('category-edit-c2'));
|
||||||
|
const input = screen.getByTestId('category-edit-input-c2');
|
||||||
|
await userEvent.clear(input);
|
||||||
|
await userEvent.type(input, 'websites{Enter}');
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
|
||||||
|
"Er bestaat al een categorie met de naam 'websites'.",
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('category-edit-input-c2')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deletes an unused category after confirmation', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('category-delete-c2'));
|
||||||
|
await userEvent.click(screen.getByTestId('category-delete-confirm-c2'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.queryByTestId('category-row-c2')).not.toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('category-row-c1')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('explains in Dutch why a category in use cannot be deleted and keeps it', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
assignMockCategories({ [STARTER]: 'c1' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
await openDialog();
|
||||||
|
|
||||||
|
await userEvent.click(await screen.findByTestId('category-delete-c1'));
|
||||||
|
await userEvent.click(screen.getByTestId('category-delete-confirm-c1'));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('categories-error')).toHaveTextContent(
|
||||||
|
'Deze categorie wordt nog gebruikt door 1 aanbieding(en). Verplaats die eerst naar een andere categorie.',
|
||||||
|
);
|
||||||
|
expect(screen.getByTestId('category-row-c1')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('category on the offerings list', () => {
|
||||||
|
it('shows the category as a badge and a rename appears in the list without a reload', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
assignMockCategories({ [STARTER]: 'c1' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByTestId(`offering-row-${STARTER}-category`, {}, LONG),
|
||||||
|
).toHaveTextContent('Websites');
|
||||||
|
expect(screen.queryByTestId(`offering-row-${PRO}-category`)).not.toBeInTheDocument();
|
||||||
|
|
||||||
|
await openDialog();
|
||||||
|
await userEvent.click(await screen.findByTestId('category-edit-c1'));
|
||||||
|
const input = screen.getByTestId('category-edit-input-c1');
|
||||||
|
await userEvent.clear(input);
|
||||||
|
await userEvent.type(input, 'Webdesign{Enter}');
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByTestId(`offering-row-${STARTER}-category`)).toHaveTextContent(
|
||||||
|
'Webdesign',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the category when an offering is marked as featured from the list', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
assignMockCategories({ [STARTER]: 'c1' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings');
|
||||||
|
|
||||||
|
await userEvent.click(
|
||||||
|
await screen.findByTestId(`offering-row-${STARTER}-featured-toggle`, {}, LONG),
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockOfferings().find((o) => o.id === STARTER)?.featured).toBe(true),
|
||||||
|
);
|
||||||
|
expect(getMockOfferings().find((o) => o.id === STARTER)?.categoryId).toBe('c1');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('category select in the offering form', () => {
|
||||||
|
async function fillRequiredFields() {
|
||||||
|
await userEvent.type(await screen.findByTestId('offering-title', {}, LONG), 'Nieuw');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-description'), 'Omschrijving');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-price'), '€ 100');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-price-note'), 'eenmalig');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-feature-0'), 'Kenmerk');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-cta-label'), 'Start');
|
||||||
|
}
|
||||||
|
|
||||||
|
it('offers "Geen categorie" first and then the categories', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings/new');
|
||||||
|
|
||||||
|
const trigger = await screen.findByTestId('offering-category', {}, LONG);
|
||||||
|
expect(trigger).toHaveTextContent('Geen categorie');
|
||||||
|
await userEvent.click(trigger);
|
||||||
|
|
||||||
|
const listbox = await screen.findByRole('listbox');
|
||||||
|
const options = within(listbox)
|
||||||
|
.getAllByRole('option')
|
||||||
|
.map((o) => o.textContent);
|
||||||
|
expect(options).toEqual(['Geen categorie', 'Websites', 'Onderhoud']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends the chosen categoryId when creating', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings/new');
|
||||||
|
|
||||||
|
await fillRequiredFields();
|
||||||
|
await userEvent.click(screen.getByTestId('offering-category'));
|
||||||
|
await userEvent.click(await screen.findByTestId('offering-category-option-c2'));
|
||||||
|
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(getMockOfferings().some((o) => o.title === 'Nieuw')).toBe(true));
|
||||||
|
expect(getMockOfferings().find((o) => o.title === 'Nieuw')?.categoryId).toBe('c2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends null when no category is chosen', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings/new');
|
||||||
|
|
||||||
|
await fillRequiredFields();
|
||||||
|
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||||
|
|
||||||
|
await waitFor(() => expect(getMockOfferings().some((o) => o.title === 'Nieuw')).toBe(true));
|
||||||
|
expect(getMockOfferings().find((o) => o.title === 'Nieuw')?.categoryId ?? null).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preselects the current category when editing', async () => {
|
||||||
|
setMockCategories([WEBSITES, ONDERHOUD]);
|
||||||
|
assignMockCategories({ [STARTER]: 'c2' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp(`/offerings/${STARTER}/edit`);
|
||||||
|
|
||||||
|
const trigger = await screen.findByTestId('offering-category', {}, LONG);
|
||||||
|
await waitFor(() => expect(trigger).toHaveTextContent('Onderhoud'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to "Geen categorie" for a category that no longer exists and saves it as none', async () => {
|
||||||
|
setMockCategories([WEBSITES]);
|
||||||
|
assignMockCategories({ [STARTER]: 'verdwenen' });
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp(`/offerings/${STARTER}/edit`);
|
||||||
|
|
||||||
|
const trigger = await screen.findByTestId('offering-category', {}, LONG);
|
||||||
|
await waitFor(() => expect(trigger).toHaveTextContent('Geen categorie'));
|
||||||
|
|
||||||
|
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(getMockOfferings().find((o) => o.id === STARTER)?.categoryId).toBeNull(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('categoryNameSchema', () => {
|
||||||
|
it('accepts 1 to 100 characters and rejects empty or longer names', () => {
|
||||||
|
expect(categoryNameSchema.safeParse('a').success).toBe(true);
|
||||||
|
expect(categoryNameSchema.safeParse('a'.repeat(100)).success).toBe(true);
|
||||||
|
expect(categoryNameSchema.safeParse('').success).toBe(false);
|
||||||
|
expect(categoryNameSchema.safeParse('a'.repeat(101)).success).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -30,6 +30,24 @@ describe('OfferingFormPage', () => {
|
|||||||
expect(screen.getByText('Enterprise')).toBeInTheDocument();
|
expect(screen.getByText('Enterprise')).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('saves an offering without description and price note', async () => {
|
||||||
|
mockAuthenticated();
|
||||||
|
renderApp('/offerings/new');
|
||||||
|
|
||||||
|
await screen.findByTestId('offering-form-submit', {}, { timeout: 10000 });
|
||||||
|
expect(screen.getByLabelText(/optioneel|optional/i, { selector: '#offering-description' })).toBeInTheDocument();
|
||||||
|
|
||||||
|
await userEvent.type(screen.getByTestId('offering-title'), 'Gezin');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-price'), '€ 175');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-feature-0'), '1 uur fotografie');
|
||||||
|
await userEvent.type(screen.getByTestId('offering-cta-label'), 'Boek');
|
||||||
|
await userEvent.click(screen.getByTestId('offering-form-submit'));
|
||||||
|
|
||||||
|
expect(await screen.findByTestId('offerings-title', {}, { timeout: 10000 })).toBeInTheDocument();
|
||||||
|
expect(screen.getByText('Gezin')).toBeInTheDocument();
|
||||||
|
expect(screen.queryByTestId('offering-description-error')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it('shows a validation error when required fields are missing', async () => {
|
it('shows a validation error when required fields are missing', async () => {
|
||||||
mockAuthenticated();
|
mockAuthenticated();
|
||||||
renderApp('/offerings/new');
|
renderApp('/offerings/new');
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { useCreateOffering } from '../services/useCreateOffering';
|
|||||||
import { useUpdateOffering } from '../services/useUpdateOffering';
|
import { useUpdateOffering } from '../services/useUpdateOffering';
|
||||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||||
import type { OfferingFormData } from '../schemas/offering';
|
import type { OfferingFormData } from '../schemas/offering';
|
||||||
|
import { fromLocalInput } from '../schemas/offeringBanner';
|
||||||
|
|
||||||
export function OfferingFormPage() {
|
export function OfferingFormPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -25,11 +26,12 @@ export function OfferingFormPage() {
|
|||||||
|
|
||||||
const onSubmit = async (values: OfferingFormData) => {
|
const onSubmit = async (values: OfferingFormData) => {
|
||||||
setServerError(null);
|
setServerError(null);
|
||||||
|
const body = { ...values, startsAt: fromLocalInput(values.startsAt), endsAt: fromLocalInput(values.endsAt) };
|
||||||
try {
|
try {
|
||||||
if (isEdit && id !== undefined) {
|
if (isEdit && id !== undefined) {
|
||||||
await updateOffering.mutateAsync({ id, ...values });
|
await updateOffering.mutateAsync({ id, ...body });
|
||||||
} else {
|
} else {
|
||||||
await createOffering.mutateAsync(values);
|
await createOffering.mutateAsync(body);
|
||||||
}
|
}
|
||||||
toast.success(t('offerings.form.successToast'));
|
toast.success(t('offerings.form.successToast'));
|
||||||
navigate({ to: '/offerings' });
|
navigate({ to: '/offerings' });
|
||||||
@@ -61,7 +63,12 @@ export function OfferingFormPage() {
|
|||||||
onDismiss={() => setServerError(null)}
|
onDismiss={() => setServerError(null)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<OfferingForm initialValues={existingOffering} onSubmit={onSubmit} isSubmitting={isSubmitting} />
|
<OfferingForm
|
||||||
|
initialValues={existingOffering}
|
||||||
|
onSubmit={onSubmit}
|
||||||
|
onCancel={() => navigate({ to: '/offerings' })}
|
||||||
|
isSubmitting={isSubmitting}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user