From 06b7f3e6906d207592060c5449456632ed7027d8 Mon Sep 17 00:00:00 2001 From: Maurice Date: Tue, 18 Aug 2026 21:17:05 +0200 Subject: [PATCH] feat(weather): answer for the hour when a past entry carries one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A journal entry made at 14:30 wants the weather of that hour. The archive path only ever asked for daily figures, so it answered with a rainy morning and a bright afternoon averaged into one number (#1614). With a time in hand it now asks for the hourly series as well and reads that hour, falling back to the daily figures when the hour has no reading — an archive gap must not turn into no answer at all. An unparseable time is treated as no time rather than as midnight, which would have been a confident wrong answer. The cache key carries the hour, so the two do not shadow each other. Nothing changes for callers that pass no time, which is every existing one. --- client/src/api/client.ts | 3 +- server/src/nest/weather/weather.controller.ts | 4 +- server/src/nest/weather/weather.impl.ts | 48 +++++++++++++++++-- server/src/nest/weather/weather.service.ts | 4 +- .../unit/nest/weather.controller.test.ts | 4 +- .../unit/nest/weather/weather.impl.test.ts | 45 +++++++++++++++++ 6 files changed, 98 insertions(+), 10 deletions(-) diff --git a/client/src/api/client.ts b/client/src/api/client.ts index 05843d54a..cd643030a 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -1029,7 +1029,8 @@ export const healthApi = { } export const weatherApi = { - get: (lat: number, lng: number, date: string): Promise => apiClient.get('/weather', { params: { lat, lng, date } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.get')), + // `time` (HH:MM) makes a past date answer for that hour instead of the day (#1614). + get: (lat: number, lng: number, date: string, time?: string): Promise => apiClient.get('/weather', { params: { lat, lng, date, time } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.get')), getCurrent: (lat: number, lng: number, lang?: string): Promise => apiClient.get('/weather', { params: { lat, lng, lang } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.getCurrent')), getDetailed: (lat: number, lng: number, date: string, lang?: string): Promise => apiClient.get('/weather/detailed', { params: { lat, lng, date, lang } }).then(r => parseInDev(weatherResultSchema, r.data, 'weather.getDetailed')), } diff --git a/server/src/nest/weather/weather.controller.ts b/server/src/nest/weather/weather.controller.ts index 41f9ca6ec..fe07451f1 100644 --- a/server/src/nest/weather/weather.controller.ts +++ b/server/src/nest/weather/weather.controller.ts @@ -27,12 +27,14 @@ export class WeatherController { @Query('lng') lng?: string, @Query('date') date?: string, @Query('lang') lang?: string, + /** HH:MM — lets a past date answer for that hour rather than the day (#1614). */ + @Query('time') time?: string, ): Promise { if (!lat || !lng) { throw new HttpException({ error: 'Latitude and longitude are required' }, 400); } try { - return await this.weather.get(lat, lng, date, lang ?? 'de'); + return await this.weather.get(lat, lng, date, lang ?? 'de', time); } catch (err: unknown) { throw toHttp(err, 'Weather error:', 'Error fetching weather data'); } diff --git a/server/src/nest/weather/weather.impl.ts b/server/src/nest/weather/weather.impl.ts index fa3eea1be..6499dd3a9 100644 --- a/server/src/nest/weather/weather.impl.ts +++ b/server/src/nest/weather/weather.impl.ts @@ -4,6 +4,21 @@ // outbound client in the codebase carries one. const WEATHER_TIMEOUT_MS = 8000; +/** + * Which slot of Open-Meteo's hourly series a HH:MM belongs to. + * + * The archive answers with one entry per hour of the requested day in the local + * timezone, so the hour is the index. Anything unparseable means "no time given", + * which falls back to the daily figures rather than guessing midnight. + */ +function hourIndexFromTime(time?: string): number | null { + if (!time) return null; + const m = /^(\d{1,2}):(\d{2})/.exec(time.trim()); + if (!m) return null; + const hour = Number(m[1]); + return Number.isInteger(hour) && hour >= 0 && hour <= 23 ? hour : null; +} + // ── Interfaces ────────────────────────────────────────────────────────── export interface WeatherResult { @@ -182,8 +197,9 @@ async function _getWeatherImpl( lng: string, date: string | undefined, lang: string, + time?: string, ): Promise { - const ck = cacheKey(lat, lng, date); + const ck = cacheKey(lat, lng, date ? `${date}T${time ?? ''}` : date); if (date) { const cached = getCached(ck); @@ -227,7 +243,13 @@ async function _getWeatherImpl( // Past date: use archive API for the actual date if (diffDays < -1) { const dateStr = targetDate.toISOString().slice(0, 10); - const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${dateStr}&end_date=${dateStr}&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum&timezone=auto`; + // With a time in hand, ask for the hourly series too: a journal entry made at + // 14:30 wants the weather of that hour, not the day's high and low averaged + // together, which is what a rainy morning and a bright afternoon collapse to. + const hourParam = hourIndexFromTime(time) != null + ? '&hourly=temperature_2m,weathercode' + : ''; + const url = `https://archive-api.open-meteo.com/v1/archive?latitude=${lat}&longitude=${lng}&start_date=${dateStr}&end_date=${dateStr}&daily=temperature_2m_max,temperature_2m_min,weathercode,precipitation_sum${hourParam}&timezone=auto`; const response = await fetch(url, { signal: AbortSignal.timeout(WEATHER_TIMEOUT_MS) }); const data = await response.json() as OpenMeteoForecast; @@ -235,6 +257,22 @@ async function _getWeatherImpl( throw new ApiError(response.status || 500, data.reason || 'Open-Meteo Archive API error'); } + const hourIdx = hourIndexFromTime(time); + const hourly = (data as { hourly?: { temperature_2m?: (number | null)[]; weathercode?: (number | null)[] } }).hourly; + if (hourIdx != null && hourly?.temperature_2m?.[hourIdx] != null) { + const temp = hourly.temperature_2m[hourIdx]!; + const code = hourly.weathercode?.[hourIdx] ?? undefined; + const descriptions = lang === 'de' ? WMO_DESCRIPTION_DE : WMO_DESCRIPTION_EN; + const result: WeatherResult = { + temp: Math.round(temp), + main: WMO_MAP[code!] || estimateCondition(temp, 0), + description: descriptions[code!] || '', + type: 'forecast', + }; + setCache(ck, result, TTL_CLIMATE_MS); + return result; + } + const daily = data.daily; if (daily && daily.time && daily.time.length > 0 && daily.temperature_2m_max[0] != null) { const code = daily.weathercode?.[0]; @@ -348,15 +386,17 @@ export async function getWeather( lng: string, date: string | undefined, lang: string, + /** HH:MM of the moment being asked about. Only the archive path can use it. */ + time?: string, ): Promise { - const ck = cacheKey(lat, lng, date); + const ck = cacheKey(lat, lng, date ? `${date}T${time ?? ''}` : date); const cached = getCached(ck); if (cached) return cached; const inFlightKey = `${ck}:${lang}`; const existing = inFlight.get(inFlightKey); if (existing) return existing; - const promise = _getWeatherImpl(lat, lng, date, lang); + const promise = _getWeatherImpl(lat, lng, date, lang, time); inFlight.set(inFlightKey, promise); try { return await promise; } finally { inFlight.delete(inFlightKey); } } diff --git a/server/src/nest/weather/weather.service.ts b/server/src/nest/weather/weather.service.ts index 22f1865cc..13c19d568 100644 --- a/server/src/nest/weather/weather.service.ts +++ b/server/src/nest/weather/weather.service.ts @@ -25,8 +25,8 @@ export class WeatherService implements OnModuleInit, OnModuleDestroy { stopCacheCleanup(); } - get(lat: string, lng: string, date: string | undefined, lang: string): Promise { - return getWeather(lat, lng, date, lang) as Promise; + get(lat: string, lng: string, date: string | undefined, lang: string, time?: string): Promise { + return getWeather(lat, lng, date, lang, time) as Promise; } getDetailed(lat: string, lng: string, date: string, lang: string): Promise { diff --git a/server/tests/unit/nest/weather.controller.test.ts b/server/tests/unit/nest/weather.controller.test.ts index df1c5d21f..71214b031 100644 --- a/server/tests/unit/nest/weather.controller.test.ts +++ b/server/tests/unit/nest/weather.controller.test.ts @@ -37,14 +37,14 @@ describe('WeatherController (parity with the legacy /api/weather route)', () => const c = makeController({ get }); const res = await c.getWeather('52.5', '13.4', undefined, undefined); expect(res).toEqual(sample); - expect(get).toHaveBeenCalledWith('52.5', '13.4', undefined, 'de'); + expect(get).toHaveBeenCalledWith('52.5', '13.4', undefined, 'de', undefined); }); it('passes an explicit lang and date through unchanged', async () => { const get = vi.fn().mockResolvedValue(sample); const c = makeController({ get }); await c.getWeather('1', '2', '2026-07-01', 'en'); - expect(get).toHaveBeenCalledWith('1', '2', '2026-07-01', 'en'); + expect(get).toHaveBeenCalledWith('1', '2', '2026-07-01', 'en', undefined); }); it('maps an ApiError to its status + { error: message }', async () => { diff --git a/server/tests/unit/nest/weather/weather.impl.test.ts b/server/tests/unit/nest/weather/weather.impl.test.ts index 49c696de6..eb25cc27d 100644 --- a/server/tests/unit/nest/weather/weather.impl.test.ts +++ b/server/tests/unit/nest/weather/weather.impl.test.ts @@ -306,6 +306,51 @@ describe('getWeather', () => { expect(vi.mocked(fetch).mock.calls[0][0]).toContain('archive-api.open-meteo.com'); }); + // #1614 — an entry made at 14:30 wants the weather of that hour. Averaging a + // rainy morning with a bright afternoon is what the daily figures do. + it('answers for the given hour when a time comes with the date', async () => { + const date = dateOffset(-5); + const hourly = { temperature_2m: Array(24).fill(null), weathercode: Array(24).fill(null) }; + hourly.temperature_2m[14] = 21; + hourly.weathercode[14] = 0; + vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ + daily: { time: [date], temperature_2m_max: [18], temperature_2m_min: [10], weathercode: [2], precipitation_sum: [0] }, + hourly, + })); + + const result = await getWeather('14.02', '24.02', date, 'en', '14:30'); + + expect(vi.mocked(fetch).mock.calls[0][0]).toContain('hourly=temperature_2m,weathercode'); + expect(result.temp).toBe(21); + // The daily average would have been 14, so this is demonstrably the hour. + expect(result.temp_max).toBeUndefined(); + }); + + it('falls back to the daily figures when the hour has no reading', async () => { + const date = dateOffset(-5); + vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ + daily: { time: [date], temperature_2m_max: [18], temperature_2m_min: [10], weathercode: [2], precipitation_sum: [0] }, + hourly: { temperature_2m: Array(24).fill(null), weathercode: Array(24).fill(null) }, + })); + + const result = await getWeather('14.03', '24.03', date, 'en', '14:30'); + + expect(result.temp).toBe(14); + expect(result.temp_max).toBe(18); + }); + + it('ignores an unparseable time rather than guessing midnight', async () => { + const date = dateOffset(-5); + vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ + daily: { time: [date], temperature_2m_max: [18], temperature_2m_min: [10], weathercode: [2], precipitation_sum: [0] }, + })); + + const result = await getWeather('14.04', '24.04', date, 'en', 'not-a-time'); + + expect(vi.mocked(fetch).mock.calls[0][0]).not.toContain('hourly='); + expect(result.temp).toBe(14); + }); + it('returns no_forecast error when archive has no data for the date', async () => { const date = dateOffset(-5); vi.mocked(fetch).mockResolvedValueOnce(mockResponse({ daily: { time: [], temperature_2m_max: [], temperature_2m_min: [], weathercode: [] } }));