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

+2 -2
View File
@@ -10839,7 +10839,7 @@
},
"nutrients": {
"label": "Nährstoffzufuhr",
"description": "Tägliche Nährstoffsummen aus Apple Health oder einem Ernährungstracker: Wasser, Energie, Makros, Vitamine und Mineralstoffe."
"description": "Tagessummen aus Apple Health oder einem Ernährungstracker: Wasser, Energie, Makros, Vitamine und Mineralstoffe."
},
"vaccinations": {
"label": "Impfungen",
@@ -12671,7 +12671,7 @@
},
"page": {
"title": "Nährstoffaufnahme",
"description": "Wasser, Energie, Makros, Vitamine und Mineralstoffe aus deiner Gesundheits-App oder einem Ernährungstracker, plus manuelle Wassereinträge.",
"description": "Wasser, Energie, Makros, Vitamine und Mineralstoffe aus deiner Gesundheits-App oder einem Tracker, plus Wassereinträge.",
"moduleOffDescription": "Aktiviere das Nährstoffe-Modul, um Flüssigkeit, Energie, Makronährstoffe und Vitamin-/Mineralstoffaufnahme hier zu sehen. Synchronisierte Werte werden Teil der Aufzeichnung, die der Coach lesen kann.",
"moduleOffCta": "Nährstoffe aktivieren",
"emptyTitle": "Noch keine Nährstoffdaten",
+1 -1
View File
@@ -12671,7 +12671,7 @@
},
"page": {
"title": "Ingesta de nutrientes",
"description": "Agua, energía, macros, vitaminas y minerales desde tu app de salud o una app de nutrición, más entradas manuales de agua.",
"description": "Agua, energía, macros, vitaminas y minerales desde tu app de salud o de nutrición, más entradas de agua.",
"moduleOffDescription": "Activa el módulo de nutrientes para ver aquí la hidratación, la energía, los macronutrientes y la ingesta de vitaminas/minerales. Los datos sincronizados pasarán a formar parte del registro que el Coach puede leer.",
"moduleOffCta": "Activar nutrientes",
"emptyTitle": "Aún no hay datos de nutrientes",
+2 -2
View File
@@ -10839,7 +10839,7 @@
},
"nutrients": {
"label": "Apports en nutriments",
"description": "Totaux quotidiens de nutriments depuis Apple Health ou une appli de suivi alimentaire : eau, énergie, macros, vitamines et minéraux."
"description": "Totaux quotidiens depuis Apple Health ou une appli de suivi : eau, énergie, macros, vitamines et minéraux."
},
"vaccinations": {
"label": "Vaccinations",
@@ -12671,7 +12671,7 @@
},
"page": {
"title": "Apports en nutriments",
"description": "Eau, énergie, macros, vitamines et minéraux depuis votre appli santé ou une appli de suivi alimentaire, plus les saisies d'eau.",
"description": "Eau, énergie, macros, vitamines et minéraux depuis votre appli santé ou de suivi, plus les saisies d'eau.",
"moduleOffDescription": "Activez le module nutriments pour voir ici l'hydratation, l'énergie, les macronutriments et les apports en vitamines/minéraux. Les données synchronisées feront partie du dossier que le Coach peut lire.",
"moduleOffCta": "Activer les nutriments",
"emptyTitle": "Pas encore de données nutritionnelles",
+1 -1
View File
@@ -10839,7 +10839,7 @@
},
"nutrients": {
"label": "Assunzione di nutrienti",
"description": "Totali giornalieri di nutrienti da Apple Health o da un'app per l'alimentazione: acqua, energia, macro, vitamine e minerali."
"description": "Totali giornalieri da Apple Health o da un'app per l'alimentazione: acqua, energia, macro, vitamine, minerali."
},
"vaccinations": {
"label": "Vaccinazioni",
+2 -2
View File
@@ -10839,7 +10839,7 @@
},
"nutrients": {
"label": "Inname van voedingsstoffen",
"description": "Dagelijkse totalen van voedingsstoffen uit Apple Health of een voedingsapp: water, energie, macro's, vitaminen en mineralen."
"description": "Dagtotalen uit Apple Health of een voedingsapp: water, energie, macro's, vitaminen en mineralen."
},
"vaccinations": {
"label": "Vaccinaties",
@@ -12671,7 +12671,7 @@
},
"page": {
"title": "Inname van voedingsstoffen",
"description": "Water, energie, macro's, vitaminen en mineralen uit je gezondheidsapp of een voedingsapp, plus handmatig ingevoerd water.",
"description": "Water, energie, macro's, vitaminen en mineralen uit je gezondheids- of voedingsapp, plus ingevoerd water.",
"moduleOffDescription": "Zet de module voedingsstoffen aan om hier je vochtinname, energie, macronutriënten en je inname van vitaminen en mineralen te zien. Gesynchroniseerde inname wordt onderdeel van de gegevens die de Coach kan lezen.",
"moduleOffCta": "Voedingsstoffen aanzetten",
"emptyTitle": "Nog geen gegevens over voedingsstoffen",
+2 -2
View File
@@ -10839,7 +10839,7 @@
},
"nutrients": {
"label": "Spożycie składników odżywczych",
"description": "Dzienne sumy składników odżywczych z Apple Health lub aplikacji dietetycznej: woda, energia, makroskładniki, witaminy i minerały."
"description": "Dzienne sumy z Apple Health lub aplikacji dietetycznej: woda, energia, makro, witaminy i minerały."
},
"vaccinations": {
"label": "Szczepienia",
@@ -12671,7 +12671,7 @@
},
"page": {
"title": "Spożycie składników odżywczych",
"description": "Woda, energia, makroskładniki, witaminy i minerały z aplikacji zdrowia lub aplikacji dietetycznej, plus ręczne wpisy wody.",
"description": "Woda, energia, makro, witaminy i minerały z aplikacji zdrowia lub dietetycznej, plus ręczne wpisy wody.",
"moduleOffDescription": "Włącz moduł składników odżywczych, aby zobaczyć tu nawodnienie, energię, makroskładniki i spożycie witamin/minerałów. Zsynchronizowane dane staną się częścią zapisu, który może odczytać Coach.",
"moduleOffCta": "Włącz składniki odżywcze",
"emptyTitle": "Brak jeszcze danych o składnikach odżywczych",
+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");
});
@@ -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);