feat(planning): predict from today to end of week with optional next week

This commit is contained in:
bleack committed 2026-11-28 21:38:37 +01:00
1 parent 02ff698140
commit d2024c59c2
6 files changed
+219 -25

No files matched your search

@@ -110,7 +110,7 @@ fun PlanningScreen(
onFinishShoppingAndAddToStock: (List<ShoppingListItem>, Map<String, StorageLocation>) -> 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 = {
@@ -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<LocalDate> {
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()
}
}
}
@@ -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<PlannedMealEntry>,
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")
) {