Updates the packages and the banner live in the browser

The build still bakes the current packages and the active banner into the HTML.
After hydration the page asks /api/v1/offerings and /api/v1/offerings/banner
once and replaces what differs; errors and time-outs keep what was baked, and
a 204 from the banner route hides the banner. The banner is now the
OfferingBanner contract (title, text, optional link) instead of layout=banner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 11:19:50 +01:00
co-authored by Claude Sonnet 5.5
parent f9180f231f
commit 12319bb841
22 changed files with 584 additions and 180 deletions
+171
View File
@@ -0,0 +1,171 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
isSafeBannerUrl,
mapBanner,
mapOfferings,
parsePriceText,
} from './offerings';
const card = (over: Record<string, unknown> = {}) => ({
id: 'x',
slug: 'newborn',
title: 'Newborn',
description: 'Mooie shoot',
price: '€ 185',
priceNote: 'incl. galerij',
features: ['1-2 uur fotografie', 'Online galerij'],
ctaLabel: 'Boek',
featured: false,
displayOrder: 2,
categoryId: null,
category: null,
layout: 'card',
...over,
});
describe('parsePriceText', () => {
it.each([
['€ 175', 175],
['€ 1.250', 1250],
['175,-', 175],
['€ 175,00', 175],
['€\u00a0185', 185],
])('leest %s als %i', (text, euros) => {
expect(parsePriceText(text)).toBe(euros);
});
it.each(['', 'op aanvraag', '€ 12,50', '€ 0', '175 of 185', null, 12])(
'geeft geen prijs voor %j',
(text) => {
expect(parsePriceText(text)).toBeNull();
},
);
it('geeft terug wat formatteren als hele euros oplevert', () => {
fc.assert(
fc.property(fc.integer({ min: 1, max: 99_999 }), (euros) => {
const grouped = euros.toLocaleString('nl-NL');
expect(parsePriceText(`€ ${grouped}`)).toBe(euros);
expect(parsePriceText(`€ ${euros}`)).toBe(euros);
}),
);
});
});
describe('mapOfferings', () => {
it('maakt pakketten in volgorde van displayOrder', () => {
const result = mapOfferings([
card({ slug: 'gezin', title: 'Gezin', displayOrder: 3 }),
card({
slug: 'zwangerschap',
title: 'Zwangerschap',
displayOrder: 1,
}),
card(),
]);
expect(result?.packages.map((p) => p.id)).toEqual([
'zwangerschap',
'newborn',
'gezin',
]);
expect(result?.packages[1]).toMatchObject({
name: 'Newborn',
price: 185,
priceNote: 'incl. galerij',
ctaLabel: 'Boek',
});
});
it('slaat ongeldige kaarten over en behoudt de rest', () => {
const result = mapOfferings([
card({ slug: 'Slecht Id' }),
card({ slug: 'a', price: 'op aanvraag' }),
card({ slug: 'b', title: ' ' }),
card({ slug: 'c', features: [] }),
card({ slug: 'd', features: ['ok', ''] }),
card({ slug: 'newborn' }),
card({ slug: 'newborn', title: 'Dubbel' }),
]);
expect(result?.packages.map((p) => p.id)).toEqual(['newborn']);
expect(result?.packages[0].name).toBe('Newborn');
});
it('verwerpt een antwoord zonder geldig pakket', () => {
expect(mapOfferings([])).toBeNull();
expect(mapOfferings([card({ price: '' })])).toBeNull();
expect(mapOfferings({ items: [] })).toBeNull();
expect(mapOfferings(null)).toBeNull();
expect(mapOfferings('fout')).toBeNull();
});
it('geeft nooit een pakket met lege of ongeldige prijs terug, wat er ook komt', () => {
fc.assert(
fc.property(fc.array(fc.jsonValue()), (answer) => {
const result = mapOfferings(answer);
for (const pkg of result?.packages ?? []) {
expect(Number.isInteger(pkg.price)).toBe(true);
expect(pkg.price).toBeGreaterThan(0);
expect(pkg.features.length).toBeGreaterThan(0);
}
}),
);
});
});
describe('mapBanner', () => {
it('neemt titel, tekst en een volledige link', () => {
expect(
mapBanner({
title: 'Kerstactie',
text: 'Alleen in december',
linkLabel: 'Boek nu',
linkUrl: '/contact',
}),
).toEqual({
title: 'Kerstactie',
text: 'Alleen in december',
link: { label: 'Boek nu', url: '/contact' },
});
});
it('laat lege velden en een halve of onveilige link weg', () => {
expect(
mapBanner({ title: 'T', text: '', linkLabel: null, linkUrl: null }),
).toEqual({ title: 'T', text: undefined, link: undefined });
expect(
mapBanner({ title: 'T', linkLabel: 'Hier', linkUrl: null })?.link,
).toBeUndefined();
expect(
mapBanner({
title: 'T',
linkLabel: 'Hier',
linkUrl: 'javascript:x',
})?.link,
).toBeUndefined();
});
it('geeft null zonder titel of zonder object', () => {
expect(mapBanner({ title: ' ' })).toBeNull();
expect(mapBanner(null)).toBeNull();
expect(mapBanner('x')).toBeNull();
expect(mapBanner([{ title: 'T' }])).toBeNull();
});
});
describe('isSafeBannerUrl', () => {
it.each(['https://example.nl/x', '/contact', '/#contact', '/a?b=1'])(
'staat %s toe',
(url) => expect(isSafeBannerUrl(url)).toBe(true),
);
it.each([
'http://example.nl',
'//evil.nl',
'javascript:alert(1)',
'mailto:a@b.nl',
'contact',
`/${String.fromCharCode(92)}evil`,
'https://',
'',
])('weigert %s', (url) => expect(isSafeBannerUrl(url)).toBe(false));
});
+142
View File
@@ -0,0 +1,142 @@
// Turns the answer of GET /api/v1/offerings (the CMS) into what the site
// shows: the shoot packages (cards) and the announcement banner. Pure functions, so
// they are tested without a network. The build step (fetchOfferings.ts) uses
// them; the site itself never calls the API (prices are in the HTML).
//
// Rule of the design: a bad answer never breaks the build and never leads to
// an empty or wrong price. Anything that is not clearly valid is dropped, and
// when no valid card is left the whole answer is rejected (null), so the
// caller keeps the last known list (the snapshot).
export interface OfferingPackage {
id: string;
name: string;
price: number; // whole euros
features: string[];
priceNote?: string;
description?: string;
ctaLabel?: string;
featured?: boolean;
}
// The announcement banner (GET /api/v1/offerings/banner). Only the title is
// required; the link is both parts or nothing.
export interface OfferingBanner {
title: string;
text?: string;
link?: { label: string; url: string };
}
export interface SiteOfferings {
packages: OfferingPackage[];
banner: OfferingBanner | null;
}
const SLUG = /^[a-z0-9-]+$/;
// "€ 175", "€ 1.250", "175,-", "€ 175,00" → whole euros. Anything else
// ("op aanvraag", "€ 12,50", "€ 0") has no usable price and gives null.
export function parsePriceText(text: unknown): number | null {
if (typeof text !== 'string') return null;
const match = /^\D*?(\d{1,3}(?:\.\d{3})+|\d+)(?:,(?:-|0{1,2}))?\D*$/.exec(
text.trim(),
);
if (!match) return null;
const euros = Number(match[1].replace(/\./g, ''));
return Number.isInteger(euros) && euros > 0 ? euros : null;
}
const asText = (value: unknown): string | undefined =>
typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
function asFeatures(value: unknown): string[] | null {
if (!Array.isArray(value)) return null;
const features = value.map(asText);
return features.length > 0 && features.every((f) => f !== undefined)
? (features as string[])
: null;
}
interface RawOffering {
[key: string]: unknown;
}
const isObject = (value: unknown): value is RawOffering =>
typeof value === 'object' && value !== null && !Array.isArray(value);
function toPackage(raw: RawOffering): OfferingPackage | null {
const id = asText(raw.slug);
const name = asText(raw.title);
const price = parsePriceText(raw.price);
const features = asFeatures(raw.features);
if (!id || !SLUG.test(id) || !name || price === null || !features) {
return null;
}
return {
id,
name,
price,
features,
priceNote: asText(raw.priceNote),
description: asText(raw.description),
ctaLabel: asText(raw.ctaLabel),
featured: raw.featured === true ? true : undefined,
};
}
// A link target the banner may use: https, or a path on this site with one
// leading slash (never '//', http, javascript: or mailto:)
export function isSafeBannerUrl(url: string): boolean {
if (url.startsWith('https://')) {
try {
return new URL(url).protocol === 'https:';
} catch {
return false;
}
}
return (
url.startsWith('/') &&
!url.startsWith('//') &&
!url.includes(String.fromCharCode(92))
);
}
// The 200 answer of /api/v1/offerings/banner, or null when it is not usable
// (no title, or a link that is half given or unsafe is left out)
export function mapBanner(answer: unknown): OfferingBanner | null {
if (!isObject(answer)) return null;
const title = asText(answer.title);
if (!title) return null;
const label = asText(answer.linkLabel);
const url = asText(answer.linkUrl);
return {
title,
text: asText(answer.text),
link: label && url && isSafeBannerUrl(url) ? { label, url } : undefined,
};
}
const orderOf = (raw: RawOffering) =>
typeof raw.displayOrder === 'number' ? raw.displayOrder : 0;
// null: the answer cannot be used (not a list, or no valid card)
export function mapOfferings(
answer: unknown,
): { packages: OfferingPackage[] } | null {
if (!Array.isArray(answer)) return null;
const rows = answer
.filter(isObject)
.map((raw, index) => ({ raw, index }))
.sort((a, b) => orderOf(a.raw) - orderOf(b.raw) || a.index - b.index)
.map(({ raw }) => raw);
const seen = new Set<string>();
const packages: OfferingPackage[] = [];
for (const raw of rows) {
const pkg = toPackage(raw);
if (!pkg || seen.has(pkg.id)) continue;
seen.add(pkg.id);
packages.push(pkg);
}
return packages.length > 0 ? { packages } : null;
}