U6: IndexHtmlInjector (markers OFFERINGS-JSON-LD / OFFERINGS-HTML), 60s cache, invalidatie bij wijziging, ETag

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 23:48:48 +01:00
co-authored by Claude Sonnet 5.5
parent a7460a0f9b
commit 284ff1f91a
9 changed files with 430 additions and 2 deletions
@@ -0,0 +1,114 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Modules.Offerings.Models;
namespace SlpModularCms.Modules.Offerings.Services;
/// <summary>
/// Fills the website's <c>&lt;!--SLP:OFFERINGS-JSON-LD--&gt;</c> and <c>&lt;!--SLP:OFFERINGS-HTML--&gt;</c> markers with the
/// current offerings (banner included): a schema.org ItemList of Offers for search engines and a plain, semantic,
/// non-hydrated list that the React app removes at start-up. Both are empty when there are no offerings.
/// The contract (markers + the JSON of <c>GET /api/v1/offerings</c>) is host-independent: a build-time variant fills
/// the same markers from the same JSON.
/// </summary>
public sealed partial class OfferingsIndexMarkers(IOfferingsService offerings) : IIndexHtmlMarkerProvider
{
public const string JsonLdMarker = "SLP:OFFERINGS-JSON-LD";
public const string HtmlMarker = "SLP:OFFERINGS-HTML";
public async Task<IReadOnlyDictionary<string, string>> RenderAsync(string publicBaseUrl, CancellationToken cancellationToken)
{
var list = await offerings.GetOfferingsAsync();
return new Dictionary<string, string>
{
[JsonLdMarker] = JsonLd(list, publicBaseUrl),
[HtmlMarker] = Html(list),
};
}
[GeneratedRegex(@"€ ?([0-9.,]+)")]
private static partial Regex EuroPrice();
/// <summary>
/// The numeric price of a label like "€ 1.500,50" (Dutch notation: dot = thousands, comma = decimals), as
/// "1500.50"; null when the label is not parseable. Never guessed.
/// </summary>
internal static string? ParsePrice(string label)
{
var match = EuroPrice().Match(label ?? string.Empty);
if (!match.Success)
{
return null;
}
var digits = match.Groups[1].Value.Trim('.', ',').Replace(".", string.Empty).Replace(',', '.');
return decimal.TryParse(digits, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value)
? value.ToString(CultureInfo.InvariantCulture)
: null;
}
internal static string JsonLd(IReadOnlyList<OfferingDto> list, string baseUrl)
{
if (list.Count == 0)
{
return string.Empty;
}
var items = list.Select((o, index) =>
{
var offer = new Dictionary<string, object>
{
["@type"] = "Offer",
["name"] = o.Title,
["description"] = o.Description,
["url"] = baseUrl + "/#pakketten",
};
if (ParsePrice(o.Price) is { } price)
{
offer["price"] = price;
offer["priceCurrency"] = "EUR";
}
return new Dictionary<string, object>
{
["@type"] = "ListItem",
["position"] = index + 1,
["item"] = offer,
};
}).ToList();
var document = new Dictionary<string, object>
{
["@context"] = "https://schema.org",
["@type"] = "ItemList",
["itemListElement"] = items,
};
// The default encoder escapes <, > and &, so the JSON can never close the script element.
return "<script type=\"application/ld+json\">" + JsonSerializer.Serialize(document) + "</script>";
}
internal static string Html(IReadOnlyList<OfferingDto> list)
{
if (list.Count == 0)
{
return string.Empty;
}
var html = new StringBuilder("<section id=\"packages-static\" aria-label=\"Pakketten\"><ul>");
foreach (var o in list)
{
var priceLine = string.Join(' ', new[] { o.Price, o.PriceNote }.Where(part => !string.IsNullOrWhiteSpace(part)));
html.Append("<li><h3>").Append(WebUtility.HtmlEncode(o.Title)).Append("</h3><p>")
.Append(WebUtility.HtmlEncode(o.Description)).Append("</p><p>")
.Append(WebUtility.HtmlEncode(priceLine)).Append("</p></li>");
}
return html.Append("</ul></section>").ToString();
}
}
@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Modules.Offerings.Data.Entities;
using SlpModularCms.Modules.Offerings.Models;
using SlpModularCms.Modules.Offerings.Repositories;
@@ -8,7 +9,8 @@ namespace SlpModularCms.Modules.Offerings.Services;
public class OfferingsService(
IOfferingRepository repository,
IOfferingCategoryRepository categories,
ILogger<OfferingsService> logger) : IOfferingsService
ILogger<OfferingsService> logger,
IIndexHtmlCache? indexCache = null) : IOfferingsService
{
public async Task<IReadOnlyList<OfferingDto>> GetOfferingsAsync()
{
@@ -59,6 +61,7 @@ public class OfferingsService(
await repository.SaveChangesAsync();
}
indexCache?.Invalidate();
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Created", callerId);
@@ -112,6 +115,7 @@ public class OfferingsService(
await repository.SaveChangesAsync();
}
indexCache?.Invalidate();
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Updated", callerId);
@@ -134,6 +138,7 @@ public class OfferingsService(
repository.Update(offering);
await repository.SaveChangesAsync();
indexCache?.Invalidate();
logger.LogInformation(
"Offering {OfferingId} {Action} by user {LastModifiedByUserId}",
offering.Id, "Deleted", callerId);
@@ -171,6 +176,7 @@ public class OfferingsService(
await repository.SaveChangesAsync();
await transaction.CommitAsync();
indexCache?.Invalidate();
logger.LogInformation(
"Offerings reordered ({Count} items) by user {LastModifiedByUserId}",
orderedIds.Count, callerId);