Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions app/src/main/kotlin/org/openstrap/app/ui/dashboard/DayViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ data class ActivityHistory(
}
}

/**
* What the week view shows of the days after the one shown: each day's active minutes, and the time asleep of each
* night by the morning it ended on. The day shown has neither for the days after it.
*/
data class WeekLater(val active: Map<LocalDate, Int> = emptyMap(), val asleepByMorning: Map<LocalDate, Long> = emptyMap())

/** How long synced data must settle before the day's scores are worked out again. */
private const val CHANGES_SETTLE_MS = 800L

Expand Down Expand Up @@ -380,6 +386,30 @@ class DayViewModel(
.onStart<RecoveryState> { emit(RecoveryState.Loading) }
}

/**
* The week ending on [end] as its last day has it, for the week view of an earlier day: active minutes are worked
* out for the days ending on the day asked, and nights load up to it, so the day shown has nothing for the days
* after it. The night after [end] belongs to the next morning, so nights are read as of that day, or today.
* Empty until read, and where the active minutes can't be worked out.
*/
@OptIn(FlowPreview::class)
fun weekThrough(end: LocalDate): Flow<WeekLater> {
val now = Today.on(clock())
val morning = minOf(end.plusDays(1), now)
val active = combine(profile, repo.changes().debounce(CHANGES_SETTLE_MS)) { p, _ -> p }
.mapLatest { p ->
withContext(work) {
catching { repo.recovery(end, p).activity?.byDay.orEmpty().mapValues { it.value.equivalent } }
.onFailure { Log.w("unstrap", "the week's active minutes failed", it) }
.getOrDefault(emptyMap())
}
}
val asleep = repo.day(morning, morning == now)
.map { d -> d.nights.mapNotNull { n -> n.asleepSeconds?.let { n.date to it } }.toMap() }
return combine(active.onStart { emit(emptyMap()) }, asleep.onStart { emit(emptyMap()) }, ::WeekLater)
.distinctUntilChanged().flowOn(work)
}

