feat(planning): implement meal plan prediction engine

Introduce WeeklyMealPredictor and related data models to suggest meals, add prediction state management to the ViewModel, and update the UI to support meal planning automation.
This commit is contained in:
bleackstorm committed 2026-11-22 13:57:39 +01:00
1 parent 8e794e6da7
commit a2f59f15d4
13 files changed
+2247 -17

No files matched your search

@@ -58,11 +58,13 @@ import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictionMealScope
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.StorageLocation
import com.example.data.model.WeekPredictionUiState
import com.example.util.ImageUtils
import java.time.LocalDate
@@ -82,6 +84,7 @@ fun PlanningScreen(
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
receiptScanState: ReceiptScanUiState,
weekPredictionState: WeekPredictionUiState,
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
@@ -95,8 +98,14 @@ fun PlanningScreen(
onAddManualShoppingItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit,
onToggleShoppingItemChecked: (ShoppingListItem, Boolean) -> Unit,
onAddShoppingItemToStock: (ShoppingListItem, Double, FoodUnit, StorageLocation) -> Unit,
onFinishShoppingAndAddToStock: (List<ShoppingListItem>, Map<String, StorageLocation>) -> Unit,
onDeleteManualShoppingItem: (String) -> Unit,
onClearCheckedShoppingItems: () -> Unit,
onPredictWeekMeals: (PredictionMealScope, Double) -> Unit,
onTogglePredictedMeal: (String) -> Unit,
onUpdatePredictedMealServings: (String, Double) -> Unit,
onConfirmPredictedMeals: () -> Unit,
onDismissWeekPrediction: () -> Unit,
onScanReceiptUri: (Uri) -> Unit,
onUpdateScannedItem: (ScannedReceiptItem) -> Unit,
onRemoveScannedItem: (String) -> Unit,
@@ -120,6 +129,8 @@ fun PlanningScreen(
var pendingCaptureUri by remember { mutableStateOf<Uri?>(null) }
var shoppingItemForStockPrompt by remember { mutableStateOf<ShoppingListItem?>(null) }
var showPredictWeekSheet by rememberSaveable { mutableStateOf(false) }
var showShoppingMode by rememberSaveable { mutableStateOf(false) }
val recipesById = remember(recipes) { recipes.associateBy { it.id } }
@@ -271,6 +282,7 @@ fun PlanningScreen(
onPreviousWeek = onPreviousWeek,
onNextWeek = onNextWeek,
onGoToCurrentWeek = onGoToCurrentWeek,
onPredictWeekClick = { showPredictWeekSheet = true },
onPlanMealClick = { date, mealType ->
editingPlannedMeal = null
planTargetDate = date
@@ -306,6 +318,7 @@ fun PlanningScreen(
PlanningSubTab.SHOPPING -> {
ShoppingListTab(
shoppingItems = shoppingItems,
hasPlannedMeals = plannedMeals.isNotEmpty(),
onAddManualItem = onAddManualShoppingItem,
onToggleItemChecked = { item, nowChecked ->
if (nowChecked) {
@@ -316,7 +329,12 @@ fun PlanningScreen(
},
onDeleteManualItem = onDeleteManualShoppingItem,
onClearChecked = onClearCheckedShoppingItems,
onScanReceiptClick = { showReceiptSourceDialog = true }
onScanReceiptClick = { showReceiptSourceDialog = true },
onOpenShoppingModeClick = { showShoppingMode = true },
onPredictWeekClick = {
activeSubTab = PlanningSubTab.WEEK
showPredictWeekSheet = true
}
)
}
}
@@ -456,6 +474,41 @@ fun PlanningScreen(
}
)
}
// AI Weekly Meal Prediction Sheet
if (showPredictWeekSheet || weekPredictionState !is WeekPredictionUiState.Idle) {
PredictWeekSheet(
weekStartDate = weekStartDate,
existingWeekMeals = plannedMeals,
predictionState = weekPredictionState,
onGenerate = { scope, servings -> onPredictWeekMeals(scope, servings) },
onToggleProposal = onTogglePredictedMeal,
onUpdateServings = onUpdatePredictedMealServings,
onConfirm = {
onConfirmPredictedMeals()
showPredictWeekSheet = false
},
onResetToConfig = { onDismissWeekPrediction() },
onDismiss = {
showPredictWeekSheet = false
onDismissWeekPrediction()
}
)
}
// Fullscreen In-Store Shopping Mode
if (showShoppingMode) {
ShoppingModeScreen(
shoppingItems = shoppingItems,
onToggleItemChecked = onToggleShoppingItemChecked,
onAddQuickItem = { name, category ->
onAddManualShoppingItem(name, null, FoodUnit.PORTION, category)
},
onFinishAndAddToStock = onFinishShoppingAndAddToStock,
onScanReceiptInstead = { showReceiptSourceDialog = true },
onDismiss = { showShoppingMode = false }
)
}
}
@Composable
@@ -473,7 +526,7 @@ private fun AddPurchasedItemToStockDialog(
}
var selectedUnit by remember(item.key) { mutableStateOf(item.unit) }
var selectedLocation by remember(item.key) {
mutableStateOf(suggestStorageLocation(item.category))
mutableStateOf(StorageLocation.defaultForCategory(item.category))
}
val parsedQty = qtyText.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0.0 }
@@ -554,13 +607,3 @@ private fun AddPurchasedItemToStockDialog(
}
)
}
private fun suggestStorageLocation(category: FoodCategory): StorageLocation {
return when (category) {
FoodCategory.PROTEIN,
FoodCategory.DAIRY,
FoodCategory.CHEESE,
FoodCategory.VEGETABLE -> StorageLocation.FRIDGE
else -> StorageLocation.PANTRY
}
}
@@ -11,16 +11,21 @@ import com.example.data.model.InventoryItem
import com.example.data.model.ManualShoppingItem
import com.example.data.model.MealFoodItem
import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictedMealProposal
import com.example.data.model.PredictionMealScope
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.StockDeductionProposal
import com.example.data.model.StorageLocation
import com.example.data.model.WeekPredictionUiState
import com.example.data.preferences.PlanningPreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.IngredientMatcher
import com.example.domain.ReceiptScannerAnalyzer
import com.example.domain.ShoppingListCalculator
import com.example.domain.WeeklyMealPredictor
import com.example.ui.common.UiEvent
import com.example.util.ImageUtils
import kotlinx.coroutines.Dispatchers
@@ -47,7 +52,9 @@ import java.util.UUID
class PlanningViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val planningPrefs = PlanningPreferencesManager.getInstance(application)
private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
private val weeklyMealPredictor by lazy { WeeklyMealPredictor() }
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
@@ -84,7 +91,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
private val recipesFlow: Flow<List<RecipeEntry>> = repository.observeRecipes()
private val customFoodsFlow: Flow<List<CustomFoodEntry>> = repository.observeCustomFoods()
private val _checkedPlanKeys = MutableStateFlow<Set<String>>(emptySet())
private val _checkedPlanKeys = MutableStateFlow(planningPrefs.getCheckedPlanKeys())
private data class ShoppingInputs(
val planned: List<PlannedMealEntry>,
@@ -127,9 +134,18 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
private val _receiptScanState = MutableStateFlow<ReceiptScanUiState>(ReceiptScanUiState.Idle)
val receiptScanState: StateFlow<ReceiptScanUiState> = _receiptScanState.asStateFlow()
private val _weekPredictionState = MutableStateFlow<WeekPredictionUiState>(WeekPredictionUiState.Idle)
val weekPredictionState: StateFlow<WeekPredictionUiState> = _weekPredictionState.asStateFlow()
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
private fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
val updated = transform(_checkedPlanKeys.value)
_checkedPlanKeys.value = updated
planningPrefs.setCheckedPlanKeys(updated)
}
// ------------------------------------------------------------------------
// Week Navigation
// ------------------------------------------------------------------------
@@ -302,7 +318,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
repository.setManualShoppingItemChecked(item.manualItemId, checked)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { current ->
updateCheckedPlanKeys { current ->
if (checked) current + item.key else current - item.key
}
}
@@ -329,7 +345,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
repository.setManualShoppingItemChecked(item.manualItemId, true)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { it - item.key }
updateCheckedPlanKeys { it - item.key }
}
emitSnackbar("${item.name} ajouté au stock (${IngredientMatcher.formatQuantity(safeQty, unit)})")
},
@@ -340,6 +356,50 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
}
}
/**
* Batch-transfers all checked shopping items into kitchen inventory at the end of a shopping trip,
* clears checked manual items, and removes processed plan-derived checked keys.
*/
fun finishShoppingAndAddToStock(
checkedItems: List<ShoppingListItem>,
locationsByKey: Map<String, StorageLocation>
) {
if (checkedItems.isEmpty()) return
viewModelScope.launch {
var addedCount = 0
val processedPlanKeys = mutableSetOf<String>()
checkedItems.forEach { item ->
val qtyToAdd = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0
val location = locationsByKey[item.key] ?: StorageLocation.defaultForCategory(item.category)
val result = repository.addOrMergeInventoryItem(
name = item.name,
quantityToAdd = qtyToAdd,
unit = item.unit,
category = item.category,
location = location
)
if (result.isSuccess) {
addedCount++
}
if (item.key.startsWith("plan_")) {
processedPlanKeys.add(item.key)
}
}
repository.clearCheckedManualShoppingItems()
if (processedPlanKeys.isNotEmpty()) {
updateCheckedPlanKeys { it - processedPlanKeys }
}
if (addedCount > 0) {
emitSnackbar(
"$addedCount article${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} au stock"
)
}
}
}
fun deleteManualShoppingItem(manualItemId: String) {
viewModelScope.launch {
repository.deleteManualShoppingItem(manualItemId)
@@ -349,11 +409,144 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
fun clearCheckedShoppingItems() {
viewModelScope.launch {
repository.clearCheckedManualShoppingItems()
_checkedPlanKeys.value = emptySet()
updateCheckedPlanKeys { emptySet() }
emitSnackbar("Articles cochés nettoyés")
}
}
// ------------------------------------------------------------------------
// Weekly Meal Prediction (Firebase AI Logic)
// ------------------------------------------------------------------------
fun predictEmptyWeekMeals(
scope: PredictionMealScope,
defaultServings: Double
) {
viewModelScope.launch {
val start = _weekStartDate.value
val existingMeals = weekPlannedMeals.value
val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet()
val emptySlots = (0L..6L).flatMap { offset ->
val day = start.plusDays(offset)
val epochDay = day.toEpochDay()
scope.mealTypes.mapNotNull { mealType ->
if ((epochDay to mealType) !in occupiedSlots) {
day to mealType
} else {
null
}
}
}
if (emptySlots.isEmpty()) {
_weekPredictionState.value = WeekPredictionUiState.Error(
message = "Tous les créneaux de cette semaine pour « ${scope.displayName} » sont déjà planifiés.",
scope = scope,
defaultServings = defaultServings
)
return@launch
}
_weekPredictionState.value = WeekPredictionUiState.Loading
val inventory = repository.getInventorySnapshot()
val recipes = repository.getAllRecipesSnapshot()
val preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() }
val recentMeals = repository.getAllMealsSnapshot()
val result = weeklyMealPredictor.predictEmptySlots(
emptySlots = emptySlots,
existingWeekMeals = existingMeals,
inventory = inventory,
recipes = recipes,
preferences = preferences,
recentJournalMeals = recentMeals,
defaultServings = defaultServings
)
result.fold(
onSuccess = { proposals ->
_weekPredictionState.value = WeekPredictionUiState.Preview(
proposals = proposals,
scope = scope,
defaultServings = defaultServings
)
},
onFailure = { error ->
_weekPredictionState.value = WeekPredictionUiState.Error(
message = error.message ?: "Impossible de générer des suggestions pour le moment.",
scope = scope,
defaultServings = defaultServings
)
}
)
}
}
fun togglePredictedMeal(proposalId: String) {
_weekPredictionState.update { state ->
if (state is WeekPredictionUiState.Preview) {
state.copy(
proposals = state.proposals.map { proposal ->
if (proposal.id == proposalId) proposal.copy(selected = !proposal.selected) else proposal
}
)
} else {
state
}
}
}
fun updatePredictedMealServings(proposalId: String, newServings: Double) {
val clamped = newServings.coerceIn(0.5, 20.0)
_weekPredictionState.update { state ->
if (state is WeekPredictionUiState.Preview) {
state.copy(
proposals = state.proposals.map { proposal ->
if (proposal.id == proposalId) {
val ratio = if (proposal.servings > 0.0) clamped / proposal.servings else 1.0
val scaledItems = proposal.items.map { item ->
val scaledWeight = item.weight?.let { w ->
Math.round(w * ratio * 10.0) / 10.0
}
item.copy(weight = scaledWeight)
}
proposal.copy(servings = clamped, items = scaledItems)
} else {
proposal
}
}
)
} else {
state
}
}
}
fun confirmPredictedMeals() {
val preview = _weekPredictionState.value as? WeekPredictionUiState.Preview ?: return
val selectedProposals = preview.proposals.filter { it.selected }
if (selectedProposals.isEmpty()) {
emitSnackbar("Sélectionnez au moins un repas à ajouter au planning")
return
}
viewModelScope.launch {
selectedProposals.forEach { proposal ->
repository.upsertPlannedMeal(proposal.toPlannedMealEntry())
}
_weekPredictionState.value = WeekPredictionUiState.Idle
emitSnackbar(
"${selectedProposals.size} repas ajouté${if (selectedProposals.size > 1) "s" else ""} au planning • courses mises à jour"
)
}
}
fun dismissWeekPrediction() {
_weekPredictionState.value = WeekPredictionUiState.Idle
}
// ------------------------------------------------------------------------
// Receipt Scanning (Firebase AI Logic Multimodal)
// ------------------------------------------------------------------------
@@ -0,0 +1,579 @@
package com.example.ui.planning
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
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.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictedMealProposal
import com.example.data.model.PredictionMealScope
import com.example.data.model.WeekPredictionUiState
import com.example.ui.common.FoodCategoryColorDotsRow
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PredictWeekSheet(
weekStartDate: LocalDate,
existingWeekMeals: List<PlannedMealEntry>,
predictionState: WeekPredictionUiState,
onGenerate: (scope: PredictionMealScope, defaultServings: Double) -> Unit,
onToggleProposal: (String) -> Unit,
onUpdateServings: (proposalId: String, servings: Double) -> Unit,
onConfirm: () -> Unit,
onResetToConfig: () -> Unit,
onDismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var selectedScope by rememberSaveable { mutableStateOf(PredictionMealScope.MAIN_MEALS) }
var defaultServings by rememberSaveable { mutableDoubleStateOf(1.0) }
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()
selectedScope.mealTypes.count { (epochDay to it) !in occupiedSlots }
}
}
ModalBottomSheet(
onDismissRequest = {
if (predictionState !is WeekPredictionUiState.Loading) {
onDismiss()
}
},
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.padding(horizontal = 20.dp, vertical = 8.dp)
.testTag("predict_week_sheet"),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
when (predictionState) {
WeekPredictionUiState.Idle -> {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Column {
Text(
text = "Prédire ma semaine",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "S'appuie sur votre stock, vos recettes, vos goûts et votre journal",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Créneaux vides à compléter",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
PredictionMealScope.entries.forEachIndexed { index, scope ->
SegmentedButton(
selected = selectedScope == scope,
onClick = { selectedScope = scope },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = PredictionMealScope.entries.size
),
modifier = Modifier.testTag("predict_scope_${scope.name.lowercase()}")
) {
Text(scope.displayName, maxLines = 1)
}
}
}
}
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "Portions par défaut",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium
)
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { defaultServings = (defaultServings - 0.5).coerceAtLeast(0.5) },
modifier = Modifier.testTag("predict_servings_minus")
) {
Icon(Icons.Default.Remove, contentDescription = "Diminuer les portions")
}
Text(
text = formatServingsLabel(defaultServings),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp)
)
IconButton(
onClick = { defaultServings = (defaultServings + 0.5).coerceAtMost(10.0) },
modifier = Modifier.testTag("predict_servings_plus")
) {
Icon(Icons.Default.Add, contentDescription = "Augmenter les portions")
}
}
}
}
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."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(12.dp)
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.weight(0.38f)
) {
Text("Annuler")
}
Button(
onClick = { onGenerate(selectedScope, defaultServings) },
enabled = emptySlotsCount > 0,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(0.62f)
.testTag("generate_week_prediction_button")
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Générer les suggestions")
}
}
Spacer(modifier = Modifier.height(8.dp))
}
WeekPredictionUiState.Loading -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 32.dp)
.testTag("predict_week_loading"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
CircularProgressIndicator()
Text(
text = "Préparation de votre semaine...",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Text(
text = "Analyse de votre stock, vos recettes, vos goûts et votre historique récent.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
is WeekPredictionUiState.Error -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 20.dp)
.testTag("predict_week_error"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(40.dp)
)
Text(
text = "Génération interrompue",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
text = predictionState.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onResetToConfig,
modifier = Modifier.weight(1f)
) {
Text("Options")
}
Button(
onClick = {
onGenerate(predictionState.scope, predictionState.defaultServings)
},
modifier = Modifier.weight(1f)
) {
Text("Réessayer")
}
}
}
}
is WeekPredictionUiState.Preview -> {
val selectedCount = predictionState.proposals.count { it.selected }
val groupedByDay = remember(predictionState.proposals) {
predictionState.proposals.groupBy { it.dateEpochDay }.entries.sortedBy { it.key }
}
val dayFmt = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) }
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Suggestions pour la semaine",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "Décochez les repas dont vous ne voulez pas ou ajustez les portions",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
TextButton(
onClick = {
onGenerate(predictionState.scope, predictionState.defaultServings)
},
modifier = Modifier.testTag("regenerate_week_prediction_button")
) {
Icon(Icons.Default.Refresh, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(4.dp))
Text("Relancer")
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 420.dp)
.testTag("predict_week_preview_list"),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
groupedByDay.forEach { (epochDay, dayProposals) ->
item(key = "day_header_$epochDay") {
val label = LocalDate.ofEpochDay(epochDay)
.format(dayFmt)
.replaceFirstChar { it.titlecase(Locale.FRENCH) }
Text(
text = label,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(top = 4.dp)
)
}
items(dayProposals, key = { it.id }) { proposal ->
PredictedProposalCard(
proposal = proposal,
onToggle = { onToggleProposal(proposal.id) },
onServingsChange = { newServings ->
onUpdateServings(proposal.id, newServings)
}
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.weight(0.35f)
) {
Text("Annuler")
}
Button(
onClick = onConfirm,
enabled = selectedCount > 0,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(0.65f)
.testTag("confirm_week_prediction_button")
) {
Text("Valider dans le Planning ($selectedCount)")
}
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
@Composable
private fun PredictedProposalCard(
proposal: PredictedMealProposal,
onToggle: () -> Unit,
onServingsChange: (Double) -> Unit
) {
val categoryDots = remember(proposal.items) {
proposal.items.flatMap { it.resolvedCategories() }.distinct().take(5)
}
Card(
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(
containerColor = if (proposal.selected) {
MaterialTheme.colorScheme.surface
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)
}
),
border = BorderStroke(
width = 1.dp,
color = if (proposal.selected) {
MaterialTheme.colorScheme.outlineVariant
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f)
}
),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onToggle)
.testTag("predicted_proposal_${proposal.id}")
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = proposal.selected,
onCheckedChange = { onToggle() }
)
Column(modifier = Modifier.weight(1f)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
Text(
text = proposal.mealType.displayName,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.primary
)
if (!proposal.recipeId.isNullOrBlank()) {
Surface(
shape = RoundedCornerShape(6.dp),
color = MaterialTheme.colorScheme.secondaryContainer
) {
Row(
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(3.dp)
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.size(11.dp)
)
Text(
text = "Recette",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
}
}
if (categoryDots.isNotEmpty()) {
FoodCategoryColorDotsRow(
categories = categoryDots,
dotSize = 7.dp,
spacing = 2.dp
)
}
}
Text(
text = proposal.title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
if (proposal.reason.isNotBlank()) {
Text(
text = proposal.reason,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
if (proposal.selected) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 44.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "${proposal.items.size} ingrédient${if (proposal.items.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { onServingsChange(proposal.servings - 0.5) },
modifier = Modifier.size(34.dp)
) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Diminuer les portions de ${proposal.title}",
modifier = Modifier.size(16.dp)
)
}
Text(
text = "${formatServingsLabel(proposal.servings)} part${if (proposal.servings > 1.0) "s" else ""}",
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.SemiBold
)
IconButton(
onClick = { onServingsChange(proposal.servings + 0.5) },
modifier = Modifier.size(34.dp)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Augmenter les portions de ${proposal.title}",
modifier = Modifier.size(16.dp)
)
}
}
}
}
}
}
}
private fun formatServingsLabel(value: Double): String {
return if (value % 1.0 == 0.0) value.toInt().toString() else value.toString()
}
@@ -18,10 +18,12 @@ 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.DeleteOutline
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material.icons.filled.ShoppingCartCheckout
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
@@ -59,11 +61,14 @@ import com.example.ui.common.FoodCategoryColorDot
@Composable
fun ShoppingListTab(
shoppingItems: List<ShoppingListItem>,
hasPlannedMeals: Boolean,
onAddManualItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit,
onToggleItemChecked: (ShoppingListItem, Boolean) -> Unit,
onDeleteManualItem: (manualItemId: String) -> Unit,
onClearChecked: () -> Unit,
onScanReceiptClick: () -> Unit
onScanReceiptClick: () -> Unit,
onOpenShoppingModeClick: () -> Unit,
onPredictWeekClick: () -> Unit
) {
var manualName by rememberSaveable { mutableStateOf("") }
var manualQtyText by rememberSaveable { mutableStateOf("") }
@@ -130,6 +135,24 @@ fun ShoppingListTab(
)
}
if (shoppingItems.isNotEmpty()) {
Button(
onClick = onOpenShoppingModeClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("open_shopping_mode_button")
) {
Icon(
imageVector = Icons.Default.ShoppingCartCheckout,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text("Mode Courses (en magasin)")
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
@@ -286,6 +309,21 @@ fun ShoppingListTab(
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
if (!hasPlannedMeals) {
Button(
onClick = onPredictWeekClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.testTag("shopping_empty_predict_week_button")
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Prédire ma semaine")
}
}
}
}
}
@@ -0,0 +1,677 @@
package com.example.ui.planning
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.view.WindowManager
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Inventory2
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material.icons.filled.WbSunny
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.ShoppingListItem
import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategoryColorDot
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ShoppingModeScreen(
shoppingItems: List<ShoppingListItem>,
onToggleItemChecked: (ShoppingListItem, Boolean) -> Unit,
onAddQuickItem: (name: String, category: FoodCategory) -> Unit,
onFinishAndAddToStock: (checkedItems: List<ShoppingListItem>, locationsByKey: Map<String, StorageLocation>) -> Unit,
onScanReceiptInstead: () -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
val activity = remember(context) { context.findActivity() }
// Keep screen awake option — disabled by default, safely cleared on exit
var keepScreenOn by rememberSaveable { mutableStateOf(false) }
var hideChecked by rememberSaveable { mutableStateOf(false) }
var quickAddName by rememberSaveable { mutableStateOf("") }
var showCheckoutDialog by remember { mutableStateOf(false) }
DisposableEffect(keepScreenOn, activity) {
val window = activity?.window
if (keepScreenOn) {
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
onDispose {
window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
val totalCount = shoppingItems.size
val checkedItems = remember(shoppingItems) { shoppingItems.filter { it.isChecked } }
val checkedCount = checkedItems.size
val progress = if (totalCount > 0) checkedCount.toFloat() / totalCount.toFloat() else 0f
val visibleItems = remember(shoppingItems, hideChecked) {
if (hideChecked) shoppingItems.filterNot { it.isChecked } else shoppingItems
}
val groupedByAisle = remember(visibleItems) {
visibleItems
.groupBy { it.category }
.entries
.sortedBy { it.key.ordinal }
}
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(
usePlatformDefaultWidth = false,
decorFitsSystemWindows = false
)
) {
BackHandler(onBack = onDismiss)
Scaffold(
contentWindowInsets = WindowInsets.safeDrawing,
modifier = Modifier
.fillMaxSize()
.testTag("shopping_mode_screen"),
topBar = {
Column {
TopAppBar(
title = {
Column {
Text(
text = "En courses",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "$checkedCount / $totalCount article${if (totalCount > 1) "s" else ""} dans le panier",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
},
navigationIcon = {
IconButton(
onClick = onDismiss,
modifier = Modifier.testTag("close_shopping_mode_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Quitter le mode courses"
)
}
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.surface
)
)
LinearProgressIndicator(
progress = { progress },
modifier = Modifier
.fillMaxWidth()
.height(5.dp)
)
}
},
bottomBar = {
Surface(
tonalElevation = 6.dp,
shadowElevation = 8.dp,
color = MaterialTheme.colorScheme.surface
) {
Row(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.padding(horizontal = 16.dp, vertical = 12.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedButton(
onClick = {
onDismiss()
onScanReceiptInstead()
},
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 14.dp),
modifier = Modifier.testTag("shopping_mode_scan_button")
) {
Icon(
imageVector = Icons.Default.DocumentScanner,
contentDescription = "Scanner le ticket de caisse",
modifier = Modifier.size(20.dp)
)
}
Button(
onClick = { showCheckoutDialog = true },
enabled = checkedCount > 0,
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier
.weight(1f)
.testTag("finish_shopping_button")
) {
Icon(
imageVector = Icons.Default.Inventory2,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = if (checkedCount > 0) {
"Terminer les courses ($checkedCount)"
} else {
"Cochez vos articles en rayon"
},
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
}
) { innerPadding ->
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.testTag("shopping_mode_list"),
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
// Controls row: Keep screen awake + Hide checked filter
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.WbSunny,
contentDescription = null,
tint = if (keepScreenOn) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.size(18.dp)
)
Text(
text = "Écran allumé",
style = MaterialTheme.typography.labelLarge
)
Switch(
checked = keepScreenOn,
onCheckedChange = { keepScreenOn = it },
modifier = Modifier.testTag("keep_screen_on_switch")
)
}
FilterChip(
selected = hideChecked,
onClick = { hideChecked = !hideChecked },
leadingIcon = {
Icon(
imageVector = Icons.Default.VisibilityOff,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
label = { Text("Masquer cochés") },
modifier = Modifier.testTag("hide_checked_chip")
)
}
}
}
// Quick add unexpected item while walking in-store
item {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = quickAddName,
onValueChange = { quickAddName = it },
placeholder = { Text("Ajouter un imprévu en rayon...") },
singleLine = true,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(1f)
.testTag("shopping_mode_quick_add_input")
)
Button(
onClick = {
val trimmed = quickAddName.trim()
if (trimmed.isNotBlank()) {
onAddQuickItem(trimmed, FoodCategory.inferFromName(trimmed))
quickAddName = ""
}
},
enabled = quickAddName.isNotBlank(),
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 16.dp),
modifier = Modifier.testTag("shopping_mode_quick_add_button")
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Ajouter l'article"
)
}
}
}
if (groupedByAisle.isEmpty()) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(40.dp)
)
Text(
text = if (totalCount > 0 && checkedCount == totalCount) {
"Tout est dans le panier !"
} else {
"Aucun article à afficher"
},
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
if (checkedCount > 0) {
Text(
text = "Appuyez sur « Terminer les courses » pour ranger vos articles dans le Stock.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
} else {
groupedByAisle.forEach { (category, aisleItems) ->
item(key = "aisle_${category.name}") {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 6.dp, bottom = 2.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FoodCategoryColorDot(category = category, size = 12.dp)
Text(
text = category.displayName,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
items(aisleItems, key = { it.key }) { item ->
InStoreShoppingCard(
item = item,
onToggle = { onToggleItemChecked(item, !item.isChecked) }
)
}
}
}
}
}
}
// Batch transfer confirmation dialog at end of shopping trip
if (showCheckoutDialog && checkedItems.isNotEmpty()) {
FinishShoppingCheckoutDialog(
checkedItems = checkedItems,
onDismiss = { showCheckoutDialog = false },
onConfirmTransfer = { locationsByKey ->
showCheckoutDialog = false
onFinishAndAddToStock(checkedItems, locationsByKey)
onDismiss()
},
onScanReceiptInstead = {
showCheckoutDialog = false
onDismiss()
onScanReceiptInstead()
}
)
}
}
@Composable
private fun InStoreShoppingCard(
item: ShoppingListItem,
onToggle: () -> Unit
) {
val missingFmt = item.formatMissingQuantity()
val inStockFmt = item.formatInStockQuantity()
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = if (item.isChecked) {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)
} else {
MaterialTheme.colorScheme.surface
}
),
border = BorderStroke(
width = if (item.isChecked) 1.dp else 1.5.dp,
color = if (item.isChecked) {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)
} else {
MaterialTheme.colorScheme.outlineVariant
}
),
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 68.dp)
.clickable(onClick = onToggle)
.testTag("in_store_item_${item.key}")
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = if (item.isChecked) {
Icons.Default.CheckCircle
} else {
Icons.Default.RadioButtonUnchecked
},
contentDescription = if (item.isChecked) "Décocher ${item.name}" else "Cocher ${item.name}",
tint = if (item.isChecked) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.size(28.dp)
)
Spacer(modifier = Modifier.width(14.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = item.name,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
textDecoration = if (item.isChecked) TextDecoration.LineThrough else null,
color = if (item.isChecked) {
MaterialTheme.colorScheme.onSurfaceVariant
} else {
MaterialTheme.colorScheme.onSurface
}
)
if (inStockFmt != null && !item.isChecked) {
Text(
text = "Déjà à la maison : $inStockFmt",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
if (missingFmt != null) {
Surface(
shape = RoundedCornerShape(12.dp),
color = if (item.isChecked) {
MaterialTheme.colorScheme.surfaceVariant
} else {
MaterialTheme.colorScheme.primaryContainer
}
) {
Text(
text = missingFmt,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = if (item.isChecked) {
MaterialTheme.colorScheme.onSurfaceVariant
} else {
MaterialTheme.colorScheme.onPrimaryContainer
},
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)
)
}
}
}
}
}
@Composable
private fun FinishShoppingCheckoutDialog(
checkedItems: List<ShoppingListItem>,
onDismiss: () -> Unit,
onConfirmTransfer: (Map<String, StorageLocation>) -> Unit,
onScanReceiptInstead: () -> Unit
) {
val locationSelections = remember(checkedItems) {
mutableStateMapOf<String, StorageLocation>().apply {
checkedItems.forEach { item ->
put(item.key, StorageLocation.defaultForCategory(item.category))
}
}
}
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.testTag("finish_shopping_checkout_dialog"),
title = {
Text(
text = "Ranger dans le Stock ?",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
},
text = {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 360.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Text(
text = "${checkedItems.size} article${if (checkedItems.size > 1) "s" else ""} coché${if (checkedItems.size > 1) "s" else ""} prêt${if (checkedItems.size > 1) "s" else ""} à être ajouté${if (checkedItems.size > 1) "s" else ""} au Stock. Ajustez l'emplacement si besoin :",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
checkedItems.forEach { item ->
val currentLoc = locationSelections[item.key] ?: StorageLocation.defaultForCategory(item.category)
val qtyLabel = item.formatMissingQuantity() ?: "1 ${item.unit.label}"
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.weight(1f)
) {
FoodCategoryColorDot(category = item.category, size = 9.dp)
Text(
text = item.name,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
Text(
text = qtyLabel,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
StorageLocation.entries.forEach { loc ->
FilterChip(
selected = currentLoc == loc,
onClick = { locationSelections[item.key] = loc },
label = {
Text(
text = loc.displayName,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
modifier = Modifier.weight(1f)
)
}
}
}
}
}
OutlinedButton(
onClick = onScanReceiptInstead,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("checkout_scan_receipt_instead_button")
) {
Icon(
imageVector = Icons.Default.DocumentScanner,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Scanner le ticket à la place")
}
}
},
confirmButton = {
Button(
onClick = { onConfirmTransfer(locationSelections.toMap()) },
modifier = Modifier.testTag("confirm_finish_shopping_button")
) {
Text("Ajouter au stock (${checkedItems.size})")
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text("Continuer")
}
}
)
}
private tailrec fun Context.findActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
}
@@ -19,12 +19,14 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Today
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
@@ -62,6 +64,7 @@ fun WeeklyPlanTab(
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
onPredictWeekClick: () -> Unit,
onPlanMealClick: (date: LocalDate, mealType: MealType) -> Unit,
onEditPlannedMeal: (PlannedMealEntry) -> Unit,
onDeletePlannedMeal: (String) -> Unit,
@@ -173,6 +176,23 @@ fun WeeklyPlanTab(
)
}
}
Button(
onClick = onPredictWeekClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 2.dp)
.testTag("predict_week_button")
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text("Prédire ma semaine")
}
}
}
}