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

@@ -297,6 +297,7 @@ fun AppRoot(
val inventoryItems by planningViewModel.inventoryItems.collectAsStateWithLifecycle()
val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle()
val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle()
val weekPredictionState by planningViewModel.weekPredictionState.collectAsStateWithLifecycle()
val pendingStockDeductions by planningViewModel.pendingStockDeductions.collectAsStateWithLifecycle()
LaunchedEffect(Unit) {
@@ -571,6 +572,7 @@ fun AppRoot(
recipes = recipes,
customFoods = customFoods,
receiptScanState = receiptScanState,
weekPredictionState = weekPredictionState,
onPreviousWeek = { planningViewModel.previousWeek() },
onNextWeek = { planningViewModel.nextWeek() },
onGoToCurrentWeek = { planningViewModel.goToCurrentWeek() },
@@ -616,12 +618,24 @@ fun AppRoot(
onAddShoppingItemToStock = { item, qty, unit, location ->
planningViewModel.addShoppingItemToStock(item, qty, unit, location)
},
onFinishShoppingAndAddToStock = { items, locationsByKey ->
planningViewModel.finishShoppingAndAddToStock(items, locationsByKey)
},
onDeleteManualShoppingItem = { id ->
planningViewModel.deleteManualShoppingItem(id)
},
onClearCheckedShoppingItems = {
planningViewModel.clearCheckedShoppingItems()
},
onPredictWeekMeals = { scope, defaultServings ->
planningViewModel.predictEmptyWeekMeals(scope, defaultServings)
},
onTogglePredictedMeal = { id -> planningViewModel.togglePredictedMeal(id) },
onUpdatePredictedMealServings = { id, servings ->
planningViewModel.updatePredictedMealServings(id, servings)
},
onConfirmPredictedMeals = { planningViewModel.confirmPredictedMeals() },
onDismissWeekPrediction = { planningViewModel.dismissWeekPrediction() },
onScanReceiptUri = { uri -> planningViewModel.scanReceiptFromUri(uri) },
onUpdateScannedItem = { item -> planningViewModel.updateScannedItem(item) },
onRemoveScannedItem = { id -> planningViewModel.removeScannedItem(id) },
@@ -17,6 +17,22 @@ enum class StorageLocation(val displayName: String) {
it.displayName.equals(trimmed, ignoreCase = true)
} ?: PANTRY
}
fun defaultForCategory(category: FoodCategory): StorageLocation {
return when (category) {
FoodCategory.PROTEIN,
FoodCategory.VEGETABLE,
FoodCategory.FRUIT,
FoodCategory.CHEESE,
FoodCategory.DAIRY -> FRIDGE
FoodCategory.STARCH,
FoodCategory.BREAD,
FoodCategory.NUTS,
FoodCategory.FAT_SEASONING,
FoodCategory.PLEASURE,
FoodCategory.OTHER -> PANTRY
}
}
}
}
@@ -135,3 +151,56 @@ sealed interface ReceiptScanUiState {
data class Preview(val items: List<ScannedReceiptItem>) : ReceiptScanUiState
data class Error(val message: String) : ReceiptScanUiState
}
enum class PredictionMealScope(
val displayName: String,
val mealTypes: List<MealType>
) {
MAIN_MEALS("Déjeuner & Dîner", listOf(MealType.LUNCH, MealType.DINNER)),
ALL_MEALS("Tous les moments", listOf(MealType.BREAKFAST, MealType.LUNCH, MealType.SNACK, MealType.DINNER))
}
data class PredictedMealProposal(
val id: String = "pred_${UUID.randomUUID().toString().take(8)}",
val dateEpochDay: Long,
val mealType: MealType,
val recipeId: String? = null,
val title: String,
val servings: Double = 1.0,
val items: List<MealFoodItem> = emptyList(),
val reason: String = "",
val selected: Boolean = true
) {
fun toPlannedMealEntry(): PlannedMealEntry {
return PlannedMealEntry(
id = "",
dateEpochDay = dateEpochDay,
mealType = mealType,
recipeId = recipeId,
customTitle = title.trim(),
servings = servings.coerceAtLeast(0.5),
itemsSerialized = if (recipeId.isNullOrBlank()) {
items.map { it.serialize() }
} else {
emptyList()
},
isConsumed = false
)
}
}
sealed interface WeekPredictionUiState {
data object Idle : WeekPredictionUiState
data object Loading : WeekPredictionUiState
data class Preview(
val proposals: List<PredictedMealProposal>,
val scope: PredictionMealScope,
val defaultServings: Double
) : WeekPredictionUiState
data class Error(
val message: String,
val scope: PredictionMealScope,
val defaultServings: Double
) : WeekPredictionUiState
}
@@ -0,0 +1,34 @@
package com.example.data.preferences
import android.content.Context
/**
* Stores lightweight planning & shopping session state (such as checked plan-derived
* shopping items) so in-store progress survives backgrounding or app restarts.
*/
class PlanningPreferencesManager private constructor(context: Context) {
private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun getCheckedPlanKeys(): Set<String> {
return prefs.getStringSet(KEY_CHECKED_PLAN_KEYS, emptySet())?.toSet() ?: emptySet()
}
fun setCheckedPlanKeys(keys: Set<String>) {
prefs.edit().putStringSet(KEY_CHECKED_PLAN_KEYS, keys.toSet()).apply()
}
companion object {
private const val PREFS_NAME = "satiea_planning_prefs"
private const val KEY_CHECKED_PLAN_KEYS = "checked_plan_keys"
@Volatile
private var instance: PlanningPreferencesManager? = null
fun getInstance(context: Context): PlanningPreferencesManager {
return instance ?: synchronized(this) {
instance ?: PlanningPreferencesManager(context).also { instance = it }
}
}
}
}
@@ -0,0 +1,361 @@
package com.example.domain
import android.util.Log
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictedMealProposal
import com.example.data.model.RecipeEntry
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.Schema
import com.google.firebase.ai.type.generationConfig
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.UUID
/**
* Predicts balanced, realistic meals for empty weekly slots using Firebase AI Logic
* (gemini-3.8-flash with strict JSON Schema output), grounded in current kitchen stock,
* saved recipes, food preferences, and recent journal habits.
*/
class WeeklyMealPredictor {
private val allowedCategoryCodes = FoodCategory.entries.map { it.code }
private val allowedUnitCodes = listOf("g", "ml", "portion")
private val responseSchema by lazy {
val ingredientSchema = Schema.obj(
properties = mapOf(
"name" to Schema.string(description = "Nom français simple de l'ingrédient (cohérent avec le stock quand possible)"),
"weight" to Schema.double(description = "Quantité numérique réaliste pour le nombre de portions demandé"),
"unit" to Schema.enumeration(
values = allowedUnitCodes,
description = "Unité : g, ml ou portion"
),
"category" to Schema.enumeration(
values = allowedCategoryCodes,
description = "Code exact de catégorie alimentaire"
)
)
)
val mealSchema = Schema.obj(
properties = mapOf(
"slotIndex" to Schema.integer(description = "Index entier exact (0..N-1) du créneau vide fourni dans la consigne"),
"recipeId" to Schema.string(
description = "ID exact d'une recette existante si réutilisée, ou chaîne vide \"\" pour un repas libre",
nullable = true
),
"title" to Schema.string(description = "Nom clair et appétissant du repas en français"),
"reason" to Schema.string(description = "Courte raison bienveillante (ex: 'Utilise vos courgettes en stock', 'Recette favorite', 'Équilibre vos légumes')"),
"ingredients" to Schema.array(
items = ingredientSchema,
description = "Liste structurée des ingrédients avec quantités pour le nombre de portions demandé (indispensable pour le calcul des courses)"
)
)
)
Schema.obj(
properties = mapOf(
"meals" to Schema.array(
items = mealSchema,
description = "Une proposition de repas variée pour chaque slotIndex vide demandé"
)
)
)
}
private val model by lazy {
val config = generationConfig {
responseMimeType = "application/json"
responseSchema = this@WeeklyMealPredictor.responseSchema
temperature = 0.65f
}
Firebase.ai.generativeModel(
modelName = "gemini-3.8-flash",
generationConfig = config
)
}
suspend fun predictEmptySlots(
emptySlots: List<Pair<LocalDate, MealType>>,
existingWeekMeals: List<PlannedMealEntry>,
inventory: List<InventoryItem>,
recipes: List<RecipeEntry>,
preferences: List<FoodPreferenceEntry>,
recentJournalMeals: List<MealEntry>,
defaultServings: Double
): Result<List<PredictedMealProposal>> {
if (emptySlots.isEmpty()) {
return Result.failure(
IllegalStateException("Tous les créneaux de cette semaine sont déjà planifiés.")
)
}
val recipesById = recipes.associateBy { it.id }
val prompt = buildPrompt(
emptySlots = emptySlots,
existingWeekMeals = existingWeekMeals,
inventory = inventory,
recipes = recipes,
preferences = preferences,
recentJournalMeals = recentJournalMeals,
defaultServings = defaultServings,
recipesById = recipesById
)
return try {
val response = withTimeout(60_000L) {
model.generateContent(prompt)
}
val jsonText = response.text
if (jsonText.isNullOrBlank()) {
Result.failure(
IllegalStateException("La génération n'a renvoyé aucune suggestion. Réessayez dans un instant.")
)
} else {
val parsed = parsePredictionJson(
jsonString = jsonText,
emptySlots = emptySlots,
recipesById = recipesById,
defaultServings = defaultServings
)
if (parsed.isEmpty()) {
Result.failure(
IllegalStateException("Aucune suggestion exploitable n'a pu être extraite. Veuillez réessayer.")
)
} else {
Result.success(parsed)
}
}
} catch (e: TimeoutCancellationException) {
Log.e(TAG, "Weekly meal prediction timed out", e)
Result.failure(
IllegalStateException("La prédiction de la semaine a dépassé le délai (60 s). Vérifiez votre connexion et réessayez.")
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Weekly meal prediction failed", e)
Result.failure(
IllegalStateException(
e.localizedMessage ?: "Impossible de prédire les repas pour le moment."
)
)
}
}
private fun buildPrompt(
emptySlots: List<Pair<LocalDate, MealType>>,
existingWeekMeals: List<PlannedMealEntry>,
inventory: List<InventoryItem>,
recipes: List<RecipeEntry>,
preferences: List<FoodPreferenceEntry>,
recentJournalMeals: List<MealEntry>,
defaultServings: Double,
recipesById: Map<String, RecipeEntry>
): String {
val dayFmt = DateTimeFormatter.ofPattern("EEEE d MMM", Locale.FRENCH)
val slotsText = emptySlots.mapIndexed { idx, (date, type) ->
"[$idx] ${date.format(dayFmt)} — ${type.displayName}"
}.joinToString("\n")
val existingText = if (existingWeekMeals.isEmpty()) {
"Aucun repas déjà planifié cette semaine."
} else {
existingWeekMeals.joinToString("\n") { entry ->
val day = LocalDate.ofEpochDay(entry.dateEpochDay).format(dayFmt)
"- $day (${entry.mealType.displayName}) : ${entry.resolvedTitle(recipesById)}"
}
}
val stockText = if (inventory.isEmpty()) {
"Stock vide."
} else {
inventory.take(40).joinToString(", ") { item ->
"${item.name} (${item.formatQuantity()}, ${item.location.displayName})"
}
}
val recipesText = if (recipes.isEmpty()) {
"Aucune recette enregistrée."
} else {
recipes.take(30).joinToString("\n") { r ->
val ingNames = r.parsedIngredients().take(6).joinToString(", ") { it.name }
"- id=\"${r.id}\" | ${r.title} (${r.servings} parts) | ingrédients: $ingNames"
}
}
val liked = preferences.filter { it.status == FoodPreferenceStatus.LIKED }.map { it.name }
val disliked = preferences.filter { it.status == FoodPreferenceStatus.DISLIKED }.map { it.name }
val toTry = preferences.filter { it.status == FoodPreferenceStatus.TO_TRY }.map { it.name }
val recentMealsText = if (recentJournalMeals.isEmpty()) {
"Aucun historique récent."
} else {
recentJournalMeals
.sortedByDescending { it.mealTimestamp }
.take(15)
.joinToString("\n") { meal ->
val type = MealType.fromString(meal.mealType).displayName
val foods = meal.parsedFoodItems().joinToString(", ") { it.name }
.ifBlank { meal.note.take(60) }
"- $type : $foods"
}
}
val categoriesHelp = FoodCategory.entries.joinToString(", ") { "${it.code} (${it.shortLabel})" }
val formattedServings = if (defaultServings % 1.0 == 0.0) {
defaultServings.toInt().toString()
} else {
defaultServings.toString()
}
return """
Tu es l'assistant culinaire bienveillant de Satiéa. Propose un planning hebdomadaire varié, équilibré et pragmatique pour les créneaux vides ci-dessous, pour $formattedServings portion(s) par repas.
CRÉNEAUX VIDES À REMPLIR (renvoie exactement 1 proposition par slotIndex) :
$slotsText
REPAS DÉJÀ PLANIFIÉS CETTE SEMAINE (ne pas les dupliquer) :
$existingText
STOCK CUISINE DISPONIBLE (à prioriser pour limiter le gaspillage et réduire les courses) :
$stockText
RECETTES ENREGISTRÉES DE L'UTILISATEUR (tu peux réutiliser un id exact dans recipeId si pertinent) :
$recipesText
GOÛTS & PRÉFÉRENCES :
- Aliments aimés : ${liked.ifEmpty { listOf("Non renseignés") }.joinToString(", ")}
- Aliments à ÉVITER absolument : ${disliked.ifEmpty { listOf("Aucun") }.joinToString(", ")}
- Découvertes à tester : ${toTry.ifEmpty { listOf("Aucune") }.joinToString(", ")}
HABITUDES RÉCENTES DU JOURNAL :
$recentMealsText
RÈGLES STRICTES :
1. Respecte absolument les aliments à éviter (ne les utilise jamais).
2. Priorise les ingrédients déjà présents dans le stock (notamment produits frais du Frigo) en gardant les mêmes noms simples pour que le calcul des courses les reconnaisse.
3. Réutilise volontiers 1 à 4 recettes existantes (en mettant leur `recipeId` exact) si elles s'accordent avec la semaine et le stock, et complète avec des repas simples et variés (`recipeId` = "").
4. Adapte chaque repas à son moment de la journée (Petit-déjeuner, Déjeuner, Collation, Dîner) et assure une belle variété sur la semaine (équilibre légumes, protéines, féculents, laitages/fruits).
5. Pour CHAQUE repas, fournis une liste `ingredients` avec des quantités réalistes pour $formattedServings portion(s), en utilisant UNIQUEMENT les unités "g", "ml" ou "portion", et les codes catégories : $categoriesHelp.
6. La `reason` doit être très courte (max 8 mots), bienveillante et concrète (ex: "Utilise vos tomates et poulet en stock").
""".trimIndent()
}
companion object {
private const val TAG = "WeeklyMealPredictor"
private val moshi: Moshi = Moshi.Builder().build()
private val mapAdapter = moshi.adapter<Map<String, Any>>(
Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java)
)
/**
* Pure JVM JSON parser (Moshi-backed) for offline testability and resilient handling
* of Gemini structured JSON responses.
*/
@Suppress("UNCHECKED_CAST")
fun parsePredictionJson(
jsonString: String,
emptySlots: List<Pair<LocalDate, MealType>>,
recipesById: Map<String, RecipeEntry>,
defaultServings: Double
): List<PredictedMealProposal> {
if (jsonString.isBlank() || emptySlots.isEmpty()) return emptyList()
val root = try {
mapAdapter.fromJson(jsonString)
} catch (_: Exception) {
null
} ?: return emptyList()
val mealsList = root["meals"] as? List<*> ?: return emptyList()
val usedSlotIndices = mutableSetOf<Int>()
val proposals = mutableListOf<PredictedMealProposal>()
for (rawEntry in mealsList) {
val obj = rawEntry as? Map<*, *> ?: continue
val slotIndex = (obj["slotIndex"] as? Number)?.toInt() ?: continue
if (slotIndex !in emptySlots.indices || !usedSlotIndices.add(slotIndex)) continue
val (date, mealType) = emptySlots[slotIndex]
val rawRecipeId = (obj["recipeId"] as? String)?.trim().orEmpty()
val matchedRecipe = rawRecipeId.takeIf { it.isNotBlank() }?.let { recipesById[it] }
val rawTitle = (obj["title"] as? String)?.trim().orEmpty()
val resolvedTitle = when {
matchedRecipe != null && rawTitle.isBlank() -> matchedRecipe.title
matchedRecipe != null -> matchedRecipe.title
rawTitle.isNotBlank() -> rawTitle
else -> continue
}
val reason = (obj["reason"] as? String)?.trim().orEmpty()
val safeServings = defaultServings.coerceAtLeast(0.5)
val parsedIngredients = mutableListOf<MealFoodItem>()
val rawIngredients = obj["ingredients"] as? List<*>
if (rawIngredients != null) {
for (rawIng in rawIngredients) {
val ingObj = rawIng as? Map<*, *> ?: continue
val ingName = (ingObj["name"] as? String)?.trim().orEmpty()
if (ingName.isBlank()) continue
val weight = (ingObj["weight"] as? Number)?.toDouble()?.takeIf { !it.isNaN() && it > 0.0 }
val unit = FoodUnit.fromCode((ingObj["unit"] as? String) ?: "portion")
val category = FoodCategory.fromCode(ingObj["category"] as? String)
?: FoodCategory.inferFromName(ingName)
parsedIngredients.add(
MealFoodItem(
name = ingName,
weight = weight,
unit = unit,
category = category,
categories = listOf(category)
)
)
}
}
val resolvedItems = if (matchedRecipe != null) {
matchedRecipe.scaledIngredients(safeServings)
} else {
parsedIngredients
}
proposals.add(
PredictedMealProposal(
id = "pred_${slotIndex}_${UUID.randomUUID().toString().take(6)}",
dateEpochDay = date.toEpochDay(),
mealType = mealType,
recipeId = matchedRecipe?.id,
title = resolvedTitle,
servings = safeServings,
items = resolvedItems,
reason = reason,
selected = true
)
)
}
return proposals.sortedWith(
compareBy<PredictedMealProposal> { it.dateEpochDay }
.thenBy { it.mealType.ordinal }
)
}
}
}
@@ -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")
}
}
}
}
@@ -157,4 +157,60 @@ class ShoppingListCalculatorTest {
assertEquals(200.0, milkProposal.deductAmount, 0.01)
assertEquals(0.0, milkProposal.remainingAfter, 0.01)
}
@Test
fun computeShoppingList_updatesMissingQuantitiesWhenPredictedMealsAreConfirmed() {
val predicted = com.example.data.model.PredictedMealProposal(
dateEpochDay = 20010L,
mealType = MealType.DINNER,
recipeId = null,
title = "Saumon riz brocolis",
servings = 2.0,
items = listOf(
MealFoodItem("Saumon", 300.0, FoodUnit.G, FoodCategory.PROTEIN),
MealFoodItem("Brocolis", 400.0, FoodUnit.G, FoodCategory.VEGETABLE),
MealFoodItem("Riz", 180.0, FoodUnit.G, FoodCategory.STARCH)
),
reason = "Utilise votre riz en stock"
)
val inventory = listOf(
InventoryItem(
id = "stock_riz",
name = "Riz",
quantity = 500.0,
unit = FoodUnit.G,
category = FoodCategory.STARCH,
location = StorageLocation.PANTRY
),
InventoryItem(
id = "stock_broc",
name = "Brocoli",
quantity = 150.0,
unit = FoodUnit.G,
category = FoodCategory.VEGETABLE,
location = StorageLocation.FRIDGE
)
)
val result = ShoppingListCalculator.computeShoppingList(
plannedMeals = listOf(predicted.toPlannedMealEntry()),
recipesById = emptyMap(),
inventory = inventory,
manualItems = emptyList()
)
// Riz fully covered (500g >= 180g)
assertNull(result.firstOrNull { it.normalizedName == "riz" })
// Brocoli partially covered (400g - 150g = 250g missing)
val broccoli = result.first { it.normalizedName == "brocoli" }
assertEquals(250.0, broccoli.missingQuantity!!, 0.01)
assertEquals(150.0, broccoli.inStockQuantity, 0.01)
// Saumon not in stock (300g missing)
val salmon = result.first { it.normalizedName == "saumon" }
assertEquals(300.0, salmon.missingQuantity!!, 0.01)
assertEquals(ShoppingItemSource.FROM_PLAN, salmon.source)
}
}
@@ -0,0 +1,28 @@
package com.example
import com.example.data.model.FoodCategory
import com.example.data.model.StorageLocation
import org.junit.Assert.assertEquals
import org.junit.Test
class StorageLocationMappingTest {
@Test
fun defaultForCategory_mapsFreshCategoriesToFridge() {
assertEquals(StorageLocation.FRIDGE, StorageLocation.defaultForCategory(FoodCategory.PROTEIN))
assertEquals(StorageLocation.FRIDGE, StorageLocation.defaultForCategory(FoodCategory.VEGETABLE))
assertEquals(StorageLocation.FRIDGE, StorageLocation.defaultForCategory(FoodCategory.FRUIT))
assertEquals(StorageLocation.FRIDGE, StorageLocation.defaultForCategory(FoodCategory.CHEESE))
assertEquals(StorageLocation.FRIDGE, StorageLocation.defaultForCategory(FoodCategory.DAIRY))
}
@Test
fun defaultForCategory_mapsDryAndPantryCategoriesToPantry() {
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.STARCH))
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.BREAD))
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.NUTS))
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.FAT_SEASONING))
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.PLEASURE))
assertEquals(StorageLocation.PANTRY, StorageLocation.defaultForCategory(FoodCategory.OTHER))
}
}
@@ -0,0 +1,118 @@
package com.example
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.domain.WeeklyMealPredictor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.time.LocalDate
class WeeklyMealPredictorTest {
@Test
fun parsePredictionJson_linksExistingRecipeParsesCustomMealAndFiltersInvalidSlots() {
val monday = LocalDate.of(2026, 11, 23)
val tuesday = LocalDate.of(2026, 11, 24)
val emptySlots = listOf(
monday to MealType.LUNCH,
monday to MealType.DINNER,
tuesday to MealType.LUNCH
)
val savedRecipe = RecipeEntry(
id = "rec_dahl",
title = "Dahl de lentilles corail",
servings = 2,
ingredientsSerialized = listOf(
MealFoodItem("Lentilles corail", 180.0, FoodUnit.G, FoodCategory.STARCH).serialize(),
MealFoodItem("Carottes", 200.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize()
)
)
val sampleJson = """
{
"meals": [
{
"slotIndex": 0,
"recipeId": "rec_dahl",
"title": "Dahl de lentilles",
"reason": "Recette favorite avec vos carottes",
"ingredients": []
},
{
"slotIndex": 1,
"recipeId": "unknown_id_ignored",
"title": "Poêlée poulet courgettes",
"reason": "Utilise le poulet du frigo",
"ingredients": [
{ "name": "Blanc de poulet", "weight": 250, "unit": "g", "category": "PROTEIN" },
{ "name": "Courgettes", "weight": 300, "unit": "g", "category": "INVALID_CODE" }
]
},
{
"slotIndex": 1,
"recipeId": "",
"title": "Doublon à ignorer",
"reason": "Duplicate slot",
"ingredients": []
},
{
"slotIndex": 99,
"recipeId": "",
"title": "Hors bornes",
"reason": "Out of range",
"ingredients": []
}
]
}
""".trimIndent()
// Default servings = 1.0 (half of the 2-serving saved recipe)
val proposals = WeeklyMealPredictor.parsePredictionJson(
jsonString = sampleJson,
emptySlots = emptySlots,
recipesById = mapOf(savedRecipe.id to savedRecipe),
defaultServings = 1.0
)
assertEquals(2, proposals.size)
// Slot 0: matched existing recipe, scaled to 1 serving (90g lentilles, 100g carottes)
val first = proposals[0]
assertEquals(monday.toEpochDay(), first.dateEpochDay)
assertEquals(MealType.LUNCH, first.mealType)
assertEquals("rec_dahl", first.recipeId)
assertEquals("Dahl de lentilles corail", first.title)
assertEquals(2, first.items.size)
assertEquals(90.0, first.items[0].weight!!, 0.01)
assertEquals(100.0, first.items[1].weight!!, 0.01)
assertTrue(first.selected)
// Slot 1: unknown recipeId safely cleared to null, invalid category falls back via inferFromName
val second = proposals[1]
assertEquals(monday.toEpochDay(), second.dateEpochDay)
assertEquals(MealType.DINNER, second.mealType)
assertNull(second.recipeId)
assertEquals("Poêlée poulet courgettes", second.title)
assertEquals(2, second.items.size)
assertEquals(FoodCategory.PROTEIN, second.items[0].category)
assertEquals(FoodCategory.VEGETABLE, second.items[1].category)
}
@Test
fun parsePredictionJson_handlesMalformedJsonGracefully() {
val slots = listOf(LocalDate.of(2026, 11, 23) to MealType.LUNCH)
val parsed = WeeklyMealPredictor.parsePredictionJson(
jsonString = "{ not valid json",
emptySlots = slots,
recipesById = emptyMap(),
defaultServings = 2.0
)
assertTrue(parsed.isEmpty())
}
}