mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 15:42:24 +00:00
Merge the untagged glucose bucket across every consumer (#943)
This commit is contained in:
commit
3bd0664edf
30 files changed
+828
-97
No files matched your search
@@ -6,6 +6,9 @@ import {
|
||||
toCanonicalMgdl,
|
||||
resolveGlucoseUnit,
|
||||
thresholdMetricForContext,
|
||||
glucoseContextBucket,
|
||||
groupByGlucoseContext,
|
||||
GLUCOSE_CONTEXT_UNSPECIFIED,
|
||||
} from "../glucose";
|
||||
|
||||
describe("glucose conversion", () => {
|
||||
@@ -108,3 +111,49 @@ describe("glucose conversion", () => {
|
||||
expect(toCanonicalMgdl(mgdlToMmol(70), "mmol/L")).toBe(70);
|
||||
});
|
||||
});
|
||||
|
||||
describe("glucose context buckets (#943)", () => {
|
||||
it("files NULL, blank and unknown values under the untagged bucket", () => {
|
||||
expect(glucoseContextBucket(null)).toBe(GLUCOSE_CONTEXT_UNSPECIFIED);
|
||||
expect(glucoseContextBucket(undefined)).toBe(GLUCOSE_CONTEXT_UNSPECIFIED);
|
||||
expect(glucoseContextBucket("")).toBe(GLUCOSE_CONTEXT_UNSPECIFIED);
|
||||
expect(glucoseContextBucket(" ")).toBe(GLUCOSE_CONTEXT_UNSPECIFIED);
|
||||
expect(glucoseContextBucket("BEFORE_MEAL")).toBe(
|
||||
GLUCOSE_CONTEXT_UNSPECIFIED,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the named contexts named, case- and whitespace-tolerant", () => {
|
||||
expect(glucoseContextBucket("FASTING")).toBe("FASTING");
|
||||
expect(glucoseContextBucket(" bedtime ")).toBe("BEDTIME");
|
||||
});
|
||||
|
||||
it("groups in canonical order with the untagged bucket last", () => {
|
||||
const rows = [
|
||||
{ ctx: null, v: 1 },
|
||||
{ ctx: "BEDTIME", v: 2 },
|
||||
{ ctx: "FASTING", v: 3 },
|
||||
{ ctx: "", v: 4 },
|
||||
];
|
||||
const grouped = groupByGlucoseContext(rows, (row) => row.ctx);
|
||||
|
||||
expect(grouped.map(([bucket]) => bucket)).toEqual([
|
||||
"FASTING",
|
||||
"BEDTIME",
|
||||
"UNSPECIFIED",
|
||||
]);
|
||||
// Input order survives inside a bucket, so a caller reading "latest" off
|
||||
// the head keeps reading the same row.
|
||||
expect(grouped[2][1].map((row) => row.v)).toEqual([1, 4]);
|
||||
});
|
||||
|
||||
it("returns nothing for no rows", () => {
|
||||
expect(groupByGlucoseContext([], () => null)).toEqual([]);
|
||||
});
|
||||
|
||||
it("judges the untagged bucket against the RANDOM threshold", () => {
|
||||
expect(thresholdMetricForContext(GLUCOSE_CONTEXT_UNSPECIFIED)).toBe(
|
||||
"BLOOD_GLUCOSE_RANDOM",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,11 @@
|
||||
* read plus the shared accumulators, so the emitted shape and ordering
|
||||
* are unchanged.
|
||||
*/
|
||||
import { convertGlucose, type GlucoseUnit } from "@/lib/glucose";
|
||||
import {
|
||||
convertGlucose,
|
||||
glucoseContextBucket,
|
||||
type GlucoseUnit,
|
||||
} from "@/lib/glucose";
|
||||
import {
|
||||
computeGlucoseClinicalMetrics,
|
||||
GLUCOSE_PANEL_WINDOW_DAYS,
|
||||
@@ -80,15 +84,18 @@ export function buildGlucoseBlock(ctx: Readonly<GlucoseBlockContext>): void {
|
||||
meta: { cluster: "glucose", source: "glucose" },
|
||||
});
|
||||
} else {
|
||||
// Group by context (NULL → "unspecified"), then per-day mean.
|
||||
// Group by context (NULL → "unspecified"), then per-day mean. The bucket
|
||||
// resolver is the shared one (#943) — this block named the untagged
|
||||
// bucket first, and the rest of the tree now resolves through the same
|
||||
// helper rather than repeating the NULL arm at each surface.
|
||||
const byContext = new Map<
|
||||
string,
|
||||
Array<{ measuredAt: Date; value: number }>
|
||||
>();
|
||||
for (const r of glucoseRows) {
|
||||
const ctxKey = r.glucoseContext
|
||||
? String(r.glucoseContext).toLowerCase()
|
||||
: "unspecified";
|
||||
const ctxKey = glucoseContextBucket(
|
||||
typeof r.glucoseContext === "string" ? r.glucoseContext : null,
|
||||
).toLowerCase();
|
||||
const list = byContext.get(ctxKey) ?? [];
|
||||
list.push({ measuredAt: r.measuredAt, value: r.value });
|
||||
byContext.set(ctxKey, list);
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
GLUCOSE_PANEL_WINDOW_DAYS,
|
||||
type GlucoseClinicalMetrics,
|
||||
} from "@/lib/analytics/glucose-metrics";
|
||||
import { groupByGlucoseContext } from "@/lib/glucose";
|
||||
import {
|
||||
computeBpInTargetFastPath,
|
||||
type BpInTargetEnvelope,
|
||||
@@ -134,13 +135,6 @@ import {
|
||||
unavailableWidgetIds,
|
||||
} from "@/lib/dashboard/widget-modules";
|
||||
|
||||
const GLUCOSE_CONTEXTS = [
|
||||
"FASTING",
|
||||
"POSTPRANDIAL",
|
||||
"RANDOM",
|
||||
"BEDTIME",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* v1.7.0 — HealthLog `MeasurementType` → iOS `MetricKind` raw value.
|
||||
*
|
||||
@@ -832,15 +826,16 @@ async function buildExtras(
|
||||
orderBy: { measuredAt: "asc" },
|
||||
select: { value: true, measuredAt: true, glucoseContext: true },
|
||||
});
|
||||
// #943 — grouped through the shared bucket resolver, so readings with no
|
||||
// meal-time tag land in `UNSPECIFIED` instead of being dropped on the floor.
|
||||
const glucoseByContext: Record<string, DataSummary> = {};
|
||||
if (glucoseRows.length > 0) {
|
||||
for (const ctx of GLUCOSE_CONTEXTS) {
|
||||
const ctxRows = glucoseRows.filter((r) => r.glucoseContext === ctx);
|
||||
if (ctxRows.length === 0) continue;
|
||||
glucoseByContext[ctx] = summarize(
|
||||
ctxRows.map((r): DataPoint => ({ date: r.measuredAt, value: r.value })),
|
||||
);
|
||||
}
|
||||
for (const [bucket, ctxRows] of groupByGlucoseContext(
|
||||
glucoseRows,
|
||||
(r) => r.glucoseContext,
|
||||
)) {
|
||||
glucoseByContext[bucket] = summarize(
|
||||
ctxRows.map((r): DataPoint => ({ date: r.measuredAt, value: r.value })),
|
||||
);
|
||||
}
|
||||
|
||||
// v1.17.0 — clinical panel from the SAME 30-day glucose rows already read
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { jsPDF } from "jspdf";
|
||||
import { GLUCOSE_CONTEXT_BUCKETS } from "@/lib/glucose";
|
||||
import autoTable from "jspdf-autotable";
|
||||
import { convertGlucose, resolveGlucoseUnit } from "../glucose";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
@@ -20,6 +21,8 @@ const GLUCOSE_LABEL_KEYS = {
|
||||
POSTPRANDIAL: "doctorReport.typeGlucosePostprandial",
|
||||
RANDOM: "doctorReport.typeGlucoseRandom",
|
||||
BEDTIME: "doctorReport.typeGlucoseBedtime",
|
||||
// #943 — readings the source never tagged with a meal time.
|
||||
UNSPECIFIED: "doctorReport.typeGlucoseUnspecified",
|
||||
} as const;
|
||||
|
||||
const DEFAULT_GLUCOSE_RANGES = {
|
||||
@@ -27,13 +30,12 @@ const DEFAULT_GLUCOSE_RANGES = {
|
||||
POSTPRANDIAL: { min: 70, max: 140 },
|
||||
RANDOM: { min: 70, max: 140 },
|
||||
BEDTIME: { min: 90, max: 150 },
|
||||
// Same band as RANDOM: an untagged reading is a spot reading.
|
||||
UNSPECIFIED: { min: 70, max: 140 },
|
||||
} as const;
|
||||
|
||||
const GLUCOSE_CONTEXTS: Array<keyof typeof GLUCOSE_LABEL_KEYS> = [
|
||||
"FASTING",
|
||||
"POSTPRANDIAL",
|
||||
"RANDOM",
|
||||
"BEDTIME",
|
||||
...GLUCOSE_CONTEXT_BUCKETS,
|
||||
];
|
||||
|
||||
/** A single charted reading. */
|
||||
|
||||
@@ -20,12 +20,14 @@ import {
|
||||
getEffectiveRange,
|
||||
type ThresholdOverridesJson,
|
||||
} from "@/lib/analytics/effective-range";
|
||||
import { resolveGlucoseUnit, thresholdMetricForContext } from "@/lib/glucose";
|
||||
import {
|
||||
GLUCOSE_CONTEXT_BUCKETS,
|
||||
groupByGlucoseContext,
|
||||
resolveGlucoseUnit,
|
||||
thresholdMetricForContext,
|
||||
} from "@/lib/glucose";
|
||||
import { computeGlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
|
||||
import type {
|
||||
GlucoseContext,
|
||||
MeasurementType,
|
||||
} from "@/generated/prisma/client";
|
||||
import type { MeasurementType } from "@/generated/prisma/client";
|
||||
import {
|
||||
reconstructSleepNights,
|
||||
type SleepStageRow,
|
||||
@@ -70,13 +72,6 @@ import {
|
||||
loadLabResults,
|
||||
} from "./clinical-records";
|
||||
|
||||
const GLUCOSE_CONTEXTS: GlucoseContext[] = [
|
||||
"FASTING",
|
||||
"POSTPRANDIAL",
|
||||
"RANDOM",
|
||||
"BEDTIME",
|
||||
];
|
||||
|
||||
const DENSE_REPORT_RAW_WINDOW_DAYS = 90;
|
||||
|
||||
/** No medication row is read unless at least one medication leaf is admitted. */
|
||||
@@ -413,9 +408,19 @@ export async function collectDoctorReportData(
|
||||
gender: userProfile?.gender ?? null,
|
||||
};
|
||||
if (glucosePanelOn) {
|
||||
for (const ctx of GLUCOSE_CONTEXTS) {
|
||||
// #943 — the untagged bucket is a bucket. A report built from a meter
|
||||
// that records no meal-time context used to carry an empty glucose panel.
|
||||
const groupedGlucose = groupByGlucoseContext(
|
||||
glucoseRows,
|
||||
(m) => m.glucoseContext,
|
||||
);
|
||||
const glucoseBuckets = denseGlucose
|
||||
? GLUCOSE_CONTEXT_BUCKETS
|
||||
: groupedGlucose.map(([bucket]) => bucket);
|
||||
for (const ctx of glucoseBuckets) {
|
||||
if (!denseGlucose) {
|
||||
const rows = glucoseRows.filter((m) => m.glucoseContext === ctx);
|
||||
const rows =
|
||||
groupedGlucose.find(([bucket]) => bucket === ctx)?.[1] ?? [];
|
||||
if (rows.length === 0) continue;
|
||||
const values = rows.map((r) => r.value);
|
||||
glucoseStats[ctx] = {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* Split out of the aggregator with the selection rework.
|
||||
*/
|
||||
import { collapseMeasurementsToCanonical } from "@/lib/doctor-report-helpers";
|
||||
import { glucoseContextBucket } from "@/lib/glucose";
|
||||
import type { DoctorReportStats } from "@/lib/doctor-report-types";
|
||||
import type { GlucoseClinicalMetrics } from "@/lib/analytics/glucose-metrics";
|
||||
import type { DenseMeasurementBucket } from "./dense-buckets";
|
||||
@@ -117,8 +118,11 @@ export function summariseDenseBuckets(
|
||||
}
|
||||
|
||||
for (const row of canonical) {
|
||||
if (row.type !== "BLOOD_GLUCOSE" || !row.glucoseContext) continue;
|
||||
accumulate(glucoseStatsAcc, row.glucoseContext, {
|
||||
if (row.type !== "BLOOD_GLUCOSE") continue;
|
||||
// #943 — a reading with no meal-time context is filed under the shared
|
||||
// untagged bucket. Skipping it here dropped the whole panel for an
|
||||
// account whose meter never records one.
|
||||
accumulate(glucoseStatsAcc, glucoseContextBucket(row.glucoseContext), {
|
||||
count: row.count,
|
||||
sum: row.sumValue,
|
||||
min: row.minValue,
|
||||
|
||||
@@ -77,6 +77,10 @@ export const GLUCOSE_LOINC: Record<string, { loinc: string; display: string }> =
|
||||
},
|
||||
RANDOM: { loinc: "2339-0", display: "Glucose [Mass/volume] in Blood" },
|
||||
BEDTIME: { loinc: "2339-0", display: "Glucose [Mass/volume] in Blood" },
|
||||
// #943 — the untagged bucket. Already named in the table above; without
|
||||
// the entry the exported bundle silently dropped every reading whose
|
||||
// source recorded no meal time.
|
||||
UNSPECIFIED: { loinc: "2339-0", display: "Glucose [Mass/volume] in Blood" },
|
||||
};
|
||||
|
||||
/* ── Clinical glucose-panel LOINCs (v1.18.0) ───────────────────────────
|
||||
|
||||
+87
-4
@@ -49,11 +49,93 @@ export function resolveGlucoseUnit(
|
||||
}
|
||||
|
||||
/**
|
||||
* Threshold metric key corresponding to a glucose context. Keeps the
|
||||
* The `GlucoseContext` enum members, in the order every surface iterates them.
|
||||
*/
|
||||
export const NAMED_GLUCOSE_CONTEXTS = [
|
||||
"FASTING",
|
||||
"POSTPRANDIAL",
|
||||
"RANDOM",
|
||||
"BEDTIME",
|
||||
] as const;
|
||||
|
||||
export type NamedGlucoseContext = (typeof NAMED_GLUCOSE_CONTEXTS)[number];
|
||||
|
||||
/**
|
||||
* The bucket every reading lands in whose `glucoseContext` column is NULL,
|
||||
* blank, or not one of the four enum members.
|
||||
*
|
||||
* It is not a `GlucoseContext` value and never reaches the database — the
|
||||
* column stays NULL. It exists because a reading without a meal-time tag is
|
||||
* still a reading, and a surface that iterates only the named contexts drops
|
||||
* it silently. That is not hypothetical: a meter synced through Apple Health
|
||||
* writes no HealthKit meal-time metadata at all, so such an account has one
|
||||
* hundred percent of its readings here and saw an empty dashboard, empty
|
||||
* targets, and an empty doctor-report panel while the data was current
|
||||
* (#943). The Coach's glucose block already grouped them under the same
|
||||
* name — this promotes that one bucket to the shared notion the rest of the
|
||||
* tree resolves through.
|
||||
*/
|
||||
export const GLUCOSE_CONTEXT_UNSPECIFIED = "UNSPECIFIED";
|
||||
|
||||
export type GlucoseContextBucket =
|
||||
NamedGlucoseContext | typeof GLUCOSE_CONTEXT_UNSPECIFIED;
|
||||
|
||||
/** Canonical iteration order: the named contexts first, untagged last. */
|
||||
export const GLUCOSE_CONTEXT_BUCKETS = [
|
||||
...NAMED_GLUCOSE_CONTEXTS,
|
||||
GLUCOSE_CONTEXT_UNSPECIFIED,
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Resolve a stored `glucose_context` cell to the bucket it belongs to.
|
||||
* NULL, an empty string, and any value outside the enum all resolve to
|
||||
* {@link GLUCOSE_CONTEXT_UNSPECIFIED} — the fail-open arm, because dropping
|
||||
* a reading is worse than filing it under "no meal-time tag".
|
||||
*/
|
||||
export function glucoseContextBucket(
|
||||
raw: string | null | undefined,
|
||||
): GlucoseContextBucket {
|
||||
if (raw == null) return GLUCOSE_CONTEXT_UNSPECIFIED;
|
||||
const key = raw.trim().toUpperCase();
|
||||
return (NAMED_GLUCOSE_CONTEXTS as readonly string[]).includes(key)
|
||||
? (key as NamedGlucoseContext)
|
||||
: GLUCOSE_CONTEXT_UNSPECIFIED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group rows into their glucose buckets, in {@link GLUCOSE_CONTEXT_BUCKETS}
|
||||
* order, skipping buckets with no rows. Row order inside a bucket is the
|
||||
* caller's input order, so a caller that reads "latest" off the head or tail
|
||||
* keeps doing so.
|
||||
*/
|
||||
export function groupByGlucoseContext<T>(
|
||||
rows: readonly T[],
|
||||
contextOf: (row: T) => string | null | undefined,
|
||||
): Array<[GlucoseContextBucket, T[]]> {
|
||||
const byBucket = new Map<GlucoseContextBucket, T[]>();
|
||||
for (const row of rows) {
|
||||
const bucket = glucoseContextBucket(contextOf(row));
|
||||
const list = byBucket.get(bucket);
|
||||
if (list) list.push(row);
|
||||
else byBucket.set(bucket, [row]);
|
||||
}
|
||||
return GLUCOSE_CONTEXT_BUCKETS.flatMap((bucket) => {
|
||||
const list = byBucket.get(bucket);
|
||||
return list ? [[bucket, list] as [GlucoseContextBucket, T[]]] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Threshold metric key corresponding to a glucose bucket. Keeps the
|
||||
* effective-range resolver the single source of truth.
|
||||
*
|
||||
* The untagged bucket borrows the RANDOM band: a reading with no meal-time
|
||||
* tag IS a spot reading, which is exactly what RANDOM means, and inventing a
|
||||
* fifth threshold would give the user a second editor row that judges the
|
||||
* same readings by a different number.
|
||||
*/
|
||||
export function thresholdMetricForContext(
|
||||
context: "FASTING" | "POSTPRANDIAL" | "RANDOM" | "BEDTIME",
|
||||
context: GlucoseContextBucket,
|
||||
):
|
||||
| "BLOOD_GLUCOSE_FASTING"
|
||||
| "BLOOD_GLUCOSE_POSTPRANDIAL"
|
||||
@@ -64,9 +146,10 @@ export function thresholdMetricForContext(
|
||||
return "BLOOD_GLUCOSE_FASTING";
|
||||
case "POSTPRANDIAL":
|
||||
return "BLOOD_GLUCOSE_POSTPRANDIAL";
|
||||
case "RANDOM":
|
||||
return "BLOOD_GLUCOSE_RANDOM";
|
||||
case "BEDTIME":
|
||||
return "BLOOD_GLUCOSE_BEDTIME";
|
||||
case "RANDOM":
|
||||
case GLUCOSE_CONTEXT_UNSPECIFIED:
|
||||
return "BLOOD_GLUCOSE_RANDOM";
|
||||
}
|
||||
}
|
||||
@@ -507,7 +507,7 @@ const analyticsDefaultResponse = z
|
||||
.record(z.string(), dataSummary)
|
||||
.nullable()
|
||||
.describe(
|
||||
"Per-context glucose summaries (FASTING / POSTPRANDIAL / RANDOM / BEDTIME) over the trailing 30 days, canonical mg/dL. Contexts with no readings are omitted; the whole block is null when the glucose module is off.",
|
||||
"Per-context glucose summaries (FASTING / POSTPRANDIAL / RANDOM / BEDTIME, plus UNSPECIFIED for readings whose source recorded no meal-time context) over the trailing 30 days, canonical mg/dL. Buckets with no readings are omitted; the whole block is null when the glucose module is off.",
|
||||
),
|
||||
glucoseClinical: glucoseClinicalSchema
|
||||
.nullable()
|
||||
|
||||
@@ -2178,7 +2178,7 @@ export const analyticsDefaultSliceResponse = z
|
||||
.record(z.string(), dataSummary)
|
||||
.nullable()
|
||||
.describe(
|
||||
"Per-context summaries (`FASTING` / `POSTPRANDIAL` / `RANDOM` / `BEDTIME`) over the trailing 30 days, canonical mg/dL. A context with no readings is omitted. NULL — not an empty object — when the glucose module is off.",
|
||||
"Per-context summaries (`FASTING` / `POSTPRANDIAL` / `RANDOM` / `BEDTIME`, plus `UNSPECIFIED` for readings whose source recorded no meal-time context) over the trailing 30 days, canonical mg/dL. A bucket with no readings is omitted. NULL — not an empty object — when the glucose module is off.",
|
||||
),
|
||||
glucoseClinical: glucoseClinicalSchema
|
||||
.nullable()
|
||||
|
||||
@@ -135,6 +135,68 @@ describe("target section builders", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("emits a card for readings with no meal-time context (#943)", () => {
|
||||
// A meter synced through Apple Health writes no HealthKit meal-time
|
||||
// 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 },
|
||||
],
|
||||
profile: {
|
||||
heightCm: 180,
|
||||
dateOfBirth: new Date("1985-01-01T00:00:00.000Z"),
|
||||
gender: "MALE",
|
||||
glucoseUnit: "mg/dL",
|
||||
hasDiabetes: false,
|
||||
thresholdsJson: null,
|
||||
},
|
||||
timezone: TZ,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(targets.map((target) => target.type)).toEqual([
|
||||
"BLOOD_GLUCOSE_UNSPECIFIED",
|
||||
]);
|
||||
expect(targets[0]).toMatchObject({
|
||||
label: "targets.glucoseUnspecified",
|
||||
current: 112,
|
||||
average30: 108,
|
||||
unit: "mg/dL",
|
||||
});
|
||||
// The untagged bucket is judged against the RANDOM band, so it still
|
||||
// carries a range and a classification rather than a blank card.
|
||||
expect(targets[0].range).not.toBeNull();
|
||||
expect(targets[0].classification).not.toBeNull();
|
||||
});
|
||||
|
||||
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 },
|
||||
],
|
||||
profile: {
|
||||
heightCm: 180,
|
||||
dateOfBirth: new Date("1985-01-01T00:00:00.000Z"),
|
||||
gender: "MALE",
|
||||
glucoseUnit: "mg/dL",
|
||||
hasDiabetes: false,
|
||||
thresholdsJson: null,
|
||||
},
|
||||
timezone: TZ,
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(targets.map((target) => target.type)).toEqual([
|
||||
"BLOOD_GLUCOSE_FASTING",
|
||||
"BLOOD_GLUCOSE_RANDOM",
|
||||
"BLOOD_GLUCOSE_UNSPECIFIED",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps summary streak ties stable by public target order", () => {
|
||||
expect(
|
||||
buildTargetPageSummary([
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
import type { GlucoseContext } from "@/generated/prisma/client";
|
||||
import { resolveGlucoseUnit } from "@/lib/glucose";
|
||||
import {
|
||||
groupByGlucoseContext,
|
||||
resolveGlucoseUnit,
|
||||
type GlucoseContextBucket,
|
||||
} from "@/lib/glucose";
|
||||
import { resolveGlucoseTarget } from "./glucose-targets";
|
||||
import { makeRangeClassifier, rollupConsistency } from "./consistency";
|
||||
import type { TargetGlucoseRow, TargetItem, TargetProfile } from "./types";
|
||||
|
||||
const GLUCOSE_CONTEXTS: GlucoseContext[] = [
|
||||
"FASTING",
|
||||
"POSTPRANDIAL",
|
||||
"RANDOM",
|
||||
"BEDTIME",
|
||||
];
|
||||
|
||||
const LABEL_BY_CONTEXT: Record<GlucoseContext, string> = {
|
||||
const LABEL_BY_CONTEXT: Record<GlucoseContextBucket, string> = {
|
||||
FASTING: "targets.glucoseFasting",
|
||||
POSTPRANDIAL: "targets.glucosePostprandial",
|
||||
RANDOM: "targets.glucoseRandom",
|
||||
BEDTIME: "targets.glucoseBedtime",
|
||||
UNSPECIFIED: "targets.glucoseUnspecified",
|
||||
};
|
||||
|
||||
interface GlucoseTargetsInput {
|
||||
@@ -35,10 +32,13 @@ export function buildGlucoseTargets({
|
||||
const unit = resolveGlucoseUnit(profile.glucoseUnit);
|
||||
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
for (const context of GLUCOSE_CONTEXTS) {
|
||||
const contextRows = rows.filter((row) => row.glucoseContext === context);
|
||||
if (contextRows.length === 0) continue;
|
||||
|
||||
// #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,
|
||||
)) {
|
||||
const latest = contextRows[0].value;
|
||||
const recent = contextRows.filter((row) => row.measuredAt >= thirtyDaysAgo);
|
||||
const average30 =
|
||||
|
||||
@@ -40,10 +40,17 @@ import {
|
||||
type UserProfileForRange,
|
||||
} from "@/lib/analytics/effective-range";
|
||||
import type { TrafficRange } from "@/lib/analytics/value-bands";
|
||||
import { thresholdMetricForContext } from "@/lib/glucose";
|
||||
import {
|
||||
thresholdMetricForContext,
|
||||
type GlucoseContextBucket,
|
||||
} from "@/lib/glucose";
|
||||
|
||||
export type GlucoseContextKey =
|
||||
"FASTING" | "POSTPRANDIAL" | "RANDOM" | "BEDTIME";
|
||||
/**
|
||||
* The buckets a glucose target can be resolved for — the four named contexts
|
||||
* plus the untagged bucket (#943), which is judged against the RANDOM band
|
||||
* because an untagged reading is a spot reading.
|
||||
*/
|
||||
export type GlucoseContextKey = GlucoseContextBucket;
|
||||
|
||||
/**
|
||||
* ADA glycemic GOAL bands for people living with diabetes (mg/dL).
|
||||
@@ -59,6 +66,9 @@ export type GlucoseContextKey =
|
||||
* higher floor guards against nocturnal hypoglycemia. Kept identical to the
|
||||
* non-diabetic bedtime band on purpose — the diabetic delta lives in the
|
||||
* fasting/post-prandial goals, where ADA is explicit.
|
||||
* UNSPECIFIED: a reading whose source recorded no meal-time context. Same band
|
||||
* as RANDOM, and for the same reason — an untagged reading is a spot
|
||||
* reading, and the post-prandial goal is the defensible comparator.
|
||||
*/
|
||||
const DIABETIC_GOAL_BANDS: Record<
|
||||
GlucoseContextKey,
|
||||
@@ -68,6 +78,7 @@ const DIABETIC_GOAL_BANDS: Record<
|
||||
POSTPRANDIAL: { min: 80, max: 180 },
|
||||
RANDOM: { min: 80, max: 180 },
|
||||
BEDTIME: { min: 90, max: 150 },
|
||||
UNSPECIFIED: { min: 80, max: 180 },
|
||||
};
|
||||
|
||||
/** Source label surfaced on the resolved range for the targets surface. */
|
||||
|
||||
Reference in new issue
Block a user