mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-18 08:02:12 +00:00
Merge remote-tracking branch 'origin/main' into fix/v1397-meta
This commit is contained in:
commit
383323b542
128 files changed
+1676
-256
No files matched your search
@@ -278,3 +278,57 @@ describe("buildGlp1SnapshotBlock side-effect tags across locales", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Injection days are the user's calendar days. The snapshot used to cut
|
||||
* them on UTC days and compare `getUTCDay()` with the schedule's local
|
||||
* weekday, so an evening injection west of UTC was reported on the next
|
||||
* day and the projection counted from the wrong day.
|
||||
*/
|
||||
describe("buildGlp1SnapshotBlock injection days in the user's zone", () => {
|
||||
it("dates a Friday-evening injection in Los Angeles on Friday", async () => {
|
||||
prismaMock.medication.findMany.mockResolvedValue([
|
||||
fakeMedication({
|
||||
schedules: [
|
||||
{ daysOfWeek: "5", windowStart: "19:00", windowEnd: "21:00" },
|
||||
],
|
||||
// Friday 2026-09-25, 20:00 in Los Angeles — Saturday in UTC.
|
||||
intakeEvents: [
|
||||
{
|
||||
takenAt: new Date("2026-09-26T03:00:00.000Z"),
|
||||
injectionSite: null,
|
||||
},
|
||||
],
|
||||
}),
|
||||
]);
|
||||
// Monday 2026-09-28, 11:00 in Los Angeles.
|
||||
const now = new Date("2026-09-28T18:00:00.000Z");
|
||||
const out = await buildGlp1SnapshotBlock(
|
||||
"user-1",
|
||||
now,
|
||||
"America/Los_Angeles",
|
||||
);
|
||||
const med = out?.medications[0];
|
||||
expect(med?.lastInjection?.date).toBe("2026-09-25");
|
||||
expect(med?.nextInjection).toEqual({ date: "2026-10-02", daysAway: 4 });
|
||||
});
|
||||
|
||||
it("names tomorrow from the local day east of UTC", async () => {
|
||||
prismaMock.medication.findMany.mockResolvedValue([
|
||||
fakeMedication({
|
||||
schedules: [{ daysOfWeek: null, windowStart: null, windowEnd: null }],
|
||||
}),
|
||||
]);
|
||||
// 2026-09-28 12:00 UTC is already 2026-09-29 02:00 on Kiritimati.
|
||||
const now = new Date("2026-09-28T12:00:00.000Z");
|
||||
const out = await buildGlp1SnapshotBlock(
|
||||
"user-1",
|
||||
now,
|
||||
"Pacific/Kiritimati",
|
||||
);
|
||||
expect(out?.medications[0].nextInjection).toEqual({
|
||||
date: "2026-09-30",
|
||||
daysAway: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -235,6 +235,7 @@ export async function readDailySpend(
|
||||
* the local meter to the same boundary keeps reasoning trivial.
|
||||
*/
|
||||
export function buildDateKey(at: Date = new Date()): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the spend meter follows the provider's UTC billing day (see the doc comment)
|
||||
return at.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import { addDays } from "@/lib/cycle/day-math";
|
||||
import { readSourceDayAggregates } from "@/lib/measurements/day-aggregates";
|
||||
import { moodDateKey } from "@/lib/mood/date-key";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
import { startOfLocalDayKey } from "@/lib/tz/local-day";
|
||||
|
||||
/** Trailing window the phase contrast walks (days). Mirrors the read route. */
|
||||
const WINDOW_DAYS = 365;
|
||||
@@ -191,7 +192,7 @@ export async function buildCycleSnapshotBlock(
|
||||
deletedAt: null,
|
||||
type: "WRIST_TEMPERATURE",
|
||||
measuredAt: {
|
||||
gte: new Date(Date.parse(`${addDays(today, -90)}T00:00:00Z`)),
|
||||
gte: startOfLocalDayKey(addDays(today, -90), tz),
|
||||
},
|
||||
},
|
||||
orderBy: { measuredAt: "asc" },
|
||||
@@ -206,7 +207,7 @@ export async function buildCycleSnapshotBlock(
|
||||
readSourceDayAggregates({
|
||||
userId,
|
||||
types: PHASE_CROSSTAB_METRIC_TYPES,
|
||||
since: new Date(Date.parse(`${from}T00:00:00Z`)),
|
||||
since: startOfLocalDayKey(from, tz),
|
||||
timeZone: tz,
|
||||
}),
|
||||
prisma.user.findUnique({
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
*/
|
||||
import type { Locale } from "@/lib/i18n/config";
|
||||
import { resolveUserTimezone } from "@/lib/tz/resolver";
|
||||
import { userDayKey } from "@/lib/tz/format";
|
||||
import { userDayKey, shiftDateKey } from "@/lib/tz/format";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import type {
|
||||
CoachFollowUp,
|
||||
@@ -93,9 +93,7 @@ export function followUpChipsEnabled(prefs: CoachPrefs): boolean {
|
||||
|
||||
/** `YYYY-MM-DD` minus `days`, as a day key. */
|
||||
function dayKeyMinus(dayKey: string, days: number): string {
|
||||
const at = new Date(`${dayKey}T00:00:00Z`);
|
||||
at.setUTCDate(at.getUTCDate() - days);
|
||||
return at.toISOString().slice(0, 10);
|
||||
return shiftDateKey(dayKey, -days);
|
||||
}
|
||||
|
||||
/** True when the record's first reading lies before `dayKey`. */
|
||||
|
||||
@@ -25,6 +25,13 @@ import { matchGlp1SideEffectTags } from "@/lib/medications/glp1-side-effect-tag-
|
||||
import type { Glp1SideEffectTag } from "@/lib/medications/glp1-side-effect-tags";
|
||||
import { isRecordOnly } from "@/lib/medications/intake-tracking";
|
||||
import { floorWhole } from "@/lib/medications/units-per-dose";
|
||||
import {
|
||||
DEFAULT_TIMEZONE,
|
||||
daysBetweenDateKeys,
|
||||
shiftDateKey,
|
||||
userDayKey,
|
||||
weekdayOfDateKey,
|
||||
} from "@/lib/tz/format";
|
||||
|
||||
/**
|
||||
* Recommended generic name for the canonical GLP-1 drug brand. The Coach
|
||||
@@ -159,13 +166,15 @@ function weeksBetween(from: Date, to: Date): number {
|
||||
return Math.max(0, Math.round(ms / (7 * 24 * 60 * 60 * 1000)));
|
||||
}
|
||||
|
||||
function isoDate(d: Date): string {
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Predict next injection from cadence + last intake.
|
||||
*
|
||||
* Works on the user's calendar days throughout: the last injection's day,
|
||||
* today and the schedule's `daysOfWeek` are all local, so the projection
|
||||
* walks local day keys. Walking UTC days and testing `getUTCDay()` against
|
||||
* a local weekday named the wrong day for anyone whose injection time sits
|
||||
* on the other side of UTC midnight.
|
||||
*
|
||||
* - Weekly cadence with a single weekday: project to the next matching
|
||||
* weekday after the last intake (or after today if no last intake).
|
||||
* - Daily / unset cadence: next is tomorrow (the existing reminder
|
||||
@@ -176,26 +185,20 @@ function predictNextInjection(
|
||||
schedule: ScheduleEntry | null,
|
||||
lastInjection: LastInjection | null,
|
||||
now: Date,
|
||||
tz: string,
|
||||
): NextInjection | null {
|
||||
if (!schedule) return null;
|
||||
const todayKey = userDayKey(now, tz);
|
||||
if (schedule.cadence === "weekly" && schedule.daysOfWeek.length > 0) {
|
||||
const targetDow = schedule.daysOfWeek[0];
|
||||
const anchor = lastInjection
|
||||
? new Date(lastInjection.date + "T00:00:00Z")
|
||||
: now;
|
||||
// Project forward from the anchor (lastInjection if known, otherwise
|
||||
// today) until we land on the target weekday.
|
||||
const cursor = new Date(anchor.getTime());
|
||||
const anchorKey = lastInjection ? lastInjection.date : todayKey;
|
||||
for (let i = 1; i <= 14; i += 1) {
|
||||
cursor.setUTCDate(cursor.getUTCDate() + 1);
|
||||
if (cursor.getUTCDay() === targetDow) {
|
||||
const daysAway = Math.max(
|
||||
0,
|
||||
Math.round(
|
||||
(cursor.getTime() - now.getTime()) / (24 * 60 * 60 * 1000),
|
||||
),
|
||||
);
|
||||
return { date: isoDate(cursor), daysAway };
|
||||
const key = shiftDateKey(anchorKey, i);
|
||||
if (weekdayOfDateKey(key) === targetDow) {
|
||||
const daysAway = Math.max(0, daysBetweenDateKeys(todayKey, key));
|
||||
return { date: key, daysAway };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -203,9 +206,7 @@ function predictNextInjection(
|
||||
// depending on what's already been logged. Surfacing "tomorrow" keeps
|
||||
// the Coach from making confident "today is your injection day"
|
||||
// claims on partial data.
|
||||
const tomorrow = new Date(now.getTime());
|
||||
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
|
||||
return { date: isoDate(tomorrow), daysAway: 1 };
|
||||
return { date: shiftDateKey(todayKey, 1), daysAway: 1 };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,6 +217,7 @@ function predictNextInjection(
|
||||
export async function buildGlp1SnapshotBlock(
|
||||
userId: string,
|
||||
now: Date = new Date(),
|
||||
tz: string = DEFAULT_TIMEZONE,
|
||||
): Promise<Glp1SnapshotBlock | null> {
|
||||
// Test environments mock parts of prisma (only `measurement` +
|
||||
// `moodEntry`) and leave `medication` undefined. Treat the absence
|
||||
@@ -295,7 +297,7 @@ export async function buildGlp1SnapshotBlock(
|
||||
return {
|
||||
value: dc.doseValue,
|
||||
unit: sanitizeForPrompt(dc.doseUnit, 20),
|
||||
effectiveFrom: isoDate(dc.effectiveFrom),
|
||||
effectiveFrom: userDayKey(dc.effectiveFrom, tz),
|
||||
note:
|
||||
decryptedNote === null ? null : sanitizeForPrompt(decryptedNote, 200),
|
||||
};
|
||||
@@ -305,7 +307,7 @@ export async function buildGlp1SnapshotBlock(
|
||||
? {
|
||||
value: latestChange.doseValue,
|
||||
unit: sanitizeForPrompt(latestChange.doseUnit, 20),
|
||||
since: isoDate(latestChange.effectiveFrom),
|
||||
since: userDayKey(latestChange.effectiveFrom, tz),
|
||||
weeksOnDose: weeksBetween(latestChange.effectiveFrom, now),
|
||||
}
|
||||
: null;
|
||||
@@ -334,7 +336,7 @@ export async function buildGlp1SnapshotBlock(
|
||||
const lastInjection: LastInjection | null =
|
||||
last && last.takenAt
|
||||
? {
|
||||
date: isoDate(last.takenAt),
|
||||
date: userDayKey(last.takenAt, tz),
|
||||
site: last.injectionSite ?? null,
|
||||
weeksAgo: weeksBetween(last.takenAt, now),
|
||||
}
|
||||
@@ -344,7 +346,7 @@ export async function buildGlp1SnapshotBlock(
|
||||
// information but no injection is predicted as due.
|
||||
const nextInjection = isRecordOnly(med)
|
||||
? null
|
||||
: predictNextInjection(schedule, lastInjection, now);
|
||||
: predictNextInjection(schedule, lastInjection, now, tz);
|
||||
|
||||
// Inventory math over the per-item entities (v1.16.10 — the same
|
||||
// rows the Bestand tab and the consumption hook move).
|
||||
|
||||
@@ -33,7 +33,7 @@ import { prisma } from "@/lib/db";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import type { Locale } from "@/lib/i18n/config";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
|
||||
import { shiftDateKey, userDayKey, weekdayOfDateKey } from "@/lib/tz/format";
|
||||
import { startOfLocalDayKey } from "@/lib/tz/local-day";
|
||||
import {
|
||||
readDailySeries,
|
||||
@@ -66,6 +66,7 @@ import type {
|
||||
|
||||
import { aggregationKind } from "./chart-spec";
|
||||
import { RESULT_TABLE_MAX_ROWS } from "./project";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* Sources the table tool leaves to their own tools: glucose needs its
|
||||
@@ -167,16 +168,14 @@ export function resolveTableRange(args: {
|
||||
|
||||
// ── Period keys ─────────────────────────────────────────────────────────
|
||||
|
||||
/** `YYYY-MM-DD` of a UTC-midnight bucket timestamp. */
|
||||
/** `YYYY-MM-DD` of a UTC-midnight bucket timestamp (a day label). */
|
||||
function dayKeyOfUtc(ms: number): string {
|
||||
return new Date(ms).toISOString().slice(0, 10);
|
||||
return dateOnlyKey(new Date(ms));
|
||||
}
|
||||
|
||||
/** Monday (`YYYY-MM-DD`) of the ISO week `dayKey` falls in. */
|
||||
function weekKeyOf(dayKey: string): string {
|
||||
const ms = Date.parse(`${dayKey}T00:00:00Z`);
|
||||
const dow = (new Date(ms).getUTCDay() + 6) % 7;
|
||||
return dayKeyOfUtc(ms - dow * 86_400_000);
|
||||
return shiftDateKey(dayKey, -((weekdayOfDateKey(dayKey) + 6) % 7));
|
||||
}
|
||||
|
||||
function monthKeyOf(dayKey: string): string {
|
||||
@@ -416,8 +415,12 @@ async function readMeasurementDays(args: {
|
||||
return { series: ordered, counts, suffixes };
|
||||
}
|
||||
|
||||
/** `YYYY-MM-DD` of an instant in UTC. */
|
||||
/**
|
||||
* `YYYY-MM-DD` of an instant in UTC. Only for the all-time month read: the
|
||||
* MONTH rollup tier buckets UTC months, so its range edges are UTC days.
|
||||
*/
|
||||
function utcDayKey(date: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the MONTH rollup tier buckets UTC months, so this read keys its edges on UTC days
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
import type { Locale } from "@/lib/i18n/config";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
|
||||
import { shiftDateKey, userDayKey, weekdayOfDateKey } from "@/lib/tz/format";
|
||||
import type {
|
||||
CoachResultCell,
|
||||
CoachResultTable,
|
||||
@@ -189,17 +189,13 @@ function mondayOfIsoWeek(weekIso: string): string | null {
|
||||
const year = Number(match[1]);
|
||||
const week = Number(match[2]);
|
||||
// Week 1 holds January 4th; its Monday is the ISO year's first Monday.
|
||||
const jan4 = Date.UTC(year, 0, 4);
|
||||
const jan4Dow = (new Date(jan4).getUTCDay() + 6) % 7;
|
||||
const monday = jan4 - jan4Dow * 86_400_000 + (week - 1) * 7 * 86_400_000;
|
||||
return new Date(monday).toISOString().slice(0, 10);
|
||||
const jan4 = `${String(year).padStart(4, "0")}-01-04`;
|
||||
return shiftDateKey(mondayOfDay(jan4), (week - 1) * 7);
|
||||
}
|
||||
|
||||
/** Monday (`YYYY-MM-DD`) of the ISO week a day key falls in. */
|
||||
function mondayOfDay(dayKey: string): string {
|
||||
const ms = Date.parse(`${dayKey}T00:00:00Z`);
|
||||
const dow = (new Date(ms).getUTCDay() + 6) % 7;
|
||||
return shiftDateKey(new Date(ms).toISOString().slice(0, 10), -dow);
|
||||
return shiftDateKey(dayKey, -((weekdayOfDateKey(dayKey) + 6) % 7));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -59,8 +59,8 @@ export function buildCoreMetricsBlocks(
|
||||
);
|
||||
const olderSys = sysRows.filter((row) => row.measuredAt < ctx.recentCutoff);
|
||||
const olderDia = diaRows.filter((row) => row.measuredAt < ctx.recentCutoff);
|
||||
const sysBand = bpBandFromRows(sysRows, "BLOOD_PRESSURE_SYS");
|
||||
const diaBand = bpBandFromRows(diaRows, "BLOOD_PRESSURE_DIA");
|
||||
const sysBand = bpBandFromRows(sysRows, "BLOOD_PRESSURE_SYS", ctx.userTz);
|
||||
const diaBand = bpBandFromRows(diaRows, "BLOOD_PRESSURE_DIA", ctx.userTz);
|
||||
const usualRange =
|
||||
sysBand || diaBand
|
||||
? {
|
||||
|
||||
@@ -297,10 +297,12 @@ export function buildDailyBpRows(
|
||||
export function bpBandFromRows(
|
||||
rows: ReadonlyArray<{ measuredAt: Date; value: number }>,
|
||||
type: "BLOOD_PRESSURE_SYS" | "BLOOD_PRESSURE_DIA",
|
||||
tz: string,
|
||||
): { low: number; high: number } | null {
|
||||
const byDay = new Map<string, { sum: number; count: number }>();
|
||||
for (const r of rows) {
|
||||
const day = r.measuredAt.toISOString().slice(0, 10);
|
||||
// The user's day, like every other day mean in the snapshot.
|
||||
const day = tzDayKey(r.measuredAt, tz);
|
||||
const acc = byDay.get(day) ?? { sum: 0, count: 0 };
|
||||
acc.sum += r.value;
|
||||
acc.count += 1;
|
||||
|
||||
@@ -744,7 +744,7 @@ async function buildCoachSnapshotImpl(
|
||||
: null;
|
||||
const glp1BlockPromise = excludesMedications
|
||||
? null
|
||||
: buildGlp1SnapshotBlock(userId, now);
|
||||
: buildGlp1SnapshotBlock(userId, now, userTz);
|
||||
const derivedBlockPromise = derivedActive
|
||||
? buildDerivedSnapshotBlock(userId, derivedProfile, now, userTz)
|
||||
: null;
|
||||
|
||||
@@ -468,6 +468,7 @@ function bucketWindow(
|
||||
* safe for every code path that reaches this helper.
|
||||
*/
|
||||
function bucketDayKey(d: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: rollup bucketStart key; non-near-UTC users are routed to the live path (see the doc comment)
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ import { wallClockInTz } from "@/lib/tz/wall-clock";
|
||||
import { defaultLocale, type Locale } from "@/lib/i18n/config";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { TRACKED_INTAKE_EVENT_WHERE } from "@/lib/medications/intake-tracking";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* v1.4.37 W2 — cold-path correlation window. Trim from 30 to 28 days
|
||||
@@ -413,7 +414,7 @@ async function fetchSeriesChunked(
|
||||
}
|
||||
|
||||
function dateFromDayKey(key: string): Date {
|
||||
return new Date(`${key}T00:00:00.000Z`);
|
||||
return dayKeyAsUtcMidnight(key);
|
||||
}
|
||||
|
||||
function isoWeekdayInTz(d: Date, timeZone: string): number {
|
||||
|
||||
@@ -183,6 +183,7 @@ export async function loadIntradayPulse(
|
||||
dateKey: string,
|
||||
): Promise<IntradayPulseResult> {
|
||||
const localOf = makeLocalResolver(timezone);
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: anchor of a superset read window; rows are cut to the exact local day afterwards
|
||||
const anchorMs = new Date(`${dateKey}T00:00:00.000Z`).getTime();
|
||||
const start = new Date(anchorMs - WINDOW_LEAD_MS);
|
||||
const end = new Date(anchorMs + WINDOW_TRAIL_MS);
|
||||
|
||||
@@ -60,6 +60,7 @@ export const MAX_PROGNOSIS_ROWS = 5000;
|
||||
|
||||
/** `YYYY-MM-DD`, this many days before the given instant, in UTC terms. */
|
||||
export function dayKeyBefore(now: Date, days: number): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: far edge of the fit window on stored day keys; a day either way does not change the fit
|
||||
return new Date(now.getTime() - days * 86_400_000).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ import {
|
||||
type RangeDeltaResult,
|
||||
type WindowAggregate,
|
||||
} from "@/lib/analytics/range-shared";
|
||||
import { dayKeyAsUtcMidnight, dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
// The range constants + result shapes live in the client-safe
|
||||
// `range-shared` module so the insights client bundle never pulls the
|
||||
@@ -156,6 +157,7 @@ function splitPerPeriod(
|
||||
export function dailyTotalsEndKey(now: number, timezone: string): string {
|
||||
const localYesterday = shiftDateKey(userDayKey(new Date(now), timezone), -1);
|
||||
const utcYesterday = shiftDateKey(
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the DAY rollups are UTC buckets, so the earlier of the local and the UTC yesterday wins (see the doc comment)
|
||||
new Date(now).toISOString().slice(0, 10),
|
||||
-1,
|
||||
);
|
||||
@@ -193,13 +195,11 @@ async function readDailyTotals(
|
||||
windowDays: number,
|
||||
endKey: string,
|
||||
): Promise<Array<{ day: string; value: number }>> {
|
||||
const from = new Date(
|
||||
`${shiftDateKey(endKey, -(2 * windowDays - 1))}T00:00:00.000Z`,
|
||||
);
|
||||
const to = new Date(`${shiftDateKey(endKey, 1)}T00:00:00.000Z`);
|
||||
const from = dayKeyAsUtcMidnight(shiftDateKey(endKey, -(2 * windowDays - 1)));
|
||||
const to = dayKeyAsUtcMidnight(shiftDateKey(endKey, 1));
|
||||
const rows = await readRollupBuckets(userId, type, "DAY", from, to);
|
||||
return rows.map((r) => ({
|
||||
day: r.bucketStart.toISOString().slice(0, 10),
|
||||
day: dateOnlyKey(r.bucketStart),
|
||||
value: r.mean * r.count,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export const LIPIDS_WINDOW_DAYS = 365;
|
||||
export const LIPIDS_MIN_PANELS = 1;
|
||||
|
||||
function panelKey(row: LipidReading): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: grouping key only, never shown; the readings of one panel share one takenAt, so any consistent day partition groups them alike
|
||||
return `${row.at.toISOString().slice(0, 10)}|${row.panel ?? ""}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
type ReportSelection,
|
||||
} from "@/lib/report-selection/selection";
|
||||
import type { ShareContext } from "@/lib/clinician-share/resolve-share-token";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* v1.28 — metadata for one document on the share's frozen set. NEVER carries
|
||||
@@ -207,7 +208,7 @@ async function loadShareDocuments(
|
||||
title: document.title,
|
||||
kind: document.kind,
|
||||
documentDate: document.documentDate
|
||||
? document.documentDate.toISOString().slice(0, 10)
|
||||
? dateOnlyKey(document.documentDate)
|
||||
: null,
|
||||
byteSize: document.byteSize,
|
||||
mimeType: document.mimeType,
|
||||
|
||||
@@ -27,6 +27,7 @@ import { addDays } from "@/lib/cycle/day-math";
|
||||
import { BBT_WINDOW } from "@/lib/cycle/types";
|
||||
import { moodDateKey } from "@/lib/mood/date-key";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
import { startOfLocalDayKey } from "@/lib/tz/local-day";
|
||||
|
||||
/** Day-log lookback: the calendar's default past span or the symptothermal
|
||||
* window, whichever reaches further back. */
|
||||
@@ -97,10 +98,9 @@ export async function refreshPredictionCacheForUser(
|
||||
deletedAt: null,
|
||||
type: "WRIST_TEMPERATURE",
|
||||
measuredAt: {
|
||||
gte: new Date(
|
||||
Date.parse(
|
||||
`${addDays(today, -TEMPERATURE_LOOKBACK_DAYS)}T00:00:00Z`,
|
||||
),
|
||||
gte: startOfLocalDayKey(
|
||||
addDays(today, -TEMPERATURE_LOOKBACK_DAYS),
|
||||
tz,
|
||||
),
|
||||
},
|
||||
},
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import type { ServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { MIN_IN_RUN, type StreakResult } from "@/lib/insights/streak-detector";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
/** Closed set of durable-state kinds. Grows by PR, never with a counter field. */
|
||||
export const MILESTONE_KINDS = [
|
||||
@@ -101,7 +102,7 @@ function dayKeyToSerial(key: string): number {
|
||||
}
|
||||
|
||||
function serialToDayKey(serial: number): string {
|
||||
return new Date(serial * 86_400_000).toISOString().slice(0, 10);
|
||||
return shiftDateKey("1970-01-01", serial);
|
||||
}
|
||||
|
||||
/** Shift a UTC-ISO day key by a whole number of days. */
|
||||
|
||||
@@ -120,6 +120,7 @@ import {
|
||||
toProfileSex,
|
||||
type ProfileSex,
|
||||
} from "@/lib/profile/sex";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
/** Briefing freshness window — mirrors the 24 h TTL on the advisor cache. */
|
||||
const BRIEFING_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
@@ -602,6 +603,7 @@ async function buildNutrientWaterBlock(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
): Promise<{ summary: DataSummary; lastSeenAt: string } | null> {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: 30-day lower bound on stored water day keys; a day either way at the far edge does not change the tile
|
||||
const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
@@ -617,7 +619,7 @@ async function buildNutrientWaterBlock(
|
||||
}
|
||||
const points: DataPoint[] = [...sumByDay.entries()]
|
||||
.map(([day, amount]) => ({
|
||||
date: new Date(`${day}T00:00:00.000Z`),
|
||||
date: dayKeyAsUtcMidnight(day),
|
||||
value: amount,
|
||||
}))
|
||||
.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||
|
||||
@@ -73,6 +73,7 @@ import {
|
||||
loadSurgicalHistory,
|
||||
loadLabResults,
|
||||
} from "./clinical-records";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
const DENSE_REPORT_RAW_WINDOW_DAYS = 90;
|
||||
|
||||
@@ -179,8 +180,8 @@ export async function collectDoctorReportData(
|
||||
// they compare against the window's first and last day in the report zone,
|
||||
// not its instants: west of UTC the window starts hours after UTC midnight,
|
||||
// and a course that ended on the first day read as over before it began.
|
||||
const firstDay = new Date(`${userDayKey(start, reportTz)}T00:00:00.000Z`);
|
||||
const lastDay = new Date(`${userDayKey(end, reportTz)}T00:00:00.000Z`);
|
||||
const firstDay = dayKeyAsUtcMidnight(userDayKey(start, reportTz));
|
||||
const lastDay = dayKeyAsUtcMidnight(userDayKey(end, reportTz));
|
||||
|
||||
const aggregateDenseTypes = days > DENSE_REPORT_RAW_WINDOW_DAYS;
|
||||
const includedDenseStatTypes = DENSE_STAT_TYPES.filter(
|
||||
@@ -607,7 +608,7 @@ export async function collectDoctorReportData(
|
||||
emergency,
|
||||
] = await Promise.all([
|
||||
gate.admits("CYCLE")
|
||||
? buildCycleExportSummary(userId, end.toISOString().slice(0, 10))
|
||||
? buildCycleExportSummary(userId, userDayKey(end, reportTz))
|
||||
: Promise.resolve(null),
|
||||
gate.admits("LAB_RESULTS")
|
||||
? loadLabResults(userId, start, end)
|
||||
|
||||
@@ -159,6 +159,13 @@ describe("maybeAutoStageLabFacts", () => {
|
||||
data: expect.objectContaining({ status: "EXTRACTED" }),
|
||||
}),
|
||||
);
|
||||
// The stated report date is stored at noon UTC, not UTC midnight.
|
||||
const moved = updateMany.mock.calls[0]![0] as {
|
||||
data: { reportDate: Date };
|
||||
};
|
||||
expect(moved.data.reportDate.toISOString()).toBe(
|
||||
"2026-07-10T12:00:00.000Z",
|
||||
);
|
||||
const created = createMany.mock.calls[0]![0] as {
|
||||
data: { status: string }[];
|
||||
};
|
||||
|
||||
@@ -28,6 +28,7 @@ import { prisma } from "@/lib/db";
|
||||
import { resolveOrMintBiomarker } from "@/lib/labs/biomarker-store";
|
||||
import { decryptFactData } from "@/lib/documents/store";
|
||||
import type { ExtractedFact } from "@/generated/prisma/client";
|
||||
import { userDayKey } from "@/lib/tz/format";
|
||||
|
||||
function observationFact(): ExtractedFact {
|
||||
return {
|
||||
@@ -94,5 +95,12 @@ describe("commitApprovedFact — OBSERVATION unit integrity", () => {
|
||||
const ref = await commitApprovedFact("user-1", observationFact());
|
||||
expect(ref).toEqual({ recordType: "labResult", recordId: "lr-1" });
|
||||
expect(prisma.labResult.create).toHaveBeenCalledOnce();
|
||||
// The stated date is stored at noon UTC: it reads back on the stated day
|
||||
// as a UTC label and formatted in a zone west of UTC alike. UTC midnight
|
||||
// showed the reading a day early there.
|
||||
const takenAt = vi.mocked(prisma.labResult.create).mock.calls[0]![0].data
|
||||
.takenAt as Date;
|
||||
expect(takenAt.toISOString()).toBe("2025-01-01T12:00:00.000Z");
|
||||
expect(userDayKey(takenAt, "America/Los_Angeles")).toBe("2025-01-01");
|
||||
});
|
||||
});
|
||||
@@ -48,6 +48,7 @@ import { localisedValues } from "@/lib/i18n/shared-resolve";
|
||||
import { BIOMARKER_CATALOG } from "@/lib/labs/biomarker-catalog";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { isModuleEnabled } from "@/lib/modules/gate";
|
||||
import { dateOnlyAtNoonUtc } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* Lab-report signals used to decide whether a transcribed document is worth an
|
||||
@@ -215,7 +216,7 @@ async function stageFactsIfStored(
|
||||
status: "EXTRACTED",
|
||||
providerType: result.providerType,
|
||||
reportDate: result.reportDate
|
||||
? new Date(`${result.reportDate}T00:00:00.000Z`)
|
||||
? dateOnlyAtNoonUtc(result.reportDate)
|
||||
: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -39,6 +39,7 @@ import type {
|
||||
MedicationStatementFactData,
|
||||
ObservationFactData,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
import { dateOnlyAtNoonUtc, isDateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/** A per-fact commit failure the caller maps to a per-fact 422 entry. */
|
||||
export class FactCommitError extends Error {
|
||||
@@ -55,11 +56,13 @@ export interface CommittedRecordRef {
|
||||
recordId: string;
|
||||
}
|
||||
|
||||
/** Parse a stated YYYY-MM-DD into a UTC instant, or fall back to now. */
|
||||
/**
|
||||
* A stated YYYY-MM-DD as the instant a date-only value is stored at (noon
|
||||
* UTC), or now when the document states none. UTC midnight read back as the
|
||||
* previous day anywhere west of UTC.
|
||||
*/
|
||||
function statedDateOrNow(date: string | null): Date {
|
||||
if (date && /^\d{4}-\d{2}-\d{2}$/u.test(date)) {
|
||||
return new Date(`${date}T00:00:00.000Z`);
|
||||
}
|
||||
if (date && isDateOnlyKey(date)) return dateOnlyAtNoonUtc(date);
|
||||
return new Date();
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
type MedicationStatementFactData,
|
||||
type ObservationFactData,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
import { statedDateKey } from "@/lib/tz/date-only";
|
||||
|
||||
const SYSTEM_PROMPT = `You transcribe a photograph, PDF, or scan of a CLINICAL DOCUMENT (a doctor's report or a hospital discharge letter) into structured facts.
|
||||
|
||||
@@ -103,11 +104,7 @@ NOTE: the document below was produced by automatic OCR, so it may contain garble
|
||||
/** A normalised ISO date string (YYYY-MM-DD) or null. */
|
||||
function normaliseDate(raw: string | null): string | null {
|
||||
if (!raw) return null;
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return null;
|
||||
const parsed = new Date(trimmed);
|
||||
if (Number.isNaN(parsed.getTime())) return null;
|
||||
return parsed.toISOString().slice(0, 10);
|
||||
return statedDateKey(raw);
|
||||
}
|
||||
|
||||
export class InboundExtractError extends Error {
|
||||
|
||||
@@ -58,6 +58,9 @@ import type {
|
||||
DocumentSourceSystemValue,
|
||||
InboundDocumentKindValue,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
import { dateOnlyAtNoonUtc, dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
import { userDayKey } from "@/lib/tz/format";
|
||||
import { resolveUserTimezone } from "@/lib/tz/resolver";
|
||||
|
||||
/**
|
||||
* The person's own uploads per hour, from the web or the phone, and the
|
||||
@@ -74,9 +77,14 @@ export function personalUploadBucket(userId: string): string {
|
||||
return `documents-upload:${userId}`;
|
||||
}
|
||||
|
||||
/** Parse a YYYY-MM-DD value into a UTC midnight Date. */
|
||||
/**
|
||||
* A YYYY-MM-DD as UTC midnight: the lower bound of that date for a range
|
||||
* filter over stored date-only values (which sit at noon UTC, or at UTC
|
||||
* midnight for rows written before the noon anchor). Not a storage anchor;
|
||||
* a stored date goes through `dateOnlyAtNoonUtc`.
|
||||
*/
|
||||
export function isoDateToUtc(value: string): Date {
|
||||
return new Date(`${value}T00:00:00.000Z`);
|
||||
return dayKeyAsUtcMidnight(value);
|
||||
}
|
||||
|
||||
export interface IngestInput {
|
||||
@@ -297,9 +305,13 @@ export async function ingestDocument(
|
||||
contentCodec: codec,
|
||||
contentSha256,
|
||||
status: "STORED",
|
||||
documentDate: input.documentDate
|
||||
? isoDateToUtc(input.documentDate)
|
||||
: new Date(),
|
||||
// The upload day when none is stated is the uploader's own day,
|
||||
// not the UTC one (just after midnight east of UTC that was
|
||||
// yesterday).
|
||||
documentDate: dateOnlyAtNoonUtc(
|
||||
input.documentDate ??
|
||||
userDayKey(new Date(), await resolveUserTimezone(input.userId)),
|
||||
),
|
||||
sourceSystem,
|
||||
sourceId,
|
||||
sourceInstance,
|
||||
|
||||
@@ -35,6 +35,7 @@ import type {
|
||||
InboundDocumentKindValue,
|
||||
InboundFactType,
|
||||
} from "@/lib/validations/inbound-documents";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* The two storage codecs `InboundDocument.contentEncrypted` may carry,
|
||||
@@ -226,12 +227,8 @@ export function serialiseDocument(
|
||||
byteSize: doc.byteSize,
|
||||
status: doc.status as InboundDocumentStatus,
|
||||
providerType: doc.providerType,
|
||||
reportDate: doc.reportDate
|
||||
? doc.reportDate.toISOString().slice(0, 10)
|
||||
: null,
|
||||
documentDate: doc.documentDate
|
||||
? doc.documentDate.toISOString().slice(0, 10)
|
||||
: null,
|
||||
reportDate: doc.reportDate ? dateOnlyKey(doc.reportDate) : null,
|
||||
documentDate: doc.documentDate ? dateOnlyKey(doc.documentDate) : null,
|
||||
errorReason: doc.errorReason,
|
||||
factCount: counts.factCount,
|
||||
pendingCount: counts.pendingCount,
|
||||
|
||||
@@ -28,8 +28,8 @@ import {
|
||||
type DailyEnvironmentObservation,
|
||||
} from "@/lib/environment/open-meteo";
|
||||
import type { EnvironmentLocationSource } from "@/generated/prisma/client";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
/** Default lookback window (days) for the nightly fetch — absorbs the archive
|
||||
* settling lag and any days missed across worker reboots. */
|
||||
export const ENVIRONMENT_LOOKBACK_DAYS = 7;
|
||||
@@ -63,19 +63,15 @@ interface TravelOverride {
|
||||
|
||||
/** UTC YYYY-MM-DD for `date` (used to bound the default lookback window). */
|
||||
export function utcDayKey(date: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the environment module keys homeSince and the backfill window on UTC days throughout, and the worker compares against the same keys
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Inclusive list of YYYY-MM-DD keys from `start` to `end` (date arithmetic). */
|
||||
export function enumerateDays(start: string, end: string): string[] {
|
||||
const out: string[] = [];
|
||||
const [sy, sm, sd] = start.split("-").map(Number);
|
||||
const [ey, em, ed] = end.split("-").map(Number);
|
||||
let cur = Date.UTC(sy, sm - 1, sd);
|
||||
const last = Date.UTC(ey, em - 1, ed);
|
||||
while (cur <= last) {
|
||||
out.push(new Date(cur).toISOString().slice(0, 10));
|
||||
cur += MS_PER_DAY;
|
||||
for (let cur = start; cur <= end; cur = shiftDateKey(cur, 1)) {
|
||||
out.push(cur);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
type AllergyDTO,
|
||||
type FamilyHistoryEntryDTO,
|
||||
} from "@/lib/records/dto";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/** Disclosed in the payload manifest AND mirrored in the export UI copy. */
|
||||
export const DOCUMENTS_MANIFEST_NOTE =
|
||||
@@ -546,10 +547,8 @@ export async function buildRecordsBackupSection(
|
||||
mimeType: d.mimeType,
|
||||
byteSize: d.byteSize,
|
||||
status: d.status,
|
||||
reportDate: d.reportDate ? d.reportDate.toISOString().slice(0, 10) : null,
|
||||
documentDate: d.documentDate
|
||||
? d.documentDate.toISOString().slice(0, 10)
|
||||
: null,
|
||||
reportDate: d.reportDate ? dateOnlyKey(d.reportDate) : null,
|
||||
documentDate: d.documentDate ? dateOnlyKey(d.documentDate) : null,
|
||||
sourceSystem: d.sourceSystem,
|
||||
sourceId: d.sourceId,
|
||||
sourceInstance: d.sourceInstance,
|
||||
|
||||
@@ -386,6 +386,7 @@ export const FITBIT_SLEEP_RANGE_DAYS = 30;
|
||||
|
||||
/** `YYYY-MM-DD` (UTC) for a Fitbit date-path segment. */
|
||||
export function fitbitDate(d: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: request window edge for the provider API, not a displayed day; rows carry their own dates
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -646,6 +646,7 @@ export function incrementalFilter(
|
||||
case "date":
|
||||
return {
|
||||
field: `${dateStyle === "camel" ? dataType.key : dataType.filter}.date`,
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: request window edge for the provider API, not a displayed day; rows carry their own dates
|
||||
bound: start.toISOString().slice(0, 10),
|
||||
};
|
||||
case "rollup":
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
nowProvenanceTimestamp,
|
||||
} from "@/lib/insights/derived/coverage";
|
||||
import type { Derived } from "@/lib/insights/derived/types";
|
||||
import { daysBetweenDateKeys } from "@/lib/tz/format";
|
||||
|
||||
/* ── tunables (documented invariants) ────────────────────────────────── */
|
||||
|
||||
@@ -1050,7 +1051,5 @@ function runFlag(
|
||||
|
||||
/** Whole-day signed difference `to − from` for two `YYYY-MM-DD` keys. */
|
||||
export function dayDiff(from: string, to: string): number {
|
||||
const a = Date.parse(`${from}T00:00:00Z`);
|
||||
const b = Date.parse(`${to}T00:00:00Z`);
|
||||
return Math.round((b - a) / (24 * 60 * 60 * 1000));
|
||||
return daysBetweenDateKeys(from, to);
|
||||
}
|
||||
@@ -61,6 +61,7 @@ export function classifyBriefingFailure(args: {
|
||||
|
||||
/** UTC YYYY-MM-DD calendar-day key for the marker payload. */
|
||||
function dateKey(at: Date = new Date()): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: internal once-per-day marker key, written and read by this module only, never shown
|
||||
return at.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -123,6 +123,7 @@ import {
|
||||
isFullyCovered,
|
||||
probeRollupCoverage,
|
||||
} from "@/lib/rollups/measurement-coverage";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* Heavy aggregate row — count/min/max/mean alongside the non-composable
|
||||
@@ -939,7 +940,7 @@ function buildDailyByType(
|
||||
// `bucketStart` is the UTC midnight of the bucketed day — the
|
||||
// same boundary Postgres' `date_trunc('day', ...)` would pick
|
||||
// when the session timezone is UTC (the container default).
|
||||
day: b.day.toISOString().slice(0, 10),
|
||||
day: dateOnlyKey(b.day),
|
||||
// Match the legacy `ROUND(AVG, 2)::double precision` semantics
|
||||
// so correlation thresholds tuned against the v1.4.34 output
|
||||
// don't drift on the third decimal.
|
||||
|
||||
@@ -155,6 +155,7 @@ const BRIEFING_REROLL_TEMPERATURE = 0.6;
|
||||
|
||||
/** UTC YYYY-MM-DD calendar-day key gating the once-per-day briefing re-roll. */
|
||||
function buildRerollDateKey(at: Date = new Date()): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: internal once-per-day re-roll gate key, never shown
|
||||
return at.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ import type {
|
||||
MeasurementType,
|
||||
} from "@/generated/prisma/client";
|
||||
import { TRACKED_INTAKE_WHERE } from "@/lib/medications/intake-tracking";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/**
|
||||
* v1.21.0 (FDREXTEND) — build the user's MEDICATION_COMPLIANCE daily series.
|
||||
@@ -223,6 +224,7 @@ export async function fetchEnvironmentSeries(
|
||||
userId: string,
|
||||
since: Date,
|
||||
): Promise<NamedSeries[]> {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: lower bound on stored environment day keys; a day either way at the far edge does not change the series
|
||||
const sinceKey = since.toISOString().slice(0, 10);
|
||||
const rows = await prisma.environmentContext.findMany({
|
||||
where: { userId, date: { gte: sinceKey } },
|
||||
@@ -758,7 +760,7 @@ function composeRollupDailyMeans(
|
||||
// DAY buckets are minted at UTC midnight; the UTC date IS the bucket's
|
||||
// day key (the same convention graded-series and the derived baselines
|
||||
// read the tier under).
|
||||
const day = r.bucketStart.toISOString().slice(0, 10);
|
||||
const day = dateOnlyKey(r.bucketStart);
|
||||
const acc = byDay.get(day) ?? { sum: 0, count: 0 };
|
||||
acc.sum += sum;
|
||||
acc.count += r.count;
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
import { pearson, MIN_PAIRED_N } from "@/lib/insights/correlations";
|
||||
import { type Locale } from "@/lib/i18n/config";
|
||||
import { getServerTranslator } from "@/lib/i18n/server-translator";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
/**
|
||||
* Locale-aware string builder — the same signature the server translator
|
||||
@@ -238,10 +239,7 @@ export interface CorrelationDiscoveryResult {
|
||||
|
||||
/** Add `lagDays` to a YYYY-MM-DD day key, returning the shifted key. */
|
||||
function shiftDay(day: string, lagDays: number): string {
|
||||
const [y, m, d] = day.split("-").map(Number);
|
||||
const dt = new Date(Date.UTC(y, m - 1, d));
|
||||
dt.setUTCDate(dt.getUTCDate() + lagDays);
|
||||
return dt.toISOString().slice(0, 10);
|
||||
return shiftDateKey(day, lagDays);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -194,3 +194,20 @@ describe("adherence storyline ↔ dashboard-tile engine parity", () => {
|
||||
expect(story).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("adherence storyline course window", () => {
|
||||
it("keeps a course on its last day in the user's zone", async () => {
|
||||
// 2026-06-21 20:00 in Los Angeles, already the 22nd in UTC. A course
|
||||
// whose `endsOn` (a calendar date) is the 21st is still running.
|
||||
const now = new Date("2026-06-22T03:00:00.000Z");
|
||||
await buildAdherenceStoryline("user-1", "America/Los_Angeles", now);
|
||||
const where = mocks.medicationFindMany.mock.calls[0]![0].where as {
|
||||
OR: [unknown, { endsOn: { gte: Date } }];
|
||||
};
|
||||
const lastDay = new Date("2026-06-21T00:00:00.000Z"); // @db.Date value
|
||||
expect(where.OR[1].endsOn.gte.getTime()).toBeLessThanOrEqual(
|
||||
lastDay.getTime(),
|
||||
);
|
||||
expect(where.OR[1].endsOn.gte.toISOString()).toBe(lastDay.toISOString());
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,7 @@ import { probeRollupCoverage } from "@/lib/rollups/measurement-coverage";
|
||||
import { readDayMeanSeries } from "@/lib/insights/derived/baseline";
|
||||
import { buildScheduleAnchoredComplianceBuckets } from "@/lib/analytics/schedule-anchored-compliance";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
|
||||
import { userDayKey } from "@/lib/tz/format";
|
||||
import { sanitizeForPrompt } from "@/lib/insights/sanitize";
|
||||
import {
|
||||
inferMedTargetClass,
|
||||
@@ -35,6 +36,7 @@ import {
|
||||
type MedTargetClass,
|
||||
} from "@/lib/medications/med-target-map";
|
||||
import { TRACKED_INTAKE_WHERE } from "@/lib/medications/intake-tracking";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
const MAD_TO_SIGMA = 1.4826;
|
||||
@@ -160,7 +162,11 @@ export async function buildAdherenceStoryline(
|
||||
timezone: string | null,
|
||||
now: Date = new Date(),
|
||||
): Promise<AdherenceStoryline | null> {
|
||||
// 1. Active medications with a confidently-known target class.
|
||||
// 1. Active medications with a confidently-known target class. `endsOn` is
|
||||
// a calendar date, so a course is over only once the user's own day has
|
||||
// passed it; comparing the column against the instant `now` dropped the
|
||||
// course's last day.
|
||||
const todayKey = userDayKey(now, timezone ?? DEFAULT_TIMEZONE);
|
||||
const meds = await prisma.medication.findMany({
|
||||
where: {
|
||||
userId,
|
||||
@@ -168,7 +174,10 @@ export async function buildAdherenceStoryline(
|
||||
// v1.39.1 (#1033) — the adherence figure below counts tracked
|
||||
// medications only, so a record-only one cannot be its subject.
|
||||
...TRACKED_INTAKE_WHERE,
|
||||
OR: [{ endsOn: null }, { endsOn: { gte: now } }],
|
||||
OR: [
|
||||
{ endsOn: null },
|
||||
{ endsOn: { gte: dayKeyAsUtcMidnight(todayKey) } },
|
||||
],
|
||||
},
|
||||
select: { name: true, treatmentClass: true },
|
||||
});
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
type Derived,
|
||||
type DerivedProvenanceSource,
|
||||
} from "./types";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/** k for the median ± k·MAD band — ≈3σ-equivalent for normal data. */
|
||||
const DEFAULT_MAD_K = 3;
|
||||
@@ -255,7 +256,7 @@ export async function readDayMeanSeries(
|
||||
const points = resolved.rows
|
||||
.filter((row) => isPlausibleMetricValue(type, row.mean))
|
||||
.map((row) => ({
|
||||
day: row.bucketStart.toISOString().slice(0, 10),
|
||||
day: dateOnlyKey(row.bucketStart),
|
||||
mean: row.mean,
|
||||
}));
|
||||
if (points.length > 0) return { points, source: "DAY" };
|
||||
|
||||
@@ -52,6 +52,7 @@ import {
|
||||
} from "./coverage";
|
||||
import { readDayMeanSeries, type BaselineProfile } from "./baseline";
|
||||
import type { Derived, DerivedProvenanceSource } from "./types";
|
||||
import { daysBetweenDateKeys, shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
/** Trailing window the fit reads (days). Matches the baseline engine. */
|
||||
const DEFAULT_WINDOW_DAYS = 30;
|
||||
@@ -266,11 +267,7 @@ export async function computeTrajectory(
|
||||
}
|
||||
|
||||
// x = days since the FIRST in-window day; y = the per-day mean.
|
||||
const dayMs = 24 * 60 * 60 * 1000;
|
||||
const startMs = new Date(`${points[0].day}T00:00:00Z`).getTime();
|
||||
const xs = points.map(
|
||||
(p) => (new Date(`${p.day}T00:00:00Z`).getTime() - startMs) / dayMs,
|
||||
);
|
||||
const xs = points.map((p) => daysBetweenDateKeys(points[0].day, p.day));
|
||||
const ys = points.map((p) => p.mean);
|
||||
|
||||
const fit = fitOls(xs, ys);
|
||||
@@ -286,9 +283,7 @@ export async function computeTrajectory(
|
||||
// Project from the last observed day-offset forward over the horizon,
|
||||
// each point carrying the widening prediction band.
|
||||
const lastX = xs[xs.length - 1];
|
||||
const lastDayMs = new Date(
|
||||
`${points[points.length - 1].day}T00:00:00Z`,
|
||||
).getTime();
|
||||
const lastDay = points[points.length - 1].day;
|
||||
const projection: TrajectoryPoint[] = [];
|
||||
for (let h = 1; h <= horizonDays; h++) {
|
||||
const x = lastX + h;
|
||||
@@ -296,7 +291,7 @@ export async function computeTrajectory(
|
||||
const half = predictionIntervalHalfWidth(fit, x);
|
||||
projection.push({
|
||||
dayOffset: h,
|
||||
date: new Date(lastDayMs + h * dayMs).toISOString().slice(0, 10),
|
||||
date: shiftDateKey(lastDay, h),
|
||||
projected,
|
||||
bandLow: projected - half,
|
||||
bandHigh: projected + half,
|
||||
|
||||
@@ -23,6 +23,7 @@ import type { StrainAnchor } from "@/lib/insights/strain-score";
|
||||
import { computeReadiness, type ReadinessComponent } from "./readiness";
|
||||
import { resolveCanonicalRecovery } from "./recovery-resolve";
|
||||
import { SPARKLINE_MAX_POINTS, type Derived } from "./types";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/** A 0–100 wellness score band. Higher is better for recovery; for stress a
|
||||
* higher score is worse, so the band direction flips (see `WELLNESS_DIR`). */
|
||||
@@ -207,7 +208,7 @@ export async function computeWellnessScore(
|
||||
// truth is the cache row, not a re-derivation here.
|
||||
let anchor: StrainAnchor | null = null;
|
||||
if (type === "STRAIN_SCORE") {
|
||||
const day = latest.measuredAt.toISOString().slice(0, 10);
|
||||
const day = dateOnlyKey(latest.measuredAt);
|
||||
const cache = await prisma.strainTrimpCache.findUnique({
|
||||
where: { userId_day: { userId, day } },
|
||||
select: { anchor: true },
|
||||
|
||||
@@ -104,6 +104,7 @@ export async function detectGlp1Plateau(
|
||||
drug,
|
||||
doseValue: latestDose.doseValue,
|
||||
doseUnit: latestDose.doseUnit,
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: dose-start label in a prompt; this builder has no zone yet
|
||||
doseSince: latestDose.effectiveFrom.toISOString().slice(0, 10),
|
||||
daysOnDose,
|
||||
weightDeltaKg: Math.round(delta * 10) / 10,
|
||||
|
||||
@@ -84,6 +84,7 @@ const ABSENT: LabChangesSummary = {
|
||||
|
||||
/** UTC calendar-day key (YYYY-MM-DD) for a sample instant. */
|
||||
function dayKey(d: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: groups draws by UTC day; this summariser has no zone yet (labReadingDay is the target)
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { daysBetweenDateKeys } from "@/lib/tz/format";
|
||||
/**
|
||||
* How old a reading may be before "today" stops being true about it.
|
||||
*
|
||||
@@ -50,8 +51,6 @@ export function isCurrentForTodayClaim(
|
||||
* answers `null` rather than a fabricated distance.
|
||||
*/
|
||||
export function dayKeyAgeInDays(then: string, today: string): number | null {
|
||||
const a = Date.parse(`${then}T00:00:00.000Z`);
|
||||
const b = Date.parse(`${today}T00:00:00.000Z`);
|
||||
if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
|
||||
return Math.round((b - a) / 86_400_000);
|
||||
const days = daysBetweenDateKeys(then, today);
|
||||
return Number.isFinite(days) ? days : null;
|
||||
}
|
||||
@@ -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 { userDayKey } from "@/lib/tz/format";
|
||||
import { userDayKey, shiftDateKey } from "@/lib/tz/format";
|
||||
import type {
|
||||
CrossMetricMeasurement,
|
||||
MoodAggregateEntry,
|
||||
@@ -254,10 +254,7 @@ export function metricDayMap(
|
||||
|
||||
/** Add `lagDays` to a YYYY-MM-DD day key (UTC-anchored, DST-immune). */
|
||||
export function shiftDayKey(day: string, lagDays: number): string {
|
||||
const [y, m, d] = day.split("-").map(Number);
|
||||
const dt = new Date(Date.UTC(y, m - 1, d));
|
||||
dt.setUTCDate(dt.getUTCDate() + lagDays);
|
||||
return dt.toISOString().slice(0, 10);
|
||||
return shiftDateKey(day, lagDays);
|
||||
}
|
||||
|
||||
/** Convert a raw metric value to the row's display unit. */
|
||||
|
||||
@@ -34,6 +34,7 @@ const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
* `YYYY-MM-DD`. Resolved in ONE place so all three engines agree.
|
||||
*/
|
||||
export function scoreDayKey(now: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the derived-score engines score UTC days, resolved here in one place (see the doc comment)
|
||||
return new Date(now.getTime() - MS_PER_DAY).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
scoreMeasuredAt,
|
||||
upsertScoreRow,
|
||||
} from "@/lib/insights/score-row";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
|
||||
/** The per-day idempotency-key prefix for a stored Strain score row. */
|
||||
export const STRAIN_SCORE_EXTERNAL_ID_PREFIX = "strain:";
|
||||
@@ -395,6 +396,7 @@ export async function computeStrainScore(
|
||||
},
|
||||
): Promise<StrainComputeResult> {
|
||||
const dayKey = strainDayKey(now);
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: UTC day window of the UTC-day score engines (scoreDayKey)
|
||||
const dayStart = new Date(`${dayKey}T00:00:00.000Z`);
|
||||
const dayEnd = new Date(dayStart.getTime() + MS_PER_DAY);
|
||||
|
||||
@@ -548,12 +550,7 @@ export async function loadStrainAnchorHistory(
|
||||
now: Date,
|
||||
): Promise<StrainAnchorHistory> {
|
||||
const dayKey = strainDayKey(now);
|
||||
const windowStart = new Date(
|
||||
new Date(`${dayKey}T00:00:00.000Z`).getTime() -
|
||||
STRAIN_CHRONIC_WINDOW_DAYS * MS_PER_DAY,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
const windowStart = shiftDateKey(dayKey, -STRAIN_CHRONIC_WINDOW_DAYS);
|
||||
|
||||
// The chronic window of cached rows, excluding the scored day itself (its
|
||||
// TRIMP is added at compute time so the distribution always reflects the
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
*/
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import { buildBaselineBand } from "@/lib/insights/derived/baseline";
|
||||
import { daysBetweenDateKeys } from "@/lib/tz/format";
|
||||
|
||||
/** One DAY-bucket point: a calendar day key (YYYY-MM-DD) + that day's mean. */
|
||||
export interface StreakPoint {
|
||||
@@ -220,8 +221,6 @@ function buildBandFromSeries(
|
||||
|
||||
/** Whole-day gap between two YYYY-MM-DD keys (>=1; 1 = adjacent). */
|
||||
function dayGap(earlier: string, later: string): number {
|
||||
const a = Date.parse(`${earlier}T00:00:00Z`);
|
||||
const b = Date.parse(`${later}T00:00:00Z`);
|
||||
if (Number.isNaN(a) || Number.isNaN(b)) return Number.POSITIVE_INFINITY;
|
||||
return Math.round((b - a) / (24 * 60 * 60 * 1000));
|
||||
const gap = daysBetweenDateKeys(earlier, later);
|
||||
return Number.isNaN(gap) ? Number.POSITIVE_INFINITY : gap;
|
||||
}
|
||||
@@ -133,6 +133,7 @@ async function readIntradaySdnn(
|
||||
now: Date,
|
||||
): Promise<number[]> {
|
||||
const dayKey = stressDayKey(now);
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: UTC day window of the UTC-day score engines (scoreDayKey)
|
||||
const dayStart = new Date(`${dayKey}T00:00:00.000Z`);
|
||||
const dayEnd = new Date(dayStart.getTime() + MS_PER_DAY);
|
||||
const rows = await prisma.measurement.findMany({
|
||||
|
||||
@@ -293,6 +293,7 @@ export async function runCoachPlanReviewTick(
|
||||
timeZone: "UTC",
|
||||
db: prisma,
|
||||
});
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the day series above is read with timeZone UTC, so the plan start is cut on the same calendar
|
||||
const startKey = plan.createdAt.toISOString().slice(0, 10);
|
||||
const before: number[] = [];
|
||||
const after: number[] = [];
|
||||
|
||||
@@ -906,6 +906,7 @@ export async function runOffhostBackup(
|
||||
}
|
||||
const s3 = s3Override ?? (await getS3Client(cfg));
|
||||
const runStartedAt = options.runStartedAt;
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: off-host object key date, the name the restore drill and the purge look up
|
||||
const dateKey = (runStartedAt ?? now).toISOString().slice(0, 10);
|
||||
|
||||
const users = await prisma.user.findMany({
|
||||
|
||||
@@ -211,7 +211,8 @@ export async function processOffhostPurges(
|
||||
const subject = request.subjectId;
|
||||
const day =
|
||||
request.reason === "data_wiped" && live.has(subject)
|
||||
? request.requestedAt.toISOString().slice(0, 10)
|
||||
? // eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: matches the UTC dates in the off-host object keys
|
||||
request.requestedAt.toISOString().slice(0, 10)
|
||||
: null;
|
||||
const prior = lastDayToDelete.get(subject);
|
||||
if (prior === undefined) lastDayToDelete.set(subject, day);
|
||||
|
||||
@@ -104,6 +104,7 @@ export async function handleMoodReminderCleanup(
|
||||
try {
|
||||
const cutoff = new Date();
|
||||
cutoff.setUTCDate(cutoff.getUTCDate() - MOOD_REMINDER_RETENTION_DAYS);
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: retention cutoff; a day either way does not matter
|
||||
const cutoffIso = cutoff.toISOString().slice(0, 10);
|
||||
const deleted = await p.moodReminderDispatch.deleteMany({
|
||||
where: { date: { lt: cutoffIso } },
|
||||
|
||||
@@ -167,6 +167,7 @@ export async function runRestoreDrill(
|
||||
}
|
||||
|
||||
const ageDays = Math.floor(
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: age of a UTC-dated off-host object key
|
||||
(now.getTime() - Date.parse(`${dateKey}T00:00:00Z`)) /
|
||||
(24 * 60 * 60 * 1000),
|
||||
);
|
||||
|
||||
@@ -119,6 +119,7 @@ export async function runStepConsolidationRepairForUser(
|
||||
// in different UTC days, so both instants are tracked).
|
||||
const touchedByUtcDay = new Map<string, Date>();
|
||||
const markTouched = (instant: Date) => {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: the rollup tier keys DAY buckets by UTC day (see the comment above)
|
||||
touchedByUtcDay.set(instant.toISOString().slice(0, 10), instant);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { labReadingDay, labReadingDaySearchRange } from "../reading-day";
|
||||
|
||||
describe("labReadingDay", () => {
|
||||
it("reads a date-only reading as its stated date in every zone", () => {
|
||||
const noon = new Date("2026-06-10T12:00:00.000Z");
|
||||
const legacyMidnight = new Date("2026-06-10T00:00:00.000Z");
|
||||
for (const tz of ["America/Los_Angeles", "Pacific/Kiritimati", "UTC"]) {
|
||||
expect(labReadingDay(noon, tz)).toBe("2026-06-10");
|
||||
expect(labReadingDay(legacyMidnight, tz)).toBe("2026-06-10");
|
||||
}
|
||||
});
|
||||
|
||||
it("reads a hand-entered instant on the user's own day", () => {
|
||||
const draw = new Date("2026-06-09T23:00:00.000Z"); // 08:00 on the 10th in Tokyo
|
||||
expect(labReadingDay(draw, "Asia/Tokyo")).toBe("2026-06-10");
|
||||
expect(labReadingDay(draw, "America/Los_Angeles")).toBe("2026-06-09");
|
||||
});
|
||||
|
||||
it("searches a range that holds the day's readings in any zone", () => {
|
||||
const range = labReadingDaySearchRange("2026-06-10");
|
||||
const kiritimatiMorning = new Date("2026-06-09T10:30:00.000Z"); // 00:30 on the 10th at UTC+14
|
||||
const utcMinus12Late = new Date("2026-06-11T10:30:00.000Z"); // 22:30 on the 10th at UTC-12
|
||||
expect(kiritimatiMorning >= range.gte && kiritimatiMorning < range.lt).toBe(
|
||||
true,
|
||||
);
|
||||
expect(utcMinus12Late >= range.gte && utcMinus12Late < range.lt).toBe(true);
|
||||
});
|
||||
});
|
||||
+19
-12
@@ -36,6 +36,12 @@ import {
|
||||
type OcrExtractedRowDto,
|
||||
OCR_MAX_ROWS,
|
||||
} from "@/lib/validations/labs-ocr";
|
||||
import {
|
||||
labReadingDay,
|
||||
labReadingDaySearchRange,
|
||||
} from "@/lib/labs/reading-day";
|
||||
import { resolveUserTimezone } from "@/lib/tz/resolver";
|
||||
import { statedDateKey } from "@/lib/tz/date-only";
|
||||
|
||||
const SYSTEM_PROMPT = `You transcribe a photograph or PDF of a laboratory test report into structured data.
|
||||
|
||||
@@ -90,12 +96,8 @@ Respond ONLY with a JSON object of this exact shape:
|
||||
/** A normalised ISO date string (YYYY-MM-DD) or null. */
|
||||
function normaliseDate(raw: string | null): string | null {
|
||||
if (!raw) return null;
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return null;
|
||||
const parsed = new Date(trimmed);
|
||||
if (Number.isNaN(parsed.getTime())) return null;
|
||||
// Keep only the calendar day — the lab reports a date, not an instant.
|
||||
return parsed.toISOString().slice(0, 10);
|
||||
return statedDateKey(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -133,6 +135,7 @@ async function annotateRow(
|
||||
userId: string,
|
||||
row: ExtractedRow,
|
||||
reportDate: string | null,
|
||||
tz: string,
|
||||
): Promise<OcrExtractedRowDto> {
|
||||
const analyte = row.analyte.trim();
|
||||
const takenAt = normaliseDate(row.takenAt) ?? reportDate;
|
||||
@@ -149,18 +152,21 @@ async function annotateRow(
|
||||
// a likely re-scan. Uses the existing (userId, analyte, takenAt) index.
|
||||
let duplicateOf: string | null = null;
|
||||
if (takenAt) {
|
||||
const dayStart = new Date(`${takenAt}T00:00:00.000Z`);
|
||||
const dayEnd = new Date(`${takenAt}T23:59:59.999Z`);
|
||||
const candidates = await prisma.labResult.findMany({
|
||||
// The reading's calendar day, the same rule the commit applies, so the
|
||||
// review screen flags exactly the rows the commit will skip.
|
||||
const rows = await prisma.labResult.findMany({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
analyte: { equals: analyte, mode: "insensitive" },
|
||||
takenAt: { gte: dayStart, lte: dayEnd },
|
||||
takenAt: labReadingDaySearchRange(takenAt),
|
||||
},
|
||||
select: { id: true, value: true, valueText: true },
|
||||
take: 25,
|
||||
select: { id: true, value: true, valueText: true, takenAt: true },
|
||||
take: 100,
|
||||
});
|
||||
const candidates = rows.filter(
|
||||
(c) => labReadingDay(c.takenAt, tz) === takenAt,
|
||||
);
|
||||
for (const c of candidates) {
|
||||
if (row.value !== null && c.value !== null && c.value === row.value) {
|
||||
duplicateOf = c.id;
|
||||
@@ -279,11 +285,12 @@ export async function runOcrExtraction(
|
||||
// noticing that a report layout or a language is unsupported and never
|
||||
// hearing about it. A count only: the string is the user's document.
|
||||
let unreadableRanges = 0;
|
||||
const tz = await resolveUserTimezone(args.userId);
|
||||
for (const row of envelope.rows.slice(0, OCR_MAX_ROWS)) {
|
||||
if (isUnreadableRange(parseReferenceRange(row.referenceText, row.unit))) {
|
||||
unreadableRanges += 1;
|
||||
}
|
||||
rows.push(await annotateRow(args.userId, row, reportDate));
|
||||
rows.push(await annotateRow(args.userId, row, reportDate, tz));
|
||||
}
|
||||
|
||||
annotate({
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* The calendar day a lab reading belongs to.
|
||||
*
|
||||
* Two kinds of reading share `LabResult.takenAt`. A scanned or document
|
||||
* reading states a date only, stored at noon UTC (rows from before the noon
|
||||
* anchor sit at UTC midnight); its day is that date. A reading entered by
|
||||
* hand carries the real instant of the draw; its day is the user's day of
|
||||
* that instant. Cutting both on the UTC day, as the duplicate checks did,
|
||||
* put a morning draw east of UTC on the previous day, so a scan of the same
|
||||
* report wrote the reading a second time.
|
||||
*/
|
||||
import { dateOnlyKey, dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const NOON_MS = 43_200_000;
|
||||
|
||||
export function labReadingDay(takenAt: Date, tz: string): string {
|
||||
const msOfDay = ((takenAt.getTime() % DAY_MS) + DAY_MS) % DAY_MS;
|
||||
if (msOfDay === 0 || msOfDay === NOON_MS) return dateOnlyKey(takenAt);
|
||||
return userDayKey(takenAt, tz);
|
||||
}
|
||||
|
||||
/**
|
||||
* A `takenAt` range wide enough to hold every reading whose
|
||||
* {@link labReadingDay} is `day`, in any zone from UTC-12 to UTC+14. It
|
||||
* over-selects by design; filter the rows with `labReadingDay` afterwards.
|
||||
*/
|
||||
export function labReadingDaySearchRange(day: string): {
|
||||
gte: Date;
|
||||
lt: Date;
|
||||
} {
|
||||
return {
|
||||
gte: dayKeyAsUtcMidnight(shiftDateKey(day, -1)),
|
||||
lt: dayKeyAsUtcMidnight(shiftDateKey(day, 2)),
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import { encryptFactData, encryptFactProvenance } from "@/lib/documents/store";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { isModuleEnabled } from "@/lib/modules/gate";
|
||||
import type { ObservationFactData } from "@/lib/validations/inbound-documents";
|
||||
import { dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
/** One inserted lab row to cross-link back to its source vault document. */
|
||||
export interface InsertedLabForLink {
|
||||
@@ -54,7 +55,7 @@ function observationFromLab(lab: InsertedLabForLink): ObservationFactData {
|
||||
unit: lab.unit,
|
||||
referenceLow: lab.referenceLow,
|
||||
referenceHigh: lab.referenceHigh,
|
||||
effectiveDate: lab.takenAt.toISOString().slice(0, 10),
|
||||
effectiveDate: dateOnlyKey(lab.takenAt),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
import { prisma } from "@/lib/db";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { dayKeyAsUtcMidnight, dateOnlyKey } from "@/lib/tz/date-only";
|
||||
|
||||
type Transaction = Prisma.TransactionClient;
|
||||
|
||||
@@ -266,7 +267,7 @@ export function toManagedProfileView(row: {
|
||||
return {
|
||||
id: row.id,
|
||||
displayName: row.displayName,
|
||||
dateOfBirth: row.dateOfBirth?.toISOString().slice(0, 10) ?? null,
|
||||
dateOfBirth: row.dateOfBirth ? dateOnlyKey(row.dateOfBirth) : null,
|
||||
gender: row.gender,
|
||||
locale: row.locale,
|
||||
timezone: row.timezone,
|
||||
@@ -373,7 +374,7 @@ export async function updateManagedProfile(input: {
|
||||
...(patch.dateOfBirth !== undefined
|
||||
? {
|
||||
dateOfBirth: patch.dateOfBirth
|
||||
? new Date(`${patch.dateOfBirth}T00:00:00.000Z`)
|
||||
? dayKeyAsUtcMidnight(patch.dateOfBirth)
|
||||
: null,
|
||||
}
|
||||
: {}),
|
||||
|
||||
@@ -453,6 +453,7 @@ function clip(text: string, max: number): { text: string; truncated: boolean } {
|
||||
}
|
||||
|
||||
function dateOnly(value: Date | null): string | null {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: text label mixing date-only columns and instants, read without a zone
|
||||
return value ? value.toISOString().slice(0, 10) : null;
|
||||
}
|
||||
|
||||
|
||||
@@ -708,6 +708,7 @@ export async function runDenseIntradayRetention(
|
||||
// The fold's canonical timestamp is local-noon of the day; reuse
|
||||
// its UTC date for the resting row's `stats:` key so a re-run
|
||||
// upserts the same row instead of minting a sibling.
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: stable stats: externalId key; changing it would mint a sibling row on re-run
|
||||
canonicalTimestamp.toISOString().slice(0, 10),
|
||||
);
|
||||
await pc.measurement.upsert({
|
||||
|
||||
@@ -250,6 +250,7 @@ export async function pruneIntradayCumulativeProfiles(
|
||||
retentionDays: number = CUMULATIVE_PROFILE_RETENTION_DAYS,
|
||||
): Promise<number> {
|
||||
const cutoffKey = shiftDateKey(
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: 400-day retention cutoff; no zone moves it by more than a day (see the doc comment)
|
||||
now.toISOString().slice(0, 10),
|
||||
-retentionDays,
|
||||
);
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
LIVE_ERA_REVISION_ARGS,
|
||||
liveEraStart,
|
||||
} from "@/lib/medications/scheduling/live-era";
|
||||
import { dayKeyForScheduledFor } from "@/lib/rollups/medication-compliance-rollups";
|
||||
|
||||
export interface ProjectTodayIntakesResult {
|
||||
projected: number;
|
||||
@@ -238,7 +239,9 @@ export async function projectTodayIntakesAndRecompute(input: {
|
||||
const seenDayKeys = new Set<string>();
|
||||
const recomputeJobs: Array<Promise<void>> = [];
|
||||
for (const m of missing) {
|
||||
const key = `${m.medicationId}|${m.scheduledFor.toISOString().slice(0, 10)}`;
|
||||
// The compliance rollup's own day for the slot: two slots on different
|
||||
// local days that share a UTC date must each get their recompute.
|
||||
const key = `${m.medicationId}|${dayKeyForScheduledFor(m.scheduledFor, userTz)}`;
|
||||
if (seenDayKeys.has(key)) continue;
|
||||
seenDayKeys.add(key);
|
||||
recomputeJobs.push(
|
||||
|
||||
@@ -236,6 +236,7 @@ function localDayWindow(day: string): { from: Date; to: Date } {
|
||||
// helper agrees belongs to this day. Cheaper and far safer than arithmetic
|
||||
// on `new Date(y, m, d)`, which slips by an hour twice a year and has
|
||||
// already been solved once in this codebase.
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: anchor of a superset window; rows are kept only when their own local day matches
|
||||
const naive = new Date(`${day}T00:00:00.000Z`);
|
||||
const from = new Date(naive.getTime() - 26 * 60 * 60 * 1000);
|
||||
const to = new Date(naive.getTime() + 50 * 60 * 60 * 1000);
|
||||
|
||||
@@ -16,5 +16,6 @@
|
||||
*/
|
||||
export function maxAcceptableNutrientDay(now: Date): string {
|
||||
const limit = new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000);
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: upper sanity bound with two days of slack for every real zone (see the doc comment)
|
||||
return limit.toISOString().slice(0, 10);
|
||||
}
|
||||
@@ -223,7 +223,7 @@ const dashboardMetricCard = z
|
||||
.datetime({ offset: true })
|
||||
.nullable()
|
||||
.describe(
|
||||
"Instant behind `latestValue`, falling back to the metric's newest reading. For `mood` this is the day START of the latest daily bucket, not a reading time — the series pins a day, so inventing an instant would be a lie. For `bmi` it is the WEIGHT metadata, since BMI moves exactly when weight does.",
|
||||
"Instant behind `latestValue`, falling back to the metric's newest reading. For `mood` this is the first instant of the latest daily bucket's day in the account's time zone, not a reading time (the series pins a local day, not an instant); formatted in that zone it always lands on the day the entry was logged. For `bmi` it is the WEIGHT metadata, since BMI moves exactly when weight does.",
|
||||
),
|
||||
allTimeCount: z
|
||||
.number()
|
||||
|
||||
@@ -181,6 +181,7 @@ export async function recordOuraSyncFailure(
|
||||
}
|
||||
|
||||
function ymd(d: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- baseline: request window edge for the provider API, not a displayed day; rows carry their own dates
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
@@ -140,6 +140,7 @@ function toUpsert(
|
||||
// A timed row keys on its instant's UTC date, as it always has.
|
||||
externalId:
|
||||
m.externalId ??
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: timed rows keep their historical UTC-date externalId so re-syncs upsert (see the comment above)
|
||||
`${resourcePrefix}:${m.day ?? m.measuredAt.toISOString().slice(0, 10)}:${m.fieldTag}`,
|
||||
sleepStage: m.sleepStage ?? null,
|
||||
}));
|
||||
|
||||
@@ -55,6 +55,7 @@ import type {
|
||||
PrismaClient,
|
||||
RollupGranularity,
|
||||
} from "@/generated/prisma/client";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
|
||||
/** Granularities that recompute asynchronously via pg-boss. */
|
||||
const ASYNC_GRANULARITIES: RollupGranularity[] = ["WEEK", "MONTH", "YEAR"];
|
||||
@@ -250,7 +251,7 @@ export async function recomputeMoodBucketsForEntry(
|
||||
// on `entry.date`) and puts a late-evening / after-midnight local
|
||||
// mood on the calendar day the user logged it in their own timezone.
|
||||
// `bucket_start` encodes the label as its UTC midnight instant.
|
||||
const bucketStart = new Date(`${dateLabel}T00:00:00.000Z`);
|
||||
const bucketStart = dayKeyAsUtcMidnight(dateLabel);
|
||||
await client.$executeRaw`
|
||||
WITH aggregate AS (
|
||||
SELECT
|
||||
@@ -718,7 +719,7 @@ function bucketSpan(
|
||||
): { from: Date; to: Date } {
|
||||
// Anchor at the label's UTC midnight; its UTC calendar parts ARE the
|
||||
// label's parts, so the existing UTC date math below is exact.
|
||||
const anchor = new Date(`${dateLabel}T00:00:00.000Z`);
|
||||
const anchor = dayKeyAsUtcMidnight(dateLabel);
|
||||
switch (granularity) {
|
||||
case "DAY": {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
dateOnlyAtNoonUtc,
|
||||
dateOnlyKey,
|
||||
dayKeyAsUtcMidnight,
|
||||
isCalendarDateKey,
|
||||
isDateOnlyKey,
|
||||
statedDateKey,
|
||||
} from "../date-only";
|
||||
import { daysBetweenDateKeys, weekdayOfDateKey } from "../format";
|
||||
|
||||
describe("date-only values", () => {
|
||||
it("stores a date at noon UTC and reads it back", () => {
|
||||
const stored = dateOnlyAtNoonUtc("2026-06-10");
|
||||
expect(stored.toISOString()).toBe("2026-06-10T12:00:00.000Z");
|
||||
expect(dateOnlyKey(stored)).toBe("2026-06-10");
|
||||
});
|
||||
|
||||
it("reads a row stored at UTC midnight as the same date", () => {
|
||||
expect(dateOnlyKey(dayKeyAsUtcMidnight("2026-06-10"))).toBe("2026-06-10");
|
||||
});
|
||||
|
||||
it("tells a shape from a real calendar date", () => {
|
||||
expect(isDateOnlyKey("2026-02-30")).toBe(true);
|
||||
expect(isCalendarDateKey("2026-02-30")).toBe(false);
|
||||
expect(isCalendarDateKey("2028-02-29")).toBe(true);
|
||||
expect(isCalendarDateKey("2026-6-1")).toBe(false);
|
||||
});
|
||||
|
||||
it("reads the date a string states", () => {
|
||||
expect(statedDateKey("2026-06-10")).toBe("2026-06-10");
|
||||
expect(statedDateKey("2026-06-10T23:30:00-07:00")).toBe("2026-06-10");
|
||||
expect(statedDateKey(" 2026-06-10 ")).toBe("2026-06-10");
|
||||
expect(statedDateKey("June 10, 2026")).toBe("2026-06-10");
|
||||
expect(statedDateKey("2026-02-30")).toBeNull();
|
||||
expect(statedDateKey("not a date")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("calendar key arithmetic", () => {
|
||||
it("counts whole days between keys across a DST change", () => {
|
||||
expect(daysBetweenDateKeys("2026-03-28", "2026-03-30")).toBe(2);
|
||||
expect(daysBetweenDateKeys("2026-03-30", "2026-03-28")).toBe(-2);
|
||||
expect(daysBetweenDateKeys("2025-12-31", "2026-01-01")).toBe(1);
|
||||
expect(daysBetweenDateKeys("bad", "2026-01-01")).toBeNaN();
|
||||
});
|
||||
|
||||
it("names the weekday of a key", () => {
|
||||
expect(weekdayOfDateKey("2026-10-01")).toBe(4); // Thursday
|
||||
expect(weekdayOfDateKey("2026-10-04")).toBe(0); // Sunday
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* Date-only values: a calendar date (`YYYY-MM-DD`) with no time of day — a
|
||||
* report's stated date, a document's filing date, a backup's label for a
|
||||
* `@db.Date` column.
|
||||
*
|
||||
* Such a value is stored in a timestamp column as noon UTC. Noon keeps the
|
||||
* date on the same calendar day whether it is read back as a UTC label
|
||||
* ({@link dateOnlyKey}) or formatted in any zone from UTC-11 to UTC+11. The
|
||||
* older anchor, UTC midnight, sits on the previous evening everywhere west
|
||||
* of UTC, which is how a stated report date came to show a day early.
|
||||
*
|
||||
* Rows written at UTC midnight before the switch still read back to the same
|
||||
* key through {@link dateOnlyKey}, so the two anchors coexist without a
|
||||
* migration.
|
||||
*/
|
||||
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/u;
|
||||
|
||||
/** True for a strict `YYYY-MM-DD` string. */
|
||||
export function isDateOnlyKey(value: string): boolean {
|
||||
return DATE_ONLY_RE.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a `YYYY-MM-DD` string that names a real calendar date.
|
||||
* `2026-02-30` passes the shape check but overflows to 2 March when parsed,
|
||||
* so a reader would return a different day than the one asked for.
|
||||
*/
|
||||
export function isCalendarDateKey(value: string): boolean {
|
||||
if (!DATE_ONLY_RE.test(value)) return false;
|
||||
const parsed = new Date(`${value}T00:00:00.000Z`);
|
||||
return (
|
||||
!Number.isNaN(parsed.getTime()) && parsed.toISOString().startsWith(value)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar date a free-form date string states, or `null`. An ISO string
|
||||
* (`2026-06-10`, `2026-06-10T08:00:00+09:00`) states the date it starts with.
|
||||
* Anything else (`June 10, 2026`) is parsed the way `Date` parses it, as local
|
||||
* time in the process zone, so the date is read back in that same zone;
|
||||
* reading it as UTC put it on the previous day for a process east of UTC.
|
||||
*/
|
||||
export function statedDateKey(raw: string): string | null {
|
||||
const trimmed = raw.trim();
|
||||
const isoPrefix = /^(\d{4}-\d{2}-\d{2})(?:$|T|\s)/u.exec(trimmed);
|
||||
if (isoPrefix) {
|
||||
return isCalendarDateKey(isoPrefix[1]) ? isoPrefix[1] : null;
|
||||
}
|
||||
const parsed = new Date(trimmed);
|
||||
if (Number.isNaN(parsed.getTime())) return null;
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${String(parsed.getFullYear()).padStart(4, "0")}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())}`;
|
||||
}
|
||||
|
||||
/** The instant a date-only value is stored as: 12:00 UTC on that date. */
|
||||
export function dateOnlyAtNoonUtc(key: string): Date {
|
||||
return new Date(`${key}T12:00:00.000Z`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The calendar date of a stored date-only value (or of a `@db.Date` column,
|
||||
* which Prisma hands back as UTC midnight). Only for values that ARE dates:
|
||||
* the day an instant fell on for a person is `userDayKey(instant, tz)`.
|
||||
*/
|
||||
export function dateOnlyKey(value: Date): string {
|
||||
return value.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calendar date `key` as UTC midnight. A LABEL, never the instant the day
|
||||
* began for anyone: it is how a `@db.Date` column holds a date (Prisma reads
|
||||
* and writes those as UTC midnight), how the day rollups key `bucketStart`,
|
||||
* and how a day-keyed series places a point on a time axis. Use it to compare
|
||||
* such a column with a day (`endsOn >= dayKeyAsUtcMidnight(todayKey)` keeps a
|
||||
* course through its last day, where comparing with the instant `now` dropped
|
||||
* it) or to build such a label. The first instant of a person's day is
|
||||
* `startOfLocalDayKey(key, tz)`.
|
||||
*/
|
||||
export function dayKeyAsUtcMidnight(key: string): Date {
|
||||
return new Date(`${key}T00:00:00.000Z`);
|
||||
}
|
||||
@@ -233,6 +233,27 @@ export function shiftDateKey(dateKey: string, deltaDays: number): string {
|
||||
return dt.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole calendar days from `fromKey` to `toKey` (negative when `toKey` is
|
||||
* earlier). Pure key arithmetic like {@link shiftDateKey}: both keys are
|
||||
* already resolved calendar dates, so no zone takes part. `NaN` when either
|
||||
* key is malformed, so a caller decides what a bad key means.
|
||||
*/
|
||||
export function daysBetweenDateKeys(fromKey: string, toKey: string): number {
|
||||
const a = Date.parse(`${fromKey}T00:00:00.000Z`);
|
||||
const b = Date.parse(`${toKey}T00:00:00.000Z`);
|
||||
return Math.round((b - a) / 86_400_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Weekday of a calendar date key, 0 = Sunday … 6 = Saturday (the
|
||||
* `getDay()` / schedule `daysOfWeek` convention). A calendar date has the
|
||||
* same weekday in every zone, so this needs none.
|
||||
*/
|
||||
export function weekdayOfDateKey(dateKey: string): number {
|
||||
return new Date(`${dateKey}T00:00:00.000Z`).getUTCDay();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wall-clock hour (0–23) an observer in `tz` reads off the clock at
|
||||
* `date`. Used for the time-of-day greeting so a traveller whose device
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod/v4";
|
||||
import { EXTERNAL_SOURCE } from "@/lib/measurements/external-source";
|
||||
import { validateEntryInstant } from "./entry-instant";
|
||||
import { isCalendarDateKey } from "@/lib/tz/date-only";
|
||||
|
||||
export const measurementTypeEnum = z.enum([
|
||||
"WEIGHT",
|
||||
@@ -869,11 +870,10 @@ export const listMeasurementsSchema = z
|
||||
// the admin drain route, so a malformed CLI invocation has the
|
||||
// same blast radius. Reject the impossible shapes at the
|
||||
// validator instead.
|
||||
.refine((s) => {
|
||||
const parsed = new Date(`${s}T00:00:00Z`);
|
||||
if (Number.isNaN(parsed.getTime())) return false;
|
||||
return s === parsed.toISOString().slice(0, 10);
|
||||
}, "dayKey must be a real calendar date (YYYY-MM-DD)")
|
||||
.refine(
|
||||
isCalendarDateKey,
|
||||
"dayKey must be a real calendar date (YYYY-MM-DD)",
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.refine(
|
||||
|
||||
@@ -191,6 +191,7 @@ export interface WithingsSleepSegment {
|
||||
* fetch derives from the same `start` / `now` Dates.
|
||||
*/
|
||||
function ymdUtc(d: Date): string {
|
||||
// eslint-disable-next-line healthlog/no-utc-day-key -- UTC by design: day-grained summary window matching the unix-second segment window (see the doc comment)
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user