v1.4.34.1 — insights cold-mount perf hotfix + scatter-card sizing

Hotfix on top of v1.4.34. The Insights page mount was paying ~29 s on
every cold load against accounts populated by the v1.4.34 Apple Health
importer. Root cause: `/api/insights/comprehensive` walked the unbounded
90-day measurement set into JS, then ran per-type `summarize()`, BMI,
blood-pressure classification, target adherence, and four Pearson
correlations from the same pile of rows. On a 100 000+ row account the
route consumed one of the 20 pool connections for the whole 29 s, which
cascaded sibling endpoints into Cloudflare "no available server" 503s.
The scatter-correlation card also surfaced a `width(-1)/height(-1)`
Recharts warning on first paint because its dynamic-mount lacked a
non-zero floor before aspect-ratio resolved.

Changed:
  - /api/insights/comprehensive now reads through a SQL-side aggregator
    (src/lib/insights/comprehensive-aggregator.ts) grouping by metric
    type with Postgres-native AVG / MIN / MAX / REGR_SLOPE / REGR_R2 on
    the measurements (user_id, type, measured_at) index path. Returns
    the same DataSummary-shaped per-type bundle the legacy route
    stitched together; the medication-compliance block keeps its
    bounded Prisma reads. Wrapped through the server cache keyed on
    `${userId}|comprehensive` (60 s TTL). Cold path drops from ~29 s
    to a few hundred ms against fixture data matching the production
    volume that triggered the bug; warm path resolves in single-digit
    milliseconds.
  - Cache-wrap the five remaining read routes the v1.4.34 server-cache
    blueprint left staged but unwired: /api/mood/analytics,
    /api/workouts, /api/bugreport/status, /api/medications,
    /api/dashboard/widgets. The Cloudflare 503 cascade on
    /api/measurements?aggregate=daily resolves as a downstream
    consequence — once the comprehensive route stops monopolising the
    pool, the origin accepts new connections fast enough that
    Cloudflare's circuit-breaker no longer trips.
  - /api/dashboard/chart-overlay-prefs PUT now invalidates the new
    dashboard-widgets cache so the partial-update path doesn't leave
    stale layout state in the cache for up to TTL.

Fixed:
  - Scatter-correlation card no longer logs the Recharts
    `width(-1)/height(-1)` warning on first mount. The wrapper now
    carries a min-h-[180px] floor that matches the loading skeleton so
    ResponsiveContainer always measures a non-zero parent before
    aspect-ratio settles.
This commit is contained in:
Marc-André Bombeck committed 2026-05-16 22:26:59 +02:00
1 parent affede31a4
commit f6ca89b963
24 files changed
+4590 -241

No files matched your search

