test(nutrients): pin the token arm, the day fold and the macro surfaces

Integration coverage for the nutrient batch under each credential (the
source row, the 403s, the module gate, re-post, backfill, coexistence
with the phone's row and the bridge bucket), kcal and g ingest with kJ
skipped, the day fold on the overview and in the correlation read, and
composition refusing energy, macros and alcohol. Route-level checks run
against Postgres rather than a stubbed handler. The energy card reports
a failed save through the shared error toast.
This commit is contained in:
Marc-André Bombeck committed 2026-11-17 19:05:32 +01:00
1 parent db0e4f9688
commit 33debe777f
16 files changed
+556 -44

No files matched your search

@@ -3,7 +3,7 @@
*
* The unit battery (`correlation-extended-channels.test.ts`) pins the pure
* shapers; this suite proves the reads that feed them: the room-climate
* hour-mean SQL and its zone conversion, the nutrient day sum across sources,
* hour-mean SQL and its zone conversion, the nutrient day fold across sources,
* the alcohol tag read from the legacy flat list, and the training read with
* a session stored by two services.
*/
@@ -100,7 +100,7 @@ describe("extended correlation channels — reads", () => {
expect(co2?.targets).toEqual(["SLEEP_DURATION"]);
});
it("sums a nutrient day across sources", async () => {
it("folds a nutrient day across sources: the larger day total, manual water on top", async () => {
const prisma = getPrismaClient();
const user = await seedUser(prisma);
await prisma.nutrientIntakeDay.createMany({
@@ -121,6 +121,15 @@ describe("extended correlation channels — reads", () => {
unit: "ml",
source: "MANUAL",
},
// A tracker reporting the same day: smaller, so it does not count.
{
userId: user.id,
day: dayKey(3),
nutrient: "water",
amount: 1400,
unit: "ml",
source: "EXTERNAL",
},
{
userId: user.id,
day: dayKey(3),
+70
View File
@@ -183,6 +183,38 @@ describe("POST /api/nutrients/batch (real Postgres)", () => {
expect(count).toBe(0);
});
it("stores energy in kcal and the macros in g, and skips energy sent in kJ", async () => {
const { POST } = await import("@/app/api/nutrients/batch/route");
const res = await POST(
postReq({
entries: [
{ day: recentDay(1), nutrient: "energy", unit: "kcal", amount: 2100 },
{ day: recentDay(1), nutrient: "protein", unit: "g", amount: 95.5 },
{ day: recentDay(1), nutrient: "sodium", unit: "mg", amount: 2300 },
{ day: recentDay(2), nutrient: "energy", unit: "kJ", amount: 8800 },
],
}),
);
const json = (await res.json()) as BatchEnvelope;
expect(json.data.inserted).toBe(3);
expect(json.data.skipped).toEqual([{ index: 3, reason: "unit_mismatch" }]);
const stored = await getPrismaClient().nutrientIntakeDay.findMany({
where: { userId: OPTED_IN_USER },
orderBy: { nutrient: "asc" },
select: { nutrient: true, unit: true, amount: true, source: true },
});
expect(stored).toEqual([
{
nutrient: "energy",
unit: "kcal",
amount: 2100,
source: "APPLE_HEALTH",
},
{ nutrient: "protein", unit: "g", amount: 95.5, source: "APPLE_HEALTH" },
{ nutrient: "sodium", unit: "mg", amount: 2300, source: "APPLE_HEALTH" },
]);
});
// Before this, `nutrient.batch.ingest` audited only when
// `inserted + updated > 0` — the ONLY durable record of the call — so a
// batch where every entry was rejected left the exact same empty
@@ -290,6 +322,44 @@ describe("GET /api/nutrients (real Postgres)", () => {
});
});
it("counts the larger day-total source and adds manual water on top", async () => {
const { GET } = await import("@/app/api/nutrients/route");
const day = recentDay(1);
await getPrismaClient().nutrientIntakeDay.createMany({
data: [
{ source: "APPLE_HEALTH", amount: 1800 },
{ source: "HEALTH_CONNECT", amount: 1600 },
{ source: "EXTERNAL", amount: 1500 },
{ source: "MANUAL", amount: 250 },
].map((r) => ({
userId: OPTED_IN_USER,
day,
nutrient: "water",
unit: "ml",
...r,
})),
});
const res = await GET(
new NextRequest("http://localhost/api/nutrients?days=14"),
);
const json = (await res.json()) as {
data: {
nutrients: Array<{
nutrient: string;
latestAmount: number;
latestBySource: Record<string, number>;
}>;
};
};
expect(json.data.nutrients).toEqual([
expect.objectContaining({
nutrient: "water",
latestAmount: 2050,
latestBySource: { APPLE_HEALTH: 1800, MANUAL: 250 },
}),
]);
});
it("refuses the read 403 module.disabled when the module is off", async () => {
const { GET } = await import("@/app/api/nutrients/route");
cookieJar.clear();
@@ -0,0 +1,215 @@
/**
* Who may call `POST /api/nutrients/batch`, and what a narrow
* `measurements:write` credential writes, against the real database and
* through the real API kit (#1402).
*
* Pinned here, read back from the stored rows:
* - a cookie session and a wildcard token write the APPLE_HEALTH row; a
* `measurements:write` token writes the EXTERNAL row, resolved from the
* credential; every other narrow token is 403 and writes nothing;
* - the module gate refuses the token like it refuses the phone;
* - a bridge re-post replaces its day in place, any past day is accepted,
* and its row coexists with the phone's for the same day;
* - a bridge counts in a rate-limit bucket of its own;
* - a supplement-only code is refused 422 for a bridge too.
*/
import { beforeEach, describe, expect, it } from "vitest";
import type { User } from "@/generated/prisma/client";
import { POST } from "@/app/api/nutrients/batch/route";
import { GET as GET_DAILY } from "@/app/api/nutrients/daily/route";
import { DOCUMENTS_WRITE_SCOPE } from "@/lib/documents/scopes";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
import { WORKOUTS_WRITE_SCOPE } from "@/lib/workouts/scopes";
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
import { callRoute, type RouteAuth } from "../../kit/call-route";
import { makeSession, makeToken, makeUser } from "../../kit/factories";
import { getPrismaClient, truncateAllTables } from "../setup";
const prisma = getPrismaClient();
const ROUTE = "/api/nutrients/batch";
const TZ = "Europe/Berlin";
interface BatchResult {
processed: number;
inserted: number;
updated: number;
skipped: Array<{ index: number; reason: string }>;
entries: Array<{ index: number; status: string; reason?: string }>;
}
beforeEach(() => truncateAllTables(prisma));
/** A local day key `n` days back from the caller's today. */
function day(n: number): string {
return shiftDateKey(userDayKey(new Date(), TZ), -n);
}
function nutrientUser(): Promise<User> {
return makeUser({
timezone: TZ,
modulePreferencesJson: { nutrients: true },
});
}
function post(entries: Array<Record<string, unknown>>, auth: RouteAuth) {
return callRoute<BatchResult>(POST, {
method: "POST",
route: ROUTE,
body: { entries },
auth,
});
}
const energy = (d: string, amount: number) => ({
day: d,
nutrient: "energy",
unit: "kcal",
amount,
});
async function rows(user: Pick<User, "id">) {
return prisma.nutrientIntakeDay.findMany({
where: { userId: user.id },
orderBy: [{ day: "asc" }, { source: "asc" }],
select: { day: true, nutrient: true, source: true, amount: true },
});
}
function bridge(user: Pick<User, "id">) {
return makeToken(user, { permissions: [MEASUREMENTS_WRITE_SCOPE] });
}
describe("POST /api/nutrients/batch: the credential picks the source", () => {
it("stores a session's day total as APPLE_HEALTH", async () => {
const user = await nutrientUser();
const res = await post([energy(day(1), 2000)], await makeSession(user));
expect(res.status).toBe(200);
expect((await rows(user)).map((r) => r.source)).toEqual(["APPLE_HEALTH"]);
});
it("stores a wildcard token's day total as APPLE_HEALTH", async () => {
const user = await nutrientUser();
const res = await post([energy(day(1), 2000)], await makeToken(user));
expect(res.status).toBe(200);
expect((await rows(user)).map((r) => r.source)).toEqual(["APPLE_HEALTH"]);
});
it("stores a measurements:write token's day total as EXTERNAL", async () => {
const user = await nutrientUser();
const res = await post(
[
energy(day(1), 2100),
{ day: day(1), nutrient: "protein", unit: "g", amount: 95 },
{ day: day(1), nutrient: "alcohol", unit: "g", amount: 24 },
],
await bridge(user),
);
expect(res.status).toBe(200);
expect(res.data.inserted).toBe(3);
const stored = await rows(user);
expect(stored.every((r) => r.source === "EXTERNAL")).toBe(true);
expect(stored.map((r) => r.nutrient).sort()).toEqual([
"alcohol",
"energy",
"protein",
]);
});
it.each([
["workouts:write", [WORKOUTS_WRITE_SCOPE]],
["documents:write", [DOCUMENTS_WRITE_SCOPE]],
["health:read", ["health:read"]],
])("refuses a %s token with 403 and writes nothing", async (_, perms) => {
const user = await nutrientUser();
const res = await post(
[energy(day(1), 2000)],
await makeToken(user, { permissions: perms }),
);
expect(res.status).toBe(403);
expect(res.meta?.errorCode).toBe("auth.scope.insufficient");
expect(await rows(user)).toEqual([]);
});
it("refuses the token with module.disabled while the module is off", async () => {
const user = await makeUser({ timezone: TZ });
const res = await post([energy(day(1), 2000)], await bridge(user));
expect(res.status).toBe(403);
expect(res.meta?.errorCode).toBe("module.disabled");
expect(await rows(user)).toEqual([]);
});
it("refuses a supplement-only code with 422", async () => {
const user = await nutrientUser();
const res = await post(
[{ day: day(1), nutrient: "dha", unit: "mg", amount: 250 }],
await bridge(user),
);
expect(res.status).toBe(422);
expect(await rows(user)).toEqual([]);
});
});
describe("POST /api/nutrients/batch: a bridge's day totals", () => {
it("replaces its day in place on a re-post, and a 0 corrects it", async () => {
const user = await nutrientUser();
const token = await bridge(user);
await post([energy(day(2), 2400)], token);
const again = await post([energy(day(2), 0)], token);
expect(again.data.entries).toEqual([{ index: 0, status: "updated" }]);
expect(await rows(user)).toEqual([
{ day: day(2), nutrient: "energy", source: "EXTERNAL", amount: 0 },
]);
});
it("accepts a day from long ago, so a bridge can backfill its history", async () => {
const user = await nutrientUser();
const res = await post([energy(day(400), 1900)], await bridge(user));
expect(res.data.inserted).toBe(1);
});
it("coexists with the phone's row for the same day, and the read counts the larger", async () => {
const user = await nutrientUser();
const session = await makeSession(user);
await post([energy(day(0), 2000)], session);
await post([energy(day(0), 2100)], await bridge(user));
expect((await rows(user)).map((r) => [r.source, r.amount])).toEqual([
["APPLE_HEALTH", 2000],
["EXTERNAL", 2100],
]);
const daily = await callRoute<{
days: Array<{ day: string; amount: number; bySource?: object }>;
}>(GET_DAILY, {
method: "GET",
route: "/api/nutrients/daily",
query: { nutrient: "energy", days: 3 },
auth: session,
});
const today = daily.data.days.at(-1);
expect(today?.day).toBe(day(0));
expect(today?.amount).toBe(2100);
expect(today?.bySource).toEqual({ EXTERNAL: 2100 });
});
it("counts in a rate-limit bucket of its own", async () => {
const user = await nutrientUser();
await post([energy(day(1), 2000)], await makeSession(user));
await post([energy(day(1), 2100)], await bridge(user));
const keys = (
await prisma.rateLimit.findMany({
where: { key: { startsWith: "nutrients:batch" } },
select: { key: true },
})
)
.map((r) => r.key)
.sort();
expect(keys).toEqual(
[
`nutrients:batch:${user.id}`,
`nutrients:batch:bridge:${user.id}`,
].sort(),
);
});
});
@@ -254,6 +254,13 @@ describe("GET /api/nutrients/catalog", () => {
scope: "total",
});
expect(byCode.get("magnesium")?.upperLimit?.scope).toBe("supplemental");
// Energy is syncable but no ingredient; magnesium is both.
expect(byCode.get("energy")).toMatchObject({
unit: "kcal",
syncable: true,
ingredient: false,
});
expect(byCode.get("magnesium")).toMatchObject({ ingredient: true });
});
it("is behind the nutrients module", async () => {
@@ -367,6 +374,22 @@ describe("PUT /api/medications/{id}/ingredients", () => {
expect(duplicate.status).toBe(422);
});
it("refuses energy, a macronutrient and alcohol: they are no ingredient", async () => {
const userId = await makeUser();
const medicationId = await vitaminD(userId);
for (const [nutrient, unit] of [
["energy", "kcal"],
["protein", "g"],
["alcohol", "g"],
]) {
const res = await putIngredients(medicationId, {
ingredients: [{ nutrient, amount: 5, unit }],
});
expect(res.status, nutrient).toBe(422);
expect(res.body.meta?.errorCode).toBe("medications.ingredients.invalid");
}
});
it("answers 404 for a medication of another account", async () => {
const other = await makeUser();
const foreign = await vitaminD(other);