Merge remote-tracking branch 'origin/main' into fix/v1397-derive

This commit is contained in:
Marc-André Bombeck committed 2026-10-01 10:30:10 +02:00
commit 533b75fdcf
70 files changed
+4167 -566

No files matched your search

+22 -10
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { buildGlucoseTargets } from "../glucose-builder";
import { foldGlucoseTargetRows } from "../glucose-read";
import { buildMedicationTarget } from "../medication-builder";
import { buildMoodTargets } from "../mood-builder";
import { buildSleepTarget } from "../sleep-builder";
@@ -8,11 +9,13 @@ import { buildVitalTargets } from "../vitals-builder";
const NOW = new Date("2026-07-21T12:00:00.000Z");
const TZ = "UTC";
const RECENT = new Date(NOW.getTime() - 30 * 86_400_000);
describe("target section builders", () => {
it("keeps the vital target order and profile-gated cards on an empty profile", () => {
const result = buildVitalTargets({
recentMeasurements: [],
restingPulseProxy: [],
latestByType: {},
average30ByType: {},
heightCm: null,
@@ -108,7 +111,7 @@ describe("target section builders", () => {
},
];
const targets = buildGlucoseTargets({
rows,
summaries: foldGlucoseTargetRows(rows, RECENT, TZ),
profile: {
heightCm: 180,
dateOfBirth: new Date("1985-01-01T00:00:00.000Z"),
@@ -140,10 +143,14 @@ describe("target section builders", () => {
// metadata, so every row arrives with a null context. Iterating the four
// named contexts alone returned no glucose target at all.
const targets = buildGlucoseTargets({
rows: [
{ value: 112, measuredAt: NOW, glucoseContext: null },
{ value: 104, measuredAt: NOW, glucoseContext: null },
],
summaries: foldGlucoseTargetRows(
[
{ value: 112, measuredAt: NOW, glucoseContext: null },
{ value: 104, measuredAt: NOW, glucoseContext: null },
],
RECENT,
TZ,
),
profile: {
heightCm: 180,
dateOfBirth: new Date("1985-01-01T00:00:00.000Z"),
@@ -173,11 +180,15 @@ describe("target section builders", () => {
it("keeps the tagged breakdown and puts the untagged bucket last (#943)", () => {
const targets = buildGlucoseTargets({
rows: [
{ value: 130, measuredAt: NOW, glucoseContext: "RANDOM" as const },
{ value: 90, measuredAt: NOW, glucoseContext: "FASTING" as const },
{ value: 111, measuredAt: NOW, glucoseContext: null },
],
summaries: foldGlucoseTargetRows(
[
{ value: 130, measuredAt: NOW, glucoseContext: "RANDOM" as const },
{ value: 90, measuredAt: NOW, glucoseContext: "FASTING" as const },
{ value: 111, measuredAt: NOW, glucoseContext: null },
],
RECENT,
TZ,
),
profile: {
heightCm: 180,
dateOfBirth: new Date("1985-01-01T00:00:00.000Z"),
@@ -235,6 +246,7 @@ describe("target section builders", () => {
describe("buildVitalTargets — user weight target", () => {
const base = {
recentMeasurements: [],
restingPulseProxy: [],
latestByType: {},
average30ByType: {},
heightCm: 178,
+28 -12
View File
@@ -27,7 +27,9 @@ import {
ensureUserMoodRollupsFresh,
readMoodDayRollups,
} from "@/lib/rollups/mood-rollups";
import { readRestingPulseProxy } from "@/lib/analytics/resting-pulse-read";
import { buildGlucoseTargets } from "./glucose-builder";
import { readGlucoseTargetSummaries } from "./glucose-read";
import { buildMedicationTarget } from "./medication-builder";
import { buildMoodTargets } from "./mood-builder";
import { buildSleepTarget } from "./sleep-builder";
@@ -76,6 +78,10 @@ export async function buildTargetsResponse(user: AuthedUser) {
"BODY_FAT",
"ACTIVITY_STEPS",
];
// Heart rate is the one vital a device streams. Its thirty days reach the
// resting-pulse card as one proxy point per day, folded in SQL below; every
// other vital is written a few times a day and is read as rows.
const recentTypes = types.filter((type) => type !== "PULSE");
const thirtyDaysAgo = new Date(queryNow.getTime() - 30 * 24 * 60 * 60 * 1000);
const oneYearAgo = new Date(queryNow.getTime() - 365 * 24 * 60 * 60 * 1000);
const moodSince = new Date(
@@ -96,7 +102,8 @@ export async function buildTargetsResponse(user: AuthedUser) {
medicationBundle,
moodRollups,
latestMoodEntry,
glucoseRows,
glucoseSummaries,
restingPulseProxy,
] = await Promise.all([
limit(() =>
prisma.user.findUnique({
@@ -116,7 +123,7 @@ export async function buildTargetsResponse(user: AuthedUser) {
prisma.measurement.findMany({
where: {
userId,
type: { in: types },
type: { in: recentTypes },
measuredAt: { gte: thirtyDaysAgo },
deletedAt: null,
},
@@ -212,16 +219,22 @@ export async function buildTargetsResponse(user: AuthedUser) {
select: { score: true, moodLoggedAt: true },
}),
),
// A sensor reporting every five minutes writes 105 000 glucose readings
// a year. The cards need the newest per meal context and the last thirty
// days per local day, so both fold in SQL.
limit(() =>
prisma.measurement.findMany({
where: {
userId,
type: "BLOOD_GLUCOSE",
measuredAt: { gte: oneYearAgo },
deletedAt: null,
},
orderBy: { measuredAt: "desc" },
select: { value: true, measuredAt: true, glucoseContext: true },
readGlucoseTargetSummaries({
userId,
since: oneYearAgo,
recentSince: thirtyDaysAgo,
timeZone: timezone,
}),
),
limit(() =>
readRestingPulseProxy({
userId,
since: thirtyDaysAgo,
timeZone: timezone,
}),
),
]);
@@ -252,6 +265,8 @@ export async function buildTargetsResponse(user: AuthedUser) {
for (const type of types) {
latestByType[type] =
latestEverByType.find((row) => row.type === type)?.value ?? null;
}
for (const type of recentTypes) {
const recent = recentMeasurements.filter(
(measurement) => measurement.type === type,
);
@@ -267,6 +282,7 @@ export async function buildTargetsResponse(user: AuthedUser) {
const vitalSection = buildVitalTargets({
recentMeasurements,
restingPulseProxy,
latestByType,
average30ByType,
heightCm,
@@ -326,7 +342,7 @@ export async function buildTargetsResponse(user: AuthedUser) {
const glucoseUnit = resolveGlucoseUnit(dbUser?.glucoseUnit ?? null);
targets.push(
...buildGlucoseTargets({
rows: glucoseRows,
summaries: glucoseSummaries,
profile: {
heightCm,
dateOfBirth: dbUser?.dateOfBirth ?? null,
+45 -17
View File
@@ -43,12 +43,13 @@ function last7DayKeys(now: Date, timezone: string): string[] {
return keys;
}
function computeStrip(
/** A day's readings folded to their sum and count, keyed by local day. */
export type DaySums = ReadonlyMap<string, { sum: number; count: number }>;
function sumByDay(
events: ReadonlyArray<{ measuredAt: Date; value: number }>,
classify: (mean: number) => DayBand | null,
timezone: string,
now: Date,
) {
): Map<string, { sum: number; count: number }> {
const byDay = new Map<string, { sum: number; count: number }>();
for (const event of events) {
const key = userDayKey(event.measuredAt, timezone);
@@ -57,7 +58,15 @@ function computeStrip(
bucket.count += 1;
byDay.set(key, bucket);
}
return byDay;
}
function computeStrip(
byDay: DaySums,
classify: (mean: number) => DayBand | null,
timezone: string,
now: Date,
) {
const consistency7d: Array<DayBand | null> = [];
let daysInRange7d = 0;
let daysLogged7d = 0;
@@ -77,13 +86,40 @@ function computeStrip(
export function rollupConsistency({
events,
...rest
}: RollupConsistencyInput): TargetConsistency {
return rollupConsistencyFromDays({
...rest,
byDay: sumByDay(events, rest.timezone),
readingCount: events.length,
});
}
interface RollupDaySumsInput extends ConsistencyClock {
/** Each local day's readings as sum and count. */
byDay: DaySums;
/** Readings behind `byDay`, for the thin-data threshold. */
readingCount: number;
classify: (mean: number) => DayBand | null;
totalReadingsThreshold?: number;
}
/**
* The same consistency as {@link rollupConsistency}, from readings already
* folded per local day. Every figure here is a function of each day's mean
* and of the reading count, so a reader that folds in SQL hands over one row
* per day instead of every reading and gets the same answer.
*/
export function rollupConsistencyFromDays({
byDay,
readingCount,
classify,
timezone,
now,
totalReadingsThreshold = 3,
}: RollupConsistencyInput): TargetConsistency {
if (events.length < totalReadingsThreshold) {
const partial = computeStrip(events, classify, timezone, now);
}: RollupDaySumsInput): TargetConsistency {
if (readingCount < totalReadingsThreshold) {
const partial = computeStrip(byDay, classify, timezone, now);
return {
...EMPTY_CONSISTENCY,
...partial,
@@ -91,15 +127,7 @@ export function rollupConsistency({
};
}
const byDay = new Map<string, { sum: number; count: number }>();
for (const event of events) {
const key = userDayKey(event.measuredAt, timezone);
const bucket = byDay.get(key) ?? { sum: 0, count: 0 };
bucket.sum += event.value;
bucket.count += 1;
byDay.set(key, bucket);
}
const strip = computeStrip(events, classify, timezone, now);
const strip = computeStrip(byDay, classify, timezone, now);
let daysInRange30d = 0;
let daysLogged30d = 0;
@@ -136,7 +164,7 @@ export function rollupConsistency({
lastMetGoalAt,
streakDays,
insufficientData:
events.length < totalReadingsThreshold || strip.daysLogged7d < 1,
readingCount < totalReadingsThreshold || strip.daysLogged7d < 1,
consistency7d: strip.consistency7d,
};
}
+35 -21
View File
@@ -4,8 +4,9 @@ import {
type GlucoseContextBucket,
} from "@/lib/glucose";
import { resolveGlucoseTarget } from "./glucose-targets";
import { makeRangeClassifier, rollupConsistency } from "./consistency";
import type { TargetGlucoseRow, TargetItem, TargetProfile } from "./types";
import { makeRangeClassifier, rollupConsistencyFromDays } from "./consistency";
import type { TargetGlucoseContextSummary } from "./glucose-read";
import type { TargetItem, TargetProfile } from "./types";
const LABEL_BY_CONTEXT: Record<GlucoseContextBucket, string> = {
FASTING: "targets.glucoseFasting",
@@ -16,38 +17,53 @@ const LABEL_BY_CONTEXT: Record<GlucoseContextBucket, string> = {
};
interface GlucoseTargetsInput {
rows: TargetGlucoseRow[];
/**
* One summary per stored meal context: the newest reading of the year and
* the last thirty days per local day (`readGlucoseTargetSummaries`).
*/
summaries: TargetGlucoseContextSummary[];
profile: TargetProfile;
timezone: string;
now: Date;
}
export function buildGlucoseTargets({
rows,
summaries,
profile,
timezone,
now,
}: GlucoseTargetsInput): TargetItem[] {
const targets: TargetItem[] = [];
const unit = resolveGlucoseUnit(profile.glucoseUnit);
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
// #943 — the untagged bucket rides the same loop. Iterating the four named
// contexts alone left an account whose source writes no meal-time tag with
// no glucose target at all, the same gap the dashboard tile had.
for (const [context, contextRows] of groupByGlucoseContext(
rows,
(row) => row.glucoseContext,
for (const [context, contextSummaries] of groupByGlucoseContext(
summaries,
(summary) => summary.glucoseContext,
)) {
const latest = contextRows[0].value;
const recent = contextRows.filter((row) => row.measuredAt >= thirtyDaysAgo);
// A bucket is one stored context today; folding several keeps the newest
// reading and adds the days up, should two ever share a bucket.
const newest = contextSummaries.reduce((a, b) =>
b.latestAt > a.latestAt ? b : a,
);
const latest = newest.latest;
const recentByDay = new Map<string, { sum: number; count: number }>();
let recentCount = 0;
let recentSum = 0;
for (const summary of contextSummaries) {
recentCount += summary.recentCount;
for (const [day, bucket] of summary.recentByDay) {
const current = recentByDay.get(day) ?? { sum: 0, count: 0 };
current.sum += bucket.sum;
current.count += bucket.count;
recentByDay.set(day, current);
recentSum += bucket.sum;
}
}
const average30 =
recent.length > 0
? Math.round(
(recent.reduce((sum, row) => sum + row.value, 0) / recent.length) *
10,
) / 10
: null;
recentCount > 0 ? Math.round((recentSum / recentCount) * 10) / 10 : null;
const resolved = resolveGlucoseTarget({
context,
hasDiabetes: profile.hasDiabetes,
@@ -97,11 +113,9 @@ export function buildGlucoseTargets({
: resolved.source === "ADA goal (diabetes)"
? "ADA goal (diabetes)"
: "ADA 2024 / DDG",
...rollupConsistency({
events: recent.map((row) => ({
measuredAt: row.measuredAt,
value: row.value,
})),
...rollupConsistencyFromDays({
byDay: recentByDay,
readingCount: recentCount,
classify: makeRangeClassifier(
range,
effectiveRange
+148
View File
@@ -0,0 +1,148 @@
/**
* The glucose rows the targets page needs, folded in Postgres.
*
* The glucose targets used to read every glucose reading of the last year and
* keep three things from them per meal context: the newest value, and for the
* last thirty days each local day's mean and the number of readings. A sensor
* that reports every five minutes puts 105 000 readings in that year, and the
* targets page is read on every visit, on the web and in the app. So the year
* is reduced to one row per context (`DISTINCT ON`) and the thirty days to one
* row per context and local day, and only those rows cross the wire.
*
* Output matches {@link foldGlucoseTargetRows} over the raw readings: the same
* newest value per context (ties broken by id, newest first), and the same
* per-day sums and counts, with days cut in the zone the caller passes by the
* expression every other day fold uses.
*/
import { Prisma, type PrismaClient } from "@/generated/prisma/client";
import type { GlucoseContext } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import { isValidTimezone, userDayKey } from "@/lib/tz/format";
import type { TargetGlucoseRow } from "./types";
/** One meal context's newest reading and its last thirty days, per day. */
export interface TargetGlucoseContextSummary {
glucoseContext: GlucoseContext | null;
latest: number;
latestAt: Date;
/** Local day → the day's readings as sum and count, since `recentSince`. */
recentByDay: Map<string, { sum: number; count: number }>;
/** Readings behind `recentByDay`. */
recentCount: number;
}
/**
* The in-memory fold over raw readings, newest first. Pure; the reference the
* SQL reader is tested against.
*/
export function foldGlucoseTargetRows(
rows: readonly TargetGlucoseRow[],
recentSince: Date,
timeZone: string,
): TargetGlucoseContextSummary[] {
const byContext = new Map<string, TargetGlucoseContextSummary>();
for (const row of rows) {
const key = row.glucoseContext ?? "";
let summary = byContext.get(key);
if (!summary) {
summary = {
glucoseContext: row.glucoseContext,
latest: row.value,
latestAt: row.measuredAt,
recentByDay: new Map(),
recentCount: 0,
};
byContext.set(key, summary);
}
if (row.measuredAt < recentSince) continue;
const day = userDayKey(row.measuredAt, timeZone);
const bucket = summary.recentByDay.get(day) ?? { sum: 0, count: 0 };
bucket.sum += row.value;
bucket.count += 1;
summary.recentByDay.set(day, bucket);
summary.recentCount += 1;
}
return [...byContext.values()];
}
export async function readGlucoseTargetSummaries(opts: {
userId: string;
/** Inclusive lower bound for the newest reading per context. */
since: Date;
/** Inclusive lower bound for the per-day fold. */
recentSince: Date;
/** IANA zone the day boundary is cut in. */
timeZone: string;
db?: Pick<PrismaClient, "$queryRaw">;
}): Promise<TargetGlucoseContextSummary[]> {
const db = opts.db ?? prisma;
const timeZone = isValidTimezone(opts.timeZone) ? opts.timeZone : "UTC";
const [latestRows, dayRows] = await Promise.all([
db.$queryRaw<
Array<{
glucose_context: GlucoseContext | null;
value: number;
measured_at: Date;
}>
>(Prisma.sql`
SELECT DISTINCT ON (m."glucose_context")
m."glucose_context" AS glucose_context,
m."value" AS value,
m."measured_at" AS measured_at
FROM measurements m
WHERE m."user_id" = ${opts.userId}
AND m."type" = 'BLOOD_GLUCOSE'::measurement_type
AND m."deleted_at" IS NULL
AND m."measured_at" >= ${opts.since}
ORDER BY m."glucose_context", m."measured_at" DESC, m."id" DESC
`),
db.$queryRaw<
Array<{
glucose_context: GlucoseContext | null;
day: string;
n: number;
sum: number;
}>
>(Prisma.sql`
WITH src AS (
SELECT
m."glucose_context" AS glucose_context,
to_char((m."measured_at" AT TIME ZONE 'UTC') AT TIME ZONE ${timeZone}, 'YYYY-MM-DD') AS day,
m."value" AS value
FROM measurements m
WHERE m."user_id" = ${opts.userId}
AND m."type" = 'BLOOD_GLUCOSE'::measurement_type
AND m."deleted_at" IS NULL
AND m."measured_at" >= ${opts.recentSince}
)
SELECT
glucose_context,
day,
COUNT(*)::int AS n,
SUM(value)::double precision AS sum
FROM src
GROUP BY glucose_context, day
`),
]);
const byContext = new Map<string, TargetGlucoseContextSummary>();
for (const row of latestRows) {
byContext.set(row.glucose_context ?? "", {
glucoseContext: row.glucose_context,
latest: Number(row.value),
latestAt: row.measured_at,
recentByDay: new Map(),
recentCount: 0,
});
}
for (const row of dayRows) {
// Every recent reading is also inside the year, so its context has a
// newest row unless `recentSince` predates `since`, which no caller does.
const summary = byContext.get(row.glucose_context ?? "");
if (!summary) continue;
const n = Number(row.n);
summary.recentByDay.set(row.day, { sum: Number(row.sum), count: n });
summary.recentCount += n;
}
return [...byContext.values()];
}
+15 -8
View File
@@ -13,7 +13,10 @@ import {
classifyPulseByTarget,
getPersonalizedPulseTarget,
} from "@/lib/analytics/pulse-targets";
import { resolveRestingPulseSeries } from "@/lib/analytics/resting-pulse";
import {
mergeRestingWithProxy,
type PulseSample,
} from "@/lib/analytics/resting-pulse";
import { getBodyFatTargetRange } from "@/lib/analytics/value-bands";
import { binaryReferenceSex, type ProfileSex } from "@/lib/profile/sex";
import { userDayKey } from "@/lib/tz/resolver";
@@ -38,7 +41,15 @@ export interface BloodPressureTargetRange {
}
interface VitalTargetsInput {
/** The last thirty days of every vital type except `PULSE`. */
recentMeasurements: TargetMeasurement[];
/**
* The resting-pulse proxy over the same thirty days, one point per local
* day, folded from raw `PULSE` in Postgres (`readRestingPulseProxy`). Raw
* heart rate is never read here: a watch that records it once a minute puts
* 43 000 readings in thirty days, and the card needs one figure per day.
*/
restingPulseProxy: PulseSample[];
latestByType: TargetValueByType;
average30ByType: TargetValueByType;
heightCm: number | null;
@@ -149,6 +160,7 @@ function buildBpPairsByDay(
export function buildVitalTargets({
recentMeasurements,
restingPulseProxy,
latestByType,
average30ByType,
heightCm,
@@ -285,19 +297,14 @@ export function buildVitalTargets({
}
const pulseTarget = getPersonalizedPulseTarget(age, referenceSex);
const restingResolved = resolveRestingPulseSeries({
const restingResolved = mergeRestingWithProxy({
restingSamples: recentMeasurements
.filter((measurement) => measurement.type === "RESTING_HEART_RATE")
.map((measurement) => ({
measuredAt: measurement.measuredAt,
value: measurement.value,
})),
pulseSamples: recentMeasurements
.filter((measurement) => measurement.type === "PULSE")
.map((measurement) => ({
measuredAt: measurement.measuredAt,
value: measurement.value,
})),
proxySamples: restingPulseProxy,
dayKeyOf: (date) => userDayKey(date, timezone),
});
const restingEvents = restingResolved.series;