feat(measurements): add custom metrics (define, log, chart)

Add a user-defined custom-metric store alongside the built-in measurements
on the Measurements surface. A user defines an arbitrary metric (name, unit,
optional target window, decimals, description), logs values, and charts them.

The store is a separate generic catalog + values pair, isolated from the
closed measurement-type system: not synced, not in FHIR, not in insights —
log and chart only. Names and units are plaintext, mirroring the biomarker
catalog. The inline list lives beneath the measurement list (no new nav
entry); tapping a metric opens a detail page with the trend chart, target
band, stat strip, and an editable value history.

Migration 0224 adds custom_metrics and custom_metric_entries.
This commit is contained in:
Marc-André Bombeck committed 2026-06-30 08:54:39 +02:00
1 parent 150b827d01
commit b3e6ba03d7
35 files changed
+4956

No files matched your search

@@ -0,0 +1,180 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
customMetric: { findFirst: vi.fn(), update: vi.fn() },
auditLog: { create: vi.fn().mockResolvedValue({}) },
},
}));
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, PATCH, DELETE } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "u", role: "USER" as const, locale: "en" },
};
const EXISTING = {
id: "cm-1",
userId: "user-1",
name: "Grip strength",
unit: "kg",
targetLow: 10,
targetHigh: 60,
decimals: 1,
description: null,
createdAt: new Date("2026-06-01T00:00:00.000Z"),
updatedAt: new Date("2026-06-01T00:00:00.000Z"),
deletedAt: null,
};
const params = (id: string) => ({ params: Promise.resolve({ id }) });
function patchReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/custom-metrics/cm-1", {
method: "PATCH",
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
});
}
function delReq(): NextRequest {
return new NextRequest("http://localhost/api/custom-metrics/cm-1", {
method: "DELETE",
});
}
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
});
describe("GET /api/custom-metrics/[id]", () => {
it("returns the metric for its owner", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(
EXISTING as never,
);
const res = await GET(
new NextRequest("http://localhost/api/custom-metrics/cm-1"),
params("cm-1"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as { data: { name: string } | null };
expect(body.data?.name).toBe("Grip strength");
});
it("404s a cross-user metric", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
...EXISTING,
userId: "other-user",
} as never);
const res = await GET(
new NextRequest("http://localhost/api/custom-metrics/cm-1"),
params("cm-1"),
);
expect(res.status).toBe(404);
});
});
describe("PATCH /api/custom-metrics/[id]", () => {
it("persists an updated target window", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(
EXISTING as never,
);
vi.mocked(prisma.customMetric.update).mockResolvedValue({
...EXISTING,
targetLow: 20,
targetHigh: 50,
} as never);
const res = await PATCH(
patchReq({ targetLow: 20, targetHigh: 50 }),
params("cm-1"),
);
expect(res.status).toBe(200);
const updateCall = vi.mocked(prisma.customMetric.update).mock
.calls[0][0] as { data: Record<string, unknown> };
expect(updateCall.data.targetLow).toBe(20);
expect(updateCall.data.targetHigh).toBe(50);
});
it("422s an inverted partial bound update without updating", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
// existing.targetHigh is 60; moving the low bound above it inverts.
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(
EXISTING as never,
);
const res = await PATCH(patchReq({ targetLow: 80 }), params("cm-1"));
expect(res.status).toBe(422);
expect(prisma.customMetric.update).not.toHaveBeenCalled();
});
it("409s a rename onto another live metric", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst)
.mockResolvedValueOnce(EXISTING as never)
.mockResolvedValueOnce({ id: "cm-other" } as never);
const res = await PATCH(patchReq({ name: "Other" }), params("cm-1"));
expect(res.status).toBe(409);
expect(prisma.customMetric.update).not.toHaveBeenCalled();
});
});
describe("DELETE /api/custom-metrics/[id]", () => {
it("soft-deletes by stamping deletedAt", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(
EXISTING as never,
);
vi.mocked(prisma.customMetric.update).mockResolvedValue(EXISTING as never);
const res = await DELETE(delReq(), params("cm-1"));
expect(res.status).toBe(200);
const updateCall = vi.mocked(prisma.customMetric.update).mock
.calls[0][0] as { data: { deletedAt: Date } };
expect(updateCall.data.deletedAt).toBeInstanceOf(Date);
});
it("404s a cross-user metric without deleting", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
...EXISTING,
userId: "other-user",
} as never);
const res = await DELETE(delReq(), params("cm-1"));
expect(res.status).toBe(404);
expect(prisma.customMetric.update).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,126 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
sanitiseZodIssues,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { serialiseCustomMetricEntry } from "@/lib/custom-metrics/custom-metric-store";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { updateCustomMetricEntrySchema } from "@/lib/validations/custom-metrics";
/**
* v1.25.5 — single logged value
* (`/api/custom-metrics/{id}/entries/{entryId}`).
*
* PATCH applies a partial edit (`data` built field-by-field; an explicit `null`
* on `note` clears it, an omitted key leaves the column untouched). DELETE
* hard-deletes the value. Every read/write is narrowed by both `userId` and the
* parent `customMetricId`; a cross-user or mismatched-parent id surfaces as 404.
*/
type RouteParams = { params: Promise<{ id: string; entryId: string }> };
export const PATCH = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id, entryId } = await params;
const existing = await prisma.customMetricEntry.findFirst({
where: { id: entryId, userId: user.id, customMetricId: id },
});
if (!existing) {
return apiError("Custom metric entry not found", 404);
}
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = updateCustomMetricEntrySchema.safeParse(body);
if (!parsed.success) {
annotate({
action: { name: "custom-metric.entry.update.validation-failed" },
meta: { issue_count: parsed.error.issues.length, entryId },
});
const auditIssues = sanitiseZodIssues(parsed.error.issues, {
stripValuesFromMessage: true,
});
prisma.auditLog
.create({
data: {
userId: user.id,
action: "custom-metric.entry.update.validation-failed",
details: JSON.stringify({ issues: auditIssues, entryId }),
},
})
.catch(() => {
/* swallow — the 422 response is the contract */
});
return returnAllZodIssues(parsed.error, 422);
}
const d = parsed.data;
// Build `data` field-by-field. `undefined` → leave the column untouched;
// an explicit `null` on `note` clears it.
const data: Record<string, unknown> = {};
if (d.value !== undefined) data.value = d.value;
if (d.measuredAt !== undefined) data.measuredAt = d.measuredAt;
if (d.note !== undefined) data.note = d.note;
const updated = await prisma.customMetricEntry.update({
where: { id: entryId },
data,
});
await auditLog("customMetricEntry.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: id, entryId },
});
annotate({
action: { name: "custom-metric.entry.update" },
meta: { customMetricId: id, entryId },
});
return apiSuccess(serialiseCustomMetricEntry(updated));
},
);
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id, entryId } = await params;
const existing = await prisma.customMetricEntry.findFirst({
where: { id: entryId, userId: user.id, customMetricId: id },
});
if (!existing) {
return apiError("Custom metric entry not found", 404);
}
await prisma.customMetricEntry.delete({ where: { id: entryId } });
await auditLog("customMetricEntry.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: id, entryId },
});
annotate({
action: { name: "custom-metric.entry.delete" },
meta: { customMetricId: id, entryId },
});
return apiSuccess({ deleted: true });
},
);
@@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
customMetric: { findFirst: vi.fn() },
customMetricEntry: {
findMany: vi.fn(),
count: vi.fn(),
create: vi.fn(),
},
auditLog: { create: vi.fn().mockResolvedValue({}) },
},
}));
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("@/lib/idempotency", () => ({
withIdempotency: (fn: unknown) => fn,
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET, POST } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "u", role: "USER" as const, locale: "en" },
};
const params = (id: string) => ({ params: Promise.resolve({ id }) });
const ENTRY = {
id: "e-1",
userId: "user-1",
customMetricId: "cm-1",
value: 42,
unit: "kg",
measuredAt: new Date("2026-06-10T00:00:00.000Z"),
note: null,
createdAt: new Date("2026-06-10T00:00:00.000Z"),
};
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
});
describe("GET /api/custom-metrics/[id]/entries", () => {
it("paginates the value feed and returns the total", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
id: "cm-1",
} as never);
vi.mocked(prisma.customMetricEntry.findMany).mockResolvedValue([
ENTRY,
] as never);
vi.mocked(prisma.customMetricEntry.count).mockResolvedValue(5 as never);
const res = await GET(
new NextRequest(
"http://localhost/api/custom-metrics/cm-1/entries?limit=1&offset=0&sortDir=desc",
),
params("cm-1"),
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { entries: unknown[]; meta: { total: number; limit: number } };
};
expect(body.data.entries).toHaveLength(1);
expect(body.data.meta.total).toBe(5);
expect(body.data.meta.limit).toBe(1);
const findCall = vi.mocked(prisma.customMetricEntry.findMany).mock
.calls[0][0] as { where: Record<string, unknown>; take: number };
expect(findCall.where.userId).toBe("user-1");
expect(findCall.where.customMetricId).toBe("cm-1");
expect(findCall.take).toBe(1);
});
it("404s a cross-user / unknown metric", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(null as never);
const res = await GET(
new NextRequest("http://localhost/api/custom-metrics/cm-x/entries"),
params("cm-x"),
);
expect(res.status).toBe(404);
expect(prisma.customMetricEntry.findMany).not.toHaveBeenCalled();
});
});
describe("POST /api/custom-metrics/[id]/entries", () => {
it("logs a value, snapshotting the metric's unit", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
id: "cm-1",
unit: "kg",
} as never);
vi.mocked(prisma.customMetricEntry.create).mockResolvedValue(
ENTRY as never,
);
const res = await POST(
new NextRequest("http://localhost/api/custom-metrics/cm-1/entries", {
method: "POST",
body: JSON.stringify({
value: 42,
measuredAt: "2026-06-10T00:00:00.000Z",
}),
headers: { "content-type": "application/json" },
}),
params("cm-1"),
);
expect(res.status).toBe(201);
const createCall = vi.mocked(prisma.customMetricEntry.create).mock
.calls[0][0] as { data: Record<string, unknown> };
expect(createCall.data.userId).toBe("user-1");
expect(createCall.data.customMetricId).toBe("cm-1");
expect(createCall.data.unit).toBe("kg");
expect(createCall.data.value).toBe(42);
});
it("404s when the parent metric is not the caller's", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(null as never);
const res = await POST(
new NextRequest("http://localhost/api/custom-metrics/cm-x/entries", {
method: "POST",
body: JSON.stringify({
value: 1,
measuredAt: "2026-06-10T00:00:00.000Z",
}),
headers: { "content-type": "application/json" },
}),
params("cm-x"),
);
expect(res.status).toBe(404);
expect(prisma.customMetricEntry.create).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,157 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
sanitiseZodIssues,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { serialiseCustomMetricEntry } from "@/lib/custom-metrics/custom-metric-store";
import { prisma } from "@/lib/db";
import { withIdempotency } from "@/lib/idempotency";
import { annotate } from "@/lib/logging/context";
import {
createCustomMetricEntrySchema,
listCustomMetricEntriesSchema,
} from "@/lib/validations/custom-metrics";
/**
* v1.25.5 — logged values for one custom metric
* (`/api/custom-metrics/{id}/entries`).
*
* GET lists the metric's values with offset pagination (the chart + history
* feed). POST records a value, snapshotting the metric's current `unit` onto
* the entry at write time (historical truth). `userId` is always narrowed from
* the session and the parent metric is verified owner-scoped (a forged / foreign
* id is a 404) before any value is read or written.
*/
type RouteParams = { params: Promise<{ id: string }> };
export const GET = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
const metric = await prisma.customMetric.findFirst({
where: { id, userId: user.id, deletedAt: null },
select: { id: true },
});
if (!metric) {
return apiError("Custom metric not found", 404);
}
const query = Object.fromEntries(request.nextUrl.searchParams);
const parsed = listCustomMetricEntriesSchema.safeParse(query);
if (!parsed.success) {
annotate({
action: { name: "custom-metric.entry.list.validation-failed" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422);
}
const { limit, offset, sortDir } = parsed.data;
const where = { userId: user.id, customMetricId: id };
const [rows, total] = await Promise.all([
prisma.customMetricEntry.findMany({
where,
orderBy: { measuredAt: sortDir },
take: limit,
skip: offset,
}),
prisma.customMetricEntry.count({ where }),
]);
annotate({
action: { name: "custom-metric.entry.list" },
meta: { customMetricId: id, total, limit, offset },
});
return apiSuccess({
entries: rows.map(serialiseCustomMetricEntry),
meta: { total, limit, offset },
});
},
);
export const POST = apiHandler(
withIdempotency<[NextRequest, RouteParams]>(postCustomMetricEntry),
);
async function postCustomMetricEntry(
request: NextRequest,
{ params }: RouteParams,
) {
const { user } = await requireAuth();
const { id } = await params;
const metric = await prisma.customMetric.findFirst({
where: { id, userId: user.id, deletedAt: null },
select: { id: true, unit: true },
});
if (!metric) {
return apiError("Custom metric not found", 404);
}
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = createCustomMetricEntrySchema.safeParse(body);
if (!parsed.success) {
annotate({
action: { name: "custom-metric.entry.create.validation-failed" },
meta: { issue_count: parsed.error.issues.length, customMetricId: id },
});
const auditIssues = sanitiseZodIssues(parsed.error.issues, {
stripValuesFromMessage: true,
});
prisma.auditLog
.create({
data: {
userId: user.id,
action: "custom-metric.entry.create.validation-failed",
details: JSON.stringify({ issues: auditIssues, customMetricId: id }),
},
})
.catch(() => {
/* swallow — the 422 response is the contract */
});
return returnAllZodIssues(parsed.error, 422);
}
const { value, measuredAt, note } = parsed.data;
// Field-by-field assignment — never spread `parsed.data`. The metric's
// current unit is snapshotted onto the entry as historical truth.
const created = await prisma.customMetricEntry.create({
data: {
userId: user.id,
customMetricId: metric.id,
value,
unit: metric.unit,
measuredAt,
note: note ?? null,
},
});
await auditLog("customMetricEntry.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: id, entryId: created.id },
});
annotate({
action: { name: "custom-metric.entry.create" },
meta: { customMetricId: id, entryId: created.id },
});
return apiSuccess(serialiseCustomMetricEntry(created), 201);
}
+185
View File
@@ -0,0 +1,185 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
sanitiseZodIssues,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { serialiseCustomMetric } from "@/lib/custom-metrics/custom-metric-store";
import { prisma } from "@/lib/db";
import { annotate } from "@/lib/logging/context";
import { updateCustomMetricSchema } from "@/lib/validations/custom-metrics";
/**
* v1.25.5 — single custom-metric resource (`/api/custom-metrics/{id}`).
*
* GET returns the metric definition. PATCH applies a partial edit (`data` built
* field-by-field; an explicit `null` clears `targetLow` / `targetHigh` /
* `decimals` / `description`, an omitted key leaves it untouched). DELETE
* soft-deletes by stamping `deletedAt`. Cross-user rows surface as 404
* (existence sealed).
*/
type RouteParams = { params: Promise<{ id: string }> };
/** Resolve an effective bound: the parsed value when present, else the stored. */
function effectiveBound(
parsed: number | null | undefined,
stored: number | null,
): number | null {
return parsed !== undefined ? parsed : stored;
}
export const GET = apiHandler(
async (_request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
const row = await prisma.customMetric.findFirst({
where: { id, deletedAt: null },
});
if (!row || row.userId !== user.id) {
return apiError("Custom metric not found", 404);
}
annotate({
action: { name: "custom-metric.metric.get" },
meta: { customMetricId: id },
});
return apiSuccess(serialiseCustomMetric(row));
},
);
export const PATCH = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
const existing = await prisma.customMetric.findFirst({
where: { id, deletedAt: null },
});
if (!existing || existing.userId !== user.id) {
return apiError("Custom metric not found", 404);
}
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = updateCustomMetricSchema.safeParse(body);
if (!parsed.success) {
annotate({
action: { name: "custom-metric.metric.update.validation-failed" },
meta: { issue_count: parsed.error.issues.length, customMetricId: id },
});
const auditIssues = sanitiseZodIssues(parsed.error.issues, {
stripValuesFromMessage: true,
});
prisma.auditLog
.create({
data: {
userId: user.id,
action: "custom-metric.metric.update.validation-failed",
details: JSON.stringify({
issues: auditIssues,
customMetricId: id,
}),
},
})
.catch(() => {
/* swallow — the 422 response is the contract */
});
return returnAllZodIssues(parsed.error, 422);
}
const d = parsed.data;
// A rename must not collide with another of the caller's LIVE metrics.
if (d.name !== undefined && d.name !== existing.name) {
const clash = await prisma.customMetric.findFirst({
where: { userId: user.id, name: d.name, deletedAt: null },
select: { id: true },
});
if (clash) {
return apiError("A custom metric with this name already exists", 409);
}
}
// Build `data` field-by-field. `undefined` → leave the column untouched;
// an explicit `null` on a target bound / decimals / description clears it.
const data: Record<string, unknown> = {};
if (d.name !== undefined) data.name = d.name;
if (d.unit !== undefined) data.unit = d.unit;
if (d.targetLow !== undefined) data.targetLow = d.targetLow;
if (d.targetHigh !== undefined) data.targetHigh = d.targetHigh;
if (d.decimals !== undefined) data.decimals = d.decimals;
if (d.description !== undefined) data.description = d.description;
// Inverted-range guard for a PARTIAL bound update. The schema refine only
// fires when both bounds arrive together; moving a single bound past the
// row's existing other bound would otherwise persist an inverted window.
const low = effectiveBound(d.targetLow, existing.targetLow);
const high = effectiveBound(d.targetHigh, existing.targetHigh);
if (low !== null && high !== null && low > high) {
return apiError("targetLow must not exceed targetHigh", 422);
}
const updated = await prisma.customMetric.update({ where: { id }, data });
await auditLog("customMetric.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: id },
});
annotate({
action: { name: "custom-metric.metric.update" },
meta: { customMetricId: id },
});
return apiSuccess(serialiseCustomMetric(updated));
},
);
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireAuth();
const { id } = await params;
const existing = await prisma.customMetric.findFirst({
where: { id, deletedAt: null },
});
if (!existing || existing.userId !== user.id) {
return apiError("Custom metric not found", 404);
}
// Soft-delete: stamp `deletedAt`. Every read filters `deletedAt: null`, so
// the metric is invisible from here on; its logged values are retained and
// a re-create under the same name revives the row (see POST). A re-delete
// is idempotent (the find above already filtered it out).
await prisma.customMetric.update({
where: { id },
data: { deletedAt: new Date() },
});
await auditLog("customMetric.delete", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: id },
});
annotate({
action: { name: "custom-metric.metric.delete" },
meta: { customMetricId: id },
});
return apiSuccess({ deleted: true });
},
);
@@ -0,0 +1,168 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
customMetric: {
findMany: vi.fn(),
findFirst: vi.fn(),
create: vi.fn(),
update: vi.fn(),
},
customMetricEntry: { findFirst: vi.fn(), count: vi.fn() },
auditLog: { create: vi.fn().mockResolvedValue({}) },
},
}));
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("@/lib/idempotency", () => ({
withIdempotency: (fn: unknown) => fn,
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { GET, POST } from "../route";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/db";
const SESSION_OK = {
session: { id: "sess-1", expiresAt: new Date(Date.now() + 3_600_000) },
user: { id: "user-1", username: "u", role: "USER" as const, locale: "en" },
};
function postReq(body: unknown): NextRequest {
return new NextRequest("http://localhost/api/custom-metrics", {
method: "POST",
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
});
}
const ROW = {
id: "cm-1",
userId: "user-1",
name: "Grip strength",
unit: "kg",
targetLow: null,
targetHigh: null,
decimals: null,
description: null,
createdAt: new Date("2026-06-01T00:00:00.000Z"),
updatedAt: new Date("2026-06-01T00:00:00.000Z"),
deletedAt: null,
};
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.auditLog.create).mockResolvedValue({} as never);
});
describe("GET /api/custom-metrics", () => {
it("lists the caller's metrics with the latest value", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findMany).mockResolvedValue([
{
...ROW,
entries: [
{
value: 42,
unit: "kg",
measuredAt: new Date("2026-06-10T00:00:00.000Z"),
},
],
_count: { entries: 3 },
},
] as never);
const res = await GET();
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { customMetrics: Array<{ latest: { value: number } | null }> };
};
expect(body.data.customMetrics).toHaveLength(1);
expect(body.data.customMetrics[0].latest?.value).toBe(42);
});
});
describe("POST /api/custom-metrics", () => {
it("creates a metric field-by-field", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue(null as never);
vi.mocked(prisma.customMetric.create).mockResolvedValue(ROW as never);
const res = await POST(postReq({ name: "Grip strength", unit: "kg" }));
expect(res.status).toBe(201);
const createCall = vi.mocked(prisma.customMetric.create).mock
.calls[0][0] as {
data: Record<string, unknown>;
};
expect(createCall.data.userId).toBe("user-1");
expect(createCall.data.name).toBe("Grip strength");
expect("userId" in createCall.data).toBe(true);
});
it("409s a duplicate live name without creating", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
id: "cm-existing",
deletedAt: null,
} as never);
const res = await POST(postReq({ name: "Grip strength", unit: "kg" }));
expect(res.status).toBe(409);
expect(prisma.customMetric.create).not.toHaveBeenCalled();
});
it("revives a soft-deleted metric of the same name", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
vi.mocked(prisma.customMetric.findFirst).mockResolvedValue({
id: "cm-old",
deletedAt: new Date("2026-05-01T00:00:00.000Z"),
} as never);
vi.mocked(prisma.customMetric.update).mockResolvedValue({
...ROW,
id: "cm-old",
} as never);
vi.mocked(prisma.customMetricEntry.findFirst).mockResolvedValue(
null as never,
);
vi.mocked(prisma.customMetricEntry.count).mockResolvedValue(0 as never);
const res = await POST(postReq({ name: "Grip strength", unit: "kg" }));
expect(res.status).toBe(201);
const updateCall = vi.mocked(prisma.customMetric.update).mock
.calls[0][0] as {
data: Record<string, unknown>;
};
expect(updateCall.data.deletedAt).toBeNull();
expect(prisma.customMetric.create).not.toHaveBeenCalled();
});
it("422s an inverted target range", async () => {
vi.mocked(getSession).mockResolvedValue(SESSION_OK as never);
const res = await POST(
postReq({ name: "X", unit: "kg", targetLow: 80, targetHigh: 20 }),
);
expect(res.status).toBe(422);
expect(prisma.customMetric.create).not.toHaveBeenCalled();
});
});
+172
View File
@@ -0,0 +1,172 @@
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
sanitiseZodIssues,
} from "@/lib/api-response";
import { auditLog } from "@/lib/auth/audit";
import { serialiseCustomMetricWithLatest } from "@/lib/custom-metrics/custom-metric-store";
import { prisma } from "@/lib/db";
import { withIdempotency } from "@/lib/idempotency";
import { annotate } from "@/lib/logging/context";
import { createCustomMetricSchema } from "@/lib/validations/custom-metrics";
/**
* v1.25.5 — user-defined custom-metric catalog (`/api/custom-metrics`).
*
* A SEPARATE generic store from the closed `MeasurementType` system: not synced,
* not in FHIR, not in AI insights — log + chart only. GET lists the caller's
* metrics with their latest logged value; POST defines a new one. `userId` is
* always narrowed from the session — never a body field — and the write `data`
* object is built field-by-field (no mass assignment). The `@@unique([userId,
* name])` index means there is never a second definition of the same name.
*/
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const rows = await prisma.customMetric.findMany({
where: { userId: user.id, deletedAt: null },
orderBy: { name: "asc" },
include: {
entries: {
orderBy: { measuredAt: "desc" },
take: 1,
select: { value: true, unit: true, measuredAt: true },
},
_count: { select: { entries: true } },
},
});
annotate({
action: { name: "custom-metric.metric.list" },
meta: { total: rows.length },
});
return apiSuccess({
customMetrics: rows.map((row) =>
serialiseCustomMetricWithLatest({
...row,
latest: row.entries[0] ?? null,
entryCount: row._count.entries,
}),
),
});
});
export const POST = apiHandler(
withIdempotency<[NextRequest]>(postCustomMetric),
);
async function postCustomMetric(request: NextRequest) {
const { user } = await requireAuth();
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = createCustomMetricSchema.safeParse(body);
if (!parsed.success) {
annotate({
action: { name: "custom-metric.metric.create.validation-failed" },
meta: { issue_count: parsed.error.issues.length },
});
const auditIssues = sanitiseZodIssues(parsed.error.issues, {
stripValuesFromMessage: true,
});
prisma.auditLog
.create({
data: {
userId: user.id,
action: "custom-metric.metric.create.validation-failed",
details: JSON.stringify({ issues: auditIssues }),
},
})
.catch(() => {
/* swallow — the 422 response is the contract */
});
return returnAllZodIssues(parsed.error, 422);
}
const { name, unit, targetLow, targetHigh, decimals, description } =
parsed.data;
// The `@@unique([userId, name])` index is the structural backstop and spans
// soft-deleted rows too. Resolve the name up front: a LIVE collision is a
// clean 409; a row that was previously soft-deleted under this name is
// REVIVED (un-deleted + redefined) rather than blocked by the index, so the
// user can re-create a metric they once removed.
const existing = await prisma.customMetric.findFirst({
where: { userId: user.id, name },
select: { id: true, deletedAt: true },
});
if (existing && existing.deletedAt === null) {
return apiError("A custom metric with this name already exists", 409);
}
// Field-by-field assignment — never spread `parsed.data`.
const created = existing
? await prisma.customMetric.update({
where: { id: existing.id },
data: {
unit,
targetLow: targetLow ?? null,
targetHigh: targetHigh ?? null,
decimals: decimals ?? null,
description: description ?? null,
deletedAt: null,
},
})
: await prisma.customMetric.create({
data: {
userId: user.id,
name,
unit,
targetLow: targetLow ?? null,
targetHigh: targetHigh ?? null,
decimals: decimals ?? null,
description: description ?? null,
},
});
await auditLog("customMetric.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: { customMetricId: created.id },
});
annotate({
action: { name: "custom-metric.metric.create" },
meta: { customMetricId: created.id, revived: existing !== null },
});
// A freshly created metric has no values; a revived one may retain entries
// logged before it was soft-deleted, so resolve the latest + count for it.
let latest: { value: number; unit: string; measuredAt: Date } | null = null;
let entryCount = 0;
if (existing) {
const [latestEntry, count] = await Promise.all([
prisma.customMetricEntry.findFirst({
where: { userId: user.id, customMetricId: created.id },
orderBy: { measuredAt: "desc" },
select: { value: true, unit: true, measuredAt: true },
}),
prisma.customMetricEntry.count({
where: { userId: user.id, customMetricId: created.id },
}),
]);
latest = latestEntry ?? null;
entryCount = count;
}
return apiSuccess(
serialiseCustomMetricWithLatest({ ...created, latest, entryCount }),
201,
);
}