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

@@ -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
)
}
}
}
}
}
}
}