feat: implement weekly meal planning and inventory

- Add Planning module with UI and ViewModel
- Update database schema to support planned meals and inventory
- Add camera permission for future features
- Refactor food category handling to support multiple tags
This commit is contained in:
bleackstorm committed 2026-11-22 12:24:47 +01:00
1 parent 1331fae119
commit 8e794e6da7
46 files changed
+6335 -192

No files matched your search

@@ -17,6 +17,7 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
@@ -29,6 +30,8 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@@ -68,10 +71,33 @@ fun FoodCategoryColorDot(
.size(size)
.clip(CircleShape)
.background(fill)
.border(width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp, color = borderColor, shape = CircleShape)
.border(
width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp,
color = borderColor,
shape = CircleShape
)
)
}
@Composable
fun FoodCategoryColorDotsRow(
categories: List<FoodCategory>,
modifier: Modifier = Modifier,
dotSize: Dp = 8.dp,
spacing: Dp = 3.dp
) {
val effective = FoodCategory.sanitizeSelection(categories).ifEmpty { listOf(FoodCategory.OTHER) }
Row(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(spacing),
verticalAlignment = Alignment.CenterVertically
) {
effective.forEach { cat ->
FoodCategoryColorDot(category = cat, size = dotSize)
}
}
}
@Composable
fun FoodCategoryBadge(
text: String,
@@ -79,15 +105,53 @@ fun FoodCategoryBadge(
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null
) {
FoodCategoryBadge(
text = text,
categories = listOf(category),
modifier = modifier,
onClick = onClick,
onRemove = onRemove
)
}
@Composable
fun FoodCategoryBadge(
text: String,
categories: List<FoodCategory>,
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null
) {
val isDark = isSatieaDarkTheme()
val effectiveCategories = FoodCategory.sanitizeSelection(categories).ifEmpty { listOf(FoodCategory.OTHER) }
val isMulti = effectiveCategories.size > 1
val primaryCategory = effectiveCategories.first()
val shape = RoundedCornerShape(11.dp)
val containerColor = if (isMulti) {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = if (isDark) 0.72f else 0.55f)
} else {
primaryCategory.badgeContainerColor(isDark)
}
val borderColor = if (isMulti) {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = if (isDark) 0.85f else 0.9f)
} else {
primaryCategory.badgeBorderColor(isDark)
}
val textColor = if (isMulti) {
MaterialTheme.colorScheme.onSurface
} else {
primaryCategory.badgeTextColor(isDark)
}
val accessibilityDesc = "$text, catégories : ${effectiveCategories.joinToString(", ") { it.displayName }}"
Surface(
shape = shape,
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark)),
color = containerColor,
border = BorderStroke(1.dp, borderColor),
modifier = modifier
.semantics { contentDescription = accessibilityDesc }
.clip(shape)
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
) {
@@ -100,12 +164,16 @@ fun FoodCategoryBadge(
),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 8.dp)
FoodCategoryColorDotsRow(
categories = effectiveCategories,
dotSize = 8.dp,
spacing = 3.dp
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = text,
style = MaterialTheme.typography.labelMedium,
color = category.badgeTextColor(isDark),
color = textColor,
fontWeight = FontWeight.SemiBold
)
if (onRemove != null) {
@@ -113,7 +181,7 @@ fun FoodCategoryBadge(
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer $text",
tint = category.badgeTextColor(isDark).copy(alpha = 0.8f),
tint = textColor.copy(alpha = 0.8f),
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
@@ -130,8 +198,24 @@ fun FoodCategorySelectorRow(
selectedCategory: FoodCategory,
onCategorySelected: (FoodCategory) -> Unit,
modifier: Modifier = Modifier
) {
FoodCategorySelectorRow(
selectedCategories = listOf(selectedCategory),
onCategoryToggled = onCategorySelected,
modifier = modifier
)
}
@Composable
fun FoodCategorySelectorRow(
selectedCategories: List<FoodCategory>,
onCategoryToggled: (FoodCategory) -> Unit,
modifier: Modifier = Modifier
) {
val isDark = isSatieaDarkTheme()
val effectiveSelected = FoodCategory.sanitizeSelection(selectedCategories)
.ifEmpty { listOf(FoodCategory.OTHER) }
.toSet()
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -140,10 +224,10 @@ fun FoodCategorySelectorRow(
.testTag("food_category_selector_row")
) {
items(FoodCategory.entries, key = { it.name }) { category ->
val isSelected = category == selectedCategory
val isSelected = category in effectiveSelected
val shape = RoundedCornerShape(12.dp)
val containerColor = if (isSelected) {
category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.34f else 0.24f)
category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.48f else 0.32f)
} else {
MaterialTheme.colorScheme.surface
}
@@ -163,7 +247,7 @@ fun FoodCategorySelectorRow(
border = BorderStroke(if (isSelected) 1.5.dp else 1.dp, borderColor),
modifier = Modifier
.clip(shape)
.clickable { onCategorySelected(category) }
.clickable { onCategoryToggled(category) }
.testTag("food_category_chip_${category.name.lowercase()}")
) {
Row(
@@ -178,6 +262,15 @@ fun FoodCategorySelectorRow(
color = if (isSelected) category.badgeTextColor(isDark) else MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
)
if (isSelected && category != FoodCategory.OTHER) {
Spacer(modifier = Modifier.width(4.dp))
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
tint = category.badgeTextColor(isDark),
modifier = Modifier.size(13.dp)
)
}
}
}
}
@@ -0,0 +1,83 @@
package com.example.ui.common
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.EditNote
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
/**
* Reusable Material 3 confirmation dialog shown when the user tries to leave a form
* (meal entry or recipe editor) that has unsaved changes.
*/
@Composable
fun UnsavedChangesDiscardDialog(
title: String = "Quitter sans enregistrer ?",
message: String = "Vos modifications en cours ne sont pas encore enregistrées. Si vous quittez maintenant, elles seront perdues.",
onContinueEditing: () -> Unit,
onConfirmDiscard: () -> Unit
) {
AlertDialog(
onDismissRequest = onContinueEditing,
modifier = Modifier.testTag("unsaved_changes_dialog"),
shape = RoundedCornerShape(22.dp),
icon = {
Icon(
imageVector = Icons.Default.EditNote,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(28.dp)
)
},
title = {
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
text = message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
},
confirmButton = {
Button(
onClick = onContinueEditing,
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
),
modifier = Modifier.testTag("unsaved_continue_button")
) {
Text("Continuer la saisie")
}
},
dismissButton = {
TextButton(
onClick = onConfirmDiscard,
modifier = Modifier.testTag("unsaved_discard_button")
) {
Text(
text = "Quitter sans enregistrer",
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.SemiBold
)
}
}
)
}
@@ -86,8 +86,8 @@ fun JournalScreen(
) {
var showDietaryGuide by remember { mutableStateOf(false) }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
Box(
@@ -151,7 +151,7 @@ fun JournalScreen(
item {
DailyBenchmarksCard(
todayMeals = todayMeals,
customCategoryLookup = customCategoryLookup,
customCategoriesLookup = customCategoriesLookup,
onOpenGuideClick = { showDietaryGuide = true }
)
}
@@ -221,7 +221,7 @@ fun JournalScreen(
items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal ->
MealCardItem(
meal = meal,
customCategoryLookup = customCategoryLookup,
customCategoriesLookup = customCategoriesLookup,
onEdit = { onEditMeal(meal) },
onDelete = { onDeleteMeal(meal.id) }
)
@@ -353,7 +353,7 @@ private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
@Composable
private fun MealCardItem(
meal: MealEntry,
customCategoryLookup: Map<String, FoodCategory>,
customCategoriesLookup: Map<String, List<FoodCategory>>,
onEdit: () -> Unit,
onDelete: () -> Unit
) {
@@ -551,7 +551,7 @@ private fun MealCardItem(
parsedFoods.forEach { food ->
FoodCategoryBadge(
text = food.displayBadge(),
category = food.resolvedCategory(customCategoryLookup)
categories = food.resolvedCategories(customCategoriesLookup)
)
}
}
@@ -173,11 +173,11 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
repository.observeCustomFoods(),
_selectedIdeaMealType
) { meals, foods, mealType ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val lookup = CustomFoodEntry.buildCategoriesLookup(foods)
DailyBenchmarkAnalyzer.analyzeToday(
meals = meals,
targetMealType = mealType,
customCategoryLookup = lookup
customCategoriesLookup = lookup
)
}
.flowOn(Dispatchers.Default)
@@ -201,10 +201,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
repository.observeMeals(),
repository.observeCustomFoods()
) { meals, foods ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val lookup = CustomFoodEntry.buildCategoriesLookup(foods)
WeeklyStatsCalculator.computeWeeklyStats(
meals = meals,
customCategoryLookup = lookup
customCategoriesLookup = lookup
)
}
.flowOn(Dispatchers.Default)
@@ -266,7 +266,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) {
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.associate {
it.name.lowercase(Locale.FRENCH) to it.category
it.name.lowercase(Locale.FRENCH) to it.resolvedCategories()
}
val existingCustom = customFoods.value.associateBy { it.name.lowercase(Locale.FRENCH) }
@@ -276,19 +276,19 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val normalized = cleanName.lowercase(Locale.FRENCH)
if (cleanName.isEmpty()) return@forEach
val chosenCategory = item.category ?: item.resolvedCategory()
val builtInCategory = existingBuiltIn[normalized]
val chosenCategories = item.resolvedCategories()
val builtInCategories = existingBuiltIn[normalized]
val existingEntry = existingCustom[normalized]
val shouldSave = when {
builtInCategory == null && existingEntry == null -> true
existingEntry != null && existingEntry.resolvedCategory() != chosenCategory -> true
builtInCategory != null && builtInCategory != chosenCategory -> true
builtInCategories == null && existingEntry == null -> true
existingEntry != null && existingEntry.resolvedCategories() != chosenCategories -> true
builtInCategories != null && builtInCategories != chosenCategories -> true
else -> false
}
if (shouldSave) {
repository.saveCustomFood(cleanName, item.unit, chosenCategory)
repository.saveCustomFood(cleanName, item.unit, chosenCategories)
}
}
}
@@ -297,15 +297,23 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
fun addCustomFoodDirectly(
name: String,
unit: FoodUnit,
category: FoodCategory? = null
categories: List<FoodCategory>
) {
val cleanName = name.trim()
if (cleanName.isEmpty()) return
viewModelScope.launch {
repository.saveCustomFood(cleanName, unit, category)
repository.saveCustomFood(cleanName, unit, categories)
}
}
fun addCustomFoodDirectly(
name: String,
unit: FoodUnit,
category: FoodCategory? = null
) {
addCustomFoodDirectly(name, unit, listOfNotNull(category))
}
fun addMeal(
mealType: MealType,
mealTimestamp: Long,
@@ -460,13 +468,11 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
_suggestionUiState.value = SuggestionUiState.Loading
val targetType = _selectedIdeaMealType.value
val currentMeals = repository.getAllMealsSnapshot()
val lookup = customFoods.value.associate {
it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory()
}
val lookup = CustomFoodEntry.buildCategoriesLookup(customFoods.value)
val gap = DailyBenchmarkAnalyzer.analyzeToday(
meals = currentMeals,
targetMealType = targetType,
customCategoryLookup = lookup
customCategoriesLookup = lookup
)
val currentPrefs = foodPreferences.value
val existingTitles = recipes.value.map { it.title }
@@ -727,7 +733,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
val lookup = customFoods.value.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, lookup)
val lookup = CustomFoodEntry.buildCategoriesLookup(customFoods.value)
return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, customCategoriesLookup = lookup)
}
}
@@ -70,26 +70,29 @@ private data class CategoryDaySummary(
@Composable
fun DailyBenchmarksCard(
todayMeals: List<MealEntry>,
customCategoryLookup: Map<String, FoodCategory>,
customCategoriesLookup: Map<String, List<FoodCategory>>,
onOpenGuideClick: () -> Unit,
modifier: Modifier = Modifier
) {
var expanded by remember { mutableStateOf(false) }
val isDark = isSatieaDarkTheme()
val summariesByCategory = remember(todayMeals, customCategoryLookup) {
val summariesByCategory = remember(todayMeals, customCategoriesLookup) {
val map = mutableMapOf<FoodCategory, CategoryDaySummary>()
todayMeals.forEach { meal ->
meal.parsedFoodItems().forEach { item ->
val cat = item.resolvedCategory(customCategoryLookup)
val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0)
val addG = if (item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0
val addP = if (item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0
map[cat] = current.copy(
count = current.count + 1,
totalGrams = current.totalGrams + addG,
totalPortions = current.totalPortions + addP
)
val cats = item.resolvedCategories(customCategoriesLookup)
val isComposite = cats.size > 1
val addG = if (!isComposite && item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0
val addP = if (!isComposite && item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0
cats.forEach { cat ->
val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0)
map[cat] = current.copy(
count = current.count + 1,
totalGrams = current.totalGrams + addG,
totalPortions = current.totalPortions + addP
)
}
}
}
map
@@ -1,6 +1,7 @@
package com.example.ui.meal
import android.net.Uri
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
@@ -25,6 +26,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
@@ -36,6 +38,7 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -53,6 +56,7 @@ import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.ui.common.UnsavedChangesDiscardDialog
import com.example.ui.journal.components.DietaryGuideSheet
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.ui.meal.components.MealDateTimePicker
@@ -87,32 +91,45 @@ fun MealEntrySheet(
initialMeal: MealEntry? = null,
defaultMealType: MealType = MealType.LUNCH,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onAddCustomFood: (String, FoodUnit, List<FoodCategory>) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit,
onSaveMeal: (MealType, Long, Int, Int, String, List<MealFoodItem>, List<String>) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val isEditingExisting = initialMeal != null && initialMeal.id.isNotBlank()
val isPrefilledNewMeal = initialMeal != null && initialMeal.id.isBlank()
var showDietaryGuide by remember { mutableStateOf(false) }
var showDiscardDialog by remember { mutableStateOf(false) }
var selectedType by rememberSaveable {
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
val initialType = remember(initialMeal?.id, defaultMealType) {
if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType
}
var mealTimestamp by rememberSaveable {
mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis())
val initialTimestamp = rememberSaveable(initialMeal?.id) {
initialMeal?.mealTimestamp ?: System.currentTimeMillis()
}
var hungerLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10))
val initialHunger = remember(initialMeal?.id) {
(initialMeal?.hungerBefore ?: 5).coerceIn(1, 10)
}
var satietyLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10))
val initialSatiety = remember(initialMeal?.id) {
(initialMeal?.satietyAfter ?: 7).coerceIn(1, 10)
}
var globalNoteText by rememberSaveable {
mutableStateOf(initialMeal?.note ?: "")
val initialNote = remember(initialMeal?.id) {
initialMeal?.note ?: ""
}
val initialFoodsSerialized = remember(initialMeal?.id) {
initialMeal?.parsedFoodItems()?.map { it.serialize() } ?: emptyList()
}
val initialPhotos = remember(initialMeal?.id) {
initialMeal?.displayPhotoUris ?: emptyList()
}
var selectedType by rememberSaveable { mutableStateOf(initialType) }
var mealTimestamp by rememberSaveable { mutableLongStateOf(initialTimestamp) }
var hungerLevel by rememberSaveable { mutableIntStateOf(initialHunger) }
var satietyLevel by rememberSaveable { mutableIntStateOf(initialSatiety) }
var globalNoteText by rememberSaveable { mutableStateOf(initialNote) }
// Preserved across rotation via custom ListSaver
val foodItemsList = rememberSaveable(saver = FoodItemListSaver) {
@@ -138,24 +155,54 @@ fun MealEntrySheet(
mutableStateListOf<String>()
}
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
// Current food builder input state
// Current food builder input state (supports multiple categories per dish)
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var selectedFoodCategoriesEncoded by rememberSaveable { mutableStateOf(FoodCategory.OTHER.code) }
val selectedFoodCategories = remember(selectedFoodCategoriesEncoded) {
FoodCategory.parseCategoryList(selectedFoodCategoriesEncoded).ifEmpty { listOf(FoodCategory.OTHER) }
}
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
val hasUnsavedChanges = isPrefilledNewMeal ||
selectedType != initialType ||
mealTimestamp != initialTimestamp ||
hungerLevel != initialHunger ||
satietyLevel != initialSatiety ||
globalNoteText.trim() != initialNote.trim() ||
foodItemsList.map { it.serialize() } != initialFoodsSerialized ||
photoUrisList.toList() != initialPhotos ||
foodNameInput.isNotBlank() ||
foodWeightInput.isNotBlank()
val currentHasUnsavedChanges by rememberUpdatedState(hasUnsavedChanges)
val sheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = true,
confirmValueChange = { targetValue ->
if (targetValue == SheetValue.Hidden && currentHasUnsavedChanges) {
showDiscardDialog = true
false
} else {
true
}
}
)
// Combine custom foods (user enriched) + built-in catalog
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
val cats = it.resolvedCategories()
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
category = cats.first(),
categories = cats
)
}
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
@@ -187,16 +234,17 @@ fun MealEntrySheet(
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && foodItemsList.size < 30) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
val resolvedCats = if (hasUserOverriddenCategory) {
selectedFoodCategories
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
FoodCategory.inferCategoriesFromName(cleanName, customCategoriesLookup)
}
val newItem = MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit,
category = resolvedCat
category = resolvedCats.firstOrNull(),
categories = resolvedCats
)
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIndex >= 0) {
@@ -205,12 +253,12 @@ fun MealEntrySheet(
foodItemsList.add(newItem)
}
if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCats)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
selectedFoodCategoriesEncoded = FoodCategory.OTHER.code
hasUserOverriddenCategory = false
}
}
@@ -233,19 +281,32 @@ fun MealEntrySheet(
}
}
val handleDismiss = {
val performDiscardAndDismiss = {
showDiscardDialog = false
newlyCapturedPhotos.forEach { photoUri ->
ImageUtils.deletePhotoFile(context, photoUri)
}
onDismiss()
}
val requestDismiss = {
if (hasUnsavedChanges) {
showDiscardDialog = true
} else {
performDiscardAndDismiss()
}
}
ModalBottomSheet(
onDismissRequest = handleDismiss,
onDismissRequest = requestDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
BackHandler(enabled = hasUnsavedChanges) {
showDiscardDialog = true
}
Column(
modifier = Modifier
.fillMaxWidth()
@@ -272,7 +333,7 @@ fun MealEntrySheet(
)
}
IconButton(
onClick = handleDismiss,
onClick = requestDismiss,
modifier = Modifier.testTag("dismiss_sheet_button")
) {
Icon(
@@ -328,7 +389,7 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(22.dp))
// Subcomponent 5: Color-coded Food items builder & flow-row chips
// Subcomponent 5: Color-coded Food items builder & multi-dot badges
FoodItemBuilderSection(
foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions,
@@ -336,24 +397,32 @@ fun MealEntrySheet(
onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
val inferred = if (input.isBlank()) {
listOf(FoodCategory.OTHER)
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
FoodCategory.inferCategoriesFromName(input, customCategoriesLookup)
}
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(inferred)
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
selectedFoodCategoriesEncoded = FoodCategory.OTHER.code
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { category ->
selectedFoodCategory = category
selectedFoodCategories = selectedFoodCategories,
onFoodCategoryToggled = { toggled ->
val updated = FoodCategory.toggleCategorySelection(selectedFoodCategories, toggled)
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(updated)
hasUserOverriddenCategory = true
},
onSuggestionSelected = { suggestion ->
foodNameInput = suggestion.name
selectedFoodUnit = suggestion.defaultUnit
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(suggestion.resolvedCategories())
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood,
@@ -364,13 +433,16 @@ fun MealEntrySheet(
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(
item.resolvedCategories(customCategoriesLookup)
)
hasUserOverriddenCategory = true
foodItemsList.remove(item)
},
onRemoveFoodItem = { item ->
foodItemsList.remove(item)
},
customCategoriesLookup = customCategoriesLookup,
onOpenGuideClick = { showDietaryGuide = true }
)
@@ -411,7 +483,7 @@ fun MealEntrySheet(
verticalAlignment = Alignment.CenterVertically
) {
TextButton(
onClick = handleDismiss,
onClick = requestDismiss,
modifier = Modifier.testTag("cancel_meal_button")
) {
Text("Annuler")
@@ -457,6 +529,15 @@ fun MealEntrySheet(
}
}
if (showDiscardDialog) {
UnsavedChangesDiscardDialog(
title = "Quitter sans enregistrer ?",
message = "Votre repas en cours n'est pas encore enregistré. Souhaitez-vous vraiment quitter sans sauvegarder ?",
onContinueEditing = { showDiscardDialog = false },
onConfirmDiscard = performDiscardAndDismiss
)
}
if (showDietaryGuide) {
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
}
@@ -46,7 +46,7 @@ import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.ui.common.FoodCategoryBadge
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.FoodCategoryColorDotsRow
import com.example.ui.common.FoodCategorySelectorRow
@OptIn(ExperimentalLayoutApi::class)
@@ -60,18 +60,24 @@ fun FoodItemBuilderSection(
onFoodWeightChange: (String) -> Unit,
selectedFoodUnit: FoodUnit,
onFoodUnitSelected: (FoodUnit) -> Unit,
selectedFoodCategory: FoodCategory,
onFoodCategorySelected: (FoodCategory) -> Unit,
selectedFoodCategories: List<FoodCategory>,
onFoodCategoryToggled: (FoodCategory) -> Unit,
onSuggestionSelected: (DefaultFoodCatalog.CatalogFood) -> Unit,
isNewCustomFood: Boolean,
onAddFoodItem: () -> Unit,
onItemClickForEdit: (MealFoodItem) -> Unit,
onRemoveFoodItem: (MealFoodItem) -> Unit,
customCategoriesLookup: Map<String, List<FoodCategory>> = emptyMap(),
sectionTitle: String = "3. Aliments & Poids (optionnel)",
addButtonLabelPrefix: String = "Ajouter à l'assiette",
addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleur) :",
addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleurs) :",
onOpenGuideClick: (() -> Unit)? = null,
modifier: Modifier = Modifier
) {
val activeCategories = FoodCategory.sanitizeSelection(selectedFoodCategories)
.ifEmpty { listOf(FoodCategory.OTHER) }
val activeConcreteCount = activeCategories.count { it != FoodCategory.OTHER }
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
@@ -138,14 +144,14 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment ou tapez-en un nouveau : sa couleur est détectée automatiquement et modifiable ci-dessous.",
text = "Sélectionnez un aliment ou un plat composé : vous pouvez associer plusieurs couleurs ci-dessous.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row with color dots
// Auto-complete / Quick suggestions row with single or multi color dots
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -153,13 +159,13 @@ fun FoodItemBuilderSection(
) {
items(matchingSuggestions, key = { it.name }) { suggestion ->
SuggestionChip(
onClick = {
onFoodNameChange(suggestion.name)
onFoodUnitSelected(suggestion.defaultUnit)
onFoodCategorySelected(suggestion.category)
},
onClick = { onSuggestionSelected(suggestion) },
icon = {
FoodCategoryColorDot(category = suggestion.category, size = 9.dp)
FoodCategoryColorDotsRow(
categories = suggestion.resolvedCategories(),
dotSize = 8.dp,
spacing = 2.dp
)
},
label = {
Text(
@@ -185,10 +191,15 @@ fun FoodItemBuilderSection(
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Comté...)")
Text("Nom de l'aliment ou plat (ex: Riz, Kebab, Comté...)")
},
leadingIcon = {
FoodCategoryColorDot(category = selectedFoodCategory, size = 11.dp)
FoodCategoryColorDotsRow(
categories = activeCategories.take(4),
dotSize = if (activeCategories.size > 2) 7.dp else 10.dp,
spacing = 2.dp,
modifier = Modifier.padding(start = 6.dp)
)
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
@@ -208,7 +219,11 @@ fun FoodItemBuilderSection(
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue",
text = if (activeConcreteCount > 1) {
"✨ « ${foodNameInput.trim()} » sera mémorisé avec ses $activeConcreteCount familles dans votre catalogue"
} else {
"✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue"
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
@@ -216,16 +231,54 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.height(10.dp))
// Food Category Color Selector
// Multi-select Food Category Color Selector
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Famille(s) / Code couleur :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Medium
)
if (activeConcreteCount > 1) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.primaryContainer,
modifier = Modifier.testTag("multi_category_count_badge")
) {
Text(
text = "$activeConcreteCount familles",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp)
)
}
}
}
Spacer(modifier = Modifier.height(2.dp))
Text(
text = "Famille / Code couleur :",
text = if (activeConcreteCount > 1) {
"Plat composé : ${activeCategories.joinToString(" · ") { it.shortLabel }}"
} else {
"Touchez plusieurs catégories pour un plat composé (ex. Kebab : Viande + Légumes + Pain)"
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
color = if (activeConcreteCount > 1) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
}
)
Spacer(modifier = Modifier.height(6.dp))
FoodCategorySelectorRow(
selectedCategory = selectedFoodCategory,
onCategorySelected = onFoodCategorySelected
selectedCategories = activeCategories,
onCategoryToggled = onFoodCategoryToggled
)
Spacer(modifier = Modifier.height(10.dp))
@@ -314,7 +367,7 @@ fun FoodItemBuilderSection(
)
}
// Added color-coded food items badges
// Added color-coded food items badges (single or multi-dot)
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
@@ -332,7 +385,7 @@ fun FoodItemBuilderSection(
foodItemsList.forEach { item ->
FoodCategoryBadge(
text = item.displayBadge(),
category = item.resolvedCategory(),
categories = item.resolvedCategories(customCategoriesLookup),
onClick = { onItemClickForEdit(item) },
onRemove = { onRemoveFoodItem(item) }
)
@@ -0,0 +1,229 @@
package com.example.ui.planning
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.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategorySelectorRow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InventoryItemEditorSheet(
initialItem: InventoryItem?,
onDismiss: () -> Unit,
onSave: (InventoryItem) -> Unit,
onDelete: ((String) -> Unit)? = null
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val isEditing = initialItem != null && initialItem.id.isNotBlank()
var name by remember(initialItem) { mutableStateOf(initialItem?.name.orEmpty()) }
var quantityText by remember(initialItem) {
mutableStateOf(
initialItem?.quantity?.let { qty ->
if (qty % 1.0 == 0.0) qty.toInt().toString() else qty.toString()
} ?: "1"
)
}
var selectedUnit by remember(initialItem) { mutableStateOf(initialItem?.unit ?: FoodUnit.G) }
var selectedCategory by remember(initialItem) {
mutableStateOf(initialItem?.category ?: FoodCategory.OTHER)
}
var hasManualCategory by remember(initialItem) { mutableStateOf(isEditing) }
var selectedLocation by remember(initialItem) {
mutableStateOf(initialItem?.location ?: StorageLocation.PANTRY)
}
val parsedQty = quantityText.replace(',', '.').toDoubleOrNull()
val canSave = name.isNotBlank() && parsedQty != null && parsedQty > 0.0
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.verticalScroll(rememberScrollState())
.padding(horizontal = 20.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Text(
text = if (isEditing) "Modifier l'article en stock" else "Ajouter au stock",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
OutlinedTextField(
value = name,
onValueChange = { updated ->
name = updated
if (!hasManualCategory && updated.isNotBlank()) {
selectedCategory = FoodCategory.inferFromName(updated)
}
},
label = { Text("Nom de l'aliment") },
placeholder = { Text("Ex. Blanc de poulet, Lait, Tomates...") },
singleLine = true,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("inventory_name_input")
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = quantityText,
onValueChange = { quantityText = it },
label = { Text("Quantité") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(1f)
.testTag("inventory_quantity_input")
)
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
FoodUnit.entries.forEach { unit ->
FilterChip(
selected = selectedUnit == unit,
onClick = { selectedUnit = unit },
label = { Text(unit.label) },
modifier = Modifier.testTag("inventory_unit_${unit.code}")
)
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Emplacement",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
StorageLocation.entries.forEach { loc ->
FilterChip(
selected = selectedLocation == loc,
onClick = { selectedLocation = loc },
label = { Text(loc.displayName) },
modifier = Modifier
.weight(1f)
.testTag("inventory_location_${loc.name.lowercase()}")
)
}
}
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Catégorie alimentaire",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
FoodCategorySelectorRow(
selectedCategory = selectedCategory,
onCategorySelected = { cat ->
selectedCategory = cat
hasManualCategory = true
}
)
}
Spacer(modifier = Modifier.height(4.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
if (isEditing && onDelete != null) {
OutlinedButton(
onClick = { onDelete(initialItem!!.id) },
shape = RoundedCornerShape(14.dp),
modifier = Modifier.testTag("delete_inventory_item_button")
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Supprimer"
)
Spacer(modifier = Modifier.width(6.dp))
Text("Supprimer")
}
}
Button(
onClick = {
val qty = parsedQty ?: return@Button
onSave(
InventoryItem(
id = initialItem?.id.orEmpty(),
name = name.trim(),
quantity = qty,
unit = selectedUnit,
category = selectedCategory,
location = selectedLocation
)
)
},
enabled = canSave,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(1f)
.testTag("save_inventory_item_button")
) {
Text(if (isEditing) "Enregistrer" else "Ajouter au stock")
}
}
Spacer(modifier = Modifier.height(12.dp))
}
}
}
@@ -0,0 +1,395 @@
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.Box
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategoryColorDot
import java.util.Locale
@Composable
fun InventoryTab(
inventoryItems: List<InventoryItem>,
onScanReceiptClick: () -> Unit,
onAddManualClick: () -> Unit,
onEditItem: (InventoryItem) -> Unit,
onAdjustQuantity: (itemId: String, delta: Double) -> Unit,
onDeleteItem: (itemId: String) -> Unit
) {
var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedLocationName by rememberSaveable { mutableStateOf<String?>(null) }
val selectedLocation = selectedLocationName?.let { StorageLocation.fromString(it) }
val countsByLocation = remember(inventoryItems) {
StorageLocation.entries.associateWith { loc ->
inventoryItems.count { it.location == loc }
}
}
val filteredItems = remember(inventoryItems, searchQuery, selectedLocation) {
val query = searchQuery.trim().lowercase(Locale.FRENCH)
inventoryItems.filter { item ->
val matchesLoc = selectedLocation == null || item.location == selectedLocation
val matchesQuery = query.isBlank() ||
item.name.lowercase(Locale.FRENCH).contains(query) ||
item.category.displayName.lowercase(Locale.FRENCH).contains(query)
matchesLoc && matchesQuery
}
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.testTag("inventory_tab_list"),
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 96.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
// Quick action banner: Scan Receipt + Add Item
item {
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f)
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.25f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Stock de la cuisine",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer
)
Text(
text = if (inventoryItems.isEmpty()) {
"Scannez un ticket de caisse ou ajoutez vos aliments"
} else {
"${inventoryItems.size} aliment${if (inventoryItems.size > 1) "s" else ""} disponible${if (inventoryItems.size > 1) "s" else ""}"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.85f)
)
}
Icon(
imageVector = Icons.Default.Kitchen,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(28.dp)
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Button(
onClick = onScanReceiptClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.weight(1f)
.testTag("scan_receipt_button")
) {
Icon(
imageVector = Icons.Default.DocumentScanner,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Scanner un ticket", maxLines = 1, overflow = TextOverflow.Ellipsis)
}
FilledTonalButton(
onClick = onAddManualClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.testTag("add_inventory_button")
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text("Ajouter")
}
}
}
}
}
// Search field
item {
OutlinedTextField(
value = searchQuery,
onValueChange = { searchQuery = it },
placeholder = { Text("Rechercher dans mon stock...") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
trailingIcon = {
if (searchQuery.isNotBlank()) {
IconButton(onClick = { searchQuery = "" }) {
Icon(Icons.Default.Close, contentDescription = "Effacer la recherche")
}
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("inventory_search_input")
)
}
// Location filter chips
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
item {
FilterChip(
selected = selectedLocation == null,
onClick = { selectedLocationName = null },
label = { Text("Tous (${inventoryItems.size})") },
modifier = Modifier.testTag("inventory_filter_all")
)
}
items(StorageLocation.entries) { loc ->
val count = countsByLocation[loc] ?: 0
FilterChip(
selected = selectedLocation == loc,
onClick = {
selectedLocationName = if (selectedLocation == loc) null else loc.name
},
label = { Text("${loc.displayName} ($count)") },
modifier = Modifier.testTag("inventory_filter_${loc.name.lowercase()}")
)
}
}
}
// Empty state
if (filteredItems.isEmpty()) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.Kitchen,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(36.dp)
)
Text(
text = if (inventoryItems.isEmpty()) {
"Votre stock est encore vide"
} else {
"Aucun article ne correspond à ce filtre"
},
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center
)
Text(
text = "Votre stock est automatiquement déduit de la liste de courses pour ne racheter que ce qui manque.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
}
} else {
items(filteredItems, key = { it.id }) { item ->
InventoryItemCard(
item = item,
onClick = { onEditItem(item) },
onStepChange = { delta -> onAdjustQuantity(item.id, delta) },
onDelete = { onDeleteItem(item.id) }
)
}
}
}
}
@Composable
private fun InventoryItemCard(
item: InventoryItem,
onClick: () -> Unit,
onStepChange: (Double) -> Unit,
onDelete: () -> Unit
) {
val step = when (item.unit) {
FoodUnit.G -> 50.0
FoodUnit.ML -> 100.0
FoodUnit.PORTION -> 1.0
}
Card(
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)),
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.testTag("inventory_card_${item.id}")
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = item.category, size = 11.dp)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = item.name,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(2.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.location.displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary
)
Text(
text = "•",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = item.category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { onStepChange(-step) },
modifier = Modifier.size(40.dp)
) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Diminuer la quantité de ${item.name}",
modifier = Modifier.size(18.dp)
)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.padding(horizontal = 4.dp)
) {
Text(
text = item.formatQuantity(),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
}
IconButton(
onClick = { onStepChange(step) },
modifier = Modifier.size(40.dp)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Augmenter la quantité de ${item.name}",
modifier = Modifier.size(18.dp)
)
}
IconButton(
onClick = onDelete,
modifier = Modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Default.DeleteOutline,
contentDescription = "Supprimer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp)
)
}
}
}
}
}
@@ -0,0 +1,528 @@
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.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.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.RestaurantMenu
import androidx.compose.material.icons.filled.Search
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.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
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.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
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.PlannedMealEntry
import com.example.data.model.RecipeEntry
import com.example.ui.meal.components.FoodItemBuilderSection
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
private enum class PlanMealMode(val label: String) {
RECIPE("Mes recettes"),
CUSTOM("Repas libre")
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlanMealSheet(
targetDate: LocalDate,
initialMealType: MealType,
initialEntry: PlannedMealEntry?,
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
onAddCustomFood: (String, FoodUnit, List<FoodCategory>) -> Unit,
onDismiss: () -> Unit,
onSave: (PlannedMealEntry) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val isEditing = initialEntry != null && initialEntry.id.isNotBlank()
var selectedMealType by remember(initialEntry, initialMealType) {
mutableStateOf(initialEntry?.mealType ?: initialMealType)
}
var mode by remember(initialEntry, recipes) {
mutableStateOf(
when {
initialEntry?.recipeId != null -> PlanMealMode.RECIPE
initialEntry != null -> PlanMealMode.CUSTOM
recipes.isNotEmpty() -> PlanMealMode.RECIPE
else -> PlanMealMode.CUSTOM
}
)
}
// Recipe mode state
var recipeSearch by remember { mutableStateOf("") }
var selectedRecipeId by remember(initialEntry) { mutableStateOf(initialEntry?.recipeId) }
var servings by remember(initialEntry) { mutableDoubleStateOf(initialEntry?.servings ?: 1.0) }
// Custom meal mode state
var customTitle by remember(initialEntry) { mutableStateOf(initialEntry?.customTitle.orEmpty()) }
val foodItemsList = remember(initialEntry) {
mutableStateListOf<MealFoodItem>().apply {
if (initialEntry != null && initialEntry.recipeId == null) {
addAll(initialEntry.parsedItems())
}
}
}
var foodNameInput by remember { mutableStateOf("") }
var foodWeightInput by remember { mutableStateOf("") }
var selectedFoodUnit by remember { mutableStateOf(FoodUnit.G) }
var selectedFoodCategories by remember { mutableStateOf(listOf(FoodCategory.OTHER)) }
var hasManualCategory by remember { mutableStateOf(false) }
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
val cats = it.resolvedCategories()
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = cats.first(),
categories = cats
)
}
val customLower = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
customMapped + DefaultFoodCatalog.builtInFoods.filter {
it.name.lowercase(Locale.FRENCH) !in customLower
}
}
val matchingSuggestions = remember(foodNameInput, mergedCatalog, foodItemsList.size) {
val addedNames = foodItemsList.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val query = foodNameInput.trim().lowercase(Locale.FRENCH)
if (query.isEmpty()) {
mergedCatalog.filter { it.name.lowercase(Locale.FRENCH) !in addedNames }.take(10)
} else {
mergedCatalog.filter {
it.name.lowercase(Locale.FRENCH).contains(query) &&
it.name.lowercase(Locale.FRENCH) !in addedNames
}.take(8)
}
}
val isNewCustomFood = remember(foodNameInput, mergedCatalog) {
val clean = foodNameInput.trim()
clean.length >= 2 && mergedCatalog.none { it.name.equals(clean, ignoreCase = true) }
}
val filteredRecipes = remember(recipes, recipeSearch) {
val q = recipeSearch.trim().lowercase(Locale.FRENCH)
if (q.isBlank()) {
recipes
} else {
recipes.filter { it.title.lowercase(Locale.FRENCH).contains(q) }
}
}
val dayFormatter = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) }
val dayLabel = remember(targetDate) {
targetDate.format(dayFormatter).replaceFirstChar { it.titlecase(Locale.FRENCH) }
}
val addCurrentFoodItem = {
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && foodItemsList.size < 25) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCats = if (hasManualCategory) {
selectedFoodCategories
} else {
FoodCategory.inferCategoriesFromName(cleanName, customCategoriesLookup)
}
foodItemsList.add(
MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit,
categories = resolvedCats
)
)
if (isNewCustomFood) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCats)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategories = listOf(FoodCategory.OTHER)
hasManualCategory = false
}
}
val canSave = when (mode) {
PlanMealMode.RECIPE -> !selectedRecipeId.isNullOrBlank()
PlanMealMode.CUSTOM -> customTitle.isNotBlank() || foodItemsList.isNotEmpty() || foodNameInput.isNotBlank()
}
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.verticalScroll(rememberScrollState())
.padding(horizontal = 20.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
Column {
Text(
text = if (isEditing) "Modifier le repas planifié" else "Planifier un repas",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = dayLabel,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.primary
)
}
// Meal type chips
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
MealType.entries.forEach { type ->
FilterChip(
selected = selectedMealType == type,
onClick = { selectedMealType = type },
label = {
Text(
text = when (type) {
MealType.BREAKFAST -> "Matin"
MealType.LUNCH -> "Midi"
MealType.SNACK -> "Goûter"
MealType.DINNER -> "Soir"
},
maxLines = 1
)
},
modifier = Modifier.weight(1f)
)
}
}
// Mode segmented toggle
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
PlanMealMode.entries.forEachIndexed { index, planMode ->
SegmentedButton(
selected = mode == planMode,
onClick = { mode = planMode },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = PlanMealMode.entries.size
),
icon = {
Icon(
imageVector = if (planMode == PlanMealMode.RECIPE) {
Icons.AutoMirrored.Filled.MenuBook
} else {
Icons.Default.RestaurantMenu
},
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
modifier = Modifier.testTag("plan_mode_${planMode.name.lowercase()}")
) {
Text(planMode.label)
}
}
}
if (mode == PlanMealMode.RECIPE) {
if (recipes.isEmpty()) {
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "Vous n'avez pas encore de recettes enregistrées. Utilisez « Repas libre » ou créez une recette dans l'onglet Recettes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(14.dp)
)
}
} else {
OutlinedTextField(
value = recipeSearch,
onValueChange = { recipeSearch = it },
placeholder = { Text("Rechercher une recette...") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
singleLine = true,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.fillMaxWidth()
)
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 220.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
filteredRecipes.forEach { recipe ->
val isSelected = selectedRecipeId == recipe.id
Card(
shape = RoundedCornerShape(14.dp),
colors = CardDefaults.cardColors(
containerColor = if (isSelected) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f)
} else {
MaterialTheme.colorScheme.surface
}
),
border = BorderStroke(
width = if (isSelected) 1.5.dp else 1.dp,
color = if (isSelected) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
}
),
modifier = Modifier
.fillMaxWidth()
.clickable {
selectedRecipeId = recipe.id
servings = recipe.servings.coerceAtLeast(1).toDouble()
}
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = recipe.title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = "${recipe.parsedIngredients().size} ingrédients • ${recipe.servings} part${if (recipe.servings > 1) "s" else ""} de base",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (isSelected) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = "Sélectionné",
tint = MaterialTheme.colorScheme.primary
)
}
}
}
}
}
if (!selectedRecipeId.isNullOrBlank()) {
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 = "Nombre de portions prévues",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium
)
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { servings = (servings - 0.5).coerceAtLeast(0.5) }
) {
Icon(Icons.Default.Remove, contentDescription = "Diminuer les portions")
}
val formatted = if (servings % 1.0 == 0.0) {
servings.toInt().toString()
} else {
servings.toString()
}
Text(
text = formatted,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 6.dp)
)
IconButton(
onClick = { servings = (servings + 0.5).coerceAtMost(20.0) }
) {
Icon(Icons.Default.Add, contentDescription = "Augmenter les portions")
}
}
}
}
}
}
} else {
OutlinedTextField(
value = customTitle,
onValueChange = { customTitle = it },
label = { Text("Nom du repas (optionnel)") },
placeholder = { Text("Ex. Bowl saumon avocat, Salade composée...") },
singleLine = true,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("plan_custom_title_input")
)
FoodItemBuilderSection(
foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { input ->
foodNameInput = input
if (!hasManualCategory && input.isNotBlank()) {
selectedFoodCategories = FoodCategory.inferCategoriesFromName(input, customCategoriesLookup)
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategories = selectedFoodCategories,
onFoodCategoryToggled = { cat ->
selectedFoodCategories = FoodCategory.toggleCategorySelection(selectedFoodCategories, cat)
hasManualCategory = true
},
onSuggestionSelected = { suggestion ->
foodNameInput = suggestion.name
selectedFoodUnit = suggestion.defaultUnit
selectedFoodCategories = suggestion.resolvedCategories()
hasManualCategory = true
},
isNewCustomFood = isNewCustomFood,
onAddFoodItem = addCurrentFoodItem,
onItemClickForEdit = { item ->
foodItemsList.remove(item)
foodNameInput = item.name
foodWeightInput = item.weight?.let { w ->
if (w % 1.0 == 0.0) w.toInt().toString() else w.toString()
}.orEmpty()
selectedFoodUnit = item.unit
selectedFoodCategories = item.resolvedCategories(customCategoriesLookup)
hasManualCategory = true
},
onRemoveFoodItem = { foodItemsList.remove(it) },
customCategoriesLookup = customCategoriesLookup,
sectionTitle = "Aliments prévus (pour le calcul des courses)",
addButtonLabelPrefix = "Ajouter au repas",
addedListCaption = "Aliments prévus :"
)
}
Spacer(modifier = Modifier.height(4.dp))
Button(
onClick = {
if (mode == PlanMealMode.CUSTOM && foodNameInput.isNotBlank()) {
addCurrentFoodItem()
}
val entry = if (mode == PlanMealMode.RECIPE) {
val recipe = recipes.firstOrNull { it.id == selectedRecipeId }
PlannedMealEntry(
id = initialEntry?.id.orEmpty(),
dateEpochDay = targetDate.toEpochDay(),
mealType = selectedMealType,
recipeId = selectedRecipeId,
customTitle = recipe?.title.orEmpty(),
servings = servings,
itemsSerialized = emptyList(),
isConsumed = initialEntry?.isConsumed ?: false
)
} else {
PlannedMealEntry(
id = initialEntry?.id.orEmpty(),
dateEpochDay = targetDate.toEpochDay(),
mealType = selectedMealType,
recipeId = null,
customTitle = customTitle.trim(),
servings = 1.0,
itemsSerialized = foodItemsList.map { it.serialize() },
isConsumed = initialEntry?.isConsumed ?: false
)
}
onSave(entry)
},
enabled = canSave,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("save_planned_meal_button")
) {
Text(if (isEditing) "Enregistrer les modifications" else "Ajouter au planning")
}
Spacer(modifier = Modifier.height(12.dp))
}
}
}
@@ -0,0 +1,566 @@
package com.example.ui.planning
import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.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.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
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.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.util.ImageUtils
import java.time.LocalDate
enum class PlanningSubTab(val label: String) {
WEEK("Semaine"),
STOCK("Stock"),
SHOPPING("Courses")
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PlanningScreen(
weekStartDate: LocalDate,
plannedMeals: List<PlannedMealEntry>,
inventoryItems: List<InventoryItem>,
shoppingItems: List<ShoppingListItem>,
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
receiptScanState: ReceiptScanUiState,
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
onSavePlannedMeal: (PlannedMealEntry) -> Unit,
onDeletePlannedMeal: (String) -> Unit,
onMarkPlannedMealAsEaten: (PlannedMealEntry) -> Unit,
onAddCustomFood: (String, FoodUnit, List<FoodCategory>) -> Unit,
onSaveInventoryItem: (InventoryItem) -> Unit,
onAdjustInventoryQuantity: (itemId: String, delta: Double) -> Unit,
onDeleteInventoryItem: (itemId: String) -> Unit,
onAddManualShoppingItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit,
onToggleShoppingItemChecked: (ShoppingListItem, Boolean) -> Unit,
onAddShoppingItemToStock: (ShoppingListItem, Double, FoodUnit, StorageLocation) -> Unit,
onDeleteManualShoppingItem: (String) -> Unit,
onClearCheckedShoppingItems: () -> Unit,
onScanReceiptUri: (Uri) -> Unit,
onUpdateScannedItem: (ScannedReceiptItem) -> Unit,
onRemoveScannedItem: (String) -> Unit,
onAddBlankScannedItem: () -> Unit,
onConfirmReceiptImport: (List<ScannedReceiptItem>, Boolean) -> Unit,
onDismissReceiptScan: () -> Unit,
onShowMessage: (String) -> Unit
) {
val context = LocalContext.current
var activeSubTab by rememberSaveable { mutableStateOf(PlanningSubTab.WEEK) }
// Sheet & Dialog states
var planTargetDate by remember { mutableStateOf<LocalDate?>(null) }
var planTargetMealType by remember { mutableStateOf(MealType.LUNCH) }
var editingPlannedMeal by remember { mutableStateOf<PlannedMealEntry?>(null) }
var showInventoryEditor by remember { mutableStateOf(false) }
var editingInventoryItem by remember { mutableStateOf<InventoryItem?>(null) }
var showReceiptSourceDialog by remember { mutableStateOf(false) }
var pendingCaptureUri by remember { mutableStateOf<Uri?>(null) }
var shoppingItemForStockPrompt by remember { mutableStateOf<ShoppingListItem?>(null) }
val recipesById = remember(recipes) { recipes.associateBy { it.id } }
// Zero-permission Photo Picker for Gallery receipt image
val pickReceiptLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri ->
if (uri != null) {
onScanReceiptUri(uri)
}
}
// Camera capture via FileProvider URI
val takeReceiptPhotoLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture()
) { success ->
val captured = pendingCaptureUri
pendingCaptureUri = null
if (success && captured != null) {
onScanReceiptUri(captured)
}
}
val launchCameraCapture = {
try {
val uri = ImageUtils.createReceiptCaptureUri(context)
pendingCaptureUri = uri
takeReceiptPhotoLauncher.launch(uri)
} catch (_: Exception) {
onShowMessage("Impossible d'ouvrir l'appareil photo")
}
}
val cameraPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
launchCameraCapture()
} else {
onShowMessage("Autorisation caméra refusée — vous pouvez choisir une photo depuis la galerie")
}
}
val triggerCameraReceiptScan = {
val hasCameraPerm = ContextCompat.checkSelfPermission(
context,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
if (hasCameraPerm) {
launchCameraCapture()
} else {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
val triggerGalleryReceiptScan = {
pickReceiptLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
val uncheckedShoppingCount = shoppingItems.count { !it.isChecked }
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.testTag("planning_screen")
) {
Column(modifier = Modifier.fillMaxSize()) {
// Header + 3-segment switcher
Column(
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp, top = 16.dp, bottom = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column {
Text(
text = when (activeSubTab) {
PlanningSubTab.WEEK -> "Planning de la semaine"
PlanningSubTab.STOCK -> "Mon Stock Cuisine"
PlanningSubTab.SHOPPING -> "Liste de Courses"
},
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = when (activeSubTab) {
PlanningSubTab.WEEK -> "Organisez vos repas et marquez-les consommés en 1 clic"
PlanningSubTab.STOCK -> "Suivez vos ingrédients disponibles et scannez vos tickets"
PlanningSubTab.SHOPPING -> "Vos besoins de la semaine ajustés selon votre stock"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
SingleChoiceSegmentedButtonRow(
modifier = Modifier
.fillMaxWidth()
.testTag("planning_subtab_row")
) {
PlanningSubTab.entries.forEachIndexed { index, subTab ->
val badgeSuffix = when (subTab) {
PlanningSubTab.WEEK -> ""
PlanningSubTab.STOCK -> if (inventoryItems.isNotEmpty()) " (${inventoryItems.size})" else ""
PlanningSubTab.SHOPPING -> if (uncheckedShoppingCount > 0) " ($uncheckedShoppingCount)" else ""
}
SegmentedButton(
selected = activeSubTab == subTab,
onClick = { activeSubTab = subTab },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = PlanningSubTab.entries.size
),
icon = {
Icon(
imageVector = when (subTab) {
PlanningSubTab.WEEK -> Icons.Default.CalendarMonth
PlanningSubTab.STOCK -> Icons.Default.Kitchen
PlanningSubTab.SHOPPING -> Icons.Default.ShoppingCart
},
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
modifier = Modifier.testTag("planning_subtab_${subTab.name.lowercase()}")
) {
Text(
text = "${subTab.label}$badgeSuffix",
maxLines = 1
)
}
}
}
}
// Active sub-tab content
Box(modifier = Modifier.weight(1f)) {
when (activeSubTab) {
PlanningSubTab.WEEK -> {
WeeklyPlanTab(
weekStartDate = weekStartDate,
plannedMeals = plannedMeals,
recipesById = recipesById,
customFoods = customFoods,
onPreviousWeek = onPreviousWeek,
onNextWeek = onNextWeek,
onGoToCurrentWeek = onGoToCurrentWeek,
onPlanMealClick = { date, mealType ->
editingPlannedMeal = null
planTargetDate = date
planTargetMealType = mealType
},
onEditPlannedMeal = { entry ->
editingPlannedMeal = entry
planTargetDate = LocalDate.ofEpochDay(entry.dateEpochDay)
planTargetMealType = entry.mealType
},
onDeletePlannedMeal = onDeletePlannedMeal,
onMarkAsEaten = onMarkPlannedMealAsEaten
)
}
PlanningSubTab.STOCK -> {
InventoryTab(
inventoryItems = inventoryItems,
onScanReceiptClick = { showReceiptSourceDialog = true },
onAddManualClick = {
editingInventoryItem = null
showInventoryEditor = true
},
onEditItem = { item ->
editingInventoryItem = item
showInventoryEditor = true
},
onAdjustQuantity = onAdjustInventoryQuantity,
onDeleteItem = onDeleteInventoryItem
)
}
PlanningSubTab.SHOPPING -> {
ShoppingListTab(
shoppingItems = shoppingItems,
onAddManualItem = onAddManualShoppingItem,
onToggleItemChecked = { item, nowChecked ->
if (nowChecked) {
shoppingItemForStockPrompt = item
} else {
onToggleShoppingItemChecked(item, false)
}
},
onDeleteManualItem = onDeleteManualShoppingItem,
onClearChecked = onClearCheckedShoppingItems,
onScanReceiptClick = { showReceiptSourceDialog = true }
)
}
}
}
}
}
// Plan Meal Sheet
val activePlanDate = planTargetDate
if (activePlanDate != null) {
PlanMealSheet(
targetDate = activePlanDate,
initialMealType = planTargetMealType,
initialEntry = editingPlannedMeal,
recipes = recipes,
customFoods = customFoods,
onAddCustomFood = onAddCustomFood,
onDismiss = {
planTargetDate = null
editingPlannedMeal = null
},
onSave = { entry ->
planTargetDate = null
editingPlannedMeal = null
onSavePlannedMeal(entry)
}
)
}
// Inventory Item Editor Sheet
if (showInventoryEditor) {
InventoryItemEditorSheet(
initialItem = editingInventoryItem,
onDismiss = {
showInventoryEditor = false
editingInventoryItem = null
},
onSave = { item ->
showInventoryEditor = false
editingInventoryItem = null
onSaveInventoryItem(item)
},
onDelete = { id ->
showInventoryEditor = false
editingInventoryItem = null
onDeleteInventoryItem(id)
}
)
}
// Receipt Source Chooser Dialog (Camera vs Gallery)
if (showReceiptSourceDialog) {
AlertDialog(
onDismissRequest = { showReceiptSourceDialog = false },
modifier = Modifier.testTag("receipt_source_dialog"),
title = {
Text(
text = "Scanner un ticket de caisse",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
text = "Prenez votre ticket bien à plat et éclairé. Seuls les aliments seront extraits et proposés à la vérification avant ajout au stock.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(4.dp))
Button(
onClick = {
showReceiptSourceDialog = false
triggerCameraReceiptScan()
},
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("receipt_source_camera_button")
) {
Icon(Icons.Default.CameraAlt, contentDescription = null)
Spacer(modifier = Modifier.width(8.dp))
Text("Prendre une photo")
}
OutlinedButton(
onClick = {
showReceiptSourceDialog = false
triggerGalleryReceiptScan()
},
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("receipt_source_gallery_button")
) {
Icon(Icons.Default.PhotoLibrary, contentDescription = null)
Spacer(modifier = Modifier.width(8.dp))
Text("Choisir depuis la galerie")
}
}
},
confirmButton = {},
dismissButton = {
TextButton(onClick = { showReceiptSourceDialog = false }) {
Text("Annuler")
}
}
)
}
// Receipt Review Sheet (Scanning / Error / Preview)
ReceiptReviewSheet(
scanState = receiptScanState,
onUpdateItem = onUpdateScannedItem,
onRemoveItem = onRemoveScannedItem,
onAddBlankItem = onAddBlankScannedItem,
onConfirmImport = onConfirmReceiptImport,
onRetryScan = {
onDismissReceiptScan()
showReceiptSourceDialog = true
},
onDismiss = onDismissReceiptScan
)
// Shopping Check -> Add to Stock Prompt Dialog
val promptItem = shoppingItemForStockPrompt
if (promptItem != null) {
AddPurchasedItemToStockDialog(
item = promptItem,
onDismiss = { shoppingItemForStockPrompt = null },
onCheckOnly = {
onToggleShoppingItemChecked(promptItem, true)
shoppingItemForStockPrompt = null
},
onAddToStock = { qty, unit, location ->
onAddShoppingItemToStock(promptItem, qty, unit, location)
shoppingItemForStockPrompt = null
}
)
}
}
@Composable
private fun AddPurchasedItemToStockDialog(
item: ShoppingListItem,
onDismiss: () -> Unit,
onCheckOnly: () -> Unit,
onAddToStock: (quantity: Double, unit: FoodUnit, location: StorageLocation) -> Unit
) {
val defaultQty = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0
var qtyText by remember(item.key) {
mutableStateOf(
if (defaultQty % 1.0 == 0.0) defaultQty.toInt().toString() else defaultQty.toString()
)
}
var selectedUnit by remember(item.key) { mutableStateOf(item.unit) }
var selectedLocation by remember(item.key) {
mutableStateOf(suggestStorageLocation(item.category))
}
val parsedQty = qtyText.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0.0 }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.testTag("add_purchased_to_stock_dialog"),
title = {
Text(
text = "Ajouter « ${item.name} » au stock ?",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
},
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text(
text = "Vous venez de cocher cet article. Voulez-vous l'ajouter directement dans votre stock cuisine ?",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
OutlinedTextField(
value = qtyText,
onValueChange = { qtyText = it },
label = { Text("Quantité") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
)
FoodUnit.entries.forEach { unit ->
FilterChip(
selected = selectedUnit == unit,
onClick = { selectedUnit = unit },
label = { Text(unit.label) }
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
StorageLocation.entries.forEach { loc ->
FilterChip(
selected = selectedLocation == loc,
onClick = { selectedLocation = loc },
label = { Text(loc.displayName) },
modifier = Modifier.weight(1f)
)
}
}
}
},
confirmButton = {
Button(
onClick = {
onAddToStock(parsedQty ?: 1.0, selectedUnit, selectedLocation)
},
enabled = parsedQty != null,
modifier = Modifier.testTag("confirm_add_purchased_to_stock")
) {
Text("Ajouter au stock")
}
},
dismissButton = {
TextButton(
onClick = onCheckOnly,
modifier = Modifier.testTag("check_only_shopping_item")
) {
Text("Cocher seulement")
}
}
)
}
private fun suggestStorageLocation(category: FoodCategory): StorageLocation {
return when (category) {
FoodCategory.PROTEIN,
FoodCategory.DAIRY,
FoodCategory.CHEESE,
FoodCategory.VEGETABLE -> StorageLocation.FRIDGE
else -> StorageLocation.PANTRY
}
}
@@ -0,0 +1,485 @@
package com.example.ui.planning
import android.app.Application
import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
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.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.repository.MealRepository
import com.example.domain.IngredientMatcher
import com.example.domain.ReceiptScannerAnalyzer
import com.example.domain.ShoppingListCalculator
import com.example.ui.common.UiEvent
import com.example.util.ImageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
import java.util.UUID
@OptIn(ExperimentalCoroutinesApi::class)
class PlanningViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
private val _weekStartDate = MutableStateFlow(currentMonday())
val weekStartDate: StateFlow<LocalDate> = _weekStartDate.asStateFlow()
val weekPlannedMeals: StateFlow<List<PlannedMealEntry>> = _weekStartDate
.flatMapLatest { startDate ->
val startEpoch = startDate.toEpochDay()
val endEpoch = startDate.plusDays(6).toEpochDay()
repository.observePlannedMealsForWeek(startEpoch, endEpoch)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
val inventoryItems: StateFlow<List<InventoryItem>> = repository.observeInventory()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
val manualShoppingItems: StateFlow<List<ManualShoppingItem>> = repository.observeManualShoppingItems()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
private val recipesFlow: Flow<List<RecipeEntry>> = repository.observeRecipes()
private val customFoodsFlow: Flow<List<CustomFoodEntry>> = repository.observeCustomFoods()
private val _checkedPlanKeys = MutableStateFlow<Set<String>>(emptySet())
private data class ShoppingInputs(
val planned: List<PlannedMealEntry>,
val recipes: List<RecipeEntry>,
val inventory: List<InventoryItem>,
val manual: List<ManualShoppingItem>,
val checkedKeys: Set<String>
)
val computedShoppingList: StateFlow<List<ShoppingListItem>> = combine(
combine(
weekPlannedMeals,
recipesFlow,
inventoryItems,
manualShoppingItems,
_checkedPlanKeys
) { planned, recipes, inventory, manual, checkedKeys ->
ShoppingInputs(planned, recipes, inventory, manual, checkedKeys)
},
customFoodsFlow
) { inputs, customFoods ->
val recipesById = inputs.recipes.associateBy { it.id }
val customLookup = CustomFoodEntry.buildCategoriesLookup(customFoods)
ShoppingListCalculator.computeShoppingList(
plannedMeals = inputs.planned,
recipesById = recipesById,
inventory = inputs.inventory,
manualItems = inputs.manual,
checkedPlanKeys = inputs.checkedKeys,
customCategoriesLookup = customLookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
private val _receiptScanState = MutableStateFlow<ReceiptScanUiState>(ReceiptScanUiState.Idle)
val receiptScanState: StateFlow<ReceiptScanUiState> = _receiptScanState.asStateFlow()
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
// ------------------------------------------------------------------------
// Week Navigation
// ------------------------------------------------------------------------
fun previousWeek() {
_weekStartDate.update { it.minusWeeks(1) }
}
fun nextWeek() {
_weekStartDate.update { it.plusWeeks(1) }
}
fun goToCurrentWeek() {
_weekStartDate.value = currentMonday()
}
// ------------------------------------------------------------------------
// Weekly Meal Planning
// ------------------------------------------------------------------------
fun savePlannedMeal(entry: PlannedMealEntry) {
viewModelScope.launch {
repository.upsertPlannedMeal(entry).fold(
onSuccess = {
val label = if (entry.id.isBlank()) "Repas ajouté au planning" else "Repas planifié mis à jour"
emitSnackbar(label)
},
onFailure = {
emitSnackbar("Impossible d'enregistrer le repas planifié")
}
)
}
}
fun deletePlannedMeal(id: String) {
viewModelScope.launch {
repository.deletePlannedMeal(id)
emitSnackbar("Repas retiré du planning")
}
}
fun togglePlannedMealConsumed(id: String, consumed: Boolean) {
viewModelScope.launch {
repository.markPlannedMealConsumed(id, consumed)
}
}
/**
* Marks an optional planned meal as consumed and computes stock deduction proposals
* for the eaten foods that match current inventory items.
*/
fun onMealLoggedCheckStock(
eatenItems: List<MealFoodItem>,
plannedMealId: String? = null
) {
viewModelScope.launch {
if (!plannedMealId.isNullOrBlank()) {
repository.markPlannedMealConsumed(plannedMealId, consumed = true)
}
val currentStock = repository.getInventorySnapshot()
val proposals = ShoppingListCalculator.computeStockDeductionProposals(
eatenItems = eatenItems,
inventory = currentStock
)
if (proposals.isNotEmpty()) {
_pendingStockDeductions.value = proposals
}
}
}
fun confirmStockDeductions(selectedProposals: List<StockDeductionProposal>) {
viewModelScope.launch {
val active = selectedProposals.filter { it.selected && it.deductAmount > 0.0 }
active.forEach { proposal ->
repository.adjustInventoryQuantity(
itemId = proposal.inventoryItem.id,
delta = -proposal.deductAmount
)
}
_pendingStockDeductions.value = null
if (active.isNotEmpty()) {
emitSnackbar(
"Stock mis à jour (${active.size} article${if (active.size > 1) "s" else ""} déduit${if (active.size > 1) "s" else ""})"
)
}
}
}
fun dismissStockDeductions() {
_pendingStockDeductions.value = null
}
// ------------------------------------------------------------------------
// Kitchen Inventory (Stock)
// ------------------------------------------------------------------------
fun saveInventoryItem(item: InventoryItem) {
viewModelScope.launch {
val result = if (item.id.isBlank()) {
repository.addOrMergeInventoryItem(
name = item.name,
quantityToAdd = item.quantity,
unit = item.unit,
category = item.category,
location = item.location
)
} else {
repository.upsertInventoryItem(item)
}
result.fold(
onSuccess = {
val message = if (item.id.isBlank()) {
"${item.name.trim()} ajouté au stock"
} else {
"${item.name.trim()} mis à jour"
}
emitSnackbar(message)
},
onFailure = {
emitSnackbar("Veuillez renseigner un nom et une quantité valide")
}
)
}
}
fun adjustInventoryQuantity(itemId: String, delta: Double) {
viewModelScope.launch {
repository.adjustInventoryQuantity(itemId, delta)
}
}
fun deleteInventoryItem(itemId: String) {
viewModelScope.launch {
repository.deleteInventoryItem(itemId)
emitSnackbar("Article retiré du stock")
}
}
// ------------------------------------------------------------------------
// Shopping List (Courses)
// ------------------------------------------------------------------------
fun addManualShoppingItem(
name: String,
quantity: Double?,
unit: FoodUnit,
category: FoodCategory
) {
val cleanName = name.trim()
if (cleanName.isBlank()) return
viewModelScope.launch {
repository.upsertManualShoppingItem(
ManualShoppingItem(
name = cleanName,
quantity = quantity?.takeIf { it > 0.0 },
unit = unit,
category = category,
isChecked = false
)
).fold(
onSuccess = { emitSnackbar("$cleanName ajouté à la liste de courses") },
onFailure = { emitSnackbar("Impossible d'ajouter cet article") }
)
}
}
fun toggleShoppingItemChecked(item: ShoppingListItem, checked: Boolean) {
viewModelScope.launch {
if (item.manualItemId != null) {
repository.setManualShoppingItemChecked(item.manualItemId, checked)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { current ->
if (checked) current + item.key else current - item.key
}
}
}
}
fun addShoppingItemToStock(
item: ShoppingListItem,
quantity: Double,
unit: FoodUnit,
location: StorageLocation
) {
viewModelScope.launch {
val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0
repository.addOrMergeInventoryItem(
name = item.name,
quantityToAdd = safeQty,
unit = unit,
category = item.category,
location = location
).fold(
onSuccess = {
if (item.manualItemId != null) {
repository.setManualShoppingItemChecked(item.manualItemId, true)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { it - item.key }
}
emitSnackbar("${item.name} ajouté au stock (${IngredientMatcher.formatQuantity(safeQty, unit)})")
},
onFailure = {
emitSnackbar("Impossible d'ajouter ${item.name} au stock")
}
)
}
}
fun deleteManualShoppingItem(manualItemId: String) {
viewModelScope.launch {
repository.deleteManualShoppingItem(manualItemId)
}
}
fun clearCheckedShoppingItems() {
viewModelScope.launch {
repository.clearCheckedManualShoppingItems()
_checkedPlanKeys.value = emptySet()
emitSnackbar("Articles cochés nettoyés")
}
}
// ------------------------------------------------------------------------
// Receipt Scanning (Firebase AI Logic Multimodal)
// ------------------------------------------------------------------------
fun scanReceiptFromUri(uri: Uri) {
viewModelScope.launch {
_receiptScanState.value = ReceiptScanUiState.Scanning
val bitmap = ImageUtils.loadResizedBitmapForAi(getApplication(), uri, maxDimension = 1440)
if (bitmap == null) {
_receiptScanState.value = ReceiptScanUiState.Error(
"Impossible de lire cette image. Essayez de reprendre la photo du ticket."
)
return@launch
}
try {
val result = receiptAnalyzer.analyzeReceipt(bitmap)
result.fold(
onSuccess = { items ->
_receiptScanState.value = ReceiptScanUiState.Preview(items)
},
onFailure = { error ->
_receiptScanState.value = ReceiptScanUiState.Error(
error.message ?: "Impossible d'analyser ce ticket pour le moment."
)
}
)
} finally {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
}
}
fun updateScannedItem(updated: ScannedReceiptItem) {
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(
items = state.items.map { if (it.id == updated.id) updated else it }
)
} else {
state
}
}
}
fun removeScannedItem(itemId: String) {
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(items = state.items.filterNot { it.id == itemId })
} else {
state
}
}
}
fun addBlankScannedItem() {
val newItem = ScannedReceiptItem(
id = "manual_${UUID.randomUUID().toString().take(6)}",
rawLabel = "Ajout manuel",
name = "",
quantity = 1.0,
unit = FoodUnit.PORTION,
category = FoodCategory.OTHER,
location = StorageLocation.PANTRY,
selected = true
)
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(items = state.items + newItem)
} else {
state
}
}
}
fun confirmScannedReceiptImport(
items: List<ScannedReceiptItem>,
alsoCheckShoppingList: Boolean
) {
viewModelScope.launch {
val selectedValid = items.filter { it.selected && it.name.isNotBlank() && it.quantity > 0.0 }
if (selectedValid.isEmpty()) {
emitSnackbar("Sélectionnez au moins un article valide à ajouter")
return@launch
}
selectedValid.forEach { scanned ->
repository.addOrMergeInventoryItem(
name = scanned.name.trim(),
quantityToAdd = scanned.quantity,
unit = scanned.unit,
category = scanned.category,
location = scanned.location
)
}
if (alsoCheckShoppingList) {
val scannedNorms = selectedValid.map { IngredientMatcher.normalize(it.name) }.toSet()
val manualItems = repository.getManualShoppingItemsSnapshot()
manualItems.forEach { manual ->
val manualNorm = IngredientMatcher.normalize(manual.name)
if (!manual.isChecked && scannedNorms.any { IngredientMatcher.matches(it, manualNorm) }) {
repository.setManualShoppingItemChecked(manual.id, true)
}
}
}
_receiptScanState.value = ReceiptScanUiState.Idle
emitSnackbar(
"${selectedValid.size} article${if (selectedValid.size > 1) "s" else ""} ajouté${if (selectedValid.size > 1) "s" else ""} au stock"
)
}
}
fun dismissReceiptScan() {
_receiptScanState.value = ReceiptScanUiState.Idle
}
private fun emitSnackbar(message: String) {
_uiEvents.trySend(UiEvent.ShowSnackbar(message))
}
companion object {
fun currentMonday(): LocalDate {
return LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
}
}
}
@@ -0,0 +1,407 @@
package com.example.ui.planning
import androidx.compose.foundation.BorderStroke
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.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.ReceiptLong
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.FilterChip
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.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.input.KeyboardType
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.FoodUnit
import com.example.data.model.ReceiptScanUiState
import com.example.data.model.ScannedReceiptItem
import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategorySelectorRow
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReceiptReviewSheet(
scanState: ReceiptScanUiState,
onUpdateItem: (ScannedReceiptItem) -> Unit,
onRemoveItem: (String) -> Unit,
onAddBlankItem: () -> Unit,
onConfirmImport: (items: List<ScannedReceiptItem>, alsoCheckShoppingList: Boolean) -> Unit,
onRetryScan: () -> Unit,
onDismiss: () -> Unit
) {
if (scanState is ReceiptScanUiState.Idle) return
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var alsoCheckShoppingList by remember { mutableStateOf(true) }
ModalBottomSheet(
onDismissRequest = {
if (scanState !is ReceiptScanUiState.Scanning) {
onDismiss()
}
},
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.padding(horizontal = 20.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
when (scanState) {
ReceiptScanUiState.Idle -> Unit
ReceiptScanUiState.Scanning -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 32.dp)
.testTag("receipt_scanning_indicator"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
CircularProgressIndicator()
Text(
text = "Lecture de votre ticket en cours...",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Text(
text = "Identification des aliments, quantités, catégories et emplacements de conservation.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
is ReceiptScanUiState.Error -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 20.dp)
.testTag("receipt_scan_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 = "Analyse impossible",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
text = scanState.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
modifier = Modifier.weight(1f)
) {
Text("Fermer")
}
Button(
onClick = onRetryScan,
modifier = Modifier.weight(1f)
) {
Text("Réessayer")
}
}
}
}
is ReceiptScanUiState.Preview -> {
val selectedValidCount = scanState.items.count {
it.selected && it.name.isNotBlank() && it.quantity > 0.0
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
Icon(
imageVector = Icons.Default.ReceiptLong,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = "Vérification du ticket",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "${scanState.items.size} aliment${if (scanState.items.size > 1) "s" else ""} détecté${if (scanState.items.size > 1) "s" else ""} • modifiez avant ajout",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
TextButton(
onClick = onAddBlankItem,
modifier = Modifier.testTag("add_blank_receipt_item_button")
) {
Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(4.dp))
Text("Ligne")
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 420.dp)
.testTag("receipt_review_list"),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(scanState.items, key = { it.id }) { scannedItem ->
ScannedItemReviewCard(
item = scannedItem,
onUpdate = onUpdateItem,
onRemove = { onRemoveItem(scannedItem.id) }
)
}
}
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 = "Cocher aussi dans la liste de courses",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f)
)
Switch(
checked = alsoCheckShoppingList,
onCheckedChange = { alsoCheckShoppingList = it },
modifier = Modifier.testTag("receipt_also_check_shopping_switch")
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.weight(0.4f)
) {
Text("Annuler")
}
Button(
onClick = { onConfirmImport(scanState.items, alsoCheckShoppingList) },
enabled = selectedValidCount > 0,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(0.6f)
.testTag("confirm_receipt_import_button")
) {
Text("Ajouter $selectedValidCount au stock")
}
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
@Composable
private fun ScannedItemReviewCard(
item: ScannedReceiptItem,
onUpdate: (ScannedReceiptItem) -> Unit,
onRemove: () -> Unit
) {
var qtyText by remember(item.id) {
mutableStateOf(
if (item.quantity % 1.0 == 0.0) item.quantity.toInt().toString() else item.quantity.toString()
)
}
Card(
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(
containerColor = if (item.selected) {
MaterialTheme.colorScheme.surface
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)
}
),
border = BorderStroke(
width = 1.dp,
color = if (item.selected) {
MaterialTheme.colorScheme.outlineVariant
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f)
}
),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = item.selected,
onCheckedChange = { onUpdate(item.copy(selected = it)) }
)
Column(modifier = Modifier.weight(1f)) {
if (item.rawLabel.isNotBlank() && !item.rawLabel.equals(item.name, ignoreCase = true)) {
Text(
text = "Ticket : ${item.rawLabel}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
OutlinedTextField(
value = item.name,
onValueChange = { onUpdate(item.copy(name = it)) },
placeholder = { Text("Nom de l'aliment") },
singleLine = true,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
}
IconButton(onClick = onRemove) {
Icon(
imageVector = Icons.Default.DeleteOutline,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = qtyText,
onValueChange = { raw ->
qtyText = raw
val parsed = raw.replace(',', '.').toDoubleOrNull()
if (parsed != null && parsed > 0.0) {
onUpdate(item.copy(quantity = parsed))
}
},
label = { Text("Qté") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.width(92.dp)
)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FoodUnit.entries.forEach { unit ->
FilterChip(
selected = item.unit == unit,
onClick = { onUpdate(item.copy(unit = unit)) },
label = { Text(unit.label) }
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
StorageLocation.entries.forEach { loc ->
FilterChip(
selected = item.location == loc,
onClick = { onUpdate(item.copy(location = loc)) },
label = { Text(loc.displayName, maxLines = 1, overflow = TextOverflow.Ellipsis) },
modifier = Modifier.weight(1f)
)
}
}
FoodCategorySelectorRow(
selectedCategory = item.category,
onCategorySelected = { cat -> onUpdate(item.copy(category = cat)) }
)
}
}
}
@@ -0,0 +1,421 @@
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.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.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
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.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.ShoppingItemSource
import com.example.data.model.ShoppingListItem
import com.example.ui.common.FoodCategoryColorDot
@Composable
fun ShoppingListTab(
shoppingItems: List<ShoppingListItem>,
onAddManualItem: (name: String, quantity: Double?, unit: FoodUnit, category: FoodCategory) -> Unit,
onToggleItemChecked: (ShoppingListItem, Boolean) -> Unit,
onDeleteManualItem: (manualItemId: String) -> Unit,
onClearChecked: () -> Unit,
onScanReceiptClick: () -> Unit
) {
var manualName by rememberSaveable { mutableStateOf("") }
var manualQtyText by rememberSaveable { mutableStateOf("") }
var manualUnit by rememberSaveable { mutableStateOf(FoodUnit.PORTION) }
val uncheckedCount = shoppingItems.count { !it.isChecked }
val checkedCount = shoppingItems.count { it.isChecked }
val groupedItems = remember(shoppingItems) {
shoppingItems
.groupBy { it.category }
.entries
.sortedBy { it.key.ordinal }
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.testTag("shopping_tab_list"),
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 96.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
// Summary & Actions Header
item {
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = if (uncheckedCount == 0) {
"Liste de courses à jour"
} else {
"$uncheckedCount article${if (uncheckedCount > 1) "s" else ""} à acheter"
},
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
Text(
text = "Calculée d'après votre planning moins votre stock actuel",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.8f)
)
}
Icon(
imageVector = Icons.Default.ShoppingCart,
contentDescription = null,
tint = MaterialTheme.colorScheme.secondary,
modifier = Modifier.size(26.dp)
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = onScanReceiptClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.weight(1f)
.testTag("shopping_scan_receipt_button")
) {
Icon(
imageVector = Icons.Default.DocumentScanner,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Retour de courses", maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (checkedCount > 0) {
TextButton(
onClick = onClearChecked,
modifier = Modifier.testTag("clear_checked_shopping_button")
) {
Icon(
imageVector = Icons.Default.DoneAll,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text("Nettoyer ($checkedCount)")
}
}
}
}
}
}
// Quick manual add bar
item {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "Ajouter un article libre",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold
)
OutlinedTextField(
value = manualName,
onValueChange = { manualName = it },
placeholder = { Text("Ex. Huile d'olive, Pommes, Pain complet...") },
singleLine = true,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("manual_shopping_name_input")
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = manualQtyText,
onValueChange = { manualQtyText = it },
placeholder = { Text("Qté") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.width(78.dp)
.testTag("manual_shopping_qty_input")
)
FoodUnit.entries.forEach { unit ->
FilterChip(
selected = manualUnit == unit,
onClick = { manualUnit = unit },
label = { Text(unit.label) }
)
}
Spacer(modifier = Modifier.weight(1f))
Button(
onClick = {
val trimmed = manualName.trim()
if (trimmed.isNotBlank()) {
val qty = manualQtyText.replace(',', '.').toDoubleOrNull()
val inferredCat = FoodCategory.inferFromName(trimmed)
onAddManualItem(trimmed, qty, manualUnit, inferredCat)
manualName = ""
manualQtyText = ""
}
},
enabled = manualName.isNotBlank(),
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(horizontal = 14.dp, vertical = 10.dp),
modifier = Modifier.testTag("add_manual_shopping_button")
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Ajouter à la liste",
modifier = Modifier.size(18.dp)
)
}
}
}
}
}
// Empty state
if (shoppingItems.isEmpty()) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.ShoppingCart,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(36.dp)
)
Text(
text = "Rien à acheter pour cette semaine !",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center
)
Text(
text = "Planifiez vos repas dans l'onglet Semaine ou ajoutez un article libre ci-dessus.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
}
} else {
groupedItems.forEach { (category, categoryItems) ->
item(key = "cat_header_${category.name}") {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FoodCategoryColorDot(category = category, size = 10.dp)
Text(
text = category.displayName,
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
items(categoryItems, key = { it.key }) { item ->
ShoppingItemCard(
item = item,
onToggleChecked = { checked -> onToggleItemChecked(item, checked) },
onDeleteManual = item.manualItemId?.let { id -> { onDeleteManualItem(id) } }
)
}
}
}
}
}
@Composable
private fun ShoppingItemCard(
item: ShoppingListItem,
onToggleChecked: (Boolean) -> Unit,
onDeleteManual: (() -> Unit)?
) {
val missingFmt = item.formatMissingQuantity()
val inStockFmt = item.formatInStockQuantity()
val sourceLabel = when (item.source) {
ShoppingItemSource.FROM_PLAN -> "Planning"
ShoppingItemSource.MANUAL -> "Manuel"
ShoppingItemSource.BOTH -> "Planning + Manuel"
}
Card(
shape = RoundedCornerShape(14.dp),
colors = CardDefaults.cardColors(
containerColor = if (item.isChecked) {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)
} else {
MaterialTheme.colorScheme.surface
}
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)),
modifier = Modifier
.fillMaxWidth()
.clickable { onToggleChecked(!item.isChecked) }
.testTag("shopping_item_${item.key}")
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = item.isChecked,
onCheckedChange = onToggleChecked
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = item.name,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
textDecoration = if (item.isChecked) TextDecoration.LineThrough else null,
color = if (item.isChecked) {
MaterialTheme.colorScheme.onSurfaceVariant
} else {
MaterialTheme.colorScheme.onSurface
}
)
val detailParts = buildList {
add(sourceLabel)
if (inStockFmt != null) {
add("En stock : $inStockFmt")
}
}
Text(
text = detailParts.joinToString(" • "),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (missingFmt != null) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.65f),
modifier = Modifier.padding(horizontal = 6.dp)
) {
Text(
text = missingFmt,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
)
}
}
if (onDeleteManual != null) {
IconButton(
onClick = onDeleteManual,
modifier = Modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Default.DeleteOutline,
contentDescription = "Supprimer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp)
)
}
}
}
}
}
@@ -0,0 +1,154 @@
package com.example.ui.planning
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.heightIn
import androidx.compose.foundation.layout.padding
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.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.StockDeductionProposal
import com.example.domain.IngredientMatcher
import com.example.ui.common.FoodCategoryColorDot
@Composable
fun StockDeductionDialog(
proposals: List<StockDeductionProposal>,
onDismiss: () -> Unit,
onConfirm: (List<StockDeductionProposal>) -> Unit
) {
val selectionMap = remember(proposals) {
mutableStateMapOf<String, Boolean>().apply {
proposals.forEach { put(it.inventoryItem.id, it.selected) }
}
}
val selectedCount = proposals.count { selectionMap[it.inventoryItem.id] == true }
AlertDialog(
onDismissRequest = onDismiss,
modifier = Modifier.testTag("stock_deduction_dialog"),
title = {
Text(
text = "Mettre à jour votre stock ?",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
},
text = {
Column(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 340.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = "Les ingrédients consommés suivants sont présents dans votre cuisine. Cochez ceux à déduire :",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
proposals.forEach { proposal ->
val checked = selectionMap[proposal.inventoryItem.id] == true
val currentFmt = proposal.inventoryItem.formatQuantity()
val deductFmt = IngredientMatcher.formatQuantity(
proposal.deductAmount,
proposal.inventoryItem.unit
)
val remainingFmt = if (proposal.remainingAfter <= 0.001) {
"Épuisé"
} else {
IngredientMatcher.formatQuantity(
proposal.remainingAfter,
proposal.inventoryItem.unit
)
}
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable {
selectionMap[proposal.inventoryItem.id] = !checked
}
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = checked,
onCheckedChange = { selectionMap[proposal.inventoryItem.id] = it }
)
FoodCategoryColorDot(
category = proposal.inventoryItem.category,
size = 9.dp
)
Spacer(modifier = Modifier.width(8.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = proposal.inventoryItem.name,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
text = "$currentFmt → $remainingFmt (-$deductFmt)",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
},
confirmButton = {
Button(
onClick = {
val resolved = proposals.map { proposal ->
proposal.copy(selected = selectionMap[proposal.inventoryItem.id] == true)
}
onConfirm(resolved)
},
enabled = selectedCount > 0,
modifier = Modifier.testTag("confirm_stock_deduction_button")
) {
Text("Déduire ($selectedCount)")
}
},
dismissButton = {
TextButton(
onClick = onDismiss,
modifier = Modifier.testTag("dismiss_stock_deduction_button")
) {
Text("Ignorer")
}
}
)
}
@@ -0,0 +1,472 @@
package com.example.ui.planning
import androidx.compose.foundation.BorderStroke
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
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.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.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
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.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry
import com.example.data.model.RecipeEntry
import com.example.ui.common.FoodCategoryColorDotsRow
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
@Composable
fun WeeklyPlanTab(
weekStartDate: LocalDate,
plannedMeals: List<PlannedMealEntry>,
recipesById: Map<String, RecipeEntry>,
customFoods: List<CustomFoodEntry>,
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
onPlanMealClick: (date: LocalDate, mealType: MealType) -> Unit,
onEditPlannedMeal: (PlannedMealEntry) -> Unit,
onDeletePlannedMeal: (String) -> Unit,
onMarkAsEaten: (PlannedMealEntry) -> Unit
) {
val today = remember { LocalDate.now() }
val currentMonday = remember { PlanningViewModel.currentMonday() }
val isCurrentWeek = weekStartDate == currentMonday
val weekDays = remember(weekStartDate) {
(0L..6L).map { weekStartDate.plusDays(it) }
}
val mealsByDayAndType = remember(plannedMeals) {
plannedMeals.groupBy { it.dateEpochDay to it.mealType }
}
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
val rangeFormatter = remember { DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) }
val dayTitleFormatter = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) }
val weekRangeLabel = remember(weekStartDate) {
val end = weekStartDate.plusDays(6)
"${weekStartDate.format(rangeFormatter)} – ${end.format(rangeFormatter)}"
}
val consumedCount = plannedMeals.count { it.isConsumed }
LazyColumn(
modifier = Modifier
.fillMaxSize()
.testTag("weekly_plan_tab_list"),
contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 96.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
// Week navigation bar
item {
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(
onClick = onPreviousWeek,
modifier = Modifier.testTag("previous_week_button")
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft,
contentDescription = "Semaine précédente"
)
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = "Semaine du $weekRangeLabel",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
Text(
text = if (plannedMeals.isEmpty()) {
"Aucun repas planifié cette semaine"
} else {
"${plannedMeals.size} repas planifié${if (plannedMeals.size > 1) "s" else ""} • $consumedCount consommé${if (consumedCount > 1) "s" else ""}"
},
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(
onClick = onNextWeek,
modifier = Modifier.testTag("next_week_button")
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
contentDescription = "Semaine suivante"
)
}
}
if (!isCurrentWeek) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
AssistChip(
onClick = onGoToCurrentWeek,
leadingIcon = {
Icon(
imageVector = Icons.Default.Today,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
label = { Text("Revenir à cette semaine") },
modifier = Modifier.testTag("current_week_button")
)
}
}
}
}
}
// 7 Day Cards
items(weekDays, key = { it.toEpochDay() }) { day ->
val isToday = day == today
val formattedDay = day.format(dayTitleFormatter).replaceFirstChar {
it.titlecase(Locale.FRENCH)
}
val dayPlannedCount = MealType.entries.sumOf { type ->
mealsByDayAndType[day.toEpochDay() to type]?.size ?: 0
}
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = if (isToday) {
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.28f)
} else {
MaterialTheme.colorScheme.surface
}
),
border = BorderStroke(
width = if (isToday) 1.5.dp else 1.dp,
color = if (isToday) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
}
),
modifier = Modifier
.fillMaxWidth()
.testTag("plan_day_card_${day.toEpochDay()}")
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = formattedDay,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = if (isToday) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurface
}
)
if (isToday) {
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.primary
) {
Text(
text = "Aujourd'hui",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.padding(horizontal = 7.dp, vertical = 2.dp)
)
}
}
}
if (dayPlannedCount > 0) {
Text(
text = "$dayPlannedCount/4",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
MealType.entries.forEachIndexed { index, mealType ->
if (index > 0) {
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f)
)
}
val slotEntries = mealsByDayAndType[day.toEpochDay() to mealType].orEmpty()
MealSlotRow(
mealType = mealType,
entries = slotEntries,
recipesById = recipesById,
customCategoriesLookup = customCategoriesLookup,
onAddClick = { onPlanMealClick(day, mealType) },
onEditEntry = onEditPlannedMeal,
onDeleteEntry = onDeletePlannedMeal,
onMarkAsEaten = onMarkAsEaten
)
}
}
}
}
}
}
@Composable
private fun MealSlotRow(
mealType: MealType,
entries: List<PlannedMealEntry>,
recipesById: Map<String, RecipeEntry>,
customCategoriesLookup: Map<String, List<com.example.data.model.FoodCategory>>,
onAddClick: () -> Unit,
onEditEntry: (PlannedMealEntry) -> Unit,
onDeleteEntry: (String) -> Unit,
onMarkAsEaten: (PlannedMealEntry) -> Unit
) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = mealType.displayName,
style = MaterialTheme.typography.labelMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
TextButton(
onClick = onAddClick,
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 4.dp),
modifier = Modifier.testTag("add_plan_${mealType.name.lowercase()}")
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Planifier ${mealType.displayName}",
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = if (entries.isEmpty()) "Planifier" else "Ajouter",
style = MaterialTheme.typography.labelMedium
)
}
}
entries.forEach { entry ->
val title = entry.resolvedTitle(recipesById)
val resolvedItems = entry.resolvedFoodItems(recipesById)
val categoryDots = remember(resolvedItems, customCategoriesLookup) {
resolvedItems
.flatMap { it.resolvedCategories(customCategoriesLookup) }
.distinct()
.take(5)
}
Surface(
shape = RoundedCornerShape(12.dp),
color = if (entry.isConsumed) {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
},
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
if (categoryDots.isNotEmpty()) {
FoodCategoryColorDotsRow(
categories = categoryDots,
dotSize = 8.dp,
spacing = 3.dp
)
Spacer(modifier = Modifier.width(8.dp))
}
Column(modifier = Modifier.weight(1f)) {
Text(
text = title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
textDecoration = if (entry.isConsumed) TextDecoration.LineThrough else null,
color = if (entry.isConsumed) {
MaterialTheme.colorScheme.onSurfaceVariant
} else {
MaterialTheme.colorScheme.onSurface
},
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
val subtitleParts = buildList {
if (!entry.recipeId.isNullOrBlank()) {
val formattedServings = if (entry.servings % 1.0 == 0.0) {
entry.servings.toInt().toString()
} else {
entry.servings.toString()
}
add("$formattedServings part${if (entry.servings > 1.0) "s" else ""}")
}
if (resolvedItems.isNotEmpty()) {
add("${resolvedItems.size} ingrédient${if (resolvedItems.size > 1) "s" else ""}")
}
}
if (subtitleParts.isNotEmpty()) {
Text(
text = subtitleParts.joinToString(" • "),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
IconButton(
onClick = { onEditEntry(entry) },
modifier = Modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Modifier $title",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp)
)
}
IconButton(
onClick = { onDeleteEntry(entry.id) },
modifier = Modifier.size(36.dp)
) {
Icon(
imageVector = Icons.Default.DeleteOutline,
contentDescription = "Retirer $title",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(18.dp)
)
}
}
if (entry.isConsumed) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(5.dp)
) {
Icon(
imageVector = Icons.Default.CheckCircle,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(16.dp)
)
Text(
text = "Noté au journal",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium
)
}
} else {
FilledTonalButton(
onClick = { onMarkAsEaten(entry) },
shape = RoundedCornerShape(10.dp),
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 6.dp),
modifier = Modifier
.height(36.dp)
.testTag("mark_eaten_${entry.id}")
) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "Marquer comme mangé",
style = MaterialTheme.typography.labelMedium
)
}
}
}
}
}
}
}
@@ -70,6 +70,7 @@ import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.domain.DailyBenchmarkGap
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.FoodCategoryColorDotsRow
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
@@ -591,7 +592,11 @@ private fun SuggestedRecipeCard(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FoodCategoryColorDot(category = item.resolvedCategory(), size = 8.dp)
FoodCategoryColorDotsRow(
categories = item.resolvedCategories(),
dotSize = 8.dp,
spacing = 2.dp
)
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.bodySmall,
@@ -79,8 +79,8 @@ fun RecipeDetailSheet(
var showDeleteConfirm by remember { mutableStateOf(false) }
val checkedSteps = remember(recipe.id) { mutableStateListOf<Int>() }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
val scaledIngredients = remember(recipe.ingredientsSerialized, displayServings) {
@@ -277,7 +277,7 @@ fun RecipeDetailSheet(
scaledIngredients.forEach { item ->
FoodCategoryBadge(
text = item.displayBadge(),
category = item.resolvedCategory(customCategoryLookup)
categories = item.resolvedCategories(customCategoriesLookup)
)
}
}
@@ -1,6 +1,7 @@
package com.example.ui.recipes
import android.net.Uri
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
@@ -40,6 +41,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
@@ -50,6 +52,7 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -69,6 +72,7 @@ import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.ui.common.UnsavedChangesDiscardDialog
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
@@ -79,26 +83,38 @@ import java.util.Locale
fun RecipeEditorSheet(
initialRecipe: RecipeEntry? = null,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onAddCustomFood: (String, FoodUnit, List<FoodCategory>) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit,
onSaveRecipe: (RecipeEntry) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var title by rememberSaveable { mutableStateOf(initialRecipe?.title ?: "") }
var selectedTag by rememberSaveable {
mutableStateOf(initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN)
var showDiscardDialog by remember { mutableStateOf(false) }
val initialTitle = remember(initialRecipe?.id) { initialRecipe?.title ?: "" }
val initialTag = remember(initialRecipe?.id) { initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN }
val initialPrepTime = remember(initialRecipe?.id) {
initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: ""
}
var prepTimeInput by rememberSaveable {
mutableStateOf(initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: "")
val initialServings = remember(initialRecipe?.id) {
(initialRecipe?.servings ?: 2).toString()
}
var servingsInput by rememberSaveable {
mutableStateOf((initialRecipe?.servings ?: 2).toString())
val initialNotes = remember(initialRecipe?.id) { initialRecipe?.notes ?: "" }
val initialPhoto = remember(initialRecipe?.id) { initialRecipe?.photoUri }
val initialIngredientsSerialized = remember(initialRecipe?.id) {
initialRecipe?.parsedIngredients()?.map { it.serialize() } ?: emptyList()
}
var notes by rememberSaveable { mutableStateOf(initialRecipe?.notes ?: "") }
var photoUri by rememberSaveable { mutableStateOf(initialRecipe?.photoUri) }
val initialSteps = remember(initialRecipe?.id) {
initialRecipe?.steps ?: emptyList()
}
var title by rememberSaveable { mutableStateOf(initialTitle) }
var selectedTag by rememberSaveable { mutableStateOf(initialTag) }
var prepTimeInput by rememberSaveable { mutableStateOf(initialPrepTime) }
var servingsInput by rememberSaveable { mutableStateOf(initialServings) }
var notes by rememberSaveable { mutableStateOf(initialNotes) }
var photoUri by rememberSaveable { mutableStateOf(initialPhoto) }
var newlySavedPhotoUri by rememberSaveable { mutableStateOf<String?>(null) }
var isProcessingPhoto by remember { mutableStateOf(false) }
@@ -117,25 +133,56 @@ fun RecipeEditorSheet(
}
}
// Ingredient builder state
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
// Ingredient builder state (multi-category)
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var selectedFoodCategoriesEncoded by rememberSaveable { mutableStateOf(FoodCategory.OTHER.code) }
val selectedFoodCategories = remember(selectedFoodCategoriesEncoded) {
FoodCategory.parseCategoryList(selectedFoodCategoriesEncoded).ifEmpty { listOf(FoodCategory.OTHER) }
}
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
// Step builder state
var stepInput by rememberSaveable { mutableStateOf("") }
val hasUnsavedChanges = title.trim() != initialTitle.trim() ||
selectedTag != initialTag ||
prepTimeInput.trim() != initialPrepTime ||
servingsInput.trim() != initialServings ||
notes.trim() != initialNotes.trim() ||
photoUri != initialPhoto ||
ingredientsList.map { it.serialize() } != initialIngredientsSerialized ||
stepsList.toList() != initialSteps ||
foodNameInput.isNotBlank() ||
foodWeightInput.isNotBlank() ||
stepInput.isNotBlank()
val currentHasUnsavedChanges by rememberUpdatedState(hasUnsavedChanges)
val sheetState = rememberModalBottomSheetState(
skipPartiallyExpanded = true,
confirmValueChange = { targetValue ->
if (targetValue == SheetValue.Hidden && currentHasUnsavedChanges) {
showDiscardDialog = true
false
} else {
true
}
}
)
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
val cats = it.resolvedCategories()
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
category = cats.first(),
categories = cats
)
}
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
@@ -167,16 +214,17 @@ fun RecipeEditorSheet(
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && ingredientsList.size < 40) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
val resolvedCats = if (hasUserOverriddenCategory) {
selectedFoodCategories
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
FoodCategory.inferCategoriesFromName(cleanName, customCategoriesLookup)
}
val item = MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit,
category = resolvedCat
category = resolvedCats.firstOrNull(),
categories = resolvedCats
)
val existingIdx = ingredientsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIdx >= 0) {
@@ -185,12 +233,12 @@ fun RecipeEditorSheet(
ingredientsList.add(item)
}
if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCats)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
selectedFoodCategoriesEncoded = FoodCategory.OTHER.code
hasUserOverriddenCategory = false
}
}
@@ -215,17 +263,30 @@ fun RecipeEditorSheet(
}
}
val handleDismiss = {
val performDiscardAndDismiss = {
showDiscardDialog = false
newlySavedPhotoUri?.let { ImageUtils.deletePhotoFile(context, it) }
onDismiss()
}
val requestDismiss = {
if (hasUnsavedChanges) {
showDiscardDialog = true
} else {
performDiscardAndDismiss()
}
}
ModalBottomSheet(
onDismissRequest = handleDismiss,
onDismissRequest = requestDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
BackHandler(enabled = hasUnsavedChanges) {
showDiscardDialog = true
}
Column(
modifier = Modifier
.fillMaxWidth()
@@ -252,7 +313,10 @@ fun RecipeEditorSheet(
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = handleDismiss) {
IconButton(
onClick = requestDismiss,
modifier = Modifier.testTag("dismiss_recipe_editor_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer"
@@ -404,7 +468,7 @@ fun RecipeEditorSheet(
Spacer(modifier = Modifier.height(18.dp))
// Color-Coded Ingredients Builder
// Color-Coded Multi-Category Ingredients Builder
FoodItemBuilderSection(
foodItemsList = ingredientsList,
matchingSuggestions = matchingSuggestions,
@@ -412,24 +476,32 @@ fun RecipeEditorSheet(
onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
val inferred = if (input.isBlank()) {
listOf(FoodCategory.OTHER)
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
FoodCategory.inferCategoriesFromName(input, customCategoriesLookup)
}
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(inferred)
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
selectedFoodCategoriesEncoded = FoodCategory.OTHER.code
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { cat ->
selectedFoodCategory = cat
selectedFoodCategories = selectedFoodCategories,
onFoodCategoryToggled = { toggled ->
val updated = FoodCategory.toggleCategorySelection(selectedFoodCategories, toggled)
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(updated)
hasUserOverriddenCategory = true
},
onSuggestionSelected = { suggestion ->
foodNameInput = suggestion.name
selectedFoodUnit = suggestion.defaultUnit
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(suggestion.resolvedCategories())
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood,
@@ -440,14 +512,17 @@ fun RecipeEditorSheet(
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(
item.resolvedCategories(customCategoriesLookup)
)
hasUserOverriddenCategory = true
ingredientsList.remove(item)
},
onRemoveFoodItem = { item -> ingredientsList.remove(item) },
customCategoriesLookup = customCategoriesLookup,
sectionTitle = "Ingrédients colorés",
addButtonLabelPrefix = "Ajouter l'ingrédient",
addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleur) :"
addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleurs) :"
)
Spacer(modifier = Modifier.height(18.dp))
@@ -573,7 +648,10 @@ fun RecipeEditorSheet(
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(onClick = handleDismiss) {
TextButton(
onClick = requestDismiss,
modifier = Modifier.testTag("cancel_recipe_button")
) {
Text("Annuler")
}
Spacer(modifier = Modifier.width(10.dp))
@@ -624,4 +702,13 @@ fun RecipeEditorSheet(
Spacer(modifier = Modifier.height(16.dp))
}
}
if (showDiscardDialog) {
UnsavedChangesDiscardDialog(
title = "Quitter sans enregistrer ?",
message = "Votre recette en cours n'est pas encore enregistrée. Souhaitez-vous vraiment quitter sans sauvegarder ?",
onContinueEditing = { showDiscardDialog = false },
onConfirmDiscard = performDiscardAndDismiss
)
}
}
@@ -104,8 +104,8 @@ fun RecipesScreen(
var selectedTag by rememberSaveable { mutableStateOf<String?>(null) }
var cravingNote by rememberSaveable { mutableStateOf("") }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
val customCategoriesLookup = remember(customFoods) {
CustomFoodEntry.buildCategoriesLookup(customFoods)
}
val filteredRecipes = remember(recipes, searchQuery, selectedTag) {
@@ -357,7 +357,7 @@ fun RecipesScreen(
items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem(
recipe = recipe,
customCategoryLookup = customCategoryLookup,
customCategoriesLookup = customCategoriesLookup,
onClick = { onRecipeClick(recipe) }
)
}
@@ -390,13 +390,13 @@ fun RecipesScreen(
@Composable
private fun RecipeCardItem(
recipe: RecipeEntry,
customCategoryLookup: Map<String, FoodCategory>,
customCategoriesLookup: Map<String, List<FoodCategory>>,
onClick: () -> Unit
) {
val isDark = isSatieaDarkTheme()
val ingredients = remember(recipe.ingredientsSerialized) { recipe.parsedIngredients() }
val dominantCategories = remember(recipe.ingredientsSerialized, customCategoryLookup) {
recipe.dominantCategories(customCategoryLookup).take(4)
val dominantCategories = remember(recipe.ingredientsSerialized, customCategoriesLookup) {
recipe.dominantCategories(customCategoriesLookup).take(4)
}
Card(