From 8f57f5e0d794b5fded24b1268662d42a46474fd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Thu, 14 May 2026 16:01:26 +0200 Subject: [PATCH] feat(schema): PersonalRecord + direction helper (Migration 0054) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Schema-only release of the personal-records feature. Lands now so the v1.5 iOS-Swift app can build its query path against the GET /api/personal-records contract from day one; the detection worker that populates the rows is explicitly out of v1.4.25 scope and will land in v1.4.26 or v1.5. Schema (prisma/migrations/0054_personal_record): - PersonalRecordDirection enum (MAX | MIN) stored on the row so the future detection worker doesn't re-resolve direction at query time. - personal_records table: userId FK (cascade), metricType (MeasurementType enum), nullable metricSlot for sport-specific PRs, direction NOT NULL, value + unit + achievedAt, optional sourceMeasurementId (SET NULL on delete so PRs survive the underlying measurement), source provenance, externalId. - Composite unique (userId, metricType, metricSlot, achievedAt) for idempotent worker re-runs. - Index (userId, metricType, value) for the "current PR" read pattern (ORDER BY value DESC LIMIT 1 / ASC LIMIT 1). Direction helper (src/lib/personal-records/pr-direction.ts): - getPRDirection(MeasurementType) -> MAX | MIN | null. Exhaustive switch covering all 28 canonical enum values: MAX — steps, active energy, flights, distance, VO2 max, HRV, total body water, bone mass, muscle mass, time in daylight. MIN — resting HR, body fat, fat mass, visceral fat, vascular age, pulse-wave velocity, audio exposure (env + headphone). null — BP, glucose, body / skin temperature, pulse, SpO2, weight, sleep duration, fat-free mass (homeostatic, clinical-edge, or direction-ambiguous metrics; the v1.4.26 worker can enrich weight from User.thresholdsJson when it ships). - isPRTrackable() convenience predicate for the future worker. API surface (src/app/api/personal-records/route.ts): - GET returns { data: PersonalRecord[], error: null } (canonical apiSuccess envelope). - Optional ?metricType=X filter, validated against measurementTypeEnum; unknown values drop silently so a loose-typed caller never 400s. - No write endpoint, no detection worker — explicitly v1.4.26 scope. Tests (drift-guard + route): - pr-direction: every MeasurementType returns one of MAX / MIN / null; per-direction bucket membership pinned. - route: 401 unauth, empty response, valid filter passthrough, unknown-filter graceful drop, seeded-record round-trip. --- .../0054_personal_record/migration.sql | 50 +++++++ prisma/schema.prisma | 51 ++++++++ .../personal-records/__tests__/route.test.ts | 123 ++++++++++++++++++ src/app/api/personal-records/route.ts | 49 +++++++ .../__tests__/pr-direction.test.ts | 85 ++++++++++++ src/lib/personal-records/pr-direction.ts | 93 +++++++++++++ 6 files changed, 451 insertions(+) create mode 100644 prisma/migrations/0054_personal_record/migration.sql create mode 100644 src/app/api/personal-records/__tests__/route.test.ts create mode 100644 src/app/api/personal-records/route.ts create mode 100644 src/lib/personal-records/__tests__/pr-direction.test.ts create mode 100644 src/lib/personal-records/pr-direction.ts diff --git a/prisma/migrations/0054_personal_record/migration.sql b/prisma/migrations/0054_personal_record/migration.sql new file mode 100644 index 000000000..5f6792af5 --- /dev/null +++ b/prisma/migrations/0054_personal_record/migration.sql @@ -0,0 +1,50 @@ +-- v1.4.25 W8d — PersonalRecord schema (no detection worker yet). +-- +-- Schema lands now so the v1.5 iOS-Swift app can build its query path +-- against a real GET /api/personal-records route from day one. The +-- worker that populates the rows (sweep on insert / nightly job) is +-- explicitly out of v1.4.25 scope — see the deferred section in the +-- W8d phase report. v1.4.25 ships the bare list endpoint that returns +-- whatever rows the DB carries (initially empty for every user). +-- +-- Direction enum (MAX | MIN) is stored on the row rather than derived +-- at read time so the future worker doesn't re-resolve a per-metric +-- lookup on every query. Some metric types deliberately carry NULL +-- direction in the helper (BP, glucose, weight, ambiguous-direction +-- metrics) — those never produce a PersonalRecord row at all, so the +-- column stays NOT NULL for the metrics where a record is actually +-- defined. +-- +-- Composite uniqueness on (userId, metricType, metricSlot, achievedAt) +-- ensures the detection worker is idempotent — re-running it never +-- inserts a duplicate. A multi-source tie (e.g. iPhone + Apple Watch +-- both report 12_348 steps for the same day) is broken by including +-- `source` so each provenance retains its row; the display layer +-- runs the existing pickCanonicalSourceRows() helper to surface one. + +CREATE TYPE "personal_record_direction" AS ENUM ('MAX', 'MIN'); + +CREATE TABLE "personal_records" ( + "id" TEXT PRIMARY KEY, + "user_id" TEXT NOT NULL REFERENCES "users"("id") ON DELETE CASCADE, + "metric_type" "measurement_type" NOT NULL, + -- Sport-specific slot for workout-driven PRs (e.g. "running_5km_time"). + -- NULL for measurement-driven PRs that don't need a sport dimension. + "metric_slot" TEXT, + "direction" "personal_record_direction" NOT NULL, + "value" DOUBLE PRECISION NOT NULL, + "unit" TEXT NOT NULL, + "achieved_at" TIMESTAMP(3) NOT NULL, + -- FK to the Measurement row that achieved the record. SET NULL on + -- delete so a PR survives the deletion of the originating + -- measurement (the PR is the historical fact, not a derived view). + "source_measurement_id" TEXT REFERENCES "measurements"("id") ON DELETE SET NULL, + "source" "measurement_source" NOT NULL DEFAULT 'MANUAL', + "external_id" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE UNIQUE INDEX "personal_records_dedup_key" + ON "personal_records" ("user_id", "metric_type", "metric_slot", "achieved_at"); +CREATE INDEX "personal_records_user_metric_idx" + ON "personal_records" ("user_id", "metric_type", "value"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 222ce50e0..39b64ef15 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -190,6 +190,11 @@ model User { // (1:1), not User — the User → WorkoutRoute path is two hops by // design. workouts Workout[] + // v1.4.25 W8d — personal records (schema only; detection worker + // lands in a later release). The GET /api/personal-records route + // ships with v1.4.25 so the iOS app can build its query path + // against a stable contract. + personalRecords PersonalRecord[] @@map("users") } @@ -444,6 +449,52 @@ model WorkoutRoute { @@map("workout_routes") } +// ─── Personal records (v1.4.25 W8d — schema only) ────────── +// +// MAX vs MIN direction is stored on the row so the future detection +// worker doesn't have to re-resolve a per-metric lookup at query time. +// Some metric types deliberately have no PR (blood pressure, glucose, +// raw weight without a goal direction); those never produce rows. +// See src/lib/personal-records/pr-direction.ts for the lookup table. +enum PersonalRecordDirection { + MAX // higher is the record (steps, VO2 max, HRV, distance, daylight) + MIN // lower is the record (resting HR, body fat, audio exposure) + + @@map("personal_record_direction") +} + +model PersonalRecord { + id String @id @default(cuid()) + userId String @map("user_id") + metricType MeasurementType @map("metric_type") + /// Per-sport-type bucket for workout-driven PRs (e.g. + /// "running_5km_time"). NULL for plain measurement-driven PRs + /// where the metric type alone is the dimension. + metricSlot String? @map("metric_slot") + direction PersonalRecordDirection + value Float + unit String + achievedAt DateTime @map("achieved_at") + /// FK to the Measurement row that achieved the record. SET NULL + /// on delete so the historical fact survives even if the + /// underlying measurement is later removed. + sourceMeasurementId String? @map("source_measurement_id") + source MeasurementSource @default(MANUAL) + externalId String? @map("external_id") + createdAt DateTime @default(now()) @map("created_at") + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + /// Idempotency guard for the detection worker — re-running it on + /// the same (user, metric, slot, achievedAt) triple is a no-op. + @@unique([userId, metricType, metricSlot, achievedAt]) + /// Hot read pattern — "current PR for this metric": + /// ORDER BY value DESC LIMIT 1 (MAX direction) / + /// ASC LIMIT 1 (MIN direction). Index covers both. + @@index([userId, metricType, value]) + @@map("personal_records") +} + // ─── Medications ─────────────────────────────────────────── /// Treatment-class discriminator (v1.4.25 W4d). GLP1 turns on the diff --git a/src/app/api/personal-records/__tests__/route.test.ts b/src/app/api/personal-records/__tests__/route.test.ts new file mode 100644 index 000000000..fdd680837 --- /dev/null +++ b/src/app/api/personal-records/__tests__/route.test.ts @@ -0,0 +1,123 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { NextRequest } from "next/server"; + +vi.mock("@/lib/db", () => ({ + prisma: { + personalRecord: { + findMany: 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 }, +}; + +function req(url: string): NextRequest { + return new NextRequest(url, { method: "GET" }); +} + +beforeEach(() => { + vi.resetAllMocks(); + vi.mocked(prisma.personalRecord.findMany).mockResolvedValue([]); +}); + +describe("GET /api/personal-records", () => { + it("returns 401 when unauthenticated", async () => { + vi.mocked(getSession).mockResolvedValue(null); + const res = await GET(req("http://localhost/api/personal-records")); + expect(res.status).toBe(401); + }); + + it("returns an empty list for a user with no records", async () => { + vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); + const res = await GET(req("http://localhost/api/personal-records")); + expect(res.status).toBe(200); + const body = (await res.json()) as { data: unknown[]; error: null }; + expect(body.data).toEqual([]); + expect(body.error).toBeNull(); + expect(prisma.personalRecord.findMany).toHaveBeenCalledWith({ + where: { userId: "user-1" }, + orderBy: { achievedAt: "desc" }, + }); + }); + + it("passes through a valid metricType filter", async () => { + vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); + const res = await GET( + req("http://localhost/api/personal-records?metricType=VO2_MAX"), + ); + expect(res.status).toBe(200); + expect(prisma.personalRecord.findMany).toHaveBeenCalledWith({ + where: { userId: "user-1", metricType: "VO2_MAX" }, + orderBy: { achievedAt: "desc" }, + }); + }); + + it("drops an unknown metricType silently (loose-typed filter contract)", async () => { + vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); + const res = await GET( + req("http://localhost/api/personal-records?metricType=BOGUS"), + ); + expect(res.status).toBe(200); + expect(prisma.personalRecord.findMany).toHaveBeenCalledWith({ + where: { userId: "user-1" }, + orderBy: { achievedAt: "desc" }, + }); + }); + + it("seeded record round-trips through the response", async () => { + vi.mocked(getSession).mockResolvedValue(SESSION_OK as never); + const fakeRecord = { + id: "pr-1", + userId: "user-1", + metricType: "VO2_MAX", + metricSlot: null, + direction: "MAX", + value: 47.2, + unit: "mL/(kg·min)", + achievedAt: new Date("2026-05-01T07:00:00.000Z"), + sourceMeasurementId: "m-1", + source: "APPLE_HEALTH", + externalId: null, + createdAt: new Date(), + }; + vi.mocked(prisma.personalRecord.findMany).mockResolvedValue([ + fakeRecord, + ] as never); + const res = await GET(req("http://localhost/api/personal-records")); + expect(res.status).toBe(200); + const body = (await res.json()) as { + data: Array<{ value: number; metricType: string }>; + }; + expect(body.data).toHaveLength(1); + expect(body.data[0].value).toBe(47.2); + expect(body.data[0].metricType).toBe("VO2_MAX"); + }); +}); diff --git a/src/app/api/personal-records/route.ts b/src/app/api/personal-records/route.ts new file mode 100644 index 000000000..38ef270fe --- /dev/null +++ b/src/app/api/personal-records/route.ts @@ -0,0 +1,49 @@ +/** + * GET /api/personal-records + * + * v1.4.25 W8d — schema-only release of the PersonalRecord feature. + * The detection worker that actually populates rows lands in a later + * release (v1.4.26 or v1.5 — TBD). This route exists today so the + * v1.5 iOS-Swift app can build its query path against a stable + * contract from day one. + * + * Query params: + * - metricType: optional MeasurementType filter (e.g. ?metricType=VO2_MAX) + * + * Response envelope (matches the project-wide `apiSuccess` contract): + * { data: PersonalRecord[], error: null } + */ +import { prisma } from "@/lib/db"; +import type { NextRequest } from "next/server"; +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { annotate } from "@/lib/logging/context"; +import { apiSuccess } from "@/lib/api-response"; +import { measurementTypeEnum } from "@/lib/validations/measurement"; +import type { MeasurementType } from "@/generated/prisma/client"; + +export const dynamic = "force-dynamic"; + +export const GET = apiHandler(async (request: NextRequest) => { + const { user } = await requireAuth(); + annotate({ action: { name: "personalRecords.list" } }); + + const { searchParams } = new URL(request.url); + const metricTypeParam = searchParams.get("metricType"); + + // Defensive parse — drop unknown values rather than 400 so the + // caller's loosely-typed filter doesn't take the page down. + const metricType: MeasurementType | null = + metricTypeParam && measurementTypeEnum.safeParse(metricTypeParam).success + ? (metricTypeParam as MeasurementType) + : null; + + const records = await prisma.personalRecord.findMany({ + where: { + userId: user.id, + ...(metricType ? { metricType } : {}), + }, + orderBy: { achievedAt: "desc" }, + }); + + return apiSuccess(records); +}); diff --git a/src/lib/personal-records/__tests__/pr-direction.test.ts b/src/lib/personal-records/__tests__/pr-direction.test.ts new file mode 100644 index 000000000..480eb01a3 --- /dev/null +++ b/src/lib/personal-records/__tests__/pr-direction.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from "vitest"; +import { getPRDirection, isPRTrackable } from "../pr-direction"; +import { measurementTypeEnum } from "@/lib/validations/measurement"; +import { + PersonalRecordDirection, + type MeasurementType, +} from "@/generated/prisma/client"; + +describe("getPRDirection", () => { + // Drift guard — every canonical MeasurementType MUST land in exactly + // one branch of the switch so the future detection worker never + // encounters an "I have a sample but no direction" race. + it("returns either MAX, MIN, or null for every MeasurementType", () => { + for (const type of measurementTypeEnum.options) { + const result = getPRDirection(type as MeasurementType); + expect( + result === null || + result === PersonalRecordDirection.MAX || + result === PersonalRecordDirection.MIN, + `getPRDirection(${type}) returned ${result}`, + ).toBe(true); + } + }); + + it("returns MAX for the activity + daylight + 'higher is better' metrics", () => { + const maxMetrics: MeasurementType[] = [ + "ACTIVITY_STEPS", + "ACTIVE_ENERGY_BURNED", + "FLIGHTS_CLIMBED", + "WALKING_RUNNING_DISTANCE", + "VO2_MAX", + "HEART_RATE_VARIABILITY", + "TOTAL_BODY_WATER", + "BONE_MASS", + "MUSCLE_MASS", + "TIME_IN_DAYLIGHT", + ]; + for (const t of maxMetrics) { + expect(getPRDirection(t)).toBe(PersonalRecordDirection.MAX); + } + }); + + it("returns MIN for resting HR + composition + cardiovascular-risk + audio", () => { + const minMetrics: MeasurementType[] = [ + "RESTING_HEART_RATE", + "BODY_FAT", + "FAT_MASS", + "VISCERAL_FAT", + "VASCULAR_AGE", + "PULSE_WAVE_VELOCITY", + "AUDIO_EXPOSURE_ENV", + "AUDIO_EXPOSURE_HEADPHONE", + ]; + for (const t of minMetrics) { + expect(getPRDirection(t)).toBe(PersonalRecordDirection.MIN); + } + }); + + it("returns null for BP, glucose, weight, sleep, and homeostatic vitals", () => { + const noPRMetrics: MeasurementType[] = [ + "BLOOD_PRESSURE_SYS", + "BLOOD_PRESSURE_DIA", + "BLOOD_GLUCOSE", + "BODY_TEMPERATURE", + "SKIN_TEMPERATURE", + "PULSE", + "OXYGEN_SATURATION", + "WEIGHT", + "SLEEP_DURATION", + "FAT_FREE_MASS", + ]; + for (const t of noPRMetrics) { + expect(getPRDirection(t)).toBeNull(); + } + }); +}); + +describe("isPRTrackable", () => { + it("returns true exactly when getPRDirection is non-null", () => { + for (const type of measurementTypeEnum.options) { + const t = type as MeasurementType; + expect(isPRTrackable(t)).toBe(getPRDirection(t) !== null); + } + }); +}); diff --git a/src/lib/personal-records/pr-direction.ts b/src/lib/personal-records/pr-direction.ts new file mode 100644 index 000000000..7b032a795 --- /dev/null +++ b/src/lib/personal-records/pr-direction.ts @@ -0,0 +1,93 @@ +/** + * MeasurementType → PersonalRecordDirection resolver. + * + * Stored vocabulary is `MAX` (higher is the record) or `MIN` (lower is + * the record). A `null` return value means "this metric does not have + * a PersonalRecord" — the future detection worker short-circuits on + * those types so it never writes a row that has ambiguous semantics. + * + * Buckets (full rationale in W8d implementation outline §5): + * + * MAX direction: + * * Activity & daylight — more is the achievement. + * * VO2 max, HRV, fat-free / muscle mass, total body water, + * bone mass — biomarkers where a higher value is the goal. + * + * MIN direction: + * * Resting heart rate — lower = better cardiovascular fitness. + * * Body fat, fat mass, visceral fat — composition metrics + * where lower is the goal. + * * Vascular age, pulse-wave velocity — lower = healthier + * arteries. + * * Audio exposure — lower = less hearing damage. The "record" + * is the quietest day (kept here for symmetry; the detection + * worker can still flag a too-loud day separately). + * + * null (no PR): + * * Blood pressure (high reading isn't an achievement; low can + * also be clinically bad), blood glucose (extremes both ways), + * body & skin temperature (homeostatic, not a goal), pulse + * (spot-reading), oxygen saturation (homeostatic), weight + * (direction is user-goal-dependent — to defer until the + * v1.4.26 worker can read User.thresholdsJson), sleep duration + * (longer is not strictly better), fat-free mass when treated + * as a derived (weight − fat) value with the same ambiguity. + * + * Adding a new MeasurementType: extend the switch below. The + * drift-guard test in `__tests__/pr-direction.test.ts` asserts every + * canonical enum value lands in exactly one branch. + */ +import type { MeasurementType } from "@/generated/prisma/client"; +import { PersonalRecordDirection } from "@/generated/prisma/client"; + +export function getPRDirection( + metricType: MeasurementType, +): PersonalRecordDirection | null { + switch (metricType) { + // MAX direction — higher value is the record. + case "ACTIVITY_STEPS": + case "ACTIVE_ENERGY_BURNED": + case "FLIGHTS_CLIMBED": + case "WALKING_RUNNING_DISTANCE": + case "VO2_MAX": + case "HEART_RATE_VARIABILITY": + case "TOTAL_BODY_WATER": + case "BONE_MASS": + case "MUSCLE_MASS": + case "TIME_IN_DAYLIGHT": + return PersonalRecordDirection.MAX; + + // MIN direction — lower value is the record. + case "RESTING_HEART_RATE": + case "BODY_FAT": + case "FAT_MASS": + case "VISCERAL_FAT": + case "VASCULAR_AGE": + case "PULSE_WAVE_VELOCITY": + case "AUDIO_EXPOSURE_ENV": + case "AUDIO_EXPOSURE_HEADPHONE": + return PersonalRecordDirection.MIN; + + // Explicitly no PersonalRecord — see comment block above. + case "BLOOD_PRESSURE_SYS": + case "BLOOD_PRESSURE_DIA": + case "BLOOD_GLUCOSE": + case "BODY_TEMPERATURE": + case "SKIN_TEMPERATURE": + case "PULSE": + case "OXYGEN_SATURATION": + case "WEIGHT": + case "SLEEP_DURATION": + case "FAT_FREE_MASS": + return null; + } +} + +/** + * Convenience predicate for the future detection worker: + * `if (!isPRTrackable(type)) return;` keeps the worker from writing + * rows that wouldn't have a defined direction anyway. + */ +export function isPRTrackable(metricType: MeasurementType): boolean { + return getPRDirection(metricType) !== null; +}