From 47fcaeb0a1a46b07c32ab680ccee11fd0ddbc3c4 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 14:44:37 +0100 Subject: [PATCH] Hero-module: Application Design (componenten, methoden, services, afhankelijkheden); antwoorden van Bryan verwerkt Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 8 +- aidlc-docs/features/hero-module/audit.md | 12 ++ .../application-design/application-design.md | 55 ++++++++ .../component-dependency.md | 70 ++++++++++ .../application-design/component-methods.md | 125 ++++++++++++++++++ .../application-design/components.md | 76 +++++++++++ .../inception/application-design/services.md | 98 ++++++++++++++ .../plans/application-design-plan.md | 26 ++-- .../inception/requirements/requirements.md | 10 +- 9 files changed, 458 insertions(+), 22 deletions(-) create mode 100644 aidlc-docs/features/hero-module/inception/application-design/application-design.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/component-dependency.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/component-methods.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/components.md create mode 100644 aidlc-docs/features/hero-module/inception/application-design/services.md diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 7c659fe..7fc5543 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -5,7 +5,7 @@ - **Feature Slug**: hero-module - **Project Type**: Brownfield - **Start Date**: 2026-11-16 -- **Current Stage**: INCEPTION - Workflow Planning (execution plan written, waiting for approval) +- **Current Stage**: INCEPTION - Application Design (artifacts written, waiting for approval) - **Branch**: feature/hero-module (worktree K:\Development\Projects\SlpModularCms-contact-forms, from master b2cacfe) ## Workspace State @@ -45,14 +45,14 @@ - [x] Reverse Engineering (skipped: targeted review) - [x] Requirements Analysis (approved by Bryan 2026-11-16) - [x] User Stories (SKIP: one persona, acceptance criteria in the requirements) -- [x] Workflow Planning (execution-plan.md, awaiting approval) -- [ ] Application Design - EXECUTE +- [x] Workflow Planning (approved by Bryan 2026-11-16) +- [x] Application Design (artifacts in inception/application-design/, awaiting approval) - [ ] Units Generation - EXECUTE ### 🟢 CONSTRUCTION PHASE - [ ] Functional Design - EXECUTE - [ ] NFR Requirements - EXECUTE - [ ] NFR Design - EXECUTE -- [ ] Infrastructure Design - CONDITIONAL (only if storage is a shared directory) +- [ ] Infrastructure Design - EXECUTE for the media unit (storage is a directory outside the release) - [ ] Code Generation - EXECUTE (per unit H0 to H6) - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE diff --git a/aidlc-docs/features/hero-module/audit.md b/aidlc-docs/features/hero-module/audit.md index 178458d..1700e7f 100644 --- a/aidlc-docs/features/hero-module/audit.md +++ b/aidlc-docs/features/hero-module/audit.md @@ -83,3 +83,15 @@ **Context**: Application Design, waiting for answers. --- + +## Answers to the design questions; Application Design artifacts + +**Timestamp**: 2026-11-16T00:00:00Z + +**User Input**: "Bryans antwoorden op de 6 ontwerpvragen (2026-11-16). 1. Opslag: een MAP buiten de release (niet de database) ... Zet opslag achter een eigen koppeling zodat database-opslag later kan ... 2. Formaten: Bryan wil dat de uploader zoveel mogelijk invoerformaten ondersteunt ... Welke uitvoerformaten ... mag het systeem zelf bepalen ... 3. Datablok ... Optie 1: Core-koppeling ... 4. Mediadienst: algemeen in Core. 5. Crop-UI: eigen lichte component. 6. Focus: standaard het MIDDEN voor alle verhoudingen; maar er moet per verhouding (mobiel/tall) een apart focuspunt ingesteld kunnen worden (optioneel, valt anders terug op het algemene punt/midden). Werk het ontwerp daarop bij en ga door." (relayed by SLP Software - SLS - Main). Also: "H0 is gemerged: PR #16, merge-commit 0824bfa op master." + +**AI Response**: Recorded the answers in the plan, widened the requirements (input formats, focus per ratio, storage), wrote components.md, component-methods.md, services.md, component-dependency.md and application-design.md. Infrastructure Design now executes for the media unit. + +**Context**: Application Design complete; waiting for approval. + +--- diff --git a/aidlc-docs/features/hero-module/inception/application-design/application-design.md b/aidlc-docs/features/hero-module/inception/application-design/application-design.md new file mode 100644 index 0000000..1cf5696 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/application-design.md @@ -0,0 +1,55 @@ +# Application Design: hero-module (consolidated) + +Details: [components.md](components.md), [component-methods.md](component-methods.md), [services.md](services.md), [component-dependency.md](component-dependency.md). Inputs: `requirements.md`, `site-contract-agreed-with-asf.md`, answers to `application-design-plan.md` (2026-11-16). + +## Decisions + +| # | Decision | Source | +|---|---|---| +| D1 | One module `SlpModularCms.Modules.Hero` (own DbContext, migrations, texts); on or off per site | Q14 (requirements) | +| D2 | A general media service in `Core.Media`: storage interface, image processor interface, upload guard, pure `FocusMath` and `VariantPlanner`, address scheme, media endpoint. Usable later for a gallery | Design Q4 = B | +| D3 | Images are stored in a **directory outside the release** behind `IMediaStore`; a database store can follow if the hosting requires it. Risk R1 recorded; Bryan tests write access on the ASF hosting and is asked again if it fails | Design Q1 = B | +| D4 | Input formats: as many as the library can decode (jpg/jpeg, png, webp always; gif, bmp, tiff, heic/avif where possible), real-signature check, metadata stripped, animation reduced to the first frame; output chosen by the system per platform (WebP required, AVIF when possible) | Design Q2 | +| D5 | `#cms-data` is composed by a Core `CmsDataBlockTransform` from `ICmsDataBlockContributor`s; Offerings becomes a contributor with byte-identical output; the Hero adds `hero` | Design Q3 = A | +| D6 | Crop model B: the host cuts `wide` (3:2) and `tall` (4:5) variants around the focus point and zoom. The focus defaults to the centre for all ratios; a separate focus (and zoom) per ratio is optional and falls back on the general one | Design Q6, contract | +| D7 | The admin focus editor is an own light component (draggable point, zoom, live `wide` and `tall` previews using a TypeScript twin of `FocusMath` with shared test vectors) | Design Q5 = A | +| D8 | Public contract: `GET /api/v1/hero` (204 = none), the same shape under `hero` in `#cms-data`; markers `CMS:HERO-HTML` (region with the first slide as ``) and `CMS:HERO-PRELOAD` (one or two preload links with `media`, byte-equal to the ``/`` attributes); addresses `/media/hero//-.`, immutable | Contract with ASF | +| D9 | One renderer (`HeroPictureRenderer`) produces both the region attributes and the preload attributes; one read model (`PublicHeroService`) feeds the API, the region, the preload and the data block | LCP requirement | +| D10 | Fail-open for page injection, fail-closed for uploads | Requirements, SECURITY-15 | +| D11 | Language: the hero row carries a `Language` (default `nl`, unique), so adding a language needs no migration of existing rows; only one is exposed and edited now | Q9 | + +## Architecture overview + +```mermaid +flowchart LR + Admin["Admin (Hero screen)"] --> Hero["Modules.Hero"] + Hero --> Media["Core.Media
(store, processor, guard, endpoint)"] + Hero --> Inj["Core.Hosting.Website
(transforms, data block, cache)"] + Off["Modules.Offerings"] --> Inj + Inj --> Pages["Website pages (SLS, ASF)"] + Media --> Pages + Dir[("Media directory
outside the release")] --- Media + Db[("MariaDB")] --- Hero + classDef new fill:#FFA726,stroke:#E65100,color:#000; + classDef chg fill:#BBDEFB,stroke:#1565C0,color:#000; + classDef ext fill:#C8E6C9,stroke:#2E7D32,color:#000; + class Hero,Media new; + class Inj,Off,Admin chg; + class Pages,Dir,Db ext; +``` + +Text alternative: the new Hero module and Core.Media (orange) work with the changed injection layer and Offerings (blue); media files live in a directory outside the release and metadata in the database; pages get the hero injected. + +## Open items carried to the next stages + +| Item | Stage | +|---|---| +| Choice and proof of the image library (win-x64, linux-arm64, formats, AVIF, licence), limits (pixels, memory, parallelism, timeouts), budgets for LCP and weight, maximum slides, grace period for old sets | NFR Requirements and NFR Design | +| Whether deleting an image used by a slide refuses or detaches; exact validation messages; byte-exact HTML of the region | Functional Design | +| Write permission of the directory on MijnHostingPartner (IIS) and the backup of the directory | Bryan with ASF; Infrastructure Design (storage is a directory, so this stage now executes for the media unit) | +| Golden files for `` and the preload; focus estimates for the 8 photos | ASF session | +| SLS rendering of the three-line title and its screen-reader text | SLS session | + +## Units (confirmed from the execution plan, adjusted) + +H0 (done, PR #16 merged, 0824bfa) · H1 image pipeline (`Core.Media` processor, guard, `FocusMath`, `VariantPlanner`) · H2 Hero module backend · H3 media store, endpoint, address scheme · H4 injection (data block contributor and Offerings change, region, preload, golden files) · H5 admin frontend · H6 seed, docs, smoke test. Infrastructure Design is now needed for H3 (directory storage). diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md new file mode 100644 index 0000000..7dfd2fe --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-dependency.md @@ -0,0 +1,70 @@ +# Component dependencies: hero-module + +## Dependency matrix + +Rows depend on columns (X = direct use). + +| | Core.Media | Core.Hosting.Website | Core.Texts | Modules.Hero | Modules.Offerings | Frontend admin | +|---|---|---|---|---|---|---| +| **Modules.Hero** | X (store, processor, guard, paths, math) | X (`IHtmlPageTransform`, `IIndexHtmlMarkerProvider`, `ICmsDataBlockContributor`, `IIndexHtmlCache`) | X | n/a | none | none | +| **Modules.Offerings** | none | X (adds `OfferingsDataContributor`; loses the data block write) | X | none | n/a | none | +| **Core.Media** | n/a | none (endpoint is mapped by the host) | none | none (knows no module) | none | none | +| **Core.Hosting.Website** | none | n/a | none | none | none | none | +| **Frontend admin** | none | none | none | HTTP only (OpenAPI) | HTTP only | n/a | +| **Api / site projects** | X (host registers the media endpoint and options) | X | X | X (project reference) | X | n/a | + +Rules: Core never references a module; the Hero module never references the Offerings module (the data block is composed through the Core contributor interface, so no module knows another). + +## Data flow + +```mermaid +flowchart TD + Admin["Admin browser
(HeroPage, FocusEditor)"] -->|"multipart upload, JSON"| HeroCtl["Hero controllers"] + HeroCtl --> HeroSvc["HeroService / HeroImageService"] + HeroSvc --> Guard["MediaUploadGuard"] + HeroSvc --> Proc["ImageProcessor (library)"] + HeroSvc --> Store["MediaStore (directory)"] + HeroSvc --> Db[("Hero tables
MariaDB")] + HeroSvc --> Cache["IIndexHtmlCache"] + Db --> PubSvc["PublicHeroService"] + PubSvc --> PubApi["GET /api/v1/hero"] + PubSvc --> Tr["Hero transform, preload, data contributor"] + Tr --> Inj["HtmlMarkerInjector"] + Inj --> Page["Website page
(first HTML)"] + Store --> MediaEp["GET /media/..."] + Page -->|"img, picture, preload"| MediaEp + Site["Website (SLS, ASF)"] -->|"refresh after load"| PubApi + Page --> Site + classDef user fill:#f6e05e,stroke:#c05621,color:#000; + classDef host fill:#63b3ed,stroke:#2b6cb0,color:#000; + classDef data fill:#9ae6b4,stroke:#2f855a,color:#000; + classDef ext fill:#CE93D8,stroke:#6A1B9A,color:#000; + class Admin user; + class HeroCtl,HeroSvc,Guard,Proc,PubSvc,PubApi,Tr,Inj,MediaEp,Cache host; + class Store,Db data; + class Page,Site ext; +``` + +Text alternative: the admin uploads through the Hero services into the media directory and the database; the public read model feeds the public endpoint and the page injection; the browser loads images from the media endpoint and the site refreshes from the public endpoint. + +## Communication patterns + +| From to | Pattern | +|---|---| +| Admin to host | REST over HTTPS, cookie/JWT as the other admin screens; multipart for the image | +| Host internal | Dependency injection; services scoped, `IMediaStore` and `IImageProcessor` singletons (stateless, thread-safe) | +| Page build | The injector (singleton with scoped providers) asks transforms in registration order; the data block contributor order fixes the key order | +| Site to host | Anonymous GET of `/api/v1/hero` and `/media/...`; ETag and 304 for pages and media | +| Change notification | Direct call `IIndexHtmlCache.Invalidate()` after commit | + +## Risks and consequences of the design choices + +| # | Risk or consequence | Mitigation | +|---|---|---| +| R1 | **Storage in a directory** (Bryan's choice): the directory must survive a deploy, be in the backup and be writable. Pi: place it in the `shared` directory next to `releases/current` and set `Media__Directory`; IIS (MijnHostingPartner, ASF production): write permission is unknown | The store sits behind `IMediaStore`, so a database store can be added without touching the Hero module. Bryan tests directory write access with ASF; if it fails Bryan is asked again. Startup check: the host logs an error and the hero admin upload is refused (public reads unaffected) when the directory is not writable. Backup: add the directory to the host's back-up script and to the release checklist | +| R2 | Image library: AVIF encoder and native binaries on win-x64 and linux-arm64, licence | Proof in NFR Requirements; processing behind `IImageProcessor`; WebP is the required output, AVIF optional | +| R3 | Wide input list (gif, bmp, tiff, heic/avif) enlarges the attack surface and the library requirements | Allow-list by real signature; decode only through the library inside the guard (pixel, memory and time limits); formats the platform cannot decode are reported as unsupported in the admin; animated input is reduced to the first frame | +| R4 | Two writers of `#cms-data` would conflict | Solved by the Core contributor; the Offerings output stays byte-identical (golden files prove it) | +| R5 | Variant addresses change when the focus changes; an old page cached by a site may point to removed files | Old set kept for a grace period after a change; sites refresh from the API after load | +| R6 | LCP regression if preload and `` differ | One renderer for both, golden-tested with the ASF files | +| R7 | Two preload links (portrait, landscape) double the first request when a browser ignores `media` on preload | Verified in the LCP measurement on both test hosts | diff --git a/aidlc-docs/features/hero-module/inception/application-design/component-methods.md b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md new file mode 100644 index 0000000..c83c9e7 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/component-methods.md @@ -0,0 +1,125 @@ +# Component methods: hero-module + +Signatures and purposes only; business rules are detailed in Functional Design per unit. Types are C# sketches. + +## Core.Media + +```csharp +public interface IMediaStore +{ + Task PutAsync(string key, Stream content, string contentType, CancellationToken ct); + Task OpenReadAsync(string key, CancellationToken ct); // null = not found; MediaFile has Stream, ContentType, Length, LastWriteTime + Task ExistsAsync(string key, CancellationToken ct); + Task DeleteAsync(string key, CancellationToken ct); + Task DeletePrefixAsync(string prefix, CancellationToken ct); // removes every file below an area/hash directory +} + +public interface IImageProcessor +{ + // Real format, pixel size and frame count; throws ImageRejectedException (reason code) for anything unsafe or unsupported. + Task InspectAsync(Stream source, CancellationToken ct); + + // Decode (orientation applied), crop around the focus for a ratio, resize without upscaling, strip metadata, encode. + Task RenderAsync(Stream source, RenderRequest request, CancellationToken ct); + + IReadOnlySet SupportedInput { get; } + IReadOnlySet SupportedOutput { get; } // WebP always; AVIF when the platform can +} + +public sealed record RenderRequest(Ratio Ratio, int Width, ImageFormat Format, int Quality, FocusSetting Focus); +public sealed record FocusSetting(double X, double Y, double Zoom); // 0..1, 0..1, >= 1; default (0.5, 0.5, 1) +public sealed record Ratio(string Name, int Numerator, int Denominator); // wide 3:2, tall 4:5 + +public interface IMediaUploadGuard +{ + // Size, real format, pixel/memory bounds, timeout and parallel gate; returns ImageInfo or throws ImageRejectedException. + Task AdmitAsync(Stream upload, long declaredLength, CancellationToken ct); +} + +public static class FocusMath // pure, property-tested +{ + public static CropRect CropFor(int imageWidth, int imageHeight, Ratio ratio, FocusSetting focus); + public static FocusSetting Normalize(FocusSetting focus); // clamps to valid ranges +} + +public static class VariantPlanner // pure, property-tested +{ + public static IReadOnlyList Plan(int sourceWidth, int sourceHeight, IReadOnlyList ratios, IReadOnlySet outputs); +} + +public static class MediaPaths // pure +{ + public static string SetHash(string originalSha256, IEnumerable<(string Ratio, FocusSetting Focus)> crops); + public static string Url(string area, string setHash, string name); // "/media/hero//wide-1600.webp" + public static bool TryParse(string path, out MediaAddress address); // strict allow-list of characters +} +``` + +`MediaEndpoint` is a minimal-API/endpoint mapping `GET|HEAD /media/{**path}`: parse, open from the store, answer with the immutable headers and `304` on a matching `If-None-Match`; any failure is a plain 404. + +## Core.Hosting.Website + +```csharp +public interface ICmsDataBlockContributor +{ + string Key { get; } // "offerings", "banners", "hero" + int Order { get; } // 100 Offerings, 200 Hero: fixes the key order in the block + Task GetAsync(HtmlTransformContext context, CancellationToken ct); // null is written as JSON null +} + +public sealed class CmsDataBlockTransform(IEnumerable contributors) : IHtmlPageTransform +{ + public bool Wants(string html); // page contains + public Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken ct); +} +``` + +## Modules.Hero + +```csharp +public interface IHeroService +{ + Task GetAsync(string language, CancellationToken ct); // management read incl. inactive + Task SaveAsync(HeroSaveRequest request, string actor, CancellationToken ct); +} + +public interface IHeroImageService +{ + Task UploadAsync(Stream upload, long length, string actor, CancellationToken ct); + Task SetFocusAsync(Guid imageId, HeroFocusRequest request, string actor, CancellationToken ct); // general + optional per ratio + Task DeleteAsync(Guid imageId, string actor, CancellationToken ct); // refuses while a slide uses it, or detaches (decided in Functional Design) + Task RemoveOrphansAsync(CancellationToken ct); +} + +public interface IPublicHeroService +{ + Task GetActiveAsync(string language, DateTimeOffset now, CancellationToken ct); // null = 204 +} + +public static class ButtonTargetValidator +{ + public static ButtonTargetResult Validate(string? target); // Anchor | Path | Https | Invalid(reason) +} + +public static class HeroPictureRenderer +{ + public static string RegionHtml(PublicHeroDto hero, ITextCatalog texts); // title, tagline, buttons, first slide + public static string PreloadHtml(PublicHeroDto hero); // one or two elements +} +``` + +DTO shape (public, `GET /api/v1/hero` and `hero` in `#cms-data`): + +```json +{ "display": "slideshow", "title": "…", "tagline": "…", "lead": null, + "buttons": [ { "label": "…", "target": "/over-mij" } ], + "slides": [ { "id": "guid", "alt": "…", "decorative": false, + "image": { "width": 1600, "height": 1067, "focus": { "x": 0.5, "y": 0.5, "zoom": 1 }, + "src": "/media/hero//wide-1600.webp", + "variants": [ { "ratio": "wide", "width": 1600, "type": "image/webp", "url": "…" }, + { "ratio": "tall", "width": 960, "type": "image/webp", "url": "…" } ] } } ] } +``` + +## Frontend + +`heroApi.getHero()`, `saveHero()`, `uploadImage(file, onProgress)`, `setFocus(imageId, …)`, `deleteImage(imageId)`; `focusMath.cropFor(...)` (TypeScript twin of `FocusMath`, same test vectors). diff --git a/aidlc-docs/features/hero-module/inception/application-design/components.md b/aidlc-docs/features/hero-module/inception/application-design/components.md new file mode 100644 index 0000000..38fc060 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/components.md @@ -0,0 +1,76 @@ +# Components: hero-module + +Namespaces follow the existing modules (`SlpModularCms.Core.*`, `SlpModularCms.Modules.Hero`). "New" = created in this feature, "Changed" = existing code that is adapted. + +## C1. `SlpModularCms.Modules.Hero` (New, the module) + +| Component | Purpose and responsibilities | +|---|---| +| `HeroModule` (`IModule`) | Registers services, DbContext, texts (`AddCmsTextsFrom`), the HTML transform, the preload marker provider and the data contributor; runs the module's migrations. Name `Hero`, switched on or off per site by the project references and committed defaults (like Offerings). | +| `HeroDbContext` + entities | Tables `Heroes`, `HeroSlides`, `HeroImages` (see data model below). Own migrations, same style as the Offerings migrations (hand-written, MySQL). | +| `IHeroRepository`, `IHeroImageRepository` | Persistence of the hero with its slides, and of the images with their variant lists. | +| `IHeroService` | Management use cases: read and save the hero (texts, buttons, display, schedule, slide list and order), validation, change notification. | +| `IHeroImageService` | Upload, replace and remove of an image: validates and processes through the media service, stores the files, writes the metadata, changes focus/zoom per ratio (regenerates the variants), removes orphans. | +| `IPublicHeroService` | The read model for sites: the active hero (schedule and active slides applied) as `PublicHeroDto`, or null. Used by `GET /hero`, the HTML transform and the data contributor, so all three show exactly the same thing. | +| `HeroController` | Public read `GET /api/v1/hero` (anonymous, `[PublicSiteEndpoint]`, `public, max-age=60`, rate-limit policy `hero-public`, 204 when there is no active hero); management `GET /api/v1/hero/all` (the full hero including inactive slides and the schedule) and `PUT /api/v1/hero` (policy `AdminOnly`). Same convention as `offerings` and `offerings/all`. | +| `HeroImagesController` (admin) | `POST /api/v1/hero/images` (multipart upload, size limit), `PUT /api/v1/hero/images/{id}/focus`, `DELETE /api/v1/hero/images/{id}`. | +| `ButtonTargetValidator` | Pure function: accepts `#anchor`, `/path`, `https://host/...`, rejects everything else. | +| `HeroHtmlTransform` (`IHtmlPageTransform`) | Fills `` regions: title lines, tagline, buttons and the first active slide as ``. Fail-open. | +| `HeroPreloadMarkerProvider` (`IIndexHtmlMarkerProvider`) | Writes the one or two `` elements at ``; shares the `srcset`/`sizes`/`media` generator with the transform so they are byte-for-byte equal. | +| `HeroPictureRenderer` | Pure: one place that produces the ``/`` attributes and the preload attributes from a `PublicHeroDto`; golden-tested. | +| `HeroDataContributor` (`ICmsDataBlockContributor`) | Adds the key `hero` (the `PublicHeroDto`, or null) to the data block. | +| `HeroTexts` + `Texts/nl.json`, `en.json` | Backend texts (validation messages) per `docs/translation-files.md`. | + +### Data model (sketch, detailed in Functional Design) + +| Entity | Fields | +|---|---| +| `Hero` | `Id`, `Language` (default `nl`; unique per language so a language can be added later without migrating rows), `Title` (text with line breaks), `Tagline`, `Lead`, `Display` (`single`/`slideshow`), `Button1Label/Target`, `Button2Label/Target`, `StartsAt`, `EndsAt`, `IsActive`, `UpdatedAt`, `UpdatedBy` | +| `HeroSlide` | `Id` (GUID, stable), `HeroId`, `ImageId`, `Alt`, `Decorative`, `SortOrder`, `IsActive` | +| `HeroImage` | `Id`, `OriginalKey` (store key), `Sha256`, `SourceFormat`, `Width`, `Height`, `Bytes`, `Focus` (general, default centre: `X`, `Y`, `Zoom`), optional `WideFocus` and `TallFocus` (`X`, `Y`, `Zoom`, nullable), `VariantSetHash`, `VariantsJson` (list of `{ratio, width, type, key, bytes}`), `CreatedAt` | + +## C2. `SlpModularCms.Core.Media` (New, general media service in Core) + +| Component | Purpose and responsibilities | +|---|---| +| `IMediaStore` | The storage interface: `PutAsync(key, stream, contentType)`, `OpenReadAsync(key)`, `DeleteAsync(key)`, `DeletePrefixAsync(prefix)`, `ExistsAsync`. Keys are relative paths made by the code, never by a client file name. Behind this interface the store can move from a directory to the database if the hosting demands it (risk R1). | +| `FileSystemMediaStore` | Implementation on a directory (`Media:Directory`) outside the release; atomic writes (temp file then move), path containment check (no `..`, no absolute paths, only a safe character set), no directory listing. | +| `IImageProcessor` | The image library behind an interface: `InspectAsync(stream)` (real format, size, frame count, or a rejection), `RenderAsync(source, RenderRequest)` (decode, apply orientation, crop around focus/zoom to a ratio, resize without upscaling, strip metadata, encode to a format and quality). Implementation chosen in NFR Requirements after a proof on win-x64 and linux-arm64 (candidates ImageSharp, NetVips, Magick.NET, SkiaSharp). | +| `ImageProcessingLimits` / `MediaOptions` | `Media:Directory`, maximum upload bytes (10 MB), maximum pixels, maximum parallel jobs, timeout, accepted input formats, output formats and quality per format. | +| `FocusMath`, `VariantPlanner` | Pure, property-tested: the crop rectangle for a ratio from focus and zoom (always inside the image, as close to the focus as the image allows), and the widths per ratio from the source size (no upscaling, monotonic steps). | +| `MediaPaths` | The address scheme `/media///`; builds and parses addresses, computes the set hash from the content hash and the crop parameters, so a change of focus gives a new address. | +| `MediaEndpoint` | `GET /media/{**path}`: anonymous, same origin; `Cache-Control: public, max-age=31536000, immutable`, `ETag`, `304`, `X-Content-Type-Options: nosniff`, content type from the stored file, `Content-Disposition` not set, rate-limit policy `media-public`; unknown or malformed path = 404 with no detail. Also `HEAD`. | +| `IMediaUploadGuard` | The upload checks in one place (size, real format, pixel and memory bounds, decode timeout, parallelism gate), used by every module that accepts images. | + +## C3. `SlpModularCms.Core.Hosting.Website` (Changed) + +| Component | Change | +|---|---| +| `ICmsDataBlockContributor` (New) | `Key`, `Order`, `GetAsync(context, ct)` returning the value (object) for that key or "no value". | +| `CmsDataBlockTransform` (New, `IHtmlPageTransform`) | Owns the `` marker: asks all contributors (ordered by `Order`) and writes `{"siteUrl": …, : , …}` into the data block. Wants = page contains the marker. Fail-open as every transform. If a contributor throws, the whole block is left as baked: a half-filled block would mislead the site (fail-open for the block as a whole). | +| `OfferingsHtmlTransform` (Changed, module Offerings) | No longer writes the data block; its regions, JSON-LD and prices stay. A new `OfferingsDataContributor` (`Order` 100) supplies `offerings` and `banners`. The output of the block stays byte-identical (key order `siteUrl`, `offerings`, `banners`, then `hero`), so all existing golden files stay green. | +| `HtmlMarkerEditor` | Unchanged API; the preload marker is written through the existing `IIndexHtmlMarkerProvider` (whole-comment replacement). | + +## C4. Frontend admin (New feature folder `frontend/src/features/hero`) + +| Component | Purpose | +|---|---| +| `HeroPage` | The Hero screen in the admin navigation (visible when the Hero module is on, via `/System/capabilities`), shows whether the hero is live (schedule, active slides). | +| `HeroForm` | Title (multi-line), tagline, lead, display, up to two buttons with target validation messages, schedule. | +| `SlideList` | Order (up/down), on/off, alt text or "decorative", remove, add. | +| `ImageUploader` | Upload with progress, shows the accepted formats and the size limit, rejection messages. | +| `FocusEditor` | Own light component: the image with a draggable focus point, a zoom control, live previews of `wide` (3:2) and `tall` (4:5) cut as the host will cut them (same pure maths, shared as a small TypeScript twin of `FocusMath` with the same test vectors), and optional per-ratio overrides with "use the general point" reset. | +| `heroApi`, translations | React Query hooks and `nl/en` texts. | + +## C5. Scripts, docs, CI + +| Component | Purpose | +|---|---| +| `scripts/Seed-Hero.ps1` (+ data) | Seeds the SLP hero and the ASF hero with its 8 photos and the focus estimates of the ASF session, on test only; needs the owner's login like `Seed-Offerings.ps1`. | +| `scripts/smoke-site.sh` (Changed) | Checks the public hero endpoint (200 or 204), a media address answers with the immutable header, and, for a site with markers, no unprocessed hero markers. | +| `docs/hero-module.md` (New) | Contract, addresses, storage and the hosting risk, operation. | +| CI H0 | Done (merged, 0824bfa). | + +## Sites (outside this repository) + +The SLP and ASF websites place the markers and render ``; contract in `site-contract-agreed-with-asf.md`. diff --git a/aidlc-docs/features/hero-module/inception/application-design/services.md b/aidlc-docs/features/hero-module/inception/application-design/services.md new file mode 100644 index 0000000..9806610 --- /dev/null +++ b/aidlc-docs/features/hero-module/inception/application-design/services.md @@ -0,0 +1,98 @@ +# Services and orchestration: hero-module + +## Services + +| Service | Responsibility | Collaborators | +|---|---|---| +| `HeroService` (management) | Reads and saves the hero: validates fields (lengths, button targets via `ButtonTargetValidator`, schedule order, slide count and order), writes the hero and slides in one transaction, calls the cache invalidation. | `IHeroRepository`, `ITextCatalog`, `IIndexHtmlCache` | +| `HeroImageService` | The upload pipeline and focus changes (below). Owns the rule that every stored file belongs to exactly one image set. | `IMediaUploadGuard`, `IImageProcessor`, `IMediaStore`, `IHeroImageRepository`, `IIndexHtmlCache` | +| `PublicHeroService` | Builds the public read model from the stored hero: schedule and `IsActive` applied, inactive slides removed, variants that exist listed, the first-slide choice made once here. | `IHeroRepository`, `TimeProvider` | +| Core `MediaEndpoint` | Serves stored variants; no knowledge of the Hero module. | `IMediaStore` | +| Core `CmsDataBlockTransform` | Composes the `#cms-data` block from all contributors. | `ICmsDataBlockContributor` implementations | +| `HeroHtmlTransform`, `HeroPreloadMarkerProvider` | Write the region and the preload from the same `PublicHeroDto` through `HeroPictureRenderer`. | `IPublicHeroService` | + +## Orchestration + +### Upload of an image + +```mermaid +sequenceDiagram + box rgba(246,224,94,0.4) Admin + participant A as Admin browser + end + box rgba(99,179,237,0.4) Host + participant C as HeroImagesController + participant S as HeroImageService + participant G as MediaUploadGuard + participant P as ImageProcessor + participant M as MediaStore + participant R as Repository + end + A->>C: POST image (multipart) + C->>S: UploadAsync(stream, length, actor) + S->>G: AdmitAsync (size, real format, bounds, timeout, gate) + G-->>S: ImageInfo or rejection + S->>M: Put original (set directory) + S->>P: Render variants per ratio and width + P-->>S: encoded files, metadata stripped + S->>M: Put variants + S->>R: Save HeroImage (hash, size, variants) + S-->>C: HeroImageDto + C-->>A: 201 with the image and its variants +``` + +Text alternative: the admin uploads; the service admits the file, stores the original, renders and stores the variants, saves the metadata, and returns the image with its variant addresses. + +Rules of the pipeline: +1. Reject early (size, real format, pixel count, frame count, timeout); a rejection is a clear 400 and nothing is stored. +2. Write to a temporary location first; only a completely processed set is made visible (one move per set). A failure removes the partial files. +3. The set hash is computed from the original's SHA-256 and the crop parameters; the variant addresses contain it. +4. At most a few uploads are processed in parallel (gate); the rest wait or get 429. + +### Change of focus + +`SetFocusAsync` validates the numbers (ranges), recomputes the set hash, renders the affected ratios again into the new set directory, saves the new addresses, then removes the old set directory (after the commit). A site that still holds the old data block keeps working until its cache expires (the old files go after a grace period, decided in Functional Design). + +### Publishing and live updates + +```mermaid +flowchart LR + Save["PUT /hero or image change"] --> Repo["Repository (commit)"] + Repo --> Inval["IIndexHtmlCache.Invalidate()"] + Inval --> Cache["HtmlMarkerInjector cache dropped"] + Req["Next page request"] --> Inj["HtmlMarkerInjector"] + Inj --> T1["CmsDataBlockTransform
(offerings, banners, hero)"] + Inj --> T2["HeroHtmlTransform
(region + first slide)"] + Inj --> T3["HeroPreloadMarkerProvider
(head)"] + T1 --> Pub["PublicHeroService"] + T2 --> Pub + T3 --> Pub + Api["GET /api/v1/hero"] --> Pub + classDef act fill:#FFA726,stroke:#E65100,color:#000; + classDef core fill:#BBDEFB,stroke:#1565C0,color:#000; + classDef mod fill:#9ae6b4,stroke:#2f855a,color:#000; + class Save,Req,Api act; + class Inval,Cache,Inj,T1 core; + class Repo,T2,T3,Pub mod; +``` + +Text alternative: a save commits and invalidates the page cache; the next page request rebuilds the page through the data block, region and preload, all reading the one public read model, which the public endpoint also uses. + +### Failure behaviour + +| Where | Behaviour | +|---|---| +| Upload or processing fails | Fail closed: 4xx with a generic message, partial files removed, nothing published. | +| `PublicHeroService` fails or finds no active hero | Region, preload and `hero` key are left as baked (data block: `hero` is `null`; the site keeps the baked hero). The page is served. | +| A contributor fails | The data block is left as baked entirely. | +| Media file missing or unreadable | 404 for that address; the data block lists only variants that were stored. | +| Storage unwritable | Upload fails with a generic 503-style message and an error log; public reads are unaffected. | + +## Cross-cutting + +- **Texts**: validation and rejection messages go through `ITextCatalog` with `HeroTexts` keys (`hero.validation.*`, `hero.image.*`); the technical rejection reason codes stay English constants. +- **Authorization**: management routes `AdminOnly`; public routes anonymous and marked `[PublicSiteEndpoint]` so they pass the availability gate. +- **Rate limiting**: new policies `hero-public` (120 per 60 s like offerings), `media-public` (high, per client address, allows the page's images), `hero-upload` (low, per user). +- **Logging**: structured, with the request id, actor and image id; never file contents or file names from the client. +- **Auditing**: `UpdatedBy`/`UpdatedAt` on the hero and `CreatedAt` plus actor on images, plus a log line per change (who, what, when) for SECURITY-13. +- **Cache keys**: the injector's per-file cache already keys by page; hero changes call `Invalidate()` like offerings and banners do. diff --git a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md index 3bce734..72f9ebd 100644 --- a/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md +++ b/aidlc-docs/features/hero-module/inception/plans/application-design-plan.md @@ -10,13 +10,13 @@ Vul per vraag de letter in na `[Answer]:`. Bij elke vraag staat mijn aanbeveling ## Plan (stappen) - [x] 1. Context geanalyseerd (requirements, contract, bestaande `HtmlMarkerInjector`/`IHtmlPageTransform`/`OfferingsHtmlTransform`) -- [ ] 2. Vragen hieronder beantwoord door Bryan -- [ ] 3. Antwoorden geanalyseerd op tegenstrijdigheden en vaagheid -- [ ] 4. `components.md` (componenten en verantwoordelijkheden) -- [ ] 5. `component-methods.md` (signaturen; bedrijfsregels volgen in Functional Design) -- [ ] 6. `services.md` (services en orkestratie) -- [ ] 7. `component-dependency.md` (afhankelijkheden, datastromen) -- [ ] 8. `application-design.md` (samenvatting) en consistentiecontrole +- [x] 2. Vragen hieronder beantwoord door Bryan (2026-11-16, via SLS-Main) +- [x] 3. Antwoorden geanalyseerd: geen tegenstrijdigheid; Q2 en Q6 verbreden de requirements (zie requirements.md, aangepast) +- [x] 4. `components.md` (componenten en verantwoordelijkheden) +- [x] 5. `component-methods.md` (signaturen; bedrijfsregels volgen in Functional Design) +- [x] 6. `services.md` (services en orkestratie) +- [x] 7. `component-dependency.md` (afhankelijkheden, datastromen) +- [x] 8. `application-design.md` (samenvatting) en consistentiecontrole - [ ] 9. Goedkeuring van Bryan ## Vragen @@ -32,7 +32,7 @@ De bestanden moeten een deploy overleven (releases worden vervangen), in de back Aanbeveling: A. -[Answer]: +[Answer]: B. Een MAP buiten de release (niet de database). Opslag komt achter een eigen koppeling zodat database-opslag later kan; risico's en gevolgen in het ontwerp; Bryan wordt opnieuw gevraagd als de proef op de hosting (MijnHostingPartner, IIS) tegenvalt. ### Vraag 2 — Welke afbeeldingsformaten leveren we? @@ -44,7 +44,7 @@ AVIF is vaak het punt waarop een bibliotheek of platform tegenvalt (win-x64 voor Aanbeveling: B. -[Answer]: +[Answer]: Invoer: zoveel mogelijk formaten (jpg/jpeg, png, webp en waar de bibliotheek het kan gif, bmp, tiff, heic/avif), met echte typecontrole en metadata strippen. Uitvoer: het systeem kiest per platform (WebP verplicht, AVIF als het kan). ### Vraag 3 — Hoe komt het hero-deel in het blok `#cms-data`? @@ -56,7 +56,7 @@ Nu schrijft alleen de Offerings-module dit blok. Er moet één blok blijven (afs Aanbeveling: A. -[Answer]: +[Answer]: A. Core-koppeling waarmee elke module een sleutel aan het datablok toevoegt; Offerings gebruikt die ook (byte-identieke uitvoer, groene golden files). ### Vraag 4 — Waar komt de beeldverwerking en het serveren van media? @@ -68,7 +68,7 @@ Er is al een plan voor een galerij (later), die dezelfde verwerking nodig heeft. Aanbeveling: B. -[Answer]: +[Answer]: B. Algemene mediadienst in Core. ### Vraag 5 — Hoe stelt de beheerder uitsnede en focus in? @@ -78,7 +78,7 @@ Aanbeveling: B. Aanbeveling: A. -[Answer]: +[Answer]: A. Eigen lichte component. ### Vraag 6 — Wat legt de beheerder per afbeelding vast? @@ -88,4 +88,4 @@ Aanbeveling: A. Aanbeveling: A. Per-verhouding-instellingen kunnen later zonder wijziging van het publieke contract, want de data bevat al per variant de verhouding. -[Answer]: +[Answer]: Standaard het midden voor alle verhoudingen; per verhouding (tall/mobiel, ook wide) kan optioneel een apart focuspunt worden ingesteld, anders terugval op het algemene punt (midden). diff --git a/aidlc-docs/features/hero-module/inception/requirements/requirements.md b/aidlc-docs/features/hero-module/inception/requirements/requirements.md index 7a262f9..20149da 100644 --- a/aidlc-docs/features/hero-module/inception/requirements/requirements.md +++ b/aidlc-docs/features/hero-module/inception/requirements/requirements.md @@ -34,7 +34,7 @@ | 5 | A | Field `display`: `single` or `slideshow` | | 6 | A | Slide: image, required alt text (or explicitly decorative), order, on/off | | 7 | A + extra | Upload; host keeps the original, reads the size, makes variants for `srcset` (WebP/AVIF); **the administrator can set a focus point and/or crop per image and per use/ratio, with a preview in the admin** | -| 8 | A + extra | JPEG, PNG, WebP up to 10 MB; real file type check; strip metadata (GPS); **the CMS resizes, compresses and optimises for the intended size**; reuse what the Decks/SDA session already has (library, settings) without duplicating code | +| 8 | A + extra, widened by Bryan (design answer Q2) | Input: as many formats as possible, mainly the common ones (jpg/jpeg, png, webp and, where the library can, gif, bmp, tiff, heic/avif), up to 10 MB, with a real file type check and metadata stripping (GPS). Output: the system chooses what is best per platform (WebP required, AVIF when it can). **The CMS resizes, compresses and optimises for the intended size**; the Decks/SDA session has nothing to reuse | | 9 | C | One language now; the data model allows more languages later without migrating existing data | | 10 | A | As banners and packages: 60 s cache, invalidated directly on every CMS change | | 11 | A | Saving is publishing (no draft) | @@ -65,10 +65,10 @@ | ID | Requirement | |---|---| -| FR-10 | Upload in the admin of JPEG, PNG and WebP, max 10 MB. The type is decided from the file content (signature and a successful decode), never from the file name or the `Content-Type`. Other types, including SVG, are rejected. | +| FR-10 | Upload in the admin, max 10 MB, of the common image formats: JPEG, PNG and WebP always, and where the chosen library supports them GIF, BMP, TIFF, HEIC and AVIF (the supported list is fixed in NFR Requirements and shown in the admin). The type is decided from the file content (signature and a successful decode), never from the file name or the `Content-Type`. Anything else, including SVG, is rejected. An animated input (GIF, WebP) is reduced to its first frame. | | FR-11 | All metadata (EXIF including GPS, ICC beyond what is needed for colour, XMP) is removed from every stored and published file. | | FR-12 | The host keeps the original (after validation) and reads its pixel size. It generates optimised variants: several widths and WebP and AVIF (the format set is settled in Application Design with the image library; if AVIF is not feasible on every platform, WebP plus the original format is the minimum). Variants are resized, compressed and sized for the intended use, not the full upload. | -| FR-13 | **Focus point and crop.** Per image the administrator can set a focus point (the subject that must not be cut off) and/or a crop rectangle (move and zoom), per use or aspect ratio (for example wide desktop hero and tall mobile hero), with a live preview of the result in the admin. The default focus is the centre. The public data contains the focus point (and the ratio variants) so that a site can use it (for example as `object-position`) and the generated variants respect it. | +| FR-13 | **Focus point and crop.** Per image the administrator can set a focus point (the subject that must not be cut off) and/or a crop rectangle (move and zoom), per use or aspect ratio (for example wide desktop hero and tall mobile hero), with a live preview of the result in the admin. The default focus is the centre for every ratio; per ratio (`tall`, `wide`) a separate focus point (and zoom) can optionally be set, otherwise the general point (the centre) applies (Bryan, design answer Q6). The public data contains the general focus point and the ratio variants so that a site can use it (for example as `object-position`) and the generated variants respect the per-ratio settings. | | FR-14 | Images are served by the host from the site's own address (same origin, no change in CSP `img-src`), at an address that contains the content hash, so they can be cached for a long time (`Cache-Control: public, max-age=31536000, immutable`). Uploading a new image gives a new address. | | FR-15 | The preload address for the LCP image is exactly the address used in the `img` (or the same `srcset`/`sizes` pair in the preload), so the browser does not download it twice. | | FR-16 | Deleting a slide or replacing its image removes files that nothing references any more (no orphans). | @@ -103,7 +103,7 @@ | NFR-03 (page weight) | The first slide delivered to a phone is a small variant (target: well below the 220 to 440 KB JPG of today at the same visual quality); the exact budgets are set in NFR Requirements. | | NFR-04 (upload safety) | The decode is bounded: maximum pixel count and maximum memory per upload (decompression-bomb protection), a timeout, at most a few uploads processed in parallel, an upload rate limit per user, a body size limit of 10 MB at the framework level. A corrupt or oversized image never takes the host down. | | NFR-05 (platforms) | The chosen library works on win-x64 self-contained (IIS production) and linux-arm64 (the Pi test hosts) and in the CI (linux x64), with a licence that suits a commercial site. This is verified, not assumed. | -| NFR-06 (storage) | The stored images survive a deploy (releases are replaced), are part of the backup, and work on the Pi and on IIS; whether bytes live in the database or in a shared directory is decided in Application Design. | +| NFR-06 (storage) | Decided (design answer Q1): the images live in a **directory outside the release**, behind an own storage interface so that database storage can follow if the hosting demands it. The directory survives a deploy (Pi: `releases/current/shared`; IIS: a data directory), is part of the backup, and the host account has write permission there. Write permission on the ASF production hosting (MijnHostingPartner, IIS) is not known and is tested by Bryan with ASF; Bryan is asked again if that test fails. | | NFR-07 (accessibility) | The CMS requires alt text or an explicit decorative flag; the sites keep their slider accessibility (pause, reduced motion, screen-reader texts). | | NFR-08 (compatibility) | The public shapes of packages, banners and the injection markers do not change; existing golden files stay green. | | NFR-09 (resilience) | A failing CMS never produces an empty or broken hero: the baked hero stays. | @@ -138,7 +138,7 @@ Layouts or sketch choice; the code line of SLS; socials; the timing, animation, | # | Item | Owner | |---|---|---| | A1 | Image library and AVIF feasibility on win-x64 and linux-arm64; licence. The SDA session has nothing to reuse (see FR-17). Candidates to compare in design: ImageSharp, SkiaSharp, NetVips, Magick.NET | CMS session | -| A2 | Storage of originals and variants (database vs shared directory) | Application Design | +| A2 | ~~Storage~~ Decided: directory outside the release behind an interface (see NFR-06); the hosting test is open | Bryan with ASF | | A3 | Exact crop/focus model: focus point only, crop per ratio, or both; which ratios (for example 16:9 and 3:4); who applies the crop (host-generated variants vs site `object-position`) | Application Design with ASF and SLS sessions | | A4 | Public JSON shape and marker names: agree with ASF (their proposal and golden files) and SLS | CMS, ASF and SLS sessions | | A5 | SLS renders the title lines and derives the screen-reader text from them; Bryan wants to see the result on SLP Software | SLS session |