mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
feat(insights): stat strip, range band, all-readings subpage, diversity nudge
Add the data-value features to the insights category pages on top of the density pass: - Stat strip: lead each metric page with min / max / median / mean, read from the already-fetched analytics summaries slice (no new network). Median is now computed in both summary producers — exact in the live path, a windowed PERCENTILE_CONT in the rollup-tier slim slice. The thin HealthKit pages mount it too for parity; no AI assessment is added there. - Range band: shade an Apple-Health-style min-max area around the daily mean line where the data supports it (non-cumulative metrics). The daily-aggregate read now emits per-day min / max from the rollup buckets; the band rides the existing target-range toggle. - All readings: a dedicated per-metric subpage at /insights/values/<type> reusing the measurement list pinned to one type (pagination + inline edit/delete). A clear entry button mounts at the foot of each category page. - Diversity nudge: a gentle hint when a metric's readings cluster on one weekday or time of day, computed from a bounded, cached timestamp window — non-blocking, self-gating. All new reads stay cache-friendly and off the navigation path.
This commit is contained in:
1 parent
cf649f72ce
commit
6ce09cc76d
32 files changed
+1063
-37
No files matched your search
@@ -24,6 +24,7 @@ const stubSummary = (): DataSummary => ({
|
||||
min: 76,
|
||||
max: 80,
|
||||
mean: 78,
|
||||
median: 78,
|
||||
avg7: 78.2,
|
||||
avg30: 77.9,
|
||||
slope7: null,
|
||||
|
||||
@@ -74,6 +74,7 @@ describe("computeSummariesSlice", () => {
|
||||
min: null,
|
||||
max: null,
|
||||
mean: null,
|
||||
median: null,
|
||||
avg7: null,
|
||||
avg30: null,
|
||||
slope7: null,
|
||||
@@ -273,6 +274,7 @@ describe("computeSummariesSlice", () => {
|
||||
type: "WEIGHT",
|
||||
avg7: 82,
|
||||
avg30: 82.5,
|
||||
median: 82.1,
|
||||
slope7: 0.02,
|
||||
r2_7: 0.5,
|
||||
slope30: 0.01,
|
||||
@@ -307,6 +309,9 @@ describe("computeSummariesSlice", () => {
|
||||
expect(weight.min).toBe(79.5);
|
||||
expect(weight.max).toBe(84.0);
|
||||
expect(weight.mean).toBe(82);
|
||||
// v1.8.5 — the windowed median flows through from the narrow
|
||||
// `PERCENTILE_CONT` column onto the slim summary.
|
||||
expect(weight.median).toBe(82.1);
|
||||
expect(weight.latest).toBe(82.7);
|
||||
expect(weight.avg7).toBe(82);
|
||||
expect(weight.slope7).toEqual({
|
||||
|
||||
@@ -76,6 +76,7 @@ describe("summarize", () => {
|
||||
expect(summary.min).toBeNull();
|
||||
expect(summary.max).toBeNull();
|
||||
expect(summary.mean).toBeNull();
|
||||
expect(summary.median).toBeNull();
|
||||
expect(summary.avg7).toBeNull();
|
||||
expect(summary.avg30).toBeNull();
|
||||
});
|
||||
@@ -88,10 +89,33 @@ describe("summarize", () => {
|
||||
expect(summary.min).toBe(70);
|
||||
expect(summary.max).toBe(80);
|
||||
expect(summary.mean).toBe(75);
|
||||
// 11 values — odd length, median is the 6th value (75).
|
||||
expect(summary.median).toBe(75);
|
||||
expect(summary.avg7).not.toBeNull();
|
||||
expect(summary.slope7).not.toBeNull();
|
||||
});
|
||||
|
||||
// v1.8.5 — median powers the category-page stat strip. It must be the
|
||||
// 50th percentile over VALUES (not timestamps) and must resist a skew
|
||||
// the mean would otherwise hide.
|
||||
it("computes the median over an even-length series as the midpoint", () => {
|
||||
// Four values; median = (72 + 74) / 2 = 73. Insertion order is
|
||||
// intentionally not sorted to prove the helper sorts by value.
|
||||
const data = makePoints([74, 70, 72, 76], 4);
|
||||
const summary = summarize(data);
|
||||
expect(summary.median).toBe(73);
|
||||
});
|
||||
|
||||
it("median diverges from the mean on a right-skewed series", () => {
|
||||
// One large outlier drags the mean up; the median stays at the
|
||||
// central reading — exactly the honesty the stat strip surfaces.
|
||||
const data = makePoints([10, 11, 12, 13, 200], 5);
|
||||
const summary = summarize(data);
|
||||
expect(summary.median).toBe(12);
|
||||
expect(summary.mean).not.toBe(summary.median);
|
||||
expect(summary.mean as number).toBeGreaterThan(summary.median as number);
|
||||
});
|
||||
|
||||
// v3 audit caught a divergence: summarize().avg7 used `now` as the
|
||||
// window anchor, while trendSlope() used the last point. A stale
|
||||
// series (no readings for weeks) reported a slope but no average.
|
||||
|
||||
@@ -109,6 +109,16 @@ interface NarrowAggregateRow {
|
||||
type: string;
|
||||
avg7: number | null;
|
||||
avg30: number | null;
|
||||
/**
|
||||
* v1.8.5 — 50th percentile over the trailing 90-day window. The
|
||||
* windowed median is cheap (the narrow query already index-scans the
|
||||
* 90-day partition) and represents the central reading the stat strip
|
||||
* surfaces next to min / max / mean. An all-time median would require
|
||||
* sorting every raw row per type, which the rollup tier cannot
|
||||
* compose and which the perf posture (v1.8.3 anti-freeze) forbids on
|
||||
* the read path. Null when the window holds no rows.
|
||||
*/
|
||||
median: number | null;
|
||||
avg30_last_month: number | null;
|
||||
slope7: number | null;
|
||||
r2_7: number | null;
|
||||
@@ -159,6 +169,7 @@ function emptySummary(): DataSummary {
|
||||
min: null,
|
||||
max: null,
|
||||
mean: null,
|
||||
median: null,
|
||||
avg7: null,
|
||||
avg30: null,
|
||||
slope7: null,
|
||||
@@ -271,6 +282,11 @@ async function computeFromRollups(userId: string): Promise<SummariesSlice> {
|
||||
WHERE m."measured_at" >= NOW() - INTERVAL '60 days'
|
||||
AND m."measured_at" < NOW() - INTERVAL '30 days'
|
||||
)::double precision AS avg30_last_month,
|
||||
PERCENTILE_CONT(0.5) WITHIN GROUP (
|
||||
ORDER BY m."value"
|
||||
) FILTER (
|
||||
WHERE m."measured_at" >= NOW() - INTERVAL '90 days'
|
||||
)::double precision AS median,
|
||||
REGR_SLOPE(
|
||||
m."value",
|
||||
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
|
||||
@@ -414,6 +430,7 @@ async function computeFromRollups(userId: string): Promise<SummariesSlice> {
|
||||
min: round2(row.min),
|
||||
max: round2(row.max),
|
||||
mean: round2(row.mean),
|
||||
median: round2(narrow?.median ?? null),
|
||||
avg7: round2(narrow?.avg7 ?? null),
|
||||
avg30: round2(narrow?.avg30 ?? null),
|
||||
slope7: buildSlope(narrow?.slope7 ?? null, narrow?.r2_7 ?? null),
|
||||
@@ -509,6 +526,11 @@ async function computeFromLiveAggregate(
|
||||
WHERE m."measured_at" >= NOW() - INTERVAL '60 days'
|
||||
AND m."measured_at" < NOW() - INTERVAL '30 days'
|
||||
)::double precision AS avg30_last_month,
|
||||
PERCENTILE_CONT(0.5) WITHIN GROUP (
|
||||
ORDER BY m."value"
|
||||
) FILTER (
|
||||
WHERE m."measured_at" >= NOW() - INTERVAL '90 days'
|
||||
)::double precision AS median,
|
||||
REGR_SLOPE(
|
||||
m."value",
|
||||
EXTRACT(EPOCH FROM m."measured_at") / 86400.0
|
||||
@@ -617,6 +639,7 @@ async function computeFromLiveAggregate(
|
||||
min: round2(row.min_value),
|
||||
max: round2(row.max_value),
|
||||
mean: round2(row.mean_value),
|
||||
median: round2(win?.median ?? null),
|
||||
avg7: round2(win?.avg7 ?? null),
|
||||
avg30: round2(win?.avg30 ?? null),
|
||||
slope7: buildSlope(win?.slope7 ?? null, win?.r2_7 ?? null),
|
||||
|
||||
@@ -120,6 +120,13 @@ export interface DataSummary {
|
||||
max: number | null;
|
||||
/** Null when the series is empty (vs the previous 0 sentinel). */
|
||||
mean: number | null;
|
||||
/**
|
||||
* v1.8.5 — 50th percentile (median) of the value series. Surfaced on
|
||||
* the insights category-page stat strip alongside min / max / mean so
|
||||
* a skewed series (a few very high or very low readings dragging the
|
||||
* mean) reads honestly. Null when the series is empty.
|
||||
*/
|
||||
median: number | null;
|
||||
avg7: number | null;
|
||||
avg30: number | null;
|
||||
slope7: TrendSlope | null;
|
||||
@@ -152,6 +159,7 @@ export function summarize(data: DataPoint[]): DataSummary {
|
||||
min: null,
|
||||
max: null,
|
||||
mean: null,
|
||||
median: null,
|
||||
avg7: null,
|
||||
avg30: null,
|
||||
slope7: null,
|
||||
@@ -184,6 +192,19 @@ export function summarize(data: DataPoint[]): DataSummary {
|
||||
}
|
||||
const mean = sum / values.length;
|
||||
|
||||
// v1.8.5 — median (50th percentile) over the full series. A separate
|
||||
// numeric sort from the date-ordered `sorted` array above so the
|
||||
// percentile is taken over values, not timestamps. Linear-interpolated
|
||||
// midpoint on an even-length series (the standard PERCENTILE_CONT
|
||||
// definition) so this matches the SQL `PERCENTILE_CONT(0.5)` the
|
||||
// rollup-tier slim slice emits.
|
||||
const valueSorted = [...values].sort((a, b) => a - b);
|
||||
const mid = Math.floor(valueSorted.length / 2);
|
||||
const median =
|
||||
valueSorted.length % 2 === 0
|
||||
? (valueSorted[mid - 1] + valueSorted[mid]) / 2
|
||||
: valueSorted[mid];
|
||||
|
||||
const now = Date.now();
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const last7 = sorted.filter((p) => now - p.date.getTime() < 7 * DAY);
|
||||
@@ -215,6 +236,7 @@ export function summarize(data: DataPoint[]): DataSummary {
|
||||
min: minVal,
|
||||
max: maxVal,
|
||||
mean: Math.round(mean * 100) / 100,
|
||||
median: Math.round(median * 100) / 100,
|
||||
avg7:
|
||||
last7.length > 0
|
||||
? Math.round(
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
import { detectMeasurementDiversity } from "../measurement-diversity";
|
||||
|
||||
/**
|
||||
* v1.8.5 — measurement-diversity detection.
|
||||
*
|
||||
* The nudge fires when a metric's readings cluster on a single weekday
|
||||
* or a narrow time-of-day band, hinting the user to spread their
|
||||
* measurements for a fuller picture. Pure function over ISO timestamps
|
||||
* so the unit test pins the thresholds without a DOM.
|
||||
*/
|
||||
|
||||
// Build N ISO timestamps, all on the same weekday (Tuesdays) at 09:00.
|
||||
function tuesdaysAt(hour: number, count: number): string[] {
|
||||
// 2026-06-02 is a Tuesday.
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const d = new Date(2026, 5, 2 + i * 7, hour, 0, 0);
|
||||
out.push(d.toISOString());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Build N timestamps spread across every weekday at varied hours.
|
||||
function spreadAcrossWeek(count: number): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const d = new Date(2026, 5, 1 + i, 6 + (i % 12), 0, 0);
|
||||
out.push(d.toISOString());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("detectMeasurementDiversity", () => {
|
||||
it("returns null below the minimum sample floor", () => {
|
||||
expect(detectMeasurementDiversity(tuesdaysAt(9, 3))).toBeNull();
|
||||
});
|
||||
|
||||
it("flags a weekday cluster when most readings fall on one day", () => {
|
||||
const result = detectMeasurementDiversity(tuesdaysAt(9, 10));
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.kind).toBe("weekday");
|
||||
});
|
||||
|
||||
it("flags a time-of-day cluster when the weekday is spread", () => {
|
||||
// Spread across weekdays but every reading at 08:00 → time cluster.
|
||||
const sameHour: string[] = [];
|
||||
for (let i = 0; i < 12; i++) {
|
||||
sameHour.push(new Date(2026, 5, 1 + i, 8, 0, 0).toISOString());
|
||||
}
|
||||
const result = detectMeasurementDiversity(sameHour);
|
||||
expect(result?.kind).toBe("timeOfDay");
|
||||
});
|
||||
|
||||
it("returns null for well-spread readings", () => {
|
||||
expect(detectMeasurementDiversity(spreadAcrossWeek(14))).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores invalid timestamps without throwing", () => {
|
||||
const mixed = [...tuesdaysAt(9, 10), "not-a-date", ""];
|
||||
const result = detectMeasurementDiversity(mixed);
|
||||
expect(result?.kind).toBe("weekday");
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ function fakeSummary(count: number): DataSummary {
|
||||
min: null,
|
||||
max: null,
|
||||
mean: null,
|
||||
median: null,
|
||||
avg7: null,
|
||||
avg30: null,
|
||||
slope7: null,
|
||||
|
||||
@@ -490,6 +490,11 @@ async function buildFromRollups(
|
||||
min: round2(composed.min),
|
||||
max: round2(composed.max),
|
||||
mean: round2(composed.mean),
|
||||
// v1.8.5 — the comprehensive aggregator feeds the AI snapshot, not
|
||||
// the category-page stat strip, and does not compute a percentile.
|
||||
// Left null so the shared `DataSummary` contract holds without
|
||||
// paying a per-type percentile sort on the AI read path.
|
||||
median: null,
|
||||
avg7: round2(narrow?.avg7 ?? null),
|
||||
avg30: round2(narrow?.avg30 ?? null),
|
||||
slope7: buildSlope(narrow?.slope7 ?? null, narrow?.r2_7 ?? null),
|
||||
@@ -662,6 +667,9 @@ async function buildFromLiveAggregate(
|
||||
min: round2(row.min_value),
|
||||
max: round2(row.max_value),
|
||||
mean: round2(row.mean_value),
|
||||
// v1.8.5 — see the parallel block above: the AI snapshot path
|
||||
// omits the percentile.
|
||||
median: null,
|
||||
avg7: round2(row.avg7),
|
||||
avg30: round2(row.avg30),
|
||||
slope7: buildSlope(row.slope7, row.r2_7),
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* v1.8.5 — measurement-diversity detection for the insights category
|
||||
* pages.
|
||||
*
|
||||
* When a user's readings for a metric cluster on a single weekday (only
|
||||
* Tuesdays) or a narrow time-of-day band (always right after waking),
|
||||
* the trend reads a biased slice of reality. This helper inspects the
|
||||
* timestamps of a bounded recent window and, if the spread is too
|
||||
* narrow, returns a hint the page surfaces as a gentle nudge to measure
|
||||
* on other days / times.
|
||||
*
|
||||
* Pure + deterministic over ISO timestamp strings so it is trivially
|
||||
* unit-tested and cache-friendly: the component computes it from the
|
||||
* raw rows it already has, with no blocking work and no extra round-trip
|
||||
* beyond the bounded list fetch it shares with the values subpage.
|
||||
*/
|
||||
|
||||
export type DiversityKind = "weekday" | "timeOfDay";
|
||||
|
||||
export interface DiversitySignal {
|
||||
kind: DiversityKind;
|
||||
/** Share (0–1) of readings that fell in the dominant bucket. */
|
||||
share: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum number of valid readings before the nudge can fire. Below
|
||||
* this the clustering is not yet meaningful — a handful of readings on
|
||||
* one day is normal for a brand-new metric.
|
||||
*/
|
||||
const MIN_SAMPLES = 8;
|
||||
|
||||
/**
|
||||
* Fraction of readings that must fall in a single bucket for the bucket
|
||||
* to count as a cluster. 0.7 keeps the nudge conservative — it only
|
||||
* fires when the spread is genuinely lopsided.
|
||||
*/
|
||||
const CLUSTER_THRESHOLD = 0.7;
|
||||
|
||||
/**
|
||||
* Time-of-day bands (in hours). A reading clusters by time when ≥
|
||||
* `CLUSTER_THRESHOLD` of readings fall in the same 6-hour band.
|
||||
*/
|
||||
const TIME_BAND_HOURS = 6;
|
||||
|
||||
interface LocalParts {
|
||||
weekday: number; // 0–6
|
||||
hour: number; // 0–23
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a timestamp's weekday + hour in the given IANA timezone, or
|
||||
* the runtime-local zone when none is supplied. Returns null for an
|
||||
* unparseable timestamp so the caller can skip it.
|
||||
*/
|
||||
function localParts(iso: string, timeZone?: string): LocalParts | null {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
if (!timeZone) {
|
||||
return { weekday: date.getDay(), hour: date.getHours() };
|
||||
}
|
||||
// Intl resolves the wall-clock weekday + hour in the target zone.
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
weekday: "short",
|
||||
hour: "numeric",
|
||||
hour12: false,
|
||||
}).formatToParts(date);
|
||||
const weekdayName = parts.find((p) => p.type === "weekday")?.value ?? "";
|
||||
const hourStr = parts.find((p) => p.type === "hour")?.value ?? "0";
|
||||
const weekdayMap: Record<string, number> = {
|
||||
Sun: 0,
|
||||
Mon: 1,
|
||||
Tue: 2,
|
||||
Wed: 3,
|
||||
Thu: 4,
|
||||
Fri: 5,
|
||||
Sat: 6,
|
||||
};
|
||||
const weekday = weekdayMap[weekdayName] ?? 0;
|
||||
// `hour12: false` can emit "24" for midnight in some engines.
|
||||
const hour = Number(hourStr) % 24;
|
||||
return { weekday, hour: Number.isFinite(hour) ? hour : 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect the timestamps and return the dominant clustering signal, or
|
||||
* null when the readings are well spread (or below the sample floor).
|
||||
* Weekday clustering takes precedence — it is the coarser, more
|
||||
* actionable bias ("you only measure on Tuesdays").
|
||||
*/
|
||||
export function detectMeasurementDiversity(
|
||||
timestamps: ReadonlyArray<string>,
|
||||
timeZone?: string,
|
||||
): DiversitySignal | null {
|
||||
const parts: LocalParts[] = [];
|
||||
for (const iso of timestamps) {
|
||||
const p = localParts(iso, timeZone);
|
||||
if (p) parts.push(p);
|
||||
}
|
||||
if (parts.length < MIN_SAMPLES) return null;
|
||||
|
||||
// Weekday histogram.
|
||||
const weekdayCounts = new Array<number>(7).fill(0);
|
||||
for (const p of parts) weekdayCounts[p.weekday] += 1;
|
||||
const topWeekday = Math.max(...weekdayCounts);
|
||||
const weekdayShare = topWeekday / parts.length;
|
||||
if (weekdayShare >= CLUSTER_THRESHOLD) {
|
||||
return { kind: "weekday", share: weekdayShare };
|
||||
}
|
||||
|
||||
// Time-of-day histogram (6-hour bands → 4 buckets).
|
||||
const bandCount = Math.ceil(24 / TIME_BAND_HOURS);
|
||||
const bandCounts = new Array<number>(bandCount).fill(0);
|
||||
for (const p of parts) {
|
||||
bandCounts[Math.floor(p.hour / TIME_BAND_HOURS) % bandCount] += 1;
|
||||
}
|
||||
const topBand = Math.max(...bandCounts);
|
||||
const timeShare = topBand / parts.length;
|
||||
if (timeShare >= CLUSTER_THRESHOLD) {
|
||||
return { kind: "timeOfDay", share: timeShare };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -374,6 +374,16 @@ export const queryKeys = {
|
||||
toIso,
|
||||
valueScale,
|
||||
] as const,
|
||||
|
||||
/**
|
||||
* v1.8.5 — bounded recent-timestamp read powering the
|
||||
* measurement-diversity nudge on an insights category page. Keyed by
|
||||
* the page's `MeasurementType` so each metric caches its own window.
|
||||
* Shares the `measurement-dependent` invalidation prefix below so an
|
||||
* edit/delete in the values subpage re-runs the clustering check.
|
||||
*/
|
||||
measurementDiversity: (type: string) =>
|
||||
["measurement-diversity", type] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -394,6 +404,8 @@ export const measurementDependentKeys = [
|
||||
queryKeys.insightsTargets(),
|
||||
queryKeys.gamificationAchievements(),
|
||||
["chart-data"] as const,
|
||||
// v1.8.5 — re-run the diversity-nudge clustering when readings change.
|
||||
["measurement-diversity"] as const,
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user