feat(nutrients): carry daily targets through backup, wipe and the API contract

Nutrient targets travel in the account-settings slice of the full
backup and are admitted code by code on restore, so an unknown code or
an out-of-range value is dropped and named while the rest come back. A
data wipe clears them. The targets route joins the OpenAPI registry,
and the regenerated contract carries the wider nutrient enums, the new
sources and the target and authority fields. Refs #1402.
This commit is contained in:
Marc-André Bombeck committed 2026-11-17 19:05:31 +01:00
1 parent 7c40ba8202
commit db0e4f9688
18 files changed
+1470 -381

No files matched your search

@@ -1,208 +0,0 @@
/**
* `POST /api/nutrients/batch` under a narrow `measurements:write` token.
*
* The credential picks the source row: a bridge token writes EXTERNAL in the
* probe, the insert and the update, counts in its own rate-limit bucket, and
* says so in the audit row; the native client keeps writing APPLE_HEALTH.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
nutrientIntakeDay: {
findMany: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
},
$transaction: vi.fn(),
},
}));
vi.mock("@/lib/api-handler", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api-handler")>();
return { ...actual, requireAuth: vi.fn() };
});
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/idempotency", () => ({
withIdempotency:
<Args extends unknown[]>(fn: (...args: Args) => Promise<Response>) =>
(...args: Args) =>
fn(...args),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserHealthContext: vi.fn(),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
const USER = { id: "user-1", username: "tester", role: "USER" as const };
function asBridge() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "t" },
user: USER,
bearerScope: MEASUREMENTS_WRITE_SCOPE,
} as never);
}
function asPhone() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "s" },
user: USER,
} as never);
}
function post(entries: unknown[]): Promise<Response> {
return POST(
new NextRequest("http://localhost/api/nutrients/batch", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ entries }),
}),
);
}
const ENERGY = {
day: "2026-11-01",
nutrient: "energy",
unit: "kcal",
amount: 2100,
};
const PROTEIN = {
day: "2026-11-02",
nutrient: "protein",
unit: "g",
amount: 95,
};
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
vi.mocked(auditLog).mockResolvedValue(undefined as never);
// ENERGY's day already exists, PROTEIN's is new.
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([
{ day: ENERGY.day, nutrient: "energy" },
] as never);
vi.mocked(prisma.nutrientIntakeDay.createMany).mockImplementation(
(async (args: { data: unknown[] }) => ({
count: args.data.length,
})) as never,
);
vi.mocked(prisma.nutrientIntakeDay.update).mockResolvedValue({} as never);
vi.mocked(prisma.$transaction).mockImplementation((async (ops: unknown[]) =>
Promise.all(ops)) as never);
});
describe("POST /api/nutrients/batch with a measurements:write token", () => {
it("asks requireAuth for the measurements:write scope", async () => {
asBridge();
await post([ENERGY]);
expect(requireAuth).toHaveBeenCalledWith(MEASUREMENTS_WRITE_SCOPE, {
writeBucket: "own",
});
});
it("writes the EXTERNAL row in the probe, the insert and the update", async () => {
asBridge();
const res = await post([ENERGY, PROTEIN]);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { inserted: number; updated: number };
};
expect(body.data).toMatchObject({ inserted: 1, updated: 1 });
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({
userId: "user-1",
source: "EXTERNAL",
});
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string; nutrient: string }> };
expect(created.data).toEqual([
expect.objectContaining({ nutrient: "protein", source: "EXTERNAL" }),
]);
const update = vi.mocked(prisma.nutrientIntakeDay.update).mock.calls[0][0];
expect(update.where).toEqual({
userId_day_nutrient_source: {
userId: "user-1",
day: ENERGY.day,
nutrient: "energy",
source: "EXTERNAL",
},
});
});
it("counts in the bridge bucket and names the source in the audit row", async () => {
asBridge();
await post([ENERGY]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:bridge:user-1",
);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "EXTERNAL" }),
}),
);
});
it("accepts alcohol, which no HealthKit type carries", async () => {
asBridge();
const res = await post([
{ day: "2026-11-01", nutrient: "alcohol", unit: "g", amount: 24 },
]);
const body = (await res.json()) as { data: { skipped: unknown[] } };
expect(body.data.skipped).toEqual([]);
});
it("skips energy posted in kJ rather than converting it", async () => {
asBridge();
const res = await post([{ ...ENERGY, unit: "kJ", amount: 8800 }]);
const body = (await res.json()) as {
data: { skipped: Array<{ reason: string }> };
};
expect(body.data.skipped).toEqual([{ index: 0, reason: "unit_mismatch" }]);
});
});
describe("POST /api/nutrients/batch from the native client", () => {
it("keeps writing the APPLE_HEALTH row in its own bucket", async () => {
asPhone();
await post([ENERGY, PROTEIN]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:user-1",
);
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({ source: "APPLE_HEALTH" });
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string }> };
expect(created.data.every((r) => r.source === "APPLE_HEALTH")).toBe(true);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "APPLE_HEALTH" }),
}),
);
});
});
+1
View File
@@ -511,6 +511,7 @@ export const USER_RESET = {
documentsLayoutJson: Prisma.DbNull,
moduleListLayoutJson: Prisma.DbNull,
activityGoalsJson: Prisma.DbNull,
nutrientTargetsJson: Prisma.DbNull,
reportSelectionJson: Prisma.DbNull,
modulePreferencesJson: Prisma.DbNull,
healthScoreConfigJson: Prisma.DbNull,
@@ -71,6 +71,7 @@ export const accountSettingsBackupSchema = z
// because no codec reads it, so such a file restores everything else.
previewFeaturesJson: z.unknown().optional(),
activityGoalsJson: z.unknown().optional(),
nutrientTargetsJson: z.unknown().optional(),
reportSelectionJson: z.unknown().optional(),
globalExcludedInjectionSites: z.array(z.string()).optional(),
healthKitConfigJson: z.unknown().optional(),
+36
View File
@@ -62,6 +62,8 @@ import { UNREADABLE_EXPORT_MARKER } from "@/lib/export/unreadable-marker";
import { locales } from "@/lib/i18n/config";
import { thresholdsUpdateSchema } from "@/lib/validations/thresholds";
import { activityGoalsSchema } from "@/lib/validations/activity-goals";
import { isNutrientCode } from "@/lib/nutrients/catalog";
import { parseNutrientTarget } from "@/lib/validations/nutrient-targets";
import { isPublicUrl } from "@/lib/validations/notifications";
import {
glucoseUnitPatchSchema,
@@ -291,6 +293,39 @@ const activityGoals: SettingCodec = {
},
};
/**
* The daily nutrient targets, code by code. A target outside its code's range,
* or a code this release does not know, is dropped and named; the valid
* targets beside it still come back.
*/
const nutrientTargets: SettingCodec = {
write: (row) => ({ nutrientTargetsJson: row.nutrientTargetsJson ?? null }),
read: (entry) => {
if (!has(entry, "nutrientTargetsJson")) return undefined;
const value = entry.nutrientTargetsJson;
if (value === null) return Prisma.DbNull;
if (typeof value !== "object" || Array.isArray(value)) {
return new Refused("nutrientTargetsJson");
}
const kept: Record<string, { value: number; direction: string }> = {};
const refused: string[] = [];
for (const [code, raw] of Object.entries(value)) {
const target = isNutrientCode(code)
? parseNutrientTarget(code, raw)
: null;
if (target) {
kept[code] = { value: target.value, direction: target.direction };
} else {
refused.push(`nutrientTargetsJson.${code}`);
}
}
return new PartlyRefused(
Object.keys(kept).length === 0 ? Prisma.DbNull : kept,
refused,
);
},
};
const injectionSites = Object.values(InjectionSite) as string[];
/** The injection sites to avoid everywhere; an unknown site is dropped. */
@@ -540,6 +575,7 @@ const ACCOUNT_SETTING_CODECS = {
documentsLayoutJson: json("documentsLayoutJson"),
moduleListLayoutJson: json("moduleListLayoutJson"),
activityGoalsJson: activityGoals,
nutrientTargetsJson: nutrientTargets,
reportSelectionJson: json("reportSelectionJson"),
globalExcludedInjectionSites: excludedSites,
healthKitConfigJson: json("healthKitConfigJson"),
+56
View File
@@ -23,12 +23,17 @@ import {
nutrientWaterWriteSchema,
nutrientWaterWriteResponseSchema,
} from "@/lib/validations/nutrients";
import {
nutrientTargetsPatchSchema,
nutrientTargetsResponseSchema,
} from "@/lib/validations/nutrient-targets";
import {
dataEnvelope,
errorEnvelope,
idempotencyKeyParameter,
idempotentWrite,
recordRefusal,
recordWriteRateLimitResponse,
stdResponses,
} from "./shared";
@@ -216,4 +221,55 @@ export const nutrientPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/nutrients/targets": {
get: {
tags: ["Nutrients"],
summary: "Daily nutrient targets",
description:
"The daily targets the person set for themselves, keyed by catalog code, each `{ value, direction }` in the code's canonical unit: `target` is an amount to reach, `limit` one to stay under. Only codes with a target appear; there is no default. Owner only. `GET /api/nutrients/daily` carries the one for its code as `personalTarget`. Behind the opt-in `nutrients` module.",
responses: {
"200": {
description: "The targets.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientTargetsResponseSchema,
"NutrientTargetsEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
},
},
patch: {
tags: ["Nutrients"],
summary: "Set daily nutrient targets",
description:
"Sets the targets the body names and keeps the rest; `null` clears one. An unknown code, or a value at or below 0 or above the code's plausibility cap, is refused with the multi-issue 422. Owner only: a shared or delegated session cannot change another person's targets. Behind the opt-in `nutrients` module.",
requestBody: {
required: true,
content: {
"application/json": { schema: nutrientTargetsPatchSchema },
},
},
responses: {
"200": {
description: "The targets after the change.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientTargetsResponseSchema,
"NutrientTargetsPatchEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
...recordWriteRateLimitResponse,
},
},
},
};
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import {
mergeNutrientTargets,
nutrientTargetCodes,
nutrientTargetsPatchSchema,
parseNutrientTargets,
} from "../nutrient-targets";
describe("nutrient targets", () => {
it("accepts a target or a limit per catalog code and null to clear", () => {
const parsed = nutrientTargetsPatchSchema.safeParse({
targets: {
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
energy: null,
},
});
expect(parsed.success).toBe(true);
});
it("refuses an unknown code, a value at or below zero, and one above the code's cap", () => {
for (const targets of [
{ creatine: { value: 5, direction: "target" } },
{ protein: { value: 0, direction: "target" } },
{ protein: { value: 1001, direction: "target" } },
{ energy: { value: 2000, direction: "maximum" } },
{ energy: { value: 2000, direction: "target", extra: 1 } },
]) {
expect(
nutrientTargetsPatchSchema.safeParse({ targets }).success,
JSON.stringify(targets),
).toBe(false);
}
});
it("merges code by code: named codes change, null clears, the rest stay", () => {
const current = parseNutrientTargets({
protein: { value: 100, direction: "target" },
sugar: { value: 50, direction: "limit" },
});
const next = mergeNutrientTargets(current, {
targets: {
protein: { value: 120, direction: "target" },
sugar: null,
fiber: { value: 30, direction: "target" },
},
});
expect(next).toEqual({
protein: { value: 120, direction: "target" },
fiber: { value: 30, direction: "target" },
});
expect(nutrientTargetCodes(next)).toEqual(["protein", "fiber"]);
});
it("reads a damaged stored value code by code and never throws", () => {
expect(parseNutrientTargets(null)).toEqual({});
expect(parseNutrientTargets([1, 2])).toEqual({});
expect(
parseNutrientTargets({
protein: { value: 120, direction: "target" },
sugar: { value: -1, direction: "limit" },
retired_code: { value: 1, direction: "target" },
}),
).toEqual({ protein: { value: 120, direction: "target" } });
});
});