From d2024c59c2500b1ba7b558da4c54f4cc26385b3b Mon Sep 17 00:00:00 2001 From: bleack Date: Sat, 28 Nov 2026 21:38:37 +0100 Subject: [PATCH] feat(planning): predict from today to end of week with optional next week --- app/src/main/java/com/example/MainActivity.kt | 8 +- .../com/example/data/model/MealPlanModels.kt | 6 +- .../com/example/ui/planning/PlanningScreen.kt | 6 +- .../example/ui/planning/PlanningViewModel.kt | 77 +++++++++-- .../example/ui/planning/PredictWeekSheet.kt | 121 ++++++++++++++++-- .../java/com/example/PlanningViewModelTest.kt | 26 ++++ 6 files changed, 219 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt index c6f0bbe..0b25f34 100644 --- a/app/src/main/java/com/example/MainActivity.kt +++ b/app/src/main/java/com/example/MainActivity.kt @@ -653,8 +653,12 @@ fun AppRoot( onClearCheckedShoppingItems = { planningViewModel.clearCheckedShoppingItems() }, - onPredictWeekMeals = { scope, defaultServings -> - planningViewModel.predictEmptyWeekMeals(scope, defaultServings) + onPredictWeekMeals = { scope, defaultServings, includeNextWeek -> + planningViewModel.predictEmptyWeekMeals( + scope = scope, + defaultServings = defaultServings, + includeNextWeek = includeNextWeek + ) }, onTogglePredictedMeal = { id -> planningViewModel.togglePredictedMeal(id) }, onUpdatePredictedMealServings = { id, servings -> diff --git a/app/src/main/java/com/example/data/model/MealPlanModels.kt b/app/src/main/java/com/example/data/model/MealPlanModels.kt index 8da5dfa..eae69cb 100644 --- a/app/src/main/java/com/example/data/model/MealPlanModels.kt +++ b/app/src/main/java/com/example/data/model/MealPlanModels.kt @@ -306,12 +306,14 @@ sealed interface WeekPredictionUiState { data class Preview( val proposals: List, val scope: PredictionMealScope, - val defaultServings: Double + val defaultServings: Double, + val includeNextWeek: Boolean = false ) : WeekPredictionUiState data class Error( val message: String, val scope: PredictionMealScope, - val defaultServings: Double + val defaultServings: Double, + val includeNextWeek: Boolean = false ) : WeekPredictionUiState } diff --git a/app/src/main/java/com/example/ui/planning/PlanningScreen.kt b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt index 7514c2d..08b2997 100644 --- a/app/src/main/java/com/example/ui/planning/PlanningScreen.kt +++ b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt @@ -110,7 +110,7 @@ fun PlanningScreen( onFinishShoppingAndAddToStock: (List, Map) -> Unit, onDeleteManualShoppingItem: (String) -> Unit, onClearCheckedShoppingItems: () -> Unit, - onPredictWeekMeals: (PredictionMealScope, Double) -> Unit, + onPredictWeekMeals: (PredictionMealScope, Double, Boolean) -> Unit, onTogglePredictedMeal: (String) -> Unit, onUpdatePredictedMealServings: (String, Double) -> Unit, onConfirmPredictedMeals: () -> Unit, @@ -547,7 +547,9 @@ fun PlanningScreen( weekStartDate = weekStartDate, existingWeekMeals = plannedMeals, predictionState = weekPredictionState, - onGenerate = { scope, servings -> onPredictWeekMeals(scope, servings) }, + onGenerate = { scope, servings, includeNextWeek -> + onPredictWeekMeals(scope, servings, includeNextWeek) + }, onToggleProposal = onTogglePredictedMeal, onUpdateServings = onUpdatePredictedMealServings, onConfirm = { diff --git a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt index 3fc594d..4cfabc7 100644 --- a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt +++ b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt @@ -47,6 +47,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.receiveAsFlow @@ -560,16 +561,39 @@ class PlanningViewModel internal constructor( fun predictEmptyWeekMeals( scope: PredictionMealScope, - defaultServings: Double + defaultServings: Double, + includeNextWeek: Boolean = false, + today: LocalDate = LocalDate.now() ) { predictionJob?.cancel() predictionJob = viewModelScope.launch { val start = _weekStartDate.value - val existingMeals = weekPlannedMeals.value + val targetDays = computePredictionDays( + weekStartDate = start, + includeNextWeek = includeNextWeek, + today = today + ) + + if (targetDays.isEmpty()) { + _weekPredictionState.value = WeekPredictionUiState.Error( + message = "Cette semaine est déjà passée. Activez « Inclure la semaine suivante » ou avancez vers une semaine à venir.", + scope = scope, + defaultServings = defaultServings, + includeNextWeek = includeNextWeek + ) + return@launch + } + + val rangeStartEpoch = targetDays.first().toEpochDay() + val rangeEndEpoch = targetDays.last().toEpochDay() + val existingMeals = if (includeNextWeek) { + repository.observePlannedMealsForWeek(rangeStartEpoch, rangeEndEpoch).first() + } else { + weekPlannedMeals.value.filter { it.dateEpochDay in rangeStartEpoch..rangeEndEpoch } + } val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet() - val emptySlots = (0L..6L).flatMap { offset -> - val day = start.plusDays(offset) + val emptySlots = targetDays.flatMap { day -> val epochDay = day.toEpochDay() scope.mealTypes.mapNotNull { mealType -> if ((epochDay to mealType) !in occupiedSlots) { @@ -582,9 +606,14 @@ class PlanningViewModel internal constructor( if (emptySlots.isEmpty()) { _weekPredictionState.value = WeekPredictionUiState.Error( - message = "Tous les créneaux de cette semaine pour « ${scope.displayName} » sont déjà planifiés.", + message = if (includeNextWeek) { + "Tous les créneaux jusqu'à la fin de la semaine suivante pour « ${scope.displayName} » sont déjà planifiés." + } else { + "Tous les créneaux restants de cette semaine pour « ${scope.displayName} » sont déjà planifiés." + }, scope = scope, - defaultServings = defaultServings + defaultServings = defaultServings, + includeNextWeek = includeNextWeek ) return@launch } @@ -611,14 +640,16 @@ class PlanningViewModel internal constructor( _weekPredictionState.value = WeekPredictionUiState.Preview( proposals = proposals, scope = scope, - defaultServings = defaultServings + defaultServings = defaultServings, + includeNextWeek = includeNextWeek ) }, onFailure = { error -> _weekPredictionState.value = WeekPredictionUiState.Error( message = error.message ?: "Impossible de générer des suggestions pour le moment.", scope = scope, - defaultServings = defaultServings + defaultServings = defaultServings, + includeNextWeek = includeNextWeek ) } ) @@ -1140,5 +1171,35 @@ class PlanningViewModel internal constructor( fun currentMonday(): LocalDate { return LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)) } + + /** + * Returns the days to predict starting from [today] (never past days) until the end + * of the displayed week, and optionally appends the full following week when + * [includeNextWeek] is true. + */ + fun computePredictionDays( + weekStartDate: LocalDate, + includeNextWeek: Boolean, + today: LocalDate = LocalDate.now() + ): List { + val currentWeekRemaining = (0L..6L) + .map { weekStartDate.plusDays(it) } + .filter { !it.isBefore(today) } + + if (!includeNextWeek) { + return currentWeekRemaining + } + + val nextWeekStart = if (weekStartDate.plusDays(6).isBefore(today)) { + today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).plusWeeks(1) + } else { + weekStartDate.plusWeeks(1) + } + val nextWeekDays = (0L..6L) + .map { nextWeekStart.plusDays(it) } + .filter { !it.isBefore(today) } + + return (currentWeekRemaining + nextWeekDays).distinct().sorted() + } } } diff --git a/app/src/main/java/com/example/ui/planning/PredictWeekSheet.kt b/app/src/main/java/com/example/ui/planning/PredictWeekSheet.kt index 16c261a..c67342f 100644 --- a/app/src/main/java/com/example/ui/planning/PredictWeekSheet.kt +++ b/app/src/main/java/com/example/ui/planning/PredictWeekSheet.kt @@ -39,6 +39,7 @@ import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Surface +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState @@ -71,7 +72,7 @@ fun PredictWeekSheet( weekStartDate: LocalDate, existingWeekMeals: List, predictionState: WeekPredictionUiState, - onGenerate: (scope: PredictionMealScope, defaultServings: Double) -> Unit, + onGenerate: (scope: PredictionMealScope, defaultServings: Double, includeNextWeek: Boolean) -> Unit, onToggleProposal: (String) -> Unit, onUpdateServings: (proposalId: String, servings: Double) -> Unit, onConfirm: () -> Unit, @@ -79,15 +80,48 @@ fun PredictWeekSheet( onDismiss: () -> Unit ) { val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val today = remember { LocalDate.now() } + val shortDayFmt = remember { DateTimeFormatter.ofPattern("EEE d MMM", Locale.FRENCH) } + var selectedScope by rememberSaveable { mutableStateOf(PredictionMealScope.MAIN_MEALS) } var defaultServings by rememberSaveable { mutableDoubleStateOf(1.0) } + val remainingCurrentWeekDays = remember(weekStartDate, today) { + PlanningViewModel.computePredictionDays( + weekStartDate = weekStartDate, + includeNextWeek = false, + today = today + ) + } + var includeNextWeek by rememberSaveable(weekStartDate) { + mutableStateOf(remainingCurrentWeekDays.isEmpty()) + } + + val targetDays = remember(weekStartDate, includeNextWeek, today) { + PlanningViewModel.computePredictionDays( + weekStartDate = weekStartDate, + includeNextWeek = includeNextWeek, + today = today + ) + } + + val nextWeekStart = remember(weekStartDate, today) { + if (weekStartDate.plusDays(6).isBefore(today)) { + PlanningViewModel.currentMonday().plusWeeks(1) + } else { + weekStartDate.plusWeeks(1) + } + } + val nextWeekRangeLabel = remember(nextWeekStart) { + "${nextWeekStart.format(shortDayFmt)} – ${nextWeekStart.plusDays(6).format(shortDayFmt)}" + } + val occupiedSlots = remember(existingWeekMeals) { existingWeekMeals.map { it.dateEpochDay to it.mealType }.toSet() } - val emptySlotsCount = remember(weekStartDate, occupiedSlots, selectedScope) { - (0L..6L).sumOf { offset -> - val epochDay = weekStartDate.plusDays(offset).toEpochDay() + val emptySlotsCount = remember(targetDays, occupiedSlots, selectedScope) { + targetDays.sumOf { day -> + val epochDay = day.toEpochDay() selectedScope.mealTypes.count { (epochDay to it) !in occupiedSlots } } } @@ -198,16 +232,73 @@ fun PredictWeekSheet( } } + if (remainingCurrentWeekDays.size < 7) { + Surface( + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), + modifier = Modifier + .fillMaxWidth() + .clickable { includeNextWeek = !includeNextWeek } + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Inclure aussi la semaine suivante", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold + ) + Text( + text = "$nextWeekRangeLabel (+7 jours)", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Spacer(modifier = Modifier.width(8.dp)) + Switch( + checked = includeNextWeek, + onCheckedChange = { includeNextWeek = it }, + modifier = Modifier.testTag("predict_include_next_week_switch") + ) + } + } + } + + val periodLabel = remember(targetDays) { + if (targetDays.isEmpty()) { + null + } else { + val first = targetDays.first().format(shortDayFmt) + val last = targetDays.last().format(shortDayFmt) + if (targetDays.size == 1) { + "Pour $first (1 jour)" + } else { + "Du $first au $last (${targetDays.size} jours)" + } + } + } + Surface( shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f), modifier = Modifier.fillMaxWidth() ) { Text( - text = if (emptySlotsCount > 0) { - "$emptySlotsCount créneau${if (emptySlotsCount > 1) "x" else ""} vide${if (emptySlotsCount > 1) "s" else ""} à proposer cette semaine. Vos repas déjà planifiés ne seront pas modifiés." - } else { - "Tous les créneaux de cette semaine pour « ${selectedScope.displayName} » sont déjà planifiés." + text = when { + targetDays.isEmpty() -> { + "Cette semaine est déjà passée. Activez « Inclure aussi la semaine suivante » pour planifier la suite." + } + emptySlotsCount > 0 -> { + "${periodLabel.orEmpty()} • $emptySlotsCount créneau${if (emptySlotsCount > 1) "x" else ""} vide${if (emptySlotsCount > 1) "s" else ""} à proposer. Les jours passés et vos repas déjà planifiés ne sont pas modifiés." + } + else -> { + "Tous les créneaux restants pour « ${selectedScope.displayName} » sont déjà planifiés." + } }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurface, @@ -227,7 +318,7 @@ fun PredictWeekSheet( Text("Annuler") } Button( - onClick = { onGenerate(selectedScope, defaultServings) }, + onClick = { onGenerate(selectedScope, defaultServings, includeNextWeek) }, enabled = emptySlotsCount > 0, shape = RoundedCornerShape(14.dp), modifier = Modifier @@ -309,7 +400,11 @@ fun PredictWeekSheet( } Button( onClick = { - onGenerate(predictionState.scope, predictionState.defaultServings) + onGenerate( + predictionState.scope, + predictionState.defaultServings, + predictionState.includeNextWeek + ) }, modifier = Modifier.weight(1f) ) { @@ -345,7 +440,11 @@ fun PredictWeekSheet( } TextButton( onClick = { - onGenerate(predictionState.scope, predictionState.defaultServings) + onGenerate( + predictionState.scope, + predictionState.defaultServings, + predictionState.includeNextWeek + ) }, modifier = Modifier.testTag("regenerate_week_prediction_button") ) { diff --git a/app/src/test/java/com/example/PlanningViewModelTest.kt b/app/src/test/java/com/example/PlanningViewModelTest.kt index 588b78a..82cf36d 100644 --- a/app/src/test/java/com/example/PlanningViewModelTest.kt +++ b/app/src/test/java/com/example/PlanningViewModelTest.kt @@ -277,4 +277,30 @@ class PlanningViewModelTest { assertEquals("p_fail", remaining[0].id) assertFalse(remaining.any { it.id == "p_ok" }) } + + @Test + fun computePredictionDays_skipsPastDaysAndOptionallyIncludesNextWeek() { + val monday = LocalDate.of(2026, 11, 23) + val saturday = LocalDate.of(2026, 11, 28) + + val remainingOnly = PlanningViewModel.computePredictionDays( + weekStartDate = monday, + includeNextWeek = false, + today = saturday + ) + assertEquals( + listOf(LocalDate.of(2026, 11, 28), LocalDate.of(2026, 11, 29)), + remainingOnly + ) + + val withNextWeek = PlanningViewModel.computePredictionDays( + weekStartDate = monday, + includeNextWeek = true, + today = saturday + ) + assertEquals(9, withNextWeek.size) + assertEquals(LocalDate.of(2026, 11, 28), withNextWeek.first()) + assertEquals(LocalDate.of(2026, 12, 6), withNextWeek.last()) + assertTrue(withNextWeek.none { it.isBefore(saturday) }) + } }