diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f417dc6..c507ed0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,7 +2,12 @@ + + + diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt index a10f5aa..bd2df95 100644 --- a/app/src/main/java/com/example/MainActivity.kt +++ b/app/src/main/java/com/example/MainActivity.kt @@ -23,6 +23,7 @@ import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.MenuBook import androidx.compose.material.icons.filled.BarChart +import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.AlertDialog @@ -63,6 +64,9 @@ import com.example.ui.journal.JournalScreen import com.example.ui.journal.MealViewModel import com.example.ui.journal.MealsUiState import com.example.ui.meal.MealEntrySheet +import com.example.ui.planning.PlanningScreen +import com.example.ui.planning.PlanningViewModel +import com.example.ui.planning.StockDeductionDialog import com.example.ui.recipes.RecipeDetailSheet import com.example.ui.recipes.RecipeEditorSheet import com.example.ui.recipes.RecipesScreen @@ -79,7 +83,8 @@ import java.time.LocalTime enum class MainTab(val title: String) { JOURNAL("Journal"), RECIPES("Recettes"), - STATS("Statistiques"), + PLANNING("Planning"), + STATS("Stats"), SETTINGS("Réglages") } @@ -91,6 +96,7 @@ private enum class PendingDriveAction { class MainActivity : ComponentActivity() { private val viewModel: MealViewModel by viewModels() + private val planningViewModel: PlanningViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -109,7 +115,10 @@ class MainActivity : ComponentActivity() { val themeMode by viewModel.themeMode.collectAsStateWithLifecycle() SatieaTheme(themeMode = themeMode) { - AppRoot(viewModel = viewModel) + AppRoot( + viewModel = viewModel, + planningViewModel = planningViewModel + ) } } } @@ -133,7 +142,8 @@ class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3Api::class) @Composable fun AppRoot( - viewModel: MealViewModel + viewModel: MealViewModel, + planningViewModel: PlanningViewModel ) { val context = LocalContext.current var googleAccount by remember { mutableStateOf(GoogleSheetsAuthHelper.getSignedInAccount(context)) } @@ -160,12 +170,30 @@ fun AppRoot( } } + LaunchedEffect(Unit) { + planningViewModel.uiEvents.collect { event -> + when (event) { + is UiEvent.ShowSnackbar -> snackbarHostState.showSnackbar(event.message) + is UiEvent.OpenUrl -> { + try { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(event.url)) + context.startActivity(intent) + } catch (_: Exception) { + snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : ${event.url}") + } + } + is UiEvent.StartActivity -> context.startActivity(event.intent) + } + } + } + var currentTab by remember { mutableStateOf(MainTab.JOURNAL) } - // Meal entry sheet state (supports editing existing meal OR pre-filling a new meal from a recipe) + // Meal entry sheet state (supports editing existing meal OR pre-filling a new meal from a recipe or plan) var showMealEntrySheet by remember { mutableStateOf(false) } var editingMeal by remember { mutableStateOf(null) } var defaultMealType by remember { mutableStateOf(MealType.LUNCH) } + var pendingConsumedPlannedMealId by remember { mutableStateOf(null) } // Recipe book sheets state var selectedRecipeId by remember { mutableStateOf(null) } @@ -263,6 +291,14 @@ fun AppRoot( val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle() val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList() + // Planning, Stock & Shopping states + val weekStartDate by planningViewModel.weekStartDate.collectAsStateWithLifecycle() + val weekPlannedMeals by planningViewModel.weekPlannedMeals.collectAsStateWithLifecycle() + val inventoryItems by planningViewModel.inventoryItems.collectAsStateWithLifecycle() + val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle() + val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle() + val pendingStockDeductions by planningViewModel.pendingStockDeductions.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { SatieaAppWidgetProvider.updateAllWidgets(context) } @@ -387,7 +423,7 @@ fun AppRoot( selected = currentTab == MainTab.JOURNAL, onClick = { currentTab = MainTab.JOURNAL }, icon = { Icon(Icons.Default.Restaurant, contentDescription = "Journal") }, - label = { Text("Journal") }, + label = { Text("Journal", maxLines = 1) }, colors = NavigationBarItemDefaults.colors( selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, indicatorColor = MaterialTheme.colorScheme.primaryContainer @@ -399,7 +435,7 @@ fun AppRoot( selected = currentTab == MainTab.RECIPES, onClick = { currentTab = MainTab.RECIPES }, icon = { Icon(Icons.AutoMirrored.Filled.MenuBook, contentDescription = "Recettes") }, - label = { Text("Recettes") }, + label = { Text("Recettes", maxLines = 1) }, colors = NavigationBarItemDefaults.colors( selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, indicatorColor = MaterialTheme.colorScheme.primaryContainer @@ -407,11 +443,23 @@ fun AppRoot( modifier = Modifier.testTag("tab_recipes") ) + NavigationBarItem( + selected = currentTab == MainTab.PLANNING, + onClick = { currentTab = MainTab.PLANNING }, + icon = { Icon(Icons.Default.CalendarMonth, contentDescription = "Planning") }, + label = { Text("Planning", maxLines = 1) }, + colors = NavigationBarItemDefaults.colors( + selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, + indicatorColor = MaterialTheme.colorScheme.primaryContainer + ), + modifier = Modifier.testTag("tab_planning") + ) + NavigationBarItem( selected = currentTab == MainTab.STATS, onClick = { currentTab = MainTab.STATS }, icon = { Icon(Icons.Default.BarChart, contentDescription = "Statistiques") }, - label = { Text("Stats") }, + label = { Text("Stats", maxLines = 1) }, colors = NavigationBarItemDefaults.colors( selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, indicatorColor = MaterialTheme.colorScheme.primaryContainer @@ -423,7 +471,7 @@ fun AppRoot( selected = currentTab == MainTab.SETTINGS, onClick = { currentTab = MainTab.SETTINGS }, icon = { Icon(Icons.Default.Settings, contentDescription = "Réglages") }, - label = { Text("Réglages") }, + label = { Text("Réglages", maxLines = 1) }, colors = NavigationBarItemDefaults.colors( selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, indicatorColor = MaterialTheme.colorScheme.primaryContainer @@ -513,6 +561,79 @@ fun AppRoot( ) } + MainTab.PLANNING -> { + val recipesById = remember(recipes) { recipes.associateBy { it.id } } + PlanningScreen( + weekStartDate = weekStartDate, + plannedMeals = weekPlannedMeals, + inventoryItems = inventoryItems, + shoppingItems = computedShoppingList, + recipes = recipes, + customFoods = customFoods, + receiptScanState = receiptScanState, + onPreviousWeek = { planningViewModel.previousWeek() }, + onNextWeek = { planningViewModel.nextWeek() }, + onGoToCurrentWeek = { planningViewModel.goToCurrentWeek() }, + onSavePlannedMeal = { entry -> planningViewModel.savePlannedMeal(entry) }, + onDeletePlannedMeal = { id -> planningViewModel.deletePlannedMeal(id) }, + onMarkPlannedMealAsEaten = { planned -> + val resolvedFoods = planned.resolvedFoodItems(recipesById) + val linkedRecipe = planned.recipeId?.let { recipesById[it] } + val title = planned.resolvedTitle(recipesById) + val prefilledMeal = MealEntry( + id = "", + mealType = planned.mealType.name, + mealTimestamp = System.currentTimeMillis(), + hungerBefore = 5, + satietyAfter = 7, + note = if (linkedRecipe != null) { + "Planifié : ${linkedRecipe.title}" + } else { + "Planifié : $title" + }, + foodItemsSerialized = resolvedFoods.map { it.serialize() }, + photoUris = listOfNotNull(linkedRecipe?.photoUri) + ) + pendingConsumedPlannedMealId = planned.id + editingMeal = prefilledMeal + defaultMealType = planned.mealType + showMealEntrySheet = true + }, + onAddCustomFood = { name, unit, categories -> + viewModel.addCustomFoodDirectly(name, unit, categories) + }, + onSaveInventoryItem = { item -> planningViewModel.saveInventoryItem(item) }, + onAdjustInventoryQuantity = { id, delta -> + planningViewModel.adjustInventoryQuantity(id, delta) + }, + onDeleteInventoryItem = { id -> planningViewModel.deleteInventoryItem(id) }, + onAddManualShoppingItem = { name, qty, unit, cat -> + planningViewModel.addManualShoppingItem(name, qty, unit, cat) + }, + onToggleShoppingItemChecked = { item, checked -> + planningViewModel.toggleShoppingItemChecked(item, checked) + }, + onAddShoppingItemToStock = { item, qty, unit, location -> + planningViewModel.addShoppingItemToStock(item, qty, unit, location) + }, + onDeleteManualShoppingItem = { id -> + planningViewModel.deleteManualShoppingItem(id) + }, + onClearCheckedShoppingItems = { + planningViewModel.clearCheckedShoppingItems() + }, + onScanReceiptUri = { uri -> planningViewModel.scanReceiptFromUri(uri) }, + onUpdateScannedItem = { item -> planningViewModel.updateScannedItem(item) }, + onRemoveScannedItem = { id -> planningViewModel.removeScannedItem(id) }, + onAddBlankScannedItem = { planningViewModel.addBlankScannedItem() }, + onConfirmReceiptImport = { items, alsoCheckShopping -> + planningViewModel.confirmScannedReceiptImport(items, alsoCheckShopping) + }, + onDismissReceiptScan = { planningViewModel.dismissReceiptScan() }, + onShowMessage = { msg -> viewModel.emitEvent(UiEvent.ShowSnackbar(msg)) } + ) + } + MainTab.STATS -> { WeeklyStatsScreen( weeklyStats = weeklyStats, @@ -562,16 +683,19 @@ fun AppRoot( initialMeal = editingMeal, defaultMealType = defaultMealType, customFoods = customFoods, - onAddCustomFood = { name, unit, category -> - viewModel.addCustomFoodDirectly(name, unit, category) + onAddCustomFood = { name, unit, categories -> + viewModel.addCustomFoodDirectly(name, unit, categories) }, onDismiss = { showMealEntrySheet = false editingMeal = null + pendingConsumedPlannedMealId = null }, onSaveMeal = { type, timestamp, hunger, satiety, note, foodItems, photos -> showMealEntrySheet = false val currentEditing = editingMeal + val consumedPlanId = pendingConsumedPlannedMealId + pendingConsumedPlannedMealId = null if (currentEditing != null && currentEditing.id.isNotBlank()) { viewModel.updateMeal( meal = currentEditing.copy( @@ -594,12 +718,26 @@ fun AppRoot( foodItems = foodItems, photoUris = photos ) + planningViewModel.onMealLoggedCheckStock( + eatenItems = foodItems, + plannedMealId = consumedPlanId + ) } editingMeal = null } ) } + // Stock Deduction Confirmation Dialog after logging a meal + val activeStockProposals = pendingStockDeductions + if (!activeStockProposals.isNullOrEmpty()) { + StockDeductionDialog( + proposals = activeStockProposals, + onDismiss = { planningViewModel.dismissStockDeductions() }, + onConfirm = { selected -> planningViewModel.confirmStockDeductions(selected) } + ) + } + // Recipe Detail Sheet val activeRecipe = selectedRecipeId?.let { id -> recipes.firstOrNull { it.id == id } } if (activeRecipe != null) { @@ -643,8 +781,8 @@ fun AppRoot( RecipeEditorSheet( initialRecipe = editingRecipe, customFoods = customFoods, - onAddCustomFood = { name, unit, category -> - viewModel.addCustomFoodDirectly(name, unit, category) + onAddCustomFood = { name, unit, categories -> + viewModel.addCustomFoodDirectly(name, unit, categories) }, onDismiss = { showRecipeEditor = false diff --git a/app/src/main/java/com/example/data/local/AppDatabase.kt b/app/src/main/java/com/example/data/local/AppDatabase.kt index 1dbbe0f..983ebe5 100644 --- a/app/src/main/java/com/example/data/local/AppDatabase.kt +++ b/app/src/main/java/com/example/data/local/AppDatabase.kt @@ -16,9 +16,12 @@ import com.squareup.moshi.Types LocalMealEntity::class, LocalCustomFoodEntity::class, LocalRecipeEntity::class, - LocalFoodPreferenceEntity::class + LocalFoodPreferenceEntity::class, + LocalPlannedMealEntity::class, + LocalInventoryItemEntity::class, + LocalShoppingItemEntity::class ], - version = 5, + version = 6, exportSchema = false ) @TypeConverters(RoomConverters::class) @@ -139,6 +142,53 @@ abstract class AppDatabase : RoomDatabase() { } } + val MIGRATION_5_6 = object : Migration(5, 6) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS `local_planned_meals` ( + `id` TEXT NOT NULL PRIMARY KEY, + `dateEpochDay` INTEGER NOT NULL, + `mealType` TEXT NOT NULL, + `recipeId` TEXT, + `customTitle` TEXT NOT NULL, + `servings` REAL NOT NULL, + `items` TEXT NOT NULL, + `isConsumed` INTEGER NOT NULL, + `updatedAt` INTEGER NOT NULL + ) + """.trimIndent() + ) + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS `local_inventory_items` ( + `id` TEXT NOT NULL PRIMARY KEY, + `name` TEXT NOT NULL, + `normalizedName` TEXT NOT NULL, + `quantity` REAL NOT NULL, + `unit` TEXT NOT NULL, + `category` TEXT NOT NULL, + `location` TEXT NOT NULL, + `updatedAt` INTEGER NOT NULL + ) + """.trimIndent() + ) + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS `local_shopping_items` ( + `id` TEXT NOT NULL PRIMARY KEY, + `name` TEXT NOT NULL, + `quantity` REAL, + `unit` TEXT NOT NULL, + `category` TEXT NOT NULL, + `isChecked` INTEGER NOT NULL, + `updatedAt` INTEGER NOT NULL + ) + """.trimIndent() + ) + } + } + fun getInstance(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } @@ -150,7 +200,7 @@ abstract class AppDatabase : RoomDatabase() { appContext, AppDatabase::class.java, "satiea_local.db" - ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5) + ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6) // Destructive migration is only permitted on debug builds if (BuildConfig.DEBUG) { diff --git a/app/src/main/java/com/example/data/local/LocalCustomFoodEntity.kt b/app/src/main/java/com/example/data/local/LocalCustomFoodEntity.kt index 0e37b3c..c51804b 100644 --- a/app/src/main/java/com/example/data/local/LocalCustomFoodEntity.kt +++ b/app/src/main/java/com/example/data/local/LocalCustomFoodEntity.kt @@ -24,8 +24,13 @@ data class LocalCustomFoodEntity( ) } + fun resolvedCategories(): List { + return FoodCategory.parseCategoryList(category) + .ifEmpty { FoodCategory.inferCategoriesFromName(name) } + } + fun resolvedCategory(): FoodCategory { - return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name) + return resolvedCategories().first() } companion object { @@ -33,6 +38,18 @@ data class LocalCustomFoodEntity( name: String, defaultUnit: FoodUnit, category: FoodCategory? = null + ): LocalCustomFoodEntity { + return create( + name = name, + defaultUnit = defaultUnit, + categories = listOfNotNull(category) + ) + } + + fun create( + name: String, + defaultUnit: FoodUnit, + categories: List ): LocalCustomFoodEntity { val cleanName = name.trim().take(100) val slugId = Normalizer.normalize(cleanName.lowercase(), Normalizer.Form.NFD) @@ -45,7 +62,7 @@ data class LocalCustomFoodEntity( slugId = slugId, name = cleanName, defaultUnit = defaultUnit.code, - category = category?.name ?: "", + category = FoodCategory.encodeCategoryList(categories), updatedAt = System.currentTimeMillis() ) } diff --git a/app/src/main/java/com/example/data/local/LocalInventoryItemEntity.kt b/app/src/main/java/com/example/data/local/LocalInventoryItemEntity.kt new file mode 100644 index 0000000..88fea85 --- /dev/null +++ b/app/src/main/java/com/example/data/local/LocalInventoryItemEntity.kt @@ -0,0 +1,55 @@ +package com.example.data.local + +import androidx.room.Entity +import androidx.room.PrimaryKey +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.domain.IngredientMatcher +import java.util.UUID + +@Entity(tableName = "local_inventory_items") +data class LocalInventoryItemEntity( + @PrimaryKey val id: String, + val name: String, + val normalizedName: String, + val quantity: Double, + val unit: String = FoodUnit.G.code, + val category: String = FoodCategory.OTHER.code, + val location: String = StorageLocation.PANTRY.name, + val updatedAt: Long = System.currentTimeMillis() +) { + fun toDomain(): InventoryItem { + return InventoryItem( + id = id, + name = name, + normalizedName = normalizedName.ifBlank { IngredientMatcher.normalize(name) }, + quantity = quantity.coerceAtLeast(0.0), + unit = FoodUnit.fromCode(unit), + category = FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name), + location = StorageLocation.fromString(location), + updatedAt = updatedAt + ) + } + + companion object { + fun fromDomain(item: InventoryItem): LocalInventoryItemEntity { + val cleanName = item.name.trim().take(100) + val norm = item.normalizedName.ifBlank { IngredientMatcher.normalize(cleanName) } + val resolvedId = item.id.ifBlank { + "inv_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}" + } + return LocalInventoryItemEntity( + id = resolvedId, + name = cleanName, + normalizedName = norm, + quantity = item.quantity.coerceAtLeast(0.0), + unit = item.unit.code, + category = item.category.code, + location = item.location.name, + updatedAt = System.currentTimeMillis() + ) + } + } +} diff --git a/app/src/main/java/com/example/data/local/LocalMealDao.kt b/app/src/main/java/com/example/data/local/LocalMealDao.kt index 24077f0..9250f34 100644 --- a/app/src/main/java/com/example/data/local/LocalMealDao.kt +++ b/app/src/main/java/com/example/data/local/LocalMealDao.kt @@ -71,4 +71,73 @@ interface LocalMealDao { @Query("DELETE FROM local_food_preferences WHERE slugId = :slugId") suspend fun deleteFoodPreferenceBySlug(slugId: String) + + // ------------------------------------------------------------------------ + // Weekly Meal Planning + // ------------------------------------------------------------------------ + + @Query("SELECT * FROM local_planned_meals WHERE dateEpochDay BETWEEN :startEpochDay AND :endEpochDay ORDER BY dateEpochDay ASC, updatedAt ASC") + fun observePlannedMealsForRange(startEpochDay: Long, endEpochDay: Long): Flow> + + @Query("SELECT * FROM local_planned_meals WHERE id = :id LIMIT 1") + suspend fun getPlannedMealById(id: String): LocalPlannedMealEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertPlannedMeal(meal: LocalPlannedMealEntity) + + @Query("UPDATE local_planned_meals SET isConsumed = :consumed, updatedAt = :updatedAt WHERE id = :id") + suspend fun markPlannedMealConsumed(id: String, consumed: Boolean, updatedAt: Long = System.currentTimeMillis()) + + @Query("DELETE FROM local_planned_meals WHERE id = :id") + suspend fun deletePlannedMealById(id: String) + + // ------------------------------------------------------------------------ + // Kitchen Inventory (Stock) + // ------------------------------------------------------------------------ + + @Query("SELECT * FROM local_inventory_items ORDER BY name ASC") + fun observeAllInventoryItems(): Flow> + + @Query("SELECT * FROM local_inventory_items ORDER BY name ASC") + suspend fun getAllInventoryItemsOnce(): List + + @Query("SELECT * FROM local_inventory_items WHERE id = :id LIMIT 1") + suspend fun getInventoryItemById(id: String): LocalInventoryItemEntity? + + @Query("SELECT * FROM local_inventory_items WHERE normalizedName = :normalizedName AND unit = :unit LIMIT 1") + suspend fun findInventoryItemByNormalizedAndUnit(normalizedName: String, unit: String): LocalInventoryItemEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertInventoryItem(item: LocalInventoryItemEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertInventoryItems(items: List) + + @Query("DELETE FROM local_inventory_items WHERE id = :id") + suspend fun deleteInventoryItemById(id: String) + + // ------------------------------------------------------------------------ + // Manual Shopping List Items + // ------------------------------------------------------------------------ + + @Query("SELECT * FROM local_shopping_items ORDER BY isChecked ASC, updatedAt DESC") + fun observeAllManualShoppingItems(): Flow> + + @Query("SELECT * FROM local_shopping_items") + suspend fun getAllManualShoppingItemsOnce(): List + + @Query("SELECT * FROM local_shopping_items WHERE id = :id LIMIT 1") + suspend fun getManualShoppingItemById(id: String): LocalShoppingItemEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun upsertManualShoppingItem(item: LocalShoppingItemEntity) + + @Query("UPDATE local_shopping_items SET isChecked = :checked, updatedAt = :updatedAt WHERE id = :id") + suspend fun setManualShoppingItemChecked(id: String, checked: Boolean, updatedAt: Long = System.currentTimeMillis()) + + @Query("DELETE FROM local_shopping_items WHERE id = :id") + suspend fun deleteManualShoppingItemById(id: String) + + @Query("DELETE FROM local_shopping_items WHERE isChecked = 1") + suspend fun clearCheckedManualShoppingItems() } diff --git a/app/src/main/java/com/example/data/local/LocalPlannedMealEntity.kt b/app/src/main/java/com/example/data/local/LocalPlannedMealEntity.kt new file mode 100644 index 0000000..7f3e246 --- /dev/null +++ b/app/src/main/java/com/example/data/local/LocalPlannedMealEntity.kt @@ -0,0 +1,53 @@ +package com.example.data.local + +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.example.data.model.MealType +import com.example.data.model.PlannedMealEntry +import java.util.UUID + +@Entity(tableName = "local_planned_meals") +data class LocalPlannedMealEntity( + @PrimaryKey val id: String, + val dateEpochDay: Long, + val mealType: String, + val recipeId: String? = null, + val customTitle: String = "", + val servings: Double = 1.0, + val items: List = emptyList(), + val isConsumed: Boolean = false, + val updatedAt: Long = System.currentTimeMillis() +) { + fun toDomain(): PlannedMealEntry { + return PlannedMealEntry( + id = id, + dateEpochDay = dateEpochDay, + mealType = MealType.fromString(mealType), + recipeId = recipeId, + customTitle = customTitle, + servings = servings.coerceAtLeast(0.5), + itemsSerialized = items, + isConsumed = isConsumed, + updatedAt = updatedAt + ) + } + + companion object { + fun fromDomain(entry: PlannedMealEntry): LocalPlannedMealEntity { + val resolvedId = entry.id.ifBlank { + "plan_${entry.dateEpochDay}_${entry.mealType.name.lowercase()}_${UUID.randomUUID().toString().take(6)}" + } + return LocalPlannedMealEntity( + id = resolvedId, + dateEpochDay = entry.dateEpochDay, + mealType = entry.mealType.name, + recipeId = entry.recipeId?.takeIf { it.isNotBlank() }, + customTitle = entry.customTitle.trim().take(120), + servings = entry.servings.coerceAtLeast(0.5), + items = entry.itemsSerialized, + isConsumed = entry.isConsumed, + updatedAt = System.currentTimeMillis() + ) + } + } +} diff --git a/app/src/main/java/com/example/data/local/LocalShoppingItemEntity.kt b/app/src/main/java/com/example/data/local/LocalShoppingItemEntity.kt new file mode 100644 index 0000000..34e2d33 --- /dev/null +++ b/app/src/main/java/com/example/data/local/LocalShoppingItemEntity.kt @@ -0,0 +1,49 @@ +package com.example.data.local + +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.ManualShoppingItem +import java.util.UUID + +@Entity(tableName = "local_shopping_items") +data class LocalShoppingItemEntity( + @PrimaryKey val id: String, + val name: String, + val quantity: Double? = null, + val unit: String = FoodUnit.PORTION.code, + val category: String = FoodCategory.OTHER.code, + val isChecked: Boolean = false, + val updatedAt: Long = System.currentTimeMillis() +) { + fun toDomain(): ManualShoppingItem { + return ManualShoppingItem( + id = id, + name = name, + quantity = quantity?.takeIf { it > 0.0 }, + unit = FoodUnit.fromCode(unit), + category = FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name), + isChecked = isChecked, + updatedAt = updatedAt + ) + } + + companion object { + fun fromDomain(item: ManualShoppingItem): LocalShoppingItemEntity { + val cleanName = item.name.trim().take(100) + val resolvedId = item.id.ifBlank { + "shop_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}" + } + return LocalShoppingItemEntity( + id = resolvedId, + name = cleanName, + quantity = item.quantity?.takeIf { it > 0.0 }, + unit = item.unit.code, + category = item.category.code, + isChecked = item.isChecked, + updatedAt = System.currentTimeMillis() + ) + } + } +} diff --git a/app/src/main/java/com/example/data/model/FoodCategory.kt b/app/src/main/java/com/example/data/model/FoodCategory.kt index 5f22f2c..9c48dd0 100644 --- a/app/src/main/java/com/example/data/model/FoodCategory.kt +++ b/app/src/main/java/com/example/data/model/FoodCategory.kt @@ -203,11 +203,106 @@ enum class FoodCategory( } } + /** + * Parses single or multiple categories from internal comma-separated codes + * (e.g. "PROTEIN,VEGETABLE,BREAD") or human-readable '+'-separated labels + * (e.g. "Viande, poisson, œufs + Légumes + Pain"). + */ + fun parseCategoryList(raw: String?): List { + if (raw.isNullOrBlank()) return emptyList() + val trimmed = raw.trim() + + // First check exact single match (important because "Viande, poisson, œufs" contains commas) + fromCode(trimmed)?.let { return listOf(it) } + + val tokens = if (trimmed.contains("+")) { + trimmed.split("+") + } else if (trimmed.contains(",")) { + trimmed.split(",") + } else { + listOf(trimmed) + } + + val parsed = tokens.mapNotNull { fromCode(it) }.distinct() + return if (parsed.size > 1) { + parsed.filterNot { it == OTHER }.ifEmpty { listOf(OTHER) } + } else { + parsed + } + } + + fun encodeCategoryList(categories: List): String { + val cleaned = sanitizeSelection(categories) + return cleaned.joinToString(",") { it.code } + } + + fun formatCategoryLabels(categories: List): String { + val cleaned = sanitizeSelection(categories) + return cleaned.joinToString(" + ") { it.displayName } + } + + fun sanitizeSelection(categories: List): List { + val distinct = categories.distinct() + return when { + distinct.isEmpty() -> emptyList() + distinct.size > 1 -> distinct.filterNot { it == OTHER }.ifEmpty { listOf(OTHER) } + else -> distinct + } + } + + /** + * Toggles a category inside a multi-select food category list. + * Picking a concrete category removes OTHER; deselecting the last category falls back to OTHER. + */ + fun toggleCategorySelection( + current: List, + toggled: FoodCategory + ): List { + if (toggled == OTHER) { + return listOf(OTHER) + } + val withoutOther = current.filterNot { it == OTHER }.distinct() + return if (toggled in withoutOther) { + val remaining = withoutOther - toggled + remaining.ifEmpty { listOf(OTHER) } + } else { + withoutOther + toggled + } + } + private fun normalize(text: String): String { return Normalizer.normalize(text.lowercase(Locale.FRENCH).trim(), Normalizer.Form.NFD) .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "") } + fun inferCategoriesFromName( + name: String, + customCategoriesLookup: Map> = emptyMap() + ): List { + val trimmed = name.trim() + if (trimmed.isEmpty()) return listOf(OTHER) + + // 1. User-saved custom categories take highest precedence + val lowerExact = trimmed.lowercase(Locale.FRENCH) + customCategoriesLookup[lowerExact]?.takeIf { it.isNotEmpty() }?.let { return sanitizeSelection(it) } + + val norm = normalize(trimmed) + customCategoriesLookup.entries + .firstOrNull { normalize(it.key) == norm } + ?.value + ?.takeIf { it.isNotEmpty() } + ?.let { return sanitizeSelection(it) } + + // 2. Exact match from built-in catalog (supports multi-category dishes like Kebab, Pizza, Burger) + DefaultFoodCatalog.builtInFoods.firstOrNull { + normalize(it.name) == norm + }?.resolvedCategories()?.let { return it } + + // 3. Smart fallback to single-category French keyword inference + val singleLookup = customCategoriesLookup.mapValues { it.value.firstOrNull() ?: OTHER } + return listOf(inferFromName(trimmed, singleLookup)) + } + fun inferFromName( name: String, customCategoryLookup: Map = emptyMap() diff --git a/app/src/main/java/com/example/data/model/MealEntry.kt b/app/src/main/java/com/example/data/model/MealEntry.kt index 7b45b37..ff68014 100644 --- a/app/src/main/java/com/example/data/model/MealEntry.kt +++ b/app/src/main/java/com/example/data/model/MealEntry.kt @@ -18,10 +18,36 @@ data class MealFoodItem( val name: String, val weight: Double? = null, val unit: FoodUnit = FoodUnit.G, - val category: FoodCategory? = null + val category: FoodCategory? = null, + val categories: List = emptyList() ) { + private fun explicitCategories(): List { + val raw = if (categories.isNotEmpty()) categories else listOfNotNull(category) + return FoodCategory.sanitizeSelection(raw) + } + + fun resolvedCategories( + customCategoriesLookup: Map> = emptyMap() + ): List { + val explicit = explicitCategories() + return if (explicit.isNotEmpty()) { + explicit + } else { + FoodCategory.inferCategoriesFromName(name, customCategoriesLookup) + } + } + fun resolvedCategory(customCategoryLookup: Map = emptyMap()): FoodCategory { - return category ?: FoodCategory.inferFromName(name, customCategoryLookup) + val explicit = explicitCategories() + return explicit.firstOrNull() ?: FoodCategory.inferFromName(name, customCategoryLookup) + } + + fun withCategories(newCategories: List): MealFoodItem { + val cleaned = FoodCategory.sanitizeSelection(newCategories) + return copy( + category = cleaned.firstOrNull(), + categories = cleaned + ) } fun serialize(): String { @@ -31,8 +57,9 @@ data class MealFoodItem( } else { "" } - return if (category != null) { - "$cleanName|$weightStr|${unit.code}|${category.code}" + val explicit = explicitCategories() + return if (explicit.isNotEmpty()) { + "$cleanName|$weightStr|${unit.code}|${FoodCategory.encodeCategoryList(explicit)}" } else { "$cleanName|$weightStr|${unit.code}" } @@ -72,8 +99,14 @@ data class MealFoodItem( if (name.isEmpty()) return null val weight = parts.getOrNull(1)?.trim()?.replace(",", ".")?.toDoubleOrNull() val unit = FoodUnit.fromCode(parts.getOrNull(2) ?: "g") - val category = FoodCategory.fromCode(parts.getOrNull(3)) - return MealFoodItem(name = name, weight = weight, unit = unit, category = category) + val parsedCategories = FoodCategory.parseCategoryList(parts.getOrNull(3)) + return MealFoodItem( + name = name, + weight = weight, + unit = unit, + category = parsedCategories.firstOrNull(), + categories = parsedCategories + ) } } } @@ -84,8 +117,21 @@ data class CustomFoodEntry( val defaultUnit: String = FoodUnit.G.code, val category: String = "" ) { + fun resolvedCategories(): List { + return FoodCategory.parseCategoryList(category) + .ifEmpty { FoodCategory.inferCategoriesFromName(name) } + } + fun resolvedCategory(): FoodCategory { - return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name) + return resolvedCategories().first() + } + + companion object { + fun buildCategoriesLookup(customFoods: List): Map> { + return customFoods.associate { + it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategories() + } + } } } @@ -128,8 +174,17 @@ object DefaultFoodCatalog { data class CatalogFood( val name: String, val defaultUnit: FoodUnit = FoodUnit.G, - val category: FoodCategory = FoodCategory.OTHER - ) + val category: FoodCategory = FoodCategory.OTHER, + val categories: List = emptyList() + ) { + fun resolvedCategories(): List { + return if (categories.isNotEmpty()) { + FoodCategory.sanitizeSelection(categories) + } else { + listOf(category) + } + } + } val builtInFoods: List = listOf( // Viande, poisson, œufs (Rouge) @@ -226,6 +281,38 @@ object DefaultFoodCatalog { CatalogFood("Confiture", FoodUnit.PORTION, FoodCategory.PLEASURE), CatalogFood("Miel", FoodUnit.PORTION, FoodCategory.PLEASURE), + // Plats composés courants (multi-catégories) + CatalogFood( + name = "Kebab", + defaultUnit = FoodUnit.PORTION, + category = FoodCategory.PROTEIN, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD) + ), + CatalogFood( + name = "Burger", + defaultUnit = FoodUnit.PORTION, + category = FoodCategory.PROTEIN, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.BREAD, FoodCategory.CHEESE, FoodCategory.VEGETABLE) + ), + CatalogFood( + name = "Pizza", + defaultUnit = FoodUnit.PORTION, + category = FoodCategory.STARCH, + categories = listOf(FoodCategory.STARCH, FoodCategory.CHEESE, FoodCategory.VEGETABLE) + ), + CatalogFood( + name = "Quiche", + defaultUnit = FoodUnit.PORTION, + category = FoodCategory.PROTEIN, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.STARCH, FoodCategory.CHEESE) + ), + CatalogFood( + name = "Salade composée", + defaultUnit = FoodUnit.PORTION, + category = FoodCategory.VEGETABLE, + categories = listOf(FoodCategory.VEGETABLE, FoodCategory.PROTEIN, FoodCategory.FAT_SEASONING) + ), + // Boissons & divers CatalogFood("Café", FoodUnit.ML, FoodCategory.OTHER), CatalogFood("Thé vert", FoodUnit.ML, FoodCategory.OTHER) diff --git a/app/src/main/java/com/example/data/model/MealPlanModels.kt b/app/src/main/java/com/example/data/model/MealPlanModels.kt new file mode 100644 index 0000000..314a48f --- /dev/null +++ b/app/src/main/java/com/example/data/model/MealPlanModels.kt @@ -0,0 +1,137 @@ +package com.example.data.model + +import com.example.domain.IngredientMatcher +import java.util.UUID + +enum class StorageLocation(val displayName: String) { + FRIDGE("Frigo"), + FREEZER("Congélateur"), + PANTRY("Placard"); + + companion object { + fun fromString(raw: String?): StorageLocation { + if (raw.isNullOrBlank()) return PANTRY + val trimmed = raw.trim() + return entries.firstOrNull { + it.name.equals(trimmed, ignoreCase = true) || + it.displayName.equals(trimmed, ignoreCase = true) + } ?: PANTRY + } + } +} + +data class PlannedMealEntry( + val id: String = "", + val dateEpochDay: Long, + val mealType: MealType, + val recipeId: String? = null, + val customTitle: String = "", + val servings: Double = 1.0, + val itemsSerialized: List = emptyList(), + val isConsumed: Boolean = false, + val updatedAt: Long = System.currentTimeMillis() +) { + fun parsedItems(): List { + return itemsSerialized.mapNotNull { MealFoodItem.deserialize(it) } + } + + fun resolvedTitle(recipesById: Map): String { + val recipeTitle = recipeId?.let { recipesById[it]?.title } + return when { + !recipeTitle.isNullOrBlank() -> recipeTitle + customTitle.isNotBlank() -> customTitle + itemsSerialized.isNotEmpty() -> parsedItems().joinToString(", ") { it.name } + else -> mealType.displayName + } + } + + fun resolvedFoodItems(recipesById: Map): List { + val recipe = recipeId?.let { recipesById[it] } + return if (recipe != null) { + recipe.scaledIngredients(servings.coerceAtLeast(0.5)) + } else { + parsedItems() + } + } +} + +data class InventoryItem( + val id: String = "", + val name: String, + val normalizedName: String = IngredientMatcher.normalize(name), + val quantity: Double, + val unit: FoodUnit = FoodUnit.G, + val category: FoodCategory = FoodCategory.OTHER, + val location: StorageLocation = StorageLocation.PANTRY, + val updatedAt: Long = System.currentTimeMillis() +) { + fun formatQuantity(): String = IngredientMatcher.formatQuantity(quantity, unit) +} + +data class ManualShoppingItem( + val id: String = "", + val name: String, + val quantity: Double? = null, + val unit: FoodUnit = FoodUnit.PORTION, + val category: FoodCategory = FoodCategory.OTHER, + val isChecked: Boolean = false, + val updatedAt: Long = System.currentTimeMillis() +) { + fun formatQuantity(): String? = quantity?.takeIf { it > 0.0 }?.let { + IngredientMatcher.formatQuantity(it, unit) + } +} + +enum class ShoppingItemSource { + FROM_PLAN, + MANUAL, + BOTH +} + +data class ShoppingListItem( + val key: String, + val name: String, + val normalizedName: String, + val missingQuantity: Double?, + val requiredQuantity: Double?, + val inStockQuantity: Double, + val unit: FoodUnit, + val category: FoodCategory, + val source: ShoppingItemSource, + val manualItemId: String? = null, + val isChecked: Boolean = false, + val relatedMealsCount: Int = 0 +) { + fun formatMissingQuantity(): String? = missingQuantity?.takeIf { it > 0.0 }?.let { + IngredientMatcher.formatQuantity(it, unit) + } + + fun formatInStockQuantity(): String? = inStockQuantity.takeIf { it > 0.0 }?.let { + IngredientMatcher.formatQuantity(it, unit) + } +} + +data class ScannedReceiptItem( + val id: String = UUID.randomUUID().toString().take(8), + val rawLabel: String, + val name: String, + val quantity: Double, + val unit: FoodUnit = FoodUnit.PORTION, + val category: FoodCategory = FoodCategory.OTHER, + val location: StorageLocation = StorageLocation.PANTRY, + val selected: Boolean = true +) + +data class StockDeductionProposal( + val inventoryItem: InventoryItem, + val deductAmount: Double, + val remainingAfter: Double, + val selected: Boolean = true +) + +sealed interface ReceiptScanUiState { + data object Idle : ReceiptScanUiState + data object Scanning : ReceiptScanUiState + data class Preview(val items: List) : ReceiptScanUiState + data class Error(val message: String) : ReceiptScanUiState +} diff --git a/app/src/main/java/com/example/data/model/RecipeEntry.kt b/app/src/main/java/com/example/data/model/RecipeEntry.kt index a743741..4356a73 100644 --- a/app/src/main/java/com/example/data/model/RecipeEntry.kt +++ b/app/src/main/java/com/example/data/model/RecipeEntry.kt @@ -59,9 +59,11 @@ data class RecipeEntry( fun categoryEnum(): RecipeCategoryTag = RecipeCategoryTag.fromString(categoryTag) - fun dominantCategories(customCategories: Map = emptyMap()): List { + fun dominantCategories( + customCategoriesLookup: Map> = emptyMap() + ): List { return parsedIngredients() - .map { it.resolvedCategory(customCategories) } + .flatMap { it.resolvedCategories(customCategoriesLookup) } .distinct() .take(5) } diff --git a/app/src/main/java/com/example/data/repository/MealRepository.kt b/app/src/main/java/com/example/data/repository/MealRepository.kt index 5e2c172..936863d 100644 --- a/app/src/main/java/com/example/data/repository/MealRepository.kt +++ b/app/src/main/java/com/example/data/repository/MealRepository.kt @@ -5,16 +5,24 @@ import android.net.Uri import com.example.data.local.AppDatabase import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalFoodPreferenceEntity +import com.example.data.local.LocalInventoryItemEntity import com.example.data.local.LocalMealDao import com.example.data.local.LocalMealEntity +import com.example.data.local.LocalPlannedMealEntity import com.example.data.local.LocalRecipeEntity +import com.example.data.local.LocalShoppingItemEntity import com.example.data.model.CustomFoodEntry import com.example.data.model.FoodCategory import com.example.data.model.FoodPreferenceEntry import com.example.data.model.FoodPreferenceStatus import com.example.data.model.FoodUnit +import com.example.data.model.InventoryItem +import com.example.data.model.ManualShoppingItem import com.example.data.model.MealEntry +import com.example.data.model.PlannedMealEntry import com.example.data.model.RecipeEntry +import com.example.data.model.StorageLocation +import com.example.domain.IngredientMatcher import com.example.util.CsvImportResult import com.example.util.CsvImporter import com.example.util.ImageUtils @@ -114,12 +122,20 @@ class MealRepository( name: String, defaultUnit: FoodUnit, category: FoodCategory? = null + ): Result { + return saveCustomFood(name, defaultUnit, listOfNotNull(category)) + } + + suspend fun saveCustomFood( + name: String, + defaultUnit: FoodUnit, + categories: List ): Result { val trimmedName = name.trim().take(100) if (trimmedName.isBlank()) { return Result.failure(IllegalArgumentException("Food name is blank")) } - val localEntity = LocalCustomFoodEntity.create(trimmedName, defaultUnit, category) + val localEntity = LocalCustomFoodEntity.create(trimmedName, defaultUnit, categories) localMealDao.insertCustomFood(localEntity) return Result.success(localEntity.slugId) } @@ -229,7 +245,7 @@ class MealRepository( LocalCustomFoodEntity.create( name = item.name, defaultUnit = item.unit, - category = item.category ?: FoodCategory.inferFromName(item.name) + categories = item.resolvedCategories() ) } if (newCustomFoods.isNotEmpty()) { @@ -336,4 +352,163 @@ class MealRepository( preferencesCount = newPreferencesCount ) } + + // ------------------------------------------------------------------------ + // Weekly Meal Planning + // ------------------------------------------------------------------------ + + fun observePlannedMealsForWeek(startEpochDay: Long, endEpochDay: Long): Flow> { + return localMealDao.observePlannedMealsForRange(startEpochDay, endEpochDay).map { list -> + list.map { it.toDomain() } + } + } + + suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result { + val entity = LocalPlannedMealEntity.fromDomain(entry) + localMealDao.upsertPlannedMeal(entity) + return Result.success(entity.id) + } + + suspend fun markPlannedMealConsumed(id: String, consumed: Boolean = true): Result { + if (id.isBlank()) return Result.failure(IllegalArgumentException("Blank planned meal ID")) + localMealDao.markPlannedMealConsumed(id, consumed) + return Result.success(Unit) + } + + suspend fun deletePlannedMeal(id: String): Result { + localMealDao.deletePlannedMealById(id) + return Result.success(Unit) + } + + // ------------------------------------------------------------------------ + // Kitchen Inventory (Stock) + // ------------------------------------------------------------------------ + + fun observeInventory(): Flow> { + return localMealDao.observeAllInventoryItems().map { list -> + list.map { it.toDomain() } + } + } + + suspend fun getInventorySnapshot(): List { + return localMealDao.getAllInventoryItemsOnce().map { it.toDomain() } + } + + suspend fun upsertInventoryItem(item: InventoryItem): Result { + val cleanName = item.name.trim() + if (cleanName.isBlank()) { + return Result.failure(IllegalArgumentException("Le nom de l'aliment est vide")) + } + val entity = LocalInventoryItemEntity.fromDomain( + item.copy( + name = cleanName, + normalizedName = IngredientMatcher.normalize(cleanName) + ) + ) + localMealDao.upsertInventoryItem(entity) + return Result.success(entity.id) + } + + /** + * Adds quantity into stock, automatically merging with an existing stock entry if one + * already exists with the same normalized name and unit. + */ + suspend fun addOrMergeInventoryItem( + name: String, + quantityToAdd: Double, + unit: FoodUnit, + category: FoodCategory, + location: StorageLocation + ): Result { + val cleanName = name.trim() + if (cleanName.isBlank() || quantityToAdd <= 0.0) { + return Result.failure(IllegalArgumentException("Article invalide")) + } + val norm = IngredientMatcher.normalize(cleanName) + val existing = localMealDao.findInventoryItemByNormalizedAndUnit(norm, unit.code) + return if (existing != null) { + val updated = existing.copy( + quantity = existing.quantity + quantityToAdd, + category = category.code, + location = location.name, + updatedAt = System.currentTimeMillis() + ) + localMealDao.upsertInventoryItem(updated) + Result.success(updated.id) + } else { + val created = LocalInventoryItemEntity.fromDomain( + InventoryItem( + name = cleanName, + normalizedName = norm, + quantity = quantityToAdd, + unit = unit, + category = category, + location = location + ) + ) + localMealDao.upsertInventoryItem(created) + Result.success(created.id) + } + } + + suspend fun adjustInventoryQuantity(itemId: String, delta: Double): Result { + val existing = localMealDao.getInventoryItemById(itemId) + ?: return Result.failure(NoSuchElementException("Article introuvable")) + val newQty = (existing.quantity + delta).coerceAtLeast(0.0) + if (newQty <= 0.0001) { + localMealDao.deleteInventoryItemById(itemId) + } else { + localMealDao.upsertInventoryItem( + existing.copy( + quantity = Math.round(newQty * 10.0) / 10.0, + updatedAt = System.currentTimeMillis() + ) + ) + } + return Result.success(Unit) + } + + suspend fun deleteInventoryItem(itemId: String): Result { + localMealDao.deleteInventoryItemById(itemId) + return Result.success(Unit) + } + + // ------------------------------------------------------------------------ + // Manual Shopping List Items + // ------------------------------------------------------------------------ + + fun observeManualShoppingItems(): Flow> { + return localMealDao.observeAllManualShoppingItems().map { list -> + list.map { it.toDomain() } + } + } + + suspend fun getManualShoppingItemsSnapshot(): List { + return localMealDao.getAllManualShoppingItemsOnce().map { it.toDomain() } + } + + suspend fun upsertManualShoppingItem(item: ManualShoppingItem): Result { + val cleanName = item.name.trim() + if (cleanName.isBlank()) { + return Result.failure(IllegalArgumentException("Le nom de l'article est vide")) + } + val entity = LocalShoppingItemEntity.fromDomain(item.copy(name = cleanName)) + localMealDao.upsertManualShoppingItem(entity) + return Result.success(entity.id) + } + + suspend fun setManualShoppingItemChecked(itemId: String, checked: Boolean): Result { + localMealDao.setManualShoppingItemChecked(itemId, checked) + return Result.success(Unit) + } + + suspend fun deleteManualShoppingItem(itemId: String): Result { + localMealDao.deleteManualShoppingItemById(itemId) + return Result.success(Unit) + } + + suspend fun clearCheckedManualShoppingItems(): Result { + localMealDao.clearCheckedManualShoppingItems() + return Result.success(Unit) + } } diff --git a/app/src/main/java/com/example/domain/DailyBenchmarkAnalyzer.kt b/app/src/main/java/com/example/domain/DailyBenchmarkAnalyzer.kt index 0517b7d..d299d43 100644 --- a/app/src/main/java/com/example/domain/DailyBenchmarkAnalyzer.kt +++ b/app/src/main/java/com/example/domain/DailyBenchmarkAnalyzer.kt @@ -76,8 +76,14 @@ object DailyBenchmarkAnalyzer { targetMealType: MealType, customCategoryLookup: Map = emptyMap(), today: LocalDate = LocalDate.now(), - zoneId: ZoneId = ZoneId.systemDefault() + zoneId: ZoneId = ZoneId.systemDefault(), + customCategoriesLookup: Map> = emptyMap() ): DailyBenchmarkGap { + val effectiveLookup: Map> = if (customCategoriesLookup.isNotEmpty()) { + customCategoriesLookup + } else { + customCategoryLookup.mapValues { listOf(it.value) } + } val todayMeals = meals.filter { meal -> Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId).toLocalDate() == today } @@ -85,9 +91,10 @@ object DailyBenchmarkAnalyzer { val counts = mutableMapOf() todayMeals.forEach { meal -> meal.parsedFoodItems().forEach { item -> - val cat = item.resolvedCategory(customCategoryLookup) - if (cat.showInBenchmarks) { - counts[cat] = (counts[cat] ?: 0) + 1 + item.resolvedCategories(effectiveLookup).forEach { cat -> + if (cat.showInBenchmarks) { + counts[cat] = (counts[cat] ?: 0) + 1 + } } } } diff --git a/app/src/main/java/com/example/domain/IngredientMatcher.kt b/app/src/main/java/com/example/domain/IngredientMatcher.kt new file mode 100644 index 0000000..b186c21 --- /dev/null +++ b/app/src/main/java/com/example/domain/IngredientMatcher.kt @@ -0,0 +1,83 @@ +package com.example.domain + +import com.example.data.model.FoodUnit +import java.text.Normalizer +import java.util.Locale + +/** + * Normalizes French ingredient names and compares items across recipes, inventory, + * shopping lists, and scanned grocery receipts. + */ +object IngredientMatcher { + + private val leadingArticlesRegex = Regex("""^(de la |de l'|du |des |de |d'|le |la |les |l'|un |une )""") + private val nonAlnumRegex = Regex("""[^a-z0-9\s]+""") + private val multiSpaceRegex = Regex("""\s+""") + + // French words ending in 's' or 'x' that are singular by nature + private val invariantSingulars = setOf( + "mais", "riz", "pois", "radis", "cassis", "ananas", "jus", "houmous", + "couscous", "tacos", "chorizo", "noix", "choux", "persil", "brebis", + "saumon", "thon", "pain", "lait", "miel", "sel" + ) + + fun normalize(raw: String): String { + val lower = Normalizer.normalize(raw.lowercase(Locale.FRENCH).trim(), Normalizer.Form.NFD) + .replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "") + .replace("œ", "oe") + .replace("æ", "ae") + + val strippedArticles = leadingArticlesRegex.replace(lower, "") + val cleaned = nonAlnumRegex.replace(strippedArticles, " ") + .replace(multiSpaceRegex, " ") + .trim() + + if (cleaned.isEmpty()) return "" + + return cleaned.split(" ") + .filter { it.isNotBlank() } + .joinToString(" ") { singularizeToken(it) } + } + + private fun singularizeToken(token: String): String { + if (token.length < 4 || token in invariantSingulars) return token + return when { + token.endsWith("eaux") && token.length > 5 -> token.dropLast(1) // poireaux -> poireau + token.endsWith("aux") && token.length > 5 -> token.dropLast(2) + "l" // cereaux -> cereal + token.endsWith("s") && !token.endsWith("ss") -> token.dropLast(1) + token.endsWith("x") && token != "noix" -> token.dropLast(1) + else -> token + } + } + + fun matches(nameA: String, nameB: String): Boolean { + val normA = normalize(nameA) + val normB = normalize(nameB) + if (normA.isEmpty() || normB.isEmpty()) return false + return normA == normB + } + + fun areUnitsCompatible(unitA: FoodUnit, unitB: FoodUnit): Boolean { + return unitA == unitB + } + + fun formatQuantity(quantity: Double?, unit: FoodUnit): String { + if (quantity == null || quantity <= 0.0) return unit.label + val rounded = if (unit == FoodUnit.PORTION) { + Math.round(quantity * 10.0) / 10.0 + } else { + Math.round(quantity * 10.0) / 10.0 + } + val numStr = if (rounded % 1.0 == 0.0) { + rounded.toInt().toString() + } else { + String.format(Locale.FRENCH, "%.1f", rounded) + } + return if (unit == FoodUnit.PORTION) { + val plural = if (rounded > 1.0) "portions" else "portion" + "$numStr $plural" + } else { + "$numStr ${unit.label}" + } + } +} diff --git a/app/src/main/java/com/example/domain/ReceiptScannerAnalyzer.kt b/app/src/main/java/com/example/domain/ReceiptScannerAnalyzer.kt new file mode 100644 index 0000000..a76c54e --- /dev/null +++ b/app/src/main/java/com/example/domain/ReceiptScannerAnalyzer.kt @@ -0,0 +1,165 @@ +package com.example.domain + +import android.graphics.Bitmap +import android.util.Log +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.ScannedReceiptItem +import com.example.data.model.StorageLocation +import com.google.firebase.Firebase +import com.google.firebase.ai.ai +import com.google.firebase.ai.type.Schema +import com.google.firebase.ai.type.content +import com.google.firebase.ai.type.generationConfig +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.withTimeout +import org.json.JSONObject +import java.util.UUID + +/** + * Analyzes supermarket receipt photos using Firebase AI Logic (gemini-3.8-flash multimodal) + * with strict JSON Schema output, converting abbreviated French receipt lines into clean + * edible food items ready for user review before adding to Stock. + */ +class ReceiptScannerAnalyzer { + + private val allowedCategoryCodes = FoodCategory.entries.map { it.code } + private val allowedUnitCodes = listOf("g", "ml", "portion") + private val allowedLocations = StorageLocation.entries.map { it.name } + + private val responseSchema by lazy { + val itemSchema = Schema.obj( + properties = mapOf( + "rawLabel" to Schema.string(description = "Libellé brut tel qu'imprimé sur le ticket"), + "name" to Schema.string(description = "Nom français propre, lisible et normalisé de l'aliment (ex: 'Lait demi-écrémé', 'Blanc de poulet', 'Carottes')"), + "quantity" to Schema.double(description = "Quantité numérique réaliste dans l'unité choisie (ex: 500 pour 500 g, 1000 pour 1 L en ml, 6 pour 6 œufs en portion)"), + "unit" to Schema.enumeration( + values = allowedUnitCodes, + description = "Unité : g (grammes), ml (millilitres) ou portion (pièces/unités)" + ), + "category" to Schema.enumeration( + values = allowedCategoryCodes, + description = "Catégorie alimentaire exacte parmi les codes fournis" + ), + "location" to Schema.enumeration( + values = allowedLocations, + description = "Emplacement de conservation conseillé : FRIDGE, FREEZER ou PANTRY" + ) + ) + ) + + Schema.obj( + properties = mapOf( + "items" to Schema.array( + items = itemSchema, + description = "Liste des articles alimentaires reconnus sur le ticket (ignorer tout le non-alimentaire, sacs, remises, totaux, TVA)" + ) + ) + ) + } + + private val model by lazy { + val config = generationConfig { + responseMimeType = "application/json" + responseSchema = this@ReceiptScannerAnalyzer.responseSchema + temperature = 0.2f + } + Firebase.ai.generativeModel( + modelName = "gemini-3.8-flash", + generationConfig = config + ) + } + + suspend fun analyzeReceipt(bitmap: Bitmap): Result> { + val categoriesHelp = FoodCategory.entries.joinToString("\n") { "- ${it.code}: ${it.displayName}" } + val prompt = """ +Analyse cette photo de ticket de caisse et extrais UNIQUEMENT les articles alimentaires achetés. + +RÈGLES STRICTES : +1. Ignore totalement les lignes non alimentaires (produits ménagers, hygiène, sacs plastique, consignes, remises fidélité, sous-totaux, TVA, carte bancaire, date, adresse du magasin). +2. Traduis les libellés abrégés des tickets français en noms français clairs et simples (ex: "LAIT 1/2 ECR 1L" -> "Lait demi-écrémé", "FILET POUL 400G" -> "Blanc de poulet", "YAOURT NAT X4" -> "Yaourt nature"). +3. Convertis toujours les quantités dans l'une de ces 3 unités exactes : + - "g" pour les solides pesés (convertis les kg en g : 1,2 kg -> 1200 g) + - "ml" pour les liquides (convertis les L et cL en ml : 1 L -> 1000 ml, 25 cL -> 250 ml) + - "portion" pour les articles vendus à l'unité ou en pack (ex: 6 œufs -> 6 portion, 4 yaourts -> 4 portion, 1 baguette -> 1 portion). Si aucun poids n'est visible, estime 1 portion. +4. Choisis la catégorie la plus juste parmi ces codes : +$categoriesHelp +5. Choisis l'emplacement conseillé : FRIDGE (produits frais, viande, fromage, yaourts, légumes frais), FREEZER (surgelés, glaces), PANTRY (sec, pâtes, riz, conserves, huiles, pain, fruits à coque, chocolat). +6. Si l'image n'est pas un ticket de caisse ou ne contient aucun aliment lisible, renvoie une liste items vide. + """.trimIndent() + + return try { + val response = withTimeout(60_000L) { + model.generateContent( + content { + image(bitmap) + text(prompt) + } + ) + } + val jsonText = response.text + if (jsonText.isNullOrBlank()) { + Result.failure(IllegalStateException("L'analyse du ticket n'a renvoyé aucune donnée. Réessayez avec une photo plus nette.")) + } else { + val parsed = parseReceiptJson(jsonText) + if (parsed.isEmpty()) { + Result.failure(IllegalStateException("Aucun aliment n'a été reconnu sur cette image. Essayez de cadrer le ticket bien à plat et éclairé.")) + } else { + Result.success(parsed) + } + } + } catch (e: TimeoutCancellationException) { + Log.e(TAG, "Receipt scan timed out", e) + Result.failure( + IllegalStateException("L'analyse du ticket a dépassé le délai (60 s). Vérifiez votre connexion et réessayez.") + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.e(TAG, "Receipt scan failed", e) + Result.failure( + IllegalStateException( + e.localizedMessage ?: "Impossible d'analyser ce ticket pour le moment." + ) + ) + } + } + + companion object { + private const val TAG = "ReceiptScannerAnalyzer" + + fun parseReceiptJson(jsonString: String): List { + val root = JSONObject(jsonString) + val itemsArr = root.optJSONArray("items") ?: return emptyList() + val results = mutableListOf() + + for (i in 0 until itemsArr.length()) { + val obj = itemsArr.optJSONObject(i) ?: continue + val name = obj.optString("name", "").trim() + if (name.isBlank()) continue + val rawLabel = obj.optString("rawLabel", name).trim().ifBlank { name } + val rawQty = obj.optDouble("quantity", 1.0) + val quantity = if (rawQty.isNaN() || rawQty <= 0.0) 1.0 else rawQty + val unit = FoodUnit.fromCode(obj.optString("unit", "portion")) + val category = FoodCategory.fromCode(obj.optString("category")) + ?: FoodCategory.inferFromName(name) + val location = StorageLocation.fromString(obj.optString("location", "PANTRY")) + + results.add( + ScannedReceiptItem( + id = "scan_${i}_${UUID.randomUUID().toString().take(6)}", + rawLabel = rawLabel, + name = name, + quantity = quantity, + unit = unit, + category = category, + location = location, + selected = true + ) + ) + } + return results + } + } +} diff --git a/app/src/main/java/com/example/domain/ShoppingListCalculator.kt b/app/src/main/java/com/example/domain/ShoppingListCalculator.kt new file mode 100644 index 0000000..b484f73 --- /dev/null +++ b/app/src/main/java/com/example/domain/ShoppingListCalculator.kt @@ -0,0 +1,241 @@ +package com.example.domain + +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.RecipeEntry +import com.example.data.model.ShoppingItemSource +import com.example.data.model.ShoppingListItem +import com.example.data.model.StockDeductionProposal +import java.util.Locale +import kotlin.math.max +import kotlin.math.min + +/** + * Pure Kotlin domain engine computing weekly shopping needs (planned meals minus available stock, + * merged with manual items) and stock deduction proposals when meals are eaten. + */ +object ShoppingListCalculator { + + private data class NeedKey( + val normalizedName: String, + val unit: FoodUnit + ) + + private data class AggregatedNeed( + val displayName: String, + val normalizedName: String, + val unit: FoodUnit, + val category: FoodCategory, + val requiredQuantity: Double?, + val mealsCount: Int + ) + + fun computeShoppingList( + plannedMeals: List, + recipesById: Map, + inventory: List, + manualItems: List, + checkedPlanKeys: Set = emptySet(), + customCategoriesLookup: Map> = emptyMap() + ): List { + // 1. Aggregate ingredients across all non-consumed planned meals for the week + val aggregatedNeeds = linkedMapOf() + + plannedMeals + .filterNot { it.isConsumed } + .forEach { planned -> + val ingredients = planned.resolvedFoodItems(recipesById) + ingredients.forEach { food -> + val norm = IngredientMatcher.normalize(food.name) + if (norm.isBlank()) return@forEach + val key = NeedKey(norm, food.unit) + val resolvedCat = food.resolvedCategories(customCategoriesLookup).firstOrNull() + ?: FoodCategory.inferFromName(food.name) + val existing = aggregatedNeeds[key] + val itemQty = food.weight?.takeIf { it > 0.0 } + + if (existing == null) { + aggregatedNeeds[key] = AggregatedNeed( + displayName = food.name.trim(), + normalizedName = norm, + unit = food.unit, + category = resolvedCat, + requiredQuantity = itemQty, + mealsCount = 1 + ) + } else { + val combinedQty = when { + existing.requiredQuantity != null && itemQty != null -> existing.requiredQuantity + itemQty + existing.requiredQuantity != null -> existing.requiredQuantity + else -> itemQty + } + aggregatedNeeds[key] = existing.copy( + requiredQuantity = combinedQty, + mealsCount = existing.mealsCount + 1 + ) + } + } + } + + // 2. Index available stock by (normalizedName, unit) and by normalizedName (for unquantified items) + val stockByKey = mutableMapOf() + val stockExistsByName = mutableSetOf() + inventory.forEach { item -> + val norm = item.normalizedName.ifBlank { IngredientMatcher.normalize(item.name) } + if (norm.isNotBlank() && item.quantity > 0.0) { + stockExistsByName.add(norm) + val key = NeedKey(norm, item.unit) + stockByKey[key] = (stockByKey[key] ?: 0.0) + item.quantity + } + } + + // 3. Subtract stock from planned needs + val resultMap = linkedMapOf() + aggregatedNeeds.forEach { (needKey, need) -> + val available = stockByKey[needKey] ?: 0.0 + val itemKey = buildPlanItemKey(need.normalizedName, need.unit) + + if (need.requiredQuantity != null) { + val missing = roundClean(need.requiredQuantity - available, need.unit) + if (missing > 0.0) { + resultMap[itemKey] = ShoppingListItem( + key = itemKey, + name = need.displayName, + normalizedName = need.normalizedName, + missingQuantity = missing, + requiredQuantity = roundClean(need.requiredQuantity, need.unit), + inStockQuantity = roundClean(available, need.unit), + unit = need.unit, + category = need.category, + source = ShoppingItemSource.FROM_PLAN, + manualItemId = null, + isChecked = itemKey in checkedPlanKeys, + relatedMealsCount = need.mealsCount + ) + } + } else { + // Unquantified planned item: include unless already present in stock + if (need.normalizedName !in stockExistsByName) { + resultMap[itemKey] = ShoppingListItem( + key = itemKey, + name = need.displayName, + normalizedName = need.normalizedName, + missingQuantity = null, + requiredQuantity = null, + inStockQuantity = 0.0, + unit = need.unit, + category = need.category, + source = ShoppingItemSource.FROM_PLAN, + manualItemId = null, + isChecked = itemKey in checkedPlanKeys, + relatedMealsCount = need.mealsCount + ) + } + } + } + + // 4. Merge manual shopping items + manualItems.forEach { manual -> + val norm = IngredientMatcher.normalize(manual.name) + val matchingPlanKey = buildPlanItemKey(norm, manual.unit) + val existingPlan = resultMap[matchingPlanKey] + + if (existingPlan != null) { + val combinedMissing = when { + existingPlan.missingQuantity != null && manual.quantity != null -> + roundClean(existingPlan.missingQuantity + manual.quantity, manual.unit) + manual.quantity != null -> roundClean(manual.quantity, manual.unit) + else -> existingPlan.missingQuantity + } + resultMap[matchingPlanKey] = existingPlan.copy( + missingQuantity = combinedMissing, + source = ShoppingItemSource.BOTH, + manualItemId = manual.id, + isChecked = manual.isChecked || existingPlan.isChecked + ) + } else { + val manualKey = "manual_${manual.id}" + val available = stockByKey[NeedKey(norm, manual.unit)] ?: 0.0 + resultMap[manualKey] = ShoppingListItem( + key = manualKey, + name = manual.name.trim(), + normalizedName = norm, + missingQuantity = manual.quantity?.takeIf { it > 0.0 }?.let { roundClean(it, manual.unit) }, + requiredQuantity = manual.quantity?.takeIf { it > 0.0 }?.let { roundClean(it, manual.unit) }, + inStockQuantity = roundClean(available, manual.unit), + unit = manual.unit, + category = manual.category, + source = ShoppingItemSource.MANUAL, + manualItemId = manual.id, + isChecked = manual.isChecked, + relatedMealsCount = 0 + ) + } + } + + // 5. Sort cleanly: unchecked first, then FoodCategory order, then alphabetical + return resultMap.values.sortedWith( + compareBy { it.isChecked } + .thenBy { it.category.ordinal } + .thenBy { it.name.lowercase(Locale.FRENCH) } + ) + } + + /** + * Proposes stock deductions for foods just eaten in a meal or marked consumed from the weekly plan. + */ + fun computeStockDeductionProposals( + eatenItems: List, + inventory: List + ): List { + if (eatenItems.isEmpty() || inventory.isEmpty()) return emptyList() + + // Aggregate eaten quantities per (normalizedName, unit) + val eatenByKey = linkedMapOf() + eatenItems.forEach { food -> + val norm = IngredientMatcher.normalize(food.name) + if (norm.isBlank()) return@forEach + val qty = food.weight?.takeIf { it > 0.0 } ?: if (food.unit == FoodUnit.PORTION) 1.0 else 0.0 + if (qty <= 0.0) return@forEach + val key = NeedKey(norm, food.unit) + eatenByKey[key] = (eatenByKey[key] ?: 0.0) + qty + } + + val proposals = mutableListOf() + inventory.forEach { stockItem -> + if (stockItem.quantity <= 0.0) return@forEach + val stockNorm = stockItem.normalizedName.ifBlank { IngredientMatcher.normalize(stockItem.name) } + val matchedQty = eatenByKey[NeedKey(stockNorm, stockItem.unit)] ?: return@forEach + val deduct = roundClean(min(stockItem.quantity, matchedQty), stockItem.unit) + if (deduct > 0.0) { + val remaining = roundClean(max(0.0, stockItem.quantity - deduct), stockItem.unit) + proposals.add( + StockDeductionProposal( + inventoryItem = stockItem, + deductAmount = deduct, + remainingAfter = remaining, + selected = true + ) + ) + } + } + return proposals.sortedBy { it.inventoryItem.name.lowercase(Locale.FRENCH) } + } + + fun buildPlanItemKey(normalizedName: String, unit: FoodUnit): String { + return "plan_${normalizedName}_${unit.code}" + } + + private fun roundClean(value: Double, unit: FoodUnit): Double { + if (value <= 0.0) return 0.0 + return if (unit == FoodUnit.PORTION) { + Math.round(value * 10.0) / 10.0 + } else { + Math.round(value * 10.0) / 10.0 + } + } +} diff --git a/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt b/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt index 9039796..ceada6d 100644 --- a/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt +++ b/app/src/main/java/com/example/domain/WeeklyStatsCalculator.kt @@ -15,8 +15,14 @@ object WeeklyStatsCalculator { fun computeWeeklyStats( meals: List, zoneId: ZoneId = ZoneId.systemDefault(), - customCategoryLookup: Map = emptyMap() + customCategoryLookup: Map = emptyMap(), + customCategoriesLookup: Map> = emptyMap() ): WeeklyStats { + val effectiveLookup: Map> = if (customCategoriesLookup.isNotEmpty()) { + customCategoriesLookup + } else { + customCategoryLookup.mapValues { listOf(it.value) } + } val todayLocalDate = LocalDate.now(zoneId) val startOfPeriod = todayLocalDate.minusDays(6) val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli() @@ -77,8 +83,9 @@ object WeeklyStatsCalculator { val categoryCounts = mutableMapOf() recentMeals.forEach { meal -> meal.parsedFoodItems().forEach { item -> - val cat = item.resolvedCategory(customCategoryLookup) - categoryCounts[cat] = (categoryCounts[cat] ?: 0) + 1 + item.resolvedCategories(effectiveLookup).forEach { cat -> + categoryCounts[cat] = (categoryCounts[cat] ?: 0) + 1 + } } } diff --git a/app/src/main/java/com/example/ui/common/FoodCategoryUi.kt b/app/src/main/java/com/example/ui/common/FoodCategoryUi.kt index 53bca3a..082b5b4 100644 --- a/app/src/main/java/com/example/ui/common/FoodCategoryUi.kt +++ b/app/src/main/java/com/example/ui/common/FoodCategoryUi.kt @@ -17,6 +17,7 @@ import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -29,6 +30,8 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.luminance import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -68,10 +71,33 @@ fun FoodCategoryColorDot( .size(size) .clip(CircleShape) .background(fill) - .border(width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp, color = borderColor, shape = CircleShape) + .border( + width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp, + color = borderColor, + shape = CircleShape + ) ) } +@Composable +fun FoodCategoryColorDotsRow( + categories: List, + modifier: Modifier = Modifier, + dotSize: Dp = 8.dp, + spacing: Dp = 3.dp +) { + val effective = FoodCategory.sanitizeSelection(categories).ifEmpty { listOf(FoodCategory.OTHER) } + Row( + modifier = modifier, + horizontalArrangement = Arrangement.spacedBy(spacing), + verticalAlignment = Alignment.CenterVertically + ) { + effective.forEach { cat -> + FoodCategoryColorDot(category = cat, size = dotSize) + } + } +} + @Composable fun FoodCategoryBadge( text: String, @@ -79,15 +105,53 @@ fun FoodCategoryBadge( modifier: Modifier = Modifier, onClick: (() -> Unit)? = null, onRemove: (() -> Unit)? = null +) { + FoodCategoryBadge( + text = text, + categories = listOf(category), + modifier = modifier, + onClick = onClick, + onRemove = onRemove + ) +} + +@Composable +fun FoodCategoryBadge( + text: String, + categories: List, + modifier: Modifier = Modifier, + onClick: (() -> Unit)? = null, + onRemove: (() -> Unit)? = null ) { val isDark = isSatieaDarkTheme() + val effectiveCategories = FoodCategory.sanitizeSelection(categories).ifEmpty { listOf(FoodCategory.OTHER) } + val isMulti = effectiveCategories.size > 1 + val primaryCategory = effectiveCategories.first() val shape = RoundedCornerShape(11.dp) + val containerColor = if (isMulti) { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = if (isDark) 0.72f else 0.55f) + } else { + primaryCategory.badgeContainerColor(isDark) + } + val borderColor = if (isMulti) { + MaterialTheme.colorScheme.outlineVariant.copy(alpha = if (isDark) 0.85f else 0.9f) + } else { + primaryCategory.badgeBorderColor(isDark) + } + val textColor = if (isMulti) { + MaterialTheme.colorScheme.onSurface + } else { + primaryCategory.badgeTextColor(isDark) + } + val accessibilityDesc = "$text, catégories : ${effectiveCategories.joinToString(", ") { it.displayName }}" + Surface( shape = shape, - color = category.badgeContainerColor(isDark), - border = BorderStroke(1.dp, category.badgeBorderColor(isDark)), + color = containerColor, + border = BorderStroke(1.dp, borderColor), modifier = modifier + .semantics { contentDescription = accessibilityDesc } .clip(shape) .then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier) ) { @@ -100,12 +164,16 @@ fun FoodCategoryBadge( ), verticalAlignment = Alignment.CenterVertically ) { - FoodCategoryColorDot(category = category, size = 8.dp) + FoodCategoryColorDotsRow( + categories = effectiveCategories, + dotSize = 8.dp, + spacing = 3.dp + ) Spacer(modifier = Modifier.width(6.dp)) Text( text = text, style = MaterialTheme.typography.labelMedium, - color = category.badgeTextColor(isDark), + color = textColor, fontWeight = FontWeight.SemiBold ) if (onRemove != null) { @@ -113,7 +181,7 @@ fun FoodCategoryBadge( Icon( imageVector = Icons.Default.Close, contentDescription = "Retirer $text", - tint = category.badgeTextColor(isDark).copy(alpha = 0.8f), + tint = textColor.copy(alpha = 0.8f), modifier = Modifier .size(18.dp) .clip(CircleShape) @@ -130,8 +198,24 @@ fun FoodCategorySelectorRow( selectedCategory: FoodCategory, onCategorySelected: (FoodCategory) -> Unit, modifier: Modifier = Modifier +) { + FoodCategorySelectorRow( + selectedCategories = listOf(selectedCategory), + onCategoryToggled = onCategorySelected, + modifier = modifier + ) +} + +@Composable +fun FoodCategorySelectorRow( + selectedCategories: List, + onCategoryToggled: (FoodCategory) -> Unit, + modifier: Modifier = Modifier ) { val isDark = isSatieaDarkTheme() + val effectiveSelected = FoodCategory.sanitizeSelection(selectedCategories) + .ifEmpty { listOf(FoodCategory.OTHER) } + .toSet() LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -140,10 +224,10 @@ fun FoodCategorySelectorRow( .testTag("food_category_selector_row") ) { items(FoodCategory.entries, key = { it.name }) { category -> - val isSelected = category == selectedCategory + val isSelected = category in effectiveSelected val shape = RoundedCornerShape(12.dp) val containerColor = if (isSelected) { - category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.34f else 0.24f) + category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.48f else 0.32f) } else { MaterialTheme.colorScheme.surface } @@ -163,7 +247,7 @@ fun FoodCategorySelectorRow( border = BorderStroke(if (isSelected) 1.5.dp else 1.dp, borderColor), modifier = Modifier .clip(shape) - .clickable { onCategorySelected(category) } + .clickable { onCategoryToggled(category) } .testTag("food_category_chip_${category.name.lowercase()}") ) { Row( @@ -178,6 +262,15 @@ fun FoodCategorySelectorRow( color = if (isSelected) category.badgeTextColor(isDark) else MaterialTheme.colorScheme.onSurfaceVariant, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium ) + if (isSelected && category != FoodCategory.OTHER) { + Spacer(modifier = Modifier.width(4.dp)) + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = category.badgeTextColor(isDark), + modifier = Modifier.size(13.dp) + ) + } } } } diff --git a/app/src/main/java/com/example/ui/common/UnsavedChangesDialog.kt b/app/src/main/java/com/example/ui/common/UnsavedChangesDialog.kt new file mode 100644 index 0000000..df4d4d2 --- /dev/null +++ b/app/src/main/java/com/example/ui/common/UnsavedChangesDialog.kt @@ -0,0 +1,83 @@ +package com.example.ui.common + +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.EditNote +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +/** + * Reusable Material 3 confirmation dialog shown when the user tries to leave a form + * (meal entry or recipe editor) that has unsaved changes. + */ +@Composable +fun UnsavedChangesDiscardDialog( + title: String = "Quitter sans enregistrer ?", + message: String = "Vos modifications en cours ne sont pas encore enregistrées. Si vous quittez maintenant, elles seront perdues.", + onContinueEditing: () -> Unit, + onConfirmDiscard: () -> Unit +) { + AlertDialog( + onDismissRequest = onContinueEditing, + modifier = Modifier.testTag("unsaved_changes_dialog"), + shape = RoundedCornerShape(22.dp), + icon = { + Icon( + imageVector = Icons.Default.EditNote, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(28.dp) + ) + }, + title = { + Text( + text = title, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + text = { + Text( + text = message, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + confirmButton = { + Button( + onClick = onContinueEditing, + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary + ), + modifier = Modifier.testTag("unsaved_continue_button") + ) { + Text("Continuer la saisie") + } + }, + dismissButton = { + TextButton( + onClick = onConfirmDiscard, + modifier = Modifier.testTag("unsaved_discard_button") + ) { + Text( + text = "Quitter sans enregistrer", + color = MaterialTheme.colorScheme.error, + fontWeight = FontWeight.SemiBold + ) + } + } + ) +} diff --git a/app/src/main/java/com/example/ui/journal/JournalScreen.kt b/app/src/main/java/com/example/ui/journal/JournalScreen.kt index 8d49567..e379b22 100644 --- a/app/src/main/java/com/example/ui/journal/JournalScreen.kt +++ b/app/src/main/java/com/example/ui/journal/JournalScreen.kt @@ -86,8 +86,8 @@ fun JournalScreen( ) { var showDietaryGuide by remember { mutableStateOf(false) } - val customCategoryLookup = remember(customFoods) { - customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val customCategoriesLookup = remember(customFoods) { + CustomFoodEntry.buildCategoriesLookup(customFoods) } Box( @@ -151,7 +151,7 @@ fun JournalScreen( item { DailyBenchmarksCard( todayMeals = todayMeals, - customCategoryLookup = customCategoryLookup, + customCategoriesLookup = customCategoriesLookup, onOpenGuideClick = { showDietaryGuide = true } ) } @@ -221,7 +221,7 @@ fun JournalScreen( items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal -> MealCardItem( meal = meal, - customCategoryLookup = customCategoryLookup, + customCategoriesLookup = customCategoriesLookup, onEdit = { onEditMeal(meal) }, onDelete = { onDeleteMeal(meal.id) } ) @@ -353,7 +353,7 @@ private fun DailyOverviewCard(todayMeals: List) { @Composable private fun MealCardItem( meal: MealEntry, - customCategoryLookup: Map, + customCategoriesLookup: Map>, onEdit: () -> Unit, onDelete: () -> Unit ) { @@ -551,7 +551,7 @@ private fun MealCardItem( parsedFoods.forEach { food -> FoodCategoryBadge( text = food.displayBadge(), - category = food.resolvedCategory(customCategoryLookup) + categories = food.resolvedCategories(customCategoriesLookup) ) } } diff --git a/app/src/main/java/com/example/ui/journal/MealViewModel.kt b/app/src/main/java/com/example/ui/journal/MealViewModel.kt index cd3aa32..d0d6a94 100644 --- a/app/src/main/java/com/example/ui/journal/MealViewModel.kt +++ b/app/src/main/java/com/example/ui/journal/MealViewModel.kt @@ -173,11 +173,11 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { repository.observeCustomFoods(), _selectedIdeaMealType ) { meals, foods, mealType -> - val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val lookup = CustomFoodEntry.buildCategoriesLookup(foods) DailyBenchmarkAnalyzer.analyzeToday( meals = meals, targetMealType = mealType, - customCategoryLookup = lookup + customCategoriesLookup = lookup ) } .flowOn(Dispatchers.Default) @@ -201,10 +201,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { repository.observeMeals(), repository.observeCustomFoods() ) { meals, foods -> - val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val lookup = CustomFoodEntry.buildCategoriesLookup(foods) WeeklyStatsCalculator.computeWeeklyStats( meals = meals, - customCategoryLookup = lookup + customCategoriesLookup = lookup ) } .flowOn(Dispatchers.Default) @@ -266,7 +266,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { private fun enrichCatalogWithFoodItems(foodItems: List) { val existingBuiltIn = DefaultFoodCatalog.builtInFoods.associate { - it.name.lowercase(Locale.FRENCH) to it.category + it.name.lowercase(Locale.FRENCH) to it.resolvedCategories() } val existingCustom = customFoods.value.associateBy { it.name.lowercase(Locale.FRENCH) } @@ -276,19 +276,19 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { val normalized = cleanName.lowercase(Locale.FRENCH) if (cleanName.isEmpty()) return@forEach - val chosenCategory = item.category ?: item.resolvedCategory() - val builtInCategory = existingBuiltIn[normalized] + val chosenCategories = item.resolvedCategories() + val builtInCategories = existingBuiltIn[normalized] val existingEntry = existingCustom[normalized] val shouldSave = when { - builtInCategory == null && existingEntry == null -> true - existingEntry != null && existingEntry.resolvedCategory() != chosenCategory -> true - builtInCategory != null && builtInCategory != chosenCategory -> true + builtInCategories == null && existingEntry == null -> true + existingEntry != null && existingEntry.resolvedCategories() != chosenCategories -> true + builtInCategories != null && builtInCategories != chosenCategories -> true else -> false } if (shouldSave) { - repository.saveCustomFood(cleanName, item.unit, chosenCategory) + repository.saveCustomFood(cleanName, item.unit, chosenCategories) } } } @@ -297,15 +297,23 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { fun addCustomFoodDirectly( name: String, unit: FoodUnit, - category: FoodCategory? = null + categories: List ) { val cleanName = name.trim() if (cleanName.isEmpty()) return viewModelScope.launch { - repository.saveCustomFood(cleanName, unit, category) + repository.saveCustomFood(cleanName, unit, categories) } } + fun addCustomFoodDirectly( + name: String, + unit: FoodUnit, + category: FoodCategory? = null + ) { + addCustomFoodDirectly(name, unit, listOfNotNull(category)) + } + fun addMeal( mealType: MealType, mealTimestamp: Long, @@ -460,13 +468,11 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { _suggestionUiState.value = SuggestionUiState.Loading val targetType = _selectedIdeaMealType.value val currentMeals = repository.getAllMealsSnapshot() - val lookup = customFoods.value.associate { - it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() - } + val lookup = CustomFoodEntry.buildCategoriesLookup(customFoods.value) val gap = DailyBenchmarkAnalyzer.analyzeToday( meals = currentMeals, targetMealType = targetType, - customCategoryLookup = lookup + customCategoriesLookup = lookup ) val currentPrefs = foodPreferences.value val existingTitles = recipes.value.map { it.title } @@ -727,7 +733,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { } fun computeWeeklyStats(meals: List, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { - val lookup = customFoods.value.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } - return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, lookup) + val lookup = CustomFoodEntry.buildCategoriesLookup(customFoods.value) + return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, customCategoriesLookup = lookup) } } diff --git a/app/src/main/java/com/example/ui/journal/components/DietaryBenchmarksSection.kt b/app/src/main/java/com/example/ui/journal/components/DietaryBenchmarksSection.kt index 82c06b4..734d811 100644 --- a/app/src/main/java/com/example/ui/journal/components/DietaryBenchmarksSection.kt +++ b/app/src/main/java/com/example/ui/journal/components/DietaryBenchmarksSection.kt @@ -70,26 +70,29 @@ private data class CategoryDaySummary( @Composable fun DailyBenchmarksCard( todayMeals: List, - customCategoryLookup: Map, + customCategoriesLookup: Map>, onOpenGuideClick: () -> Unit, modifier: Modifier = Modifier ) { var expanded by remember { mutableStateOf(false) } val isDark = isSatieaDarkTheme() - val summariesByCategory = remember(todayMeals, customCategoryLookup) { + val summariesByCategory = remember(todayMeals, customCategoriesLookup) { val map = mutableMapOf() todayMeals.forEach { meal -> meal.parsedFoodItems().forEach { item -> - val cat = item.resolvedCategory(customCategoryLookup) - val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0) - val addG = if (item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0 - val addP = if (item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0 - map[cat] = current.copy( - count = current.count + 1, - totalGrams = current.totalGrams + addG, - totalPortions = current.totalPortions + addP - ) + val cats = item.resolvedCategories(customCategoriesLookup) + val isComposite = cats.size > 1 + val addG = if (!isComposite && item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0 + val addP = if (!isComposite && item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0 + cats.forEach { cat -> + val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0) + map[cat] = current.copy( + count = current.count + 1, + totalGrams = current.totalGrams + addG, + totalPortions = current.totalPortions + addP + ) + } } } map diff --git a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt index d87ec50..02eeac6 100644 --- a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt +++ b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt @@ -1,6 +1,7 @@ package com.example.ui.meal import android.net.Uri +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts @@ -25,6 +26,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SheetValue import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState @@ -36,6 +38,7 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -53,6 +56,7 @@ import com.example.data.model.FoodUnit import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType +import com.example.ui.common.UnsavedChangesDiscardDialog import com.example.ui.journal.components.DietaryGuideSheet import com.example.ui.meal.components.FoodItemBuilderSection import com.example.ui.meal.components.MealDateTimePicker @@ -87,32 +91,45 @@ fun MealEntrySheet( initialMeal: MealEntry? = null, defaultMealType: MealType = MealType.LUNCH, customFoods: List = emptyList(), - onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> }, + onAddCustomFood: (String, FoodUnit, List) -> Unit = { _, _, _ -> }, onDismiss: () -> Unit, onSaveMeal: (MealType, Long, Int, Int, String, List, List) -> Unit ) { - val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val isEditingExisting = initialMeal != null && initialMeal.id.isNotBlank() + val isPrefilledNewMeal = initialMeal != null && initialMeal.id.isBlank() var showDietaryGuide by remember { mutableStateOf(false) } + var showDiscardDialog by remember { mutableStateOf(false) } - var selectedType by rememberSaveable { - mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType) + val initialType = remember(initialMeal?.id, defaultMealType) { + if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType } - var mealTimestamp by rememberSaveable { - mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis()) + val initialTimestamp = rememberSaveable(initialMeal?.id) { + initialMeal?.mealTimestamp ?: System.currentTimeMillis() } - var hungerLevel by rememberSaveable { - mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10)) + val initialHunger = remember(initialMeal?.id) { + (initialMeal?.hungerBefore ?: 5).coerceIn(1, 10) } - var satietyLevel by rememberSaveable { - mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10)) + val initialSatiety = remember(initialMeal?.id) { + (initialMeal?.satietyAfter ?: 7).coerceIn(1, 10) } - var globalNoteText by rememberSaveable { - mutableStateOf(initialMeal?.note ?: "") + val initialNote = remember(initialMeal?.id) { + initialMeal?.note ?: "" } + val initialFoodsSerialized = remember(initialMeal?.id) { + initialMeal?.parsedFoodItems()?.map { it.serialize() } ?: emptyList() + } + val initialPhotos = remember(initialMeal?.id) { + initialMeal?.displayPhotoUris ?: emptyList() + } + + var selectedType by rememberSaveable { mutableStateOf(initialType) } + var mealTimestamp by rememberSaveable { mutableLongStateOf(initialTimestamp) } + var hungerLevel by rememberSaveable { mutableIntStateOf(initialHunger) } + var satietyLevel by rememberSaveable { mutableIntStateOf(initialSatiety) } + var globalNoteText by rememberSaveable { mutableStateOf(initialNote) } // Preserved across rotation via custom ListSaver val foodItemsList = rememberSaveable(saver = FoodItemListSaver) { @@ -138,24 +155,54 @@ fun MealEntrySheet( mutableStateListOf() } - val customCategoryLookup = remember(customFoods) { - customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val customCategoriesLookup = remember(customFoods) { + CustomFoodEntry.buildCategoriesLookup(customFoods) } - // Current food builder input state + // Current food builder input state (supports multiple categories per dish) var foodNameInput by rememberSaveable { mutableStateOf("") } var foodWeightInput by rememberSaveable { mutableStateOf("") } var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) } - var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) } + var selectedFoodCategoriesEncoded by rememberSaveable { mutableStateOf(FoodCategory.OTHER.code) } + val selectedFoodCategories = remember(selectedFoodCategoriesEncoded) { + FoodCategory.parseCategoryList(selectedFoodCategoriesEncoded).ifEmpty { listOf(FoodCategory.OTHER) } + } var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) } + val hasUnsavedChanges = isPrefilledNewMeal || + selectedType != initialType || + mealTimestamp != initialTimestamp || + hungerLevel != initialHunger || + satietyLevel != initialSatiety || + globalNoteText.trim() != initialNote.trim() || + foodItemsList.map { it.serialize() } != initialFoodsSerialized || + photoUrisList.toList() != initialPhotos || + foodNameInput.isNotBlank() || + foodWeightInput.isNotBlank() + + val currentHasUnsavedChanges by rememberUpdatedState(hasUnsavedChanges) + + val sheetState = rememberModalBottomSheetState( + skipPartiallyExpanded = true, + confirmValueChange = { targetValue -> + if (targetValue == SheetValue.Hidden && currentHasUnsavedChanges) { + showDiscardDialog = true + false + } else { + true + } + } + ) + // Combine custom foods (user enriched) + built-in catalog val mergedCatalog = remember(customFoods) { val customMapped = customFoods.map { + val cats = it.resolvedCategories() DefaultFoodCatalog.CatalogFood( name = it.name, defaultUnit = FoodUnit.fromCode(it.defaultUnit), - category = it.resolvedCategory() + category = cats.first(), + categories = cats ) } val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet() @@ -187,16 +234,17 @@ fun MealEntrySheet( val cleanName = foodNameInput.trim() if (cleanName.isNotEmpty() && foodItemsList.size < 30) { val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 } - val resolvedCat = if (hasUserOverriddenCategory) { - selectedFoodCategory + val resolvedCats = if (hasUserOverriddenCategory) { + selectedFoodCategories } else { - FoodCategory.inferFromName(cleanName, customCategoryLookup) + FoodCategory.inferCategoriesFromName(cleanName, customCategoriesLookup) } val newItem = MealFoodItem( name = cleanName, weight = parsedWeight, unit = selectedFoodUnit, - category = resolvedCat + category = resolvedCats.firstOrNull(), + categories = resolvedCats ) val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) } if (existingIndex >= 0) { @@ -205,12 +253,12 @@ fun MealEntrySheet( foodItemsList.add(newItem) } if (isNewCustomFood || hasUserOverriddenCategory) { - onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat) + onAddCustomFood(cleanName, selectedFoodUnit, resolvedCats) } foodNameInput = "" foodWeightInput = "" selectedFoodUnit = FoodUnit.G - selectedFoodCategory = FoodCategory.OTHER + selectedFoodCategoriesEncoded = FoodCategory.OTHER.code hasUserOverriddenCategory = false } } @@ -233,19 +281,32 @@ fun MealEntrySheet( } } - val handleDismiss = { + val performDiscardAndDismiss = { + showDiscardDialog = false newlyCapturedPhotos.forEach { photoUri -> ImageUtils.deletePhotoFile(context, photoUri) } onDismiss() } + val requestDismiss = { + if (hasUnsavedChanges) { + showDiscardDialog = true + } else { + performDiscardAndDismiss() + } + } + ModalBottomSheet( - onDismissRequest = handleDismiss, + onDismissRequest = requestDismiss, sheetState = sheetState, containerColor = MaterialTheme.colorScheme.surface, dragHandle = null ) { + BackHandler(enabled = hasUnsavedChanges) { + showDiscardDialog = true + } + Column( modifier = Modifier .fillMaxWidth() @@ -272,7 +333,7 @@ fun MealEntrySheet( ) } IconButton( - onClick = handleDismiss, + onClick = requestDismiss, modifier = Modifier.testTag("dismiss_sheet_button") ) { Icon( @@ -328,7 +389,7 @@ fun MealEntrySheet( Spacer(modifier = Modifier.height(22.dp)) - // Subcomponent 5: Color-coded Food items builder & flow-row chips + // Subcomponent 5: Color-coded Food items builder & multi-dot badges FoodItemBuilderSection( foodItemsList = foodItemsList, matchingSuggestions = matchingSuggestions, @@ -336,24 +397,32 @@ fun MealEntrySheet( onFoodNameChange = { input -> foodNameInput = input if (!hasUserOverriddenCategory) { - selectedFoodCategory = if (input.isBlank()) { - FoodCategory.OTHER + val inferred = if (input.isBlank()) { + listOf(FoodCategory.OTHER) } else { - FoodCategory.inferFromName(input, customCategoryLookup) + FoodCategory.inferCategoriesFromName(input, customCategoriesLookup) } + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(inferred) } if (input.isBlank()) { hasUserOverriddenCategory = false - selectedFoodCategory = FoodCategory.OTHER + selectedFoodCategoriesEncoded = FoodCategory.OTHER.code } }, foodWeightInput = foodWeightInput, onFoodWeightChange = { foodWeightInput = it }, selectedFoodUnit = selectedFoodUnit, onFoodUnitSelected = { selectedFoodUnit = it }, - selectedFoodCategory = selectedFoodCategory, - onFoodCategorySelected = { category -> - selectedFoodCategory = category + selectedFoodCategories = selectedFoodCategories, + onFoodCategoryToggled = { toggled -> + val updated = FoodCategory.toggleCategorySelection(selectedFoodCategories, toggled) + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(updated) + hasUserOverriddenCategory = true + }, + onSuggestionSelected = { suggestion -> + foodNameInput = suggestion.name + selectedFoodUnit = suggestion.defaultUnit + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(suggestion.resolvedCategories()) hasUserOverriddenCategory = true }, isNewCustomFood = isNewCustomFood, @@ -364,13 +433,16 @@ fun MealEntrySheet( if (it % 1.0 == 0.0) it.toInt().toString() else it.toString() } ?: "" selectedFoodUnit = item.unit - selectedFoodCategory = item.resolvedCategory(customCategoryLookup) + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList( + item.resolvedCategories(customCategoriesLookup) + ) hasUserOverriddenCategory = true foodItemsList.remove(item) }, onRemoveFoodItem = { item -> foodItemsList.remove(item) }, + customCategoriesLookup = customCategoriesLookup, onOpenGuideClick = { showDietaryGuide = true } ) @@ -411,7 +483,7 @@ fun MealEntrySheet( verticalAlignment = Alignment.CenterVertically ) { TextButton( - onClick = handleDismiss, + onClick = requestDismiss, modifier = Modifier.testTag("cancel_meal_button") ) { Text("Annuler") @@ -457,6 +529,15 @@ fun MealEntrySheet( } } + if (showDiscardDialog) { + UnsavedChangesDiscardDialog( + title = "Quitter sans enregistrer ?", + message = "Votre repas en cours n'est pas encore enregistré. Souhaitez-vous vraiment quitter sans sauvegarder ?", + onContinueEditing = { showDiscardDialog = false }, + onConfirmDiscard = performDiscardAndDismiss + ) + } + if (showDietaryGuide) { DietaryGuideSheet(onDismiss = { showDietaryGuide = false }) } diff --git a/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt b/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt index e788c87..2f3c5b8 100644 --- a/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt +++ b/app/src/main/java/com/example/ui/meal/components/FoodItemBuilderSection.kt @@ -46,7 +46,7 @@ import com.example.data.model.FoodCategory import com.example.data.model.FoodUnit import com.example.data.model.MealFoodItem import com.example.ui.common.FoodCategoryBadge -import com.example.ui.common.FoodCategoryColorDot +import com.example.ui.common.FoodCategoryColorDotsRow import com.example.ui.common.FoodCategorySelectorRow @OptIn(ExperimentalLayoutApi::class) @@ -60,18 +60,24 @@ fun FoodItemBuilderSection( onFoodWeightChange: (String) -> Unit, selectedFoodUnit: FoodUnit, onFoodUnitSelected: (FoodUnit) -> Unit, - selectedFoodCategory: FoodCategory, - onFoodCategorySelected: (FoodCategory) -> Unit, + selectedFoodCategories: List, + onFoodCategoryToggled: (FoodCategory) -> Unit, + onSuggestionSelected: (DefaultFoodCatalog.CatalogFood) -> Unit, isNewCustomFood: Boolean, onAddFoodItem: () -> Unit, onItemClickForEdit: (MealFoodItem) -> Unit, onRemoveFoodItem: (MealFoodItem) -> Unit, + customCategoriesLookup: Map> = emptyMap(), sectionTitle: String = "3. Aliments & Poids (optionnel)", addButtonLabelPrefix: String = "Ajouter à l'assiette", - addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleur) :", + addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleurs) :", onOpenGuideClick: (() -> Unit)? = null, modifier: Modifier = Modifier ) { + val activeCategories = FoodCategory.sanitizeSelection(selectedFoodCategories) + .ifEmpty { listOf(FoodCategory.OTHER) } + val activeConcreteCount = activeCategories.count { it != FoodCategory.OTHER } + Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f), @@ -138,14 +144,14 @@ fun FoodItemBuilderSection( Spacer(modifier = Modifier.height(4.dp)) Text( - text = "Sélectionnez un aliment ou tapez-en un nouveau : sa couleur est détectée automatiquement et modifiable ci-dessous.", + text = "Sélectionnez un aliment ou un plat composé : vous pouvez associer plusieurs couleurs ci-dessous.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) Spacer(modifier = Modifier.height(10.dp)) - // Auto-complete / Quick suggestions row with color dots + // Auto-complete / Quick suggestions row with single or multi color dots if (matchingSuggestions.isNotEmpty()) { LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp), @@ -153,13 +159,13 @@ fun FoodItemBuilderSection( ) { items(matchingSuggestions, key = { it.name }) { suggestion -> SuggestionChip( - onClick = { - onFoodNameChange(suggestion.name) - onFoodUnitSelected(suggestion.defaultUnit) - onFoodCategorySelected(suggestion.category) - }, + onClick = { onSuggestionSelected(suggestion) }, icon = { - FoodCategoryColorDot(category = suggestion.category, size = 9.dp) + FoodCategoryColorDotsRow( + categories = suggestion.resolvedCategories(), + dotSize = 8.dp, + spacing = 2.dp + ) }, label = { Text( @@ -185,10 +191,15 @@ fun FoodItemBuilderSection( .fillMaxWidth() .testTag("food_name_input"), placeholder = { - Text("Nom de l'aliment (ex: Riz basmati, Saumon, Comté...)") + Text("Nom de l'aliment ou plat (ex: Riz, Kebab, Comté...)") }, leadingIcon = { - FoodCategoryColorDot(category = selectedFoodCategory, size = 11.dp) + FoodCategoryColorDotsRow( + categories = activeCategories.take(4), + dotSize = if (activeCategories.size > 2) 7.dp else 10.dp, + spacing = 2.dp, + modifier = Modifier.padding(start = 6.dp) + ) }, singleLine = true, shape = RoundedCornerShape(12.dp), @@ -208,7 +219,11 @@ fun FoodItemBuilderSection( if (isNewCustomFood) { Spacer(modifier = Modifier.height(4.dp)) Text( - text = "✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue", + text = if (activeConcreteCount > 1) { + "✨ « ${foodNameInput.trim()} » sera mémorisé avec ses $activeConcreteCount familles dans votre catalogue" + } else { + "✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue" + }, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.secondary ) @@ -216,16 +231,54 @@ fun FoodItemBuilderSection( Spacer(modifier = Modifier.height(10.dp)) - // Food Category Color Selector + // Multi-select Food Category Color Selector + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = "Famille(s) / Code couleur :", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = FontWeight.Medium + ) + if (activeConcreteCount > 1) { + Surface( + shape = RoundedCornerShape(8.dp), + color = MaterialTheme.colorScheme.primaryContainer, + modifier = Modifier.testTag("multi_category_count_badge") + ) { + Text( + text = "$activeConcreteCount familles", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onPrimaryContainer, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp) + ) + } + } + } + + Spacer(modifier = Modifier.height(2.dp)) Text( - text = "Famille / Code couleur :", + text = if (activeConcreteCount > 1) { + "Plat composé : ${activeCategories.joinToString(" · ") { it.shortLabel }}" + } else { + "Touchez plusieurs catégories pour un plat composé (ex. Kebab : Viande + Légumes + Pain)" + }, style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant + color = if (activeConcreteCount > 1) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f) + } ) + Spacer(modifier = Modifier.height(6.dp)) FoodCategorySelectorRow( - selectedCategory = selectedFoodCategory, - onCategorySelected = onFoodCategorySelected + selectedCategories = activeCategories, + onCategoryToggled = onFoodCategoryToggled ) Spacer(modifier = Modifier.height(10.dp)) @@ -314,7 +367,7 @@ fun FoodItemBuilderSection( ) } - // Added color-coded food items badges + // Added color-coded food items badges (single or multi-dot) if (foodItemsList.isNotEmpty()) { Spacer(modifier = Modifier.height(14.dp)) Text( @@ -332,7 +385,7 @@ fun FoodItemBuilderSection( foodItemsList.forEach { item -> FoodCategoryBadge( text = item.displayBadge(), - category = item.resolvedCategory(), + categories = item.resolvedCategories(customCategoriesLookup), onClick = { onItemClickForEdit(item) }, onRemove = { onRemoveFoodItem(item) } ) diff --git a/app/src/main/java/com/example/ui/planning/InventoryItemEditorSheet.kt b/app/src/main/java/com/example/ui/planning/InventoryItemEditorSheet.kt new file mode 100644 index 0000000..94cdd08 --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/InventoryItemEditorSheet.kt @@ -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)) + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/InventoryTab.kt b/app/src/main/java/com/example/ui/planning/InventoryTab.kt new file mode 100644 index 0000000..c9aeb76 --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/InventoryTab.kt @@ -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, + 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(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) + ) + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/PlanMealSheet.kt b/app/src/main/java/com/example/ui/planning/PlanMealSheet.kt new file mode 100644 index 0000000..1aceeb6 --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/PlanMealSheet.kt @@ -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, + customFoods: List, + onAddCustomFood: (String, FoodUnit, List) -> 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().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)) + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/PlanningScreen.kt b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt new file mode 100644 index 0000000..37afd2a --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt @@ -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, + inventoryItems: List, + shoppingItems: List, + recipes: List, + customFoods: List, + receiptScanState: ReceiptScanUiState, + onPreviousWeek: () -> Unit, + onNextWeek: () -> Unit, + onGoToCurrentWeek: () -> Unit, + onSavePlannedMeal: (PlannedMealEntry) -> Unit, + onDeletePlannedMeal: (String) -> Unit, + onMarkPlannedMealAsEaten: (PlannedMealEntry) -> Unit, + onAddCustomFood: (String, FoodUnit, List) -> 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, 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(null) } + var planTargetMealType by remember { mutableStateOf(MealType.LUNCH) } + var editingPlannedMeal by remember { mutableStateOf(null) } + + var showInventoryEditor by remember { mutableStateOf(false) } + var editingInventoryItem by remember { mutableStateOf(null) } + + var showReceiptSourceDialog by remember { mutableStateOf(false) } + var pendingCaptureUri by remember { mutableStateOf(null) } + + var shoppingItemForStockPrompt by remember { mutableStateOf(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 + } +} diff --git a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt new file mode 100644 index 0000000..c419704 --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt @@ -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(Channel.BUFFERED) + val uiEvents: Flow = _uiEvents.receiveAsFlow() + + private val _weekStartDate = MutableStateFlow(currentMonday()) + val weekStartDate: StateFlow = _weekStartDate.asStateFlow() + + val weekPlannedMeals: StateFlow> = _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> = repository.observeInventory() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + val manualShoppingItems: StateFlow> = repository.observeManualShoppingItems() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = emptyList() + ) + + private val recipesFlow: Flow> = repository.observeRecipes() + private val customFoodsFlow: Flow> = repository.observeCustomFoods() + + private val _checkedPlanKeys = MutableStateFlow>(emptySet()) + + private data class ShoppingInputs( + val planned: List, + val recipes: List, + val inventory: List, + val manual: List, + val checkedKeys: Set + ) + + val computedShoppingList: StateFlow> = 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.Idle) + val receiptScanState: StateFlow = _receiptScanState.asStateFlow() + + private val _pendingStockDeductions = MutableStateFlow?>(null) + val pendingStockDeductions: StateFlow?> = _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, + 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) { + 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, + 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)) + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt b/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt new file mode 100644 index 0000000..6970e6e --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt @@ -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, 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)) } + ) + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/ShoppingListTab.kt b/app/src/main/java/com/example/ui/planning/ShoppingListTab.kt new file mode 100644 index 0000000..c5b09bf --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/ShoppingListTab.kt @@ -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, + 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) + ) + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/StockDeductionDialog.kt b/app/src/main/java/com/example/ui/planning/StockDeductionDialog.kt new file mode 100644 index 0000000..e784d9d --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/StockDeductionDialog.kt @@ -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, + onDismiss: () -> Unit, + onConfirm: (List) -> Unit +) { + val selectionMap = remember(proposals) { + mutableStateMapOf().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") + } + } + ) +} diff --git a/app/src/main/java/com/example/ui/planning/WeeklyPlanTab.kt b/app/src/main/java/com/example/ui/planning/WeeklyPlanTab.kt new file mode 100644 index 0000000..f51ca1f --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/WeeklyPlanTab.kt @@ -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, + recipesById: Map, + customFoods: List, + 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, + recipesById: Map, + customCategoriesLookup: Map>, + 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 + ) + } + } + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/recipes/IdeasAndTastesSection.kt b/app/src/main/java/com/example/ui/recipes/IdeasAndTastesSection.kt index 516e0c6..aa9cfbe 100644 --- a/app/src/main/java/com/example/ui/recipes/IdeasAndTastesSection.kt +++ b/app/src/main/java/com/example/ui/recipes/IdeasAndTastesSection.kt @@ -70,6 +70,7 @@ import com.example.data.model.RecipeSuggestion import com.example.data.model.SuggestionUiState import com.example.domain.DailyBenchmarkGap import com.example.ui.common.FoodCategoryColorDot +import com.example.ui.common.FoodCategoryColorDotsRow import com.example.ui.common.badgeBorderColor import com.example.ui.common.badgeContainerColor import com.example.ui.common.badgeTextColor @@ -591,7 +592,11 @@ private fun SuggestedRecipeCard( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - FoodCategoryColorDot(category = item.resolvedCategory(), size = 8.dp) + FoodCategoryColorDotsRow( + categories = item.resolvedCategories(), + dotSize = 8.dp, + spacing = 2.dp + ) Text( text = item.displayBadge(), style = MaterialTheme.typography.bodySmall, diff --git a/app/src/main/java/com/example/ui/recipes/RecipeDetailSheet.kt b/app/src/main/java/com/example/ui/recipes/RecipeDetailSheet.kt index d6d636e..0c716fe 100644 --- a/app/src/main/java/com/example/ui/recipes/RecipeDetailSheet.kt +++ b/app/src/main/java/com/example/ui/recipes/RecipeDetailSheet.kt @@ -79,8 +79,8 @@ fun RecipeDetailSheet( var showDeleteConfirm by remember { mutableStateOf(false) } val checkedSteps = remember(recipe.id) { mutableStateListOf() } - val customCategoryLookup = remember(customFoods) { - customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val customCategoriesLookup = remember(customFoods) { + CustomFoodEntry.buildCategoriesLookup(customFoods) } val scaledIngredients = remember(recipe.ingredientsSerialized, displayServings) { @@ -277,7 +277,7 @@ fun RecipeDetailSheet( scaledIngredients.forEach { item -> FoodCategoryBadge( text = item.displayBadge(), - category = item.resolvedCategory(customCategoryLookup) + categories = item.resolvedCategories(customCategoriesLookup) ) } } diff --git a/app/src/main/java/com/example/ui/recipes/RecipeEditorSheet.kt b/app/src/main/java/com/example/ui/recipes/RecipeEditorSheet.kt index 9a0cdf3..b193852 100644 --- a/app/src/main/java/com/example/ui/recipes/RecipeEditorSheet.kt +++ b/app/src/main/java/com/example/ui/recipes/RecipeEditorSheet.kt @@ -1,6 +1,7 @@ package com.example.ui.recipes import android.net.Uri +import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts @@ -40,6 +41,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SheetValue import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -50,6 +52,7 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -69,6 +72,7 @@ import com.example.data.model.FoodUnit import com.example.data.model.MealFoodItem import com.example.data.model.RecipeCategoryTag import com.example.data.model.RecipeEntry +import com.example.ui.common.UnsavedChangesDiscardDialog import com.example.ui.meal.components.FoodItemBuilderSection import com.example.util.ImageUtils import kotlinx.coroutines.launch @@ -79,26 +83,38 @@ import java.util.Locale fun RecipeEditorSheet( initialRecipe: RecipeEntry? = null, customFoods: List = emptyList(), - onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> }, + onAddCustomFood: (String, FoodUnit, List) -> Unit = { _, _, _ -> }, onDismiss: () -> Unit, onSaveRecipe: (RecipeEntry) -> Unit ) { - val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val context = LocalContext.current val coroutineScope = rememberCoroutineScope() - var title by rememberSaveable { mutableStateOf(initialRecipe?.title ?: "") } - var selectedTag by rememberSaveable { - mutableStateOf(initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN) + var showDiscardDialog by remember { mutableStateOf(false) } + + val initialTitle = remember(initialRecipe?.id) { initialRecipe?.title ?: "" } + val initialTag = remember(initialRecipe?.id) { initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN } + val initialPrepTime = remember(initialRecipe?.id) { + initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: "" } - var prepTimeInput by rememberSaveable { - mutableStateOf(initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: "") + val initialServings = remember(initialRecipe?.id) { + (initialRecipe?.servings ?: 2).toString() } - var servingsInput by rememberSaveable { - mutableStateOf((initialRecipe?.servings ?: 2).toString()) + val initialNotes = remember(initialRecipe?.id) { initialRecipe?.notes ?: "" } + val initialPhoto = remember(initialRecipe?.id) { initialRecipe?.photoUri } + val initialIngredientsSerialized = remember(initialRecipe?.id) { + initialRecipe?.parsedIngredients()?.map { it.serialize() } ?: emptyList() } - var notes by rememberSaveable { mutableStateOf(initialRecipe?.notes ?: "") } - var photoUri by rememberSaveable { mutableStateOf(initialRecipe?.photoUri) } + val initialSteps = remember(initialRecipe?.id) { + initialRecipe?.steps ?: emptyList() + } + + var title by rememberSaveable { mutableStateOf(initialTitle) } + var selectedTag by rememberSaveable { mutableStateOf(initialTag) } + var prepTimeInput by rememberSaveable { mutableStateOf(initialPrepTime) } + var servingsInput by rememberSaveable { mutableStateOf(initialServings) } + var notes by rememberSaveable { mutableStateOf(initialNotes) } + var photoUri by rememberSaveable { mutableStateOf(initialPhoto) } var newlySavedPhotoUri by rememberSaveable { mutableStateOf(null) } var isProcessingPhoto by remember { mutableStateOf(false) } @@ -117,25 +133,56 @@ fun RecipeEditorSheet( } } - // Ingredient builder state - val customCategoryLookup = remember(customFoods) { - customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + // Ingredient builder state (multi-category) + val customCategoriesLookup = remember(customFoods) { + CustomFoodEntry.buildCategoriesLookup(customFoods) } var foodNameInput by rememberSaveable { mutableStateOf("") } var foodWeightInput by rememberSaveable { mutableStateOf("") } var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) } - var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) } + var selectedFoodCategoriesEncoded by rememberSaveable { mutableStateOf(FoodCategory.OTHER.code) } + val selectedFoodCategories = remember(selectedFoodCategoriesEncoded) { + FoodCategory.parseCategoryList(selectedFoodCategoriesEncoded).ifEmpty { listOf(FoodCategory.OTHER) } + } var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) } // Step builder state var stepInput by rememberSaveable { mutableStateOf("") } + val hasUnsavedChanges = title.trim() != initialTitle.trim() || + selectedTag != initialTag || + prepTimeInput.trim() != initialPrepTime || + servingsInput.trim() != initialServings || + notes.trim() != initialNotes.trim() || + photoUri != initialPhoto || + ingredientsList.map { it.serialize() } != initialIngredientsSerialized || + stepsList.toList() != initialSteps || + foodNameInput.isNotBlank() || + foodWeightInput.isNotBlank() || + stepInput.isNotBlank() + + val currentHasUnsavedChanges by rememberUpdatedState(hasUnsavedChanges) + + val sheetState = rememberModalBottomSheetState( + skipPartiallyExpanded = true, + confirmValueChange = { targetValue -> + if (targetValue == SheetValue.Hidden && currentHasUnsavedChanges) { + showDiscardDialog = true + false + } else { + true + } + } + ) + val mergedCatalog = remember(customFoods) { val customMapped = customFoods.map { + val cats = it.resolvedCategories() DefaultFoodCatalog.CatalogFood( name = it.name, defaultUnit = FoodUnit.fromCode(it.defaultUnit), - category = it.resolvedCategory() + category = cats.first(), + categories = cats ) } val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet() @@ -167,16 +214,17 @@ fun RecipeEditorSheet( val cleanName = foodNameInput.trim() if (cleanName.isNotEmpty() && ingredientsList.size < 40) { val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 } - val resolvedCat = if (hasUserOverriddenCategory) { - selectedFoodCategory + val resolvedCats = if (hasUserOverriddenCategory) { + selectedFoodCategories } else { - FoodCategory.inferFromName(cleanName, customCategoryLookup) + FoodCategory.inferCategoriesFromName(cleanName, customCategoriesLookup) } val item = MealFoodItem( name = cleanName, weight = parsedWeight, unit = selectedFoodUnit, - category = resolvedCat + category = resolvedCats.firstOrNull(), + categories = resolvedCats ) val existingIdx = ingredientsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) } if (existingIdx >= 0) { @@ -185,12 +233,12 @@ fun RecipeEditorSheet( ingredientsList.add(item) } if (isNewCustomFood || hasUserOverriddenCategory) { - onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat) + onAddCustomFood(cleanName, selectedFoodUnit, resolvedCats) } foodNameInput = "" foodWeightInput = "" selectedFoodUnit = FoodUnit.G - selectedFoodCategory = FoodCategory.OTHER + selectedFoodCategoriesEncoded = FoodCategory.OTHER.code hasUserOverriddenCategory = false } } @@ -215,17 +263,30 @@ fun RecipeEditorSheet( } } - val handleDismiss = { + val performDiscardAndDismiss = { + showDiscardDialog = false newlySavedPhotoUri?.let { ImageUtils.deletePhotoFile(context, it) } onDismiss() } + val requestDismiss = { + if (hasUnsavedChanges) { + showDiscardDialog = true + } else { + performDiscardAndDismiss() + } + } + ModalBottomSheet( - onDismissRequest = handleDismiss, + onDismissRequest = requestDismiss, sheetState = sheetState, containerColor = MaterialTheme.colorScheme.surface, dragHandle = null ) { + BackHandler(enabled = hasUnsavedChanges) { + showDiscardDialog = true + } + Column( modifier = Modifier .fillMaxWidth() @@ -252,7 +313,10 @@ fun RecipeEditorSheet( color = MaterialTheme.colorScheme.onSurfaceVariant ) } - IconButton(onClick = handleDismiss) { + IconButton( + onClick = requestDismiss, + modifier = Modifier.testTag("dismiss_recipe_editor_button") + ) { Icon( imageVector = Icons.Default.Close, contentDescription = "Fermer" @@ -404,7 +468,7 @@ fun RecipeEditorSheet( Spacer(modifier = Modifier.height(18.dp)) - // Color-Coded Ingredients Builder + // Color-Coded Multi-Category Ingredients Builder FoodItemBuilderSection( foodItemsList = ingredientsList, matchingSuggestions = matchingSuggestions, @@ -412,24 +476,32 @@ fun RecipeEditorSheet( onFoodNameChange = { input -> foodNameInput = input if (!hasUserOverriddenCategory) { - selectedFoodCategory = if (input.isBlank()) { - FoodCategory.OTHER + val inferred = if (input.isBlank()) { + listOf(FoodCategory.OTHER) } else { - FoodCategory.inferFromName(input, customCategoryLookup) + FoodCategory.inferCategoriesFromName(input, customCategoriesLookup) } + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(inferred) } if (input.isBlank()) { hasUserOverriddenCategory = false - selectedFoodCategory = FoodCategory.OTHER + selectedFoodCategoriesEncoded = FoodCategory.OTHER.code } }, foodWeightInput = foodWeightInput, onFoodWeightChange = { foodWeightInput = it }, selectedFoodUnit = selectedFoodUnit, onFoodUnitSelected = { selectedFoodUnit = it }, - selectedFoodCategory = selectedFoodCategory, - onFoodCategorySelected = { cat -> - selectedFoodCategory = cat + selectedFoodCategories = selectedFoodCategories, + onFoodCategoryToggled = { toggled -> + val updated = FoodCategory.toggleCategorySelection(selectedFoodCategories, toggled) + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(updated) + hasUserOverriddenCategory = true + }, + onSuggestionSelected = { suggestion -> + foodNameInput = suggestion.name + selectedFoodUnit = suggestion.defaultUnit + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList(suggestion.resolvedCategories()) hasUserOverriddenCategory = true }, isNewCustomFood = isNewCustomFood, @@ -440,14 +512,17 @@ fun RecipeEditorSheet( if (it % 1.0 == 0.0) it.toInt().toString() else it.toString() } ?: "" selectedFoodUnit = item.unit - selectedFoodCategory = item.resolvedCategory(customCategoryLookup) + selectedFoodCategoriesEncoded = FoodCategory.encodeCategoryList( + item.resolvedCategories(customCategoriesLookup) + ) hasUserOverriddenCategory = true ingredientsList.remove(item) }, onRemoveFoodItem = { item -> ingredientsList.remove(item) }, + customCategoriesLookup = customCategoriesLookup, sectionTitle = "Ingrédients colorés", addButtonLabelPrefix = "Ajouter l'ingrédient", - addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleur) :" + addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleurs) :" ) Spacer(modifier = Modifier.height(18.dp)) @@ -573,7 +648,10 @@ fun RecipeEditorSheet( horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically ) { - TextButton(onClick = handleDismiss) { + TextButton( + onClick = requestDismiss, + modifier = Modifier.testTag("cancel_recipe_button") + ) { Text("Annuler") } Spacer(modifier = Modifier.width(10.dp)) @@ -624,4 +702,13 @@ fun RecipeEditorSheet( Spacer(modifier = Modifier.height(16.dp)) } } + + if (showDiscardDialog) { + UnsavedChangesDiscardDialog( + title = "Quitter sans enregistrer ?", + message = "Votre recette en cours n'est pas encore enregistrée. Souhaitez-vous vraiment quitter sans sauvegarder ?", + onContinueEditing = { showDiscardDialog = false }, + onConfirmDiscard = performDiscardAndDismiss + ) + } } diff --git a/app/src/main/java/com/example/ui/recipes/RecipesScreen.kt b/app/src/main/java/com/example/ui/recipes/RecipesScreen.kt index 1cbb66a..6967e06 100644 --- a/app/src/main/java/com/example/ui/recipes/RecipesScreen.kt +++ b/app/src/main/java/com/example/ui/recipes/RecipesScreen.kt @@ -104,8 +104,8 @@ fun RecipesScreen( var selectedTag by rememberSaveable { mutableStateOf(null) } var cravingNote by rememberSaveable { mutableStateOf("") } - val customCategoryLookup = remember(customFoods) { - customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() } + val customCategoriesLookup = remember(customFoods) { + CustomFoodEntry.buildCategoriesLookup(customFoods) } val filteredRecipes = remember(recipes, searchQuery, selectedTag) { @@ -357,7 +357,7 @@ fun RecipesScreen( items(filteredRecipes, key = { it.id }) { recipe -> RecipeCardItem( recipe = recipe, - customCategoryLookup = customCategoryLookup, + customCategoriesLookup = customCategoriesLookup, onClick = { onRecipeClick(recipe) } ) } @@ -390,13 +390,13 @@ fun RecipesScreen( @Composable private fun RecipeCardItem( recipe: RecipeEntry, - customCategoryLookup: Map, + customCategoriesLookup: Map>, onClick: () -> Unit ) { val isDark = isSatieaDarkTheme() val ingredients = remember(recipe.ingredientsSerialized) { recipe.parsedIngredients() } - val dominantCategories = remember(recipe.ingredientsSerialized, customCategoryLookup) { - recipe.dominantCategories(customCategoryLookup).take(4) + val dominantCategories = remember(recipe.ingredientsSerialized, customCategoriesLookup) { + recipe.dominantCategories(customCategoriesLookup).take(4) } Card( diff --git a/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt b/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt index 4744f7b..c538f57 100644 --- a/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt +++ b/app/src/main/java/com/example/util/GoogleSheetsDataFormatter.kt @@ -129,7 +129,7 @@ object GoogleSheetsDataFormatter { } catch (_: Exception) { "" } - val categoryLabel = food.resolvedCategory().displayName + val categoryLabel = FoodCategory.formatCategoryLabels(food.resolvedCategories()) rows.add( listOf( food.name, @@ -153,7 +153,7 @@ object GoogleSheetsDataFormatter { val sortedRecipes = recipes.sortedBy { it.title.lowercase(Locale.FRENCH) } for (recipe in sortedRecipes) { val ingredientsStr = recipe.parsedIngredients().joinToString(" ; ") { item -> - val catLabel = item.resolvedCategory().displayName + val catLabel = FoodCategory.formatCategoryLabels(item.resolvedCategories()) "${item.displayCsv()} [$catLabel]" } val stepsStr = recipe.steps @@ -281,8 +281,9 @@ object GoogleSheetsDataFormatter { val unitStr = row.getOrNull(1)?.toString()?.trim() ?: "g" val unit = FoodUnit.fromCode(unitStr) val categoryRaw = row.getOrNull(3)?.toString()?.trim().orEmpty() - val resolvedCategory = parseFoodCategory(categoryRaw) ?: FoodCategory.inferFromName(name) - foods.add(LocalCustomFoodEntity.create(name, unit, resolvedCategory)) + val resolvedCategories = FoodCategory.parseCategoryList(categoryRaw) + .ifEmpty { FoodCategory.inferCategoriesFromName(name) } + foods.add(LocalCustomFoodEntity.create(name, unit, resolvedCategories)) } return foods } @@ -373,10 +374,11 @@ object GoogleSheetsDataFormatter { val match = ingredientCategoryRegex.matchEntire(trimmed) val baseText = match?.groupValues?.getOrNull(1)?.trim() ?: trimmed val categoryLabel = match?.groupValues?.getOrNull(2)?.trim() - val explicitCategory = categoryLabel?.let { parseFoodCategory(it) } + val explicitCategories = categoryLabel?.let { FoodCategory.parseCategoryList(it) }.orEmpty() val parsed = CsvImporter.parseFoodItems(baseText).firstOrNull() ?: return@mapNotNull null - parsed.copy(category = explicitCategory ?: parsed.resolvedCategory()) + val finalCategories = explicitCategories.ifEmpty { parsed.resolvedCategories() } + parsed.withCategories(finalCategories) } } diff --git a/app/src/main/java/com/example/util/ImageUtils.kt b/app/src/main/java/com/example/util/ImageUtils.kt index 87ee39c..cb9b6af 100644 --- a/app/src/main/java/com/example/util/ImageUtils.kt +++ b/app/src/main/java/com/example/util/ImageUtils.kt @@ -148,4 +148,74 @@ object ImageUtils { null } } + + /** + * Creates a temporary FileProvider URI inside cacheDir/receipt_scans/ for capturing a + * receipt photo with the device camera without needing external storage permissions. + */ + fun createReceiptCaptureUri(context: Context): Uri { + val dir = File(context.applicationContext.cacheDir, "receipt_scans").apply { + if (!exists()) mkdirs() + } + val file = File(dir, "receipt_${System.currentTimeMillis()}.jpg") + return androidx.core.content.FileProvider.getUriForFile( + context.applicationContext, + "${context.applicationContext.packageName}.fileprovider", + file + ) + } + + /** + * Decodes and scales an image URI to a crisp, memory-safe Bitmap (maxDimension px on longest edge) + * suitable for multimodal Gemini Vision analysis (well under the 20MB inline payload limit). + */ + suspend fun loadResizedBitmapForAi( + context: Context, + sourceUri: Uri, + maxDimension: Int = 1440 + ): Bitmap? = withContext(Dispatchers.IO) { + try { + val boundsOptions = BitmapFactory.Options().apply { inJustDecodeBounds = true } + context.contentResolver.openInputStream(sourceUri)?.use { stream -> + BitmapFactory.decodeStream(stream, null, boundsOptions) + } ?: return@withContext null + + if (boundsOptions.outWidth <= 0 || boundsOptions.outHeight <= 0) { + return@withContext null + } + + var inSampleSize = 1 + if (boundsOptions.outHeight > maxDimension || boundsOptions.outWidth > maxDimension) { + val halfHeight = boundsOptions.outHeight / 2 + val halfWidth = boundsOptions.outWidth / 2 + while (halfHeight / inSampleSize >= maxDimension && halfWidth / inSampleSize >= maxDimension) { + inSampleSize *= 2 + } + } + + val decodeOptions = BitmapFactory.Options().apply { + this.inSampleSize = inSampleSize + } + val decoded = context.contentResolver.openInputStream(sourceUri)?.use { stream -> + BitmapFactory.decodeStream(stream, null, decodeOptions) + } ?: return@withContext null + + if (decoded.width > maxDimension || decoded.height > maxDimension) { + val ratio = minOf( + maxDimension.toFloat() / decoded.width, + maxDimension.toFloat() / decoded.height + ) + val targetW = (decoded.width * ratio).toInt().coerceAtLeast(1) + val targetH = (decoded.height * ratio).toInt().coerceAtLeast(1) + Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also { + if (it != decoded) decoded.recycle() + } + } else { + decoded + } + } catch (e: Exception) { + Log.e(TAG, "Error loading bitmap for AI vision: ${e.message}", e) + null + } + } } diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 6091b0a..82f2205 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -1,4 +1,5 @@ + diff --git a/app/src/test/java/com/example/IngredientMatcherTest.kt b/app/src/test/java/com/example/IngredientMatcherTest.kt new file mode 100644 index 0000000..4ca5261 --- /dev/null +++ b/app/src/test/java/com/example/IngredientMatcherTest.kt @@ -0,0 +1,49 @@ +package com.example + +import com.example.data.model.FoodUnit +import com.example.domain.IngredientMatcher +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class IngredientMatcherTest { + + @Test + fun normalize_stripsAccentsLigaturesArticlesAndPlurals() { + assertEquals("oeuf", IngredientMatcher.normalize("Œufs")) + assertEquals("oeuf", IngredientMatcher.normalize("des oeufs")) + assertEquals("tomate cerise", IngredientMatcher.normalize("Tomates cerises")) + assertEquals("pate complete", IngredientMatcher.normalize("Pâtes complètes")) + assertEquals("poireau", IngredientMatcher.normalize("Poireaux")) + assertEquals("creme fraiche", IngredientMatcher.normalize("De la Crème fraîche")) + } + + @Test + fun normalize_preservesInvariantSingulars() { + assertEquals("mais", IngredientMatcher.normalize("Maïs")) + assertEquals("radis", IngredientMatcher.normalize("Radis")) + assertEquals("ananas", IngredientMatcher.normalize("Ananas")) + assertEquals("couscous", IngredientMatcher.normalize("Couscous")) + assertEquals("riz", IngredientMatcher.normalize("Riz")) + } + + @Test + fun matches_handlesPluralAndCaseDifferences() { + assertTrue(IngredientMatcher.matches("Blanc de poulet", "blanc de poulets")) + assertTrue(IngredientMatcher.matches("Carottes", "carotte")) + assertTrue(IngredientMatcher.matches("Œuf", "Oeufs")) + assertFalse(IngredientMatcher.matches("Lait", "Beurre")) + } + + @Test + fun formatQuantity_rendersCleanFrenchUnits() { + assertEquals("250 g", IngredientMatcher.formatQuantity(250.0, FoodUnit.G)) + assertEquals("1500 g", IngredientMatcher.formatQuantity(1500.0, FoodUnit.G)) + assertEquals("1000 ml", IngredientMatcher.formatQuantity(1000.0, FoodUnit.ML)) + assertEquals("250 ml", IngredientMatcher.formatQuantity(250.0, FoodUnit.ML)) + assertEquals("1 portion", IngredientMatcher.formatQuantity(1.0, FoodUnit.PORTION)) + assertEquals("4 portions", IngredientMatcher.formatQuantity(4.0, FoodUnit.PORTION)) + assertEquals("1,5 portions", IngredientMatcher.formatQuantity(1.5, FoodUnit.PORTION)) + } +} diff --git a/app/src/test/java/com/example/LocalDatabaseTest.kt b/app/src/test/java/com/example/LocalDatabaseTest.kt index 924b9e4..329bf79 100644 --- a/app/src/test/java/com/example/LocalDatabaseTest.kt +++ b/app/src/test/java/com/example/LocalDatabaseTest.kt @@ -6,23 +6,32 @@ import androidx.test.core.app.ApplicationProvider import com.example.data.local.AppDatabase import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalFoodPreferenceEntity +import com.example.data.local.LocalInventoryItemEntity import com.example.data.local.LocalMealDao import com.example.data.local.LocalMealEntity +import com.example.data.local.LocalPlannedMealEntity import com.example.data.local.LocalRecipeEntity +import com.example.data.local.LocalShoppingItemEntity import com.example.data.model.FoodCategory import com.example.data.model.FoodPreferenceStatus import com.example.data.model.FoodUnit +import com.example.data.model.InventoryItem +import com.example.data.model.ManualShoppingItem import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType +import com.example.data.model.PlannedMealEntry import com.example.data.model.RecipeCategoryTag import com.example.data.model.RecipeEntry +import com.example.data.model.StorageLocation import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -176,4 +185,77 @@ class LocalDatabaseTest { val afterDelete = dao.getAllFoodPreferencesOnce() assertEquals(2, afterDelete.size) } + + @Test + fun testPlannedMealsInventoryAndShoppingCrud() = runTest { + // 1. Planned meals range query + consumed update + val planned = PlannedMealEntry( + id = "plan_mon_lunch", + dateEpochDay = 20050L, + mealType = MealType.LUNCH, + customTitle = "Salade César", + itemsSerialized = listOf( + MealFoodItem("Poulet", 150.0, FoodUnit.G, FoodCategory.PROTEIN).serialize() + ), + isConsumed = false + ) + dao.upsertPlannedMeal(LocalPlannedMealEntity.fromDomain(planned)) + + val week = dao.observePlannedMealsForRange(20050L, 20056L).first().map { it.toDomain() } + assertEquals(1, week.size) + assertEquals("Salade César", week[0].customTitle) + assertFalse(week[0].isConsumed) + + dao.markPlannedMealConsumed("plan_mon_lunch", true) + val afterConsumed = dao.observePlannedMealsForRange(20050L, 20056L).first().map { it.toDomain() } + assertTrue(afterConsumed[0].isConsumed) + + dao.deletePlannedMealById("plan_mon_lunch") + assertEquals(0, dao.observePlannedMealsForRange(20050L, 20056L).first().size) + + // 2. Inventory item upsert + normalized lookup + val stockItem = InventoryItem( + id = "inv_chicken", + name = "Blanc de poulet", + quantity = 400.0, + unit = FoodUnit.G, + category = FoodCategory.PROTEIN, + location = StorageLocation.FRIDGE + ) + dao.upsertInventoryItem(LocalInventoryItemEntity.fromDomain(stockItem)) + + val loadedStock = dao.observeAllInventoryItems().first().map { it.toDomain() } + assertEquals(1, loadedStock.size) + assertEquals(StorageLocation.FRIDGE, loadedStock[0].location) + assertNotNull(dao.findInventoryItemByNormalizedAndUnit("blanc de poulet", FoodUnit.G.code)) + + dao.deleteInventoryItemById("inv_chicken") + assertEquals(0, dao.getAllInventoryItemsOnce().size) + + // 3. Manual shopping item check + clearChecked + val manual1 = ManualShoppingItem( + id = "shop_1", + name = "Huile d'olive", + quantity = 500.0, + unit = FoodUnit.ML, + category = FoodCategory.FAT_SEASONING, + isChecked = false + ) + val manual2 = ManualShoppingItem( + id = "shop_2", + name = "Pommes", + quantity = 6.0, + unit = FoodUnit.PORTION, + category = FoodCategory.FRUIT, + isChecked = true + ) + dao.upsertManualShoppingItem(LocalShoppingItemEntity.fromDomain(manual1)) + dao.upsertManualShoppingItem(LocalShoppingItemEntity.fromDomain(manual2)) + assertEquals(2, dao.observeAllManualShoppingItems().first().size) + + dao.clearCheckedManualShoppingItems() + val remaining = dao.getAllManualShoppingItemsOnce().map { it.toDomain() } + assertEquals(1, remaining.size) + assertEquals("Huile d'olive", remaining[0].name) + } } diff --git a/app/src/test/java/com/example/MultiCategoryFoodTest.kt b/app/src/test/java/com/example/MultiCategoryFoodTest.kt new file mode 100644 index 0000000..f8e924c --- /dev/null +++ b/app/src/test/java/com/example/MultiCategoryFoodTest.kt @@ -0,0 +1,211 @@ +package com.example + +import com.example.data.local.LocalCustomFoodEntity +import com.example.data.model.CustomFoodEntry +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.MealEntry +import com.example.data.model.MealFoodItem +import com.example.data.model.MealType +import com.example.data.model.RecipeCategoryTag +import com.example.data.model.RecipeEntry +import com.example.domain.DailyBenchmarkAnalyzer +import com.example.domain.WeeklyStatsCalculator +import com.example.util.GoogleSheetsDataFormatter +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneId + +class MultiCategoryFoodTest { + + private val testZone = ZoneId.of("Europe/Paris") + + @Test + fun serializeAndDeserialize_multiCategoryDish_roundTripsCleanly() { + val kebab = MealFoodItem( + name = "Kebab", + weight = 1.0, + unit = FoodUnit.PORTION, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD) + ) + + val serialized = kebab.serialize() + assertEquals("Kebab|1|portion|PROTEIN,VEGETABLE,BREAD", serialized) + + val restored = MealFoodItem.deserialize(serialized) + assertNotNull(restored) + assertEquals("Kebab", restored!!.name) + assertEquals(1.0, restored.weight) + assertEquals(FoodUnit.PORTION, restored.unit) + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD), + restored.resolvedCategories() + ) + assertEquals(FoodCategory.PROTEIN, restored.resolvedCategory()) + } + + @Test + fun deserialize_legacySingleCategory_remains100PercentCompatible() { + val legacySingle = MealFoodItem.deserialize("Poulet|150|g|PROTEIN") + assertNotNull(legacySingle) + assertEquals(listOf(FoodCategory.PROTEIN), legacySingle!!.resolvedCategories()) + assertEquals("Poulet|150|g|PROTEIN", legacySingle.serialize()) + + val legacyNoCategory = MealFoodItem.deserialize("Comté|30|g") + assertNotNull(legacyNoCategory) + assertEquals(listOf(FoodCategory.CHEESE), legacyNoCategory!!.resolvedCategories()) + } + + @Test + fun toggleCategorySelection_handlesMultiSelectAndOtherFallback() { + var selection = listOf(FoodCategory.OTHER) + + // Adding concrete category replaces OTHER + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.PROTEIN) + assertEquals(listOf(FoodCategory.PROTEIN), selection) + + // Adding second and third categories + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.VEGETABLE) + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.BREAD) + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD), + selection + ) + + // Toggling existing category removes it + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.VEGETABLE) + assertEquals(listOf(FoodCategory.PROTEIN, FoodCategory.BREAD), selection) + + // Removing all remaining falls back to OTHER + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.PROTEIN) + selection = FoodCategory.toggleCategorySelection(selection, FoodCategory.BREAD) + assertEquals(listOf(FoodCategory.OTHER), selection) + + // Selecting OTHER resets concrete selection + selection = FoodCategory.toggleCategorySelection( + listOf(FoodCategory.PROTEIN, FoodCategory.BREAD), + FoodCategory.OTHER + ) + assertEquals(listOf(FoodCategory.OTHER), selection) + } + + @Test + fun parseCategoryList_handlesFrenchDisplayNamesWithCommasAndPlus() { + // Single category with commas inside displayName ("Viande, poisson, œufs") + val singleProtein = FoodCategory.parseCategoryList("Viande, poisson, œufs") + assertEquals(listOf(FoodCategory.PROTEIN), singleProtein) + + // Multi-category human-readable label with '+' + val multi = FoodCategory.parseCategoryList("Viande, poisson, œufs + Légumes + Pain") + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD), + multi + ) + } + + @Test + fun googleSheetsFormatter_roundTripsMultiCategoryCustomFoodsAndRecipes() { + val customKebab = LocalCustomFoodEntity.create( + name = "Kebab maison", + defaultUnit = FoodUnit.PORTION, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD) + ) + val foodRows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(listOf(customKebab), testZone) + assertEquals("Viande, poisson, œufs + Légumes + Pain", foodRows[1][3]) + + val restoredFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows) + assertEquals(1, restoredFoods.size) + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD), + restoredFoods[0].resolvedCategories() + ) + + val compositeRecipe = RecipeEntry( + id = "rec_kebab", + title = "Assiette Kebab Maison", + categoryTag = RecipeCategoryTag.MAIN.name, + prepTimeMinutes = 25, + servings = 2, + ingredientsSerialized = listOf( + MealFoodItem( + name = "Kebab maison", + weight = 2.0, + unit = FoodUnit.PORTION, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD) + ).serialize() + ), + steps = listOf("Griller la viande et garnir le pain avec les crudités.") + ) + val recipeRows = GoogleSheetsDataFormatter.formatRecipesToRows(listOf(compositeRecipe)) + val restoredRecipes = GoogleSheetsDataFormatter.parseRowsToRecipes(recipeRows) + assertEquals(1, restoredRecipes.size) + val restoredIngredients = restoredRecipes[0].parsedIngredients() + assertEquals(1, restoredIngredients.size) + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD), + restoredIngredients[0].resolvedCategories() + ) + } + + @Test + fun weeklyStatsAndDailyBenchmarks_countEveryCategoryOfCompositeDish() { + val today = LocalDate.now(testZone) + val noonMillis = today.atTime(12, 30).atZone(testZone).toInstant().toEpochMilli() + + val kebabItem = MealFoodItem( + name = "Kebab", + weight = 1.0, + unit = FoodUnit.PORTION, + categories = listOf(FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.BREAD) + ) + val meal = MealEntry( + id = "meal_kebab", + mealType = MealType.LUNCH.name, + mealTimestamp = noonMillis, + hungerBefore = 6, + satietyAfter = 8, + foodItemsSerialized = listOf(kebabItem.serialize()) + ) + + val stats = WeeklyStatsCalculator.computeWeeklyStats( + meals = listOf(meal), + zoneId = testZone + ) + assertEquals(1, stats.categoryDistribution[FoodCategory.PROTEIN]) + assertEquals(1, stats.categoryDistribution[FoodCategory.VEGETABLE]) + assertEquals(1, stats.categoryDistribution[FoodCategory.BREAD]) + + val gap = DailyBenchmarkAnalyzer.analyzeToday( + meals = listOf(meal), + targetMealType = MealType.DINNER, + today = today, + zoneId = testZone + ) + assertEquals(1, gap.presentTodayCounts[FoodCategory.PROTEIN]) + assertEquals(1, gap.presentTodayCounts[FoodCategory.VEGETABLE]) + assertEquals(1, gap.presentTodayCounts[FoodCategory.BREAD]) + assertTrue(FoodCategory.BREAD !in gap.allMissingTodayCategories) + assertTrue(FoodCategory.PROTEIN !in gap.allMissingTodayCategories) + assertTrue(FoodCategory.VEGETABLE !in gap.allMissingTodayCategories) + } + + @Test + fun customFoodLookup_resolvesMultiCategoryDishWhenMealItemHasNoExplicitCategory() { + val customEntry = CustomFoodEntry( + id = "tacos_maison", + name = "Tacos maison", + defaultUnit = FoodUnit.PORTION.code, + category = "PROTEIN,CHEESE,STARCH" + ) + val lookup = CustomFoodEntry.buildCategoriesLookup(listOf(customEntry)) + + val itemWithoutExplicitCat = MealFoodItem(name = "Tacos maison", weight = 1.0, unit = FoodUnit.PORTION) + assertEquals( + listOf(FoodCategory.PROTEIN, FoodCategory.CHEESE, FoodCategory.STARCH), + itemWithoutExplicitCat.resolvedCategories(lookup) + ) + } +} diff --git a/app/src/test/java/com/example/ReceiptScannerAnalyzerTest.kt b/app/src/test/java/com/example/ReceiptScannerAnalyzerTest.kt new file mode 100644 index 0000000..4a9d178 --- /dev/null +++ b/app/src/test/java/com/example/ReceiptScannerAnalyzerTest.kt @@ -0,0 +1,65 @@ +package com.example + +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.StorageLocation +import com.example.domain.ReceiptScannerAnalyzer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [36]) +class ReceiptScannerAnalyzerTest { + + @Test + fun parseReceiptJson_parsesFrenchItemsAndSkipsBlankEntries() { + val sampleJson = """ + { + "items": [ + { + "rawLabel": "LAIT 1/2 ECR 1L", + "name": "Lait demi-écrémé", + "quantity": 1000, + "unit": "ml", + "category": "DAIRY", + "location": "FRIDGE" + }, + { + "rawLabel": "FILET POUL 450G", + "name": "Blanc de poulet", + "quantity": 450, + "unit": "g", + "category": "PROTEIN", + "location": "FRIDGE" + }, + { + "rawLabel": "VIDE", + "name": " ", + "quantity": 1, + "unit": "portion", + "category": "OTHER", + "location": "PANTRY" + } + ] + } + """.trimIndent() + + val parsed = ReceiptScannerAnalyzer.parseReceiptJson(sampleJson) + assertEquals(2, parsed.size) + assertEquals("Lait demi-écrémé", parsed[0].name) + assertEquals(1000.0, parsed[0].quantity, 0.01) + assertEquals(FoodUnit.ML, parsed[0].unit) + assertEquals(FoodCategory.DAIRY, parsed[0].category) + assertEquals(StorageLocation.FRIDGE, parsed[0].location) + assertTrue(parsed[0].selected) + + assertEquals("Blanc de poulet", parsed[1].name) + assertEquals(450.0, parsed[1].quantity, 0.01) + assertEquals(FoodUnit.G, parsed[1].unit) + assertEquals(FoodCategory.PROTEIN, parsed[1].category) + } +} diff --git a/app/src/test/java/com/example/ShoppingListCalculatorTest.kt b/app/src/test/java/com/example/ShoppingListCalculatorTest.kt new file mode 100644 index 0000000..a221cae --- /dev/null +++ b/app/src/test/java/com/example/ShoppingListCalculatorTest.kt @@ -0,0 +1,160 @@ +package com.example + +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.InventoryItem +import com.example.data.model.ManualShoppingItem +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.data.model.ShoppingItemSource +import com.example.data.model.StorageLocation +import com.example.domain.ShoppingListCalculator +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class ShoppingListCalculatorTest { + + @Test + fun computeShoppingList_scalesRecipesSubtractsStockAndMergesManualItems() { + val recipe = RecipeEntry( + id = "rec_pasta", + title = "Pâtes au poulet", + servings = 2, + ingredientsSerialized = listOf( + MealFoodItem("Pâtes complètes", 200.0, FoodUnit.G, FoodCategory.STARCH).serialize(), + MealFoodItem("Blanc de poulet", 250.0, FoodUnit.G, FoodCategory.PROTEIN).serialize(), + MealFoodItem("Tomates", 300.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize() + ) + ) + + // Planned for 4 servings (2x the base recipe -> 400g pâtes, 500g poulet, 600g tomates) + val plannedMeals = listOf( + PlannedMealEntry( + id = "plan_1", + dateEpochDay = 20000L, + mealType = MealType.LUNCH, + recipeId = recipe.id, + servings = 4.0, + isConsumed = false + ), + // Already consumed meal should NOT generate shopping needs + PlannedMealEntry( + id = "plan_done", + dateEpochDay = 20000L, + mealType = MealType.DINNER, + customTitle = "Soupe", + itemsSerialized = listOf( + MealFoodItem("Carottes", 200.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize() + ), + isConsumed = true + ) + ) + + // Stock covers all pâtes (500g >= 400g) and partial poulet (200g of 500g needed) + val inventory = listOf( + InventoryItem( + id = "inv_1", + name = "Pâte complète", + quantity = 500.0, + unit = FoodUnit.G, + category = FoodCategory.STARCH, + location = StorageLocation.PANTRY + ), + InventoryItem( + id = "inv_2", + name = "Blanc de poulet", + quantity = 200.0, + unit = FoodUnit.G, + category = FoodCategory.PROTEIN, + location = StorageLocation.FRIDGE + ) + ) + + // Manual item merges with Tomates (+200g -> 800g) and adds Lait (1000 ml) + val manualItems = listOf( + ManualShoppingItem( + id = "man_1", + name = "Tomate", + quantity = 200.0, + unit = FoodUnit.G, + category = FoodCategory.VEGETABLE + ), + ManualShoppingItem( + id = "man_2", + name = "Lait demi-écrémé", + quantity = 1000.0, + unit = FoodUnit.ML, + category = FoodCategory.DAIRY + ) + ) + + val result = ShoppingListCalculator.computeShoppingList( + plannedMeals = plannedMeals, + recipesById = mapOf(recipe.id to recipe), + inventory = inventory, + manualItems = manualItems + ) + + // Pâtes fully covered by stock -> absent; Carottes consumed -> absent + assertNull(result.firstOrNull { it.normalizedName.contains("pate") }) + assertNull(result.firstOrNull { it.normalizedName.contains("carotte") }) + + // Poulet: 500g needed - 200g in stock = 300g missing + val chicken = result.first { it.normalizedName == "blanc de poulet" } + assertEquals(300.0, chicken.missingQuantity!!, 0.01) + assertEquals(200.0, chicken.inStockQuantity, 0.01) + assertEquals(ShoppingItemSource.FROM_PLAN, chicken.source) + + // Tomates: 600g planned + 200g manual = 800g missing + val tomatoes = result.first { it.normalizedName == "tomate" } + assertEquals(800.0, tomatoes.missingQuantity!!, 0.01) + assertEquals(ShoppingItemSource.BOTH, tomatoes.source) + assertEquals("man_1", tomatoes.manualItemId) + + // Lait: manual only + val milk = result.first { it.normalizedName == "lait demi ecreme" } + assertEquals(1000.0, milk.missingQuantity!!, 0.01) + assertEquals(ShoppingItemSource.MANUAL, milk.source) + } + + @Test + fun computeStockDeductionProposals_matchesEatenFoodsWithStock() { + val eaten = listOf( + MealFoodItem("Œufs", 2.0, FoodUnit.PORTION, FoodCategory.PROTEIN), + MealFoodItem("Lait", 300.0, FoodUnit.ML, FoodCategory.DAIRY), + MealFoodItem("Avocat", 1.0, FoodUnit.PORTION, FoodCategory.FAT_SEASONING) + ) + val inventory = listOf( + InventoryItem( + id = "i1", + name = "Oeuf", + quantity = 6.0, + unit = FoodUnit.PORTION, + category = FoodCategory.PROTEIN, + location = StorageLocation.FRIDGE + ), + InventoryItem( + id = "i2", + name = "Lait", + quantity = 200.0, + unit = FoodUnit.ML, + category = FoodCategory.DAIRY, + location = StorageLocation.FRIDGE + ) + ) + + val proposals = ShoppingListCalculator.computeStockDeductionProposals(eaten, inventory) + assertEquals(2, proposals.size) + + val eggProposal = proposals.first { it.inventoryItem.id == "i1" } + assertEquals(2.0, eggProposal.deductAmount, 0.01) + assertEquals(4.0, eggProposal.remainingAfter, 0.01) + + val milkProposal = proposals.first { it.inventoryItem.id == "i2" } + assertEquals(200.0, milkProposal.deductAmount, 0.01) + assertEquals(0.0, milkProposal.remainingAfter, 0.01) + } +}