Modern Apps git

← Modern-Apps.git

health: day view summed averages and lost midnight-crossing records (#947)

Commit
dfde2c7471b3b94d65bd752a2a9b7fc664b2d5b6
Author
Vayun Mathur <[email protected]>
When
2026-11-30 18:46 UTC (5 days ago)
Parents
6271713
Four construction bugs made day-view values wrong. (1) The day tab summed hourly AVERAGES for line metrics (heart rate, weight, height, BP and every other continuous metric) — replaced with proper averaging via dayAverage for line metrics. (2) Range queries used startTime >= :start AND endTime <= :end, so any interval crossing midnight (sleep, exercise, steps, hydration) vanished from BOTH days and a point exactly at 00:00 counted in both — now half-open [start, end) bucketed by start. (3) Four screens computed a 'day' as start + 24.hours — on DST spring-forward the range leaked an hour of the next day, on fall-back it dropped the day's last hour — now HealthChartData.dayRange() (next calendar midnight) everywhere. (4) Basal metabolic rate, stored kcal/day (a rate), was summed as a cumulative — reclassified as an averaged line metric.

Sum semantics for genuinely cumulative metrics (steps, distance, water, workout minutes, nutrition) verified correct and untouched; kg/lb and sleep-hours conversions verified correct.

New DayView947Test (day averaging, DST 23h/25h ranges, straddle/midnight bucketing, cm-m round trip) and updated HealthDaoTest expectations. Verified: :health:testDevUnitTest 640 tests, 0 failures; lint errors are pre-existing detector findings in untouched files.

Diff

health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex a58f81e831..f713f4f174 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -19,6 +19,7 @@ _Install: ./install health (dev by default)._ **Architecture / data-flow:** `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicationSchedule`, `MedicalRecords`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule`; reminders flow `DoseScheduler` → receivers → `DoseReminderActivity` + `service/DoseSoundService`. **Entry points + reading order:** `MainActivity.kt` → `ui/TodayPage.kt` → `platform/MedicalViewModel.kt` → `data/HealthRepository.kt` → `domain/FhirRecords.kt` → `platform/DoseScheduler.kt`. **Gotchas:**+- Day views use half-open local-calendar ranges (`HealthChartData.dayRange`, DAO `startTime in [start, end)`, bucketed by start): DST days are 23/25h, midnight point records belong to the new day, and intervals crossing midnight count on their start day. Day-tab line metrics average their hourly averages; bar metrics sum their hourly sums; basal metabolic rate (stored kcal/day) is an averaged line metric, while Today hydration converts stored litres to ml. - `util/` is NOT a closed package root — don't add more files there - Medical data is dual-homed (Room + Health Connect) — writes must update both or they diverge - Dose reminders need the boot path re-armed like clock alarms; sound runs through a foreground service
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex 974d703d08..5dc4133852 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -156,9 +156,16 @@ interface HealthDao {     @Query("SELECT * FROM Record WHERE type = :type ORDER BY startTime DESC LIMIT 1")     suspend fun getLastRecord(type: RecordType): Record? +    // Range queries below are half-open on startTime: [startTime, endTime). A record is+    // bucketed by the day/hour its startTime falls in (matching the GROUP BY below), so a+    // point record exactly at midnight belongs only to the new day, and an interval that+    // straddles the range end (e.g. a sleep/exercise/step record crossing midnight) is+    // counted on its start day instead of vanishing from both days (#947). The previous+    // `endTime <= :endTime` containment dropped every straddling record and double-counted+    // midnight point records.     @Query(         "SELECT COALESCE(SUM(CASE WHEN :type = 'Nutrition' THEN nutrition_calories ELSE value END), 0.0) " +-            "FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime"+            "FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime"     )     fun sumInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double> @@ -210,7 +217,7 @@ interface HealthDao {             COALESCE(SUM(nutrition_vitaminK), 0.0) AS vitaminK,             COALESCE(SUM(nutrition_zinc), 0.0) AS zinc,             COALESCE(SUM(nutrition_calories), 0.0) AS calories-        FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime+        FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime     """)     fun sumNutritionInRange(         type: RecordType,@@ -218,11 +225,11 @@ interface HealthDao {         endTime: kotlin.time.Instant,     ): Flow<NutritionData> -    @Query("SELECT MIN(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT MIN(value) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")     fun minInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double?>-    @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT MAX(value) FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")     fun maxInRange(type: RecordType, startTime: kotlin.time.Instant, endTime: kotlin.time.Instant): Flow<Double?>-    @Query("SELECT * FROM Record WHERE type = :type AND startTime >= :startTime AND endTime <= :endTime")+    @Query("SELECT * FROM Record WHERE type = :type AND startTime >= :startTime AND startTime < :endTime")     fun getAllInRange(         type: RecordType,         startTime: kotlin.time.Instant,@@ -237,7 +244,7 @@ interface HealthDao {     FROM Record      WHERE type = :type        AND startTime >= :startTime -      AND endTime <= :endTime+      AND startTime < :endTime     GROUP BY day     ORDER BY day ASC """)@@ -255,7 +262,7 @@ interface HealthDao {     FROM Record      WHERE type = :type        AND startTime >= :startTime -      AND endTime <= :endTime+      AND startTime < :endTime     GROUP BY hourBlock     ORDER BY hourBlock ASC """)@@ -273,7 +280,7 @@ interface HealthDao {     FROM Record      WHERE type = :type        AND startTime >= :startTime -      AND endTime <= :endTime+      AND startTime < :endTime     GROUP BY day     ORDER BY day ASC """)@@ -291,7 +298,7 @@ interface HealthDao {     FROM Record      WHERE type = :type        AND startTime >= :startTime -      AND endTime <= :endTime+      AND startTime < :endTime     GROUP BY hourBlock     ORDER BY hourBlock ASC """)
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 1055f897a3..86fec5f5ad 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthChartData.kt@@ -17,6 +17,7 @@ import com.vayunmathur.library.util.localizedMonthNames import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.isoDayNumber import kotlinx.datetime.minus import kotlinx.datetime.number@@ -50,6 +51,18 @@ internal object HealthChartData {     /** Nutrition facts are quoted per this many grams. */     private const val GRAMS_PER_100G = 100.0 +    /**+     * The half-open local-calendar day range [start of [day], start of next day) in [tz].+     * Calendar arithmetic, not `start + 24h`: DST days are 23/25 hours long, and a fixed+     * 24-hour span leaks the next day's first hour (spring) or drops the day's last hour+     * (fall) from Today/Nutrition day views (#947).+     */+    internal fun dayRange(+        day: LocalDate,+        tz: TimeZone,+    ): Pair<kotlin.time.Instant, kotlin.time.Instant> =+        day.atStartOfDayIn(tz) to day.plus(1, DateTimeUnit.DAY).atStartOfDayIn(tz)+     /** Date range and aggregation periods for each chart tab. */     internal fun resolveChartRange(         anchorDate: LocalDate,@@ -246,12 +259,26 @@ internal object HealthChartData {         } else {             if (config.isDualSeries) history.mapNotNull { it.secondaryValue } else emptyList()         }+        // Day tab: rawPairs are hourly buckets. Bar metrics bucket hourly *sums*, so the+        // day value is their sum; line metrics bucket hourly *averages*, so the day value+        // must average them — summing averaged weight/heart-rate/BP hourly values showed+        // e.g. a whole day of hourly weights added together (#947).+        val dayPrimary = when {+            nonNullPrimary.isEmpty() -> 0.0+            config.isLineChart -> nonNullPrimary.average()+            else -> nonNullPrimary.sum()+        }+        val daySecondary = when {+            nonNullSecondary.isEmpty() -> null+            config.isLineChart -> nonNullSecondary.average()+            else -> nonNullSecondary.sum()+        }         return MetricDashboardData(-            totalValue = nonNullPrimary.sum(),+            totalValue = if (selectedTab == 0) dayPrimary else nonNullPrimary.sum(),             dailyAverage = if (nonNullPrimary.isEmpty()) 0.0-            else (if (selectedTab == 0) nonNullPrimary.sum() else nonNullPrimary.average()),-            secondaryAverage = if (nonNullSecondary.isEmpty()) null-            else (if (selectedTab == 0) nonNullSecondary.sum() else nonNullSecondary.average()),+            else (if (selectedTab == 0) dayPrimary else nonNullPrimary.average()),+            secondaryAverage = if (selectedTab == 0) daySecondary+            else if (nonNullSecondary.isEmpty()) null else nonNullSecondary.average(),             chartData = mappedChart,             secondaryChartData = mappedSecondaryChart,             historyItems = history,
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 e9267941c3..9f86245a3a 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthViewModel.kt@@ -136,7 +136,7 @@ class HealthViewModel(     fun sleepRecordForDay(day: LocalDate): Flow<Record?> {         val tz = TimeZone.currentSystemDefault()         val searchStart = day.atStartOfDayIn(tz).minus(12.hours)-        val searchEnd = day.atStartOfDayIn(tz).plus(24.hours)+        val searchEnd = day.plus(1, DateTimeUnit.DAY).atStartOfDayIn(tz)         return repository.getAllInRange(RecordType.Sleep, searchStart, searchEnd)             .onEach { _hasLoadedRecords.value = true }             .map { records ->
health/src/main/java/com/vayunmathur/health/ui/HealthMetricConfig.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/HealthMetricConfig.kt b/health/src/main/java/com/vayunmathur/health/ui/HealthMetricConfig.ktindex 18ff8becd2..fe917f4b3e 100644--- a/health/src/main/java/com/vayunmathur/health/ui/HealthMetricConfig.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/HealthMetricConfig.kt@@ -23,8 +23,11 @@ enum class HealthMetricConfig(         "cal",         500.0     ),+    // Basal rate is stored kcal/day (a rate, not a cumulative total), so it must be+    // averaged like the other line metrics — summing hourly/daily rates overstates it (#947).     BASAL_METABOLIC_RATE(-        R.string.metric_basal_metabolic_rate, RecordType.CaloriesBasal, "cal", 1800.0+        R.string.metric_basal_metabolic_rate, RecordType.CaloriesBasal, "cal", 1800.0,+        isLineChart = true, useDecimals = true     ),     STEPS(         R.string.metric_steps,
health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt b/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.ktindex fd1f8bb93c..d0c4f27545 100644--- a/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/NutritionDetailsPage.kt@@ -12,7 +12,6 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.TimeZone-import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.minus import kotlinx.datetime.plus import kotlinx.datetime.todayIn@@ -42,7 +41,6 @@ import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.round import kotlin.time.Clock-import kotlin.time.Duration.Companion.hours  /** Full per-day nutrition breakdown — heavy content lives here. */ @OptIn(ExperimentalMaterial3Api::class)@@ -61,8 +59,8 @@ fun NutritionDetailsPage(backStack: NavBackStack<Route>, viewModel: HealthViewMo     ) { padding ->         HorizontalPager(state = pagerState, modifier = Modifier.fillMaxSize()) { page ->             val day = today.minus(initialPage - page, DateTimeUnit.DAY)-            val dayStart = day.atStartOfDayIn(tz)-            val dayEnd = dayStart.plus(24.hours)+            val (dayStart, dayEnd) =+                com.vayunmathur.health.platform.HealthChartData.dayRange(day, tz)              val loggedMeals by remember(dayStart, dayEnd) {                 viewModel.getAllRecordsInRange(RecordType.Nutrition, dayStart, dayEnd)
health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt b/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.ktindex 06c3b294dc..571a60305d 100644--- a/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt@@ -26,7 +26,6 @@ import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.ToggleFloatingActionButton import kotlinx.datetime.TimeZone-import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.plus import kotlinx.datetime.todayIn import androidx.compose.runtime.Composable@@ -55,7 +54,6 @@ import com.vayunmathur.health.platform.NutritionUiState import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.round import kotlin.time.Clock-import kotlin.time.Duration.Companion.hours  /** Immutable value describing nutrient dv. */ data class NutrientDV(@@ -120,8 +118,7 @@ internal val hydrationNutrient = NutrientDV("Hydration", 3.0, "L") { 0.0 } fun NutritionPage(backStack: NavBackStack<Route>, viewModel: HealthViewModel) {     val tz = TimeZone.currentSystemDefault()     val today = Clock.System.todayIn(tz)-    val dayStart = today.atStartOfDayIn(tz)-    val dayEnd = dayStart.plus(24.hours)+    val (dayStart, dayEnd) = com.vayunmathur.health.platform.HealthChartData.dayRange(today, tz)      val totals by remember(dayStart, dayEnd) {         viewModel.sumNutritionInRange(RecordType.Nutrition, dayStart, dayEnd)
health/src/main/java/com/vayunmathur/health/ui/TodayPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/TodayPage.kt b/health/src/main/java/com/vayunmathur/health/ui/TodayPage.ktindex 9f41fc42e8..7122a94f9a 100644--- a/health/src/main/java/com/vayunmathur/health/ui/TodayPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/TodayPage.kt@@ -50,10 +50,8 @@ import com.vayunmathur.library.util.sharedText import com.vayunmathur.library.util.round import kotlinx.coroutines.flow.map import kotlinx.datetime.TimeZone-import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock-import kotlin.time.Duration.Companion.hours  /** Binds [HealthViewModel] and the back stack to the stateless [TodayScreen]. */ @Composable@@ -62,8 +60,7 @@ fun TodayPage(backStack: NavBackStack<Route>, viewModel: HealthViewModel) {     val today = now.date      val dayRange = remember(today) {-        val start = today.atStartOfDayIn(TimeZone.currentSystemDefault())-        start to start.plus(24.hours)+        com.vayunmathur.health.platform.HealthChartData.dayRange(today, TimeZone.currentSystemDefault())     }     val dayStart = dayRange.first     val dayEnd = dayRange.second
health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt b/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.ktindex 276d56d367..7282fbeacf 100644--- a/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt+++ b/health/src/test/java/com/vayunmathur/health/data/HealthDaoTest.kt@@ -91,14 +91,57 @@ class HealthDaoTest {             listOf(                 record("in1", startMillis = 1_000L, endMillis = 2_000L, value = 10.0),                 record("in2", startMillis = 3_000L, endMillis = 4_000L, value = 20.0),-                // Starts inside but ends outside: excluded by the end bound.-                record("out", startMillis = 5_000L, endMillis = 50_000L, value = 100.0),+                // Starts after the window: excluded by the start bound.+                record("out", startMillis = 50_000L, endMillis = 51_000L, value = 100.0),             )         )         val (start, end) = range()         assertEquals(30.0, dao.sumInRange(RecordType.Steps, start, end).first())     } +    @Test+    fun `sumInRange counts a straddling interval on its start day - 947`() = runTest {+        // Interval crossing the range end (e.g. steps/sleep/exercise over midnight)+        // used to vanish from both days under `endTime <= :endTime` containment (#947).+        dao.upsert(+            listOf(record("straddle", startMillis = 5_000L, endMillis = 50_000L, value = 100.0))+        )+        val (start, end) = range()+        assertEquals(100.0, dao.sumInRange(RecordType.Steps, start, end).first())+        // ...and is not counted again by the following window (its start is before it).+        val next = dao.sumInRange(+            RecordType.Steps,+            kotlin.time.Instant.fromEpochMilliseconds(10_000L),+            kotlin.time.Instant.fromEpochMilliseconds(60_000L),+        ).first()+        assertEquals(0.0, next)+    }++    @Test+    fun `midnight point record belongs only to the new day - 947`() = runTest {+        dao.upsert(+            listOf(record("midnight", startMillis = 10_000L, endMillis = 10_000L, value = 42.0))+        )+        val before = dao.sumInRange(+            RecordType.Steps,+            kotlin.time.Instant.fromEpochMilliseconds(0),+            kotlin.time.Instant.fromEpochMilliseconds(10_000L),+        ).first()+        val after = dao.sumInRange(+            RecordType.Steps,+            kotlin.time.Instant.fromEpochMilliseconds(10_000L),+            kotlin.time.Instant.fromEpochMilliseconds(20_000L),+        ).first()+        assertEquals(0.0, before)+        assertEquals(42.0, after)+        val inDay = dao.getAllInRange(+            RecordType.Steps,+            kotlin.time.Instant.fromEpochMilliseconds(10_000L),+            kotlin.time.Instant.fromEpochMilliseconds(20_000L),+        ).first().map { it.id }+        assertEquals(listOf("midnight"), inDay)+    }+     @Test     fun `nutrition sums read the calories column`() = runTest {         val nutrition = record("n1", type = RecordType.Nutrition, value = 999.0)
health/src/test/java/com/vayunmathur/health/ui/BarChartBinderTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/BarChartBinderTest.kt b/health/src/test/java/com/vayunmathur/health/ui/BarChartBinderTest.ktindex e25eae2a6d..6b95a414af 100644--- a/health/src/test/java/com/vayunmathur/health/ui/BarChartBinderTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/BarChartBinderTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.health.ui +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText
health/src/test/java/com/vayunmathur/health/ui/HealthTodayW6Test.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/HealthTodayW6Test.kt b/health/src/test/java/com/vayunmathur/health/ui/HealthTodayW6Test.ktindex ce8db7adcc..ea0f55c3b6 100644--- a/health/src/test/java/com/vayunmathur/health/ui/HealthTodayW6Test.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/HealthTodayW6Test.kt@@ -1,5 +1,7 @@ package com.vayunmathur.health.ui +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onAllNodesWithText
health/src/test/java/com/vayunmathur/health/ui/NutritionDetailsDeleteTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/NutritionDetailsDeleteTest.kt b/health/src/test/java/com/vayunmathur/health/ui/NutritionDetailsDeleteTest.ktindex c9e0ad1c9f..ecf8014596 100644--- a/health/src/test/java/com/vayunmathur/health/ui/NutritionDetailsDeleteTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/NutritionDetailsDeleteTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.health.ui +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performTouchInput
health/src/test/java/com/vayunmathur/health/ui/NutritionPageBindingTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/NutritionPageBindingTest.kt b/health/src/test/java/com/vayunmathur/health/ui/NutritionPageBindingTest.ktindex 3ed30b6deb..601577f17f 100644--- a/health/src/test/java/com/vayunmathur/health/ui/NutritionPageBindingTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/NutritionPageBindingTest.kt@@ -1,5 +1,7 @@ package com.vayunmathur.health.ui +// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch.+ import android.app.Application import androidx.compose.ui.test.hasClickAction import androidx.compose.ui.test.junit4.createComposeRule
health/src/test/java/com/vayunmathur/health/util/DayView947Test.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/DayView947Test.kt b/health/src/test/java/com/vayunmathur/health/util/DayView947Test.ktnew file mode 100644index 0000000000..926f2a140e--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/util/DayView947Test.kt@@ -0,0 +1,111 @@+package com.vayunmathur.health.util++import com.vayunmathur.health.platform.HealthChartData+import com.vayunmathur.health.ui.HealthMetricConfig+import com.vayunmathur.library.util.Tuple3+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone++/**+ * Regression tests for #947 (day view displayed wrong values).+ *+ * Day-tab buckets are hourly: bar metrics hold hourly sums (the day value is their+ * sum) while line metrics hold hourly averages (the day value is their average).+ * Day ranges are local calendar days, not fixed 24-hour spans.+ */+class DayView947Test {++    @Test+    fun `weight day view averages hourly averages instead of summing them`() {+        val pairs = listOf(Tuple3(0L, 70.0, 0.0), Tuple3(1L, 80.0, 0.0))+        val data = HealthChartData.buildDashboardData(+            HealthMetricConfig.WEIGHT, 0, pairs,+            listOf("a" to 70.0, "b" to 80.0), null, emptyList(),+        )+        assertEquals(75.0, data.dailyAverage)+        assertEquals(75.0, data.totalValue)+    }++    @Test+    fun `blood pressure day view averages both series`() {+        val pairs = listOf(Tuple3(0L, 120.0, 80.0), Tuple3(1L, 130.0, 90.0))+        val data = HealthChartData.buildDashboardData(+            HealthMetricConfig.BLOOD_PRESSURE, 0, pairs,+            listOf("a" to 120.0, "b" to 130.0), listOf("a" to 80.0, "b" to 90.0), emptyList(),+        )+        assertEquals(125.0, data.dailyAverage)+        assertEquals(85.0, data.secondaryAverage)+    }++    @Test+    fun `height day view averages scaled centimetres`() {+        val scaled = HealthChartData.scaleForDisplay(+            HealthMetricConfig.HEIGHT,+            listOf(Tuple3(0L, 1.70, 0.0), Tuple3(1L, 1.80, 0.0)),+        )+        val data = HealthChartData.buildDashboardData(+            HealthMetricConfig.HEIGHT, 0, scaled,+            scaled.map { it.first.toString() to it.second }, null, emptyList(),+        )+        assertEquals(175.0, data.dailyAverage)+    }++    @Test+    fun `steps and hydration day views still sum hourly sums`() {+        val steps = HealthChartData.buildDashboardData(+            HealthMetricConfig.STEPS, 0,+            listOf(Tuple3(0L, 100.0, 0.0), Tuple3(1L, 50.0, 0.0)),+            listOf("a" to 100.0, "b" to 50.0), null, emptyList(),+        )+        assertEquals(150.0, steps.dailyAverage)+        val water = HealthChartData.buildDashboardData(+            HealthMetricConfig.HYDRATION, 0,+            listOf(Tuple3(0L, 0.25, 0.0), Tuple3(1L, 0.5, 0.0)),+            listOf("a" to 0.25, "b" to 0.5), null, emptyList(),+        )+        // Stored/displayed litres in the chart (Today converts the same sum to ml).+        assertEquals(0.75, water.dailyAverage)+    }++    @Test+    fun `basal metabolic rate is averaged not summed`() {+        assertTrue(HealthMetricConfig.BASAL_METABOLIC_RATE.isLineChart)+        val data = HealthChartData.buildDashboardData(+            HealthMetricConfig.BASAL_METABOLIC_RATE, 0,+            listOf(Tuple3(0L, 1800.0, 0.0), Tuple3(1L, 1900.0, 0.0)),+            listOf("a" to 1800.0, "b" to 1900.0), null, emptyList(),+        )+        assertEquals(1850.0, data.dailyAverage)+    }++    @Test+    fun `day range is a calendar day across DST`() {+        val denver = TimeZone.of("America/Denver")+        // 2026-03-08 spring forward: 23-hour local day.+        val spring = HealthChartData.dayRange(LocalDate(2026, 3, 8), denver)+        assertEquals(23L, (spring.second - spring.first).inWholeHours)+        // 2026-11-01 fall back: 25-hour local day.+        val fall = HealthChartData.dayRange(LocalDate(2026, 11, 1), denver)+        assertEquals(25L, (fall.second - fall.first).inWholeHours)+        // Ordinary day, and the end is the next day's start (half-open).+        val plain = HealthChartData.dayRange(LocalDate(2026, 3, 4), denver)+        assertEquals(24L, (plain.second - plain.first).inWholeHours)+        assertEquals(+            HealthChartData.dayRange(LocalDate(2026, 3, 5), denver).first,+            plain.second,+        )+    }++    @Test+    fun `unit round trips keep stored units`() {+        // Height: entered cm -> stored m -> displayed cm.+        assertEquals(1.75, com.vayunmathur.health.domain.Centimeters(175.0).toMeters().value)+        assertEquals(+            175.0,+            com.vayunmathur.health.domain.Meters(1.75).toCentimeters().value,+        )+    }+}
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 1bd96673f6..9762dfc768 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt@@ -1,4 +1,6 @@ package com.vayunmathur.health.util++// FIXTURE RELATIVE-TIME EXCEPTION: timestamps are seeded relative to the wall clock the code under test reads internally, so the fresh/expired/relative-time branch under test keeps its meaning; a fixed past instant would silently change that branch. import com.vayunmathur.health.data.HealthAPI import com.vayunmathur.health.platform.HealthChartData