From a68ec9421f0030b056a2a6f78ca3886b681e375a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc-Andr=C3=A9=20Bombeck?= Date: Tue, 17 Nov 2026 18:46:48 +0100 Subject: [PATCH] feat(nutrients): store daily nutrient targets per account A nullable users.nutrient_targets_json column (migration 0499) holds a target or limit per catalog code in the code's canonical unit. GET and PATCH /api/nutrients/targets read and merge it behind the nutrients module; PATCH refuses unknown codes and values above the code's plausibility cap, and audits the codes set, never the amounts. --- .../0499_user_nutrient_targets/migration.sql | 19 +++ prisma/schema.prisma | 7 + src/app/api/nutrients/targets/route.ts | 76 ++++++++++ ...eine-card.tsx => single-nutrient-card.tsx} | 0 src/lib/nutrients/targets.ts | 19 +++ src/lib/validations/nutrient-targets.ts | 141 ++++++++++++++++++ 6 files changed, 262 insertions(+) create mode 100644 prisma/migrations/0499_user_nutrient_targets/migration.sql create mode 100644 src/app/api/nutrients/targets/route.ts rename src/components/insights/nutrients/{caffeine-card.tsx => single-nutrient-card.tsx} (100%) create mode 100644 src/lib/nutrients/targets.ts create mode 100644 src/lib/validations/nutrient-targets.ts diff --git a/prisma/migrations/0499_user_nutrient_targets/migration.sql b/prisma/migrations/0499_user_nutrient_targets/migration.sql new file mode 100644 index 000000000..9559429a3 --- /dev/null +++ b/prisma/migrations/0499_user_nutrient_targets/migration.sql @@ -0,0 +1,19 @@ +-- Optional daily nutrient targets a person sets for themselves (#1402): +-- energy, protein and the other catalog codes, each a value in the code's +-- canonical unit and a direction (an amount to reach or one to stay under). +-- +-- Nullable, no default, no backfill: null reads as "no target set", which is +-- every account's state today. IF NOT EXISTS keeps a replay on a database +-- that already ran a build carrying the column harmless. Reversibility: +-- dropping the column removes the targets; the charts fall back to the +-- dietary reference. +-- +-- @retry-on-lock-timeout + +DO $migration$ +BEGIN + PERFORM set_config('lock_timeout', '5s', true); + ALTER TABLE "users" + ADD COLUMN IF NOT EXISTS "nutrient_targets_json" JSONB; +END +$migration$; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index c1077c52d..480a62222 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -429,6 +429,13 @@ model User { /// `/api/activity/goals`, read by the activity calendar /// (`/api/activity/calendar`), which reports progress against each goal set. activityGoalsJson Json? @map("activity_goals_json") + /// Optional daily nutrient targets the person set for themselves, keyed by + /// catalog code: `{ value, direction: "target" | "limit" }` in the code's + /// canonical unit. Null or an absent key = no target. Parsed by + /// `src/lib/validations/nutrient-targets.ts`, written through + /// `/api/nutrients/targets`, read by `/api/nutrients/daily` and the MCP + /// `get_nutrients` tool, whose charts prefer it over the dietary reference. + nutrientTargetsJson Json? @map("nutrient_targets_json") // Blood-glucose display unit preference. Canonical storage is mg/dL. glucoseUnit String? @map("glucose_unit") // "mg/dL" | "mmol/L" | null = default "mg/dL" // v1.18.6 — explicit "I have diabetes / clinician glucose targets" opt-in. diff --git a/src/app/api/nutrients/targets/route.ts b/src/app/api/nutrients/targets/route.ts new file mode 100644 index 000000000..80273873b --- /dev/null +++ b/src/app/api/nutrients/targets/route.ts @@ -0,0 +1,76 @@ +/** + * GET / PATCH the caller's daily nutrient targets (#1402). + * + * Every target is optional and set by the person; there is no default. PATCH + * replaces the codes the body names (`null` clears one) and keeps the rest; an + * unknown code or an out-of-range value is refused with the multi-issue 422. + * The targets live on their own `User` column (`nutrient_targets_json`); + * `GET /api/nutrients/daily` and the MCP `get_nutrients` tool return the one + * for the code they serve. Behind the opt-in `nutrients` module, like every + * other nutrient route. + */ +import { apiHandler, requireAuth } from "@/lib/api-handler"; +import { apiSuccess, getClientIp } from "@/lib/api-response"; +import { parseJsonBody } from "@/lib/api/body"; +import { auditLog } from "@/lib/auth/audit"; +import { Prisma } from "@/generated/prisma/client"; +import { prisma, toJson } from "@/lib/db"; +import { annotate } from "@/lib/logging/context"; +import { requireModuleEnabled } from "@/lib/modules/gate"; +import { readNutrientTargets } from "@/lib/nutrients/targets"; +import { + mergeNutrientTargets, + nutrientTargetCodes, + nutrientTargetsPatchSchema, +} from "@/lib/validations/nutrient-targets"; + +export const dynamic = "force-dynamic"; + +export const GET = apiHandler(async () => { + const { user } = await requireAuth(); + const gate = await requireModuleEnabled(user.id, "nutrients"); + if (!gate.enabled) return gate.response; + + const targets = await readNutrientTargets(user.id); + annotate({ + action: { name: "nutrient.targets.read" }, + meta: { set: nutrientTargetCodes(targets) }, + }); + return apiSuccess({ targets }); +}); + +export const PATCH = apiHandler(async (request: Request) => { + const { user } = await requireAuth(); + const gate = await requireModuleEnabled(user.id, "nutrients"); + if (!gate.enabled) return gate.response; + + const parsed = await parseJsonBody(request, nutrientTargetsPatchSchema, { + maxBytes: 8 * 1024, + action: "nutrient.targets.validation-failed", + }); + if (!parsed.ok) return parsed.error; + + const next = mergeNutrientTargets( + await readNutrientTargets(user.id), + parsed.data, + ); + const set = nutrientTargetCodes(next); + await prisma.user.update({ + where: { id: user.id }, + data: { + nutrientTargetsJson: set.length === 0 ? Prisma.DbNull : toJson(next), + }, + }); + + // Codes only, never the amounts: a target is a health figure. + await auditLog("nutrient.targets.update", { + userId: user.id, + ipAddress: getClientIp(request), + details: { set }, + }); + annotate({ + action: { name: "nutrient.targets.update" }, + meta: { set }, + }); + return apiSuccess({ targets: next }); +}); diff --git a/src/components/insights/nutrients/caffeine-card.tsx b/src/components/insights/nutrients/single-nutrient-card.tsx similarity index 100% rename from src/components/insights/nutrients/caffeine-card.tsx rename to src/components/insights/nutrients/single-nutrient-card.tsx diff --git a/src/lib/nutrients/targets.ts b/src/lib/nutrients/targets.ts new file mode 100644 index 000000000..470f73bac --- /dev/null +++ b/src/lib/nutrients/targets.ts @@ -0,0 +1,19 @@ +/** + * The read side of the person's daily nutrient targets (#1402), shared by the + * targets route, the daily series and the MCP `get_nutrients` tool. + */ +import { prisma } from "@/lib/db"; +import { + parseNutrientTargets, + type NutrientTargets, +} from "@/lib/validations/nutrient-targets"; + +export async function readNutrientTargets( + userId: string, +): Promise { + const row = await prisma.user.findUnique({ + where: { id: userId }, + select: { nutrientTargetsJson: true }, + }); + return parseNutrientTargets(row?.nutrientTargetsJson ?? null); +} diff --git a/src/lib/validations/nutrient-targets.ts b/src/lib/validations/nutrient-targets.ts new file mode 100644 index 000000000..b46e32730 --- /dev/null +++ b/src/lib/validations/nutrient-targets.ts @@ -0,0 +1,141 @@ +/** + * Daily nutrient targets a person sets for themselves (#1402). + * + * Stored in `User.nutrientTargetsJson`, keyed by catalog code. Each target is + * an amount in the code's canonical unit and a direction: `target` is an + * amount to reach (protein), `limit` one to stay under (sugar, sodium). Every + * code is optional and `null` clears it; an account that never set one stores + * nothing. The charts prefer the person's own number over the dietary + * reference; nothing here judges whether a target is sensible beyond the + * code's plausibility cap, which only stops a unit slip. + */ +import { z } from "zod/v4"; + +import { + NUTRIENT_CATALOG, + NUTRIENT_CODES, + type NutrientCode, +} from "@/lib/nutrients/catalog"; + +export interface NutrientTarget { + value: number; + direction: "target" | "limit"; +} + +/** The resolved targets: only the codes that carry one. */ +export type NutrientTargets = Partial>; + +function targetSchema(code: NutrientCode) { + return z + .object({ + value: z + .number() + .finite() + .positive() + .max(NUTRIENT_CATALOG[code].plausibleDailyMax), + direction: z.enum(["target", "limit"]), + }) + .strict(); +} + +const targetShape = Object.fromEntries( + NUTRIENT_CODES.map((code) => [ + code, + targetSchema(code).nullable().optional(), + ]), +) as Record< + NutrientCode, + z.ZodOptional>> +>; + +/** + * The PATCH body: `targets` names the codes to change, each a target or + * `null` to clear it. An unknown code is refused. + */ +export const nutrientTargetsPatchSchema = z + .object({ + targets: z + .object(targetShape) + .strict() + .describe( + "The codes to change, each `{ value, direction }` in the code's canonical unit (see the catalogue) or `null` to clear it. Codes left out stay as they were. `value` is above 0 and at most the code's plausibility cap.", + ), + }) + .strict() + .meta({ + id: "NutrientTargetsPatchRequest", + description: "Set or clear daily nutrient targets, code by code.", + }); + +export type NutrientTargetsPatch = z.infer; + +export const nutrientTargetsResponseSchema = z + .object({ + targets: z + .record( + z.string(), + z.object({ + value: z.number(), + direction: z.enum(["target", "limit"]), + }), + ) + .describe( + "Only the codes that carry a target. Decode unknown keys leniently.", + ), + }) + .meta({ + id: "NutrientTargets", + description: + "The daily nutrient targets the user set, keyed by catalog code, each in the code's canonical unit.", + }); + +/** Whether one stored entry is a valid target for `code`. */ +export function parseNutrientTarget( + code: NutrientCode, + raw: unknown, +): NutrientTarget | null { + const parsed = targetSchema(code).safeParse(raw); + return parsed.success ? parsed.data : null; +} + +/** + * Read a stored value. Anything that does not parse (a hand-edited row, a + * code a later release removed) reads code by code: a valid target survives, + * an invalid one reads as not set. Never throws. + */ +export function parseNutrientTargets(raw: unknown): NutrientTargets { + const out: NutrientTargets = {}; + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) { + return out; + } + const record = raw as Record; + for (const code of NUTRIENT_CODES) { + const target = parseNutrientTarget(code, record[code]); + if (target) + out[code] = { value: target.value, direction: target.direction }; + } + return out; +} + +/** + * Apply a validated PATCH: a code the body names replaces the stored target + * (`null` clears it), a code it leaves out stays. Built code by code, never by + * spreading the body. + */ +export function mergeNutrientTargets( + current: NutrientTargets, + patch: NutrientTargetsPatch, +): NutrientTargets { + const next: NutrientTargets = {}; + for (const code of NUTRIENT_CODES) { + const change = patch.targets[code]; + const kept = change === undefined ? current[code] : change; + if (kept) next[code] = { value: kept.value, direction: kept.direction }; + } + return next; +} + +/** The codes that carry a target, in catalogue order. */ +export function nutrientTargetCodes(targets: NutrientTargets): NutrientCode[] { + return NUTRIENT_CODES.filter((code) => targets[code] !== undefined); +}