mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
feat(nutrients): track energy, macronutrients, sodium, potassium and alcohol
The catalog gains energy (kcal), protein, carbohydrates, fat, sugar and fiber (g), sodium and potassium (mg) and alcohol (g of ethanol, no HealthKit type). Each code now names its group and whether a supplement's composition may list it; references name their authority (EFSA, or IOM for protein and carbohydrates, NIH ODS for chromium). Day totals fold through one rule everywhere: the largest of the day-total sources (Apple Health, Health Connect, an external bridge) counts, manual water and supplement doses add on top. This also stops Apple Health and Health Connect totals for the same day from adding up. The nutrients page gets an energy and macronutrient card with an inline daily target, and an alcohol card next to caffeine. The correlation scan gives the macros their own budget of two channels and leaves logged alcohol out. Daily series and the MCP tool return the target the person set. Refs #1402.
This commit is contained in:
1 parent
a68ec9421f
commit
8f96c2f0a2
47 files changed
+1947
-430
No files matched your search
@@ -75,6 +75,8 @@ function isMaskPlaceholder(words: string[]): boolean {
|
||||
* reason. Prune an entry only when the value genuinely diverges in a locale.
|
||||
*/
|
||||
const LEGIT_IDENTICAL = new Set<string>([
|
||||
// The Android platform's product name, written the same in every locale.
|
||||
"nutrients.sources.HEALTH_CONNECT",
|
||||
// #1350 — "Google Calendar" is the product's own name in the Spanish and
|
||||
// Italian UI, and "Cycle (HealthLog)" is the French word for the same thing.
|
||||
"cycle.feed.fetcher.GOOGLE",
|
||||
|
||||
@@ -57,6 +57,7 @@ const CATALOGS: Readonly<Record<string, string>> = {
|
||||
"lib/measurements/apple-health-mapping.ts":
|
||||
"the HealthKit identifier mapping table",
|
||||
"lib/labs/biomarker-catalog.ts": "the biomarker catalogue",
|
||||
"lib/nutrients/catalog.ts": "the nutrient catalog, one entry per code",
|
||||
"app/privacy/page.tsx":
|
||||
"legal copy rendered as React text, one long static component",
|
||||
};
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
* `GET /api/nutrients/catalog` — the nutrient catalogue as the forms use it.
|
||||
*
|
||||
* One entry per code: canonical unit, label in the account's language,
|
||||
* whether HealthKit may send it (`syncable`), the input units with their
|
||||
* whether the nutrient batch accepts it (`syncable`), whether a supplement's
|
||||
* composition may name it (`ingredient`), the input units with their
|
||||
* factor to the canonical unit, and the tolerable upper intake level with its
|
||||
* scope and source (or null). Clients build the composition form from this
|
||||
* and never convert units themselves.
|
||||
@@ -27,6 +28,7 @@ export const GET = apiHandler(async () => {
|
||||
labelKey: def.labelKey,
|
||||
label: nutrientLabel(def.code, user.locale ?? null),
|
||||
syncable: def.syncable,
|
||||
ingredient: def.ingredient,
|
||||
inputUnits: def.inputUnits.map((u) => ({
|
||||
unit: u.unit,
|
||||
factorToCanonical: u.factorToCanonical,
|
||||
|
||||
@@ -14,6 +14,7 @@ vi.mock("@/lib/db", () => ({
|
||||
nutrientIntakeDay: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
user: { findUnique: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -62,6 +63,7 @@ interface DailyResponse {
|
||||
windowDays: number;
|
||||
days: Array<{ day: string; amount: number }>;
|
||||
reference: { kind: string; direction: string; value: number } | null;
|
||||
personalTarget: { value: number; direction: string } | null;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -70,6 +72,9 @@ 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);
|
||||
});
|
||||
|
||||
describe("GET /api/nutrients/daily", () => {
|
||||
@@ -114,7 +119,7 @@ describe("GET /api/nutrients/daily", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("sums amounts across sources within the same day before bucketing", async () => {
|
||||
it("folds sources within the same day before bucketing", async () => {
|
||||
// Relative day-keys — a fixed literal slides out of the window as the
|
||||
// calendar advances (a `?days=3` window only ever holds today..today-2).
|
||||
const utcDay = (offset: number) =>
|
||||
@@ -122,9 +127,11 @@ describe("GET /api/nutrients/daily", () => {
|
||||
const today = utcDay(0);
|
||||
const yesterday = utcDay(1);
|
||||
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([
|
||||
{ day: today, amount: 900 },
|
||||
{ day: today, amount: 600 },
|
||||
{ day: yesterday, amount: 400 },
|
||||
{ day: today, amount: 900, source: "APPLE_HEALTH" },
|
||||
{ day: today, amount: 600, source: "MANUAL" },
|
||||
// The smaller of two day-total sources does not count.
|
||||
{ day: yesterday, amount: 400, source: "APPLE_HEALTH" },
|
||||
{ day: yesterday, amount: 350, source: "EXTERNAL" },
|
||||
] as never);
|
||||
|
||||
const res = await GET(getReq("?nutrient=water&days=3"));
|
||||
@@ -139,6 +146,7 @@ describe("GET /api/nutrients/daily", () => {
|
||||
const res = await GET(getReq("?nutrient=water&days=7"));
|
||||
const body = (await res.json()) as DailyResponse;
|
||||
expect(body.data.reference).toEqual({
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
value: 2000,
|
||||
@@ -146,6 +154,27 @@ 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"));
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
* `GET /api/nutrients/daily?nutrient=<code>&days=N` — per-day summed
|
||||
* series for one nutrient, plus its resolved EFSA reference (v1.29).
|
||||
* `GET /api/nutrients/daily?nutrient=<code>&days=N` — per-day series for one
|
||||
* nutrient, plus its resolved dietary reference (v1.29) and the target the
|
||||
* person set for it (#1402).
|
||||
*
|
||||
* Feeds the `/insights/nutrients` hydration + caffeine charts: a dense
|
||||
* day-bucketed series (one row per calendar day in the window, 0 for a
|
||||
* day with no logged data) summed ACROSS sources — a day can carry an
|
||||
* APPLE_HEALTH row and a MANUAL row since migration 0249, and the
|
||||
* Feeds the `/insights/nutrients` charts: a dense day-bucketed series (one row
|
||||
* per calendar day in the window, 0 for a day with no logged data) folded
|
||||
* across sources by `foldNutrientDay` — a day can carry several rows, and the
|
||||
* chart shows one honest bar per day. The window is anchored to the
|
||||
* caller's own local "today" (`User.timezone`), not a UTC floor —
|
||||
* unlike the coarser window on `GET /api/nutrients`, a chart with a
|
||||
@@ -51,16 +51,15 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { nutrient, days } = parsed.data;
|
||||
const definition = NUTRIENT_CATALOG[nutrient];
|
||||
|
||||
// Summed across sources within a day, split by source and judged against
|
||||
// the upper intake level in `readNutrientDaily` (v1.43), the same read the
|
||||
// overview and the MCP tool use.
|
||||
// Folded across sources within a day, split by source and judged against
|
||||
// the upper intake level in `readNutrientDaily`, the same read the overview
|
||||
// and the MCP tool use.
|
||||
const userTz = user.timezone || DEFAULT_TIMEZONE;
|
||||
const { days: daySeries, rowCount } = await readNutrientDaily(
|
||||
user.id,
|
||||
userTz,
|
||||
nutrient,
|
||||
days,
|
||||
);
|
||||
const {
|
||||
days: daySeries,
|
||||
rowCount,
|
||||
personalTarget,
|
||||
} = await readNutrientDaily(user.id, userTz, nutrient, days);
|
||||
|
||||
const sex = binaryReferenceSex(user.gender);
|
||||
const reference = resolveNutrientReference(nutrient, sex);
|
||||
@@ -76,6 +75,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
windowDays: days,
|
||||
days: daySeries,
|
||||
reference,
|
||||
personalTarget,
|
||||
upperLimit: definition.upperLimit,
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
* Feeds the read-only settings card (Settings → Sources): per nutrient
|
||||
* with data inside the window, the latest synced day + total and the
|
||||
* count of days carrying data — the smallest honest surface for "what
|
||||
* does the server hold". Catalog order, no pagination (≤ 26 rows).
|
||||
* does the server hold". Catalog order, no pagination (one row per catalog
|
||||
* code at most).
|
||||
* Module-gated like the ingest path: 403 `module.disabled` when the
|
||||
* opt-in `nutrients` module is off. `userId` is narrowed from auth.
|
||||
*
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Leaf } from "lucide-react";
|
||||
import { Coffee, Leaf, Wine } from "lucide-react";
|
||||
|
||||
import { EmptyState } from "@/components/ui/empty-state";
|
||||
import { QueryErrorCard } from "@/components/ui/query-error-card";
|
||||
import { SubPageShell } from "@/components/insights/sub-page-shell";
|
||||
import { HydrationCard } from "@/components/insights/nutrients/hydration-card";
|
||||
import { CaffeineCard } from "@/components/insights/nutrients/caffeine-card";
|
||||
import { EnergyMacrosCard } from "@/components/insights/nutrients/energy-macros-card";
|
||||
import { SingleNutrientCard } from "@/components/insights/nutrients/single-nutrient-card";
|
||||
import { MicronutrientsCard } from "@/components/insights/nutrients/micronutrients-card";
|
||||
import { useAuth } from "@/hooks/use-auth";
|
||||
import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
@@ -44,11 +45,11 @@ function lastAttemptReasonKey(reason: string): string {
|
||||
* `/insights/nutrients` — hydration + micronutrients (v1.29).
|
||||
*
|
||||
* Custom sub-page (NOT `HealthKitMetricPage` — that scaffold is
|
||||
* Measurement-backed; this store is `NutrientIntakeDay`). Three cards:
|
||||
* hydration hero (always renders once the module is on — even at 0 mL,
|
||||
* the quick-add entry point IS the first-run invitation), caffeine
|
||||
* (self-gates to nothing without data), micronutrients (self-gates to
|
||||
* an EmptyState without data). Degradation ladder:
|
||||
* Measurement-backed; this store is `NutrientIntakeDay`). Five cards:
|
||||
* hydration hero (always renders once the module is on — even at 0 mL),
|
||||
* energy and macronutrients, caffeine and alcohol (each self-gates to
|
||||
* nothing without data), micronutrients (self-gates to an EmptyState
|
||||
* without data). Degradation ladder:
|
||||
*
|
||||
* - module off → never reaches this page: the shell answers the URL with
|
||||
* the module notice (`ModulePageGate`), like every other module page.
|
||||
@@ -76,7 +77,7 @@ function lastAttemptReasonKey(reason: string): string {
|
||||
* - module on, zero rows, no recorded attempt → the generic EmptyState
|
||||
* explaining where data comes from (a health-app sync or a manual
|
||||
* water entry) instead of three near-empty cards.
|
||||
* - otherwise → the three-card spine.
|
||||
* - otherwise → the card spine.
|
||||
*/
|
||||
export default function InsightsNutrientsPage() {
|
||||
const { t } = useTranslations();
|
||||
@@ -147,7 +148,19 @@ export default function InsightsNutrientsPage() {
|
||||
description={t("nutrients.page.description")}
|
||||
>
|
||||
<HydrationCard />
|
||||
<CaffeineCard />
|
||||
<EnergyMacrosCard />
|
||||
<SingleNutrientCard
|
||||
code="caffeine"
|
||||
icon={Coffee}
|
||||
metaKey="nutrients.caffeine.ceilingMeta"
|
||||
loadErrorKey="nutrients.caffeine.loadError"
|
||||
/>
|
||||
<SingleNutrientCard
|
||||
code="alcohol"
|
||||
icon={Wine}
|
||||
metaKey={null}
|
||||
loadErrorKey="nutrients.alcohol.loadError"
|
||||
/>
|
||||
<MicronutrientsCard />
|
||||
</SubPageShell>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"use client";
|
||||
|
||||
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";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { QueryErrorRow } from "@/components/ui/query-error-row";
|
||||
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 { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { apiGet, apiPatch } from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import {
|
||||
NUTRIENT_CATALOG,
|
||||
nutrientCodesInGroup,
|
||||
type NutrientCode,
|
||||
} from "@/lib/nutrients/catalog";
|
||||
import type {
|
||||
NutrientDailySeries,
|
||||
NutrientIntakeOverview,
|
||||
NutrientPersonalTargetDto,
|
||||
} from "./types";
|
||||
import { nutrientUnitLabel } from "./unit-label";
|
||||
|
||||
const WINDOW_DAYS = 30;
|
||||
|
||||
/** Energy and the macros, in catalog order. */
|
||||
const MACRO_CODES = nutrientCodesInGroup("energy_macro");
|
||||
|
||||
function formatAmount(
|
||||
fmt: { number: (v: number, d?: number) => string },
|
||||
amount: number,
|
||||
): string {
|
||||
return fmt.number(Math.round(amount * 10) / 10, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Energy and macronutrients on `/insights/nutrients` (#1402).
|
||||
*
|
||||
* Renders only when one of the energy and macro codes has data in the
|
||||
* window; most accounts never log them. A segmented row picks the code (only
|
||||
* the codes with data), and one 30-day bar chart shows it: the day's total
|
||||
* as the content value, and a dashed line at the person's own target when
|
||||
* one is set, else at the dietary reference where one exists (energy, fat
|
||||
* and sugar have none). The value stays foreground and the bars are never
|
||||
* coloured by attainment (ui-standards.md): a day above the line is a bar
|
||||
* above a line. The person sets or clears a target for the chosen code
|
||||
* inline.
|
||||
*/
|
||||
export function EnergyMacrosCard() {
|
||||
const { t } = useTranslations();
|
||||
|
||||
const overview = useQuery({
|
||||
queryKey: queryKeys.nutrientIntake(WINDOW_DAYS),
|
||||
queryFn: () =>
|
||||
apiGet<NutrientIntakeOverview>(`/api/nutrients?days=${WINDOW_DAYS}`),
|
||||
});
|
||||
const logged = new Set(
|
||||
(overview.data?.nutrients ?? []).map((row) => row.nutrient),
|
||||
);
|
||||
const codes = MACRO_CODES.filter((code) => logged.has(code));
|
||||
const [picked, setPicked] = useState<NutrientCode | null>(null);
|
||||
const code = picked && codes.includes(picked) ? picked : (codes[0] ?? null);
|
||||
|
||||
// The page shows the overview's own failure; this card adds nothing then.
|
||||
if (!code) return null;
|
||||
|
||||
return (
|
||||
<Card data-slot="nutrients-energy-macros-card">
|
||||
<CardHeader>
|
||||
<TileHeader icon={Flame} title={t("nutrients.macros.title")} />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{codes.length > 1 ? (
|
||||
<Segmented
|
||||
size="sm"
|
||||
className="flex-wrap"
|
||||
options={codes.map((c) => ({
|
||||
value: c,
|
||||
label: t(`nutrients.macros.short.${c}`),
|
||||
}))}
|
||||
value={code}
|
||||
onChange={setPicked}
|
||||
label={t("nutrients.macros.pickLabel")}
|
||||
slot="nutrients-macros-pick"
|
||||
/>
|
||||
) : null}
|
||||
<MacroSeries key={code} code={code} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function MacroSeries({ code }: { code: NutrientCode }) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
const { data, isLoading, isError, error, refetch } = useQuery({
|
||||
queryKey: queryKeys.nutrientDaily(code, WINDOW_DAYS),
|
||||
queryFn: () =>
|
||||
apiGet<NutrientDailySeries>(
|
||||
`/api/nutrients/daily?nutrient=${code}&days=${WINDOW_DAYS}`,
|
||||
),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
if (isError && !data) {
|
||||
return (
|
||||
<QueryErrorRow
|
||||
inset
|
||||
error={error}
|
||||
slot="nutrients-macros-error"
|
||||
message={t("nutrients.macros.loadError")}
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (isLoading || !data) {
|
||||
return (
|
||||
<div className="space-y-3" aria-hidden="true">
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<Skeleton className="h-[240px] w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const unit = nutrientUnitLabel(data.unit, t);
|
||||
const name = t(`nutrients.names.${code}`);
|
||||
const today = data.days.at(-1)?.amount ?? 0;
|
||||
const target = data.personalTarget ?? null;
|
||||
const reference = data.reference;
|
||||
const lineValue = target?.value ?? reference?.value ?? null;
|
||||
|
||||
let meta: string | null = null;
|
||||
if (target) {
|
||||
meta = t(
|
||||
target.direction === "limit"
|
||||
? "nutrients.macros.limitMeta"
|
||||
: "nutrients.macros.targetMeta",
|
||||
{ value: formatAmount(fmt, target.value), unit },
|
||||
);
|
||||
} else if (reference) {
|
||||
meta = t("nutrients.macros.referenceMeta", {
|
||||
value: formatAmount(fmt, reference.value),
|
||||
unit,
|
||||
authority: reference.authority ?? "EFSA",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4" data-slot="nutrients-macros-series">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<p
|
||||
className="text-2xl font-bold tabular-nums"
|
||||
data-slot="nutrients-macros-today"
|
||||
>
|
||||
{formatAmount(fmt, today)} {unit}
|
||||
</p>
|
||||
{meta ? (
|
||||
<p
|
||||
className="text-muted-foreground text-xs"
|
||||
data-slot="nutrients-macros-meta"
|
||||
>
|
||||
{meta}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
{editing ? null : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setEditing(true)}
|
||||
data-slot="nutrients-macros-edit-target"
|
||||
>
|
||||
{t(
|
||||
target
|
||||
? "nutrients.macros.editTarget"
|
||||
: "nutrients.macros.setTarget",
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{editing ? (
|
||||
<TargetEditor
|
||||
code={code}
|
||||
name={name}
|
||||
unit={unit}
|
||||
current={target}
|
||||
onDone={() => setEditing(false)}
|
||||
/>
|
||||
) : null}
|
||||
<NutrientDailyBarChartDynamic
|
||||
days={data.days}
|
||||
unit={unit}
|
||||
valueLabel={name}
|
||||
referenceValue={lineValue}
|
||||
dayLinks
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set or clear the person's daily amount for one code: a number in the code's
|
||||
* canonical unit and whether it is an amount to reach or one to stay under.
|
||||
*/
|
||||
function TargetEditor({
|
||||
code,
|
||||
name,
|
||||
unit,
|
||||
current,
|
||||
onDone,
|
||||
}: {
|
||||
code: NutrientCode;
|
||||
name: string;
|
||||
unit: string;
|
||||
current: NutrientPersonalTargetDto | null;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const { t } = useTranslations();
|
||||
const queryClient = useQueryClient();
|
||||
const [value, setValue] = useState(current ? String(current.value) : "");
|
||||
const [direction, setDirection] = useState<"target" | "limit">(
|
||||
current?.direction ?? "target",
|
||||
);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const inputId = `nutrient-target-${code}`;
|
||||
|
||||
const parsed = Number(value.replace(",", "."));
|
||||
const valid =
|
||||
value.trim() !== "" &&
|
||||
Number.isFinite(parsed) &&
|
||||
parsed > 0 &&
|
||||
parsed <= NUTRIENT_CATALOG[code].plausibleDailyMax;
|
||||
|
||||
async function save(next: NutrientPersonalTargetDto | null) {
|
||||
setSaving(true);
|
||||
try {
|
||||
await apiPatch("/api/nutrients/targets", { targets: { [code]: next } });
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.nutrientTargets(),
|
||||
}),
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: queryKeys.nutrientDaily(code, WINDOW_DAYS),
|
||||
}),
|
||||
]);
|
||||
onDone();
|
||||
} catch {
|
||||
toast.error(t("nutrients.macros.saveFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
className="bg-muted/40 space-y-3 rounded-lg border p-3"
|
||||
data-slot="nutrients-macros-target-editor"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (valid) void save({ value: parsed, direction });
|
||||
}}
|
||||
>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={inputId}>
|
||||
{t("nutrients.macros.targetLabel", { name, unit })}
|
||||
</Label>
|
||||
<Input
|
||||
id={inputId}
|
||||
inputMode="decimal"
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
aria-invalid={value.trim() !== "" && !valid}
|
||||
className="max-w-40"
|
||||
/>
|
||||
</div>
|
||||
<Segmented
|
||||
mode="toggle"
|
||||
size="sm"
|
||||
options={[
|
||||
{ value: "target", label: t("nutrients.macros.directionTarget") },
|
||||
{ value: "limit", label: t("nutrients.macros.directionLimit") },
|
||||
]}
|
||||
value={direction}
|
||||
onChange={setDirection}
|
||||
label={t("nutrients.macros.directionLabel")}
|
||||
slot="nutrients-macros-direction"
|
||||
/>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="submit" size="sm" disabled={!valid || saving}>
|
||||
{t("common.save")}
|
||||
</Button>
|
||||
{current ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={saving}
|
||||
onClick={() => void save(null)}
|
||||
>
|
||||
{t("nutrients.macros.clearTarget")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={saving}
|
||||
onClick={onDone}
|
||||
>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -18,7 +18,7 @@ const WINDOW_DAYS = 30;
|
||||
/**
|
||||
* v1.29 — hydration hero card on `/insights/nutrients`.
|
||||
*
|
||||
* Today's total (all sources summed) as the content value, a muted EFSA
|
||||
* Today's total (all sources folded) as the content value, a muted
|
||||
* reference-intake meta line (omitted when the profile has no sex on
|
||||
* file — the catalog's own contract), a 30-day bar chart with a dashed
|
||||
* reference line. No ring, no attainment colour — the bar chart with a
|
||||
@@ -86,6 +86,7 @@ export function HydrationCard() {
|
||||
{t("nutrients.hydration.referenceMeta", {
|
||||
value: fmt.integer(Math.round(data.reference.value)),
|
||||
unit: data.unit,
|
||||
authority: data.reference.authority ?? "EFSA",
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
@@ -14,10 +14,12 @@ import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import { binaryReferenceSex } from "@/lib/profile/sex";
|
||||
import {
|
||||
NUTRIENT_CODES,
|
||||
NUTRIENT_CATALOG,
|
||||
isNutrientCode,
|
||||
nutrientCodesInGroup,
|
||||
resolveNutrientReference,
|
||||
type NutrientCode,
|
||||
type NutrientGroup,
|
||||
} from "@/lib/nutrients/catalog";
|
||||
import type {
|
||||
NutrientAmountBySource,
|
||||
@@ -28,10 +30,16 @@ import { nutrientUnitLabel } from "./unit-label";
|
||||
|
||||
const WINDOW_DAYS = 30;
|
||||
|
||||
/** The vitamin/mineral codes — water + caffeine ride their own cards. */
|
||||
const MICRONUTRIENT_CODES = NUTRIENT_CODES.filter(
|
||||
(code) => code !== "water" && code !== "caffeine",
|
||||
);
|
||||
/**
|
||||
* The groups this card lists. Water, caffeine, alcohol and energy with the
|
||||
* macros ride their own cards.
|
||||
*/
|
||||
const MICRONUTRIENT_GROUPS: ReadonlyArray<NutrientGroup> = [
|
||||
"vitamin",
|
||||
"mineral",
|
||||
"omega3",
|
||||
];
|
||||
const MICRONUTRIENT_CODES = nutrientCodesInGroup(...MICRONUTRIENT_GROUPS);
|
||||
|
||||
function formatAmount(
|
||||
fmt: { number: (v: number, d?: number) => string },
|
||||
@@ -45,6 +53,8 @@ const SOURCES = [
|
||||
{ key: "APPLE_HEALTH", color: "var(--chart-1)" },
|
||||
{ key: "MANUAL", color: "var(--chart-2)" },
|
||||
{ key: "SUPPLEMENT", color: "var(--chart-3)" },
|
||||
{ key: "EXTERNAL", color: "var(--chart-4)" },
|
||||
{ key: "HEALTH_CONNECT", color: "var(--chart-5)" },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
@@ -144,9 +154,9 @@ function UpperLimitNote({
|
||||
*
|
||||
* Rows ONLY for codes with data in the last 30 days (catalog order),
|
||||
* each carrying a latest-day total + a muted "N of 30 days · ref X
|
||||
* (EFSA)" meta line — reference omitted when the profile has no sex on
|
||||
* file. A muted footer counts "M of 24 tracked"; zero rows collapse the
|
||||
* card to a single honest `EmptyState`, never 24 empty rows. No
|
||||
* (authority)" meta line — reference omitted when the profile has no sex on
|
||||
* file. A muted footer counts "M of N tracked"; zero rows collapse the
|
||||
* card to a single honest `EmptyState`, never a column of empty rows. No
|
||||
* sparkline in slice 1 — sparse series make sparklines lie.
|
||||
*/
|
||||
export function MicronutrientsCard() {
|
||||
@@ -168,8 +178,7 @@ export function MicronutrientsCard() {
|
||||
const rows = (data?.nutrients ?? []).filter(
|
||||
(row) =>
|
||||
isNutrientCode(row.nutrient) &&
|
||||
row.nutrient !== "water" &&
|
||||
row.nutrient !== "caffeine",
|
||||
MICRONUTRIENT_GROUPS.includes(NUTRIENT_CATALOG[row.nutrient].group),
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -229,6 +238,7 @@ export function MicronutrientsCard() {
|
||||
window: WINDOW_DAYS,
|
||||
value: formatAmount(fmt, reference.value),
|
||||
unit: unitLabel,
|
||||
authority: reference.authority,
|
||||
})
|
||||
: t("nutrients.micronutrients.rowMetaNoRef", {
|
||||
days: row.daysWithData,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Coffee } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||
import { QueryErrorRow } from "@/components/ui/query-error-row";
|
||||
@@ -11,30 +11,52 @@ import { useTranslations, useFormatters } from "@/lib/i18n/context";
|
||||
import { apiGet } from "@/lib/api/api-fetch";
|
||||
import { queryKeys } from "@/lib/query-keys";
|
||||
import type { NutrientDailySeries } from "./types";
|
||||
import { nutrientUnitLabel } from "./unit-label";
|
||||
|
||||
const WINDOW_DAYS = 30;
|
||||
|
||||
interface SingleNutrientCardProps {
|
||||
/** The catalog code the card charts (`caffeine`, `alcohol`). */
|
||||
code: string;
|
||||
icon: LucideIcon;
|
||||
/**
|
||||
* The i18n key of the meta line naming the reference, or `null` for a code
|
||||
* whose reference the card does not draw (alcohol has none to draw).
|
||||
*/
|
||||
metaKey: string | null;
|
||||
/** The i18n key of the failed-read message. */
|
||||
loadErrorKey: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.29 — caffeine card on `/insights/nutrients`. Rendered ONLY when the
|
||||
* window carries at least one logged day. The EFSA safe-level value is
|
||||
* phrased as a ceiling, never "limit exceeded" colouring: a day above the
|
||||
* dashed line is just a bar above a dashed line.
|
||||
* One nutrient's card on `/insights/nutrients`: today's total and a 30-day
|
||||
* bar chart. Rendered ONLY when the window carries at least one logged day.
|
||||
* Caffeine's EFSA safe level is phrased as a ceiling and drawn as a dashed
|
||||
* line, never as "limit exceeded" colouring: a day above the line is just a
|
||||
* bar above a dashed line. Alcohol draws no line.
|
||||
*
|
||||
* Nothing is drawn while the read is on its way. Most accounts never log
|
||||
* caffeine, so a loading card was most often a card that collapsed again a
|
||||
* these, so a loading card was most often a card that collapsed again a
|
||||
* moment later. A failed read says so with a retry, instead of passing for
|
||||
* a month without caffeine; it is its own read, so the hydration card's
|
||||
* notice does not cover it.
|
||||
* a month without data; it is its own read, so the hydration card's notice
|
||||
* does not cover it.
|
||||
*/
|
||||
export function CaffeineCard() {
|
||||
export function SingleNutrientCard({
|
||||
code,
|
||||
icon,
|
||||
metaKey,
|
||||
loadErrorKey,
|
||||
}: SingleNutrientCardProps) {
|
||||
const { t } = useTranslations();
|
||||
const fmt = useFormatters();
|
||||
const title = t(`nutrients.names.${code}`);
|
||||
const slot = `nutrients-${code}-card`;
|
||||
|
||||
const { data, error, isError, refetch } = useQuery({
|
||||
queryKey: queryKeys.nutrientDaily("caffeine", WINDOW_DAYS),
|
||||
queryKey: queryKeys.nutrientDaily(code, WINDOW_DAYS),
|
||||
queryFn: () =>
|
||||
apiGet<NutrientDailySeries>(
|
||||
`/api/nutrients/daily?nutrient=caffeine&days=${WINDOW_DAYS}`,
|
||||
`/api/nutrients/daily?nutrient=${code}&days=${WINDOW_DAYS}`,
|
||||
),
|
||||
// The "route swing within a minute is a free cache hit" convention used
|
||||
// across the insights queries.
|
||||
@@ -45,16 +67,16 @@ export function CaffeineCard() {
|
||||
// card beside it.
|
||||
if (isError && !data) {
|
||||
return (
|
||||
<Card data-slot="nutrients-caffeine-card">
|
||||
<Card data-slot={slot}>
|
||||
<CardHeader>
|
||||
<TileHeader icon={Coffee} title={t("nutrients.names.caffeine")} />
|
||||
<TileHeader icon={icon} title={title} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<QueryErrorRow
|
||||
inset
|
||||
error={error}
|
||||
slot="nutrients-caffeine-error"
|
||||
message={t("nutrients.caffeine.loadError")}
|
||||
slot={`nutrients-${code}-error`}
|
||||
message={t(loadErrorKey)}
|
||||
onRetry={() => void refetch()}
|
||||
/>
|
||||
</CardContent>
|
||||
@@ -66,31 +88,34 @@ export function CaffeineCard() {
|
||||
if (!data || !hasData) return null;
|
||||
|
||||
const todayTotal = data.days.at(-1)?.amount ?? 0;
|
||||
const unit = nutrientUnitLabel(data.unit, t);
|
||||
const reference = metaKey ? data.reference : null;
|
||||
|
||||
return (
|
||||
<Card data-slot="nutrients-caffeine-card">
|
||||
<Card data-slot={slot}>
|
||||
<CardHeader>
|
||||
<TileHeader icon={Coffee} title={t("nutrients.names.caffeine")} />
|
||||
<TileHeader icon={icon} title={title} />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
<p className="text-2xl font-bold tabular-nums">
|
||||
{fmt.integer(Math.round(todayTotal))} {data.unit}
|
||||
{fmt.integer(Math.round(todayTotal))} {unit}
|
||||
</p>
|
||||
{data.reference ? (
|
||||
{metaKey && reference ? (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("nutrients.caffeine.ceilingMeta", {
|
||||
value: fmt.integer(Math.round(data.reference.value)),
|
||||
unit: data.unit,
|
||||
{t(metaKey, {
|
||||
value: fmt.integer(Math.round(reference.value)),
|
||||
unit,
|
||||
authority: reference.authority ?? "EFSA",
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<NutrientDailyBarChartDynamic
|
||||
days={data.days}
|
||||
unit={data.unit}
|
||||
valueLabel={t("nutrients.names.caffeine")}
|
||||
referenceValue={data.reference?.value ?? null}
|
||||
unit={unit}
|
||||
valueLabel={title}
|
||||
referenceValue={reference?.value ?? null}
|
||||
dayLinks
|
||||
/>
|
||||
</CardContent>
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
*/
|
||||
|
||||
export interface ResolvedNutrientReferenceDto {
|
||||
/** The body that set the value; absent on an older server (read as EFSA). */
|
||||
authority?: "EFSA" | "IOM" | "NIH ODS";
|
||||
kind: "PRI" | "AI" | "safeLevel";
|
||||
direction: "target" | "upperGuidance";
|
||||
value: number;
|
||||
@@ -24,12 +26,23 @@ export interface NutrientDailySeries {
|
||||
aboveUpperLimit?: boolean | null;
|
||||
}>;
|
||||
reference: ResolvedNutrientReferenceDto | null;
|
||||
/** The target the person set for this nutrient; absent on an older server. */
|
||||
personalTarget?: NutrientPersonalTargetDto | null;
|
||||
upperLimit?: NutrientUpperLimitDto | null;
|
||||
}
|
||||
|
||||
/** v1.43 — an amount split by source; a source with nothing is absent. */
|
||||
/** A daily amount the person set: one to reach, or one to stay under. */
|
||||
export interface NutrientPersonalTargetDto {
|
||||
value: number;
|
||||
direction: "target" | "limit";
|
||||
}
|
||||
|
||||
/** An amount split by the sources that counted; any other is absent. */
|
||||
export type NutrientAmountBySource = Partial<
|
||||
Record<"APPLE_HEALTH" | "MANUAL" | "SUPPLEMENT", number>
|
||||
Record<
|
||||
"APPLE_HEALTH" | "HEALTH_CONNECT" | "EXTERNAL" | "MANUAL" | "SUPPLEMENT",
|
||||
number
|
||||
>
|
||||
>;
|
||||
|
||||
/** v1.43 — the tolerable upper intake level the server judged against. */
|
||||
|
||||
@@ -48,9 +48,6 @@ export const COMPOSITION_CATEGORIES: ReadonlySet<string> = new Set([
|
||||
"SUPPLEMENT",
|
||||
]);
|
||||
|
||||
/** Water is a day total, never a supplement ingredient. */
|
||||
const NOT_AN_INGREDIENT = "water";
|
||||
|
||||
interface EditorRow {
|
||||
key: number;
|
||||
nutrient: string;
|
||||
@@ -127,9 +124,7 @@ function CompositionEditor({
|
||||
const queryClient = useQueryClient();
|
||||
const formId = useId();
|
||||
const catalog = useNutrientCatalog(open);
|
||||
const entries = (catalog.data?.entries ?? []).filter(
|
||||
(entry) => entry.code !== NOT_AN_INGREDIENT,
|
||||
);
|
||||
const entries = (catalog.data?.entries ?? []).filter((e) => e.ingredient);
|
||||
const byCode = new Map(entries.map((entry) => [entry.code, entry]));
|
||||
|
||||
const [rows, setRows] = useState<EditorRow[]>(() =>
|
||||
|
||||
@@ -29,6 +29,8 @@ export interface NutrientCatalogEntryDto {
|
||||
labelKey: string;
|
||||
label: string;
|
||||
syncable: boolean;
|
||||
/** Whether a supplement's composition may name this code. */
|
||||
ingredient: boolean;
|
||||
inputUnits: Array<{ unit: string; factorToCanonical: number }>;
|
||||
upperLimit: {
|
||||
value: number;
|
||||
|
||||
@@ -125,6 +125,7 @@ import {
|
||||
type ProfileSex,
|
||||
} from "@/lib/profile/sex";
|
||||
import { dayKeyAsUtcMidnight } from "@/lib/tz/date-only";
|
||||
import { foldNutrientDays } from "@/lib/nutrients/day-total";
|
||||
|
||||
/** Briefing freshness window — mirrors the 24 h TTL on the advisor cache. */
|
||||
const BRIEFING_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
@@ -601,9 +602,9 @@ async function buildMoodBlock(
|
||||
|
||||
/**
|
||||
* v1.29 — fluid-intake dashboard tile block, read from `NutrientIntakeDay`
|
||||
* (nutrient="water", last 30 day-keys, summed ACROSS SOURCES per day —
|
||||
* migration 0249 can carry an APPLE_HEALTH row and a MANUAL row for the
|
||||
* same day). ≤ 60 rows off the existing `(userId, nutrient, day desc)`
|
||||
* (nutrient="water", last 30 day-keys, folded ACROSS SOURCES per day by
|
||||
* `foldNutrientDay` — migration 0249 can carry an APPLE_HEALTH row and a
|
||||
* MANUAL row for the same day). A few rows per day off the existing `(userId, nutrient, day desc)`
|
||||
* index. Sparse by construction (only days with an actual write become a
|
||||
* `DataPoint`) — matching the convention every real `MeasurementType`
|
||||
* summary follows: an unlogged day is absent, not a zero reading. `null`
|
||||
@@ -623,18 +624,15 @@ async function buildNutrientWaterBlock(
|
||||
.slice(0, 10);
|
||||
const rows = await prisma.nutrientIntakeDay.findMany({
|
||||
where: { userId, nutrient: "water", day: { gte: since } },
|
||||
select: { day: true, amount: true },
|
||||
select: { day: true, amount: true, source: true },
|
||||
});
|
||||
if (rows.length === 0) return null;
|
||||
|
||||
const sumByDay = new Map<string, number>();
|
||||
for (const row of rows) {
|
||||
sumByDay.set(row.day, (sumByDay.get(row.day) ?? 0) + row.amount);
|
||||
}
|
||||
const points: DataPoint[] = [...sumByDay.entries()]
|
||||
.map(([day, amount]) => ({
|
||||
const folds = foldNutrientDays(rows, (row) => row.day);
|
||||
const points: DataPoint[] = [...folds.entries()]
|
||||
.map(([day, fold]) => ({
|
||||
date: dayKeyAsUtcMidnight(day),
|
||||
value: amount,
|
||||
value: fold.total,
|
||||
}))
|
||||
.sort((a, b) => a.date.getTime() - b.date.getTime());
|
||||
|
||||
|
||||
@@ -285,9 +285,11 @@ export const DAILY_SUM_SPECS: readonly DailySumSpec[] = [
|
||||
];
|
||||
|
||||
/**
|
||||
* Nutrition columns (grams) onto the nutrient catalog. Energy and the
|
||||
* macronutrients are left out: the catalog is supplements and water, never a
|
||||
* food diary.
|
||||
* Nutrition columns (grams) onto the nutrient catalog: the vitamins, the
|
||||
* minerals this import has always read, and caffeine. Energy, the
|
||||
* macronutrients, sodium and potassium are in the catalog since #1402 but not
|
||||
* read from a Health Connect export yet; they arrive through the HealthKit sync
|
||||
* or a bridge token.
|
||||
*/
|
||||
export const NUTRITION_COLUMNS: Readonly<
|
||||
Partial<Record<NutrientCode, { column: string; factor: number }>>
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
buildOvernightClimateSeries,
|
||||
buildTrainingLoadSeries,
|
||||
buildWorkoutMinutesSeries,
|
||||
MAX_MACRONUTRIENT_CHANNELS,
|
||||
MAX_MICRONUTRIENT_CHANNELS,
|
||||
MIN_ALCOHOL_DAYS,
|
||||
MIN_OVERNIGHT_HOURS,
|
||||
@@ -38,12 +39,22 @@ function daily(values: number[], from = 0): DailySeriesPoint[] {
|
||||
}
|
||||
|
||||
describe("buildNutrientDailySeries", () => {
|
||||
it("sums sources per day and maps water and caffeine to their channels", () => {
|
||||
it("folds sources per day and maps water and caffeine to their channels", () => {
|
||||
const out = buildNutrientDailySeries(
|
||||
[
|
||||
{ day: dayN(0), nutrient: "water", amount: 1200 },
|
||||
{ day: dayN(0), nutrient: "water", amount: 300 },
|
||||
{ day: dayN(1), nutrient: "caffeine", amount: 95 },
|
||||
{
|
||||
day: dayN(0),
|
||||
nutrient: "water",
|
||||
amount: 1200,
|
||||
source: "APPLE_HEALTH",
|
||||
},
|
||||
{ day: dayN(0), nutrient: "water", amount: 300, source: "MANUAL" },
|
||||
{
|
||||
day: dayN(1),
|
||||
nutrient: "caffeine",
|
||||
amount: 95,
|
||||
source: "APPLE_HEALTH",
|
||||
},
|
||||
],
|
||||
{ minDays: 20 },
|
||||
);
|
||||
@@ -68,15 +79,30 @@ describe("buildNutrientDailySeries", () => {
|
||||
];
|
||||
codes.forEach((code, c) => {
|
||||
for (let d = 0; d < 30 - c; d += 1) {
|
||||
rows.push({ day: dayN(d), nutrient: code, amount: 10 + (d % 3) });
|
||||
rows.push({
|
||||
day: dayN(d),
|
||||
nutrient: code,
|
||||
amount: 10 + (d % 3),
|
||||
source: "APPLE_HEALTH",
|
||||
});
|
||||
}
|
||||
});
|
||||
for (let d = 0; d < 40; d += 1) {
|
||||
rows.push({ day: dayN(d), nutrient: "vitamin_c", amount: 500 });
|
||||
rows.push({
|
||||
day: dayN(d),
|
||||
nutrient: "vitamin_c",
|
||||
amount: 500,
|
||||
source: "APPLE_HEALTH",
|
||||
});
|
||||
}
|
||||
// One varying code below the day floor.
|
||||
for (let d = 0; d < 10; d += 1) {
|
||||
rows.push({ day: dayN(d), nutrient: "copper", amount: d });
|
||||
rows.push({
|
||||
day: dayN(d),
|
||||
nutrient: "copper",
|
||||
amount: d,
|
||||
source: "APPLE_HEALTH",
|
||||
});
|
||||
}
|
||||
const keys = buildNutrientDailySeries(rows, { minDays: 20 })
|
||||
.map((s) => s.key)
|
||||
@@ -89,6 +115,70 @@ describe("buildNutrientDailySeries", () => {
|
||||
"NUTRIENT:vitamin_d",
|
||||
]);
|
||||
});
|
||||
|
||||
it("counts only the largest day-total source when a tracker and Apple Health both report", () => {
|
||||
const out = buildNutrientDailySeries(
|
||||
[
|
||||
{
|
||||
day: dayN(0),
|
||||
nutrient: "water",
|
||||
amount: 2000,
|
||||
source: "APPLE_HEALTH",
|
||||
},
|
||||
{ day: dayN(0), nutrient: "water", amount: 2100, source: "EXTERNAL" },
|
||||
{ day: dayN(0), nutrient: "water", amount: 250, source: "MANUAL" },
|
||||
],
|
||||
{ minDays: 20 },
|
||||
);
|
||||
expect(out[0].points).toEqual([{ day: dayN(0), value: 2350 }]);
|
||||
});
|
||||
|
||||
it("gives the macros their own budget, so they never crowd out the micronutrients, and leaves alcohol out", () => {
|
||||
const rows: Array<{
|
||||
day: string;
|
||||
nutrient: string;
|
||||
amount: number;
|
||||
source: string;
|
||||
}> = [];
|
||||
const push = (code: string, days: number) => {
|
||||
for (let d = 0; d < days; d += 1) {
|
||||
rows.push({
|
||||
day: dayN(d),
|
||||
nutrient: code,
|
||||
amount: 10 + (d % 4),
|
||||
source: "EXTERNAL",
|
||||
});
|
||||
}
|
||||
};
|
||||
// Six macros logged every day, more than any micronutrient.
|
||||
for (const code of [
|
||||
"energy",
|
||||
"protein",
|
||||
"carbohydrates",
|
||||
"fat",
|
||||
"sugar",
|
||||
"fiber",
|
||||
]) {
|
||||
push(code, 60);
|
||||
}
|
||||
push("alcohol", 60);
|
||||
for (const code of ["zinc", "iron", "magnesium", "vitamin_d", "selenium"]) {
|
||||
push(code, 30);
|
||||
}
|
||||
const keys = buildNutrientDailySeries(rows, { minDays: 20 })
|
||||
.map((s) => s.key)
|
||||
.slice(2);
|
||||
expect(MAX_MACRONUTRIENT_CHANNELS).toBe(2);
|
||||
expect(keys).toEqual([
|
||||
"NUTRIENT:iron",
|
||||
"NUTRIENT:magnesium",
|
||||
"NUTRIENT:selenium",
|
||||
"NUTRIENT:vitamin_d",
|
||||
"NUTRIENT:carbohydrates",
|
||||
"NUTRIENT:energy",
|
||||
]);
|
||||
expect(keys).not.toContain("NUTRIENT:alcohol");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAlcoholDailySeries", () => {
|
||||
|
||||
@@ -1168,13 +1168,13 @@ export async function fetchLabDraws(
|
||||
// ─── v1.44 — the extended channel families ─────────────────────────────────
|
||||
|
||||
/**
|
||||
* Upper bound on nutrient rows read for one scan: 180 days × 28 codes × two
|
||||
* sources is about ten thousand; the cap falls on the oldest rows.
|
||||
* Upper bound on nutrient rows read for one scan: 180 days × 37 codes × three
|
||||
* sources is about twenty thousand; the cap falls on the oldest rows.
|
||||
*/
|
||||
const NUTRIENT_READ_CAP = 12_000;
|
||||
const NUTRIENT_READ_CAP = 20_000;
|
||||
|
||||
/**
|
||||
* HYDRATION, CAFFEINE and up to four micronutrients from the nutrient log.
|
||||
* HYDRATION, CAFFEINE and the capped micronutrient and macro channels.
|
||||
* The caller skips this read when the opt-in `nutrients` module is off.
|
||||
*/
|
||||
export async function fetchNutrientSeries(
|
||||
@@ -1186,7 +1186,7 @@ export async function fetchNutrientSeries(
|
||||
where: { userId, day: { gte: userDayKey(since, tz) } },
|
||||
orderBy: { day: "desc" },
|
||||
take: NUTRIENT_READ_CAP,
|
||||
select: { day: true, nutrient: true, amount: true },
|
||||
select: { day: true, nutrient: true, amount: true, source: true },
|
||||
});
|
||||
return buildNutrientDailySeries(rows, { minDays: MIN_PAIRED_N });
|
||||
}
|
||||
|
||||
@@ -36,6 +36,12 @@
|
||||
*/
|
||||
import { dayKeyForUserTz } from "@/lib/measurements/consolidation-tz";
|
||||
import { shiftDateKey } from "@/lib/tz/format";
|
||||
import { foldNutrientDays } from "@/lib/nutrients/day-total";
|
||||
import {
|
||||
NUTRIENT_CATALOG,
|
||||
isNutrientCode,
|
||||
type NutrientGroup,
|
||||
} from "@/lib/nutrients/catalog";
|
||||
import type { DoseHistoryRow } from "@/lib/medications/scheduling/dose-history";
|
||||
import {
|
||||
ALCOHOL_CHANNEL_KEY,
|
||||
@@ -258,34 +264,44 @@ export interface NutrientDayRow {
|
||||
day: string;
|
||||
nutrient: string;
|
||||
amount: number;
|
||||
source: string;
|
||||
}
|
||||
|
||||
/** Ceiling on `NUTRIENT:<code>` channels in one scan. */
|
||||
/** Ceiling on vitamin, mineral and omega-3 `NUTRIENT:<code>` channels in one scan. */
|
||||
export const MAX_MICRONUTRIENT_CHANNELS = 4;
|
||||
|
||||
/** Ceiling on energy and macronutrient `NUTRIENT:<code>` channels in one scan. */
|
||||
export const MAX_MACRONUTRIENT_CHANNELS = 2;
|
||||
|
||||
/**
|
||||
* The intake channels from the nutrient log: water as HYDRATION, caffeine as
|
||||
* CAFFEINE, and at most {@link MAX_MICRONUTRIENT_CHANNELS} micronutrients as
|
||||
* `NUTRIENT:<code>`.
|
||||
* CAFFEINE, at most {@link MAX_MICRONUTRIENT_CHANNELS} micronutrients and at
|
||||
* most {@link MAX_MACRONUTRIENT_CHANNELS} energy or macronutrient codes as
|
||||
* `NUTRIENT:<code>`. The two budgets are separate so a food tracker's six
|
||||
* daily macros cannot crowd the vitamins out of the scan. Logged alcohol is
|
||||
* left out: the ALCOHOL channel already comes from the mood tag, and a second
|
||||
* alcohol channel would mostly correlate with the first.
|
||||
*
|
||||
* A day's amount is the sum across its sources (a manual water entry and the
|
||||
* Apple Health total are two rows, and reads sum them). A day without a row is
|
||||
* no point: the log does not say whether nothing was taken or nothing was
|
||||
* recorded. The micronutrients admitted are those with at least `minDays`
|
||||
* logged days and any day-to-day variance, the most-logged first (code as the
|
||||
* tie-break): a daily supplement at a fixed dose is a constant, and a
|
||||
* constant cannot correlate with anything. Pure.
|
||||
* A day's amount is `foldNutrientDay` over its sources (the largest day-total
|
||||
* source counts, a manual water entry adds on top), the same fold every read
|
||||
* uses. A day without a row is no point: the log does not say whether nothing
|
||||
* was taken or nothing was recorded. The codes admitted are those with at
|
||||
* least `minDays` logged days and any day-to-day variance, the most-logged
|
||||
* first (code as the tie-break): a daily supplement at a fixed dose is a
|
||||
* constant, and a constant cannot correlate with anything. Pure.
|
||||
*/
|
||||
export function buildNutrientDailySeries(
|
||||
rows: readonly NutrientDayRow[],
|
||||
opts: { minDays: number },
|
||||
): NamedSeries[] {
|
||||
const finite = rows.filter((row) => Number.isFinite(row.amount));
|
||||
const folds = foldNutrientDays(finite, (row) => `${row.nutrient}|${row.day}`);
|
||||
const byNutrient = new Map<string, Map<string, number>>();
|
||||
for (const row of rows) {
|
||||
if (!Number.isFinite(row.amount)) continue;
|
||||
const days = byNutrient.get(row.nutrient) ?? new Map<string, number>();
|
||||
days.set(row.day, (days.get(row.day) ?? 0) + row.amount);
|
||||
byNutrient.set(row.nutrient, days);
|
||||
for (const [key, fold] of folds) {
|
||||
const [nutrient, day] = key.split("|");
|
||||
const days = byNutrient.get(nutrient) ?? new Map<string, number>();
|
||||
days.set(day, fold.total);
|
||||
byNutrient.set(nutrient, days);
|
||||
}
|
||||
const pointsOf = (code: string): DailySeriesPoint[] =>
|
||||
[...(byNutrient.get(code) ?? new Map<string, number>()).entries()]
|
||||
@@ -304,18 +320,30 @@ export function buildNutrientDailySeries(
|
||||
points: pointsOf("caffeine"),
|
||||
},
|
||||
];
|
||||
const candidates = [...byNutrient.keys()]
|
||||
.filter((code) => code !== "water" && code !== "caffeine")
|
||||
.map((code) => ({ code, points: pointsOf(code) }))
|
||||
.filter(
|
||||
({ points }) =>
|
||||
points.length >= opts.minDays &&
|
||||
points.some((p) => p.value !== points[0].value),
|
||||
)
|
||||
.sort(
|
||||
(a, b) => b.points.length - a.points.length || (a.code < b.code ? -1 : 1),
|
||||
)
|
||||
.slice(0, MAX_MICRONUTRIENT_CHANNELS);
|
||||
const admitted = (
|
||||
groups: ReadonlySet<NutrientGroup>,
|
||||
budget: number,
|
||||
): Array<{ code: string; points: DailySeriesPoint[] }> =>
|
||||
[...byNutrient.keys()]
|
||||
.filter(
|
||||
(code) =>
|
||||
isNutrientCode(code) && groups.has(NUTRIENT_CATALOG[code].group),
|
||||
)
|
||||
.map((code) => ({ code, points: pointsOf(code) }))
|
||||
.filter(
|
||||
({ points }) =>
|
||||
points.length >= opts.minDays &&
|
||||
points.some((p) => p.value !== points[0].value),
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
b.points.length - a.points.length || (a.code < b.code ? -1 : 1),
|
||||
)
|
||||
.slice(0, budget);
|
||||
const candidates = [
|
||||
...admitted(MICRONUTRIENT_GROUPS, MAX_MICRONUTRIENT_CHANNELS),
|
||||
...admitted(MACRONUTRIENT_GROUPS, MAX_MACRONUTRIENT_CHANNELS),
|
||||
];
|
||||
for (const { code, points } of candidates) {
|
||||
out.push({
|
||||
key: `${NUTRIENT_CHANNEL_PREFIX}${code}`,
|
||||
@@ -326,6 +354,15 @@ export function buildNutrientDailySeries(
|
||||
return out;
|
||||
}
|
||||
|
||||
const MICRONUTRIENT_GROUPS: ReadonlySet<NutrientGroup> = new Set([
|
||||
"vitamin",
|
||||
"mineral",
|
||||
"omega3",
|
||||
]);
|
||||
const MACRONUTRIENT_GROUPS: ReadonlySet<NutrientGroup> = new Set([
|
||||
"energy_macro",
|
||||
]);
|
||||
|
||||
/** One mood entry as the alcohol channel reads it. */
|
||||
export interface AlcoholTagEntry {
|
||||
at: Date;
|
||||
|
||||
@@ -3353,7 +3353,7 @@
|
||||
{
|
||||
"name": "get_nutrients",
|
||||
"title": "Get nutrient intake",
|
||||
"description": "Fetch the user's synced micronutrient intake — water, caffeine, and the 24 tracked vitamins/minerals — as day totals summed across sources (e.g. an Apple Health sync AND a manual water entry on the same day). Omit `nutrient` for a presence overview across every logged code (latest logged day, latest day's total, days with data). Pass a catalog code, or the nutrient's display name in any language HealthLog ships (e.g. 'water', 'magnesium', 'vitamin_d', 'Magnésium', 'Żelazo'), for that nutrient's per-day series over a trailing window, plus its EFSA dietary reference resolved against the user's own profile sex — omitted, never guessed, when sex is not on file. Gated on the opt-in `nutrients` module. Returns { present: false, reason: \"module_disabled\" } when the module is off, or { present: false } when nothing matches.",
|
||||
"description": "Fetch the user's nutrient intake — water, caffeine, the tracked vitamins and minerals (sodium and potassium included), dietary energy in kcal, the macronutrients (protein, carbohydrates, fat, sugar, fiber) in g, and alcohol in g of ethanol — as day totals across sources. Apple Health, Health Connect and a food-tracker bridge each report the whole day, so only the largest of them counts; a manual water entry and taken supplements add on top. Omit `nutrient` for a presence overview across every logged code (latest logged day, latest day's total, days with data). Pass a catalog code, or the nutrient's display name in any language HealthLog ships (e.g. 'water', 'magnesium', 'vitamin_d', 'Magnésium', 'Żelazo'), for that nutrient's per-day series over a trailing window, plus its dietary reference (with the authority that set it: EFSA, or IOM for protein and carbohydrates) resolved against the user's own profile sex — omitted, never guessed, when sex is not on file or the nutrient has none — and the target the user set for it, if any. Gated on the opt-in `nutrients` module. Returns { present: false, reason: \"module_disabled\" } when the module is off, or { present: false } when nothing matches.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -3451,6 +3451,14 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"authority": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"EFSA",
|
||||
"IOM",
|
||||
"NIH ODS"
|
||||
]
|
||||
},
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -3485,6 +3493,33 @@
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"personalTarget": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"value": {
|
||||
"type": "number"
|
||||
},
|
||||
"direction": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"target",
|
||||
"limit"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"value",
|
||||
"direction"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -115,7 +115,7 @@ describe("resolveNutrientCode — every shipped locale, not just English", () =>
|
||||
it("still refuses a word that is in no bundle — a parse miss stays a miss", () => {
|
||||
expect(resolveNutrientCode("bananas")).toBeNull();
|
||||
expect(resolveNutrientCode("Bananen")).toBeNull();
|
||||
expect(resolveNutrientCode("protein")).toBeNull();
|
||||
expect(resolveNutrientCode("creatine")).toBeNull();
|
||||
});
|
||||
|
||||
// The property, not a sample: EVERY code's name in EVERY shipped locale
|
||||
@@ -226,11 +226,13 @@ describe("getNutrients — per-nutrient mode", () => {
|
||||
expect(result.days).toHaveLength(3);
|
||||
// Female reference for magnesium is 300 mg (EFSA DRV 2015).
|
||||
expect(result.reference).toEqual({
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
value: 300,
|
||||
source: "EFSA DRV 2015 (adults)",
|
||||
});
|
||||
expect(result.personalTarget).toBeNull();
|
||||
});
|
||||
|
||||
it("omits the reference (never guesses) when the profile has no sex on file", async () => {
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
* coverage review G1).
|
||||
*
|
||||
* Thin façade over the SAME two reads `GET /api/nutrients` (presence
|
||||
* overview) and `GET /api/nutrients/daily` (per-day summed series + the
|
||||
* resolved EFSA reference) run: the same tz-anchored day-key math
|
||||
* (`userDayKey` / `shiftDateKey` against the caller's own local "today"),
|
||||
* the same sum-across-sources fold (a day can carry an APPLE_HEALTH row AND
|
||||
* a MANUAL row since migration 0249), and the same sex-aware
|
||||
* overview) and `GET /api/nutrients/daily` (per-day series + the resolved
|
||||
* dietary reference + the person's own target) run: the same tz-anchored
|
||||
* day-key math (`userDayKey` / `shiftDateKey` against the caller's own local
|
||||
* "today"), the same `foldNutrientDay` across sources (the largest day-total
|
||||
* source counts, manual and supplement rows add on top), and the same sex-aware
|
||||
* `resolveNutrientReference` — omit, never guess, when the profile has no
|
||||
* sex on file. No new analytics.
|
||||
*
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
labelIn,
|
||||
} from "@/lib/i18n/localised-label-index";
|
||||
import { DEFAULT_TIMEZONE } from "@/lib/tz/format";
|
||||
import type { NutrientTarget } from "@/lib/validations/nutrient-targets";
|
||||
|
||||
/** The i18n key the app already labels a nutrient with, in every bundle. */
|
||||
function nutrientLabelKey(code: NutrientCode): string {
|
||||
@@ -134,6 +135,7 @@ export interface NutrientsDailyResult {
|
||||
windowDays?: number;
|
||||
days?: NutrientDailyEntry[];
|
||||
reference?: ResolvedNutrientReference | null;
|
||||
personalTarget?: NutrientTarget | null;
|
||||
upperLimit?: NutrientUpperLimit | null;
|
||||
}
|
||||
|
||||
@@ -141,7 +143,7 @@ export interface NutrientsDailyResult {
|
||||
* Resolve a free-text nutrient name to a catalog code, or `null`. Forgiving
|
||||
* for an NL assistant (the exact code, or the display name in ANY shipped
|
||||
* language, with case, accents and separators folded) but closed to the
|
||||
* 26-code catalog — an unresolved name reports
|
||||
* nutrient catalog — an unresolved name reports
|
||||
* `{ present: false, reason: "unknown_nutrient" }` rather than inventing a
|
||||
* series.
|
||||
*
|
||||
@@ -201,12 +203,11 @@ async function readDaily(
|
||||
days: number,
|
||||
): Promise<NutrientsDailyResult> {
|
||||
const definition = NUTRIENT_CATALOG[nutrient];
|
||||
const { days: daySeries, rowCount } = await readNutrientDaily(
|
||||
userId,
|
||||
userTz,
|
||||
nutrient,
|
||||
days,
|
||||
);
|
||||
const {
|
||||
days: daySeries,
|
||||
rowCount,
|
||||
personalTarget,
|
||||
} = await readNutrientDaily(userId, userTz, nutrient, days);
|
||||
const reference = resolveNutrientReference(nutrient, sex);
|
||||
|
||||
return {
|
||||
@@ -218,6 +219,7 @@ async function readDaily(
|
||||
windowDays: days,
|
||||
days: daySeries,
|
||||
reference,
|
||||
personalTarget,
|
||||
upperLimit: definition.upperLimit,
|
||||
};
|
||||
}
|
||||
@@ -237,7 +239,7 @@ function clampDays(
|
||||
* `get_nutrients` entry point. No `nutrient` → the presence overview
|
||||
* (latest day / latest total / days-with-data per logged code). A named
|
||||
* `nutrient` → that code's per-day summed series over a trailing window plus
|
||||
* its resolved EFSA reference. `{ present: false, reason: "module_disabled" }`
|
||||
* its resolved dietary reference and the person's own target. `{ present: false, reason: "module_disabled" }`
|
||||
* when the opt-in `nutrients` module is off — checked before any other read,
|
||||
* mirroring both backing routes.
|
||||
*/
|
||||
|
||||
@@ -627,7 +627,7 @@ export const MCP_RESOURCE_TEMPLATES: McpResourceTemplateDefinition[] = [
|
||||
uriTemplate: "healthlog://nutrient/{code}",
|
||||
title: "Nutrient intake",
|
||||
description:
|
||||
"One tracked nutrient's per-day summed intake series (e.g. healthlog://nutrient/water) over the default 30-day window, plus its EFSA dietary reference resolved against the user's own profile sex. Same read get_nutrients serves. Gated on the opt-in nutrients module. Returns { present: false } when the module is off or nothing is logged for that code.",
|
||||
"One tracked nutrient's per-day intake series (e.g. healthlog://nutrient/water, healthlog://nutrient/protein) over the default 30-day window, plus its dietary reference resolved against the user's own profile sex and the user's own target, if set. Same read get_nutrients serves. Gated on the opt-in nutrients module. Returns { present: false } when the module is off or nothing is logged for that code.",
|
||||
mimeType: "application/json",
|
||||
complete: { code: completeNutrient },
|
||||
async list(ctx) {
|
||||
|
||||
@@ -33,6 +33,7 @@ const getNutrientsOutput: z.ZodRawShape = {
|
||||
days: z.array(z.object({ day: z.string(), amount: z.number() })).optional(),
|
||||
reference: z
|
||||
.object({
|
||||
authority: z.enum(["EFSA", "IOM", "NIH ODS"]).optional(),
|
||||
kind: z.enum(["PRI", "AI", "safeLevel"]),
|
||||
direction: z.enum(["target", "upperGuidance"]),
|
||||
value: z.number(),
|
||||
@@ -40,13 +41,20 @@ const getNutrientsOutput: z.ZodRawShape = {
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
personalTarget: z
|
||||
.object({
|
||||
value: z.number(),
|
||||
direction: z.enum(["target", "limit"]),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
};
|
||||
|
||||
export const getNutrientsTool: McpToolDefinition = {
|
||||
name: "get_nutrients",
|
||||
title: "Get nutrient intake",
|
||||
description:
|
||||
"Fetch the user's synced micronutrient intake — water, caffeine, and the 24 tracked vitamins/minerals — as day totals summed across sources (e.g. an Apple Health sync AND a manual water entry on the same day). Omit `nutrient` for a presence overview across every logged code (latest logged day, latest day's total, days with data). Pass a catalog code, or the nutrient's display name in any language HealthLog ships (e.g. 'water', 'magnesium', 'vitamin_d', 'Magnésium', 'Żelazo'), for that nutrient's per-day series over a trailing window, plus its EFSA dietary reference resolved against the user's own profile sex — omitted, never guessed, when sex is not on file. Gated on the opt-in `nutrients` module. Returns { present: false, reason: \"module_disabled\" } when the module is off, or { present: false } when nothing matches.",
|
||||
"Fetch the user's nutrient intake — water, caffeine, the tracked vitamins and minerals (sodium and potassium included), dietary energy in kcal, the macronutrients (protein, carbohydrates, fat, sugar, fiber) in g, and alcohol in g of ethanol — as day totals across sources. Apple Health, Health Connect and a food-tracker bridge each report the whole day, so only the largest of them counts; a manual water entry and taken supplements add on top. Omit `nutrient` for a presence overview across every logged code (latest logged day, latest day's total, days with data). Pass a catalog code, or the nutrient's display name in any language HealthLog ships (e.g. 'water', 'magnesium', 'vitamin_d', 'Magnésium', 'Żelazo'), for that nutrient's per-day series over a trailing window, plus its dietary reference (with the authority that set it: EFSA, or IOM for protein and carbohydrates) resolved against the user's own profile sex — omitted, never guessed, when sex is not on file or the nutrient has none — and the target the user set for it, if any. Gated on the opt-in `nutrients` module. Returns { present: false, reason: \"module_disabled\" } when the module is off, or { present: false } when nothing matches.",
|
||||
inputShape: {
|
||||
nutrient: z
|
||||
.string()
|
||||
|
||||
@@ -218,7 +218,8 @@ async function addNutrientCandidates(
|
||||
origin: string,
|
||||
legacy: AddCandidate,
|
||||
): Promise<void> {
|
||||
// Nutrients (water/caffeine/24 micronutrients) presence
|
||||
// Nutrients (water, caffeine, vitamins and minerals, energy and macros,
|
||||
// alcohol) presence
|
||||
// probe, gated on the opt-in `nutrients` module exactly like the
|
||||
// ingest/read routes: an account that never turned the module on gets
|
||||
// no rows here, mirroring the module's own dark-by-default posture.
|
||||
|
||||
@@ -1235,12 +1235,11 @@ export const HK_QUANTITY_TYPE_DEFERRED = new Set<string>([
|
||||
// BREATHING_DISTURBANCES, and `HKCategoryTypeIdentifierSleepApneaEvent`
|
||||
// (the fired screening event) → BREATHING_DISTURBANCE_EVENT.
|
||||
// Nutrition — the Measurement path stays PERMANENTLY closed to
|
||||
// Dietary types. Energy / macros (and sodium): indefinite hold, the
|
||||
// anti-goal against diet-app territory stands. Water + caffeine (and
|
||||
// the 24 micro Dietary vitamin/mineral identifiers, which were never
|
||||
// Dietary types. Water, caffeine, energy, the macros, sodium (and the
|
||||
// other micro Dietary vitamin/mineral identifiers, which were never
|
||||
// listed here because no sample ever mapped) ride the dedicated
|
||||
// day-total endpoint `POST /api/nutrients/batch` (closed catalog in
|
||||
// `src/lib/nutrients/catalog.ts`) — never Measurements, so the two
|
||||
// `src/lib/nutrients/catalog.ts`) — never Measurements, so the
|
||||
// entries below stay deferred and a stray sample-grain post keeps
|
||||
// skipping as unmappable.
|
||||
"HKQuantityTypeIdentifierDietaryWater",
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
NUTRIENT_CATALOG,
|
||||
catalogEntryFor,
|
||||
isCanonicalNutrientUnit,
|
||||
isNutrientCode,
|
||||
isIngredientNutrientCode,
|
||||
toCanonicalNutrientAmount,
|
||||
type NutrientCode,
|
||||
} from "@/lib/nutrients/catalog";
|
||||
@@ -56,7 +56,10 @@ export function canonicalComposition(
|
||||
): CompositionCheck {
|
||||
const ingredients: CanonicalIngredient[] = [];
|
||||
for (const [index, input] of inputs.entries()) {
|
||||
if (!isNutrientCode(input.nutrient)) {
|
||||
// Water, energy, the macros and alcohol are catalogue codes but no
|
||||
// ingredient a capsule declares: refused as unknown, like a code the
|
||||
// catalogue never heard of.
|
||||
if (!isIngredientNutrientCode(input.nutrient)) {
|
||||
return { ok: false, kind: "unknownNutrient", index };
|
||||
}
|
||||
const code = input.nutrient;
|
||||
|
||||
@@ -53,6 +53,7 @@ import type { OcrVisionPick } from "@/lib/labs/ocr-run";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import {
|
||||
NUTRIENT_DEFINITIONS,
|
||||
isIngredientNutrientCode,
|
||||
isNutrientCode,
|
||||
parseNutrientInputUnit,
|
||||
toCanonicalNutrientAmount,
|
||||
@@ -100,7 +101,7 @@ export async function requireSupplementLabelProvider(
|
||||
/** The code list the prompt offers, one `code: English name` per line. */
|
||||
function codeList(): string {
|
||||
return NUTRIENT_DEFINITIONS.filter(
|
||||
(def) => def.code !== "water" && def.code !== "caffeine",
|
||||
(def) => def.ingredient && def.group !== "caffeine",
|
||||
)
|
||||
.map((def) => `- ${def.code}: ${labelIn("en", def.labelKey) ?? def.code}`)
|
||||
.join("\n");
|
||||
@@ -175,7 +176,7 @@ export function proposalFromLabel(
|
||||
const unit = line.unit ? parseNutrientInputUnit(line.unit) : null;
|
||||
const amount = line.amount ?? null;
|
||||
const usable =
|
||||
isNutrientCode(code) &&
|
||||
isIngredientNutrientCode(code) &&
|
||||
!seen.has(code) &&
|
||||
unit !== null &&
|
||||
amount !== null &&
|
||||
|
||||
@@ -17,19 +17,24 @@ import {
|
||||
NUTRIENT_DEFINITIONS,
|
||||
SYNCABLE_NUTRIENT_CODES,
|
||||
isAboveUpperLimit,
|
||||
isNutrientCode,
|
||||
isIngredientNutrientCode,
|
||||
isSyncableNutrientCode,
|
||||
nutrientCodesInGroup,
|
||||
resolveNutrientReference,
|
||||
toCanonicalNutrientAmount,
|
||||
} from "../catalog";
|
||||
|
||||
/** The codes HealthKit sends, which carry an HK identifier and a reference. */
|
||||
/** The codes the batch accepts. */
|
||||
const SYNCABLE = NUTRIENT_DEFINITIONS.filter((d) => d.syncable);
|
||||
/** The codes HealthKit carries. */
|
||||
const HEALTHKIT = NUTRIENT_DEFINITIONS.filter((d) => d.hkIdentifier !== null);
|
||||
/** Codes that deliberately carry no reference, each for a stated reason. */
|
||||
const REFERENCE_LESS = ["energy", "fat", "sugar", "alcohol"];
|
||||
|
||||
describe("nutrient catalog", () => {
|
||||
it("carries exactly the 26 syncable codes plus the two supplement-only ones (no sodium, no potassium, no macros)", () => {
|
||||
expect(SYNCABLE_NUTRIENT_CODES).toHaveLength(26);
|
||||
expect(NUTRIENT_CODES).toHaveLength(28);
|
||||
it("carries the 35 syncable codes plus the two supplement-only ones", () => {
|
||||
expect(SYNCABLE_NUTRIENT_CODES).toHaveLength(35);
|
||||
expect(NUTRIENT_CODES).toHaveLength(37);
|
||||
expect(NUTRIENT_CODES.filter((c) => !isSyncableNutrientCode(c))).toEqual([
|
||||
"dha",
|
||||
"epa",
|
||||
@@ -37,8 +42,7 @@ describe("nutrient catalog", () => {
|
||||
expect(Object.keys(NUTRIENT_CATALOG).sort()).toEqual(
|
||||
[...NUTRIENT_CODES].sort(),
|
||||
);
|
||||
// The maintainer exclusions stay excluded.
|
||||
for (const banned of [
|
||||
for (const code of [
|
||||
"sodium",
|
||||
"potassium",
|
||||
"energy",
|
||||
@@ -47,17 +51,59 @@ describe("nutrient catalog", () => {
|
||||
"fat",
|
||||
"sugar",
|
||||
"fiber",
|
||||
"alcohol",
|
||||
]) {
|
||||
expect(isNutrientCode(banned), `banned code present: ${banned}`).toBe(
|
||||
false,
|
||||
expect(isSyncableNutrientCode(code), code).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("every syncable code but alcohol carries a HealthKit identifier", () => {
|
||||
expect(HEALTHKIT).toHaveLength(34);
|
||||
expect(
|
||||
SYNCABLE.filter((d) => d.hkIdentifier === null).map((d) => d.code),
|
||||
).toEqual(["alcohol"]);
|
||||
expect(NUTRIENT_CATALOG.energy.hkIdentifier).toBe(
|
||||
"HKQuantityTypeIdentifierDietaryEnergyConsumed",
|
||||
);
|
||||
expect(NUTRIENT_CATALOG.fat.hkIdentifier).toBe(
|
||||
"HKQuantityTypeIdentifierDietaryFatTotal",
|
||||
);
|
||||
});
|
||||
|
||||
it("groups every code, and only vitamins, minerals, caffeine and omega-3 are ingredients", () => {
|
||||
const groups = (g: string) =>
|
||||
NUTRIENT_DEFINITIONS.filter((d) => d.group === g).map((d) => d.code);
|
||||
expect(groups("vitamin")).toHaveLength(13);
|
||||
expect(groups("mineral")).toHaveLength(13);
|
||||
expect(groups("energy_macro")).toEqual([
|
||||
"energy",
|
||||
"protein",
|
||||
"carbohydrates",
|
||||
"fat",
|
||||
"sugar",
|
||||
"fiber",
|
||||
]);
|
||||
expect(groups("alcohol")).toEqual(["alcohol"]);
|
||||
expect(groups("omega3")).toEqual(["dha", "epa"]);
|
||||
for (const def of NUTRIENT_DEFINITIONS) {
|
||||
expect(def.ingredient, def.code).toBe(
|
||||
["vitamin", "mineral", "caffeine", "omega3"].includes(def.group),
|
||||
);
|
||||
}
|
||||
expect(isIngredientNutrientCode("magnesium")).toBe(true);
|
||||
expect(isIngredientNutrientCode("energy")).toBe(false);
|
||||
expect(isIngredientNutrientCode("alcohol")).toBe(false);
|
||||
expect(isIngredientNutrientCode("water")).toBe(false);
|
||||
expect(isIngredientNutrientCode("nope")).toBe(false);
|
||||
expect(nutrientCodesInGroup("energy_macro")).toEqual(
|
||||
groups("energy_macro"),
|
||||
);
|
||||
});
|
||||
|
||||
it("codes and HealthKit identifiers are unique, and every HK id is a Dietary quantity type", () => {
|
||||
const codes = new Set<string>();
|
||||
const hkIds = new Set<string>();
|
||||
for (const def of SYNCABLE) {
|
||||
for (const def of HEALTHKIT) {
|
||||
expect(def.hkIdentifier).not.toBeNull();
|
||||
const hk = def.hkIdentifier!;
|
||||
expect(codes.has(def.code)).toBe(false);
|
||||
@@ -68,10 +114,18 @@ describe("nutrient catalog", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("every unit is canonical (mg | ug | ml) and water is the only ml type", () => {
|
||||
it("every unit is canonical (mg | ug | ml | g | kcal) and water is the only ml type", () => {
|
||||
for (const def of NUTRIENT_DEFINITIONS) {
|
||||
expect(["mg", "ug", "ml"]).toContain(def.unit);
|
||||
expect(["mg", "ug", "ml", "g", "kcal"]).toContain(def.unit);
|
||||
}
|
||||
expect(
|
||||
NUTRIENT_DEFINITIONS.filter((d) => d.unit === "kcal").map((d) => d.code),
|
||||
).toEqual(["energy"]);
|
||||
expect(
|
||||
NUTRIENT_DEFINITIONS.filter((d) => d.unit === "g").map((d) => d.code),
|
||||
).toEqual(["protein", "carbohydrates", "fat", "sugar", "fiber", "alcohol"]);
|
||||
expect(NUTRIENT_CATALOG.sodium.unit).toBe("mg");
|
||||
expect(NUTRIENT_CATALOG.potassium.unit).toBe("mg");
|
||||
const mlCodes = NUTRIENT_DEFINITIONS.filter((d) => d.unit === "ml").map(
|
||||
(d) => d.code,
|
||||
);
|
||||
@@ -115,9 +169,14 @@ describe("nutrient catalog", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("every syncable code has a reference entry carrying kind, direction, a citation, and a resolvable value", () => {
|
||||
it("every syncable code but the documented reference-less ones has a reference entry carrying authority, kind, direction, a citation, and a resolvable value", () => {
|
||||
expect(
|
||||
SYNCABLE.filter((d) => d.reference === null).map((d) => d.code),
|
||||
).toEqual(REFERENCE_LESS);
|
||||
for (const def of SYNCABLE) {
|
||||
if (REFERENCE_LESS.includes(def.code)) continue;
|
||||
const ref = def.reference!;
|
||||
expect(["EFSA", "IOM", "NIH ODS"]).toContain(ref.authority);
|
||||
expect(ref, `missing reference: ${def.code}`).toBeTruthy();
|
||||
expect(["PRI", "AI", "safeLevel"]).toContain(ref.kind);
|
||||
expect(["target", "upperGuidance"]).toContain(ref.direction);
|
||||
@@ -135,25 +194,40 @@ describe("nutrient catalog", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("caffeine is the one upperGuidance reference; everything else is a target", () => {
|
||||
it("caffeine and sodium are the upperGuidance references; everything else is a target", () => {
|
||||
for (const def of SYNCABLE) {
|
||||
expect(def.reference!.direction).toBe(
|
||||
def.code === "caffeine" ? "upperGuidance" : "target",
|
||||
if (!def.reference) continue;
|
||||
expect(def.reference.direction, def.code).toBe(
|
||||
def.code === "caffeine" || def.code === "sodium"
|
||||
? "upperGuidance"
|
||||
: "target",
|
||||
);
|
||||
}
|
||||
expect(NUTRIENT_CATALOG.sodium.reference!.kind).toBe("safeLevel");
|
||||
expect(NUTRIENT_CATALOG.sodium.reference!.adult).toBe(2000);
|
||||
expect(NUTRIENT_CATALOG.caffeine.reference!.kind).toBe("safeLevel");
|
||||
expect(NUTRIENT_CATALOG.caffeine.reference!.adult).toBe(400);
|
||||
});
|
||||
|
||||
it("every citation names EFSA, except the documented chromium exception (EFSA sets no DRV)", () => {
|
||||
it("every citation names its authority; the non-EFSA ones are exactly chromium, protein and carbohydrates, and each says why EFSA does not apply", () => {
|
||||
const nonEfsa: string[] = [];
|
||||
for (const def of SYNCABLE) {
|
||||
if (def.code === "chromium") {
|
||||
expect(def.reference!.source).toContain("NIH");
|
||||
expect(def.reference!.source).toContain("EFSA");
|
||||
continue;
|
||||
const ref = def.reference;
|
||||
if (!ref) continue;
|
||||
expect(ref.source, `citation: ${def.code}`).toContain(ref.authority);
|
||||
if (ref.authority !== "EFSA") {
|
||||
nonEfsa.push(def.code);
|
||||
// The citation also names EFSA, saying why its value is not used.
|
||||
expect(ref.source, def.code).toContain("EFSA");
|
||||
}
|
||||
expect(def.reference!.source, `citation: ${def.code}`).toContain("EFSA");
|
||||
}
|
||||
expect(nonEfsa).toEqual(["chromium", "protein", "carbohydrates"]);
|
||||
expect(NUTRIENT_CATALOG.chromium.reference!.authority).toBe("NIH ODS");
|
||||
expect(NUTRIENT_CATALOG.protein.reference!.male).toBe(56);
|
||||
expect(NUTRIENT_CATALOG.protein.reference!.female).toBe(46);
|
||||
expect(NUTRIENT_CATALOG.carbohydrates.reference!.adult).toBe(130);
|
||||
expect(NUTRIENT_CATALOG.fiber.reference!.adult).toBe(25);
|
||||
expect(NUTRIENT_CATALOG.potassium.reference!.adult).toBe(3500);
|
||||
});
|
||||
|
||||
it("iron carries the EFSA sex split (11 male / 16 female)", () => {
|
||||
@@ -204,6 +278,7 @@ describe("resolveNutrientReference (v1.29)", () => {
|
||||
it("resolves caffeine's upperGuidance ceiling regardless of sex", () => {
|
||||
const ref = resolveNutrientReference("caffeine", null);
|
||||
expect(ref).toEqual({
|
||||
authority: "EFSA",
|
||||
kind: "safeLevel",
|
||||
direction: "upperGuidance",
|
||||
value: 400,
|
||||
@@ -216,8 +291,12 @@ describe("resolveNutrientReference (v1.29)", () => {
|
||||
expect(resolveNutrientReference("epa", "FEMALE")).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves every syncable code to a non-null reference for at least one sex", () => {
|
||||
it("resolves every syncable code with a reference to a non-null value for at least one sex", () => {
|
||||
for (const code of SYNCABLE_NUTRIENT_CODES) {
|
||||
if (REFERENCE_LESS.includes(code)) {
|
||||
expect(resolveNutrientReference(code, "MALE")).toBeNull();
|
||||
continue;
|
||||
}
|
||||
const resolved =
|
||||
resolveNutrientReference(code, "MALE") ??
|
||||
resolveNutrientReference(code, "FEMALE");
|
||||
@@ -254,6 +333,15 @@ describe("input units and the converter (v1.43)", () => {
|
||||
expect(toCanonicalNutrientAmount("water", 1.5, "l")).toBe(1500);
|
||||
});
|
||||
|
||||
it("converts macros from mg and keeps energy in kcal only", () => {
|
||||
expect(toCanonicalNutrientAmount("protein", 500, "mg")).toBe(0.5);
|
||||
expect(toCanonicalNutrientAmount("protein", 30, "g")).toBe(30);
|
||||
expect(toCanonicalNutrientAmount("energy", 2100, "kcal")).toBe(2100);
|
||||
// No kJ: 4.184× off and still plausible, so refused.
|
||||
expect(toCanonicalNutrientAmount("energy", 8800, "kJ")).toBeNull();
|
||||
expect(toCanonicalNutrientAmount("energy", 2, "g")).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses a unit the code does not list rather than guessing", () => {
|
||||
// Vitamin E has no IU: its factor depends on the natural or synthetic form.
|
||||
expect(toCanonicalNutrientAmount("vitamin_e", 400, "IU")).toBeNull();
|
||||
@@ -307,8 +395,8 @@ describe("upper intake levels (v1.43)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the batch contract stays the syncable codes (v1.43)", () => {
|
||||
it("refuses dha and epa in the HealthKit batch and accepts a syncable code", async () => {
|
||||
describe("the batch contract is the syncable codes", () => {
|
||||
it("refuses dha and epa in the batch and accepts a syncable code, energy and alcohol included", async () => {
|
||||
const { nutrientBatchSchema } = await import("@/lib/validations/nutrients");
|
||||
const entry = (nutrient: string) => ({
|
||||
entries: [{ day: "2026-07-10", nutrient, unit: "mg", amount: 100 }],
|
||||
@@ -318,5 +406,7 @@ describe("the batch contract stays the syncable codes (v1.43)", () => {
|
||||
expect(nutrientBatchSchema.safeParse(entry("magnesium")).success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(nutrientBatchSchema.safeParse(entry("energy")).success).toBe(true);
|
||||
expect(nutrientBatchSchema.safeParse(entry("alcohol")).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* How one day's nutrient rows add up: the largest day-total source counts,
|
||||
* additive sources add on top, and the split always sums to the total.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { foldNutrientDay, foldNutrientDays } from "../day-total";
|
||||
import { DAY_TOTAL_SOURCES } from "../sources";
|
||||
|
||||
describe("foldNutrientDay", () => {
|
||||
it("counts only the larger of a tracker total and the Apple Health total", () => {
|
||||
const fold = foldNutrientDay([
|
||||
{ source: "APPLE_HEALTH", amount: 2000 },
|
||||
{ source: "EXTERNAL", amount: 2100 },
|
||||
]);
|
||||
expect(fold).toEqual({ total: 2100, bySource: { EXTERNAL: 2100 } });
|
||||
});
|
||||
|
||||
it("no longer adds Apple Health and Health Connect on top of each other", () => {
|
||||
const fold = foldNutrientDay([
|
||||
{ source: "APPLE_HEALTH", amount: 1800 },
|
||||
{ source: "HEALTH_CONNECT", amount: 1700 },
|
||||
]);
|
||||
expect(fold).toEqual({ total: 1800, bySource: { APPLE_HEALTH: 1800 } });
|
||||
});
|
||||
|
||||
it("adds manual and supplement rows on top of the counted day total", () => {
|
||||
const fold = foldNutrientDay([
|
||||
{ source: "APPLE_HEALTH", amount: 1500 },
|
||||
{ source: "EXTERNAL", amount: 1200 },
|
||||
{ source: "MANUAL", amount: 250 },
|
||||
{ source: "SUPPLEMENT", amount: 100 },
|
||||
]);
|
||||
expect(fold).toEqual({
|
||||
total: 1850,
|
||||
bySource: { APPLE_HEALTH: 1500, MANUAL: 250, SUPPLEMENT: 100 },
|
||||
});
|
||||
});
|
||||
|
||||
it("adds a source outside the closed set to the total without naming it", () => {
|
||||
const fold = foldNutrientDay([
|
||||
{ source: "APPLE_HEALTH", amount: 10 },
|
||||
{ source: "SOMETHING_NEW", amount: 5 },
|
||||
]);
|
||||
expect(fold).toEqual({ total: 15, bySource: { APPLE_HEALTH: 10 } });
|
||||
});
|
||||
|
||||
it("breaks a tie by source order, whatever order the rows arrive in", () => {
|
||||
const rows = DAY_TOTAL_SOURCES.map((source) => ({ source, amount: 70 }));
|
||||
const forward = foldNutrientDay(rows);
|
||||
const backward = foldNutrientDay([...rows].reverse());
|
||||
expect(forward).toEqual({ total: 70, bySource: { EXTERNAL: 70 } });
|
||||
expect(backward).toEqual(forward);
|
||||
});
|
||||
|
||||
it("returns zero and an empty split for no rows", () => {
|
||||
expect(foldNutrientDay([])).toEqual({ total: 0, bySource: {} });
|
||||
});
|
||||
|
||||
it("keeps the split summing to the total for every mix of known sources", () => {
|
||||
const sources = [
|
||||
"APPLE_HEALTH",
|
||||
"HEALTH_CONNECT",
|
||||
"EXTERNAL",
|
||||
"MANUAL",
|
||||
"SUPPLEMENT",
|
||||
];
|
||||
for (let mask = 1; mask < 1 << sources.length; mask += 1) {
|
||||
const rows = sources
|
||||
.filter((_, i) => mask & (1 << i))
|
||||
.map((source, i) => ({ source, amount: 10 * (i + 1) + mask }));
|
||||
const fold = foldNutrientDay(rows);
|
||||
const sum = Object.values(fold.bySource).reduce((a, b) => a + b, 0);
|
||||
expect(sum, `mask ${mask}`).toBe(fold.total);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("foldNutrientDays", () => {
|
||||
it("folds each key on its own", () => {
|
||||
const folds = foldNutrientDays(
|
||||
[
|
||||
{ day: "2026-11-01", source: "APPLE_HEALTH", amount: 1 },
|
||||
{ day: "2026-11-01", source: "EXTERNAL", amount: 3 },
|
||||
{ day: "2026-11-02", source: "MANUAL", amount: 2 },
|
||||
],
|
||||
(row) => row.day,
|
||||
);
|
||||
expect(folds.get("2026-11-01")?.total).toBe(3);
|
||||
expect(folds.get("2026-11-02")?.total).toBe(2);
|
||||
});
|
||||
});
|
||||
+274
-69
@@ -1,49 +1,57 @@
|
||||
/**
|
||||
* Nutrient catalog — the closed code set for the micronutrient-intake
|
||||
* sync (v1.28).
|
||||
* Nutrient catalog — the closed code set for nutrient intake.
|
||||
*
|
||||
* 26 syncable codes: the 24 HealthKit `Dietary*` vitamin/mineral quantity
|
||||
* types plus DietaryWater and DietaryCaffeine. v1.43 adds two codes no
|
||||
* HealthKit type carries (`dha`, `epa`), which only a supplement's
|
||||
* composition produces; they appear in responses and never in the batch. Energy, carbohydrates,
|
||||
* protein, fat, sugar, fiber AND sodium/potassium are deliberately NOT
|
||||
* here — the anti-goal against diet-app territory stands, and
|
||||
* sodium/potassium are food-composition signals, not "substances
|
||||
* taken" (maintainer decision, out until explicit user demand).
|
||||
* 35 syncable codes: the HealthKit `Dietary*` vitamin and mineral quantity
|
||||
* types (sodium and potassium among them), water and caffeine, dietary energy
|
||||
* and the macronutrients (protein, carbohydrates, fat, sugar, fiber), and
|
||||
* alcohol. Energy and the macros came in by maintainer decision on #1402, once
|
||||
* users asked to bring the day totals a food tracker already computes. "Syncable"
|
||||
* means the batch accepts the code; whether HealthKit carries it is a separate
|
||||
* question, answered by `hkIdentifier !== null`. Alcohol is the one syncable
|
||||
* code HealthKit has no dietary type for: only a bridge token posts it. Two
|
||||
* further codes (`dha`, `epa`) come only from a supplement's composition; they
|
||||
* appear in responses and never in the batch.
|
||||
*
|
||||
* This catalog is the single source of truth for:
|
||||
* - the closed `nutrient` code enum on the wire and in storage;
|
||||
* - the canonical storage unit per code, which is ALSO the pinned
|
||||
* HealthKit query unit for iOS (mass types in mg or µg as listed,
|
||||
* water in mL — never IU). The batch route rejects any entry whose
|
||||
* echoed `unit` differs, because a silent µg/mg confusion is a
|
||||
* 1000× corruption and the one-string echo is the cheapest guard;
|
||||
* HealthKit query unit for iOS (mass types in g, mg or µg as listed,
|
||||
* water in mL, energy in kcal — never IU, never kJ). The batch route
|
||||
* rejects any entry whose echoed `unit` differs, because a silent µg/mg
|
||||
* or kJ/kcal confusion corrupts the value and the one-string echo is the
|
||||
* cheapest guard;
|
||||
* - the generous per-day plausibility cap (ingest guard against
|
||||
* unit-confused or corrupted writers, NOT a health judgement —
|
||||
* values above high-dose supplement reality get skipped);
|
||||
* - the EFSA dietary reference values a later Coach block compares
|
||||
* against. Every reference names its EFSA value kind (PRI /
|
||||
* AI / safeLevel) and a direction: `target` for reference intakes,
|
||||
* `upperGuidance` for caffeine's safe-level ceiling. Sex-split
|
||||
* values resolve against the user profile at consumption time —
|
||||
* a profile without sex omits the reference, never guesses.
|
||||
* - the dietary reference values the insights surfaces and the Coach
|
||||
* compare against. Every reference names its authority, its value kind
|
||||
* (PRI / AI / safeLevel) and a direction: `target` for reference intakes,
|
||||
* `upperGuidance` for a do-not-exceed level (caffeine, sodium). Sex-split
|
||||
* values resolve against the user profile at consumption time — a profile
|
||||
* without sex omits the reference, never guesses;
|
||||
* - the group a code belongs to (vitamin, mineral, energy and macros, …),
|
||||
* which the surfaces read instead of listing codes by hand, and whether a
|
||||
* supplement's composition may name it.
|
||||
*
|
||||
* Reference values are the EFSA DRV Finder adult values (Dietary
|
||||
* Reference Values for the EU population); each entry cites its source
|
||||
* verbatim in `reference.source`. Where EFSA expresses a vitamin per
|
||||
* energy unit (thiamin, niacin), the entry carries the value at the
|
||||
* 10 MJ/day reference energy intake and says so in the citation.
|
||||
* Chromium is the one exception: EFSA concluded no DRV can be set, so
|
||||
* the entry cites the NIH ODS adequate intake instead — spelled out in
|
||||
* its source string.
|
||||
* Reference values are the EFSA DRV Finder adult values (Dietary Reference
|
||||
* Values for the EU population) wherever EFSA sets a value per day; each entry
|
||||
* cites its source verbatim in `reference.source`. Where EFSA expresses a
|
||||
* vitamin per energy unit (thiamin, niacin), the entry carries the value at the
|
||||
* 10 MJ/day reference energy intake and says so in the citation. Three codes
|
||||
* cite another authority, named in `reference.authority`: chromium (EFSA
|
||||
* concluded no DRV can be set; NIH ODS adequate intake), protein and
|
||||
* carbohydrates (EFSA states them per kilogram of body weight or as a share of
|
||||
* energy, never per day; the IOM recommended dietary allowance is the per-day
|
||||
* figure). Energy, fat, sugar and alcohol carry no reference: EFSA's energy
|
||||
* requirement depends on age, sex and activity, fat is a share of energy, and
|
||||
* sugar and alcohol have no intake to aim for.
|
||||
*/
|
||||
|
||||
import type { BinaryReferenceSex } from "@/lib/profile/sex";
|
||||
|
||||
/**
|
||||
* The codes HealthKit may send in the nutrient batch. `NUTRIENT_CODES` adds
|
||||
* the supplement-only codes below them; the batch validates against this
|
||||
* tuple, so its contract stays the 26 codes it always was.
|
||||
* The codes the nutrient batch accepts. `NUTRIENT_CODES` adds the
|
||||
* supplement-only codes below them; the batch validates against this tuple.
|
||||
*/
|
||||
export const SYNCABLE_NUTRIENT_CODES = [
|
||||
// 13 vitamins
|
||||
@@ -60,7 +68,7 @@ export const SYNCABLE_NUTRIENT_CODES = [
|
||||
"vitamin_d",
|
||||
"vitamin_e",
|
||||
"vitamin_k",
|
||||
// 11 minerals (sodium + potassium excluded by directive)
|
||||
// 13 minerals
|
||||
"calcium",
|
||||
"iron",
|
||||
"magnesium",
|
||||
@@ -72,9 +80,20 @@ export const SYNCABLE_NUTRIENT_CODES = [
|
||||
"chromium",
|
||||
"molybdenum",
|
||||
"iodine",
|
||||
"sodium",
|
||||
"potassium",
|
||||
// taken substances with correlation value
|
||||
"water",
|
||||
"caffeine",
|
||||
// energy and macronutrients (#1402)
|
||||
"energy",
|
||||
"protein",
|
||||
"carbohydrates",
|
||||
"fat",
|
||||
"sugar",
|
||||
"fiber",
|
||||
// no HealthKit dietary type; a bridge token posts it
|
||||
"alcohol",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
@@ -93,7 +112,7 @@ export type NutrientCode = (typeof NUTRIENT_CODES)[number];
|
||||
export type SyncableNutrientCode = (typeof SYNCABLE_NUTRIENT_CODES)[number];
|
||||
|
||||
/** Canonical storage units. `ug` is µg on the wire — ASCII on purpose. */
|
||||
export type NutrientUnit = "mg" | "ug" | "ml";
|
||||
export type NutrientUnit = "mg" | "ug" | "ml" | "g" | "kcal";
|
||||
|
||||
/**
|
||||
* v1.43 — every unit an amount may be ENTERED in. The canonical units plus
|
||||
@@ -101,7 +120,7 @@ export type NutrientUnit = "mg" | "ug" | "ml";
|
||||
* one fixed mass (vitamin D, preformed vitamin A); vitamin E has none, because
|
||||
* its IU depends on whether the form is natural or synthetic.
|
||||
*/
|
||||
export type NutrientInputUnitCode = NutrientUnit | "g" | "l" | "IU";
|
||||
export type NutrientInputUnitCode = NutrientUnit | "l" | "IU";
|
||||
|
||||
/** The unit vocabulary, spelled once. Every other file reads it from here. */
|
||||
export const NUTRIENT_UNIT = {
|
||||
@@ -111,6 +130,7 @@ export const NUTRIENT_UNIT = {
|
||||
g: "g",
|
||||
l: "l",
|
||||
IU: "IU",
|
||||
kcal: "kcal",
|
||||
} as const satisfies Record<NutrientInputUnitCode, NutrientInputUnitCode>;
|
||||
|
||||
export interface NutrientInputUnit {
|
||||
@@ -147,7 +167,15 @@ export type NutrientUpperLimitForm =
|
||||
"retinol" | "folic_acid" | "magnesium_salts" | "alpha_tocopherol";
|
||||
|
||||
export interface NutrientReference {
|
||||
/** EFSA value type, named in Coach prose later (Slice B). */
|
||||
/**
|
||||
* The body that set the value. EFSA wherever it sets a per-day value; the
|
||||
* catalogue header names each exception and why.
|
||||
*/
|
||||
authority: NutrientReferenceAuthority;
|
||||
/**
|
||||
* Value type in EFSA's vocabulary. An IOM recommended dietary allowance is
|
||||
* carried as `PRI`, the concept it matches.
|
||||
*/
|
||||
kind: "PRI" | "AI" | "safeLevel";
|
||||
/** `target` = reference intake; `upperGuidance` = do-not-exceed. */
|
||||
direction: "target" | "upperGuidance";
|
||||
@@ -160,6 +188,22 @@ export interface NutrientReference {
|
||||
source: string;
|
||||
}
|
||||
|
||||
export type NutrientReferenceAuthority = "EFSA" | "IOM" | "NIH ODS";
|
||||
|
||||
/**
|
||||
* Which family a code belongs to. The surfaces group by it (the micronutrient
|
||||
* card lists vitamins and minerals, the energy card the `energy_macro` codes)
|
||||
* instead of listing codes by hand.
|
||||
*/
|
||||
export type NutrientGroup =
|
||||
| "vitamin"
|
||||
| "mineral"
|
||||
| "water"
|
||||
| "caffeine"
|
||||
| "energy_macro"
|
||||
| "alcohol"
|
||||
| "omega3";
|
||||
|
||||
export interface NutrientDefinition {
|
||||
code: NutrientCode;
|
||||
/**
|
||||
@@ -167,8 +211,19 @@ export interface NutrientDefinition {
|
||||
* supplement-only code (`dha`, `epa`).
|
||||
*/
|
||||
hkIdentifier: string | null;
|
||||
/** Whether HealthKit may send this code in the nutrient batch. */
|
||||
/**
|
||||
* Whether the nutrient batch accepts this code. HealthKit carries it only
|
||||
* when `hkIdentifier` is set; alcohol is syncable through a token alone.
|
||||
*/
|
||||
syncable: boolean;
|
||||
/** The family the code belongs to. */
|
||||
group: NutrientGroup;
|
||||
/**
|
||||
* Whether a supplement's composition may name this code. False for water,
|
||||
* energy and the macros, and alcohol: what a capsule contains is a substance
|
||||
* taken, not a meal.
|
||||
*/
|
||||
ingredient: boolean;
|
||||
/** Canonical storage unit AND the pinned HK query unit. */
|
||||
unit: NutrientUnit;
|
||||
/** i18n key for the display name (settings card + exports). */
|
||||
@@ -207,6 +262,13 @@ const METRIC_INPUT_UNITS: Readonly<
|
||||
{ unit: NUTRIENT_UNIT.ml, factorToCanonical: 1 },
|
||||
{ unit: NUTRIENT_UNIT.l, factorToCanonical: 1000 },
|
||||
],
|
||||
g: [
|
||||
{ unit: NUTRIENT_UNIT.g, factorToCanonical: 1 },
|
||||
{ unit: NUTRIENT_UNIT.mg, factorToCanonical: 0.001 },
|
||||
],
|
||||
// No kJ: a value typed in kilojoules and read as kilocalories is off by a
|
||||
// factor of 4.184 and still looks plausible, so energy is entered in one unit.
|
||||
kcal: [{ unit: NUTRIENT_UNIT.kcal, factorToCanonical: 1 }],
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -330,17 +392,27 @@ function inputUnitsFor(
|
||||
];
|
||||
}
|
||||
|
||||
/** Groups whose codes a supplement's composition may not name. */
|
||||
const NON_INGREDIENT_GROUPS: ReadonlySet<NutrientGroup> = new Set([
|
||||
"water",
|
||||
"energy_macro",
|
||||
"alcohol",
|
||||
]);
|
||||
|
||||
function def(
|
||||
code: NutrientCode,
|
||||
group: NutrientGroup,
|
||||
hkSuffix: string,
|
||||
unit: NutrientUnit,
|
||||
plausibleDailyMax: number,
|
||||
reference: NutrientReference,
|
||||
reference: NutrientReference | null,
|
||||
): NutrientDefinition {
|
||||
return {
|
||||
code,
|
||||
hkIdentifier: `HKQuantityTypeIdentifierDietary${hkSuffix}`,
|
||||
syncable: true,
|
||||
group,
|
||||
ingredient: !NON_INGREDIENT_GROUPS.has(group),
|
||||
unit,
|
||||
labelKey: `nutrients.names.${code}`,
|
||||
plausibleDailyMax,
|
||||
@@ -350,7 +422,32 @@ function def(
|
||||
};
|
||||
}
|
||||
|
||||
/** A code that only a supplement's composition produces (v1.43). */
|
||||
/**
|
||||
* A code the batch accepts that no HealthKit dietary type carries, so only a
|
||||
* bridge token posts it. It names no reference.
|
||||
*/
|
||||
function tokenOnly(
|
||||
code: NutrientCode,
|
||||
group: NutrientGroup,
|
||||
unit: NutrientUnit,
|
||||
plausibleDailyMax: number,
|
||||
): NutrientDefinition {
|
||||
return {
|
||||
code,
|
||||
hkIdentifier: null,
|
||||
syncable: true,
|
||||
group,
|
||||
ingredient: !NON_INGREDIENT_GROUPS.has(group),
|
||||
unit,
|
||||
labelKey: `nutrients.names.${code}`,
|
||||
plausibleDailyMax,
|
||||
reference: null,
|
||||
inputUnits: inputUnitsFor(code, unit),
|
||||
upperLimit: UPPER_LIMITS[code] ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** A code that only a supplement's composition produces. */
|
||||
function supplementOnly(
|
||||
code: NutrientCode,
|
||||
unit: NutrientUnit,
|
||||
@@ -360,6 +457,8 @@ function supplementOnly(
|
||||
code,
|
||||
hkIdentifier: null,
|
||||
syncable: false,
|
||||
group: "omega3",
|
||||
ingredient: true,
|
||||
unit,
|
||||
labelKey: `nutrients.names.${code}`,
|
||||
plausibleDailyMax,
|
||||
@@ -375,7 +474,8 @@ export const NUTRIENT_CATALOG: Readonly<
|
||||
Record<NutrientCode, NutrientDefinition>
|
||||
> = Object.freeze({
|
||||
// ── Vitamins ─────────────────────────────────────────────────────
|
||||
vitamin_a: def("vitamin_a", "VitaminA", "ug", 15000, {
|
||||
vitamin_a: def("vitamin_a", "vitamin", "VitaminA", "ug", 15000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 750,
|
||||
@@ -387,167 +487,255 @@ export const NUTRIENT_CATALOG: Readonly<
|
||||
// the ingest guard compares with `>`, so a 1000× error slipped through at
|
||||
// precisely this one analyte. 500 still clears any real supplement dose
|
||||
// (high-dose thiamin tops out around 300 mg) while catching that collision.
|
||||
thiamin: def("thiamin", "Thiamin", "mg", 500, {
|
||||
thiamin: def("thiamin", "vitamin", "Thiamin", "mg", 500, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 1.0,
|
||||
source: "EFSA DRV 2016 (PRI 0.1 mg/MJ ≈ 1.0 mg/d at 10 MJ/d)",
|
||||
}),
|
||||
riboflavin: def("riboflavin", "Riboflavin", "mg", 1000, {
|
||||
riboflavin: def("riboflavin", "vitamin", "Riboflavin", "mg", 1000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 1.6,
|
||||
source: "EFSA DRV 2017 (adults)",
|
||||
}),
|
||||
niacin: def("niacin", "Niacin", "mg", 3000, {
|
||||
niacin: def("niacin", "vitamin", "Niacin", "mg", 3000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 16,
|
||||
source: "EFSA DRV 2014 (PRI 1.6 mg NE/MJ ≈ 16 mg NE/d at 10 MJ/d)",
|
||||
}),
|
||||
pantothenic_acid: def("pantothenic_acid", "PantothenicAcid", "mg", 2000, {
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 5,
|
||||
source: "EFSA DRV 2014 (adults)",
|
||||
}),
|
||||
vitamin_b6: def("vitamin_b6", "VitaminB6", "mg", 1000, {
|
||||
pantothenic_acid: def(
|
||||
"pantothenic_acid",
|
||||
"vitamin",
|
||||
"PantothenicAcid",
|
||||
"mg",
|
||||
2000,
|
||||
{
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 5,
|
||||
source: "EFSA DRV 2014 (adults)",
|
||||
},
|
||||
),
|
||||
vitamin_b6: def("vitamin_b6", "vitamin", "VitaminB6", "mg", 1000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 1.7,
|
||||
female: 1.6,
|
||||
source: "EFSA DRV 2016 (adults)",
|
||||
}),
|
||||
biotin: def("biotin", "Biotin", "ug", 20000, {
|
||||
biotin: def("biotin", "vitamin", "Biotin", "ug", 20000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 40,
|
||||
source: "EFSA DRV 2014 (adults)",
|
||||
}),
|
||||
folate: def("folate", "Folate", "ug", 5000, {
|
||||
folate: def("folate", "vitamin", "Folate", "ug", 5000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 330,
|
||||
source: "EFSA DRV 2014 (dietary folate equivalents, adults)",
|
||||
}),
|
||||
vitamin_b12: def("vitamin_b12", "VitaminB12", "ug", 5000, {
|
||||
vitamin_b12: def("vitamin_b12", "vitamin", "VitaminB12", "ug", 5000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 4,
|
||||
source: "EFSA DRV 2015 (cobalamin, adults)",
|
||||
}),
|
||||
vitamin_c: def("vitamin_c", "VitaminC", "mg", 10000, {
|
||||
vitamin_c: def("vitamin_c", "vitamin", "VitaminC", "mg", 10000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 110,
|
||||
female: 95,
|
||||
source: "EFSA DRV 2013 (adults)",
|
||||
}),
|
||||
vitamin_d: def("vitamin_d", "VitaminD", "ug", 1000, {
|
||||
vitamin_d: def("vitamin_d", "vitamin", "VitaminD", "ug", 1000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 15,
|
||||
source: "EFSA DRV 2016 (adults, assuming minimal cutaneous synthesis)",
|
||||
}),
|
||||
vitamin_e: def("vitamin_e", "VitaminE", "mg", 2000, {
|
||||
vitamin_e: def("vitamin_e", "vitamin", "VitaminE", "mg", 2000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
male: 13,
|
||||
female: 11,
|
||||
source: "EFSA DRV 2015 (alpha-tocopherol, adults)",
|
||||
}),
|
||||
vitamin_k: def("vitamin_k", "VitaminK", "ug", 10000, {
|
||||
vitamin_k: def("vitamin_k", "vitamin", "VitaminK", "ug", 10000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 70,
|
||||
source: "EFSA DRV 2017 (phylloquinone, adults)",
|
||||
}),
|
||||
// ── Minerals ─────────────────────────────────────────────────────
|
||||
calcium: def("calcium", "Calcium", "mg", 5000, {
|
||||
calcium: def("calcium", "mineral", "Calcium", "mg", 5000, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 950,
|
||||
source: "EFSA DRV 2015 (adults ≥ 25 y)",
|
||||
}),
|
||||
iron: def("iron", "Iron", "mg", 500, {
|
||||
iron: def("iron", "mineral", "Iron", "mg", 500, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 11,
|
||||
female: 16,
|
||||
source: "EFSA DRV 2015 (adults; 16 mg premenopausal women)",
|
||||
}),
|
||||
magnesium: def("magnesium", "Magnesium", "mg", 2000, {
|
||||
magnesium: def("magnesium", "mineral", "Magnesium", "mg", 2000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
male: 350,
|
||||
female: 300,
|
||||
source: "EFSA DRV 2015 (adults)",
|
||||
}),
|
||||
phosphorus: def("phosphorus", "Phosphorus", "mg", 5000, {
|
||||
phosphorus: def("phosphorus", "mineral", "Phosphorus", "mg", 5000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 550,
|
||||
source: "EFSA DRV 2015 (adults)",
|
||||
}),
|
||||
zinc: def("zinc", "Zinc", "mg", 200, {
|
||||
zinc: def("zinc", "mineral", "Zinc", "mg", 200, {
|
||||
authority: "EFSA",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 9.4,
|
||||
female: 7.5,
|
||||
source: "EFSA DRV 2014 (adults, at 300 mg/d phytate intake)",
|
||||
}),
|
||||
copper: def("copper", "Copper", "mg", 20, {
|
||||
copper: def("copper", "mineral", "Copper", "mg", 20, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
male: 1.6,
|
||||
female: 1.3,
|
||||
source: "EFSA DRV 2015 (adults)",
|
||||
}),
|
||||
manganese: def("manganese", "Manganese", "mg", 50, {
|
||||
manganese: def("manganese", "mineral", "Manganese", "mg", 50, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 3,
|
||||
source: "EFSA DRV 2013 (adults)",
|
||||
}),
|
||||
selenium: def("selenium", "Selenium", "ug", 1000, {
|
||||
selenium: def("selenium", "mineral", "Selenium", "ug", 1000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 70,
|
||||
source: "EFSA DRV 2014 (adults)",
|
||||
}),
|
||||
chromium: def("chromium", "Chromium", "ug", 2000, {
|
||||
chromium: def("chromium", "mineral", "Chromium", "ug", 2000, {
|
||||
authority: "NIH ODS",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
male: 35,
|
||||
female: 25,
|
||||
source: "NIH ODS 2018 (adults 19–50 y; EFSA 2014 sets no DRV for chromium)",
|
||||
}),
|
||||
molybdenum: def("molybdenum", "Molybdenum", "ug", 2000, {
|
||||
molybdenum: def("molybdenum", "mineral", "Molybdenum", "ug", 2000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 65,
|
||||
source: "EFSA DRV 2013 (adults)",
|
||||
}),
|
||||
iodine: def("iodine", "Iodine", "ug", 2000, {
|
||||
iodine: def("iodine", "mineral", "Iodine", "ug", 2000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 150,
|
||||
source: "EFSA DRV 2014 (adults)",
|
||||
}),
|
||||
sodium: def("sodium", "mineral", "Sodium", "mg", 50000, {
|
||||
authority: "EFSA",
|
||||
kind: "safeLevel",
|
||||
direction: "upperGuidance",
|
||||
adult: 2000,
|
||||
source: "EFSA DRV 2019 (safe and adequate intake, adults)",
|
||||
}),
|
||||
potassium: def("potassium", "mineral", "Potassium", "mg", 30000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 3500,
|
||||
source: "EFSA DRV 2016 (adults)",
|
||||
}),
|
||||
// ── Taken substances with correlation value ──────────────────────
|
||||
water: def("water", "Water", "ml", 20000, {
|
||||
water: def("water", "water", "Water", "ml", 20000, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
male: 2500,
|
||||
female: 2000,
|
||||
source: "EFSA DRV 2010 (total water incl. food moisture, adults)",
|
||||
}),
|
||||
caffeine: def("caffeine", "Caffeine", "mg", 2000, {
|
||||
caffeine: def("caffeine", "caffeine", "Caffeine", "mg", 2000, {
|
||||
authority: "EFSA",
|
||||
kind: "safeLevel",
|
||||
direction: "upperGuidance",
|
||||
adult: 400,
|
||||
source: "EFSA 2015 scientific opinion on the safety of caffeine (adults)",
|
||||
}),
|
||||
// ── Energy and macronutrients (#1402) ────────────────────────────
|
||||
// EFSA's average energy requirement depends on age, sex and activity level
|
||||
// (EFSA 2013), so energy carries no single reference.
|
||||
energy: def("energy", "energy_macro", "EnergyConsumed", "kcal", 20000, null),
|
||||
protein: def("protein", "energy_macro", "Protein", "g", 1000, {
|
||||
authority: "IOM",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
male: 56,
|
||||
female: 46,
|
||||
source:
|
||||
"IOM 2005 DRI for macronutrients (RDA 0.8 g/kg/d, 56 g/d men, 46 g/d women; EFSA 2012 sets a PRI of 0.83 g/kg/d and no g/d value)",
|
||||
}),
|
||||
carbohydrates: def(
|
||||
"carbohydrates",
|
||||
"energy_macro",
|
||||
"Carbohydrates",
|
||||
"g",
|
||||
2000,
|
||||
{
|
||||
authority: "IOM",
|
||||
kind: "PRI",
|
||||
direction: "target",
|
||||
adult: 130,
|
||||
source:
|
||||
"IOM 2005 DRI for macronutrients (RDA 130 g/d, adults; EFSA 2010 sets 45–60 % of energy and no g/d value)",
|
||||
},
|
||||
),
|
||||
// EFSA (2010) states fat as 20–35 % of energy; there is no per-day figure.
|
||||
fat: def("fat", "energy_macro", "FatTotal", "g", 1000, null),
|
||||
// EFSA (2022) set no safe level for added and free sugars.
|
||||
sugar: def("sugar", "energy_macro", "Sugar", "g", 1500, null),
|
||||
fiber: def("fiber", "energy_macro", "Fiber", "g", 500, {
|
||||
authority: "EFSA",
|
||||
kind: "AI",
|
||||
direction: "target",
|
||||
adult: 25,
|
||||
source: "EFSA DRV 2010 (dietary fibre, adults)",
|
||||
}),
|
||||
// Grams of ethanol. HealthKit has no dietary type for it (its alcohol
|
||||
// quantity is the number of drinks), so only a bridge token posts it.
|
||||
alcohol: tokenOnly("alcohol", "alcohol", "g", 1000),
|
||||
// ── Supplement-only (v1.43) ──────────────────────────────────────
|
||||
// Omega-3 fatty acids from fish or algae oil capsules. The cap sits well
|
||||
// above the 5 g a day EFSA reviewed, so only a unit slip trips it.
|
||||
@@ -613,6 +801,7 @@ export function toCanonicalNutrientAmount(
|
||||
* unit.
|
||||
*/
|
||||
const INPUT_UNIT_SPELLINGS: Readonly<Record<string, NutrientInputUnitCode>> = {
|
||||
kcal: NUTRIENT_UNIT.kcal,
|
||||
mg: NUTRIENT_UNIT.mg,
|
||||
ug: NUTRIENT_UNIT.ug,
|
||||
µg: NUTRIENT_UNIT.ug,
|
||||
@@ -664,8 +853,23 @@ export function isAboveUpperLimit(
|
||||
return compared > limit.value;
|
||||
}
|
||||
|
||||
/** Whether a supplement's composition may name `code`. */
|
||||
export function isIngredientNutrientCode(code: string): code is NutrientCode {
|
||||
return isNutrientCode(code) && NUTRIENT_CATALOG[code].ingredient;
|
||||
}
|
||||
|
||||
/** The codes of one group, in catalogue order. */
|
||||
export function nutrientCodesInGroup(
|
||||
...groups: NutrientGroup[]
|
||||
): NutrientCode[] {
|
||||
return NUTRIENT_CODES.filter((code) =>
|
||||
groups.includes(NUTRIENT_CATALOG[code].group),
|
||||
);
|
||||
}
|
||||
|
||||
/** A catalog reference resolved to one concrete number for a profile. */
|
||||
export interface ResolvedNutrientReference {
|
||||
authority: NutrientReferenceAuthority;
|
||||
kind: NutrientReference["kind"];
|
||||
direction: NutrientReference["direction"];
|
||||
value: number;
|
||||
@@ -693,6 +897,7 @@ export function resolveNutrientReference(
|
||||
(sex === "MALE" ? ref.male : sex === "FEMALE" ? ref.female : undefined);
|
||||
if (value === undefined) return null;
|
||||
return {
|
||||
authority: ref.authority,
|
||||
kind: ref.kind,
|
||||
direction: ref.direction,
|
||||
value,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* How one day's nutrient rows add up to the day's intake.
|
||||
*
|
||||
* A day can carry one row per source. Two kinds of source exist:
|
||||
*
|
||||
* - day-total sources (`DAY_TOTAL_SOURCES`: a bridge, Apple Health, Health
|
||||
* Connect) each report everything eaten that day, and usually report the
|
||||
* same meals. Only the LARGEST of them counts; the others are left out.
|
||||
* - additive sources (water entered by hand, taken supplement doses, and any
|
||||
* source outside the closed set) report something no tracker saw, so they
|
||||
* add on top.
|
||||
*
|
||||
* `bySource` names only the rows that counted, so its values always sum to
|
||||
* `total`. Every summation of nutrient rows reads this one fold, so no two
|
||||
* surfaces disagree about a day.
|
||||
*/
|
||||
import {
|
||||
DAY_TOTAL_SOURCES,
|
||||
isNutrientSource,
|
||||
type NutrientSource,
|
||||
} from "@/lib/nutrients/sources";
|
||||
|
||||
/** A day's amount split by source; a source that did not count is absent. */
|
||||
export type NutrientAmountBySource = Partial<Record<NutrientSource, number>>;
|
||||
|
||||
export interface NutrientDayRow {
|
||||
source: string;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface NutrientDayFold {
|
||||
total: number;
|
||||
bySource: NutrientAmountBySource;
|
||||
}
|
||||
|
||||
const DAY_TOTAL_SET: ReadonlySet<string> = new Set(DAY_TOTAL_SOURCES);
|
||||
|
||||
/** Fold one day's rows (one nutrient) into the day's total and its split. */
|
||||
export function foldNutrientDay(
|
||||
rows: ReadonlyArray<NutrientDayRow>,
|
||||
): NutrientDayFold {
|
||||
let total = 0;
|
||||
const bySource: NutrientAmountBySource = {};
|
||||
|
||||
// The largest day-total row, ties broken by `DAY_TOTAL_SOURCES` order.
|
||||
let winner: NutrientDayRow | null = null;
|
||||
for (const row of rows) {
|
||||
if (!DAY_TOTAL_SET.has(row.source)) continue;
|
||||
if (
|
||||
winner === null ||
|
||||
row.amount > winner.amount ||
|
||||
(row.amount === winner.amount &&
|
||||
DAY_TOTAL_SOURCES.indexOf(row.source as NutrientSource) <
|
||||
DAY_TOTAL_SOURCES.indexOf(winner.source as NutrientSource))
|
||||
) {
|
||||
winner = row;
|
||||
}
|
||||
}
|
||||
if (winner !== null) {
|
||||
total += winner.amount;
|
||||
bySource[winner.source as NutrientSource] = winner.amount;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
if (DAY_TOTAL_SET.has(row.source)) continue;
|
||||
total += row.amount;
|
||||
// A source outside the closed set still counts toward the total; it only
|
||||
// cannot be named in the split.
|
||||
if (isNutrientSource(row.source)) {
|
||||
bySource[row.source] = (bySource[row.source] ?? 0) + row.amount;
|
||||
}
|
||||
}
|
||||
return { total, bySource };
|
||||
}
|
||||
|
||||
/**
|
||||
* Group rows by a key (day, or day and nutrient) and fold each group. The
|
||||
* caller picks the key; the fold is the same.
|
||||
*/
|
||||
export function foldNutrientDays<T extends NutrientDayRow>(
|
||||
rows: ReadonlyArray<T>,
|
||||
keyOf: (row: T) => string,
|
||||
): Map<string, NutrientDayFold> {
|
||||
const groups = new Map<string, T[]>();
|
||||
for (const row of rows) {
|
||||
const key = keyOf(row);
|
||||
const group = groups.get(key);
|
||||
if (group) group.push(row);
|
||||
else groups.set(key, [row]);
|
||||
}
|
||||
const folds = new Map<string, NutrientDayFold>();
|
||||
for (const [key, group] of groups) folds.set(key, foldNutrientDay(group));
|
||||
return folds;
|
||||
}
|
||||
+45
-45
@@ -3,9 +3,10 @@
|
||||
* `GET /api/nutrients/daily` and the MCP `get_nutrients` tool.
|
||||
*
|
||||
* A day can carry one row per source (migration 0249 put `source` in the
|
||||
* key, v1.43 added `SUPPLEMENT`), so every read sums a day across its rows
|
||||
* and, since v1.43, also keeps the split by source and judges the day
|
||||
* against the nutrient's upper intake level. The judgement is made here,
|
||||
* key), so every read folds a day's rows through `foldNutrientDay` (the
|
||||
* largest day-total source counts, additive sources add on top), keeps the
|
||||
* split by source, and judges the day against the nutrient's upper intake
|
||||
* level. The judgement is made here,
|
||||
* once, so no client and no prompt ever compares a number against a limit
|
||||
* of its own.
|
||||
*/
|
||||
@@ -19,14 +20,18 @@ import {
|
||||
type NutrientUpperLimit,
|
||||
} from "@/lib/nutrients/catalog";
|
||||
import {
|
||||
NUTRIENT_SOURCE,
|
||||
isNutrientSource,
|
||||
type NutrientSource,
|
||||
} from "@/lib/nutrients/sources";
|
||||
foldNutrientDay,
|
||||
foldNutrientDays,
|
||||
type NutrientAmountBySource,
|
||||
type NutrientDayFold as DayFold,
|
||||
type NutrientDayRow,
|
||||
} from "@/lib/nutrients/day-total";
|
||||
import { NUTRIENT_SOURCE } from "@/lib/nutrients/sources";
|
||||
import { readNutrientTargets } from "@/lib/nutrients/targets";
|
||||
import { shiftDateKey, userDayKey } from "@/lib/tz/format";
|
||||
import type { NutrientTarget } from "@/lib/validations/nutrient-targets";
|
||||
|
||||
/** A day's amount split by source; a source with nothing is absent. */
|
||||
export type NutrientAmountBySource = Partial<Record<NutrientSource, number>>;
|
||||
export type { NutrientAmountBySource };
|
||||
|
||||
interface StoredRow {
|
||||
nutrient: string;
|
||||
@@ -36,20 +41,6 @@ interface StoredRow {
|
||||
source: string;
|
||||
}
|
||||
|
||||
interface DayFold {
|
||||
total: number;
|
||||
bySource: NutrientAmountBySource;
|
||||
}
|
||||
|
||||
function addToDay(fold: DayFold, source: string, amount: number): void {
|
||||
fold.total += amount;
|
||||
// A source outside the closed set still counts toward the day's total; it
|
||||
// only cannot be named in the split.
|
||||
if (isNutrientSource(source)) {
|
||||
fold.bySource[source] = (fold.bySource[source] ?? 0) + amount;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether one folded day is above the code's upper limit (null without one). */
|
||||
function dayAboveLimit(code: NutrientCode, fold: DayFold): boolean | null {
|
||||
return isAboveUpperLimit(code, {
|
||||
@@ -100,7 +91,12 @@ export async function readNutrientOverview(
|
||||
|
||||
const byCode = new Map<
|
||||
string,
|
||||
{ unit: string; latestDay: string; latest: DayFold; daysSeen: Set<string> }
|
||||
{
|
||||
unit: string;
|
||||
latestDay: string;
|
||||
latestRows: NutrientDayRow[];
|
||||
daysSeen: Set<string>;
|
||||
}
|
||||
>();
|
||||
for (const row of rows) {
|
||||
let summary = byCode.get(row.nutrient);
|
||||
@@ -110,7 +106,7 @@ export async function readNutrientOverview(
|
||||
summary = {
|
||||
unit: row.unit,
|
||||
latestDay: row.day,
|
||||
latest: { total: 0, bySource: {} },
|
||||
latestRows: [],
|
||||
daysSeen: new Set(),
|
||||
};
|
||||
byCode.set(row.nutrient, summary);
|
||||
@@ -119,7 +115,7 @@ export async function readNutrientOverview(
|
||||
// once.
|
||||
summary.daysSeen.add(row.day);
|
||||
if (row.day === summary.latestDay) {
|
||||
addToDay(summary.latest, row.source, row.amount);
|
||||
summary.latestRows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,15 +123,16 @@ export async function readNutrientOverview(
|
||||
(code) => isNutrientCode(code) && byCode.has(code),
|
||||
).map((code) => {
|
||||
const summary = byCode.get(code)!;
|
||||
const latest = foldNutrientDay(summary.latestRows);
|
||||
return {
|
||||
nutrient: code,
|
||||
unit: summary.unit,
|
||||
latestDay: summary.latestDay,
|
||||
latestAmount: summary.latest.total,
|
||||
latestAmount: latest.total,
|
||||
daysWithData: summary.daysSeen.size,
|
||||
latestBySource: summary.latest.bySource,
|
||||
latestBySource: latest.bySource,
|
||||
upperLimit: NUTRIENT_CATALOG[code].upperLimit,
|
||||
latestAboveUpperLimit: dayAboveLimit(code, summary.latest),
|
||||
latestAboveUpperLimit: dayAboveLimit(code, latest),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -152,29 +149,28 @@ export interface NutrientDailyEntry {
|
||||
/**
|
||||
* One nutrient's dense day series over the window: one entry per calendar
|
||||
* day, 0 and an empty split on a day without data, each judged against the
|
||||
* upper limit.
|
||||
* upper limit; and the target the person set for the nutrient, or null.
|
||||
*/
|
||||
export async function readNutrientDaily(
|
||||
userId: string,
|
||||
timezone: string,
|
||||
nutrient: NutrientCode,
|
||||
days: number,
|
||||
): Promise<{ days: NutrientDailyEntry[]; rowCount: number }> {
|
||||
): Promise<{
|
||||
days: NutrientDailyEntry[];
|
||||
rowCount: number;
|
||||
personalTarget: NutrientTarget | null;
|
||||
}> {
|
||||
const since = nutrientWindowStart(timezone, days);
|
||||
const rows = await prisma.nutrientIntakeDay.findMany({
|
||||
where: { userId, nutrient, day: { gte: since } },
|
||||
select: { day: true, amount: true, source: true },
|
||||
});
|
||||
const [rows, targets] = await Promise.all([
|
||||
prisma.nutrientIntakeDay.findMany({
|
||||
where: { userId, nutrient, day: { gte: since } },
|
||||
select: { day: true, amount: true, source: true },
|
||||
}),
|
||||
readNutrientTargets(userId),
|
||||
]);
|
||||
|
||||
const folds = new Map<string, DayFold>();
|
||||
for (const row of rows) {
|
||||
let fold = folds.get(row.day);
|
||||
if (!fold) {
|
||||
fold = { total: 0, bySource: {} };
|
||||
folds.set(row.day, fold);
|
||||
}
|
||||
addToDay(fold, row.source, row.amount);
|
||||
}
|
||||
const folds = foldNutrientDays(rows, (row) => row.day);
|
||||
|
||||
const series: NutrientDailyEntry[] = [];
|
||||
for (let i = 0; i < days; i++) {
|
||||
@@ -187,5 +183,9 @@ export async function readNutrientDaily(
|
||||
aboveUpperLimit: dayAboveLimit(nutrient, fold),
|
||||
});
|
||||
}
|
||||
return { days: series, rowCount: rows.length };
|
||||
return {
|
||||
days: series,
|
||||
rowCount: rows.length,
|
||||
personalTarget: targets[nutrient] ?? null,
|
||||
};
|
||||
}
|
||||
@@ -2,13 +2,19 @@
|
||||
* Where a nutrient day row came from. A closed set enforced here rather than
|
||||
* by a database enum (`NutrientIntakeDay.source` is text and part of the key):
|
||||
*
|
||||
* - `APPLE_HEALTH`: the day total HealthKit synced (`POST /api/nutrients/batch`);
|
||||
* - `APPLE_HEALTH`: the day total HealthKit synced (`POST /api/nutrients/batch`
|
||||
* from the native client);
|
||||
* - `HEALTH_CONNECT`: the day total an Android Health Connect import wrote;
|
||||
* - `EXTERNAL`: the day total a bridge posted with a `measurements:write`
|
||||
* token (`POST /api/nutrients/batch`), typically a food tracker;
|
||||
* - `MANUAL`: water entered by hand (`POST /api/nutrients/water`);
|
||||
* - `SUPPLEMENT` (v1.43): the sum of the day's taken supplement doses, from
|
||||
* each medication's composition. Derived and recomputed, never entered.
|
||||
*/
|
||||
export const NUTRIENT_SOURCE = {
|
||||
APPLE_HEALTH: "APPLE_HEALTH",
|
||||
HEALTH_CONNECT: "HEALTH_CONNECT",
|
||||
EXTERNAL: "EXTERNAL",
|
||||
MANUAL: "MANUAL",
|
||||
SUPPLEMENT: "SUPPLEMENT",
|
||||
} as const;
|
||||
@@ -21,3 +27,16 @@ const SOURCES: ReadonlySet<string> = new Set(Object.values(NUTRIENT_SOURCE));
|
||||
export function isNutrientSource(value: string): value is NutrientSource {
|
||||
return SOURCES.has(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sources that each report the WHOLE day's intake, usually the same meals
|
||||
* logged once and mirrored through several systems (a food tracker writes into
|
||||
* Apple Health and also posts to HealthLog). Adding them would count a meal
|
||||
* twice, so a day counts only the largest of them. Order is the tie-break: on
|
||||
* equal amounts the earlier source is the one that counts.
|
||||
*/
|
||||
export const DAY_TOTAL_SOURCES: ReadonlyArray<NutrientSource> = [
|
||||
NUTRIENT_SOURCE.EXTERNAL,
|
||||
NUTRIENT_SOURCE.APPLE_HEALTH,
|
||||
NUTRIENT_SOURCE.HEALTH_CONNECT,
|
||||
];
|
||||
@@ -45,9 +45,11 @@ const moduleDisabled = {
|
||||
/**
|
||||
* The catalog table, rendered into the endpoint description so the
|
||||
* OpenAPI file is the one authoritative home of the code ↔ HK ↔ unit
|
||||
* contract (µg is `ug` on the wire; water is mL; never IU).
|
||||
* contract (µg is `ug` on the wire; water is mL; energy is kcal; never IU,
|
||||
* never kJ). Only the codes HealthKit carries; the batch also accepts
|
||||
* `alcohol`, which no HealthKit type does.
|
||||
*/
|
||||
const catalogTable = NUTRIENT_DEFINITIONS.filter((d) => d.syncable)
|
||||
const catalogTable = NUTRIENT_DEFINITIONS.filter((d) => d.hkIdentifier !== null)
|
||||
.map((d) => `| ${d.code} | ${d.hkIdentifier} | ${d.unit} |`)
|
||||
.join("\n");
|
||||
|
||||
@@ -60,7 +62,12 @@ const nutrientCatalogEntry = z
|
||||
syncable: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether HealthKit may send this code in the nutrient batch. `dha` and `epa` are not syncable: they appear in responses only.",
|
||||
"Whether the nutrient batch accepts this code. `dha` and `epa` are not syncable: they appear in responses only.",
|
||||
),
|
||||
ingredient: z
|
||||
.boolean()
|
||||
.describe(
|
||||
"Whether a supplement's composition may name this code. False for water, energy, the macronutrients and alcohol.",
|
||||
),
|
||||
inputUnits: z
|
||||
.array(z.object({ unit: z.string(), factorToCanonical: z.number() }))
|
||||
@@ -103,9 +110,9 @@ export const nutrientPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
post: {
|
||||
parameters: [idempotencyKeyParameter],
|
||||
tags: ["Nutrients"],
|
||||
summary: "Ingest micronutrient day totals (v1.28)",
|
||||
summary: "Ingest nutrient day totals (v1.28)",
|
||||
description:
|
||||
"Bulk upsert of supplement-style daily totals synced from HealthKit — vitamins, minerals, water, caffeine. Day totals only: compute HKStatisticsCollectionQuery cumulative sums day-anchored in the user's current IANA timezone; `day` is yyyy-MM-dd in that timezone (the same rule as the `stats:` day keys). Never post raw samples. Upsert key is (day, nutrient): a re-post replaces the stored total and reports `updated`. Post the current + previous local day per sync; backfill 30 days on first enable. Max 500 entries; Idempotency-Key supported; rate limit 60/min. Per-entry skips (`unit_mismatch` | `value_out_of_range` | `day_invalid`) are terminal — log and drop, do not retry the entry. `upsert_failed` is not one of them: it is a server-side write failure for the entry's whole write group, nothing was stored, and the entry should be sent again on a later sync; a response carrying it is `Cache-Control: no-store` and is not replayed for its `Idempotency-Key`. Behind the opt-in `nutrients` module (403 `module.disabled` when off). Query HealthKit with exactly the listed unit per code (`ug` = microgram; do not convert to IU):\n\n| code | HealthKit identifier | unit |\n| --- | --- | --- |\n" +
|
||||
"Bulk upsert of daily nutrient totals: vitamins, minerals, water, caffeine, energy (kcal), the macronutrients (g) and alcohol (g of ethanol). Two kinds of caller. The native client syncs from HealthKit with a cookie session or its login token, and its rows are stored as source APPLE_HEALTH. A bridge (a food tracker, a script) posts with a `measurements:write` token, and its rows are stored as source EXTERNAL; the body never chooses the source. A bridge may post any past day, and posts 0 to correct a day it got wrong. On the reads, the largest of the day-total sources (EXTERNAL, APPLE_HEALTH, HEALTH_CONNECT) counts for a day, so a tracker that also writes into Apple Health is not counted twice. Units are fixed per code (table below); energy is kcal, and a kJ value is skipped `unit_mismatch`, never converted.\n\nFor the native client: day totals only: compute HKStatisticsCollectionQuery cumulative sums day-anchored in the user's current IANA timezone; `day` is yyyy-MM-dd in that timezone (the same rule as the `stats:` day keys). Never post raw samples. Upsert key is (day, nutrient): a re-post replaces the stored total and reports `updated`. Post the current + previous local day per sync; backfill 30 days on first enable. Max 500 entries; Idempotency-Key supported; rate limit 60/min. Per-entry skips (`unit_mismatch` | `value_out_of_range` | `day_invalid`) are terminal — log and drop, do not retry the entry. `upsert_failed` is not one of them: it is a server-side write failure for the entry's whole write group, nothing was stored, and the entry should be sent again on a later sync; a response carrying it is `Cache-Control: no-store` and is not replayed for its `Idempotency-Key`. Behind the opt-in `nutrients` module (403 `module.disabled` when off). Query HealthKit with exactly the listed unit per code (`ug` = microgram; do not convert to IU). `alcohol` has no HealthKit type and is posted by bridges only, in g:\n\n| code | HealthKit identifier | unit |\n| --- | --- | --- |\n" +
|
||||
catalogTable,
|
||||
requestBody: {
|
||||
required: true,
|
||||
@@ -159,7 +166,7 @@ export const nutrientPaths: NonNullable<ZodOpenApiObject["paths"]> = {
|
||||
tags: ["Nutrients"],
|
||||
summary: "One nutrient's day-bucketed series (v1.29)",
|
||||
description:
|
||||
"Dense per-day series for one catalog code over the last `days` days (default 30) — one entry per calendar day, 0 for a day with no logged data, summed ACROSS SOURCES (a day may carry both an APPLE_HEALTH row and a MANUAL row since migration 0249). Feeds the `/insights/nutrients` hydration + caffeine charts. Also returns the EFSA reference resolved against the caller's profile sex — `null` when the profile has no sex on file (never guessed). Behind the opt-in `nutrients` module.",
|
||||
"Dense per-day series for one catalog code over the last `days` days (default 30) — one entry per calendar day, 0 for a day with no logged data, folded across sources (the largest of the day-total sources APPLE_HEALTH, HEALTH_CONNECT and EXTERNAL, plus MANUAL and SUPPLEMENT on top). Feeds the `/insights/nutrients` charts. Also returns the dietary reference resolved against the caller's profile sex — `null` when the profile has no sex on file (never guessed) or the nutrient has none — and the user's own target for the nutrient, if set. Behind the opt-in `nutrients` module.",
|
||||
requestParams: { query: nutrientDailyQuerySchema },
|
||||
responses: {
|
||||
"200": {
|
||||
|
||||
@@ -22,4 +22,9 @@ export const nutrientKeys = {
|
||||
* it.
|
||||
*/
|
||||
nutrientCatalog: () => ["nutrients", "catalog"] as const,
|
||||
/**
|
||||
* The daily targets the person set, from `GET /api/nutrients/targets`. The
|
||||
* target editor reads it; the daily series carries the one for its code.
|
||||
*/
|
||||
nutrientTargets: () => ["nutrients", "targets"] as const,
|
||||
};
|
||||
@@ -21,17 +21,17 @@ export const MAX_NUTRIENT_ENTRIES_PER_BATCH = 500;
|
||||
export const nutrientCodeEnum = z.enum(NUTRIENT_CODES).meta({
|
||||
id: "NutrientCode",
|
||||
description:
|
||||
"Closed nutrient catalog code — 24 HealthKit Dietary vitamin/mineral types plus water and caffeine, and (v1.43, responses only) `dha` and `epa`, which only a supplement's composition produces. Energy, macros and sodium/potassium are out of scope. Decode unknown values leniently.",
|
||||
"Closed nutrient catalog code: the vitamins and minerals (sodium and potassium included), water, caffeine, dietary energy (`energy`, kcal), the macronutrients (`protein`, `carbohydrates`, `fat`, `sugar`, `fiber`, g), `alcohol` (grams of ethanol), and (responses only) `dha` and `epa`, which only a supplement's composition produces. The set grows; decode unknown values leniently.",
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.43 — the codes the batch accepts: the catalogue without the
|
||||
* supplement-only codes, so the HealthKit sync contract stays unchanged.
|
||||
* The codes the batch accepts: the catalogue without the supplement-only
|
||||
* codes.
|
||||
*/
|
||||
export const syncableNutrientCodeEnum = z.enum(SYNCABLE_NUTRIENT_CODES).meta({
|
||||
id: "SyncableNutrientCode",
|
||||
description:
|
||||
"A nutrient code HealthKit may send: the 24 Dietary vitamin/mineral types plus water and caffeine. Never `dha` or `epa`.",
|
||||
"A nutrient code the batch accepts: the HealthKit Dietary vitamin, mineral, energy and macronutrient types, water and caffeine, plus `alcohol` (no HealthKit type; a bridge token posts it). Never `dha` or `epa`.",
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -39,8 +39,9 @@ export const syncableNutrientCodeEnum = z.enum(SYNCABLE_NUTRIENT_CODES).meta({
|
||||
* computed client-side (the `stats:` day-key contract); the server
|
||||
* trusts the string after regex + calendar sanity, no re-derivation.
|
||||
* `unit` deliberately rides the wire even though the catalog pins it:
|
||||
* a µg/mg confusion is a silent 1000× corruption and the one-string
|
||||
* echo is the cheapest guard — a mismatch skips the entry.
|
||||
* a µg/mg confusion is a silent 1000× corruption (kJ read as kcal a 4.184×
|
||||
* one) and the one-string echo is the cheapest guard — a mismatch skips the
|
||||
* entry.
|
||||
*/
|
||||
export const nutrientEntrySchema = z
|
||||
.object({
|
||||
@@ -53,7 +54,7 @@ export const nutrientEntrySchema = z
|
||||
.meta({
|
||||
id: "NutrientIntakeEntry",
|
||||
description:
|
||||
"One nutrient day total. day = YYYY-MM-DD in the user's IANA timezone; unit must equal the catalog's canonical unit for the code (mg | ug | ml) or the entry is skipped unit_mismatch.",
|
||||
"One nutrient day total. day = YYYY-MM-DD in the user's IANA timezone; unit must equal the catalog's canonical unit for the code (mg | ug | ml | g | kcal) or the entry is skipped unit_mismatch. Energy is kcal only; a kJ value is skipped, never converted.",
|
||||
});
|
||||
|
||||
export const nutrientBatchSchema = z
|
||||
@@ -66,7 +67,7 @@ export const nutrientBatchSchema = z
|
||||
.meta({
|
||||
id: "NutrientBatchRequest",
|
||||
description:
|
||||
"Bulk day-total upsert, max 500 entries. Upsert key is the composite primary key (userId, day, nutrient, source); this route always writes the APPLE_HEALTH source row, so a manual water entry is never clobbered. A re-post replaces the stored total (last-writer-wins day-total contract).",
|
||||
"Bulk day-total upsert, max 500 entries. Upsert key is the composite primary key (userId, day, nutrient, source). The credential decides the source, never the body: a cookie session or a native-login token writes the APPLE_HEALTH row, a `measurements:write` token the EXTERNAL row. A manual water entry is never clobbered. A re-post replaces the stored total (last-writer-wins day-total contract); post 0 to correct a day.",
|
||||
});
|
||||
|
||||
/** Per-entry outcome — a re-post is by definition an update, never a duplicate. */
|
||||
@@ -130,17 +131,19 @@ export const nutrientUpperLimitSchema = z
|
||||
"The tolerable upper intake level, with the unit, whether it applies to the total intake or to the supplemental share only, and the cited source. `null` where no level is established.",
|
||||
});
|
||||
|
||||
/** v1.43 — a day total split by where it came from. */
|
||||
/** A day total split by the sources that counted toward it. */
|
||||
export const nutrientBySourceSchema = z
|
||||
.object({
|
||||
APPLE_HEALTH: z.number().optional(),
|
||||
HEALTH_CONNECT: z.number().optional(),
|
||||
EXTERNAL: z.number().optional(),
|
||||
MANUAL: z.number().optional(),
|
||||
SUPPLEMENT: z.number().optional(),
|
||||
})
|
||||
.meta({
|
||||
id: "NutrientAmountBySource",
|
||||
description:
|
||||
"The amount split by source: synced from Apple Health, entered by hand, and counted from taken supplement doses. A source with nothing is absent.",
|
||||
"The amount split by the sources that counted: synced from Apple Health, imported from Health Connect, posted by a bridge token (EXTERNAL), entered by hand, and counted from taken supplement doses. APPLE_HEALTH, HEALTH_CONNECT and EXTERNAL each report the whole day, usually the same meals, so only the largest of them counts and the others are absent here; MANUAL and SUPPLEMENT add on top. The values sum to the day's total. A source that did not count is absent. Decode unknown keys leniently.",
|
||||
});
|
||||
|
||||
export const nutrientOverviewSchema = z
|
||||
@@ -228,6 +231,18 @@ export const nutrientWaterWriteResponseSchema = z
|
||||
description: "The MANUAL water row after the add/set write.",
|
||||
});
|
||||
|
||||
/** A target or limit the user set for one nutrient. */
|
||||
export const nutrientPersonalTargetSchema = z
|
||||
.object({
|
||||
value: z.number().positive(),
|
||||
direction: z.enum(["target", "limit"]),
|
||||
})
|
||||
.meta({
|
||||
id: "NutrientPersonalTarget",
|
||||
description:
|
||||
"A user-set daily amount in the nutrient's canonical unit. `target` = an amount to reach, `limit` = an amount to stay under.",
|
||||
});
|
||||
|
||||
/** `GET /api/nutrients/daily` query — one nutrient's day-bucketed series. */
|
||||
export const nutrientDailyQuerySchema = z.object({
|
||||
nutrient: nutrientCodeEnum,
|
||||
@@ -235,6 +250,12 @@ export const nutrientDailyQuerySchema = z.object({
|
||||
});
|
||||
|
||||
const resolvedNutrientReferenceSchema = z.object({
|
||||
authority: z
|
||||
.enum(["EFSA", "IOM", "NIH ODS"])
|
||||
.optional()
|
||||
.describe(
|
||||
"The body that set the value: EFSA wherever it sets a per-day value, IOM for protein and carbohydrates, NIH ODS for chromium.",
|
||||
),
|
||||
kind: z.enum(["PRI", "AI", "safeLevel"]),
|
||||
direction: z.enum(["target", "upperGuidance"]),
|
||||
value: z.number(),
|
||||
@@ -263,6 +284,12 @@ export const nutrientDailySeriesSchema = z
|
||||
}),
|
||||
),
|
||||
reference: resolvedNutrientReferenceSchema.nullable(),
|
||||
personalTarget: nutrientPersonalTargetSchema
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"The target or limit the user set for this nutrient (`PATCH /api/nutrients/targets`), or null. A chart prefers it over `reference`.",
|
||||
),
|
||||
upperLimit: nutrientUpperLimitSchema
|
||||
.nullable()
|
||||
.optional()
|
||||
@@ -271,5 +298,5 @@ export const nutrientDailySeriesSchema = z
|
||||
.meta({
|
||||
id: "NutrientDailySeries",
|
||||
description:
|
||||
"Dense day-bucketed series (one entry per day in the window, 0 for a day with no data) summed across sources, plus the EFSA reference resolved against the caller's profile sex (null when sex is unknown on the profile).",
|
||||
"Dense day-bucketed series (one entry per day in the window, 0 for a day with no data). A day's amount is the largest of the day-total sources plus the additive ones (see NutrientAmountBySource). Carries the dietary reference resolved against the caller's profile sex (null when sex is unknown on the profile or the nutrient has none) and the user's own target, if set.",
|
||||
});
|
||||
Reference in new issue
Block a user