v1.4.37 — final web polish before iOS focus

Carries the v1.4.36 perf carry-over for the full /api/analytics
route (correlations + healthScore + bp_in_target on the rollup-
coverage probe, 111s cold worst-case down to ~1.5-3s on power-user
accounts), consolidates Apple Health step samples into a one-row-
per-day list view with chevron drill-down and a nightly drain
(~50x table compression once it converges), restores
IntakeHistoryListV2 to the pre-v1.4.28 contract, converges every
Coach affordance behind a single feature gate with an invariant
test pin, lifts the medication-detail Mounjaro card to byte-
equivalent parity with Ramipril, brings the Insights overview
hero row to height parity, hardens getClientIp behind a new
TRUST_CF_CONNECTING_IP env flag, ships the Arztbericht hero card
on Settings -> Export, adds the Medikamenteneinnahme quick-add
overlay to the dashboard, drops the timezone override toggle for
a silent browser-zone auto-seed, and fixes the v1.4.36 red CI
workflows. Documentation refreshed across all three repos with
five new architecture diagrams in the Dracula palette. Unit suite
4354 -> 4486 passing; typecheck + lint clean.
This commit is contained in:
Marc-André Bombeck committed 2026-05-17 15:36:38 +02:00
1 parent 0e2a99f8e7
commit 88028fa082
121 files changed
+13912 -1437

No files matched your search

+13 -2
View File
@@ -58,8 +58,19 @@ describe("v1.4.20 B3 — /insights mounts CorrelationRow + TrendsRow", () => {
});
describe("v1.4.20 B3 — /api/analytics surfaces correlations", () => {
// v1.4.37 W2 — the inline correlation builder relocated to
// `src/lib/analytics/correlations-fast-path.ts`. The route now
// delegates through `computeCorrelationHypothesesFastPath`; the
// three Pearson runner imports live alongside the new dispatcher.
// These guards continue to pin the same load-bearing surface — we
// just look up the corresponding file.
const CORRELATIONS_FAST_PATH = join(
ROOT,
"src/lib/analytics/correlations-fast-path.ts",
);
it("imports the three correlation runners", () => {
const src = load(ANALYTICS_ROUTE_PATH);
const src = load(CORRELATIONS_FAST_PATH);
expect(src).toContain("correlateBpCompliance");
expect(src).toContain("correlateMoodPulse");
expect(src).toContain("correlateWeightWeekday");
@@ -72,7 +83,7 @@ describe("v1.4.20 B3 — /api/analytics surfaces correlations", () => {
});
it("annotates the wide event with per-hypothesis status", () => {
const src = load(ANALYTICS_ROUTE_PATH);
const src = load(CORRELATIONS_FAST_PATH);
expect(src).toMatch(
/annotate\(\{[\s\S]*correlations:[\s\S]*bpCompliance:[\s\S]*moodPulse:[\s\S]*weightWeekday:/,
);
+13 -1
View File
@@ -29,6 +29,13 @@ interface Messages {
dashboard: {
quickAddMeasurement: string;
quickAddMood: string;
/**
* v1.4.37 W7b — third quick-add row: medication intake. Same
* contract as the other two: distinct from siblings and from the
* trigger label, otherwise the screen-reader hears "Hinzufügen,
* Hinzufügen, Hinzufügen, Hinzufügen" with no way to discriminate.
*/
quickAddMedicationIntake: string;
};
}
@@ -47,21 +54,26 @@ describe("dashboard quick-add submenu labels", () => {
const measurement = messages.dashboard.quickAddMeasurement;
const mood = messages.dashboard.quickAddMood;
const medicationIntake = messages.dashboard.quickAddMedicationIntake;
const trigger = messages.common.add;
// Non-empty
expect(measurement.trim().length).toBeGreaterThan(0);
expect(mood.trim().length).toBeGreaterThan(0);
expect(medicationIntake.trim().length).toBeGreaterThan(0);
// Distinct from each other — the icon is decorative (aria-hidden),
// so the only thing distinguishing the two rows is the visible text.
// so the only thing distinguishing the rows is the visible text.
expect(measurement).not.toBe(mood);
expect(measurement).not.toBe(medicationIntake);
expect(mood).not.toBe(medicationIntake);
// Distinct from the trigger label. The trigger sits ABOVE the menu
// and announces itself first; if a menu item then repeats the same
// word, screen-readers / users get no signal which row does what.
expect(measurement).not.toBe(trigger);
expect(mood).not.toBe(trigger);
expect(medicationIntake).not.toBe(trigger);
},
);
});
+48 -6
View File
@@ -1,17 +1,18 @@
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.25 W3e — Coach drawer mount + per-card CTA gate.
*
* Two scenarios:
* Three scenarios:
* 1. AI provider configured → per-card "Ask Coach" CTAs render
* alongside each card; the drawer is mounted at the page level.
* 2. AI provider NOT configured → CTAs are completely absent (no
* broken-button state) but the drawer mount stays present (it's
* controlled by the parent regardless; no harm in mounting it
* collapsed, and it costs ~0 since closed Sheets render only the
* portal root).
* broken-button state).
* 3. v1.4.37 W5 — operator's global Coach flag off → both the CTAs
* and the page-level drawer mount vanish. The flag default is
* all-on for fresh installs and on any fetch error, so the path
* stays open by default (mocked via `useFeatureFlags` below).
*/
vi.mock("next/navigation", () => ({
@@ -19,6 +20,20 @@ vi.mock("next/navigation", () => ({
usePathname: () => "/targets",
}));
let coachFlag = true;
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => ({
...actual.DEFAULT_ASSISTANT_FLAGS,
coach: coachFlag,
}),
};
});
const sampleData = {
targets: [
{
@@ -110,6 +125,10 @@ function render() {
}
describe("/targets page — Coach drawer mount + CTA gate", () => {
beforeEach(() => {
coachFlag = true;
});
it("renders the per-card Coach CTA when an AI provider is configured", () => {
providerChainResponse = { activeProvider: "openai" };
const html = render();
@@ -130,4 +149,27 @@ describe("/targets page — Coach drawer mount + CTA gate", () => {
// configured we don't render a CTA whose click would 404.
expect(html).not.toContain('data-slot="target-coach-cta"');
});
// v1.4.37 W5 — Marc directive: when the operator turns off the
// global Coach flag, every Coach affordance on /targets must vanish.
// That is BOTH the per-card CTAs (currently gated through `aiEnabled`)
// AND the page-level <CoachDrawer> mount — so the SSE machinery,
// Sheet portal and source-chip thread never load.
it("hides every per-card Coach CTA when the global Coach flag is off", () => {
coachFlag = false;
providerChainResponse = { activeProvider: "openai" };
const html = render();
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("does not mount the CoachDrawer when the global Coach flag is off", () => {
coachFlag = false;
providerChainResponse = { activeProvider: "openai" };
const html = render();
// The drawer renders a Sheet that the body markup exposes via a
// role + the i18n key it carries. We grep on the localised
// composer label that the drawer always paints.
expect(html).not.toContain('data-slot="coach-drawer"');
expect(html).not.toContain('data-slot="coach-drawer-composer"');
});
});
+16
View File
@@ -135,6 +135,22 @@ vi.mock("@/hooks/use-auth", () => ({
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly with the
// all-on default so the i18n assertions below run against the visible
// Coach surfaces.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
@@ -98,6 +98,22 @@ vi.mock("@/hooks/use-auth", () => ({
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly so the page
// runs with the all-on default (CTAs + drawer mount visible) the
// responsive assertions below pin.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
@@ -71,6 +71,22 @@ vi.mock("@/hooks/use-auth", () => ({
}),
}));
// v1.4.37 W5 — `/targets/page.tsx` now reads `useFeatureFlags` to gate
// the Coach drawer + per-card CTAs. The hook resolves QueryClientContext
// from `@tanstack/react-query`, and this test mocks the library
// without exposing that context. Mock the hook directly with the
// all-on default so the spacing assertions below run against the
// fully-painted page shape.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: () => actual.DEFAULT_ASSISTANT_FLAGS,
};
});
import { I18nProvider } from "@/lib/i18n/context";
import TargetsPage from "../targets/page";
+42 -3
View File
@@ -19,12 +19,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
// v1.4.37 W2 — `ensureUserRollupsFresh` pokes `measurement.findFirst`
// for the newest-measurement watermark; mock both shapes.
measurement: {
findMany: vi.fn(),
findFirst: vi.fn().mockResolvedValue(null),
},
moodEntry: { findMany: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
medication: { findMany: vi.fn() },
// v1.4.33 C1 — slim summaries slice runs through `$queryRaw`.
$queryRaw: vi.fn(),
// v1.4.33 C1 — slim summaries slice runs through `$queryRaw`. The
// v1.4.36 per-type coverage probe and the v1.4.37 default-slice
// probe also ride `$queryRaw`. Default to an empty coverage map so
// the route falls back to the live aggregator branches and the
// assertions stay byte-shape stable.
$queryRaw: vi.fn().mockResolvedValue([]),
$queryRawUnsafe: vi.fn().mockResolvedValue([]),
// v1.4.35 — slim slice also reads DAY buckets; the freshness
// watermark inside `ensureUserRollupsFresh` pokes `findFirst`.
// Default both to empty so the parity check falls back to live
@@ -32,7 +42,13 @@ vi.mock("@/lib/db", () => ({
measurementRollup: {
findMany: vi.fn().mockResolvedValue([]),
findFirst: vi.fn().mockResolvedValue(null),
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
upsert: vi.fn().mockResolvedValue({}),
},
$transaction: vi.fn().mockImplementation(async (queries: unknown[]) => {
if (Array.isArray(queries)) return Promise.all(queries);
return undefined;
}),
},
}));
@@ -119,6 +135,29 @@ beforeEach(() => {
vi.mocked(prisma.measurementRollup.findFirst).mockResolvedValue(
null as never,
);
vi.mocked(prisma.measurementRollup.deleteMany).mockResolvedValue(
{ count: 0 } as never,
);
vi.mocked(prisma.measurementRollup.upsert).mockResolvedValue(
{} as never,
);
// v1.4.37 W2 — `ensureUserRollupsFresh` reads `measurement.findFirst`;
// the per-type coverage probe + the rollup-recompute aggregator ride
// `$queryRaw` / `$queryRawUnsafe`. Default to empty so the route
// falls back to the live fast-path branches and the assertions stay
// byte-shape stable.
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null as never);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.$queryRaw as any).mockResolvedValue([]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.$queryRawUnsafe as any).mockResolvedValue([]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.$transaction as any).mockImplementation(
async (queries: unknown) => {
if (Array.isArray(queries)) return Promise.all(queries);
return undefined;
},
);
});
afterEach(() => {
+71 -594
View File
@@ -7,60 +7,26 @@ import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
import { computeSummariesSlice } from "@/lib/analytics/summaries-slice";
import { getBpTargets } from "@/lib/analytics/bp-targets";
import { computeBpInTargetWindows } from "@/lib/analytics/bp-in-target";
import { userDayKey, DEFAULT_TIMEZONE } from "@/lib/tz/resolver";
import { calculateCompliance } from "@/lib/analytics/compliance";
import {
computeHealthScore,
defaultWeightTargetFromHeight,
type ContributingSource,
type HealthScoreInput,
type HealthScoreResult,
} from "@/lib/analytics/health-score";
import {
correlateBpCompliance,
correlateMoodPulse,
correlateWeightWeekday,
type CorrelationResult,
} from "@/lib/insights/correlations";
import type {
MeasurementSource,
MeasurementType,
} from "@/generated/prisma/client";
import { measurementTypeEnum } from "@/lib/validations/measurement";
import { pickCanonicalSourceRows } from "@/lib/analytics/source-priority";
import type { SourcePriorityMetricKey } from "@/lib/validations/source-priority";
import { ensureUserRollupsFresh } from "@/lib/measurements/rollups";
import { probeRollupCoverage } from "@/lib/measurements/rollup-coverage";
import { computeBpInTargetFastPath } from "@/lib/analytics/bp-in-target-fast-path";
import { computeUserHealthScoreFastPath } from "@/lib/analytics/health-score-fast-path";
import { computeCorrelationHypothesesFastPath } from "@/lib/analytics/correlations-fast-path";
import {
cumulativeMetricKey,
isCumulativeDaySumType,
pickCumulativeDaySum,
} from "@/lib/measurements/cumulative-day-sum";
export const dynamic = "force-dynamic";
/**
* v1.4.36 W4c — cumulative MeasurementType → SourcePriorityMetricKey
* for `pickCanonicalSourceRows`. Returns `null` for types without a
* dedicated priority ladder (e.g. TIME_IN_DAYLIGHT), which fall
* through the picker's "no ladder" pass-through branch.
*/
function cumulativeMetricKey(
type: MeasurementType,
): SourcePriorityMetricKey | null {
switch (type) {
case "ACTIVITY_STEPS":
return "steps";
case "ACTIVE_ENERGY_BURNED":
return "activeEnergy";
case "WALKING_RUNNING_DISTANCE":
return "walkingRunningDistance";
case "FLIGHTS_CLIMBED":
return "flightsClimbed";
default:
return null;
}
}
/**
* v1.4.33 C1 — pull `?slice=…` from either a NextRequest (the
* route's production wrapper) or a plain `Request` (the integration
@@ -155,6 +121,15 @@ async function buildAnalyticsResponse(user: AuthedUser) {
// shape is untouched.
await ensureUserRollupsFresh(user.id);
// v1.4.37 W2 — single per-type coverage probe shared by the
// bp_in_target / healthScore / correlations branches below. The
// probe is one indexed query against `measurement_rollups`; the
// three downstream branches each reuse the resulting `coverage`
// map to decide between the rollup-fast-path and the live
// fallback. Probing once instead of per-branch keeps the fan-out
// cost flat across the three branches.
const coverage = await probeRollupCoverage(user.id);
// v1.4.25 W7b — every day-bucket call inside this route now honours
// the user's display timezone. The legacy `berlinDayKey()` import
// remains for sleep-stage and correlation paths that share their
@@ -333,57 +308,23 @@ async function buildAnalyticsResponse(user: AuthedUser) {
const bpTargets = getBpTargets(user.dateOfBirth);
if (bpTargets) {
const now = new Date();
// v1.4.22 A1 — re-anchor the BD-Zielbereich tile headline to the
// last-30-day window. Up to v1.4.19 the headline pinned to the
// 30-day average (so 7d / 30d / total all read 50 %). v1.4.19 A1
// flipped the headline to all-time, which made the tile correct
// but emotionally wrong: the headline was the slowest-moving
// aggregate possible, punishing recent improvement. v1.4.22 A1
// re-routes the headline to last-30-days and surfaces 7d / 30d /
// all-time as a 3-line sub-row so power users still see the
// long-arc number without it dominating. The helper still returns
// every window — only the headline pick changed.
//
// v1.4.23 H2 — chunked aggregation replaces an unbounded findMany.
// The W2-of-v1.4.20 fix did the right thing semantically (all-time
// window for the headline) but read the entire BP table into one
// array per type. A 5-year power user holds ~9 000 rows × 2; the
// single-shot fetch produced a 50-100 ms Prisma round-trip plus a
// ~2 MB allocation per request. Page through in 5 000-row chunks
// so the working set stays bounded; accumulate into the same
// `BpReading[]` shape the existing helper expects. The
// `analytics.bp_in_target.row_count` wide-event meta lets ops
// attribute slow requests to specific outlier users.
// v1.4.29 M1 — bound the BP-in-target reads to the trailing
// 365 days. `computeBpInTargetWindows` only needs the last
// year (the longest sub-window it computes is `priorYear`);
// pre-bound, each chunked walk pulled the entire BP history
// every dashboard mount.
const bpInTargetSince = new Date(
now.getTime() - 365 * 24 * 60 * 60 * 1000,
);
const [sysData, diaData] = await Promise.all([
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_SYS", {
since: bpInTargetSince,
}),
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_DIA", {
since: bpInTargetSince,
}),
]);
annotate({
meta: {
analytics: {
bp_in_target: {
row_count: sysData.length + diaData.length,
sys_rows: sysData.length,
dia_rows: diaData.length,
},
},
},
// v1.4.37 W2 — probe-gated dispatcher replaces the inline chunked
// read. When BOTH BP types have DAY-bucket coverage the helper
// pairs the per-day MEAN SYS + MEAN DIA from `measurement_rollups`
// and counts in-target days against the five reporting windows,
// skipping the heavy 365-day chunked walk against `measurements`.
// Falls back to the legacy `computeBpInTargetWindows` over a
// chunked read when coverage is partial so a brand-new account
// (no buckets yet) still sees per-event numbers. The helper emits
// a `path: "rollup" | "live"` annotate so prod logs prove which
// branch fired. See `bp-in-target-fast-path.ts` for the
// documented per-day-mean approximation.
const windows = await computeBpInTargetFastPath({
userId: user.id,
targets: bpTargets,
now,
coverage,
});
const windows = computeBpInTargetWindows(sysData, diaData, bpTargets, now);
bpInTargetPct = windows.last30Days?.pct ?? null;
bpInTargetPct7d = windows.last7Days?.pct ?? null;
bpInTargetPct30d = windows.last30Days?.pct ?? null;
@@ -420,32 +361,39 @@ async function buildAnalyticsResponse(user: AuthedUser) {
}
// v1.4.20 phase B3 — three pre-defined correlation hypotheses.
// All three run on the trailing 30 days so a sparse account doesn't
// burn the n >= 20 gate on a stale window (v1.4.23 H6 raised the
// floor from 14 → 20). Each runner gates on n >= 20 + p < 0.05;
// below the bar the result.status === "insufficient" and the UI
// paints an EmptyState.
const correlations = await computeCorrelationHypotheses(user.id, userTz);
// v1.4.37 W2 — probe-gated helper. The 28-day scan window (down
// from 30 to keep the cold critical path tight while still
// satisfying the n >= 20 surface gate) reads SYS / PULSE / WEIGHT
// per-day means from `measurement_rollups` when the user has full
// coverage; mood and medication-intake reads always stay live (no
// rollup equivalent). The helper emits `meta.correlations.path` +
// `meta.correlations.window_days` so prod logs prove the branch
// selection and the truthful window.
const correlations = await computeCorrelationHypothesesFastPath({
userId: user.id,
userTz,
now: new Date(),
coverage,
});
// v1.4.20 phase B5 — Personal Health Score. Server-deterministic
// composite of BP-in-target % + weight-trend alignment + mood
// stability + medication compliance. The "vs last week" delta
// re-runs the same compute against a 7-day-shifted snapshot.
const healthScore = await computeUserHealthScore(user.id, {
//
// v1.4.37 W2 — probe-gated helper. The weight pillar derives from
// DAY-bucket means on `measurement_rollups` when the user has full
// coverage; the source-attribution accordion still pulls a narrow
// 2-column projection from `measurements` for the ingest-path
// pills. Falls back to the legacy 37-day raw read on partial /
// missing coverage. Path annotate sits on `meta.healthScore.path`.
const healthScore = await computeUserHealthScoreFastPath({
userId: user.id,
bpInTargetPct,
heightCm: user.heightCm ?? null,
now: new Date(),
coverage,
});
if (healthScore) {
annotate({
meta: {
healthScore: {
score: healthScore.score,
band: healthScore.band,
delta: healthScore.delta,
},
},
});
}
return {
summaries: results,
@@ -538,160 +486,11 @@ async function computeSleepStageBreakdown(
};
}
/**
* Build inputs for the three pre-defined hypotheses + run them.
* Pure-ish — only Prisma reads, no external calls.
*
* Window: trailing 30 days. Anything older falls outside the surface
* because the user-facing "based on N paired readings · last 30 days"
* source-chip has to remain truthful.
*/
async function computeCorrelationHypotheses(
userId: string,
userTz: string,
): Promise<{
bpCompliance: CorrelationResult;
moodPulse: CorrelationResult;
weightWeekday: CorrelationResult;
}> {
const DAY_MS = 24 * 60 * 60 * 1000;
const since = new Date(Date.now() - 30 * DAY_MS);
// v1.4.23 Sr-H1 — the four measurement reads route through the
// chunked helper so even a noisy 30-day window (e.g. minute-level
// HealthKit pulse samples) cannot allocate an unbounded buffer. The
// helper still returns the full filtered series the Pearson runners
// need; we just bound the per-page Prisma round-trip.
const [sysRows, pulseRows, weightRows, moodRows, intakeRows] =
await Promise.all([
fetchMeasurementSeriesChunked(userId, "BLOOD_PRESSURE_SYS", { since }),
fetchMeasurementSeriesChunked(userId, "PULSE", { since }),
fetchMeasurementSeriesChunked(userId, "WEIGHT", { since }),
prisma.moodEntry.findMany({
where: { userId, moodLoggedAt: { gte: since } },
select: { score: true, moodLoggedAt: true, date: true },
}),
prisma.medicationIntakeEvent.findMany({
where: { userId, scheduledFor: { gte: since } },
select: { scheduledFor: true, takenAt: true, skipped: true },
}),
]);
// ── Hypothesis 1: BP × medication compliance ────────────────
// Aggregate by the user's display-tz day key so DST + UTC boundary
// issues don't split a day's readings. The day's "compliance %" is
// taken / expected for that calendar day across all medications.
const dayKey = (d: Date): string => userDayKey(d, userTz);
const dailySys = new Map<string, number[]>();
for (const row of sysRows) {
const key = dayKey(row.measuredAt);
const list = dailySys.get(key) ?? [];
list.push(row.value);
dailySys.set(key, list);
}
const dailyCompliance = new Map<
string,
{ expected: number; taken: number }
>();
for (const event of intakeRows) {
const key = dayKey(event.scheduledFor);
const slot = dailyCompliance.get(key) ?? { expected: 0, taken: 0 };
slot.expected += 1;
if (event.takenAt && !event.skipped) slot.taken += 1;
dailyCompliance.set(key, slot);
}
const bpCompliancePairs: Array<{
date: Date;
systolic: number;
compliancePct: number;
}> = [];
for (const [key, sysValues] of dailySys.entries()) {
const slot = dailyCompliance.get(key);
if (!slot || slot.expected === 0) continue;
const compliancePct = (slot.taken / slot.expected) * 100;
const meanSys = sysValues.reduce((s, v) => s + v, 0) / sysValues.length;
bpCompliancePairs.push({
date: dateFromDayKey(key),
systolic: meanSys,
compliancePct,
});
}
const bpCompliance = correlateBpCompliance({ daily: bpCompliancePairs });
// ── Hypothesis 2: Mood × resting pulse ──────────────────────
// Same-day pairing: take the day's mean mood vs the day's mean pulse.
// "Resting" is approximated by mean — HealthLog has no separate
// resting-pulse field, so we accept the noise rather than skip.
const dailyMood = new Map<string, number[]>();
for (const row of moodRows) {
const key = userDayKey(row.moodLoggedAt, userTz);
const list = dailyMood.get(key) ?? [];
list.push(row.score);
dailyMood.set(key, list);
}
const dailyPulse = new Map<string, number[]>();
for (const row of pulseRows) {
const key = userDayKey(row.measuredAt, userTz);
const list = dailyPulse.get(key) ?? [];
list.push(row.value);
dailyPulse.set(key, list);
}
const moodPulsePairs: Array<{
date: Date;
mood: number;
restingPulse: number;
}> = [];
for (const [key, moodScores] of dailyMood.entries()) {
const pulseValues = dailyPulse.get(key);
if (!pulseValues || pulseValues.length === 0) continue;
const meanMood = moodScores.reduce((s, v) => s + v, 0) / moodScores.length;
const meanPulse =
pulseValues.reduce((s, v) => s + v, 0) / pulseValues.length;
moodPulsePairs.push({
date: dateFromDayKey(key),
mood: meanMood,
restingPulse: meanPulse,
});
}
const moodPulse = correlateMoodPulse({ daily: moodPulsePairs });
// ── Hypothesis 3: Weight × weekday ──────────────────────────
// 0 = Monday … 6 = Sunday. ISO weekday minus 1.
//
// v1.4.25 W10 reconcile (Code-H1) — buckets the weekday by the
// user's display tz, matching W7's per-user-tz threading that the
// BP, mood, sleep, and pulse aggregators above already honour. The
// pre-W10 helper was pinned to `Europe/Berlin` and would land a
// user-local 23:30 weight reading from `Pacific/Auckland` under
// Sunday's bucket instead of Monday's — Pearson on the wrong
// weekday column.
const weightWeekdayPairs: Array<{ weekday: number; weight: number }> = [];
for (const row of weightRows) {
const isoWeekday = isoWeekdayInTz(row.measuredAt, userTz); // 1..7, 1=Mon
weightWeekdayPairs.push({
weekday: isoWeekday - 1,
weight: row.value,
});
}
const weightWeekday = correlateWeightWeekday({ daily: weightWeekdayPairs });
// Annotate so admin observability can attribute coverage to the
// corresponding wide-event rather than chasing it via DB queries.
annotate({
meta: {
correlations: {
bpCompliance: bpCompliance.status,
moodPulse: moodPulse.status,
weightWeekday: weightWeekday.status,
},
},
});
return { bpCompliance, moodPulse, weightWeekday };
}
// v1.4.37 W2 — `computeCorrelationHypotheses` body relocated to
// `src/lib/analytics/correlations-fast-path.ts` so the probe-gated
// rollup / live dispatcher can be unit-tested independently of the
// route. The new helper also tightens the scan window to 28 days and
// emits a sentinel on `meta.correlations.window_days` / `degraded`.
/**
* v1.4.23 Sr-H1 — paged read of every Measurement of a given type for
@@ -793,338 +592,16 @@ async function fetchMeasurementSeriesChunked(
return out;
}
// v1.4.22 W5 reconcile (Code-MED-3) — `berlinDayKey()` lifted to
// `src/lib/analytics/berlin-day.ts` so the targets route's sparkline
// bucketing shares the same Europe/Berlin contract. The
// `weekday: "short"` formatter still lives here because it's only
// used by `isoWeekdayInTz()` below.
//
// v1.4.25 W10 reconcile (Code-H1) — formatter is now per-tz so the
// weight-weekday correlator honours the same per-user-tz contract the
// BP/mood/pulse aggregators above already use. Memoised by tz so the
// formatter is built once per unique timezone per process (tz strings
// rarely change at runtime; the cache is bounded by the IANA database
// to a few hundred entries even in the worst case).
const WEEKDAY_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();
function getWeekdayFormatter(timeZone: string): Intl.DateTimeFormat {
let formatter = WEEKDAY_FORMATTER_CACHE.get(timeZone);
if (!formatter) {
formatter = new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
weekday: "short",
});
WEEKDAY_FORMATTER_CACHE.set(timeZone, formatter);
}
return formatter;
}
function dateFromDayKey(key: string): Date {
// Anchor to UTC midnight — the date is a sortable bucket label rather
// than a wall-clock timestamp, so DST drift is irrelevant. The tz
// info is already baked into the key (built via `userDayKey` upstream).
return new Date(`${key}T00:00:00.000Z`);
}
const ISO_WEEKDAY: Record<string, number> = {
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
Sun: 7,
};
function isoWeekdayInTz(d: Date, timeZone: string): number {
const parts = getWeekdayFormatter(timeZone).formatToParts(d);
const weekday = parts.find((p) => p.type === "weekday")?.value ?? "Mon";
return ISO_WEEKDAY[weekday] ?? 1;
}
// v1.4.37 W2 — `WEEKDAY_FORMATTER_CACHE`, `getWeekdayFormatter`,
// `dateFromDayKey`, `ISO_WEEKDAY`, and `isoWeekdayInTz` relocated
// alongside the correlation runner in
// `src/lib/analytics/correlations-fast-path.ts`. They were only ever
// used by the weight-weekday + day-key helpers inside the old inline
// correlation builder.
/**
* v1.4.25 W8e — collapse the persisted `MeasurementSource` enum onto
* the camelCase token set the health-score analytics layer consumes.
*
* - `MANUAL` and `IMPORT` (CSV import — still user-supplied data) both
* surface as `"manual"`.
* - `WITHINGS` and `APPLE_HEALTH` ride one-to-one.
*
* Returns `null` for source values that don't fall into the three
* exposed buckets — defence-in-depth in case the enum grows before the
* client is taught about it.
*/
function mapMeasurementSourceToLabel(
source: MeasurementSource,
): ContributingSource | null {
switch (source) {
case "MANUAL":
case "IMPORT":
return "manual";
case "WITHINGS":
return "withings";
case "APPLE_HEALTH":
return "appleHealth";
default:
return null;
}
}
/**
* v1.4.25 W8e — deduplicate the contributing-source list for a single
* component. Returns the empty array when nothing in the input maps
* onto a known label so downstream `resolveSourceLabel` falls through
* to `none` (matches the empty-state branch).
*/
function uniqueComponentSources(
rows: ReadonlyArray<MeasurementSource>,
): ReadonlyArray<ContributingSource> {
const seen = new Set<ContributingSource>();
for (const src of rows) {
const label = mapMeasurementSourceToLabel(src);
if (label) seen.add(label);
}
return Array.from(seen);
}
/**
* Build the Health Score input from the user's last-30-day weight,
* mood, and medication-compliance data, plus the already-computed
* `bpInTargetPct` headline. Re-runs the same compute against a
* 7-day-shifted window to populate the "vs last week" delta.
*
* Returns null when the score wouldn't carry any signal (every
* component nullable + no medications). The route surfaces the
* `null` to the UI so the hero panel hides cleanly.
*/
async function computeUserHealthScore(
userId: string,
input: { bpInTargetPct: number | null; heightCm: number | null },
): Promise<HealthScoreResult | null> {
const DAY_MS = 24 * 60 * 60 * 1000;
const now = new Date();
const since30d = new Date(now.getTime() - 30 * DAY_MS);
// Prior week's snapshot — shift everything 7 days into the past so
// both windows close at the same wall-clock-of-day boundary.
const prevSince30d = new Date(now.getTime() - 37 * DAY_MS);
const prevUntil = new Date(now.getTime() - 7 * DAY_MS);
// v1.4.25 W8e — read the `source` column alongside the value so the
// health-score provenance accordion knows which ingest path drove
// each component. The weight + BP reads already paid the row cost;
// adding the column to the SELECT is free in Postgres terms (no extra
// round-trip, no extra plan node) and the alternative — a second
// aggregate just for the source pill — would burn another findMany.
const [weightRows, bpSysRowsForSource, moodRows, medications] =
await Promise.all([
prisma.measurement.findMany({
where: {
userId,
type: "WEIGHT",
measuredAt: { gte: prevSince30d, lte: now },
},
select: { value: true, measuredAt: true, source: true },
orderBy: { measuredAt: "asc" },
}),
// BP source attribution rides on the systolic-readings row set —
// diastolic rows always carry the same `source` because both
// halves of a pair are persisted in the same write. Pull only the
// trailing 30 days to keep the call bounded for power users.
prisma.measurement.findMany({
where: {
userId,
type: "BLOOD_PRESSURE_SYS",
measuredAt: { gte: since30d, lte: now },
},
select: { measuredAt: true, source: true },
orderBy: { measuredAt: "asc" },
}),
prisma.moodEntry.findMany({
where: {
userId,
moodLoggedAt: { gte: prevSince30d, lte: now },
},
select: { score: true, moodLoggedAt: true },
orderBy: { moodLoggedAt: "asc" },
}),
prisma.medication.findMany({
where: { userId, active: true },
select: {
id: true,
createdAt: true,
schedules: {
select: {
windowStart: true,
windowEnd: true,
},
},
},
}),
]);
// Compliance30 per active medication, then again for the prior-week
// snapshot. The compliance helper anchors on `Date.now()` internally;
// for the previous-week snapshot we reuse the same helper but pass a
// shifted "createdAt" floor so the window mathematically reflects the
// [-37d, -7d] period — equivalent to running the helper a week ago.
let medicationCompliance30: number[] = [];
let medicationCompliance30Previous: number[] = [];
if (medications.length > 0) {
const medIds = medications.map((m) => m.id);
const intakeEvents = await prisma.medicationIntakeEvent.findMany({
where: {
userId,
medicationId: { in: medIds },
scheduledFor: { gte: prevSince30d, lte: now },
},
select: {
medicationId: true,
scheduledFor: true,
takenAt: true,
skipped: true,
},
});
const eventsByMed = new Map<string, typeof intakeEvents>();
for (const ev of intakeEvents) {
const list = eventsByMed.get(ev.medicationId);
if (list) list.push(ev);
else eventsByMed.set(ev.medicationId, [ev]);
}
medicationCompliance30 = medications.map((med) => {
const events = eventsByMed.get(med.id) ?? [];
return calculateCompliance(events, med.schedules, 30, med.createdAt).rate;
});
medicationCompliance30Previous = medications.map((med) => {
const events = (eventsByMed.get(med.id) ?? []).filter(
(e) => e.scheduledFor <= prevUntil,
);
// Compute compliance against the prior-week-aligned window by
// remapping the helper's "now": shift each event's scheduledFor
// and takenAt forward by 7 days so the helper's internal `now`
// anchor still captures the same logical 30 days.
const shifted = events.map((e) => ({
scheduledFor: new Date(e.scheduledFor.getTime() + 7 * DAY_MS),
takenAt: e.takenAt ? new Date(e.takenAt.getTime() + 7 * DAY_MS) : null,
skipped: e.skipped,
}));
return calculateCompliance(shifted, med.schedules, 30, med.createdAt)
.rate;
});
}
const fallbackTarget = defaultWeightTargetFromHeight(input.heightCm);
const weightSeriesLast30d = weightRows
.filter((r) => r.measuredAt >= since30d)
.map((r) => ({ date: r.measuredAt.toISOString(), kg: r.value }));
const weightSeriesPrev30d = weightRows
.filter((r) => r.measuredAt >= prevSince30d && r.measuredAt <= prevUntil)
.map((r) => ({ date: r.measuredAt.toISOString(), kg: r.value }));
const moodSeriesLast30d = moodRows
.filter((r) => r.moodLoggedAt >= since30d)
.map((r) => ({
date: r.moodLoggedAt.toISOString(),
score: r.score,
}));
const moodSeriesPrev30d = moodRows
.filter(
(r) => r.moodLoggedAt >= prevSince30d && r.moodLoggedAt <= prevUntil,
)
.map((r) => ({
date: r.moodLoggedAt.toISOString(),
score: r.score,
}));
// Skip any input shape where literally nothing is computable — the
// hero panel hides instead of painting a misleading "0".
if (
input.bpInTargetPct === null &&
weightSeriesLast30d.length === 0 &&
moodSeriesLast30d.length === 0 &&
medicationCompliance30.length === 0
) {
// Tag-only annotation so admin observability can see the empty path.
annotate({
meta: {
healthScore: { score: null, reason: "no_components_available" },
},
});
return null;
}
// v1.4.25 W8e — build per-component source attribution from the rows
// we already hold in memory. `mapMeasurementSourceToLabel` collapses
// the persisted `MeasurementSource` enum onto the camelCase token list
// the analytics helper consumes; `IMPORT` rides under `manual`
// because the v1.4.20 CSV importer ingests user-supplied data — it's
// not a wearable stream.
const windowEndAt = now.toISOString();
const weightSourcesIn30d = uniqueComponentSources(
weightRows
.filter((r) => r.measuredAt >= since30d)
.map((r) => r.source),
);
const latestWeightInWindow = weightRows
.filter((r) => r.measuredAt >= since30d)
.at(-1);
const bpSourceTokens = uniqueComponentSources(
bpSysRowsForSource.map((r) => r.source),
);
const latestBpInWindow = bpSysRowsForSource.at(-1);
// Mood doesn't yet have a non-manual ingest (v1.5 will introduce
// Apple Health mood) so the source list is always `["manual"]` when
// there are entries in window. Keep the lookup explicit so the
// v1.5 ingest path slot just drops in.
const moodSourceTokens = moodSeriesLast30d.length > 0
? (["manual"] as const)
: [];
const latestMoodInWindow = moodRows
.filter((r) => r.moodLoggedAt >= since30d)
.at(-1);
// Medication compliance always derives from logged intake events —
// user-driven manual logging today.
const complianceSourceTokens = medicationCompliance30.length > 0
? (["manual"] as const)
: [];
const current: HealthScoreInput = {
bpInTargetRate: input.bpInTargetPct,
weightSeriesLast30d,
weightTargetKg: fallbackTarget,
moodEntriesLast30d: moodSeriesLast30d,
medicationCompliance30,
attribution: {
bpSources: bpSourceTokens,
asOfBp: latestBpInWindow?.measuredAt.toISOString() ?? null,
weightSources: weightSourcesIn30d,
asOfWeight: latestWeightInWindow?.measuredAt.toISOString() ?? null,
moodSources: moodSourceTokens,
asOfMood: latestMoodInWindow?.moodLoggedAt.toISOString() ?? null,
complianceSources: complianceSourceTokens,
asOfCompliance: complianceSourceTokens.length > 0 ? windowEndAt : null,
windowEndAt,
},
};
// The all-time `bpInTargetPct` is a slow-moving aggregate and would
// need a full historical re-pair to "rewind" by a week. We pass the
// same value to the previous snapshot so the delta primarily
// reflects week-over-week changes in the weight / mood / compliance
// pillars — the components that actually move on a weekly cadence.
const previous: HealthScoreInput = {
bpInTargetRate: input.bpInTargetPct,
weightSeriesLast30d: weightSeriesPrev30d,
weightTargetKg: fallbackTarget,
moodEntriesLast30d: moodSeriesPrev30d,
medicationCompliance30: medicationCompliance30Previous,
};
return computeHealthScore(current, previous);
}
// v1.4.37 W2 — `mapMeasurementSourceToLabel`, `uniqueComponentSources`,
// and the inline `computeUserHealthScore` body relocated to
// `src/lib/analytics/health-score-fast-path.ts` so the probe-gated
// rollup / live dispatcher can be unit-tested independently of the
// route. The route now delegates through `computeUserHealthScoreFastPath`.
@@ -0,0 +1,346 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
/**
* v1.4.37 W7c — GET /api/measurements gains two new branches for
* cumulative HK types (steps, active energy, distance, flights,
* daylight):
*
* 1. `?type=ACTIVITY_STEPS&groupBy=day` → one synthesised row per
* user-TZ day with `value` = SUM and `sampleCount` = number of
* per-sample rows behind the bucket.
* 2. `?type=ACTIVITY_STEPS&dayKey=YYYY-MM-DD` → raw per-sample rows
* for that single calendar day in the user's IANA timezone.
*
* Spot metrics (BP, weight, pulse, etc.) keep the legacy
* `findMany`-only behaviour even when these params are present —
* the schema accepts the params but the route gates each branch on
* `CUMULATIVE_HK_TYPES`.
*/
vi.mock("@/lib/db", () => ({
prisma: {
measurement: {
findMany: vi.fn(),
count: vi.fn(),
},
measurementRollup: {
findMany: vi.fn(),
},
$queryRaw: vi.fn(),
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-1",
username: "test-user",
role: "USER" as const,
timezone: "Europe/Berlin",
},
};
function getRequest(query: string): NextRequest {
return new NextRequest(`http://localhost/api/measurements?${query}`, {
method: "GET",
});
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
});
describe("GET /api/measurements — groupBy=day (W7c collapsed list)", () => {
it("collapses per-sample step rows into one row per user-TZ day with sampleCount", async () => {
// Three Apple-Watch chunks on 2026-05-15 (Europe/Berlin) +
// two on 2026-05-16 — the route should sum each day's bucket.
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{
id: "m-1",
type: "ACTIVITY_STEPS",
value: 1200,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-15T08:00:00.000Z"),
notes: null,
},
{
id: "m-2",
type: "ACTIVITY_STEPS",
value: 3400,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-15T11:00:00.000Z"),
notes: null,
},
{
id: "m-3",
type: "ACTIVITY_STEPS",
value: 800,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-15T16:00:00.000Z"),
notes: null,
},
{
id: "m-4",
type: "ACTIVITY_STEPS",
value: 2500,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-16T07:00:00.000Z"),
notes: null,
},
{
id: "m-5",
type: "ACTIVITY_STEPS",
value: 4500,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-16T14:00:00.000Z"),
notes: null,
},
] as never);
const res = await GET(
getRequest(
"type=ACTIVITY_STEPS&groupBy=day&from=2026-05-15T00:00:00Z&to=2026-05-17T00:00:00Z",
),
);
expect(res.status).toBe(200);
const json = (await res.json()) as {
data: {
measurements: Array<{
type: string;
value: number;
unit: string;
dayKey: string;
sampleCount: number;
measuredAt: string;
}>;
meta: { groupBy?: string; total: number };
};
};
expect(json.data.meta.groupBy).toBe("day");
expect(json.data.measurements.length).toBe(2);
// Sort is desc by default — newer day first.
const [day16, day15] = json.data.measurements;
expect(day16.dayKey).toBe("2026-05-16");
expect(day16.value).toBe(7000);
expect(day16.sampleCount).toBe(2);
expect(day16.unit).toBe("steps");
expect(day15.dayKey).toBe("2026-05-15");
expect(day15.value).toBe(5400);
expect(day15.sampleCount).toBe(3);
// The collapsed row's measuredAt anchors to local noon so the
// row sorts cleanly between same-day spot samples (canonical
// daily-timestamp contract shared with the drain helper).
expect(day15.measuredAt).toContain("2026-05-15T10:00:00");
});
it("falls back to the legacy findMany path when groupBy=day is set on a non-cumulative type", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{
id: "m-1",
type: "PULSE",
value: 60,
unit: "bpm",
source: "MANUAL",
measuredAt: new Date("2026-05-15T09:00:00.000Z"),
notes: null,
},
] as never);
vi.mocked(prisma.measurement.count).mockResolvedValue(1 as never);
const res = await GET(getRequest("type=PULSE&groupBy=day"));
expect(res.status).toBe(200);
const json = (await res.json()) as {
data: {
measurements: Array<{ type: string }>;
meta: { groupBy?: string };
};
};
// Spot metrics keep the per-sample shape; the collapse branch
// never fires.
expect(json.data.meta.groupBy).toBeUndefined();
expect(json.data.measurements.length).toBe(1);
});
});
describe("GET /api/measurements — dayKey drill-down (W7c)", () => {
it("returns per-sample rows for the requested calendar day in the user's TZ", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{
id: "m-1",
type: "ACTIVITY_STEPS",
value: 1200,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-15T08:00:00.000Z"),
notes: null,
},
{
id: "m-2",
type: "ACTIVITY_STEPS",
value: 3400,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: new Date("2026-05-15T15:00:00.000Z"),
notes: null,
},
] as never);
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2026-05-15"),
);
expect(res.status).toBe(200);
const json = (await res.json()) as {
data: {
measurements: Array<{ id: string; value: number }>;
meta: { dayKey?: string };
};
};
expect(json.data.meta.dayKey).toBe("2026-05-15");
expect(json.data.measurements.length).toBe(2);
expect(json.data.measurements[0].value).toBe(1200);
// The route resolves the user-TZ day boundary, so the underlying
// findMany must be called with measuredAt: { gte, lt } shape.
const call = vi.mocked(prisma.measurement.findMany).mock.calls[0]?.[0];
expect(call).toBeDefined();
const measuredAt = (call as { where: { measuredAt?: unknown } }).where
.measuredAt as { gte?: Date; lt?: Date };
expect(measuredAt.gte).toBeInstanceOf(Date);
expect(measuredAt.lt).toBeInstanceOf(Date);
// Window is exactly 24 hours wide on a non-DST-transition day for
// a whole-hour-offset zone. The DST-aware drill-down test below
// pins the 23-/25-hour shape on the two transition days per year.
expect(measuredAt.lt!.getTime() - measuredAt.gte!.getTime()).toBe(
24 * 60 * 60 * 1000,
);
});
// v1.4.37 W10 H-1 — DST awareness. The drill-down window must honour
// the day's true local span (23 h on spring-forward, 25 h on
// fall-back) so the row count matches what the collapsed daily row
// displays. Previous shape (`canonicalDailyTimestamp ± 12h`) leaked
// an hour from the previous day on spring-forward and hid the first
// hour of `today` on fall-back.
it("returns a 23-hour window on the Berlin spring-forward day (2025-03-30)", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2025-03-30"),
);
expect(res.status).toBe(200);
const call = vi.mocked(prisma.measurement.findMany).mock.calls[0]?.[0];
const measuredAt = (call as { where: { measuredAt?: unknown } }).where
.measuredAt as { gte?: Date; lt?: Date };
expect(measuredAt.gte!.toISOString()).toBe("2025-03-29T23:00:00.000Z");
expect(measuredAt.lt!.toISOString()).toBe("2025-03-30T22:00:00.000Z");
expect(measuredAt.lt!.getTime() - measuredAt.gte!.getTime()).toBe(
23 * 60 * 60 * 1000,
);
});
it("returns a 25-hour window on the Berlin fall-back day (2025-10-26)", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2025-10-26"),
);
expect(res.status).toBe(200);
const call = vi.mocked(prisma.measurement.findMany).mock.calls[0]?.[0];
const measuredAt = (call as { where: { measuredAt?: unknown } }).where
.measuredAt as { gte?: Date; lt?: Date };
expect(measuredAt.gte!.toISOString()).toBe("2025-10-25T22:00:00.000Z");
expect(measuredAt.lt!.toISOString()).toBe("2025-10-26T23:00:00.000Z");
expect(measuredAt.lt!.getTime() - measuredAt.gte!.getTime()).toBe(
25 * 60 * 60 * 1000,
);
});
it("rejects a malformed dayKey at the validation gate (no DB call)", async () => {
const res = await GET(getRequest("type=ACTIVITY_STEPS&dayKey=15.05.2026"));
expect(res.status).toBe(422);
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
});
it("ignores dayKey on non-cumulative types and falls back to the legacy path", async () => {
vi.mocked(prisma.measurement.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.measurement.count).mockResolvedValue(0 as never);
const res = await GET(getRequest("type=PULSE&dayKey=2026-05-15"));
expect(res.status).toBe(200);
const json = (await res.json()) as {
data: { meta: { dayKey?: string } };
};
// No dayKey echo on the legacy path — proves the W7c branch
// didn't fire for the spot metric.
expect(json.data.meta.dayKey).toBeUndefined();
});
});
describe("GET /api/measurements — schema rejections (W10 reconcile)", () => {
// v1.4.37 W10 H1 — the groupBy=day collapsed path runs the collapse
// AFTER the per-sample scan, so it can't honour a non-zero offset
// without a Postgres-side date_trunc grouping that's a v1.4.38
// backlog item. The validator must reject the combination instead
// of silently rendering "showing 1-25 of N" with the wrong N.
it("rejects offset>0 when groupBy=day is set", async () => {
const res = await GET(
getRequest("type=ACTIVITY_STEPS&groupBy=day&offset=25"),
);
expect(res.status).toBe(422);
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
});
// v1.4.37 W10 H1 — same restriction for the drill-down branch; it
// returns a single bounded page per dayKey, not a cursor.
it("rejects offset>0 when dayKey is set", async () => {
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2026-05-15&offset=25"),
);
expect(res.status).toBe(422);
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
});
// v1.4.37 W10 H2 — `2026-02-30` is a YYYY-MM-DD string but not a
// real calendar date. `new Date()` silently overflows it to March
// 2, so the drill-down would point at the wrong day. The validator
// refine must reject it at parse time.
it("rejects impossible calendar dates on dayKey (2026-02-30)", async () => {
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2026-02-30"),
);
expect(res.status).toBe(422);
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
});
it("rejects impossible month on dayKey (2026-13-01)", async () => {
const res = await GET(
getRequest("type=ACTIVITY_STEPS&dayKey=2026-13-01"),
);
expect(res.status).toBe(422);
expect(prisma.measurement.findMany).not.toHaveBeenCalled();
});
});
+163 -2
View File
@@ -19,6 +19,11 @@ import {
type AggregateGrain,
} from "@/lib/measurements/range-aggregation";
import { CUMULATIVE_HK_TYPES } from "@/lib/measurements/apple-health-mapping";
import {
canonicalDailyTimestamp,
dayKeyForUserTz,
localDayWindow,
} from "@/lib/measurements/drain-per-sample-cumulative";
import { withIdempotency } from "@/lib/idempotency";
import { invalidateUserMeasurements } from "@/lib/cache/invalidate";
import {
@@ -42,8 +47,19 @@ export const GET = apiHandler(async (request: NextRequest) => {
return apiError(parsed.error.issues[0].message, 422);
}
const { type, from, to, limit, offset, sortBy, sortDir, aggregate, source } =
parsed.data;
const {
type,
from,
to,
limit,
offset,
sortBy,
sortDir,
aggregate,
source,
groupBy,
dayKey,
} = parsed.data;
const where = {
userId: user.id,
@@ -58,6 +74,151 @@ export const GET = apiHandler(async (request: NextRequest) => {
: {}),
};
// v1.4.37 W7c — list-view drill-down to per-sample rows for a single
// calendar day in the user's IANA timezone. Resolves the day's UTC
// bounds against `User.timezone`, then runs a plain `findMany` so the
// expandable list row shows every per-sample chunk the daily collapse
// hid. Gated to cumulative HK types — the spot-sample types render
// one-row-per-event already and have nothing to drill into.
if (dayKey && type && CUMULATIVE_HK_TYPES.has(type as MeasurementType)) {
const tz =
user.timezone && user.timezone.length > 0
? user.timezone
: "Europe/Berlin";
// Resolve `[dayStart, dayEnd)` for the requested calendar day in
// the user's local zone. v1.4.37 W10 — `localDayWindow` honours
// DST: the previous shape (`canonicalDailyTimestamp ± 12 h`)
// silently leaked or hid one hour of samples on spring-forward
// (23-h day) and fall-back (25-h day) by always spanning exactly
// 24 h. Works for every IANA offset including sub-half-hour
// zones (Asia/Kathmandu UTC+5:45, Pacific/Chatham UTC+12:45).
const { dayStart, dayEnd } = localDayWindow(dayKey, tz);
const samples = await prisma.measurement.findMany({
where: {
userId: user.id,
type: type as MeasurementType,
measuredAt: { gte: dayStart, lt: dayEnd },
},
orderBy: { measuredAt: sortDir },
// Cap the drill-down — a phone-only stepCount day can hit a few
// hundred rows; the route ceiling keeps a pathological day bounded.
take: Math.min(limit, 1000),
});
annotate({
action: { name: "measurement.list" },
meta: { total: samples.length, type, dayKey, mode: "drill-down" },
});
return apiSuccess({
measurements: samples,
meta: { total: samples.length, limit, offset: 0, dayKey },
});
}
// v1.4.37 W7c — collapsed "one row per day" mode for cumulative
// types. The list page renders the day's SUM as a single synthesised
// row with a `sampleCount` chevron that drills back into the
// per-sample rows via the `dayKey=…` branch above.
if (
groupBy === "day" &&
type &&
CUMULATIVE_HK_TYPES.has(type as MeasurementType)
) {
const tz =
user.timezone && user.timezone.length > 0
? user.timezone
: "Europe/Berlin";
const rows = await prisma.measurement.findMany({
where,
orderBy: { measuredAt: "asc" },
// Per-sample row scan within the requested window — bounded by
// the existing `limit` cap (default 100, max 5000) so a wide
// multi-year window can still walk the whole range when the
// chart explicitly asks for it.
take: limit,
select: {
id: true,
type: true,
value: true,
unit: true,
source: true,
measuredAt: true,
notes: true,
},
});
// Group by the user's calendar day, sum values, keep a representative
// unit/source from the bucket's first row so the rendered row carries
// a sensible label even when the bucket mixes sources.
type Bucket = {
dayKey: string;
total: number;
sampleCount: number;
latest: Date;
unit: string;
source: string;
};
const buckets = new Map<string, Bucket>();
for (const row of rows) {
const key = dayKeyForUserTz(row.measuredAt, tz);
const slot = buckets.get(key);
if (!slot) {
buckets.set(key, {
dayKey: key,
total: row.value,
sampleCount: 1,
latest: row.measuredAt,
unit: row.unit,
source: row.source,
});
} else {
slot.total += row.value;
slot.sampleCount += 1;
if (row.measuredAt > slot.latest) slot.latest = row.measuredAt;
}
}
const measurements = Array.from(buckets.values())
.map((b) => ({
// Synthetic id so the list-row key stays stable across pages
// and the row never collides with a real `Measurement.id`.
id: `day:${type}:${b.dayKey}`,
type,
value: b.total,
unit: b.unit,
source: b.source,
// Anchor the row's timestamp to local noon so the row sorts
// cleanly between same-day spot samples — matches the
// `canonicalDailyTimestamp` convention used by the drain.
measuredAt: canonicalDailyTimestamp(b.dayKey, tz).toISOString(),
notes: null,
dayKey: b.dayKey,
sampleCount: b.sampleCount,
}))
.sort((a, b) => {
const cmp = a.dayKey < b.dayKey ? -1 : a.dayKey > b.dayKey ? 1 : 0;
return sortDir === "asc" ? cmp : -cmp;
});
annotate({
action: { name: "measurement.list" },
meta: {
total: measurements.length,
type,
groupBy: "day",
rowsScanned: rows.length,
},
});
return apiSuccess({
measurements,
meta: {
total: measurements.length,
limit,
offset: 0,
groupBy: "day",
},
});
}
// v1.4.28 FB-D2 — server-side aggregation. Gated on an explicit
// `aggregate` param so the iOS contract (raw `MeasurementWireDTO`
// shape on `GET /api/measurements`) is byte-stable for any caller
@@ -0,0 +1,157 @@
/**
* v1.4.37 W3 — GET /api/medications/[id]/intake `status` filter tests.
*
* Pins the contract added to fix the v1.4.36 regression where
* `IntakeHistoryListV2` rendered rows with `takenAt:null AND
* skipped:false` as "Eingenommen". The route now accepts an optional
* `status` query param:
*
* - default (`status:"all"`) keeps the byte-stable contract for the
* iOS Swift client and the dashboard tiles already on the wire.
* - `status:"completed"` — taken OR skipped — is what the
* detail-page list passes so ambiguous "missed / unconfirmed"
* rows stay out of the user-facing table.
* - `status:"taken"` / `status:"skipped"` cover the two single-arm
* branches future surfaces may need.
*
* The route-level guard (404 on cross-user reads) is exercised by
* the shared `assertMedicationOwnership` test suite — this file only
* cares about the Prisma `where` fragment derived from the new knob.
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
medication: { findUnique: vi.fn() },
medicationIntakeEvent: {
findMany: vi.fn(),
count: vi.fn(),
},
},
}));
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({
auditLog: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/db-compat", () => ({
ensureDbCompatibility: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET } from "../route";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth/session";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "marc", role: "USER" as const },
};
const MED_OK = { id: "med-1", userId: "user-1" };
function makeRequest(query: string): NextRequest {
return new NextRequest(
`http://localhost/api/medications/med-1/intake?${query}`,
);
}
const ROUTE_PARAMS = { params: Promise.resolve({ id: "med-1" }) };
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.medication.findUnique).mockResolvedValue(MED_OK as never);
vi.mocked(prisma.medicationIntakeEvent.findMany).mockResolvedValue(
[] as never,
);
vi.mocked(prisma.medicationIntakeEvent.count).mockResolvedValue(0);
});
describe("GET /api/medications/[id]/intake — status filter", () => {
it("applies no status filter when `status` is omitted (back-compat)", async () => {
const res = await GET(makeRequest("limit=25&offset=0"), ROUTE_PARAMS);
expect(res.status).toBe(200);
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
.calls[0][0]?.where;
expect(where).toEqual({ medicationId: "med-1", userId: "user-1" });
});
it("applies no status filter when explicitly passed `status=all`", async () => {
const res = await GET(
makeRequest("limit=25&offset=0&status=all"),
ROUTE_PARAMS,
);
expect(res.status).toBe(200);
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
.calls[0][0]?.where;
expect(where).toEqual({ medicationId: "med-1", userId: "user-1" });
});
it("filters to confirmed-taken rows for `status=taken`", async () => {
await GET(makeRequest("status=taken"), ROUTE_PARAMS);
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
.calls[0][0]?.where;
expect(where).toEqual({
medicationId: "med-1",
userId: "user-1",
takenAt: { not: null },
skipped: false,
});
});
it("filters to skipped rows for `status=skipped`", async () => {
await GET(makeRequest("status=skipped"), ROUTE_PARAMS);
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
.calls[0][0]?.where;
expect(where).toEqual({
medicationId: "med-1",
userId: "user-1",
skipped: true,
});
});
it("filters to taken-or-skipped rows for `status=completed` (the detail-page contract)", async () => {
await GET(makeRequest("status=completed"), ROUTE_PARAMS);
const where = vi.mocked(prisma.medicationIntakeEvent.findMany).mock
.calls[0][0]?.where;
expect(where).toEqual({
medicationId: "med-1",
userId: "user-1",
OR: [{ takenAt: { not: null }, skipped: false }, { skipped: true }],
});
});
it("rejects unknown status values with a 422", async () => {
const res = await GET(makeRequest("status=junk"), ROUTE_PARAMS);
expect(res.status).toBe(422);
expect(prisma.medicationIntakeEvent.findMany).not.toHaveBeenCalled();
});
it("propagates the `status` value to the count call so totals match the visible page", async () => {
await GET(makeRequest("status=completed"), ROUTE_PARAMS);
const countArgs = vi.mocked(prisma.medicationIntakeEvent.count).mock
.calls[0][0];
expect(countArgs?.where).toEqual({
medicationId: "med-1",
userId: "user-1",
OR: [{ takenAt: { not: null }, skipped: false }, { skipped: true }],
});
});
});
+26 -3
View File
@@ -177,8 +177,31 @@ export const GET = apiHandler(
return apiError(parsed.error.issues[0].message, 422);
}
const { limit, offset, sortBy, sortDir } = parsed.data;
const where = { medicationId: id, userId: user.id };
const { limit, offset, sortBy, sortDir, status } = parsed.data;
// v1.4.37 W3 — translate the optional `status` filter into a Prisma
// `where` fragment. Default `status:"all"` keeps the contract
// byte-stable for the iOS Swift client and the dashboard tiles that
// were on the wire before this knob existed. The detail-page
// IntakeHistoryListV2 component opts into `status:"completed"` so
// ambiguous "missed / never confirmed" rows
// (`takenAt IS NULL AND skipped = false`) stay out of the user-facing
// table — they were the source of the v1.4.36 regression where rows
// with no takenAt rendered an "Eingenommen" chip.
const statusFilter =
status === "taken"
? { takenAt: { not: null }, skipped: false }
: status === "skipped"
? { skipped: true }
: status === "completed"
? {
OR: [
{ takenAt: { not: null }, skipped: false },
{ skipped: true },
],
}
: {};
const where = { medicationId: id, userId: user.id, ...statusFilter };
const [events, total] = await Promise.all([
prisma.medicationIntakeEvent.findMany({
@@ -192,7 +215,7 @@ export const GET = apiHandler(
annotate({
action: { name: "medication.intake.list" },
meta: { medication_id: id, total },
meta: { medication_id: id, total, status },
});
return apiSuccess({ events, meta: { total, limit, offset } });
+47 -2
View File
@@ -11,6 +11,7 @@ import {
Heart,
Moon,
Percent,
Pill,
Plus,
Smile,
Target,
@@ -38,6 +39,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { MeasurementForm } from "@/components/measurements/measurement-form";
import { MoodForm } from "@/components/mood/mood-form";
import { MedicationIntakeQuickAdd } from "@/components/dashboard/medication-intake-quick-add";
import { TrendCard } from "@/components/charts/trend-card";
import { TrendHint } from "@/components/charts/trend-hint";
import { summaryToTrend7Delta } from "@/lib/analytics/trend-delta";
@@ -196,13 +198,19 @@ export default function DashboardPage() {
const { t } = useTranslations();
const fmt = useFormatters();
const [quickEntryDialog, setQuickEntryDialog] = useState<
"measurement" | "mood" | null
"measurement" | "mood" | "medicationIntake" | null
>(null);
// v1.4.27 R4 RC2 — DOM handles for the form action-row portal target
// on each quick-entry sheet. The Sheet branch sticky-pins this slot.
const [measurementFooterEl, setMeasurementFooterEl] =
useState<HTMLDivElement | null>(null);
const [moodFooterEl, setMoodFooterEl] = useState<HTMLDivElement | null>(null);
// v1.4.37 W7b — medication-intake quick-add lives on the same Sheet
// primitive as the other two quick-entries; the form's action row is
// portalled into this slot so Save / Cancel stay reachable above the
// mobile soft keyboard.
const [medicationIntakeFooterEl, setMedicationIntakeFooterEl] =
useState<HTMLDivElement | null>(null);
// v1.4.29 M5 — the three inline dashboard queries default to a
// 0-ms `staleTime`, so a tab-focus-and-return triggered a refetch
@@ -526,7 +534,14 @@ export default function DashboardPage() {
return (
<div className="space-y-6">
<div className="flex items-start justify-between gap-4">
{/* v1.4.37 W4a item 7 — centre-align the Hinzufügen button
against the 2-line title block on mobile (< sm). The
`welcomeText` line wraps under the title at < 380 px so the
button used to float at the top of the row without a
baseline anchor; `items-center sm:items-start` keeps the
mobile vertical centre while preserving the original
top-aligned posture on sm+ (where the title is one line). */}
<div className="flex items-center justify-between gap-4 sm:items-start">
<div>
<h1 className="text-2xl font-bold tracking-tight">
{t("dashboard.title")}
@@ -575,6 +590,17 @@ export default function DashboardPage() {
<Waves className="mr-2 h-4 w-4" aria-hidden="true" />
{t("dashboard.quickAddMood")}
</DropdownMenuItem>
{/* v1.4.37 W7b — third quick-add row: medication intake.
Same Sheet-on-mobile / Dialog-on-desktop primitive as
the other two; the menu label is a self-contained
verb-phrase so it doesn't collide with the trigger or
the sibling rows (cf. quick-add-labels.test.ts). */}
<DropdownMenuItem
onClick={() => setQuickEntryDialog("medicationIntake")}
>
<Pill className="mr-2 h-4 w-4" aria-hidden="true" />
{t("dashboard.quickAddMedicationIntake")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -623,6 +649,25 @@ export default function DashboardPage() {
footerSlot={moodFooterEl}
/>
</ResponsiveSheet>
{/* v1.4.37 W7b — third Sheet: medication intake. Same
ResponsiveSheet contract as the two above; the form's footer
(Cancel + Save) portals into the sticky-pinned slot so it
stays reachable above the soft keyboard on mobile. */}
<ResponsiveSheet
open={quickEntryDialog === "medicationIntake"}
onOpenChange={(open) => !open && setQuickEntryDialog(null)}
title={t("dashboard.medicationIntakeQuickAdd.sheetTitle")}
description={t("dashboard.medicationIntakeQuickAdd.sheetDescription")}
footer={
<div ref={setMedicationIntakeFooterEl} className="flex w-full" />
}
>
<MedicationIntakeQuickAdd
onSuccess={() => setQuickEntryDialog(null)}
onCancel={() => setQuickEntryDialog(null)}
footerSlot={medicationIntakeFooterEl}
/>
</ResponsiveSheet>
{(() => {
type TrendEntry = { id: string; order: number; node: React.ReactNode };
+24 -8
View File
@@ -15,6 +15,7 @@ import {
import { TargetsSummaryHeader } from "@/components/targets/targets-summary-header";
import { CoachDrawer } from "@/components/insights/coach-panel/coach-drawer";
import { useCoachHandoff } from "@/hooks/use-coach-handoff";
import { useFeatureFlags } from "@/hooks/use-feature-flags";
type TargetData = TargetCardData;
@@ -154,7 +155,15 @@ export default function TargetsPage() {
},
enabled: isAuthenticated,
});
const aiEnabled = chainStatus?.activeProvider != null;
// v1.4.37 W5 — operator's global Coach flag layered on top of the
// per-user provider chain. Either gate disables every Coach
// affordance on this page: the per-card CTAs (via `aiEnabled`
// threaded into <TargetCard>) and the page-level <CoachDrawer> mount
// below. The flag default is all-on for fresh installs and on any
// fetch error, so the path stays open by default.
const flags = useFeatureFlags();
const coachEnabled = flags.coach;
const aiEnabled = coachEnabled && chainStatus?.activeProvider != null;
// v1.4.25 W3e — Coach drawer state owned by the page. The per-card
// CTA + summary header both feed the same drawer so the user only
@@ -281,13 +290,20 @@ export default function TargetsPage() {
{/* v1.4.25 W3e — Coach drawer mounted at the page level. The
drawer is fully-controlled; per-card CTAs flip `coachOpen`
and seed `coachPrefill` via the `askCoach()` hook callback. */}
<CoachDrawer
open={coachOpen}
onOpenChange={setCoachOpen}
prefill={coachPrefill}
key={`coach-drawer-${coachScope?.sources?.join(",") ?? "default"}`}
/>
and seed `coachPrefill` via the `askCoach()` hook callback.
v1.4.37 W5 — short-circuit when the operator turned the
global Coach flag off so the SSE machinery + Sheet portal
never mount. The per-card CTAs already hide via `aiEnabled`
above, so the drawer can never be triggered with the flag
off; the gate is defence-in-depth. */}
{coachEnabled && (
<CoachDrawer
open={coachOpen}
onOpenChange={setCoachOpen}
prefill={coachPrefill}
key={`coach-drawer-${coachScope?.sources?.join(",") ?? "default"}`}
/>
)}
</div>
);
}
+11 -2
View File
@@ -544,13 +544,22 @@ export function MoodChart({
// visibly heavier corner radius than BP / weight in the same
// row. Align to the `rounded-md` shell so the three trend
// tiles share one corner radius.
//
// v1.4.37 W4a item 5 — collapse the Card's inter-row gap to
// 0 so the only space between the title and the chart strip
// is the CardHeader's own `pb-1` (4 px), matching the
// `mb-1` HealthChart paints below its plain `<div>` title.
// Pre-fix Mood's `gap-1` (4 px) on top of the header `pb-1`
// stacked an extra 4 px below the title, which read as a
// ~12-16 px taller card than the BP/weight siblings inside
// the trends row.
className={
mini ? "gap-1 rounded-md py-2 shadow-none" : undefined
mini ? "gap-0 rounded-md py-2 shadow-none" : undefined
}
>
<CardHeader
className={
mini ? "px-2 pb-1 [&]:gap-0.5" : "pb-2"
mini ? "px-2 pb-1 [&]:gap-0" : "pb-2"
}
>
{/* v1.4.19 A2 — mobile-first header: stack title row above
@@ -0,0 +1,188 @@
/**
* v1.4.37 W7b — `<MedicationIntakeQuickAdd>` contract suite.
*
* Project convention is SSR-only tests (vitest runs in `node`
* environment; `@testing-library/react` is not installed). The
* assertions below cover:
*
* 1. The pure `pickDefaultMedicationId` helper — the cool/easy
* default-selection logic Marc asked for ("auto-select when one is
* due"). Tested across the four ranked branches: empty,
* single-active, due-now, alphabetical fallback.
* 2. The empty-state SSR markup — when the user has no active
* medications, the form is suppressed and an EmptyState-style
* hint with a CTA to `/medications` is rendered.
* 3. The populated-state SSR markup — picker + dose + time fields
* mount with the right labels + 44 px touch floor.
* 4. The POST submit contract — the handler that fires on Save is
* observed via a fetch spy: the request method, URL, and body
* shape (takenAt ISO string, skipped:false) must match the
* `/api/medications/[id]/intake` route signature so the dashboard
* quick-add stays in lockstep with the API W3 hardened.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
// Stub @tanstack/react-query so the SSR render path doesn't try to
// reach into a real QueryClient. The default-stub returns the
// populated medications list; per-test mockReturnValue calls override.
const mockUseQuery = vi.fn();
const mockInvalidateQueries = vi.fn().mockResolvedValue(undefined);
const mockQueryClient = { invalidateQueries: mockInvalidateQueries };
vi.mock("@tanstack/react-query", () => ({
useQuery: (opts: unknown) => mockUseQuery(opts),
useQueryClient: () => mockQueryClient,
}));
vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));
import {
MedicationIntakeQuickAdd,
pickDefaultMedicationId,
type MedicationOption,
} from "../medication-intake-quick-add";
function makeMed(
id: string,
overrides: Partial<MedicationOption> = {},
): MedicationOption {
return {
id,
name: `Med ${id}`,
dose: "5 mg",
active: true,
schedules: [],
lastTakenAt: null,
todayEventCount: 0,
...overrides,
};
}
function renderSSR(node: React.ReactElement, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
beforeEach(() => {
vi.clearAllMocks();
mockUseQuery.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("pickDefaultMedicationId — auto-select heuristic", () => {
it("returns null when no active medications exist", () => {
expect(pickDefaultMedicationId([])).toBeNull();
expect(
pickDefaultMedicationId([makeMed("a", { active: false })]),
).toBeNull();
});
it("auto-selects the single active medication", () => {
expect(pickDefaultMedicationId([makeMed("solo")])).toBe("solo");
});
it("prefers an in-window medication over the alphabetical fallback", () => {
// 10:00 Berlin time on a weekday. The morning slot for med "b" is
// open (08:00–11:00); med "a" has no schedule so it can only
// surface via the alphabetical fallback. The helper must pick "b".
const now = new Date("2026-05-12T08:00:00Z"); // 10:00 Berlin (UTC+2)
const result = pickDefaultMedicationId(
[
makeMed("a"),
makeMed("b", {
schedules: [
{
id: "s1",
windowStart: "08:00",
windowEnd: "11:00",
daysOfWeek: null,
label: null,
dose: null,
},
],
}),
],
now,
);
expect(result).toBe("b");
});
it("falls back to the alphabetical-first active medication when nothing is due", () => {
// 03:00 Berlin time: no schedules overlap. The helper should
// alphabetically sort and pick the leading id, "ramipril".
const now = new Date("2026-05-12T01:00:00Z"); // 03:00 Berlin
const result = pickDefaultMedicationId(
[
makeMed("z", { name: "Zolpidem" }),
makeMed("r", { name: "Ramipril" }),
],
now,
);
expect(result).toBe("r");
});
});
describe("<MedicationIntakeQuickAdd> — SSR contract", () => {
it("renders the empty-state with a CTA to /medications when no active medications", () => {
mockUseQuery.mockReturnValue({ data: [], isLoading: false });
const html = renderSSR(<MedicationIntakeQuickAdd />);
expect(html).toContain('data-testid="medication-intake-quick-add-empty"');
// Visible copy resolves from i18n (no raw key leak).
expect(html).toContain("No medications yet");
expect(html).toContain('href="/medications"');
// The form itself must not render — otherwise we'd ship a Save
// button with no medication to record.
expect(html).not.toContain(
'data-testid="medication-intake-quick-add-form"',
);
// v1.4.37 W10 — the empty-state CTA must clear the 44 px touch
// floor that W-CI raised on the onboarding checklist. The
// `size="sm"` default would land at 32 px without an explicit
// `min-h-11 sm:min-h-9` override.
expect(html).toContain("min-h-11");
});
it("renders the populated form with picker + dose + time fields", () => {
mockUseQuery.mockReturnValue({
data: [
makeMed("med-1", { name: "Ramipril", dose: "5 mg" }),
makeMed("med-2", { name: "Mounjaro", dose: "5 mg" }),
],
isLoading: false,
});
const html = renderSSR(<MedicationIntakeQuickAdd />);
expect(html).toContain('data-testid="medication-intake-quick-add-form"');
// Field-level testids pinned for the e2e + future-coverage handles.
expect(html).toContain(
'data-testid="medication-intake-quick-add-medication"',
);
expect(html).toContain('data-testid="medication-intake-quick-add-dose"');
expect(html).toContain(
'data-testid="medication-intake-quick-add-taken-at"',
);
// 44 px touch floor on every interactive field + the footer Save
// button (WCAG 2.5.5). v1.4.37 W10 added the floor to the footer
// buttons; the form fields already carried it.
expect(html.match(/min-h-11/g)?.length ?? 0).toBeGreaterThanOrEqual(3);
});
it("does not leak raw i18n keys in either locale", () => {
mockUseQuery.mockReturnValue({ data: [], isLoading: false });
const en = renderSSR(<MedicationIntakeQuickAdd />, "en");
const de = renderSSR(<MedicationIntakeQuickAdd />, "de");
expect(en).not.toContain("dashboard.medicationIntakeQuickAdd");
expect(de).not.toContain("dashboard.medicationIntakeQuickAdd");
// German locale ships Marc-Voice DE copy with umlauts (UTF-8
// end-to-end, never their HTML entity form).
expect(de).toContain("Medikamente angelegt");
});
});
@@ -0,0 +1,452 @@
"use client";
import { useId, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DateTimeInput } from "@/components/ui/date-input";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Loader2, Pill, Plus } from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";
import { useTranslations } from "@/lib/i18n/context";
import {
invalidateKeys,
medicationDependentKeys,
queryKeys,
} from "@/lib/query-keys";
import {
reduceCurrentWindowStatus,
toBerlinDate,
type ScheduleWindowInput,
} from "@/lib/medications/window-status";
/**
* v1.4.37 W7b — dashboard "Hinzufügen" → "Medikamenteneinnahme" quick-add.
*
* Marc's brief: the dashboard's top-right "Hinzufügen" menu logs
* measurements and mood entries; add a medication-intake action so a
* dose can be logged in a few taps without leaving the dashboard.
*
* Form shape mirrors `MoodForm` / `MeasurementForm`:
*
* 1. Medication picker. Auto-selects the only active medication when
* the user has one; otherwise defaults to the first medication
* whose schedule window is currently open (the cool/easy slice).
* Falls back to the most-recently-created entry when nothing is
* due. Disabled when the user has no active medications — the
* sheet body renders an EmptyState-style hint instead of an
* unusable form.
* 2. Dose. Pre-filled from the medication's catalogue dose for
* visual confirmation ("this is the strength I'm logging").
* v1.4.37 W10 — rendered read-only because the POST body has no
* `dose` field; any user edit would be silently dropped. When
* the user wants to record a half/double dose they still edit
* the medication itself on `/medications` until the v1.4.38
* schema grows a `doseOverride` slot. Hint copy below the
* field warns about the constraint so the user's mental model
* tracks what the server persists.
* 3. Time taken. Defaults to `now` (local datetime-local format
* shaped the same as `MoodForm`).
*
* On success: invalidate `medicationDependentKeys` (medications +
* analytics + insights + intake-summary + achievements) PLUS the
* inline per-medication compliance chart key so the detail page tile
* refreshes if it happens to be mounted elsewhere in the app.
*
* Mounted inside `<ResponsiveSheet>` from `page.tsx`; the action row
* is portalled into the sheet's sticky footer slot via `footerSlot`,
* matching the `MoodForm` / `MeasurementForm` contract so the Save
* button stays reachable above the mobile keyboard.
*/
interface Schedule extends ScheduleWindowInput {
id: string;
label: string | null;
dose: string | null;
}
export interface MedicationOption {
id: string;
name: string;
dose: string;
active: boolean;
schedules: Schedule[];
lastTakenAt: string | null;
todayEventCount: number | null;
}
interface MedicationIntakeQuickAddProps {
onSuccess?: () => void;
onCancel?: () => void;
/**
* v1.4.27 R4 RC2 contract — when mounted inside the responsive sheet,
* the parent passes the sheet's sticky footer slot so the action row
* (Cancel + Save) renders pinned above the soft keyboard. The
* `<form>` keeps `submit-on-Enter` working through the HTML `form`
* attribute on the portalled Save button.
*/
footerSlot?: HTMLElement | null;
}
function getDefaultIntakeAtValue(): string {
const now = new Date();
const offset = now.getTimezoneOffset();
const local = new Date(now.getTime() - offset * 60 * 1000);
return local.toISOString().slice(0, 16);
}
/**
* Pick the medication that should be pre-selected when the sheet opens.
*
* Priority:
* 1. The active medication whose schedule window is currently open
* (or late / very_late) — this is the "due now" surface.
* 2. The single active medication when the user has exactly one.
* 3. The first active medication alphabetically (stable fallback).
*
* Returns the medication id or `null` when no active medication exists.
*/
export function pickDefaultMedicationId(
options: MedicationOption[],
now: Date = new Date(),
thresholds: { lateMinutes: number; missedMinutes: number } = {
lateMinutes: 120,
missedMinutes: 240,
},
): string | null {
const actives = options.filter((m) => m.active);
if (actives.length === 0) return null;
if (actives.length === 1) return actives[0].id;
const nowBerlin = toBerlinDate(now);
const due = actives.find((m) => {
const status = reduceCurrentWindowStatus({
schedules: m.schedules,
nowBerlin,
lateMinutes: thresholds.lateMinutes,
missedMinutes: thresholds.missedMinutes,
active: true,
lastTakenAt: m.lastTakenAt,
todayEventCount: m.todayEventCount ?? 0,
});
return status.status !== null;
});
if (due) return due.id;
// Stable alphabetical fallback when nothing is currently due.
const sorted = [...actives].sort((a, b) =>
a.name.localeCompare(b.name, "de", { sensitivity: "base" }),
);
return sorted[0]?.id ?? null;
}
export function MedicationIntakeQuickAdd({
onSuccess,
onCancel,
footerSlot,
}: MedicationIntakeQuickAddProps) {
const { t } = useTranslations();
const queryClient = useQueryClient();
const { data: medicationsRaw, isLoading: medicationsLoading } = useQuery({
queryKey: queryKeys.medications(),
queryFn: async () => {
const res = await fetch("/api/medications");
if (!res.ok) throw new Error("Failed to load medications");
const json = await res.json();
return json.data as MedicationOption[];
},
});
const medications = useMemo(
() =>
Array.isArray(medicationsRaw)
? medicationsRaw.filter((m) => m.active)
: [],
[medicationsRaw],
);
const sortedMedications = useMemo(
() =>
[...medications].sort((a, b) =>
a.name.localeCompare(b.name, "de", { sensitivity: "base" }),
),
[medications],
);
// User-driven medication override; `null` means "use the auto-pick".
// Derived selection prefers the override, falls back to the heuristic
// so a freshly-mounted sheet shows the cool/easy default without any
// effect-driven setState.
const [medicationOverride, setMedicationOverride] = useState<string | null>(
null,
);
// v1.4.37 W10 — the dose field is informational only. The intake
// POST body has no `dose` slot, so any user edit would be silently
// dropped on submit. Until the v1.4.38 schema grows a `doseOverride`
// field, render the input as read-only so the user's mental model
// tracks what the server actually persists. The state holder is
// kept (as `null`) so the medication-switch handler still resets
// the slot cleanly if the schema ever grows the field.
const [doseOverride, setDoseOverride] = useState<string | null>(null);
const [takenAt, setTakenAt] = useState<string>(getDefaultIntakeAtValue);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const errorId = useId();
const errorDescriptor = error ? errorId : undefined;
const formId = useId();
const defaultMedicationId = useMemo(
() => pickDefaultMedicationId(medications),
[medications],
);
const medicationId = medicationOverride ?? defaultMedicationId ?? "";
const selectedMedication = medications.find((m) => m.id === medicationId);
const dose = doseOverride ?? selectedMedication?.dose ?? "";
function handleMedicationChange(value: string) {
setMedicationOverride(value);
// Reset the dose override when the medication changes so the new
// default flows through on the next render. The dose field is
// currently read-only (see v1.4.37 W10 note above), but the reset
// stays in place so the slot is ready to switch back to editable
// when the v1.4.38 doseOverride schema lands.
setDoseOverride(null);
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!medicationId || loading) return;
setError(null);
setLoading(true);
try {
const timestamp = new Date(takenAt).toISOString();
const res = await fetch(`/api/medications/${medicationId}/intake`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
takenAt: timestamp,
skipped: false,
}),
});
const json = await res.json();
if (!res.ok) {
setError(
typeof json?.error === "string"
? json.error
: t("dashboard.medicationIntakeQuickAdd.saveError"),
);
setLoading(false);
return;
}
await invalidateKeys(queryClient, medicationDependentKeys);
// Fan-out to every inline compliance chart key (one per medication)
// so the detail-page tile refreshes when the user re-enters it.
await queryClient.invalidateQueries({
queryKey: ["compliance-chart-inline"],
});
toast.success(t("common.saved"));
onSuccess?.();
} catch {
setError(t("dashboard.medicationIntakeQuickAdd.saveError"));
} finally {
setLoading(false);
}
}
const footerNode = (
<div className="flex w-full items-center justify-end gap-2">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={loading}
className="min-h-11 sm:min-h-9"
>
{t("common.cancel")}
</Button>
)}
<Button
type="submit"
form={formId}
disabled={loading || !medicationId || medications.length === 0}
className="min-h-11 sm:min-h-9"
>
{loading ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{t("common.save")}
</Button>
</div>
);
// Empty-state branch: the user has no active medications. Render a
// hint + CTA into the body so the user has a single tap into the
// medication-creation surface. The form itself is suppressed so we
// don't ship an unusable Save button.
if (!medicationsLoading && medications.length === 0) {
const emptyFooter = (
<div className="flex w-full items-center justify-end gap-2">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
className="min-h-11 sm:min-h-9"
>
{t("common.close")}
</Button>
)}
</div>
);
return (
<>
<div
data-testid="medication-intake-quick-add-empty"
className="flex flex-col items-center gap-3 py-4 text-center"
role="status"
aria-live="polite"
>
<Pill className="text-muted-foreground h-6 w-6" aria-hidden="true" />
<div className="space-y-1">
<p className="text-sm font-medium">
{t("dashboard.medicationIntakeQuickAdd.emptyTitle")}
</p>
<p className="text-muted-foreground text-xs">
{t("dashboard.medicationIntakeQuickAdd.emptyDescription")}
</p>
</div>
<Button
asChild
size="sm"
variant="outline"
className="min-h-11 sm:min-h-9"
>
<Link href="/medications">
{t("dashboard.medicationIntakeQuickAdd.emptyCta")}
</Link>
</Button>
</div>
{footerSlot ? createPortal(emptyFooter, footerSlot) : emptyFooter}
</>
);
}
return (
<form
id={formId}
onSubmit={handleSubmit}
className="space-y-4"
data-testid="medication-intake-quick-add-form"
>
<div className="space-y-2">
<Label htmlFor="medication-intake-medication">
{t("dashboard.medicationIntakeQuickAdd.medicationLabel")}
</Label>
<Select
value={medicationId}
onValueChange={handleMedicationChange}
disabled={medicationsLoading || medications.length === 0}
>
<SelectTrigger
id="medication-intake-medication"
data-testid="medication-intake-quick-add-medication"
className="min-h-11"
>
<SelectValue
placeholder={t(
"dashboard.medicationIntakeQuickAdd.medicationPlaceholder",
)}
/>
</SelectTrigger>
<SelectContent>
{sortedMedications.map((m) => (
<SelectItem key={m.id} value={m.id}>
<span className="flex items-center gap-2">
<Pill
className="text-muted-foreground h-4 w-4"
aria-hidden="true"
/>
<span>{m.name}</span>
{m.dose ? (
<span className="text-muted-foreground text-xs">
({m.dose})
</span>
) : null}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="medication-intake-dose">
{t("dashboard.medicationIntakeQuickAdd.doseLabel")}
</Label>
<Input
id="medication-intake-dose"
data-testid="medication-intake-quick-add-dose"
value={dose}
readOnly
aria-readonly="true"
tabIndex={-1}
placeholder={
selectedMedication?.dose ??
t("dashboard.medicationIntakeQuickAdd.dosePlaceholder")
}
autoComplete="off"
className="min-h-11 bg-muted/40"
/>
<p className="text-muted-foreground text-xs">
{t("dashboard.medicationIntakeQuickAdd.doseHint")}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="medication-intake-taken-at">
{t("dashboard.medicationIntakeQuickAdd.timeLabel")}
</Label>
<DateTimeInput
id="medication-intake-taken-at"
data-testid="medication-intake-quick-add-taken-at"
value={takenAt}
onChange={(e) => setTakenAt(e.target.value)}
required
aria-required="true"
aria-invalid={!!error || undefined}
aria-describedby={errorDescriptor}
/>
</div>
{error && (
<div
id={errorId}
role="alert"
aria-live="assertive"
className="bg-destructive/10 text-destructive rounded-lg p-3 text-sm"
>
{error}
</div>
)}
{footerSlot ? createPortal(footerNode, footerSlot) : footerNode}
</form>
);
}
@@ -328,6 +328,36 @@ describe("<HealthScoreCard>", () => {
expect(disclaimerOpen?.[0]).toContain("mt-auto");
});
// v1.4.37 W4a item 1 — the inner column switched from `flex
// flex-col gap-3` to a 7-row grid so the slack collects on row 6
// (the provenance accordion) instead of clumping under the
// disclaimer. Pin both the grid switch and the `1fr` slack row so
// a future refactor can't silently revert to flex and re-introduce
// the "Karte hört bei der Trennlinie auf" Marc-reported bug.
it("uses a 7-row grid on the inner column so slack distributes on the accordion row", () => {
const html = ssr(
<HealthScoreCard
score={86}
band="green"
components={baseComponents}
delta={null}
/>,
);
// The inner column lives directly after the card wrapper. Match
// the first <div> that opens after the wrapper and assert the
// grid + grid-rows-[...1fr...] contract.
const innerColumn = html.match(
/<div[^>]*data-slot="health-score-card"[^>]*>\s*(?:<!--[\s\S]*?-->\s*)?<div([^>]*)>/,
);
expect(innerColumn).not.toBeNull();
const innerAttrs = innerColumn?.[1] ?? "";
expect(innerAttrs).toContain("grid");
expect(innerAttrs).toContain("flex-1");
expect(innerAttrs).toContain(
"grid-rows-[auto_auto_auto_auto_auto_1fr_auto]",
);
});
it("exposes the progressbar role + ARIA values for screen readers", () => {
const html = ssr(
<HealthScoreCard
@@ -89,4 +89,22 @@ describe("<InsightStatusCard>", () => {
const html = render(<InsightStatusCard {...baseProps} text={null} />);
expect(html).toContain("No analysis yet.");
});
it("renders the structured skeleton (v1.4.37) when loading instead of a centred spinner", () => {
const html = render(
<InsightStatusCard {...baseProps} text={null} loading />,
);
// The skeleton mounts the same icon dot, title bar, prose lines,
// and footer that the loaded card paints so the loading state
// previews the final geometry instead of pinning the card to a
// single centred spinner row. The aria-busy + sr-only label
// preserve the accessible "loading" semantics for assistive
// tech.
expect(html).toContain('aria-busy="true"');
expect(html).toContain('data-testid="insight-status-card-loading"');
expect(html).toContain("Loading");
// The classic Loader2 + visible "common.loading" copy retired so
// we do not double-paint the announcement.
expect(html).not.toContain("animate-spin");
});
});
+10 -1
View File
@@ -256,7 +256,16 @@ export function HealthScoreCard({
"flex h-full flex-col",
)}
>
<div className="flex flex-1 flex-col gap-3">
{/* v1.4.37 W4a item 1 — swap the inner column from `flex
flex-col` to a 7-row grid so the recovered vertical slack
(when the parent hero-row stretches the card past the
natural content height) collects on row 6 (the provenance
accordion) instead of clumping under the disclaimer. The
score number stays anchored at the top, the disclaimer at
the bottom, and the card fills the row down to the
"Wirkt mein Medikament?" chip — closing Marc's "Karte hört
bei der Trennlinie auf" report against v1.4.36. */}
<div className="grid flex-1 grid-rows-[auto_auto_auto_auto_auto_1fr_auto] gap-3">
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<p
+71 -39
View File
@@ -4,6 +4,7 @@ import { Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useTranslations } from "@/lib/i18n/context";
import { formatRelativeTime } from "@/lib/i18n/relative-time";
import { useFeatureFlags } from "@/hooks/use-feature-flags";
import { cn } from "@/lib/utils";
import { SuggestedPrompts } from "./suggested-prompts";
import {
@@ -118,6 +119,14 @@ export function HeroStrip({
healthScore,
}: HeroStripProps) {
const { t } = useTranslations();
// v1.4.37 W5 — operator-level Coach gate. When the global Coach flag
// is off every Coach affordance must vanish from this band (the
// action-row button, the suggested-prompts chip strip, and the
// HealthScoreCard's `onAskCoach` prop). The button and chips both
// open the Coach drawer, so leaving them visible while the drawer
// mount is suppressed would surface dead controls.
const flags = useFeatureFlags();
const coachEnabled = flags.coach;
const greetingKey = resolveGreetingKey(now ?? new Date());
const greetingBase = t(greetingKey);
const greeting = userName ? `${greetingBase}, ${userName}` : greetingBase;
@@ -207,45 +216,61 @@ export function HeroStrip({
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{/* B2b wires this into the Coach drawer. The button is
enabled whenever the parent supplies an `onAskCoach`
handler; older parents that haven't adopted B2b yet
still get the disabled "Coming soon" affordance so the
hero doesn't break. v1.4.28 retired the weekly-report
button, leaving Coach as the only hero-row action. */}
<Button
type="button"
variant="outline"
onClick={onAskCoach ? () => onAskCoach() : undefined}
disabled={!onAskCoach}
title={onAskCoach ? undefined : comingSoon}
data-slot="insights-hero-strip-action-coach"
className="gap-1.5"
>
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
<span>{t("insights.heroActionAskCoach")}</span>
</Button>
{/*
* v1.4.25 W3 — the regenerate button moved to the new
* `<InsightsTabStrip>` (icon-only RefreshCw, sticky next
* to the pill nav) so the user can re-run the analysis
* without scrolling back to the hero band.
*/}
</div>
{/*
* v1.4.37 W5 — the action row only carries the Coach button
* today (v1.4.28 retired the weekly-report affordance). When
* the operator turns the global Coach flag off the whole row
* disappears rather than collapsing to an empty flex shell.
*/}
{coachEnabled && (
<div className="flex flex-wrap items-center gap-2">
{/* B2b wires this into the Coach drawer. The button is
enabled whenever the parent supplies an `onAskCoach`
handler; older parents that haven't adopted B2b yet
still get the disabled "Coming soon" affordance so the
hero doesn't break. v1.4.28 retired the weekly-report
button, leaving Coach as the only hero-row action. */}
<Button
type="button"
variant="outline"
onClick={onAskCoach ? () => onAskCoach() : undefined}
disabled={!onAskCoach}
title={onAskCoach ? undefined : comingSoon}
data-slot="insights-hero-strip-action-coach"
className="gap-1.5"
>
<Sparkles className="h-3.5 w-3.5" aria-hidden="true" />
<span>{t("insights.heroActionAskCoach")}</span>
</Button>
{/*
* v1.4.25 W3 — the regenerate button moved to the new
* `<InsightsTabStrip>` (icon-only RefreshCw, sticky next
* to the pill nav) so the user can re-run the analysis
* without scrolling back to the hero band.
*/}
</div>
)}
<div
data-slot="insights-hero-strip-prompts"
className="border-border/50 border-t pt-4"
>
{/*
* v1.4.20 phase B2b — chip clicks open the Coach drawer
* with the localised prompt pre-filled in the composer.
* The parent owns drawer state so the chip strip stays
* presentational.
*/}
<SuggestedPrompts onPick={onPickPrompt ?? (() => undefined)} />
</div>
{coachEnabled && (
<div
data-slot="insights-hero-strip-prompts"
className="border-border/50 border-t pt-4"
>
{/*
* v1.4.20 phase B2b — chip clicks open the Coach drawer
* with the localised prompt pre-filled in the composer.
* The parent owns drawer state so the chip strip stays
* presentational.
*
* v1.4.37 W5 — the strip is a Coach-only affordance
* (every chip seeds a Coach turn), so it is gated on the
* same flag as the action-row button above. Without the
* gate the chips would still paint while the drawer is
* suppressed, leaving inert controls in the band.
*/}
<SuggestedPrompts onPick={onPickPrompt ?? (() => undefined)} />
</div>
)}
</div>
{healthScore && (
@@ -255,7 +280,14 @@ export function HeroStrip({
components={healthScore.components}
delta={healthScore.delta}
onAskCoach={
onAskCoach ? (prefill: string) => onAskCoach(prefill) : undefined
// v1.4.37 W5 — short-circuit the prop drilling even
// though `HealthScoreCard` retired its inline button in
// v1.4.27. A future re-addition can't accidentally
// surface a Coach affordance from this card while the
// operator has the flag off.
coachEnabled && onAskCoach
? (prefill: string) => onAskCoach(prefill)
: undefined
}
/>
)}
@@ -3,7 +3,6 @@
import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Loader2 } from "lucide-react";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { stripChartTokens } from "@/lib/insights/chart-tokens";
import { cn } from "@/lib/utils";
@@ -40,13 +39,30 @@ export function InsightStatusCard({
if (!flags.insightStatus) return null;
if (loading) {
// v1.4.37 — structured skeleton over the centred spinner. When the
// per-metric status route had to fall back to the 20 s provider
// race the user used to stare at a single centred spinner with
// "Lade…" copy, which gave no sense of progress and pinned the
// card to a flat dot. The skeleton paints the actual rendered
// geometry (icon dot, title bar, three text lines, footer) so the
// loading state previews where the assessment will land. Heights
// mirror `<CardTitle>` (`text-base` → 1 rem) and the prose
// (`text-sm` → 0.875 rem) so the post-load swap reflows by less
// than a row.
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<Loader2 className="text-dracula-purple h-5 w-5 animate-spin motion-reduce:animate-none" />
<span className="text-muted-foreground ml-2 text-sm">
{t("common.loading")}
</span>
<Card aria-busy="true" aria-live="polite" data-testid="insight-status-card-loading">
<CardHeader className="pb-2">
<div className="flex items-center gap-2">
<div className="bg-muted h-5 w-5 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-4 w-32 animate-pulse rounded motion-reduce:animate-none" />
</div>
</CardHeader>
<CardContent className="space-y-2">
<div className="bg-muted h-3.5 w-full animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-11/12 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted h-3.5 w-9/12 animate-pulse rounded motion-reduce:animate-none" />
<div className="bg-muted/70 h-3 w-1/3 animate-pulse rounded motion-reduce:animate-none" />
<span className="sr-only">{t("common.loading")}</span>
</CardContent>
</Card>
);
@@ -2,6 +2,7 @@
import { Quote } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { useFeatureFlags } from "@/hooks/use-feature-flags";
import { cn } from "@/lib/utils";
/**
@@ -47,6 +48,15 @@ export function SuggestedPrompts({
className,
}: SuggestedPromptsProps) {
const { t } = useTranslations();
// v1.4.37 W5 — every chip is a Coach affordance: clicking one seeds
// the Coach drawer's composer and opens it. When the operator turns
// the global Coach flag off the strip must vanish along with the
// hero action button and the drawer mount. The HeroStrip caller
// already guards on `flags.coach`; the in-component gate is
// defence-in-depth so a future caller that mounts <SuggestedPrompts>
// outside the hero band can never leak a Coach surface.
const flags = useFeatureFlags();
if (!flags.coach) return null;
const items =
prompts ??
DEFAULT_PROMPT_KEYS.map((key) => t(`insights.suggestedPrompts.${key}`));
+1 -1
View File
@@ -117,7 +117,7 @@ function SidebarUserSection({ collapsed }: { collapsed: boolean }) {
<DropdownMenuContent
side="right"
align="end"
className="w-56"
className="w-60"
sideOffset={8}
>
<div className="flex items-center gap-3 px-2 py-2">
+1 -1
View File
@@ -81,7 +81,7 @@ export function TopBar() {
<span className="hidden sm:inline">{user.username}</span>
<ChevronDown className="h-3 w-3 opacity-60" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuContent align="end" className="w-60">
<DropdownMenuItem asChild>
<Link href="/settings/account" className="cursor-pointer">
<Settings className="mr-2 h-4 w-4" />
@@ -0,0 +1,108 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
/**
* v1.4.37 W7c — when the list filter is a cumulative HK type, the
* list view renders one row per user-TZ day with the day's total and
* a chevron that drills back into the per-sample chunks via a
* separate query. This test mocks both queries (the parent + the
* drill-down) and asserts the rendered surface paints the collapsed
* shape without leaking per-sample rows by default.
*/
const collapsed = [
{
id: "day:ACTIVITY_STEPS:2026-05-15",
type: "ACTIVITY_STEPS",
value: 12000,
unit: "steps",
source: "APPLE_HEALTH",
measuredAt: "2026-05-15T10:00:00.000Z",
notes: null,
dayKey: "2026-05-15",
sampleCount: 42,
},
];
// Per-mock TanStack Query stub: when the queryKey starts with
// "measurement-drilldown" we serve nothing (drill-down should not
// fire until the chevron is clicked, which static render never
// triggers).
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ queryKey }: { queryKey: unknown[] }) => {
if (
Array.isArray(queryKey) &&
queryKey[0] === "measurement-drilldown"
) {
return { data: undefined, isLoading: false };
}
return {
data: { measurements: collapsed, meta: { total: 1 } },
isLoading: false,
};
},
useQueryClient: () => ({ invalidateQueries: vi.fn() }),
useMutation: () => ({
mutate: vi.fn(),
mutateAsync: vi.fn(),
isPending: false,
isError: false,
error: null,
}),
}));
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/measurements",
}));
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
user: { id: "u1", username: "marc", role: "USER" },
isAuthenticated: true,
isLoading: false,
}),
}));
import { I18nProvider } from "@/lib/i18n/context";
import { MeasurementList } from "../measurement-list";
function render(locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<MeasurementList />
</I18nProvider>,
);
}
describe("MeasurementList — cumulative-type collapsed view (W7c)", () => {
it("renders the daily-total caption with the sample count", () => {
const html = render("en");
// The daily-total caption ("(42 samples)") sits next to the
// day's total ("12000 steps") on the collapsed row.
expect(html).toContain("12,000 steps");
expect(html).toMatch(/\(42 samples\)/);
});
it("renders a chevron-expand button on the collapsed row", () => {
const html = render("en");
expect(html).toContain('data-testid="measurement-day-expand"');
// The chevron exposes its expanded state via aria-expanded so
// assistive tech announces the toggle correctly.
expect(html).toMatch(/aria-expanded="false"/);
});
it("does not paint edit/delete affordances on the synthesised daily row", () => {
const html = render("en");
// The edit + delete actions are hidden because the synthetic
// `day:…` id has no real Measurement row backing it. The chevron
// is the only action.
expect(html).not.toMatch(/aria-label="Edit"/);
expect(html).not.toMatch(/aria-label="Delete"/);
});
it("localises the daily-total caption in German", () => {
const html = render("de");
expect(html).toMatch(/\(42 Einzelwerte\)/);
});
});
+375 -109
View File
@@ -48,15 +48,17 @@ import {
Trash2,
ChevronLeft,
ChevronRight,
ChevronDown,
ArrowUp,
ArrowDown,
ArrowUpDown,
MoreHorizontal,
} from "lucide-react";
import { useId, useState } from "react";
import { Fragment, useId, useState } from "react";
import { createPortal } from "react-dom";
import { formatDateTime } from "@/lib/format";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { CUMULATIVE_DAY_SUM_TYPES } from "@/lib/measurements/cumulative-day-sum";
import { invalidateKeys, measurementDependentKeys } from "@/lib/query-keys";
import { DateTimeInput } from "@/components/ui/date-input";
import {
@@ -65,6 +67,15 @@ import {
MEASUREMENT_TYPE_COLORS as TYPE_COLORS,
} from "./measurement-list-meta";
/**
* v1.4.37 W7c — cumulative HK types whose list view collapses to one
* row per user-TZ day with an expand-chevron drill-down to the
* per-sample chunks. Mirrors the server-side
* `CUMULATIVE_DAY_SUM_TYPES` so the route's `groupBy=day` branch and
* the client's filter-detection agree on the same five identifiers.
*/
const CUMULATIVE_TYPES = new Set<string>(CUMULATIVE_DAY_SUM_TYPES);
interface Measurement {
id: string;
type: string;
@@ -73,6 +84,13 @@ interface Measurement {
source: string;
measuredAt: string;
notes: string | null;
/**
* v1.4.37 W7c — present only on collapsed daily rows returned by
* `?type=…&groupBy=day`. Drives the expand chevron + the drill-down
* fetch keyed by the user's calendar day.
*/
dayKey?: string;
sampleCount?: number;
}
interface MeasurementListProps {
@@ -140,6 +158,21 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
const [sortBy, setSortBy] = useState<string>("measuredAt");
const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
// v1.4.37 W7c — set of dayKeys whose drill-down is currently
// expanded. Each key maps to a one-shot query that lazy-fetches
// the per-sample rows for that calendar day on first open.
const [expandedDayKeys, setExpandedDayKeys] = useState<Set<string>>(
() => new Set(),
);
function toggleExpand(dayKey: string) {
setExpandedDayKeys((prev) => {
const next = new Set(prev);
if (next.has(dayKey)) next.delete(dayKey);
else next.add(dayKey);
return next;
});
}
const [editing, setEditing] = useState<Measurement | null>(null);
const [editValue, setEditValue] = useState("");
const [editMeasuredAt, setEditMeasuredAt] = useState("");
@@ -172,6 +205,16 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
setPage(1);
}
// v1.4.37 W7c — when the type filter is a cumulative HK type
// (steps, active energy, distance, flights, daylight) the list
// collapses to one row per user-TZ day via the route's
// `groupBy=day` mode. The chevron in the row drills back into the
// per-sample chunks via a separate `dayKey=…` query. Matches the
// Apple Health.app / Garmin / Withings pattern documented in
// `.planning/research/v1437-step-aggregation.md` §"How the leaders
// do it" — never list per-sample chunks as the default view.
const isCumulativeFilter = CUMULATIVE_TYPES.has(typeFilter);
const { data, isLoading } = useQuery({
queryKey: [
"measurements",
@@ -179,6 +222,7 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
page,
sortBy,
sortDir,
isCumulativeFilter ? "groupBy=day" : "raw",
],
queryFn: async () => {
const params = new URLSearchParams();
@@ -187,6 +231,22 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
params.set("offset", String((page - 1) * PAGE_SIZE));
params.set("sortBy", sortBy);
params.set("sortDir", sortDir);
if (isCumulativeFilter) {
params.set("groupBy", "day");
// The collapsed mode synthesises one row per day from the
// window of raw samples. Use the server-side ceiling (5000)
// so a chatty pre-drain Apple-Watch account (≈200 per-sample
// chunks/day on the busiest days) still fills several screens
// of daily rows before the nightly drain reduces each day to
// a single `stats:` row. Post-drain the scan is trivially
// short — every day reduces to 1 row.
params.set("limit", "5000");
// The synthesised rows live entirely in the collapse branch
// — pagination/offset don't apply on the server side. Reset
// the offset so a sort-direction flip doesn't paginate into
// an empty slice.
params.set("offset", "0");
}
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch");
const json = await res.json();
@@ -269,7 +329,16 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
},
});
const totalPages = data ? Math.ceil(data.meta.total / PAGE_SIZE) : 0;
// v1.4.37 W7c — the collapsed daily view paints up to 5000
// synthesised rows in one shot (one row per day for the
// configured window). Pagination would force a second server
// round-trip that re-fires the same scan, so the day-grouped
// path collapses to a single page. Per-sample lists continue to
// paginate at PAGE_SIZE = 25.
const totalPages =
data && !isCumulativeFilter
? Math.ceil(data.meta.total / PAGE_SIZE)
: 0;
function startEdit(measurement: Measurement) {
if (onEdit) {
@@ -450,62 +519,118 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
</TableRow>
</TableHeader>
<TableBody>
{data.measurements.map((m) => (
<TableRow key={m.id}>
<TableCell className="pl-4">
<Badge
variant="secondary"
className={TYPE_COLORS[m.type] ?? ""}
>
{TYPE_LABEL_KEYS[m.type]
? t(TYPE_LABEL_KEYS[m.type])
: m.type}
</Badge>
</TableCell>
<TableCell className="font-semibold tabular-nums">
{m.value} {m.unit}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{formatDateTime(m.measuredAt)}
</TableCell>
<TableCell className="text-sm">
{m.notes ? (
<span title={m.notes}>
{truncateComment(m.notes)}
</span>
) : (
<span className="text-muted-foreground">-</span>
{data.measurements.map((m) => {
const isGrouped =
m.dayKey !== undefined && m.sampleCount !== undefined;
const isExpanded = isGrouped
? expandedDayKeys.has(m.dayKey as string)
: false;
return (
<Fragment key={m.id}>
<TableRow>
<TableCell className="pl-4">
<Badge
variant="secondary"
className={TYPE_COLORS[m.type] ?? ""}
>
{TYPE_LABEL_KEYS[m.type]
? t(TYPE_LABEL_KEYS[m.type])
: m.type}
</Badge>
</TableCell>
<TableCell className="font-semibold tabular-nums">
{fmt.integer(m.value)} {m.unit}
{isGrouped && (
<span className="text-muted-foreground ml-2 text-xs font-normal">
{t("measurements.dailyTotalCaption", {
count: fmt.integer(
m.sampleCount as number,
),
})}
</span>
)}
</TableCell>
<TableCell className="text-muted-foreground text-sm">
{formatDateTime(m.measuredAt)}
</TableCell>
<TableCell className="text-sm">
{m.notes ? (
<span title={m.notes}>
{truncateComment(m.notes)}
</span>
) : (
<span className="text-muted-foreground">-</span>
)}
</TableCell>
<TableCell>
{m.source !== "MANUAL" && (
<Badge
variant="outline"
data-testid="measurement-source-badge"
className={`text-xs ${sourceBadgeClass(m.source)}`.trim()}
>
{formatMeasurementSource(m.source, t)}
</Badge>
)}
</TableCell>
<TableCell className="pr-4 text-right">
<div className="flex items-center justify-end gap-1">
{isGrouped ? (
<Button
variant="ghost"
size="icon"
className="h-10 w-10"
data-testid="measurement-day-expand"
onClick={() =>
toggleExpand(m.dayKey as string)
}
aria-expanded={isExpanded}
aria-label={
isExpanded
? t("measurements.collapseDay")
: t("measurements.expandDay")
}
>
<ChevronDown
className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
/>
</Button>
) : (
<>
<Button
variant="ghost"
size="icon"
className="h-10 w-10"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() =>
deleteMutation.mutate(m.id)
}
/>
</>
)}
</div>
</TableCell>
</TableRow>
{isGrouped && isExpanded && (
<TableRow>
<TableCell colSpan={6} className="p-0">
<DayDrillDown
type={m.type}
dayKey={m.dayKey as string}
unit={m.unit}
layout="desktop"
/>
</TableCell>
</TableRow>
)}
</TableCell>
<TableCell>
{m.source !== "MANUAL" && (
<Badge
variant="outline"
data-testid="measurement-source-badge"
className={`text-xs ${sourceBadgeClass(m.source)}`.trim()}
>
{formatMeasurementSource(m.source, t)}
</Badge>
)}
</TableCell>
<TableCell className="pr-4 text-right">
<div className="flex items-center justify-end gap-1">
<Button
variant="ghost"
size="icon"
className="h-10 w-10"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<DeleteButton
onConfirm={() => deleteMutation.mutate(m.id)}
/>
</div>
</TableCell>
</TableRow>
))}
</Fragment>
);
})}
</TableBody>
</Table>
</div>
@@ -514,75 +639,116 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
<div className="space-y-2 md:hidden">
{data.measurements.map((m) => {
const Icon = TYPE_ICONS[m.type];
const isGrouped =
m.dayKey !== undefined && m.sampleCount !== undefined;
const isExpanded = isGrouped
? expandedDayKeys.has(m.dayKey as string)
: false;
return (
<div
key={m.id}
className="bg-card border-border flex items-center justify-between rounded-lg border p-3"
className="bg-card border-border rounded-lg border p-3"
>
<div className="flex items-center gap-2.5 overflow-hidden">
{Icon && (
<div
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${TYPE_COLORS[m.type] ?? ""}`}
>
<Icon className="h-4 w-4" />
</div>
)}
<div className="min-w-0">
{/* v1.4.27 MB7 / CF-76 — bump the metadata
badges from `text-[10px]` to `text-[11px]`
so the legibility floor (12 px is the
mobile baseline; 11 px is the lowest
tolerated value for non-primary chrome)
holds across the row. The badge heights
stay at `h-5` / `h-4` since the type-
preface badge owns vertical real estate
inside the headline line. */}
{(m.type === "BLOOD_PRESSURE_SYS" ||
m.type === "BLOOD_PRESSURE_DIA") && (
<Badge
variant="outline"
className="mr-1.5 h-5 px-1 text-[11px]"
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5 overflow-hidden">
{Icon && (
<div
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${TYPE_COLORS[m.type] ?? ""}`}
>
{t(TYPE_LABEL_KEYS[m.type])}
</Badge>
<Icon className="h-4 w-4" />
</div>
)}
<span className="font-semibold tabular-nums">
{m.value} {m.unit}
</span>
<p className="text-muted-foreground truncate text-xs">
<span>{formatDateTime(m.measuredAt)}</span>
{m.source !== "MANUAL" && (
<div className="min-w-0">
{/* v1.4.27 MB7 / CF-76 — bump the metadata
badges from `text-[10px]` to `text-[11px]`
so the legibility floor (12 px is the
mobile baseline; 11 px is the lowest
tolerated value for non-primary chrome)
holds across the row. */}
{(m.type === "BLOOD_PRESSURE_SYS" ||
m.type === "BLOOD_PRESSURE_DIA") && (
<Badge
variant="outline"
data-testid="measurement-source-badge"
className={`ml-1.5 h-4 px-1 text-[11px] ${sourceBadgeClass(m.source)}`.trim()}
className="mr-1.5 h-5 px-1 text-[11px]"
>
{formatMeasurementSource(m.source, t)}
{t(TYPE_LABEL_KEYS[m.type])}
</Badge>
)}
</p>
{m.notes && (
<span className="font-semibold tabular-nums">
{fmt.integer(m.value)} {m.unit}
</span>
{isGrouped && (
<span className="text-muted-foreground ml-1.5 text-[11px]">
{t("measurements.dailyTotalCaption", {
count: fmt.integer(m.sampleCount as number),
})}
</span>
)}
<p className="text-muted-foreground truncate text-xs">
{truncateComment(m.notes)}
<span>{formatDateTime(m.measuredAt)}</span>
{m.source !== "MANUAL" && (
<Badge
variant="outline"
data-testid="measurement-source-badge"
className={`ml-1.5 h-4 px-1 text-[11px] ${sourceBadgeClass(m.source)}`.trim()}
>
{formatMeasurementSource(m.source, t)}
</Badge>
)}
</p>
{m.notes && (
<p className="text-muted-foreground truncate text-xs">
{truncateComment(m.notes)}
</p>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
{isGrouped ? (
<Button
variant="ghost"
size="icon"
className="size-11"
data-testid="measurement-day-expand"
onClick={() => toggleExpand(m.dayKey as string)}
aria-expanded={isExpanded}
aria-label={
isExpanded
? t("measurements.collapseDay")
: t("measurements.expandDay")
}
>
<ChevronDown
className={`h-4 w-4 transition-transform ${isExpanded ? "rotate-180" : ""}`}
/>
</Button>
) : (
<>
<Button
variant="ghost"
size="icon"
className="size-11"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-4 w-4" />
</Button>
<DeleteButton
className="size-11"
onConfirm={() => deleteMutation.mutate(m.id)}
/>
</>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="icon"
className="size-11"
onClick={() => startEdit(m)}
aria-label={t("common.edit")}
>
<Pencil className="h-4 w-4" />
</Button>
<DeleteButton
className="size-11"
onConfirm={() => deleteMutation.mutate(m.id)}
{isGrouped && isExpanded && (
<DayDrillDown
type={m.type}
dayKey={m.dayKey as string}
unit={m.unit}
layout="mobile"
/>
</div>
)}
</div>
);
})}
@@ -807,6 +973,106 @@ export function MeasurementList({ onEdit, onAddFirst }: MeasurementListProps) {
);
}
/**
* v1.4.37 W7c — lazy drill-down for a collapsed cumulative-type day.
* Fires a separate `GET /api/measurements?type=…&dayKey=…` only when
* the row is expanded; the result is rendered as a nested list of the
* per-sample chunks that summed into the parent row's daily total.
*/
function DayDrillDown({
type,
dayKey,
unit,
layout,
}: {
type: string;
dayKey: string;
unit: string;
layout: "desktop" | "mobile";
}) {
const { t } = useTranslations();
const { isAuthenticated } = useAuth();
const { data, isLoading, error } = useQuery({
queryKey: ["measurement-drilldown", type, dayKey],
queryFn: async () => {
const params = new URLSearchParams();
params.set("type", type);
params.set("dayKey", dayKey);
params.set("sortDir", "asc");
const res = await fetch(`/api/measurements?${params}`);
if (!res.ok) throw new Error("Failed to fetch drill-down");
const json = await res.json();
return json.data as { measurements: Measurement[] };
},
enabled: isAuthenticated,
// The drill-down is per-day — once fetched it rarely needs to
// re-fetch (the underlying day has already stabilised for
// anything older than the drain's 36 h cutoff). Keep it cached
// for the session.
staleTime: 5 * 60 * 1000,
});
if (isLoading) {
return (
<div className="text-muted-foreground flex items-center gap-2 py-2 text-xs">
<Loader2 className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
{t("common.loading")}
</div>
);
}
if (error) {
return (
<div className="text-destructive py-2 text-xs">
{t("measurements.saveError")}
</div>
);
}
const rows = data?.measurements ?? [];
if (rows.length === 0) {
return (
<div className="text-muted-foreground py-2 text-xs">
{t("measurements.emptyDescription")}
</div>
);
}
if (layout === "desktop") {
return (
<div className="bg-muted/40 space-y-1 p-2">
{rows.map((s) => (
<div
key={s.id}
className="flex items-center justify-between gap-3 px-2 py-1 text-xs"
>
<span className="text-muted-foreground tabular-nums">
{formatDateTime(s.measuredAt)}
</span>
<span className="font-medium tabular-nums">
{s.value} {unit}
</span>
</div>
))}
</div>
);
}
return (
<div className="bg-muted/40 mt-2 space-y-1 rounded-md p-2">
{rows.map((s) => (
<div
key={s.id}
className="flex items-center justify-between gap-2 px-1 py-1 text-xs"
>
<span className="text-muted-foreground tabular-nums">
{formatDateTime(s.measuredAt)}
</span>
<span className="font-medium tabular-nums">
{s.value} {unit}
</span>
</div>
))}
</div>
);
}
function SortableHead({
column,
label,
@@ -61,13 +61,16 @@ function seedIntake(
const sortDir = opts.sortDir ?? "desc";
const limit = opts.limit ?? 25;
const offset = opts.offset ?? 0;
// v1.4.37 W3 — the component pins `status:"completed"` on the
// server-side query and threads it through the cache key, so the
// seed mirrors that shape verbatim.
client.setQueryData(
[
"medications",
medId,
"intake",
"list",
{ sortBy, sortDir, limit, offset },
{ sortBy, sortDir, limit, offset, status: "completed" },
],
{ events: rows, meta: { total, limit, offset } },
);
@@ -93,10 +96,7 @@ describe("<IntakeHistoryListV2> — empty state", () => {
it("renders the empty-state title and CTA in English", () => {
const client = makeClient();
seedIntake(client, "med-1", []);
const html = render(
<IntakeHistoryListV2 medicationId="med-1" />,
client,
);
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
expect(html).toContain("No intakes recorded yet");
expect(html).toContain("Open daily intake");
expect(html).toContain('href="/medications"');
@@ -138,23 +138,101 @@ describe("<IntakeHistoryListV2> — populated rows", () => {
createdAt: "2026-05-14T20:00:00.000Z",
},
]);
const html = render(
<IntakeHistoryListV2 medicationId="med-1" />,
client,
);
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
expect(html).toContain("Taken");
expect(html).toContain("Skipped");
expect(html).toContain("Website");
expect(html).toContain("Telegram / Reminder");
});
it("renders the taken row with a green Check chip and the skipped row with an outline SkipForward chip", () => {
// v1.4.37 W3 — guards the regression Marc reported on 2026-05-17:
// before the fix, every row used the same secondary badge with the
// "Eingenommen" label regardless of skipped status. The chip must
// surface a distinct icon + label per branch and never label a
// skipped row "Eingenommen".
const client = makeClient();
seedIntake(client, "med-status", [
{
id: "evt-taken",
medicationId: "med-status",
scheduledFor: "2026-05-15T08:00:00.000Z",
takenAt: "2026-05-15T08:02:00.000Z",
skipped: false,
source: "WEB",
createdAt: "2026-05-15T08:02:00.000Z",
},
{
id: "evt-skipped",
medicationId: "med-status",
scheduledFor: "2026-05-14T08:00:00.000Z",
takenAt: null,
skipped: true,
source: "REMINDER",
createdAt: "2026-05-14T20:00:00.000Z",
},
]);
const html = render(
<IntakeHistoryListV2 medicationId="med-status" />,
client,
);
// Distinct lucide icons per branch — proves the row matched the
// correct status arm and isn't just printing a label.
expect(html).toContain("lucide-check");
expect(html).toContain("lucide-skip-forward");
// The green styling pins the taken branch visually so a future
// refactor cannot silently collapse the two chips back into one
// neutral badge.
expect(html).toMatch(/bg-green-500\/20[^"]*text-green-400/);
// Skipped rows render as a muted outline chip — never as the
// secondary "Eingenommen" badge.
expect(html).toMatch(/text-muted-foreground[^"]*gap-1[^"]*text-xs/);
expect(html).toContain("Taken");
expect(html).toContain("Skipped");
});
it("renders the skipped chip in German without leaking the Eingenommen label", () => {
// v1.4.37 W3 — UAT echo. Marc reported a German row labelled
// both "übersprungen" and "eingenommen". The fix means a
// skipped-only fixture renders "Übersprungen" exactly once and
// "Eingenommen" zero times.
const client = makeClient();
seedIntake(client, "med-skipped", [
{
id: "evt-skipped",
medicationId: "med-skipped",
scheduledFor: "2026-04-29T05:00:00.000Z",
takenAt: null,
skipped: true,
source: "REMINDER",
createdAt: "2026-04-29T05:01:00.000Z",
},
]);
const html = render(
<IntakeHistoryListV2 medicationId="med-skipped" />,
client,
"de",
);
// Locate the table-body slice so we only count chip labels, not
// the column headers (which also say "Eingenommen" for the
// takenAt column header).
const tbodyMatch = html.match(/<tbody[\s\S]*?<\/tbody>/);
expect(tbodyMatch).not.toBeNull();
const body = tbodyMatch?.[0] ?? "";
expect(body).toContain("Übersprungen");
expect(body).not.toContain("Eingenommen");
});
it("renders the section title across both locales", () => {
const client = makeClient();
seedIntake(client, "med-1", []);
const enHtml = render(
<IntakeHistoryListV2 medicationId="med-1" />,
client,
);
const enHtml = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
expect(enHtml).toContain("Intake history");
const deClient = makeClient();
@@ -182,10 +260,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
createdAt: "2026-05-15T08:02:00.000Z",
},
]);
const html = render(
<IntakeHistoryListV2 medicationId="med-1" />,
client,
);
const html = render(<IntakeHistoryListV2 medicationId="med-1" />, client);
// Default sort = takenAt desc, so the "taken" header carries the
// arrow-down icon and the "scheduled" header carries the neutral
// dual-arrow icon.
@@ -235,10 +310,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
],
50,
);
const html = render(
<IntakeHistoryListV2 medicationId="med-2" />,
client,
);
const html = render(<IntakeHistoryListV2 medicationId="med-2" />, client);
expect(html).toContain("Previous");
expect(html).toContain("Next");
// a11y: pagination buttons clear the 44 px mobile touch floor and
@@ -265,10 +337,7 @@ describe("<IntakeHistoryListV2> — sort indicators", () => {
],
1,
);
const html = render(
<IntakeHistoryListV2 medicationId="med-3" />,
client,
);
const html = render(<IntakeHistoryListV2 medicationId="med-3" />, client);
expect(html).not.toContain(">Previous<");
expect(html).not.toContain(">Next<");
});
@@ -164,10 +164,13 @@ beforeEach(() => {
describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
it("renders the GLP-1 variant when treatmentClass === 'GLP1' is active", () => {
// Headline differentiator: the GLP-1 card stamps the
// `medications.treatmentClassGlp1` badge ("GLP-1 injection")
// which the generic card never renders. Presence of the badge is
// the contract pin for "GLP-1 variant is showing".
// v1.4.37 W4b — the category-label slot now mirrors the generic
// card (real `medication.category` lookup) so Ramipril and
// Mounjaro share the same row shape. The variant differentiator
// moved into the GLP-1-specific rows below the header (last/next
// injection, rotation hint). We verify the GLP-1 card no longer
// hard-codes the treatment-class label into the category slot,
// and that the actual category lookup wins.
const client = makeClient();
seedCompliance(client, med7p5.id);
seedGlp1Details(client, med7p5.id, {});
@@ -177,7 +180,9 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
client,
);
expect(html).toContain("GLP-1 injection");
// Category is OTHER → "Other" badge wins.
expect(html).toContain("Other");
expect(html).not.toContain("GLP-1 injection");
// v1.4.28 FB-G1 — the Syringe glyph + middle-dot separator on the
// list row are gone. The list row reads as the canonical two-line
// shape: `{name} {dose}` on line 1, class label on line 2.
@@ -357,13 +362,15 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
expect(html).not.toContain("Low stock");
});
it("side-effect quick-log button hands off the medication object", () => {
// SSR can't fire DOM clicks, so we smoke-check the contract:
// - the button renders when onLogSideEffect is supplied
// - invoking the handler synchronously delivers the GLP-1
// medication object the parent will then prefill MoodEntry with
// (the parent's MoodEntry mutation reads med.name to build the
// pre-tagged side-effect entry).
it("side-effect quick-log moves into the header actions overflow", () => {
// v1.4.37 W4b — the side-effect quick-log no longer sits in the
// primary actions row (which used to read as a three-button row
// and broke symmetry with the generic Ramipril card). It now
// lives behind a kebab overflow in the header `actions` slot.
// SSR doesn't open Radix Portal content, so we assert the trigger
// surfaces with the localised `common.moreOptions` aria-label and
// smoke-check that invoking the handler delivers the GLP-1
// medication object the parent prefills MoodEntry with.
const client = makeClient();
seedCompliance(client, med7p5.id);
seedGlp1Details(client, med7p5.id, {});
@@ -378,21 +385,27 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
client,
);
// Button renders with the localised label.
expect(html).toContain("Log side effect");
// Kebab trigger renders with the localised aria-label.
expect(html).toContain('aria-label="More options"');
// The side-effect button must no longer ride alongside
// Eingenommen / Übersprungen in the primary actions row.
expect(html).not.toMatch(
/class="[^"]*flex[^"]*gap-2[^"]*"[^>]*>[\s\S]*?Log side effect/,
);
// Invoke the supplied handler the way the button's onClick would —
// pins the prefill payload contract for MoodEntry.
// Invoke the supplied handler the way the menu item's onClick
// would — pins the prefill payload contract for MoodEntry.
handler(med7p5);
expect(handler).toHaveBeenCalledWith(
expect.objectContaining({ name: "Mounjaro", treatmentClass: "GLP1" }),
);
});
it("omits the side-effect button when onLogSideEffect is not supplied", () => {
// Back-compat: the button is opt-in via the prop. Pages that
// haven't wired the MoodEntry hand-off yet should still render
// the card without a dead button.
it("omits the overflow kebab when onLogSideEffect is not supplied", () => {
// Back-compat: the overflow is opt-in via the prop. Pages that
// haven't wired the MoodEntry hand-off yet render Mounjaro with
// exactly the same header-actions shape as Ramipril (history +
// edit, no kebab) so the medications list stays symmetric.
const client = makeClient();
seedCompliance(client, med7p5.id);
seedGlp1Details(client, med7p5.id, {});
@@ -402,7 +415,7 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
client,
);
expect(html).not.toContain("Log side effect");
expect(html).not.toContain('aria-label="More options"');
});
it("AI-disabled state: no Coach hand-off button is rendered today", () => {
@@ -446,8 +459,11 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
expect(html).toContain("opacity-60");
expect(html).toContain("Paused since");
// Primary actions ("Taken" / "Skipped") are suppressed for
// inactive medications.
expect(html).not.toContain("Log side effect");
// inactive medications. The header-actions overflow trigger is
// unconditionally absent when `onLogSideEffect` is not supplied
// (this test fixture doesn't wire it), so Mounjaro and Ramipril
// headers stay shape-equivalent in the paused state.
expect(html).not.toContain('aria-label="More options"');
});
it("renders German copy under the 'de' locale", () => {
@@ -468,7 +484,12 @@ describe("<Glp1MedicationCard> — GLP-1 variant rendering", () => {
"de",
);
expect(html).toContain("GLP-1-Injektion");
// v1.4.37 W4b — the German category badge now comes from the
// shared category-label lookup (Sonstiges for OTHER) instead of
// the hard-coded "GLP-1-Injektion" label, so the GLP-1 card stays
// visually symmetric with the generic card on the medications list.
expect(html).toContain("Sonstiges");
expect(html).not.toContain("GLP-1-Injektion");
expect(html).toContain("Letzter Termin:");
expect(html).toContain("Bauch, unten links");
// v1.4.28 retired the "Dosis-Historie" disclosure on the GLP-1 card.
@@ -0,0 +1,319 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { MedicationCard } from "@/components/medications/medication-card";
import {
Glp1MedicationCard,
type Glp1Medication,
} from "@/components/medications/glp1-medication-card";
/**
* v1.4.37 W4b — symmetry contract between the generic medication card
* (Ramipril/non-GLP-1) and the GLP-1 variant (Mounjaro). Marc reported
* during the v1.4.37 UX audit that the two cards "felt different"
* even though both should read as the same row shape. These tests pin
* the load-bearing structural seams so a future refactor can't quietly
* regress the parity.
*
* What we assert:
* 1. Header `actions` cluster — both cards always render `History`
* and `Pencil` icon buttons. The Mounjaro card optionally renders
* an additional kebab when `onLogSideEffect` is wired; absent the
* prop the headers are byte-shape equivalent.
* 2. Category-label badge — both cards consult the same
* `getMedicationCategoryLabel` lookup. No card hard-codes the
* `medications.treatmentClassGlp1` string into the slot.
* 3. Take-now status pill — when the current time is inside a
* configured schedule window and `lastTakenAt` is null/older, both
* cards render the `medications.takeNow` localised text.
* 4. Primary actions row — exactly two buttons (Eingenommen /
* Übersprungen). The side-effect quick-log lives in the header
* overflow when wired, not in this row.
* 5. Purple dose accent — both cards render
* `font-medium text-purple-400` on the upcoming schedule dose.
*/
function makeClient(): QueryClient {
return new QueryClient({
defaultOptions: {
queries: { retry: false, gcTime: 0, staleTime: Infinity },
},
});
}
function render(
node: React.ReactNode,
client: QueryClient,
locale: "en" | "de" = "en",
) {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<QueryClientProvider client={client}>{node}</QueryClientProvider>
</I18nProvider>,
);
}
function seedCompliance(client: QueryClient, medId: string) {
client.setQueryData(["medications", medId, "compliance"], {
compliance7: { rate: 90, streak: 0, totalExpected: 7, taken: 6 },
compliance30: { rate: 88 },
});
}
function seedGlp1Details(client: QueryClient, medId: string) {
client.setQueryData(["medications", medId, "glp1-details"], {
doseChanges: [],
recentIntakes: [],
inventory: null,
});
}
/**
* Schedule that fires every day of the week from 00:00 to 23:59 so
* the SSR snapshot always lands inside the current window regardless
* of the host clock — pinning the "take now" pill assertion.
*/
const allDayWindow = {
windowStart: "00:00",
windowEnd: "23:59",
label: null,
daysOfWeek: null,
};
const ramipril = {
id: "med-ramipril-1",
name: "Ramipril",
dose: "5 mg",
category: "BLOOD_PRESSURE",
treatmentClass: undefined as string | undefined,
active: true,
notificationsEnabled: true,
pausedAt: null,
lastTakenAt: null,
todayEventCount: 0,
schedules: [
{
id: "s-ramipril-1",
...allDayWindow,
dose: "5 mg",
},
],
};
const mounjaro: Glp1Medication = {
id: "med-mounjaro-1",
name: "Mounjaro",
dose: "7.5 mg",
category: "HORMONE",
treatmentClass: "GLP1",
dosesPerUnit: 4,
active: true,
notificationsEnabled: true,
pausedAt: null,
lastTakenAt: null,
todayEventCount: 0,
schedules: [
{
id: "s-mounjaro-1",
...allDayWindow,
dose: "7.5 mg",
},
],
};
describe("medication card symmetry — Ramipril vs Mounjaro", () => {
it("both cards render History + Pencil header buttons", () => {
const client = makeClient();
seedCompliance(client, ramipril.id);
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const ramiprilHtml = render(
<MedicationCard medication={ramipril} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
client,
);
for (const html of [ramiprilHtml, mounjaroHtml]) {
expect(html).toContain("lucide-history");
expect(html).toContain("lucide-pencil");
}
});
it("neither card paints a kebab when no overflow prop is wired", () => {
// Symmetry default: without onLogSideEffect, the Mounjaro header
// shape matches the Ramipril header exactly (history + edit only).
const client = makeClient();
seedCompliance(client, ramipril.id);
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const ramiprilHtml = render(
<MedicationCard medication={ramipril} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
client,
);
for (const html of [ramiprilHtml, mounjaroHtml]) {
expect(html).not.toContain('aria-label="More options"');
}
});
it("Mounjaro gains a kebab when onLogSideEffect is supplied (GLP-1-only)", () => {
const client = makeClient();
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const html = render(
<Glp1MedicationCard
medication={mounjaro}
onEdit={() => {}}
onLogSideEffect={() => {}}
/>,
client,
);
expect(html).toContain('aria-label="More options"');
});
it("category label uses the shared category-map lookup on both cards", () => {
const client = makeClient();
seedCompliance(client, ramipril.id);
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const ramiprilHtml = render(
<MedicationCard medication={ramipril} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
client,
);
// Ramipril → BLOOD_PRESSURE → "Blood Pressure".
expect(ramiprilHtml).toContain("Blood Pressure");
// Mounjaro → HORMONE → "Hormones". The card must NOT hard-code
// the treatment-class label into the slot any more.
expect(mounjaroHtml).toContain("Hormones");
expect(mounjaroHtml).not.toContain("GLP-1 injection");
});
it("both cards render the take-now pill when inside the current schedule window", () => {
const client = makeClient();
seedCompliance(client, ramipril.id);
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const ramiprilHtml = render(
<MedicationCard medication={ramipril} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard medication={mounjaro} onEdit={() => {}} />,
client,
);
for (const html of [ramiprilHtml, mounjaroHtml]) {
expect(html).toContain("Take now");
// Coloured-pill contract — the in_window pill class carries
// the success token, not the warning token.
expect(html).toContain("text-success");
}
});
it("primary actions row carries exactly two buttons on both cards", () => {
const client = makeClient();
seedCompliance(client, ramipril.id);
seedCompliance(client, mounjaro.id);
seedGlp1Details(client, mounjaro.id);
const ramiprilHtml = render(
<MedicationCard medication={ramipril} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard
medication={mounjaro}
onEdit={() => {}}
onLogSideEffect={() => {}}
/>,
client,
);
for (const html of [ramiprilHtml, mounjaroHtml]) {
// Taken / Skipped — and no third in-row button. We assert the
// primary-actions buttons via icon class names since those
// surface on both cards.
expect(html).toContain("lucide-check");
expect(html).toContain("lucide-skip-forward");
}
// The Stethoscope glyph is GLP-1-only; SSR doesn't open the
// Radix Portal so even when wired the menu item is hidden from
// the initial markup. The primary row must NOT carry it.
expect(mounjaroHtml).not.toMatch(
/class="[^"]*flex[^"]*gap-2[^"]*"[^>]*>[\s\S]*?lucide-stethoscope/,
);
});
it("purple dose accent surfaces on the upcoming schedule dose on both cards", () => {
// Pin the asymmetry from the v1.4.37 UX audit (item 11): the
// GLP-1 card historically lacked the purple accent. Both cards
// must now stamp the same `text-purple-400` token on the
// schedule dose. We render at a window that's NOT currently
// active so the "next intake" line (which carries the accent)
// surfaces instead of the take-now pill.
const futureWindow = {
windowStart: "01:00",
windowEnd: "02:00",
label: null,
daysOfWeek: null,
};
const ramiprilFuture = {
...ramipril,
schedules: [
{
id: "s-ramipril-future",
...futureWindow,
dose: "5 mg",
},
],
};
const mounjaroFuture: Glp1Medication = {
...mounjaro,
schedules: [
{
id: "s-mounjaro-future",
...futureWindow,
dose: "7.5 mg",
},
],
};
const client = makeClient();
seedCompliance(client, ramiprilFuture.id);
seedCompliance(client, mounjaroFuture.id);
seedGlp1Details(client, mounjaroFuture.id);
const ramiprilHtml = render(
<MedicationCard medication={ramiprilFuture} onEdit={() => {}} />,
client,
);
const mounjaroHtml = render(
<Glp1MedicationCard medication={mounjaroFuture} onEdit={() => {}} />,
client,
);
// Both surfaces carry the purple token on the upcoming dose.
expect(ramiprilHtml).toContain("text-purple-400");
expect(mounjaroHtml).toContain("text-purple-400");
});
});
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useEffect, useReducer, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import {
@@ -8,6 +8,7 @@ import {
Flame,
History,
Loader2,
MoreVertical,
Pencil,
SkipForward,
Stethoscope,
@@ -16,16 +17,29 @@ import {
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MedicationCardHeader } from "@/components/medications/MedicationCardHeader";
import { Progress } from "@/components/ui/progress";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { invalidateKeys, medicationDependentKeys } from "@/lib/query-keys";
import { formatDateTime, formatTime } from "@/lib/format";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
import {
describeInjectionSite,
nextInjectionSite,
type InjectionSiteKey,
} from "@/lib/medications/injection-sites";
import {
reduceCurrentWindowStatus,
toBerlinDate,
} from "@/lib/medications/window-status";
/**
* v1.4.25 W4d — GLP-1 medication card variant.
*
@@ -77,6 +91,7 @@ export interface Glp1Medication {
notificationsEnabled: boolean;
pausedAt: string | null;
lastTakenAt: string | null;
todayEventCount?: number;
schedules: ScheduleLite[];
}
@@ -155,9 +170,10 @@ export function Glp1MedicationCard({
onLogSideEffect,
}: Glp1MedicationCardProps) {
const queryClient = useQueryClient();
const { t } = useTranslations();
const { t, locale } = useTranslations();
const fmt = useFormatters();
const [intakeLoading, setIntakeLoading] = useState<string | null>(null);
const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
const { data: compliance } = useQuery({
queryKey: ["medications", medication.id, "compliance"],
@@ -171,6 +187,20 @@ export function Glp1MedicationCard({
enabled: medication.active,
});
// v1.4.37 W4b — same reminder-thresholds source as the generic
// medication card so the take-now / overdue / very-overdue pill
// tiers identically on both surfaces.
const { data: thresholds } = useQuery({
queryKey: ["settings", "reminder-thresholds"],
queryFn: async () => {
const res = await fetch("/api/settings/reminder-thresholds");
if (!res.ok) return null;
const json = await res.json();
return json.data as { lateMinutes: number; missedMinutes: number };
},
staleTime: 5 * 60 * 1000,
});
// Pull GLP-1-specific extras (dose history + recent injection sites +
// pen inventory). Lives behind a dedicated endpoint so the standard
// medications grid loads in parallel without paying for it.
@@ -185,6 +215,14 @@ export function Glp1MedicationCard({
staleTime: 60 * 1000,
});
// Re-render once a minute so the in-window / overdue pill tracks
// wall-clock progress without a route reload — mirrors the generic
// medication card's tick cadence.
useEffect(() => {
const interval = setInterval(forceUpdate, 60_000);
return () => clearInterval(interval);
}, []);
async function recordIntake(skipped: boolean) {
const key = skipped ? "skip" : "take";
setIntakeLoading(key);
@@ -209,6 +247,28 @@ export function Glp1MedicationCard({
const rate30 = compliance?.compliance30?.rate ?? 0;
const streak = compliance?.compliance7?.streak ?? 0;
// v1.4.37 W4b — symmetric take-now / overdue pill with the generic
// card. Sort schedules by `windowStart` so the most-actionable
// earliest window wins when multiple GLP-1 windows overlap (rare
// today; the parity is what matters).
const sortedSchedules = [...medication.schedules].sort(
(a, b) =>
a.windowStart.localeCompare(b.windowStart) ||
a.windowEnd.localeCompare(b.windowEnd),
);
const nowBerlin = toBerlinDate(now);
const lateMinutes = thresholds?.lateMinutes ?? 120;
const missedMinutes = thresholds?.missedMinutes ?? 240;
const currentWindowStatus = reduceCurrentWindowStatus({
schedules: sortedSchedules,
nowBerlin,
lateMinutes,
missedMinutes,
active: medication.active,
lastTakenAt: medication.lastTakenAt,
todayEventCount: medication.todayEventCount ?? 0,
});
const recentInjections = details?.recentIntakes ?? [];
const lastSite =
recentInjections.find((i) => i.injectionSite)?.injectionSite ?? null;
@@ -280,20 +340,86 @@ export function Glp1MedicationCard({
>
<Pencil className="h-4 w-4" />
</Button>
{/* v1.4.37 W4b — GLP-1 specifics (side-effect quick-log etc.)
live in the header actions overflow so the primary action
row stays the canonical two-button shape (Eingenommen /
Übersprungen) shared with the generic medication card. The
kebab only renders when at least one overflow item is wired
for this medication kind. */}
{onLogSideEffect && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="min-h-11 min-w-11"
aria-label={t("common.moreOptions")}
>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuItem
onClick={() => onLogSideEffect(medication)}
className="whitespace-nowrap"
>
<Stethoscope className="mr-2 h-4 w-4" />
{t("medications.glp1LogSideEffect")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</>
);
const categoryLabel = getMedicationCategoryLabel(medication.category, t);
return (
<Card className={medication.active ? "" : "opacity-60"}>
<MedicationCardHeader
name={medication.name}
dose={medication.dose}
categoryLabel={t("medications.treatmentClassGlp1")}
categoryLabel={categoryLabel}
stateBadges={stateBadges}
actions={headerActions}
/>
<CardContent className="space-y-3.5">
{/* v1.4.37 W4b — take-now / overdue / very-overdue pill,
byte-equivalent with the generic medication card. The
GLP-1 card historically omitted this row, which made
Mounjaro feel different from Ramipril on the medications
grid even though the underlying schedule contract is
the same shape. */}
{currentWindowStatus.status && (
<p className="text-sm">
<span
className={
currentWindowStatus.status === "in_window"
? "text-success font-medium"
: currentWindowStatus.status === "late"
? "text-dracula-yellow font-medium"
: "text-warning font-medium"
}
>
{currentWindowStatus.status === "in_window"
? t("medications.takeNow")
: currentWindowStatus.status === "late"
? t("medications.overdue")
: t("medications.veryOverdue")}
</span>
<span className="text-muted-foreground hidden sm:inline">
{" "}
—{" "}
{formatTimeWindowRange(
currentWindowStatus.schedule!.windowStart,
currentWindowStatus.schedule!.windowEnd,
locale,
)}
</span>
</p>
)}
{/* Injection state — last + next */}
<div className="space-y-1 text-sm">
{medication.lastTakenAt && (
@@ -308,7 +434,21 @@ export function Glp1MedicationCard({
})}
</p>
)}
<p className="text-foreground/85">{nextInjectionLabel()}</p>
<p className="text-foreground/85">
{nextInjectionLabel()}
{/* v1.4.37 W4b — purple dose accent on the upcoming
schedule dose, byte-equivalent with the generic
medication card. Schedule.dose can override the
medication-level dose during titration, so we surface
it here when set. Hidden below sm: to keep the narrow
viewport row tight, matching the generic card. */}
{schedule?.dose && (
<span className="hidden font-medium text-purple-400 sm:inline">
{" "}
— {schedule.dose}
</span>
)}
</p>
</div>
{/* Rotation hint — only when we have a last + recommended site
@@ -379,18 +519,20 @@ export function Glp1MedicationCard({
</div>
)}
{/* Primary actions row — matches the generic card's
min-h-11 tap-target rule. The third button opens the
side-effect log pre-tagged with the GLP-1 drug name. */}
{/* Primary actions row — byte-equivalent with the generic
medication card. v1.4.37 W4b moved the GLP-1-specific
side-effect quick-log out of this row and into the
header-actions overflow (kebab) so Mounjaro and Ramipril
share the canonical two-button primary row. */}
{medication.active && (
<div className="flex flex-wrap gap-2">
<div className="flex gap-2">
<Button
className="min-h-11 flex-1"
onClick={() => recordIntake(false)}
disabled={!!intakeLoading}
>
{intakeLoading === "take" ? (
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
<Loader2 className="mr-1 h-4 w-4 animate-spin motion-reduce:animate-none" />
) : (
<Check className="mr-1 h-4 w-4" />
)}
@@ -403,22 +545,12 @@ export function Glp1MedicationCard({
disabled={!!intakeLoading}
>
{intakeLoading === "skip" ? (
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
<Loader2 className="mr-1 h-4 w-4 animate-spin motion-reduce:animate-none" />
) : (
<SkipForward className="mr-1 h-4 w-4" />
)}
{t("medications.skipped")}
</Button>
{onLogSideEffect && (
<Button
variant="ghost"
className="min-h-11"
onClick={() => onLogSideEffect(medication)}
>
<Stethoscope className="mr-1 h-4 w-4" />
{t("medications.glp1LogSideEffect")}
</Button>
)}
</div>
)}
</CardContent>
@@ -3,18 +3,21 @@
import { useQuery } from "@tanstack/react-query";
import { useState, useMemo } from "react";
import Link from "next/link";
import { Loader2, ArrowUp, ArrowDown, ArrowUpDown, History } from "lucide-react";
import {
Loader2,
ArrowUp,
ArrowDown,
ArrowUpDown,
History,
Check,
SkipForward,
} from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import {
Table,
@@ -40,8 +43,19 @@ import {
* - Paginated 25/page via the existing `?limit=&offset=` query on
* `GET /api/medications/[id]/intake`. The route already supports
* `sortBy=takenAt|scheduledFor|createdAt|source` + `sortDir=asc|desc`.
* - v1.4.37 W3: filters server-side with `?status=completed` so the
* detail-page list shows only rows the user actually actioned
* (taken OR skipped). The ambiguous "missed / never confirmed"
* rows (`takenAt IS NULL AND skipped = false`) stay hidden here
* and remain visible on the calendar / today surfaces. This
* restores the v1 component's effective behaviour and fixes the
* bug where such rows rendered as "Eingenommen" with an empty
* leading column.
* - Sortable by `takenAt` (default) and `scheduledFor`. Click the
* header to toggle the direction; switching column resets to desc.
* - Status chip: green Check + "Eingenommen" for taken rows,
* outline SkipForward + "Übersprungen" for skipped rows. The
* component never labels a row both at once.
* - Source badge surfaces WEB / API / REMINDER / IMPORT using the
* existing `medications.source*` keys.
* - Empty state copy + CTA back to the daily intake page.
@@ -74,6 +88,13 @@ interface IntakeHistoryListV2Props {
type SortKey = "takenAt" | "scheduledFor";
const DEFAULT_PAGE_SIZE = 25;
/**
* v1.4.37 W3 — pinned to "completed" for the detail-page surface so
* planned / missed rows never leak into the table. Lifted to a
* module-level constant so the queryKey stays stable across renders
* and `setQueryData` in tests can pre-seed the same shape.
*/
const STATUS_FILTER = "completed";
export function IntakeHistoryListV2({
medicationId,
@@ -95,7 +116,7 @@ export function IntakeHistoryListV2({
medicationId,
"intake",
"list",
{ sortBy, sortDir, limit: pageSize, offset },
{ sortBy, sortDir, limit: pageSize, offset, status: STATUS_FILTER },
],
queryFn: async () => {
const params = new URLSearchParams({
@@ -103,6 +124,7 @@ export function IntakeHistoryListV2({
sortDir,
limit: String(pageSize),
offset: String(offset),
status: STATUS_FILTER,
});
const res = await fetch(
`/api/medications/${medicationId}/intake?${params.toString()}`,
@@ -206,36 +228,65 @@ export function IntakeHistoryListV2({
{sortIndicator("scheduledFor")}
</button>
</TableHead>
<TableHead>{t("medications.intakeHistoryColStatus")}</TableHead>
<TableHead>{t("medications.intakeHistoryColSource")}</TableHead>
<TableHead>
{t("medications.intakeHistoryColStatus")}
</TableHead>
<TableHead>
{t("medications.intakeHistoryColSource")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{events.map((event) => (
<TableRow key={event.id}>
<TableCell className="text-sm">
{event.takenAt ? formatters.dateTime(event.takenAt) : "—"}
</TableCell>
<TableCell className="text-sm">
{formatters.dateTime(event.scheduledFor)}
</TableCell>
<TableCell>
<Badge
variant={event.skipped ? "outline" : "secondary"}
className="text-xs"
>
{event.skipped
? t("medications.intakeHistoryStatusSkipped")
: t("medications.intakeHistoryStatusTaken")}
</Badge>
</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{sourceLabels[event.source] ?? event.source}
</Badge>
</TableCell>
</TableRow>
))}
{events.map((event) => {
// v1.4.37 W3 — `status=completed` server filter
// guarantees that every row is either a taken or a
// skipped event. We derive the branch from the data
// itself rather than trusting a single `skipped`
// flag so a malformed row (e.g. `skipped:false` with
// `takenAt:null`, the v1.4.36 regression) never
// sneaks past as "Eingenommen".
const isTaken = !event.skipped && !!event.takenAt;
const isSkipped = event.skipped;
return (
<TableRow key={event.id}>
<TableCell className="text-sm">
{event.takenAt
? formatters.dateTime(event.takenAt)
: "—"}
</TableCell>
<TableCell className="text-sm">
{formatters.dateTime(event.scheduledFor)}
</TableCell>
<TableCell>
{isTaken ? (
<Badge
variant="secondary"
className="gap-1 bg-green-500/20 text-xs text-green-400"
>
<Check aria-hidden="true" className="h-3 w-3" />
{t("medications.intakeHistoryStatusTaken")}
</Badge>
) : isSkipped ? (
<Badge
variant="outline"
className="text-muted-foreground gap-1 text-xs"
>
<SkipForward
aria-hidden="true"
className="h-3 w-3"
/>
{t("medications.intakeHistoryStatusSkipped")}
</Badge>
) : null}
</TableCell>
<TableCell>
<Badge variant="outline" className="text-xs">
{sourceLabels[event.source] ?? event.source}
</Badge>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
+16 -152
View File
@@ -10,6 +10,12 @@ import { MedicationCardHeader } from "@/components/medications/MedicationCardHea
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
import { formatTimeWindowRange } from "@/lib/time-window-format";
import { formatDateTime, formatTime } from "@/lib/format";
import { getMedicationCategoryLabel } from "@/lib/medications/category-label";
import {
parseTimeToMinutes,
reduceCurrentWindowStatus,
toBerlinDate,
} from "@/lib/medications/window-status";
import {
Check,
SkipForward,
@@ -71,33 +77,6 @@ interface MedicationCardProps {
onEdit: (med: Medication) => void;
}
function parseTimeToMinutes(value: string): number {
const [h, m] = value.split(":").map(Number);
if (
!Number.isFinite(h) ||
!Number.isFinite(m) ||
h < 0 ||
h > 23 ||
m < 0 ||
m > 59
) {
return 0;
}
return h * 60 + m;
}
function toBerlinDate(date: Date): Date {
// Intentionally en-US: this is not user-facing display — it produces a
// parseable string ("1/2/2026, 3:04:05 PM") that we feed back into Date
// to shift the *value* from UTC to Berlin-local for arithmetic. Display
// formatting goes through useFormatters() elsewhere.
return new Date(
date.toLocaleString("en-US", {
timeZone: "Europe/Berlin",
}),
);
}
function getNextOccurrenceTimestamp(
schedule: Schedule,
nowBerlin: Date,
@@ -139,67 +118,6 @@ function getNextOccurrenceTimestamp(
return null;
}
type MedicationWindowStatus = "in_window" | "late" | "very_late" | null;
function getWindowStatus(
schedule: Schedule,
nowBerlin: Date,
lateMinutes: number,
missedMinutes: number,
): MedicationWindowStatus {
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedNow =
nowMins < startMins && endMins > 24 * 60 ? nowMins + 24 * 60 : nowMins;
// Currently in window
if (adjustedNow >= startMins && adjustedNow <= endMins) return "in_window";
// Past window end: check late thresholds
const minutesPastEnd = adjustedNow - endMins;
if (minutesPastEnd > 0 && minutesPastEnd <= lateMinutes) return "late";
if (minutesPastEnd > lateMinutes && minutesPastEnd <= missedMinutes)
return "very_late";
return null;
}
function isLastIntakeInCurrentWindow(
lastTakenAt: string | null,
schedule: Schedule,
nowBerlin: Date,
): boolean {
if (!lastTakenAt) return false;
const intake = toBerlinDate(new Date(lastTakenAt));
// Must be same calendar day
if (
intake.getFullYear() !== nowBerlin.getFullYear() ||
intake.getMonth() !== nowBerlin.getMonth() ||
intake.getDate() !== nowBerlin.getDate()
) {
return false;
}
const intakeMins = intake.getHours() * 60 + intake.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedIntake =
intakeMins < startMins && endMins > 24 * 60
? intakeMins + 24 * 60
: intakeMins;
return adjustedIntake >= startMins && adjustedIntake <= endMins;
}
export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
const queryClient = useQueryClient();
const { t, locale } = useTranslations();
@@ -255,21 +173,7 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
const rate7 = compliance?.compliance7?.rate ?? 0;
const rate30 = compliance?.compliance30?.rate ?? 0;
const streak = compliance?.compliance7?.streak ?? 0;
const categoryLabels: Record<string, string> = {
BLOOD_PRESSURE: t("medications.categoryBloodPressure"),
VITAMIN: t("medications.categoryVitamin"),
SUPPLEMENT: t("medications.categorySupplement"),
PAIN_RELIEF: t("medications.categoryPainRelief"),
ALLERGY: t("medications.categoryAllergy"),
DIGESTIVE: t("medications.categoryDigestive"),
THYROID: t("medications.categoryThyroid"),
HORMONE: t("medications.categoryHormone"),
SKIN: t("medications.categorySkin"),
SLEEP_AID: t("medications.categorySleepAid"),
OTHER: t("medications.categoryOther"),
};
const categoryLabel =
categoryLabels[medication.category] ?? t("medications.categoryOther");
const categoryLabel = getMedicationCategoryLabel(medication.category, t);
const sortedSchedules = [...medication.schedules].sort(
(a, b) =>
a.windowStart.localeCompare(b.windowStart) ||
@@ -293,55 +197,15 @@ export function MedicationCard({ medication, onEdit }: MedicationCardProps) {
const lateMinutes = thresholds?.lateMinutes ?? 120;
const missedMinutes = thresholds?.missedMinutes ?? 240;
// Count schedules that are past their window (overdue today)
const passedScheduleCount = medication.active
? sortedSchedules.filter((s) => {
const recurrence = parseScheduleRecurrence(s.daysOfWeek);
if (
recurrence.daysOfWeek.length > 0 &&
!recurrence.daysOfWeek.includes(nowBerlin.getDay())
) {
return false;
}
const endMins = parseTimeToMinutes(s.windowEnd);
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
return nowMins > endMins;
}).length
: 0;
const todayEvents = medication.todayEventCount ?? 0;
const hasUncoveredOverdue = todayEvents < passedScheduleCount;
const currentWindowStatus = medication.active
? sortedSchedules.reduce<{
status: MedicationWindowStatus;
schedule: Schedule | null;
}>(
(best, s) => {
const status = getWindowStatus(
s,
nowBerlin,
lateMinutes,
missedMinutes,
);
if (!status) return best;
// Don't show late/very_late if all overdue schedules are covered by events
if (status !== "in_window" && !hasUncoveredOverdue) return best;
// Don't show in_window if last intake is already within this window today
if (
status === "in_window" &&
isLastIntakeInCurrentWindow(medication.lastTakenAt, s, nowBerlin)
)
return best;
const priority = { in_window: 3, late: 2, very_late: 1 };
if (!best.status || priority[status] > priority[best.status]) {
return { status, schedule: s };
}
return best;
},
{ status: null, schedule: null },
)
: { status: null, schedule: null };
const currentWindowStatus = reduceCurrentWindowStatus({
schedules: sortedSchedules,
nowBerlin,
lateMinutes,
missedMinutes,
active: medication.active,
lastTakenAt: medication.lastTakenAt,
todayEventCount: medication.todayEventCount ?? 0,
});
function formatLastTakenAt(value: string): string {
// Intentionally en-CA: gives YYYY-MM-DD which is locale-independent and
@@ -326,7 +326,12 @@ export function GettingStartedChecklist() {
onClick={() => setExpanded((prev) => !prev)}
aria-expanded={expanded}
aria-controls="getting-started-body"
className="hover:text-foreground -m-1 flex min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors"
// v1.4.37 W-CI — lift the toggle to clear the WCAG 2.5.5 mobile
// tap-target floor on Pixel-5 (Marc's iOS-textarea-zoom sweep
// pinned the floor at 44 px; the previous `p-1` padding left
// the toggle at 32 px). `sm:min-h-10` returns to the desktop
// 40 px tier so the dashboard header rhythm is unchanged.
className="hover:text-foreground -m-1 flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-md p-1 text-left transition-colors sm:min-h-10"
>
<ChevronDown
aria-hidden="true"
@@ -353,7 +358,14 @@ export function GettingStartedChecklist() {
<Button
type="button"
variant="ghost"
className="text-muted-foreground hover:text-foreground"
// v1.4.37 W-CI — the shadcn `default` Button is `h-10` (40 px)
// across breakpoints; lift to 44 px on mobile to clear the
// WCAG 2.5.5 floor that the rest of the input primitives
// follow via `h-11 sm:h-10`. The dismiss CTA is one of the
// few primary buttons rendered above the fold on the
// onboarded-user dashboard so the regression was visible to
// the touch-target spec.
className="text-muted-foreground hover:text-foreground min-h-11 sm:min-h-10"
onClick={() => setDismissedAll(true)}
>
{t("gettingStarted.dismissAll")}
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { resolveInitialTimezone } from "../account-section";
/**
* v1.4.37 — silent browser-timezone auto-seed for the account
* profile picker.
*
* The retired "Browser-Zeitzone übernehmen" button used to ask the
* user to opt in; v1.4.37 seeds the form for them on first mount
* whenever the stored value is still the Europe/Berlin default and
* the browser reports a different IANA zone. The helper that drives
* that decision is pure so the contract can be pinned without
* mounting the full AccountSection component tree (which depends on
* react-query, useAuth, next/navigation, etc.).
*/
describe("resolveInitialTimezone — v1.4.37 silent auto-seed", () => {
it("pre-fills the browser zone when the stored value is the Berlin default and the browser is elsewhere", () => {
expect(resolveInitialTimezone("Europe/Berlin", "America/New_York")).toBe(
"America/New_York",
);
});
it("pre-fills the browser zone when the stored value is null and the browser is elsewhere", () => {
expect(resolveInitialTimezone(null, "Asia/Tokyo")).toBe("Asia/Tokyo");
});
it("pre-fills the browser zone when the stored value is an empty string and the browser is elsewhere", () => {
expect(resolveInitialTimezone("", "Europe/London")).toBe("Europe/London");
});
it("keeps Berlin when the browser is also Berlin (no seed needed)", () => {
expect(resolveInitialTimezone("Europe/Berlin", "Europe/Berlin")).toBe(
"Europe/Berlin",
);
});
it("keeps Berlin when the browser detection returned an empty string", () => {
// detectBrowserTimezone falls back to Europe/Berlin on engines
// without Intl.DateTimeFormat, but guard against future shapes
// that hand back an empty string.
expect(resolveInitialTimezone("Europe/Berlin", "")).toBe("Europe/Berlin");
});
it("respects any non-Berlin stored value — explicit user choice wins over browser detection", () => {
expect(
resolveInitialTimezone("America/Los_Angeles", "Europe/Berlin"),
).toBe("America/Los_Angeles");
});
it("respects a non-Berlin stored value even when the browser reports a different non-Berlin zone", () => {
// User stored Pacific, then opened the form from a hotel in
// Tokyo. The stored value still wins; the user can change it
// explicitly via the picker if they want.
expect(resolveInitialTimezone("America/Los_Angeles", "Asia/Tokyo")).toBe(
"America/Los_Angeles",
);
});
});
@@ -0,0 +1,116 @@
/**
* v1.4.37 W7a — Arztbericht hero card contract.
*
* The flagship doctor-report PDF surface was promoted from one of five
* grid cards into a hero card at the top of `/settings/export`. This
* suite pins the SSR contract:
*
* 1. The hero renders with the expected `data-testid` slot.
* 2. The value statement is present (Marc-Voice copy, no AI mention).
* 3. The CTA button is present, clears the 44 px touch floor, and
* carries an `aria-describedby` link to the value statement.
* 4. The CTA is wired to a click handler (the prop `data-testid`
* surface is the e2e contract).
* 5. Both DE and EN locales resolve their copy without leaking the
* raw i18n key.
*
* Project convention is SSR-only tests (no `@testing-library/react`).
* The actual click-flow + PDF generation is exercised by the e2e
* Playwright path and the dialog's own integration tests.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/settings/export",
}));
import { I18nProvider } from "@/lib/i18n/context";
import { ArztberichtHeroCard } from "../arztbericht-hero-card";
function renderSSR(node: React.ReactElement, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
describe("<ArztberichtHeroCard> — SSR contract", () => {
it("renders the hero slot with eyebrow + title", () => {
const html = renderSSR(<ArztberichtHeroCard />);
expect(html).toContain('data-testid="export-hero-doctor-report"');
// Title falls back to the existing doctorReport.title key — keeps
// a single source-of-truth for the brand name.
expect(html).toContain("Doctor Report");
// Eyebrow surfaces the use-case framing.
expect(html).toContain("Doctor visit");
});
it("renders the value statement as a Marc-Voice one-liner", () => {
const html = renderSSR(<ArztberichtHeroCard />);
expect(html).toContain('data-testid="export-hero-doctor-report-value"');
expect(html).toContain("printable PDF report");
// No AI/Coach name-drop in the user-facing artefact (Marc-Voice).
expect(html.toLowerCase()).not.toContain("coach");
expect(html.toLowerCase()).not.toContain(" ai ");
});
it("renders the CTA with min-h-11 touch target + aria-describedby", () => {
const html = renderSSR(<ArztberichtHeroCard />);
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
// 44 px touch floor (WCAG 2.5.5) — the hero CTA pins `h-11` on
// mobile and falls back to the compact `sm:h-10` on pointer
// devices.
expect(html).toContain("h-11");
// Aria-describedby links the CTA to the value statement so screen
// readers announce the framing alongside the action label.
expect(html).toMatch(/aria-describedby="[^"]+"/);
});
it("does NOT leak raw i18n keys", () => {
const html = renderSSR(<ArztberichtHeroCard />);
expect(html).not.toContain("settings.sections.export.hero");
expect(html).not.toContain("settings.sections.export.cards.doctorReport");
});
it("renders German copy when the DE locale is active", () => {
const html = renderSSR(<ArztberichtHeroCard />, "de");
expect(html).toContain("Arztbericht");
expect(html).toContain("Arzttermin");
// Umlauts encoded as their literal UTF-8 character (not their HTML
// entity), matching the rest of the codebase.
expect(html).toContain("druckbarer PDF-Bericht");
expect(html).not.toContain("settings.sections.export.hero");
});
it("uses the hero-gradient + glow-purple visual treatment", () => {
const html = renderSSR(<ArztberichtHeroCard />);
// Same surface utilities as the Insights hero strip — keeps the
// app's hero language consistent.
expect(html).toContain("hero-gradient");
expect(html).toContain("glow-purple");
});
it("does not paint dialog markup in the closed-state SSR pass", () => {
// Radix Dialog renders its portal content lazily, so the closed
// SSR pass never carries `role="dialog"`. The CTA testid IS
// present so the e2e suite can drive the open from there. Pinning
// this contract guards against an accidental `defaultOpen={true}`
// regression that would briefly paint the dialog above the page on
// every cold mount.
const html = renderSSR(<ArztberichtHeroCard />);
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
expect(html).not.toContain('role="dialog"');
});
});
describe("<ArztberichtHeroCard> — heading hierarchy", () => {
it("uses an <h2> so it nests cleanly below the page-level <h1>", () => {
const html = renderSSR(<ArztberichtHeroCard />);
// Page-level h1 (settings-section-export-title) wraps the section;
// hero owns the h2 slot. The export-section test pins the outer
// h1; this assertion pins the hero's contribution.
expect(html).toMatch(/<h2[^>]*id="export-hero-doctor-report-title"/);
});
});
@@ -1,15 +1,24 @@
/**
* v1.4.16 Phase B7 — Settings → Export section.
*
* The acceptance criterion for the consolidated Export menu is "five cards":
* 1. Doctor Report (PDF)
* The acceptance criterion for the consolidated Export menu was "five
* cards":
* 1. Doctor Report (PDF) — promoted to the hero in v1.4.37 W7a;
* now lives at the top of the page, NOT in the grid
* 2. Measurements CSV
* 3. Medications CSV (with optional intake-history toggle)
* 4. Mood CSV
* 5. Full JSON Backup
*
* Each card must surface a title, a 1-line description, and a download/generate
* button. SSR-only smoke test — interaction is exercised by the e2e suite.
* Each card must surface a title, a 1-line description, and a
* download/generate button. SSR-only smoke test — interaction is
* exercised by the e2e suite.
*
* v1.4.37 W7a — the doctor-report card was extracted into
* `<ArztberichtHeroCard>` and rendered above the grid. The remaining
* four cards stay under a "Weitere Export-Optionen" / "Other export
* options" sub-heading. The hero owns its own contract test; this
* suite pins the page-level shape.
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@@ -51,12 +60,27 @@ describe("<ExportSection> — SSR smoke", () => {
expect(html).not.toContain("settings.sections.export.");
});
it("renders exactly five export cards", () => {
it("renders the Arztbericht hero card at the top of the page", () => {
const html = render(<ExportSection />);
// The hero owns its own contract suite; here we pin that the page
// mounts it, and that the legacy in-grid doctor-report card is
// gone (v1.4.37 W7a moved it into the hero).
expect(html).toContain('data-testid="export-hero-doctor-report"');
expect(html).not.toContain('data-testid="export-card-doctor-report"');
});
it("renders the 'Other export options' sub-heading above the grid", () => {
const html = render(<ExportSection />);
expect(html).toContain("Other export options");
expect(html).toContain('id="settings-section-export-other-title"');
});
it("renders exactly four secondary export cards in the grid", () => {
const html = render(<ExportSection />);
// Each card carries a stable data-testid so the e2e suite can target
// them without relying on the localised label.
// them without relying on the localised label. The doctor-report
// card is no longer in this grid — it's the hero above.
const ids = [
"export-card-doctor-report",
"export-card-measurements-csv",
"export-card-medications-csv",
"export-card-mood-csv",
@@ -75,17 +99,20 @@ describe("<ExportSection> — SSR smoke", () => {
expect(html).toContain('data-testid="export-medications-include-intake"');
});
it("renders a download/generate button per card", () => {
it("renders a download/generate button per secondary card + the hero CTA", () => {
const html = render(<ExportSection />);
// Buttons are typed `button` and decorated with a stable testid so a
// single regex finds all five — the labels themselves are i18n'd.
// Four secondary cards each carry an `export-action-*` testid; the
// hero owns the `export-hero-doctor-report-action` slot.
const buttonMatches = html.match(/data-testid="export-action-/g);
expect(buttonMatches?.length ?? 0).toBe(5);
expect(buttonMatches?.length ?? 0).toBe(4);
expect(html).toContain('data-testid="export-hero-doctor-report-action"');
});
it("German locale renders the DE heading", () => {
it("German locale renders the DE heading + hero copy", () => {
const html = render(<ExportSection />, "de");
expect(html).toContain("Export");
expect(html).toContain("Arztbericht");
expect(html).toContain("Weitere Export-Optionen");
expect(html).not.toContain("settings.sections.export.");
});
});
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { TimezonePicker } from "../timezone-picker";
/**
* v1.4.37 — the "Browser-Zeitzone übernehmen" / "Use browser timezone"
* affordance retired. Auto-seeding now happens silently inside the
* account-section bootstrap (`detectBrowserTimezone()` on first mount
* when the stored value is still the Europe/Berlin default), so the
* picker chrome is just `<Label>` + `<NativeSelect>` + the hint line.
*
* These SSR smoke tests pin that contract end-to-end so a regression
* that re-adds either the button copy or the icon would fail the
* suite before reaching production.
*/
function render(node: React.ReactNode, locale: "en" | "de" = "en") {
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>{node}</I18nProvider>,
);
}
describe("<TimezonePicker> v1.4.37 affordance removal", () => {
it("renders the label, select, and hint without the legacy button (en)", () => {
const html = render(
<TimezonePicker value="Europe/Berlin" onChange={() => {}} />,
);
expect(html).toContain("Timezone");
expect(html).toContain("Used for chart axis labels");
expect(html).not.toContain("Use browser timezone");
});
it("renders the label, select, and hint without the legacy button (de)", () => {
const html = render(
<TimezonePicker value="Europe/Berlin" onChange={() => {}} />,
"de",
);
expect(html).toContain("Zeitzone");
expect(html).not.toContain("Browser-Zeitzone übernehmen");
});
it("keeps the stored value selectable even when not in the IANA list", () => {
// A made-up zone simulates an engine where the runtime IANA list
// has rolled but the user's stored value is still valid. The
// picker keeps the value as an extra <option> so the form does
// not silently fall back to the first list entry.
const html = render(
<TimezonePicker value="Antarctica/Casey" onChange={() => {}} />,
);
expect(html).toContain("Antarctica/Casey");
});
});
+42 -1
View File
@@ -45,6 +45,7 @@ import { locales, localeLabels, type Locale } from "@/lib/i18n/config";
import { useTranslations } from "@/lib/i18n/context";
import { describePasskeyError } from "@/lib/passkey-errors";
import { TimezonePicker } from "@/components/settings/timezone-picker";
import { detectBrowserTimezone, DEFAULT_TIMEZONE } from "@/lib/tz/format";
interface PasskeyInfo {
id: string;
@@ -59,6 +60,46 @@ interface PasskeyInfo {
// contract now. Existing `<select className={NATIVE_SELECT_CLASS}>`
// call sites in this file swapped to `<NativeSelect>` below.
/**
* v1.4.37 — silent browser-zone auto-seed for the timezone picker.
*
* Until v1.4.37 the picker carried a "Browser-Zeitzone übernehmen" /
* "Use browser timezone" button so the user could overwrite the
* Europe/Berlin seed with their detected zone on demand. The button
* was visually noisy next to the picker on mobile and almost every
* user wants the browser zone anyway, so the affordance retired and
* the bootstrap effect seeds the form for them.
*
* Rules:
*
* - If the stored value is anything other than the Europe/Berlin
* default, respect it. The user explicitly picked it.
* - If the stored value is the Europe/Berlin default but the
* browser actually IS in Berlin, leave it alone — the picker
* stays on Berlin and the next save is a no-op.
* - If the stored value is the default AND the browser reports a
* non-Berlin zone, pre-fill the picker with the detected zone.
* The form's existing submit handler persists the change on the
* next save; no toast, no banner, no opt-in.
*
* The bootstrap deliberately runs inline during render (the strict
* `react-hooks/set-state-in-effect` rule outlaws setState in an
* effect for this hydration shape), so this helper has to stay
* pure — no DOM access, no `useState`. The detected browser zone is
* passed in by the caller via `detectBrowserTimezone()`.
*/
export function resolveInitialTimezone(
storedTimezone: string | null | undefined,
detectedBrowserTimezone: string,
): string {
const stored = storedTimezone || DEFAULT_TIMEZONE;
const shouldAutoSeed =
stored === DEFAULT_TIMEZONE &&
detectedBrowserTimezone.length > 0 &&
detectedBrowserTimezone !== DEFAULT_TIMEZONE;
return shouldAutoSeed ? detectedBrowserTimezone : stored;
}
export function AccountSection() {
const { t, locale, setLocale } = useTranslations();
const { user, isLoading, isAuthenticated, refetch } = useAuth();
@@ -130,7 +171,7 @@ export function AccountSection() {
: "",
);
setGender(user.gender ?? "");
setTimezone(user.timezone || "Europe/Berlin");
setTimezone(resolveInitialTimezone(user.timezone, detectBrowserTimezone()));
}
async function handleSaveProfile(e: React.FormEvent) {
@@ -0,0 +1,196 @@
"use client";
/**
* v1.4.37 W7a — Settings → Export Arztbericht hero card.
*
* The doctor-report PDF is HealthLog's flagship export — the artefact a
* user actually carries into a doctor's appointment. The v1.4.16 phase
* B7 layout treated it as one of five equal cards in the grid, which
* undersold the feature. Marc 2026-05-17:
*
* "Können wir unter Einstellungen > Export den Arztbericht als Hero
* Card machen?"
*
* This component lifts the doctor-report card out of the grid and
* paints it with the same `hero-gradient + glow-purple` visual treatment
* as the Insights hero strip (`src/components/insights/hero-strip.tsx`),
* so the surface feels consistent with the rest of the app. The CTA
* routes through the existing `<DoctorReportDialog>` + `/api/doctor-
* report` flow — only the framing changed.
*
* Layout:
*
* ┌─ hero ────────────────────────────────────────────┐
* │ [icon] eyebrow │
* │ H2 title (settings.sections.export.cards. │
* │ doctorReport.title) │
* │ one-line value statement │
* │ ───── │
* │ [Configure & generate] PDF · printable │
* └───────────────────────────────────────────────────┘
*
* Mobile-first: at < sm the CTA stacks below the value statement (the
* action row is `flex-wrap`), the hero pads down to `px-4 py-5`, and
* the title clamps to a single line.
*
* a11y:
* - The CTA button clears the 44 px touch floor (`min-h-11`).
* - `focus-visible:ring` ships via the default `<Button>` variant.
* - The CTA is `aria-describedby={valueStatementId}` so a screen
* reader announces the value statement alongside the action.
* - The hero's `<h2>` slots beneath the page-level `<h1>` so the
* outline reads h1 (Export) → h2 (Arztbericht hero) → h2
* (Weitere Export-Optionen) → h2 (each remaining card).
*/
import { useEffect, useId, useState } from "react";
import { Loader2, Stethoscope } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DoctorReportDialog,
type DoctorReportSubmitPayload,
} from "@/components/doctor-report/doctor-report-dialog";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
export function ArztberichtHeroCard() {
const { t, locale } = useTranslations();
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [defaultPracticeName, setDefaultPracticeName] = useState<string | null>(
null,
);
const [error, setError] = useState<string | null>(null);
const valueStatementId = useId();
// Pre-fill the practice name from the user profile so the dialog opens
// ready-to-submit. Best-effort: if the request fails, the dialog still
// works without a pre-fill — mirrors the legacy `<DoctorReportCard>`.
useEffect(() => {
let cancelled = false;
fetch("/api/auth/me", { credentials: "include" })
.then((res) => (res.ok ? res.json() : null))
.then((json) => {
if (cancelled || !json) return;
const name = json?.data?.lastReportPracticeName;
if (typeof name === "string") setDefaultPracticeName(name);
})
.catch(() => {
// ignore — pre-fill is a UX nicety
});
return () => {
cancelled = true;
};
}, []);
async function handleSubmit(payload: DoctorReportSubmitPayload) {
setBusy(true);
setError(null);
try {
const res = await fetch("/api/doctor-report", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
startDate: payload.startDate,
endDate: payload.endDate,
practiceName: payload.practiceName,
sections: payload.sections,
}),
});
if (!res.ok) {
setError(`${res.status}`);
return;
}
const json = await res.json();
const { generateDoctorReportPDF } =
await import("@/lib/doctor-report-pdf");
const doc = generateDoctorReportPDF(json.data, { t, locale });
const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report";
doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`);
if (payload.practiceName) setDefaultPracticeName(payload.practiceName);
setOpen(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
return (
<section
data-testid="export-hero-doctor-report"
aria-labelledby="export-hero-doctor-report-title"
className={cn(
"hero-gradient glow-purple animate-insight-in",
// `isolate` traps the purple glow inside the hero so the
// shadow doesn't leak through the cards below — same trick
// the Insights `<HeroStrip>` uses.
"relative isolate overflow-hidden rounded-xl px-4 py-5 sm:px-6 sm:py-6",
)}
>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2">
<Stethoscope
className="text-dracula-purple h-5 w-5 shrink-0"
aria-hidden="true"
/>
<span className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
{t("settings.sections.export.hero.eyebrow")}
</span>
</div>
<h2
id="export-hero-doctor-report-title"
className="text-2xl leading-tight font-semibold tracking-tight sm:text-[28px]"
>
{t("settings.sections.export.cards.doctorReport.title")}
</h2>
<p
id={valueStatementId}
data-testid="export-hero-doctor-report-value"
className="text-muted-foreground max-w-2xl text-sm leading-relaxed"
>
{t("settings.sections.export.hero.valueStatement")}
</p>
</div>
<div className="flex flex-wrap items-center gap-3 border-t border-border/50 pt-4">
<Button
data-testid="export-hero-doctor-report-action"
variant="default"
// `min-h-11` (44 px) is the WCAG 2.5.5 touch-target floor;
// we override the default `<Button>` height on mobile and
// fall back to the compact `sm:h-10` on pointer devices.
className="h-11 px-5 text-sm font-medium sm:h-10"
onClick={() => setOpen(true)}
disabled={busy}
aria-describedby={valueStatementId}
>
{busy && (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
)}
{t("settings.sections.export.hero.cta")}
</Button>
<span className="text-muted-foreground text-xs">
{t("settings.sections.export.hero.formatHint")}
</span>
</div>
{error && (
<p role="alert" className="text-destructive text-xs">
{error}
</p>
)}
</div>
<DoctorReportDialog
open={open}
onOpenChange={setOpen}
defaultPracticeName={defaultPracticeName}
onSubmit={handleSubmit}
/>
</section>
);
}
+38 -120
View File
@@ -9,16 +9,23 @@
* per export type, each with its own filter inputs and a clear
* "Download" / "Generate" button.
*
* 1. Doctor Report (PDF) — date range + practice name dialog
* 1. Doctor Report (PDF) — hero card at the top of the page
* (v1.4.37 W7a, see
* `<ArztberichtHeroCard>`)
* 2. Measurements CSV — optional `since`/`until`
* 3. Medications CSV — optional intake-history toggle
* 4. Mood CSV — optional `since`/`until`
* 5. Full JSON Backup — single-file user-scoped dump
*
* v1.4.37 W7a — the doctor-report card was promoted to the page hero so
* the flagship "PDF for the doctor" flow no longer competes for visual
* weight with the secondary CSV/JSON exports. The remaining four cards
* live under a "Weitere Export-Optionen" sub-heading.
*
* Mobile-first: cards stack on `<md`, two-column grid on `>=md`.
*/
import { useEffect, useState } from "react";
import { useState } from "react";
import {
Download,
FileJson,
@@ -26,7 +33,6 @@ import {
FileText,
Loader2,
Pill,
Stethoscope,
Waves,
} from "lucide-react";
@@ -34,13 +40,10 @@ import { Button } from "@/components/ui/button";
import { DateInput } from "@/components/ui/date-input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import {
DoctorReportDialog,
type DoctorReportSubmitPayload,
} from "@/components/doctor-report/doctor-report-dialog";
import { ArztberichtHeroCard } from "@/components/settings/arztbericht-hero-card";
import { useTranslations } from "@/lib/i18n/context";
type ExportFormat = "PDF" | "CSV" | "JSON";
type ExportFormat = "CSV" | "JSON";
/**
* Trigger a browser download for a given URL by spinning up an anchor
@@ -82,14 +85,33 @@ export function ExportSection() {
</p>
</header>
{/* Mobile: single column. Desktop (md+): 2-column grid. */}
<div className="grid gap-4 md:grid-cols-2">
<DoctorReportCard />
<MeasurementsCsvCard />
<MedicationsCsvCard />
<MoodCsvCard />
<FullBackupCard />
</div>
{/* v1.4.37 W7a — Arztbericht hero. The doctor-report PDF is the
flagship "data out" path; the previous grid layout buried it
alongside the four CSV/JSON exports. The hero now sits at the
top of the page; the same generation flow runs underneath. */}
<ArztberichtHeroCard />
{/* v1.4.37 W7a — secondary export options. The doctor-report
card moved into the hero above, so this group renders the
four remaining destinations under a dedicated sub-heading.
Mobile: single column. Desktop (md+): 2-column grid. */}
<section
aria-labelledby="settings-section-export-other-title"
className="space-y-3"
>
<h2
id="settings-section-export-other-title"
className="text-base font-semibold tracking-tight"
>
{t("settings.sections.export.otherOptionsHeading")}
</h2>
<div className="grid gap-4 md:grid-cols-2">
<MeasurementsCsvCard />
<MedicationsCsvCard />
<MoodCsvCard />
<FullBackupCard />
</div>
</section>
</section>
);
}
@@ -140,110 +162,6 @@ function ExportCardShell({
);
}
// ─────────────────────────── Doctor Report ───────────────────────────
function DoctorReportCard() {
const { t, locale } = useTranslations();
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [defaultPracticeName, setDefaultPracticeName] = useState<string | null>(
null,
);
const [error, setError] = useState<string | null>(null);
// Pre-fill the practice name from the user profile so the dialog opens
// ready-to-submit. Best-effort: if the request fails, the dialog still
// works without a pre-fill.
useEffect(() => {
let cancelled = false;
fetch("/api/auth/me", { credentials: "include" })
.then((res) => (res.ok ? res.json() : null))
.then((json) => {
if (cancelled || !json) return;
const name = json?.data?.lastReportPracticeName;
if (typeof name === "string") setDefaultPracticeName(name);
})
.catch(() => {
// ignore — pre-fill is a UX nicety
});
return () => {
cancelled = true;
};
}, []);
async function handleSubmit(payload: DoctorReportSubmitPayload) {
setBusy(true);
setError(null);
try {
const res = await fetch("/api/doctor-report", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
startDate: payload.startDate,
endDate: payload.endDate,
practiceName: payload.practiceName,
// v1.4.25 W6c — per-section toggles. The aggregator drops
// disabled sections (mood is filtered server-side so the
// data never leaves the DB row).
sections: payload.sections,
}),
});
if (!res.ok) {
setError(`${res.status}`);
return;
}
const json = await res.json();
const { generateDoctorReportPDF } =
await import("@/lib/doctor-report-pdf");
const doc = generateDoctorReportPDF(json.data, { t, locale });
const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report";
doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`);
if (payload.practiceName) setDefaultPracticeName(payload.practiceName);
setOpen(false);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setBusy(false);
}
}
return (
<ExportCardShell
testId="export-card-doctor-report"
icon={Stethoscope}
title={t("settings.sections.export.cards.doctorReport.title")}
description={t("settings.sections.export.cards.doctorReport.description")}
format="PDF"
outerClassName="md:col-span-2"
footer={
<Button
data-testid="export-action-doctor-report"
variant="default"
size="sm"
onClick={() => setOpen(true)}
disabled={busy}
>
{busy && <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />}
{t("settings.sections.export.cards.doctorReport.action")}
</Button>
}
>
{error && (
<p role="alert" className="text-destructive text-xs">
{error}
</p>
)}
<DoctorReportDialog
open={open}
onOpenChange={setOpen}
defaultPracticeName={defaultPracticeName}
onSubmit={handleSubmit}
/>
</ExportCardShell>
);
}
// ─────────────────────────── CSV cards ───────────────────────────
interface DateRangeFieldsProps {
+30 -71
View File
@@ -3,29 +3,30 @@
/**
* Per-user timezone picker (v1.4.25 W7).
*
* Renders a native `<select>` over `Intl.supportedValuesOf('timeZone')`
* plus a "use my browser zone" button. The control is uncontrolled
* w.r.t. its parent — the parent passes in `value` + `onChange`, but
* the parent owns the network round-trip so this component stays
* synchronous + presentational. The save POSTs
* Renders a native `<select>` over `Intl.supportedValuesOf('timeZone')`.
* The control is uncontrolled w.r.t. its parent — the parent passes in
* `value` + `onChange`, but the parent owns the network round-trip so
* this component stays synchronous + presentational. The save POSTs
* `PUT /api/auth/me/timezone` in the parent form's submit handler.
*
* v1.4.37 — the "Browser-Zeitzone übernehmen" button retired. The
* account-section bootstrap effect now seeds the form silently with
* `detectBrowserTimezone()` on first mount when the stored value is
* still the Europe/Berlin default, so the affordance is no longer
* needed and the picker reads cleaner alongside the surrounding form
* rows.
*
* Fallback: on older engines without `Intl.supportedValuesOf` we
* render a free-text input. Every modern browser back to mid-2022
* (Chrome 99 / Safari 15.4 / Firefox 99) ships the API; the fallback
* is defensive only.
*/
import { useMemo, useState } from "react";
import { Compass } from "lucide-react";
import { useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import {
detectBrowserTimezone,
listSupportedTimezones,
} from "@/lib/tz/format";
import { listSupportedTimezones } from "@/lib/tz/format";
import { useTranslations } from "@/lib/i18n/context";
// v1.4.27 MB7 / CF-52 — the in-file `NATIVE_SELECT_CLASS` constant
@@ -54,11 +55,6 @@ export function TimezonePicker({
// `listSupportedTimezones()` is engine-side; memoise so the list
// isn't reconstructed on every render.
const zones = useMemo(() => listSupportedTimezones(), []);
const [detected] = useState(() => detectBrowserTimezone());
const handleUseBrowserTz = () => {
if (detected) onChange(detected);
};
const labelHint = hint ?? t("settings.timezoneHint");
@@ -75,20 +71,6 @@ export function TimezonePicker({
autoComplete="off"
/>
<p className="text-muted-foreground text-xs">{labelHint}</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={handleUseBrowserTz}
aria-label={
detected
? t("settings.timezoneDetectAria", { tz: detected })
: undefined
}
>
<Compass className="mr-2 h-4 w-4" />
{t("settings.timezoneDetect")}
</Button>
</div>
);
}
@@ -96,46 +78,23 @@ export function TimezonePicker({
return (
<div className="space-y-2">
<Label htmlFor={id}>{t("settings.timezone")}</Label>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center">
<NativeSelect
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
className="sm:max-w-sm"
>
{/* Preserve the stored value even if the runtime's IANA
list changed across engines or tzdata rolls. */}
{!zones.includes(value) && value.length > 0 && (
<option value={value}>{value}</option>
)}
{zones.map((zone) => (
<option key={zone} value={zone}>
{zone}
</option>
))}
</NativeSelect>
{/* v1.4.33 — visible label is "use browser zone"; the actual
IANA zone is read out via aria-label so screen-reader users
still hear which zone the click will apply. Previously the
label inlined `(Europe/Berlin)`, which on a 393 CSS px
viewport wrapped the button to two lines and broke height
parity with the adjacent select. */}
<Button
type="button"
variant="outline"
size="sm"
onClick={handleUseBrowserTz}
className="sm:w-auto"
aria-label={
detected
? t("settings.timezoneDetectAria", { tz: detected })
: undefined
}
>
<Compass className="mr-2 h-4 w-4" />
{t("settings.timezoneDetect")}
</Button>
</div>
<NativeSelect
id={id}
value={value}
onChange={(e) => onChange(e.target.value)}
className="sm:max-w-sm"
>
{/* Preserve the stored value even if the runtime's IANA
list changed across engines or tzdata rolls. */}
{!zones.includes(value) && value.length > 0 && (
<option value={value}>{value}</option>
)}
{zones.map((zone) => (
<option key={zone} value={zone}>
{zone}
</option>
))}
</NativeSelect>
<p className="text-muted-foreground text-xs">{labelHint}</p>
</div>
);
@@ -3,6 +3,24 @@ import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import { TargetCard, type TargetCardData } from "../target-card";
import { DEFAULT_ASSISTANT_FLAGS } from "@/hooks/use-feature-flags";
// v1.4.37 W4a item 9 — when the operator disables the Coach feature
// flag globally, the per-card CTA must disappear. The hook reads from
// QueryClientContext but falls back to the all-on default in SSR;
// the flag-off path needs an explicit mock so the test can drive the
// negative case without a QueryClientProvider.
vi.mock("@/hooks/use-feature-flags", async () => {
const actual = await vi.importActual<
typeof import("@/hooks/use-feature-flags")
>("@/hooks/use-feature-flags");
return {
...actual,
useFeatureFlags: vi.fn(() => actual.DEFAULT_ASSISTANT_FLAGS),
};
});
const { useFeatureFlags } = await import("@/hooks/use-feature-flags");
/**
* v1.4.25 W3e — `<TargetCard>` composition. Three load-bearing cases:
@@ -100,6 +118,35 @@ describe("<TargetCard>", () => {
expect(html).not.toContain('data-slot="target-coach-cta"');
});
// v1.4.37 W4a item 9 — operator-level feature flag.
it("suppresses the Coach CTA when the global Coach flag is OFF", () => {
// Swap the mock for this case only — flag-off should hide the
// CTA regardless of the user-level aiEnabled state. Restore the
// all-on default so the rest of the suite doesn't see a leaked
// mock state.
vi.mocked(useFeatureFlags).mockReturnValueOnce({
...DEFAULT_ASSISTANT_FLAGS,
coach: false,
});
const html = render({
target: fullDataTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).not.toContain('data-slot="target-coach-cta"');
});
it("renders the Coach CTA when both aiEnabled AND the global Coach flag are ON", () => {
// Positive control: the default-mock returns the all-on flag set,
// so the CTA should mount when aiEnabled is also true.
const html = render({
target: fullDataTarget,
aiEnabled: true,
onAskCoach: vi.fn(),
});
expect(html).toContain('data-slot="target-coach-cta"');
});
it("renders MOOD_STABILITY headline as a verbal label, not the σ value", () => {
const moodStability: TargetCardData = {
...fullDataTarget,
+17 -3
View File
@@ -28,6 +28,7 @@ import {
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { useTranslations } from "@/lib/i18n/context";
import { useFeatureFlags } from "@/hooks/use-feature-flags";
import { moodStabilityLabel } from "@/lib/targets/mood-stability-label";
import { ConsistencyStrip } from "./consistency-strip";
import { RangeBar } from "./range-bar";
@@ -343,6 +344,13 @@ export function TargetCard({
sourceLink,
}: TargetCardProps) {
const { t, locale } = useTranslations();
// v1.4.37 W4a item 9 — when the operator disables the Coach
// feature flag globally, every per-card "Ask the coach" CTA must
// disappear (not greyed-out, not a placeholder). The card's
// existing `aiEnabled` gate guards on the user-level provider
// chain; this flag guards on the operator-level feature switch.
// Both must be ON for the CTA to mount.
const flags = useFeatureFlags();
// v1.4.25 W3f — per-card edit affordance. Cog top-right of every
// card opens the edit dialog; the dialog handles the read-only path
@@ -413,9 +421,15 @@ export function TargetCard({
data-slot="target-card"
data-target-type={target.type}
data-status={statusGroup}
className="flex h-full flex-col"
// v1.4.37 W4a item 3 — override the Card primitive's default
// `gap-4 md:gap-6` to `gap-3 md:gap-4`. The default gap stacked
// on top of the CardHeader's `pb-3` rendered a ~36 px dead
// space between "Blutdruck optimal" and the headline number;
// the tighter rhythm pulls the value back under the label so
// the card reads as one unit instead of two separated blocks.
className="flex h-full flex-col gap-3 md:gap-4"
>
<CardHeader className="gap-2 pb-3 sm:gap-3">
<CardHeader className="gap-2 pb-0 sm:gap-3">
{/* Row 1: icon + label (left) ⋯ status pill + edit-cog (right
on sm+, stacked on mobile). Stacking on mobile keeps the
headline number visible at sub-380px viewports where an
@@ -662,7 +676,7 @@ export function TargetCard({
source link right. `mt-auto` pins to card bottom so grid
cells align. */}
<div className="mt-auto flex flex-row items-center justify-between gap-3 pt-1">
{aiEnabled && (
{aiEnabled && flags.coach && (
<TargetCoachButton
prefill={coachPrefill}
sources={coachSources}
+7 -1
View File
@@ -74,7 +74,13 @@ function DropdownMenuItem({
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex min-h-11 cursor-default items-center gap-2 rounded-sm px-2 py-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
// v1.4.37 W4a item 2 — `whitespace-nowrap` keeps every
// dropdown row on a single line (the sidebar 3-dot menu's
// "Benachrichtigungs-Center" otherwise wrapped at the
// hyphen on sub-pixel rounding inside the legacy w-56
// container). Applies app-wide so the top-bar w-48 menus
// get the same protection.
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex min-h-11 cursor-default items-center gap-2 rounded-sm px-2 py-2 text-sm whitespace-nowrap outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
+9 -1
View File
@@ -41,7 +41,15 @@ function SelectTrigger({
// clear WCAG 2.5.5 and shrinks to 40 px on sm+ to match the
// desktop input rhythm. `size=sm` (filter chips) intentionally
// keeps the 32 px footprint.
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-11 data-[size=default]:sm:h-10 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
// v1.4.37 W4a item 4 — split the trigger's horizontal padding
// (`pl-3 pr-2.5`) and push the chevron icon 4 px further right
// via `[&_svg:last-child]:mr-1` so the trailing glyph parks at
// the same visual gutter as the browser-native date-input
// calendar icon (~16-20 px on Chromium). The old uniform
// `px-3` parked the chevron 12 px from the edge, which read
// visibly tighter than the date-picker glyph when both
// controls shared a form row.
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent pl-3 pr-2.5 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-11 data-[size=default]:sm:h-10 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:last-child]:mr-1",
className,
)}
{...props}
+84 -3
View File
@@ -5,16 +5,20 @@ import {
_resetTrustViolationWarningForTests,
} from "../api-response";
const ORIGINAL_ENV = process.env.TRUST_PROXY_HOPS;
const ORIGINAL_HOPS = process.env.TRUST_PROXY_HOPS;
const ORIGINAL_CF_FLAG = process.env.TRUST_CF_CONNECTING_IP;
beforeEach(() => {
delete process.env.TRUST_PROXY_HOPS;
delete process.env.TRUST_CF_CONNECTING_IP;
_resetTrustViolationWarningForTests();
});
afterEach(() => {
if (ORIGINAL_ENV === undefined) delete process.env.TRUST_PROXY_HOPS;
else process.env.TRUST_PROXY_HOPS = ORIGINAL_ENV;
if (ORIGINAL_HOPS === undefined) delete process.env.TRUST_PROXY_HOPS;
else process.env.TRUST_PROXY_HOPS = ORIGINAL_HOPS;
if (ORIGINAL_CF_FLAG === undefined) delete process.env.TRUST_CF_CONNECTING_IP;
else process.env.TRUST_CF_CONNECTING_IP = ORIGINAL_CF_FLAG;
});
function makeRequest(headers: Record<string, string>): Request {
@@ -139,6 +143,83 @@ describe("getClientIp trust-violation warning (F-6, 2026-05-16)", () => {
});
});
/**
* v1.4.37 — Cloudflare's `cf-connecting-ip` carries the visitor IP
* for every request that lands on its edge. The Coolify-fronted
* HealthLog stack sits behind Cloudflare; without consulting this
* header, the admin sign-in geo lookup had no signal to resolve from
* because XFF stops at the Caddy loopback. The header is honoured
* only under `TRUST_CF_CONNECTING_IP=1` so a self-hosted deployment
* without Cloudflare in front cannot be tricked by an attacker
* setting the header directly.
*/
describe("getClientIp Cloudflare cf-connecting-ip branch (v1.4.37)", () => {
it("returns cf-connecting-ip when the env flag is on and the header is present", () => {
process.env.TRUST_CF_CONNECTING_IP = "1";
const ip = getClientIp(
makeRequest({
"cf-connecting-ip": "203.0.113.42",
"x-forwarded-for": "1.1.1.1, 192.0.2.7",
}),
);
expect(ip).toBe("203.0.113.42");
});
it("ignores cf-connecting-ip when the env flag is off (default)", () => {
// Default — header set by an attacker on a deployment without
// Cloudflare in front must NOT be trusted; the helper falls
// through to the XFF / x-real-ip chain.
const ip = getClientIp(
makeRequest({
"cf-connecting-ip": "203.0.113.42",
"x-forwarded-for": "9.9.9.9, 5.6.7.8",
}),
);
expect(ip).toBe("5.6.7.8");
});
it("ignores cf-connecting-ip when the env flag is any value other than '1'", () => {
process.env.TRUST_CF_CONNECTING_IP = "true";
const ip = getClientIp(
makeRequest({
"cf-connecting-ip": "203.0.113.42",
"x-forwarded-for": "9.9.9.9, 5.6.7.8",
}),
);
expect(ip).toBe("5.6.7.8");
});
it("falls back to the XFF chain when the env flag is on but cf-connecting-ip is missing", () => {
process.env.TRUST_CF_CONNECTING_IP = "1";
const ip = getClientIp(
makeRequest({ "x-forwarded-for": "1.1.1.1, 5.6.7.8" }),
);
expect(ip).toBe("5.6.7.8");
});
it("rejects a malformed cf-connecting-ip when the env flag is on", () => {
process.env.TRUST_CF_CONNECTING_IP = "1";
const ip = getClientIp(
makeRequest({
"cf-connecting-ip": "<<not-an-ip>>",
"x-forwarded-for": "1.1.1.1, 5.6.7.8",
}),
);
expect(ip).toBe("5.6.7.8");
});
it("getClientIpOrTrustWarning also prefers cf-connecting-ip when the flag is on", () => {
process.env.TRUST_CF_CONNECTING_IP = "1";
const result = getClientIpOrTrustWarning(
makeRequest({
"cf-connecting-ip": "203.0.113.42",
"x-forwarded-for": "1.1.1.1",
}),
);
expect(result).toEqual({ ip: "203.0.113.42", trustViolation: false });
});
});
describe("getClientIpOrTrustWarning shape (F-6, 2026-05-16)", () => {
it("returns trustViolation=false on a well-formed chain", () => {
const result = getClientIpOrTrustWarning(
@@ -0,0 +1,282 @@
/**
* v1.4.37 W2 — unit pin for the probe-gated bp_in_target helper.
*
* Mocks Prisma + the rollup-coverage probe so the path-selection
* contract is verifiable without a Postgres container. Real-rollup
* coverage with byte-shape parity lives in the integration suite at
* `tests/integration/bp-in-target.test.ts`.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
measurementRollup: { findMany: vi.fn() },
},
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
}));
vi.mock("@/lib/measurements/rollup-coverage", () => ({
isFullyCovered: vi.fn(),
probeRollupCoverage: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import {
isFullyCovered,
probeRollupCoverage,
} from "@/lib/measurements/rollup-coverage";
import { computeBpInTargetFastPath } from "../bp-in-target-fast-path";
const MEASUREMENT_FIND_MANY = prisma.measurement.findMany as unknown as ReturnType<typeof vi.fn>;
const ROLLUP_FIND_MANY = prisma.measurementRollup.findMany as unknown as ReturnType<typeof vi.fn>;
const PROBE = probeRollupCoverage as unknown as ReturnType<typeof vi.fn>;
const FULLY_COVERED = isFullyCovered as unknown as ReturnType<typeof vi.fn>;
const ANNOTATE = annotate as unknown as ReturnType<typeof vi.fn>;
const TARGETS_UNDER_65 = {
sysLow: 120,
sysHigh: 129,
diaLow: 70,
diaHigh: 79,
};
beforeEach(() => {
MEASUREMENT_FIND_MANY.mockReset();
ROLLUP_FIND_MANY.mockReset();
PROBE.mockReset();
FULLY_COVERED.mockReset();
ANNOTATE.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("computeBpInTargetFastPath", () => {
describe("rollup-fast-path — both BP types covered", () => {
it("composes in-target % from DAY buckets without reading raw measurements", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["BLOOD_PRESSURE_DIA", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
const now = new Date("2026-05-17T12:00:00.000Z");
const today = new Date("2026-05-17T00:00:00.000Z");
const yesterday = new Date("2026-05-16T00:00:00.000Z");
const twoDaysAgo = new Date("2026-05-15T00:00:00.000Z");
ROLLUP_FIND_MANY
// SYS day buckets
.mockResolvedValueOnce([
{
bucketStart: today,
count: 2,
mean: 125, // in-target
minValue: 120,
maxValue: 130,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
{
bucketStart: yesterday,
count: 1,
mean: 145, // out-of-target (sys too high)
minValue: 145,
maxValue: 145,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
{
bucketStart: twoDaysAgo,
count: 3,
mean: 122, // in-target
minValue: 118,
maxValue: 127,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
])
// DIA day buckets
.mockResolvedValueOnce([
{
bucketStart: today,
count: 2,
mean: 75,
minValue: 72,
maxValue: 78,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
{
bucketStart: yesterday,
count: 1,
mean: 85,
minValue: 85,
maxValue: 85,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
{
bucketStart: twoDaysAgo,
count: 3,
mean: 78,
minValue: 70,
maxValue: 79,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
]);
const result = await computeBpInTargetFastPath({
userId: "user-rollup",
targets: TARGETS_UNDER_65,
now,
coverage,
});
expect(result.path).toBe("rollup");
// 2 in-target days (today + 2-days-ago) out of 3 → 5 in-target
// pair-counts out of 6 total. round(5/6 * 100) = 83.
expect(result.last7Days).toEqual({ pct: 83, pairs: 6 });
expect(result.last30Days).toEqual({ pct: 83, pairs: 6 });
expect(result.allTime).toEqual({ pct: 83, pairs: 6 });
expect(MEASUREMENT_FIND_MANY).not.toHaveBeenCalled();
expect(ROLLUP_FIND_MANY).toHaveBeenCalledTimes(2);
});
it("pins the path:rollup annotate so prod logs can prove the branch", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["BLOOD_PRESSURE_DIA", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
ROLLUP_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
await computeBpInTargetFastPath({
userId: "user-rollup",
targets: TARGETS_UNDER_65,
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const bpCall = calls.find(
(c) => c?.meta?.analytics?.bp_in_target?.path === "rollup",
);
expect(bpCall).toBeDefined();
});
it("returns null for windows with no paired days", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["BLOOD_PRESSURE_DIA", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
ROLLUP_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await computeBpInTargetFastPath({
userId: "user-fresh",
targets: TARGETS_UNDER_65,
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
expect(result.last7Days).toBeNull();
expect(result.last30Days).toBeNull();
expect(result.allTime).toBeNull();
expect(result.path).toBe("rollup");
});
});
describe("live fallback — partial or no coverage", () => {
it("falls back to the chunked findMany when SYS bucket coverage is missing", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", false],
["BLOOD_PRESSURE_DIA", true],
]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
// First findMany = SYS rows, second = DIA rows.
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([
{ id: "1", measuredAt: new Date("2026-05-15T08:00:00.000Z"), value: 122 },
])
.mockResolvedValueOnce([
{ id: "2", measuredAt: new Date("2026-05-15T08:00:00.000Z"), value: 76 },
]);
const result = await computeBpInTargetFastPath({
userId: "user-partial",
targets: TARGETS_UNDER_65,
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
expect(result.path).toBe("live");
// One paired in-target reading.
expect(result.last30Days).toEqual({ pct: 100, pairs: 1 });
expect(ROLLUP_FIND_MANY).not.toHaveBeenCalled();
expect(MEASUREMENT_FIND_MANY).toHaveBeenCalledTimes(2);
});
it("pins the path:live annotate", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["BLOOD_PRESSURE_DIA", false],
]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
await computeBpInTargetFastPath({
userId: "user-partial",
targets: TARGETS_UNDER_65,
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const bpCall = calls.find(
(c) => c?.meta?.analytics?.bp_in_target?.path === "live",
);
expect(bpCall).toBeDefined();
});
it("probes coverage when the caller omits the map", async () => {
const coverage = new Map<string, boolean>([]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await computeBpInTargetFastPath({
userId: "user-fresh",
targets: TARGETS_UNDER_65,
now: new Date("2026-05-17T12:00:00.000Z"),
});
expect(PROBE).toHaveBeenCalledWith("user-fresh");
expect(result.path).toBe("live");
});
});
});
@@ -0,0 +1,197 @@
/**
* v1.4.37 W2 — unit pin for the probe-gated correlation runner.
*
* Mocks Prisma + the rollup-coverage probe so the path-selection
* contract is verifiable without a Postgres container. Real-data
* coverage of the actual Pearson + ANOVA math lives in
* `correlations.test.ts`; this file only checks WHICH read path the
* runner takes and that the sentinel annotate carries the window.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
measurementRollup: { findMany: vi.fn() },
moodEntry: { findMany: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
},
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
}));
vi.mock("@/lib/measurements/rollup-coverage", () => ({
isFullyCovered: vi.fn(),
probeRollupCoverage: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import {
isFullyCovered,
probeRollupCoverage,
} from "@/lib/measurements/rollup-coverage";
import {
CORRELATION_WINDOW_DAYS,
computeCorrelationHypothesesFastPath,
} from "../correlations-fast-path";
const MEASUREMENT_FIND_MANY = prisma.measurement.findMany as unknown as ReturnType<typeof vi.fn>;
const ROLLUP_FIND_MANY = prisma.measurementRollup.findMany as unknown as ReturnType<typeof vi.fn>;
const MOOD_FIND_MANY = prisma.moodEntry.findMany as unknown as ReturnType<typeof vi.fn>;
const INTAKE_FIND_MANY = prisma.medicationIntakeEvent.findMany as unknown as ReturnType<typeof vi.fn>;
const PROBE = probeRollupCoverage as unknown as ReturnType<typeof vi.fn>;
const FULLY_COVERED = isFullyCovered as unknown as ReturnType<typeof vi.fn>;
const ANNOTATE = annotate as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
MEASUREMENT_FIND_MANY.mockReset();
ROLLUP_FIND_MANY.mockReset();
MOOD_FIND_MANY.mockReset();
INTAKE_FIND_MANY.mockReset();
PROBE.mockReset();
FULLY_COVERED.mockReset();
ANNOTATE.mockReset();
MOOD_FIND_MANY.mockResolvedValue([]);
INTAKE_FIND_MANY.mockResolvedValue([]);
ROLLUP_FIND_MANY.mockResolvedValue([]);
MEASUREMENT_FIND_MANY.mockResolvedValue([]);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("computeCorrelationHypothesesFastPath", () => {
it("scans the trailing 28 days (CORRELATION_WINDOW_DAYS)", () => {
expect(CORRELATION_WINDOW_DAYS).toBe(28);
});
describe("rollup-fast-path — SYS / PULSE / WEIGHT covered", () => {
it("reads per-day means from measurement_rollups, never from measurements", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["PULSE", true],
["WEIGHT", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
ROLLUP_FIND_MANY
.mockResolvedValueOnce([]) // SYS buckets
.mockResolvedValueOnce([]) // PULSE buckets
.mockResolvedValueOnce([]); // WEIGHT buckets
const result = await computeCorrelationHypothesesFastPath({
userId: "user-rollup",
userTz: "Europe/Berlin",
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
expect(result.path).toBe("rollup");
expect(result.windowDays).toBe(28);
expect(result.degraded).toBe(false);
// No raw measurement reads when on rollup-fast-path.
expect(MEASUREMENT_FIND_MANY).not.toHaveBeenCalled();
expect(ROLLUP_FIND_MANY).toHaveBeenCalledTimes(3);
// Mood + intake reads always live.
expect(MOOD_FIND_MANY).toHaveBeenCalledTimes(1);
expect(INTAKE_FIND_MANY).toHaveBeenCalledTimes(1);
});
it("pins path:rollup + window_days:28 on the annotate", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", true],
["PULSE", true],
["WEIGHT", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
ROLLUP_FIND_MANY.mockResolvedValue([]);
await computeCorrelationHypothesesFastPath({
userId: "user-rollup",
userTz: "Europe/Berlin",
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const corrCall = calls.find((c) => c?.meta?.correlations !== undefined);
expect(corrCall).toBeDefined();
expect(corrCall.meta.correlations.path).toBe("rollup");
expect(corrCall.meta.correlations.window_days).toBe(28);
expect(corrCall.meta.correlations.degraded).toBe(false);
});
});
describe("live fallback", () => {
it("falls back when SYS coverage is missing", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", false],
["PULSE", true],
["WEIGHT", true],
]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY
.mockResolvedValueOnce([]) // SYS rows
.mockResolvedValueOnce([]) // PULSE rows
.mockResolvedValueOnce([]); // WEIGHT rows
const result = await computeCorrelationHypothesesFastPath({
userId: "user-partial",
userTz: "Europe/Berlin",
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
expect(result.path).toBe("live");
expect(MEASUREMENT_FIND_MANY).toHaveBeenCalledTimes(3);
expect(ROLLUP_FIND_MANY).not.toHaveBeenCalled();
});
it("pins path:live on the annotate", async () => {
const coverage = new Map<string, boolean>([
["BLOOD_PRESSURE_SYS", false],
]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY.mockResolvedValue([]);
await computeCorrelationHypothesesFastPath({
userId: "user-partial",
userTz: "Europe/Berlin",
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const corrCall = calls.find((c) => c?.meta?.correlations !== undefined);
expect(corrCall).toBeDefined();
expect(corrCall.meta.correlations.path).toBe("live");
});
});
describe("coverage probing", () => {
it("probes coverage when the caller omits the map", async () => {
const coverage = new Map<string, boolean>([]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY.mockResolvedValue([]);
await computeCorrelationHypothesesFastPath({
userId: "user-fresh",
userTz: "Europe/Berlin",
now: new Date("2026-05-17T12:00:00.000Z"),
});
expect(PROBE).toHaveBeenCalledWith("user-fresh");
});
});
});
@@ -0,0 +1,241 @@
/**
* v1.4.37 W2 — unit pin for the probe-gated Health Score helper.
*
* Mocks Prisma + the rollup-coverage probe so the path-selection
* contract is verifiable without a Postgres container. Real-rollup
* coverage lives in the integration suite at
* `tests/integration/analytics-health-score.test.ts`.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findMany: vi.fn() },
measurementRollup: { findMany: vi.fn() },
moodEntry: { findMany: vi.fn() },
medication: { findMany: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
},
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
}));
vi.mock("@/lib/measurements/rollup-coverage", () => ({
isFullyCovered: vi.fn(),
probeRollupCoverage: vi.fn(),
}));
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import {
isFullyCovered,
probeRollupCoverage,
} from "@/lib/measurements/rollup-coverage";
import { computeUserHealthScoreFastPath } from "../health-score-fast-path";
const MEASUREMENT_FIND_MANY = prisma.measurement.findMany as unknown as ReturnType<typeof vi.fn>;
const ROLLUP_FIND_MANY = prisma.measurementRollup.findMany as unknown as ReturnType<typeof vi.fn>;
const MOOD_FIND_MANY = prisma.moodEntry.findMany as unknown as ReturnType<typeof vi.fn>;
const MEDICATION_FIND_MANY = prisma.medication.findMany as unknown as ReturnType<typeof vi.fn>;
const INTAKE_FIND_MANY = prisma.medicationIntakeEvent.findMany as unknown as ReturnType<typeof vi.fn>;
const PROBE = probeRollupCoverage as unknown as ReturnType<typeof vi.fn>;
const FULLY_COVERED = isFullyCovered as unknown as ReturnType<typeof vi.fn>;
const ANNOTATE = annotate as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
MEASUREMENT_FIND_MANY.mockReset();
ROLLUP_FIND_MANY.mockReset();
MOOD_FIND_MANY.mockReset();
MEDICATION_FIND_MANY.mockReset();
INTAKE_FIND_MANY.mockReset();
PROBE.mockReset();
FULLY_COVERED.mockReset();
ANNOTATE.mockReset();
// Defaults — empty everywhere. Individual tests override.
ROLLUP_FIND_MANY.mockResolvedValue([]);
MOOD_FIND_MANY.mockResolvedValue([]);
MEDICATION_FIND_MANY.mockResolvedValue([]);
INTAKE_FIND_MANY.mockResolvedValue([]);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("computeUserHealthScoreFastPath", () => {
describe("rollup-fast-path — WEIGHT fully covered", () => {
it("derives the weight series from DAY buckets and pins path:rollup", async () => {
const coverage = new Map<string, boolean>([
["WEIGHT", true],
["BLOOD_PRESSURE_SYS", true],
["BLOOD_PRESSURE_DIA", true],
]);
FULLY_COVERED.mockReturnValue(true);
PROBE.mockResolvedValue(coverage);
const now = new Date("2026-05-17T12:00:00.000Z");
// Two day-buckets inside the trailing 30 days, descending mean.
ROLLUP_FIND_MANY.mockResolvedValueOnce([
{
bucketStart: new Date("2026-05-10T00:00:00.000Z"),
count: 1,
mean: 82.5,
minValue: 82.5,
maxValue: 82.5,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
{
bucketStart: new Date("2026-05-14T00:00:00.000Z"),
count: 1,
mean: 81.5,
minValue: 81.5,
maxValue: 81.5,
sd: null,
slope: null,
r2: null,
computedAt: now,
},
]);
// Weight source-attribution read (narrow 2-column).
MEASUREMENT_FIND_MANY
.mockResolvedValueOnce([
{
measuredAt: new Date("2026-05-10T08:00:00.000Z"),
source: "WITHINGS",
},
{
measuredAt: new Date("2026-05-14T08:00:00.000Z"),
source: "WITHINGS",
},
])
// BP-SYS source attribution read (parallel after rollup).
.mockResolvedValueOnce([]);
const result = await computeUserHealthScoreFastPath({
userId: "user-rollup",
bpInTargetPct: 85,
heightCm: 178,
now,
coverage,
});
expect(result).not.toBeNull();
// Path annotate proves the rollup branch fired.
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const pathCall = calls.find(
(c) => c?.meta?.healthScore?.path === "rollup",
);
expect(pathCall).toBeDefined();
// The rollup branch must NOT have called `measurement.findMany`
// for the 37-day raw weight read; only the narrow 2-column source
// pull + the BP source pull.
expect(MEASUREMENT_FIND_MANY).toHaveBeenCalledTimes(2);
// Both findMany calls projected a narrow select (no `value`).
const calledArgs = MEASUREMENT_FIND_MANY.mock.calls.map((c) => c[0]);
for (const arg of calledArgs) {
expect(arg.select.value).toBeUndefined();
}
// Weight pillar value should reflect the downward slope from
// bucket means (helper reports a numeric weight value).
expect(result?.components.weight.value).not.toBeNull();
});
});
describe("live fallback — WEIGHT not covered", () => {
it("reads raw weight rows and pins path:live", async () => {
const coverage = new Map<string, boolean>([
["WEIGHT", false],
]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
const now = new Date("2026-05-17T12:00:00.000Z");
MEASUREMENT_FIND_MANY
// Weight (live) — 37-day window, 3-column projection.
.mockResolvedValueOnce([
{
measuredAt: new Date("2026-05-10T08:00:00.000Z"),
value: 82.5,
source: "MANUAL",
},
{
measuredAt: new Date("2026-05-14T08:00:00.000Z"),
value: 81.5,
source: "MANUAL",
},
])
// BP-SYS source attribution.
.mockResolvedValueOnce([]);
const result = await computeUserHealthScoreFastPath({
userId: "user-live",
bpInTargetPct: 75,
heightCm: 178,
now,
coverage,
});
expect(result).not.toBeNull();
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const pathCall = calls.find(
(c) => c?.meta?.healthScore?.path === "live",
);
expect(pathCall).toBeDefined();
// Live path read raw weight (value selected).
const weightCall = MEASUREMENT_FIND_MANY.mock.calls[0][0];
expect(weightCall.select.value).toBe(true);
expect(weightCall.where.type).toBe("WEIGHT");
expect(ROLLUP_FIND_MANY).not.toHaveBeenCalled();
});
});
describe("empty path", () => {
it("returns null with reason:no_components_available when nothing is computable", async () => {
const coverage = new Map<string, boolean>([]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
// No weight rows, no BP rows, no mood, no medications.
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const result = await computeUserHealthScoreFastPath({
userId: "user-empty",
bpInTargetPct: null,
heightCm: null,
now: new Date("2026-05-17T12:00:00.000Z"),
coverage,
});
expect(result).toBeNull();
const calls = ANNOTATE.mock.calls.map((c) => c[0]);
const nullCall = calls.find(
(c) => c?.meta?.healthScore?.reason === "no_components_available",
);
expect(nullCall).toBeDefined();
});
});
describe("coverage probing", () => {
it("probes coverage when the caller omits the map", async () => {
const coverage = new Map<string, boolean>([]);
FULLY_COVERED.mockReturnValue(false);
PROBE.mockResolvedValue(coverage);
MEASUREMENT_FIND_MANY.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
await computeUserHealthScoreFastPath({
userId: "user-fresh",
bpInTargetPct: null,
heightCm: null,
now: new Date("2026-05-17T12:00:00.000Z"),
});
expect(PROBE).toHaveBeenCalledWith("user-fresh");
});
});
});
+376
View File
@@ -0,0 +1,376 @@
/**
* v1.4.37 W2 — probe-gated BP-in-target windowing.
*
* The `/api/analytics` default slice computes six BP-in-target
* percentages (7 days, 30 days, all-time, prior month, prior year)
* from chunked findMany walks over `BLOOD_PRESSURE_SYS` and
* `BLOOD_PRESSURE_DIA`. v1.4.29 M1 already bounded the read to the
* trailing 365 days, but for a power user with multi-year wearable
* sync history the cold-pool round-trip still dominates the FULL-slice
* critical path. Live-tenant numbers (v1.4.36 perf-verify): the
* concurrent fan-out of bp_in_target + correlations + healthScore
* took 111 s on the very first cold hit.
*
* Read shape (v1.4.37)
* --------------------
* 1. **Probe** — `probeRollupCoverage` returns the per-type DAY-bucket
* coverage map. If BOTH `BLOOD_PRESSURE_SYS` and
* `BLOOD_PRESSURE_DIA` are covered we take the rollup-fast-path;
* otherwise we fall back to the legacy chunked-read aggregator so
* a brand-new user (no buckets yet) still sees correct numbers.
*
* 2. **Rollup-fast-path** — read the trailing-395-day DAY buckets
* for both BP types (one indexed query per type against
* `measurement_rollups`). Per day, treat the bucket's MEAN value
* as the day's representative SYS / DIA reading; pair them by
* day-key; run the existing `isBpReadingInTarget` predicate; count
* in-target days per window.
*
* **Documented approximation**: the live path pairs each
* individual SYS reading with the closest DIA inside the same
* session (≤ 5 min) or the same Berlin day. The rollup path
* instead pairs the **per-day mean** SYS with the per-day mean
* DIA. For a typical user logging two-or-three readings per day
* this lands within ±2 % of the per-event count (the day either
* averages in-target or out, and the per-event count tracks the
* mean closely). For a user logging readings at extreme ends of
* the band (one 119/79, one 145/95 in the same day) the rollup
* path may classify the day as in-target when the per-event path
* would not, or vice versa. This is the intentional
* cold-critical-path trade-off; the live path remains the
* fallback so partial-coverage accounts and the very first cold
* hit on a fresh user see the per-event number.
*
* 3. **Live fallback** — runs the legacy chunked-read aggregator
* so the response shape on cold/uncovered accounts matches
* v1.4.36 byte-for-byte.
*
* Returns the same six-window envelope `computeBpInTargetWindows`
* produces; the route's downstream code is untouched. The annotate
* dict carries a `path: "rollup" | "live"` breadcrumb so prod logs
* make the path-selection decision visible.
*/
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { readRollupBuckets } from "@/lib/measurements/rollups";
import {
isFullyCovered,
probeRollupCoverage,
type RollupCoverageMap,
} from "@/lib/measurements/rollup-coverage";
import {
computeBpInTargetWindows,
isBpReadingInTarget,
type BpReading,
} from "./bp-in-target";
import type { BpTargets } from "./bp-targets";
/**
* Result envelope — identical shape to `computeBpInTargetWindows` so
* the route's downstream coercion never has to branch on path. Path
* annotation lives in the meta dict the helper emits.
*/
export interface BpInTargetEnvelope {
last7Days: { pct: number; pairs: number } | null;
last30Days: { pct: number; pairs: number } | null;
allTime: { pct: number; pairs: number } | null;
priorMonth: { pct: number; pairs: number } | null;
priorYear: { pct: number; pairs: number } | null;
/** `"rollup"` when the fast-path fired; `"live"` on the fallback. */
path: "rollup" | "live";
/**
* Row count over the trailing window the helper actually pulled —
* surfaced on `meta.analytics.bp_in_target` so ops can attribute slow
* requests to specific outlier accounts.
*/
rowCount: number;
}
/**
* One DAY-bucket-derived BP reading. Treats the bucket's mean as the
* day's representative reading; bucket count is preserved so the live
* path's `pairs` denominator can be reconstructed without per-event
* reads.
*/
interface DayBucketReading {
/** UTC midnight of the bucket's start. */
day: Date;
/** Bucket mean — used as the day's representative value. */
meanValue: number;
/** Per-day reading count; sum across days reconstructs `pairs`. */
perDayCount: number;
}
/**
* Public entrypoint. Probes coverage, dispatches to the rollup-fast-path
* or the live fallback, emits the `path` annotate, returns the envelope.
*
* `coverage` may be passed by the caller when it has already probed
* (the analytics route probes once and re-uses the result across the
* three branches). Omit it to probe inside the helper.
*/
export async function computeBpInTargetFastPath(input: {
userId: string;
targets: BpTargets;
now: Date;
coverage?: RollupCoverageMap;
}): Promise<BpInTargetEnvelope> {
const { userId, targets, now } = input;
const coverage = input.coverage ?? (await probeRollupCoverage(userId));
const sysCovered = coverage.get("BLOOD_PRESSURE_SYS") === true;
const diaCovered = coverage.get("BLOOD_PRESSURE_DIA") === true;
// Belt-and-braces: only take the rollup path when EVERY logged type
// is covered AND both BP types are present in the map. A brand-new
// user without BP at all falls into `isFullyCovered === false`
// (coverage map is empty) and the route's downstream code already
// skips the BP block when `getBpTargets` returns null; we still call
// the live fallback here so the helper's contract stays single-shot.
if (isFullyCovered(coverage) && sysCovered && diaCovered) {
return computeFromRollups(userId, targets, now);
}
return computeFromLive(userId, targets, now);
}
/**
* Rollup-fast-path — DAY buckets carry mean SYS / mean DIA per day.
* We pair the means by day key, run the in-target predicate, and bucket
* the days into the five reporting windows the analytics tile consumes.
*/
async function computeFromRollups(
userId: string,
targets: BpTargets,
now: Date,
): Promise<BpInTargetEnvelope> {
// v1.4.22 W5 reconcile (Code-H2) — the priorYear window starts 395
// days ago. We read 396 days so the boundary day rolls cleanly into
// the prior-year bucket without being dropped.
const DAY_MS = 24 * 60 * 60 * 1000;
const readSince = new Date(now.getTime() - 396 * DAY_MS);
const [sysBuckets, diaBuckets] = await Promise.all([
readRollupBuckets(
userId,
"BLOOD_PRESSURE_SYS",
"DAY",
readSince,
now,
),
readRollupBuckets(
userId,
"BLOOD_PRESSURE_DIA",
"DAY",
readSince,
now,
),
]);
const sysByDay = new Map<string, DayBucketReading>();
for (const r of sysBuckets) {
sysByDay.set(dayKey(r.bucketStart), {
day: r.bucketStart,
meanValue: r.mean,
perDayCount: r.count,
});
}
const diaByDay = new Map<string, DayBucketReading>();
for (const r of diaBuckets) {
diaByDay.set(dayKey(r.bucketStart), {
day: r.bucketStart,
meanValue: r.mean,
perDayCount: r.count,
});
}
// Pair by day key — only days that have both SYS and DIA buckets
// count toward the denominator.
const pairsByDay: Array<{
day: Date;
sys: number;
dia: number;
perDayPairCount: number;
}> = [];
let rowCount = 0;
for (const [key, sys] of sysByDay.entries()) {
const dia = diaByDay.get(key);
if (!dia) continue;
// The day's pair count is the min of the two per-type bucket counts —
// each SYS reading can pair with at most one DIA reading that day,
// and vice versa. Conservative under-count beats an over-count when
// one half is missing.
const perDayPairCount = Math.min(sys.perDayCount, dia.perDayCount);
pairsByDay.push({
day: sys.day,
sys: sys.meanValue,
dia: dia.meanValue,
perDayPairCount,
});
rowCount += sys.perDayCount + dia.perDayCount;
}
const sevenDaysAgo = new Date(now.getTime() - 7 * DAY_MS);
const thirtyDaysAgo = new Date(now.getTime() - 30 * DAY_MS);
const sixtyDaysAgo = new Date(now.getTime() - 60 * DAY_MS);
const threeSixtyFiveDaysAgo = new Date(now.getTime() - 365 * DAY_MS);
const threeNinetyFiveDaysAgo = new Date(now.getTime() - 395 * DAY_MS);
const last7 = bucketWindow(pairsByDay, sevenDaysAgo, now, targets);
const last30 = bucketWindow(pairsByDay, thirtyDaysAgo, now, targets);
// All-time on the rollup path is bounded to the 395-day read window.
// Documented above — same trade-off the per-event path makes when the
// user's history extends beyond 365 days.
const allTime = bucketWindow(pairsByDay, threeNinetyFiveDaysAgo, now, targets);
const priorMonth = bucketWindow(
pairsByDay,
sixtyDaysAgo,
thirtyDaysAgo,
targets,
);
const priorYear = bucketWindow(
pairsByDay,
threeNinetyFiveDaysAgo,
threeSixtyFiveDaysAgo,
targets,
);
annotate({
meta: {
analytics: {
bp_in_target: {
row_count: rowCount,
sys_rows: sysBuckets.reduce((s, b) => s + b.count, 0),
dia_rows: diaBuckets.reduce((s, b) => s + b.count, 0),
path: "rollup",
},
},
},
});
return {
last7Days: last7,
last30Days: last30,
allTime,
priorMonth,
priorYear,
path: "rollup",
rowCount,
};
}
/**
* Bucket the per-day pairs into one of the five reporting windows and
* compute the in-target %. Mirrors the per-event helper's
* `null`-on-empty contract.
*/
function bucketWindow(
pairsByDay: Array<{
day: Date;
sys: number;
dia: number;
perDayPairCount: number;
}>,
from: Date,
to: Date,
targets: BpTargets,
): { pct: number; pairs: number } | null {
let pairs = 0;
let inTarget = 0;
const fromMs = from.getTime();
const toMs = to.getTime();
for (const p of pairsByDay) {
const dayMs = p.day.getTime();
if (dayMs < fromMs || dayMs >= toMs) continue;
pairs += p.perDayPairCount;
if (isBpReadingInTarget(p.sys, p.dia, targets)) {
inTarget += p.perDayPairCount;
}
}
if (pairs === 0) return null;
return {
pct: Math.round((inTarget / pairs) * 100),
pairs,
};
}
function dayKey(d: Date): string {
return d.toISOString().slice(0, 10);
}
/**
* Live fallback — preserves v1.4.36 behaviour exactly. Reads the
* trailing 365-day window in chunks, hands the series to the existing
* `computeBpInTargetWindows` helper, surfaces the result inside the
* shared envelope.
*/
async function computeFromLive(
userId: string,
targets: BpTargets,
now: Date,
): Promise<BpInTargetEnvelope> {
const DAY_MS = 24 * 60 * 60 * 1000;
const bpInTargetSince = new Date(now.getTime() - 365 * DAY_MS);
const [sysData, diaData] = await Promise.all([
fetchSeriesChunked(userId, "BLOOD_PRESSURE_SYS", bpInTargetSince),
fetchSeriesChunked(userId, "BLOOD_PRESSURE_DIA", bpInTargetSince),
]);
const rowCount = sysData.length + diaData.length;
annotate({
meta: {
analytics: {
bp_in_target: {
row_count: rowCount,
sys_rows: sysData.length,
dia_rows: diaData.length,
path: "live",
},
},
},
});
const windows = computeBpInTargetWindows(sysData, diaData, targets, now);
return {
last7Days: windows.last7Days,
last30Days: windows.last30Days,
allTime: windows.allTime,
priorMonth: windows.priorMonth,
priorYear: windows.priorYear,
path: "live",
rowCount,
};
}
/**
* Cursor-paged read of one BP type. Mirrors the route's
* `fetchMeasurementSeriesChunked` shape but pruned to the only two
* fields the in-target helper consumes (`measuredAt` + `value`) so the
* Prisma round-trip stays minimal on the cold fallback path.
*/
const CHUNK = 5000;
async function fetchSeriesChunked(
userId: string,
type: "BLOOD_PRESSURE_SYS" | "BLOOD_PRESSURE_DIA",
since: Date,
): Promise<BpReading[]> {
const out: BpReading[] = [];
let cursorId: string | undefined;
for (let page = 0; page < 1000; page++) {
const chunk = await prisma.measurement.findMany({
where: { userId, type, measuredAt: { gte: since } },
orderBy: [{ measuredAt: "asc" }, { id: "asc" }],
select: { id: true, measuredAt: true, value: true },
take: CHUNK,
...(cursorId ? { cursor: { id: cursorId }, skip: 1 } : {}),
});
if (chunk.length === 0) break;
for (const row of chunk) {
out.push({ measuredAt: row.measuredAt, value: row.value });
}
if (chunk.length < CHUNK) break;
cursorId = chunk[chunk.length - 1].id;
}
return out;
}
+371
View File
@@ -0,0 +1,371 @@
/**
* v1.4.37 W2 — probe-gated correlation hypothesis runner.
*
* The three pre-defined hypotheses (BP × medication compliance, mood ×
* resting pulse, weight × weekday) need PAIRED day-level samples
* across two streams. The pairing logic is not linearly composable
* from DAY rollup buckets the way `count / min / max / mean` is, but
* the only inputs the runners consume from the measurement stream are
* **per-day means** for the three measurement types (SYS, PULSE,
* WEIGHT). The rollup table carries those means as a first-class
* column — when DAY-bucket coverage is present we can hydrate the
* per-day-mean maps directly from `measurement_rollups` and skip the
* raw chunked findMany walks against `measurements` entirely.
*
* Read shape (v1.4.37)
* --------------------
* 1. **Tightened window** — the previous helper read the trailing 30
* days. The v1.4.37 helper reads **28 days**. The Pearson +
* ANOVA runners require `n >= 20` paired samples (v1.4.23 H6) so
* 28 still satisfies the surface gate; the 2-day tighten removes
* ~7 % of the cold-pool read volume and lines the correlation
* window up with the dashboard's "trailing 4 weeks" tile shorthand.
* The meta-dict annotate carries `window_days: 28` as a sentinel
* so the UI / docs can quote the truthful window.
*
* 2. **Probe-gated SYS / PULSE / WEIGHT** — when DAY-bucket coverage
* exists for all three types the runner hydrates the per-day-mean
* maps from `measurement_rollups`. Each rollup row already
* carries the day's `mean` value computed by Postgres' `AVG`, so
* the pairing logic is byte-for-byte identical to the live path's
* "average the day's raw values" step.
*
* 3. **Mood + medication intake** — no rollup equivalent today; both
* reads stay live regardless of coverage. The mood read is small
* (per-day entries, bounded by the 28-day window) and the
* medication intake read scales with active medications × 28 days
* so neither dominates the cost.
*
* 4. **Best-effort sentinel** — the route surface advertises a
* 28-day correlation window. Older data (> 28 days) is
* intentionally NOT scanned on the cold critical path. The
* runner emits `degraded: false` on the happy path; downstream
* consumers can extend the window via a separate dedicated
* endpoint when richer historical context is needed.
*/
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { readRollupBuckets } from "@/lib/measurements/rollups";
import {
isFullyCovered,
probeRollupCoverage,
type RollupCoverageMap,
} from "@/lib/measurements/rollup-coverage";
import {
correlateBpCompliance,
correlateMoodPulse,
correlateWeightWeekday,
type CorrelationResult,
} from "@/lib/insights/correlations";
import { userDayKey } from "@/lib/tz/resolver";
/**
* v1.4.37 W2 — cold-path correlation window. Trim from 30 to 28 days
* keeps the `n >= 20` Pearson gate comfortably reachable while shaving
* two days off every read the runner issues. Kept as a constant so the
* sentinel annotate and the SQL/Prisma WHERE clauses stay in lockstep.
*/
export const CORRELATION_WINDOW_DAYS = 28;
const CHUNK = 5000;
interface ChunkedRow {
measuredAt: Date;
value: number;
}
interface MoodRow {
score: number;
moodLoggedAt: Date;
}
interface IntakeRow {
scheduledFor: Date;
takenAt: Date | null;
skipped: boolean;
}
export interface CorrelationHypothesesResult {
bpCompliance: CorrelationResult;
moodPulse: CorrelationResult;
weightWeekday: CorrelationResult;
/**
* Sentinel — `true` when the runner's scan window was tightened
* below the canonical surface (e.g. fell back to a partial read).
* Today this is always `false`: the 28-day window is the canonical
* surface. Reserved for a future "best-effort under load shedding"
* branch.
*/
degraded: boolean;
/** Window the runner actually scanned, in days. */
windowDays: number;
/** `"rollup"` when SYS / PULSE / WEIGHT rode the rollup-fast-path. */
path: "rollup" | "live";
}
export interface CorrelationsFastPathInput {
userId: string;
userTz: string;
now: Date;
coverage?: RollupCoverageMap;
}
export async function computeCorrelationHypothesesFastPath(
input: CorrelationsFastPathInput,
): Promise<CorrelationHypothesesResult> {
const DAY_MS = 24 * 60 * 60 * 1000;
const { userId, userTz, now } = input;
const since = new Date(now.getTime() - CORRELATION_WINDOW_DAYS * DAY_MS);
const coverage = input.coverage ?? (await probeRollupCoverage(userId));
// The three measurement-derived streams ride the rollup-fast-path
// only when EVERY type the user has logged is covered AND each of
// SYS / PULSE / WEIGHT is in the coverage map. Partial coverage
// falls back to the live path so a brand-new metric type doesn't
// make the correlation card vanish.
const measurementsOnRollups =
isFullyCovered(coverage) &&
coverage.get("BLOOD_PRESSURE_SYS") === true &&
coverage.get("PULSE") === true &&
coverage.get("WEIGHT") === true;
let dailySysMean: Map<string, number>;
let dailyPulseMean: Map<string, number>;
let weightRows: ChunkedRow[];
if (measurementsOnRollups) {
// Rollup-fast-path. One indexed read per type against
// `measurement_rollups`, projecting the per-day mean directly.
//
// The rollup table buckets at UTC midnight (`date_trunc('day', …)`
// in Postgres). For a user whose display tz sits more than a few
// hours from UTC the bucket's `bucketStart` can land on the
// previous local calendar day relative to the same wall-clock
// reading on the live path. Today the production tenant is
// Berlin-centric (UTC+1/+2 → midnight UTC = 01:00/02:00 Berlin,
// same calendar day) so the shift is benign. A v1.5 follow-up
// could mint per-user-tz buckets if the discrepancy materialises
// on a non-Berlin account; the n >= 20 surface gate absorbs the
// single-day phase shift either way.
const [sysBuckets, pulseBuckets, weightBuckets] = await Promise.all([
readRollupBuckets(userId, "BLOOD_PRESSURE_SYS", "DAY", since, now),
readRollupBuckets(userId, "PULSE", "DAY", since, now),
readRollupBuckets(userId, "WEIGHT", "DAY", since, now),
]);
dailySysMean = new Map();
for (const b of sysBuckets) {
dailySysMean.set(userDayKey(b.bucketStart, userTz), b.mean);
}
dailyPulseMean = new Map();
for (const b of pulseBuckets) {
dailyPulseMean.set(userDayKey(b.bucketStart, userTz), b.mean);
}
// The weekday hypothesis needs the per-event weight series for
// ANOVA — the runner expects one row per measurement so the group
// counts reflect reality. Hydrate from buckets by emitting one
// pseudo-row per bucket carrying the day's mean. For weight the
// typical usage is one weigh-in per day, so the rollup shape is
// already aligned; if a power user logged 3 weigh-ins on a single
// Monday the rollup collapses them into one mean, which is the
// statistically correct "this Monday's weight" datapoint anyway.
weightRows = weightBuckets.map((b) => ({
measuredAt: b.bucketStart,
value: b.mean,
}));
} else {
// Live fallback — chunked reads against the measurements table.
const [sysRows, pulseRows, weightRowsLive] = await Promise.all([
fetchSeriesChunked(userId, "BLOOD_PRESSURE_SYS", since),
fetchSeriesChunked(userId, "PULSE", since),
fetchSeriesChunked(userId, "WEIGHT", since),
]);
dailySysMean = new Map();
const sysBuckets = new Map<string, number[]>();
for (const r of sysRows) {
const key = userDayKey(r.measuredAt, userTz);
const list = sysBuckets.get(key) ?? [];
list.push(r.value);
sysBuckets.set(key, list);
}
for (const [key, list] of sysBuckets.entries()) {
const sum = list.reduce((s, v) => s + v, 0);
dailySysMean.set(key, sum / list.length);
}
dailyPulseMean = new Map();
const pulseBuckets = new Map<string, number[]>();
for (const r of pulseRows) {
const key = userDayKey(r.measuredAt, userTz);
const list = pulseBuckets.get(key) ?? [];
list.push(r.value);
pulseBuckets.set(key, list);
}
for (const [key, list] of pulseBuckets.entries()) {
const sum = list.reduce((s, v) => s + v, 0);
dailyPulseMean.set(key, sum / list.length);
}
weightRows = weightRowsLive;
}
// Mood + intake — always live. Both reads are small (28-day window,
// narrow projections) and neither has a rollup equivalent today.
const [moodRows, intakeRows] = await Promise.all([
prisma.moodEntry.findMany({
where: { userId, moodLoggedAt: { gte: since } },
select: { score: true, moodLoggedAt: true },
}) as Promise<MoodRow[]>,
prisma.medicationIntakeEvent.findMany({
where: { userId, scheduledFor: { gte: since } },
select: { scheduledFor: true, takenAt: true, skipped: true },
}) as Promise<IntakeRow[]>,
]);
// ── Hypothesis 1: BP × medication compliance ────────────────
const dailyCompliance = new Map<
string,
{ expected: number; taken: number }
>();
for (const event of intakeRows) {
const key = userDayKey(event.scheduledFor, userTz);
const slot = dailyCompliance.get(key) ?? { expected: 0, taken: 0 };
slot.expected += 1;
if (event.takenAt && !event.skipped) slot.taken += 1;
dailyCompliance.set(key, slot);
}
const bpCompliancePairs: Array<{
date: Date;
systolic: number;
compliancePct: number;
}> = [];
for (const [key, meanSys] of dailySysMean.entries()) {
const slot = dailyCompliance.get(key);
if (!slot || slot.expected === 0) continue;
const compliancePct = (slot.taken / slot.expected) * 100;
bpCompliancePairs.push({
date: dateFromDayKey(key),
systolic: meanSys,
compliancePct,
});
}
const bpCompliance = correlateBpCompliance({ daily: bpCompliancePairs });
// ── Hypothesis 2: Mood × resting pulse ──────────────────────
const dailyMood = new Map<string, number[]>();
for (const row of moodRows) {
const key = userDayKey(row.moodLoggedAt, userTz);
const list = dailyMood.get(key) ?? [];
list.push(row.score);
dailyMood.set(key, list);
}
const moodPulsePairs: Array<{
date: Date;
mood: number;
restingPulse: number;
}> = [];
for (const [key, moodScores] of dailyMood.entries()) {
const meanPulse = dailyPulseMean.get(key);
if (meanPulse === undefined) continue;
const meanMood = moodScores.reduce((s, v) => s + v, 0) / moodScores.length;
moodPulsePairs.push({
date: dateFromDayKey(key),
mood: meanMood,
restingPulse: meanPulse,
});
}
const moodPulse = correlateMoodPulse({ daily: moodPulsePairs });
// ── Hypothesis 3: Weight × weekday ──────────────────────────
const weightWeekdayPairs: Array<{ weekday: number; weight: number }> = [];
for (const row of weightRows) {
const isoWeekday = isoWeekdayInTz(row.measuredAt, userTz);
weightWeekdayPairs.push({
weekday: isoWeekday - 1,
weight: row.value,
});
}
const weightWeekday = correlateWeightWeekday({ daily: weightWeekdayPairs });
annotate({
meta: {
correlations: {
bpCompliance: bpCompliance.status,
moodPulse: moodPulse.status,
weightWeekday: weightWeekday.status,
path: measurementsOnRollups ? "rollup" : "live",
window_days: CORRELATION_WINDOW_DAYS,
degraded: false,
},
},
});
return {
bpCompliance,
moodPulse,
weightWeekday,
degraded: false,
windowDays: CORRELATION_WINDOW_DAYS,
path: measurementsOnRollups ? "rollup" : "live",
};
}
async function fetchSeriesChunked(
userId: string,
type: "BLOOD_PRESSURE_SYS" | "PULSE" | "WEIGHT",
since: Date,
): Promise<ChunkedRow[]> {
const out: ChunkedRow[] = [];
let cursorId: string | undefined;
for (let page = 0; page < 1000; page++) {
const chunk = await prisma.measurement.findMany({
where: { userId, type, measuredAt: { gte: since } },
orderBy: [{ measuredAt: "asc" }, { id: "asc" }],
select: { id: true, measuredAt: true, value: true },
take: CHUNK,
...(cursorId ? { cursor: { id: cursorId }, skip: 1 } : {}),
});
if (chunk.length === 0) break;
for (const row of chunk) {
out.push({ measuredAt: row.measuredAt, value: row.value });
}
if (chunk.length < CHUNK) break;
cursorId = chunk[chunk.length - 1].id;
}
return out;
}
function dateFromDayKey(key: string): Date {
return new Date(`${key}T00:00:00.000Z`);
}
const WEEKDAY_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();
function getWeekdayFormatter(timeZone: string): Intl.DateTimeFormat {
let formatter = WEEKDAY_FORMATTER_CACHE.get(timeZone);
if (!formatter) {
formatter = new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
weekday: "short",
});
WEEKDAY_FORMATTER_CACHE.set(timeZone, formatter);
}
return formatter;
}
const ISO_WEEKDAY: Record<string, number> = {
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
Sun: 7,
};
function isoWeekdayInTz(d: Date, timeZone: string): number {
const parts = getWeekdayFormatter(timeZone).formatToParts(d);
const weekday = parts.find((p) => p.type === "weekday")?.value ?? "Mon";
return ISO_WEEKDAY[weekday] ?? 1;
}
+383
View File
@@ -0,0 +1,383 @@
/**
* v1.4.37 W2 — probe-gated Health Score builder.
*
* The `/api/analytics` default slice builds the Personal Health Score
* by combining BP-in-target % (already computed upstream) with three
* additional pillars: weight-trend alignment, mood stability, and
* medication compliance. Up to v1.4.37 the route inlined four parallel
* `findMany` reads (weight 37 days, BP-SYS 30 days for source pills,
* mood 37 days, active medications) plus a fifth for intake events.
* On a cold connection pool the round-trip latency stacks — the
* v1.4.36 perf-verify recorded the bp_in_target + healthScore +
* correlations fan-out at 111 s wall-clock against Marc's
* 311 779-row tenant.
*
* Read shape (v1.4.37)
* --------------------
* 1. **Probe** — `probeRollupCoverage` returns the per-type DAY-bucket
* coverage map. When WEIGHT is covered we take the rollup-fast-path
* for the weight pillar; the slope/alignment math runs against
* per-day MEAN weight derived from `measurement_rollups` instead
* of the raw `measurements` table.
*
* 2. **Source attribution** — only the raw rows know which ingest
* path produced each reading, so the per-component
* `HealthScoreSourceAttribution` slice still needs a narrow read
* against `measurements` (selecting only `source` + `measuredAt`).
* That read is cheap (30-day window, 2-column projection) and
* stays live regardless of coverage.
*
* 3. **Live fallback** — when the probe shows WEIGHT is not covered
* (brand-new user, no buckets yet) the helper reads the raw
* weight rows the same way the legacy route did so the score
* stays correct on first cold-mount.
*
* The mood / medication / compliance pillars don't have rollup
* equivalents (the rollup table only carries `Measurement` aggregates)
* — those reads remain live regardless. The path annotate on
* `meta.healthScore.path` makes the branch selection visible in prod
* logs.
*/
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { readRollupBuckets } from "@/lib/measurements/rollups";
import {
isFullyCovered,
probeRollupCoverage,
type RollupCoverageMap,
} from "@/lib/measurements/rollup-coverage";
import { calculateCompliance } from "./compliance";
import {
computeHealthScore,
defaultWeightTargetFromHeight,
type ContributingSource,
type HealthScoreInput,
type HealthScoreResult,
} from "./health-score";
import type { MeasurementSource } from "@/generated/prisma/client";
/**
* v1.4.25 W8e — collapse the persisted `MeasurementSource` enum onto
* the camelCase token set the health-score analytics layer consumes.
*
* - `MANUAL` and `IMPORT` (CSV import — still user-supplied data) both
* surface as `"manual"`.
* - `WITHINGS` and `APPLE_HEALTH` ride one-to-one.
*
* Returns `null` for source values that don't fall into the three
* exposed buckets — defence-in-depth in case the enum grows before the
* client is taught about it.
*/
function mapMeasurementSourceToLabel(
source: MeasurementSource,
): ContributingSource | null {
switch (source) {
case "MANUAL":
case "IMPORT":
return "manual";
case "WITHINGS":
return "withings";
case "APPLE_HEALTH":
return "appleHealth";
default:
return null;
}
}
function uniqueComponentSources(
rows: ReadonlyArray<MeasurementSource>,
): ReadonlyArray<ContributingSource> {
const seen = new Set<ContributingSource>();
for (const src of rows) {
const label = mapMeasurementSourceToLabel(src);
if (label) seen.add(label);
}
return Array.from(seen);
}
export interface HealthScoreFastPathInput {
userId: string;
bpInTargetPct: number | null;
heightCm: number | null;
now: Date;
/**
* Per-type rollup coverage map. The caller (analytics route) probes
* once and shares the result across all three fast-path helpers so
* the probe cost stays flat in the fan-out.
*/
coverage?: RollupCoverageMap;
}
/**
* Public entrypoint. Returns the same shape `computeHealthScore`
* returns, plus a `path` annotate emitted on the meta dict.
*
* Returns null when no component can be computed (the route surfaces
* `null` to the UI so the hero panel hides cleanly).
*/
export async function computeUserHealthScoreFastPath(
input: HealthScoreFastPathInput,
): Promise<HealthScoreResult | null> {
const DAY_MS = 24 * 60 * 60 * 1000;
const { userId, bpInTargetPct, heightCm, now } = input;
const since30d = new Date(now.getTime() - 30 * DAY_MS);
const prevSince30d = new Date(now.getTime() - 37 * DAY_MS);
const prevUntil = new Date(now.getTime() - 7 * DAY_MS);
const coverage = input.coverage ?? (await probeRollupCoverage(userId));
const weightCovered =
isFullyCovered(coverage) && coverage.get("WEIGHT") === true;
// Weight series — rollup-fast-path when fully covered, raw findMany
// otherwise. The raw read selects only the columns the slope helper
// and the source-attribution accordion need (value + measuredAt +
// source) so the projection stays narrow.
let weightSeriesLast30d: Array<{ date: string; kg: number }>;
let weightSeriesPrev30d: Array<{ date: string; kg: number }>;
let weightSourcesIn30d: ReadonlyArray<ContributingSource>;
let latestWeightAsOf: string | null;
if (weightCovered) {
// Rollup-fast-path — per-day MEAN weight from `measurement_rollups`.
// Linear regression on per-day means produces a slope equivalent
// to per-event regression for a series with consistent sampling
// cadence (one weigh-in per day is the canonical pattern).
const dayBuckets = await readRollupBuckets(
userId,
"WEIGHT",
"DAY",
prevSince30d,
now,
);
weightSeriesLast30d = dayBuckets
.filter((b) => b.bucketStart >= since30d)
.map((b) => ({
date: b.bucketStart.toISOString(),
kg: b.mean,
}));
weightSeriesPrev30d = dayBuckets
.filter((b) => b.bucketStart >= prevSince30d && b.bucketStart <= prevUntil)
.map((b) => ({
date: b.bucketStart.toISOString(),
kg: b.mean,
}));
// Source attribution still needs the raw rows — only the raw table
// carries the `source` enum. Pull the narrow 30-day window with a
// 2-column projection so the round-trip stays minimal.
const sourceRows = await prisma.measurement.findMany({
where: {
userId,
type: "WEIGHT",
measuredAt: { gte: since30d, lte: now },
},
select: { measuredAt: true, source: true },
orderBy: { measuredAt: "asc" },
});
weightSourcesIn30d = uniqueComponentSources(sourceRows.map((r) => r.source));
latestWeightAsOf = sourceRows.at(-1)?.measuredAt.toISOString() ?? null;
} else {
// Live fallback — raw rows over the 37-day window. Mirrors the
// pre-v1.4.37 behaviour exactly.
const weightRows = await prisma.measurement.findMany({
where: {
userId,
type: "WEIGHT",
measuredAt: { gte: prevSince30d, lte: now },
},
select: { value: true, measuredAt: true, source: true },
orderBy: { measuredAt: "asc" },
});
weightSeriesLast30d = weightRows
.filter((r) => r.measuredAt >= since30d)
.map((r) => ({ date: r.measuredAt.toISOString(), kg: r.value }));
weightSeriesPrev30d = weightRows
.filter((r) => r.measuredAt >= prevSince30d && r.measuredAt <= prevUntil)
.map((r) => ({ date: r.measuredAt.toISOString(), kg: r.value }));
weightSourcesIn30d = uniqueComponentSources(
weightRows
.filter((r) => r.measuredAt >= since30d)
.map((r) => r.source),
);
latestWeightAsOf =
weightRows.filter((r) => r.measuredAt >= since30d).at(-1)?.measuredAt
.toISOString() ?? null;
}
// Remaining reads — mood, BP-SYS source attribution, medications +
// intake — run in parallel. None has a rollup equivalent today so
// these are always live.
const [bpSysRowsForSource, moodRows, medications] = await Promise.all([
prisma.measurement.findMany({
where: {
userId,
type: "BLOOD_PRESSURE_SYS",
measuredAt: { gte: since30d, lte: now },
},
select: { measuredAt: true, source: true },
orderBy: { measuredAt: "asc" },
}),
prisma.moodEntry.findMany({
where: {
userId,
moodLoggedAt: { gte: prevSince30d, lte: now },
},
select: { score: true, moodLoggedAt: true },
orderBy: { moodLoggedAt: "asc" },
}),
prisma.medication.findMany({
where: { userId, active: true },
select: {
id: true,
createdAt: true,
schedules: {
select: {
windowStart: true,
windowEnd: true,
},
},
},
}),
]);
let medicationCompliance30: number[] = [];
let medicationCompliance30Previous: number[] = [];
if (medications.length > 0) {
const medIds = medications.map((m) => m.id);
const intakeEvents = await prisma.medicationIntakeEvent.findMany({
where: {
userId,
medicationId: { in: medIds },
scheduledFor: { gte: prevSince30d, lte: now },
},
select: {
medicationId: true,
scheduledFor: true,
takenAt: true,
skipped: true,
},
});
const eventsByMed = new Map<string, typeof intakeEvents>();
for (const ev of intakeEvents) {
const list = eventsByMed.get(ev.medicationId);
if (list) list.push(ev);
else eventsByMed.set(ev.medicationId, [ev]);
}
medicationCompliance30 = medications.map((med) => {
const events = eventsByMed.get(med.id) ?? [];
return calculateCompliance(events, med.schedules, 30, med.createdAt).rate;
});
medicationCompliance30Previous = medications.map((med) => {
const events = (eventsByMed.get(med.id) ?? []).filter(
(e) => e.scheduledFor <= prevUntil,
);
// Shift forward by 7 days so the helper's `now` anchor still
// captures the same logical 30 days (pre-v1.4.37 behaviour).
const shifted = events.map((e) => ({
scheduledFor: new Date(e.scheduledFor.getTime() + 7 * DAY_MS),
takenAt: e.takenAt ? new Date(e.takenAt.getTime() + 7 * DAY_MS) : null,
skipped: e.skipped,
}));
return calculateCompliance(shifted, med.schedules, 30, med.createdAt)
.rate;
});
}
const fallbackTarget = defaultWeightTargetFromHeight(heightCm);
const moodSeriesLast30d = moodRows
.filter((r) => r.moodLoggedAt >= since30d)
.map((r) => ({
date: r.moodLoggedAt.toISOString(),
score: r.score,
}));
const moodSeriesPrev30d = moodRows
.filter(
(r) => r.moodLoggedAt >= prevSince30d && r.moodLoggedAt <= prevUntil,
)
.map((r) => ({
date: r.moodLoggedAt.toISOString(),
score: r.score,
}));
// Empty-path early-out — nothing computable, hero hides cleanly.
if (
bpInTargetPct === null &&
weightSeriesLast30d.length === 0 &&
moodSeriesLast30d.length === 0 &&
medicationCompliance30.length === 0
) {
annotate({
meta: {
healthScore: {
score: null,
reason: "no_components_available",
path: weightCovered ? "rollup" : "live",
},
},
});
return null;
}
const windowEndAt = now.toISOString();
const bpSourceTokens = uniqueComponentSources(
bpSysRowsForSource.map((r) => r.source),
);
const latestBpInWindow = bpSysRowsForSource.at(-1);
// Mood doesn't yet have a non-manual ingest (v1.5 will introduce
// Apple Health mood) — preserve the manual-only contract.
const moodSourceTokens =
moodSeriesLast30d.length > 0 ? (["manual"] as const) : [];
const latestMoodInWindow = moodRows
.filter((r) => r.moodLoggedAt >= since30d)
.at(-1);
const complianceSourceTokens =
medicationCompliance30.length > 0 ? (["manual"] as const) : [];
const current: HealthScoreInput = {
bpInTargetRate: bpInTargetPct,
weightSeriesLast30d,
weightTargetKg: fallbackTarget,
moodEntriesLast30d: moodSeriesLast30d,
medicationCompliance30,
attribution: {
bpSources: bpSourceTokens,
asOfBp: latestBpInWindow?.measuredAt.toISOString() ?? null,
weightSources: weightSourcesIn30d,
asOfWeight: latestWeightAsOf,
moodSources: moodSourceTokens,
asOfMood: latestMoodInWindow?.moodLoggedAt.toISOString() ?? null,
complianceSources: complianceSourceTokens,
asOfCompliance: complianceSourceTokens.length > 0 ? windowEndAt : null,
windowEndAt,
},
};
// Previous-window snapshot — same logic, prior-week-shifted series.
// The bpInTargetPct stays pinned to the current value because the
// route does not pay for a second historical pair-search; the delta
// reflects week-over-week movement in the weight / mood / compliance
// pillars only.
const previous: HealthScoreInput = {
bpInTargetRate: bpInTargetPct,
weightSeriesLast30d: weightSeriesPrev30d,
weightTargetKg: fallbackTarget,
moodEntriesLast30d: moodSeriesPrev30d,
medicationCompliance30: medicationCompliance30Previous,
};
const result = computeHealthScore(current, previous);
annotate({
meta: {
healthScore: {
score: result.score,
band: result.band,
delta: result.delta,
path: weightCovered ? "rollup" : "live",
},
},
});
return result;
}
+62 -36
View File
@@ -75,12 +75,41 @@ export async function safeJson<T = unknown>(
* observed when the request arrived.
* - "N" (>1) → trust N hops; read the Nth-from-rightmost XFF entry.
*
* Cloudflare opt-in (`TRUST_CF_CONNECTING_IP=1`): when the env flag is
* set, the helper prefers the `cf-connecting-ip` header before walking
* the XFF chain. Cloudflare strips and re-sets this header on every
* request that lands on its edge, so it carries the real visitor IP
* even when XFF/x-real-ip end up as the Coolify proxy's loopback
* address. The flag is OFF by default: a self-hosted deployment
* without Cloudflare in front would otherwise trust an attacker-set
* header on the public internet.
*
* Returns the resolved IP or null when no trusted source is available.
*/
function looksLikeIp(s: string): boolean {
return /^[0-9a-fA-F.:]+$/.test(s) && s.length >= 3 && s.length <= 45;
}
/**
* v1.4.37 — Cloudflare puts the visitor IP into `cf-connecting-ip` on
* every request hitting the edge. The Coolify-fronted HealthLog stack
* sits behind Cloudflare; without consulting this header, every
* `getClientIp` caller landed with the Caddy loopback IP and the geo
* resolver had no signal to backfill the admin sign-in overview from.
*
* The header is honoured only when `TRUST_CF_CONNECTING_IP=1`. A
* self-hosted deployment without Cloudflare in front must NOT trust
* the header — any attacker can set it on a direct request and the
* downstream geo resolver would happily report a forged location.
*/
function readCfConnectingIp(request: Request): string | null {
if (process.env.TRUST_CF_CONNECTING_IP !== "1") return null;
const candidate = request.headers.get("cf-connecting-ip");
if (!candidate) return null;
const trimmed = candidate.trim();
return looksLikeIp(trimmed) ? trimmed : null;
}
function parseTrustProxyHops(raw: string | undefined): number {
if (raw === undefined) return 1;
const trimmed = raw.trim();
@@ -123,7 +152,34 @@ function warnTrustViolationOnce(hops: number, chainLength: number): void {
);
}
export function getClientIp(request: Request): string | null {
/**
* Tagged return shape so a caller can apply a tighter universal
* rate-limit when the trust chain is misconfigured. F-6 (mobile security
* audit, 2026-05-16): callers today fall back to a literal `"unknown"`
* string, collapsing every anonymous request into one bucket. New
* callers should branch on `trustViolation === true` and route the
* request to a tighter global rate-limit instead of the per-IP one.
*
* Existing callers using `getClientIp(request) ?? "unknown"` keep
* working unchanged; this helper is additive.
*
* v1.4.37 — also the single resolver for the CF / XFF / x-real-ip
* ladder. `getClientIp` projects this helper's `.ip` so the rotation-
* attack guard, the Cloudflare opt-in and the one-shot trust-violation
* warning live in one place.
*/
export function getClientIpOrTrustWarning(request: Request): {
ip: string | null;
trustViolation: boolean;
} {
// v1.4.37 — Cloudflare's `cf-connecting-ip` takes precedence when
// the env flag opts in. The header is operator-controlled (Cloudflare
// re-sets it on every request hitting its edge) so trusting it
// bypasses the XFF trust-violation accounting entirely — there is no
// chain to violate.
const cfIp = readCfConnectingIp(request);
if (cfIp) return { ip: cfIp, trustViolation: false };
const hops = parseTrustProxyHops(process.env.TRUST_PROXY_HOPS);
if (hops > 0) {
@@ -139,47 +195,13 @@ export function getClientIp(request: Request): string | null {
// attacker-controlled) entry would re-introduce the very rotation
// attack TRUST_PROXY_HOPS was meant to close. Refuse to read XFF.
if (chain.length >= hops) {
return chain[chain.length - hops];
return { ip: chain[chain.length - hops], trustViolation: false };
}
// F-6 (mobile security audit, 2026-05-16): emit a one-shot
// operator signal when the chain shape doesn't match the
// configured trust. Without this warning the silent degrade was
// invisible until rate-limits visibly misfired in production.
warnTrustViolationOnce(hops, chain.length);
}
}
const realIp = request.headers.get("x-real-ip");
return realIp && looksLikeIp(realIp) ? realIp : null;
}
/**
* Tagged return shape so a caller can apply a tighter universal
* rate-limit when the trust chain is misconfigured. F-6 (mobile security
* audit, 2026-05-16): callers today fall back to a literal `"unknown"`
* string, collapsing every anonymous request into one bucket. New
* callers should branch on `trustViolation === true` and route the
* request to a tighter global rate-limit instead of the per-IP one.
*
* Existing callers using `getClientIp(request) ?? "unknown"` keep
* working unchanged; this helper is additive.
*/
export function getClientIpOrTrustWarning(request: Request): {
ip: string | null;
trustViolation: boolean;
} {
const hops = parseTrustProxyHops(process.env.TRUST_PROXY_HOPS);
if (hops > 0) {
const forwarded = request.headers.get("x-forwarded-for");
if (forwarded) {
const chain = forwarded
.split(",")
.map((s) => s.trim())
.filter(looksLikeIp);
if (chain.length >= hops) {
return { ip: chain[chain.length - hops], trustViolation: false };
}
warnTrustViolationOnce(hops, chain.length);
const realIp = request.headers.get("x-real-ip");
return {
ip: realIp && looksLikeIp(realIp) ? realIp : null,
@@ -193,3 +215,7 @@ export function getClientIpOrTrustWarning(request: Request): {
trustViolation: false,
};
}
export function getClientIp(request: Request): string | null {
return getClientIpOrTrustWarning(request).ip;
}
@@ -0,0 +1,216 @@
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { CoachLaunchProvider } from "@/lib/insights/coach-launch-context";
import type { AssistantFlagSet } from "@/hooks/use-feature-flags";
import { HeroStrip } from "@/components/insights/hero-strip";
import { SuggestedPrompts } from "@/components/insights/suggested-prompts";
import { CoachLaunchButton } from "@/components/insights/coach-launch-button";
import { LayoutCoachFab } from "@/components/insights/layout-coach-fab";
import { LayoutCoachMount } from "@/components/insights/layout-coach-mount";
/**
* v1.4.37 W5 — Coach disable cascade invariant.
*
* Marc directive: when the operator turns the global Coach flag off,
* every Coach affordance on every surface must vanish — no
* grey-out, no error, no inert button, no DOM trace. The web app
* gates each surface via `useFeatureFlags()` and a `flags.coach`
* short-circuit; the invariant below pins the contract so a future
* surface addition can't silently leak the affordance.
*
* How to extend: when a new Coach-bearing surface lands (button,
* drawer, chip strip, FAB, inline pill), add an entry to the
* `COACH_SURFACES` fixture below and bump the `expect(... .length)`
* count in the trailing sync-check. The contract per surface is
* "renders nothing measurable in the SSR output when the Coach flag
* is off"; surfaces that need data-slot probes should expose a
* stable `data-slot="coach-*"` attribute the test can grep.
*
* The hook layer is covered by `src/hooks/__tests__/
* use-feature-flags.test.tsx`; this file is the integration-style
* contract that walks each surface and asserts the gate is present.
*/
/**
* Build a QueryClient pre-seeded with the operator's flag matrix so
* every `useFeatureFlags()` consumer reads the supplied set
* synchronously during the SSR pass (no fetch round-trip required).
*/
function buildClient(flags: Partial<AssistantFlagSet>): QueryClient {
const client = new QueryClient({
defaultOptions: { queries: { retry: 0 } },
});
client.setQueryData(["feature-flags"], {
assistant: {
enabled: true,
coach: true,
briefing: true,
insightStatus: true,
correlations: true,
healthScoreExplainer: true,
...flags,
},
});
return client;
}
function renderWithFlags(node: React.ReactNode, coach: boolean): string {
const client = buildClient({ coach });
return renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">{node}</I18nProvider>
</QueryClientProvider>,
);
}
// ────────────────────────────────────────────────────────────────────
// Coach-bearing surface fixture.
//
// Each entry mounts the surface in isolation, supplies the minimum
// non-Coach scaffolding the component needs (CoachLaunchProvider, …)
// and exposes a stable substring that proves the surface painted. The
// substring should be unique enough that a "did not render" check is
// meaningful — typically the surface's `data-slot="coach-*"`
// attribute or its localised label.
//
// IMPORTANT: when adding a new Coach surface to the codebase, add a
// matching entry here. The test below walks every entry and asserts
// the surface vanishes when the operator's global Coach flag is off.
// ────────────────────────────────────────────────────────────────────
interface CoachSurface {
/** Human-readable description that surfaces in the test output. */
name: string;
/** Mounts the surface in isolation. Receives no props. */
mount: () => React.ReactNode;
/**
* Substring that proves the surface painted when the flag is ON.
* Empty string means "the surface's SSR shape is intentionally
* blank even with the flag on" (e.g. lazy-loaded subtrees); the
* positive-case test is skipped while the negative-case
* `coach-*` slot grep still pins the gate.
*/
proofWhenOn: string;
}
const COACH_SURFACES: CoachSurface[] = [
{
name: "HeroStrip action-row 'Ask the coach' button",
mount: () => (
<HeroStrip
briefing={null}
now={new Date(2026, 4, 10, 9, 0, 0)}
onAskCoach={() => undefined}
/>
),
proofWhenOn: 'data-slot="insights-hero-strip-action-coach"',
},
{
name: "HeroStrip SuggestedPrompts chip strip",
mount: () => (
<HeroStrip
briefing={null}
now={new Date(2026, 4, 10, 9, 0, 0)}
onPickPrompt={() => undefined}
/>
),
proofWhenOn: 'data-slot="insights-hero-strip-prompts"',
},
{
name: "SuggestedPrompts standalone",
mount: () => <SuggestedPrompts onPick={() => undefined} />,
proofWhenOn: 'data-slot="insights-suggested-prompts"',
},
{
name: "CoachLaunchButton inline pill",
mount: () => (
// The button only renders inside <CoachLaunchProvider>; wrap so
// the Coach-flag-off branch is the dispositive guard.
<CoachLaunchProvider>
<CoachLaunchButton />
</CoachLaunchProvider>
),
proofWhenOn: 'data-slot="coach-launch-inline"',
},
{
name: "LayoutCoachFab sticky mobile button",
mount: () => (
<CoachLaunchProvider>
<LayoutCoachFab />
</CoachLaunchProvider>
),
proofWhenOn: 'data-slot="coach-launch-fab"',
},
{
name: "LayoutCoachMount drawer subtree",
mount: () => (
<CoachLaunchProvider>
<LayoutCoachMount />
</CoachLaunchProvider>
),
// The drawer is lazy-loaded via next/dynamic and SSRs to nothing
// even when the flag is on; the contract here is "no Coach-marked
// mount point ever paints when the flag is off". Skip the proof
// check; the negative `coach-*` slot grep still pins the gate.
proofWhenOn: "",
},
];
describe("Coach disable cascade invariant", () => {
// Silence the dev-only "should not be used during SSR" warning some
// components emit when their effects would normally mount.
beforeEach(() => {
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "warn").mockImplementation(() => undefined);
});
for (const surface of COACH_SURFACES) {
it(`${surface.name} — paints when the Coach flag is on`, () => {
// Skip the positive proof for surfaces whose SSR shape is
// intentionally empty (lazy-loaded drawer subtrees). The
// negative assertion below still pins the gate.
if (!surface.proofWhenOn) return;
const html = renderWithFlags(surface.mount(), true);
expect(html).toContain(surface.proofWhenOn);
});
it(`${surface.name} — vanishes when the Coach flag is off`, () => {
const html = renderWithFlags(surface.mount(), false);
if (surface.proofWhenOn) {
expect(html).not.toContain(surface.proofWhenOn);
}
// Every Coach-bearing surface in the app marks its mount point
// with a `coach-` slot. Pin the negative shape against the
// shared prefix so a surface that grows a new `coach-*` slot
// without a gate fails this test by default.
expect(html).not.toMatch(/data-slot="coach-[a-z]/);
// The suggested-prompts strip uses an `insights-suggested-prompts`
// slot (legacy naming pre-dates the `coach-` convention); pin
// it explicitly so the gate can't regress.
expect(html).not.toContain('data-slot="insights-suggested-prompts"');
// Same story for the hero strip's coach action button + prompts
// wrapper.
expect(html).not.toContain(
'data-slot="insights-hero-strip-action-coach"',
);
expect(html).not.toContain('data-slot="insights-hero-strip-prompts"');
});
}
it("fixture stays in sync with the Coach gate call sites", () => {
// Counts the Coach-bearing surfaces the fixture knows about. If a
// contributor adds a new `useFeatureFlags()` + `flags.coach` gate
// to a render path, the count below must move and this assertion
// forces them to revisit the fixture. The number tracks the
// surfaces the fixture mounts directly; cross-cut gates on
// sub-pages (target-card, /targets page) are owned by other
// invariants (`targets-coach-mount.test.tsx`,
// `target-card.test.tsx`).
expect(COACH_SURFACES.length).toBe(6);
});
});
@@ -79,6 +79,126 @@ describe("generateBmiStatusForUser — v1.4.6 bucketed payload", () => {
});
});
describe("generateBmiStatusForUser — v1.4.37 timeout-stub persistence", () => {
it("persists a sentinel row keyed to today when the provider times out", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
heightCm: 175,
} as never);
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(null);
vi.mocked(prisma.measurement.findMany).mockResolvedValue([
{ value: 80, measuredAt: new Date() },
] as never);
vi.mocked(prisma.auditLog.create).mockResolvedValue({
createdAt: new Date(),
} as never);
// Simulate a provider that never resolves before the timeout. The
// helper races the call against `STATUS_PROVIDER_TIMEOUT_MS`; a
// promise that hangs forever cuts the race short.
vi.mocked(resolveProvider).mockResolvedValue({
type: "anthropic",
generateCompletion: vi.fn(
() => new Promise(() => {
/* never resolves */
}),
),
} as never);
// Shrink the timeout window so this test does not hang the suite
// for the full 20 s. The withTimeout helper polls in ~1 s
// increments; this still exercises the same race shape.
vi.useFakeTimers();
const promise = generateBmiStatusForUser("user-1", { locale: "en" });
await vi.advanceTimersByTimeAsync(25_000);
const result = await promise;
vi.useRealTimers();
// The user-facing payload still reads the deterministic no-key
// fallback, but the cached/updatedAt fields signal "this is a
// stub" so the next mount short-circuits at the cache lookup.
expect(result.text).toBeTruthy();
expect(result.cached).toBe(true);
expect(result.updatedAt).toBeTruthy();
const createCalls = vi.mocked(prisma.auditLog.create).mock.calls;
expect(createCalls.length).toBe(1);
const details = (createCalls[0][0] as { data: { details: string } }).data
.details;
const parsed = JSON.parse(details) as {
dateKey?: string;
text?: string;
timeout?: boolean;
model?: string;
};
expect(parsed.text).toBeTruthy();
expect(parsed.timeout).toBe(true);
expect(parsed.model).toBe("timeout-stub");
// The dateKey must read as a valid YYYY-MM-DD so the cache hit
// logic on the next mount matches against today's berlin key.
expect(parsed.dateKey).toMatch(/^\d{4}-\d{2}-\d{2}$/);
});
it("subsequent mounts short-circuit at the cache lookup and skip the race", async () => {
// First mount: cache miss, provider times out, stub persisted.
// Simulate that prior state by handing back the stub row from
// findFirst on the second invocation.
const stubRow = {
createdAt: new Date(),
details: JSON.stringify({
dateKey: new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
})
.formatToParts(new Date())
.reduce<Record<string, string>>((acc, p) => {
if (p.type !== "literal") acc[p.type] = p.value;
return acc;
}, {}),
locale: "en",
text: "BMI is a directional metric…",
timeout: true,
}),
};
// Build a real YYYY-MM-DD string the same way the source helper
// does so the cache-key match is exact.
const parts = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(new Date());
const y = parts.find((p) => p.type === "year")!.value;
const m = parts.find((p) => p.type === "month")!.value;
const d = parts.find((p) => p.type === "day")!.value;
const todayKey = `${y}-${m}-${d}`;
stubRow.details = JSON.stringify({
dateKey: todayKey,
locale: "en",
text: "BMI is a directional metric…",
timeout: true,
});
vi.mocked(prisma.auditLog.findFirst).mockResolvedValue(stubRow as never);
const providerCall = vi.fn();
vi.mocked(resolveProvider).mockResolvedValue({
type: "anthropic",
generateCompletion: providerCall,
} as never);
const result = await generateBmiStatusForUser("user-1", { locale: "en" });
// Cache short-circuit fires before the provider call — no race,
// no second persist.
expect(providerCall).not.toHaveBeenCalled();
expect(result.text).toBe("BMI is a directional metric…");
expect(result.cached).toBe(true);
expect(result.updatedAt).toBe(stubRow.createdAt.toISOString());
expect(prisma.auditLog.create).not.toHaveBeenCalled();
});
});
describe("generateBmiStatusForUser — token-leak hardening (v1.4.27 F16)", () => {
it("strips metric: tokens out of the cached text before persisting", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
+29 -19
View File
@@ -126,26 +126,36 @@ describe("extractFeatures — v1.4.36 W3 bucketed payload", () => {
expect(features.context.ageYears).toBeGreaterThan(40);
});
it("throws FeaturesPayloadTooLargeError when the serialised payload exceeds the 5 MB cap", async () => {
// Fabricate an absurdly long bucket list so the JSON dump crosses
// the ceiling. ~200 KB per series × 28 series ≈ ~5.6 MB.
const giant = new Array(200_000).fill(null).map((_, i) => ({
bucketStart: new Date(Date.now() - i * dayMs),
count: i,
mean: i,
minValue: i,
maxValue: i,
sd: 0,
slope: 0,
r2: 0,
computedAt: new Date(),
}));
prismaMock.measurementRollup.findMany.mockResolvedValue(giant);
// Constructs a ~5.6 MB rollup payload and runs the whole serialiser
// pipeline; the slower GitHub-Actions runners cross the default 5 s
// budget. Raise this single test only — the rest of the suite stays
// on the default timeout. Vitest 4 takes the timeout as a numeric
// second argument (the old `it(name, fn, options)` signature was
// removed in v4).
it(
"throws FeaturesPayloadTooLargeError when the serialised payload exceeds the 5 MB cap",
{ timeout: 30_000 },
async () => {
// Fabricate an absurdly long bucket list so the JSON dump crosses
// the ceiling. ~200 KB per series × 28 series ≈ ~5.6 MB.
const giant = new Array(200_000).fill(null).map((_, i) => ({
bucketStart: new Date(Date.now() - i * dayMs),
count: i,
mean: i,
minValue: i,
maxValue: i,
sd: 0,
slope: 0,
r2: 0,
computedAt: new Date(),
}));
prismaMock.measurementRollup.findMany.mockResolvedValue(giant);
await expect(extractFeatures("user-1", true)).rejects.toThrow(
FeaturesPayloadTooLargeError,
);
});
await expect(extractFeatures("user-1", true)).rejects.toThrow(
FeaturesPayloadTooLargeError,
);
},
);
it("exposes the size cap as a public constant", () => {
expect(FEATURES_MAX_BYTES).toBe(5 * 1024 * 1024);
+42 -2
View File
@@ -291,11 +291,51 @@ export async function generateBmiStatusForUser(
);
if (raced.timedOut || raced.value === null) {
// v1.4.37 — persist a sentinel row keyed to today so the next
// mount short-circuits at the cache lookup above instead of
// re-racing the same 20 s provider call on every cold visit.
// Without this, a single stall (provider hiccup, network blip,
// model warm-up) leaves the user staring at the loading state
// on every reload until the daily 02:20 pre-warm job runs.
// The body is the same no-key fallback the caller returned
// before, so the user-facing UI is identical; only the
// re-fire frequency drops to zero for the rest of the day.
// `meta.timeout` is set so the daily pg-boss pre-warm worker
// (the same job that originally seeded the cache) can
// recognise and overwrite the stub rather than respect it as
// a real assessment.
const stubText = getNoKeyBmiStatusText(locale);
let stubUpdatedAt: string | null = null;
try {
const stub = await prisma.auditLog.create({
data: {
userId,
action: cacheAction,
details: JSON.stringify({
dateKey: todayKey,
locale,
text: stubText,
providerType: provider.type,
model: "timeout-stub",
tokensUsed: null,
timeout: true,
}),
},
select: { createdAt: true },
});
stubUpdatedAt = stub.createdAt.toISOString();
} catch {
// The persist is best-effort — if the row write fails the
// caller still sees the deterministic fallback text and the
// next mount falls back to the (still expensive) race. Do
// not surface the error: the user does not care that the
// cache write missed, only that the page rendered.
}
return {
hasProvider: true,
text: getNoKeyBmiStatusText(locale),
text: stubText,
cached: true,
updatedAt: null,
updatedAt: stubUpdatedAt,
};
}
@@ -0,0 +1,64 @@
/**
* v1.4.37 W7c — pg-boss queue registration for the nightly drain of
* per-sample APPLE_HEALTH cumulative rows. The drain helper exists
* since v1.4.30 but only ran via the admin endpoint / CLI; the
* scheduled wrapper closes the loop so the list view stops painting
* hundreds of step chunks per day.
*
* Same source-text-grep approach as the Withings queue regression
* guard so we never have to boot pg-boss + Prisma to assert the
* scheduler wiring stays intact.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
const REMINDER_WORKER_PATH = join(__dirname, "..", "reminder-worker.ts");
const source = readFileSync(REMINDER_WORKER_PATH, "utf8");
describe("reminder-worker — drainPerSampleCumulative nightly schedule", () => {
it("declares the drain queue at the documented Berlin cadence", () => {
expect(source).toMatch(
/DRAIN_CUMULATIVE_QUEUE\s*=\s*["']drain-per-sample-cumulative["']/,
);
// 03:45 Europe/Berlin — between audit-log cleanup (03:15) and the
// feedback aggregator (04:00). Keep the slot stable so an operator
// staring at the cron table can find the job easily.
expect(source).toMatch(/DRAIN_CUMULATIVE_CRON\s*=\s*["']45 3 \* \* \*["']/);
});
it("passes a 36 hour grace window into the drain helper", () => {
expect(source).toMatch(/DRAIN_CUMULATIVE_CUTOFF_HOURS\s*=\s*36/);
expect(source).toMatch(/cutoffHours:\s*DRAIN_CUMULATIVE_CUTOFF_HOURS/);
});
it("imports drainPerSampleCumulative from the existing helper module", () => {
expect(source).toMatch(
/import\s*\{\s*drainPerSampleCumulative\s*\}\s*from\s*["']@\/lib\/measurements\/drain-per-sample-cumulative["']/,
);
});
it("registers a boss.work handler against the drain queue", () => {
expect(source).toMatch(
/boss\.work[\s\S]{0,200}DRAIN_CUMULATIVE_QUEUE[\s\S]{0,400}drainPerSampleCumulative/,
);
});
it("schedules the drain cron via boss.schedule (allQueues + schedules)", () => {
expect(source).toMatch(
/\[DRAIN_CUMULATIVE_QUEUE,\s*DRAIN_CUMULATIVE_CRON\]/,
);
});
it("registers the drain queue in the allQueues createQueue loop", () => {
// pg-boss v12 requires explicit createQueue before scheduling. The
// allQueues array drives the boot-time `for (const q of allQueues)`
// loop; missing the entry silently no-ops the schedule below.
const allQueuesMatch = source.match(
/const allQueues\s*=\s*\[([\s\S]*?)\];/,
);
expect(allQueuesMatch).not.toBeNull();
expect(allQueuesMatch![1]).toMatch(/\bDRAIN_CUMULATIVE_QUEUE\b/);
});
});
@@ -8,6 +8,8 @@ vi.mock("@/lib/geo", () => ({
import {
GEO_BACKFILL_BATCH_CAP,
GEO_BACKFILL_CRON,
GEO_BACKFILL_QUEUE,
GEO_BACKFILL_WINDOW_DAYS,
runGeoBackfill,
} from "../geo-backfill";
@@ -217,3 +219,39 @@ describe("runGeoBackfill", () => {
expect(prisma.auditLog.update).not.toHaveBeenCalled();
});
});
/**
* v1.4.37 — the helper is now scheduled via pg-boss at the hourly
* :40 slot. The schedule constants live in the helper module so the
* reminder-worker boot pulls them by import; this test pins both
* shapes so a regression that drops the cadence or drifts the queue
* name lands here, not in production.
*/
describe("geo-backfill scheduling contract (v1.4.37)", () => {
it("exports the pg-boss queue name", () => {
expect(GEO_BACKFILL_QUEUE).toBe("geo-backfill");
});
it("schedules on the :40 slot every hour to avoid colliding with the existing crons", () => {
expect(GEO_BACKFILL_CRON).toBe("40 * * * *");
});
it("reminder-worker imports both the runner and the schedule constants", async () => {
// Source-text probe avoids importing the worker module (which
// would drag pg-boss + a live Postgres connection). The contract
// is binary: the worker either registers the queue + cron or it
// does not; both presence checks pin the v1.4.37 scheduling
// shape end-to-end.
const fs = await import("node:fs/promises");
const path = await import("node:path");
const workerSrc = await fs.readFile(
path.resolve(__dirname, "..", "reminder-worker.ts"),
"utf-8",
);
expect(workerSrc).toContain(
"import {\n runGeoBackfill,\n GEO_BACKFILL_QUEUE,\n GEO_BACKFILL_CRON,\n} from \"@/lib/jobs/geo-backfill\";",
);
expect(workerSrc).toContain("GEO_BACKFILL_QUEUE, GEO_BACKFILL_CRON");
expect(workerSrc).toContain("handleGeoBackfill");
});
});
+12
View File
@@ -38,6 +38,18 @@ import { lookupIpAsn, lookupIpLocation } from "@/lib/geo";
export const GEO_BACKFILL_BATCH_CAP = 5000;
export const GEO_BACKFILL_WINDOW_DAYS = 30;
/**
* v1.4.37 — pg-boss queue name + cron expression for the recurring
* backfill. Offset to :40 every hour so the schedule does not collide
* with the existing :00 / :15 / :30 Withings + moodlog crons that
* already crowd the top of the hour. The helper is idempotent + the
* batch cap is per-call, so an hourly cadence is the right balance
* between freshness of the admin sign-in "Standort" column and the
* audit-log write budget.
*/
export const GEO_BACKFILL_QUEUE = "geo-backfill";
export const GEO_BACKFILL_CRON = "40 * * * *";
export interface GeoBackfillSummary {
scanned: number;
located: number;
+103
View File
@@ -33,6 +33,11 @@ import { cleanupExpiredIdempotencyKeys } from "@/lib/jobs/idempotency-cleanup";
import { cleanupOldAuditLogs } from "@/lib/jobs/audit-log-cleanup";
import { runHostMetricTick } from "@/lib/jobs/host-metric-sampler";
import { aggregateRecommendationFeedback } from "@/lib/jobs/feedback-aggregator";
import {
runGeoBackfill,
GEO_BACKFILL_QUEUE,
GEO_BACKFILL_CRON,
} from "@/lib/jobs/geo-backfill";
import {
PR_DETECTION_QUEUE,
PR_DETECTION_CONCURRENCY,
@@ -62,6 +67,7 @@ import {
type RollupFullBackfillPayload,
type RollupRecomputePayload,
} from "@/lib/measurements/rollups";
import { drainPerSampleCumulative } from "@/lib/measurements/drain-per-sample-cumulative";
import { expireStaleInUseItems } from "@/lib/medications/inventory/service";
import { rotateLegacyMoodLogSecrets } from "@/lib/moodlog-secret";
import { deleteMessage } from "@/lib/telegram";
@@ -157,6 +163,23 @@ const HOST_METRIC_CRON = "* * * * *";
// audit-log) so the previous-day's noise is gone before we aggregate.
const FEEDBACK_AGGREGATOR_QUEUE = "feedback-aggregator";
const FEEDBACK_AGGREGATOR_CRON = "0 4 * * *";
// v1.4.37 — hourly geo backfill. Queue name + cron expression live
// in `@/lib/jobs/geo-backfill` so a unit test can pin the scheduling
// contract without importing this worker boot file.
// v1.4.37 W7c — nightly drain of per-sample APPLE_HEALTH cumulative
// rows. Collapses each user × cumulative-type × calendar-day bucket
// into one `stats:…` row so the list view stops painting hundreds of
// step chunks per day. 03:45 Europe/Berlin slots in between the
// 03:15 audit-log cleanup and the 04:00 feedback aggregator. The
// 36-hour grace window keeps today + the trailing watch-sync window
// intact for real-time visibility; only completed-and-stable days
// fall to the drain.
const DRAIN_CUMULATIVE_QUEUE = "drain-per-sample-cumulative";
const DRAIN_CUMULATIVE_CRON = "45 3 * * *";
const DRAIN_CUMULATIVE_CUTOFF_HOURS = 36;
interface DrainCumulativePayload {
triggeredAt: string;
}
interface ReminderCheckPayload {
triggeredAt: string;
@@ -248,6 +271,10 @@ interface FeedbackAggregatorPayload {
triggeredAt: string;
}
interface GeoBackfillPayload {
triggeredAt: string;
}
// Re-export timezone utilities under local names for backward compatibility
const getUserTodayBounds = getUserTodayBoundsUtil;
const getDayOfWeekInTz = getDayOfWeekInTzUtil;
@@ -1155,6 +1182,32 @@ async function handleFeedbackAggregator(
});
}
/**
* v1.4.37 — geo-backfill worker. Walks `audit_logs` rows that landed
* with a null `location` (offline MMDB missing at write time, online
* provider unreachable) and re-resolves them through the now-bundled
* resolver chain. The helper is idempotent and capped per pass so
* the hourly cadence cannot starve a live login spike.
*/
async function handleGeoBackfill(jobs: Job<GeoBackfillPayload>[]) {
void jobs;
await withBackgroundEvent("job.geo_backfill", async (evt) => {
const p = getWorkerPrisma();
try {
const summary = await runGeoBackfill(p);
evt.addMeta("geo_backfill_scanned", summary.scanned);
evt.addMeta("geo_backfill_located", summary.located);
evt.addMeta("geo_backfill_carrier_resolved", summary.carrierResolved);
evt.addMeta("geo_backfill_still_unresolved", summary.stillUnresolved);
} catch (err) {
// The admin sign-in overview tolerates a stale Standort cell —
// log and move on so a one-off resolver hiccup does not poison
// the queue and block the next pass.
evt.addWarning(`geo-backfill failed: ${err}`);
}
});
}
async function handlePrDetection(
jobs: Job<PrDetectionPayload | { userId?: undefined }>[],
) {
@@ -1466,11 +1519,17 @@ export async function startReminderWorker() {
OFFHOST_BACKUP_QUEUE,
HOST_METRIC_QUEUE,
FEEDBACK_AGGREGATOR_QUEUE,
GEO_BACKFILL_QUEUE,
PR_DETECTION_QUEUE,
MEDICATION_INVENTORY_EXPIRE_QUEUE,
APPLE_HEALTH_IMPORT_QUEUE,
ROLLUP_RECOMPUTE_QUEUE,
ROLLUP_FULL_BACKFILL_QUEUE,
// v1.4.37 W7c — explicit createQueue is required before the
// nightly schedule below registers (pg-boss v12 contract). Without
// this entry the drain schedule silently no-ops and the
// per-sample APPLE_HEALTH rows never collapse.
DRAIN_CUMULATIVE_QUEUE,
];
for (const q of allQueues) {
@@ -1511,6 +1570,11 @@ export async function startReminderWorker() {
[OFFHOST_BACKUP_QUEUE, OFFHOST_BACKUP_CRON],
[HOST_METRIC_QUEUE, HOST_METRIC_CRON],
[FEEDBACK_AGGREGATOR_QUEUE, FEEDBACK_AGGREGATOR_CRON],
// v1.4.37 — hourly geo backfill. The helper is idempotent + capped
// at 5 000 rows per pass; running it at :40 every hour catches the
// long tail of audit rows that landed with the offline MMDB
// missing or the online provider unreachable.
[GEO_BACKFILL_QUEUE, GEO_BACKFILL_CRON],
// Fallback rescan every 30 minutes — protects against ingest paths
// that ship measurements without enqueueing a per-user job. The
// cron payload deliberately omits a `userId` so the handler iterates
@@ -1522,6 +1586,10 @@ export async function startReminderWorker() {
// EXPIRED at 03:30 Europe/Berlin (in the existing 02:xx–03:xx
// maintenance window, right after idempotency-cleanup).
[MEDICATION_INVENTORY_EXPIRE_QUEUE, MEDICATION_INVENTORY_EXPIRE_CRON],
// v1.4.37 W7c — nightly fold of per-sample APPLE_HEALTH cumulative
// rows into one row per day per type. Slots between the
// audit-log cleanup (03:15) and the feedback aggregator (04:00).
[DRAIN_CUMULATIVE_QUEUE, DRAIN_CUMULATIVE_CRON],
];
for (const [name, cron] of schedules) {
@@ -1624,6 +1692,11 @@ export async function startReminderWorker() {
{ localConcurrency: 1 },
handleFeedbackAggregator,
);
await boss.work<GeoBackfillPayload>(
GEO_BACKFILL_QUEUE,
{ localConcurrency: 1 },
handleGeoBackfill,
);
await boss.work<PrDetectionPayload>(
PR_DETECTION_QUEUE,
{ localConcurrency: PR_DETECTION_CONCURRENCY },
@@ -1691,6 +1764,36 @@ export async function startReminderWorker() {
},
);
// v1.4.37 W7c — nightly drain worker. Walks every user × cumulative
// type and folds per-sample APPLE_HEALTH rows older than the cutoff
// into one `stats:…` row per calendar day. Idempotent — a second run
// collapses zero buckets once every day is in the `stats:` shape.
// Concurrency-1 so the drain never crowds the dashboard request pool
// and a long backfill on Marc's account (300 k+ measurement rows)
// stays a single sequential walk.
await boss.work<DrainCumulativePayload>(
DRAIN_CUMULATIVE_QUEUE,
{ localConcurrency: 1 },
async (jobs) => {
for (const job of jobs) {
try {
const summary = await drainPerSampleCumulative(getWorkerPrisma(), {
dryRun: false,
cutoffHours: DRAIN_CUMULATIVE_CUTOFF_HOURS,
log: (line) => workerLog("info", line),
});
workerLog(
"info",
`[drain-cumulative] triggeredAt=${job.data.triggeredAt} usersScanned=${summary.totals.usersScanned} bucketsCollapsed=${summary.totals.bucketsCollapsed} perSampleRowsDeleted=${summary.totals.perSampleRowsDeleted} dailyRowsUpserted=${summary.totals.dailyRowsUpserted}`,
);
} catch (err) {
recordError();
workerLog("error", "[drain-cumulative] run failed", err);
}
}
},
);
// v1.4.35.1 — fire-and-forget boot-time backfill discovery. Finds
// every user with measurements but no rollup coverage and enqueues
// a full-fold per account. Idempotent across reboots: the discovery
@@ -1,7 +1,10 @@
import { describe, expect, it } from "vitest";
import { SOURCE_PRIORITY_METRIC_KEYS } from "@/lib/validations/source-priority";
import { CUMULATIVE_HK_TYPES } from "../apple-health-mapping";
import {
CUMULATIVE_DAY_SUM_TYPES,
cumulativeMetricKey,
isCumulativeDaySumType,
pickCumulativeDaySum,
} from "../cumulative-day-sum";
@@ -105,3 +108,51 @@ describe("isCumulativeDaySumType", () => {
expect(isCumulativeDaySumType("MOOD")).toBe(false);
});
});
describe("CUMULATIVE_DAY_SUM_TYPES / CUMULATIVE_HK_TYPES parity", () => {
// v1.4.37 W10 — single source of truth. The day-sum array is derived
// from `CUMULATIVE_HK_TYPES` so adding a sixth cumulative HK type to
// the mapping module automatically flows through every downstream
// consumer (analytics route, exports, chart). The set equivalence
// guard pins the contract — divergence is impossible at runtime, but
// a future refactor that flips the derivation back to a literal
// would trip this assertion before shipping.
it("matches CUMULATIVE_HK_TYPES membership exactly", () => {
expect(new Set(CUMULATIVE_DAY_SUM_TYPES)).toEqual(CUMULATIVE_HK_TYPES);
});
});
describe("cumulativeMetricKey", () => {
// v1.4.37 W10 — pinned mapping from MeasurementType →
// SourcePriorityMetricKey for the cumulative analytics fast-path.
// Every member of CUMULATIVE_HK_TYPES must resolve either to a real
// SourcePriorityMetricKey (so the canonical-source picker fires) or
// to `null` (so the picker's no-ladder pass-through branch runs).
// A new cumulative HK type without an explicit map entry falls
// through to the default branch (returns null) — that's the
// intended escape hatch for types like TIME_IN_DAYLIGHT that have
// no clinical competitor; pin the audit here so the operator is
// forced to think about it.
it("returns a known SourcePriorityMetricKey or null for every CUMULATIVE_HK_TYPES member", () => {
const validKeys = new Set<string>(SOURCE_PRIORITY_METRIC_KEYS);
for (const type of CUMULATIVE_HK_TYPES) {
const key = cumulativeMetricKey(type);
if (key !== null) {
expect(validKeys.has(key)).toBe(true);
}
}
});
it("explicitly maps the four metrics that own a SourcePriorityMetricKey ladder", () => {
expect(cumulativeMetricKey("ACTIVITY_STEPS")).toBe("steps");
expect(cumulativeMetricKey("ACTIVE_ENERGY_BURNED")).toBe("activeEnergy");
expect(cumulativeMetricKey("WALKING_RUNNING_DISTANCE")).toBe(
"walkingRunningDistance",
);
expect(cumulativeMetricKey("FLIGHTS_CLIMBED")).toBe("flightsClimbed");
});
it("returns null for TIME_IN_DAYLIGHT (no clinical competitor today)", () => {
expect(cumulativeMetricKey("TIME_IN_DAYLIGHT")).toBeNull();
});
});
@@ -1,11 +1,15 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import {
bucketRowsByUserDay,
canonicalDailyTimestamp,
dayKeyForUserTz,
drainPerSampleCumulative,
localDayWindow,
localStartOfDay,
sumBucketValues,
} from "../drain-per-sample-cumulative";
import type { PrismaClient } from "@/generated/prisma/client";
describe("dayKeyForUserTz", () => {
it("anchors the calendar day to the user's IANA zone", () => {
@@ -55,6 +59,94 @@ describe("canonicalDailyTimestamp", () => {
});
});
describe("localStartOfDay", () => {
// v1.4.37 W10 — local 00:00 resolution for any IANA zone. Used by
// the W7c drill-down to anchor the per-day UTC window.
it("returns Berlin 00:00 CET in winter (UTC+1)", () => {
// 2026-01-15 00:00 CET = 2026-01-14 23:00 UTC.
const ts = localStartOfDay("2026-01-15", "Europe/Berlin");
expect(ts.toISOString()).toBe("2026-01-14T23:00:00.000Z");
});
it("returns Berlin 00:00 CEST in summer (UTC+2)", () => {
// 2026-05-16 00:00 CEST = 2026-05-15 22:00 UTC.
const ts = localStartOfDay("2026-05-16", "Europe/Berlin");
expect(ts.toISOString()).toBe("2026-05-15T22:00:00.000Z");
});
it("returns plain UTC midnight for tz=UTC", () => {
const ts = localStartOfDay("2026-05-16", "UTC");
expect(ts.toISOString()).toBe("2026-05-16T00:00:00.000Z");
});
it("handles half-hour-offset zones (Asia/Kolkata UTC+5:30)", () => {
// 2026-05-16 00:00 IST = 2026-05-15 18:30 UTC.
const ts = localStartOfDay("2026-05-16", "Asia/Kolkata");
expect(ts.toISOString()).toBe("2026-05-15T18:30:00.000Z");
});
});
describe("localDayWindow — DST-aware [dayStart, dayEnd) drill-down bounds", () => {
// v1.4.37 W10 H-1 — the previous `canonicalDailyTimestamp ± 12h`
// shape silently leaked or hid an hour of samples on the two days
// per year when Europe/Berlin (and every other DST-observing IANA
// zone) transitions. `localDayWindow` walks the day's true local
// 00:00 → next-day 00:00 boundary so the window covers the right
// 23 / 24 / 25-hour span.
it("spring-forward day (Berlin 2025-03-30) is exactly 23 hours wide", () => {
const { dayStart, dayEnd } = localDayWindow(
"2025-03-30",
"Europe/Berlin",
);
// 2025-03-30 00:00 CET = 2025-03-29 23:00 UTC.
// 2025-03-31 00:00 CEST = 2025-03-30 22:00 UTC.
expect(dayStart.toISOString()).toBe("2025-03-29T23:00:00.000Z");
expect(dayEnd.toISOString()).toBe("2025-03-30T22:00:00.000Z");
expect(dayEnd.getTime() - dayStart.getTime()).toBe(23 * 60 * 60 * 1000);
});
it("fall-back day (Berlin 2025-10-26) is exactly 25 hours wide", () => {
const { dayStart, dayEnd } = localDayWindow(
"2025-10-26",
"Europe/Berlin",
);
// 2025-10-26 00:00 CEST = 2025-10-25 22:00 UTC.
// 2025-10-27 00:00 CET = 2025-10-26 23:00 UTC.
expect(dayStart.toISOString()).toBe("2025-10-25T22:00:00.000Z");
expect(dayEnd.toISOString()).toBe("2025-10-26T23:00:00.000Z");
expect(dayEnd.getTime() - dayStart.getTime()).toBe(25 * 60 * 60 * 1000);
});
it("regular day is exactly 24 hours wide", () => {
const { dayStart, dayEnd } = localDayWindow(
"2026-05-16",
"Europe/Berlin",
);
expect(dayEnd.getTime() - dayStart.getTime()).toBe(24 * 60 * 60 * 1000);
});
it("crosses a month boundary cleanly (2026-05-31 → 2026-06-01)", () => {
const { dayStart, dayEnd } = localDayWindow(
"2026-05-31",
"Europe/Berlin",
);
expect(dayStart.toISOString()).toBe("2026-05-30T22:00:00.000Z");
expect(dayEnd.toISOString()).toBe("2026-05-31T22:00:00.000Z");
});
it("crosses a year boundary cleanly (2025-12-31 → 2026-01-01)", () => {
const { dayStart, dayEnd } = localDayWindow(
"2025-12-31",
"Europe/Berlin",
);
// Berlin in December is CET (UTC+1).
expect(dayStart.toISOString()).toBe("2025-12-30T23:00:00.000Z");
expect(dayEnd.toISOString()).toBe("2025-12-31T23:00:00.000Z");
});
});
describe("bucketRowsByUserDay", () => {
it("groups per-sample rows by the user's calendar day", () => {
const rows = [
@@ -152,3 +244,83 @@ describe("sumBucketValues", () => {
expect(sumBucketValues(rows)).toBeCloseTo(20.0);
});
});
// v1.4.37 W7c — the scheduled nightly drain passes a 36 h grace
// window so today + the trailing watch-sync reconciliation period
// stay per-sample for the list view. The test below pins that the
// cutoffHours option filters by `measuredAt: { lt: cutoff }` rather
// than collapsing every row in sight.
describe("drainPerSampleCumulative — cutoffHours", () => {
function buildPrismaMock() {
const findManyUser = vi.fn();
const findManyMeasurement = vi.fn().mockResolvedValue([]);
return {
user: { findMany: findManyUser },
measurement: { findMany: findManyMeasurement },
$transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) =>
cb({}),
),
} as unknown as PrismaClient & {
user: { findMany: ReturnType<typeof vi.fn> };
measurement: { findMany: ReturnType<typeof vi.fn> };
};
}
it("passes a measuredAt cutoff into the per-sample findMany when cutoffHours is set", async () => {
const prismaMock = buildPrismaMock();
prismaMock.user.findMany.mockResolvedValue([
{ id: "user-1", timezone: "Europe/Berlin" },
]);
const beforeAt = Date.now();
await drainPerSampleCumulative(prismaMock, {
cutoffHours: 36,
log: () => {},
});
const afterAt = Date.now();
// The helper iterates every cumulative type — assert the first
// findMany call carries the expected cutoff filter shape.
const call = prismaMock.measurement.findMany.mock.calls[0]?.[0];
expect(call).toBeDefined();
expect(call.where.source).toBe("APPLE_HEALTH");
expect(call.where.measuredAt?.lt).toBeInstanceOf(Date);
const cutoff = call.where.measuredAt!.lt as Date;
const expectedMin = beforeAt - 36 * 60 * 60 * 1000;
const expectedMax = afterAt - 36 * 60 * 60 * 1000;
expect(cutoff.getTime()).toBeGreaterThanOrEqual(expectedMin);
expect(cutoff.getTime()).toBeLessThanOrEqual(expectedMax);
});
it("omits the cutoff filter when cutoffHours is not provided (CLI / admin one-shot)", async () => {
const prismaMock = buildPrismaMock();
prismaMock.user.findMany.mockResolvedValue([
{ id: "user-1", timezone: "Europe/Berlin" },
]);
await drainPerSampleCumulative(prismaMock, { log: () => {} });
const call = prismaMock.measurement.findMany.mock.calls[0]?.[0];
expect(call).toBeDefined();
expect(call.where.source).toBe("APPLE_HEALTH");
// Legacy callers (CLI, admin endpoint) must keep the all-rows
// behaviour so a backfill drains everything the operator asked for.
expect(call.where.measuredAt).toBeUndefined();
});
it("ignores a zero cutoffHours value (treat 0 as not-set)", async () => {
const prismaMock = buildPrismaMock();
prismaMock.user.findMany.mockResolvedValue([
{ id: "user-1", timezone: "Europe/Berlin" },
]);
await drainPerSampleCumulative(prismaMock, {
cutoffHours: 0,
log: () => {},
});
const call = prismaMock.measurement.findMany.mock.calls[0]?.[0];
expect(call.where.measuredAt).toBeUndefined();
});
});
+54 -12
View File
@@ -62,25 +62,33 @@ export function pickCumulativeDaySum<T extends CumulativeRow>(
return out;
}
import type { MeasurementType } from "@/generated/prisma/client";
import type { SourcePriorityMetricKey } from "@/lib/validations/source-priority";
import { CUMULATIVE_HK_TYPES } from "./apple-health-mapping";
/**
* v1.4.36 W4c — Canonical set of cumulative metric types whose
* dashboard tile should read the *day's sum* and not the latest
* slice. Kept here so the analytics route and any other consumer
* (Coach snapshot, exports) share the same source of truth.
* v1.4.36 W4c / v1.4.37 W10 — Canonical list of cumulative metric
* types whose dashboard tile should read the *day's sum* and not the
* latest slice.
*
* The set lives in `apple-health-mapping.ts` as `CUMULATIVE_HK_TYPES`
* (used by the measurements route + nightly drain + chart). This
* array is the same membership in stable alphabetical order so
* downstream consumers (analytics route, exports) can iterate
* deterministically. The W10 reconcile pass collapses the previously
* duplicated literal to a single derivation so adding a sixth type
* in `apple-health-mapping.ts` automatically flows through every
* cumulative-day-sum consumer.
*
* Note: SLEEP_DURATION is also cumulative but the route handles
* it inline because the picker is the canonical sleep source ladder
* ("sleep" metricKey vs "default"). Once Apple-Health passthrough
* lands and the sleep ladder needs the same shared treatment it can
* fold into this list.
* fold into `CUMULATIVE_HK_TYPES`.
*/
export const CUMULATIVE_DAY_SUM_TYPES = [
"ACTIVITY_STEPS",
"ACTIVE_ENERGY_BURNED",
"WALKING_RUNNING_DISTANCE",
"FLIGHTS_CLIMBED",
"TIME_IN_DAYLIGHT",
] as const;
export const CUMULATIVE_DAY_SUM_TYPES = Array.from(
CUMULATIVE_HK_TYPES,
).sort() as readonly MeasurementType[];
export type CumulativeDaySumType = (typeof CUMULATIVE_DAY_SUM_TYPES)[number];
@@ -89,3 +97,37 @@ export function isCumulativeDaySumType(
): type is CumulativeDaySumType {
return (CUMULATIVE_DAY_SUM_TYPES as readonly string[]).includes(type);
}
/**
* v1.4.36 W4c / v1.4.37 W10 — cumulative MeasurementType →
* SourcePriorityMetricKey lookup for `pickCanonicalSourceRows`.
*
* Returns `null` for types without a dedicated priority ladder
* (e.g. TIME_IN_DAYLIGHT, which lacks a clinical-grade competitor
* to Apple Health for daylight minutes today). The picker treats a
* `null` ladder as the "no priority — pass through every row"
* branch, so the bucket-and-sum runs over every source.
*
* Hoisted out of `src/app/api/analytics/route.ts` so adding a new
* cumulative metric is a single-line edit here rather than a
* route-level switch that drifts from the `SourcePriorityMetricKey`
* enum + `CUMULATIVE_HK_TYPES` set. A parity test pins the contract:
* every member of `CUMULATIVE_HK_TYPES` either resolves to a real
* `SourcePriorityMetricKey` or is explicitly mapped to `null`.
*/
export function cumulativeMetricKey(
type: MeasurementType,
): SourcePriorityMetricKey | null {
switch (type) {
case "ACTIVITY_STEPS":
return "steps";
case "ACTIVE_ENERGY_BURNED":
return "activeEnergy";
case "WALKING_RUNNING_DISTANCE":
return "walkingRunningDistance";
case "FLIGHTS_CLIMBED":
return "flightsClimbed";
default:
return null;
}
}
@@ -77,6 +77,20 @@ export interface DrainOptions {
dryRun?: boolean;
/** Logger sink — defaults to `console.log`. */
log?: (line: string) => void;
/**
* v1.4.37 W7c — protect recent per-sample rows from collapse so late
* watch syncs still surface in real time before the list view shows
* the day's total. When set, rows whose `measuredAt` is newer than
* `now() - cutoffHours` are excluded from the scan; the drain only
* acts on completed days that have had enough time to stabilise.
*
* The scheduled nightly call passes `36` so the previous day's
* trailing sync window (Apple Watch reconciliations land up to a few
* hours after midnight when the watch wasn't worn) is fully covered.
* The CLI + admin endpoint default to `undefined` (drain everything
* the operator points at) for explicit one-shot use.
*/
cutoffHours?: number;
}
/**
@@ -89,6 +103,30 @@ export function dayKeyForUserTz(date: Date, tz: string): string {
return new Intl.DateTimeFormat("sv-SE", { timeZone: tz }).format(date);
}
/**
* Read the IANA-zone offset (in minutes east of UTC) at a given
* instant. Returns 0 for UTC and any zone the shortOffset formatter
* can't resolve (defensive — Node 22's full-icu build covers every
* zone we care about).
*/
function tzOffsetMinutesAt(instant: Date, tz: string): number {
const fmt = new Intl.DateTimeFormat("en-US", {
timeZone: tz,
hour12: false,
hour: "2-digit",
minute: "2-digit",
timeZoneName: "shortOffset",
});
const parts = fmt.formatToParts(instant);
const tzPart = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT";
const match = tzPart.match(/GMT([+-])(\d{1,2})(?::(\d{2}))?/);
if (!match) return 0;
const sign = match[1] === "+" ? 1 : -1;
const hours = Number.parseInt(match[2], 10);
const minutes = match[3] ? Number.parseInt(match[3], 10) : 0;
return sign * (hours * 60 + minutes);
}
/**
* Compute the canonical timestamp for a calendar-day key in the user's
* timezone. Returns the JS-Date instant at the user's local 12:00 noon
@@ -105,31 +143,66 @@ export function canonicalDailyTimestamp(
// build "12:00 UTC of the day", read what wall-clock that shows in
// the target zone, then shift by the resulting offset.
const utcNoon = new Date(`${dateKey}T12:00:00.000Z`);
const fmt = new Intl.DateTimeFormat("en-US", {
timeZone: tz,
hour12: false,
hour: "2-digit",
minute: "2-digit",
timeZoneName: "shortOffset",
});
// The shortOffset entry looks like "GMT+2", "GMT-5:30", or "GMT".
const parts = fmt.formatToParts(utcNoon);
const tzPart = parts.find((p) => p.type === "timeZoneName")?.value ?? "GMT";
const match = tzPart.match(/GMT([+-])(\d{1,2})(?::(\d{2}))?/);
if (!match) {
// UTC — noon UTC is noon local.
return utcNoon;
}
const sign = match[1] === "+" ? 1 : -1;
const hours = Number.parseInt(match[2], 10);
const minutes = match[3] ? Number.parseInt(match[3], 10) : 0;
const offsetMinutes = sign * (hours * 60 + minutes);
const offsetMinutes = tzOffsetMinutesAt(utcNoon, tz);
// utcNoon represents 12:00 UTC. The user's local clock reads
// 12:00 + offsetMinutes at that instant. To anchor at local 12:00,
// subtract the offset.
return new Date(utcNoon.getTime() - offsetMinutes * 60 * 1000);
}
/**
* v1.4.37 W10 — Compute the JS-Date instant at the user's local 00:00
* for a calendar-day key. Robust on DST transitions because the offset
* is read at the UTC-midnight instant of the day, and EU/US DST
* transitions happen at local 02:00 / 03:00 — so the offset at UTC
* midnight is unambiguous on every day of the year.
*
* Used by the W7c drill-down branch to resolve [dayStart, dayEnd) on
* a 23-h spring-forward or 25-h fall-back day; the previous shape
* (`canonicalDailyTimestamp ± 12h`) silently leaked or hid an hour
* of samples on two days per year.
*
* Pair with `localStartOfDay(nextDayKey, tz)` for the right bound so
* the returned window covers the true local-day span — 23 h on
* spring-forward, 24 h on a regular day, 25 h on fall-back.
*/
export function localStartOfDay(dateKey: string, tz: string): Date {
// Anchor at 00:00 UTC of the day; the offset read at that instant
// is the same offset the local clock uses at midnight (DST
// transitions in EU/US happen at 02:00 / 03:00 local, not at the
// 00:00 boundary). For sub-half-hour zones (Asia/Kathmandu UTC+5:45,
// Pacific/Chatham UTC+12:45) the minute component is preserved.
const utcMidnight = new Date(`${dateKey}T00:00:00.000Z`);
const offsetMinutes = tzOffsetMinutesAt(utcMidnight, tz);
// Local 00:00 at this date = UTC midnight - offset.
return new Date(utcMidnight.getTime() - offsetMinutes * 60 * 1000);
}
/**
* v1.4.37 W10 — Resolve the [dayStart, dayEnd) UTC window for a
* calendar-day key in the user's IANA timezone. The window honours
* DST so the drill-down branch returns the correct 23 / 24 / 25-hour
* span for transition days.
*
* Returns a tuple where `dayEnd` is the local 00:00 of the FOLLOWING
* calendar day — `< dayEnd` is the canonical half-open bound used by
* the route's `measuredAt: { gte: dayStart, lt: dayEnd }` predicate.
*/
export function localDayWindow(
dateKey: string,
tz: string,
): { dayStart: Date; dayEnd: Date } {
const dayStart = localStartOfDay(dateKey, tz);
// Add ONE day to dateKey using UTC arithmetic on a noon anchor (noon
// sidesteps every DST edge case for the calendar increment). Then
// re-extract the ISO date slice — guaranteed to be the next-day key.
const nextUtcNoon = new Date(`${dateKey}T12:00:00.000Z`);
nextUtcNoon.setUTCDate(nextUtcNoon.getUTCDate() + 1);
const nextDateKey = nextUtcNoon.toISOString().slice(0, 10);
const dayEnd = localStartOfDay(nextDateKey, tz);
return { dayStart, dayEnd };
}
/**
* Group an array of per-sample rows into per-day buckets keyed by the
* user's timezone. Exposed for unit testing the bucketing semantics
@@ -190,6 +263,14 @@ export async function drainPerSampleCumulative(
): Promise<DrainSummary> {
const dryRun = options.dryRun ?? false;
const log = options.log ?? ((line) => console.log(line));
// v1.4.37 W7c — when the scheduler passes a cutoff window we leave
// rows newer than the cutoff alone so the user's "today" view keeps
// updating in real time. Cutoff is computed once per invocation so
// every per-user-type scan uses the same boundary instant.
const cutoffAt =
typeof options.cutoffHours === "number" && options.cutoffHours > 0
? new Date(Date.now() - options.cutoffHours * 60 * 60 * 1000)
: null;
const users = options.userId
? await prismaClient.user.findMany({
@@ -224,6 +305,10 @@ export async function drainPerSampleCumulative(
userId: user.id,
source: "APPLE_HEALTH",
type,
// v1.4.37 W7c — exclude rows that fall inside the grace
// window so the nightly scheduled drain never collapses
// today's still-in-flight watch syncs.
...(cutoffAt ? { measuredAt: { lt: cutoffAt } } : {}),
},
select: {
id: true,
+41
View File
@@ -0,0 +1,41 @@
/**
* v1.4.37 W4b — shared medication category-label lookup.
*
* Both the generic `<MedicationCard>` and the GLP-1 variant render
* `categoryLabel` into the same `<MedicationCardHeader>` outline badge.
* Historically the generic card kept its own inline lookup table while
* the GLP-1 card hard-coded `medications.treatmentClassGlp1` into the
* slot — Marc reported the asymmetry during the v1.4.37 UX audit
* (audit item 11). The GLP-1 nature is already implied by the
* rotation hint + injection metadata rows, so both surfaces should
* paint the actual medication category instead.
*
* The lookup is a small string map; we keep it as a function that takes
* the bound `t()` translator so the keys stay one source of truth and
* we don't need to drill a separate `categoryLabels` object through
* the card props.
*/
type Translator = (key: string, params?: Record<string, string | number>) => string;
const MEDICATION_CATEGORY_KEYS: Record<string, string> = {
BLOOD_PRESSURE: "medications.categoryBloodPressure",
VITAMIN: "medications.categoryVitamin",
SUPPLEMENT: "medications.categorySupplement",
PAIN_RELIEF: "medications.categoryPainRelief",
ALLERGY: "medications.categoryAllergy",
DIGESTIVE: "medications.categoryDigestive",
THYROID: "medications.categoryThyroid",
HORMONE: "medications.categoryHormone",
SKIN: "medications.categorySkin",
SLEEP_AID: "medications.categorySleepAid",
OTHER: "medications.categoryOther",
};
export function getMedicationCategoryLabel(
category: string,
t: Translator,
): string {
const key = MEDICATION_CATEGORY_KEYS[category] ?? "medications.categoryOther";
return t(key);
}
+204
View File
@@ -0,0 +1,204 @@
/**
* v1.4.37 W4b — shared current-window status helper for medication
* detail cards.
*
* Both the generic `<MedicationCard>` (Ramipril etc.) and the GLP-1
* variant (`<Glp1MedicationCard>` — Mounjaro etc.) need to paint the
* same coloured "take now / overdue / very overdue" pill at the top of
* their detail surface. The logic was historically inlined in the
* generic card only, which produced the visible asymmetry Marc reported
* during the v1.4.37 UX audit (audit item 11).
*
* Lifting the schedule-window math into one helper guarantees both card
* variants stay byte-equivalent for the status row — same thresholds,
* same in-window / late / very-late tiering, same overnight-window
* handling, same "don't show in-window if last intake already covered
* this window today" guard. The GLP-1 schedule shape carries the same
* `windowStart` / `windowEnd` / `daysOfWeek` fields as the generic
* schedule, so the helper accepts any schedule that satisfies the
* minimal `ScheduleWindowInput` shape.
*/
import { parseScheduleRecurrence } from "@/lib/medication-schedule";
export interface ScheduleWindowInput {
windowStart: string;
windowEnd: string;
daysOfWeek: string | null;
}
export type MedicationWindowStatus = "in_window" | "late" | "very_late" | null;
export interface CurrentWindowStatus<Schedule extends ScheduleWindowInput> {
status: MedicationWindowStatus;
schedule: Schedule | null;
}
/**
* Convert a `Date` from its underlying UTC instant into the wall-clock
* value in Europe/Berlin so the per-minute arithmetic below treats the
* user's day boundary correctly. Intentionally en-US — this is not a
* user-facing format string, only a parseable round-trip to shift the
* value into Berlin local time.
*/
export function toBerlinDate(date: Date): Date {
return new Date(date.toLocaleString("en-US", { timeZone: "Europe/Berlin" }));
}
export function parseTimeToMinutes(value: string): number {
const [h, m] = value.split(":").map(Number);
if (
!Number.isFinite(h) ||
!Number.isFinite(m) ||
h < 0 ||
h > 23 ||
m < 0 ||
m > 59
) {
return 0;
}
return h * 60 + m;
}
function getWindowStatus<Schedule extends ScheduleWindowInput>(
schedule: Schedule,
nowBerlin: Date,
lateMinutes: number,
missedMinutes: number,
): MedicationWindowStatus {
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedNow =
nowMins < startMins && endMins > 24 * 60 ? nowMins + 24 * 60 : nowMins;
// Currently in window
if (adjustedNow >= startMins && adjustedNow <= endMins) return "in_window";
// Past window end: check late thresholds
const minutesPastEnd = adjustedNow - endMins;
if (minutesPastEnd > 0 && minutesPastEnd <= lateMinutes) return "late";
if (minutesPastEnd > lateMinutes && minutesPastEnd <= missedMinutes)
return "very_late";
return null;
}
function isLastIntakeInCurrentWindow<Schedule extends ScheduleWindowInput>(
lastTakenAt: string | null,
schedule: Schedule,
nowBerlin: Date,
): boolean {
if (!lastTakenAt) return false;
const intake = toBerlinDate(new Date(lastTakenAt));
// Must be same calendar day
if (
intake.getFullYear() !== nowBerlin.getFullYear() ||
intake.getMonth() !== nowBerlin.getMonth() ||
intake.getDate() !== nowBerlin.getDate()
) {
return false;
}
const intakeMins = intake.getHours() * 60 + intake.getMinutes();
const startMins = parseTimeToMinutes(schedule.windowStart);
let endMins = parseTimeToMinutes(schedule.windowEnd);
// Handle overnight windows
if (endMins <= startMins) endMins += 24 * 60;
const adjustedIntake =
intakeMins < startMins && endMins > 24 * 60
? intakeMins + 24 * 60
: intakeMins;
return adjustedIntake >= startMins && adjustedIntake <= endMins;
}
/**
* Count how many of the supplied schedules are past their window today,
* honouring the recurrence's allowed days-of-week. Used by both cards
* to suppress "overdue" pills once the user has already covered every
* passed schedule with intake events for the day.
*/
export function countPassedSchedules<Schedule extends ScheduleWindowInput>(
schedules: Schedule[],
nowBerlin: Date,
): number {
return schedules.filter((s) => {
const recurrence = parseScheduleRecurrence(s.daysOfWeek);
if (
recurrence.daysOfWeek.length > 0 &&
!recurrence.daysOfWeek.includes(nowBerlin.getDay())
) {
return false;
}
const endMins = parseTimeToMinutes(s.windowEnd);
const nowMins = nowBerlin.getHours() * 60 + nowBerlin.getMinutes();
return nowMins > endMins;
}).length;
}
/**
* Reduce a list of schedules into the most actionable window status
* for the card header pill. Returns `null` status when the medication
* is paused, no schedule is currently in/past its window, or every
* overdue schedule is already covered by today's intake events.
*
* Priority: in_window > late > very_late. Suppresses an `in_window`
* status when the last intake already falls inside the window so the
* pill doesn't nag after the user took the dose.
*/
export function reduceCurrentWindowStatus<Schedule extends ScheduleWindowInput>(
options: {
schedules: Schedule[];
nowBerlin: Date;
lateMinutes: number;
missedMinutes: number;
active: boolean;
lastTakenAt: string | null;
todayEventCount: number;
},
): CurrentWindowStatus<Schedule> {
const {
schedules,
nowBerlin,
lateMinutes,
missedMinutes,
active,
lastTakenAt,
todayEventCount,
} = options;
if (!active) return { status: null, schedule: null };
const passedScheduleCount = countPassedSchedules(schedules, nowBerlin);
const hasUncoveredOverdue = todayEventCount < passedScheduleCount;
return schedules.reduce<CurrentWindowStatus<Schedule>>(
(best, s) => {
const status = getWindowStatus(s, nowBerlin, lateMinutes, missedMinutes);
if (!status) return best;
// Don't show late/very_late if all overdue schedules are covered
// by intake events for the day.
if (status !== "in_window" && !hasUncoveredOverdue) return best;
// Don't show in_window if last intake is already within this
// window today.
if (
status === "in_window" &&
isLastIntakeInCurrentWindow(lastTakenAt, s, nowBerlin)
) {
return best;
}
const priority = { in_window: 3, late: 2, very_late: 1 };
if (!best.status || priority[status] > priority[best.status]) {
return { status, schedule: s };
}
return best;
},
{ status: null, schedule: null },
);
}
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
createMeasurementSchema,
getUnitForType,
listMeasurementsSchema,
validateMeasurementRange,
} from "../measurement";
@@ -173,4 +174,65 @@ describe("measurement validation", () => {
}
});
});
// v1.4.37 W7c — list-view "one row per day" mode for cumulative
// types. The schema pins the optional `groupBy` enum + `dayKey`
// shape; the route gates each branch on whether the resolved type
// is in `CUMULATIVE_HK_TYPES`. Tests below pin the parser surface.
describe("listMeasurementsSchema — v1.4.37 W7c groupBy + dayKey", () => {
it("accepts an omitted groupBy + dayKey (legacy per-sample list)", () => {
const parsed = listMeasurementsSchema.safeParse({});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.groupBy).toBeUndefined();
expect(parsed.data.dayKey).toBeUndefined();
}
});
it("accepts groupBy=day", () => {
const parsed = listMeasurementsSchema.safeParse({
type: "ACTIVITY_STEPS",
groupBy: "day",
});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.groupBy).toBe("day");
}
});
it("rejects an unknown groupBy value", () => {
const parsed = listMeasurementsSchema.safeParse({
type: "ACTIVITY_STEPS",
groupBy: "week",
});
expect(parsed.success).toBe(false);
});
it("accepts a well-formed YYYY-MM-DD dayKey", () => {
const parsed = listMeasurementsSchema.safeParse({
type: "ACTIVITY_STEPS",
dayKey: "2026-05-15",
});
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.dayKey).toBe("2026-05-15");
}
});
it("rejects a malformed dayKey (DD.MM.YYYY)", () => {
const parsed = listMeasurementsSchema.safeParse({
type: "ACTIVITY_STEPS",
dayKey: "15.05.2026",
});
expect(parsed.success).toBe(false);
});
it("rejects a partial dayKey (missing day component)", () => {
const parsed = listMeasurementsSchema.safeParse({
type: "ACTIVITY_STEPS",
dayKey: "2026-05",
});
expect(parsed.success).toBe(false);
});
});
});
+91 -38
View File
@@ -235,44 +235,97 @@ export const updateMeasurementSchema = z.object({
.optional(),
});
export const listMeasurementsSchema = z.object({
type: measurementTypeEnum.optional(),
from: z.iso
.datetime({ offset: true })
.transform((s) => new Date(s))
.optional(),
to: z.iso
.datetime({ offset: true })
.transform((s) => new Date(s))
.optional(),
// v1.4.28 FB-D2 — when the chart sends an explicit from/to window the
// payload is already bounded; lift the per-request ceiling to 5000
// (still cheaper than the legacy unbounded `while (true)` walk).
// Callers that omit from/to keep the historical 500-row cap.
limit: z.coerce.number().int().min(1).max(5000).optional().default(100),
offset: z.coerce.number().int().min(0).optional().default(0),
sortBy: z
.enum(["type", "value", "measuredAt", "source"])
.optional()
.default("measuredAt"),
sortDir: z.enum(["asc", "desc"]).optional().default("desc"),
// v1.4.28 FB-D2 — bucket hint for range-aware queries. When set the
// GET handler runs a server-side `date_trunc` aggregation and returns
// one row per bucket per type rather than the raw measurement rows.
// Omitting `aggregate` keeps the raw wire shape (iOS contract); the
// chart-data client must opt in explicitly.
aggregate: z.enum(["raw", "daily", "weekly", "monthly"]).optional(),
// v1.4.36 W1 — opt-in source switch for daily-aggregate reads. When
// `source=rollup` + `aggregate=daily`, the route reads from the
// persistent `measurement_rollups` DAY buckets instead of running a
// live `date_trunc` GROUP BY scan over the raw `measurements` table.
// The chart-data client opts in for the trends-row strip + every
// sub-page chart so the three parallel daily-aggregate requests stop
// burning a full table scan each. The route falls back to live SQL
// when the rollup bucket set is empty for the requested window so
// brand-new accounts still see correct data on their first chart.
source: z.enum(["rollup"]).optional(),
});
export const listMeasurementsSchema = z
.object({
type: measurementTypeEnum.optional(),
from: z.iso
.datetime({ offset: true })
.transform((s) => new Date(s))
.optional(),
to: z.iso
.datetime({ offset: true })
.transform((s) => new Date(s))
.optional(),
// v1.4.28 FB-D2 — when the chart sends an explicit from/to window the
// payload is already bounded; lift the per-request ceiling to 5000
// (still cheaper than the legacy unbounded `while (true)` walk).
// Callers that omit from/to keep the historical 500-row cap.
limit: z.coerce.number().int().min(1).max(5000).optional().default(100),
offset: z.coerce.number().int().min(0).optional().default(0),
sortBy: z
.enum(["type", "value", "measuredAt", "source"])
.optional()
.default("measuredAt"),
sortDir: z.enum(["asc", "desc"]).optional().default("desc"),
// v1.4.28 FB-D2 — bucket hint for range-aware queries. When set the
// GET handler runs a server-side `date_trunc` aggregation and returns
// one row per bucket per type rather than the raw measurement rows.
// Omitting `aggregate` keeps the raw wire shape (iOS contract); the
// chart-data client must opt in explicitly.
aggregate: z.enum(["raw", "daily", "weekly", "monthly"]).optional(),
// v1.4.36 W1 — opt-in source switch for daily-aggregate reads. When
// `source=rollup` + `aggregate=daily`, the route reads from the
// persistent `measurement_rollups` DAY buckets instead of running a
// live `date_trunc` GROUP BY scan over the raw `measurements` table.
// The chart-data client opts in for the trends-row strip + every
// sub-page chart so the three parallel daily-aggregate requests stop
// burning a full table scan each. The route falls back to live SQL
// when the rollup bucket set is empty for the requested window so
// brand-new accounts still see correct data on their first chart.
source: z.enum(["rollup"]).optional(),
// v1.4.37 W7c — list-view "one row per day" mode for cumulative
// types (steps, active energy, distance, flights, daylight). When
// `groupBy=day` is set and `type` is a cumulative HK type, the route
// returns one synthesised row per user-TZ day with `value` = SUM
// and `sampleCount` = number of per-sample rows behind the bucket.
// Omitted = legacy per-sample list behaviour (iOS contract stable).
//
// v1.4.37 W10 — the route's groupBy=day branch hard-codes `offset:0`
// in the meta because the collapse runs after the per-sample scan;
// real pagination would require Postgres-side `date_trunc` grouping
// and a separate `prisma.count({ distinct: ["dayKey"] })`. Until
// that lands, reject any caller threading a non-zero offset so the
// pagination contract isn't silently dropped.
groupBy: z.enum(["day"]).optional(),
// v1.4.37 W7c — drill-down to per-sample rows for a single day in
// the user's IANA timezone. Format `YYYY-MM-DD`; the route resolves
// the day boundary against the user's `User.timezone`. Used by the
// expandable list row to reveal the chunks that contributed to the
// collapsed daily total.
//
// v1.4.37 W10 — same offset restriction as `groupBy=day`; the
// drill-down branch returns a single bounded page rather than a
// cursor.
dayKey: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "dayKey must be YYYY-MM-DD")
// v1.4.37 W10 — a `YYYY-MM-DD` string can satisfy the regex while
// still being an impossible calendar date (`2026-02-30`,
// `2026-13-01`). `new Date("2026-02-30T00:00:00Z")` silently
// overflows to March 2, so the drill-down would return rows from
// a different day than the user asked for. The same helper feeds
// the admin drain route, so a malformed CLI invocation has the
// same blast radius. Reject the impossible shapes at the
// validator instead.
.refine(
(s) => {
const parsed = new Date(`${s}T00:00:00Z`);
if (Number.isNaN(parsed.getTime())) return false;
return s === parsed.toISOString().slice(0, 10);
},
"dayKey must be a real calendar date (YYYY-MM-DD)",
)
.optional(),
})
.refine(
({ offset, groupBy, dayKey }) =>
!(offset > 0 && (groupBy === "day" || dayKey != null)),
{
message:
"offset is not supported with groupBy=day or dayKey; use a smaller window or omit offset",
path: ["offset"],
},
);
export const createBatchMeasurementSchema = z.object({
measurements: z.array(createMeasurementSchema).min(1).max(5),
+28 -11
View File
@@ -89,6 +89,24 @@ export const listIntakeEventsSchema = z.object({
.optional()
.default("scheduledFor"),
sortDir: z.enum(["asc", "desc"]).optional().default("desc"),
/**
* v1.4.37 W3 — server-side status filter so the medication detail
* page (IntakeHistoryListV2) can hide unconfirmed / planned rows.
*
* - "all" (default): every event, preserves the byte-stable contract
* the iOS Swift client and existing dashboard consumers depend on.
* - "taken": only rows where the dose was confirmed taken
* (`takenAt IS NOT NULL AND skipped = false`).
* - "skipped": only rows the user explicitly skipped (`skipped = true`).
* - "completed": taken OR skipped — anything the user actually
* actioned. Excludes the ambiguous "missed / never confirmed"
* rows (`takenAt IS NULL AND skipped = false`) that the v1 list
* rendered as "verpasst" before the v1 component retired.
*/
status: z
.enum(["all", "taken", "skipped", "completed"])
.optional()
.default("all"),
});
export const updateIntakeEventSchema = z.object({
@@ -142,8 +160,12 @@ export const updateInventoryItemSchema = z.object({
notes: z.string().max(200).nullable().optional(),
});
export type CreateInventoryItemInput = z.infer<typeof createInventoryItemSchema>;
export type UpdateInventoryItemInput = z.infer<typeof updateInventoryItemSchema>;
export type CreateInventoryItemInput = z.infer<
typeof createInventoryItemSchema
>;
export type UpdateInventoryItemInput = z.infer<
typeof updateInventoryItemSchema
>;
/**
* v1.4.25 W21 Fix-K — `POST /api/medications/[id]/glp1` body validators.
@@ -182,11 +204,7 @@ export const glp1DoseChangePostSchema = z.object({
.refine((d) => d.getTime() <= Date.now() + FIVE_YEARS_MS, {
message: "effectiveFrom must be within 5 years of now",
}),
doseValue: z
.number()
.finite()
.min(0)
.max(MAX_DOSE_MG),
doseValue: z.number().finite().min(0).max(MAX_DOSE_MG),
doseUnit: z.string().min(1).max(10),
note: z.string().max(MAX_NOTE_CHARS).nullable().optional(),
});
@@ -207,10 +225,9 @@ export const glp1PostBodySchema = z
doseChange: glp1DoseChangePostSchema.optional(),
inventory: glp1InventoryPostSchema.optional(),
})
.refine(
(b) => Boolean(b.doseChange) !== Boolean(b.inventory),
{ message: "Body must carry exactly one of doseChange or inventory" },
);
.refine((b) => Boolean(b.doseChange) !== Boolean(b.inventory), {
message: "Body must carry exactly one of doseChange or inventory",
});
export type Glp1DoseChangePostInput = z.infer<typeof glp1DoseChangePostSchema>;
export type Glp1InventoryPostInput = z.infer<typeof glp1InventoryPostSchema>;