health: ingredient meals no longer zero every micronutrient
- Commit
b0bfb629b9112568fcdd21ddcec26f47cc769be2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 20:18 UTC (5 days ago)
- Parents
c8946b7
Logging a meal from an ingredient (or a recipe) hand-enumerated only 7 macro fields when scaling per-100g nutrition โ protein, carbs, fat, fiber, sugar, sodium, calories โ so calcium, iron, vitamins and every other micronutrient silently stored as 0 while calories were right. Daily totals and the Health Connect export then showed catalog micronutrients as 0 for all self-logged meals. NutritionData.scaledBy/plus now live in one new data file covering all 41 fields, and both call sites (recipe fold, ingredient log) use it, so any future nutrient field scales by construction. Regression tests assert scaled micronutrients through both paths. Medications, dose scheduling and Health Connect conflicts were audited and cleared. Verified: :health:testDevUnitTest 648 tests, 0 failures; lint errors are pre-existing on untouched files.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex e8c9032ee7..e74061e680 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -30,6 +30,7 @@ _Install: ./install health (dev by default)._ ### data/ โ Room entities + repository - com/vayunmathur/health/data/HealthRepository.kt - com/vayunmathur/health/data/Record.kt+- com/vayunmathur/health/data/NutritionScaling.kt - com/vayunmathur/health/data/MedicationSchedule.kt - com/vayunmathur/health/data/MedicalRecords.kt - com/vayunmathur/health/data/FoodModels.kt
health/src/main/java/com/vayunmathur/health/data/NutritionScaling.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/NutritionScaling.kt b/health/src/main/java/com/vayunmathur/health/data/NutritionScaling.ktnew file mode 100644index 0000000000..676a03156e--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/data/NutritionScaling.kt@@ -0,0 +1,97 @@+package com.vayunmathur.health.data++/**+ * Every field multiplied by [factor] (per-100g facts to grams eaten, or+ * a quantity in 100g units). Scaling lives here, on the value that owns+ * the fields, so a nutrient added to this class is scaled by construction+ * at every caller instead of being silently dropped by the callers that+ * happen to enumerate fields by hand.+ */+fun NutritionData.scaledBy(factor: Double): NutritionData = NutritionData(+ protein = protein * factor,+ carbohydrates = carbohydrates * factor,+ fat = fat * factor,+ fiber = fiber * factor,+ sugar = sugar * factor,+ sodium = sodium * factor,+ biotin = biotin * factor,+ caffeine = caffeine * factor,+ calcium = calcium * factor,+ chloride = chloride * factor,+ cholesterol = cholesterol * factor,+ chromium = chromium * factor,+ copper = copper * factor,+ folate = folate * factor,+ folicAcid = folicAcid * factor,+ iodine = iodine * factor,+ iron = iron * factor,+ magnesium = magnesium * factor,+ manganese = manganese * factor,+ molybdenum = molybdenum * factor,+ monounsaturatedFat = monounsaturatedFat * factor,+ niacin = niacin * factor,+ pantothenicAcid = pantothenicAcid * factor,+ phosphorus = phosphorus * factor,+ polyunsaturatedFat = polyunsaturatedFat * factor,+ potassium = potassium * factor,+ riboflavin = riboflavin * factor,+ saturatedFat = saturatedFat * factor,+ selenium = selenium * factor,+ thiamin = thiamin * factor,+ transFat = transFat * factor,+ unsaturatedFat = unsaturatedFat * factor,+ vitaminA = vitaminA * factor,+ vitaminB12 = vitaminB12 * factor,+ vitaminB6 = vitaminB6 * factor,+ vitaminC = vitaminC * factor,+ vitaminD = vitaminD * factor,+ vitaminE = vitaminE * factor,+ vitaminK = vitaminK * factor,+ zinc = zinc * factor,+ calories = calories * factor,+)++/** Field-wise sum, for accumulating scaled ingredient contributions. */+operator fun NutritionData.plus(other: NutritionData): NutritionData = NutritionData(+ protein = protein + other.protein,+ carbohydrates = carbohydrates + other.carbohydrates,+ fat = fat + other.fat,+ fiber = fiber + other.fiber,+ sugar = sugar + other.sugar,+ sodium = sodium + other.sodium,+ biotin = biotin + other.biotin,+ caffeine = caffeine + other.caffeine,+ calcium = calcium + other.calcium,+ chloride = chloride + other.chloride,+ cholesterol = cholesterol + other.cholesterol,+ chromium = chromium + other.chromium,+ copper = copper + other.copper,+ folate = folate + other.folate,+ folicAcid = folicAcid + other.folicAcid,+ iodine = iodine + other.iodine,+ iron = iron + other.iron,+ magnesium = magnesium + other.magnesium,+ manganese = manganese + other.manganese,+ molybdenum = molybdenum + other.molybdenum,+ monounsaturatedFat = monounsaturatedFat + other.monounsaturatedFat,+ niacin = niacin + other.niacin,+ pantothenicAcid = pantothenicAcid + other.pantothenicAcid,+ phosphorus = phosphorus + other.phosphorus,+ polyunsaturatedFat = polyunsaturatedFat + other.polyunsaturatedFat,+ potassium = potassium + other.potassium,+ riboflavin = riboflavin + other.riboflavin,+ saturatedFat = saturatedFat + other.saturatedFat,+ selenium = selenium + other.selenium,+ thiamin = thiamin + other.thiamin,+ transFat = transFat + other.transFat,+ unsaturatedFat = unsaturatedFat + other.unsaturatedFat,+ vitaminA = vitaminA + other.vitaminA,+ vitaminB12 = vitaminB12 + other.vitaminB12,+ vitaminB6 = vitaminB6 + other.vitaminB6,+ vitaminC = vitaminC + other.vitaminC,+ vitaminD = vitaminD + other.vitaminD,+ vitaminE = vitaminE + other.vitaminE,+ vitaminK = vitaminK + other.vitaminK,+ zinc = zinc + other.zinc,+ calories = calories + other.calories,+)
health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.ktindex 1f5faef290..c3f8d9a611 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt@@ -5,6 +5,8 @@ import com.vayunmathur.health.R import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.NutritionData import com.vayunmathur.health.data.RecordType+import com.vayunmathur.health.data.plus+import com.vayunmathur.health.data.scaledBy import com.vayunmathur.health.ui.HealthMetricConfig import com.vayunmathur.health.ui.HistoryItem import com.vayunmathur.health.ui.MetricDashboardData@@ -429,29 +431,18 @@ internal object HealthChartData { quantity: Double, ): NutritionData { val ingredients = repository.getIngredientsForRecipe(recipeId)- var protein = 0.0- var carbs = 0.0- var fat = 0.0- var fiber = 0.0- var sugar = 0.0- var sodium = 0.0- var kcal = 0.0-+ var total = NutritionData() ingredients.forEach { ri -> val ing = repository.getIngredient(ri.ingredientId) ?: return@forEach val units = repository.getUnitsForIngredient(ing.id) val unit = units.find { it.id == ri.unitId } val grams = unit?.grams ?: 1.0 val totalGrams = ri.quantity * grams * quantity- // Nutrition facts are per 100g; scale to the actual grams in the recipe.- protein += (ing.nutritionData.protein / GRAMS_PER_100G) * totalGrams- carbs += (ing.nutritionData.carbohydrates / GRAMS_PER_100G) * totalGrams- fat += (ing.nutritionData.fat / GRAMS_PER_100G) * totalGrams- fiber += (ing.nutritionData.fiber / GRAMS_PER_100G) * totalGrams- sugar += (ing.nutritionData.sugar / GRAMS_PER_100G) * totalGrams- sodium += (ing.nutritionData.sodium / GRAMS_PER_100G) * totalGrams- kcal += (ing.nutritionData.calories / GRAMS_PER_100G) * totalGrams+ // Nutrition facts are per 100g; scale every field to the actual+ // grams in the recipe (scaledBy owns the field list, so+ // micronutrients are not dropped here).+ total += ing.nutritionData.scaledBy(totalGrams / GRAMS_PER_100G) }- return NutritionData(protein, carbs, fat, fiber, sugar, sodium, calories = kcal)+ return total } }
health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.ktindex 0401798a0d..bdf4fa39a2 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt@@ -28,6 +28,7 @@ import com.vayunmathur.health.data.RecipeIngredient import com.vayunmathur.health.data.Record import com.vayunmathur.health.data.RecordType import com.vayunmathur.health.data.ServingUnit+import com.vayunmathur.health.data.scaledBy import com.vayunmathur.health.data.storedBodyFatRecord import com.vayunmathur.health.data.storedBodyWaterMassRecord import com.vayunmathur.health.data.storedBoneMassRecord@@ -386,18 +387,11 @@ class HealthViewModel( val nutrition: NutritionData = when (target) { is LogMealTarget.FromRecipe -> HealthChartData.computeRecipeNutrition(repository, target.recipeId, quantity)- is LogMealTarget.FromIngredient -> {- val ing = target.ingredient- NutritionData(- protein = ing.nutritionData.protein * quantity,- carbohydrates = ing.nutritionData.carbohydrates * quantity,- fat = ing.nutritionData.fat * quantity,- fiber = ing.nutritionData.fiber * quantity,- sugar = ing.nutritionData.sugar * quantity,- sodium = ing.nutritionData.sodium * quantity,- calories = ing.nutritionData.calories * quantity,- )- }+ is LogMealTarget.FromIngredient ->+ // Quantity is in 100g units (the dialog labels it+ // "Quantity x 100g") and the facts are per 100g, so this+ // is a plain scale of every field, micronutrients included.+ target.ingredient.nutritionData.scaledBy(quantity) } val displayName = when (target) { is LogMealTarget.FromRecipe -> target.name
health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.ktindex 9762dfc768..9b45e835c1 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt@@ -276,4 +276,45 @@ class HealthChartDataTest { val total = HealthChartData.computeRecipeNutrition(repo, "rcp-chart-1", 2.0) assertEquals(400.0, total.calories) }++ @Test+ fun `recipe nutrition keeps micronutrients scaled to grams used`() = runTest {+ val repo = repository()+ // Per-100g facts carrying fields beyond the seven macros the old+ // hand-enumerated scaling kept: logging this recipe used to store+ // all of these as 0.0.+ val ingredient = Ingredient(+ id = "ing-chart-micro",+ originalName = "Spinach",+ nutritionData = NutritionData(+ protein = 2.0, carbohydrates = 3.0, fat = 1.0, fiber = 2.0,+ sugar = 1.0, sodium = 80.0, calcium = 100.0, iron = 4.0,+ potassium = 500.0, cholesterol = 10.0, saturatedFat = 0.5,+ vitaminA = 900.0, vitaminC = 30.0, vitaminD = 2.0,+ calories = 25.0,+ ),+ )+ val unit = ServingUnit(id = "unit-chart-micro", ingredientId = ingredient.id, name = "Gram", grams = 1.0)+ repo.insertIngredient(ingredient)+ repo.insertServingUnit(unit)+ repo.insertRecipe(Recipe(id = "rcp-chart-micro", name = "Salad"))+ repo.insertRecipeIngredient(+ RecipeIngredient(id = "ri-chart-micro", recipeId = "rcp-chart-micro", ingredientId = ingredient.id, quantity = 50.0, unitId = unit.id)+ )+ // 50g is half the per-100g facts; one serving.+ val scaled = HealthChartData.computeRecipeNutrition(repo, "rcp-chart-micro", 1.0)+ assertEquals(50.0, scaled.calcium)+ assertEquals(2.0, scaled.iron)+ assertEquals(250.0, scaled.potassium)+ assertEquals(5.0, scaled.cholesterol)+ assertEquals(0.25, scaled.saturatedFat)+ assertEquals(450.0, scaled.vitaminA)+ assertEquals(15.0, scaled.vitaminC)+ assertEquals(1.0, scaled.vitaminD)+ assertEquals(12.5, scaled.calories)+ // Two servings double every field, not just calories.+ val doubled = HealthChartData.computeRecipeNutrition(repo, "rcp-chart-micro", 2.0)+ assertEquals(100.0, doubled.calcium)+ assertEquals(30.0, doubled.vitaminC)+ } }
health/src/test/java/com/vayunmathur/health/util/HealthViewModelTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthViewModelTest.kt b/health/src/test/java/com/vayunmathur/health/util/HealthViewModelTest.ktindex 706e6bec26..3b47fe5510 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthViewModelTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthViewModelTest.kt@@ -223,6 +223,46 @@ class HealthViewModelTest { assertEquals("Oats", rows.first().metadata) } + @Test+ fun `log meal from ingredient keeps micronutrients scaled by quantity`() = runTest {+ val repo = repository()+ val vm = viewModel()+ HealthAPI.initLocal(context, repo)+ // Per-100g facts with micronutrients: the old hand-enumerated copy+ // stored only protein/carbs/fat/fiber/sugar/sodium/calories and+ // silently zeroed the rest in the logged record (and therefore in+ // the day totals and the Health Connect export built from it).+ val ingredient = Ingredient(+ id = "ing-vm-micro",+ originalName = "Spinach",+ nutritionData = NutritionData(+ protein = 2.0, carbohydrates = 3.0, fat = 1.0, fiber = 2.0,+ sugar = 1.0, sodium = 80.0, calcium = 100.0, iron = 4.0,+ potassium = 500.0, vitaminC = 30.0, vitaminD = 2.0,+ calories = 25.0,+ ),+ )+ repo.insertIngredient(ingredient)+ // A day no other test logs on: the in-memory database is shared+ // across this class, so reusing another test's instant would leak+ // this row into its unfiltered range query.+ val at = Instant.parse("2026-03-06T09:30:00Z")+ // Quantity is in 100g units, so 2.0 means 200g: double every field.+ vm.logMeal(HealthViewModel.LogMealTarget.FromIngredient(ingredient), 2.0, at)+ val start = kotlin.time.Instant.fromEpochMilliseconds(at.toEpochMilli() - 3_600_000)+ val end = kotlin.time.Instant.fromEpochMilliseconds(at.toEpochMilli() + 3_600_000)+ settle { repo.getAllInRange(RecordType.Nutrition, start, end).first().any { it.metadata == "Spinach" } }+ val stored = repo.getAllInRange(RecordType.Nutrition, start, end).first()+ .first { it.metadata == "Spinach" }.nutritionData+ assertNotNull(stored)+ assertEquals(200.0, stored.calcium)+ assertEquals(8.0, stored.iron)+ assertEquals(1000.0, stored.potassium)+ assertEquals(60.0, stored.vitaminC)+ assertEquals(4.0, stored.vitaminD)+ assertEquals(50.0, stored.calories)+ }+ @Test fun `ingredient crud round trips`() = runTest { val repo = repository()