Reads the shoot packages and an optional banner from the CMS at build time

The build asks GET /api/v1/offerings and bakes the packages into the pages,
with a committed snapshot as fallback so a CMS outage never breaks the build
or shows an empty price. The form choices and ?pakket= use the same list. An
offering with layout=banner becomes an optional band under the price cards.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 08:13:01 +01:00
co-authored by Claude Sonnet 5.5
parent 7737104a77
commit 5bfbde1881
16 changed files with 626 additions and 40 deletions
+3
View File
@@ -30,3 +30,6 @@ lighthouse-reports
# Gegenereerde cache van Start
.tanstack
# Written by config/fetchOfferings.ts before every build
src/content/offerings.generated.json
+69
View File
@@ -0,0 +1,69 @@
// Build step, runs before the build: asks the CMS for the shoot packages and
// writes src/content/offerings.generated.json, which the site imports. With
// no address, a failing CMS or an unusable answer the committed snapshot
// (src/content/offerings.snapshot.json) is used, so the build never fails
// and never shows empty prices. The log says which one was used.
//
// OFFERINGS_URL: the site's own address that serves the API, for example
// https://test.andreaslop.nl (the API is same-origin, /api/v1/offerings).
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { mapOfferings, type SiteOfferings } from './offerings.ts';
const SNAPSHOT = fileURLToPath(
new URL('../src/content/offerings.snapshot.json', import.meta.url),
);
const GENERATED = fileURLToPath(
new URL('../src/content/offerings.generated.json', import.meta.url),
);
const TIMEOUT_MS = 10_000;
const ATTEMPTS = 2;
async function fetchAnswer(base: string): Promise<unknown> {
const url = new URL('/api/v1/offerings', base);
for (let attempt = 1; ; attempt++) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(TIMEOUT_MS),
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error(`status ${response.status}`);
return await response.json();
} catch (error) {
if (attempt >= ATTEMPTS) throw error;
}
}
}
async function main() {
const snapshot = JSON.parse(
readFileSync(SNAPSHOT, 'utf8'),
) as SiteOfferings;
const base = process.env.OFFERINGS_URL?.trim();
let result = { ...snapshot, source: 'snapshot' };
if (!base) {
console.log('[offerings] no OFFERINGS_URL: using the snapshot');
} else {
try {
const mapped = mapOfferings(await fetchAnswer(base));
if (mapped) {
result = { ...mapped, source: 'cms' };
console.log(
`[offerings] ${mapped.packages.length} packages` +
`${mapped.banner ? ' and a banner' : ''} from ${base}`,
);
} else {
console.warn(
`[offerings] answer of ${base} has no valid package: using the snapshot`,
);
}
} catch (error) {
console.warn(
`[offerings] ${base} not reachable (${String(error)}): using the snapshot`,
);
}
}
writeFileSync(GENERATED, JSON.stringify(result, null, 4) + '\n');
}
await main();
+135
View File
@@ -0,0 +1,135 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { 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',
});
expect(result?.banner).toBeNull();
});
it('houdt de banner buiten de pakketten en neemt de eerste bruikbare', () => {
const result = mapOfferings([
card(),
card({
slug: 'actie',
title: 'Kerstactie',
price: '€ 99 i.p.v. € 150',
layout: 'banner',
displayOrder: 9,
}),
card({
slug: 'actie2',
title: 'Tweede',
layout: 'banner',
displayOrder: 10,
}),
]);
expect(result?.packages.map((p) => p.id)).toEqual(['newborn']);
expect(result?.banner).toMatchObject({
title: 'Kerstactie',
priceText: '€ 99 i.p.v. € 150',
});
});
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([card({ layout: 'banner' })])).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);
}
}),
);
});
});
+130
View File
@@ -0,0 +1,130 @@
// Turns the answer of GET /api/v1/offerings (the CMS) into what the site
// shows: the shoot packages (cards) and at most one 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;
}
export interface OfferingBanner {
title: string;
description: string;
priceText: string;
priceNote?: string;
features: string[];
ctaLabel?: 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,
};
}
function toBanner(raw: RawOffering): OfferingBanner | null {
const title = asText(raw.title);
const priceText = asText(raw.price);
const features = asFeatures(raw.features);
if (!title || !priceText || !features) return null;
return {
title,
description: asText(raw.description) ?? '',
priceText,
priceNote: asText(raw.priceNote),
features,
ctaLabel: asText(raw.ctaLabel),
};
}
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): SiteOfferings | 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[] = [];
let banner: OfferingBanner | null = null;
for (const raw of rows) {
if (raw.layout === 'banner') {
// The CMS allows one banner per site; the first usable one wins
banner ??= toBanner(raw);
continue;
}
const pkg = toPackage(raw);
if (!pkg || seen.has(pkg.id)) continue;
seen.add(pkg.id);
packages.push(pkg);
}
return packages.length > 0 ? { packages, banner } : null;
}
+1 -1
View File
@@ -6,7 +6,7 @@
"packageManager": "pnpm@12.11.2",
"scripts": {
"dev": "vite",
"build": "tsc && vite build && node config/externalizeInlineScripts.ts",
"build": "node config/fetchOfferings.ts && tsc && vite build && node config/externalizeInlineScripts.ts",
"preview": "node config/previewServer.ts",
"e2e": "vitest run --config vitest.e2e.config.ts",
"postinstall": "chakra typegen ./src/theme.ts",
@@ -0,0 +1,88 @@
import { Box, chakra, Heading, Text, useRecipe } from '@chakra-ui/react';
import { Link } from '@tanstack/react-router';
import type { PricingBanner } from '@/content/types';
type PriceBannerProps = {
banner: PricingBanner;
};
// The optional dark band under the price cards (an offering with
// layout=banner in the CMS), for an offer or an announcement. It is not a
// bookable package: the button only leads to the contact form, without a
// chosen package. The price is free text from the CMS ("€ 99 i.p.v. € 150").
export default function PriceBanner({ banner }: PriceBannerProps) {
const linkButton = useRecipe({ key: 'linkButton' });
return (
<Box
as="aside"
aria-labelledby="price-banner-title"
data-testid="price-banner"
mt="gridGap"
px="clamp(1.5rem, 4vw, 3.5rem)"
py="clamp(2rem, 4vw, 3rem)"
bg="ink"
color="white"
display="grid"
gap={{ base: 6, md: 10 }}
gridTemplateColumns={{ base: '1fr', md: '1fr auto' }}
alignItems="center"
>
<Box>
<Heading
as="h3"
id="price-banner-title"
fontSize="1.5rem"
color="white"
mb={2}
>
{banner.title}
</Heading>
{banner.description && (
<Text color="white" opacity={0.85} mb={3}>
{banner.description}
</Text>
)}
{banner.features.length > 0 && (
<chakra.ul
listStyleType="none"
display="flex"
flexWrap="wrap"
columnGap={6}
rowGap={1}
fontSize="sm"
opacity={0.85}
>
{banner.features.map((feature) => (
<chakra.li key={feature}>{feature}</chakra.li>
))}
</chakra.ul>
)}
</Box>
<Box textAlign={{ base: 'start', md: 'center' }}>
<Text
fontFamily="heading"
fontSize="1.75rem"
lineHeight="1.1"
color="white"
>
{banner.priceText}
</Text>
{banner.priceNote && (
<Text fontSize="sm" opacity={0.85} mb={4}>
{banner.priceNote}
</Text>
)}
<Box
asChild
css={linkButton({ variant: 'light', size: 'fit' })}
mt={banner.priceNote ? 0 : 4}
>
<Link to="/" hash="contact" data-testid="price-banner-cta">
{banner.ctaLabel ?? 'Neem contact op'}
</Link>
</Box>
</Box>
</Box>
);
}
@@ -32,6 +32,44 @@ describe('Pricing', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows an optional banner under the cards, not as a package', async () => {
const banner = {
title: 'Kerstactie',
description: 'Alleen in december',
priceText: '€ 99 i.p.v. € 150',
priceNote: 'tot 31 december',
features: ['30 minuten', '10 foto’s'],
ctaLabel: 'Boek de actie',
};
const { container } = await renderWithProviders(
<Pricing content={content} packages={packages} banner={banner} />,
);
const section = screen.getByRole('region', { name: 'Prijzen' });
const shown = within(section).getByTestId('price-banner');
expect(
within(shown).getByText('€ 99 i.p.v. € 150'),
).toBeInTheDocument();
expect(
within(shown).getByRole('link', { name: 'Boek de actie' }),
).toHaveAttribute('href', '/#contact');
// The cards are still the three packages: no card and no booking
// link with a package for the banner
expect(
within(section).queryByTestId('price-card-kerstactie'),
).not.toBeInTheDocument();
expect(
within(section).getAllByTestId(/^price-card-[a-z]+$/),
).toHaveLength(3);
expect(await axeResults(container)).toHaveNoViolations();
});
it('shows no banner without one', async () => {
await renderWithProviders(
<Pricing content={content} packages={packages} banner={null} />,
);
expect(screen.queryByTestId('price-banner')).not.toBeInTheDocument();
});
it('can be linked to as /#prijzen', async () => {
await renderWithProviders(
<Pricing content={content} packages={packages} />,
+14 -2
View File
@@ -3,8 +3,13 @@ import DeferredImage from '@/components/DeferredImage/DeferredImage';
import PageSection from '@/components/PageSection/PageSection';
import Reveal from '@/components/Reveal/Reveal';
import SectionHeading from '@/components/SectionHeading/SectionHeading';
import type { HomeContent, PricingPackage } from '@/content/types';
import type {
HomeContent,
PricingBanner,
PricingPackage,
} from '@/content/types';
import { visiblePackages } from '@/lib/visiblePackages';
import PriceBanner from './PriceBanner';
import PriceCard from './PriceCard';
const TITLE_ID = 'pricing-title';
@@ -22,12 +27,14 @@ const decorationPositions = [
type PricingProps = {
content: HomeContent['pricing'];
packages: PricingPackage[];
// Optional band under the cards; not a package
banner?: PricingBanner | null;
};
// "Prijzen": the shoot packages as cards (design .pricing). One column on
// phones and tablets, three from `lg`. Without a valid package the section
// is left out entirely.
export default function Pricing({ content, packages }: PricingProps) {
export default function Pricing({ content, packages, banner }: PricingProps) {
const shown = visiblePackages(packages);
if (shown.length === 0) return null;
@@ -72,6 +79,11 @@ export default function Pricing({ content, packages }: PricingProps) {
</Reveal>
))}
</Grid>
{banner && (
<Reveal>
<PriceBanner banner={banner} />
</Reveal>
)}
</Box>
</PageSection>
);
+35
View File
@@ -0,0 +1,35 @@
{
"packages": [
{
"id": "zwangerschap",
"name": "Zwangerschap",
"price": 175,
"features": [
"1 uur fotografie",
"Minstens 30 zorgvuldig nabewerkte foto's",
"Persoonlijke online fotogalerij"
]
},
{
"id": "newborn",
"name": "Newborn",
"price": 185,
"features": [
"1-2 uur fotografie",
"Minstens 40 zorgvuldig nabewerkte foto's",
"Persoonlijke online fotogalerij"
]
},
{
"id": "gezin",
"name": "Gezin",
"price": 175,
"features": [
"1 uur fotografie",
"Minstens 30 zorgvuldig nabewerkte foto's",
"Persoonlijke online fotogalerij"
]
}
],
"banner": null
}
+27 -35
View File
@@ -1,38 +1,30 @@
import type { PricingPackage } from './types';
import type { PricingBanner, PricingPackage } from './types';
import snapshot from './offerings.snapshot.json';
// The shoot packages until the CMS API exists (live site, October 2026), in
// display order. Andrea uses the small business scheme (KOR): no VAT.
const packages: PricingPackage[] = [
{
id: 'zwangerschap',
name: 'Zwangerschap',
price: 175,
features: [
'1 uur fotografie',
"Minstens 30 zorgvuldig nabewerkte foto's",
'Persoonlijke online fotogalerij',
],
},
{
id: 'newborn',
name: 'Newborn',
price: 185,
features: [
'1-2 uur fotografie',
"Minstens 40 zorgvuldig nabewerkte foto's",
'Persoonlijke online fotogalerij',
],
},
{
id: 'gezin',
name: 'Gezin',
price: 175,
features: [
'1 uur fotografie',
"Minstens 30 zorgvuldig nabewerkte foto's",
'Persoonlijke online fotogalerij',
],
},
];
interface Offerings {
packages: PricingPackage[];
banner: PricingBanner | null;
}
// The shoot packages and the optional banner. config/fetchOfferings.ts writes
// offerings.generated.json before every build with what the CMS says; without
// it (tests, a build without CMS address, a CMS that is down) the committed
// snapshot is used. Andrea uses the small business scheme (KOR): no VAT.
// Tests always use the snapshot, so they do not depend on a build.
const generated =
import.meta.env.MODE === 'test'
? {}
: import.meta.glob<Offerings>('./offerings.generated.json', {
eager: true,
import: 'default',
});
const offerings: Offerings =
generated['./offerings.generated.json'] ?? (snapshot as Offerings);
// In display order
const packages: PricingPackage[] = offerings.packages;
export const banner: PricingBanner | null = offerings.banner;
export default packages;
+17
View File
@@ -94,6 +94,23 @@ export interface PricingPackage {
name: string;
price: number; // whole euros
features: string[];
// From the CMS offering; all optional
priceNote?: string;
description?: string;
ctaLabel?: string;
featured?: boolean;
}
// The one optional banner under the price cards (an offering with
// layout=banner in the CMS). It is not a bookable package: it is not in the
// form's choices and not in the package count. The price is free text.
export interface PricingBanner {
title: string;
description: string;
priceText: string;
priceNote?: string;
features: string[];
ctaLabel?: string;
}
// The kinds of shoot Andrea offers. The ids are stable: they go into URLs
+6 -2
View File
@@ -9,7 +9,7 @@ import IntroGallery from '../components/home/IntroGallery/IntroGallery';
import heroContent from '../content/heroContent';
import homeContent from '../content/homeContent';
import instagramContent from '../content/instagramContent';
import packages from '../content/packages';
import packages, { banner } from '../content/packages';
import testimonials from '../content/testimonials';
import siteContent from '../content/siteContent';
import { visibleSocials } from '../lib/visibleSocials';
@@ -42,7 +42,11 @@ function Index() {
<Hero content={heroContent} socials={siteContent.socials} />
<IntroGallery content={homeContent.intro} />
<AboutBlock content={homeContent.about} />
<Pricing content={homeContent.pricing} packages={packages} />
<Pricing
content={homeContent.pricing}
packages={packages}
banner={banner}
/>
<Testimonials
content={homeContent.testimonials}
testimonials={testimonials}