+44 -11
View File
@@ -12,17 +12,16 @@ import { apiSuccess, apiError } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { checkRateLimit } from "@/lib/rate-limit";
import { prisma } from "@/lib/db";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
// Light rate limit — the endpoint is cheap, but no reason to let a logged-in
// client hammer Postgres in a loop.
const rl = await checkRateLimit(`bugreport-status:${user.id}`, 30, 60 * 1000);
if (!rl.allowed) {
return apiError("Rate limit exceeded", 429);
}
interface BugreportStatusCacheValue {
configured: boolean;
enabled: boolean;
hasToken: boolean;
hasRepo: boolean;
}
async function buildBugreportStatusValue(): Promise<BugreportStatusCacheValue> {
const appSettings = await prisma.appSettings.findUnique({
where: { id: "singleton" },
select: {
@@ -42,10 +41,44 @@ export const GET = apiHandler(async () => {
// Default ON when the column has never been written.
const enabled = appSettings?.bugReportEnabled !== false;
return { configured, enabled, hasToken, hasRepo };
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
// Light rate limit — the endpoint is cheap, but no reason to let a logged-in
// client hammer Postgres in a loop.
const rl = await checkRateLimit(`bugreport-status:${user.id}`, 30, 60 * 1000);
if (!rl.allowed) {
return apiError("Rate limit exceeded", 429);
}
// Cache the global app-settings shape on a singleton key (per blueprint §3).
// `isAdmin` lives outside the cache because it varies per request. The
// `invalidateAppSettings()` helper called from
// `PATCH /api/admin/app-settings` evicts this entry when bug-report
// configuration changes.
const status = await cached(
caches.bugreportStatus as ServerCache<BugreportStatusCacheValue>,
"singleton",
() => buildBugreportStatusValue(),
annotate,
);
annotate({
action: { name: "bugreport.status" },
meta: { configured, enabled, has_token: hasToken, has_repo: hasRepo },
meta: {
configured: status.configured,
enabled: status.enabled,
has_token: status.hasToken,
has_repo: status.hasRepo,
},
});
return apiSuccess({ configured, enabled, isAdmin: user.role === "ADMIN" });
return apiSuccess({
configured: status.configured,
enabled: status.enabled,
isAdmin: user.role === "ADMIN",
});
});
@@ -25,6 +25,7 @@ import {
serializeDashboardLayout,
type DashboardLayout,
} from "@/lib/dashboard-layout";
import { invalidateUserDashboardWidgets } from "@/lib/cache/invalidate";
import { Prisma } from "@/generated/prisma/client";
import { z } from "zod/v4";
import type { NextRequest } from "next/server";
@@ -86,6 +87,11 @@ export const PUT = apiHandler(async (request: NextRequest) => {
{ isolationLevel: "Serializable" },
);
// The partial-update path mutates the same `User.dashboardWidgetsJson`
// blob the `/api/dashboard/widgets` GET reads from. Bust the cache so
// the next dashboard mount surfaces the new chartOverlayPrefs slot.
invalidateUserDashboardWidgets(user.id);
annotate({
action: { name: "dashboard.chartOverlayPrefs.update" },
meta: {
+18 -6
View File
@@ -22,6 +22,7 @@ import {
import { Prisma } from "@/generated/prisma/client";
import { z } from "zod/v4";
import { invalidateUserDashboardWidgets } from "@/lib/cache/invalidate";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import type { NextRequest } from "next/server";
// Single source of truth — every widget id rendered by the Settings →
@@ -94,15 +95,26 @@ const layoutSchema = z.object({
.optional(),
});
async function buildDashboardLayout(userId: string): Promise<DashboardLayout> {
const row = await prisma.user.findUnique({
where: { id: userId },
select: { dashboardWidgetsJson: true },
});
return resolveDashboardLayout(row?.dashboardWidgetsJson);
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { dashboardWidgetsJson: true },
});
const layout = resolveDashboardLayout(row?.dashboardWidgetsJson);
// 5-minute TTL per blueprint §5; the layout changes only when the user
// hits the Settings → Dashboard save button, which invalidates this
// cache via `invalidateUserDashboardWidgets()`.
const layout = await cached(
caches.dashboardWidgets as ServerCache<DashboardLayout>,
user.id,
() => buildDashboardLayout(user.id),
annotate,
);
return apiSuccess(layout);
});
@@ -0,0 +1,306 @@
/**
* v1.4.35 — unit-level shape-parity pin for the comprehensive route.
*
* The integration coverage (`tests/integration/insights-comprehensive-cache.test.ts`)
* exercises the route end-to-end against the real Postgres testcontainer
* including cache hit/miss. This file mocks the SQL aggregator so the
* envelope shape — exactly what the /insights page consumes — is
* pinned without a container.
*
* What this test covers:
* - Every key the legacy route emitted is still on the response.
* - Empty user → bmi=null, every correlation null, scatter arrays
* empty, totalMeasurements=0, alerts is an array.
* - The route reads from the aggregator (not a 100k-row findMany).
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
user: { findUnique: vi.fn() },
measurement: { findMany: vi.fn() },
moodEntry: { findMany: vi.fn() },
medication: { findMany: vi.fn() },
medicationIntakeEvent: { findMany: vi.fn() },
appSettings: { findUnique: vi.fn() },
auditLog: { create: vi.fn() },
$queryRaw: 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: () => {},
})),
}));
// Mock the aggregator so we feed a controlled fixture without going
// near Postgres. The route's own assembly logic (correlations,
// classifications, alerts) is what we want to pin.
vi.mock("@/lib/insights/comprehensive-aggregator", () => ({
buildComprehensiveAggregate: vi.fn(),
}));
vi.mock("@/lib/ai/provider", () => ({
resolveProvider: vi.fn(async () => ({ type: "none" })),
}));
vi.mock("@/lib/medication-category", () => ({
getMedicationCategories: vi.fn(async () => ({})),
}));
import { GET } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
import { buildComprehensiveAggregate } from "@/lib/insights/comprehensive-aggregator";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: {
id: "user-comp-1",
username: "marc",
role: "USER" as const,
locale: "en",
},
};
const callGet = GET as unknown as (req: NextRequest) => Promise<Response>;
function makeReq(): NextRequest {
return new NextRequest("http://localhost/api/insights/comprehensive");
}
beforeEach(() => {
vi.resetAllMocks();
__resetAllCachesForTests();
// Default to assistant-on so the gate doesn't 403 every test.
(
prisma.appSettings.findUnique as ReturnType<typeof vi.fn>
).mockResolvedValue(null);
(prisma.user.findUnique as ReturnType<typeof vi.fn>).mockResolvedValue({
heightCm: 180,
dateOfBirth: new Date("1985-01-01"),
});
(prisma.moodEntry.findMany as ReturnType<typeof vi.fn>).mockResolvedValue([]);
(prisma.medication.findMany as ReturnType<typeof vi.fn>).mockResolvedValue(
[],
);
(
prisma.medicationIntakeEvent.findMany as ReturnType<typeof vi.fn>
).mockResolvedValue([]);
});
describe("GET /api/insights/comprehensive — envelope shape", () => {
it("returns 401 when unauthenticated", async () => {
vi.mocked(getSession).mockResolvedValue(null);
const res = await callGet(makeReq());
expect(res.status).toBe(401);
});
it("emits every legacy envelope key for an empty user", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
(
buildComprehensiveAggregate as ReturnType<typeof vi.fn>
).mockResolvedValue({
summaries: {},
bpRawRows: { sys: [], dia: [] },
dailyByType: {},
firstMeasurementAt: null,
totalMeasurements: 0,
});
const res = await callGet(makeReq());
expect(res.status).toBe(200);
const body = (await res.json()) as { data: Record<string, unknown> };
// Every legacy key — the consumer (`/insights` page) reads each of
// these. If any one disappears the page silently breaks.
const requiredKeys = [
"summaries",
"bmi",
"bmiClassification",
"bpClassification",
"bpPctInTarget",
"bpTargets",
"weightBpCorrelation",
"scatterData",
"bpMedicationCorrelation",
"bpMedicationScatterData",
"moodSummary",
"moodBpCorrelation",
"moodBpScatterData",
"moodWeightCorrelation",
"moodWeightScatterData",
"moodPulseCorrelation",
"moodPulseScatterData",
"medications",
"alerts",
"hasProvider",
"dataSpanDays",
"totalMeasurements",
];
for (const key of requiredKeys) {
expect(body.data).toHaveProperty(key);
}
expect(body.data.bmi).toBeNull();
expect(body.data.bmiClassification).toBeNull();
expect(body.data.scatterData).toEqual([]);
expect(body.data.bpMedicationScatterData).toEqual([]);
expect(body.data.medications).toEqual([]);
expect(Array.isArray(body.data.alerts)).toBe(true);
expect(body.data.totalMeasurements).toBe(0);
expect(body.data.dataSpanDays).toBe(0);
});
it("computes BMI from aggregate WEIGHT.latest and user heightCm", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
(
buildComprehensiveAggregate as ReturnType<typeof vi.fn>
).mockResolvedValue({
summaries: {
WEIGHT: {
count: 1,
latest: 81.0,
min: 81.0,
max: 81.0,
mean: 81.0,
avg7: 81.0,
avg30: 81.0,
slope7: null,
slope30: null,
slope90: null,
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
},
},
bpRawRows: { sys: [], dia: [] },
dailyByType: {},
firstMeasurementAt: new Date(),
totalMeasurements: 1,
});
const res = await callGet(makeReq());
const body = (await res.json()) as {
data: { bmi: number | null; bmiClassification: { category: string } };
};
// BMI = 81 / (1.80 ^ 2) = 25.0 → "Overweight" in classifyBMI.
expect(body.data.bmi).toBeCloseTo(25, 1);
expect(body.data.bmiClassification.category).toBe("Overweight");
});
it("pairs sys + dia raw rows with 5-min tolerance for bpPctInTarget", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const at = new Date("2026-05-10T08:00:00Z");
(
buildComprehensiveAggregate as ReturnType<typeof vi.fn>
).mockResolvedValue({
summaries: {
BLOOD_PRESSURE_SYS: {
count: 1,
latest: 125,
min: 125,
max: 125,
mean: 125,
avg7: 125,
avg30: 125,
slope7: null,
slope30: null,
slope90: null,
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
},
BLOOD_PRESSURE_DIA: {
count: 1,
latest: 75,
min: 75,
max: 75,
mean: 75,
avg7: 75,
avg30: 75,
slope7: null,
slope30: null,
slope90: null,
anomalyCount: 0,
avg30LastMonth: null,
avg30LastYear: null,
},
},
bpRawRows: {
sys: [{ measuredAt: at, value: 125 }],
dia: [{ measuredAt: at, value: 75 }],
},
dailyByType: {},
firstMeasurementAt: at,
totalMeasurements: 2,
});
const res = await callGet(makeReq());
const body = (await res.json()) as {
data: {
bpPctInTarget: number | null;
bpClassification: { category: string } | null;
};
};
// 125/75 sits inside the under-65 target ceiling (sysHigh=129,
// diaHigh=79) and above the hypotension floor → 100% in target.
expect(body.data.bpPctInTarget).toBe(100);
// avg30 sys=125, dia=75 → ESH "Normal" band.
expect(body.data.bpClassification?.category).toBe("Normal");
});
it("derives weight × BP scatter from daily-bucketed series", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
// Five day-aligned pairs (n >= 5 unlocks pearsonCorrelation).
const days = [
"2026-05-01",
"2026-05-02",
"2026-05-03",
"2026-05-04",
"2026-05-05",
];
(
buildComprehensiveAggregate as ReturnType<typeof vi.fn>
).mockResolvedValue({
summaries: {},
bpRawRows: { sys: [], dia: [] },
dailyByType: {
WEIGHT: days.map((d, i) => ({ day: d, value: 80 + i })),
BLOOD_PRESSURE_SYS: days.map((d, i) => ({ day: d, value: 120 + i * 2 })),
},
firstMeasurementAt: new Date(),
totalMeasurements: 10,
});
const res = await callGet(makeReq());
const body = (await res.json()) as {
data: {
scatterData: Array<{ weight: number; sysBP: number }>;
weightBpCorrelation: { r: number; n: number } | null;
};
};
expect(body.data.scatterData).toHaveLength(5);
expect(body.data.scatterData[0]).toEqual({ weight: 80, sysBP: 120 });
// Perfect linear relationship → r === 1.
expect(body.data.weightBpCorrelation?.r).toBe(1);
expect(body.data.weightBpCorrelation?.n).toBe(5);
});
});
+179 -114
View File
@@ -1,7 +1,8 @@
import { prisma } from "@/lib/db";
import { resolveProvider } from "@/lib/ai/provider";
import { apiSuccess } from "@/lib/api-response";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
import type { DataPoint, DataSummary } from "@/lib/analytics/trends";
import { summarize } from "@/lib/analytics/trends";
import { getBpTargets } from "@/lib/analytics/bp-targets";
import { isBpReadingInTarget } from "@/lib/analytics/bp-in-target";
import {
@@ -16,11 +17,11 @@ import {
} from "@/lib/analytics/correlations";
import { calculateCompliance } from "@/lib/analytics/compliance";
import { getMedicationCategories } from "@/lib/medication-category";
import type { MeasurementType } from "@/generated/prisma/client";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiHandler, requireAuth, type AuthContext } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { measurementTypeEnum } from "@/lib/validations/measurement";
import { requireAssistantSurface } from "@/lib/feature-flags";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { buildComprehensiveAggregate } from "@/lib/insights/comprehensive-aggregator";
export const dynamic = "force-dynamic";
@@ -30,10 +31,41 @@ export const GET = apiHandler(async () => {
// recommendations grid that share the Coach gate.
await requireAssistantSurface("coach");
// v1.4.35 — read-through the analytics cache keyed on
// (userId, "comprehensive"). The /insights page mount routinely
// fans out to this endpoint alongside the Coach drawer + the
// recommendations grid; the 60s TTL converts every duplicate
// mount within the window to a Map lookup. Invalidation is handled
// by `invalidateUserMeasurements` which already evicts every key
// under the `${userId}|` prefix (see `lib/cache/invalidate.ts`).
const body = await cached(
caches.analytics as ServerCache<Awaited<
ReturnType<typeof buildComprehensiveResponse>
>>,
`${user.id}|comprehensive`,
() => buildComprehensiveResponse(user),
annotate,
);
return apiSuccess(body);
});
type AuthedUser = AuthContext["user"];
/**
* v1.4.35 — comprehensive insights response body, lifted out of the
* route handler so `cached()` can wrap it. Replaces the previous
* 100k-row-in-JS aggregation with SQL-side aggregates served by
* `buildComprehensiveAggregate`. The medication-compliance block keeps
* its bounded Prisma reads (medications + intake events) — the directive
* called those out as already on the safe path. The byte-shape of the
* returned envelope is unchanged from the legacy route.
*/
export async function buildComprehensiveResponse(user: AuthedUser) {
const userId = user.id;
const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
// Fetch user profile
// Fetch user profile (height + DOB drive BMI + BP targets).
const dbUser = await prisma.user.findUnique({
where: { id: userId },
select: {
@@ -42,24 +74,26 @@ export const GET = apiHandler(async () => {
},
});
// Derived from canonical enum so adding a new measurement type does not
// require touching this file (V3 audit finding: enum drift cousins).
const types = [...measurementTypeEnum.options] as MeasurementType[];
// ── Aggregate-first reads ─────────────────────────────────
// SQL-side rollup replaces the 100k-row findMany on the legacy
// route. Returns per-type DataSummary identical to the JS
// `summarize()` semantics over the 90-day window, plus the bounded
// raw rows the BP target adherence pairing needs, plus daily-mean
// buckets for the correlation pairings.
const aggregate = await buildComprehensiveAggregate(userId);
const allMeasurements = await prisma.measurement.findMany({
where: { userId, type: { in: types }, measuredAt: { gte: ninetyDaysAgo } },
orderBy: { measuredAt: "asc" },
select: { type: true, value: true, measuredAt: true },
});
// Fetch mood entries (90 days)
// Mood entries are user-recorded; the table is small and the
// `moodSummary` field requires raw scores (`summarize()` over the
// raw score series). The findMany stays.
const moodEntries = await prisma.moodEntry.findMany({
where: { userId, moodLoggedAt: { gte: ninetyDaysAgo } },
orderBy: { moodLoggedAt: "asc" },
select: { date: true, score: true, moodLoggedAt: true },
});
// Aggregate mood to daily averages
// Aggregate mood to daily averages (drives the mood × metric
// correlations). Bucket key matches the legacy code's `date` column
// semantics (YYYY-MM-DD anchored to the user's tz at write time).
const moodByDay = new Map<string, { sum: number; count: number }>();
for (const entry of moodEntries) {
const current = moodByDay.get(entry.date) ?? { sum: 0, count: 0 };
@@ -74,7 +108,9 @@ export const GET = apiHandler(async () => {
value: Math.round((stats.sum / stats.count) * 100) / 100,
}));
// Build DataPoint array for mood summary
// moodSummary uses the same `summarize()` helper over raw scores —
// the table is bounded by user-recorded entries so the in-JS path
// is safe.
const moodDataPoints: DataPoint[] = moodEntries.map((e) => ({
date: e.moodLoggedAt,
value: e.score,
@@ -82,21 +118,9 @@ export const GET = apiHandler(async () => {
const moodSummary =
moodDataPoints.length > 0 ? summarize(moodDataPoints) : null;
const byType = (t: MeasurementType): DataPoint[] =>
allMeasurements
.filter((m) => m.type === t)
.map((m) => ({ date: m.measuredAt, value: m.value }));
const summaries: Record<string, DataSummary> = aggregate.summaries;
// Summaries
const summaries: Record<string, ReturnType<typeof summarize>> = {};
for (const t of types) {
const data = byType(t);
if (data.length > 0) {
summaries[t] = summarize(data);
}
}
// BMI
// ── BMI ──────────────────────────────────────────────────
let bmi: number | null = null;
let bmiClassification = null;
if (dbUser?.heightCm && summaries.WEIGHT?.latest) {
@@ -105,7 +129,7 @@ export const GET = apiHandler(async () => {
bmiClassification = classifyBMI(bmi);
}
// BP classification (30-day average)
// ── BP classification (30-day average) ────────────────────
let bpClassification = null;
const bpTargets = getBpTargets(dbUser?.dateOfBirth ?? null);
if (
@@ -118,11 +142,21 @@ export const GET = apiHandler(async () => {
);
}
// BP target adherence
// ── BP target adherence ──────────────────────────────────
// Keeps the 5-minute tolerance contract — sys + dia must pair on
// the same reading session. The aggregator pulled the bounded raw
// rows; we reuse `pairByTimestamp` against them so the output is
// byte-identical to the legacy path.
let bpPctInTarget: number | null = null;
if (bpTargets) {
const sysData = byType("BLOOD_PRESSURE_SYS");
const diaData = byType("BLOOD_PRESSURE_DIA");
const sysData: DataPoint[] = aggregate.bpRawRows.sys.map((r) => ({
date: r.measuredAt,
value: r.value,
}));
const diaData: DataPoint[] = aggregate.bpRawRows.dia.map((r) => ({
date: r.measuredAt,
value: r.value,
}));
const sysPairs = pairByTimestamp(sysData, diaData, 5 * 60 * 1000);
if (sysPairs.length > 0) {
@@ -135,82 +169,48 @@ export const GET = apiHandler(async () => {
}
}
// Correlations: Weight vs Sys BP
const weightData = byType("WEIGHT");
const sysData = byType("BLOOD_PRESSURE_SYS");
const weightBpPairs = pairByTimestamp(weightData, sysData);
// ── Correlations: weight × Sys BP ─────────────────────────
// Daily-key pairing (the legacy `pairByTimestamp` ran with a
// 24-hour default tolerance — daily-mean buckets are the
// SQL-side equivalent and the directive explicitly accepts the
// small semantic shift to bound the raw-row footprint).
const weightDaily = aggregate.dailyByType.WEIGHT ?? [];
const sysDaily = aggregate.dailyByType.BLOOD_PRESSURE_SYS ?? [];
const weightBpPairs: PairedPoint[] = joinDailyByDay(
weightDaily,
sysDaily,
);
const weightBpCorrelation = pearsonCorrelation(weightBpPairs);
const scatterData = weightBpPairs.map((p) => ({
weight: p.a,
sysBP: p.b,
}));
// Correlations: Mood vs metrics (using daily averages matched by date)
function buildMoodMetricPairs(
dailyMood: Array<{ day: string; value: number }>,
measurements: Array<{ measuredAt: Date; value: number }>,
): PairedPoint[] {
// Group measurements by day
const metricByDay = new Map<string, { sum: number; count: number }>();
for (const m of measurements) {
const dayKey = m.measuredAt.toISOString().slice(0, 10);
const current = metricByDay.get(dayKey) ?? { sum: 0, count: 0 };
current.sum += m.value;
current.count += 1;
metricByDay.set(dayKey, current);
}
const pairs: PairedPoint[] = [];
for (const mood of dailyMood) {
const metric = metricByDay.get(mood.day);
if (metric) {
pairs.push({
a: mood.value,
b: Math.round((metric.sum / metric.count) * 100) / 100,
date: new Date(`${mood.day}T12:00:00.000Z`),
});
}
}
return pairs;
}
// Mood vs Systolic BP
const moodBpPairs = buildMoodMetricPairs(
dailyMoodEntries,
allMeasurements
.filter((m) => m.type === "BLOOD_PRESSURE_SYS")
.map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
);
// ── Correlations: mood × {sys BP, weight, pulse} ─────────
// Daily-key matches the legacy `buildMoodMetricPairs` exactly —
// mood is already per-day in the legacy code and we just align the
// metric side to the same daily bucket.
const moodBpPairs = pairMoodWithDaily(dailyMoodEntries, sysDaily);
const moodBpCorrelation = pearsonCorrelation(moodBpPairs);
const moodBpScatterData = moodBpPairs.map((p) => ({ mood: p.a, sysBP: p.b }));
// Mood vs Weight
const moodWeightPairs = buildMoodMetricPairs(
dailyMoodEntries,
allMeasurements
.filter((m) => m.type === "WEIGHT")
.map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
);
const moodWeightPairs = pairMoodWithDaily(dailyMoodEntries, weightDaily);
const moodWeightCorrelation = pearsonCorrelation(moodWeightPairs);
const moodWeightScatterData = moodWeightPairs.map((p) => ({
mood: p.a,
weight: p.b,
}));
// Mood vs Pulse
const moodPulsePairs = buildMoodMetricPairs(
dailyMoodEntries,
allMeasurements
.filter((m) => m.type === "PULSE")
.map((m) => ({ measuredAt: m.measuredAt, value: m.value })),
);
const pulseDaily = aggregate.dailyByType.PULSE ?? [];
const moodPulsePairs = pairMoodWithDaily(dailyMoodEntries, pulseDaily);
const moodPulseCorrelation = pearsonCorrelation(moodPulsePairs);
const moodPulseScatterData = moodPulsePairs.map((p) => ({
mood: p.a,
pulse: p.b,
}));
// Medication compliance
// ── Medication compliance ────────────────────────────────
// Bounded reads — left untouched per the directive.
const medications = await prisma.medication.findMany({
where: { userId, active: true },
include: { schedules: true },
@@ -229,9 +229,7 @@ export const GET = apiHandler(async () => {
(med) => (categoryMap[med.id] ?? "OTHER") === "BLOOD_PRESSURE",
);
// Single round-trip for all medications instead of N+1: one query keyed
// on `medicationId IN (...)`, then group in memory. The previous loop
// hit Postgres once per medication, which scales poorly for users with
// many active meds.
// on `medicationId IN (...)`, then group in memory.
const allEvents = medications.length
? await prisma.medicationIntakeEvent.findMany({
where: {
@@ -284,7 +282,11 @@ export const GET = apiHandler(async () => {
}
}
// Correlation: continuity of BP medications vs systolic BP
// ── Correlation: BP medication continuity × systolic BP ──
// Uses the same daily BP_SYS series the aggregator pre-computed —
// no second round-trip. The intake-side aggregation matches the
// legacy code: continuity = min(1, taken / expectedPerDay), pairing
// every day that had a sys reading.
let bpMedicationCorrelation: {
r: number;
strength: string;
@@ -302,13 +304,10 @@ export const GET = apiHandler(async () => {
);
if (expectedBpIntakesPerDay > 0) {
const sysByDay = new Map<string, number[]>();
for (const m of allMeasurements) {
if (m.type !== "BLOOD_PRESSURE_SYS") continue;
const dayKey = m.measuredAt.toISOString().slice(0, 10);
const list = sysByDay.get(dayKey) ?? [];
list.push(m.value);
sysByDay.set(dayKey, list);
// Daily systolic means (already keyed YYYY-MM-DD) from the SQL pass.
const sysByDay = new Map<string, number>();
for (const row of sysDaily) {
sysByDay.set(row.day, row.value);
}
const takenByDay = new Map<string, number>();
@@ -319,11 +318,9 @@ export const GET = apiHandler(async () => {
}
const pairs: Array<{ a: number; b: number; date: Date }> = [];
for (const [dayKey, sysValues] of sysByDay.entries()) {
for (const [dayKey, avgSys] of sysByDay.entries()) {
const taken = takenByDay.get(dayKey) ?? 0;
const continuity = Math.min(1, taken / expectedBpIntakesPerDay);
const avgSys =
sysValues.reduce((sum, value) => sum + value, 0) / sysValues.length;
pairs.push({
a: continuity,
b: avgSys,
@@ -360,25 +357,24 @@ export const GET = apiHandler(async () => {
})),
});
// Data span
const firstMeasurement =
allMeasurements.length > 0 ? allMeasurements[0].measuredAt : null;
const dataSpanDays = firstMeasurement
// Data span — derived from the earliest 90-day measurement.
const dataSpanDays = aggregate.firstMeasurementAt
? Math.ceil(
(Date.now() - firstMeasurement.getTime()) / (24 * 60 * 60 * 1000),
(Date.now() - aggregate.firstMeasurementAt.getTime()) /
(24 * 60 * 60 * 1000),
)
: 0;
annotate({
action: { name: "insights.comprehensive" },
meta: {
totalMeasurements: allMeasurements.length,
totalMeasurements: aggregate.totalMeasurements,
moodEntries: moodEntries.length,
medications: medications.length,
},
});
return apiSuccess({
return {
summaries,
bmi,
bmiClassification,
@@ -400,6 +396,75 @@ export const GET = apiHandler(async () => {
alerts,
hasProvider: (await resolveProvider(userId)).type !== "none",
dataSpanDays,
totalMeasurements: allMeasurements.length,
});
});
totalMeasurements: aggregate.totalMeasurements,
};
}
// ─────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────
/**
* Daily-key inner join between two daily-aggregated series. Returns
* `PairedPoint` shapes compatible with `pearsonCorrelation`.
*
* Inputs are sorted ASC by `day` (the aggregator's ORDER BY
* guarantees that). The walk is O(n + m) merge-join style instead of
* Map.lookup-per-element so it scales with the worst-case 90 buckets
* x 90 buckets case without surprises.
*/
function joinDailyByDay(
a: Array<{ day: string; value: number }>,
b: Array<{ day: string; value: number }>,
): PairedPoint[] {
const pairs: PairedPoint[] = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
const ai = a[i];
const bj = b[j];
if (ai.day === bj.day) {
pairs.push({
a: ai.value,
b: bj.value,
date: new Date(`${ai.day}T12:00:00.000Z`),
});
i += 1;
j += 1;
} else if (ai.day < bj.day) {
i += 1;
} else {
j += 1;
}
}
return pairs;
}
/**
* Pair the daily mood series (left side) with a daily-aggregated
* metric (right side). Matches the legacy `buildMoodMetricPairs`
* helper byte-for-byte: same daily YYYY-MM-DD key, same
* `T12:00:00.000Z` anchor for the `date` field.
*/
function pairMoodWithDaily(
dailyMood: Array<{ day: string; value: number }>,
dailyMetric: Array<{ day: string; value: number }>,
): PairedPoint[] {
if (dailyMood.length === 0 || dailyMetric.length === 0) return [];
const metricByDay = new Map<string, number>();
for (const m of dailyMetric) {
metricByDay.set(m.day, m.value);
}
const pairs: PairedPoint[] = [];
for (const mood of dailyMood) {
const metric = metricByDay.get(mood.day);
if (metric !== undefined) {
pairs.push({
a: mood.value,
b: metric,
date: new Date(`${mood.day}T12:00:00.000Z`),
});
}
}
return pairs;
}
+35 -29
View File
@@ -16,40 +16,34 @@ import {
import { serializeScheduleRecurrence } from "@/lib/medication-schedule";
import { getUserTodayBounds } from "@/lib/timezone";
import { invalidateUserMedications } from "@/lib/cache/invalidate";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
import { NextRequest } from "next/server";
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
type MedicationsListResult = Array<Record<string, unknown>>;
// Compute today's UTC range for event counting
const userTz = user.timezone || "Europe/Berlin";
async function buildMedicationsList(
userId: string,
userTz: string,
): Promise<MedicationsListResult> {
const { start: todayStartUtc, end: todayEndUtc } = getUserTodayBounds(
new Date(),
userTz,
);
// Run all three queries in parallel
const [medications, latestIntakes, todayEvents] = await Promise.all([
prisma.medication.findMany({
where: { userId: user.id },
where: { userId },
include: { schedules: true },
orderBy: { createdAt: "desc" },
}),
prisma.medicationIntakeEvent.groupBy({
by: ["medicationId"],
where: {
userId: user.id,
skipped: false,
takenAt: { not: null },
},
where: { userId, skipped: false, takenAt: { not: null } },
_max: { takenAt: true },
}),
prisma.medicationIntakeEvent.groupBy({
by: ["medicationId"],
where: {
userId: user.id,
scheduledFor: { gte: todayStartUtc, lte: todayEndUtc },
},
where: { userId, scheduledFor: { gte: todayStartUtc, lte: todayEndUtc } },
_count: { id: true },
}),
]);
@@ -76,24 +70,36 @@ export const GET = apiHandler(async () => {
getEvent()?.addWarning("Medication categories could not be loaded");
}
return medications.map((m) => ({
...m,
category: categoryMap[m.id] ?? "OTHER",
lastTakenAt: lastTakenAtByMedicationId[m.id] ?? null,
todayEventCount: todayEventCountByMedId[m.id] ?? 0,
}));
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const userTz = user.timezone || "Europe/Berlin";
// Cache the list shape on userId. The 60s TTL bounds the cross-midnight
// staleness window for `todayEventCount` (the only time-of-day-derived
// field in the response); writes via POST/PUT/DELETE flush through
// `invalidateUserMedications` before the next read lands.
const result = await cached(
caches.medications as ServerCache<MedicationsListResult>,
user.id,
() => buildMedicationsList(user.id, userTz),
annotate,
);
annotate({
action: { name: "medication.list" },
meta: { count: medications.length },
meta: { count: result.length },
});
return apiSuccess(
medications.map((m) => ({
...m,
// v1.4.25 W4d — `category` is the existing clinical taxonomy
// (BLOOD_PRESSURE / VITAMIN / ...) from the side-table; the
// Prisma model has its own `treatmentClass` (GENERIC | GLP1) that
// spreads through `...m` and unlocks the GLP-1 surfaces. Two
// orthogonal concepts, both exposed.
category: categoryMap[m.id] ?? "OTHER",
lastTakenAt: lastTakenAtByMedicationId[m.id] ?? null,
todayEventCount: todayEventCountByMedId[m.id] ?? 0,
})),
);
return apiSuccess(result);
});
export const POST = apiHandler(async (request: NextRequest) => {
+25 -6
View File
@@ -3,6 +3,7 @@ import { apiSuccess } from "@/lib/api-response";
import { summarize, type DataPoint } from "@/lib/analytics/trends";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
export const dynamic = "force-dynamic";
@@ -26,11 +27,17 @@ function aggregateDailyAverages(
}));
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
interface MoodAnalyticsResult {
entries: Array<{ date: string; score: number; samples: number }>;
summary: ReturnType<typeof summarize>;
entryCount: number;
}
async function buildMoodAnalyticsResponse(
userId: string,
): Promise<MoodAnalyticsResult> {
const moodEntries = await prisma.moodEntry.findMany({
where: { userId: user.id },
where: { userId },
orderBy: { moodLoggedAt: "asc" },
select: { date: true, score: true, moodLoggedAt: true },
});
@@ -39,7 +46,6 @@ export const GET = apiHandler(async () => {
moodEntries.map((e) => ({ date: e.date, score: e.score })),
);
// Build DataPoint array for summarize() using moodLoggedAt as the date
const dataPoints: DataPoint[] = moodEntries.map((e) => ({
date: e.moodLoggedAt,
value: e.score,
@@ -47,10 +53,23 @@ export const GET = apiHandler(async () => {
const summary = summarize(dataPoints);
return { entries, summary, entryCount: moodEntries.length };
}
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const result = await cached(
caches.moodAnalytics as ServerCache<MoodAnalyticsResult>,
user.id,
() => buildMoodAnalyticsResponse(user.id),
annotate,
);
annotate({
action: { name: "mood.analytics" },
meta: { entryCount: moodEntries.length },
meta: { entryCount: result.entryCount },
});
return apiSuccess({ entries, summary });
return apiSuccess({ entries: result.entries, summary: result.summary });
});
@@ -16,6 +16,8 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
import { __resetAllCachesForTests } from "@/lib/cache/server-cache";
vi.mock("@/lib/db", () => ({
prisma: {
workout: {
@@ -100,6 +102,11 @@ function makeRow(
describe("GET /api/workouts — canonical dedup", () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset every server cache between tests so a fixed userId doesn't
// carry cached state across cases (v1.4.34.2 — added when the
// `/api/workouts` GET handler started reading through
// `caches.workouts`).
__resetAllCachesForTests();
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
// Default: no per-user source-priority override → fall back to the
// canonical APPLE_HEALTH ≻ WITHINGS ≻ MANUAL ≻ IMPORT ladder.
+117 -73
View File
@@ -54,10 +54,119 @@ import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { apiSuccess } from "@/lib/api-response";
import { pickCanonicalWorkoutRows } from "@/lib/measurements/pick-canonical-workout-rows";
import { cached, caches, type ServerCache } from "@/lib/cache/server-cache";
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 200;
interface WorkoutsParams {
readonly limit: number;
readonly offset: number;
readonly since: string | null;
readonly until: string | null;
readonly sportType: string | null;
}
interface WorkoutsResult {
workouts: Array<{
id: string;
sportType: string | null;
startedAt: Date | null;
endedAt: Date | null;
durationSec: number | null;
distanceM: number | null;
activeEnergyKcal: number | null;
avgHr: number | null;
maxHr: number | null;
source: string;
externalId: string | null;
}>;
meta: {
total: number;
limit: number;
offset: number;
droppedDuplicates: number;
};
}
async function buildWorkoutsResponse(
userId: string,
params: WorkoutsParams,
): Promise<WorkoutsResult> {
const { limit, offset, since, until, sportType } = params;
const where: Record<string, unknown> = { userId };
if (since || until) {
const range: Record<string, Date> = {};
if (since) {
const d = new Date(since);
if (!Number.isNaN(d.getTime())) range.gte = d;
}
if (until) {
const d = new Date(until);
if (!Number.isNaN(d.getTime())) range.lte = d;
}
if (Object.keys(range).length > 0) {
where.startedAt = range;
}
}
if (sportType) {
where.sportType = sportType;
}
const rows = await prisma.workout.findMany({
where,
orderBy: [{ startedAt: "desc" }, { id: "asc" }],
select: {
id: true,
source: true,
externalId: true,
sportType: true,
startedAt: true,
endedAt: true,
durationSec: true,
totalDistanceM: true,
totalEnergyKcal: true,
avgHeartRate: true,
maxHeartRate: true,
createdAt: true,
},
});
const userRow = await prisma.user.findUnique({
where: { id: userId },
select: { sourcePriorityJson: true },
});
const canonical = pickCanonicalWorkoutRows(
rows,
userRow?.sourcePriorityJson ?? null,
);
const page = canonical.slice(offset, offset + limit).map((row) => ({
id: row.id,
sportType: row.sportType,
startedAt: row.startedAt,
endedAt: row.endedAt,
durationSec: row.durationSec,
distanceM: row.totalDistanceM,
activeEnergyKcal: row.totalEnergyKcal,
avgHr: row.avgHeartRate,
maxHr: row.maxHeartRate,
source: row.source,
externalId: row.externalId,
}));
return {
workouts: page,
meta: {
total: canonical.length,
limit,
offset,
droppedDuplicates: rows.length - canonical.length,
},
};
}
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "workouts.list" } });
@@ -79,80 +188,15 @@ export const GET = apiHandler(async (request: NextRequest) => {
const until = searchParams.get("until");
const sportType = searchParams.get("sportType");
const where: Record<string, unknown> = { userId: user.id };
if (since || until) {
const range: Record<string, Date> = {};
if (since) {
const d = new Date(since);
if (!Number.isNaN(d.getTime())) range.gte = d;
}
if (until) {
const d = new Date(until);
if (!Number.isNaN(d.getTime())) range.lte = d;
}
if (Object.keys(range).length > 0) {
where.startedAt = range;
}
}
if (sportType) {
where.sportType = sportType;
}
const params: WorkoutsParams = { limit, offset, since, until, sportType };
const cacheKey = `${user.id}|${limit}|${offset}|${since ?? ""}|${until ?? ""}|${sportType ?? ""}`;
// Read the full filtered set, descending start. The picker requires
// deterministic input order; the `(startedAt, id)` secondary sort
// pins the tie-break for rows that share a millisecond stamp.
const rows = await prisma.workout.findMany({
where,
orderBy: [{ startedAt: "desc" }, { id: "asc" }],
select: {
id: true,
source: true,
externalId: true,
sportType: true,
startedAt: true,
endedAt: true,
durationSec: true,
totalDistanceM: true,
totalEnergyKcal: true,
avgHeartRate: true,
maxHeartRate: true,
createdAt: true,
},
});
// Pass the user's source-priority blob so the picker honours the
// per-user ladder. The picker preserves input order on the returned
// subset; descending-start input → descending-start output.
const userRow = await prisma.user.findUnique({
where: { id: user.id },
select: { sourcePriorityJson: true },
});
const canonical = pickCanonicalWorkoutRows(
rows,
userRow?.sourcePriorityJson ?? null,
const result = await cached(
caches.workouts as ServerCache<WorkoutsResult>,
cacheKey,
() => buildWorkoutsResponse(user.id, params),
annotate,
);
const page = canonical.slice(offset, offset + limit).map((row) => ({
id: row.id,
sportType: row.sportType,
startedAt: row.startedAt,
endedAt: row.endedAt,
durationSec: row.durationSec,
distanceM: row.totalDistanceM,
activeEnergyKcal: row.totalEnergyKcal,
avgHr: row.avgHeartRate,
maxHr: row.maxHeartRate,
source: row.source,
externalId: row.externalId,
}));
return apiSuccess({
workouts: page,
meta: {
total: canonical.length,
limit,
offset,
droppedDuplicates: rows.length - canonical.length,
},
});
return apiSuccess(result);
});