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:
@@ -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();
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user