diff --git a/messages/de.json b/messages/de.json index 06ca76108..2b6d4bfb1 100644 --- a/messages/de.json +++ b/messages/de.json @@ -5809,7 +5809,7 @@ "subtitle": "Lege fest, welche Quelle gewinnt, wenn zwei dieselbe Messgröße liefern.", "nutrients": { "title": "Synchronisierte Nährstoffzufuhr", - "description": "Tagessummen der letzten {days} Tage aus Apple Health und den eingenommenen Supplementen.", + "description": "Tagessummen der letzten {days} Tage aus Apple Health oder einem Ernährungstracker und den eingenommenen Supplementen.", "empty": "Noch keine Nährstoffdaten synchronisiert.", "latest": "{amount} {unit} am {date}", "daysWithData": "{count} von {days} Tagen", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Tokens für Messwerte, Trainings, Dokumente und Medikamenten-Einnahme prüfen und widerrufen.", "measurementsToken": { "title": "Messwert-Tokens", - "description": "Erzeuge ein Token, damit eine Waage, eine Uhr oder deine Hausautomatisierung Messwerte und Werte deiner eigenen Metriken eintragen kann.", + "description": "Erzeuge ein Token, damit eine Waage, eine Uhr, ein Ernährungstracker oder deine Hausautomatisierung Messwerte, Werte deiner eigenen Metriken und tägliche Nährstoffsummen eintragen kann.", "detail": "Das Token wird nur einmal angezeigt.", - "scopeNote": "Es kann ausschließlich neue Werte in deine eigene Akte eintragen, auch für eigene Metriken, die du bereits angelegt hast. Es kann deine Daten nicht lesen, keine Metrik anlegen, nichts ändern oder löschen und kein weiteres Token erstellen. Messwerte werden als von einem externen Gerät gekennzeichnet, damit du sie später erkennst; Werte eigener Metriken tragen keine solche Kennzeichnung. Beides lässt sich jederzeit korrigieren. Die ID einer eigenen Metrik ist der Teil nach /custom-metrics/ in der Adresse ihrer Seite.", + "scopeNote": "Es kann ausschließlich neue Werte in deine eigene Akte eintragen, auch für eigene Metriken, die du bereits angelegt hast, und tägliche Nährstoffsummen, solange das Nährstoffe-Modul aktiv ist. Es kann deine Daten nicht lesen, keine Metrik anlegen, nichts ändern oder löschen und kein weiteres Token erstellen. Messwerte und Nährstoffsummen werden als von einem externen Gerät gekennzeichnet, damit du sie später erkennst; Werte eigener Metriken tragen keine solche Kennzeichnung. Messwerte und Werte eigener Metriken kannst du jederzeit selbst korrigieren; einen Nährstofftag korrigiert der Tracker, indem er ihn erneut sendet. Die ID einer eigenen Metrik ist der Teil nach /custom-metrics/ in der Adresse ihrer Seite.", "createFailed": "Das Token konnte nicht erstellt werden. Bitte versuche es erneut.", "namePlaceholder": "Name, z. B. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Nährstoffzufuhr", - "description": "Tägliche Mikronährstoff-Summen aus Apple Health." + "description": "Tägliche Nährstoffsummen aus Apple Health oder einem Ernährungstracker: Wasser, Energie, Makros, Vitamine und Mineralstoffe." }, "vaccinations": { "label": "Impfungen", @@ -12658,15 +12658,24 @@ "water": "Wasser", "caffeine": "Koffein", "dha": "DHA (Omega-3)", - "epa": "EPA (Omega-3)" + "epa": "EPA (Omega-3)", + "energy": "Energie", + "protein": "Eiweiß", + "carbohydrates": "Kohlenhydrate", + "fat": "Fett", + "sugar": "Zucker", + "fiber": "Ballaststoffe", + "sodium": "Natrium", + "potassium": "Kalium", + "alcohol": "Alkohol" }, "page": { "title": "Nährstoffaufnahme", - "description": "Flüssigkeits- und Vitamin-/Mineralstoffaufnahme aus der Gesundheits-App deines Telefons, plus manuelle Wassereinträge.", - "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.", + "description": "Wasser, Energie, Makros, Vitamine und Mineralstoffe aus deiner Gesundheits-App oder einem Ernährungstracker, plus manuelle Wassereinträge.", + "moduleOffDescription": "Aktiviere das Nährstoffe-Modul, um Flüssigkeit, Energie, Makronährstoffe und Vitamin-/Mineralstoffaufnahme hier zu sehen. Synchronisierte Werte werden Teil der Aufzeichnung, die der Coach lesen kann.", "moduleOffCta": "Nährstoffe aktivieren", "emptyTitle": "Noch keine Nährstoffdaten", - "emptyDescription": "Daten kommen aus der Synchronisierung der Gesundheits-App deines Telefons oder einem manuellen Wassereintrag.", + "emptyDescription": "Daten kommen aus der Synchronisierung der Gesundheits-App deines Telefons, von einem Ernährungstracker mit Messwert-Token oder aus einem manuellen Wassereintrag.", "loadError": "Deine Nährstoffdaten konnten nicht geladen werden", "lastAttemptTitle": "Eine Synchronisierung ist angekommen, aber nichts konnte gespeichert werden", "lastAttemptAt": "Letzter Versuch: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Richtwert {value} {unit}/Tag (EFSA)", + "referenceMeta": "Richtwert {value} {unit}/Tag ({authority})", "loadError": "Wasser konnte nicht geladen werden." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitamine & Mineralstoffe", - "rowMeta": "{days} von {window} Tagen, Richtwert {value} {unit} (EFSA)", + "rowMeta": "{days} von {window} Tagen, Richtwert {value} {unit} ({authority})", "rowMetaNoRef": "{days} von {window} Tagen", "footer": "{tracked} von {total} erfassten Mikronährstoffen haben Daten in diesem Zeitraum.", "emptyTitle": "Noch keine Mikronährstoffdaten synchronisiert", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "Die Höchstmenge ist für Alpha-Tocopherol festgelegt." } }, - "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.", + "sparseNote": "Ein niedriger Wert bedeutet hier meist lückenhafte Erfassung, keinen Mangel. Die Tagessummen spiegeln wider, was deine Apps erfasst haben, nicht die gesamte Nahrungsaufnahme. Melden ein Tracker und Apple Health denselben Tag, zählt die größere Summe.", "units": { "IU": "IE" }, "sources": { "APPLE_HEALTH": "Synchronisiert", "MANUAL": "Eingetragen", - "SUPPLEMENT": "Präparate" + "SUPPLEMENT": "Präparate", + "EXTERNAL": "Extern", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energie & Makronährstoffe", + "short": { + "energy": "Energie", + "protein": "Eiweiß", + "carbohydrates": "KH", + "fat": "Fett", + "sugar": "Zucker", + "fiber": "Ballaststoffe" + }, + "pickLabel": "Nährstoff", + "referenceMeta": "Richtwert {value} {unit}/Tag ({authority})", + "targetMeta": "Dein Ziel {value} {unit}/Tag", + "limitMeta": "Deine Obergrenze {value} {unit}/Tag", + "setTarget": "Ziel setzen", + "editTarget": "Ziel ändern", + "clearTarget": "Ziel entfernen", + "targetLabel": "{name} pro Tag in {unit}", + "directionLabel": "Art des Ziels", + "directionTarget": "Mindestens erreichen", + "directionLimit": "Darunter bleiben", + "saveFailed": "Das Ziel konnte nicht gespeichert werden. Bitte versuche es erneut.", + "loadError": "Energie und Makronährstoffe konnten nicht geladen werden." + }, + "alcohol": { + "loadError": "Alkohol konnte nicht geladen werden." } }, "daily": { diff --git a/messages/en.json b/messages/en.json index bc4d11216..c090cbbb8 100644 --- a/messages/en.json +++ b/messages/en.json @@ -5809,7 +5809,7 @@ "subtitle": "Decide which source wins when two report the same metric.", "nutrients": { "title": "Synced nutrient intake", - "description": "Daily totals over the last {days} days: what Apple Health synced plus the supplements you took.", + "description": "Daily totals over the last {days} days: what Apple Health or a food tracker synced plus the supplements you took.", "empty": "No nutrient data has been synced yet.", "latest": "{amount} {unit} on {date}", "daysWithData": "{count} of {days} days", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Review and revoke tokens for measurements, workouts, documents and medication intake.", "measurementsToken": { "title": "Measurement tokens", - "description": "Mint a token so a scale, a watch bridge or your home automation can add readings and custom-metric values.", + "description": "Mint a token so a scale, a watch bridge, a food tracker or your home automation can add readings, custom-metric values and daily nutrient totals.", "detail": "The token is shown once.", - "scopeNote": "It can only add new readings to your own record, and values to custom metrics you already created. It cannot read your data, create a custom metric, change or delete anything, or create another token. Readings are marked as coming from an external device, so you can tell them apart later; custom-metric values carry no such mark. You can still correct both yourself. A custom metric's ID is the part after /custom-metrics/ in the address of its page.", + "scopeNote": "It can only add new readings to your own record, values to custom metrics you already created, and daily nutrient totals while the nutrients module is on. It cannot read your data, create a custom metric, change or delete anything, or create another token. Readings and nutrient totals are marked as coming from an external device, so you can tell them apart later; custom-metric values carry no such mark. You can still correct readings and custom-metric values yourself; a tracker corrects a nutrient day by sending it again. A custom metric's ID is the part after /custom-metrics/ in the address of its page.", "createFailed": "The token could not be created. Please try again.", "namePlaceholder": "Name, e.g. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Nutrient intake", - "description": "Daily micronutrient totals synced from Apple Health." + "description": "Daily nutrient totals from Apple Health or a food tracker: water, energy, macros, vitamins and minerals." }, "vaccinations": { "label": "Vaccinations", @@ -12658,15 +12658,24 @@ "water": "Water", "caffeine": "Caffeine", "dha": "DHA (omega-3)", - "epa": "EPA (omega-3)" + "epa": "EPA (omega-3)", + "energy": "Energy", + "protein": "Protein", + "carbohydrates": "Carbohydrates", + "fat": "Fat", + "sugar": "Sugar", + "fiber": "Fiber", + "sodium": "Sodium", + "potassium": "Potassium", + "alcohol": "Alcohol" }, "page": { "title": "Nutrient intake", - "description": "Hydration and vitamin/mineral intake synced from your phone's health app, plus manual water entries.", - "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.", + "description": "Water, energy, macros, vitamins and minerals from your health app or a food tracker, plus manual water entries.", + "moduleOffDescription": "Turn on the nutrients module to see hydration, energy, macronutrients 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.", + "emptyDescription": "Data arrives from your phone's health app sync, a food tracker with a measurement token, or a manual water entry.", "loadError": "Your nutrient data could not be loaded", "lastAttemptTitle": "A sync arrived, but nothing could be stored", "lastAttemptAt": "Last attempt: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Reference intake {value} {unit}/day (EFSA)", + "referenceMeta": "Reference intake {value} {unit}/day ({authority})", "loadError": "Could not load water." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitamins & minerals", - "rowMeta": "{days} of {window} days, ref {value} {unit} (EFSA)", + "rowMeta": "{days} of {window} days, ref {value} {unit} ({authority})", "rowMetaNoRef": "{days} of {window} days", "footer": "{tracked} of {total} tracked micronutrients have data in this window.", "emptyTitle": "No micronutrient data synced yet", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "The level is set for alpha-tocopherol." } }, - "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.", + "sparseNote": "A low number here usually means sparse logging, not a deficiency. Day totals reflect what your apps logged, not total dietary intake. When a tracker and Apple Health report the same day, the larger total counts.", "units": { "IU": "IU" }, "sources": { "APPLE_HEALTH": "Synced", "MANUAL": "Entered", - "SUPPLEMENT": "Supplements" + "SUPPLEMENT": "Supplements", + "EXTERNAL": "External", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energy & macronutrients", + "short": { + "energy": "Energy", + "protein": "Protein", + "carbohydrates": "Carbs", + "fat": "Fat", + "sugar": "Sugar", + "fiber": "Fiber" + }, + "pickLabel": "Nutrient", + "referenceMeta": "Reference {value} {unit}/day ({authority})", + "targetMeta": "Your target {value} {unit}/day", + "limitMeta": "Your limit {value} {unit}/day", + "setTarget": "Set target", + "editTarget": "Edit target", + "clearTarget": "Remove target", + "targetLabel": "Daily {name} in {unit}", + "directionLabel": "Kind of target", + "directionTarget": "Reach at least", + "directionLimit": "Stay under", + "saveFailed": "The target could not be saved. Please try again.", + "loadError": "Could not load energy and macronutrients." + }, + "alcohol": { + "loadError": "Could not load alcohol." } }, "daily": { diff --git a/messages/es.json b/messages/es.json index 41be21086..9c4e28679 100644 --- a/messages/es.json +++ b/messages/es.json @@ -5809,7 +5809,7 @@ "subtitle": "Decide qué fuente prevalece cuando dos informan la misma métrica.", "nutrients": { "title": "Ingesta de nutrientes sincronizada", - "description": "Totales diarios de los últimos {days} días: lo que sincronizó Apple Health más los suplementos que tomaste.", + "description": "Totales diarios de los últimos {days} días: lo que sincronizó Apple Health o una app de nutrición más los suplementos que tomaste.", "empty": "Todavía no se han sincronizado datos de nutrientes.", "latest": "{amount} {unit} el {date}", "daysWithData": "{count} de {days} días", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Revisa y revoca los tokens de mediciones, entrenamientos, documentos y tomas de medicación.", "measurementsToken": { "title": "Tokens de mediciones", - "description": "Crea un token para que una báscula, un reloj o tu domótica añadan mediciones y valores de tus métricas personalizadas.", + "description": "Crea un token para que una báscula, un reloj, una app de nutrición o tu domótica añadan mediciones, valores de tus métricas personalizadas y totales diarios de nutrientes.", "detail": "El token se muestra una sola vez.", - "scopeNote": "Solo puede añadir mediciones nuevas a tu propio historial y valores a las métricas personalizadas que ya creaste: no puede leer tus datos, ni crear una métrica, ni modificar o borrar nada, ni crear otro token. Las mediciones se marcan como procedentes de un dispositivo externo, así las distingues más tarde; los valores de las métricas personalizadas no llevan esa marca. Puedes corregir ambos igualmente. El ID de una métrica personalizada es la parte que sigue a /custom-metrics/ en la dirección de su página.", + "scopeNote": "Solo puede añadir mediciones nuevas a tu propio historial, valores a las métricas personalizadas que ya creaste y totales diarios de nutrientes mientras el módulo de nutrientes esté activado: no puede leer tus datos, ni crear una métrica, ni modificar o borrar nada, ni crear otro token. Las mediciones y los totales de nutrientes se marcan como procedentes de un dispositivo externo, así los distingues más tarde; los valores de las métricas personalizadas no llevan esa marca. Puedes seguir corrigiendo tú mismo las mediciones y los valores de las métricas; una app de nutrición corrige un día volviendo a enviarlo. El ID de una métrica personalizada es la parte que sigue a /custom-metrics/ en la dirección de su página.", "createFailed": "No se pudo crear el token. Inténtalo de nuevo.", "namePlaceholder": "Nombre, p. ej. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Ingesta de nutrientes", - "description": "Totales diarios de micronutrientes sincronizados desde Apple Health." + "description": "Totales diarios de nutrientes desde Apple Health o una app de nutrición: agua, energía, macros, vitaminas y minerales." }, "vaccinations": { "label": "Vacunas", @@ -12658,15 +12658,24 @@ "water": "Agua", "caffeine": "Cafeína", "dha": "DHA (ácido graso omega-3)", - "epa": "EPA (ácido graso omega-3)" + "epa": "EPA (ácido graso omega-3)", + "energy": "Energía", + "protein": "Proteínas", + "carbohydrates": "Carbohidratos", + "fat": "Grasas", + "sugar": "Azúcares", + "fiber": "Fibra", + "sodium": "Sodio", + "potassium": "Potasio", + "alcohol": "Alcohol" }, "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.", - "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.", + "description": "Agua, energía, macros, vitaminas y minerales desde tu app de salud o una app de nutrición, más entradas manuales de agua.", + "moduleOffDescription": "Activa el módulo de nutrientes para ver aquí la hidratación, la energía, los macronutrientes y la ingesta de vitaminas/minerales. Los datos sincronizados pasarán a formar parte del registro que el Coach puede leer.", "moduleOffCta": "Activar nutrientes", "emptyTitle": "Aún no hay datos de nutrientes", - "emptyDescription": "Los datos llegan desde la sincronización de la app de salud de tu teléfono o desde una entrada manual de agua.", + "emptyDescription": "Los datos llegan desde la sincronización de la app de salud de tu teléfono, desde una app de nutrición con un token de mediciones o desde una entrada manual de agua.", "loadError": "No se pudieron cargar tus datos de nutrientes", "lastAttemptTitle": "Se recibió una sincronización, pero no se pudo guardar nada", "lastAttemptAt": "Último intento: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Ingesta de referencia {value} {unit}/día (EFSA)", + "referenceMeta": "Ingesta de referencia {value} {unit}/día ({authority})", "loadError": "No se pudo cargar el agua." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitaminas y minerales", - "rowMeta": "{days} de {window} días, ref. {value} {unit} (EFSA)", + "rowMeta": "{days} de {window} días, ref. {value} {unit} ({authority})", "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", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "El nivel está fijado para el alfa-tocoferol." } }, - "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.", + "sparseNote": "Un valor bajo aquí suele significar un registro escaso, no una deficiencia: los totales diarios reflejan lo que registraron tus apps, no la ingesta dietética total. Cuando una app de nutrición y Apple Health informan del mismo día, cuenta el total mayor.", "units": { "IU": "UI" }, "sources": { "APPLE_HEALTH": "Sincronizado", "MANUAL": "Introducido", - "SUPPLEMENT": "Suplementos" + "SUPPLEMENT": "Suplementos", + "EXTERNAL": "Externo", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energía y macronutrientes", + "short": { + "energy": "Energía", + "protein": "Proteínas", + "carbohydrates": "Carbos", + "fat": "Grasas", + "sugar": "Azúcares", + "fiber": "Fibra" + }, + "pickLabel": "Nutriente", + "referenceMeta": "Referencia {value} {unit}/día ({authority})", + "targetMeta": "Tu objetivo {value} {unit}/día", + "limitMeta": "Tu límite {value} {unit}/día", + "setTarget": "Fijar objetivo", + "editTarget": "Cambiar objetivo", + "clearTarget": "Quitar objetivo", + "targetLabel": "{name} al día en {unit}", + "directionLabel": "Tipo de objetivo", + "directionTarget": "Alcanzar al menos", + "directionLimit": "Quedarse por debajo", + "saveFailed": "No se pudo guardar el objetivo. Inténtalo de nuevo.", + "loadError": "No se pudieron cargar la energía y los macronutrientes." + }, + "alcohol": { + "loadError": "No se pudo cargar el alcohol." } }, "daily": { diff --git a/messages/fr.json b/messages/fr.json index 84226f8ee..c0eb9796b 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -5809,7 +5809,7 @@ "subtitle": "Choisissez la source prioritaire en cas de doublon de mesure.", "nutrients": { "title": "Apports en nutriments synchronisés", - "description": "Totaux quotidiens sur les {days} derniers jours : ce qu’Apple Health a synchronisé, plus les compléments que vous avez pris.", + "description": "Totaux quotidiens sur les {days} derniers jours : ce qu’Apple Health ou une appli de suivi alimentaire a synchronisé, plus les compléments que vous avez pris.", "empty": "Aucune donnée de nutriments synchronisée pour l'instant.", "latest": "{amount} {unit} le {date}", "daysWithData": "{count} jours sur {days}", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Consultez et révoquez les jetons des mesures, entraînements, documents et prises de médicaments.", "measurementsToken": { "title": "Jetons de mesures", - "description": "Créez un jeton pour qu'une balance, une montre ou votre domotique ajoutent des mesures et des valeurs à vos mesures personnalisées.", + "description": "Créez un jeton pour qu'une balance, une montre, une appli de suivi alimentaire ou votre domotique ajoutent des mesures, des valeurs à vos mesures personnalisées et des totaux quotidiens de nutriments.", "detail": "Le jeton n'est affiché qu'une fois.", - "scopeNote": "Il peut uniquement ajouter de nouvelles mesures à votre propre dossier, ainsi que des valeurs aux mesures personnalisées que vous avez déjà créées : il ne peut pas lire vos données, ni créer une mesure personnalisée, ni modifier ou supprimer quoi que ce soit, ni créer un autre jeton. Les mesures sont signalées comme provenant d'un appareil externe, ce qui vous permet de les reconnaître plus tard ; les valeurs des mesures personnalisées ne portent pas cette marque. Vous pouvez toujours corriger les unes comme les autres. L'identifiant d'une mesure personnalisée est la partie qui suit /custom-metrics/ dans l'adresse de sa page.", + "scopeNote": "Il peut uniquement ajouter de nouvelles mesures à votre propre dossier, des valeurs aux mesures personnalisées que vous avez déjà créées et des totaux quotidiens de nutriments tant que le module nutriments est activé : il ne peut pas lire vos données, ni créer une mesure personnalisée, ni modifier ou supprimer quoi que ce soit, ni créer un autre jeton. Les mesures et les totaux de nutriments sont signalés comme provenant d'un appareil externe, ce qui vous permet de les reconnaître plus tard ; les valeurs des mesures personnalisées ne portent pas cette marque. Vous pouvez toujours corriger vous-même les mesures et les valeurs personnalisées ; une appli de suivi corrige un jour de nutriments en l'envoyant à nouveau. L'identifiant d'une mesure personnalisée est la partie qui suit /custom-metrics/ dans l'adresse de sa page.", "createFailed": "Le jeton n'a pas pu être créé. Veuillez réessayer.", "namePlaceholder": "Nom, p. ex. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Apports en nutriments", - "description": "Totaux quotidiens de micronutriments synchronisés depuis Apple Health." + "description": "Totaux quotidiens de nutriments depuis Apple Health ou une appli de suivi alimentaire : eau, énergie, macros, vitamines et minéraux." }, "vaccinations": { "label": "Vaccinations", @@ -12658,15 +12658,24 @@ "water": "Eau", "caffeine": "Caféine", "dha": "DHA (oméga-3)", - "epa": "EPA (oméga-3)" + "epa": "EPA (oméga-3)", + "energy": "Énergie", + "protein": "Protéines", + "carbohydrates": "Glucides", + "fat": "Lipides", + "sugar": "Sucres", + "fiber": "Fibres", + "sodium": "Sodium", + "potassium": "Potassium", + "alcohol": "Alcool" }, "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.", - "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.", + "description": "Eau, énergie, macros, vitamines et minéraux depuis votre appli santé ou une appli de suivi alimentaire, plus les saisies d'eau.", + "moduleOffDescription": "Activez le module nutriments pour voir ici l'hydratation, l'énergie, les macronutriments et les apports en vitamines/minéraux. Les données synchronisées feront partie du dossier que le Coach peut lire.", "moduleOffCta": "Activer les nutriments", "emptyTitle": "Pas encore de données nutritionnelles", - "emptyDescription": "Les données proviennent de la synchronisation de l'appli santé de votre téléphone ou d'une saisie manuelle d'eau.", + "emptyDescription": "Les données proviennent de la synchronisation de l'appli santé de votre téléphone, d'une appli de suivi alimentaire munie d'un jeton de mesures ou d'une saisie manuelle d'eau.", "loadError": "Vos données de nutriments n'ont pas pu être chargées", "lastAttemptTitle": "Une synchronisation est arrivée, mais rien n'a pu être enregistré", "lastAttemptAt": "Dernière tentative : {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Apport de référence {value} {unit}/jour (EFSA)", + "referenceMeta": "Apport de référence {value} {unit}/jour ({authority})", "loadError": "Impossible de charger l'eau." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitamines et minéraux", - "rowMeta": "{days} sur {window} jours, réf. {value} {unit} (EFSA)", + "rowMeta": "{days} sur {window} jours, réf. {value} {unit} ({authority})", "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", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "La limite est fixée pour l'alpha-tocophérol." } }, - "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.", + "sparseNote": "Une valeur basse ici signifie généralement un suivi partiel, pas une carence : les totaux journaliers reflètent ce que vos applis ont enregistré, pas l'apport alimentaire total. Quand une appli de suivi et Apple Health indiquent le même jour, c'est le total le plus élevé qui compte.", "units": { "IU": "UI" }, "sources": { "APPLE_HEALTH": "Synchronisé", "MANUAL": "Saisi", - "SUPPLEMENT": "Compléments" + "SUPPLEMENT": "Compléments", + "EXTERNAL": "Externe", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Énergie et macronutriments", + "short": { + "energy": "Énergie", + "protein": "Protéines", + "carbohydrates": "Glucides", + "fat": "Lipides", + "sugar": "Sucres", + "fiber": "Fibres" + }, + "pickLabel": "Nutriment", + "referenceMeta": "Référence {value} {unit}/jour ({authority})", + "targetMeta": "Votre objectif {value} {unit}/jour", + "limitMeta": "Votre limite {value} {unit}/jour", + "setTarget": "Définir un objectif", + "editTarget": "Modifier l'objectif", + "clearTarget": "Supprimer l'objectif", + "targetLabel": "{name} par jour en {unit}", + "directionLabel": "Type d'objectif", + "directionTarget": "Atteindre au moins", + "directionLimit": "Rester en dessous", + "saveFailed": "L'objectif n'a pas pu être enregistré. Veuillez réessayer.", + "loadError": "Impossible de charger l'énergie et les macronutriments." + }, + "alcohol": { + "loadError": "Impossible de charger l'alcool." } }, "daily": { diff --git a/messages/it.json b/messages/it.json index 506eb23f8..652bf1d60 100644 --- a/messages/it.json +++ b/messages/it.json @@ -5809,7 +5809,7 @@ "subtitle": "Decidi quale fonte prevale quando due riportano la stessa metrica.", "nutrients": { "title": "Assunzione di nutrienti sincronizzata", - "description": "Totali giornalieri degli ultimi {days} giorni: quanto sincronizzato da Apple Health più gli integratori che hai assunto.", + "description": "Totali giornalieri degli ultimi {days} giorni: quanto sincronizzato da Apple Health o da un'app per l'alimentazione più gli integratori che hai assunto.", "empty": "Nessun dato sui nutrienti ancora sincronizzato.", "latest": "{amount} {unit} il {date}", "daysWithData": "{count} giorni su {days}", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Rivedi e revoca i token per misurazioni, allenamenti, documenti e assunzioni di farmaci.", "measurementsToken": { "title": "Token per misurazioni", - "description": "Crea un token perché una bilancia, un orologio o la tua domotica aggiungano misurazioni e valori delle tue metriche personalizzate.", + "description": "Crea un token perché una bilancia, un orologio, un'app per l'alimentazione o la tua domotica aggiungano misurazioni, valori delle tue metriche personalizzate e totali giornalieri di nutrienti.", "detail": "Il token viene mostrato una sola volta.", - "scopeNote": "Può soltanto aggiungere nuove misurazioni alla tua cartella e valori alle metriche personalizzate che hai già creato: non può leggere i tuoi dati, creare una metrica, modificare o eliminare nulla, né creare un altro token. Le misurazioni vengono contrassegnate come provenienti da un dispositivo esterno, così le riconosci in seguito; i valori delle metriche personalizzate non hanno questo contrassegno. Puoi comunque correggere entrambi. L'ID di una metrica personalizzata è la parte che segue /custom-metrics/ nell'indirizzo della sua pagina.", + "scopeNote": "Può soltanto aggiungere nuove misurazioni alla tua cartella, valori alle metriche personalizzate che hai già creato e totali giornalieri di nutrienti finché il modulo nutrienti è attivo: non può leggere i tuoi dati, creare una metrica, modificare o eliminare nulla, né creare un altro token. Le misurazioni e i totali di nutrienti vengono contrassegnati come provenienti da un dispositivo esterno, così li riconosci in seguito; i valori delle metriche personalizzate non hanno questo contrassegno. Misurazioni e valori delle metriche puoi sempre correggerli tu; un'app per l'alimentazione corregge un giorno inviandolo di nuovo. L'ID di una metrica personalizzata è la parte che segue /custom-metrics/ nell'indirizzo della sua pagina.", "createFailed": "Non è stato possibile creare il token. Riprova.", "namePlaceholder": "Nome, ad es. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Assunzione di nutrienti", - "description": "Totali giornalieri di micronutrienti sincronizzati da Apple Health." + "description": "Totali giornalieri di nutrienti da Apple Health o da un'app per l'alimentazione: acqua, energia, macro, vitamine e minerali." }, "vaccinations": { "label": "Vaccinazioni", @@ -12658,15 +12658,24 @@ "water": "Acqua", "caffeine": "Caffeina", "dha": "DHA (acido grasso omega-3)", - "epa": "EPA (acido grasso omega-3)" + "epa": "EPA (acido grasso omega-3)", + "energy": "Energia", + "protein": "Proteine", + "carbohydrates": "Carboidrati", + "fat": "Grassi", + "sugar": "Zuccheri", + "fiber": "Fibre", + "sodium": "Sodio", + "potassium": "Potassio", + "alcohol": "Alcol" }, "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.", - "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.", + "description": "Acqua, energia, macro, vitamine e minerali dall'app salute o da un'app per l'alimentazione, più l'acqua inserita a mano.", + "moduleOffDescription": "Attiva il modulo nutrienti per vedere qui idratazione, energia, macronutrienti 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.", + "emptyDescription": "I dati arrivano dalla sincronizzazione dell'app salute del telefono, da un'app per l'alimentazione con un token di misurazione o da una voce di acqua inserita manualmente.", "loadError": "Non è stato possibile caricare i tuoi dati sui nutrienti", "lastAttemptTitle": "È arrivata una sincronizzazione, ma non è stato possibile salvare nulla", "lastAttemptAt": "Ultimo tentativo: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Apporto di riferimento {value} {unit}/giorno (EFSA)", + "referenceMeta": "Apporto di riferimento {value} {unit}/giorno ({authority})", "loadError": "Impossibile caricare l'acqua." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitamine e minerali", - "rowMeta": "{days} di {window} giorni, rif. {value} {unit} (EFSA)", + "rowMeta": "{days} di {window} giorni, rif. {value} {unit} ({authority})", "rowMetaNoRef": "{days} di {window} giorni", "footer": "{tracked} di {total} micronutrienti monitorati hanno dati in questo periodo.", "emptyTitle": "Nessun dato sui micronutrienti ancora sincronizzato", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "Il livello è fissato per l'alfa-tocoferolo." } }, - "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.", + "sparseNote": "Un valore basso qui di solito indica una registrazione poco frequente, non una carenza: i totali giornalieri riflettono ciò che le tue app hanno registrato, non l'apporto alimentare totale. Quando un'app per l'alimentazione e Apple Health riportano lo stesso giorno, conta il totale più alto.", "units": { "IU": "UI" }, "sources": { "APPLE_HEALTH": "Sincronizzato", "MANUAL": "Inserito", - "SUPPLEMENT": "Integratori" + "SUPPLEMENT": "Integratori", + "EXTERNAL": "Esterno", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energia e macronutrienti", + "short": { + "energy": "Energia", + "protein": "Proteine", + "carbohydrates": "Carboidrati", + "fat": "Grassi", + "sugar": "Zuccheri", + "fiber": "Fibre" + }, + "pickLabel": "Nutriente", + "referenceMeta": "Riferimento {value} {unit}/giorno ({authority})", + "targetMeta": "Il tuo obiettivo {value} {unit}/giorno", + "limitMeta": "Il tuo limite {value} {unit}/giorno", + "setTarget": "Imposta obiettivo", + "editTarget": "Modifica obiettivo", + "clearTarget": "Rimuovi obiettivo", + "targetLabel": "{name} al giorno in {unit}", + "directionLabel": "Tipo di obiettivo", + "directionTarget": "Raggiungere almeno", + "directionLimit": "Restare sotto", + "saveFailed": "Non è stato possibile salvare l'obiettivo. Riprova.", + "loadError": "Impossibile caricare energia e macronutrienti." + }, + "alcohol": { + "loadError": "Impossibile caricare l'alcol." } }, "daily": { diff --git a/messages/ko.json b/messages/ko.json index 89fe1732c..4c3669292 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -5809,7 +5809,7 @@ "subtitle": "같은 지표를 두 소스가 보낼 때 어느 쪽을 쓸지 정해요.", "nutrients": { "title": "동기화된 영양 섭취", - "description": "최근 {days}일간의 하루 합계예요. Apple Health에서 동기화한 값에 복용한 보충제가 더해져요.", + "description": "최근 {days}일간의 하루 합계예요. Apple Health나 식단 기록 앱에서 동기화한 값에 복용한 보충제가 더해져요.", "empty": "아직 동기화된 영양 데이터가 없어요.", "latest": "{date}에 {amount} {unit}", "daysWithData": "{days}일 중 {count}일", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "측정값, 운동, 문서, 복용 기록용 토큰을 확인하고 폐기해요.", "measurementsToken": { "title": "측정 토큰", - "description": "체중계나 시계, 홈 오토메이션이 측정값과 사용자 지표 값을 기록할 수 있도록 토큰을 만들어요.", + "description": "체중계나 시계, 식단 기록 앱, 홈 오토메이션이 측정값, 사용자 지표 값, 하루 영양소 합계를 기록할 수 있도록 토큰을 만들어요.", "detail": "토큰은 한 번만 표시돼요.", - "scopeNote": "본인 기록에 새 측정값을 추가하고, 이미 만든 사용자 지표에 값을 추가하는 것만 할 수 있어요. 데이터를 읽거나, 사용자 지표를 만들거나, 무언가를 고치거나 지우거나, 다른 토큰을 만들 수는 없어요. 측정값은 외부 기기에서 온 것으로 표시되어 나중에 구분할 수 있지만, 사용자 지표 값에는 이런 표시가 없어요. 둘 다 언제든 고칠 수 있어요. 사용자 지표의 ID는 해당 지표 페이지 주소에서 /custom-metrics/ 뒤에 오는 부분이에요.", + "scopeNote": "본인 기록에 새 측정값을 추가하고, 이미 만든 사용자 지표에 값을 추가하고, 영양소 모듈이 켜져 있는 동안 하루 영양소 합계를 추가하는 것만 할 수 있어요. 데이터를 읽거나, 사용자 지표를 만들거나, 무언가를 고치거나 지우거나, 다른 토큰을 만들 수는 없어요. 측정값과 영양소 합계는 외부 기기에서 온 것으로 표시되어 나중에 구분할 수 있지만, 사용자 지표 값에는 이런 표시가 없어요. 측정값과 사용자 지표 값은 언제든 직접 고칠 수 있고, 영양소 하루 합계는 식단 기록 앱이 다시 보내서 고쳐요. 사용자 지표의 ID는 해당 지표 페이지 주소에서 /custom-metrics/ 뒤에 오는 부분이에요.", "createFailed": "토큰을 만들지 못했어요. 다시 시도해 주세요.", "namePlaceholder": "이름 (예: Home Assistant)", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "영양소 섭취", - "description": "Apple Health에서 동기화한 하루 미량영양소 합계." + "description": "Apple Health나 식단 기록 앱의 하루 영양소 합계: 수분, 에너지, 다량영양소, 비타민, 미네랄." }, "vaccinations": { "label": "예방접종", @@ -12658,15 +12658,24 @@ "water": "수분", "caffeine": "카페인", "dha": "DHA (오메가-3)", - "epa": "EPA (오메가-3)" + "epa": "EPA (오메가-3)", + "energy": "에너지", + "protein": "단백질", + "carbohydrates": "탄수화물", + "fat": "지방", + "sugar": "당류", + "fiber": "식이섬유", + "sodium": "나트륨", + "potassium": "칼륨", + "alcohol": "알코올" }, "page": { "title": "영양소 섭취", - "description": "휴대폰 건강 앱에서 동기화된 수분·비타민/미네랄 섭취량과 직접 입력한 수분 기록이에요.", - "moduleOffDescription": "영양소 모듈을 켜면 수분과 비타민/미네랄 섭취량을 여기서 볼 수 있어요. 동기화된 섭취량은 코치가 읽는 기록에 포함돼요.", + "description": "건강 앱이나 식단 기록 앱의 수분·에너지·다량영양소·비타민·미네랄과 직접 입력한 수분 기록이에요.", + "moduleOffDescription": "영양소 모듈을 켜면 수분, 에너지, 다량영양소, 비타민/미네랄 섭취량을 여기서 볼 수 있어요. 동기화된 섭취량은 코치가 읽는 기록에 포함돼요.", "moduleOffCta": "영양소 켜기", "emptyTitle": "아직 영양소 데이터가 없어요", - "emptyDescription": "휴대폰 건강 앱 동기화나 직접 입력한 수분 기록에서 데이터가 들어와요.", + "emptyDescription": "휴대폰 건강 앱 동기화, 측정값 토큰을 쓰는 식단 기록 앱, 또는 직접 입력한 수분 기록에서 데이터가 들어와요.", "loadError": "영양소 데이터를 불러오지 못했어요", "lastAttemptTitle": "동기화는 도착했지만 아무것도 저장하지 못했어요", "lastAttemptAt": "마지막 시도: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "권장 섭취량 {value} {unit}/일 (EFSA)", + "referenceMeta": "권장 섭취량 {value} {unit}/일 ({authority})", "loadError": "수분을 불러오지 못했어요." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "비타민·미네랄", - "rowMeta": "{window}일 중 {days}일, 기준 {value} {unit} (EFSA)", + "rowMeta": "{window}일 중 {days}일, 기준 {value} {unit} ({authority})", "rowMetaNoRef": "{window}일 중 {days}일", "footer": "이 기간에 데이터가 있는 미량영양소는 추적 중인 {total}개 중 {tracked}개예요.", "emptyTitle": "아직 동기화된 미량영양소 데이터가 없어요", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "이 상한은 알파토코페롤 기준이에요." } }, - "sparseNote": "여기 수치가 낮은 건 보통 결핍이 아니라 기록이 드물다는 뜻이에요. Apple Health의 하루 합계는 앱이 기록한 양만 반영하고, 전체 식이 섭취량은 아니에요.", + "sparseNote": "여기 수치가 낮은 건 보통 결핍이 아니라 기록이 드물다는 뜻이에요. 하루 합계는 앱이 기록한 양만 반영하고, 전체 식이 섭취량은 아니에요. 식단 기록 앱과 Apple Health가 같은 날을 보고하면 더 큰 합계가 반영돼요.", "units": { "IU": "IU" }, "sources": { "APPLE_HEALTH": "동기화됨", "MANUAL": "직접 입력", - "SUPPLEMENT": "보충제" + "SUPPLEMENT": "보충제", + "EXTERNAL": "외부", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "에너지·다량영양소", + "short": { + "energy": "에너지", + "protein": "단백질", + "carbohydrates": "탄수화물", + "fat": "지방", + "sugar": "당류", + "fiber": "식이섬유" + }, + "pickLabel": "영양소", + "referenceMeta": "기준 {value} {unit}/일 ({authority})", + "targetMeta": "내 목표 {value} {unit}/일", + "limitMeta": "내 상한 {value} {unit}/일", + "setTarget": "목표 설정", + "editTarget": "목표 수정", + "clearTarget": "목표 삭제", + "targetLabel": "하루 {name} ({unit})", + "directionLabel": "목표 종류", + "directionTarget": "이상 채우기", + "directionLimit": "이하로 유지", + "saveFailed": "목표를 저장하지 못했어요. 다시 시도해 주세요.", + "loadError": "에너지와 다량영양소를 불러오지 못했어요." + }, + "alcohol": { + "loadError": "알코올을 불러오지 못했어요." } }, "daily": { diff --git a/messages/nl.json b/messages/nl.json index ddf85f494..6e5e2770b 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -5809,7 +5809,7 @@ "subtitle": "Bepaal welke bron voorrang krijgt als twee bronnen dezelfde meetwaarde melden.", "nutrients": { "title": "Gesynchroniseerde inname van voedingsstoffen", - "description": "Dagtotalen over de afgelopen {days} dagen: wat Apple Health heeft gesynchroniseerd plus de supplementen die je hebt ingenomen.", + "description": "Dagtotalen over de afgelopen {days} dagen: wat Apple Health of een voedingsapp heeft gesynchroniseerd plus de supplementen die je hebt ingenomen.", "empty": "Er zijn nog geen gegevens over voedingsstoffen gesynchroniseerd.", "latest": "{amount} {unit} op {date}", "daysWithData": "{count} van {days} dagen", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Bekijk tokens voor metingen, trainingen, documenten en medicatie-inname en trek ze in.", "measurementsToken": { "title": "Metingtokens", - "description": "Maak een token aan zodat een weegschaal, een horlogekoppeling of je domotica metingen en waarden voor je eigen metingen kan toevoegen.", + "description": "Maak een token aan zodat een weegschaal, een horlogekoppeling, een voedingsapp of je domotica metingen, waarden voor je eigen metingen en dagtotalen van voedingsstoffen kan toevoegen.", "detail": "Het token wordt één keer getoond.", - "scopeNote": "Het kan alleen nieuwe metingen aan je eigen dossier toevoegen, en waarden aan eigen metingen die je al hebt aangemaakt. Het kan je gegevens niet lezen, geen eigen meting aanmaken, niets wijzigen of verwijderen en geen ander token aanmaken. Metingen worden gemarkeerd als afkomstig van een extern apparaat, zodat je ze later kunt onderscheiden; waarden van eigen metingen krijgen die markering niet. Je kunt beide nog steeds zelf corrigeren. De ID van een eigen meting is het deel na /custom-metrics/ in het adres van de pagina ervan.", + "scopeNote": "Het kan alleen nieuwe metingen aan je eigen dossier toevoegen, waarden aan eigen metingen die je al hebt aangemaakt, en dagtotalen van voedingsstoffen zolang de module voedingsstoffen aan staat. Het kan je gegevens niet lezen, geen eigen meting aanmaken, niets wijzigen of verwijderen en geen ander token aanmaken. Metingen en voedingstotalen worden gemarkeerd als afkomstig van een extern apparaat, zodat je ze later kunt onderscheiden; waarden van eigen metingen krijgen die markering niet. Metingen en waarden van eigen metingen kun je nog steeds zelf corrigeren; een voedingsapp corrigeert een dag door hem opnieuw te sturen. De ID van een eigen meting is het deel na /custom-metrics/ in het adres van de pagina ervan.", "createFailed": "Het token kon niet worden aangemaakt. Probeer het opnieuw.", "namePlaceholder": "Naam, bijv. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Inname van voedingsstoffen", - "description": "Dagelijkse totalen van micronutriënten, gesynchroniseerd vanuit Apple Health." + "description": "Dagelijkse totalen van voedingsstoffen uit Apple Health of een voedingsapp: water, energie, macro's, vitaminen en mineralen." }, "vaccinations": { "label": "Vaccinaties", @@ -12658,15 +12658,24 @@ "water": "Water", "caffeine": "Cafeïne", "dha": "DHA (omega-3)", - "epa": "EPA (omega-3)" + "epa": "EPA (omega-3)", + "energy": "Energie", + "protein": "Eiwit", + "carbohydrates": "Koolhydraten", + "fat": "Vet", + "sugar": "Suiker", + "fiber": "Vezels", + "sodium": "Natrium", + "potassium": "Kalium", + "alcohol": "Alcohol" }, "page": { "title": "Inname van voedingsstoffen", - "description": "Vochtinname en inname van vitaminen en mineralen, gesynchroniseerd vanuit de gezondheidsapp op je telefoon, plus handmatig ingevoerd water.", - "moduleOffDescription": "Zet de module voedingsstoffen aan om hier je vochtinname en je inname van vitaminen en mineralen te zien. Gesynchroniseerde inname wordt onderdeel van de gegevens die de Coach kan lezen.", + "description": "Water, energie, macro's, vitaminen en mineralen uit je gezondheidsapp of een voedingsapp, plus handmatig ingevoerd water.", + "moduleOffDescription": "Zet de module voedingsstoffen aan om hier je vochtinname, energie, macronutriënten en je inname van vitaminen en mineralen te zien. Gesynchroniseerde inname wordt onderdeel van de gegevens die de Coach kan lezen.", "moduleOffCta": "Voedingsstoffen aanzetten", "emptyTitle": "Nog geen gegevens over voedingsstoffen", - "emptyDescription": "Gegevens komen binnen via de synchronisatie met de gezondheidsapp op je telefoon of via handmatig ingevoerd water.", + "emptyDescription": "Gegevens komen binnen via de synchronisatie met de gezondheidsapp op je telefoon, via een voedingsapp met een metingentoken of via handmatig ingevoerd water.", "loadError": "Je gegevens over voedingsstoffen konden niet worden geladen", "lastAttemptTitle": "Er is een synchronisatie binnengekomen, maar er kon niets worden opgeslagen", "lastAttemptAt": "Laatste poging: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Referentie-inname {value} {unit}/dag (EFSA)", + "referenceMeta": "Referentie-inname {value} {unit}/dag ({authority})", "loadError": "Water kon niet worden geladen." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitaminen en mineralen", - "rowMeta": "{days} van {window} dagen, ref. {value} {unit} (EFSA)", + "rowMeta": "{days} van {window} dagen, ref. {value} {unit} ({authority})", "rowMetaNoRef": "{days} van {window} dagen", "footer": "{tracked} van {total} gevolgde micronutriënten hebben gegevens in deze periode.", "emptyTitle": "Nog geen gegevens over micronutriënten gesynchroniseerd", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "De grens is vastgesteld voor alfa-tocoferol." } }, - "sparseNote": "Een laag getal betekent hier meestal dat er weinig is vastgelegd, niet dat er een tekort is. Dagtotalen in Apple Health weerspiegelen wat je apps hebben vastgelegd, niet je totale inname via voeding.", + "sparseNote": "Een laag getal betekent hier meestal dat er weinig is vastgelegd, niet dat er een tekort is. Dagtotalen weerspiegelen wat je apps hebben vastgelegd, niet je totale inname via voeding. Melden een voedingsapp en Apple Health dezelfde dag, dan telt het grootste totaal.", "units": { "IU": "IE" }, "sources": { "APPLE_HEALTH": "Gesynchroniseerd", "MANUAL": "Ingevoerd", - "SUPPLEMENT": "Supplementen" + "SUPPLEMENT": "Supplementen", + "EXTERNAL": "Extern", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energie en macronutriënten", + "short": { + "energy": "Energie", + "protein": "Eiwit", + "carbohydrates": "Koolh.", + "fat": "Vet", + "sugar": "Suiker", + "fiber": "Vezels" + }, + "pickLabel": "Voedingsstof", + "referenceMeta": "Referentie {value} {unit}/dag ({authority})", + "targetMeta": "Jouw doel {value} {unit}/dag", + "limitMeta": "Jouw grens {value} {unit}/dag", + "setTarget": "Doel instellen", + "editTarget": "Doel wijzigen", + "clearTarget": "Doel verwijderen", + "targetLabel": "{name} per dag in {unit}", + "directionLabel": "Soort doel", + "directionTarget": "Minstens halen", + "directionLimit": "Eronder blijven", + "saveFailed": "Het doel kon niet worden opgeslagen. Probeer het opnieuw.", + "loadError": "Energie en macronutriënten konden niet worden geladen." + }, + "alcohol": { + "loadError": "Alcohol kon niet worden geladen." } }, "daily": { diff --git a/messages/pl.json b/messages/pl.json index aa2b039d2..6bd3f2fe6 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -5809,7 +5809,7 @@ "subtitle": "Zdecyduj, które źródło wygrywa, gdy dwa podają tę samą metrykę.", "nutrients": { "title": "Zsynchronizowane spożycie składników", - "description": "Dzienne sumy z ostatnich {days} dni: dane zsynchronizowane z Apple Health oraz przyjęte suplementy.", + "description": "Dzienne sumy z ostatnich {days} dni: dane zsynchronizowane z Apple Health lub aplikacji dietetycznej oraz przyjęte suplementy.", "empty": "Nie zsynchronizowano jeszcze danych o składnikach odżywczych.", "latest": "{amount} {unit} dnia {date}", "daysWithData": "{count} z {days} dni", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Przeglądaj i unieważniaj tokeny do pomiarów, treningów, dokumentów i przyjęć leków.", "measurementsToken": { "title": "Tokeny pomiarów", - "description": "Utwórz token, aby waga, zegarek lub automatyka domowa mogły dodawać pomiary i wartości Twoich metryk własnych.", + "description": "Utwórz token, aby waga, zegarek, aplikacja dietetyczna lub automatyka domowa mogły dodawać pomiary, wartości Twoich metryk własnych i dzienne sumy składników odżywczych.", "detail": "Token pokazujemy tylko raz.", - "scopeNote": "Może wyłącznie dodawać nowe pomiary do Twojej dokumentacji oraz wartości do już utworzonych metryk własnych: nie odczyta danych, nie utworzy metryki, niczego nie zmieni ani nie usunie i nie utworzy kolejnego tokenu. Pomiary są oznaczane jako pochodzące z urządzenia zewnętrznego, dzięki czemu później je rozpoznasz; wartości metryk własnych nie mają takiego oznaczenia. Jedne i drugie nadal możesz poprawić. Identyfikator metryki własnej to część po /custom-metrics/ w adresie jej strony.", + "scopeNote": "Może wyłącznie dodawać nowe pomiary do Twojej dokumentacji, wartości do już utworzonych metryk własnych oraz dzienne sumy składników odżywczych, dopóki moduł składników odżywczych jest włączony: nie odczyta danych, nie utworzy metryki, niczego nie zmieni ani nie usunie i nie utworzy kolejnego tokenu. Pomiary i sumy składników są oznaczane jako pochodzące z urządzenia zewnętrznego, dzięki czemu później je rozpoznasz; wartości metryk własnych nie mają takiego oznaczenia. Pomiary i wartości metryk możesz nadal poprawiać sam; aplikacja dietetyczna poprawia dzień, wysyłając go ponownie. Identyfikator metryki własnej to część po /custom-metrics/ w adresie jej strony.", "createFailed": "Nie udało się utworzyć tokenu. Spróbuj ponownie.", "namePlaceholder": "Nazwa, np. Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Spożycie składników odżywczych", - "description": "Dzienne sumy mikroskładników synchronizowane z Apple Health." + "description": "Dzienne sumy składników odżywczych z Apple Health lub aplikacji dietetycznej: woda, energia, makroskładniki, witaminy i minerały." }, "vaccinations": { "label": "Szczepienia", @@ -12658,15 +12658,24 @@ "water": "Woda", "caffeine": "Kofeina", "dha": "DHA (kwas omega-3)", - "epa": "EPA (kwas omega-3)" + "epa": "EPA (kwas omega-3)", + "energy": "Energia", + "protein": "Białko", + "carbohydrates": "Węglowodany", + "fat": "Tłuszcz", + "sugar": "Cukry", + "fiber": "Błonnik", + "sodium": "Sód", + "potassium": "Potas", + "alcohol": "Alkohol" }, "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.", - "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.", + "description": "Woda, energia, makroskładniki, witaminy i minerały z aplikacji zdrowia lub aplikacji dietetycznej, plus ręczne wpisy wody.", + "moduleOffDescription": "Włącz moduł składników odżywczych, aby zobaczyć tu nawodnienie, energię, makroskładniki i spożycie witamin/minerałów. Zsynchronizowane dane staną się częścią zapisu, który może odczytać Coach.", "moduleOffCta": "Włącz składniki odżywcze", "emptyTitle": "Brak jeszcze danych o składnikach odżywczych", - "emptyDescription": "Dane pochodzą z synchronizacji aplikacji zdrowia telefonu lub z ręcznego wpisu wody.", + "emptyDescription": "Dane pochodzą z synchronizacji aplikacji zdrowia telefonu, z aplikacji dietetycznej z tokenem pomiarów lub z ręcznego wpisu wody.", "loadError": "Nie udało się wczytać danych o składnikach odżywczych", "lastAttemptTitle": "Synchronizacja dotarła, ale nic nie udało się zapisać", "lastAttemptAt": "Ostatnia próba: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Zalecane spożycie {value} {unit}/dzień (EFSA)", + "referenceMeta": "Zalecane spożycie {value} {unit}/dzień ({authority})", "loadError": "Nie udało się załadować wody." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Witaminy i minerały", - "rowMeta": "{days} z {window} dni, zalecane {value} {unit} (EFSA)", + "rowMeta": "{days} z {window} dni, zalecane {value} {unit} ({authority})", "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", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "Poziom ustalono dla alfa-tokoferolu." } }, - "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.", + "sparseNote": "Niska wartość zwykle oznacza tu rzadkie zapisywanie, a nie niedobór. Dzienne sumy odzwierciedlają to, co zapisały twoje aplikacje, a nie całkowite spożycie w diecie. Gdy aplikacja dietetyczna i Apple Health podają ten sam dzień, liczy się większa suma.", "units": { "IU": "j.m." }, "sources": { "APPLE_HEALTH": "Zsynchronizowane", "MANUAL": "Wpisane", - "SUPPLEMENT": "Suplementy" + "SUPPLEMENT": "Suplementy", + "EXTERNAL": "Zewnętrzne", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energia i makroskładniki", + "short": { + "energy": "Energia", + "protein": "Białko", + "carbohydrates": "Węgle", + "fat": "Tłuszcz", + "sugar": "Cukry", + "fiber": "Błonnik" + }, + "pickLabel": "Składnik", + "referenceMeta": "Wartość referencyjna {value} {unit}/dzień ({authority})", + "targetMeta": "Twój cel {value} {unit}/dzień", + "limitMeta": "Twój limit {value} {unit}/dzień", + "setTarget": "Ustaw cel", + "editTarget": "Zmień cel", + "clearTarget": "Usuń cel", + "targetLabel": "{name} dziennie w {unit}", + "directionLabel": "Rodzaj celu", + "directionTarget": "Osiągnąć co najmniej", + "directionLimit": "Nie przekraczać", + "saveFailed": "Nie udało się zapisać celu. Spróbuj ponownie.", + "loadError": "Nie udało się wczytać energii i makroskładników." + }, + "alcohol": { + "loadError": "Nie udało się wczytać alkoholu." } }, "daily": { diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 351ec8538..bc1ddd374 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -5809,7 +5809,7 @@ "subtitle": "Decida qual fonte prevalece quando duas informam a mesma métrica.", "nutrients": { "title": "Ingestão de nutrientes sincronizada", - "description": "Totais diários nos últimos {days} dias: o que o Apple Health sincronizou mais os suplementos que você tomou.", + "description": "Totais diários nos últimos {days} dias: o que o Apple Health ou um app de dieta sincronizou mais os suplementos que você tomou.", "empty": "Nenhum dado de nutrientes foi sincronizado ainda.", "latest": "{amount} {unit} em {date}", "daysWithData": "{count} de {days} dias", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Revise e revogue tokens para medições, treinos, documentos e tomadas de medicamentos.", "measurementsToken": { "title": "Tokens de medição", - "description": "Gere um token para que uma balança, uma ponte de relógio ou sua automação residencial possa adicionar leituras e valores das suas métricas personalizadas.", + "description": "Gere um token para que uma balança, uma ponte de relógio, um app de dieta ou sua automação residencial possa adicionar leituras, valores das suas métricas personalizadas e totais diários de nutrientes.", "detail": "O token é exibido uma vez.", - "scopeNote": "Ele só pode adicionar novas leituras ao seu próprio registro e valores às métricas personalizadas que você já criou. Não pode ler seus dados, criar uma métrica, alterar ou excluir nada, nem criar outro token. As leituras são marcadas como vindas de um dispositivo externo, para você distingui-las depois; os valores de métricas personalizadas não recebem essa marca. Você ainda pode corrigir ambos. O ID de uma métrica personalizada é a parte depois de /custom-metrics/ no endereço da página dela.", + "scopeNote": "Ele só pode adicionar novas leituras ao seu próprio registro, valores às métricas personalizadas que você já criou e totais diários de nutrientes enquanto o módulo de nutrientes estiver ativo. Não pode ler seus dados, criar uma métrica, alterar ou excluir nada, nem criar outro token. As leituras e os totais de nutrientes são marcados como vindos de um dispositivo externo, para você distingui-los depois; os valores de métricas personalizadas não recebem essa marca. Você ainda pode corrigir leituras e valores de métricas; um app de dieta corrige um dia enviando-o de novo. O ID de uma métrica personalizada é a parte depois de /custom-metrics/ no endereço da página dela.", "createFailed": "O token não pôde ser criado. Tente novamente.", "namePlaceholder": "Nome, ex.: Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Ingestão de nutrientes", - "description": "Totais diários de micronutrientes sincronizados do Apple Health." + "description": "Totais diários de nutrientes do Apple Health ou de um app de dieta: água, energia, macros, vitaminas e minerais." }, "vaccinations": { "label": "Vacinas", @@ -12658,15 +12658,24 @@ "water": "Água", "caffeine": "Cafeína", "dha": "DHA (ômega-3)", - "epa": "EPA (ômega-3)" + "epa": "EPA (ômega-3)", + "energy": "Energia", + "protein": "Proteínas", + "carbohydrates": "Carboidratos", + "fat": "Gorduras", + "sugar": "Açúcares", + "fiber": "Fibras", + "sodium": "Sódio", + "potassium": "Potássio", + "alcohol": "Álcool" }, "page": { "title": "Ingestão de nutrientes", - "description": "Hidratação e ingestão de vitaminas/minerais sincronizadas do app de saúde do seu telefone, mais entradas manuais de água.", - "moduleOffDescription": "Ative o módulo de nutrientes para ver hidratação e ingestão de vitaminas/minerais aqui. A ingestão sincronizada passa a fazer parte do registro que o Coach pode ler.", + "description": "Água, energia, macros, vitaminas e minerais do seu app de saúde ou de um app de dieta, mais entradas manuais de água.", + "moduleOffDescription": "Ative o módulo de nutrientes para ver hidratação, energia, macronutrientes e ingestão de vitaminas/minerais aqui. A ingestão sincronizada passa a fazer parte do registro que o Coach pode ler.", "moduleOffCta": "Ativar nutrientes", "emptyTitle": "Nenhum dado de nutrientes ainda", - "emptyDescription": "Os dados chegam pela sincronização do app de saúde do seu telefone ou por uma entrada manual de água.", + "emptyDescription": "Os dados chegam pela sincronização do app de saúde do seu telefone, por um app de dieta com um token de medições ou por uma entrada manual de água.", "loadError": "Não foi possível carregar seus dados de nutrientes", "lastAttemptTitle": "Uma sincronização chegou, mas nada pôde ser armazenado", "lastAttemptAt": "Última tentativa: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Ingestão de referência {value} {unit}/dia (EFSA)", + "referenceMeta": "Ingestão de referência {value} {unit}/dia ({authority})", "loadError": "Não foi possível carregar a água." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Vitaminas e minerais", - "rowMeta": "{days} de {window} dias, ref. {value} {unit} (EFSA)", + "rowMeta": "{days} de {window} dias, ref. {value} {unit} ({authority})", "rowMetaNoRef": "{days} de {window} dias", "footer": "{tracked} de {total} micronutrientes acompanhados têm dados nesta janela.", "emptyTitle": "Nenhum dado de micronutriente sincronizado ainda", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "O nível é definido para alfa-tocoferol." } }, - "sparseNote": "Um número baixo aqui geralmente significa registro esparso, não deficiência. Os totais diários do Apple Health refletem o que seus aplicativos registraram, não a ingestão dietética total.", + "sparseNote": "Um número baixo aqui geralmente significa registro esparso, não deficiência. Os totais diários refletem o que seus aplicativos registraram, não a ingestão dietética total. Quando um app de dieta e o Apple Health informam o mesmo dia, vale o total maior.", "units": { "IU": "UI" }, "sources": { "APPLE_HEALTH": "Sincronizado", "MANUAL": "Inserido", - "SUPPLEMENT": "Suplementos" + "SUPPLEMENT": "Suplementos", + "EXTERNAL": "Externo", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Energia e macronutrientes", + "short": { + "energy": "Energia", + "protein": "Proteínas", + "carbohydrates": "Carbos", + "fat": "Gorduras", + "sugar": "Açúcares", + "fiber": "Fibras" + }, + "pickLabel": "Nutriente", + "referenceMeta": "Referência {value} {unit}/dia ({authority})", + "targetMeta": "Sua meta {value} {unit}/dia", + "limitMeta": "Seu limite {value} {unit}/dia", + "setTarget": "Definir meta", + "editTarget": "Alterar meta", + "clearTarget": "Remover meta", + "targetLabel": "{name} por dia em {unit}", + "directionLabel": "Tipo de meta", + "directionTarget": "Atingir pelo menos", + "directionLimit": "Ficar abaixo", + "saveFailed": "Não foi possível salvar a meta. Tente novamente.", + "loadError": "Não foi possível carregar energia e macronutrientes." + }, + "alcohol": { + "loadError": "Não foi possível carregar o álcool." } }, "daily": { diff --git a/messages/ru.json b/messages/ru.json index acd103c36..06170fe8b 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -5809,7 +5809,7 @@ "subtitle": "Решите, какой источник побеждает, когда два сообщают один и тот же показатель.", "nutrients": { "title": "Синхронизированный приём нутриентов", - "description": "Дневные итоги за последние {days} дней: что синхронизировал Apple Health плюс принятые вами добавки.", + "description": "Дневные итоги за последние {days} дней: что синхронизировал Apple Health или трекер питания, плюс принятые вами добавки.", "empty": "Данные о нутриентах ещё не синхронизированы.", "latest": "{amount} {unit} {date}", "daysWithData": "{count} из {days} дней", @@ -6997,9 +6997,9 @@ "apiTokensDescription": "Просматривайте и отзывайте токены для измерений, тренировок, документов и приёма лекарств.", "measurementsToken": { "title": "Токены измерений", - "description": "Создайте токен, чтобы весы, мост для часов или ваша система умного дома могли добавлять измерения и значения ваших собственных показателей.", + "description": "Создайте токен, чтобы весы, мост для часов, трекер питания или ваша система умного дома могли добавлять измерения, значения ваших собственных показателей и дневные итоги нутриентов.", "detail": "Токен показывается один раз.", - "scopeNote": "Он может только добавлять новые измерения в вашу собственную историю и значения в уже созданные вами собственные показатели. Он не может читать ваши данные, создавать показатели, изменять или удалять что-либо или создавать другой токен. Измерения помечаются как пришедшие с внешнего устройства, чтобы вы могли отличить их позже; значения собственных показателей такой пометки не получают. Вы всё равно можете исправить и то, и другое сами. Идентификатор собственного показателя указан в адресе его страницы после /custom-metrics/.", + "scopeNote": "Он может только добавлять новые измерения в вашу собственную историю, значения в уже созданные вами собственные показатели и дневные итоги нутриентов, пока включён модуль нутриентов. Он не может читать ваши данные, создавать показатели, изменять или удалять что-либо или создавать другой токен. Измерения и итоги нутриентов помечаются как пришедшие с внешнего устройства, чтобы вы могли отличить их позже; значения собственных показателей такой пометки не получают. Измерения и значения показателей вы по-прежнему можете исправить сами; трекер питания исправляет день, отправив его заново. Идентификатор собственного показателя указан в адресе его страницы после /custom-metrics/.", "createFailed": "Не удалось создать токен. Попробуйте снова.", "namePlaceholder": "Название, например Home Assistant", "appleHealth": { @@ -10839,7 +10839,7 @@ }, "nutrients": { "label": "Приём нутриентов", - "description": "Ежедневные итоги микронутриентов, синхронизированные из Apple Health." + "description": "Ежедневные итоги нутриентов из Apple Health или трекера питания: вода, энергия, макронутриенты, витамины и минералы." }, "vaccinations": { "label": "Вакцинация", @@ -12658,15 +12658,24 @@ "water": "Вода", "caffeine": "Кофеин", "dha": "DHA (омега-3)", - "epa": "EPA (омега-3)" + "epa": "EPA (омега-3)", + "energy": "Энергия", + "protein": "Белки", + "carbohydrates": "Углеводы", + "fat": "Жиры", + "sugar": "Сахара", + "fiber": "Клетчатка", + "sodium": "Натрий", + "potassium": "Калий", + "alcohol": "Алкоголь" }, "page": { "title": "Приём нутриентов", - "description": "Вода и приём витаминов и минералов, синхронизированные из приложения здоровья на телефоне, плюс ручные записи воды.", - "moduleOffDescription": "Включите модуль нутриентов, чтобы видеть здесь воду и приём витаминов и минералов. Синхронизированный приём становится частью записи, которую может читать Coach.", + "description": "Вода, энергия, макронутриенты, витамины и минералы из приложения здоровья или трекера питания, плюс ручные записи воды.", + "moduleOffDescription": "Включите модуль нутриентов, чтобы видеть здесь воду, энергию, макронутриенты и приём витаминов и минералов. Синхронизированный приём становится частью записи, которую может читать Coach.", "moduleOffCta": "Включить нутриенты", "emptyTitle": "Данных о нутриентах пока нет", - "emptyDescription": "Данные поступают из синхронизации с приложением здоровья на телефоне или из ручной записи воды.", + "emptyDescription": "Данные поступают из синхронизации с приложением здоровья на телефоне, из трекера питания с токеном измерений или из ручной записи воды.", "loadError": "Не удалось загрузить данные о нутриентах", "lastAttemptTitle": "Синхронизация пришла, но сохранить ничего не удалось", "lastAttemptAt": "Последняя попытка: {date}", @@ -12679,7 +12688,7 @@ } }, "hydration": { - "referenceMeta": "Референсный приём {value} {unit}/день (EFSA)", + "referenceMeta": "Референсный приём {value} {unit}/день ({authority})", "loadError": "Не удалось загрузить воду." }, "caffeine": { @@ -12688,7 +12697,7 @@ }, "micronutrients": { "title": "Витамины и минералы", - "rowMeta": "{days} из {window} дней, реф. {value} {unit} (EFSA)", + "rowMeta": "{days} из {window} дней, реф. {value} {unit} ({authority})", "rowMetaNoRef": "{days} из {window} дней", "footer": "Из {total} отслеживаемых микронутриентов данные в этом окне есть у {tracked}.", "emptyTitle": "Данные о микронутриентах ещё не синхронизированы", @@ -12703,14 +12712,43 @@ "alpha_tocopherol": "Уровень установлен для альфа-токоферола." } }, - "sparseNote": "Низкое число здесь обычно означает редкие записи, а не дефицит. Суточные итоги Apple Health отражают то, что записали ваши приложения, а не общий приём с пищей.", + "sparseNote": "Низкое число здесь обычно означает редкие записи, а не дефицит. Суточные итоги отражают то, что записали ваши приложения, а не общий приём с пищей. Если трекер питания и Apple Health сообщают об одном и том же дне, учитывается больший итог.", "units": { "IU": "МЕ" }, "sources": { "APPLE_HEALTH": "Синхронизировано", "MANUAL": "Введено", - "SUPPLEMENT": "Добавки" + "SUPPLEMENT": "Добавки", + "EXTERNAL": "Внешний источник", + "HEALTH_CONNECT": "Health Connect" + }, + "macros": { + "title": "Энергия и макронутриенты", + "short": { + "energy": "Энергия", + "protein": "Белки", + "carbohydrates": "Углеводы", + "fat": "Жиры", + "sugar": "Сахара", + "fiber": "Клетчатка" + }, + "pickLabel": "Нутриент", + "referenceMeta": "Референс {value} {unit}/день ({authority})", + "targetMeta": "Ваша цель {value} {unit}/день", + "limitMeta": "Ваш предел {value} {unit}/день", + "setTarget": "Задать цель", + "editTarget": "Изменить цель", + "clearTarget": "Удалить цель", + "targetLabel": "{name} в день, {unit}", + "directionLabel": "Тип цели", + "directionTarget": "Достичь не меньше", + "directionLimit": "Не превышать", + "saveFailed": "Не удалось сохранить цель. Попробуйте ещё раз.", + "loadError": "Не удалось загрузить энергию и макронутриенты." + }, + "alcohol": { + "loadError": "Не удалось загрузить алкоголь." } }, "daily": { diff --git a/src/__tests__/i18n-english-leak-guard.test.ts b/src/__tests__/i18n-english-leak-guard.test.ts index 70faa52e6..c49b3b556 100644 --- a/src/__tests__/i18n-english-leak-guard.test.ts +++ b/src/__tests__/i18n-english-leak-guard.test.ts @@ -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([ + // 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", diff --git a/src/__tests__/source-size-ratchet.test.ts b/src/__tests__/source-size-ratchet.test.ts index b1db6ba8c..414fdbd5e 100644 --- a/src/__tests__/source-size-ratchet.test.ts +++ b/src/__tests__/source-size-ratchet.test.ts @@ -57,6 +57,7 @@ const CATALOGS: Readonly> = { "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", }; diff --git a/src/app/api/nutrients/catalog/route.ts b/src/app/api/nutrients/catalog/route.ts index 3f63755c5..3efc523d9 100644 --- a/src/app/api/nutrients/catalog/route.ts +++ b/src/app/api/nutrients/catalog/route.ts @@ -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, diff --git a/src/app/api/nutrients/daily/__tests__/route.test.ts b/src/app/api/nutrients/daily/__tests__/route.test.ts index 2c326657f..e2068afb4 100644 --- a/src/app/api/nutrients/daily/__tests__/route.test.ts +++ b/src/app/api/nutrients/daily/__tests__/route.test.ts @@ -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")); diff --git a/src/app/api/nutrients/daily/route.ts b/src/app/api/nutrients/daily/route.ts index faf15b4a1..60aae9729 100644 --- a/src/app/api/nutrients/daily/route.ts +++ b/src/app/api/nutrients/daily/route.ts @@ -1,11 +1,11 @@ /** - * `GET /api/nutrients/daily?nutrient=&days=N` — per-day summed - * series for one nutrient, plus its resolved EFSA reference (v1.29). + * `GET /api/nutrients/daily?nutrient=&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, }); }); diff --git a/src/app/api/nutrients/route.ts b/src/app/api/nutrients/route.ts index c90ea487e..944d82074 100644 --- a/src/app/api/nutrients/route.ts +++ b/src/app/api/nutrients/route.ts @@ -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. * diff --git a/src/app/insights/nutrients/page.tsx b/src/app/insights/nutrients/page.tsx index e64c2b046..c2ae72054 100644 --- a/src/app/insights/nutrients/page.tsx +++ b/src/app/insights/nutrients/page.tsx @@ -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")} > - + + + ); diff --git a/src/components/insights/nutrients/energy-macros-card.tsx b/src/components/insights/nutrients/energy-macros-card.tsx new file mode 100644 index 000000000..1004c9a9b --- /dev/null +++ b/src/components/insights/nutrients/energy-macros-card.tsx @@ -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(`/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(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 ( + + + + + + {codes.length > 1 ? ( + ({ + value: c, + label: t(`nutrients.macros.short.${c}`), + }))} + value={code} + onChange={setPicked} + label={t("nutrients.macros.pickLabel")} + slot="nutrients-macros-pick" + /> + ) : null} + + + + ); +} + +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( + `/api/nutrients/daily?nutrient=${code}&days=${WINDOW_DAYS}`, + ), + staleTime: 60_000, + }); + + if (isError && !data) { + return ( + void refetch()} + /> + ); + } + if (isLoading || !data) { + return ( + + ); + } + + 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 ( +
+
+
+

+ {formatAmount(fmt, today)} {unit} +

+ {meta ? ( +

+ {meta} +

+ ) : null} +
+ {editing ? null : ( + + )} +
+ {editing ? ( + setEditing(false)} + /> + ) : null} + +
+ ); +} + +/** + * 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 ( +
{ + event.preventDefault(); + if (valid) void save({ value: parsed, direction }); + }} + > +
+ + setValue(event.target.value)} + aria-invalid={value.trim() !== "" && !valid} + className="max-w-40" + /> +
+ +
+ + {current ? ( + + ) : null} + +
+ + ); +} diff --git a/src/components/insights/nutrients/hydration-card.tsx b/src/components/insights/nutrients/hydration-card.tsx index 1f62f9fc2..a08d42627 100644 --- a/src/components/insights/nutrients/hydration-card.tsx +++ b/src/components/insights/nutrients/hydration-card.tsx @@ -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", })}

) : null} diff --git a/src/components/insights/nutrients/micronutrients-card.tsx b/src/components/insights/nutrients/micronutrients-card.tsx index 8518a3993..5dfa97b1f 100644 --- a/src/components/insights/nutrients/micronutrients-card.tsx +++ b/src/components/insights/nutrients/micronutrients-card.tsx @@ -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 = [ + "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, diff --git a/src/components/insights/nutrients/single-nutrient-card.tsx b/src/components/insights/nutrients/single-nutrient-card.tsx index dd0adf75d..cc5e0e4b2 100644 --- a/src/components/insights/nutrients/single-nutrient-card.tsx +++ b/src/components/insights/nutrients/single-nutrient-card.tsx @@ -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( - `/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 ( - + - + void refetch()} /> @@ -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 ( - + - +

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

- {data.reference ? ( + {metaKey && reference ? (

- {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", })}

) : null}
diff --git a/src/components/insights/nutrients/types.ts b/src/components/insights/nutrients/types.ts index e59289586..c9b684eee 100644 --- a/src/components/insights/nutrients/types.ts +++ b/src/components/insights/nutrients/types.ts @@ -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. */ diff --git a/src/components/medications/sections/composition-section.tsx b/src/components/medications/sections/composition-section.tsx index 0b0a2d86f..eb0f5f271 100644 --- a/src/components/medications/sections/composition-section.tsx +++ b/src/components/medications/sections/composition-section.tsx @@ -48,9 +48,6 @@ export const COMPOSITION_CATEGORIES: ReadonlySet = 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(() => diff --git a/src/components/medications/sections/use-composition.ts b/src/components/medications/sections/use-composition.ts index 11cce7d3d..09dce38b6 100644 --- a/src/components/medications/sections/use-composition.ts +++ b/src/components/medications/sections/use-composition.ts @@ -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; diff --git a/src/lib/dashboard/snapshot.ts b/src/lib/dashboard/snapshot.ts index e7a5f1502..8b731c589 100644 --- a/src/lib/dashboard/snapshot.ts +++ b/src/lib/dashboard/snapshot.ts @@ -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(); - 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()); diff --git a/src/lib/import/health-connect/mapper.ts b/src/lib/import/health-connect/mapper.ts index 05a218d55..329816fd4 100644 --- a/src/lib/import/health-connect/mapper.ts +++ b/src/lib/import/health-connect/mapper.ts @@ -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> diff --git a/src/lib/insights/__tests__/correlation-extended-channels.test.ts b/src/lib/insights/__tests__/correlation-extended-channels.test.ts index 0b0accfa7..e52ec343a 100644 --- a/src/lib/insights/__tests__/correlation-extended-channels.test.ts +++ b/src/lib/insights/__tests__/correlation-extended-channels.test.ts @@ -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", () => { diff --git a/src/lib/insights/correlation-channel-series.ts b/src/lib/insights/correlation-channel-series.ts index 69c572b59..da8198f97 100644 --- a/src/lib/insights/correlation-channel-series.ts +++ b/src/lib/insights/correlation-channel-series.ts @@ -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 }); } diff --git a/src/lib/insights/correlation-series-builders.ts b/src/lib/insights/correlation-series-builders.ts index dc3381884..177b23a92 100644 --- a/src/lib/insights/correlation-series-builders.ts +++ b/src/lib/insights/correlation-series-builders.ts @@ -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:` channels in one scan. */ +/** Ceiling on vitamin, mineral and omega-3 `NUTRIENT:` channels in one scan. */ export const MAX_MICRONUTRIENT_CHANNELS = 4; +/** Ceiling on energy and macronutrient `NUTRIENT:` 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:`. + * CAFFEINE, at most {@link MAX_MICRONUTRIENT_CHANNELS} micronutrients and at + * most {@link MAX_MACRONUTRIENT_CHANNELS} energy or macronutrient codes as + * `NUTRIENT:`. 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>(); - for (const row of rows) { - if (!Number.isFinite(row.amount)) continue; - const days = byNutrient.get(row.nutrient) ?? new Map(); - 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(); + days.set(day, fold.total); + byNutrient.set(nutrient, days); } const pointsOf = (code: string): DailySeriesPoint[] => [...(byNutrient.get(code) ?? new Map()).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, + 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 = new Set([ + "vitamin", + "mineral", + "omega3", +]); +const MACRONUTRIENT_GROUPS: ReadonlySet = new Set([ + "energy_macro", +]); + /** One mood entry as the alcohol channel reads it. */ export interface AlcoholTagEntry { at: Date; diff --git a/src/lib/mcp/__tests__/__snapshots__/tools-list.write-session.snap b/src/lib/mcp/__tests__/__snapshots__/tools-list.write-session.snap index ea9b92925..49d678657 100644 --- a/src/lib/mcp/__tests__/__snapshots__/tools-list.write-session.snap +++ b/src/lib/mcp/__tests__/__snapshots__/tools-list.write-session.snap @@ -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": [ diff --git a/src/lib/mcp/__tests__/nutrients-read.test.ts b/src/lib/mcp/__tests__/nutrients-read.test.ts index 8253f1623..f5316332c 100644 --- a/src/lib/mcp/__tests__/nutrients-read.test.ts +++ b/src/lib/mcp/__tests__/nutrients-read.test.ts @@ -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 () => { diff --git a/src/lib/mcp/nutrients-read.ts b/src/lib/mcp/nutrients-read.ts index cd2e4e365..d141b3261 100644 --- a/src/lib/mcp/nutrients-read.ts +++ b/src/lib/mcp/nutrients-read.ts @@ -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 { 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. */ diff --git a/src/lib/mcp/resources.ts b/src/lib/mcp/resources.ts index c975cc89d..bebd48aa3 100644 --- a/src/lib/mcp/resources.ts +++ b/src/lib/mcp/resources.ts @@ -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) { diff --git a/src/lib/mcp/tools/get-nutrients.ts b/src/lib/mcp/tools/get-nutrients.ts index 9edc2cf34..cb73030d3 100644 --- a/src/lib/mcp/tools/get-nutrients.ts +++ b/src/lib/mcp/tools/get-nutrients.ts @@ -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() diff --git a/src/lib/mcp/tools/search.ts b/src/lib/mcp/tools/search.ts index 48e1c1d4b..55c319840 100644 --- a/src/lib/mcp/tools/search.ts +++ b/src/lib/mcp/tools/search.ts @@ -218,7 +218,8 @@ async function addNutrientCandidates( origin: string, legacy: AddCandidate, ): Promise { - // 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. diff --git a/src/lib/measurements/apple-health-mapping.ts b/src/lib/measurements/apple-health-mapping.ts index 02a7931a0..33765cffd 100644 --- a/src/lib/measurements/apple-health-mapping.ts +++ b/src/lib/measurements/apple-health-mapping.ts @@ -1235,12 +1235,11 @@ export const HK_QUANTITY_TYPE_DEFERRED = new Set([ // 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", diff --git a/src/lib/medications/ingredients/composition.ts b/src/lib/medications/ingredients/composition.ts index 1b8b3da8f..eab51f174 100644 --- a/src/lib/medications/ingredients/composition.ts +++ b/src/lib/medications/ingredients/composition.ts @@ -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; diff --git a/src/lib/medications/ingredients/label-extract.ts b/src/lib/medications/ingredients/label-extract.ts index 8e9872fae..558196e16 100644 --- a/src/lib/medications/ingredients/label-extract.ts +++ b/src/lib/medications/ingredients/label-extract.ts @@ -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 && diff --git a/src/lib/nutrients/__tests__/catalog.test.ts b/src/lib/nutrients/__tests__/catalog.test.ts index 37b6911b7..3eb8059fb 100644 --- a/src/lib/nutrients/__tests__/catalog.test.ts +++ b/src/lib/nutrients/__tests__/catalog.test.ts @@ -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(); const hkIds = new Set(); - 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); }); }); diff --git a/src/lib/nutrients/__tests__/day-total.test.ts b/src/lib/nutrients/__tests__/day-total.test.ts new file mode 100644 index 000000000..11784cd1c --- /dev/null +++ b/src/lib/nutrients/__tests__/day-total.test.ts @@ -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); + }); +}); diff --git a/src/lib/nutrients/catalog.ts b/src/lib/nutrients/catalog.ts index 9aab97e8e..203019646 100644 --- a/src/lib/nutrients/catalog.ts +++ b/src/lib/nutrients/catalog.ts @@ -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; 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 = 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 > = 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> = { + 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, diff --git a/src/lib/nutrients/day-total.ts b/src/lib/nutrients/day-total.ts new file mode 100644 index 000000000..dea4d5df5 --- /dev/null +++ b/src/lib/nutrients/day-total.ts @@ -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>; + +export interface NutrientDayRow { + source: string; + amount: number; +} + +export interface NutrientDayFold { + total: number; + bySource: NutrientAmountBySource; +} + +const DAY_TOTAL_SET: ReadonlySet = 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, +): 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( + rows: ReadonlyArray, + keyOf: (row: T) => string, +): Map { + const groups = new Map(); + 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(); + for (const [key, group] of groups) folds.set(key, foldNutrientDay(group)); + return folds; +} diff --git a/src/lib/nutrients/read.ts b/src/lib/nutrients/read.ts index 1f8a3329e..95703a158 100644 --- a/src/lib/nutrients/read.ts +++ b/src/lib/nutrients/read.ts @@ -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>; +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 } + { + unit: string; + latestDay: string; + latestRows: NutrientDayRow[]; + daysSeen: Set; + } >(); 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(); - 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, + }; } diff --git a/src/lib/nutrients/sources.ts b/src/lib/nutrients/sources.ts index 483f28734..cddd0caf5 100644 --- a/src/lib/nutrients/sources.ts +++ b/src/lib/nutrients/sources.ts @@ -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 = 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 = [ + NUTRIENT_SOURCE.EXTERNAL, + NUTRIENT_SOURCE.APPLE_HEALTH, + NUTRIENT_SOURCE.HEALTH_CONNECT, +]; diff --git a/src/lib/openapi/routes/nutrients.ts b/src/lib/openapi/routes/nutrients.ts index 3d7458b54..39fcf1137 100644 --- a/src/lib/openapi/routes/nutrients.ts +++ b/src/lib/openapi/routes/nutrients.ts @@ -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 = { 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 = { 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": { diff --git a/src/lib/query-keys/nutrients.ts b/src/lib/query-keys/nutrients.ts index b0fffd7cf..53d424ceb 100644 --- a/src/lib/query-keys/nutrients.ts +++ b/src/lib/query-keys/nutrients.ts @@ -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, }; diff --git a/src/lib/validations/nutrients.ts b/src/lib/validations/nutrients.ts index 331b00efc..73b786a6c 100644 --- a/src/lib/validations/nutrients.ts +++ b/src/lib/validations/nutrients.ts @@ -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.", });