diff --git a/messages/de.json b/messages/de.json index 0e7bda121..d37ac34c6 100644 --- a/messages/de.json +++ b/messages/de.json @@ -2486,6 +2486,7 @@ "navPulse": "Puls", "navMood": "Stimmung", "navMedication": "Medikamente", + "navNutrients": "Nährstoffe", "navBmi": "BMI", "navSleep": "Schlaf", "navHrv": "HRV", @@ -8548,7 +8549,36 @@ "iodine": "Jod", "water": "Wasser", "caffeine": "Koffein" - } + }, + "page": { + "title": "Nährstoffaufnahme", + "description": "Flüssigkeits- und Vitamin-/Mineralstoffaufnahme aus der Gesundheits-App deines Telefons, plus manuelle Wassereinträge.", + "moduleOffTitle": "Nährstoffaufnahme ist aus", + "moduleOffDescription": "Aktiviere das Nährstoffe-Modul, um Flüssigkeits- und Vitamin-/Mineralstoffaufnahme hier zu sehen. Synchronisierte Werte werden Teil der Aufzeichnung, die der Coach lesen kann.", + "moduleOffCta": "Nährstoffe aktivieren", + "emptyTitle": "Noch keine Nährstoffdaten", + "emptyDescription": "Daten kommen aus der Synchronisierung der Gesundheits-App deines Telefons oder einem manuellen Wassereintrag." + }, + "hydration": { + "referenceMeta": "Richtwert {value} {unit}/Tag · EFSA", + "quickAddTitle": "Wasser hinzufügen", + "quickAddCustomLabel": "Eigene Menge (ml)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Hinzufügen", + "quickAddError": "Konnte nicht gespeichert werden — versuch's noch mal.", + "editTotal": "Heutige Summe bearbeiten" + }, + "caffeine": { + "ceilingMeta": "Sichere Obergrenze {value} {unit}/Tag · EFSA" + }, + "micronutrients": { + "title": "Vitamine & Mineralstoffe", + "rowMeta": "{days} von {window} Tagen · Richtwert {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} von {window} Tagen", + "footer": "{tracked} von {total} erfassten Mikronährstoffen haben Daten in diesem Zeitraum.", + "emptyTitle": "Noch keine Mikronährstoffdaten synchronisiert" + }, + "sparseNote": "Ein niedriger Wert bedeutet hier meist lückenhafte Erfassung, keinen Mangel — die Tagessummen aus Apple Health spiegeln wider, was deine Apps erfasst haben, nicht die gesamte Nahrungsaufnahme." }, "daily": { "line": { diff --git a/messages/en.json b/messages/en.json index c2195f3dc..e6046c31f 100644 --- a/messages/en.json +++ b/messages/en.json @@ -2486,6 +2486,7 @@ "navPulse": "Pulse", "navMood": "Mood", "navMedication": "Medication", + "navNutrients": "Nutrients", "navBmi": "BMI", "navSleep": "Sleep", "navHrv": "HRV", @@ -8548,7 +8549,36 @@ "iodine": "Iodine", "water": "Water", "caffeine": "Caffeine" - } + }, + "page": { + "title": "Nutrient intake", + "description": "Hydration and vitamin/mineral intake synced from your phone's health app, plus manual water entries.", + "moduleOffTitle": "Nutrient intake is off", + "moduleOffDescription": "Turn on the nutrients module to see hydration and vitamin/mineral intake here. Synced intake becomes part of the record the Coach can read.", + "moduleOffCta": "Turn on nutrients", + "emptyTitle": "No nutrient data yet", + "emptyDescription": "Data arrives from your phone's health app sync or a manual water entry." + }, + "hydration": { + "referenceMeta": "Reference intake {value} {unit}/day · EFSA", + "quickAddTitle": "Add water", + "quickAddCustomLabel": "Custom amount (mL)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Add", + "quickAddError": "Couldn't save that — try again.", + "editTotal": "Edit today's total" + }, + "caffeine": { + "ceilingMeta": "Safe-level ceiling {value} {unit}/day · EFSA" + }, + "micronutrients": { + "title": "Vitamins & minerals", + "rowMeta": "{days} of {window} days · ref {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} of {window} days", + "footer": "{tracked} of {total} tracked micronutrients have data in this window.", + "emptyTitle": "No micronutrient data synced yet" + }, + "sparseNote": "A low number here usually means sparse logging, not a deficiency — Apple Health day totals reflect what your apps logged, not total dietary intake." }, "daily": { "line": { diff --git a/messages/es.json b/messages/es.json index a29101256..78dc73526 100644 --- a/messages/es.json +++ b/messages/es.json @@ -2486,6 +2486,7 @@ "navPulse": "Pulso", "navMood": "Estado de ánimo", "navMedication": "Medicamento", + "navNutrients": "Nutrientes", "navBmi": "IMC", "navSleep": "Sueño", "navHrv": "VFC", @@ -8548,7 +8549,36 @@ "iodine": "Yodo", "water": "Agua", "caffeine": "Cafeína" - } + }, + "page": { + "title": "Ingesta de nutrientes", + "description": "Hidratación e ingesta de vitaminas/minerales sincronizadas desde la app de salud de tu teléfono, más entradas manuales de agua.", + "moduleOffTitle": "La ingesta de nutrientes está desactivada", + "moduleOffDescription": "Activa el módulo de nutrientes para ver aquí la hidratación y la ingesta de vitaminas/minerales. Los datos sincronizados pasarán a formar parte del registro que el Coach puede leer.", + "moduleOffCta": "Activar nutrientes", + "emptyTitle": "Aún no hay datos de nutrientes", + "emptyDescription": "Los datos llegan desde la sincronización de la app de salud de tu teléfono o desde una entrada manual de agua." + }, + "hydration": { + "referenceMeta": "Ingesta de referencia {value} {unit}/día · EFSA", + "quickAddTitle": "Añadir agua", + "quickAddCustomLabel": "Cantidad personalizada (mL)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Añadir", + "quickAddError": "No se pudo guardar. Inténtalo de nuevo.", + "editTotal": "Editar el total de hoy" + }, + "caffeine": { + "ceilingMeta": "Límite de seguridad {value} {unit}/día · EFSA" + }, + "micronutrients": { + "title": "Vitaminas y minerales", + "rowMeta": "{days} de {window} días · ref. {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} de {window} días", + "footer": "{tracked} de {total} micronutrientes registrados tienen datos en este periodo.", + "emptyTitle": "Aún no hay datos de micronutrientes sincronizados" + }, + "sparseNote": "Un valor bajo aquí suele significar un registro escaso, no una deficiencia: los totales diarios de Apple Health reflejan lo que registraron tus apps, no la ingesta dietética total." }, "daily": { "line": { diff --git a/messages/fr.json b/messages/fr.json index d3726d425..26b85adea 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -2486,6 +2486,7 @@ "navPulse": "Pouls", "navMood": "Humeur", "navMedication": "Médicament", + "navNutrients": "Nutriments", "navBmi": "IMC", "navSleep": "Sommeil", "navHrv": "VFC", @@ -8548,7 +8549,36 @@ "iodine": "Iode", "water": "Eau", "caffeine": "Caféine" - } + }, + "page": { + "title": "Apports en nutriments", + "description": "Hydratation et apports en vitamines/minéraux synchronisés depuis l'appli santé de votre téléphone, plus les entrées manuelles d'eau.", + "moduleOffTitle": "Le suivi des nutriments est désactivé", + "moduleOffDescription": "Activez le module nutriments pour voir ici l'hydratation et les apports en vitamines/minéraux. Les données synchronisées feront partie du dossier que le Coach peut lire.", + "moduleOffCta": "Activer les nutriments", + "emptyTitle": "Pas encore de données nutritionnelles", + "emptyDescription": "Les données proviennent de la synchronisation de l'appli santé de votre téléphone ou d'une saisie manuelle d'eau." + }, + "hydration": { + "referenceMeta": "Apport de référence {value} {unit}/jour · EFSA", + "quickAddTitle": "Ajouter de l'eau", + "quickAddCustomLabel": "Quantité personnalisée (mL)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Ajouter", + "quickAddError": "Échec de l'enregistrement — réessayez.", + "editTotal": "Modifier le total du jour" + }, + "caffeine": { + "ceilingMeta": "Plafond de sécurité {value} {unit}/jour · EFSA" + }, + "micronutrients": { + "title": "Vitamines et minéraux", + "rowMeta": "{days} sur {window} jours · réf. {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} sur {window} jours", + "footer": "{tracked} des {total} micronutriments suivis ont des données sur cette période.", + "emptyTitle": "Aucune donnée de micronutriments synchronisée pour l'instant" + }, + "sparseNote": "Une valeur basse ici signifie généralement un suivi partiel, pas une carence — les totaux journaliers Apple Health reflètent ce que vos applis ont enregistré, pas l'apport alimentaire total." }, "daily": { "line": { diff --git a/messages/it.json b/messages/it.json index b07a3cf88..0b879650e 100644 --- a/messages/it.json +++ b/messages/it.json @@ -2486,6 +2486,7 @@ "navPulse": "Polso", "navMood": "Umore", "navMedication": "Farmaco", + "navNutrients": "Nutrienti", "navBmi": "IMC", "navSleep": "Sonno", "navHrv": "HRV", @@ -8548,7 +8549,36 @@ "iodine": "Iodio", "water": "Acqua", "caffeine": "Caffeina" - } + }, + "page": { + "title": "Apporto di nutrienti", + "description": "Idratazione e apporto di vitamine/minerali sincronizzati dall'app salute del telefono, più le voci di acqua inserite manualmente.", + "moduleOffTitle": "L'apporto di nutrienti è disattivato", + "moduleOffDescription": "Attiva il modulo nutrienti per vedere qui idratazione e apporto di vitamine/minerali. I dati sincronizzati diventano parte dei dati che il Coach può leggere.", + "moduleOffCta": "Attiva nutrienti", + "emptyTitle": "Ancora nessun dato sui nutrienti", + "emptyDescription": "I dati arrivano dalla sincronizzazione dell'app salute del telefono o da una voce di acqua inserita manualmente." + }, + "hydration": { + "referenceMeta": "Apporto di riferimento {value} {unit}/giorno · EFSA", + "quickAddTitle": "Aggiungi acqua", + "quickAddCustomLabel": "Quantità personalizzata (mL)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Aggiungi", + "quickAddError": "Salvataggio non riuscito. Riprova.", + "editTotal": "Modifica il totale di oggi" + }, + "caffeine": { + "ceilingMeta": "Limite di sicurezza {value} {unit}/giorno · EFSA" + }, + "micronutrients": { + "title": "Vitamine e minerali", + "rowMeta": "{days} di {window} giorni · rif. {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} di {window} giorni", + "footer": "{tracked} di {total} micronutrienti monitorati hanno dati in questo periodo.", + "emptyTitle": "Nessun dato sui micronutrienti ancora sincronizzato" + }, + "sparseNote": "Un valore basso qui di solito indica una registrazione poco frequente, non una carenza — i totali giornalieri di Apple Health riflettono ciò che le tue app hanno registrato, non l'apporto alimentare totale." }, "daily": { "line": { diff --git a/messages/pl.json b/messages/pl.json index 592f41484..7c09659ab 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -2486,6 +2486,7 @@ "navPulse": "Tętno", "navMood": "Nastrój", "navMedication": "Lek", + "navNutrients": "Składniki odżywcze", "navBmi": "BMI", "navSleep": "Sen", "navHrv": "HRV", @@ -8548,7 +8549,36 @@ "iodine": "Jod", "water": "Woda", "caffeine": "Kofeina" - } + }, + "page": { + "title": "Spożycie składników odżywczych", + "description": "Nawodnienie oraz spożycie witamin/minerałów zsynchronizowane z aplikacji zdrowia telefonu, plus ręczne wpisy wody.", + "moduleOffTitle": "Śledzenie składników odżywczych jest wyłączone", + "moduleOffDescription": "Włącz moduł składników odżywczych, aby zobaczyć tu nawodnienie i spożycie witamin/minerałów. Zsynchronizowane dane staną się częścią zapisu, który może odczytać Coach.", + "moduleOffCta": "Włącz składniki odżywcze", + "emptyTitle": "Brak jeszcze danych o składnikach odżywczych", + "emptyDescription": "Dane pochodzą z synchronizacji aplikacji zdrowia telefonu lub z ręcznego wpisu wody." + }, + "hydration": { + "referenceMeta": "Zalecane spożycie {value} {unit}/dzień · EFSA", + "quickAddTitle": "Dodaj wodę", + "quickAddCustomLabel": "Własna ilość (mL)", + "quickAddCustomPlaceholder": "250", + "quickAddSubmit": "Dodaj", + "quickAddError": "Nie udało się zapisać — spróbuj ponownie.", + "editTotal": "Edytuj dzisiejszą sumę" + }, + "caffeine": { + "ceilingMeta": "Bezpieczny limit {value} {unit}/dzień · EFSA" + }, + "micronutrients": { + "title": "Witaminy i minerały", + "rowMeta": "{days} z {window} dni · zalecane {value} {unit} (EFSA)", + "rowMetaNoRef": "{days} z {window} dni", + "footer": "{tracked} z {total} śledzonych mikroskładników ma dane w tym okresie.", + "emptyTitle": "Brak jeszcze zsynchronizowanych danych o mikroskładnikach" + }, + "sparseNote": "Niska wartość zwykle oznacza tu rzadkie zapisywanie, a nie niedobór — dzienne sumy z Apple Health odzwierciedlają to, co zapisały twoje aplikacje, a nie całkowite spożycie w diecie." }, "daily": { "line": { diff --git a/src/app/insights/nutrients/page.tsx b/src/app/insights/nutrients/page.tsx new file mode 100644 index 000000000..5f123e74c --- /dev/null +++ b/src/app/insights/nutrients/page.tsx @@ -0,0 +1,112 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Leaf } from "lucide-react"; +import { toast } from "sonner"; + +import { Button } from "@/components/ui/button"; +import { EmptyState } from "@/components/ui/empty-state"; +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 { MicronutrientsCard } from "@/components/insights/nutrients/micronutrients-card"; +import { useAuth } from "@/hooks/use-auth"; +import { useTranslations } from "@/lib/i18n/context"; +import { apiGet, apiPatch } from "@/lib/api/api-fetch"; +import { queryKeys } from "@/lib/query-keys"; +import type { NutrientIntakeOverview } from "@/components/insights/nutrients/types"; + +const WINDOW_DAYS = 30; + +/** + * `/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: + * + * - module off → one EmptyState with an in-context enable CTA. The + * module STAYS opt-in (2026-07-17 memo — the HealthKit read prompt + * on the device is not visible consent to a server / Coach holding + * a supplement pattern); this page just makes the toggle + * discoverable in context instead of buried in Settings. + * - module on, zero rows anywhere in the window → one EmptyState + * explaining where data comes from (phone health-app sync or + * manual water entry) instead of three near-empty cards. + * - otherwise → the three-card spine. + */ +export default function InsightsNutrientsPage() { + const { t } = useTranslations(); + const { user } = useAuth(); + const queryClient = useQueryClient(); + + const nutrientsEnabled = user?.modules?.nutrients === true; + + const overview = useQuery({ + queryKey: queryKeys.nutrientIntake(WINDOW_DAYS), + queryFn: () => + apiGet(`/api/nutrients?days=${WINDOW_DAYS}`), + enabled: nutrientsEnabled, + }); + + const enableModule = useMutation({ + mutationFn: () => apiPatch("/api/auth/me/modules", { nutrients: true }), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.authMe() }); + }, + onError: () => toast.error(t("nutrients.hydration.quickAddError")), + }); + + if (!nutrientsEnabled) { + return ( + + } + title={t("nutrients.page.moduleOffTitle")} + description={t("nutrients.page.moduleOffDescription")} + ctaSize="lg" + action={ + + } + /> + + ); + } + + const hasAnyData = (overview.data?.nutrients.length ?? 0) > 0; + if (!overview.isLoading && !hasAnyData) { + return ( + + } + title={t("nutrients.page.emptyTitle")} + description={t("nutrients.page.emptyDescription")} + /> + + ); + } + + return ( + + + + + + ); +} diff --git a/src/components/charts/chart-runtime.ts b/src/components/charts/chart-runtime.ts index e17e14850..4368e24d3 100644 --- a/src/components/charts/chart-runtime.ts +++ b/src/components/charts/chart-runtime.ts @@ -43,3 +43,4 @@ export { DrugLevelChart } from "@/components/medications/drug-level-chart"; export { EfficacyChart } from "@/components/medications/detail/efficacy/efficacy-chart"; export { AssessmentHistoryChart } from "@/components/mental-health/assessment-history-chart"; export { IntradayPulseChart } from "@/components/insights/intraday-pulse-chart"; +export { NutrientDailyBarChart } from "./nutrient-daily-bar-chart"; diff --git a/src/components/charts/nutrient-daily-bar-chart-dynamic.tsx b/src/components/charts/nutrient-daily-bar-chart-dynamic.tsx new file mode 100644 index 000000000..2295076e0 --- /dev/null +++ b/src/components/charts/nutrient-daily-bar-chart-dynamic.tsx @@ -0,0 +1,32 @@ +"use client"; + +import dynamic from "next/dynamic"; +import type { ComponentProps, ReactElement } from "react"; + +import { ChartErrorBoundary } from "@/components/charts/chart-error-state"; +import { ChartSkeleton } from "@/components/charts/chart-skeleton"; +import { importWithRetry } from "@/lib/retry-import"; + +/** + * v1.29 — single `next/dynamic` boundary for ``, + * mirroring `health-chart-dynamic.tsx`. Both the hydration card and the + * caffeine card on `/insights/nutrients` share this one lazy boundary so + * recharts stays off the route's first-load JS and is fetched once. + */ +const NutrientDailyBarChartLazy = dynamic( + () => + importWithRetry(() => import("@/components/charts/chart-runtime")).then( + (mod) => ({ default: mod.NutrientDailyBarChart }), + ), + { ssr: false, loading: () => }, +); + +export function NutrientDailyBarChartDynamic( + props: ComponentProps, +): ReactElement { + return ( + + + + ); +} diff --git a/src/components/charts/nutrient-daily-bar-chart.tsx b/src/components/charts/nutrient-daily-bar-chart.tsx new file mode 100644 index 000000000..84bd26eaa --- /dev/null +++ b/src/components/charts/nutrient-daily-bar-chart.tsx @@ -0,0 +1,134 @@ +"use client"; + +import { useMemo } from "react"; +import { + Bar, + CartesianGrid, + ComposedChart, + ReferenceLine, + ResponsiveContainer, + Tooltip, + XAxis, + YAxis, +} from "recharts"; + +import { CHART_HEIGHT_PX } from "@/lib/charts/constants"; +import { prefersReducedMotion } from "@/lib/charts/reduced-motion"; +import { formatDateShort } from "@/lib/format"; + +import { RichChartTooltip, type RichTooltipRow } from "./chart-tooltip"; + +/** + * v1.29 — 30-day daily bar chart for the nutrients hydration / caffeine + * cards. One bar per day (dense series — 0 for an unlogged day, summed + * across sources), an optional thin dashed EFSA reference line, no + * attainment colouring (UI-STANDARDS: value stays foreground, the bar + + * reference line ARE the context). Registered in + * `src/components/charts/chart-runtime.ts` — never import recharts + * directly at the call site. + */ + +interface NutrientDailyBarChartProps { + /** Dense day series, ascending (oldest first). */ + days: ReadonlyArray<{ day: string; amount: number }>; + unit: string; + /** Already-localised tooltip row label (e.g. "Water"). */ + valueLabel: string; + /** Optional dashed reference line value (EFSA target / ceiling). */ + referenceValue?: number | null; +} + +/** Noon UTC so every viewer timezone renders the same calendar day. */ +function dayToDate(day: string): Date { + return new Date(`${day}T12:00:00.000Z`); +} + +export function NutrientDailyBarChart({ + days, + unit, + valueLabel, + referenceValue, +}: NutrientDailyBarChartProps) { + const points = useMemo( + () => days.map((d) => ({ day: d.day, amount: Math.round(d.amount) })), + [days], + ); + + const yDomain = useMemo<[number, number]>(() => { + const values = points.map((p) => p.amount); + if (referenceValue != null) values.push(referenceValue); + const max = values.length > 0 ? Math.max(...values) : 1; + return [0, max > 0 ? max * 1.15 : 1]; + }, [points, referenceValue]); + + const animate = !prefersReducedMotion(); + const barColor = "var(--info)"; + + return ( + + + + formatDateShort(dayToDate(day))} + tick={{ fontSize: 11, fill: "var(--muted-foreground)" }} + stroke="var(--border)" + minTickGap={24} + /> + + {referenceValue != null ? ( + + ) : null} + { + const active = props.active ?? false; + const payload = props.payload as + | ReadonlyArray<{ payload?: { day: string; amount: number } }> + | undefined; + const point = payload?.[0]?.payload; + if (!active || !point) { + return ; + } + const rows: RichTooltipRow[] = [ + { + name: valueLabel, + value: `${point.amount} ${unit}`, + color: barColor, + }, + ]; + return ( + + ); + }} + /> + + + + ); +} diff --git a/src/components/insights/insights-layout-shell.tsx b/src/components/insights/insights-layout-shell.tsx index c4e01849a..c4e34fa26 100644 --- a/src/components/insights/insights-layout-shell.tsx +++ b/src/components/insights/insights-layout-shell.tsx @@ -106,6 +106,21 @@ export function InsightsLayoutShell({ children }: { children: ReactNode }) { // dashboard tile so navigation between surfaces is a free cache hit. const workoutsProbe = useWorkouts({ limit: 1 }); + // v1.29 — nutrients-presence gate. The nutrients pill gates on at + // least one `NutrientIntakeDay` row in a 1-day probe window (any + // nutrient, any source). Enabled only when the opt-in module is on — + // the route 403s "module.disabled" otherwise, so probing while off + // would just burn a request every mount. + const nutrientsEnabled = user?.modules?.nutrients === true; + const nutrientsProbe = useQuery({ + queryKey: queryKeys.nutrientIntake(1), + queryFn: () => + apiGet<{ nutrients: Array<{ nutrient: string }> }>( + "/api/nutrients?days=1", + ), + enabled: isAuthenticated && nutrientsEnabled, + }); + // v1.4.31 — memoise the `availability` prop so an unchanged // payload doesn't recreate the object on every cache-write of // analytics or comprehensive. The strip is wrapped in @@ -117,10 +132,18 @@ export function InsightsLayoutShell({ children }: { children: ReactNode }) { const hasMood = (comprehensiveQuery.data?.moodSummary?.count ?? 0) > 0; const hasMedication = (comprehensiveQuery.data?.medications?.length ?? 0) > 0; const hasWorkouts = (workoutsProbe.data?.workouts.length ?? 0) > 0; + const hasNutrients = (nutrientsProbe.data?.nutrients.length ?? 0) > 0; const availability: InsightInputs | undefined = useMemo(() => { if (!isAuthenticated) return undefined; - return { summaries, hasMood, hasMedication, hasWorkouts }; - }, [isAuthenticated, summaries, hasMood, hasMedication, hasWorkouts]); + return { summaries, hasMood, hasMedication, hasWorkouts, hasNutrients }; + }, [ + isAuthenticated, + summaries, + hasMood, + hasMedication, + hasWorkouts, + hasNutrients, + ]); // v1.15.14 W2 — couple the tab strip to the saved insights layout. // A sub-page pill now shows iff its metric has data AND its slug is diff --git a/src/components/insights/insights-tab-strip.tsx b/src/components/insights/insights-tab-strip.tsx index 400a74126..34339ce0b 100644 --- a/src/components/insights/insights-tab-strip.tsx +++ b/src/components/insights/insights-tab-strip.tsx @@ -343,6 +343,8 @@ export const SUB_PAGE_TABS: Record< mood: { labelKey: "insights.navMood", metric: "MOOD" }, // ── events ── medications: { labelKey: "insights.navMedication", metric: "MEDICATION" }, + // v1.29 — nutrient intake (hydration + micronutrients). + nutrients: { labelKey: "insights.navNutrients", metric: "NUTRIENTS" }, }; /** @@ -364,6 +366,9 @@ const SUB_PAGE_MODULE: Partial> = { "breathing-disturbances": "sleep", "blood-glucose": "glucose", workouts: "workouts", + // v1.29 — the nutrients pill gates on the opt-in `nutrients` module on + // top of the `hasNutrients` data floor. + nutrients: "nutrients", }; /** diff --git a/src/components/insights/nutrients/caffeine-card.tsx b/src/components/insights/nutrients/caffeine-card.tsx new file mode 100644 index 000000000..e89733df1 --- /dev/null +++ b/src/components/insights/nutrients/caffeine-card.tsx @@ -0,0 +1,81 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { Coffee } from "lucide-react"; + +import { Card, CardContent, CardHeader } from "@/components/ui/card"; +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 } from "@/lib/api/api-fetch"; +import { queryKeys } from "@/lib/query-keys"; +import type { NutrientDailySeries } from "./types"; + +const WINDOW_DAYS = 30; + +/** + * v1.29 — caffeine card on `/insights/nutrients`. Rendered ONLY when the + * window carries at least one logged day (a query-error also collapses + * to nothing rather than a card the user can do nothing with — the + * hydration card above already carries the surface's error affordance). + * 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. + */ +export function CaffeineCard() { + const { t } = useTranslations(); + const fmt = useFormatters(); + + const { data, isLoading } = useQuery({ + queryKey: queryKeys.nutrientDaily("caffeine", WINDOW_DAYS), + queryFn: () => + apiGet( + `/api/nutrients/daily?nutrient=caffeine&days=${WINDOW_DAYS}`, + ), + }); + + if (isLoading) { + return ( + + + + ); + } + + const hasData = (data?.days ?? []).some((d) => d.amount > 0); + if (!data || !hasData) return null; + + const todayTotal = data.days.at(-1)?.amount ?? 0; + + return ( + + + + + +
+

+ {fmt.integer(Math.round(todayTotal))} {data.unit} +

+ {data.reference ? ( +

+ {t("nutrients.caffeine.ceilingMeta", { + value: fmt.integer(Math.round(data.reference.value)), + unit: data.unit, + })} +

+ ) : null} +
+ +
+
+ ); +} diff --git a/src/components/insights/nutrients/hydration-card.tsx b/src/components/insights/nutrients/hydration-card.tsx new file mode 100644 index 000000000..ed7d30b69 --- /dev/null +++ b/src/components/insights/nutrients/hydration-card.tsx @@ -0,0 +1,110 @@ +"use client"; + +import { useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { GlassWater, Plus } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardHeader } from "@/components/ui/card"; +import { QueryErrorCard } from "@/components/ui/query-error-card"; +import { Skeleton } from "@/components/ui/skeleton"; +import { TileHeader } from "@/components/insights/tile-header"; +import { NutrientDailyBarChartDynamic } from "@/components/charts/nutrient-daily-bar-chart-dynamic"; +import { WaterQuickAddSheet } from "@/components/insights/nutrients/water-quick-add-sheet"; +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"; + +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 + * 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, and the quick-add entry point. No ring, no attainment + * colour — the bar chart with a reference line IS the context + * (UI-STANDARDS: value stays foreground, never coloured by attainment). + */ +export function HydrationCard() { + const { t } = useTranslations(); + const fmt = useFormatters(); + const [sheetOpen, setSheetOpen] = useState(false); + + const { data, isLoading, isError, refetch } = useQuery({ + queryKey: queryKeys.nutrientDaily("water", WINDOW_DAYS), + queryFn: () => + apiGet( + `/api/nutrients/daily?nutrient=water&days=${WINDOW_DAYS}`, + ), + }); + + if (isError) { + return ; + } + + const todayTotal = data?.days.at(-1)?.amount ?? 0; + + return ( + + + setSheetOpen(true)} + data-slot="nutrients-hydration-add" + > + + + {isLoading || !data ? ( + + ) : ( + <> +
+

