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,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
}
}