mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
fix(vacay): move holiday lookups to Nager.Holidays v4
This commit is contained in:
@@ -146,7 +146,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
|
||||
#### 🗺️ Atlas, Vacay and Collections
|
||||
|
||||
- **Atlas**: countries and regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, a bucket list, travel stats, and a tour activities tab with planned against recorded totals
|
||||
- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
|
||||
- **Vacay**: leave calendar with half days, public holidays from [nagerholidays.com](https://nagerholidays.com), school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
|
||||
- **Collections** (off by default): a place library outside any trip with lists, labels, ratings, a status per place, cover images, GPX and file export, copy into a trip, and sharing by invite
|
||||
- **Dawarich** (off by default): link a Dawarich instance for recorded tracks, suggested stays and countries for the Atlas
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ function calendarRegionCodes(country: string, data: unknown): { region: string;
|
||||
* `if (W)` checks, resolved by trekMcpAccessPolicy). Vacay is plan-scoped, not
|
||||
* trip-scoped, so there is no trip-permission layer; the only per-call guard is
|
||||
* the demo-user check on every write (including decline_vacay_invite, which the
|
||||
* legacy registrar missed). The nager.at- and openholidaysapi-backed lookups
|
||||
* legacy registrar missed). The nagerholidays.com- and openholidaysapi-backed lookups
|
||||
* carry the open-world readonly annotation.
|
||||
*
|
||||
* Tools past the original 26 close REST surface the legacy registrar never had:
|
||||
|
||||
@@ -80,6 +80,37 @@ export interface Holiday {
|
||||
counties?: string[] | null;
|
||||
}
|
||||
|
||||
interface NagerHolidayV4 {
|
||||
date: string;
|
||||
name: string;
|
||||
nationalHoliday: boolean;
|
||||
subdivisionCodes: string[] | null;
|
||||
}
|
||||
|
||||
/** Adapt Nager.Holidays v4 records to Vacay's long-standing holiday shape. */
|
||||
function normalizeNagerHolidays(data: unknown): Holiday[] | undefined {
|
||||
if (!Array.isArray(data)) return undefined;
|
||||
const holidays: Holiday[] = [];
|
||||
for (const row of data) {
|
||||
if (
|
||||
!row || typeof row !== 'object' ||
|
||||
typeof row.date !== 'string' || typeof row.name !== 'string' ||
|
||||
typeof row.nationalHoliday !== 'boolean' ||
|
||||
(row.subdivisionCodes !== null &&
|
||||
(!Array.isArray(row.subdivisionCodes) || row.subdivisionCodes.some((code: unknown) => typeof code !== 'string')))
|
||||
) return undefined;
|
||||
const holiday = row as NagerHolidayV4;
|
||||
holidays.push({
|
||||
date: holiday.date,
|
||||
name: holiday.name,
|
||||
localName: holiday.name,
|
||||
global: holiday.nationalHoliday,
|
||||
counties: holiday.subdivisionCodes,
|
||||
});
|
||||
}
|
||||
return holidays;
|
||||
}
|
||||
|
||||
export interface SchoolHoliday {
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
@@ -134,7 +165,7 @@ export interface VacayShare {
|
||||
* imports.
|
||||
*
|
||||
* Multi-statement writes run in uow.transactional(), never around the
|
||||
* nager.at fetch (timed out and ok-checked, cached per instance for the TTL);
|
||||
* nagerholidays.com fetch (timed out and ok-checked, cached per instance for the TTL);
|
||||
* addYear does not swallow real errors. TripsService injects this class.
|
||||
*
|
||||
* `removeShare`/`setShareHidden` scope their ownership check in the SQL
|
||||
@@ -449,9 +480,10 @@ export class VacayService {
|
||||
if (cached && Date.now() - cached.time < CACHE_TTL) return cached.data as Holiday[];
|
||||
if (!COUNTRY_RE.test(country)) return undefined;
|
||||
try {
|
||||
const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
const resp = await fetch(`https://nagerholidays.com/api/v4/Holidays/${country}/${year}`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) { discardBody(resp); return undefined; }
|
||||
const parsed = await readCappedJson<Holiday[]>(resp, MAX_HOLIDAY_BYTES);
|
||||
const data = await readCappedJson<unknown>(resp, MAX_HOLIDAY_BYTES);
|
||||
const parsed = normalizeNagerHolidays(data);
|
||||
if (parsed === undefined) return undefined;
|
||||
this.holidayCache.set(cacheKey, { data: parsed, time: Date.now() });
|
||||
return parsed;
|
||||
@@ -1284,7 +1316,7 @@ export class VacayService {
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Holidays (nager.at proxy with cache)
|
||||
// Holidays (nagerholidays.com proxy with cache)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
async getCountries(): Promise<{ data?: unknown }> {
|
||||
@@ -1292,7 +1324,7 @@ export class VacayService {
|
||||
const cached = this.holidayCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data };
|
||||
try {
|
||||
const resp = await fetch('https://date.nager.at/api/v3/AvailableCountries', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
const resp = await fetch('https://nagerholidays.com/api/v4/Countries/Available', { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) { discardBody(resp); throw new DomainError(502, 'Failed to fetch countries'); }
|
||||
const data = await readCappedJson(resp, MAX_HOLIDAY_BYTES);
|
||||
if (data === undefined) throw new DomainError(502, 'Failed to fetch countries');
|
||||
@@ -1307,19 +1339,9 @@ export class VacayService {
|
||||
// Both segments land in the URL path, so they are checked before the cache
|
||||
// lookup rather than after it.
|
||||
if (!YEAR_RE.test(year) || !COUNTRY_RE.test(country)) throw new DomainError(502, 'Failed to fetch holidays');
|
||||
const cacheKey = `${year}-${country}`;
|
||||
const cached = this.holidayCache.get(cacheKey);
|
||||
if (cached && Date.now() - cached.time < CACHE_TTL) return { data: cached.data };
|
||||
try {
|
||||
const resp = await fetch(`https://date.nager.at/api/v3/PublicHolidays/${year}/${country}`, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!resp.ok) { discardBody(resp); throw new DomainError(502, 'Failed to fetch holidays'); }
|
||||
const data = await readCappedJson(resp, MAX_HOLIDAY_BYTES);
|
||||
if (data === undefined) throw new DomainError(502, 'Failed to fetch holidays');
|
||||
this.holidayCache.set(cacheKey, { data, time: Date.now() });
|
||||
return { data };
|
||||
} catch {
|
||||
throw new DomainError(502, 'Failed to fetch holidays');
|
||||
}
|
||||
const data = await this.fetchPublicHolidays(Number(year), country);
|
||||
if (data === undefined) throw new DomainError(502, 'Failed to fetch holidays');
|
||||
return { data };
|
||||
}
|
||||
|
||||
async getSchoolHolidayRegions(country: string, language = 'EN'): Promise<{ data?: unknown }> {
|
||||
|
||||
@@ -111,6 +111,7 @@ beforeAll(async () => {
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
(svc as unknown as { holidayCache: Map<string, unknown> }).holidayCache.clear();
|
||||
// Stub fetch with empty holiday list by default so updatePlan / applyHolidayCalendars
|
||||
// never makes real network calls.
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
@@ -1389,7 +1390,7 @@ describe('applyHolidayCalendars', () => {
|
||||
// Override fetch to return one global holiday matching that entry
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [{ date: holidayDate, global: true }],
|
||||
json: async () => [{ date: holidayDate, name: 'New Year', nationalHoliday: true, subdivisionCodes: null }],
|
||||
}));
|
||||
|
||||
await svc.applyHolidayCalendars(plan.id);
|
||||
@@ -1406,7 +1407,10 @@ describe('applyHolidayCalendars', () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed')));
|
||||
await expect(svc.applyHolidayCalendars(plan.id)).resolves.toBeUndefined();
|
||||
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => [{ date: '2031-07-14', global: true }] }));
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => [{ date: '2031-07-14', name: 'Bastille Day', nationalHoliday: true, subdivisionCodes: null }],
|
||||
}));
|
||||
const entries = (svc as unknown as { entries: { deleteForPlanAndDate: () => Promise<void> } }).entries;
|
||||
const del = vi.spyOn(entries, 'deleteForPlanAndDate').mockRejectedValueOnce(new Error('database is locked'));
|
||||
await expect(svc.applyHolidayCalendars(plan.id)).rejects.toThrow('database is locked');
|
||||
@@ -1774,7 +1778,59 @@ describe('quirk fixes', () => {
|
||||
// Nothing cached: a retry hits the network again.
|
||||
expect(await asLegacyResult(fresh.getCountries())).toEqual({ error: 'Failed to fetch countries', status: 502 });
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(fetchMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://nagerholidays.com/api/v4/Countries/Available',
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-070e: getHolidays maps Nager.Holidays v4 fields to the Vacay response and caches by year and country', async () => {
|
||||
const holidays = [
|
||||
{ date: '2026-01-01', name: "New Year's Day", countryCode: 'US', nationalHoliday: true, subdivisionCodes: null, holidayTypes: ['Public'] },
|
||||
{ date: '2026-02-16', name: 'Washington’s Birthday', countryCode: 'US', nationalHoliday: false, subdivisionCodes: ['US-CA'], holidayTypes: ['Public'] },
|
||||
];
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => holidays });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const fresh = await freshVacayService();
|
||||
|
||||
const expected = [
|
||||
{ date: '2026-01-01', name: "New Year's Day", localName: "New Year's Day", global: true, counties: null },
|
||||
{ date: '2026-02-16', name: 'Washington’s Birthday', localName: 'Washington’s Birthday', global: false, counties: ['US-CA'] },
|
||||
];
|
||||
expect((await fresh.getHolidays('2026', 'US')).data).toEqual(expected);
|
||||
expect((await fresh.getHolidays('2026', 'US')).data).toEqual(expected);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://nagerholidays.com/api/v4/Holidays/US/2026',
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-070f: getCountries passes through v4 country records and caches them', async () => {
|
||||
const countries = [{ countryCode: 'US', name: 'United States' }, { countryCode: 'CN', name: 'China' }];
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => countries });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const fresh = await freshVacayService();
|
||||
|
||||
expect((await fresh.getCountries()).data).toEqual(countries);
|
||||
expect((await fresh.getCountries()).data).toEqual(countries);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://nagerholidays.com/api/v4/Countries/Available',
|
||||
expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-070g: getHolidays treats an invalid v4 payload as an upstream failure and does not cache it', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => [{ date: '2026-01-01', name: 'New Year' }] })
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => [] });
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const fresh = await freshVacayService();
|
||||
|
||||
expect(await asLegacyResult(fresh.getHolidays('2026', 'CN'))).toEqual({ error: 'Failed to fetch holidays', status: 502 });
|
||||
expect((await fresh.getHolidays('2026', 'CN')).data).toEqual([]);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('VACAY-SVC-070a: getHolidays refuses a year or country that is not a plain code', async () => {
|
||||
@@ -1814,7 +1870,7 @@ describe('quirk fixes', () => {
|
||||
});
|
||||
|
||||
it('VACAY-SVC-070d: a chunked provider body past the cap reads as the usual fetch error', async () => {
|
||||
// nager.at answers chunked, so there is no content-length for the declared
|
||||
// Nager.Holidays answers chunked, so there is no content-length for the declared
|
||||
// check to look at — only the streaming read stops this being buffered whole.
|
||||
const payload = `[${'{"date":"2026-01-01"},'.repeat(200_000)}{"date":"2026-12-24"}]`;
|
||||
const fetchMock = vi.fn().mockImplementation(async () => {
|
||||
|
||||
Reference in New Issue
Block a user