/**
* Yesterday's score for a failed [date]: from the last Recovery worked out when its week covers yesterday, else
* worked out for yesterday itself; null when that fails too.
Expand Down
22 changes: 20 additions & 2 deletions app/src/main/kotlin/org/openstrap/app/ui/glow/ActivityDetail.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.openstrap.app.ui.glow

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import org.openstrap.app.data.Weeks
import org.openstrap.app.presentation.Units
import org.openstrap.app.presentation.LoadBand
Expand Down Expand Up @@ -63,6 +65,7 @@ import org.openstrap.app.presentation.Range
import org.openstrap.app.ui.dashboard.Score
import org.openstrap.app.presentation.TabCopy
import org.openstrap.app.presentation.TodayCopy
import org.openstrap.app.ui.dashboard.WeekLater
import org.openstrap.app.ui.dashboard.WeekStory
import org.openstrap.app.ui.theme.AppIcons
import org.openstrap.app.ui.theme.MetricColors
Expand Down Expand Up @@ -94,6 +97,8 @@ internal class ActivityDetailContext(
val onBack: () -> Unit,
/** The day picked, which the strip shows at once while [state] and [r] may still be the last day's. */
val stripDate: LocalDate = state.date,
/** The week ending on a day as that day has it, for the week view's days after the one shown. */
val weekThrough: (LocalDate) -> Flow<WeekLater> = { flowOf(WeekLater()) },
) {
val today: LocalDate get() = LocalDate.now()
val isToday: Boolean get() = state.date == today
Expand Down Expand Up @@ -954,6 +959,18 @@ private fun ActivityRelated(current: Score, ctx: ActivityDetailContext, heartPoi

/* ----------------------------------------------- Week ----------------------------------------------- */

/**
* The week ending on [end] as that day has it. A past day has no active minutes or nights for the days after it, so
* those come from the week's last day. The night after the day shown is one of them, even on the week's last day.
*/
@Composable
private fun weekLater(ctx: ActivityDetailContext, end: LocalDate): WeekLater {
val later by remember(end, ctx.state.date, ctx.weekThrough) {
if (ctx.state.date < LocalDate.now()) ctx.weekThrough(end) else flowOf(WeekLater())
}.collectAsStateWithLifecycle(WeekLater())
return later
}

/**
* The week story, opened from Your week on Today: the card's own week (the phone's first day to its last, up to the day
* shown), steps a day as dot bars to scrub, the week in a few numbers, a sentence comparing with the week before where
Expand All @@ -973,12 +990,13 @@ internal fun WeekDetail(ctx: ActivityDetailContext) {
val zone = ZoneId.systemDefault()
fun dayOf(w: WorkoutAnalysis) = Instant.ofEpochSecond(w.workout.start).atZone(zone).toLocalDate()
val stepsByDay = steps.orEmpty().associate { it.date to Math.round(it.value) }
val later = weekLater(ctx, end)
val days = WeekStory.days(
week, stepsByDay,
ctx.r?.activity?.byDay.orEmpty().mapValues { it.value.equivalent },
later.active + ctx.r?.activity?.byDay.orEmpty().mapValues { it.value.equivalent },
ctx.workouts.filter { dayOf(it) in start..end && it.workout.sportType != org.openstrap.app.data.Workouts.GENERIC_ACTIVITY }
.sortedBy { it.workout.start }.groupBy(::dayOf).mapValues { (_, v) -> v.map { it.sportName } },
ctx.state.nights.mapNotNull { n -> n.asleepSeconds?.let { n.date to it } }.toMap(),
later.asleepByMorning + ctx.state.nights.mapNotNull { n -> n.asleepSeconds?.let { n.date to it } }.toMap(),
)
// Steps a day leave out today while it's still going, so a morning's few steps don't pull the week down; today
// alone still counts, rather than nothing.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ internal fun DetailHost(
ActivityDetailContext(
day, shown.recovery, workouts, activity, histories.daily, onOpen = push, onSwitch = {},
onSelectDay = dayVm::select, onEditProfile = onOpenProfile, contentPadding = padding, onBack = pop,
weekThrough = dayVm::weekThrough,
),
)
is Detail.Workout -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,42 @@ class DayViewModelUiStateTest {
assertNull(s.stressStrip[10])
}

@Test fun `the week view gets the later days' active minutes and nights from the week's last day`() = runTest {
val repo = FakeDays()
val clock = FixedClock(Instant.parse("2026-01-25T12:00:00Z"))
val vm = DayViewModel(repo, clock = { clock.clock }, work = UnconfinedTestDispatcher(testScheduler))
// Thursday the 15th is shown, and its week ends on Sunday the 18th.
val sunday = date.plusDays(3)
fun night(morning: LocalDate) = org.openstrap.app.data.SleepNight(morning, SleepSession(0, 8 * 3600, lightMinutes = 420))
repo.changed = flowOf(Unit)
repo.result = { d ->
val day = org.openstrap.app.data.Activity.Day(
0, org.openstrap.app.data.Activity.Mvpa(0, 0, 0), 0, null, 8000,
byDay = mapOf(d to org.openstrap.app.data.Activity.Mvpa(10, 5, 0), d.minusDays(1) to org.openstrap.app.data.Activity.Mvpa(30, 0, 0)),
)
org.openstrap.app.data.RecoveryResult(
d, org.openstrap.app.data.Recovery.Readiness(null, emptyList(), 30, false, emptyList(), false),
org.openstrap.app.data.Recovery.ChargeDay(emptyList(), null, null, 0f, 0f, 0f, 0f, null, null, anchored = true), emptyList(),
0f, null, 52f, 190f, true, org.openstrap.app.data.Recovery.StressThreshold(60, null, 0), activity = day,
)
}
repo.nights = { d -> listOf(night(d.minusDays(1)), night(d)) }
val w = vm.weekThrough(sunday).first { it.active.isNotEmpty() && it.asleepByMorning.isNotEmpty() }
assertEquals(mapOf(sunday to 20, sunday.minusDays(1) to 30), w.active)
// Sunday's night ended on Monday morning, so the nights are Monday's.
assertEquals(setOf(sunday, sunday.plusDays(1)), w.asleepByMorning.keys)
assertEquals(sunday.plusDays(1) to false, repo.dayAsked)
// This week's last morning is today's, never tomorrow's.
val today = LocalDate.of(2026, 1, 25)
vm.weekThrough(today).first { it.asleepByMorning.isNotEmpty() }
assertEquals(today to true, repo.dayAsked)
// Active minutes that can't be worked out leave the nights standing.
repo.result = null
val nightsOnly = vm.weekThrough(sunday).first { it.asleepByMorning.isNotEmpty() }
assertTrue(nightsOnly.active.isEmpty())
vm.viewModelScope.coroutineContext[Job]?.cancel()
}

/** A day repository with one day of Heart points and energy, noting the windows asked for. */
private inner class FakeDays : DayRepository {
var paiWindow: Pair<LocalDate, LocalDate>? = null
Expand All @@ -231,12 +267,20 @@ class DayViewModelUiStateTest {
override fun personalBest(kind: String): Flow<org.openstrap.app.data.db.PersonalBest?> = stored
override suspend fun mostStepsBefore(date: LocalDate): Int = 25000

override fun day(date: LocalDate, isToday: Boolean): Flow<DayData> = flowOf(DayData(date, isToday))
var result: ((LocalDate) -> RecoveryResult)? = null
var changed: Flow<Unit> = emptyFlow()
var nights: (LocalDate) -> List<org.openstrap.app.data.SleepNight> = { emptyList() }
var dayAsked: Pair<LocalDate, Boolean>? = null

override fun day(date: LocalDate, isToday: Boolean): Flow<DayData> {
dayAsked = date to isToday
return flowOf(DayData(date, isToday, nights = nights(date)))
}
override fun daysWithData(): Flow<Set<LocalDate>> = flowOf(emptySet())
override suspend fun hourlySteps(from: LocalDate, to: LocalDate): Map<LocalDate, List<Float>> = emptyMap()
override suspend fun recovery(date: LocalDate, profile: UserProfile): RecoveryResult = error("not read here")
override suspend fun recovery(date: LocalDate, profile: UserProfile): RecoveryResult = result?.invoke(date) ?: error("not read here")
override suspend fun healthspan(date: LocalDate, profile: UserProfile): Healthspan.Outcome = error("not read here")
override fun changes(): Flow<Unit> = emptyFlow()
override fun changes(): Flow<Unit> = changed
override fun deletedSleep(): Flow<List<SleepEdits.Resolved>> = flowOf(emptyList())
override suspend fun setSleepTimes(strap: SleepSession, start: Long, end: Long) = Unit
override suspend fun deleteSleep(strap: SleepSession) = Unit
Expand Down