ASF-injectie 3/5: CmsPageHtml (neutrale lijst + banner-HTML, prijsregels) en OfferingsHtmlTransform; golden files van ASF (16027f5) slagen

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 16:08:31 +01:00
co-authored by Claude Sonnet 5.5
parent a13661517d
commit ef4fb9dda5
29 changed files with 650 additions and 0 deletions
@@ -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;
/// <summary>
/// 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 <c>SlpModularCms.Modules.Offerings.Tests/Golden/host-injection</c> and are tested against this class.
/// </summary>
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();
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>The amount with a dot as thousands separator (1250 is "1.250").</summary>
public static string FormatAmount(int euros) => euros.ToString("#,##0", CultureInfo.InvariantCulture).Replace(',', '.');
/// <summary>"€&amp;nbsp;185": the euro sign, the entity for a non-breaking space (written as text) and the amount.</summary>
public static string PriceHtml(int euros) => "€&nbsp;" + FormatAmount(euros);
/// <summary>The offerings that have a place in the list: see <see cref="OfferingsList"/>.</summary>
internal static IReadOnlyList<(OfferingDto Offering, string Slug, string Title, int Euros, IReadOnlyList<string> Features)> Keep(
IReadOnlyList<OfferingDto> offerings)
{
var kept = new List<(OfferingDto, string, string, int, IReadOnlyList<string>)>();
var seen = new HashSet<string>(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;
}
/// <summary>
/// The packages as one plain list, or an empty string when no package is kept. A package is kept when its slug is
/// <c>[a-z0-9-]+</c> (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 <c>displayOrder</c>.
/// </summary>
public static string OfferingsList(IReadOnlyList<OfferingDto> offerings)
{
var kept = Keep(offerings);
if (kept.Count == 0)
{
return string.Empty;
}
var html = new StringBuilder("<ul class=\"cms-offerings\">");
foreach (var (offering, slug, title, euros, features) in kept)
{
var name = Encode(title);
var id = Encode(slug);
html.Append("<li class=\"cms-offering\" data-slug=\"").Append(id).Append('"')
.Append(offering.Featured ? " data-featured=\"true\"" : string.Empty).Append('>')
.Append("<h3>").Append(name).Append("</h3>")
.Append("<p class=\"cms-price\">").Append(PriceHtml(euros)).Append("</p>")
.Append("<ul class=\"cms-features\">");
foreach (var feature in features)
{
html.Append("<li>").Append(Encode(feature)).Append("</li>");
}
html.Append("</ul>")
.Append("<a href=\"/?pakket=").Append(id).Append("#contact\">Boek ").Append(name).Append("</a>")
.Append("</li>");
}
return html.Append("</ul>").ToString();
}
/// <summary>
/// A banner as one <c>&lt;aside&gt;</c>, 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.
/// </summary>
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<string>();
if (title.Length > 0) parts.Add("<strong>" + Encode(title) + "</strong>");
if (text.Length > 0) parts.Add("<span>" + Encode(text) + "</span>");
if (label.Length > 0 && url.Length > 0 && OfferingBannerLinks.IsAllowed(url))
{
parts.Add("<a href=\"" + Encode(url) + "\">" + Encode(label) + "</a>");
}
return "<aside class=\"cms-banner\">" + string.Join(' ', parts) + "</aside>";
}
/// <summary>Encodes exactly <c>&amp; &lt; &gt; " '</c> (other characters, accents included, stay as they are).</summary>
public static string Encode(string text)
{
var builder = new StringBuilder(text.Length + 8);
foreach (var c in text)
{
switch (c)
{
case '&': builder.Append("&amp;"); break;
case '<': builder.Append("&lt;"); break;
case '>': builder.Append("&gt;"); break;
case '"': builder.Append("&quot;"); break;
case '\'': builder.Append("&#39;"); break;
default: builder.Append(c); break;
}
}
return builder.ToString();
}
}
@@ -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;
/// <summary>
/// Writes the live packages and banners into a prerendered page (see <see cref="HtmlMarkerEditor"/> 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).
/// </summary>
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<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken)
{
var wantsData = html.Contains("<!--" + DataMarker + "-->", StringComparison.Ordinal);
var wantsOfferings = wantsData
|| html.Contains("<!--" + OfferingsRegion + "-->", StringComparison.Ordinal)
|| html.Contains("<!--" + JsonLdMarker, StringComparison.Ordinal)
|| html.Contains(PriceAttribute + "=", StringComparison.Ordinal);
var wantsTop = wantsData || html.Contains("<!--" + BannerTopRegion + "-->", StringComparison.Ordinal);
var wantsBottom = wantsData || html.Contains("<!--" + BannerBottomRegion + "-->", 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;
}
/// <summary>The data block: the answers of the public API plus the address of the site, safe inside a script element.</summary>
public static string DataBlock(string siteUrl, IReadOnlyList<OfferingDto> live, PublicOfferingBannerDto? top, PublicOfferingBannerDto? bottom)
{
var json = JsonSerializer.Serialize(
new { siteUrl, offerings = live, banners = new { top, bottom } }, ApiJson);
return "<script type=\"application/json\" id=\"" + DataBlockId + "\">" + HtmlMarkerEditor.EscapeForScript(json) + "</script>";
}
private static int? FindPrice(IReadOnlyList<OfferingDto> live, string slug)
=> live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering
? CmsPageHtml.WholeEuros(offering.Price)
: null;
/// <summary>
/// Sets <c>offers.price</c> (whole euros, a JSON number) on the node of the page's JSON-LD that has an <c>offers</c>
/// object; without a price (no live package, or a price text that is no price) <c>offers</c> is removed. Returns
/// null when the text is not JSON (the baked block is left alone).
/// </summary>
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<JsonObject>().FirstOrDefault() : holder["offers"] as JsonObject;
if (offers is null)
{
return json;
}
offers["price"] = euros.Value;
}
// Valid JSON never contains a literal "</script": the relaxed encoder does not escape "<", so do it here.
return root.ToJsonString(LdJson).Replace("</", "<\\/", StringComparison.Ordinal);
}
private static JsonObject? FindOffersHolder(JsonNode node)
{
switch (node)
{
case JsonObject obj:
if (obj["offers"] is JsonObject or JsonArray)
{
return obj;
}
foreach (var (_, child) in obj)
{
if (child is not null && FindOffersHolder(child) is { } found)
{
return found;
}
}
return null;
case JsonArray array:
foreach (var child in array)
{
if (child is not null && FindOffersHolder(child) is { } found)
{
return found;
}
}
return null;
default:
return null;
}
}
}