feat(planning): decouple shopping list period with quick presets and custom date range

This commit is contained in:
bleack committed 2026-11-29 16:17:06 +01:00
1 parent 6bbbe7d423
commit 0af8021bf2
7 files changed
+292 -4

No files matched your search

@@ -316,6 +316,8 @@ fun AppRoot(
val weekPlannedMeals by planningViewModel.weekPlannedMeals.collectAsStateWithLifecycle()
val inventoryItems by planningViewModel.inventoryItems.collectAsStateWithLifecycle()
val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle()
val shoppingPeriod by planningViewModel.shoppingPeriod.collectAsStateWithLifecycle()
val shoppingPlannedMeals by planningViewModel.shoppingPlannedMeals.collectAsStateWithLifecycle()
val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle()
val barcodeScanItems by planningViewModel.barcodeScanItems.collectAsStateWithLifecycle()
val barcodeScanFeedback by planningViewModel.barcodeScanFeedback.collectAsStateWithLifecycle()
@@ -595,6 +597,12 @@ fun AppRoot(
plannedMeals = weekPlannedMeals,
inventoryItems = inventoryItems,
shoppingItems = computedShoppingList,
shoppingPeriod = shoppingPeriod,
shoppingPlannedMeals = shoppingPlannedMeals,
onSelectShoppingPeriod = { preset -> planningViewModel.selectShoppingPeriod(preset) },
onSelectCustomShoppingRange = { startEpoch, endEpoch ->
planningViewModel.selectCustomShoppingRange(startEpoch, endEpoch)
},
recipes = recipes,
customFoods = customFoods,
receiptScanState = receiptScanState,
@@ -1,8 +1,10 @@
package com.example.data.model
import com.example.domain.IngredientMatcher
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters
import java.util.Locale
import java.util.UUID
@@ -191,6 +193,83 @@ enum class ShoppingItemSource {
BOTH
}
enum class ShoppingPeriodPreset(val label: String) {
ALL_UPCOMING("Tout à venir"),
NEXT_7_DAYS("7 jours"),
CURRENT_WEEK("Cette semaine"),
NEXT_WEEK("Semaine suivante"),
CUSTOM("Dates…")
}
data class ShoppingPeriodSelection(
val preset: ShoppingPeriodPreset = ShoppingPeriodPreset.ALL_UPCOMING,
val customStartEpochDay: Long? = null,
val customEndEpochDay: Long? = null
) {
fun resolveRange(today: LocalDate = LocalDate.now()): Pair<LocalDate, LocalDate> {
val currentMonday = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
return when (preset) {
ShoppingPeriodPreset.ALL_UPCOMING -> today to today.plusYears(5)
ShoppingPeriodPreset.NEXT_7_DAYS -> today to today.plusDays(6)
ShoppingPeriodPreset.CURRENT_WEEK -> today to currentMonday.plusDays(6)
ShoppingPeriodPreset.NEXT_WEEK -> {
val nextMonday = currentMonday.plusWeeks(1)
nextMonday to nextMonday.plusDays(6)
}
ShoppingPeriodPreset.CUSTOM -> {
val rawStart = customStartEpochDay?.let(LocalDate::ofEpochDay) ?: today
val rawEnd = customEndEpochDay?.let(LocalDate::ofEpochDay) ?: rawStart.plusDays(6)
if (rawEnd.isBefore(rawStart)) rawEnd to rawStart else rawStart to rawEnd
}
}
}
fun formatCustomChipLabel(): String {
if (preset != ShoppingPeriodPreset.CUSTOM || customStartEpochDay == null || customEndEpochDay == null) {
return ShoppingPeriodPreset.CUSTOM.label
}
val start = LocalDate.ofEpochDay(minOf(customStartEpochDay, customEndEpochDay))
val end = LocalDate.ofEpochDay(maxOf(customStartEpochDay, customEndEpochDay))
return formatShortDateRange(start, end)
}
fun formatScopeSummary(
plannedMeals: List<PlannedMealEntry>,
today: LocalDate = LocalDate.now()
): String {
val activeMeals = plannedMeals.filterNot { it.isConsumed }
val (rangeStart, rangeEnd) = resolveRange(today)
if (activeMeals.isEmpty()) {
return when (preset) {
ShoppingPeriodPreset.ALL_UPCOMING -> "Aucun repas planifié à venir"
else -> "Aucun repas planifié (${formatShortDateRange(rangeStart, rangeEnd)})"
}
}
val displayStart = if (preset == ShoppingPeriodPreset.ALL_UPCOMING) {
LocalDate.ofEpochDay(activeMeals.minOf { it.dateEpochDay })
} else {
rangeStart
}
val displayEnd = if (preset == ShoppingPeriodPreset.ALL_UPCOMING) {
LocalDate.ofEpochDay(activeMeals.maxOf { it.dateEpochDay })
} else {
rangeEnd
}
return "${activeMeals.size} repas (${formatShortDateRange(displayStart, displayEnd)}) • moins votre stock"
}
companion object {
fun formatShortDateRange(start: LocalDate, end: LocalDate): String {
val fmt = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH)
return if (start == end) {
start.format(fmt)
} else {
"${start.format(fmt)} – ${end.format(fmt)}"
}
}
}
}
data class ShoppingListItem(
val key: String,
val name: String,
@@ -67,6 +67,8 @@ import com.example.data.model.ReceiptScanUiState
import com.example.data.model.RecipeEntry
import com.example.data.model.ScannedReceiptItem
import com.example.data.model.ShoppingListItem
import com.example.data.model.ShoppingPeriodPreset
import com.example.data.model.ShoppingPeriodSelection
import com.example.data.model.StorageLocation
import com.example.data.model.WeekPredictionUiState
import com.example.util.ImageUtils
@@ -86,6 +88,10 @@ fun PlanningScreen(
plannedMeals: List<PlannedMealEntry>,
inventoryItems: List<InventoryItem>,
shoppingItems: List<ShoppingListItem>,
shoppingPeriod: ShoppingPeriodSelection = ShoppingPeriodSelection(),
shoppingPlannedMeals: List<PlannedMealEntry> = plannedMeals,
onSelectShoppingPeriod: (ShoppingPeriodPreset) -> Unit = {},
onSelectCustomShoppingRange: (startEpochDay: Long, endEpochDay: Long) -> Unit = { _, _ -> },
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
receiptScanState: ReceiptScanUiState,
@@ -245,6 +251,9 @@ fun PlanningScreen(
}
val uncheckedShoppingCount = shoppingItems.count { !it.isChecked }
val shoppingScopeSummary = remember(shoppingPeriod, shoppingPlannedMeals) {
shoppingPeriod.formatScopeSummary(shoppingPlannedMeals)
}
Box(
modifier = Modifier
@@ -375,7 +384,11 @@ fun PlanningScreen(
PlanningSubTab.SHOPPING -> {
ShoppingListTab(
shoppingItems = shoppingItems,
hasPlannedMeals = plannedMeals.isNotEmpty(),
hasPlannedMeals = shoppingPlannedMeals.any { !it.isConsumed },
shoppingPeriod = shoppingPeriod,
shoppingScopeSummary = shoppingScopeSummary,
onSelectShoppingPeriod = onSelectShoppingPeriod,
onSelectCustomShoppingRange = onSelectCustomShoppingRange,
onAddManualItem = onAddManualShoppingItem,
onToggleItemChecked = { item, nowChecked ->
if (nowChecked) {
@@ -568,6 +581,7 @@ fun PlanningScreen(
if (showShoppingMode) {
ShoppingModeScreen(
shoppingItems = shoppingItems,
scopeSummary = shoppingScopeSummary,
onToggleItemChecked = onToggleShoppingItemChecked,
onAddQuickItem = { name, category ->
onAddManualShoppingItem(name, null, FoodUnit.PORTION, category)
@@ -25,6 +25,8 @@ import com.example.data.model.RecipeEntry
import com.example.data.model.ScannedBarcodeItem
import com.example.data.model.ScannedReceiptItem
import com.example.data.model.ShoppingListItem
import com.example.data.model.ShoppingPeriodPreset
import com.example.data.model.ShoppingPeriodSelection
import com.example.data.model.StockDeductionProposal
import com.example.data.model.StorageLocation
import com.example.data.model.WeekPredictionUiState
@@ -182,6 +184,20 @@ class PlanningViewModel internal constructor(
private val _checkedPlanKeys = MutableStateFlow(planningPrefs.getCheckedPlanKeys())
private val _shoppingPeriod = MutableStateFlow(ShoppingPeriodSelection())
val shoppingPeriod: StateFlow<ShoppingPeriodSelection> = _shoppingPeriod.asStateFlow()
val shoppingPlannedMeals: StateFlow<List<PlannedMealEntry>> = _shoppingPeriod
.flatMapLatest { selection ->
val (startDate, endDate) = selection.resolveRange()
repository.observePlannedMealsForWeek(startDate.toEpochDay(), endDate.toEpochDay())
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
private data class ShoppingInputs(
val planned: List<PlannedMealEntry>,
val recipes: List<RecipeEntry>,
@@ -192,7 +208,7 @@ class PlanningViewModel internal constructor(
val computedShoppingList: StateFlow<List<ShoppingListItem>> = combine(
combine(
weekPlannedMeals,
shoppingPlannedMeals,
recipesFlow,
inventoryItems,
manualShoppingItems,
@@ -555,6 +571,21 @@ class PlanningViewModel internal constructor(
}
}
fun selectShoppingPeriod(preset: ShoppingPeriodPreset) {
if (preset == ShoppingPeriodPreset.CUSTOM) return
_shoppingPeriod.value = ShoppingPeriodSelection(preset = preset)
}
fun selectCustomShoppingRange(startEpochDay: Long, endEpochDay: Long) {
val safeStart = minOf(startEpochDay, endEpochDay)
val safeEnd = maxOf(startEpochDay, endEpochDay)
_shoppingPeriod.value = ShoppingPeriodSelection(
preset = ShoppingPeriodPreset.CUSTOM,
customStartEpochDay = safeStart,
customEndEpochDay = safeEnd
)
}
// ------------------------------------------------------------------------
// Weekly Meal Prediction (Firebase AI Logic)
// ------------------------------------------------------------------------
@@ -9,16 +9,19 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.DoneAll
@@ -28,6 +31,9 @@ import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.DateRangePicker
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -37,6 +43,7 @@ import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDateRangePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -56,12 +63,22 @@ import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.ShoppingItemSource
import com.example.data.model.ShoppingListItem
import com.example.data.model.ShoppingPeriodPreset
import com.example.data.model.ShoppingPeriodSelection
import com.example.ui.common.FoodCategoryColorDot
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneOffset
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShoppingListTab(
shoppingItems: List<ShoppingListItem>,
hasPlannedMeals: Boolean,
shoppingPeriod: ShoppingPeriodSelection = ShoppingPeriodSelection(),
shoppingScopeSummary: String = "Calculée d'après votre planning moins votre stock actuel",
onSelectShoppingPeriod: (ShoppingPeriodPreset) -> Unit = {},
onSelectCustomShoppingRange: (startEpochDay: Long, endEpochDay: Long) -> Unit = { _, _ -> },
onAddManualItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit,
onToggleItemChecked: (ShoppingListItem, Boolean) -> Unit,
onDeleteManualItem: (manualItemId: String) -> Unit,
@@ -73,6 +90,7 @@ fun ShoppingListTab(
var manualName by rememberSaveable { mutableStateOf("") }
var manualQtyText by rememberSaveable { mutableStateOf("") }
var manualUnit by rememberSaveable { mutableStateOf(FoodUnit.PORTION) }
var showDateRangePicker by remember { mutableStateOf(false) }
val uncheckedCount = shoppingItems.count { !it.isChecked }
val checkedCount = shoppingItems.count { it.isChecked }
@@ -122,9 +140,9 @@ fun ShoppingListTab(
color = MaterialTheme.colorScheme.onSecondaryContainer
)
Text(
text = "Calculée d'après votre planning moins votre stock actuel",
text = shoppingScopeSummary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.8f)
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.85f)
)
}
Icon(
@@ -192,6 +210,48 @@ fun ShoppingListTab(
}
}
// Quick shopping period selector
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("shopping_period_selector")
) {
items(ShoppingPeriodPreset.entries) { preset ->
val isSelected = shoppingPeriod.preset == preset
val label = if (preset == ShoppingPeriodPreset.CUSTOM) {
shoppingPeriod.formatCustomChipLabel()
} else {
preset.label
}
FilterChip(
selected = isSelected,
onClick = {
if (preset == ShoppingPeriodPreset.CUSTOM) {
showDateRangePicker = true
} else {
onSelectShoppingPeriod(preset)
}
},
leadingIcon = if (preset == ShoppingPeriodPreset.CUSTOM) {
{
Icon(
imageVector = Icons.Default.DateRange,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
}
} else {
null
},
label = { Text(label, maxLines = 1) },
modifier = Modifier.testTag("shopping_period_${preset.name.lowercase()}")
)
}
}
}
// Quick manual add bar
item {
Surface(
@@ -357,6 +417,60 @@ fun ShoppingListTab(
}
}
}
if (showDateRangePicker) {
val today = remember { LocalDate.now() }
val initialStartMillis = (shoppingPeriod.customStartEpochDay ?: today.toEpochDay()) * 86_400_000L
val initialEndMillis = (shoppingPeriod.customEndEpochDay ?: today.plusDays(6).toEpochDay()) * 86_400_000L
val pickerState = rememberDateRangePickerState(
initialSelectedStartDateMillis = initialStartMillis,
initialSelectedEndDateMillis = initialEndMillis
)
DatePickerDialog(
onDismissRequest = { showDateRangePicker = false },
confirmButton = {
TextButton(
onClick = {
val startMillis = pickerState.selectedStartDateMillis
if (startMillis != null) {
val startEpoch = Instant.ofEpochMilli(startMillis)
.atZone(ZoneOffset.UTC)
.toLocalDate()
.toEpochDay()
val endMillis = pickerState.selectedEndDateMillis ?: startMillis
val endEpoch = Instant.ofEpochMilli(endMillis)
.atZone(ZoneOffset.UTC)
.toLocalDate()
.toEpochDay()
onSelectCustomShoppingRange(startEpoch, endEpoch)
}
showDateRangePicker = false
},
enabled = pickerState.selectedStartDateMillis != null
) {
Text("Valider")
}
},
dismissButton = {
TextButton(onClick = { showDateRangePicker = false }) {
Text("Annuler")
}
}
) {
DateRangePicker(
state = pickerState,
title = {
Text(
text = "Période des courses",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(start = 24.dp, top = 16.dp)
)
},
modifier = Modifier.height(460.dp)
)
}
}
}
@Composable
@@ -83,6 +83,7 @@ import com.example.ui.common.FoodCategoryColorDot
@Composable
fun ShoppingModeScreen(
shoppingItems: List<ShoppingListItem>,
scopeSummary: String? = null,
onToggleItemChecked: (ShoppingListItem, Boolean) -> Unit,
onAddQuickItem: (name: String, category: FoodCategory) -> Unit,
onFinishAndAddToStock: (checkedItems: List<ShoppingListItem>, locationsByKey: Map<String, StorageLocation>) -> Unit,
@@ -154,6 +155,15 @@ fun ShoppingModeScreen(
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
if (!scopeSummary.isNullOrBlank()) {
Text(
text = scopeSummary,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
},
navigationIcon = {