feat: sync Geneva public holidays and let the shop choose which close it

The rolling twelve-month window is fetched from openholidaysapi.org each
night at 03:00 local, and can be triggered from the page, from
POST /api/admin/holidays/sync, or from `npm run holidays:sync` for the
first run after a deployment.

The calendar is fetched twice, once per language, and the two answers
joined on the entry id. Holiday names are proper nouns with established
English forms — "Jeûne genevois" is not something a translation model
should be improvising, and this costs one extra HTTP call.

Two properties are load-bearing and tested against a real database.
The sync is idempotent: running it twice leaves exactly what running it
once did, verified live as well as against a mock. And it never touches
`isAutoClosed` on an existing row — that is the shop's decision, not the
API's, and a nightly job quietly reopening a day the owner had closed
would be invisible until someone found the door locked.

When the API is down the local cache is left untouched and the failure
is recorded with its timestamp, so the page can say how stale the
calendar is rather than showing nothing. Retries widen the gap between
attempts; the nightly job can afford to wait, the shop cannot afford a
stale calendar for a day.

node-cron runs inside the application process rather than an external
cron hitting an endpoint: one container, one shop, no second instance to
coordinate with, and no trigger endpoint to protect and document. The
reasoning is recorded next to the schedule.

Verified against the live API: nine Geneva holidays, both languages,
including the cantonal Restauration de la République.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012cSY9pVhZmJUKNN7wf1Myd
This commit is contained in:
2026-09-20 21:23:47 +02:00
co-authored by Claude Opus 5
parent ea945b50d6
commit 830e595393
12 changed files with 921 additions and 1 deletions
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it, vi } from 'vitest';
import { parseHolidays, withRetries, type ApiHoliday } from './openholidays';
const FR: ApiHoliday[] = [
{
id: 'a',
startDate: '2026-09-10',
endDate: '2026-09-10',
nationwide: false,
name: [{ language: 'FR', text: 'Jeûne genevois' }],
},
{
id: 'b',
startDate: '2026-12-25',
endDate: '2026-12-25',
nationwide: true,
name: [{ language: 'FR', text: 'Noël' }],
},
];
const EN: ApiHoliday[] = [
{ id: 'a', startDate: '2026-09-10', endDate: '2026-09-10', name: [{ language: 'EN', text: 'Geneva Fast' }] },
{ id: 'b', startDate: '2026-12-25', endDate: '2026-12-25', name: [{ language: 'EN', text: 'Christmas Day' }] },
];
describe('parseHolidays', () => {
it('joins the two language calls on the entry id', () => {
// Holiday names are proper nouns with established English forms; joining
// beats sending them through a translation model.
expect(parseHolidays(FR, EN)).toEqual([
{ date: '2026-09-10', nameFr: 'Jeûne genevois', nameEn: 'Geneva Fast', nationwide: false },
{ date: '2026-12-25', nameFr: 'Noël', nameEn: 'Christmas Day', nationwide: true },
]);
});
it('falls back to the French name when the English call comes back short', () => {
expect(parseHolidays(FR, [])[0]).toMatchObject({ nameFr: 'Jeûne genevois', nameEn: 'Jeûne genevois' });
});
it('expands an entry that spans several days', () => {
const spanning: ApiHoliday[] = [
{
id: 'c',
startDate: '2026-12-24',
endDate: '2026-12-26',
name: [{ language: 'FR', text: 'Fêtes' }],
},
];
expect(parseHolidays(spanning, []).map((holiday) => holiday.date)).toEqual([
'2026-12-24',
'2026-12-25',
'2026-12-26',
]);
});
it('treats a missing end date as a single day', () => {
const single: ApiHoliday[] = [
{ id: 'd', startDate: '2026-08-01', endDate: '', name: [{ language: 'FR', text: 'Fête nationale' }] },
];
expect(parseHolidays(single, [])).toHaveLength(1);
});
it('ignores a reversed range rather than spinning', () => {
const reversed: ApiHoliday[] = [
{ id: 'e', startDate: '2026-08-05', endDate: '2026-08-01', name: [{ language: 'FR', text: 'X' }] },
];
expect(parseHolidays(reversed, [])).toHaveLength(1);
});
it('drops an entry with no usable name', () => {
expect(parseHolidays([{ id: 'f', startDate: '2026-08-01', endDate: '2026-08-01' }], [])).toEqual([]);
});
it('defaults an unstated scope to nationwide', () => {
const vague: ApiHoliday[] = [
{ id: 'g', startDate: '2026-08-01', endDate: '2026-08-01', name: [{ language: 'FR', text: 'X' }] },
];
expect(parseHolidays(vague, [])[0]?.nationwide).toBe(true);
});
it('accepts an empty calendar', () => {
expect(parseHolidays([], [])).toEqual([]);
});
});
describe('withRetries', () => {
it('returns the first success without waiting', async () => {
const sleep = vi.fn(async (_ms: number) => undefined);
expect(await withRetries(async () => 'ok', 3, 100, sleep)).toBe('ok');
expect(sleep).not.toHaveBeenCalled();
});
it('retries and widens the gap', async () => {
const sleep = vi.fn(async (_ms: number) => undefined);
let attempts = 0;
const result = await withRetries(
async () => {
attempts += 1;
if (attempts < 3) {
throw new Error('transient');
}
return 'ok';
},
3,
100,
sleep,
);
expect(result).toBe('ok');
expect(sleep.mock.calls.map((call) => call[0])).toEqual([100, 200]);
});
it('gives up after the last attempt and reports the final error', async () => {
const sleep = vi.fn(async (_ms: number) => undefined);
await expect(
withRetries(
async () => {
throw new Error('toujours en panne');
},
3,
10,
sleep,
),
).rejects.toThrow('toujours en panne');
expect(sleep).toHaveBeenCalledTimes(2);
});
});
+124
View File
@@ -0,0 +1,124 @@
/**
* Client for openholidaysapi.org.
*
* The API answers in one language at a time, so the calendar is fetched twice
* and the two answers are joined on the entry id. That is cheaper and far more
* reliable than sending holiday names through the translation service: these
* are proper nouns with established English forms, and "Jeûne genevois" is not
* something a model should be improvising.
*/
import { addCivilDays, compareCivil, type CivilDate } from '@/lib/schedule/civil';
export type ApiHoliday = {
id: string;
startDate: string;
endDate: string;
nationwide?: boolean;
name?: { language: string; text: string }[];
};
export type ParsedHoliday = {
date: CivilDate;
nameFr: string;
nameEn: string;
nationwide: boolean;
};
export type FetchOptions = {
baseUrl: string;
countryIsoCode: string;
subdivisionCode: string;
validFrom: CivilDate;
validTo: CivilDate;
signal?: AbortSignal;
};
/** A single entry can span days; each day becomes its own row. */
export function parseHolidays(french: ApiHoliday[], english: ApiHoliday[]): ParsedHoliday[] {
const englishById = new Map(english.map((entry) => [entry.id, textOf(entry, 'EN')]));
const parsed: ParsedHoliday[] = [];
for (const entry of french) {
const nameFr = textOf(entry, 'FR');
if (!nameFr || !entry.startDate) {
continue;
}
// Falling back to the French name keeps the screen bilingual-ish rather
// than blank if the English call ever comes back short.
const nameEn = englishById.get(entry.id) || nameFr;
const end = entry.endDate && compareCivil(entry.endDate, entry.startDate) >= 0 ? entry.endDate : entry.startDate;
let cursor = entry.startDate;
// Bounded: a malformed range must not spin.
for (let guard = 0; compareCivil(cursor, end) <= 0 && guard < 31; guard += 1) {
parsed.push({ date: cursor, nameFr, nameEn, nationwide: entry.nationwide ?? true });
cursor = addCivilDays(cursor, 1);
}
}
return parsed;
}
export async function fetchHolidays(options: FetchOptions): Promise<ParsedHoliday[]> {
const [french, english] = await Promise.all([
request(options, 'FR'),
request(options, 'EN'),
]);
return parseHolidays(french, english);
}
async function request(options: FetchOptions, language: 'FR' | 'EN'): Promise<ApiHoliday[]> {
const url = new URL('/PublicHolidays', options.baseUrl);
url.searchParams.set('countryIsoCode', options.countryIsoCode);
url.searchParams.set('subdivisionCode', options.subdivisionCode);
url.searchParams.set('languageIsoCode', language);
url.searchParams.set('validFrom', options.validFrom);
url.searchParams.set('validTo', options.validTo);
const response = await fetch(url, {
signal: options.signal ?? AbortSignal.timeout(15_000),
headers: { accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`openholidaysapi a répondu ${response.status}`);
}
const body: unknown = await response.json();
return Array.isArray(body) ? (body as ApiHoliday[]) : [];
}
function textOf(entry: ApiHoliday, language: string): string {
const names = entry.name ?? [];
const match = names.find((name) => name.language?.toUpperCase() === language);
return (match?.text ?? names[0]?.text ?? '').trim();
}
/**
* Retries with a widening gap.
*
* The daily sync can afford to wait; failing on a transient blip and leaving
* the shop with a stale calendar for a day cannot be afforded.
*/
export async function withRetries<T>(
work: () => Promise<T>,
attempts = 3,
delayMs = 500,
sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
): Promise<T> {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
return await work();
} catch (error) {
lastError = error;
if (attempt < attempts - 1) {
await sleep(delayMs * 2 ** attempt);
}
}
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
+132
View File
@@ -0,0 +1,132 @@
/**
* Keeps a rolling twelve-month window of public holidays in the local cache.
*
* Idempotent by construction: running it twice leaves exactly what running it
* once did. The one field it never touches on an existing row is
* `isAutoClosed` — that is the shop's decision, not the API's, and a nightly
* job quietly reopening a day the owner had closed would be the worst kind of
* bug: invisible until someone finds the door locked.
*/
import { prisma } from '@/lib/db';
import { addCivilDays, toCivilDate, type CivilDate } from '@/lib/schedule/civil';
import { loadSettings } from '@/lib/schedule/context';
import { fetchHolidays, withRetries, type ParsedHoliday } from './openholidays';
export const SYNC_KEY = 'holidays';
export type SyncOutcome =
| { ok: true; created: number; updated: number; removed: number; from: CivilDate; to: CivilDate }
| { ok: false; error: string };
export type SyncDeps = {
fetcher?: (options: {
baseUrl: string;
countryIsoCode: string;
subdivisionCode: string;
validFrom: CivilDate;
validTo: CivilDate;
}) => Promise<ParsedHoliday[]>;
now?: Date;
};
export async function syncHolidays(deps: SyncDeps = {}): Promise<SyncOutcome> {
const now = deps.now ?? new Date();
const settings = await loadSettings();
const today = toCivilDate(now, settings.timezone);
const from = today;
const to = addCivilDays(today, 365);
const options = {
baseUrl: process.env.HOLIDAYS_API_URL ?? 'https://openholidaysapi.org',
countryIsoCode: settings.countryIsoCode,
subdivisionCode: settings.subdivisionCode,
validFrom: from,
validTo: to,
};
let holidays: ParsedHoliday[];
try {
const fetcher = deps.fetcher ?? ((input) => fetchHolidays(input));
holidays = await withRetries(() => fetcher(options));
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await prisma.syncState.upsert({
where: { key: SYNC_KEY },
update: { lastErrorAt: now, lastError: message.slice(0, 500) },
create: { key: SYNC_KEY, lastErrorAt: now, lastError: message.slice(0, 500) },
});
// The local cache is left exactly as it was: a stale calendar beats none.
return { ok: false, error: message };
}
const existing = await prisma.publicHoliday.findMany({
where: {
subdivisionCode: settings.subdivisionCode,
date: { gte: asDate(from), lte: asDate(to) },
},
});
const existingByDate = new Map(existing.map((row) => [asCivil(row.date), row]));
let created = 0;
let updated = 0;
for (const holiday of holidays) {
const current = existingByDate.get(holiday.date);
if (current) {
const changed =
current.nameFr !== holiday.nameFr ||
current.nameEn !== holiday.nameEn ||
current.nationwide !== holiday.nationwide;
if (changed) {
updated += 1;
}
await prisma.publicHoliday.update({
where: { id: current.id },
data: {
nameFr: holiday.nameFr,
nameEn: holiday.nameEn,
nationwide: holiday.nationwide,
syncedAt: now,
// isAutoClosed deliberately absent: the shop owns that choice.
},
});
} else {
created += 1;
await prisma.publicHoliday.create({
data: {
date: asDate(holiday.date),
nameFr: holiday.nameFr,
nameEn: holiday.nameEn,
nationwide: holiday.nationwide,
subdivisionCode: settings.subdivisionCode,
syncedAt: now,
},
});
}
}
// Days the API no longer lists — a cancelled or corrected holiday.
const fetchedDates = new Set(holidays.map((holiday) => holiday.date));
const stale = existing.filter((row) => !fetchedDates.has(asCivil(row.date)));
if (stale.length > 0) {
await prisma.publicHoliday.deleteMany({ where: { id: { in: stale.map((row) => row.id) } } });
}
await prisma.syncState.upsert({
where: { key: SYNC_KEY },
update: { lastSuccessAt: now, lastErrorAt: null, lastError: null },
create: { key: SYNC_KEY, lastSuccessAt: now },
});
return { ok: true, created, updated, removed: stale.length, from, to };
}
function asCivil(value: Date): CivilDate {
return value.toISOString().slice(0, 10);
}
function asDate(value: CivilDate): Date {
return new Date(`${value}T00:00:00.000Z`);
}