mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 23:33:29 +00:00
feat(labs): show each marker's slope and where the line would leave the range
The biomarker detail read now carries a trend: the least-squares line through every numeric reading of the marker (all stored in its unit), with the slope's 95 % interval and p-value. It needs three readings over at least a year. The line is placed against the marker's band, and an exit date is given only when the interval excludes zero, the line is inside the band today and reaches a bound within three years. The detail page words it as a straight-line projection, not a forecast.
This commit is contained in:
1 parent
faa3ef867b
commit
2ba6214a65
20 files changed
+993
-11
No files matched your search
@@ -16,7 +16,7 @@ vi.mock("@/lib/db", () => {
|
||||
createMany: vi.fn(),
|
||||
},
|
||||
biomarkerMerge: { findFirst: vi.fn(async () => null) },
|
||||
labResult: { deleteMany: vi.fn() },
|
||||
labResult: { deleteMany: vi.fn(), findMany: vi.fn(async () => []) },
|
||||
auditLog: { create: vi.fn().mockResolvedValue({}) },
|
||||
};
|
||||
// `$transaction` is set in `beforeEach`: the batch form for the delete, the
|
||||
@@ -50,7 +50,7 @@ vi.mock("next/headers", () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
import { PUT, DELETE } from "../route";
|
||||
import { GET, PUT, DELETE } from "../route";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { prisma } from "@/lib/db";
|
||||
@@ -105,6 +105,56 @@ beforeEach(() => {
|
||||
vi.mocked(prisma.biomarkerMerge.findFirst).mockResolvedValue(null as never);
|
||||
});
|
||||
|
||||
describe("GET /api/biomarkers/[id] — trend (v1.44)", () => {
|
||||
const YEAR_MS = 365.25 * 86_400_000;
|
||||
const getReq = () =>
|
||||
new NextRequest("http://localhost/api/biomarkers/bm-1", { method: "GET" });
|
||||
|
||||
it("carries the marker's slope over every stored reading", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.biomarker.findFirst).mockResolvedValue(EXISTING as never);
|
||||
const t0 = Date.now() - 2 * YEAR_MS;
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([
|
||||
{ takenAt: new Date(t0), value: 60 },
|
||||
{ takenAt: new Date(t0 + YEAR_MS), value: 70 },
|
||||
{ takenAt: new Date(t0 + 2 * YEAR_MS), value: 80 },
|
||||
] as never);
|
||||
const res = await GET(getReq(), params("bm-1"));
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json();
|
||||
expect(body.data.name).toBe("LDL");
|
||||
expect(body.data.trend).toMatchObject({
|
||||
status: "ok",
|
||||
n: 3,
|
||||
slopePerYear: 10,
|
||||
projection: "exits",
|
||||
exitBound: "high",
|
||||
});
|
||||
expect(prisma.labResult.findMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
userId: "user-1",
|
||||
biomarkerId: "bm-1",
|
||||
deletedAt: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("answers insufficient below three readings", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
vi.mocked(prisma.biomarker.findFirst).mockResolvedValue(EXISTING as never);
|
||||
vi.mocked(prisma.labResult.findMany).mockResolvedValue([] as never);
|
||||
const body = await (await GET(getReq(), params("bm-1"))).json();
|
||||
expect(body.data.trend).toEqual({
|
||||
status: "insufficient",
|
||||
reason: "too_few_values",
|
||||
n: 0,
|
||||
spanDays: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/biomarkers/[id]", () => {
|
||||
it("drops the marker and its readings in one userId-narrowed transaction", async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
|
||||
|
||||
@@ -26,6 +26,10 @@ import { mergedInto } from "@/lib/labs/biomarker-merge";
|
||||
import { encryptContextToBytes } from "@/lib/labs/biomarker-store";
|
||||
import { matchAnalyteKey } from "@/lib/labs/analyte-match";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { computeLabTrend } from "@/lib/labs/lab-trend";
|
||||
|
||||
/** Upper bound on readings the trend line reads. */
|
||||
const LAB_TREND_READ_CAP = 2000;
|
||||
import { updateBiomarkerSchema } from "@/lib/validations/biomarkers";
|
||||
import { effectiveBound, isInvertedRange } from "@/lib/validations/labs";
|
||||
|
||||
@@ -58,14 +62,44 @@ export const GET = apiHandler(
|
||||
});
|
||||
}
|
||||
|
||||
const aliases = await aliasNamesByMarker(prisma, user.id, [row]);
|
||||
const [aliases, readings] = await Promise.all([
|
||||
aliasNamesByMarker(prisma, user.id, [row]),
|
||||
// v1.44 — the marker's numeric readings for the trend line. Every
|
||||
// reading is stored in the marker's unit, so the series needs no
|
||||
// conversion; the cap is far above any real panel history.
|
||||
prisma.labResult.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
biomarkerId: id,
|
||||
deletedAt: null,
|
||||
value: { not: null },
|
||||
},
|
||||
orderBy: { takenAt: "asc" },
|
||||
take: LAB_TREND_READ_CAP,
|
||||
select: { takenAt: true, value: true },
|
||||
}),
|
||||
]);
|
||||
const trend = computeLabTrend(
|
||||
readings.flatMap((r) =>
|
||||
r.value === null ? [] : [{ takenAt: r.takenAt, value: r.value }],
|
||||
),
|
||||
{ low: row.lowerBound, high: row.upperBound },
|
||||
new Date(),
|
||||
);
|
||||
|
||||
annotate({
|
||||
action: { name: "labs.biomarker.get" },
|
||||
meta: { biomarkerId: id },
|
||||
meta: {
|
||||
biomarkerId: id,
|
||||
trend: trend.status,
|
||||
...(trend.status === "ok" ? { projection: trend.projection } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
return apiSuccess(serialiseBiomarker(row, aliases.get(row.id) ?? []));
|
||||
return apiSuccess({
|
||||
...serialiseBiomarker(row, aliases.get(row.id) ?? []),
|
||||
trend,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
Reference in new issue
Block a user