Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(weather): answer the day 16 days out with climate instead of an error

Maurice18867d94998d
diff --git a/server/src/nest/weather/weather.impl.ts b/server/src/nest/weather/weather.impl.ts
index dde60cc19..bf28da623 100644
--- a/server/src/nest/weather/weather.impl.ts
+++ b/server/src/nest/weather/weather.impl.ts
@@ -640,6 +640,47 @@ async function detailedFromArchive(
};
}
+/**
+ * The last day Open-Meteo's forecast answers, counted in calendar days from today.
+ * The fraction of a day between now and the target's midnight is not that count:
+ * the day 16 out lies 15.x days away and slipped through a `<= 16` test (#3216).
+ */
+const FORECAST_LAST_DAY = 15;
+
+function calendarDaysAhead(day: string, now: Date): number {
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
+ return Math.round((Date.parse(`${day}T00:00:00Z`) - today) / 86_400_000);
+}
+
+/**
+ * The forecast counts its range from the place's own date, which trails UTC's in
+ * the Americas for part of the day, so its last day can still be refused there.
+ */
+function isOutsideForecastRange(status: number, reason: string | undefined): boolean {
+ return status === 400 && /out of allowed range/i.test(reason ?? '');
+}
+
+/** Last year's day standing in for a trip day the forecast does not reach. */
+async function detailedClimate(
+ lat: string,
+ lng: string,
+ targetDate: Date,
+ now: Date,
+ descriptions: Record<number, string>,
+ ck: string,
+): Promise<WeatherResult> {
+ let refYear = targetDate.getFullYear() - 1;
+ // Archive API only has data up to yesterday — go back further if needed
+ const yesterday = new Date(now.getTime() - 86400000);
+ if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
+ const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
+
+ const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
+ if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
+ setCache(ck, climate, TTL_CLIMATE_MS);
+ return climate;
+}
+
async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, lang: string): Promise<WeatherResult> {
const ck = `detailed_${cacheKey(lat, lng, date, lang)}`;
@@ -652,18 +693,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const dateStr = targetDate.toISOString().slice(0, 10);
const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN;
- // Climate path (> 16 days out): last year's day stands in for the trip's.
- if (diffDays > 16) {
- let refYear = targetDate.getFullYear() - 1;
- // Archive API only has data up to yesterday — go back further if needed
- const yesterday = new Date(now.getTime() - 86400000);
- if (new Date(refYear, targetDate.getMonth(), targetDate.getDate()) > yesterday) refYear--;
- const refDateStr = `${refYear}-${String(targetDate.getMonth() + 1).padStart(2, '0')}-${String(targetDate.getDate()).padStart(2, '0')}`;
-
- const climate = await detailedFromArchive(lat, lng, refDateStr, 'climate', descriptions);
- if (!climate) return { temp: 0, main: '', description: '', type: '', error: 'no_forecast' };
- setCache(ck, climate, TTL_CLIMATE_MS);
- return climate;
+ // Climate path: past the forecast's last day, last year's day stands in for the trip's.
+ if (calendarDaysAhead(dateStr, now) > FORECAST_LAST_DAY) {
+ return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
}
// Past day: the forecast API answers nulls once a date is a couple of months
@@ -678,7 +710,7 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
}
}
- // Forecast path (<= 16 days)
+ // Forecast path (up to today + 15 days)
const url =
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lng}` +
`&hourly=temperature_2m,precipitation_probability,precipitation,weathercode,windspeed_10m,relativehumidity_2m` +
@@ -688,6 +720,9 @@ async function _getDetailedWeatherImpl(lat: string, lng: string, date: string, l
const { response, data } = await fetchOpenMeteo(url);
if (!response.ok || data.error) {
+ if (isOutsideForecastRange(response.status, data.reason)) {
+ return detailedClimate(lat, lng, targetDate, now, descriptions, ck);
+ }
throw new ApiError(response.status || 500, data.reason || 'Open-Meteo API error');
}
diff --git a/server/tests/unit/nest/weather/weather.impl.test.ts b/server/tests/unit/nest/weather/weather.impl.test.ts
index e594f161b..d7876491c 100644
--- a/server/tests/unit/nest/weather/weather.impl.test.ts
+++ b/server/tests/unit/nest/weather/weather.impl.test.ts
@@ -1223,3 +1223,110 @@ describe('size cap on the Open-Meteo body', () => {
expect(result.temp).toBe(15);
});
});
+
+// ── the forecast's last day (#3216) ──────────────────────────────────────────
+
+describe('getDetailedWeather at the edge of the forecast range', () => {
+ const FORECAST = 'api.open-meteo.com/v1/forecast';
+ const ARCHIVE = 'archive-api.open-meteo.com/v1/archive';
+
+ const archiveDay = {
+ daily: {
+ time: ['2025-12-11'],
+ temperature_2m_max: [8],
+ temperature_2m_min: [2],
+ weathercode: [3],
+ precipitation_sum: [0],
+ windspeed_10m_max: [12],
+ sunrise: ['2025-12-11T07:50'],
+ sunset: ['2025-12-11T16:10'],
+ },
+ hourly: { time: [], temperature_2m: [] },
+ };
+
+ const forecastDay = (date: string) => ({
+ daily: {
+ time: [date],
+ temperature_2m_max: [10],
+ temperature_2m_min: [4],
+ weathercode: [1],
+ sunrise: [`${date}T07:50`],
+ sunset: [`${date}T16:10`],
+ precipitation_probability_max: [10],
+ precipitation_sum: [0],
+ windspeed_10m_max: [9],
+ },
+ hourly: { time: [], temperature_2m: [] },
+ });
+
+ /** Answers like Open-Meteo: the forecast refuses a start_date past `lastForecastDay`. */
+ function openMeteo(lastForecastDay: string) {
+ vi.mocked(fetch).mockImplementation(async (input) => {
+ const url = String(input);
+ if (url.includes(FORECAST)) {
+ const start = /start_date=([\d-]+)/.exec(url)?.[1] ?? '';
+ if (start > lastForecastDay) {
+ return mockResponse(
+ {
+ error: true,
+ reason: `Parameter 'start_date' is out of allowed range from 2026-08-24 to ${lastForecastDay}`,
+ },
+ false,
+ 400,
+ );
+ }
+ return mockResponse(forecastDay(start));
+ }
+ if (url.includes(ARCHIVE)) return mockResponse(archiveDay);
+ throw new Error(`unexpected request ${url}`);
+ });
+ }
+
+ beforeEach(() => {
+ vi.mocked(fetch).mockReset();
+ });
+
+ it('WEATHER-HORIZON-001: the day 16 days out answers with climate instead of failing', async () => {
+ vi.setSystemTime(new Date('2026-11-25T13:00:00Z'));
+ openMeteo('2026-12-10');
+
+ const result = await getDetailedWeather('47.10', '11.30', '2026-12-11', 'en');
+
+ expect(result.type).toBe('climate');
+ expect(result.temp_max).toBe(8);
+ const asked = vi.mocked(fetch).mock.calls.map(([u]) => String(u));
+ expect(asked.some((u) => u.includes(FORECAST))).toBe(false);
+ expect(asked.some((u) => u.includes(`${ARCHIVE}`) && u.includes('start_date=2025-12-11'))).toBe(true);
+ });
+
+ it('WEATHER-HORIZON-002: the day 15 days out keeps its forecast, late in the UTC day too', async () => {
+ vi.setSystemTime(new Date('2026-11-25T23:30:00Z'));
+ openMeteo('2026-12-10');
+
+ const result = await getDetailedWeather('47.11', '11.31', '2026-12-10', 'en');
+
+ expect(result.type).toBe('forecast');
+ expect(result.temp_max).toBe(10);
+ });
+
+ it('WEATHER-HORIZON-003: a place whose local date is still behind UTC falls back to climate on the refusal', async () => {
+ // 02:00 UTC is still the day before in the Americas, so Open-Meteo's range
+ // there ends a day earlier than UTC's today + 15.
+ vi.setSystemTime(new Date('2026-11-26T02:00:00Z'));
+ openMeteo('2026-12-10');
+
+ const result = await getDetailedWeather('40.71', '-74.00', '2026-12-11', 'en');
+
+ expect(result.type).toBe('climate');
+ expect(result.temp_max).toBe(8);
+ });
+
+ it('WEATHER-HORIZON-004: any other refusal of the forecast still surfaces as an error', async () => {
+ vi.setSystemTime(new Date('2026-11-25T13:00:00Z'));
+ vi.mocked(fetch).mockResolvedValue(
+ mockResponse({ error: true, reason: 'Cannot initialize WeatherVariable' }, false, 400),
+ );
+
+ await expect(getDetailedWeather('47.12', '11.32', '2026-12-01', 'en')).rejects.toMatchObject({ status: 400 });
+ });
+});