+ {fmt.integer(Math.round(todayTotal))} {data.unit} +

+ {data.reference ? ( +

+ {t("nutrients.hydration.referenceMeta", { + value: fmt.integer(Math.round(data.reference.value)), + unit: data.unit, + })} +

+ ) : null} +
+ + + )} +
+ +
+ ); +} diff --git a/src/components/insights/nutrients/micronutrients-card.tsx b/src/components/insights/nutrients/micronutrients-card.tsx new file mode 100644 index 000000000..5919d438c --- /dev/null +++ b/src/components/insights/nutrients/micronutrients-card.tsx @@ -0,0 +1,144 @@ +"use client"; + +import { useQuery } from "@tanstack/react-query"; +import { Leaf } from "lucide-react"; + +import { Card, CardContent, CardHeader } from "@/components/ui/card"; +import { EmptyState } from "@/components/ui/empty-state"; +import { Skeleton } from "@/components/ui/skeleton"; +import { TileHeader } from "@/components/insights/tile-header"; +import { useAuth } from "@/hooks/use-auth"; +import { useTranslations, useFormatters } from "@/lib/i18n/context"; +import { apiGet } from "@/lib/api/api-fetch"; +import { queryKeys } from "@/lib/query-keys"; +import { + NUTRIENT_CODES, + isNutrientCode, + resolveNutrientReference, + type NutrientCode, +} from "@/lib/nutrients/catalog"; +import type { NutrientIntakeOverview } from "./types"; + +const WINDOW_DAYS = 30; + +/** Wire `ug` renders as µg; mg / ml pass through. */ +const UNIT_LABELS: Record = { mg: "mg", ug: "µg", ml: "ml" }; + +/** The 24 vitamin/mineral codes — water + caffeine ride their own cards. */ +const MICRONUTRIENT_CODES = NUTRIENT_CODES.filter( + (code) => code !== "water" && code !== "caffeine", +); + +function formatAmount( + fmt: { number: (v: number, d?: number) => string }, + amount: number, +): string { + return fmt.number(Math.round(amount * 10) / 10, 1); +} + +/** + * v1.29 — micronutrients card on `/insights/nutrients`. + * + * 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 + * sparkline in slice 1 — sparse series make sparklines lie. + */ +export function MicronutrientsCard() { + const { t } = useTranslations(); + const fmt = useFormatters(); + const { user } = useAuth(); + const sex = + user?.gender === "MALE" || user?.gender === "FEMALE" ? user.gender : null; + + const { data, isLoading } = useQuery({ + queryKey: queryKeys.nutrientIntake(WINDOW_DAYS), + queryFn: () => + apiGet(`/api/nutrients?days=${WINDOW_DAYS}`), + }); + + const rows = (data?.nutrients ?? []).filter( + (row) => + isNutrientCode(row.nutrient) && + row.nutrient !== "water" && + row.nutrient !== "caffeine", + ); + + return ( + + + + + + {isLoading ? ( + + ) : rows.length === 0 ? ( + } + title={t("nutrients.micronutrients.emptyTitle")} + size="compact" + /> + ) : ( + <> +
    + {rows.map((row) => { + const reference = resolveNutrientReference( + row.nutrient as NutrientCode, + sex, + ); + const unitLabel = UNIT_LABELS[row.unit] ?? row.unit; + return ( +
  • + + {t(`nutrients.names.${row.nutrient}`)} + + + + {formatAmount(fmt, row.latestAmount)} {unitLabel} + + + {reference + ? t("nutrients.micronutrients.rowMeta", { + days: row.daysWithData, + window: WINDOW_DAYS, + value: formatAmount(fmt, reference.value), + unit: unitLabel, + }) + : t("nutrients.micronutrients.rowMetaNoRef", { + days: row.daysWithData, + window: WINDOW_DAYS, + })} + + +
  • + ); + })} +
+

+ {t("nutrients.micronutrients.footer", { + tracked: rows.length, + total: MICRONUTRIENT_CODES.length, + })} +

+ + )} +

+ {t("nutrients.sparseNote")} +

+
+
+ ); +} diff --git a/src/components/insights/nutrients/types.ts b/src/components/insights/nutrients/types.ts new file mode 100644 index 000000000..9e448fba4 --- /dev/null +++ b/src/components/insights/nutrients/types.ts @@ -0,0 +1,35 @@ +/** + * v1.29 — shared client-side DTOs for the `/insights/nutrients` cards. + * Mirror the Zod response schemas in `src/lib/validations/nutrients.ts` + * (`nutrientDailySeriesSchema` / `nutrientOverviewSchema`) — kept as + * plain interfaces here so the client components stay decoupled from + * the server-only Zod module graph. + */ + +export interface ResolvedNutrientReferenceDto { + kind: "PRI" | "AI" | "safeLevel"; + direction: "target" | "upperGuidance"; + value: number; + source: string; +} + +export interface NutrientDailySeries { + nutrient: string; + unit: string; + windowDays: number; + days: Array<{ day: string; amount: number }>; + reference: ResolvedNutrientReferenceDto | null; +} + +export interface NutrientOverviewRow { + nutrient: string; + unit: string; + latestDay: string; + latestAmount: number; + daysWithData: number; +} + +export interface NutrientIntakeOverview { + windowDays: number; + nutrients: NutrientOverviewRow[]; +} diff --git a/src/components/insights/nutrients/water-quick-add-sheet.tsx b/src/components/insights/nutrients/water-quick-add-sheet.tsx new file mode 100644 index 000000000..2b60136cd --- /dev/null +++ b/src/components/insights/nutrients/water-quick-add-sheet.tsx @@ -0,0 +1,177 @@ +"use client"; + +import { useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { toast } from "sonner"; + +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { ResponsiveSheet } from "@/components/ui/responsive-sheet"; +import { useTranslations } from "@/lib/i18n/context"; +import { apiPost } from "@/lib/api/api-fetch"; +import { queryKeys } from "@/lib/query-keys"; + +/** + * v1.29 — manual water quick-add sheet, opened from the hydration card. + * + * Chips (+200/+300/+500 mL) fire immediately (mode "add") and keep the + * sheet open so a run of taps composes one round number; the sheet stays + * a lightweight stepper, not a form the user has to re-open per tap. The + * custom-amount field and the "edit today's total" disclosure both close + * on submit — the two are one-shot actions. + * + * Every write hits `POST /api/nutrients/water`, which owns ONLY the + * `source="MANUAL"` row (migration 0249) — never the Apple-synced row. + */ + +const QUICK_CHIPS_ML = [200, 300, 500] as const; + +interface WaterQuickAddSheetProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** Today's combined (all-source) total, for the "edit total" pre-fill. */ + todayTotalMl: number; +} + +export function WaterQuickAddSheet({ + open, + onOpenChange, + todayTotalMl, +}: WaterQuickAddSheetProps) { + const { t } = useTranslations(); + const queryClient = useQueryClient(); + const [customAmount, setCustomAmount] = useState(""); + const [editMode, setEditMode] = useState(false); + const [editAmount, setEditAmount] = useState(() => String(todayTotalMl)); + + const invalidate = () => { + void queryClient.invalidateQueries({ queryKey: ["nutrients"] }); + void queryClient.invalidateQueries({ + queryKey: queryKeys.dashboardSnapshot(), + }); + }; + + const addMutation = useMutation({ + mutationFn: (amountMl: number) => + apiPost("/api/nutrients/water", { amountMl, mode: "add" as const }), + onSuccess: invalidate, + onError: () => toast.error(t("nutrients.hydration.quickAddError")), + }); + + const setMutation = useMutation({ + mutationFn: (amountMl: number) => + apiPost("/api/nutrients/water", { amountMl, mode: "set" as const }), + onSuccess: () => { + invalidate(); + setEditMode(false); + onOpenChange(false); + }, + onError: () => toast.error(t("nutrients.hydration.quickAddError")), + }); + + const handleCustomAdd = () => { + const amount = Number(customAmount); + if (!Number.isFinite(amount) || amount <= 0) return; + addMutation.mutate(amount); + setCustomAmount(""); + onOpenChange(false); + }; + + const handleEditSave = () => { + const amount = Number(editAmount); + if (!Number.isFinite(amount) || amount < 0) return; + setMutation.mutate(amount); + }; + + return ( + +
+ {QUICK_CHIPS_ML.map((amountMl) => ( + + ))} +
+ +
+
+ + setCustomAmount(e.target.value)} + /> +
+ +
+ + {editMode ? ( +
+ +
+ setEditAmount(e.target.value)} + /> + +
+
+ ) : ( + + )} +
+ ); +} diff --git a/src/lib/insights/metric-availability.ts b/src/lib/insights/metric-availability.ts index 1d8dc20ba..434655e91 100644 --- a/src/lib/insights/metric-availability.ts +++ b/src/lib/insights/metric-availability.ts @@ -119,7 +119,12 @@ export type InsightMetric = | "GRIP_STRENGTH" | "PAIN_NRS" | "WAIST_CIRCUMFERENCE" - | "WAIST_TO_HEIGHT"; + | "WAIST_TO_HEIGHT" + // v1.29 — nutrient intake (hydration + micronutrients). Event/store + // driven (`NutrientIntakeDay`, not a `Measurement` series) like + // `MOOD` / `MEDICATION` / `WORKOUTS`, so it reads the boolean + // `hasNutrients` flag rather than a `summaries[…].count`. + | "NUTRIENTS"; /** * Inputs the gating helper consumes. The `summaries` shape mirrors @@ -141,6 +146,13 @@ export interface InsightInputs { * the helper treats `undefined` as "not available". */ hasWorkouts?: boolean; + /** + * v1.29 — whether the user has at least one `NutrientIntakeDay` row in + * the probe window (any nutrient, any source). Drives the nutrients + * pill. Optional so legacy mounts keep type-checking; the helper + * treats `undefined` as "not available". + */ + hasNutrients?: boolean; } /** @@ -156,6 +168,7 @@ export function hasMetricData( if (metric === "MOOD") return inputs.hasMood; if (metric === "MEDICATION") return inputs.hasMedication; if (metric === "WORKOUTS") return inputs.hasWorkouts === true; + if (metric === "NUTRIENTS") return inputs.hasNutrients === true; if (metric === "BMI") { // BMI is derived from WEIGHT + the profile height. The chart // mounts even at one weight reading; the gate matches. diff --git a/src/lib/insights/sub-page-metric.ts b/src/lib/insights/sub-page-metric.ts index f85ef3454..16180fd6a 100644 --- a/src/lib/insights/sub-page-metric.ts +++ b/src/lib/insights/sub-page-metric.ts @@ -135,6 +135,12 @@ const SUB_PAGE_METRIC = { mood: ["MOOD"], // ── events (medication adherence is event-driven; no measurement series) ── medications: [], + // v1.29 — nutrient intake (hydration + micronutrients). Backed by + // `NutrientIntakeDay`, not a `Measurement` series, so the metric list + // stays empty like `medications` / `workouts`; the tab-strip pill gates + // on `hasNutrients` (threaded from a lightweight probe read) instead of + // a `summaries[…].count`. + nutrients: [], } as const satisfies Record; export type SubPageSlug = keyof typeof SUB_PAGE_METRIC; @@ -305,6 +311,9 @@ const FLAT_SLUG_MANAGER_GROUP: Partial> = { sleep: "sleep", mood: "mood", medications: "events", + // v1.29 — nutrient intake filed with the metabolic cluster (alongside + // blood glucose / skin / wrist temperature). + nutrients: "metabolic", }; /**