diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/SOURCE.md b/src/SlpModularCms.Modules.Offerings.Tests/Golden/SOURCE.md new file mode 100644 index 0000000..7d70e40 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/SOURCE.md @@ -0,0 +1,7 @@ +# Golden files of the website build (ASF) + +`host-injection/` is a copy of `web/contract/host-injection` of the Andrea Slop Fotografie website repository, +ASF commit `16027f5` (branch `feature/asf-packages-cms`). It is the contract for the plain HTML the CMS host writes +between the CMS markers (see `host-injection/README.md` for the rules). `GoldenHtmlTests` runs `CmsPageHtml` against +every input/expected pair. When the website changes the contract it sends new files and the commit; replace the +folder and note the new commit here. diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/README.md b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/README.md new file mode 100644 index 0000000..1fe37f5 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/README.md @@ -0,0 +1,28 @@ +# Host injection contract (ASF site and CMS host) + +The ASF build leaves markers in the prerendered pages; the CMS host fills them from live data. This folder holds the golden files for the two list regions. For every `NAME.input.json` there is a `NAME.expected.html`: the host's template must give exactly that text (the file ends with one newline that is not part of the HTML) for that input. The ASF repo tests its own implementation (`src/lib/cmsHtml.ts`) against the same files; to change the contract, change the code and run `UPDATE_GOLDEN=1 pnpm test src/lib/cmsHtml.test.ts`, then send the new files to the CMS session. The files come from ASF commit: see `git log -1 -- web/contract/host-injection` in the ASF repo. + +## Inputs + +- `offerings-*.input.json`: the answer of `GET /api/v1/offerings` (an array). +- `banner-*.input.json`: `{ "position": "top" | "bottom", "answer": | null }`; `null` is a 204. + +## Rules for the packages region (``) + +1. Keep a package only when all hold: `slug` is a string matching `^[a-z0-9-]+$`; `title` is a non-empty string after trimming; `features` is a non-empty array of non-empty strings (each trimmed); `price` is readable as whole euros above zero (below); the slug was not used by an earlier kept package (the first one wins). Trim all texts. Any other package is skipped. +2. Order by `displayOrder` (a number; missing counts as 0), ties keep the given order. +3. Price text to whole euros: trim, then the regex `^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$`; group 1 without dots is the amount; it must be a whole number above zero. So "€ 175", "€ 1.250", "175,-", "€ 175,00" are readable; "op aanvraag", "€ 12,50", "€ 0", "175 of 185" are not. +4. Output: ``; nothing at all (empty string) when no package is kept. +5. Per package: `
  • ` + `

    NAME

    ` + `

    € AMOUNT

    ` + `` + `Boek NAME` + `
  • `. `data-featured="true"` only when `featured` is the boolean `true`. AMOUNT uses a dot as thousands separator (1.250). The literal text ` ` is written, not a character. `description`, `priceNote` and `ctaLabel` are not used. +6. Escape every text (name, features, slug, amount) as: `&` `&`, `<` `<`, `>` `>`, `"` `"`, `'` `'`. + +## Rules for the banner regions (``, ``) + +1. `null` answer: empty string. Bottom: the title is required, otherwise empty string. Top: title or text is required, otherwise empty string. +2. Output ``. Parts: `TITLE`, `TEXT`, `LABEL` (trim all texts; empty means absent). +3. The link is written only when label and URL are both present and the URL is safe: it starts with `https://` and parses as a URL, or it starts with one `/` (not `//`, no backslash). Otherwise the link part is left out. +4. Escape as above (also in the `href`). + +## Where the region sits + +`…` (and the two banner pairs) are written by the build; the host replaces what is between the markers and leaves the markers. See `aidlc-docs/features/asf-cms-host-injection/plan.md` for the other markers (data block, JSON-LD price, inline price). diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.expected.html new file mode 100644 index 0000000..dee1360 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.input.json new file mode 100644 index 0000000..d724870 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-full.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "Kerstactie", + "text": "Alleen in december", + "linkLabel": "Boek de actie", + "linkUrl": "/contact", + "position": "bottom" + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.expected.html new file mode 100644 index 0000000..3c6ff7f --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.input.json new file mode 100644 index 0000000..f5d76d1 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-bottom-title-only.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "Past er niets bij?", + "text": null, + "linkLabel": null, + "linkUrl": null, + "position": "bottom" + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.expected.html new file mode 100644 index 0000000..2d00e76 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.input.json new file mode 100644 index 0000000..71607bb --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-hostile.input.json @@ -0,0 +1,10 @@ +{ + "position": "bottom", + "answer": { + "title": "", + "text": "\"quote\" & 'single'", + "linkLabel": "Meer", + "linkUrl": "https://voorbeeld.nl/?a=1&b=2", + "position": "bottom" + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.expected.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.input.json new file mode 100644 index 0000000..bb9ad06 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-none.input.json @@ -0,0 +1,4 @@ +{ + "position": "bottom", + "answer": null +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.expected.html new file mode 100644 index 0000000..fe80976 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.input.json new file mode 100644 index 0000000..dfe6a32 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-text-only.input.json @@ -0,0 +1,10 @@ +{ + "position": "top", + "answer": { + "title": "", + "text": "Nog twee plekken in december", + "linkLabel": null, + "linkUrl": null, + "position": "top" + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.expected.html new file mode 100644 index 0000000..07cbc33 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.input.json new file mode 100644 index 0000000..b5b9292 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/banner-top-unsafe-link.input.json @@ -0,0 +1,10 @@ +{ + "position": "top", + "answer": { + "title": "Nieuw", + "text": "x", + "linkLabel": "Hier", + "linkUrl": "http://voorbeeld.nl", + "position": "top" + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.expected.html new file mode 100644 index 0000000..28faf04 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.input.json new file mode 100644 index 0000000..14fa4b7 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-featured.input.json @@ -0,0 +1,18 @@ +[ + { + "slug": "newborn", + "title": "Newborn", + "price": "€ 185", + "features": ["1-2 uur fotografie"], + "displayOrder": 0, + "featured": true + }, + { + "slug": "gezin", + "title": "Gezin", + "price": "€ 1.250,-", + "features": ["Hele dag"], + "displayOrder": 1, + "featured": false + } +] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.expected.html new file mode 100644 index 0000000..48fa6e0 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.input.json new file mode 100644 index 0000000..e4f1196 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-hostile.input.json @@ -0,0 +1,9 @@ +[ + { + "slug": "xss", + "title": " & \"co\"", + "price": "€ 100", + "features": ["vet", "o'brien & zoon"], + "displayOrder": 0 + } +] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.expected.html new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.input.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-none.input.json @@ -0,0 +1 @@ +[] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.expected.html new file mode 100644 index 0000000..05a1f7d --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.input.json new file mode 100644 index 0000000..0329aca --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-skipped.input.json @@ -0,0 +1,58 @@ +[ + { + "slug": "goed", + "title": "Goed", + "price": "€ 100", + "features": ["a"], + "displayOrder": 0 + }, + { + "slug": "Slecht Slug", + "title": "Fout", + "price": "€ 100", + "features": ["a"], + "displayOrder": 1 + }, + { + "slug": "goed", + "title": "Dubbel", + "price": "€ 100", + "features": ["a"], + "displayOrder": 2 + }, + { + "slug": "aanvraag", + "title": "Op aanvraag", + "price": "op aanvraag", + "features": ["a"], + "displayOrder": 3 + }, + { + "slug": "leeg", + "title": "Zonder kenmerken", + "price": "€ 100", + "features": [], + "displayOrder": 4 + }, + { + "slug": "zonder-titel", + "title": "", + "price": "€ 100", + "features": ["a"], + "displayOrder": 5 + }, + { + "slug": "nul", + "title": "Nul", + "price": "€ 0", + "features": ["a"], + "displayOrder": 6 + }, + { + "slug": "komma", + "title": "Komma", + "price": "€ 12,50", + "features": ["a"], + "displayOrder": 7 + } +] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.expected.html b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.expected.html new file mode 100644 index 0000000..fedebf2 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.expected.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.input.json b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.input.json new file mode 100644 index 0000000..75fdd9c --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Golden/host-injection/offerings-standard.input.json @@ -0,0 +1,29 @@ +[ + { + "slug": "gezin", + "title": "Gezin", + "price": "€ 175", + "features": [ + "1 uur fotografie", + "Minstens 30 zorgvuldig nabewerkte foto's" + ], + "displayOrder": 2, + "description": "Een shoot met het hele gezin!", + "priceNote": "eenmalig, incl. btw" + }, + { + "slug": "zwangerschap", + "title": "Zwangerschap", + "price": "€ 175", + "features": ["1 uur fotografie", "Persoonlijke online fotogalerij"], + "displayOrder": 0 + }, + { + "slug": "newborn", + "title": "Newborn", + "price": "€ 185", + "features": ["1-2 uur fotografie"], + "displayOrder": 1, + "ctaLabel": "Boek nu" + } +] diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/GoldenHtmlTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/GoldenHtmlTests.cs new file mode 100644 index 0000000..bb79d1c --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/GoldenHtmlTests.cs @@ -0,0 +1,99 @@ +using System.Text.Json; +using FluentAssertions; +using SlpModularCms.Modules.Offerings.Models; +using SlpModularCms.Modules.Offerings.Services; + +namespace SlpModularCms.Modules.Offerings.Tests.Services; + +/// +/// The plain HTML written between the CMS markers must be exactly what the website build expects: the golden files of +/// the website repository (Golden/SOURCE.md names the commit) are run through . +/// +public class GoldenHtmlTests +{ + private static string Dir => Path.Combine(AppContext.BaseDirectory, "Golden", "host-injection"); + + public static IEnumerable Offerings() => Names("offerings-"); + public static IEnumerable Banners() => Names("banner-"); + + private static IEnumerable Names(string prefix) => + Directory.GetFiles(Dir, prefix + "*.input.json").Select(f => new object[] { Path.GetFileName(f)[..^".input.json".Length] }).OrderBy(o => (string)o[0]); + + // The expected files end with one newline that is not part of the HTML. + private static string Expected(string name) + { + var text = File.ReadAllText(Path.Combine(Dir, name + ".expected.html")); + return text.EndsWith('\n') ? text[..^1] : text; + } + + private static JsonElement Input(string name) => JsonDocument.Parse(File.ReadAllText(Path.Combine(Dir, name + ".input.json"))).RootElement; + + private static string? Text(JsonElement e, string property) => + e.TryGetProperty(property, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + [Fact] + public void TheGoldenFiles_AreThere() + { + Offerings().Count().Should().BeGreaterThanOrEqualTo(5); + Banners().Count().Should().BeGreaterThanOrEqualTo(6); + } + + [Theory] + [MemberData(nameof(Offerings))] + public void OfferingsList_MatchesTheGoldenFile(string name) + { + var offerings = Input(name).EnumerateArray().Select((o, i) => new OfferingDto( + Id: i.ToString(), + Slug: Text(o, "slug")!, + Title: Text(o, "title")!, + Description: Text(o, "description") ?? string.Empty, + Price: Text(o, "price")!, + PriceNote: Text(o, "priceNote") ?? string.Empty, + Features: o.GetProperty("features").EnumerateArray().Select(f => f.GetString()!).ToList(), + CtaLabel: Text(o, "ctaLabel") ?? string.Empty, + Featured: o.TryGetProperty("featured", out var f) && f.ValueKind == JsonValueKind.True, + DisplayOrder: o.TryGetProperty("displayOrder", out var d) ? d.GetInt32() : 0)).ToList(); + + CmsPageHtml.OfferingsList(offerings).Should().Be(Expected(name)); + } + + [Theory] + [MemberData(nameof(Banners))] + public void Banner_MatchesTheGoldenFile(string name) + { + var input = Input(name); + var position = input.GetProperty("position").GetString()!; + var answer = input.GetProperty("answer"); + PublicOfferingBannerDto? banner = answer.ValueKind == JsonValueKind.Null + ? null + : new PublicOfferingBannerDto(Text(answer, "title")!, Text(answer, "text")!, Text(answer, "linkLabel"), Text(answer, "linkUrl"), position); + + CmsPageHtml.Banner(banner, position).Should().Be(Expected(name)); + } + + [Theory] + [InlineData("€ 175", 175)] + [InlineData("€ 1.250", 1250)] + [InlineData("175,-", 175)] + [InlineData("€ 175,00", 175)] + [InlineData("€ 1.250,-", 1250)] + [InlineData("op aanvraag", null)] + [InlineData("€ 12,50", null)] + [InlineData("€ 0", null)] + [InlineData("175 of 185", null)] + [InlineData("", null)] + [InlineData(null, null)] + public void WholeEuros_ReadsOnlyWholeEuroPrices(string? text, int? expected) => + CmsPageHtml.WholeEuros(text).Should().Be(expected); + + [Theory] + [InlineData(185, "185")] + [InlineData(1250, "1.250")] + [InlineData(1000000, "1.000.000")] + public void FormatAmount_UsesADotAsThousandsSeparator(int euros, string expected) => + CmsPageHtml.FormatAmount(euros).Should().Be(expected); + + [Fact] + public void Encode_EscapesTheFiveCharacters_AndLeavesAccentsAlone() + => CmsPageHtml.Encode("é & < > \" '").Should().Be("é & < > " '"); +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/SlpModularCms.Modules.Offerings.Tests.csproj b/src/SlpModularCms.Modules.Offerings.Tests/SlpModularCms.Modules.Offerings.Tests.csproj index 83473b2..6d0f57f 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/SlpModularCms.Modules.Offerings.Tests.csproj +++ b/src/SlpModularCms.Modules.Offerings.Tests/SlpModularCms.Modules.Offerings.Tests.csproj @@ -26,6 +26,10 @@ + + + + diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index 8396372..faa9a26 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -31,6 +31,7 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/CmsPageHtml.cs b/src/SlpModularCms.Modules.Offerings/Services/CmsPageHtml.cs new file mode 100644 index 0000000..ed5a301 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/CmsPageHtml.cs @@ -0,0 +1,161 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; + +namespace SlpModularCms.Modules.Offerings.Services; + +/// +/// The plain, crawlable HTML the CMS host writes between the CMS markers of a prerendered page, from live data +/// (pure functions). The rules are a contract with the website build; its golden files (input JSON and expected +/// HTML) are in SlpModularCms.Modules.Offerings.Tests/Golden/host-injection and are tested against this class. +/// +public static partial class CmsPageHtml +{ + [GeneratedRegex(@"^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$", RegexOptions.CultureInvariant)] + private static partial Regex WholeEuroPrice(); + + [GeneratedRegex("^[a-z0-9-]+$", RegexOptions.CultureInvariant)] + private static partial Regex SlugPattern(); + + /// + /// A price text read as whole euros above zero: "€ 175", "€ 1.250", "175,-" and "€ 175,00" are 175, 1250, 175, 175; + /// "op aanvraag", "€ 12,50", "€ 0" and "175 of 185" are not a price (null). Never guessed. + /// + public static int? WholeEuros(string? price) + { + var match = WholeEuroPrice().Match((price ?? string.Empty).Trim()); + if (!match.Success) + { + return null; + } + + return int.TryParse(match.Groups[1].Value.Replace(".", string.Empty), NumberStyles.None, CultureInfo.InvariantCulture, out var euros) + && euros > 0 + ? euros + : null; + } + + /// The amount with a dot as thousands separator (1250 is "1.250"). + public static string FormatAmount(int euros) => euros.ToString("#,##0", CultureInfo.InvariantCulture).Replace(',', '.'); + + /// "€&nbsp;185": the euro sign, the entity for a non-breaking space (written as text) and the amount. + public static string PriceHtml(int euros) => "€ " + FormatAmount(euros); + + /// The offerings that have a place in the list: see . + internal static IReadOnlyList<(OfferingDto Offering, string Slug, string Title, int Euros, IReadOnlyList Features)> Keep( + IReadOnlyList offerings) + { + var kept = new List<(OfferingDto, string, string, int, IReadOnlyList)>(); + var seen = new HashSet(StringComparer.Ordinal); + + foreach (var offering in offerings.OrderBy(o => o.DisplayOrder)) + { + var slug = (offering.Slug ?? string.Empty).Trim(); + var title = (offering.Title ?? string.Empty).Trim(); + var features = (offering.Features ?? []).Select(f => (f ?? string.Empty).Trim()).ToList(); + + if (!SlugPattern().IsMatch(slug) || title.Length == 0 + || features.Count == 0 || features.Any(f => f.Length == 0) + || WholeEuros(offering.Price) is not { } euros + || !seen.Add(slug)) + { + continue; + } + + kept.Add((offering, slug, title, euros, features)); + } + + return kept; + } + + /// + /// The packages as one plain list, or an empty string when no package is kept. A package is kept when its slug is + /// [a-z0-9-]+ (the first of a duplicate wins), it has a title, at least one feature (none blank) and a price + /// that reads as whole euros above zero; the order is displayOrder. + /// + public static string OfferingsList(IReadOnlyList offerings) + { + var kept = Keep(offerings); + if (kept.Count == 0) + { + return string.Empty; + } + + var html = new StringBuilder("
      "); + foreach (var (offering, slug, title, euros, features) in kept) + { + var name = Encode(title); + var id = Encode(slug); + html.Append("
    • ') + .Append("

      ").Append(name).Append("

      ") + .Append("

      ").Append(PriceHtml(euros)).Append("

      ") + .Append("
        "); + foreach (var feature in features) + { + html.Append("
      • ").Append(Encode(feature)).Append("
      • "); + } + + html.Append("
      ") + .Append("Boek ").Append(name).Append("") + .Append("
    • "); + } + + return html.Append("
    ").ToString(); + } + + /// + /// A banner as one <aside>, or an empty string for no banner. A bottom banner needs a title; a top banner + /// needs a title or a text. The link is written only when label and URL are both present and the URL is safe. + /// + public static string Banner(PublicOfferingBannerDto? banner, string position) + { + if (banner is null) + { + return string.Empty; + } + + var title = (banner.Title ?? string.Empty).Trim(); + var text = (banner.Text ?? string.Empty).Trim(); + var label = (banner.LinkLabel ?? string.Empty).Trim(); + var url = (banner.LinkUrl ?? string.Empty).Trim(); + + var hasContent = position == OfferingBannerPositions.Top ? title.Length > 0 || text.Length > 0 : title.Length > 0; + if (!hasContent) + { + return string.Empty; + } + + var parts = new List(); + if (title.Length > 0) parts.Add("" + Encode(title) + ""); + if (text.Length > 0) parts.Add("" + Encode(text) + ""); + if (label.Length > 0 && url.Length > 0 && OfferingBannerLinks.IsAllowed(url)) + { + parts.Add("" + Encode(label) + ""); + } + + return ""; + } + + /// Encodes exactly & < > " ' (other characters, accents included, stay as they are). + public static string Encode(string text) + { + var builder = new StringBuilder(text.Length + 8); + foreach (var c in text) + { + switch (c) + { + case '&': builder.Append("&"); break; + case '<': builder.Append("<"); break; + case '>': builder.Append(">"); break; + case '"': builder.Append("""); break; + case '\'': builder.Append("'"); break; + default: builder.Append(c); break; + } + } + + return builder.ToString(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs new file mode 100644 index 0000000..8e44bed --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs @@ -0,0 +1,170 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Data.Entities; +using SlpModularCms.Modules.Offerings.Models; + +namespace SlpModularCms.Modules.Offerings.Services; + +/// +/// Writes the live packages and banners into a prerendered page (see for the marker +/// formats): the plain lists in the regions, the data block the website reads instead of fetching, the price in the +/// page's JSON-LD and inline prices. It only touches what a page marks; a page without markers is not handed to it. +/// Any exception means "leave the page as it was built" (the injector logs it and serves the baked page). +/// +public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferingBannersService banners) : IHtmlPageTransform +{ + public const string OfferingsRegion = "CMS:OFFERINGS-HTML"; + public const string BannerTopRegion = "CMS:BANNER-TOP-HTML"; + public const string BannerBottomRegion = "CMS:BANNER-BOTTOM-HTML"; + public const string DataMarker = "CMS:DATA"; + public const string DataBlockId = "cms-data"; + public const string JsonLdMarker = "CMS:OFFER-JSON-LD"; + public const string PriceAttribute = "data-cms-price"; + + // The shape of GET /api/v1/offerings and /offerings/banner: camelCase, nulls written. + private static readonly JsonSerializerOptions ApiJson = new(JsonSerializerDefaults.Web); + + private static readonly JsonSerializerOptions LdJson = new() + { + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public bool Wants(string html) => HtmlMarkerEditor.HasMarkers(html); + + public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) + { + var wantsData = html.Contains("", StringComparison.Ordinal); + var wantsOfferings = wantsData + || html.Contains("", StringComparison.Ordinal) + || html.Contains("", StringComparison.Ordinal); + var wantsBottom = wantsData || html.Contains("", StringComparison.Ordinal); + + var live = wantsOfferings ? await offerings.GetOfferingsAsync() : []; + var top = wantsTop ? await banners.GetActiveAsync(OfferingBannerPositions.Top) : null; + var bottom = wantsBottom ? await banners.GetActiveAsync(OfferingBannerPositions.Bottom) : null; + + if (wantsOfferings) + { + html = HtmlMarkerEditor.ReplaceRegion(html, OfferingsRegion, CmsPageHtml.OfferingsList(live)); + html = HtmlMarkerEditor.EditJsonLd(html, JsonLdMarker, (slug, json) => EditOfferJsonLd(json, FindPrice(live, slug))); + html = HtmlMarkerEditor.ReplaceInlineValues(html, PriceAttribute, + slug => FindPrice(live, slug) is { } euros ? CmsPageHtml.PriceHtml(euros) : null); + } + + if (wantsTop) + { + html = HtmlMarkerEditor.ReplaceRegion(html, BannerTopRegion, CmsPageHtml.Banner(top, OfferingBannerPositions.Top)); + } + + if (wantsBottom) + { + html = HtmlMarkerEditor.ReplaceRegion(html, BannerBottomRegion, CmsPageHtml.Banner(bottom, OfferingBannerPositions.Bottom)); + } + + if (wantsData) + { + html = HtmlMarkerEditor.ReplaceDataBlock(html, DataMarker, DataBlockId, DataBlock(context.SiteUrl, live, top, bottom)); + } + + return html; + } + + /// The data block: the answers of the public API plus the address of the site, safe inside a script element. + public static string DataBlock(string siteUrl, IReadOnlyList live, PublicOfferingBannerDto? top, PublicOfferingBannerDto? bottom) + { + var json = JsonSerializer.Serialize( + new { siteUrl, offerings = live, banners = new { top, bottom } }, ApiJson); + return ""; + } + + private static int? FindPrice(IReadOnlyList live, string slug) + => live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering + ? CmsPageHtml.WholeEuros(offering.Price) + : null; + + /// + /// Sets offers.price (whole euros, a JSON number) on the node of the page's JSON-LD that has an offers + /// object; without a price (no live package, or a price text that is no price) offers is removed. Returns + /// null when the text is not JSON (the baked block is left alone). + /// + internal static string? EditOfferJsonLd(string json, int? euros) + { + JsonNode? root; + try + { + root = JsonNode.Parse(json); + } + catch (JsonException) + { + return null; + } + + if (root is null) + { + return null; + } + + var holder = FindOffersHolder(root); + if (holder is null) + { + return json; + } + + if (euros is null) + { + holder.Remove("offers"); + } + else + { + var offers = holder["offers"] is JsonArray array ? array.OfType().FirstOrDefault() : holder["offers"] as JsonObject; + if (offers is null) + { + return json; + } + + offers["price"] = euros.Value; + } + + // Valid JSON never contains a literal "