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

+1 -2
View File
@@ -32,7 +32,7 @@
*/
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiHandler, isScopedCredential, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
@@ -46,7 +46,6 @@ import { withIdempotency } from "@/lib/idempotency";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { invalidateUserHealthContext } from "@/lib/cache/invalidate";
import { isScopedCredential } from "@/lib/auth/guards/context";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
import { NUTRIENT_CATALOG } from "@/lib/nutrients/catalog";
import { maxAcceptableNutrientDay } from "@/lib/nutrients/day-bounds";
@@ -63,7 +63,6 @@ interface DailyResponse {
windowDays: number;
days: Array<{ day: string; amount: number }>;
reference: { kind: string; direction: string; value: number } | null;
personalTarget: { value: number; direction: string } | null;
};
}
@@ -72,9 +71,8 @@ beforeEach(() => {
vi.mocked(getSession).mockResolvedValue(sessionFor("FEMALE") as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true } as never);
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([] as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
nutrientTargetsJson: null,
} as never);
// No targets set: the account row carries none.
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
});
describe("GET /api/nutrients/daily", () => {
@@ -154,27 +152,6 @@ describe("GET /api/nutrients/daily", () => {
});
});
it("returns the person's own target for the code, and null without one", async () => {
vi.mocked(prisma.user.findUnique).mockResolvedValue({
nutrientTargetsJson: {
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
},
} as never);
const protein = (await (
await GET(getReq("?nutrient=protein&days=7"))
).json()) as DailyResponse;
expect(protein.data.personalTarget).toEqual({
value: 120,
direction: "target",
});
expect(protein.data.unit).toBe("g");
const water = (await (
await GET(getReq("?nutrient=water&days=7"))
).json()) as DailyResponse;
expect(water.data.personalTarget).toBeNull();
});
it("omits the reference when the profile has no sex on file — never guesses", async () => {
vi.mocked(getSession).mockResolvedValue(sessionFor(null) as never);
const res = await GET(getReq("?nutrient=water&days=7"));
@@ -0,0 +1,169 @@
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import type { NutrientDailySeries, NutrientOverviewRow } from "../types";
const state = vi.hoisted(() => ({
rows: [] as NutrientOverviewRow[],
daily: {} as Record<string, NutrientDailySeries>,
chartLine: [] as Array<number | null>,
}));
vi.mock("@tanstack/react-query", () => ({
useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {
if (queryKey[1] === "daily") {
return {
data: state.daily[queryKey[2] as string],
isLoading: false,
isError: false,
refetch: () => undefined,
};
}
return {
data: { nutrients: state.rows, windowDays: 30, lastAttempt: null },
isLoading: false,
isError: false,
refetch: () => undefined,
};
},
useQueryClient: () => ({ invalidateQueries: async () => undefined }),
}));
vi.mock("@/components/charts/nutrient-daily-bar-chart-dynamic", () => ({
NutrientDailyBarChartDynamic: ({
referenceValue,
}: {
referenceValue: number | null;
}) => {
state.chartLine.push(referenceValue);
return <div data-slot="chart" />;
},
}));
import { EnergyMacrosCard } from "../energy-macros-card";
import { MicronutrientsCard } from "../micronutrients-card";
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({ user: { gender: "MALE" } }),
}));
function row(nutrient: string, unit: string): NutrientOverviewRow {
return {
nutrient,
unit,
latestDay: "2026-11-15",
latestAmount: 100,
daysWithData: 3,
};
}
function series(
nutrient: string,
unit: string,
extra: Partial<NutrientDailySeries> = {},
): NutrientDailySeries {
return {
nutrient,
unit,
windowDays: 30,
days: [
{ day: "2026-11-14", amount: 2000 },
{ day: "2026-11-15", amount: 2150 },
],
reference: null,
personalTarget: null,
...extra,
};
}
function render(node: React.ReactNode) {
state.chartLine = [];
return renderToStaticMarkup(
<I18nProvider initialLocale="en">{node}</I18nProvider>,
);
}
describe("EnergyMacrosCard", () => {
it("renders nothing when no energy or macro code has data", () => {
state.rows = [row("water", "ml"), row("magnesium", "mg")];
expect(render(<EnergyMacrosCard />)).toBe("");
});
it("offers only the logged codes and shows the first one's latest day", () => {
state.rows = [row("energy", "kcal"), row("protein", "g")];
state.daily = { energy: series("energy", "kcal") };
const html = render(<EnergyMacrosCard />);
expect(html).toContain('data-slot="nutrients-energy-macros-card"');
expect(html).toContain('data-slot="nutrients-macros-pick-energy"');
expect(html).toContain('data-slot="nutrients-macros-pick-protein"');
expect(html).not.toContain("nutrients-macros-pick-fat");
expect(html).toContain("2,150");
expect(html).toContain("kcal");
// Energy has no reference: no meta line, no dashed line.
expect(html).not.toContain('data-slot="nutrients-macros-meta"');
expect(state.chartLine).toEqual([null]);
});
it("draws the person's own target over the reference and names it", () => {
state.rows = [row("protein", "g")];
state.daily = {
protein: series("protein", "g", {
reference: {
authority: "IOM",
kind: "PRI",
direction: "target",
value: 56,
source: "IOM 2005",
},
personalTarget: { value: 120, direction: "target" },
}),
};
const html = render(<EnergyMacrosCard />);
expect(html).toContain("Your target 120 g/day");
expect(html).toContain("Edit target");
expect(state.chartLine).toEqual([120]);
});
it("falls back to the reference with its authority when no target is set", () => {
state.rows = [row("protein", "g")];
state.daily = {
protein: series("protein", "g", {
reference: {
authority: "IOM",
kind: "PRI",
direction: "target",
value: 56,
source: "IOM 2005",
},
}),
};
const html = render(<EnergyMacrosCard />);
expect(html).toContain("Reference 56 g/day (IOM)");
expect(html).toContain("Set target");
expect(state.chartLine).toEqual([56]);
});
});
describe("MicronutrientsCard grouping", () => {
it("lists sodium and potassium as minerals and leaves the macros and alcohol to their own cards", () => {
state.rows = [
row("sodium", "mg"),
row("potassium", "mg"),
row("energy", "kcal"),
row("protein", "g"),
row("alcohol", "g"),
row("caffeine", "mg"),
];
const html = render(<MicronutrientsCard />);
expect(html).toContain("Sodium");
expect(html).toContain("Potassium");
expect(html).not.toContain("Energy");
expect(html).not.toContain("Protein");
expect(html).not.toContain("Alcohol");
expect(html).not.toContain("Caffeine");
// Sodium's reference is EFSA's safe and adequate intake.
expect(html).toContain("ref 2,000.0 mg (EFSA)");
});
});
@@ -3,7 +3,6 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Flame } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
@@ -14,6 +13,7 @@ import { Segmented } from "@/components/ui/segmented";
import { Skeleton } from "@/components/ui/skeleton";
import { TileHeader } from "@/components/insights/tile-header";
import { NutrientDailyBarChartDynamic } from "@/components/charts/nutrient-daily-bar-chart-dynamic";
import { showErrorToast } from "@/lib/errors/error-toast";
import { useTranslations, useFormatters } from "@/lib/i18n/context";
import { apiGet, apiPatch } from "@/lib/api/api-fetch";
import { queryKeys } from "@/lib/query-keys";
@@ -34,11 +34,18 @@ const WINDOW_DAYS = 30;
/** Energy and the macros, in catalog order. */
const MACRO_CODES = nutrientCodesInGroup("energy_macro");
/** One decimal where there is one: 2150 kcal, 82.5 g. */
function formatAmount(
fmt: { number: (v: number, d?: number) => string },
fmt: {
number: (v: number, d?: number) => string;
integer: (v: number) => string;
},
amount: number,
): string {
return fmt.number(Math.round(amount * 10) / 10, 1);
const rounded = Math.round(amount * 10) / 10;
return Number.isInteger(rounded)
? fmt.integer(rounded)
: fmt.number(rounded, 1);
}
/**
@@ -255,8 +262,8 @@ function TargetEditor({
}),
]);
onDone();
} catch {
toast.error(t("nutrients.macros.saveFailed"));
} catch (cause) {
showErrorToast(t("nutrients.macros.saveFailed"), { cause });
} finally {
setSaving(false);
}
@@ -50,6 +50,18 @@ describe("canonicalComposition", () => {
).toEqual({ ok: false, kind: "unknownNutrient", index: 1 });
});
it("refuses a catalogue code that is no ingredient: energy, a macro, alcohol, water", () => {
for (const nutrient of ["energy", "protein", "alcohol", "water"]) {
expect(
canonicalComposition([
{ nutrient: "zinc", amount: 10, unit: "mg" },
{ nutrient, amount: 5, unit: "g" },
]),
nutrient,
).toEqual({ ok: false, kind: "unknownNutrient", index: 1 });
}
});
it("names the row and the allowed units of a unit the code does not offer", () => {
expect(
canonicalComposition([
@@ -137,6 +137,30 @@ describe("proposalFromLabel", () => {
]);
});
it("never proposes energy or a macronutrient, even when the model names one", () => {
const proposal = proposalFromLabel({
lines: [
{
printedText: "Eiweiß 2 g",
nutrient: "protein",
amount: 2,
unit: "g",
},
{
printedText: "Energie 10 kcal",
nutrient: "energy",
amount: 10,
unit: "kcal",
},
],
});
expect(proposal.ingredients).toEqual([]);
expect(proposal.unmatched.map((u) => u.printedText)).toEqual([
"Eiweiß 2 g",
"Energie 10 kcal",
]);
});
it("proposes a code once; a second line for it is unmatched", () => {
const proposal = proposalFromLabel({
lines: [
@@ -229,6 +253,13 @@ describe("executeSupplementLabelExtraction", () => {
]
)[0];
expect(JSON.stringify(params)).toContain("image/png");
// The closed code list offers ingredients only: no energy, macros,
// alcohol, water or caffeine.
const prompt = JSON.stringify(params);
expect(prompt).toContain("- magnesium:");
for (const code of ["energy", "protein", "alcohol", "water", "caffeine"]) {
expect(prompt).not.toContain(`- ${code}:`);
}
expect(settle).toHaveBeenCalledWith("user-1", budget, 4000, "anthropic");
});