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

This commit is contained in:
Marc-André Bombeck committed 2026-10-01 10:34:17 +02:00
commit da8cc7a6ee
74 files changed
+2304 -292

No files matched your search

@@ -227,6 +227,30 @@ describe("renderDoctorReportPdfBytes", () => {
expect(text).not.toContain("450 h");
});
it("prints the raw glucose row in the owner's unit, like the glucose panel", async () => {
// The measurement table used to take BLOOD_GLUCOSE's canonical unit and
// number, so an mmol/L account read "99.0 mg/dL" two lines above its own
// context rows in mmol/L.
const data = makeData({
glucoseUnit: "mmol/L",
stats: {
...makeData().stats,
BLOOD_GLUCOSE: { avg: 108, min: 90, max: 126, count: 9, latest: 99 },
},
});
const bytes = renderDoctorReportPdfBytes(data, {
timeFormat: "AUTO",
dateFormat: "AUTO",
t: getServerTranslator("en").t,
locale: "en",
now: FIXED_NOW,
});
const text = await extractText(bytes);
expect(text).toContain("5.5 mmol/L");
expect(text).toContain("6.0 mmol/L");
expect(text).not.toContain("mg/dL");
});
it("omits the sleep vitals row when there are no sleep stats", async () => {
const bytes = renderDoctorReportPdfBytes(makeData(), {
timeFormat: "AUTO",
@@ -9,6 +9,29 @@ import { describe, expect, it } from "vitest";
import { buildInterpretationBlock } from "../interpretation-block";
describe("buildInterpretationBlock", () => {
it("classifies on the canonical value but prints in the reader's unit", () => {
const toF = (c: number) => Math.round((c * 1.8 + 32) * 10) / 10;
const block = buildInterpretationBlock({
metricKey: "BODY_TEMPERATURE",
value: 36.8,
sex: null,
locale: "en",
display: { unit: "°F", convert: toF },
});
expect(block).toBeDefined();
expect(block).toContain("Current value 98.2 °F");
expect(block).not.toContain("°C");
// Same band as the canonical block names.
const canonical = buildInterpretationBlock({
metricKey: "BODY_TEMPERATURE",
value: 36.8,
sex: null,
locale: "en",
})!;
const band = (text: string) => text.match(/is in the "([^"]+)" band/)![1];
expect(band(block!)).toBe(band(canonical));
});
it("renders the band position for visceral fat 2.7 (the headline case)", () => {
const en = buildInterpretationBlock({
metricKey: "VISCERAL_FAT",
+21 -11
View File
@@ -130,9 +130,17 @@ function proximityPhrase(
*/
export function buildInterpretationBlock(args: {
metricKey: string;
/** The value in the guideline's own (canonical) unit — what is classified. */
value: number;
sex: "MALE" | "FEMALE" | null | undefined;
locale: Locale;
/**
* Print the block in the reader's unit. Classification always runs on the
* canonical value against the canonical bands; only the printed numbers and
* the unit symbol are converted, so a prompt whose snapshot reads °F does
* not carry a band table in °C beside it.
*/
display?: { unit: string; convert: (canonical: number) => number };
}): string | undefined {
const resolved = resolveInterpretation(args.metricKey, args.sex ?? null);
if (!resolved) return undefined;
@@ -140,22 +148,24 @@ export function buildInterpretationBlock(args: {
const loc: "en" | "de" = instructionLocale(args.locale);
const pos = classifyBandPosition(args.value, resolved.bands);
const rows = resolved.bands
const show = (n: number) => (args.display ? args.display.convert(n) : n);
const unit = args.display ? args.display.unit : resolved.unit;
const shownBands = resolved.bands.map((band) => ({
...band,
upTo: band.upTo === null ? null : show(band.upTo),
}));
const rows = shownBands
.map((band, i) =>
bandRow(
band,
i > 0 ? resolved.bands[i - 1].upTo : null,
resolved.unit,
loc,
),
bandRow(band, i > 0 ? shownBands[i - 1].upTo : null, unit, loc),
)
.map((r) => ` - ${r}`)
.join("\n");
const proximity = proximityPhrase(
pos.proximity,
pos.nearestEdge,
resolved.unit,
pos.nearestEdge === null ? null : show(pos.nearestEdge),
unit,
loc,
);
const valence = valencePhrase(pos.band.valence, loc);
@@ -164,14 +174,14 @@ export function buildInterpretationBlock(args: {
if (loc === "en") {
return `INTERPRETATION CONTEXT (guideline bands — computed server-side; state, do NOT recompute):
- Current value ${args.value} ${resolved.unit} is in the "${pos.band.label}" band, and ${proximity}.
- Current value ${show(args.value)} ${unit} is in the "${pos.band.label}" band, and ${proximity}.
- Guideline bands (${resolved.source}; ${direction}):
${rows}
- Values in the "${pos.band.label}" band are considered ${valence} per these guidelines.${caveat}
- Name where the value sits and what that band means in plain words. Judge any trend BY this position: a shift deep inside a favourable band is a footnote; the same shift approaching or crossing a boundary is the headline. Frame consequence without diagnosis ("values in this range are considered …", never "you have / are at risk of …").`;
}
return `EINORDNUNGS-KONTEXT (Leitlinien-Bänder — serverseitig berechnet; nennen, NICHT neu rechnen):
- Der aktuelle Wert ${args.value} ${resolved.unit} liegt im Band "${pos.band.label}" und ${proximity}.
- Der aktuelle Wert ${show(args.value)} ${unit} liegt im Band "${pos.band.label}" und ${proximity}.
- Leitlinien-Bänder (${resolved.source}; ${direction}):
${rows}
- Werte im Band "${pos.band.label}" gelten laut diesen Leitlinien als ${valence}.${caveat}
@@ -240,6 +240,7 @@ function score(args: {
timezone: "UTC",
sourcePriorityJson: null,
thresholdsJson: null,
glucoseUnit: "mg/dL" as const,
},
modules: args.modules,
healthScoreConfigJson: args.healthScoreConfigJson,
@@ -318,6 +318,7 @@ function scoreInput(healthScoreConfigJson: unknown) {
timezone: "UTC",
sourcePriorityJson: null,
thresholdsJson: null,
glucoseUnit: "mg/dL" as const,
},
modules: {
glucose: true,
@@ -14,6 +14,7 @@ const live = {
source: "live" as const,
readFailed: false,
timezone: "Europe/Berlin",
glucoseUnit: "mg/dL" as const,
};
function days(count: number, value: number) {
@@ -160,6 +161,41 @@ describe("reference-score pillars", () => {
expect(eligible.status).toBe("ok");
});
it("writes the fasting labels in the reader's glucose unit, value and band canonical", () => {
const fasting = days(8, 99).map((point) => ({
value: point.value,
at: new Date(`${point.day}T08:00:00Z`),
source: "APPLE_HEALTH",
}));
const mmol = computeGlycaemiaPillar({
...live,
glucoseUnit: "mmol/L",
asOf: NOW,
hba1c: [],
fastingGlucose: fasting,
});
const mgdl = computeGlycaemiaPillar({
...live,
asOf: NOW,
hba1c: [],
fastingGlucose: fasting,
});
expect(mmol.status).toBe("ok");
expect(mgdl.status).toBe("ok");
if (mmol.status !== "ok" || mgdl.status !== "ok") return;
// These labels reach the app as finished text.
expect(mmol.value.observed.label).toBe("Fasting median 5.5 mmol/L");
expect(mmol.value.reference.label).toBe("3.9–5.5 mmol/L fasting");
expect(mgdl.value.observed.label).toBe("Fasting median 99 mg/dL");
expect(mgdl.value.reference.label).toBe("70–99 mg/dL fasting");
// The score and the numbers the web converts from do not move.
expect(mmol.value.observed.value).toBe(99);
expect(mmol.value.observed.unit).toBe("mg/dL");
expect(mmol.value.reference.low).toBe(70);
expect(mmol.value.reference.high).toBe(99);
expect(mmol.value.score).toBe(mgdl.value.score);
});
it("does not use fasting fallback when the preferred lab read failed", () => {
const result = computeGlycaemiaPillar({
...live,
@@ -137,6 +137,7 @@ describe("score reader bounds and source parity", () => {
timezone: "Europe/Berlin",
sourcePriorityJson: null,
thresholdsJson: null,
glucoseUnit: "mg/dL" as const,
},
modules: {
glucose: true,
@@ -233,6 +233,7 @@ const live = {
source: "live" as const,
readFailed: false,
timezone: "Europe/Berlin",
glucoseUnit: "mg/dL" as const,
};
function days(count: number, value: number) {
+3
View File
@@ -5,6 +5,7 @@ import { getBpTargets } from "@/lib/analytics/bp-targets";
import { resolveModuleMap } from "@/lib/modules/gate";
import { loadUserSourcePriority } from "@/lib/rollups/measurement-read";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import { resolveGlucoseUnit } from "@/lib/glucose";
import { computeAndRecordUserHealthScore } from "./record";
import type { CompositeValue } from "./types";
@@ -23,6 +24,7 @@ export async function computeHealthScoreDerived(
timezone: true,
thresholdsJson: true,
healthScoreConfigJson: true,
glucoseUnit: true,
},
});
const now = new Date();
@@ -59,6 +61,7 @@ export async function computeHealthScoreDerived(
timezone,
sourcePriorityJson,
thresholdsJson: user.thresholdsJson,
glucoseUnit: resolveGlucoseUnit(user.glucoseUnit),
},
modules: {
glucose: modules.glucose !== false,
+6 -2
View File
@@ -1,4 +1,5 @@
import type { Derived } from "@/lib/insights/derived/types";
import { convertGlucose } from "@/lib/glucose";
import type { GlycaemiaPillarInput, PillarValue } from "./types";
import {
@@ -153,10 +154,13 @@ export function computeGlycaemiaPillar(
FASTING_GLUCOSE_REFERENCE.low,
FASTING_GLUCOSE_REFERENCE.high,
),
// `value`, `unit` and the band stay canonical: the score is computed on
// them and the web converts from them. The labels are finished text a
// client prints as-is, so they are written in the reader's unit.
observed: {
value: observed,
unit: "mg/dL",
label: `Fasting median ${Math.round(observed)} mg/dL`,
label: `Fasting median ${convertGlucose(observed, input.glucoseUnit)} ${input.glucoseUnit}`,
asOf: fasting.at(-1)!.at.toISOString(),
sources: uniqueSources(fasting.map((row) => row.source)),
},
@@ -164,7 +168,7 @@ export function computeGlycaemiaPillar(
kind: "clinical-threshold",
low: FASTING_GLUCOSE_REFERENCE.low,
high: FASTING_GLUCOSE_REFERENCE.high,
label: `${FASTING_GLUCOSE_REFERENCE.low}–${FASTING_GLUCOSE_REFERENCE.high} mg/dL fasting`,
label: `${convertGlucose(FASTING_GLUCOSE_REFERENCE.low, input.glucoseUnit)}–${convertGlucose(FASTING_GLUCOSE_REFERENCE.high, input.glucoseUnit)} ${input.glucoseUnit} fasting`,
source: "ADA 2025; Selvin 2010",
},
noiseFloor: Math.max(1, Math.abs(ceilingScore - floorScore)),
+8
View File
@@ -42,6 +42,7 @@ import type { HealthScoreReport, PillarInputs, ScorePillarId } from "./types";
import { computeWeightGoal } from "./weight-goal";
import { DAY_MS, uniqueSources } from "./shared";
import type { DerivedProvenanceSource } from "@/lib/insights/derived/types";
import type { GlucoseUnit } from "@/lib/glucose";
const HISTORY_OFFSET_DAYS = 14;
const SCORE_READ_DAYS = 365 + HISTORY_OFFSET_DAYS;
@@ -52,6 +53,12 @@ export interface ScoreReaderProfile {
timezone: string;
sourcePriorityJson: unknown;
thresholdsJson: unknown;
/**
* The record's glucose unit, for the glycaemia pillar's display labels.
* Required: those labels are served as finished text (the app prints them
* verbatim), and a caller that forgets the unit must not get mg/dL.
*/
glucoseUnit: GlucoseUnit;
}
export interface UserHealthScoreInput {
@@ -513,6 +520,7 @@ function scoreInputsFor(args: {
},
GLYCAEMIA: {
source: "live",
glucoseUnit: input.profile.glucoseUnit,
readFailed:
(!input.modules.glucose || !args.glucose.ok) &&
(!input.modules.labs || !args.labs.ok),
+7
View File
@@ -8,6 +8,7 @@ import type {
// runtime cycle. The tier's definition belongs beside the rule that
// produces it; its NAME belongs here, where the wire shape is declared.
import type { ScoreBreadthTier } from "./breadth";
import type { GlucoseUnit } from "@/lib/glucose";
/**
* The scoring method's identity.
@@ -346,6 +347,12 @@ export interface GlucoseReading {
export interface GlycaemiaPillarInput extends DomainReadState {
asOf: Date;
/**
* The unit the fasting-glucose labels are written in. The scored value,
* its `unit` and the reference band stay canonical mg/dL; only the two
* human-readable labels follow the reader.
*/
glucoseUnit: GlucoseUnit;
hba1cReadFailed?: boolean;
fastingReadFailed?: boolean;
hba1c: HbA1cReading[];
+2 -1
View File
@@ -49,7 +49,7 @@ import {
GLUCOSE_PANEL_WINDOW_DAYS,
type GlucoseClinicalMetrics,
} from "@/lib/analytics/glucose-metrics";
import { groupByGlucoseContext } from "@/lib/glucose";
import { groupByGlucoseContext, resolveGlucoseUnit } from "@/lib/glucose";
import {
computeBpInTargetFastPath,
type BpInTargetEnvelope,
@@ -788,6 +788,7 @@ async function buildExtras(
timezone: userTz,
sourcePriorityJson: scoreSourcePriority,
thresholdsJson: user.thresholdsJson,
glucoseUnit: resolveGlucoseUnit(user.glucoseUnit),
},
modules: {
glucose: modules.glucose !== false,
+11 -25
View File
@@ -19,7 +19,11 @@ import {
REPORT_GROUPS,
} from "./report-selection/catalogue";
import { getUnitForType } from "./validations/measurement";
import {
DOCTOR_REPORT_TYPE_UNIT_KEYS,
reportStatUnit,
} from "./doctor-report/stat-display";
import { resolveGlucoseUnit } from "./glucose";
import {
makeFormatters,
type DateFormatPreference,
@@ -175,18 +179,9 @@ export interface DoctorReportRenderOptions {
includeCharts?: boolean;
}
export const DOCTOR_REPORT_TYPE_UNIT_KEYS: Record<string, string | null> = {
WEIGHT: "kg",
BLOOD_PRESSURE_SYS: "mmHg",
BLOOD_PRESSURE_DIA: "mmHg",
PULSE: "bpm",
BODY_FAT: "%",
SLEEP_DURATION: "h",
ACTIVITY_STEPS: null, // translated unit
TOTAL_BODY_WATER: "kg",
BONE_MASS: "kg",
OXYGEN_SATURATION: "%",
};
// The unit map moved beside the clinician view's reader of it; re-exported so
// the enum-coverage test keeps one import.
export { DOCTOR_REPORT_TYPE_UNIT_KEYS };
/**
* The measurement table is driven by the selection, not by a whitelist.
@@ -238,18 +233,9 @@ export function buildDoctorReportPdfDocument(
const footerTz =
userTz && isValidTimezone(userTz) ? userTz : DEFAULT_TIMEZONE;
const unitFor = (type: string): string => {
const staticUnit = DOCTOR_REPORT_TYPE_UNIT_KEYS[type];
if (staticUnit === null && type === "ACTIVITY_STEPS") {
return t("doctorReport.unitSteps");
}
if (staticUnit !== undefined && staticUnit !== null) return staticUnit;
// Every other type falls back to the canonical unit the measurement
// validation layer already records. A type with no recorded unit prints
// none — an absent unit is absent, not a guessed symbol.
const canonical = getUnitForType(type);
return canonical === "unknown" ? "" : canonical;
};
const glucoseUnit = resolveGlucoseUnit(data.glucoseUnit ?? null);
const unitFor = (type: string): string =>
reportStatUnit(type, glucoseUnit, t);
const doc = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4" });
patchPdfTextSanitiser(doc);
@@ -2,6 +2,7 @@ import type { jsPDF } from "jspdf";
import { GLUCOSE_CONTEXT_BUCKETS } from "@/lib/glucose";
import autoTable from "jspdf-autotable";
import { convertGlucose, resolveGlucoseUnit } from "../glucose";
import { reportStatValue } from "../doctor-report/stat-display";
import type { MeasurementType } from "@/generated/prisma/client";
import { MEASUREMENT_TYPE_LABEL_KEYS } from "../measurements/type-label-keys";
import {
@@ -235,12 +236,9 @@ export function buildMeasurementsChartsSection(
const s = data.stats[type];
if (!s) continue;
const unit = unitFor(type);
// SLEEP_DURATION stats are per-night asleep totals in MINUTES (the data
// layer reconstructs them for exactly this row); the vitals unit is
// hours (`h`), so convert to keep value and unit consistent — the same
// hours value the FHIR sleep Observation emits.
const conv =
type === "SLEEP_DURATION" ? (v: number) => v / 60 : (v: number) => v;
// Sleep minutes print as hours and glucose in the owner's unit; the
// clinician view reads the same helper, so the two cannot drift.
const conv = (v: number) => reportStatValue(type, v, glucoseUnit);
groupRows.push([
t(MEASUREMENT_TYPE_LABEL_KEYS[type as MeasurementType] ?? ""),
`${num(conv(s.latest))} ${unit}`.trim(),
+79
View File
@@ -0,0 +1,79 @@
/**
* How a measurement statistic reads in the clinician-facing artefacts: the
* PDF report and the shared clinician view.
*
* Both describe the same record to the same reader, so they take the unit and
* the displayed number from here and nowhere else. Before this module the PDF
* carried its own unit map and the clinician view printed bare numbers, so a
* doctor opening a share link read "latest 5.8 (avg 6.1, range 4.9–7.4)" with
* no unit at all, and for an account on mmol/L the glucose rows of the PDF's
* measurement table still printed raw mg/dL beside a mmol/L glucose panel.
*
* The policy, which `display-transform.ts` states for the metric/imperial
* preference: a document handed to a clinician stays SI for mass, length and
* temperature regardless of the owner's imperial preference. Glucose is the
* exception, because mmol/L versus mg/dL is not an imperial question — it is
* the clinical convention of the country the record lives in — so glucose
* follows the owner's `glucoseUnit` here as it does everywhere a person reads
* it.
*/
import { convertGlucose, type GlucoseUnit } from "@/lib/glucose";
import { getUnitForType } from "@/lib/validations/measurement";
/**
* Report-specific unit symbols, where the report's own reading differs from
* the validation layer's canonical unit. `null` marks a unit that has to be
* translated (steps). Everything absent falls back to `getUnitForType`.
*/
export const DOCTOR_REPORT_TYPE_UNIT_KEYS: Record<string, string | null> = {
WEIGHT: "kg",
BLOOD_PRESSURE_SYS: "mmHg",
BLOOD_PRESSURE_DIA: "mmHg",
PULSE: "bpm",
BODY_FAT: "%",
SLEEP_DURATION: "h",
ACTIVITY_STEPS: null, // translated unit
TOTAL_BODY_WATER: "kg",
BONE_MASS: "kg",
OXYGEN_SATURATION: "%",
};
/**
* The unit symbol a report statistic of `type` is printed with.
*
* `translate` resolves the one translated unit (steps). A type with no
* recorded unit prints none — an absent unit is absent, not a guessed symbol.
*/
export function reportStatUnit(
type: string,
glucoseUnit: GlucoseUnit,
translate: (key: string) => string,
): string {
if (type === "BLOOD_GLUCOSE") return glucoseUnit;
const staticUnit = DOCTOR_REPORT_TYPE_UNIT_KEYS[type];
if (staticUnit === null && type === "ACTIVITY_STEPS") {
return translate("doctorReport.unitSteps");
}
if (staticUnit !== undefined && staticUnit !== null) return staticUnit;
const canonical = getUnitForType(type);
return canonical === "unknown" ? "" : canonical;
}
/**
* The number a report statistic of `type` is printed as, in the unit
* {@link reportStatUnit} names.
*
* SLEEP_DURATION statistics are per-night asleep totals in minutes (the data
* layer reconstructs them for exactly this row) while the unit is hours, so
* they are divided — the same hours value the FHIR sleep Observation emits.
* Glucose is stored in mg/dL and converted to the owner's unit.
*/
export function reportStatValue(
type: string,
value: number,
glucoseUnit: GlucoseUnit,
): number {
if (type === "SLEEP_DURATION") return value / 60;
if (type === "BLOOD_GLUCOSE") return convertGlucose(value, glucoseUnit);
return value;
}
@@ -507,3 +507,134 @@ describe("generateMetricStatus — generation path", () => {
expect(result.text).toContain("Steady.");
});
});
describe("generateMetricStatus — the note is written in the reader's units", () => {
function seed(values: (day: number) => number, days = 120) {
const now = new Date();
const records: Array<{ value: number; measuredAt: Date }> = [];
for (let day = 0; day < days; day++) {
records.push({
value: values(day),
measuredAt: new Date(now.getTime() - day * dayMs),
});
}
vi.mocked(prisma.measurement.count).mockResolvedValue(days as never);
vi.mocked(prisma.measurement.findMany).mockResolvedValue(records as never);
}
function snapshotOf(userPrompt: string) {
return JSON.parse(userPrompt.match(/\{[\s\S]*\}/)![0]);
}
it("states glucose, its band and its series in mmol/L for an mmol/L reader", async () => {
seed((day) => 99 + (day % 4) * 3);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: null,
gender: null,
unitPreference: "metric",
glucoseUnit: "mmol/L",
} as never);
const captured = { systemPrompt: null, userPrompt: null } as {
systemPrompt: string | null;
userPrompt: string | null;
};
stubCompletion('{"summary":"Steady."}', captured);
await generateMetricStatus({
metric: "BLOOD_GLUCOSE",
userId: "user-1",
locale: "en",
});
expect(captured.systemPrompt).toContain("unit: mmol/L");
// 70–140 mg/dL is 3.9–7.8 mmol/L.
expect(captured.systemPrompt).toContain("3.9–7.8 mmol/L");
// The shared safety contract quotes its own fixed thresholds; the metric
// block itself must not carry the canonical band.
expect(captured.systemPrompt).not.toContain("70–140 mg/dL");
const snapshot = snapshotOf(captured.userPrompt!);
expect(snapshot.metric.unit).toBe("mmol/L");
expect(snapshot.metric.normalRange).toMatchObject({ low: 3.9, high: 7.8 });
const recentMeans = snapshot.BLOOD_GLUCOSE.series.recent.map(
(b: { mean: number }) => b.mean,
);
expect(recentMeans.length).toBeGreaterThan(0);
for (const mean of recentMeans) {
expect(mean).toBeGreaterThan(5);
expect(mean).toBeLessThan(6.5);
}
expect(captured.userPrompt).not.toContain("mg/dL");
});
it("states body temperature in °F for an imperial reader, guideline band included", async () => {
seed((day) => 36.6 + (day % 3) * 0.1);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: null,
gender: null,
unitPreference: "imperial",
glucoseUnit: null,
} as never);
const captured = { systemPrompt: null, userPrompt: null } as {
systemPrompt: string | null;
userPrompt: string | null;
};
stubCompletion('{"summary":"Steady."}', captured);
await generateMetricStatus({
metric: "BODY_TEMPERATURE",
userId: "user-1",
locale: "en",
});
expect(captured.systemPrompt).toContain("unit: °F");
expect(captured.systemPrompt).not.toContain("36.1–37.2 °C");
// The interpretation block classifies in °C but prints in °F.
expect(captured.userPrompt).toContain("INTERPRETATION CONTEXT");
expect(captured.userPrompt).not.toContain("°C");
expect(snapshotOf(captured.userPrompt!).metric.unit).toBe("°F");
});
it("writes the no-provider floor in the reader's glucose unit", async () => {
seed((day) => 99 + (day % 4) * 3);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: null,
gender: null,
unitPreference: "metric",
glucoseUnit: "mmol/L",
} as never);
vi.mocked(runStatusCompletion).mockResolvedValue({ kind: "none" } as never);
const result = await generateMetricStatus({
metric: "BLOOD_GLUCOSE",
userId: "user-1",
locale: "en",
});
expect(result.text).toMatch(/\d\.\d mmol\/L/);
expect(result.text).not.toContain("mg/dL");
});
it("leaves a metric reader on the default units byte-identical", async () => {
seed((day) => 99 + (day % 4) * 3);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
dateOfBirth: null,
gender: null,
unitPreference: null,
glucoseUnit: null,
} as never);
const captured = { systemPrompt: null, userPrompt: null } as {
systemPrompt: string | null;
userPrompt: string | null;
};
stubCompletion('{"summary":"Steady."}', captured);
await generateMetricStatus({
metric: "BLOOD_GLUCOSE",
userId: "user-1",
locale: "en",
});
expect(captured.systemPrompt).toContain("70–140 mg/dL");
expect(snapshotOf(captured.userPrompt!).metric.unit).toBe("mg/dL");
});
});
@@ -106,13 +106,31 @@ describe("computeTrendDescriptor", () => {
});
describe("numericDescriptorCopy", () => {
it("states a preference-bound slot in the unit the caller resolves", () => {
const d = computeTrendDescriptor(series([181.6, 178.5]), {
absoluteFloor: 0.66,
relativeFloor: 0.01,
decimals: 1,
})!;
const copy = numericDescriptorCopy("weight", d, (type) =>
type === "WEIGHT" ? "lb" : "?",
);
expect(copy?.params.unit).toBe(" lb");
expect(TREND_SLOT_DESCRIPTOR_META.distance.unitType).toBe(
"WALKING_RUNNING_DISTANCE",
);
expect(TREND_SLOT_DESCRIPTOR_META.body_temp.unitType).toBe(
"BODY_TEMPERATURE",
);
});
it("resolves the rising template with a signed delta and spaced unit", () => {
const d = computeTrendDescriptor(series([120, 128]), {
absoluteFloor: 2,
relativeFloor: 0.02,
decimals: 0,
})!;
const copy = numericDescriptorCopy("bp", d);
const copy = numericDescriptorCopy("bp", d, () => "unused");
expect(copy?.key).toBe("insights.trendDescriptor.rising");
expect(copy?.params.delta).toBe("+8");
expect(copy?.params.unit).toBe(" mmHg");
@@ -124,7 +142,7 @@ describe("numericDescriptorCopy", () => {
relativeFloor: 0.05,
decimals: 0,
})!;
const copy = numericDescriptorCopy("steps", d);
const copy = numericDescriptorCopy("steps", d, () => "unused");
expect(copy?.key).toBe("insights.trendDescriptor.rising");
expect(copy?.params.unit).toBe("");
});
@@ -135,14 +153,14 @@ describe("numericDescriptorCopy", () => {
relativeFloor: 0.01,
decimals: 1,
})!;
const copy = numericDescriptorCopy("weight", d);
const copy = numericDescriptorCopy("weight", d, () => "kg");
expect(copy?.key).toBe("insights.trendDescriptor.falling");
expect(copy?.params.delta).toBe("−1.4");
});
it("returns null for a slot with no numeric meta (mood)", () => {
const d = computeTrendDescriptor(series([3, 4]), MOOD_DESCRIPTOR_CONFIG)!;
expect(numericDescriptorCopy("mood", d)).toBeNull();
expect(numericDescriptorCopy("mood", d, () => "")).toBeNull();
});
it("covers every numeric slot in the descriptor meta", () => {
@@ -154,7 +172,7 @@ describe("numericDescriptorCopy", () => {
relativeFloor: 0,
decimals: 1,
})!;
expect(numericDescriptorCopy(metric, d)).not.toBeNull();
expect(numericDescriptorCopy(metric, d, () => "u")).not.toBeNull();
}
});
});
@@ -0,0 +1,60 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: vi.fn() },
insightNarrative: { findMany: vi.fn() },
},
}));
vi.mock("@/lib/insights/status-invalidation", () => ({
enqueueStatusRefillForUser: vi.fn(),
}));
vi.mock("@/lib/jobs/period-narrative-shared", () => ({
enqueueNarrativeWarm: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { enqueueStatusRefillForUser } from "@/lib/insights/status-invalidation";
import { enqueueNarrativeWarm } from "@/lib/jobs/period-narrative-shared";
import { refreshTextsAfterUnitChange } from "../unit-change-refresh";
beforeEach(() => {
vi.resetAllMocks();
});
describe("refreshTextsAfterUnitChange", () => {
it("refills the status cards in the reader's locale and re-warms each stored narrative", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
locale: "de",
} as never);
vi.mocked(enqueueStatusRefillForUser).mockResolvedValue(12);
vi.mocked(prisma.insightNarrative.findMany).mockResolvedValue([
{ period: "week", locale: "de" },
{ period: "month", locale: "en" },
{ period: "year", locale: "de" },
{ period: "week", locale: "xx" },
] as never);
await refreshTextsAfterUnitChange("user-1");
expect(enqueueStatusRefillForUser).toHaveBeenCalledWith("user-1", "de");
expect(enqueueNarrativeWarm).toHaveBeenCalledTimes(2);
expect(enqueueNarrativeWarm).toHaveBeenCalledWith({
userId: "user-1",
period: "week",
locale: "de",
});
expect(enqueueNarrativeWarm).toHaveBeenCalledWith({
userId: "user-1",
period: "month",
locale: "en",
});
});
it("never throws into the preference write", async () => {
vi.mocked(prisma.user.findUnique).mockRejectedValue(new Error("db down"));
await expect(refreshTextsAfterUnitChange("user-1")).resolves.toBe(
undefined,
);
});
});
+29
View File
@@ -598,6 +598,35 @@ export function scaleGradedSeries(
};
}
/**
* Re-express a canonical graded series in a display unit: absolute bucket
* values (`min / max / mean`) take the full affine conversion, the yearly
* slope — a rate, not a level — takes the factor alone, exactly as
* `applyDisplayTransformDelta` treats a delta. Bucket keys and counts are
* untouched. Used where a series is narrated in the reader's unit; the
* series it is built from stays canonical.
*/
export function convertGradedSeries(
series: GradedSeries,
conversion: { factor: number; offset?: number },
digits = 2,
): GradedSeries {
const offset = conversion.offset ?? 0;
const abs = (v: number) => round(v * conversion.factor + offset, digits);
const bucket = <T extends { min: number; max: number; mean: number }>(
b: T,
): T => ({ ...b, min: abs(b.min), max: abs(b.max), mean: abs(b.mean) });
return {
recent: series.recent.map(bucket),
weekly: series.weekly.map(bucket),
monthly: series.monthly.map(bucket),
yearly: series.yearly.map((b) => ({
...bucket(b),
slope: b.slope === null ? null : round(b.slope * conversion.factor, 4),
})),
};
}
/**
* Assembled-snapshot soft char cap, mirroring the Coach's
* `MAX_SNAPSHOT_CHARS` (~24 000 chars ≈ ~6 000 tokens against the
+129 -16
View File
@@ -58,7 +58,9 @@ import { applyPayloadBudget } from "@/lib/insights/bucket-series";
import {
buildGradedSeriesFromPoints,
buildGradedSeriesWithRollups,
convertGradedSeries,
degradeStatusSnapshotToBudget,
type GradedSeries,
} from "@/lib/insights/graded-series";
import {
type SupportedLocale,
@@ -84,6 +86,16 @@ import { hashInsightSnapshot } from "@/lib/insights/snapshot-hash";
import { returnTimeoutFallback } from "@/lib/insights/timeout-fallback";
import { annotate } from "@/lib/logging/context";
import { binaryReferenceSex } from "@/lib/profile/sex";
import {
applyDisplayTransform,
getReadingTransform,
invertDisplayTransform,
isUnitSensitiveType,
resolveUnitPreferences,
transformRescales,
type DisplayTransform,
type UnitPreferences,
} from "@/lib/measurements/display-transform";
export interface MetricStatusResult {
hasProvider: boolean;
@@ -222,9 +234,40 @@ export async function generateMetricStatus(args: {
const user = await prisma.user.findUnique({
where: { id: args.userId },
select: { dateOfBirth: true, gender: true },
select: {
dateOfBirth: true,
gender: true,
unitPreference: true,
glucoseUnit: true,
},
});
// The note is written in the reader's units. The series, the reference band
// and the signal are converted once, here, before any of them reaches the
// prompt or the deterministic floor; the registry entry, the rollups and
// the guideline classification stay canonical. An untransformed metric (and
// every metric on the default preferences that does not rescale) passes
// through unchanged, so its snapshot hash does not move.
const reading = readingDisplay(
meta,
resolveUnitPreferences({
unitPreference: user?.unitPreference,
glucoseUnit: user?.glucoseUnit,
}),
);
const shownMeta: MetricStatusMeta = {
...meta,
unit: reading.unit,
...(meta.normalRange
? {
normalRange: {
low: reading.toDisplay(meta.normalRange.low),
high: reading.toDisplay(meta.normalRange.high),
},
}
: {}),
};
const now = new Date();
// Bounded raw read for the derived recent stats; the monthly/yearly
@@ -295,7 +338,10 @@ export async function generateMetricStatus(args: {
})
.then((r) => r.reverse());
for (const m of rows) {
points.push({ measuredAt: m.measuredAt, value: m.value });
points.push({
measuredAt: m.measuredAt,
value: reading.toDisplay(m.value),
});
}
measurements = rows.map((m) => ({ measuredAt: m.measuredAt }));
}
@@ -309,11 +355,13 @@ export async function generateMetricStatus(args: {
// recent/weekly/monthly/yearly bucket is a night total, not a stage sum.
const graded = isSleep
? buildGradedSeriesFromPoints(points, now, userTz)
: await buildGradedSeriesWithRollups(
args.userId,
meta.measurementType,
now,
userTz,
: reading.convertGraded(
await buildGradedSeriesWithRollups(
args.userId,
meta.measurementType,
now,
userTz,
),
);
const summary = summarizeSeries(
series.daily.map((bucket) => ({ value: bucket.value })),
@@ -344,7 +392,14 @@ export async function generateMetricStatus(args: {
// metric + profile; otherwise keep the existing flat anchor (strictly
// additive, never a regression). Age + sex only — no ancestry/region.
const sharpenedRange = lookupNormalRange(meta.id, ageYears, sex);
const normalRange = sharpenedRange ?? meta.normalRange;
const canonicalRange = sharpenedRange ?? meta.normalRange;
const normalRange = canonicalRange
? {
...canonicalRange,
low: reading.toDisplay(canonicalRange.low),
high: reading.toDisplay(canonicalRange.high),
}
: canonicalRange;
// v1.13.x — the SIGNAL block: the recent-vs-baseline comparison + the
// normal-swing verdict, computed server-side so the model states it rather
@@ -353,7 +408,7 @@ export async function generateMetricStatus(args: {
// when the recent window is empty, in which case it is omitted.
const signal = buildMetricSignal({
metric: meta.displayName,
unit: meta.unit,
unit: shownMeta.unit,
direction: meta.direction,
graded,
normalRange: normalRange ?? null,
@@ -369,7 +424,7 @@ export async function generateMetricStatus(args: {
metric: {
id: meta.id,
displayName: meta.displayName,
unit: meta.unit,
unit: shownMeta.unit,
direction: meta.direction,
...(normalRange ? { normalRange } : {}),
...(sharpenedRange ? { normalRangeSource: "age-sex-adjusted" } : {}),
@@ -477,14 +532,24 @@ export async function generateMetricStatus(args: {
// window exists); absent for uncovered metrics (fail-soft to personal-
// relative). Sex-split bands (waist) resolve only when the profile carries a
// sex.
// The guideline bands are canonical, so the band position is classified on
// the canonical value; the block then prints in the reader's unit.
const interpretationValue = signal?.current ?? latest?.value ?? null;
const interpretationBlock =
interpretationValue !== null
? buildInterpretationBlock({
metricKey: meta.id,
value: interpretationValue,
value: reading.toCanonical(interpretationValue),
sex,
locale,
...(reading.converts
? {
display: {
unit: reading.unit,
convert: reading.toDisplay,
},
}
: {}),
})
: undefined;
@@ -502,9 +567,9 @@ export async function generateMetricStatus(args: {
userId: args.userId,
cacheAction,
capability: "statusText",
systemPrompt: getMetricArchetypeSystemPrompt(meta, locale),
systemPrompt: getMetricArchetypeSystemPrompt(shownMeta, locale),
userPrompt: getMetricArchetypeUserPrompt(
meta,
shownMeta,
snapshotJson,
todayKey,
locale,
@@ -526,7 +591,7 @@ export async function generateMetricStatus(args: {
if (outcome.kind === "none") {
return {
hasProvider: false,
text: getNoKeyMetricStatusText(locale, signal),
text: getNoKeyMetricStatusText(locale, signal, reading.decimals),
cached: true,
updatedAt: null,
};
@@ -537,7 +602,7 @@ export async function generateMetricStatus(args: {
reason: outcome.kind,
userId: args.userId,
todayKey,
stubText: getNoKeyMetricStatusText(locale, signal),
stubText: getNoKeyMetricStatusText(locale, signal, reading.decimals),
});
}
@@ -553,7 +618,7 @@ export async function generateMetricStatus(args: {
reason: "screened",
userId: args.userId,
todayKey,
stubText: getNoKeyMetricStatusText(locale, signal),
stubText: getNoKeyMetricStatusText(locale, signal, reading.decimals),
});
}
const text = screened.text;
@@ -577,3 +642,51 @@ export function resolveMetricStatusLocale(
): SupportedLocale {
return normalizeLocale(locale);
}
/**
* How one metric's numbers are written for this reader: the unit symbol, the
* conversions in both directions, and the decimals a value is read at.
*
* Only a unit-sensitive type (`isUnitSensitiveType`: glucose and the
* metric/imperial set) converts; every other metric keeps its registry unit
* and its stored numbers. A transform that does not rescale (`converts`
* false) is the identity, so the default preferences leave a snapshot
* byte-identical for the metrics whose registry unit already is the display
* unit.
*/
function readingDisplay(
meta: MetricStatusMeta,
preferences: UnitPreferences,
): {
unit: string;
decimals: number | undefined;
converts: boolean;
toDisplay: (canonical: number) => number;
toCanonical: (display: number) => number;
convertGraded: (series: GradedSeries) => GradedSeries;
} {
if (!isUnitSensitiveType(meta.measurementType)) {
return {
unit: meta.unit,
decimals: undefined,
converts: false,
toDisplay: (v) => v,
toCanonical: (v) => v,
convertGraded: (series) => series,
};
}
const transform: DisplayTransform = getReadingTransform(
meta.measurementType,
preferences,
);
const converts = transformRescales(transform);
return {
unit: transform.displayUnit,
decimals: transform.decimals,
converts,
toDisplay: (v) => applyDisplayTransform(v, transform),
toCanonical: (v) => invertDisplayTransform(v, transform),
convertGraded: (series) =>
converts ? convertGradedSeries(series, transform) : series,
};
}
@@ -225,9 +225,11 @@ describe("buildPeriodNarrativeContext — grain (QA F3)", () => {
expect(sleepDelta).toBeDefined();
// The pre-fix local `toDailyMeans` twin would have averaged the three
// segment durations: (240 + 90 + 80) / 3 ≈ 137 — a number with no
// clinical meaning. The correct grain is the night's TOTAL (410).
expect(sleepDelta!.current).toBe(410);
expect(sleepDelta!.current).not.toBeCloseTo((240 + 90 + 80) / 3, 0);
// clinical meaning. The correct grain is the night's TOTAL (410 min),
// narrated in the hours its unit names: this used to read "410 h".
expect(sleepDelta!.unit).toBe("h");
expect(sleepDelta!.current).toBe(6.83);
expect(sleepDelta!.current).not.toBeCloseTo((240 + 90 + 80) / 3 / 60, 1);
});
it("orders the measurement read DESC + cap so the CURRENT period survives a capped window (QA F2)", async () => {
@@ -113,6 +113,7 @@ describe("buildDeterministicNarrative", () => {
bandTransitions: [
{
type: "BLOOD_PRESSURE_SYS",
unit: "mmHg",
center: 140,
bandLow: 110,
bandHigh: 130,
@@ -9,6 +9,9 @@ import type {
DailySeriesPoint,
NamedSeries,
} from "@/lib/insights/correlation-discovery";
import { DEFAULT_UNIT_PREFERENCES } from "@/lib/measurements/display-transform";
import { buildDeterministicNarrative } from "../period-narrative-deterministic";
import { buildNarrativeUserPrompt } from "../period-narrative-generate";
/**
* Build a contiguous daily series ending at `endDay` (YYYY-MM-DD), one point
@@ -42,6 +45,7 @@ function monthInput(
discoverySeries,
locale: "en",
computedAt: "2026-04-30T12:00:00.000Z",
units: DEFAULT_UNIT_PREFERENCES,
};
}
@@ -122,6 +126,119 @@ describe("assemblePeriodNarrativeContext — metric deltas", () => {
});
});
describe("assemblePeriodNarrativeContext — the reader's units", () => {
function glucoseAndWeight() {
const m = new Map<string, DailySeriesPoint[]>();
// Prior 30 days at 90 mg/dL / 80 kg, current 30 at 108 mg/dL / 82 kg.
m.set(
"BLOOD_GLUCOSE",
seriesEndingAt(
[...Array(30).fill(90), ...Array(30).fill(108)],
"2026-04-30",
),
);
m.set(
"WEIGHT",
seriesEndingAt(
[...Array(30).fill(80), ...Array(30).fill(82)],
"2026-04-30",
),
);
return m;
}
it("narrates glucose in mmol/L and weight in pounds when the reader chose them", () => {
const ctx = assertReady(
assemblePeriodNarrativeContext({
...monthInput(glucoseAndWeight()),
units: { system: "imperial", glucoseUnit: "mmol/L" },
}),
);
const g = ctx.metricDeltas.find((d) => d.type === "BLOOD_GLUCOSE")!;
expect(g.unit).toBe("mmol/L");
expect(g.current).toBe(6);
expect(g.prior).toBe(5);
expect(g.delta).toBe(1);
// Percent is unit-free.
expect(g.deltaPercent).toBe(20);
const w = ctx.metricDeltas.find((d) => d.type === "WEIGHT")!;
expect(w.unit).toBe("lb");
expect(w.current).toBe(180.8);
expect(w.delta).toBe(4.4);
const prose = buildDeterministicNarrative(ctx, "en");
expect(prose).toContain("mmol/L");
expect(prose).toContain("lb");
expect(prose).not.toContain("mg/dL");
expect(prose).not.toContain("kg");
const prompt = buildNarrativeUserPrompt(ctx, "en");
expect(prompt).toContain("BLOOD_GLUCOSE: 6 mmol/L");
expect(prompt).not.toContain("mg/dL");
});
it("keeps mg/dL and kilograms on the default preferences", () => {
const ctx = assertReady(
assemblePeriodNarrativeContext(monthInput(glucoseAndWeight())),
);
const g = ctx.metricDeltas.find((d) => d.type === "BLOOD_GLUCOSE")!;
expect(g.unit).toBe("mg/dL");
expect(g.current).toBe(108);
expect(ctx.metricDeltas.find((d) => d.type === "WEIGHT")!.unit).toBe("kg");
});
it("narrates sleep minutes as hours, the unit it always claimed", () => {
const m = new Map<string, DailySeriesPoint[]>();
m.set(
"SLEEP_DURATION",
seriesEndingAt(
[...Array(30).fill(420), ...Array(30).fill(450)],
"2026-04-30",
),
);
m.set(
"WEIGHT",
seriesEndingAt(
[...Array(30).fill(80), ...Array(30).fill(82)],
"2026-04-30",
),
);
const ctx = assertReady(assemblePeriodNarrativeContext(monthInput(m)));
const s = ctx.metricDeltas.find((d) => d.type === "SLEEP_DURATION")!;
expect(s.unit).toBe("h");
expect(s.current).toBe(7.5);
expect(s.delta).toBe(0.5);
});
it("states a band transition with its unit, converted", () => {
const m = new Map<string, DailySeriesPoint[]>();
const prior = Array.from({ length: 30 }, (_, i) => 90 + (i % 3));
m.set(
"BLOOD_GLUCOSE",
seriesEndingAt([...prior, ...Array(30).fill(140)], "2026-04-30"),
);
m.set(
"WEIGHT",
seriesEndingAt(
[...Array(30).fill(80), ...Array(30).fill(82)],
"2026-04-30",
),
);
const ctx = assertReady(
assemblePeriodNarrativeContext({
...monthInput(m),
units: { system: "metric", glucoseUnit: "mmol/L" },
}),
);
const t = ctx.bandTransitions.find((b) => b.type === "BLOOD_GLUCOSE")!;
expect(t.unit).toBe("mmol/L");
expect(t.center).toBe(7.8);
expect(t.movedOut).toBe(true);
expect(buildNarrativeUserPrompt(ctx, "en")).toContain(
"BLOOD_GLUCOSE: 7.8 mmol/L",
);
});
});
describe("assemblePeriodNarrativeContext — band transitions", () => {
it("flags a vital whose current center moved above its prior band", () => {
const m = new Map<string, DailySeriesPoint[]>();
@@ -259,8 +259,9 @@ export function buildNarrativeUserPrompt(
: locale === "de"
? "im Bereich"
: "in range";
const unit = b.unit ? ` ${b.unit}` : "";
lines.push(
`- ${b.type}: ${b.center} (${b.bandLow}–${b.bandHigh}) → ${where}`,
`- ${b.type}: ${b.center}${unit} (${b.bandLow}–${b.bandHigh}${unit}) → ${where}`,
);
}
}
+112 -25
View File
@@ -56,6 +56,14 @@ import { VITALS_BASELINE_TYPES } from "@/lib/insights/derived/registry";
import { assembleDiscoveryMatrix } from "@/lib/insights/discovery-matrix";
import { resolveModuleMap } from "@/lib/modules/gate";
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
import {
applyDisplayTransform,
applyDisplayTransformDelta,
getReadingTransform,
isUnitSensitiveType,
resolveUnitPreferences,
type UnitPreferences,
} from "@/lib/measurements/display-transform";
const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -74,20 +82,80 @@ export const MIN_COVERED_DAYS_PER_METRIC = 3;
/** A band must rest on at least this many prior-period days to be trusted. */
export const MIN_BASELINE_DAYS = 7;
/** The metrics the period-delta beat scans, with their display unit. */
const DELTA_METRICS: Array<{ type: MeasurementType; unit: string }> = [
{ type: "WEIGHT", unit: "kg" },
{ type: "BLOOD_PRESSURE_SYS", unit: "mmHg" },
{ type: "BLOOD_PRESSURE_DIA", unit: "mmHg" },
{ type: "PULSE", unit: "bpm" },
{ type: "RESTING_HEART_RATE", unit: "bpm" },
{ type: "HEART_RATE_VARIABILITY", unit: "ms" },
{ type: "SLEEP_DURATION", unit: "h" },
{ type: "ACTIVITY_STEPS", unit: "" },
{ type: "BODY_FAT", unit: "%" },
{ type: "BLOOD_GLUCOSE", unit: "mg/dL" },
/**
* The metrics the period-delta beat scans. Their unit is not listed here: a
* reading is narrated in the reader's unit (see `narratedUnit`), and the list
* used to pin kilograms and mg/dL for everyone.
*/
const DELTA_METRICS: MeasurementType[] = [
"WEIGHT",
"BLOOD_PRESSURE_SYS",
"BLOOD_PRESSURE_DIA",
"PULSE",
"RESTING_HEART_RATE",
"HEART_RATE_VARIABILITY",
"SLEEP_DURATION",
"ACTIVITY_STEPS",
"BODY_FAT",
"BLOOD_GLUCOSE",
];
/**
* Unit symbols of the narrated types whose unit no preference changes. The
* sleep channel is a per-night total in minutes and is narrated in hours.
*/
const FIXED_NARRATED_UNITS: Partial<Record<MeasurementType, string>> = {
BLOOD_PRESSURE_SYS: "mmHg",
BLOOD_PRESSURE_DIA: "mmHg",
PULSE: "bpm",
RESTING_HEART_RATE: "bpm",
HEART_RATE_VARIABILITY: "ms",
RESPIRATORY_RATE: "breaths/min",
OXYGEN_SATURATION: "%",
SLEEP_DURATION: "h",
ACTIVITY_STEPS: "",
BODY_FAT: "%",
};
/**
* How one narrated type is written for this reader: its unit symbol, the
* conversion of an absolute value (a mean, a band edge) and of a difference
* (a delta — factor only, never an affine offset). The computation itself
* stays canonical, so the personal-band floors and the percent change do not
* depend on the unit the reader chose.
*/
function narratedUnit(
type: MeasurementType,
units: UnitPreferences,
): {
unit: string;
abs: (canonical: number) => number;
delta: (canonical: number) => number;
} {
if (isUnitSensitiveType(type)) {
const transform = getReadingTransform(type, units);
return {
unit: transform.displayUnit,
// Rounded to the unit's own grain (one decimal for lb and mmol/L), the
// grain every screen shows the same reading at.
abs: (v) => round2(applyDisplayTransform(v, transform)),
delta: (v) => round2(applyDisplayTransformDelta(v, transform)),
};
}
if (type === "SLEEP_DURATION") {
return {
unit: "h",
abs: (v) => round2(v / 60),
delta: (v) => round2(v / 60),
};
}
return {
unit: FIXED_NARRATED_UNITS[type] ?? "",
abs: round2,
delta: round2,
};
}
// ── context shape ───────────────────────────────────────────────────────
/** One metric's current-period mean vs the prior period of equal length. */
@@ -114,6 +182,8 @@ export interface MetricDelta {
*/
export interface BandTransition {
type: MeasurementType;
/** Unit of `center` / `bandLow` / `bandHigh`, in the reader's preference. */
unit: string;
/** Current-period robust center (median of per-day means). */
center: number;
/** Prior-period band edges. */
@@ -243,6 +313,12 @@ export interface AssembleInput {
locale: Locale;
/** Compute time (ISO). */
computedAt: string;
/**
* The reader's unit preferences. Required for the same reason the locale
* is: the context carries numbers a page and a prompt print verbatim, and a
* caller that stays quiet must not get kilograms and mg/dL by default.
*/
units: UnitPreferences;
}
/**
@@ -262,12 +338,14 @@ export function assemblePeriodNarrativeContext(
discoverySeries,
locale,
computedAt,
units,
} = input;
// ── metric deltas (current period vs prior period of equal length) ──────
const metricDeltas: MetricDelta[] = [];
const metricsWithCoverage: string[] = [];
for (const { type, unit } of DELTA_METRICS) {
for (const type of DELTA_METRICS) {
const shown = narratedUnit(type, units);
const points = seriesByMetric.get(type) ?? [];
const { current, prior } = splitByPeriod(points, currentFrom, priorFrom);
const currentAvg = meanOrNull(current);
@@ -280,16 +358,21 @@ export function assemblePeriodNarrativeContext(
currentAvg !== null && priorAvg !== null
? round2(currentAvg - priorAvg)
: null;
// Percent on the canonical values: it is unit-free for a pure rescale,
// and the one affine unit (°F) would otherwise move it.
const deltaPercent =
delta !== null && priorAvg !== null && priorAvg !== 0
? Math.round((delta / Math.abs(priorAvg)) * 1000) / 10
: null;
metricDeltas.push({
type,
unit,
current: currentAvg === null ? null : round2(currentAvg),
prior: priorAvg === null ? null : round2(priorAvg),
delta,
unit: shown.unit,
current: currentAvg === null ? null : shown.abs(currentAvg),
prior: priorAvg === null ? null : shown.abs(priorAvg),
delta:
currentAvg !== null && priorAvg !== null
? shown.delta(currentAvg - priorAvg)
: null,
deltaPercent,
currentDays: current.length,
priorDays: prior.length,
@@ -324,11 +407,13 @@ export function assemblePeriodNarrativeContext(
const center = median(current);
const above = center > band.high;
const below = center < band.low;
const shown = narratedUnit(type, units);
bandTransitions.push({
type,
center: round2(center),
bandLow: round2(band.low),
bandHigh: round2(band.high),
unit: shown.unit,
center: shown.abs(center),
bandLow: shown.abs(band.low),
bandHigh: shown.abs(band.high),
direction: above ? "above" : below ? "below" : "in",
movedOut: above || below,
baselineDays: prior.length,
@@ -479,9 +564,13 @@ export async function buildPeriodNarrativeContext(
const profile = await prisma.user.findUnique({
where: { id: userId },
select: { timezone: true },
select: { timezone: true, unitPreference: true, glucoseUnit: true },
});
const tz = profile?.timezone ?? DEFAULT_TIMEZONE;
const units = resolveUnitPreferences({
unitPreference: profile?.unitPreference,
glucoseUnit: profile?.glucoseUnit,
});
const currentFrom = tzDayKey(
new Date(now.getTime() - periodDays * MS_PER_DAY),
@@ -523,10 +612,7 @@ export async function buildPeriodNarrativeContext(
// comment for why it is one and not four.
includeMoodFactors: true,
extraMeasurementTypes: Array.from(
new Set<MeasurementType>([
...DELTA_METRICS.map((m) => m.type),
...VITALS_BASELINE_TYPES,
]),
new Set<MeasurementType>([...DELTA_METRICS, ...VITALS_BASELINE_TYPES]),
),
});
@@ -553,5 +639,6 @@ export async function buildPeriodNarrativeContext(
discoverySeries,
locale: opts.locale,
computedAt: now.toISOString(),
units,
});
}
+7 -1
View File
@@ -439,6 +439,12 @@ const GENERIC_METRIC_POINTER: Localized<string> = {
export function getNoKeyMetricStatusText(
locale: InsightLocale,
signal?: MetricSignal | null,
/**
* Decimals the signal's unit is read at (0 for mg/dL, 1 for mmol/L or
* pounds). Defaults to one, which was the only precision before the
* signal could arrive in the reader's unit.
*/
digits = 1,
): string {
const grounded =
signal && Number.isFinite(signal.current)
@@ -449,7 +455,7 @@ export function getNoKeyMetricStatusText(
// localised upstream, so it stands for every locale.
label: { en: signal.metric },
...(signal.unit ? { unit: ` ${signal.unit}` } : {}),
digits: 1,
digits,
pointer: GENERIC_METRIC_POINTER,
},
locale,
+6 -6
View File
@@ -51,7 +51,12 @@ export interface TrendChartConfig {
types: string[];
/** Recharts stroke colours, positionally matched to `types`. */
colors: string[];
/** Display unit (chart legend / tooltip). */
/**
* Display unit (chart legend / tooltip) for a metric no preference
* changes. A single-series slot whose type has a display transform
* (weight, distance, body temperature) carries none: the renderer takes
* the unit, scale and offset from the reader's preference instead.
*/
unit?: string;
/** Y-axis unit label when it differs from the value unit. */
yAxisUnit?: string;
@@ -114,7 +119,6 @@ export const TREND_CHART_CONFIG: Record<
kind: "health-chart",
types: ["WEIGHT"],
colors: ["var(--chart-1)"],
unit: "kg",
titleKey: "charts.weight",
captionKey: "insights.trendsRow.caption.weight",
annotationKey: "weight",
@@ -212,8 +216,6 @@ export const TREND_CHART_CONFIG: Record<
kind: "health-chart",
types: ["WALKING_RUNNING_DISTANCE"],
colors: ["var(--chart-4)"],
unit: "km",
yAxisUnit: "km",
titleKey: "charts.distance",
captionKey: "insights.trendsRow.caption.distance",
detailHref: "/insights/walking-distance",
@@ -234,8 +236,6 @@ export const TREND_CHART_CONFIG: Record<
kind: "health-chart",
types: ["BODY_TEMPERATURE"],
colors: ["var(--destructive)"],
unit: "°C",
yAxisUnit: "°C",
titleKey: "charts.bodyTemperature",
captionKey: "insights.trendsRow.caption.body_temp",
detailHref: "/insights/body-temperature",
+21 -7
View File
@@ -140,8 +140,18 @@ export function computeTrendDescriptor(
* dedicated copy rather than the numeric `{delta} {unit}` template.
*/
export interface TrendSlotDescriptorMeta {
/** Display unit interpolated into the numeric descriptor template. */
unit: string;
/**
* Display unit interpolated into the numeric descriptor template, for a
* metric no preference changes.
*/
unit?: string;
/**
* For a metric whose unit follows the reader's preference: the
* measurement type the caller resolves the unit of (and converts the
* series and the noise floor through) before describing it. Such a slot
* declares its `absoluteFloor` in the CANONICAL unit (kg, m, °C).
*/
unitType?: string;
config: TrendDescriptorConfig;
}
@@ -154,7 +164,7 @@ export const TREND_SLOT_DESCRIPTOR_META: Record<
config: { absoluteFloor: 2, relativeFloor: 0.02, decimals: 0 },
},
weight: {
unit: "kg",
unitType: "WEIGHT",
config: { absoluteFloor: 0.3, relativeFloor: 0.01, decimals: 1 },
},
pulse: {
@@ -186,15 +196,16 @@ export const TREND_SLOT_DESCRIPTOR_META: Record<
config: { absoluteFloor: 1, relativeFloor: 0.1, decimals: 0 },
},
distance: {
unit: "km",
config: { absoluteFloor: 0.3, relativeFloor: 0.05, decimals: 1 },
unitType: "WALKING_RUNNING_DISTANCE",
// 300 m — canonical metres, converted to the reader's km or mi.
config: { absoluteFloor: 300, relativeFloor: 0.05, decimals: 1 },
},
vo2_max: {
unit: "",
config: { absoluteFloor: 0.5, relativeFloor: 0.02, decimals: 1 },
},
body_temp: {
unit: "°C",
unitType: "BODY_TEMPERATURE",
config: { absoluteFloor: 0.2, relativeFloor: 0.005, decimals: 1 },
},
};
@@ -231,9 +242,12 @@ export interface TrendDescriptorCopy {
export function numericDescriptorCopy(
metric: string,
descriptor: TrendDescriptor,
/** Resolves a `unitType` slot's unit under the reader's preference. */
unitFor: (type: string) => string,
): TrendDescriptorCopy | null {
const meta = TREND_SLOT_DESCRIPTOR_META[metric];
if (!meta) return null;
const unit = meta.unitType ? unitFor(meta.unitType) : (meta.unit ?? "");
// Signed, formatted magnitude (e.g. "+8", "-1.4"). `stable` still
// carries its small delta so the caption can read "stable (±0 …)" if a
@@ -255,7 +269,7 @@ export function numericDescriptorCopy(
// reads "({delta}{unit})" → "(+8 mmHg)" with a unit, "(+1200)"
// without one — no dangling space inside the parens for unit-less
// metrics (steps, flights).
unit: meta.unit ? ` ${meta.unit}` : "",
unit: unit ? ` ${unit}` : "",
},
};
}
+63
View File
@@ -0,0 +1,63 @@
/**
* Re-warm the stored texts that quote numbers after a unit preference changes.
*
* A status note and a period narrative are written once and served all day
* (the narrative for up to twenty hours). Both now state their figures in the
* reader's units, so a note written before a switch from mg/dL to mmol/L — or
* from metric to imperial — keeps saying the old unit until something
* regenerates it. Nothing did: neither preference write touched the stored
* text.
*
* The refill goes through the same hash-gated path as the manual regenerate:
* every card the record has is enqueued, the worker forces a fresh snapshot,
* and a card whose snapshot did not change (a metric that does not depend on
* the preference) gets a timestamp refresh and no model call. Narratives are
* re-warmed only where one already exists. Best-effort and fire-and-forget:
* the preference write never waits on it and never fails because of it.
*/
import { prisma } from "@/lib/db";
import { enqueueNarrativeWarm } from "@/lib/jobs/period-narrative-shared";
import { enqueueStatusRefillForUser } from "@/lib/insights/status-invalidation";
import { normalizeLocale } from "@/lib/insights/status-shared";
import { locales, type Locale } from "@/lib/i18n/config";
import type { NarrativePeriod } from "@/lib/insights/narrative/period-narrative";
import { annotate } from "@/lib/logging/context";
export async function refreshTextsAfterUnitChange(
userId: string,
): Promise<void> {
try {
const user = await prisma.user.findUnique({
where: { id: userId },
select: { locale: true },
});
const statusScopes = await enqueueStatusRefillForUser(
userId,
normalizeLocale(user?.locale),
);
const narratives = await prisma.insightNarrative.findMany({
where: { userId },
select: { period: true, locale: true },
});
let narrativeCount = 0;
for (const row of narratives) {
if (row.period !== "week" && row.period !== "month") continue;
if (!(locales as readonly string[]).includes(row.locale)) continue;
void enqueueNarrativeWarm({
userId,
period: row.period as NarrativePeriod,
locale: row.locale as Locale,
});
narrativeCount++;
}
annotate({
action: { name: "insights.unit-change.refresh" },
meta: { status_scopes: statusScopes, narratives: narrativeCount },
});
} catch {
// Best-effort: the nightly warm and the next ingest still converge the
// texts; a failed enqueue must not surface on the preference write.
}
}
@@ -10,7 +10,14 @@ import {
transformRescales,
TRANSFORMED_TYPES,
DEFAULT_UNIT_PREFERENCE,
DEFAULT_UNIT_PREFERENCES,
getQuantityTransform,
getReadingTransform,
isUnitSensitiveType,
paceSecondsPerDistanceUnit,
resolveUnitPreferences,
} from "../display-transform";
import { convertGlucose } from "@/lib/glucose";
describe("display-transform", () => {
it("converts WALKING_SPEED m/s → km/h (factor 3.6)", () => {
@@ -308,3 +315,85 @@ describe("display-transform — converted values carry the declared precision",
expect(invertDisplayTransform(185.2, imperial)).not.toBe(84);
});
});
describe("display-transform — both unit preferences, one resolver", () => {
it("reads glucose in the preferred clinical unit, matching convertGlucose", () => {
const mmol = getReadingTransform("BLOOD_GLUCOSE", {
system: "metric",
glucoseUnit: "mmol/L",
});
expect(mmol.displayUnit).toBe("mmol/L");
for (const mgdl of [54, 70, 99, 126, 140, 250]) {
expect(applyDisplayTransform(mgdl, mmol)).toBe(
convertGlucose(mgdl, "mmol/L"),
);
}
const mgdl = getReadingTransform("BLOOD_GLUCOSE", DEFAULT_UNIT_PREFERENCES);
expect(mgdl.displayUnit).toBe("mg/dL");
expect(applyDisplayTransform(99, mgdl)).toBe(99);
});
it("leaves glucose alone under the imperial preference", () => {
const t = getReadingTransform("BLOOD_GLUCOSE", {
system: "imperial",
glucoseUnit: "mg/dL",
});
expect(t.displayUnit).toBe("mg/dL");
});
it("delegates every other type to the metric/imperial registry", () => {
expect(
getReadingTransform("WEIGHT", {
system: "imperial",
glucoseUnit: "mmol/L",
}).displayUnit,
).toBe("lb");
expect(
getReadingTransform("PULSE", {
system: "imperial",
glucoseUnit: "mmol/L",
}).displayUnit,
).toBe("bpm");
});
it("marks glucose and the transformed set as unit-sensitive", () => {
expect(isUnitSensitiveType("BLOOD_GLUCOSE")).toBe(true);
expect(isUnitSensitiveType("WEIGHT")).toBe(true);
expect(isUnitSensitiveType("HEART_RATE_VARIABILITY")).toBe(false);
});
it("resolves the stored columns with their defaults", () => {
expect(resolveUnitPreferences({})).toEqual(DEFAULT_UNIT_PREFERENCES);
expect(
resolveUnitPreferences({
unitPreference: "imperial",
glucoseUnit: "mmol/L",
}),
).toEqual({ system: "imperial", glucoseUnit: "mmol/L" });
expect(resolveUnitPreferences({ unitPreference: "bogus" }).system).toBe(
"metric",
);
});
it("converts workout distance, elevation and pace per preference", () => {
const km = getQuantityTransform("distance", "metric");
const mi = getQuantityTransform("distance", "imperial");
expect(applyDisplayTransform(5000, km)).toBe(5);
expect(km.displayUnit).toBe("km");
expect(applyDisplayTransform(5000, mi)).toBe(3.11);
expect(mi.displayUnit).toBe("mi");
expect(
applyDisplayTransform(100, getQuantityTransform("elevation", "imperial")),
).toBe(328.1);
expect(getQuantityTransform("elevation", "metric").displayUnit).toBe("m");
// 30 min over 5 km: 360 s/km, 579.4 s/mi.
expect(paceSecondsPerDistanceUnit(1800, 5000, "metric")).toBeCloseTo(
360,
6,
);
expect(paceSecondsPerDistanceUnit(1800, 5000, "imperial")).toBeCloseTo(
579.36,
2,
);
});
});
+131
View File
@@ -61,12 +61,54 @@
*/
import type { MeasurementType } from "@/generated/prisma/client";
import {
MGDL_PER_MMOL,
resolveGlucoseUnit,
type GlucoseUnit,
} from "@/lib/glucose";
import { getUnitForType } from "@/lib/validations/measurement";
export type UnitPreference = "metric" | "imperial";
export const DEFAULT_UNIT_PREFERENCE: UnitPreference = "metric";
/** The stored preference column resolved to a branch; anything unknown is metric. */
export function resolveUnitPreference(
raw: string | null | undefined,
): UnitPreference {
return raw === "imperial" ? "imperial" : DEFAULT_UNIT_PREFERENCE;
}
/**
* Both unit choices a person makes, together. They are separate columns
* because they are separate questions — metric versus imperial is about mass,
* length and temperature, mg/dL versus mmol/L is the clinical convention of
* the country the record lives in — but a surface that renders a reading
* needs both, and taking them as one value is what keeps a server-side text
* producer from honouring one and forgetting the other.
*/
export interface UnitPreferences {
system: UnitPreference;
glucoseUnit: GlucoseUnit;
}
/** Resolve both stored columns at once (each falls back to its default). */
export function resolveUnitPreferences(row: {
unitPreference?: string | null;
glucoseUnit?: string | null;
}): UnitPreferences {
return {
system: resolveUnitPreference(row.unitPreference),
glucoseUnit: resolveGlucoseUnit(row.glucoseUnit),
};
}
/** The defaults: metric, mg/dL. */
export const DEFAULT_UNIT_PREFERENCES: UnitPreferences = {
system: DEFAULT_UNIT_PREFERENCE,
glucoseUnit: "mg/dL",
};
export interface DisplayTransform {
/** Multiplier applied to the raw canonical value for display. */
factor: number;
@@ -156,6 +198,95 @@ const TRANSFORMS: Partial<
},
};
/**
* Blood glucose, stored in mg/dL, read in either clinical unit. Keyed by the
* glucose preference rather than metric/imperial. The mmol/L branch rounds to
* one decimal through `applyDisplayTransform`, which is exactly what
* `mgdlToMmol` does, so a server-side text and a screen built on
* `convertGlucose` print the same figure.
*/
const GLUCOSE_TRANSFORM: Record<GlucoseUnit, DisplayTransform> = {
"mg/dL": { factor: 1, displayUnit: "mg/dL", decimals: 0 },
"mmol/L": { factor: 1 / MGDL_PER_MMOL, displayUnit: "mmol/L", decimals: 1 },
};
/**
* The transform for a reading of `type` under BOTH unit preferences — the
* one resolver a server-side text producer (a status note, a narrative, a
* prompt) takes its numbers and unit symbols from.
*
* The client surfaces keep `getDisplayTransform` through `useUnitDisplay`
* and convert glucose through `convertGlucose` at the few places that render
* it; folding glucose into that path would convert it a second time on the
* screens that already do. Text built on the server has no such history, so
* it starts from the complete answer.
*/
export function getReadingTransform(
type: string,
preferences: UnitPreferences,
): DisplayTransform {
if (type === "BLOOD_GLUCOSE")
return GLUCOSE_TRANSFORM[preferences.glucoseUnit];
return getDisplayTransform(type, preferences.system);
}
/**
* Every measurement type whose displayed number or unit depends on a unit
* preference: the metric/imperial set plus glucose. Text that quoted one of
* these was written in a unit, and goes stale when the preference changes.
*/
export function isUnitSensitiveType(type: string): boolean {
return type === "BLOOD_GLUCOSE" || TRANSFORMED_TYPES.has(type);
}
/**
* Quantities that are not a stored measurement type but are read in a unit
* system all the same: a workout's distance and its elevation gain, both
* stored in metres. Same rules as the type registry — the metric distance
* branch reads kilometres, which is a rescale, so it rounds; the metric
* elevation branch is the identity.
*/
export type QuantityKind = "distance" | "elevation";
// 1 m = 3.28083989501 ft.
const M_TO_FT = 3.28083989501;
const QUANTITY_TRANSFORMS: Record<
QuantityKind,
Record<UnitPreference, DisplayTransform>
> = {
distance: {
metric: { factor: 0.001, displayUnit: "km", decimals: 2 },
imperial: { factor: 0.000621371192237, displayUnit: "mi", decimals: 2 },
},
elevation: {
metric: { factor: 1, displayUnit: "m", decimals: 1 },
imperial: { factor: M_TO_FT, displayUnit: "ft", decimals: 1 },
},
};
/** The transform for a metre-valued quantity under a metric/imperial preference. */
export function getQuantityTransform(
kind: QuantityKind,
preference: UnitPreference,
): DisplayTransform {
return QUANTITY_TRANSFORMS[kind][preference];
}
/**
* Seconds per displayed distance unit (per km, or per mile) from a duration
* and a distance in metres. A pace is a rate in the inverse direction of a
* distance, so it divides by the factor instead of multiplying.
*/
export function paceSecondsPerDistanceUnit(
durationSec: number,
meters: number,
preference: UnitPreference,
): number {
const { factor } = QUANTITY_TRANSFORMS.distance[preference];
return durationSec / (meters * factor);
}
/**
* Every type with a registered transform. The structural guard test uses
* this set to assert no display surface hardcodes a unit string / scale
+14 -6
View File
@@ -239,11 +239,17 @@ const scorePillarIdEnum = z.enum(SCORE_PILLAR_IDS);
const pillarValue = z.object({
score: z.number(),
observed: z.object({
value: z.number(),
unit: z.string(),
value: z
.number()
.describe(
"The scored value in its canonical unit (fasting glucose in mg/dL).",
),
unit: z.string().describe("The canonical unit of `value`."),
label: z
.string()
.describe("The complete display value, paired or panel values included."),
.describe(
"The complete display value, paired or panel values included, written in the reader's units (fasting glucose in the account's glucose unit).",
),
asOf: z.iso.datetime({ offset: true }),
sources: z.array(z.string()),
}),
@@ -253,9 +259,11 @@ const pillarValue = z.object({
"population-percentile",
"guideline-band",
]),
low: z.number().nullable(),
high: z.number().nullable(),
label: z.string(),
low: z.number().nullable().describe("Lower band edge, canonical unit."),
high: z.number().nullable().describe("Upper band edge, canonical unit."),
label: z
.string()
.describe("The band as display text, in the reader's units."),
source: z.string(),
}),
personalReference: z
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import { METRIC_BOUNDS } from "@/lib/analytics/effective-range";
import { resolveTargetUnitAdapter } from "../target-unit-display";
import { toCanonicalMgdl } from "@/lib/glucose";
/**
* v1.32.27 — the target/threshold unit adapter.
@@ -18,7 +19,7 @@ const KG_PER_LB = 0.45359237;
describe("resolveTargetUnitAdapter — metric account (identity)", () => {
it("leaves a weight threshold bit-for-bit untouched", () => {
const units = resolveTargetUnitAdapter("WEIGHT", "kg", "metric");
const units = resolveTargetUnitAdapter("WEIGHT", "kg", "metric", "mg/dL");
expect(units.rescales).toBe(false);
expect(units.unit).toBe("kg");
// Not "close to" — exactly the same double, in both directions.
@@ -37,6 +38,7 @@ describe("resolveTargetUnitAdapter — metric account (identity)", () => {
"BLOOD_PRESSURE_SYS",
"mmHg",
preference,
"mg/dL",
);
expect(units.rescales).toBe(false);
expect(units.unit).toBe("mmHg");
@@ -51,11 +53,14 @@ describe("resolveTargetUnitAdapter — metric account (identity)", () => {
it("is inert for the keys the edit sheet passes on its non-metric paths", () => {
// A derived card (BMI, mood, medication compliance) has no editable
// threshold and the sheet resolves the adapter with an empty key;
// glucose keeps its own mg/dL ↔ mmol/L dialect and must never pick
// up a second conversion on top.
for (const key of ["", "BMI", "BLOOD_GLUCOSE_FASTING"]) {
const units = resolveTargetUnitAdapter(key, "mmol/L", "imperial");
// threshold and the sheet resolves the adapter with an empty key.
for (const key of ["", "BMI"]) {
const units = resolveTargetUnitAdapter(
key,
"mmol/L",
"imperial",
"mg/dL",
);
expect(units.rescales).toBe(false);
expect(units.unit).toBe("mmol/L");
expect(units.toDisplay(5.5)).toBe(5.5);
@@ -66,14 +71,15 @@ describe("resolveTargetUnitAdapter — metric account (identity)", () => {
it("keeps the whole-hundred step for a step-count target", () => {
for (const preference of ["metric", "imperial"] as const) {
expect(
resolveTargetUnitAdapter("ACTIVITY_STEPS", "steps", preference).step,
resolveTargetUnitAdapter("ACTIVITY_STEPS", "steps", preference, "mg/dL")
.step,
).toBe(100);
}
});
});
describe("resolveTargetUnitAdapter — imperial weight class", () => {
const units = resolveTargetUnitAdapter("WEIGHT", "kg", "imperial");
const units = resolveTargetUnitAdapter("WEIGHT", "kg", "imperial", "mg/dL");
it("announces pounds and a one-decimal step", () => {
expect(units.rescales).toBe(true);
@@ -145,7 +151,12 @@ describe("resolveTargetUnitAdapter — imperial weight class", () => {
it("carries the same treatment across the whole weight class", () => {
for (const metric of ["TOTAL_BODY_WATER", "BONE_MASS"] as const) {
const adapter = resolveTargetUnitAdapter(metric, "kg", "imperial");
const adapter = resolveTargetUnitAdapter(
metric,
"kg",
"imperial",
"mg/dL",
);
expect(adapter.unit).toBe("lb");
const bounds = adapter.bounds(METRIC_BOUNDS[metric]);
expect(adapter.toCanonical(bounds.min)).toBeGreaterThanOrEqual(
@@ -169,6 +180,7 @@ describe("resolveTargetUnitAdapter — temperature (the affine one)", () => {
"BODY_TEMPERATURE",
"celsius",
"imperial",
"mg/dL",
);
it("shifts absolute readings but never a difference", () => {
@@ -208,6 +220,7 @@ describe("resolveTargetUnitAdapter — temperature (the affine one)", () => {
"BODY_TEMPERATURE",
"celsius",
"metric",
"mg/dL",
);
expect(metricUnits.rescales).toBe(false);
expect(metricUnits.toDisplay(37)).toBe(37);
@@ -224,3 +237,73 @@ describe("resolveTargetUnitAdapter — temperature (the affine one)", () => {
expect(units.toCanonical(bounds.max)).toBeLessThanOrEqual(45);
});
});
describe("resolveTargetUnitAdapter — glucose thresholds follow the glucose unit", () => {
const contexts = [
"BLOOD_GLUCOSE_FASTING",
"BLOOD_GLUCOSE_POSTPRANDIAL",
"BLOOD_GLUCOSE_RANDOM",
"BLOOD_GLUCOSE_BEDTIME",
] as const;
it("reads mmol/L for an mmol/L reader, whatever the metric/imperial branch", () => {
for (const metric of contexts) {
for (const preference of ["metric", "imperial"] as const) {
const units = resolveTargetUnitAdapter(
metric,
"mg/dL",
preference,
"mmol/L",
);
expect(units.unit).toBe("mmol/L");
expect(units.rescales).toBe(true);
expect(units.step).toBe(0.1);
// The 70–99 mg/dL fasting default reads 3.9–5.5.
expect(units.toDisplay(70)).toBe(3.9);
expect(units.toDisplay(99)).toBe(5.5);
}
}
});
it("round-trips a typed mmol/L value to whole mg/dL and back", () => {
const units = resolveTargetUnitAdapter(
"BLOOD_GLUCOSE_FASTING",
"mg/dL",
"metric",
"mmol/L",
);
expect(units.toCanonical(5.5)).toBe(99);
expect(units.toDisplay(units.toCanonical(5.5))).toBe(5.5);
expect(units.toCanonical(3.9)).toBe(toCanonicalMgdl(3.9, "mmol/L"));
});
it("rounds the canonical 40–400 mg/dL guardrail inward", () => {
const units = resolveTargetUnitAdapter(
"BLOOD_GLUCOSE_FASTING",
"mg/dL",
"metric",
"mmol/L",
);
const bounds = units.bounds(METRIC_BOUNDS.BLOOD_GLUCOSE_FASTING);
expect(bounds).toEqual({ min: 2.3, max: 22.1 });
expect(units.toCanonical(bounds.min)).toBeGreaterThanOrEqual(
METRIC_BOUNDS.BLOOD_GLUCOSE_FASTING.min,
);
expect(units.toCanonical(bounds.max)).toBeLessThanOrEqual(
METRIC_BOUNDS.BLOOD_GLUCOSE_FASTING.max,
);
});
it("stays the exact identity for an mg/dL reader", () => {
const units = resolveTargetUnitAdapter(
"BLOOD_GLUCOSE_FASTING",
"mg/dL",
"imperial",
"mg/dL",
);
expect(units.unit).toBe("mg/dL");
expect(units.rescales).toBe(false);
expect(units.toDisplay(99)).toBe(99);
expect(units.toCanonical(99)).toBe(99);
});
});
+46 -1
View File
@@ -48,6 +48,12 @@ import {
transformRescales,
type UnitPreference,
} from "@/lib/measurements/display-transform";
import {
MGDL_PER_MMOL,
convertGlucose,
toCanonicalMgdl,
type GlucoseUnit,
} from "@/lib/glucose";
/** Canonical decimals a converted threshold value persists with. */
const CANONICAL_DECIMALS = 2;
@@ -119,6 +125,41 @@ function identityAdapter(metric: string, unit: string): TargetUnitAdapter {
};
}
/**
* The glucose thresholds (`BLOOD_GLUCOSE_FASTING` and its siblings) are
* stored in mg/dL and read in the reader's glucose unit. The settings editor
* used to take the identity path for them, so an mmol/L account was asked
* for mg/dL figures under a label that said nothing, against 40–400 bounds
* and a "default: 70–99" hint — while the insights sheet for the same
* threshold already spoke mmol/L.
*
* mmol/L reads at one decimal; the canonical write rounds to whole mg/dL
* (`toCanonicalMgdl`), the precision every glucose path stores. Guardrails
* round inward exactly like the imperial branch: 40 mg/dL is 2.22 mmol/L,
* shown as 2.3 so that the typed bound inverts to 41 mg/dL and passes.
*/
function glucoseAdapter(glucoseUnit: GlucoseUnit): TargetUnitAdapter {
if (glucoseUnit === "mg/dL") return identityAdapter("BLOOD_GLUCOSE", "mg/dL");
const toMmol = (mgdl: number) => mgdl / MGDL_PER_MMOL;
return {
unit: "mmol/L",
step: 0.1,
rescales: true,
toDisplay: (canonical) => convertGlucose(canonical, "mmol/L"),
toCanonical: (display) => toCanonicalMgdl(display, "mmol/L"),
toDisplayDelta: (canonicalDelta) => roundTo(toMmol(canonicalDelta), 1),
bounds: (canonical) => ({
min: ceilTo(toMmol(canonical.min), 1),
max: floorTo(toMmol(canonical.max), 1),
}),
};
}
/** True for a glucose threshold metric or target-card type. */
export function isGlucoseTargetMetric(metric: string): boolean {
return metric === "BLOOD_GLUCOSE" || metric.startsWith("BLOOD_GLUCOSE_");
}
/**
* Resolve the unit adapter for one threshold metric / target-card type.
*
@@ -128,13 +169,17 @@ function identityAdapter(metric: string, unit: string): TargetUnitAdapter {
* on, so a metric participates exactly when it has a registered
* transform. `canonicalUnit` is the unit the surface announced before
* this release (`METRIC_BOUNDS[metric].unit` or the targets payload's
* `unit`) and is what an untransformed metric keeps.
* `unit`) and is what an untransformed metric keeps. `glucoseUnit` is
* the reader's glucose preference; it decides the glucose thresholds and
* nothing else.
*/
export function resolveTargetUnitAdapter(
metric: string,
canonicalUnit: string,
preference: UnitPreference,
glucoseUnit: GlucoseUnit,
): TargetUnitAdapter {
if (isGlucoseTargetMetric(metric)) return glucoseAdapter(glucoseUnit);
if (!hasDisplayTransform(metric))
return identityAdapter(metric, canonicalUnit);