feat(recipes): add Cook With Stock filter, step-by-step Cooking Mode with timers, and leftovers management

This commit is contained in:
bleack committed 2026-11-29 16:36:53 +01:00
1 parent 9b44e488fc
commit 7181ea58fc
7 files changed
+1077 -6

No files matched your search

+48 -1
View File
@@ -70,6 +70,7 @@ import com.example.ui.planning.BarcodeScannerScreen
import com.example.ui.planning.PlanningScreen import com.example.ui.planning.PlanningScreen
import com.example.ui.planning.PlanningViewModel import com.example.ui.planning.PlanningViewModel
import com.example.ui.planning.StockDeductionDialog import com.example.ui.planning.StockDeductionDialog
import com.example.ui.recipes.CookingModeScreen
import com.example.ui.recipes.ImportRecipeSheet import com.example.ui.recipes.ImportRecipeSheet
import com.example.ui.recipes.RecipeDetailSheet import com.example.ui.recipes.RecipeDetailSheet
import com.example.ui.recipes.RecipeEditorSheet import com.example.ui.recipes.RecipeEditorSheet
@@ -244,6 +245,7 @@ fun AppRoot(
var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) } var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) }
var showImportRecipeSheet by rememberSaveable { mutableStateOf(false) } var showImportRecipeSheet by rememberSaveable { mutableStateOf(false) }
var showBarcodeScanner by rememberSaveable { mutableStateOf(false) } var showBarcodeScanner by rememberSaveable { mutableStateOf(false) }
var cookingModeTarget by remember { mutableStateOf<Pair<RecipeEntry, Int>?>(null) }
LaunchedEffect(openPlanningRequested) { LaunchedEffect(openPlanningRequested) {
if (openPlanningRequested) { if (openPlanningRequested) {
@@ -482,7 +484,7 @@ fun AppRoot(
} }
} }
BackHandler(enabled = currentTab != MainTab.JOURNAL && !showBarcodeScanner) { BackHandler(enabled = currentTab != MainTab.JOURNAL && !showBarcodeScanner && cookingModeTarget == null) {
currentTab = MainTab.JOURNAL currentTab = MainTab.JOURNAL
} }
@@ -595,6 +597,7 @@ fun AppRoot(
MainTab.RECIPES -> { MainTab.RECIPES -> {
RecipesScreen( RecipesScreen(
recipes = recipes, recipes = recipes,
inventoryItems = inventoryItems,
customFoods = customFoods, customFoods = customFoods,
foodPreferences = foodPreferences, foodPreferences = foodPreferences,
selectedIdeaMealType = selectedIdeaMealType, selectedIdeaMealType = selectedIdeaMealType,
@@ -861,6 +864,7 @@ fun AppRoot(
if (activeRecipe != null) { if (activeRecipe != null) {
RecipeDetailSheet( RecipeDetailSheet(
recipe = activeRecipe, recipe = activeRecipe,
inventoryItems = inventoryItems,
customFoods = customFoods, customFoods = customFoods,
onDismiss = { selectedRecipeId = null }, onDismiss = { selectedRecipeId = null },
onEdit = { onEdit = {
@@ -872,6 +876,16 @@ fun AppRoot(
selectedRecipeId = null selectedRecipeId = null
viewModel.deleteRecipe(activeRecipe.id) viewModel.deleteRecipe(activeRecipe.id)
}, },
onStartCookingMode = { rec, servings ->
selectedRecipeId = null
cookingModeTarget = rec to servings
},
onSaveLeftoversToStock = { rec, leftovers, location ->
planningViewModel.saveLeftoversToStock(rec, leftovers, location)
},
onPlanLeftoversTomorrow = { rec, leftovers ->
planningViewModel.planLeftoversForTomorrow(rec, leftovers)
},
onLogAsMeal = { recipe, eatenServings -> onLogAsMeal = { recipe, eatenServings ->
selectedRecipeId = null selectedRecipeId = null
val suggestedType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour) val suggestedType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
@@ -962,5 +976,38 @@ fun AppRoot(
onDismiss = { showBarcodeScanner = false } onDismiss = { showBarcodeScanner = false }
) )
} }
cookingModeTarget?.let { (cookingRecipe, cookedServings) ->
CookingModeScreen(
recipe = cookingRecipe,
cookedServings = cookedServings,
customFoods = customFoods,
onLogAsMeal = { rec, eatenServings ->
val suggestedType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
val scaled = rec.scaledIngredients(eatenServings.toDouble())
val prefilledMeal = MealEntry(
id = "",
mealType = suggestedType.name,
mealTimestamp = System.currentTimeMillis(),
hungerBefore = 5,
satietyAfter = 7,
note = "Recette : ${rec.title}",
foodItemsSerialized = scaled.map { it.serialize() },
photoUris = listOfNotNull(rec.photoUri)
)
currentTab = MainTab.JOURNAL
editingMeal = prefilledMeal
defaultMealType = suggestedType
showMealEntrySheet = true
},
onSaveLeftoversToStock = { rec, leftovers, location ->
planningViewModel.saveLeftoversToStock(rec, leftovers, location)
},
onPlanLeftoversTomorrow = { rec, leftovers ->
planningViewModel.planLeftoversForTomorrow(rec, leftovers)
},
onDismiss = { cookingModeTarget = null }
)
}
} }
} }
@@ -0,0 +1,107 @@
package com.example.domain
import com.example.data.model.InventoryItem
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeEntry
data class RecipeStockMatch(
val totalIngredients: Int,
val availableCount: Int,
val missingIngredients: List<MealFoodItem>
) {
val missingCount: Int
get() = missingIngredients.size
val isFullyAvailable: Boolean
get() = totalIngredients > 0 && missingCount == 0
val isAlmostAvailable: Boolean
get() = totalIngredients > 0 && missingCount <= 2
fun badgeLabel(): String? {
if (totalIngredients <= 0) return null
return when {
isFullyAvailable -> "Tous en stock ($availableCount/$totalIngredients)"
missingCount == 1 -> "Manque 1 ingrédient"
missingCount == 2 -> "Manque 2 ingrédients"
else -> "$availableCount/$totalIngredients en stock"
}
}
}
/**
* Evaluates which ingredients of a recipe are currently available in the user's kitchen stock
* and extracts cooking durations from step instructions for integrated timers.
*/
object RecipeStockMatcher {
fun evaluate(
recipe: RecipeEntry,
inventory: List<InventoryItem>,
servings: Int = recipe.servings
): RecipeStockMatch {
val ingredients = recipe.scaledIngredients(servings.coerceAtLeast(1).toDouble())
if (ingredients.isEmpty()) {
return RecipeStockMatch(
totalIngredients = 0,
availableCount = 0,
missingIngredients = emptyList()
)
}
val activeStockNames = inventory
.filter { it.quantity > 0.0 }
.map { it.normalizedName.ifBlank { IngredientMatcher.normalize(it.name) } }
.filter { it.isNotBlank() }
val missing = mutableListOf<MealFoodItem>()
var available = 0
ingredients.forEach { food ->
val norm = IngredientMatcher.normalize(food.name)
val isPresent = norm.isNotBlank() && activeStockNames.any { stockNorm ->
IngredientMatcher.matches(norm, stockNorm)
}
if (isPresent) {
available++
} else {
missing.add(food)
}
}
return RecipeStockMatch(
totalIngredients = ingredients.size,
availableCount = available,
missingIngredients = missing
)
}
/**
* Extracts the first cooking duration in minutes mentioned in a French recipe step
* (e.g. "enfourner 25 min" -> 25, "mijoter 1h30" -> 90, "cuire 10 minutes" -> 10).
*/
fun extractDurationMinutes(stepText: String): Int? {
val hourMinRegex = Regex("""(\d+)\s*h\s*(\d{1,2})\b""", RegexOption.IGNORE_CASE)
hourMinRegex.find(stepText)?.let { match ->
val h = match.groupValues[1].toIntOrNull() ?: 0
val m = match.groupValues[2].toIntOrNull() ?: 0
val total = h * 60 + m
if (total in 1..600) return total
}
val hoursOnlyRegex = Regex("""(\d+)\s*(?:h|heures?)\b""", RegexOption.IGNORE_CASE)
hoursOnlyRegex.find(stepText)?.let { match ->
val h = match.groupValues[1].toIntOrNull() ?: 0
val total = h * 60
if (total in 1..600) return total
}
val minutesRegex = Regex("""(\d+)\s*(?:min(?:utes?)?|mn)\b""", RegexOption.IGNORE_CASE)
minutesRegex.find(stepText)?.let { match ->
val m = match.groupValues[1].toIntOrNull() ?: 0
if (m in 1..600) return m
}
return null
}
}
@@ -586,6 +586,77 @@ class PlanningViewModel internal constructor(
) )
} }
// ------------------------------------------------------------------------
// Leftovers & Batch Cooking
// ------------------------------------------------------------------------
fun saveLeftoversToStock(
recipe: RecipeEntry,
servings: Int,
location: StorageLocation
) {
val safeServings = servings.coerceAtLeast(1)
viewModelScope.launch {
val dominantCategory = recipe.dominantCategories().firstOrNull() ?: FoodCategory.OTHER
val expirationEpochDay = when (location) {
StorageLocation.FRIDGE -> LocalDate.now().plusDays(3).toEpochDay()
StorageLocation.FREEZER, StorageLocation.PANTRY -> null
}
val result = repository.addOrMergeInventoryItem(
name = "Restes : ${recipe.title.trim()}",
quantityToAdd = safeServings.toDouble(),
unit = FoodUnit.PORTION,
category = dominantCategory,
location = location,
expirationDateEpochDay = expirationEpochDay
)
if (result.isSuccess) {
val dlcNote = if (location == StorageLocation.FRIDGE) " (DLC +3 j)" else ""
emitSnackbar(
"$safeServings part${if (safeServings > 1) "s" else ""} ajoutée${if (safeServings > 1) "s" else ""} au ${location.displayName}$dlcNote"
)
} else {
emitSnackbar("Impossible d'enregistrer les restes dans le stock")
}
}
}
fun planLeftoversForTomorrow(
recipe: RecipeEntry,
servings: Int
) {
val safeServings = servings.coerceAtLeast(1)
viewModelScope.launch {
val tomorrow = LocalDate.now().plusDays(1)
val tomorrowEpoch = tomorrow.toEpochDay()
val tomorrowMeals = repository.observePlannedMealsForWeek(tomorrowEpoch, tomorrowEpoch).first()
val occupiedTypes = tomorrowMeals.map { it.mealType }.toSet()
val targetMealType = when {
MealType.LUNCH !in occupiedTypes -> MealType.LUNCH
MealType.DINNER !in occupiedTypes -> MealType.DINNER
else -> MealType.LUNCH
}
val entry = PlannedMealEntry(
id = "",
dateEpochDay = tomorrowEpoch,
mealType = targetMealType,
recipeId = recipe.id.takeIf { it.isNotBlank() },
customTitle = "Restes : ${recipe.title.trim()}",
servings = safeServings.toDouble(),
itemsSerialized = emptyList(),
isConsumed = false
)
val result = repository.upsertPlannedMeal(entry)
if (result.isSuccess) {
emitSnackbar(
"Restes planifiés pour demain (${targetMealType.displayName}) • $safeServings part${if (safeServings > 1) "s" else ""}"
)
} else {
emitSnackbar("Impossible de planifier les restes pour demain")
}
}
}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Weekly Meal Prediction (Firebase AI Logic) // Weekly Meal Prediction (Firebase AI Logic)
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@@ -0,0 +1,575 @@
package com.example.ui.recipes
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.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
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.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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.AcUnit
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Timer
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.FilledTonalButton
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.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.RecipeEntry
import com.example.data.model.StorageLocation
import com.example.domain.RecipeStockMatcher
import com.example.ui.common.FoodCategoryBadge
import kotlinx.coroutines.delay
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun CookingModeScreen(
recipe: RecipeEntry,
cookedServings: Int,
customFoods: List<CustomFoodEntry>,
onLogAsMeal: (RecipeEntry, Int) -> Unit,
onSaveLeftoversToStock: (RecipeEntry, Int, StorageLocation) -> Unit,
onPlanLeftoversTomorrow: (RecipeEntry, Int) -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
val activity = remember(context) { context.findActivity() }
val haptic = LocalHapticFeedback.current
// Keep screen awake automatically during Cooking Mode
DisposableEffect(activity) {
val window = activity?.window
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
onDispose {
window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
val steps = remember(recipe.steps) {
recipe.steps.ifEmpty { listOf("Préparez les ingrédients et assemblez la recette selon vos goûts.") }
}
val customLookup = remember(customFoods) { CustomFoodEntry.buildCategoriesLookup(customFoods) }
val scaledIngredients = remember(recipe.ingredientsSerialized, cookedServings) {
recipe.scaledIngredients(cookedServings.coerceAtLeast(1).toDouble())
}
var currentStepIndex by rememberSaveable(recipe.id) { mutableIntStateOf(0) }
var showIngredientsPanel by rememberSaveable(recipe.id) { mutableStateOf(false) }
var showFinishDialog by remember { mutableStateOf(false) }
// Integrated kitchen timer state
var remainingSeconds by rememberSaveable(recipe.id) { mutableIntStateOf(0) }
var timerRunning by rememberSaveable(recipe.id) { mutableStateOf(false) }
LaunchedEffect(timerRunning, remainingSeconds) {
if (timerRunning && remainingSeconds > 0) {
delay(1000L)
remainingSeconds -= 1
if (remainingSeconds == 0) {
timerRunning = false
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
}
}
}
val currentStepText = steps.getOrElse(currentStepIndex) { "" }
val detectedMinutes = remember(currentStepText) {
RecipeStockMatcher.extractDurationMinutes(currentStepText)
}
val progress = (currentStepIndex + 1).toFloat() / steps.size.toFloat()
BackHandler(onBack = onDismiss)
Scaffold(
contentWindowInsets = WindowInsets.safeDrawing,
modifier = Modifier
.fillMaxSize()
.testTag("cooking_mode_screen"),
topBar = {
Column {
TopAppBar(
title = {
Column {
Text(
text = recipe.title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = "Mode Cuisine • $cookedServings part${if (cookedServings > 1) "s" else ""} • écran allumé",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary
)
}
},
navigationIcon = {
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Quitter le mode cuisine")
}
},
actions = {
TextButton(onClick = { showIngredientsPanel = !showIngredientsPanel }) {
Text(if (showIngredientsPanel) "Étapes" else "Ingrédients")
}
}
)
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)
) {
OutlinedButton(
onClick = { if (currentStepIndex > 0) currentStepIndex-- },
enabled = currentStepIndex > 0,
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier.weight(0.38f)
) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Préc.")
}
if (currentStepIndex < steps.lastIndex) {
Button(
onClick = { currentStepIndex++ },
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier.weight(0.62f)
) {
Text("Étape suivante", fontWeight = FontWeight.SemiBold)
Spacer(modifier = Modifier.width(6.dp))
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, modifier = Modifier.size(18.dp))
}
} else {
Button(
onClick = { showFinishDialog = true },
shape = RoundedCornerShape(14.dp),
contentPadding = PaddingValues(vertical = 14.dp),
modifier = Modifier
.weight(0.62f)
.testTag("finish_cooking_button")
) {
Icon(Icons.Default.Check, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("J'ai fini !", fontWeight = FontWeight.SemiBold)
}
}
}
}
}
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.verticalScroll(rememberScrollState())
.padding(horizontal = 20.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Kitchen Timer Card
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = if (timerRunning) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f)
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
}
),
border = if (timerRunning) BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.4f)) else null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Timer,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = formatTimerClock(remainingSeconds),
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Bold
)
}
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
IconButton(
onClick = {
if (remainingSeconds > 0) timerRunning = !timerRunning
},
enabled = remainingSeconds > 0
) {
Icon(
imageVector = if (timerRunning) Icons.Default.Pause else Icons.Default.PlayArrow,
contentDescription = if (timerRunning) "Pause" else "Démarrer"
)
}
IconButton(
onClick = {
timerRunning = false
remainingSeconds = 0
},
enabled = remainingSeconds > 0
) {
Icon(Icons.Default.Refresh, contentDescription = "Réinitialiser")
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
listOf(1, 5, 10, 15).forEach { mins ->
FilterChip(
selected = false,
onClick = {
remainingSeconds += mins * 60
timerRunning = true
},
label = { Text("+$mins min", maxLines = 1) },
modifier = Modifier.weight(1f)
)
}
}
}
}
if (showIngredientsPanel) {
Text(
text = "Ingrédients ($cookedServings part${if (cookedServings > 1) "s" else ""})",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
scaledIngredients.forEach { item ->
FoodCategoryBadge(
text = item.displayBadge(),
categories = item.resolvedCategories(customLookup)
)
}
}
} else {
// Active step card (large readable typography)
Card(
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(22.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = "Étape ${currentStepIndex + 1} sur ${steps.size}",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
Text(
text = currentStepText,
style = MaterialTheme.typography.headlineSmall.copy(lineHeight = 32.sp),
color = MaterialTheme.colorScheme.onSurface
)
if (detectedMinutes != null) {
FilledTonalButton(
onClick = {
remainingSeconds = detectedMinutes * 60
timerRunning = true
},
shape = RoundedCornerShape(12.dp)
) {
Icon(Icons.Default.Timer, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Lancer le minuteur ($detectedMinutes min)")
}
}
}
}
// Quick step overview pills
if (steps.size > 1) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
steps.indices.forEach { idx ->
Surface(
shape = RoundedCornerShape(8.dp),
color = when {
idx == currentStepIndex -> MaterialTheme.colorScheme.primary
idx < currentStepIndex -> MaterialTheme.colorScheme.primaryContainer
else -> MaterialTheme.colorScheme.surfaceVariant
},
modifier = Modifier
.weight(1f)
.height(8.dp)
.clickable { currentStepIndex = idx }
) {}
}
}
}
}
}
}
if (showFinishDialog) {
var eatenNow by remember { mutableIntStateOf(1.coerceAtMost(cookedServings)) }
val leftovers = (cookedServings - eatenNow).coerceAtLeast(0)
AlertDialog(
onDismissRequest = { showFinishDialog = false },
title = {
Text(
text = "Bon appétit !",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(
text = "Vous avez cuisiné $cookedServings part${if (cookedServings > 1) "s" else ""} de « ${recipe.title} ».",
style = MaterialTheme.typography.bodyMedium
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Parts mangées maintenant :", style = MaterialTheme.typography.labelLarge)
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(
onClick = { if (eatenNow > 0) eatenNow-- },
enabled = eatenNow > 0
) { Text("−", fontWeight = FontWeight.Bold) }
Text("$eatenNow", fontWeight = FontWeight.Bold)
TextButton(
onClick = { if (eatenNow < cookedServings) eatenNow++ },
enabled = eatenNow < cookedServings
) { Text("+", fontWeight = FontWeight.Bold) }
}
}
if (leftovers > 0) {
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "Que faire des $leftovers part${if (leftovers > 1) "s" else ""} restante${if (leftovers > 1) "s" else ""} ?",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
FilledTonalButton(
onClick = {
onSaveLeftoversToStock(recipe, leftovers, StorageLocation.FRIDGE)
},
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 6.dp),
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Kitchen, contentDescription = null, modifier = Modifier.size(15.dp))
Spacer(modifier = Modifier.width(4.dp))
Text("Frigo", maxLines = 1)
}
FilledTonalButton(
onClick = {
onSaveLeftoversToStock(recipe, leftovers, StorageLocation.FREEZER)
},
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 6.dp),
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.AcUnit, contentDescription = null, modifier = Modifier.size(15.dp))
Spacer(modifier = Modifier.width(4.dp))
Text("Congél.", maxLines = 1)
}
}
OutlinedButton(
onClick = {
onPlanLeftoversTomorrow(recipe, leftovers)
},
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Default.CalendarMonth, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Planifier pour demain")
}
}
}
}
}
},
confirmButton = {
if (eatenNow > 0) {
Button(
onClick = {
showFinishDialog = false
onDismiss()
onLogAsMeal(recipe, eatenNow)
}
) {
Icon(Icons.Default.Restaurant, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Noter au journal")
}
} else {
Button(
onClick = {
showFinishDialog = false
onDismiss()
}
) {
Text("Terminer")
}
}
},
dismissButton = {
TextButton(
onClick = {
showFinishDialog = false
onDismiss()
}
) {
Text("Fermer")
}
}
)
}
}
private fun formatTimerClock(totalSeconds: Int): String {
val safe = totalSeconds.coerceAtLeast(0)
val hours = safe / 3600
val mins = (safe % 3600) / 60
val secs = safe % 60
return if (hours > 0) {
String.format(Locale.FRENCH, "%d:%02d:%02d", hours, mins, secs)
} else {
String.format(Locale.FRENCH, "%02d:%02d", mins, secs)
}
}
private tailrec fun Context.findActivity(): Activity? = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}
@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@@ -19,11 +20,15 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AcUnit
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.RadioButtonUnchecked import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.Remove import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Restaurant
@@ -32,11 +37,13 @@ import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
@@ -59,7 +66,10 @@ import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.InventoryItem
import com.example.data.model.RecipeEntry import com.example.data.model.RecipeEntry
import com.example.data.model.StorageLocation
import com.example.domain.RecipeStockMatcher
import com.example.ui.common.FoodCategoryBadge import com.example.ui.common.FoodCategoryBadge
import java.util.Locale import java.util.Locale
@@ -67,10 +77,14 @@ import java.util.Locale
@Composable @Composable
fun RecipeDetailSheet( fun RecipeDetailSheet(
recipe: RecipeEntry, recipe: RecipeEntry,
inventoryItems: List<InventoryItem> = emptyList(),
customFoods: List<CustomFoodEntry>, customFoods: List<CustomFoodEntry>,
onDismiss: () -> Unit, onDismiss: () -> Unit,
onEdit: () -> Unit, onEdit: () -> Unit,
onDelete: () -> Unit, onDelete: () -> Unit,
onStartCookingMode: (RecipeEntry, Int) -> Unit = { _, _ -> },
onSaveLeftoversToStock: (RecipeEntry, Int, StorageLocation) -> Unit = { _, _, _ -> },
onPlanLeftoversTomorrow: (RecipeEntry, Int) -> Unit = { _, _ -> },
onLogAsMeal: (RecipeEntry, Int) -> Unit onLogAsMeal: (RecipeEntry, Int) -> Unit
) { ) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
@@ -87,6 +101,10 @@ fun RecipeDetailSheet(
recipe.scaledIngredients(displayServings.toDouble()) recipe.scaledIngredients(displayServings.toDouble())
} }
val stockMatch = remember(recipe, inventoryItems, displayServings) {
if (inventoryItems.isEmpty()) null else RecipeStockMatcher.evaluate(recipe, inventoryItems, displayServings)
}
ModalBottomSheet( ModalBottomSheet(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
sheetState = sheetState, sheetState = sheetState,
@@ -281,7 +299,49 @@ fun RecipeDetailSheet(
) )
} }
} }
if (stockMatch != null && stockMatch.totalIngredients > 0) {
Spacer(modifier = Modifier.height(10.dp))
Text(
text = if (stockMatch.isFullyAvailable) {
"✓ Tous les ingrédients sont déjà dans votre stock"
} else {
"En stock : ${stockMatch.availableCount}/${stockMatch.totalIngredients} • Manque : " +
stockMatch.missingIngredients.joinToString(", ") { it.name }
},
style = MaterialTheme.typography.labelSmall,
color = if (stockMatch.isFullyAvailable) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
} }
)
}
}
}
}
// Cooking Mode launch button
if (recipe.steps.isNotEmpty() || scaledIngredients.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
FilledTonalButton(
onClick = { onStartCookingMode(recipe, displayServings) },
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.height(46.dp)
.testTag("start_cooking_mode_button")
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Lancer le Mode Cuisine (pas-à-pas & minuteur)",
fontWeight = FontWeight.SemiBold
)
} }
} }
@@ -444,6 +504,70 @@ fun RecipeDetailSheet(
} }
} }
// Leftovers & Batch Cooking section when cooked servings > eaten servings
val leftoverServings = (displayServings - eatenServings).coerceAtLeast(0)
if (leftoverServings > 0) {
Spacer(modifier = Modifier.height(12.dp))
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.45f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.secondary.copy(alpha = 0.3f)),
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_leftovers_card")
) {
Column(
modifier = Modifier.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "Restes / Batch cooking ($leftoverServings part${if (leftoverServings > 1) "s" else ""} restante${if (leftoverServings > 1) "s" else ""})",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FilledTonalButton(
onClick = {
onSaveLeftoversToStock(recipe, leftoverServings, StorageLocation.FRIDGE)
},
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.Kitchen, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Frigo (+3 j)", maxLines = 1)
}
FilledTonalButton(
onClick = {
onSaveLeftoversToStock(recipe, leftoverServings, StorageLocation.FREEZER)
},
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp),
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.AcUnit, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Congélateur", maxLines = 1)
}
}
OutlinedButton(
onClick = { onPlanLeftoversTomorrow(recipe, leftoverServings) },
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Default.CalendarMonth, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Planifier les restes pour demain")
}
}
}
}
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
} }
} }
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.People import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
@@ -64,12 +65,15 @@ import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.InventoryItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry import com.example.data.model.RecipeEntry
import com.example.data.model.RecipeSuggestion import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState import com.example.data.model.SuggestionUiState
import com.example.domain.DailyBenchmarkGap import com.example.domain.DailyBenchmarkGap
import com.example.domain.RecipeStockMatch
import com.example.domain.RecipeStockMatcher
import com.example.ui.common.FoodCategoryColorDot import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor import com.example.ui.common.badgeContainerColor
@@ -85,6 +89,7 @@ private enum class RecipesSubTab(val label: String) {
@Composable @Composable
fun RecipesScreen( fun RecipesScreen(
recipes: List<RecipeEntry>, recipes: List<RecipeEntry>,
inventoryItems: List<InventoryItem> = emptyList(),
customFoods: List<CustomFoodEntry>, customFoods: List<CustomFoodEntry>,
foodPreferences: List<FoodPreferenceEntry>, foodPreferences: List<FoodPreferenceEntry>,
selectedIdeaMealType: MealType, selectedIdeaMealType: MealType,
@@ -105,20 +110,44 @@ fun RecipesScreen(
var activeSubTab by rememberSaveable { mutableStateOf(RecipesSubTab.BOOK) } var activeSubTab by rememberSaveable { mutableStateOf(RecipesSubTab.BOOK) }
var searchQuery by rememberSaveable { mutableStateOf("") } var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedTag by rememberSaveable { mutableStateOf<String?>(null) } var selectedTag by rememberSaveable { mutableStateOf<String?>(null) }
var filterByStockOnly by rememberSaveable { mutableStateOf(false) }
var cravingNote by rememberSaveable { mutableStateOf("") } var cravingNote by rememberSaveable { mutableStateOf("") }
val customCategoriesLookup = remember(customFoods) { val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods) CustomFoodEntry.buildCategoriesLookup(customFoods)
} }
val filteredRecipes = remember(recipes, searchQuery, selectedTag) { val stockMatchesByRecipeId = remember(recipes, inventoryItems) {
if (inventoryItems.isEmpty()) {
emptyMap()
} else {
recipes.associate { recipe ->
recipe.id to RecipeStockMatcher.evaluate(recipe, inventoryItems)
}
}
}
val stockReadyCount = remember(stockMatchesByRecipeId) {
stockMatchesByRecipeId.values.count { it.isAlmostAvailable }
}
val filteredRecipes = remember(recipes, searchQuery, selectedTag, filterByStockOnly, stockMatchesByRecipeId) {
val query = searchQuery.trim().lowercase(Locale.FRENCH) val query = searchQuery.trim().lowercase(Locale.FRENCH)
recipes.filter { recipe -> val filtered = recipes.filter { recipe ->
val matchesTag = selectedTag == null || recipe.categoryTag.equals(selectedTag, ignoreCase = true) val matchesTag = selectedTag == null || recipe.categoryTag.equals(selectedTag, ignoreCase = true)
val matchesQuery = query.isBlank() || val matchesQuery = query.isBlank() ||
recipe.title.lowercase(Locale.FRENCH).contains(query) || recipe.title.lowercase(Locale.FRENCH).contains(query) ||
recipe.parsedIngredients().any { it.name.lowercase(Locale.FRENCH).contains(query) } recipe.parsedIngredients().any { it.name.lowercase(Locale.FRENCH).contains(query) }
matchesTag && matchesQuery val matchesStock = !filterByStockOnly || (stockMatchesByRecipeId[recipe.id]?.isAlmostAvailable == true)
matchesTag && matchesQuery && matchesStock
}
if (filterByStockOnly) {
filtered.sortedWith(
compareBy<RecipeEntry> { stockMatchesByRecipeId[it.id]?.missingCount ?: Int.MAX_VALUE }
.thenByDescending { stockMatchesByRecipeId[it.id]?.availableCount ?: 0 }
)
} else {
filtered
} }
} }
@@ -316,10 +345,34 @@ fun RecipesScreen(
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
if (inventoryItems.isNotEmpty()) {
item { item {
FilterChip( FilterChip(
selected = selectedTag == null, selected = filterByStockOnly,
onClick = { selectedTag = null }, onClick = { filterByStockOnly = !filterByStockOnly },
leadingIcon = {
Icon(
imageVector = Icons.Default.Kitchen,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
label = { Text("Avec mon stock ($stockReadyCount)") },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onSecondaryContainer
),
modifier = Modifier.testTag("recipe_filter_stock")
)
}
}
item {
FilterChip(
selected = selectedTag == null && !filterByStockOnly,
onClick = {
selectedTag = null
filterByStockOnly = false
},
label = { Text("Toutes") }, label = { Text("Toutes") },
colors = FilterChipDefaults.filterChipColors( colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
@@ -373,6 +426,7 @@ fun RecipesScreen(
onClick = { onClick = {
searchQuery = "" searchQuery = ""
selectedTag = null selectedTag = null
filterByStockOnly = false
} }
) { ) {
Text("Réinitialiser les filtres") Text("Réinitialiser les filtres")
@@ -384,6 +438,7 @@ fun RecipesScreen(
items(filteredRecipes, key = { it.id }) { recipe -> items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem( RecipeCardItem(
recipe = recipe, recipe = recipe,
stockMatch = stockMatchesByRecipeId[recipe.id],
customCategoriesLookup = customCategoriesLookup, customCategoriesLookup = customCategoriesLookup,
onClick = { onRecipeClick(recipe) } onClick = { onRecipeClick(recipe) }
) )
@@ -417,6 +472,7 @@ fun RecipesScreen(
@Composable @Composable
private fun RecipeCardItem( private fun RecipeCardItem(
recipe: RecipeEntry, recipe: RecipeEntry,
stockMatch: RecipeStockMatch? = null,
customCategoriesLookup: Map<String, List<FoodCategory>>, customCategoriesLookup: Map<String, List<FoodCategory>>,
onClick: () -> Unit onClick: () -> Unit
) { ) {
@@ -498,6 +554,39 @@ private fun RecipeCardItem(
overflow = TextOverflow.Ellipsis overflow = TextOverflow.Ellipsis
) )
val stockBadge = stockMatch?.badgeLabel()
if (stockBadge != null) {
Spacer(modifier = Modifier.height(6.dp))
val (bg, fg) = when {
stockMatch.isFullyAvailable -> MaterialTheme.colorScheme.secondaryContainer to MaterialTheme.colorScheme.onSecondaryContainer
stockMatch.isAlmostAvailable -> MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.7f) to MaterialTheme.colorScheme.onPrimaryContainer
else -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
}
Surface(
shape = RoundedCornerShape(8.dp),
color = bg
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
) {
Icon(
imageVector = Icons.Default.Kitchen,
contentDescription = null,
tint = fg,
modifier = Modifier.size(13.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = stockBadge,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.SemiBold,
color = fg
)
}
}
}
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
// Metadata chips (prep time, servings, ingredient count) // Metadata chips (prep time, servings, ingredient count)
@@ -0,0 +1,58 @@
package com.example
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeEntry
import com.example.domain.RecipeStockMatcher
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class RecipeStockMatcherTest {
@Test
fun evaluate_identifiesFullAndPartialStockMatches() {
val recipe = RecipeEntry(
id = "r1",
title = "Omelette aux courgettes",
servings = 2,
ingredientsSerialized = listOf(
MealFoodItem("Œufs", 4.0, FoodUnit.PORTION, categories = listOf(FoodCategory.PROTEIN)).serialize(),
MealFoodItem("Courgettes", 300.0, FoodUnit.G, categories = listOf(FoodCategory.VEGETABLE)).serialize(),
MealFoodItem("Comté", 40.0, FoodUnit.G, categories = listOf(FoodCategory.CHEESE)).serialize()
)
)
val partialStock = listOf(
InventoryItem(id = "i1", name = "Oeuf", quantity = 6.0, unit = FoodUnit.PORTION),
InventoryItem(id = "i2", name = "Courgette", quantity = 500.0, unit = FoodUnit.G)
)
val partial = RecipeStockMatcher.evaluate(recipe, partialStock)
assertEquals(3, partial.totalIngredients)
assertEquals(2, partial.availableCount)
assertEquals(1, partial.missingCount)
assertFalse(partial.isFullyAvailable)
assertTrue(partial.isAlmostAvailable)
assertEquals("Manque 1 ingrédient", partial.badgeLabel())
val fullStock = partialStock + InventoryItem(id = "i3", name = "Comté", quantity = 150.0, unit = FoodUnit.G)
val full = RecipeStockMatcher.evaluate(recipe, fullStock)
assertTrue(full.isFullyAvailable)
assertEquals(0, full.missingCount)
assertEquals("Tous en stock (3/3)", full.badgeLabel())
}
@Test
fun extractDurationMinutes_parsesFrenchMinutesAndHours() {
assertEquals(25, RecipeStockMatcher.extractDurationMinutes("Enfourner pendant 25 min à 180°C."))
assertEquals(10, RecipeStockMatcher.extractDurationMinutes("Laisser mijoter 10 minutes à feu doux."))
assertEquals(90, RecipeStockMatcher.extractDurationMinutes("Cuire 1h30 en cocotte."))
assertEquals(120, RecipeStockMatcher.extractDurationMinutes("Laisser reposer 2 heures au frais."))
assertNull(RecipeStockMatcher.extractDurationMinutes("Couper les tomates en dés et assaisonner."))
}
}