diff --git a/src/app/api/analytics/route.ts b/src/app/api/analytics/route.ts index 6285e55c4..642afa8af 100644 --- a/src/app/api/analytics/route.ts +++ b/src/app/api/analytics/route.ts @@ -83,13 +83,22 @@ export const GET = apiHandler(async (request?: Request) => { // mount, and the Coach drawer all hit this endpoint within seconds // of each other; the 60s TTL converts the 7.99s combined dashboard // wait to a Map lookup on every subsequent caller. - const body = await cached( + const cachedBody = await cached( caches.analytics as ServerCache>>, `${user.id}|default`, () => buildAnalyticsResponse(user), annotate, ); + // v1.4.38 — `lastSeenByType` lives inside the cached envelope as + // `{ lastSeenAt }` only; derive the `daysAgo` caption per call so + // the staleness label updates correctly across day boundaries. + // The cache TTL is 60s, but the day boundary it can straddle would + // otherwise leave the cached `daysAgo` off by one until the next + // refresh. Re-deriving on read is a single Date subtraction per + // type and stays on the hot path's Map-lookup side of the cache. + const body = enrichLastSeenDaysAgo(cachedBody); + const response = apiSuccess(body); // v1.4.34 IW-B — bfcache-friendly directive so back-forward navigation // restores the dashboard from memory. Per `src/lib/http/cache-headers.ts`: @@ -104,6 +113,44 @@ export const GET = apiHandler(async (request?: Request) => { type AuthedUser = Awaited>["user"]; +/** + * v1.4.38 — derive `daysAgo` from the cached `lastSeenAt` ISO string + * per request. The cached envelope deliberately omits `daysAgo` so + * the dashboard tile staleness caption stays correct across day + * boundaries even when the body has been sitting in the 60s LRU. + * + * Returns a shallow-copied envelope with the enriched + * `lastSeenByType` map; everything else is passed through unchanged. + */ +function enrichLastSeenDaysAgo< + T extends { + lastSeenByType: Record; + }, +>( + body: T, +): Omit & { + lastSeenByType: Record< + string, + { lastSeenAt: string; daysAgo: number } | null + >; +} { + const nowMs = Date.now(); + const enriched: Record< + string, + { lastSeenAt: string; daysAgo: number } | null + > = {}; + for (const [type, slot] of Object.entries(body.lastSeenByType)) { + if (slot === null) { + enriched[type] = null; + continue; + } + const lastMs = new Date(slot.lastSeenAt).getTime(); + const daysAgo = Math.floor((nowMs - lastMs) / (24 * 60 * 60 * 1000)); + enriched[type] = { lastSeenAt: slot.lastSeenAt, daysAgo }; + } + return { ...body, lastSeenByType: enriched }; +} + /** * v1.4.34 IW-G — the heavy default-slice body, lifted out of the route * handler so `cached()` can wrap it. Returns the raw JSON payload; the @@ -163,13 +210,15 @@ async function buildAnalyticsResponse(user: AuthedUser) { // tiles whose latest reading is older than a week. The series read // already orders ascending (`fetchMeasurementSeriesChunked`'s stable // `(measuredAt, id)` order); the last entry is the freshest sample. - // Surface as ISO + a server-computed `daysAgo` so the client never - // has to do tz-aware date math to colour the tile. - const nowForStaleness = new Date(); - const lastSeenByType: Record = {}; + // + // v1.4.38 — the cached body now carries only `lastSeenAt` (ISO); + // `daysAgo` is derived in the GET wrapper per call. Storing the + // computed delta inside the cache let the value stale across day + // boundaries (60s TTL straddling midnight could surface a "vor 3d" + // caption that should read "vor 4d"). The ISO timestamp does not + // age, so re-deriving on read costs nothing and pins the caption + // to the real wall-clock at every request. + const lastSeenByType: Record = {}; let totalRowsReadForAggregate = 0; const measurementsByType = await Promise.all( @@ -184,13 +233,8 @@ async function buildAnalyticsResponse(user: AuthedUser) { // most-recent point without an extra pass. const latest = measurements.at(-1); if (latest) { - const daysAgo = Math.floor( - (nowForStaleness.getTime() - latest.measuredAt.getTime()) / - (24 * 60 * 60 * 1000), - ); lastSeenByType[type] = { lastSeenAt: latest.measuredAt.toISOString(), - daysAgo, }; } else { lastSeenByType[type] = null;