mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 07:13:29 +00:00
feat(insights): /insights/nutrients — hydration, caffeine, vitamins
New routed sub-page, gated on the opt-in nutrients module with an in-context enable CTA (the module stays opt-in — the 2026-07-17 consent memo's reasoning holds; this just makes the toggle discoverable instead of buried in Settings): - Hydration card (hero): today's total, a muted EFSA reference-intake line (sex-resolved, omitted when the profile has no sex on file), a 30-day bar chart with a dashed reference line, and quick-add chips (+200/+300/+500 mL + custom + edit-today's-total) in a ResponsiveSheet, POSTing to /api/nutrients/water. - Caffeine card: same anatomy, rendered only when the window has data; the EFSA safe-level reads as a ceiling, never "exceeded" colouring. - Micronutrients card: rows only for the 24 vitamin/mineral codes with data in the window (catalog order), a muted "M of 24 tracked" footer, and one honest sentence that sparse logging isn't a deficiency. Zero rows collapse to a single EmptyState. No ring, no attainment colour anywhere — the bar chart plus its dashed reference line IS the context (UI-STANDARDS: values stay foreground). The bar chart is a new NutrientDailyBarChart, registered in the shared chart-runtime barrel behind its own next/dynamic boundary so recharts stays off the route's first-load JS. Tab-strip wiring: nutrients joins the flat pill set (event/store driven like medications/workouts — a lightweight 1-day probe read drives the pill's data-availability gate, module gate on top). ~20 new i18n keys across en/de/es/fr/it/pl.
This commit is contained in:
1 parent
b396b51d35
commit
16d142762a
19 files changed
+1065
-9
No files matched your search
+31
-1
@@ -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": {
|
||||
|
||||
+31
-1
@@ -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": {
|
||||
|
||||
+31
-1
@@ -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": {
|
||||
|
||||
+31
-1
@@ -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": {
|
||||
|
||||
+31
-1
@@ -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": {
|
||||
|
||||
+31
-1
@@ -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": {
|
||||
|
||||
@@ -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<NutrientIntakeOverview>(`/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 (
|
||||
<SubPageShell title={t("nutrients.page.title")}>
|
||||
<EmptyState
|
||||
icon={<Leaf className="size-6" />}
|
||||
title={t("nutrients.page.moduleOffTitle")}
|
||||
description={t("nutrients.page.moduleOffDescription")}
|
||||
ctaSize="lg"
|
||||
action={
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => enableModule.mutate()}
|
||||
disabled={enableModule.isPending}
|
||||
data-slot="nutrients-enable-module"
|
||||
>
|
||||
{t("nutrients.page.moduleOffCta")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
}
|
||||
|
||||
const hasAnyData = (overview.data?.nutrients.length ?? 0) > 0;
|
||||
if (!overview.isLoading && !hasAnyData) {
|
||||
return (
|
||||
<SubPageShell
|
||||
title={t("nutrients.page.title")}
|
||||
description={t("nutrients.page.description")}
|
||||
>
|
||||
<EmptyState
|
||||
icon={<Leaf className="size-6" />}
|
||||
title={t("nutrients.page.emptyTitle")}
|
||||
description={t("nutrients.page.emptyDescription")}
|
||||
/>
|
||||
</SubPageShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SubPageShell
|
||||
title={t("nutrients.page.title")}
|
||||
description={t("nutrients.page.description")}
|
||||
>
|
||||
<HydrationCard />
|
||||
<CaffeineCard />
|
||||
<MicronutrientsCard />
|
||||
</SubPageShell>
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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 `<NutrientDailyBarChart>`,
|
||||
* 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: () => <ChartSkeleton /> },
|
||||
);
|
||||
|
||||
export function NutrientDailyBarChartDynamic(
|
||||
props: ComponentProps<typeof NutrientDailyBarChartLazy>,
|
||||
): ReactElement {
|
||||
return (
|
||||
<ChartErrorBoundary>
|
||||
<NutrientDailyBarChartLazy {...props} />
|
||||
</ChartErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<ResponsiveContainer width="100%" height={CHART_HEIGHT_PX}>
|
||||
<ComposedChart
|
||||
data={points}
|
||||
margin={{ top: 8, right: 12, bottom: 4, left: 0 }}
|
||||
>
|
||||
<CartesianGrid
|
||||
strokeDasharray="3 3"
|
||||
stroke="var(--border)"
|
||||
vertical={false}
|
||||
/>
|
||||
<XAxis
|
||||
dataKey="day"
|
||||
tickFormatter={(day: string) => formatDateShort(dayToDate(day))}
|
||||
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
|
||||
stroke="var(--border)"
|
||||
minTickGap={24}
|
||||
/>
|
||||
<YAxis
|
||||
domain={yDomain}
|
||||
tick={{ fontSize: 11, fill: "var(--muted-foreground)" }}
|
||||
stroke="var(--border)"
|
||||
width={44}
|
||||
/>
|
||||
{referenceValue != null ? (
|
||||
<ReferenceLine
|
||||
y={referenceValue}
|
||||
stroke="var(--muted-foreground)"
|
||||
strokeOpacity={0.6}
|
||||
strokeDasharray="4 4"
|
||||
/>
|
||||
) : null}
|
||||
<Tooltip
|
||||
content={(props) => {
|
||||
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 <RichChartTooltip active={false} rows={[]} />;
|
||||
}
|
||||
const rows: RichTooltipRow[] = [
|
||||
{
|
||||
name: valueLabel,
|
||||
value: `${point.amount} ${unit}`,
|
||||
color: barColor,
|
||||
},
|
||||
];
|
||||
return (
|
||||
<RichChartTooltip
|
||||
active
|
||||
label={formatDateShort(dayToDate(point.day))}
|
||||
rows={rows}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Bar
|
||||
dataKey="amount"
|
||||
fill={barColor}
|
||||
radius={[2, 2, 0, 0]}
|
||||
isAnimationActive={animate}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<Record<SubPageSlug, ModuleKey>> = {
|
||||
"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",
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -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<NutrientDailySeries>(
|
||||
`/api/nutrients/daily?nutrient=caffeine&days=${WINDOW_DAYS}`,
|
||||
),
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<Card data-slot="nutrients-caffeine-card">
|
||||
<CardContent className="py-6" aria-hidden="true">
|
||||
<Skeleton className="h-[280px] w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const hasData = (data?.days ?? []).some((d) => d.amount > 0);
|
||||
if (!data || !hasData) return null;
|
||||
|
||||
const todayTotal = data.days.at(-1)?.amount ?? 0;
|
||||
|
||||
return (
|
||||
<Card data-slot="nutrients-caffeine-card">
|
||||
<CardHeader>
|
||||
<TileHeader icon={Coffee} title={t("nutrients.names.caffeine")} />
|
||||
</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}
|
||||
</p>
|
||||
{data.reference ? (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("nutrients.caffeine.ceilingMeta", {
|
||||
value: fmt.integer(Math.round(data.reference.value)),
|
||||
unit: data.unit,
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<NutrientDailyBarChartDynamic
|
||||
days={data.days}
|
||||
unit={data.unit}
|
||||
valueLabel={t("nutrients.names.caffeine")}
|
||||
referenceValue={data.reference?.value ?? null}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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<NutrientDailySeries>(
|
||||
`/api/nutrients/daily?nutrient=water&days=${WINDOW_DAYS}`,
|
||||
),
|
||||
});
|
||||
|
||||
if (isError) {
|
||||
return <QueryErrorCard onRetry={refetch} />;
|
||||
}
|
||||
|
||||
const todayTotal = data?.days.at(-1)?.amount ?? 0;
|
||||
|
||||
return (
|
||||
<Card data-slot="nutrients-hydration-card">
|
||||
<CardHeader>
|
||||
<TileHeader
|
||||
icon={GlassWater}
|
||||
title={t("nutrients.names.water")}
|
||||
right={
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setSheetOpen(true)}
|
||||
data-slot="nutrients-hydration-add"
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{t("nutrients.hydration.quickAddTitle")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{isLoading || !data ? (
|
||||
<div className="space-y-3" aria-hidden="true">
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<Skeleton className="h-[240px] w-full" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1">
|
||||
<p
|
||||
className="text-2xl font-bold tabular-nums"
|
||||
data-slot="nutrients-hydration-today"
|
||||
>
|
||||
{fmt.integer(Math.round(todayTotal))} {data.unit}
|
||||
</p>
|
||||
{data.reference ? (
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("nutrients.hydration.referenceMeta", {
|
||||
value: fmt.integer(Math.round(data.reference.value)),
|
||||
unit: data.unit,
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<NutrientDailyBarChartDynamic
|
||||
days={data.days}
|
||||
unit={data.unit}
|
||||
valueLabel={t("nutrients.names.water")}
|
||||
referenceValue={data.reference?.value ?? null}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
<WaterQuickAddSheet
|
||||
open={sheetOpen}
|
||||
onOpenChange={setSheetOpen}
|
||||
todayTotalMl={Math.round(todayTotal)}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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<string, string> = { 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<NutrientIntakeOverview>(`/api/nutrients?days=${WINDOW_DAYS}`),
|
||||
});
|
||||
|
||||
const rows = (data?.nutrients ?? []).filter(
|
||||
(row) =>
|
||||
isNutrientCode(row.nutrient) &&
|
||||
row.nutrient !== "water" &&
|
||||
row.nutrient !== "caffeine",
|
||||
);
|
||||
|
||||
return (
|
||||
<Card data-slot="nutrients-micronutrients-card">
|
||||
<CardHeader>
|
||||
<TileHeader icon={Leaf} title={t("nutrients.micronutrients.title")} />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{isLoading ? (
|
||||
<div className="space-y-1" aria-hidden="true">
|
||||
<Skeleton className="h-9 w-full rounded-md" />
|
||||
<Skeleton className="h-9 w-full rounded-md" />
|
||||
<Skeleton className="h-9 w-full rounded-md" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={<Leaf className="size-6" />}
|
||||
title={t("nutrients.micronutrients.emptyTitle")}
|
||||
size="compact"
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<ul
|
||||
className="divide-border divide-y rounded-md border"
|
||||
role="list"
|
||||
>
|
||||
{rows.map((row) => {
|
||||
const reference = resolveNutrientReference(
|
||||
row.nutrient as NutrientCode,
|
||||
sex,
|
||||
);
|
||||
const unitLabel = UNIT_LABELS[row.unit] ?? row.unit;
|
||||
return (
|
||||
<li
|
||||
key={row.nutrient}
|
||||
data-slot="nutrients-micronutrient-row"
|
||||
className="flex items-baseline justify-between gap-3 p-2"
|
||||
>
|
||||
<span className="text-sm">
|
||||
{t(`nutrients.names.${row.nutrient}`)}
|
||||
</span>
|
||||
<span className="flex flex-col items-end gap-0.5 text-right">
|
||||
<span className="text-sm font-medium tabular-nums">
|
||||
{formatAmount(fmt, row.latestAmount)} {unitLabel}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs tabular-nums">
|
||||
{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,
|
||||
})}
|
||||
</span>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{t("nutrients.micronutrients.footer", {
|
||||
tracked: rows.length,
|
||||
total: MICRONUTRIENT_CODES.length,
|
||||
})}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-muted-foreground text-sm">
|
||||
{t("nutrients.sparseNote")}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -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 (
|
||||
<ResponsiveSheet
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
title={t("nutrients.hydration.quickAddTitle")}
|
||||
>
|
||||
<div className="flex flex-wrap gap-2" data-slot="water-quick-add-chips">
|
||||
{QUICK_CHIPS_ML.map((amountMl) => (
|
||||
<Button
|
||||
key={amountMl}
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={addMutation.isPending}
|
||||
onClick={() => {
|
||||
addMutation.mutate(amountMl);
|
||||
toast.success(`+${amountMl} mL`);
|
||||
}}
|
||||
>
|
||||
+{amountMl} mL
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<div className="flex-1 space-y-1.5">
|
||||
<Label htmlFor="water-custom-amount">
|
||||
{t("nutrients.hydration.quickAddCustomLabel")}
|
||||
</Label>
|
||||
<Input
|
||||
id="water-custom-amount"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
max={20000}
|
||||
placeholder={t("nutrients.hydration.quickAddCustomPlaceholder")}
|
||||
value={customAmount}
|
||||
onChange={(e) => setCustomAmount(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleCustomAdd}
|
||||
disabled={addMutation.isPending || !customAmount}
|
||||
>
|
||||
{t("nutrients.hydration.quickAddSubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{editMode ? (
|
||||
<div className="border-border/70 space-y-1.5 border-t pt-4">
|
||||
<Label htmlFor="water-edit-total">
|
||||
{t("nutrients.hydration.editTotal")}
|
||||
</Label>
|
||||
<div className="flex items-end gap-2">
|
||||
<Input
|
||||
id="water-edit-total"
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
max={20000}
|
||||
className="flex-1"
|
||||
value={editAmount}
|
||||
onChange={(e) => setEditAmount(e.target.value)}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleEditSave}
|
||||
disabled={setMutation.isPending}
|
||||
>
|
||||
{t("nutrients.hydration.quickAddSubmit")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground self-start"
|
||||
onClick={() => {
|
||||
setEditAmount(String(todayTotalMl));
|
||||
setEditMode(true);
|
||||
}}
|
||||
>
|
||||
{t("nutrients.hydration.editTotal")}
|
||||
</Button>
|
||||
)}
|
||||
</ResponsiveSheet>
|
||||
);
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<string, readonly string[]>;
|
||||
|
||||
export type SubPageSlug = keyof typeof SUB_PAGE_METRIC;
|
||||
@@ -305,6 +311,9 @@ const FLAT_SLUG_MANAGER_GROUP: Partial<Record<SubPageSlug, ManagerGroup>> = {
|
||||
sleep: "sleep",
|
||||
mood: "mood",
|
||||
medications: "events",
|
||||
// v1.29 — nutrient intake filed with the metabolic cluster (alongside
|
||||
// blood glucose / skin / wrist temperature).
|
||||
nutrients: "metabolic",
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user