mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-09 21:10:59 +00:00
feat(insights): let a caller choose the derived-metric window
`GET /api/insights/derived` accepts `windowDays`, bounded to 1..90, and threads it to the dispatcher. Omitting it changes nothing: every engine keeps its own default, so a caller that asks for nothing reads exactly what it read before. Ninety is where the tier this route promises runs out. The rollup router opens its WEEK floor at 91 days, and the baseline engines cannot compose a spread from WEEK buckets, so a 91-day request falls through to a raw `measurement.findMany` with no row cap — for a densely sampled type that is a full history scan, and the analytics-read budget allows 120 of them a minute per account. The trailing `series` is capped at 30 points regardless, so past the ceiling a wider window would only broaden the mean behind the value. Out of range is a 422 rather than a clamp. An unhonoured window is visible rather than silent. `provenance.windowDays` is the window the engine actually used and `coverage.historyDays` the days that actually backed it, so a three-week record answering a thirty-day request reports both numbers instead of implying coverage it does not have. `HEALTH_SCORE` composes fixed per-pillar windows and reports the widest; a new suite freezes that it is the only metric that does, so an arm added later cannot quietly drop the parameter. Recovery keeps its canonical resolution under the wider window. A worn band stamps the wake morning and the computed proxy the night before, and only `resolveCanonicalRecovery` pairs them; a test seeds forty such nights, asks for sixty days, and holds the answer to forty nights with a flat trend — a bypass leaves eighty rows and a false climb. Contract: model `WellnessScoreValue` field for field and publish it. The envelope's `value` has to stay an open record because one route serves eighteen differently-shaped metrics, so nothing can `$ref` the shape and it went out undocumented — `series`, `daysInWindow` and `asOf` were on the wire with no way to find them short of inspecting a live response. It is registered in the forced-components slot instead, held against the runtime interface by a test, and the fields it does not cover are named in the schema comment so the remaining gap is known rather than invisible.
This commit is contained in:
1 parent
d290422923
commit
d7d8e437ee
11 files changed
+659
-9
No files matched your search
@@ -89,6 +89,7 @@ import { GET } from "../route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { computeDerivedMetric } from "@/lib/insights/derived";
|
||||
import { DERIVED_MAX_WINDOW_DAYS } from "@/lib/insights/derived/types";
|
||||
|
||||
const SESSION_OK = {
|
||||
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
|
||||
@@ -108,6 +109,14 @@ function makeReq(metric?: string, type?: string): NextRequest {
|
||||
return new NextRequest(url);
|
||||
}
|
||||
|
||||
function makeReqWith(params: Record<string, string>): NextRequest {
|
||||
const url = new URL("http://localhost/api/insights/derived");
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
url.searchParams.set(key, value);
|
||||
}
|
||||
return new NextRequest(url);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(prisma.appSettings.findUnique).mockResolvedValue(null as never);
|
||||
@@ -205,3 +214,59 @@ describe("GET /api/insights/derived", () => {
|
||||
expect(body.data?.reason).toBe("no_readings_in_window");
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/insights/derived — windowDays", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
});
|
||||
|
||||
it("threads a caller-supplied window into the compute call", async () => {
|
||||
await callGet(makeReqWith({ metric: "VITALS_BASELINE", windowDays: "30" }));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ metric: "VITALS_BASELINE", windowDays: 30 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves the window undefined when the caller omits it, so each engine keeps its own default", async () => {
|
||||
await callGet(makeReq("VITALS_BASELINE"));
|
||||
expect(computeDerivedMetric).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ windowDays: undefined }),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts the ceiling exactly", async () => {
|
||||
const res = await callGet(
|
||||
makeReqWith({
|
||||
metric: "VITALS_BASELINE",
|
||||
windowDays: String(DERIVED_MAX_WINDOW_DAYS),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(computeDerivedMetric).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ windowDays: DERIVED_MAX_WINDOW_DAYS }),
|
||||
);
|
||||
});
|
||||
|
||||
it("422s one day past the ceiling without touching the compute layer", async () => {
|
||||
const res = await callGet(
|
||||
makeReqWith({
|
||||
metric: "VITALS_BASELINE",
|
||||
windowDays: String(DERIVED_MAX_WINDOW_DAYS + 1),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(422);
|
||||
expect(computeDerivedMetric).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("422s on a zero, negative, fractional or non-numeric window", async () => {
|
||||
for (const windowDays of ["0", "-7", "1.5", "thirty", ""]) {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
const res = await callGet(
|
||||
makeReqWith({ metric: "VITALS_BASELINE", windowDays }),
|
||||
);
|
||||
expect(res.status, `windowDays=${windowDays}`).toBe(422);
|
||||
expect(computeDerivedMetric).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* v1.10.0 — generic derived-wellness-metric route.
|
||||
*
|
||||
* `GET /api/insights/derived?metric=<DERIVED_METRIC_ID>[&type=<MeasurementType>]`
|
||||
* `GET /api/insights/derived?metric=<DERIVED_METRIC_ID>[&type=<MeasurementType>][&windowDays=N]`
|
||||
* serves the compute-once `Derived<T>` value for any metric registered
|
||||
* in `derived/registry.ts`. Mirrors the v1.8.7.1 `metric-status` route
|
||||
* precedent: `apiHandler` wrapper, Zod `safeParse` on the query, a closed
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
DERIVED_METRIC_IDS,
|
||||
type DerivedMetricId,
|
||||
} from "@/lib/insights/derived";
|
||||
import { DERIVED_MAX_WINDOW_DAYS } from "@/lib/insights/derived/types";
|
||||
import { resolveDerivedAssessment } from "@/lib/insights/derived/derived-assessment-ai";
|
||||
import { resolveServerLocale } from "@/lib/i18n/server-locale";
|
||||
|
||||
@@ -66,6 +67,20 @@ const derivedQuerySchema = z.object({
|
||||
// the dispatcher; an unsupported value yields an `insufficient`, not a
|
||||
// 422, so the contract stays forgiving for iOS combinations.
|
||||
type: z.string().optional(),
|
||||
// Trailing window override, in days. Absent means "engine default" — each
|
||||
// compute keeps its own (14 for the wellness trend, 30 for the baselines, a
|
||||
// year for vascular age), so omitting the parameter changes nothing. The
|
||||
// ceiling is the point past which the derived engines stop resolving against
|
||||
// DAY rollup buckets and degrade to an uncapped raw read; the reasoning is
|
||||
// written out at `DERIVED_MAX_WINDOW_DAYS`. Out of range is a 422 rather
|
||||
// than a silent clamp: a caller that asked for a year should learn that it
|
||||
// is not on offer, not read back a number it did not choose.
|
||||
windowDays: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(DERIVED_MAX_WINDOW_DAYS)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
@@ -88,6 +103,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const parsed = derivedQuerySchema.safeParse({
|
||||
metric: request.nextUrl.searchParams.get("metric"),
|
||||
type: request.nextUrl.searchParams.get("type") ?? undefined,
|
||||
windowDays: request.nextUrl.searchParams.get("windowDays") ?? undefined,
|
||||
});
|
||||
if (!parsed.success) {
|
||||
annotate({
|
||||
@@ -113,11 +129,21 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
userId: user.id,
|
||||
profile,
|
||||
type: parsed.data.type ?? null,
|
||||
windowDays: parsed.data.windowDays,
|
||||
});
|
||||
|
||||
annotate({
|
||||
action: { name: "insights.derived" },
|
||||
meta: { metric, status: derived.status },
|
||||
meta: {
|
||||
metric,
|
||||
status: derived.status,
|
||||
// Both halves of the window story: what the caller asked for (null when
|
||||
// they asked for nothing) and what the engine actually read. They differ
|
||||
// for a metric that composes fixed per-pillar windows, and a dashboard
|
||||
// that sees them drift apart is looking at a real answer, not a bug.
|
||||
window_days_requested: parsed.data.windowDays ?? null,
|
||||
window_days_effective: derived.provenance.windowDays,
|
||||
},
|
||||
});
|
||||
|
||||
// v1.13.2 — additive per-score assessment: a short "why is this score what
|
||||
|
||||
Reference in new issue
Block a user