fix(tz): one default zone, and the user's own calendar where Berlin was hard-coded

The status assessments folded their recent days, weeks, months and years on
Berlin days whatever the user's zone, the mood and cycle crosstabs keyed
their metric days in Berlin, the resting-pulse proxy defaulted to Berlin
days, the briefing's opener rotated at Berlin midnight, and every
assessment prompt labelled today's date as Berlin's. They now use the
user's zone. Rollup months and years are labelled by their UTC start,
which is how they are cut; read in a zone west of UTC the label named the
month before.

"Europe/Berlin" was written out in some eighty places. DEFAULT_TIMEZONE in
lib/tz/format is now the one definition: the second copy in mood/date-key,
DISPLAY_TIMEZONE, the Berlin-only day key helpers and the per-route copies
are gone. An in-repo lint rule rejects the literal outside lib/tz and
tests; four areas another change owns are listed as pending.
This commit is contained in:
Marc-André Bombeck committed 2026-09-26 16:23:14 +02:00
1 parent c366d4946c
commit 9d2fd1db14
124 files changed
+705 -415

No files matched your search

+6 -3
View File
@@ -41,7 +41,8 @@ import {
import type { CrossMetricMeasurement } from "@/lib/insights/mood-aggregates";
import { addDays } from "@/lib/cycle/day-math";
import { readSourceDayAggregates } from "@/lib/measurements/day-aggregates";
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/** Trailing window the phase contrast walks (days). Mirrors the read route. */
const WINDOW_DAYS = 365;
@@ -200,12 +201,13 @@ export async function buildCycleSnapshotBlock(
// many readings to hold as objects (#1023). The crosstab only needs
// each day's sum and count per source and device, which is what the
// per-source picker decides on, so the fold runs in SQL. Days are the
// Berlin days `metricDayMap` keys on.
// user's days, the ones `metricDayMap` keys on and the phase days are
// dated in.
readSourceDayAggregates({
userId,
types: PHASE_CROSSTAB_METRIC_TYPES,
since: new Date(Date.parse(`${from}T00:00:00Z`)),
timeZone: "Europe/Berlin",
timeZone: tz,
}),
prisma.user.findUnique({
where: { id: userId },
@@ -292,6 +294,7 @@ export async function buildCycleSnapshotBlock(
phaseByDay,
measurements,
userPriorityJson: userRow?.sourcePriorityJson ?? null,
timeZone: tz,
}),
);
+1 -1
View File
@@ -17,7 +17,7 @@
import { prisma } from "@/lib/db";
import { isIllnessEnabled } from "@/lib/illness/gate";
import { computeEpisodeCorrelation } from "@/lib/illness/correlation-read";
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { decryptFromBytes } from "@/lib/ai/coach/bytes-codec";
import { sanitizeForPrompt } from "@/lib/insights/sanitize";
+2 -1
View File
@@ -56,6 +56,7 @@ import {
loadBaselineProfile,
isDerivedOk,
} from "@/lib/insights/derived";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/** Trailing window for the discovery scan — mirrors the insight route. */
@@ -209,7 +210,7 @@ export async function readCoachCorrelations(
where: { id: userId },
select: { timezone: true },
});
const tz = userRow?.timezone ?? "Europe/Berlin";
const tz = userRow?.timezone ?? DEFAULT_TIMEZONE;
const since = new Date(Date.now() - WINDOW_DAYS * MS_PER_DAY);
// The channel set is the shared one, so the Coach scans exactly what the
+2 -1
View File
@@ -22,6 +22,7 @@ import {
buildWorkoutEvidence,
type WorkoutEvidenceInput,
} from "./workout-evidence";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
interface WorkoutEvidenceRow {
sportType: string;
@@ -108,7 +109,7 @@ export function createWorkoutEvidenceBuilder(
sportType: row.sportType,
source: row.source,
startedAt: row.startedAt,
timezone: profile?.timezone ?? "Europe/Berlin",
timezone: profile?.timezone ?? DEFAULT_TIMEZONE,
durationSec: row.durationSec,
totalEnergyKcal: row.totalEnergyKcal,
totalDistanceM: row.totalDistanceM,
@@ -15,6 +15,7 @@ describe("buildBriefingPersonalisationBlock", () => {
"user-1",
null,
"en",
"UTC",
day("2026-06-27T08:00:00Z"),
);
expect(en).toContain("OPENER HINT:");
@@ -22,6 +23,7 @@ describe("buildBriefingPersonalisationBlock", () => {
"user-1",
null,
"de",
"UTC",
day("2026-06-27T08:00:00Z"),
);
expect(de).toContain("OPENER-HINWEIS:");
@@ -33,6 +35,7 @@ describe("buildBriefingPersonalisationBlock", () => {
"user-1",
null,
"en",
"UTC",
day(`2026-06-${String(d).padStart(2, "0")}T08:00:00Z`),
);
expect(out).not.toContain("NAME:");
@@ -47,6 +50,7 @@ describe("buildBriefingPersonalisationBlock", () => {
"user-42",
"Alex Rivera",
"en",
"UTC",
day(`2026-06-${String(d).padStart(2, "0")}T08:00:00Z`),
);
if (out.includes('"Alex"')) withName += 1;
@@ -62,6 +66,7 @@ describe("buildBriefingPersonalisationBlock", () => {
"user-42",
"Alex Rivera",
"en",
"UTC",
day("2026-06-30T08:00:00Z"),
);
expect(out).not.toContain("Rivera");
+2 -2
View File
@@ -68,12 +68,12 @@ export function getBloodPressureUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's blood pressure. Open with what the reading MEANS in plain words — the overall read, not the number (e.g. "calm and right where you want it", "running a touch higher than your usual this week") — then bring in the systolic/diastolic figures right after as support, judged as ONE pair and placed against their own weekly/monthly baseline; never lead with the numbers. Close with one doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the measurement count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zum Blutdruck dieser Person. Beginne mit der BEDEUTUNG in klaren Worten — dem Gesamteindruck, nicht der Zahl (z. B. "ruhig und genau da, wo du ihn haben willst", "diese Woche einen Tick höher als sonst") — und bring danach die systolischen/diastolischen Werte als Beleg, als EIN Paar beurteilt und gegen die eigene Wochen-/Monats-Baseline eingeordnet; führe nie mit den Werten. Schließe nur dann mit einem machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Messanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+2 -2
View File
@@ -55,12 +55,12 @@ export function getBmiUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's BMI. Open with what its band placement MEANS in plain words — where it sits and whether that's holding or shifting, not the number (e.g. "sitting comfortably in the healthy band", "edging toward the next band up") — then bring in the current value and WHO band right after as support, saying against their own weekly/monthly baseline whether it has crossed a band or is nearing a boundary; never lead with the value. Close with one doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Leave the weight pace to the weight card. Judge confidence from the measurement count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zum BMI dieser Person. Beginne mit der BEDEUTUNG der Bandlage in klaren Worten — wo er liegt und ob das hält oder sich verschiebt, nicht der Zahl (z. B. "liegt bequem im gesunden Band", "nähert sich dem nächsten Band") — und bring danach den aktuellen Wert und das WHO-Band als Beleg, samt Angabe gegen die eigene Wochen-/Monats-Baseline, ob er ein Band gewechselt hat oder sich einer Bandgrenze nähert; führe nie mit dem Wert. Schließe nur dann mit einem machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Das Gewichtstempo bleibt der Gewichts-Karte überlassen. Konfidenz aus Messanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+2 -2
View File
@@ -63,12 +63,12 @@ export function getGeneralStatusUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short overall assessment across the available health metrics. Open with the overall read in plain words — how things are looking taken together, not a number (e.g. "a steady stretch across the board", "one thing standing out this week") — then bring in the one or two metrics that stand out as support, each placed against the person's own weekly/monthly baseline; never lead with a value. Close with the single most important doable step only when the overall picture genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the measurement count, density and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Gesamteinschätzung über die verfügbaren Gesundheitsdaten. Beginne mit dem Gesamteindruck in klaren Worten — wie es zusammengenommen aussieht, nicht mit einer Zahl (z. B. "über alles hinweg eine ruhige Phase", "diese Woche sticht eine Sache heraus") — und bring danach die ein bis zwei auffälligsten Metriken als Beleg, jeweils gegen die eigene Wochen-/Monats-Baseline eingeordnet; führe nie mit einem Wert. Schließe nur dann mit dem einen wichtigsten machbaren Schritt, wenn das Gesamtbild wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Messanzahl, Dichte und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+4 -11
View File
@@ -47,6 +47,7 @@ import {
outlookContract,
formattingContract,
} from "./shared-contracts";
import { userDayKey } from "@/lib/tz/format";
/**
* Stable identifier for the active system prompt revision.
@@ -63,16 +64,6 @@ import {
*/
export const PROMPT_VERSION = "5.1.0" as const;
/** Europe/Berlin YYYY-MM-DD day key — the rotation boundary for the opener. */
function berlinDayKey(now: Date): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(now);
}
/**
* v1.22 (W6) — the daily-briefing personalization SYSTEM CONTEXT block.
*
@@ -92,9 +83,11 @@ export function buildBriefingPersonalisationBlock(
userId: string,
displayName: string | null,
locale: Locale,
/** The user's zone: the opener rotates at the user's own midnight. */
timeZone: string,
now: Date = new Date(),
): string {
const dayKey = berlinDayKey(now);
const dayKey = userDayKey(now, timeZone);
const hint = openerArchetypeHint(`${userId}:briefing:${dayKey}`, locale);
const firstName = firstNameFromDisplayName(displayName);
const useName =
+2 -2
View File
@@ -57,12 +57,12 @@ export function getMedicationComplianceUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's medication adherence. Open with what it MEANS in plain words — how reliable the routine is looking, not the number (e.g. "your routine's been rock-solid", "a few doses have slipped lately") — then bring in the recent rate right after as support, placed against their own baseline (compliance7 vs compliance30); never lead with the value. Close with one doable, blame-free step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the event count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zur Einnahmetreue dieser Person. Beginne mit der BEDEUTUNG in klaren Worten — wie verlässlich die Routine aussieht, nicht der Zahl (z. B. "deine Routine sitzt richtig gut", "zuletzt sind ein paar Dosen durchgerutscht") — und bring danach die jüngste Rate als Beleg, gegen die eigene Baseline eingeordnet (compliance7 vs. compliance30); führe nie mit dem Wert. Schließe nur dann mit einem machbaren, wertfreien Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Ereignisanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+2 -2
View File
@@ -165,12 +165,12 @@ export function getMetricArchetypeUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's ${meta.displayName.toLowerCase()}. Open with what it MEANS in plain words — the read, not the number (e.g. "running a little calmer than usual", "steady and right where it's been") — then bring in ONE concrete number from the snapshot right after as support, placed against their own weekly/monthly baseline; never lead with the value. Close with one doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the measurement count and recency.${ctxBlock}${extraBlock}${interpBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zu ${meta.displayName} dieser Person. Beginne mit der BEDEUTUNG in klaren Worten — dem Eindruck, nicht der Zahl (z. B. "läuft gerade etwas ruhiger als sonst", "stabil und genau da, wo es war") — und bring danach EINE konkrete Zahl aus dem Snapshot als Beleg, gegen die eigene Wochen-/Monats-Baseline eingeordnet; führe nie mit dem Wert. Schließe nur dann mit einem machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Messanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}${interpBlock}
${snapshotJson}`;
+2 -2
View File
@@ -57,12 +57,12 @@ export function getMoodUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's mood. Open with what the recent pattern MEANS in plain words — the read, not the number (e.g. "a brighter stretch than usual", "steady, holding where it's been") — then bring in the recent level right after as support, placed against their own weekly/monthly baseline; never lead with the value. Close with one kind, doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the entry count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zur Stimmung dieser Person. Beginne mit der BEDEUTUNG des jüngsten Musters in klaren Worten — dem Eindruck, nicht der Zahl (z. B. "eine hellere Phase als sonst", "stabil, hält sich, wo sie war") — und bring danach das jüngste Niveau als Beleg, gegen die eigene Wochen-/Monats-Baseline eingeordnet; führe nie mit dem Wert. Schließe nur dann mit einem freundlichen, machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Eintragsanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+2 -2
View File
@@ -55,12 +55,12 @@ export function getPulseUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's resting pulse. Open with what it MEANS in plain words — the read, not the number (e.g. "running a little calmer than usual", "steady, right where it's been") — then bring in ONE concrete number from the snapshot right after as support, placed against their own weekly/monthly baseline; never lead with the value. Close with one doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the measurement count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zum Ruhepuls dieser Person. Beginne mit der BEDEUTUNG in klaren Worten — dem Eindruck, nicht der Zahl (z. B. "läuft gerade etwas ruhiger als sonst", "stabil, genau da, wo er war") — und bring danach EINE konkrete Zahl aus dem Snapshot als Beleg, gegen die eigene Wochen-/Monats-Baseline eingeordnet; führe nie mit dem Wert. Schließe nur dann mit einem machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Messanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
+2 -2
View File
@@ -63,12 +63,12 @@ export function getWeightUserPrompt(
? `\nOPENER HINT: ${openerHint}`
: "";
if (instructionLocale(locale) === "en") {
return `Date: ${todayKey} (Europe/Berlin)${openerLine}
return `Date: ${todayKey}${openerLine}
Write one short assessment of this person's weight. Open with what the trend MEANS in plain words — the direction and momentum, not the number (e.g. "easing down steadily", "holding right where it's settled") — then bring in ONE concrete number from the snapshot right after as support, read as a continuous trend and pace against their own weekly/monthly baseline (kg/week, plateau, milestone — not the single value, and not the WHO band, which the BMI card covers); never lead with the value. Close with one doable step only when the finding genuinely implies one; when nothing is, skip the step rather than manufacture filler. Judge confidence from the measurement count and recency.${ctxBlock}${extraBlock}
${snapshotJson}`;
}
return `Datum: ${todayKey} (Europe/Berlin)${openerLine}
return `Datum: ${todayKey}${openerLine}
Schreibe eine kurze Einschätzung zum Gewicht dieser Person. Beginne mit der BEDEUTUNG in klaren Worten — Richtung und Tempo, nicht der Zahl (z. B. "geht ruhig nach unten", "hält sich genau da, wo es sich eingependelt hat") — und bring danach EINE konkrete Zahl aus dem Snapshot als Beleg, als kontinuierlichen Trend und Tempo gegen die eigene Wochen-/Monats-Baseline gelesen (kg/Woche, Plateau, Meilenstein — nicht der Einzelwert und nicht das WHO-Band, das die BMI-Karte trägt); führe nie mit dem Wert. Schließe nur dann mit einem machbaren Schritt, wenn der Befund wirklich einen hergibt; ist nichts umsetzbar, lass den Schritt weg statt Fülltext zu erfinden. Konfidenz aus Messanzahl und Aktualität ableiten.${ctxBlock}${extraBlock}
${snapshotJson}`;
@@ -29,7 +29,6 @@ import {
resolveRestingPulseSeries,
type PulseSample,
} from "@/lib/analytics/resting-pulse";
import { toBerlinDayKey } from "@/lib/tz/resolver";
import { userDayKey } from "@/lib/tz/format";
import { percentile } from "@/lib/insights/strain-score";
import { localDayWindow } from "@/lib/tz/local-day";
@@ -96,7 +95,7 @@ describe("loadIntradayPulse", () => {
// Sanity: under the OLD hardcoded-Berlin bug all six samples fall on the
// SAME Berlin day — proving the two tz groupings genuinely diverge.
const berlinDays = new Set(
[...dayA, ...dayB].map((d) => toBerlinDayKey(d)),
[...dayA, ...dayB].map((d) => userDayKey(d, "Europe/Berlin")),
);
expect(berlinDays.size).toBe(1);
@@ -151,7 +150,7 @@ describe("loadIntradayPulse", () => {
const buggyBerlin = resolveRestingPulseSeries({
restingSamples: [],
pulseSamples: pulseHistory as PulseSample[],
dayKeyOf: (d) => toBerlinDayKey(d),
dayKeyOf: (d) => userDayKey(d, "Europe/Berlin"),
});
const buggyBaseline = median(
buggyBerlin.series.slice(-30).map((p) => p.value),
@@ -13,6 +13,9 @@ import {
type PulseSample,
} from "../resting-pulse";
import { zonedWallClockToUtc } from "@/lib/tz/wall-clock";
import { userDayKey } from "@/lib/tz/format";
const DAY_KEY = (d: Date) => userDayKey(d, "Europe/Berlin");
/**
* The zone `deriveRestingProxyFromPulse` buckets in by default
@@ -69,7 +72,7 @@ describe("deriveRestingProxyFromPulse", () => {
),
);
}
const proxy = deriveRestingProxyFromPulse(samples);
const proxy = deriveRestingProxyFromPulse(samples, DAY_KEY);
expect(proxy).toHaveLength(1);
// 510 samples, only 10 below ~80 — but the 20th percentile of the
// whole day still lands in the workout band because 98 % of samples
@@ -94,7 +97,7 @@ describe("deriveRestingProxyFromPulse", () => {
for (let i = 0; i < 10; i++) {
samples.push(day(`2026-06-02T18:${String(i).padStart(2, "0")}:00`, 150));
}
const proxy = deriveRestingProxyFromPulse(samples);
const proxy = deriveRestingProxyFromPulse(samples, DAY_KEY);
expect(proxy).toHaveLength(1);
// 20th percentile sits in the low band, well below the workout reads.
expect(proxy[0].value).toBeLessThanOrEqual(80);
@@ -112,7 +115,7 @@ describe("deriveRestingProxyFromPulse", () => {
day("2026-06-01T12:00:00", 64),
day("2026-06-01T20:00:00", 68),
];
const proxy = deriveRestingProxyFromPulse(samples);
const proxy = deriveRestingProxyFromPulse(samples, DAY_KEY);
expect(proxy).toHaveLength(2);
expect(proxy[0].measuredAt.getTime()).toBeLessThan(
proxy[1].measuredAt.getTime(),
@@ -125,7 +128,9 @@ describe("deriveRestingProxyFromPulse", () => {
const oneSampleWorkoutDay: PulseSample[] = [
day("2026-06-05T18:00:00", 165),
];
expect(deriveRestingProxyFromPulse(oneSampleWorkoutDay)).toEqual([]);
expect(deriveRestingProxyFromPulse(oneSampleWorkoutDay, DAY_KEY)).toEqual(
[],
);
// A day below the min-sample floor is dropped; only the day with enough
// samples contributes.
@@ -135,13 +140,13 @@ describe("deriveRestingProxyFromPulse", () => {
day("2026-06-06T08:00:00", 62),
day("2026-06-06T09:00:00", 64),
];
const proxy = deriveRestingProxyFromPulse(mixed);
const proxy = deriveRestingProxyFromPulse(mixed, DAY_KEY);
expect(proxy).toHaveLength(1);
expect(proxy[0].value).toBeLessThan(150);
});
it("returns empty for no samples", () => {
expect(deriveRestingProxyFromPulse([])).toEqual([]);
expect(deriveRestingProxyFromPulse([], DAY_KEY)).toEqual([]);
});
});
@@ -158,6 +163,7 @@ describe("resolveRestingPulseSeries", () => {
day("2026-06-01T18:00:00", 150),
);
const { series, which } = resolveRestingPulseSeries({
dayKeyOf: DAY_KEY,
restingSamples,
pulseSamples,
});
@@ -174,6 +180,7 @@ describe("resolveRestingPulseSeries", () => {
day("2026-06-01T18:00:00", 150),
];
const { series, which } = resolveRestingPulseSeries({
dayKeyOf: DAY_KEY,
restingSamples: [],
pulseSamples,
});
@@ -184,7 +191,11 @@ describe("resolveRestingPulseSeries", () => {
it("reports 'none' when neither series has data", () => {
expect(
resolveRestingPulseSeries({ restingSamples: [], pulseSamples: [] }),
resolveRestingPulseSeries({
dayKeyOf: DAY_KEY,
restingSamples: [],
pulseSamples: [],
}),
).toEqual({ series: [], which: "none" });
});
@@ -218,6 +229,7 @@ describe("resolveRestingPulseSeries", () => {
}
const { series, which } = resolveRestingPulseSeries({
dayKeyOf: DAY_KEY,
restingSamples,
pulseSamples,
});
@@ -249,6 +261,7 @@ describe("resolveRestingPulseSeries", () => {
// A native day must not be second-guessed by the proxy, and a native
// account with no gap days keeps the honest 'resting' label.
const { series, which } = resolveRestingPulseSeries({
dayKeyOf: DAY_KEY,
restingSamples: [day("2026-06-01T04:00:00", 58)],
pulseSamples: [
day("2026-06-01T07:00:00", 80),
@@ -276,7 +289,7 @@ describe("deriveRestingProxyFromPulse — the day bucket is the PROFILE day", ()
day("2026-06-02T15:00:00", 68),
day("2026-06-02T21:00:00", 70),
];
const proxy = deriveRestingProxyFromPulse(samples);
const proxy = deriveRestingProxyFromPulse(samples, DAY_KEY);
expect(proxy).toHaveLength(1);
});
@@ -293,7 +306,7 @@ describe("deriveRestingProxyFromPulse — the day bucket is the PROFILE day", ()
day("2026-06-02T00:30:00", 82),
day("2026-06-02T00:50:00", 84),
];
const proxy = deriveRestingProxyFromPulse(samples);
const proxy = deriveRestingProxyFromPulse(samples, DAY_KEY);
expect(proxy).toHaveLength(2);
});
+1 -1
View File
@@ -22,7 +22,7 @@
*/
import { prisma } from "@/lib/db";
import { decodeKeyList } from "@/lib/mood/context-vocabulary";
import { DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { resolveLinkedDayFigures } from "@/lib/mood/linked-context";
import type { PrognosisDayInput } from "./features";
+2 -1
View File
@@ -22,7 +22,8 @@ import {
dayKeyAgeInDays,
isCurrentForTodayClaim,
} from "@/lib/insights/measurement-freshness";
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import type { FeatureContribution } from "./forecast";
import { countQualifyingDays } from "./load";
+7 -9
View File
@@ -39,7 +39,6 @@
* Pure & deterministic — unit-tested in `__tests__/resting-pulse.test.ts`.
*/
import { percentile } from "@/lib/insights/strain-score";
import { toBerlinDayKey } from "@/lib/tz/resolver";
/** A timestamped heart-rate sample. */
export interface PulseSample {
@@ -78,12 +77,11 @@ export const RESTING_PROXY_MIN_DAILY_SAMPLES = 3;
export function deriveRestingProxyFromPulse(
pulseSamples: ReadonlyArray<PulseSample>,
/**
* Day-key function used to bucket samples. Defaults to Berlin-day so
* direct callers / tests stay zero-config; the targets route passes
* its own `userDayKey(d, userTz)` so the proxy buckets align with the
* route's consistency-strip day buckets for non-Berlin users.
* Day-key function used to bucket samples: the user's own day
* (`userDayKey(d, userTz)`), so the proxy buckets line up with every other
* day bucket the user sees.
*/
dayKeyOf: (d: Date) => string = toBerlinDayKey,
dayKeyOf: (d: Date) => string,
): PulseSample[] {
if (pulseSamples.length === 0) return [];
const byDay = new Map<string, { firstAt: Date; values: number[] }>();
@@ -139,10 +137,10 @@ export function deriveRestingProxyFromPulse(
export function resolveRestingPulseSeries(input: {
restingSamples: ReadonlyArray<PulseSample>;
pulseSamples: ReadonlyArray<PulseSample>;
/** Optional day-key for the proxy buckets (defaults to Berlin-day). */
dayKeyOf?: (d: Date) => string;
/** Day key for the proxy buckets: the user's own day. */
dayKeyOf: (d: Date) => string;
}): { series: PulseSample[]; which: "resting" | "proxy" | "none" } {
const dayKeyOf = input.dayKeyOf ?? toBerlinDayKey;
const dayKeyOf = input.dayKeyOf;
const byTime = (a: PulseSample, b: PulseSample) =>
a.measuredAt.getTime() - b.measuredAt.getTime();
+33 -6
View File
@@ -119,7 +119,11 @@ describe("computePhaseMetricCrosstab — MOOD + GLUCOSE outcomes (QA HIGH)", ()
it("surfaces a luteal-vs-follicular GLUCOSE contrast", () => {
const { phaseByDay, measurements } = contrastFor("BLOOD_GLUCOSE", 105, 92);
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
const glucose = rows.find((r) => r.metricKey === "bloodGlucose");
expect(glucose).toBeDefined();
expect(glucose!.display).toBe("glucose");
@@ -133,7 +137,11 @@ describe("computePhaseMetricCrosstab — MOOD + GLUCOSE outcomes (QA HIGH)", ()
4.4,
2.6,
);
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
const mood = rows.find((r) => r.metricKey === "mood");
expect(mood).toBeDefined();
expect(mood!.display).toBe("mood");
@@ -164,7 +172,11 @@ describe("computePhaseMetricCrosstab", () => {
lutealRhr: 63,
follicularRhr: 57,
});
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
const rhr = rows.find((r) => r.metricKey === "restingHeartRate");
expect(rhr).toBeDefined();
// luteal higher → positive delta (lutealAvg − follicularAvg)
@@ -183,7 +195,11 @@ describe("computePhaseMetricCrosstab", () => {
lutealRhr: 63,
follicularRhr: 57,
});
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
expect(rows).toEqual([]);
});
@@ -193,7 +209,11 @@ describe("computePhaseMetricCrosstab", () => {
lutealRhr: 60,
follicularRhr: 60,
});
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
// No real separation → nothing clears p < 0.05.
expect(
rows.find((r) => r.metricKey === "restingHeartRate"),
@@ -216,7 +236,11 @@ describe("computePhaseMetricCrosstab", () => {
phaseByDay.set(key, i % 2 === 0 ? "MENSTRUAL" : "OVULATORY");
measurements.push(m("RESTING_HEART_RATE", key, 200));
}
const rows = computePhaseMetricCrosstab({ phaseByDay, measurements });
const rows = computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
});
const rhr = rows.find((r) => r.metricKey === "restingHeartRate")!;
// Means reflect only the luteal/follicular days, not the 200-bpm noise.
expect(rhr.lutealAvg).toBeLessThan(70);
@@ -226,6 +250,7 @@ describe("computePhaseMetricCrosstab", () => {
it("returns empty for an empty phase map", () => {
expect(
computePhaseMetricCrosstab({
timeZone: "Europe/Berlin",
phaseByDay: new Map(),
measurements: [m("RESTING_HEART_RATE", "2026-03-01", 60)],
}),
@@ -287,6 +312,7 @@ describe("discoverPhaseCorrelations", () => {
);
}
const result = discoverPhaseCorrelations({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
locale: "en",
@@ -320,6 +346,7 @@ describe("discoverPhaseCorrelations", () => {
measurements.push(m("RESTING_HEART_RATE", key, 60)); // constant → no variance
}
const result = discoverPhaseCorrelations({
timeZone: "Europe/Berlin",
phaseByDay,
measurements,
locale: "en",
+16 -2
View File
@@ -183,6 +183,8 @@ export function computePhaseMetricCrosstab(args: {
measurements: CrossMetricMeasurement[];
/** The user's source-priority blob (threaded into `metricDayMap`). */
userPriorityJson?: unknown;
/** The user's zone, the calendar the phase days are keyed on. */
timeZone: string;
}): PhaseMetricCrosstabRow[] {
const { phaseByDay, measurements } = args;
const userPriorityJson = args.userPriorityJson ?? null;
@@ -198,7 +200,12 @@ export function computePhaseMetricCrosstab(args: {
(typeof PHASE_CROSSTAB_METRICS)[PhaseCrosstabMetricKey],
]
>) {
const metricByDay = metricDayMap(measurements, cfg.type, userPriorityJson);
const metricByDay = metricDayMap(
measurements,
cfg.type,
userPriorityJson,
args.timeZone,
);
if (metricByDay.size === 0) continue;
const lutealVals: number[] = [];
@@ -293,6 +300,8 @@ export function discoverPhaseCorrelations(args: {
phaseByDay: Map<string, CyclePhase>;
measurements: CrossMetricMeasurement[];
userPriorityJson?: unknown;
/** The user's zone, the calendar the phase days are keyed on. */
timeZone: string;
/**
* The reader's locale. Each surviving row carries a finished `interpretation`
* sentence that the cycle route serves straight to the client, so it has to
@@ -307,7 +316,12 @@ export function discoverPhaseCorrelations(args: {
const phaseSeries = buildPhaseDiscoverySeries(phaseByDay);
const outcomeSeries: NamedSeries[] = [];
for (const [, cfg] of Object.entries(PHASE_CROSSTAB_METRICS)) {
const byDay = metricDayMap(measurements, cfg.type, userPriorityJson);
const byDay = metricDayMap(
measurements,
cfg.type,
userPriorityJson,
args.timeZone,
);
if (byDay.size === 0) continue;
const points: DailySeriesPoint[] = [];
for (const [day, value] of byDay) points.push({ day, value });
+2 -1
View File
@@ -25,7 +25,8 @@ import {
import { persistPredictionCache } from "@/lib/cycle/prediction-cache";
import { addDays } from "@/lib/cycle/day-math";
import { BBT_WINDOW } from "@/lib/cycle/types";
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/** Day-log lookback: the calendar's default past span or the symptothermal
* window, whichever reaches further back. */
+2 -2
View File
@@ -33,7 +33,7 @@ import { resolveJobLocale } from "@/lib/i18n/job-locale";
import { getServerTranslator } from "@/lib/i18n/server-translator";
import type { ServerTranslator } from "@/lib/i18n/server-translator";
import { wallClockInTz } from "@/lib/tz/wall-clock";
import { userDayKey } from "@/lib/tz/format";
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { dispatchNotification } from "@/lib/notifications/dispatcher";
import { loadDailyDigest } from "@/lib/daily/load-digest";
import type { DailyDigest } from "@/lib/daily/digest";
@@ -175,7 +175,7 @@ export async function maybeDispatchDailyBriefing(
return "opted-out";
}
const tz = user.timezone || "Europe/Berlin";
const tz = user.timezone || DEFAULT_TIMEZONE;
const { hour } = wallClockInTz(now, tz);
if (
hour < DAILY_BRIEFING_MORNING_EARLIEST_HOUR ||
+2 -2
View File
@@ -22,7 +22,6 @@ import {
import { getUnitForType } from "./validations/measurement";
import {
makeFormatters,
DISPLAY_TIMEZONE,
type DateFormatPreference,
type TimeFormatPreference,
} from "./format-locale";
@@ -39,6 +38,7 @@ import {
pdfCursorState,
type DoctorReportPdfRenderContext,
} from "./doctor-report-pdf/render-context";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
type T = (key: string, params?: Record<string, string | number>) => string;
@@ -236,7 +236,7 @@ export function buildDoctorReportPdfDocument(
formatters.number(value, decimals);
const fmtDate = (iso: string) => formatters.date(iso);
const footerTz =
userTz && isValidTimezone(userTz) ? userTz : DISPLAY_TIMEZONE;
userTz && isValidTimezone(userTz) ? userTz : DEFAULT_TIMEZONE;
const unitFor = (type: string): string => {
const staticUnit = DOCTOR_REPORT_TYPE_UNIT_KEYS[type];
+2 -2
View File
@@ -61,7 +61,7 @@ import { loadDenseMeasurementBuckets } from "./dense-buckets";
import { summariseDenseBuckets } from "./measurement-series";
import { emptyGlucoseClinical } from "./glucose-panel";
import { buildAdministrationLedger, buildGlp1Block } from "./medications";
import { validTimezoneOr } from "@/lib/tz/format";
import { validTimezoneOr, DEFAULT_TIMEZONE } from "@/lib/tz/format";
import {
loadAllergies,
loadAnamnesis,
@@ -147,7 +147,7 @@ export async function collectDoctorReportData(
insurerIkNumber: true,
},
});
const reportTz = validTimezoneOr(userProfile?.timezone, "Europe/Berlin");
const reportTz = validTimezoneOr(userProfile?.timezone, DEFAULT_TIMEZONE);
const aggregateDenseTypes = days > DENSE_REPORT_RAW_WINDOW_DAYS;
const densePulse = aggregateDenseTypes && !excluded.includes("PULSE");
+1 -2
View File
@@ -27,8 +27,7 @@ import {
reanchorAppointmentReminder,
type AppointmentReminderInput,
} from "@/lib/encounters/appointment-reminder";
const DEFAULT_TIMEZONE = "Europe/Berlin";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* The record owner's zone AND language, read together.
+4 -12
View File
@@ -9,22 +9,14 @@
* (jobs, API routes, PDF generation) pass the locale explicitly through
* `makeFormatters(locale)`. The optional second argument carries the
* per-user timezone (v1.4.25 W7) — when omitted the formatter falls back
* to `DISPLAY_TIMEZONE` so legacy callers keep rendering in Europe/Berlin.
* to `DEFAULT_TIMEZONE` so legacy callers keep rendering in the default zone.
*
* UTC is always preserved in the database.
*/
import type { Locale } from "./i18n/config";
import { getDateTimeFormat, getNumberFormat } from "./intl/formatter-cache";
import { isValidTimezone } from "./tz/format";
/**
* Fallback timezone for surfaces that are not yet user-scoped (admin
* tables, audit log viewer, anything without a resolved user). User-
* scoped surfaces should call `makeFormatters(locale, userTz)` with
* the value from `resolveUserTimezone()`.
*/
export const DISPLAY_TIMEZONE = "Europe/Berlin";
import { DEFAULT_TIMEZONE, isValidTimezone } from "./tz/format";
/**
* Map our short locale ("de" / "en") to a full BCP-47 tag suitable for
@@ -185,7 +177,7 @@ export interface Formatters {
* `useFormatters()` silently took the default. A caller with nothing to
* pass writes "AUTO" and thereby says so. Same for `userTz`: pass the
* resolved profile zone, or an explicit `undefined` to accept the
* `DISPLAY_TIMEZONE` fallback.
* `DEFAULT_TIMEZONE` fallback.
*/
export function makeFormatters(
locale: Locale,
@@ -199,7 +191,7 @@ export function makeFormatters(
// every page that renders a timestamp. Validate here (cheap — the
// probe memoises successful constructions) and fall back to Berlin,
// matching `formatInUserTz` / `hourInTz` / `isNearUtc`.
const tz = userTz && isValidTimezone(userTz) ? userTz : DISPLAY_TIMEZONE;
const tz = userTz && isValidTimezone(userTz) ? userTz : DEFAULT_TIMEZONE;
const hourOpts = hourCycleOptions(timeFormat);
// Field-order locale for the numeric date renderers. AUTO keeps the
// user's own locale; DMY/MDY/YMD pin a canonical locale whose default
@@ -6,7 +6,6 @@ import {
bridgeFrozenStreakGaps,
calculateLongestStreak,
evaluateAchievementsWithCompletionDates,
getUniqueBerlinDays,
type AchievementMetrics,
type AchievementProgress,
type EarnabilityFlags,
@@ -68,16 +67,6 @@ const NONE_EARNABLE: EarnabilityFlags = {
};
describe("gamification achievements", () => {
it("deduplicates and sorts day keys", () => {
const days = getUniqueBerlinDays([
new Date("2026-02-11T12:00:00Z"),
new Date("2026-02-10T12:00:00Z"),
new Date("2026-02-11T16:00:00Z"),
]);
expect(days).toEqual(["2026-02-10", "2026-02-11"]);
});
it("calculates the longest streak", () => {
expect(
calculateLongestStreak([
@@ -7,7 +7,7 @@ import {
getHiddenMetrics,
getMoodMetrics,
} from "@/lib/gamification/expansion-metrics";
import { toBerlinDayKey } from "@/lib/gamification/achievements";
import { userDayKey } from "@/lib/tz/format";
// Mirror of the module-private Berlin-hour derivation so the parity test can
// build a CORRECT precomputed `measurementHours` array.
@@ -408,7 +408,7 @@ describe("achievements Intl precompute — byte-identical parity", () => {
];
const measurementDayKeys = measurements.map((m) =>
toBerlinDayKey(m.measuredAt),
userDayKey(m.measuredAt, "Europe/Berlin"),
);
const measurementHours = measurements.map((m) => berlinHour(m.measuredAt));
-26
View File
@@ -1,5 +1,3 @@
const BERLIN_TIMEZONE = "Europe/Berlin";
export const GAMIFICATION_ROLLOUT_AT = new Date("2026-02-20T00:00:00.000Z");
export type AchievementMetricKey =
@@ -233,13 +231,6 @@ export interface AchievementSummary {
nextAchievement: AchievementProgress | null;
}
const DAY_KEY_FORMATTER = new Intl.DateTimeFormat("en-US", {
timeZone: BERLIN_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const STREAK_TARGETS = [1, 7, 30, 180, 360] as const;
function buildStreakAchievements(config: {
@@ -723,23 +714,6 @@ function dayKeyToNumber(dayKey: string): number {
return Date.UTC(year, month - 1, day) / 86_400_000;
}
export function toBerlinDayKey(date: Date): string {
const parts = DAY_KEY_FORMATTER.formatToParts(date);
const year = parts.find((part) => part.type === "year")?.value;
const month = parts.find((part) => part.type === "month")?.value;
const day = parts.find((part) => part.type === "day")?.value;
if (!year || !month || !day) {
throw new Error("Could not format date");
}
return `${year}-${month}-${day}`;
}
export function getUniqueBerlinDays(dates: Date[]): string[] {
return Array.from(new Set(dates.map((date) => toBerlinDayKey(date)))).sort();
}
export function calculateLongestStreak(dayKeys: string[]): number {
if (dayKeys.length === 0) return 0;
+3 -3
View File
@@ -14,7 +14,6 @@ import {
import { apiFetchRaw } from "@/lib/api/api-fetch";
import { locales, defaultLocale, type Locale } from "./config";
import {
DISPLAY_TIMEZONE,
makeFormatters,
type Formatters,
type TimeFormatPreference,
@@ -32,6 +31,7 @@ import {
primeMessages,
type MessageBundle,
} from "./load-locale";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
interface I18nContextValue {
locale: Locale;
@@ -370,7 +370,7 @@ export function useDateFormatPreference(): DateFormatPreference {
/**
* The user's mirrored profile timezone, resolved to a renderable IANA zone:
* valid mirror value → `DISPLAY_TIMEZONE` (Europe/Berlin). Reactive to
* valid mirror value → `DEFAULT_TIMEZONE` (Europe/Berlin). Reactive to
* mirror changes (profile save, cross-tab, `/api/auth/me` re-fetch) via the
* same localStorage-mirror pattern as the hour-cycle preference. SSR and the
* pre-fetch state resolve Berlin — deliberately NO browser-timezone rung
@@ -386,7 +386,7 @@ export function useDisplayTimezone(): string {
readStoredTimezone,
() => "",
);
return stored !== "" ? stored : DISPLAY_TIMEZONE;
return stored !== "" ? stored : DEFAULT_TIMEZONE;
}
/**
@@ -42,7 +42,7 @@ import { prisma } from "@/lib/db";
import { runStatusCompletion } from "@/lib/insights/status-provider";
import { hashInsightSnapshot } from "@/lib/insights/snapshot-hash";
import { PROMPT_VERSION } from "@/lib/ai/prompts/base-system";
import { toBerlinDayKey } from "@/lib/tz/resolver";
import { userDayKey } from "@/lib/tz/format";
import {
generateBiomarkerStatus,
biomarkerStatusScope,
@@ -142,7 +142,7 @@ describe("generateBiomarkerStatus — empty-data guard", () => {
describe("generateBiomarkerStatus — cache read", () => {
it("serves today's cached text without calling the provider", async () => {
const todayKey = toBerlinDayKey(new Date());
const todayKey = userDayKey(new Date(), "Europe/Berlin");
vi.mocked(prisma.insightStatusCache.findUnique).mockResolvedValue(
noteRow({
dateKey: todayKey,
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import {
applyPayloadBudget,
bucketSeries,
dayOffsetToBerlinDayKey,
dayOffsetToDayKey,
} from "../bucket-series";
const dayMs = 24 * 60 * 60 * 1000;
@@ -75,7 +75,7 @@ describe("bucketSeries()", () => {
});
});
describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
describe("dayOffsetToDayKey() across DST boundaries", () => {
// Europe/Berlin DST in 2024: spring-forward at 2024-03-31 02:00 → 03:00,
// fall-back at 2024-10-27 03:00 → 02:00. Naive `now − dayOffset·86_400_000`
// would crawl past those boundaries by an hour and silently land on the
@@ -85,8 +85,8 @@ describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
it("produces today's Berlin date for dayOffset 0 around the spring-forward", () => {
// 2024-03-31 11:30 Berlin (= 09:30 UTC, after the gap).
const now = new Date("2024-03-31T09:30:00.000Z");
expect(dayOffsetToBerlinDayKey(now, 0)).toBe("2024-03-31");
expect(dayOffsetToBerlinDayKey(now, 1)).toBe("2024-03-30");
expect(dayOffsetToDayKey(now, 0)).toBe("2024-03-31");
expect(dayOffsetToDayKey(now, 1)).toBe("2024-03-30");
});
it("crossing the spring-forward DST boundary stays on the correct Berlin calendar day", () => {
@@ -96,10 +96,10 @@ describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
// 11:30 CET → still 2024-03-30. That happens to look right here, so
// the killer case is dayOffset 2 from a moment LATE on the day before
// the gap.
expect(dayOffsetToBerlinDayKey(now, 0)).toBe("2024-04-02");
expect(dayOffsetToBerlinDayKey(now, 1)).toBe("2024-04-01");
expect(dayOffsetToBerlinDayKey(now, 2)).toBe("2024-03-31");
expect(dayOffsetToBerlinDayKey(now, 3)).toBe("2024-03-30");
expect(dayOffsetToDayKey(now, 0)).toBe("2024-04-02");
expect(dayOffsetToDayKey(now, 1)).toBe("2024-04-01");
expect(dayOffsetToDayKey(now, 2)).toBe("2024-03-31");
expect(dayOffsetToDayKey(now, 3)).toBe("2024-03-30");
});
it("crossing the spring-forward boundary from late-evening Berlin time does not slip a day", () => {
@@ -108,9 +108,9 @@ describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
// 23:30 CET, which Intl formats as 2024-03-30. The CALENDAR-day
// answer is 2024-03-31 — one Berlin calendar day earlier than today.
const now = new Date("2024-03-31T22:30:00.000Z");
expect(dayOffsetToBerlinDayKey(now, 0)).toBe("2024-04-01");
expect(dayOffsetToBerlinDayKey(now, 1)).toBe("2024-03-31");
expect(dayOffsetToBerlinDayKey(now, 2)).toBe("2024-03-30");
expect(dayOffsetToDayKey(now, 0)).toBe("2024-04-01");
expect(dayOffsetToDayKey(now, 1)).toBe("2024-03-31");
expect(dayOffsetToDayKey(now, 2)).toBe("2024-03-30");
});
it("crossing the fall-back boundary from late-evening Berlin time does not slip a day", () => {
@@ -120,9 +120,9 @@ describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
// 01:30 → 2024-10-27. That's actually correct by coincidence, so we
// probe the dayOffset where the bias bites:
const now = new Date("2024-10-27T23:30:00.000Z");
expect(dayOffsetToBerlinDayKey(now, 0)).toBe("2024-10-28");
expect(dayOffsetToBerlinDayKey(now, 1)).toBe("2024-10-27");
expect(dayOffsetToBerlinDayKey(now, 2)).toBe("2024-10-26");
expect(dayOffsetToDayKey(now, 0)).toBe("2024-10-28");
expect(dayOffsetToDayKey(now, 1)).toBe("2024-10-27");
expect(dayOffsetToDayKey(now, 2)).toBe("2024-10-26");
});
it("crossing the fall-back boundary the other direction (early-morning) stays put", () => {
@@ -131,9 +131,9 @@ describe("dayOffsetToBerlinDayKey() across DST boundaries", () => {
// is what naive 24h subtraction gives because the day was 25 hours
// long).
const now = new Date("2024-10-27T01:30:00.000Z");
expect(dayOffsetToBerlinDayKey(now, 0)).toBe("2024-10-27");
expect(dayOffsetToBerlinDayKey(now, 1)).toBe("2024-10-26");
expect(dayOffsetToBerlinDayKey(now, 7)).toBe("2024-10-20");
expect(dayOffsetToDayKey(now, 0)).toBe("2024-10-27");
expect(dayOffsetToDayKey(now, 1)).toBe("2024-10-26");
expect(dayOffsetToDayKey(now, 7)).toBe("2024-10-20");
});
});
@@ -174,16 +174,14 @@ describe("bucketSeries() honours the per-user timezone (M-TZ3)", () => {
expect(berlin).toEqual(def);
});
it("dayOffsetToBerlinDayKey resolves the offset in the passed timezone", () => {
it("dayOffsetToDayKey resolves the offset in the passed timezone", () => {
// `now` is 05-09 in LA but 05-10 in Berlin.
expect(dayOffsetToBerlinDayKey(reading, 0, "America/Los_Angeles")).toBe(
expect(dayOffsetToDayKey(reading, 0, "America/Los_Angeles")).toBe(
"2026-05-09",
);
// Default (no tz) and explicit Berlin agree.
expect(dayOffsetToBerlinDayKey(reading, 0)).toBe("2026-05-10");
expect(dayOffsetToBerlinDayKey(reading, 0, "Europe/Berlin")).toBe(
"2026-05-10",
);
expect(dayOffsetToDayKey(reading, 0)).toBe("2026-05-10");
expect(dayOffsetToDayKey(reading, 0, "Europe/Berlin")).toBe("2026-05-10");
});
it("applyPayloadBudget threads the timezone through to the buckets", () => {
@@ -43,6 +43,8 @@ import {
import { foldDayAggregates } from "@/lib/measurements/__tests__/fake-day-aggregates";
import type { ReadDayAggregatesOptions } from "@/lib/measurements/day-aggregates";
const TZ = "Europe/Berlin";
const dayMs = 24 * 60 * 60 * 1000;
/** Readings spanning `days` back from `now`, `perDay` per day. */
@@ -80,7 +82,7 @@ describe("buildGradedSeriesWithRollups — bounded reads (#1023)", () => {
rows: [rollupRow(new Date("2025-09-01T00:00:00Z"), 79)],
});
await buildGradedSeriesWithRollups("u1", "PULSE", now);
await buildGradedSeriesWithRollups("u1", "PULSE", now, TZ);
expect(findMany).not.toHaveBeenCalled();
const opts = readDayAggregates.mock.calls[0][0] as ReadDayAggregatesOptions;
@@ -99,7 +101,7 @@ describe("buildGradedSeriesWithRollups — bounded reads (#1023)", () => {
serveFrom(points(800, now));
readBestGranularityRollups.mockResolvedValue(null);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now, TZ);
expect(series.monthly.length).toBeGreaterThan(0);
expect(series.yearly.length).toBeGreaterThan(0);
@@ -129,7 +131,7 @@ describe("buildGradedSeriesWithRollups — bounded reads (#1023)", () => {
},
);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now, TZ);
expect(series.monthly.length).toBeGreaterThan(0);
expect(series.yearly.length).toBeGreaterThan(0);
@@ -148,7 +150,7 @@ describe("buildGradedSeriesWithRollups — bounded reads (#1023)", () => {
: null,
);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now);
const series = await buildGradedSeriesWithRollups("u1", "WEIGHT", now, TZ);
expect(series.monthly).toHaveLength(1);
expect(series.yearly.length).toBeGreaterThan(0);
@@ -170,7 +172,7 @@ describe("buildGradedSeriesFromDayAggregates — parity with the raw fold", () =
{ measuredAt: new Date(now.getTime() - 21 * dayMs), value: 99 },
{ measuredAt: new Date(now.getTime() - 91 * dayMs), value: 41 },
];
const raw = buildGradedSeriesFromPoints(rows, now);
const raw = buildGradedSeriesFromPoints(rows, now, TZ);
const agg = buildGradedSeriesFromDayAggregates(
foldDayAggregates(rows, {
since: new Date(0),
@@ -9,6 +9,8 @@ import {
type SleepStageRow,
} from "@/lib/analytics/sleep-night";
const TZ = "Europe/Berlin";
const dayMs = 24 * 60 * 60 * 1000;
function dailyPoints(
@@ -34,7 +36,7 @@ describe("buildGradedSeriesFromPoints", () => {
const now = new Date("2026-05-31T12:00:00Z");
it("keeps the last ~14-21 days at daily granularity", () => {
const s = buildGradedSeriesFromPoints(dailyPoints(400, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(400, now), now, TZ);
expect(s.recent.length).toBeGreaterThan(0);
expect(s.recent.length).toBeLessThanOrEqual(21);
// Each recent bucket carries daily aggregates.
@@ -51,7 +53,7 @@ describe("buildGradedSeriesFromPoints", () => {
});
it("folds the weeks after the recent window into ~8-10 ISO-week buckets", () => {
const s = buildGradedSeriesFromPoints(dailyPoints(400, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(400, now), now, TZ);
expect(s.weekly.length).toBeGreaterThan(0);
expect(s.weekly.length).toBeLessThanOrEqual(12);
for (const w of s.weekly) {
@@ -64,7 +66,7 @@ describe("buildGradedSeriesFromPoints", () => {
});
it("folds older history into ~9-12 monthly buckets", () => {
const s = buildGradedSeriesFromPoints(dailyPoints(730, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(730, now), now, TZ);
expect(s.monthly.length).toBeGreaterThan(0);
expect(s.monthly.length).toBeLessThanOrEqual(14);
for (const m of s.monthly) {
@@ -77,7 +79,7 @@ describe("buildGradedSeriesFromPoints", () => {
it("folds multi-year history into yearly buckets with a trend slope", () => {
// 3+ years so at least one year lands in the yearly bucket.
const s = buildGradedSeriesFromPoints(dailyPoints(1200, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(1200, now), now, TZ);
expect(s.yearly.length).toBeGreaterThan(0);
for (const y of s.yearly) {
expect(y).toHaveProperty("year");
@@ -87,7 +89,7 @@ describe("buildGradedSeriesFromPoints", () => {
});
it("collapses a 2-year daily weigher into <= ~50 buckets, not 730", () => {
const s = buildGradedSeriesFromPoints(dailyPoints(730, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(730, now), now, TZ);
// ~21 recent + ~10 weekly + ~12 monthly + ~2-3 yearly. Worst-case
// boundary slack lands ~46; the point is the order-of-magnitude
// collapse from 730 daily readings, not an exact bucket count.
@@ -95,12 +97,12 @@ describe("buildGradedSeriesFromPoints", () => {
});
it("returns empty buckets for an empty input", () => {
const s = buildGradedSeriesFromPoints([], now);
const s = buildGradedSeriesFromPoints([], now, TZ);
expect(countBuckets(s)).toBe(0);
});
it("does not duplicate a day across recent and weekly", () => {
const s = buildGradedSeriesFromPoints(dailyPoints(120, now), now);
const s = buildGradedSeriesFromPoints(dailyPoints(120, now), now, TZ);
// The most recent ISO week of the recent window must not also be a
// weekly bucket — recent days are excluded from the weekly fold.
const recentDates = new Set(s.recent.map((r) => r.date));
@@ -115,7 +117,7 @@ describe("buildGradedSeriesFromPoints", () => {
{ measuredAt: new Date(now.getTime() - 1000), value: 90 },
{ measuredAt: new Date(now.getTime() - 2000), value: 80 },
];
const s = buildGradedSeriesFromPoints(points, now);
const s = buildGradedSeriesFromPoints(points, now, TZ);
expect(s.recent.length).toBe(1);
expect(s.recent[0].min).toBe(70);
expect(s.recent[0].max).toBe(90);
@@ -174,9 +176,27 @@ describe("buildGradedSeriesFromPoints", () => {
const points = reconstructSleepNights(rows, "UTC")
.filter((n) => n.asleepMinutes > 0)
.map((n) => ({ measuredAt: n.measuredAt, value: n.asleepMinutes }));
const graded = buildGradedSeriesFromPoints(points, sleepNow);
const graded = buildGradedSeriesFromPoints(points, sleepNow, TZ);
const recentMean = graded.recent.at(-1)?.mean ?? 0;
expect(recentMean).toBe(480); // night total, not ~1218 (stage sum)
expect(recentMean).toBeLessThan(960); // < 16 h — never impossible
});
});
describe("buildGradedSeriesFromPoints — the user's calendar", () => {
it.each([
// 23:30 on 9 June in New York is already 10 June in UTC and Berlin.
["America/New_York", "2026-06-10T03:30:00.000Z", "2026-06-09"],
// 08:00 on 10 June in Auckland and Tonga is still 9 June in UTC.
["Pacific/Auckland", "2026-06-09T20:00:00.000Z", "2026-06-10"],
["Pacific/Tongatapu", "2026-06-09T19:00:00.000Z", "2026-06-10"],
])("keys a reading on its local day in %s", (tz, iso, day) => {
const now = new Date("2026-06-12T12:00:00.000Z");
const s = buildGradedSeriesFromPoints(
[{ measuredAt: new Date(iso), value: 70 }],
now,
tz,
);
expect(s.recent.map((r) => r.date)).toEqual([day]);
});
});
@@ -1006,7 +1006,12 @@ describe("computeTagMetricCrosstab", () => {
meas(i, "ACTIVE_ENERGY_BURNED", 350 + (i % 2 === 0 ? 20 : -20)),
);
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find(
(r) => r.tag === "worked_out" && r.metricKey === "activeEnergy",
);
@@ -1045,7 +1050,12 @@ describe("computeTagMetricCrosstab", () => {
meas(i, "SLEEP_DURATION", 360 + (i % 2 === 0 ? 6 : -6)),
);
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find((r) => r.metricKey === "sleepDuration");
expect(row).toBeDefined();
expect(row!.display).toBe("hours");
@@ -1079,7 +1089,12 @@ describe("computeTagMetricCrosstab", () => {
meas(i - 1, "RECOVERY_SCORE", 80 + (i % 2 === 0 ? 3 : -3)),
);
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find((r) => r.metricKey === "nextDayRecovery");
expect(row).toBeDefined();
expect(row!.mode).toBe("nextDay");
@@ -1134,7 +1149,12 @@ describe("computeTagMetricCrosstab", () => {
62,
54,
);
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find(
(r) => r.tag === "alcohol" && r.metricKey === "nextDayRestingHeartRate",
);
@@ -1156,7 +1176,12 @@ describe("computeTagMetricCrosstab", () => {
38,
55,
);
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find(
(r) =>
r.tag === "alcohol" && r.metricKey === "nextDayHeartRateVariability",
@@ -1183,6 +1208,7 @@ describe("computeTagMetricCrosstab", () => {
{ key, categoryKey: "health", labelKey, icon },
);
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
@@ -1220,7 +1246,12 @@ describe("computeTagMetricCrosstab", () => {
measurements.push(meas(i, "ACTIVE_ENERGY_BURNED", 350));
}
expect(CROSSTAB_MIN_PRESENT_DAYS).toBeGreaterThan(3);
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
expect(rows.find((r) => r.tag === "worked_out")).toBeUndefined();
});
@@ -1235,7 +1266,12 @@ describe("computeTagMetricCrosstab", () => {
entries.push(entry(i, 3, []));
measurements.push(meas(i, "ACTIVE_ENERGY_BURNED", 350));
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
expect(rows).toEqual([]);
});
@@ -1245,6 +1281,7 @@ describe("computeTagMetricCrosstab", () => {
entries.push(structuredEntry(i, 4, i < 12 ? [WORKOUT] : []));
}
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements: [],
now: NOW,
@@ -1301,7 +1338,12 @@ describe("computeTagMetricCrosstab", () => {
),
);
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find(
(r) => r.tag === "worked_out" && r.metricKey === "activeEnergy",
);
@@ -1335,7 +1377,12 @@ describe("computeTagMetricCrosstab", () => {
sourcedMeas(i, "SLEEP_DURATION", 360 + (i % 2 === 0 ? 6 : -6), "WHOOP"),
);
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find((r) => r.metricKey === "sleepDuration");
expect(row).toBeDefined();
// 8 h, not 16 h — the Fitbit twin is dropped, not summed on top.
@@ -1370,7 +1417,12 @@ describe("computeTagMetricCrosstab", () => {
measurements.push(sourcedMeas(i, "SLEEP_DURATION", 120 + j, "WHOOP"));
measurements.push(sourcedMeas(i, "SLEEP_DURATION", 120 + j, "WHOOP"));
}
const rows = computeTagMetricCrosstab({ entries, measurements, now: NOW });
const rows = computeTagMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
});
const row = rows.find((r) => r.metricKey === "sleepDuration");
expect(row).toBeDefined();
expect(row!.withAvg).toBeCloseTo(8, 1); // 3 × 160 = 480 min = 8 h
@@ -1478,6 +1530,7 @@ describe("computeFactorMetricCrosstab", () => {
);
}
const rows = computeFactorMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
@@ -1517,6 +1570,7 @@ describe("computeFactorMetricCrosstab", () => {
);
}
const rows = computeFactorMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
@@ -1543,6 +1597,7 @@ describe("computeFactorMetricCrosstab", () => {
CROSSTAB_MIN_PRESENT_DAYS + CROSSTAB_MIN_ABSENT_DAYS,
).toBeGreaterThan(6);
const rows = computeFactorMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
@@ -1558,7 +1613,12 @@ describe("computeFactorMetricCrosstab", () => {
measurements.push(meas(i, "SLEEP_DURATION", 420));
}
expect(
computeFactorMetricCrosstab({ entries, measurements, now: NOW }),
computeFactorMetricCrosstab({
timeZone: "Europe/Berlin",
entries,
measurements,
now: NOW,
}),
).toEqual([]);
});
+15 -11
View File
@@ -33,7 +33,7 @@ import { sanitizeForPrompt } from "@/lib/insights/sanitize";
import { getNoKeyBloodPressureStatusText } from "@/lib/insights/no-key-fallbacks";
import {
applyPayloadBudget,
dayOffsetToBerlinDayKey,
dayOffsetToDayKey,
type DailyBucket,
} from "@/lib/insights/bucket-series";
import {
@@ -67,6 +67,7 @@ import { annotate } from "@/lib/logging/context";
import { resolveUserTimezone, userDayKey } from "@/lib/tz/resolver";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { TRACKED_INTAKE_WHERE } from "@/lib/medications/intake-tracking";
import { canonicalDailyTimestamp } from "@/lib/measurements/consolidation-tz";
/**
* Cap on the embedded correlation / paired-daily arrays. The Pearson
@@ -78,7 +79,7 @@ const CORRELATION_PAIR_CAP = 30;
/**
* Pair two daily-bucket series on `dayOffset`. The synthesised `date`
* field is anchored at the UTC midnight of the Berlin calendar day —
* `dayOffsetToBerlinDayKey()` is the source of truth so DST boundaries
* `dayOffsetToDayKey()` is the source of truth so DST boundaries
* don't slip the day-key by one. Each pair also carries `dayKey`
* directly so callers can label points without re-formatting.
*/
@@ -94,10 +95,9 @@ function pairDailyBuckets(
.map((entry) => {
const b = mapB.get(entry.dayOffset);
if (b == null) return null;
const dayKey = dayOffsetToBerlinDayKey(now, entry.dayOffset, tz);
// UTC midnight of the Berlin day — formatting this Date with
// `toBerlinDayKey()` is guaranteed DST-safe because the y-m-d
// fields below are the Berlin calendar day fields by construction.
const dayKey = dayOffsetToDayKey(now, entry.dayOffset, tz);
// UTC midnight of the user's day: an ordering handle only; `dayKey`
// is the day itself.
const [y, m, d] = dayKey.split("-").map(Number);
return {
a: entry.value,
@@ -435,8 +435,8 @@ export async function prepareBloodPressureStatusForUser(
}
const continuityVsSystolicSeries = sysSeries.daily.map((point) => {
// DST-safe: dayOffsetToBerlinDayKey computes calendar days, not 24h ticks.
const dayKey = dayOffsetToBerlinDayKey(now, point.dayOffset, userTz);
// DST-safe: dayOffsetToDayKey computes calendar days, not 24h ticks.
const dayKey = dayOffsetToDayKey(now, point.dayOffset, userTz);
const taken = takenByDay.get(dayKey) ?? 0;
const continuityPct =
expectedBpIntakesPerDay > 0
@@ -480,18 +480,22 @@ export async function prepareBloodPressureStatusForUser(
const gradedFromDaily = (buckets: DailyBucket[]) =>
buildGradedSeriesFromPoints(
buckets.map((b) => ({
measuredAt: new Date(dayOffsetToBerlinDayKey(now, b.dayOffset, userTz)),
measuredAt: canonicalDailyTimestamp(
dayOffsetToDayKey(now, b.dayOffset, userTz),
userTz,
),
value: b.value,
})),
now,
userTz,
);
// The two BP channels source their recent / weekly slices from a
// bounded raw read and their monthly / yearly tail from the MONTH /
// YEAR rollup tier (full-history in-memory fallback on a cold-tier
// coverage miss). Mood has no rollup tier, so it stays an in-memory fold.
const [sysGraded, diaGraded] = await Promise.all([
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_SYS", now),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_DIA", now),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_SYS", now, userTz),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_DIA", now, userTz),
]);
const moodGraded = gradedFromDaily(moodSeries.daily);
+1
View File
@@ -256,6 +256,7 @@ export async function prepareBmiStatusForUser(
userId,
"WEIGHT",
now,
userTz,
);
const bmiGraded = scaleGradedSeries(weightGraded, 1 / heightFactor, 2);
const bmiSeries = {
+1 -1
View File
@@ -96,7 +96,7 @@ function utcMidnightOfUserDay(date: Date, tz: string): number {
* `tz` defaults to Berlin only so legacy callers keep working; per-user
* surfaces pass the resolved `User.timezone`.
*/
export function dayOffsetToBerlinDayKey(
export function dayOffsetToDayKey(
now: Date,
dayOffset: number,
tz: string = DEFAULT_TIMEZONE,
@@ -886,6 +886,7 @@ export async function generateComprehensiveInsight(
userId,
dbUser?.displayName ?? null,
locale,
await resolveUserTimezone(userId),
);
const systemPrompt = buildSystemPromptWithReferences(
locale,
+7 -3
View File
@@ -218,7 +218,7 @@ export async function prepareGeneralStatusForUser(
const series = applyPayloadBudget(records, { now, tz: userTz });
dailyByType.set(type, series);
const graded = buildGradedSeriesFromPoints(records, now);
const graded = buildGradedSeriesFromPoints(records, now, userTz);
return [
[
@@ -298,7 +298,11 @@ export async function prepareGeneralStatusForUser(
now,
tz: userTz,
});
const adherenceGraded = buildGradedSeriesFromPoints(adherenceRecords, now);
const adherenceGraded = buildGradedSeriesFromPoints(
adherenceRecords,
now,
userTz,
);
// Fetch mood context (optional — for enrichment only). v1.4.28
// FB-D2 — cap at 90 entries.
@@ -316,7 +320,7 @@ export async function prepareGeneralStatusForUser(
value: entry.score,
}));
const moodSeries = applyPayloadBudget(moodRecords, { now, tz: userTz });
const moodGraded = buildGradedSeriesFromPoints(moodRecords, now);
const moodGraded = buildGradedSeriesFromPoints(moodRecords, now, userTz);
const moodSummary = summarizeSeries(
moodSeries.daily.map((bucket) => ({ value: bucket.value })),
);
+29 -37
View File
@@ -57,7 +57,7 @@ import {
readDayAggregates,
type DayAggregateRow,
} from "@/lib/measurements/day-aggregates";
import { toBerlinYmd } from "@/lib/tz/resolver";
import { userDayKey } from "@/lib/tz/format";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -87,7 +87,7 @@ const MONTHLY_WINDOW_MS = WEEKLY_WINDOW_MS + MONTHLY_MONTHS * 30 * MS_PER_DAY;
const COLD_FALLBACK_WINDOW_DAYS = 1095;
export interface RecentDayBucket {
/** Berlin YYYY-MM-DD. */
/** YYYY-MM-DD in the user's zone. */
date: string;
min: number;
max: number;
@@ -96,7 +96,7 @@ export interface RecentDayBucket {
}
export interface WeeklyBucket {
/** ISO week key like 2026-W19 (Berlin-anchored). */
/** ISO week key like 2026-W19 (the user's calendar). */
weekISO: string;
min: number;
max: number;
@@ -105,7 +105,7 @@ export interface WeeklyBucket {
}
export interface MonthlyBucket {
/** Berlin YYYY-MM. */
/** YYYY-MM (the user's calendar; UTC for rollup months). */
month: string;
min: number;
max: number;
@@ -114,7 +114,7 @@ export interface MonthlyBucket {
}
export interface YearlyBucket {
/** Berlin YYYY. */
/** YYYY (the user's calendar; UTC for rollup years). */
year: string;
min: number;
max: number;
@@ -141,28 +141,13 @@ function round(value: number, digits = 2): number {
return Math.round(value * factor) / factor;
}
function berlinDayKey(date: Date): string {
const { year, month, day } = toBerlinYmd(date);
return `${year}-${month}-${day}`;
}
function berlinMonthKey(date: Date): string {
const { year, month } = toBerlinYmd(date);
return `${year}-${month}`;
}
function berlinYearKey(date: Date): string {
return toBerlinYmd(date).year;
}
/**
* ISO week key (Berlin-anchored). Mirrors the Coach's `isoWeekKey` but
* fixed to the user's Berlin display day so the week label agrees with
* the rest of the snapshot.
*/
function berlinIsoWeekKey(date: Date): string {
const { year, month, day } = toBerlinYmd(date);
return isoWeekKeyOfYmd(year, month, day);
/** The `YYYY-MM-DD` day `date` falls on in `timeZone`, as its parts. */
function localYmd(
date: Date,
timeZone: string,
): { year: string; month: string; day: string } {
const [year, month, day] = userDayKey(date, timeZone).split("-");
return { year, month, day };
}
/** ISO week key of a calendar date given as `YYYY`, `MM`, `DD`. */
@@ -228,6 +213,7 @@ function leastSquaresSlope(values: number[]): number | null {
export function buildGradedSeriesFromPoints(
points: Point[],
now: Date,
timeZone: string,
): GradedSeries {
const nowMs = now.getTime();
@@ -242,14 +228,16 @@ export function buildGradedSeriesFromPoints(
const ageMs = nowMs - p.measuredAt.getTime();
if (ageMs < 0) continue; // future reading — ignore
// Every bucket is a period of the user's own calendar.
const { year, month, day } = localYmd(p.measuredAt, timeZone);
if (ageMs < RECENT_WINDOW_MS) {
foldInto(recentAgg, berlinDayKey(p.measuredAt), p.value);
foldInto(recentAgg, `${year}-${month}-${day}`, p.value);
} else if (ageMs < WEEKLY_WINDOW_MS) {
foldInto(weeklyAgg, berlinIsoWeekKey(p.measuredAt), p.value);
foldInto(weeklyAgg, isoWeekKeyOfYmd(year, month, day), p.value);
} else if (ageMs < MONTHLY_WINDOW_MS) {
foldInto(monthlyAgg, berlinMonthKey(p.measuredAt), p.value);
foldInto(monthlyAgg, `${year}-${month}`, p.value);
} else {
const yk = berlinYearKey(p.measuredAt);
const yk = year;
foldInto(yearlyAgg, yk, p.value);
const list = yearlyValues.get(yk);
if (list) list.push(p.value);
@@ -336,7 +324,7 @@ function gradedSegmentStarts(now: Date): Date[] {
*
* Replaces the raw `findMany` over the window (#1023): a watch that streams
* heart rate every few seconds put a million rows into that read, which is
* what exhausted the worker's heap. The rows here are one per Berlin day per
* what exhausted the worker's heap. The rows here are one per local day per
* age segment, and their sum / count / min / max are exact, so the recent,
* weekly and monthly slices come out identical to folding the raw rows.
*
@@ -349,6 +337,7 @@ async function readGradedDayAggregates(
type: MeasurementType,
since: Date,
now: Date,
timeZone: string,
): Promise<DayAggregateRow[]> {
return readDayAggregates({
userId,
@@ -356,7 +345,7 @@ async function readGradedDayAggregates(
since,
// Future-dated readings were skipped by the in-memory fold.
until: now,
timeZone: "Europe/Berlin",
timeZone,
// `readDayAggregates` puts a row at segment k when it is older than k
// starts (`measured_at < start`). The in-memory fold treats an age of
// exactly the window as the older bucket, so shift each start by 1 ms.
@@ -435,10 +424,12 @@ export function buildGradedSeriesFromDayAggregates(
/**
* Project a rollup bucket row to a monthly/yearly graded bucket. The
* tier already carries min/max/mean/slope per bucket — no JS folding.
* Rollup buckets are UTC months and years, so the label is read off the
* bucket start in UTC: read in a zone west of UTC it named the month before.
*/
function rollupMonthly(rows: RollupBucketRow[]): MonthlyBucket[] {
return rows.map((r) => ({
month: berlinMonthKey(r.bucketStart),
month: r.bucketStart.toISOString().slice(0, 7),
min: round(r.minValue),
max: round(r.maxValue),
mean: round(r.mean),
@@ -448,7 +439,7 @@ function rollupMonthly(rows: RollupBucketRow[]): MonthlyBucket[] {
function rollupYearly(rows: RollupBucketRow[]): YearlyBucket[] {
return rows.map((r) => ({
year: berlinYearKey(r.bucketStart),
year: r.bucketStart.toISOString().slice(0, 4),
min: round(r.minValue),
max: round(r.maxValue),
mean: round(r.mean),
@@ -485,10 +476,11 @@ export async function buildGradedSeriesWithRollups(
userId: string,
type: MeasurementType,
now: Date,
timeZone: string,
): Promise<GradedSeries> {
const since = new Date(now.getTime() - WEEKLY_WINDOW_MS);
const recentGraded = buildGradedSeriesFromDayAggregates(
await readGradedDayAggregates(userId, type, since, now),
await readGradedDayAggregates(userId, type, since, now, timeZone),
);
// v1.11.2 — load the source-priority blob once and thread it into both
@@ -548,7 +540,7 @@ export async function buildGradedSeriesWithRollups(
now.getTime() - COLD_FALLBACK_WINDOW_DAYS * MS_PER_DAY,
);
const fullGraded = buildGradedSeriesFromDayAggregates(
await readGradedDayAggregates(userId, type, fallbackSince, now),
await readGradedDayAggregates(userId, type, fallbackSince, now, timeZone),
);
if (!monthlyCovered) monthly = fullGraded.monthly;
if (!yearlyCovered) yearly = fullGraded.yearly;
@@ -310,7 +310,7 @@ export async function prepareMedicationComplianceStatusForUser(
now,
tz: userTz,
});
const dailySeries = buildGradedSeriesFromPoints(perDayRecords, now);
const dailySeries = buildGradedSeriesFromPoints(perDayRecords, now, userTz);
const latestDay = dailyBudgeted.daily[0] ?? null;
// v1.18.10 (HIGH-4) — the finished recent-vs-baseline adherence comparison
@@ -41,6 +41,7 @@ import {
syncAcceptedPatterns,
} from "@/lib/insights/correlation-patterns";
import type { RelevantCorrelation } from "@/lib/insights/assessment-context";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
/** Trailing window for the discovery scan — mirrors the route. */
@@ -92,7 +93,7 @@ export async function getRelevantCorrelationsForMetric(
where: { id: userId },
select: { timezone: true },
});
const tz = profile?.timezone ?? "Europe/Berlin";
const tz = profile?.timezone ?? DEFAULT_TIMEZONE;
const since = new Date(Date.now() - WINDOW_DAYS * MS_PER_DAY);
// The channel set is the shared one — every family the correlations page
+2 -1
View File
@@ -308,11 +308,12 @@ export async function generateMetricStatus(args: {
// straight from the deduped per-night TIME-ASLEEP `points` instead, so every
// recent/weekly/monthly/yearly bucket is a night total, not a stage sum.
const graded = isSleep
? buildGradedSeriesFromPoints(points, now)
? buildGradedSeriesFromPoints(points, now, userTz)
: await buildGradedSeriesWithRollups(
args.userId,
meta.measurementType,
now,
userTz,
);
const summary = summarizeSeries(
series.daily.map((bucket) => ({ value: bucket.value })),
+6 -4
View File
@@ -27,7 +27,7 @@ import {
import { MIN_PAIRED_N } from "@/lib/insights/correlations";
import {
applyPayloadBudget,
dayOffsetToBerlinDayKey,
dayOffsetToDayKey,
type DailyBucket,
} from "@/lib/insights/bucket-series";
import { round, summarizeSeries } from "@/lib/insights/status-shared";
@@ -294,7 +294,7 @@ export const MOOD_ORANGE_MAX = 3.5;
/**
* Pair two daily-bucket series on `dayOffset`. The synthesised `date`
* field is anchored at the UTC midnight of the Berlin calendar day —
* `dayOffsetToBerlinDayKey()` is the source of truth so DST boundaries
* `dayOffsetToDayKey()` is the source of truth so DST boundaries
* don't slip the day-key by one. Each pair also carries `dayKey`
* directly so callers can label points without re-formatting.
*/
@@ -310,7 +310,7 @@ export function pairDailyBuckets(
.map((entry) => {
const b = mapB.get(entry.dayOffset);
if (b == null) return null;
const dayKey = dayOffsetToBerlinDayKey(now, entry.dayOffset, tz);
const dayKey = dayOffsetToDayKey(now, entry.dayOffset, tz);
const [y, m, d] = dayKey.split("-").map(Number);
return {
a: entry.value,
@@ -626,12 +626,14 @@ export function computeMoodAggregates(args: {
measurements,
now,
userPriorityJson,
timeZone: tz,
});
const factorCrosstab = computeFactorMetricCrosstab({
entries,
measurements,
now,
userPriorityJson,
timeZone: tz,
});
// v1.38 — every context value against the day's pleasantness, one BH-FDR
@@ -682,7 +684,7 @@ export function computeMoodAggregates(args: {
a4: entry.a4 ?? null,
a5: entry.a5 ?? null,
})),
dayOffsetToBerlinDayKey(now, 0, tz),
dayOffsetToDayKey(now, 0, tz),
),
weekday,
timeOfDay,
+25 -13
View File
@@ -17,7 +17,7 @@ import { welchTTest } from "@/lib/insights/correlations";
import { round } from "@/lib/insights/status-shared";
import { metricKeyForType } from "@/lib/measurements/cumulative-day-sum";
import { MS_PER_DAY } from "@/lib/time-constants";
import { toBerlinYmd } from "@/lib/tz/resolver";
import { userDayKey } from "@/lib/tz/format";
import type {
CrossMetricMeasurement,
MoodAggregateEntry,
@@ -181,14 +181,9 @@ const CROSSTAB_SUM_TYPES = new Set<string>([
"ACTIVITY_STEPS",
]);
/** Berlin-calendar day key (`YYYY-MM-DD`) for a row's `measuredAt`. */
function berlinDayKey(measuredAt: Date): string {
const { year, month, day } = toBerlinYmd(measuredAt);
return `${year}-${month}-${day}`;
}
/**
* Build a Berlin-day-keyed metric map with the right aggregation. Energy
* Build a metric map keyed by the user's local day, the calendar mood
* entries are dated on, with the right aggregation. Energy
* and step totals are SUMMED per day (HealthKit `stats:` rows are already
* one daily-total row, so the sum is the total either way); sleep duration
* is SUMMED across per-stage rows to get the night total; everything else
@@ -198,7 +193,7 @@ function berlinDayKey(measuredAt: Date): string {
* Cross-source de-dup: before bucketing, the rows for this metric run
* through the SAME canonical-source picker the analytics steps/sleep path
* uses (`pickCanonicalSourceRows`, keyed by `metricKeyForType` + the
* Berlin day key). Without it, the moment two sources report the same day
* local day key). Without it, the moment two sources report the same day
* (Fitbit + Apple steps, Fitbit + WHOOP sleep) the SUM channels would
* double-count and bias the Welch delta. The picker collapses each day to
* one source (and one device-type within it), so the sum reflects one
@@ -211,7 +206,10 @@ export function metricDayMap(
measurements: CrossMetricMeasurement[],
type: string,
userPriorityJson: unknown,
/** The user's zone: days are the user's own calendar days. */
timeZone: string,
): Map<string, number> {
const dayKeyOf = (d: Date) => userDayKey(d, timeZone);
const summed = CROSSTAB_SUM_TYPES.has(type);
const typeRows = measurements.filter((m) => m.type === type);
@@ -235,13 +233,13 @@ export function metricDayMap(
})),
metricKey,
userPriorityJson,
berlinDayKey,
dayKeyOf,
).canonicalRows
: typeRows;
const byDay = new Map<string, { sum: number; count: number }>();
for (const m of canonicalRows) {
const key = berlinDayKey(m.measuredAt);
const key = dayKeyOf(m.measuredAt);
const cur = byDay.get(key) ?? { sum: 0, count: 0 };
cur.sum += m.value;
cur.count += m.count ?? 1;
@@ -297,6 +295,8 @@ export function computeTagMetricCrosstab(args: {
* test default) resolves to the default ladders.
*/
userPriorityJson?: unknown;
/** The user's zone, the calendar the metric days are cut on. */
timeZone: string;
}): TagMetricCrosstabRow[] {
const { entries, measurements, now } = args;
const windowDays = args.windowDays ?? 365;
@@ -319,7 +319,12 @@ export function computeTagMetricCrosstab(args: {
for (const [metricKey, cfg] of Object.entries(CROSSTAB_METRICS) as Array<
[CrosstabMetricKey, (typeof CROSSTAB_METRICS)[CrosstabMetricKey]]
>) {
const metricByDay = metricDayMap(measurements, cfg.type, userPriorityJson);
const metricByDay = metricDayMap(
measurements,
cfg.type,
userPriorityJson,
args.timeZone,
);
if (metricByDay.size === 0) continue;
for (const [tagKey, ref] of structuredMeta) {
@@ -609,6 +614,8 @@ export function computeFactorMetricCrosstab(args: {
now: Date;
windowDays?: number;
userPriorityJson?: unknown;
/** The user's zone, the calendar the metric days are cut on. */
timeZone: string;
}): FactorMetricCrosstabRow[] {
const { entries, measurements, now } = args;
const windowDays = args.windowDays ?? 365;
@@ -627,7 +634,12 @@ export function computeFactorMetricCrosstab(args: {
(typeof FACTOR_CROSSTAB_METRICS)[FactorCrosstabMetricKey],
]
>) {
const metricByDay = metricDayMap(measurements, cfg.type, userPriorityJson);
const metricByDay = metricDayMap(
measurements,
cfg.type,
userPriorityJson,
args.timeZone,
);
if (metricByDay.size === 0) continue;
for (const [factorKey, series] of factorSeries) {
+2 -2
View File
@@ -14,7 +14,7 @@
* "no correlation" filler.
*/
import { dayOffsetToBerlinDayKey } from "@/lib/insights/bucket-series";
import { dayOffsetToDayKey } from "@/lib/insights/bucket-series";
import { round } from "@/lib/insights/status-shared";
import { MS_PER_DAY } from "@/lib/time-constants";
import { DEFAULT_TIMEZONE, userDayKey } from "@/lib/tz/format";
@@ -120,7 +120,7 @@ function weekdayOfOffset(
dayOffset: number,
tz: string = DEFAULT_TIMEZONE,
): number {
const dayKey = dayOffsetToBerlinDayKey(now, dayOffset, tz);
const dayKey = dayOffsetToDayKey(now, dayOffset, tz);
const d = new Date(dayKey + "T00:00:00Z");
return (d.getUTCDay() + 6) % 7;
}
+2 -2
View File
@@ -10,7 +10,7 @@
* `fetchMoodAggregates`.
*/
import { dayOffsetToBerlinDayKey } from "@/lib/insights/bucket-series";
import { dayOffsetToDayKey } from "@/lib/insights/bucket-series";
import {
MOOD_GREEN_MAX,
MOOD_GREEN_MIN,
@@ -87,7 +87,7 @@ export function computeWeekdayAverages(
): WeekdayRow[] {
const sums = new Map<number, { sum: number; count: number }>();
for (const bucket of daily) {
const dayKey = dayOffsetToBerlinDayKey(now, bucket.dayOffset, tz);
const dayKey = dayOffsetToDayKey(now, bucket.dayOffset, tz);
const d = new Date(dayKey + "T00:00:00Z");
const weekday = (d.getUTCDay() + 6) % 7; // Monday = 0
const cur = sums.get(weekday) ?? { sum: 0, count: 0 };
+2 -1
View File
@@ -305,7 +305,7 @@ export async function prepareMoodStatusForUser(
// `applyPayloadBudget` daily buckets drive the in-target %, latest,
// and correlations; the compact graded series reaches the prompt.
const moodSeries = applyPayloadBudget(moodPoints, { now, tz: userTz });
const moodGraded = buildGradedSeriesFromPoints(moodPoints, now);
const moodGraded = buildGradedSeriesFromPoints(moodPoints, now, userTz);
const moodSummary = summarizeSeries(
moodSeries.daily.map((bucket) => ({ value: bucket.value })),
);
@@ -490,6 +490,7 @@ export async function prepareMoodStatusForUser(
measurements,
now,
userPriorityJson,
timeZone: userTz,
});
// v1.8.6 — the same threshold-gated narrative feed the user sees on
@@ -53,6 +53,7 @@ import {
validateNarrativeText,
buildNarrativeCorrection,
} from "@/lib/insights/narrative/narrative-grounding";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Stable identifier for the narrative prompt revision. Bumped whenever the
@@ -347,7 +348,7 @@ export async function generatePeriodNarrative(
where: { id: userId },
select: { timezone: true },
});
const tz = profile?.timezone ?? "Europe/Berlin";
const tz = profile?.timezone ?? DEFAULT_TIMEZONE;
const completion = await runCompletion({
userId,
@@ -55,6 +55,7 @@ import { buildBaselineBand, median } from "@/lib/insights/derived/baseline";
import { VITALS_BASELINE_TYPES } from "@/lib/insights/derived/registry";
import { assembleDiscoveryMatrix } from "@/lib/insights/discovery-matrix";
import { resolveModuleMap } from "@/lib/modules/gate";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -480,7 +481,7 @@ export async function buildPeriodNarrativeContext(
where: { id: userId },
select: { timezone: true },
});
const tz = profile?.timezone ?? "Europe/Berlin";
const tz = profile?.timezone ?? DEFAULT_TIMEZONE;
const currentFrom = tzDayKey(
new Date(now.getTime() - periodDays * MS_PER_DAY),
+7 -2
View File
@@ -233,7 +233,12 @@ export async function preparePulseStatusForUser(
// Primary metric: recent / weekly fold from the bounded raw read, the
// monthly / yearly tail comes from the MONTH / YEAR rollup tier (with
// a full-history in-memory fallback on a cold-tier coverage miss).
const pulseGraded = await buildGradedSeriesWithRollups(userId, "PULSE", now);
const pulseGraded = await buildGradedSeriesWithRollups(
userId,
"PULSE",
now,
userTz,
);
const pulseSummary = summarizeSeries(
pulseSeries.daily.map((bucket) => ({ value: bucket.value })),
);
@@ -255,7 +260,7 @@ export async function preparePulseStatusForUser(
value: entry.score,
}));
const moodSeries = applyPayloadBudget(moodPoints, { now, tz: userTz });
const moodGraded = buildGradedSeriesFromPoints(moodPoints, now);
const moodGraded = buildGradedSeriesFromPoints(moodPoints, now, userTz);
const moodSummary = summarizeSeries(
moodSeries.daily.map((bucket) => ({ value: bucket.value })),
);
+14 -9
View File
@@ -24,7 +24,7 @@ import {
import { getRelevantCorrelationsForMetric } from "@/lib/insights/metric-correlation-context";
import {
applyPayloadBudget,
dayOffsetToBerlinDayKey,
dayOffsetToDayKey,
type DailyBucket,
} from "@/lib/insights/bucket-series";
import {
@@ -59,6 +59,7 @@ import {
import { annotate } from "@/lib/logging/context";
import { resolveUserTimezone, userDayKey } from "@/lib/tz/resolver";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { canonicalDailyTimestamp } from "@/lib/measurements/consolidation-tz";
/**
* Cap on the embedded correlation pair arrays. The Pearson coefficient
@@ -70,7 +71,7 @@ const CORRELATION_PAIR_CAP = 30;
/**
* Pair two daily-bucket series on `dayOffset`. The synthesised `date`
* field is anchored at the UTC midnight of the Berlin calendar day —
* `dayOffsetToBerlinDayKey()` is the source of truth so DST boundaries
* `dayOffsetToDayKey()` is the source of truth so DST boundaries
* don't slip the day-key by one. Each pair also carries `dayKey`
* directly so callers can label points without re-formatting.
*/
@@ -86,7 +87,7 @@ function pairDailyBuckets(
.map((entry) => {
const b = mapB.get(entry.dayOffset);
if (b == null) return null;
const dayKey = dayOffsetToBerlinDayKey(now, entry.dayOffset, tz);
const dayKey = dayOffsetToDayKey(now, entry.dayOffset, tz);
const [y, m, d] = dayKey.split("-").map(Number);
return {
a: entry.value,
@@ -370,16 +371,20 @@ export async function prepareWeightStatusForUser(
// on a cold-tier coverage miss). Mood has no rollup tier, so it stays
// an in-memory fold.
const [weightGraded, sysGraded, diaGraded] = await Promise.all([
buildGradedSeriesWithRollups(userId, "WEIGHT", now),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_SYS", now),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_DIA", now),
buildGradedSeriesWithRollups(userId, "WEIGHT", now, userTz),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_SYS", now, userTz),
buildGradedSeriesWithRollups(userId, "BLOOD_PRESSURE_DIA", now, userTz),
]);
const moodGraded = buildGradedSeriesFromPoints(
moodSeries.daily.map((b) => ({
measuredAt: new Date(dayOffsetToBerlinDayKey(now, b.dayOffset, userTz)),
measuredAt: canonicalDailyTimestamp(
dayOffsetToDayKey(now, b.dayOffset, userTz),
userTz,
),
value: b.value,
})),
now,
userTz,
);
const weightVsSystolicPairs = pairDailyBuckets(
@@ -408,7 +413,7 @@ export async function prepareWeightStatusForUser(
// pairDailyBuckets — derive dayOffset from the offsets in sysSeries.
const sysOffsetByDay = new Map(
sysSeries.daily.map((bucket) => {
const dayKey = dayOffsetToBerlinDayKey(now, bucket.dayOffset, userTz);
const dayKey = dayOffsetToDayKey(now, bucket.dayOffset, userTz);
return [dayKey, bucket.dayOffset];
}),
);
@@ -433,7 +438,7 @@ export async function prepareWeightStatusForUser(
const latestWeight = weightSeries.daily[0] ?? null;
const previousWeight = weightSeries.daily[1] ?? null;
const latestWeightDay = latestWeight
? dayOffsetToBerlinDayKey(now, latestWeight.dayOffset, userTz)
? dayOffsetToDayKey(now, latestWeight.dayOffset, userTz)
: null;
const sameDayBp = latestWeightDay
? (pairedSystolicDiastolic.find((entry) => entry.day === latestWeightDay) ??
+12 -7
View File
@@ -36,6 +36,7 @@ import { importAppleHealthEcg } from "@/lib/apple-health/ecg-import";
import { extractExportXml } from "@/lib/import/unzip-export-xml";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { invalidateStatusInsightsForTypes } from "@/lib/insights/status-invalidation";
import { trackBackgroundTask } from "@/lib/logging/background-tasks";
import { jobDone, jobFailed, type JobOutcome } from "@/lib/jobs/job-outcome";
import {
streamParseExportXml,
@@ -47,6 +48,7 @@ import {
ROLLUP_FOLD_WINDOW_MS,
} from "@/lib/rollups/measurement-rollups";
import { withBackgroundEvent } from "@/lib/logging/background";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Queue + cron for the periodic orphan-ImportJob sweep. v1.32.1
@@ -372,7 +374,7 @@ export async function handleAppleHealthImport(
const userTimezone =
userRow?.timezone && userRow.timezone.length > 0
? userRow.timezone
: "Europe/Berlin";
: DEFAULT_TIMEZONE;
// Phase 1: unpacking
await writeProgress(prisma, importJobId, "unpacking", {
@@ -542,12 +544,15 @@ export async function handleAppleHealthImport(
.filter(([, stat]) => stat.inserted + stat.updated > 0)
.map(([type]) => type as MeasurementType);
if (importedTypes.length > 0) {
invalidateStatusInsightsForTypes(userId, importedTypes).catch((err) => {
console.warn(
`[apple-health-import] status-insight invalidate failed for user ${userId}`,
err,
);
});
// Registered so the test suite can await the detached handle.
trackBackgroundTask(
invalidateStatusInsightsForTypes(userId, importedTypes).catch((err) => {
console.warn(
`[apple-health-import] status-insight invalidate failed for user ${userId}`,
err,
);
}),
);
}
// Best-effort cleanup. A failed unlink is not fatal — `/tmp` is
+3 -2
View File
@@ -48,6 +48,7 @@ import { dispatchNotification } from "@/lib/notifications/dispatcher";
import type { EventType } from "@/lib/notifications/types";
import { isCycleReminderClientManaged } from "@/lib/validations/notification-prefs";
import { getEvent } from "@/lib/logging/context";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Local-time hour (0–23) at which the daily cycle reminder fires. 09:00 is
@@ -138,7 +139,7 @@ export function cycleReminderLocalDate(
now: Date,
timezone: string,
): string | null {
const parts = wallClockInTz(now, timezone || "Europe/Berlin");
const parts = wallClockInTz(now, timezone || DEFAULT_TIMEZONE);
if (parts.hour !== CYCLE_REMINDER_LOCAL_HOUR) return null;
return `${parts.year.toString().padStart(4, "0")}-${parts.month
.toString()
@@ -386,7 +387,7 @@ export async function runCycleReminderTick(
continue;
}
const timezone = user.timezone || "Europe/Berlin";
const timezone = user.timezone || DEFAULT_TIMEZONE;
const today = cycleReminderLocalDate(now, timezone);
if (!today) {
summary.skippedOutsideWindow += 1;
+2 -1
View File
@@ -28,6 +28,7 @@ import {
maybeDispatchDailyBriefing,
type DailyBriefingDispatchDeps,
} from "@/lib/daily/daily-briefing-push";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
export const DAILY_BRIEFING_QUEUE = "daily-briefing";
/** Every 15 minutes; the per-user local-hour gate selects the fallback slot. */
@@ -94,7 +95,7 @@ export async function runDailyBriefingTick(
for (const pref of prefs) {
const userId = pref.channel?.userId;
if (!userId) continue;
cohort.set(userId, pref.channel.user?.timezone || "Europe/Berlin");
cohort.set(userId, pref.channel.user?.timezone || DEFAULT_TIMEZONE);
}
for (const [userId, tz] of cohort) {
+2 -1
View File
@@ -32,6 +32,7 @@ import {
DEFAULT_MOOD_REMINDER_HOUR,
resolveMoodReminderHour,
} from "@/lib/validations/notification-prefs";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Default hour of day (in the user's local timezone) at which the mood
@@ -88,7 +89,7 @@ export function evaluateMoodReminderWindow(
return { fire: false, localDate: null, localHour: -1 };
}
const targetHour = user.reminderHour ?? MOOD_REMINDER_LOCAL_HOUR;
const parts = wallClockInTz(now, user.timezone || "Europe/Berlin");
const parts = wallClockInTz(now, user.timezone || DEFAULT_TIMEZONE);
const inWindow = parts.hour === targetHour;
const isoDate = `${parts.year.toString().padStart(4, "0")}-${parts.month
.toString()
+2 -1
View File
@@ -42,6 +42,7 @@ import {
enqueueNarrativeWarm,
type PeriodNarrativePayload,
} from "@/lib/jobs/period-narrative-shared";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
export { PERIOD_NARRATIVE_QUEUE, PERIOD_NARRATIVE_CRON, enqueueNarrativeWarm };
export type { PeriodNarrativePayload };
@@ -74,7 +75,7 @@ export interface NarrativeWarmRunResult {
*/
export function periodsForDay(
now: Date,
tz = "Europe/Berlin",
tz = DEFAULT_TIMEZONE,
): NarrativePeriod[] {
// Resolve the local weekday + day-of-month in the maintenance-window tz so
// the boundary matches the user-facing calendar, not UTC.
@@ -44,6 +44,7 @@ import {
LIVE_ERA_REVISION_ARGS,
liveEraStart as liveEraStartOf,
} from "@/lib/medications/scheduling/live-era";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
export interface ReminderCheckPayload {
triggeredAt: string;
@@ -198,7 +199,7 @@ export async function handleReminderCheck(
let notificationsFailed = 0;
for (const med of medications) {
const userTz = med.user.timezone || "Europe/Berlin";
const userTz = med.user.timezone || DEFAULT_TIMEZONE;
const { start: todayStart, end: todayEnd } = getUserTodayBounds(
now,
userTz,
+2 -1
View File
@@ -28,6 +28,7 @@ import {
type JobHandler,
type JobWithMetadataHandler,
} from "@/lib/jobs/run-job";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Cron schedule tuple: `[queueName, cronExpression, sendOptions?]`. The
@@ -223,7 +224,7 @@ export async function createAndSchedule(
cron,
{},
{
tz: "Europe/Berlin",
tz: DEFAULT_TIMEZONE,
...(sendOptions ?? {}),
},
);
+1 -1
View File
@@ -1518,7 +1518,7 @@ export const MCP_TOOLS: McpToolDefinition[] = [
return { present: false };
}
const userTz = user?.timezone || "Europe/Berlin";
const userTz = user?.timezone || DEFAULT_TIMEZONE;
// Same feeder reads + horizon the medications list route / dashboard
// builder use, so the open-overdue detection matches the in-app cards.
+2 -1
View File
@@ -40,7 +40,8 @@ import { afterMeasurementMutation } from "@/lib/rollups/after-measurement-mutati
import { recomputeMoodBucketsForEntry } from "@/lib/rollups/mood-rollups";
import { MOOD_ENUM_BY_SCORE } from "@/lib/mood/labels";
import { getScoreForMood } from "@/lib/validations/mood";
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { deriveA1 } from "@/lib/mood/level-a";
import {
classifyExternalId,
+1 -1
View File
@@ -40,13 +40,13 @@ import {
dayKeyForUserTz,
type PerSampleRow,
} from "./consolidation-tz";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
// Re-export the shared grace constant so the established
// `consolidation-base` import surface stays unchanged for callers.
export { CONSOLIDATION_GRACE_CUTOFF_HOURS };
/** Fallback timezone for users with no `User.timezone` set. */
const DEFAULT_TIMEZONE = "Europe/Berlin";
/**
* Options shared by every drain. Each drain re-exports its own alias of
@@ -67,6 +67,7 @@ import { meanBucketValue } from "./consolidate-daily-mean";
import { recomputeBucketsForMeasurement } from "@/lib/rollups/measurement-rollups";
import { percentile } from "@/lib/insights/strain-score";
import type { PerSampleRow } from "./drain-per-sample-cumulative";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* iOS#34 / #69 — heart-rate (PULSE) is the densest spot signal after
@@ -533,7 +534,7 @@ export async function runDenseIntradayRetention(
// The base walks users serially; recordBucket needs the current user's tz
// for the dry-run hourly fan-out estimate (writeDay never runs on dry-run).
let currentTz = "Europe/Berlin";
let currentTz = DEFAULT_TIMEZONE;
const walk = await runConsolidation<MeasurementType>({
prismaClient,
+2 -1
View File
@@ -11,7 +11,8 @@
* are fixing for non-Berlin users.
*/
import { describe, expect, it } from "vitest";
import { moodDateKey, effectiveMoodTz, DEFAULT_TIMEZONE } from "../date-key";
import { moodDateKey, effectiveMoodTz } from "../date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
describe("moodDateKey", () => {
it("formats a UTC instant as a Europe/Berlin YYYY-MM-DD by default", () => {
+2 -1
View File
@@ -18,7 +18,8 @@ import { prisma as defaultPrisma } from "@/lib/db";
import { MOOD_ENUM_BY_SCORE } from "@/lib/mood/labels";
import { getScoreForMood } from "@/lib/validations/mood";
import { deriveA1 } from "@/lib/mood/level-a";
import { moodDateKey, DEFAULT_TIMEZONE } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { encryptNote } from "@/lib/crypto/note-cipher";
import { invalidateUserMood } from "@/lib/cache/invalidate";
import { recomputeMoodBucketsForEntry } from "@/lib/rollups/mood-rollups";
+1 -3
View File
@@ -28,9 +28,7 @@
* legacy date string (`effectiveMoodTz`).
*/
import { userDayKey } from "@/lib/tz/format";
export const DEFAULT_TIMEZONE = "Europe/Berlin";
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Build the `YYYY-MM-DD` day-key for a mood entry given the user's
+2 -1
View File
@@ -48,7 +48,8 @@ import { prisma } from "@/lib/db";
import { isModuleEnabled } from "@/lib/modules/gate";
import { moduleForMeasurementType } from "@/lib/modules/measurement-scope";
import type { ModuleKey } from "@/lib/modules/registry";
import { DEFAULT_TIMEZONE, moodDateKey } from "@/lib/mood/date-key";
import { moodDateKey } from "@/lib/mood/date-key";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import {
reconstructSleepNights,
type SleepStageRow,
+3 -2
View File
@@ -60,6 +60,7 @@ import {
stdResponses,
updatedAtTokenField,
} from "./shared";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
// ── Request schemas — annotated for spec emission ────────────────────
//
@@ -458,7 +459,7 @@ const moodEntryDto = z
date: z
.string()
.describe(
"YYYY-MM-DD, anchored to the row's `tz` (legacy rows with `tz: null` read as Europe/Berlin).",
`YYYY-MM-DD, anchored to the row's \`tz\` (legacy rows with \`tz: null\` read as ${DEFAULT_TIMEZONE}).`,
),
mood: moodLevelEnum,
score: z
@@ -501,7 +502,7 @@ const moodEntryDto = z
.string()
.nullable()
.describe(
"IANA zone the `date` label is anchored to. Null on legacy rows (read as Europe/Berlin).",
`IANA zone the \`date\` label is anchored to. Null on legacy rows (read as ${DEFAULT_TIMEZONE}).`,
),
syncedAt: z.iso.datetime({ offset: true }),
createdAt: z.iso.datetime({ offset: true }),
@@ -61,6 +61,7 @@ import {
type MeasurementType,
type PrismaClient,
} from "@/generated/prisma/client";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/**
* Minimum sample count per metric before the worker writes its first
@@ -245,7 +246,7 @@ export async function detectPersonalRecordsForUser(
const tz =
userRow?.timezone && userRow.timezone.length > 0
? userRow.timezone
: "Europe/Berlin";
: DEFAULT_TIMEZONE;
const priorityJson = userRow?.sourcePriorityJson ?? null;
// v1.34 — resolve the weight goal once per run: the user's own target band
+2 -2
View File
@@ -11,7 +11,7 @@
* 2. the legacy helpers in `src/lib/format.ts` (plain functions, no React
* context) render the same zone as hook-based call sites.
*
* Fallback chain: valid mirrored profile zone → `DISPLAY_TIMEZONE`
* Fallback chain: valid mirrored profile zone → `DEFAULT_TIMEZONE`
* (Europe/Berlin) inside `makeFormatters`. Deliberately NO browser-timezone
* rung — every server-rendered artifact (doctor-report PDF, exports,
* briefing) resolves profile → Berlin, and a browser rung would let the same
@@ -36,7 +36,7 @@ const CHANGE_EVENT = "healthlog:timezone-change";
/**
* Best-effort read of the mirrored zone. "" on SSR / no mirror / invalid
* stored value — callers treat "" as "fall back to `DISPLAY_TIMEZONE`"
* stored value — callers treat "" as "fall back to `DEFAULT_TIMEZONE`"
* (which `makeFormatters` does on its own for an empty `userTz`).
*/
export function readStoredTimezone(): string {
+1 -1
View File
@@ -178,7 +178,7 @@ export type FormatInUserTzShape =
* - "datetime" — `2026-05-11 11:05` (24h, locale-independent for
* audit/PDF tables). Equivalent to the `formatters.dateTime`
* helper but with a per-call timezone instead of the global
* `DISPLAY_TIMEZONE`.
* `DEFAULT_TIMEZONE`.
*
* - "date" — `2026-05-11` (ISO date in the user's zone). Used as a
* stable day-bucket key for per-user aggregation.
+1 -49
View File
@@ -2,7 +2,7 @@
* v1.4.25 W7 — per-user timezone resolver (server-only).
*
* HealthLog historically pinned every display surface to the
* `DISPLAY_TIMEZONE` constant ("Europe/Berlin"). The per-user
* `DEFAULT_TIMEZONE` constant ("Europe/Berlin"). The per-user
* timezone feature (Option B in `.planning/feature-user-timezone.md`)
* threads the user's stored zone through every surface that renders
* a date or buckets by day — exports, charts, AI Coach snapshot,
@@ -51,54 +51,6 @@ export {
hourInTz,
} from "./format";
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
/**
* Format a Date as `YYYY-MM-DD` in `Europe/Berlin`. The seven Insight
* status helpers (`bmi`, `blood-pressure`, `weight`, `pulse`, `mood`,
* `medication-compliance`, `general`) all key their per-day cache on
* this — the maintainer's primary tenant runs in Berlin and the cache
* action row reads identically across helpers when the formatter lives
* here.
*
* For per-user surfaces, prefer `userDayKey(date, tz)` from `./format`.
* This helper exists for the cache-key path where the day-bucket is
* intentionally Berlin-anchored regardless of the requesting user's
* stored zone.
*/
export function toBerlinDayKey(date: Date): string {
const { year, month, day } = toBerlinYmd(date);
return `${year}-${month}-${day}`;
}
/**
* Same formatter, but returns the numeric `{year, month, day}` parts
* instead of the reassembled string. Used by `bucket-series.ts` for
* `Date.UTC(year, month - 1, day)` arithmetic where parsing the string
* back would be wasted work.
*/
export function toBerlinYmd(date: Date): {
year: string;
month: string;
day: string;
} {
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
const year = parts.find((part) => part.type === "year")?.value;
const month = parts.find((part) => part.type === "month")?.value;
const day = parts.find((part) => part.type === "day")?.value;
if (!year || !month || !day) {
throw new Error("Could not derive Berlin day key");
}
return { year, month, day };
}
const TTL_MS = 60_000;
interface CacheEntry {
+1 -1
View File
@@ -17,9 +17,9 @@ import {
deriveSeries,
type SeriesInputRecord,
} from "@/lib/vaccinations/series";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
/** Matches the visits service: the fallback when an account never set one. */
const DEFAULT_TIMEZONE = "Europe/Berlin";
/** The relations every vaccination response resolves. */
export const VACCINATION_INCLUDE = {