From 8260dba5a584c023e42b9b75835e6487a2be0802 Mon Sep 17 00:00:00 2001 From: bleackstorm <49142331+bleackstorm@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:56:44 +0100 Subject: [PATCH] refactor: improve robustness and accessibility - Refactor MealRepository methods to be open for extension - Add finiteness checks for quantity calculations - Update receipt icon to support RTL layouts - Adjust component visibility modifiers --- .../preferences/PlanningPreferencesManager.kt | 2 +- .../example/data/repository/MealRepository.kt | 8 +- .../com/example/domain/IngredientMatcher.kt | 8 +- .../example/domain/ShoppingListCalculator.kt | 8 +- .../com/example/domain/WeeklyMealPredictor.kt | 85 +++--- .../example/ui/planning/PlanningViewModel.kt | 136 +++++++-- .../example/ui/planning/ReceiptReviewSheet.kt | 4 +- .../example/PlanningPreferencesManagerTest.kt | 60 ++++ .../java/com/example/PlanningViewModelTest.kt | 279 ++++++++++++++++++ .../com/example/WeeklyMealPredictorTest.kt | 41 +++ 10 files changed, 551 insertions(+), 80 deletions(-) create mode 100644 app/src/test/java/com/example/PlanningPreferencesManagerTest.kt create mode 100644 app/src/test/java/com/example/PlanningViewModelTest.kt diff --git a/app/src/main/java/com/example/data/preferences/PlanningPreferencesManager.kt b/app/src/main/java/com/example/data/preferences/PlanningPreferencesManager.kt index 808c90e..b3bb5ba 100644 --- a/app/src/main/java/com/example/data/preferences/PlanningPreferencesManager.kt +++ b/app/src/main/java/com/example/data/preferences/PlanningPreferencesManager.kt @@ -6,7 +6,7 @@ import android.content.Context * Stores lightweight planning & shopping session state (such as checked plan-derived * shopping items) so in-store progress survives backgrounding or app restarts. */ -class PlanningPreferencesManager private constructor(context: Context) { +class PlanningPreferencesManager internal constructor(context: Context) { private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) 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 936863d..30231c0 100644 --- a/app/src/main/java/com/example/data/repository/MealRepository.kt +++ b/app/src/main/java/com/example/data/repository/MealRepository.kt @@ -44,7 +44,7 @@ data class RestoredDataCounts( * All meals, custom foods, and recipes live locally on device, while optional * backup and restoration use the user's personal Google Drive / Sheets. */ -class MealRepository( +open class MealRepository( private val localMealDao: LocalMealDao, private val context: Context? = null ) { @@ -363,7 +363,7 @@ class MealRepository( } } - suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result { + open suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result { val entity = LocalPlannedMealEntity.fromDomain(entry) localMealDao.upsertPlannedMeal(entity) return Result.success(entity.id) @@ -413,7 +413,7 @@ class MealRepository( * 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( + open suspend fun addOrMergeInventoryItem( name: String, quantityToAdd: Double, unit: FoodUnit, @@ -502,7 +502,7 @@ class MealRepository( return Result.success(Unit) } - suspend fun deleteManualShoppingItem(itemId: String): Result { + open suspend fun deleteManualShoppingItem(itemId: String): Result { localMealDao.deleteManualShoppingItemById(itemId) return Result.success(Unit) } diff --git a/app/src/main/java/com/example/domain/IngredientMatcher.kt b/app/src/main/java/com/example/domain/IngredientMatcher.kt index b186c21..9fa799e 100644 --- a/app/src/main/java/com/example/domain/IngredientMatcher.kt +++ b/app/src/main/java/com/example/domain/IngredientMatcher.kt @@ -62,12 +62,8 @@ object IngredientMatcher { } 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 - } + if (quantity == null || !quantity.isFinite() || quantity <= 0.0) return unit.label + val rounded = Math.round(quantity * 10.0) / 10.0 val numStr = if (rounded % 1.0 == 0.0) { rounded.toInt().toString() } else { diff --git a/app/src/main/java/com/example/domain/ShoppingListCalculator.kt b/app/src/main/java/com/example/domain/ShoppingListCalculator.kt index b484f73..3bba1b7 100644 --- a/app/src/main/java/com/example/domain/ShoppingListCalculator.kt +++ b/app/src/main/java/com/example/domain/ShoppingListCalculator.kt @@ -231,11 +231,7 @@ object ShoppingListCalculator { } 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 - } + if (!value.isFinite() || value <= 0.0) return 0.0 + return Math.round(value * 10.0) / 10.0 } } diff --git a/app/src/main/java/com/example/domain/WeeklyMealPredictor.kt b/app/src/main/java/com/example/domain/WeeklyMealPredictor.kt index 7dfd89a..6f839be 100644 --- a/app/src/main/java/com/example/domain/WeeklyMealPredictor.kt +++ b/app/src/main/java/com/example/domain/WeeklyMealPredictor.kt @@ -16,8 +16,8 @@ import com.google.firebase.Firebase import com.google.firebase.ai.ai import com.google.firebase.ai.type.Schema import com.google.firebase.ai.type.generationConfig +import com.squareup.moshi.JsonClass import com.squareup.moshi.Moshi -import com.squareup.moshi.Types import kotlinx.coroutines.CancellationException import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.withTimeout @@ -262,15 +262,12 @@ RÈGLES STRICTES : private const val TAG = "WeeklyMealPredictor" private val moshi: Moshi = Moshi.Builder().build() - private val mapAdapter = moshi.adapter>( - Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java) - ) + private val responseAdapter = moshi.adapter(PredictionResponseDto::class.java).lenient() /** - * Pure JVM JSON parser (Moshi-backed) for offline testability and resilient handling + * Pure JVM JSON parser (typed Moshi DTOs) for offline testability and resilient handling * of Gemini structured JSON responses. */ - @Suppress("UNCHECKED_CAST") fun parsePredictionJson( jsonString: String, emptySlots: List>, @@ -279,56 +276,47 @@ RÈGLES STRICTES : ): List { if (jsonString.isBlank() || emptySlots.isEmpty()) return emptyList() val root = try { - mapAdapter.fromJson(jsonString) + responseAdapter.fromJson(jsonString) } catch (_: Exception) { null } ?: return emptyList() - val mealsList = root["meals"] as? List<*> ?: return emptyList() + val mealsList = root.meals ?: return emptyList() val usedSlotIndices = mutableSetOf() val proposals = mutableListOf() - for (rawEntry in mealsList) { - val obj = rawEntry as? Map<*, *> ?: continue - val slotIndex = (obj["slotIndex"] as? Number)?.toInt() ?: continue + for (mealDto in mealsList) { + val slotIndex = mealDto.slotIndex ?: continue if (slotIndex !in emptySlots.indices || !usedSlotIndices.add(slotIndex)) continue val (date, mealType) = emptySlots[slotIndex] - val rawRecipeId = (obj["recipeId"] as? String)?.trim().orEmpty() + val rawRecipeId = mealDto.recipeId?.trim().orEmpty() val matchedRecipe = rawRecipeId.takeIf { it.isNotBlank() }?.let { recipesById[it] } - val rawTitle = (obj["title"] as? String)?.trim().orEmpty() + val rawTitle = mealDto.title?.trim().orEmpty() val resolvedTitle = when { - matchedRecipe != null && rawTitle.isBlank() -> matchedRecipe.title matchedRecipe != null -> matchedRecipe.title rawTitle.isNotBlank() -> rawTitle else -> continue } - val reason = (obj["reason"] as? String)?.trim().orEmpty() - val safeServings = defaultServings.coerceAtLeast(0.5) + val reason = mealDto.reason?.trim().orEmpty() + val safeServings = defaultServings.takeIf { it.isFinite() }?.coerceAtLeast(0.5) ?: 1.0 - val parsedIngredients = mutableListOf() - val rawIngredients = obj["ingredients"] as? List<*> - if (rawIngredients != null) { - for (rawIng in rawIngredients) { - val ingObj = rawIng as? Map<*, *> ?: continue - val ingName = (ingObj["name"] as? String)?.trim().orEmpty() - if (ingName.isBlank()) continue - val weight = (ingObj["weight"] as? Number)?.toDouble()?.takeIf { !it.isNaN() && it > 0.0 } - val unit = FoodUnit.fromCode((ingObj["unit"] as? String) ?: "portion") - val category = FoodCategory.fromCode(ingObj["category"] as? String) - ?: FoodCategory.inferFromName(ingName) - parsedIngredients.add( - MealFoodItem( - name = ingName, - weight = weight, - unit = unit, - category = category, - categories = listOf(category) - ) - ) - } + val parsedIngredients = mealDto.ingredients.orEmpty().mapNotNull { ingDto -> + val ingName = ingDto.name?.trim().orEmpty() + if (ingName.isBlank()) return@mapNotNull null + val weight = ingDto.weight?.takeIf { it.isFinite() && it > 0.0 } + val unit = FoodUnit.fromCode(ingDto.unit ?: "portion") + val category = FoodCategory.fromCode(ingDto.category) + ?: FoodCategory.inferFromName(ingName) + MealFoodItem( + name = ingName, + weight = weight, + unit = unit, + category = category, + categories = listOf(category) + ) } val resolvedItems = if (matchedRecipe != null) { @@ -359,3 +347,26 @@ RÈGLES STRICTES : } } } + +@JsonClass(generateAdapter = true) +internal data class PredictionResponseDto( + val meals: List? = null +) + +@JsonClass(generateAdapter = true) +internal data class PredictedMealDto( + val slotIndex: Int? = null, + val recipeId: String? = null, + val title: String? = null, + val reason: String? = null, + val ingredients: List? = null +) + +@JsonClass(generateAdapter = true) +internal data class PredictedIngredientDto( + val name: String? = null, + val weight: Double? = null, + val unit: String? = null, + val category: String? = null +) + diff --git a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt index 7148f7c..7fa8dc9 100644 --- a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt +++ b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt @@ -6,10 +6,13 @@ 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.FoodPreferenceEntry 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.PredictedMealProposal import com.example.data.model.PredictionMealScope @@ -30,6 +33,7 @@ import com.example.ui.common.UiEvent import com.example.util.ImageUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -42,19 +46,66 @@ import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.updateAndGet import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import java.time.DayOfWeek import java.time.LocalDate import java.time.temporal.TemporalAdjusters import java.util.UUID +internal fun interface WeekSlotPredictor { + suspend fun predictEmptySlots( + emptySlots: List>, + existingWeekMeals: List, + inventory: List, + recipes: List, + preferences: List, + recentJournalMeals: List, + defaultServings: Double + ): Result> +} + @OptIn(ExperimentalCoroutinesApi::class) -class PlanningViewModel(application: Application) : AndroidViewModel(application) { +class PlanningViewModel internal constructor( + application: Application, + private val repository: MealRepository, + private val planningPrefs: PlanningPreferencesManager, + private val weekSlotPredictor: WeekSlotPredictor +) : AndroidViewModel(application) { + + constructor(application: Application) : this( + application = application, + repository = MealRepository(application), + planningPrefs = PlanningPreferencesManager.getInstance(application), + weekSlotPredictor = object : WeekSlotPredictor { + private val delegate by lazy { WeeklyMealPredictor() } + override suspend fun predictEmptySlots( + emptySlots: List>, + existingWeekMeals: List, + inventory: List, + recipes: List, + preferences: List, + recentJournalMeals: List, + defaultServings: Double + ): Result> { + return delegate.predictEmptySlots( + emptySlots = emptySlots, + existingWeekMeals = existingWeekMeals, + inventory = inventory, + recipes = recipes, + preferences = preferences, + recentJournalMeals = recentJournalMeals, + defaultServings = defaultServings + ) + } + } + ) - private val repository = MealRepository(application) - private val planningPrefs = PlanningPreferencesManager.getInstance(application) private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() } - private val weeklyMealPredictor by lazy { WeeklyMealPredictor() } + private val checkedKeysMutex = Mutex() + private var predictionJob: Job? = null private val _uiEvents = Channel(Channel.BUFFERED) val uiEvents: Flow = _uiEvents.receiveAsFlow() @@ -140,10 +191,11 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application private val _pendingStockDeductions = MutableStateFlow?>(null) val pendingStockDeductions: StateFlow?> = _pendingStockDeductions.asStateFlow() - private fun updateCheckedPlanKeys(transform: (Set) -> Set) { - val updated = transform(_checkedPlanKeys.value) - _checkedPlanKeys.value = updated - planningPrefs.setCheckedPlanKeys(updated) + private suspend fun updateCheckedPlanKeys(transform: (Set) -> Set) { + checkedKeysMutex.withLock { + val updated = _checkedPlanKeys.updateAndGet(transform) + planningPrefs.setCheckedPlanKeys(updated) + } } // ------------------------------------------------------------------------ @@ -357,8 +409,9 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application } /** - * Batch-transfers all checked shopping items into kitchen inventory at the end of a shopping trip, - * clears checked manual items, and removes processed plan-derived checked keys. + * Batch-transfers checked shopping items into kitchen inventory at the end of a shopping trip. + * Only items whose stock addition succeeded are removed from checked plan keys / manual items, + * preventing data loss on partial failures. */ fun finishShoppingAndAddToStock( checkedItems: List, @@ -367,10 +420,12 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application if (checkedItems.isEmpty()) return viewModelScope.launch { var addedCount = 0 + var failedCount = 0 val processedPlanKeys = mutableSetOf() + val processedManualIds = mutableSetOf() checkedItems.forEach { item -> - val qtyToAdd = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0 + val qtyToAdd = item.missingQuantity?.takeIf { it.isFinite() && it > 0.0 } ?: 1.0 val location = locationsByKey[item.key] ?: StorageLocation.defaultForCategory(item.category) val result = repository.addOrMergeInventoryItem( name = item.name, @@ -381,19 +436,30 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application ) if (result.isSuccess) { addedCount++ - } - if (item.key.startsWith("plan_")) { - processedPlanKeys.add(item.key) + if (item.key.startsWith("plan_")) { + processedPlanKeys.add(item.key) + } + item.manualItemId?.let { processedManualIds.add(it) } + } else { + failedCount++ } } - repository.clearCheckedManualShoppingItems() + processedManualIds.forEach { manualId -> + repository.deleteManualShoppingItem(manualId) + } if (processedPlanKeys.isNotEmpty()) { updateCheckedPlanKeys { it - processedPlanKeys } } - if (addedCount > 0) { - emitSnackbar( + when { + failedCount > 0 && addedCount > 0 -> emitSnackbar( + "$addedCount ajouté${if (addedCount > 1) "s" else ""} au stock, $failedCount en échec" + ) + failedCount > 0 -> emitSnackbar( + "Impossible d'ajouter $failedCount article${if (failedCount > 1) "s" else ""} au stock" + ) + addedCount > 0 -> emitSnackbar( "$addedCount article${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} au stock" ) } @@ -422,7 +488,8 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application scope: PredictionMealScope, defaultServings: Double ) { - viewModelScope.launch { + predictionJob?.cancel() + predictionJob = viewModelScope.launch { val start = _weekStartDate.value val existingMeals = weekPlannedMeals.value val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet() @@ -455,7 +522,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application val preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() } val recentMeals = repository.getAllMealsSnapshot() - val result = weeklyMealPredictor.predictEmptySlots( + val result = weekSlotPredictor.predictEmptySlots( emptySlots = emptySlots, existingWeekMeals = existingMeals, inventory = inventory, @@ -533,17 +600,38 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application } viewModelScope.launch { + var savedCount = 0 + val failedProposals = mutableListOf() + selectedProposals.forEach { proposal -> - repository.upsertPlannedMeal(proposal.toPlannedMealEntry()) + val result = repository.upsertPlannedMeal(proposal.toPlannedMealEntry()) + if (result.isSuccess) { + savedCount++ + } else { + failedProposals.add(proposal) + } + } + + if (failedProposals.isEmpty()) { + _weekPredictionState.value = WeekPredictionUiState.Idle + emitSnackbar( + "$savedCount repas ajouté${if (savedCount > 1) "s" else ""} au planning • courses mises à jour" + ) + } else { + _weekPredictionState.value = preview.copy(proposals = failedProposals) + val message = if (savedCount > 0) { + "$savedCount repas ajouté${if (savedCount > 1) "s" else ""}, ${failedProposals.size} en échec — vous pouvez réessayer" + } else { + "Impossible d'enregistrer les repas sélectionnés (${failedProposals.size} en échec)" + } + emitSnackbar(message) } - _weekPredictionState.value = WeekPredictionUiState.Idle - emitSnackbar( - "${selectedProposals.size} repas ajouté${if (selectedProposals.size > 1) "s" else ""} au planning • courses mises à jour" - ) } } fun dismissWeekPrediction() { + predictionJob?.cancel() + predictionJob = null _weekPredictionState.value = WeekPredictionUiState.Idle } diff --git a/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt b/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt index 6970e6e..2fff1c4 100644 --- a/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt +++ b/app/src/main/java/com/example/ui/planning/ReceiptReviewSheet.kt @@ -18,10 +18,10 @@ 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.automirrored.filled.ReceiptLong 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 @@ -181,7 +181,7 @@ fun ReceiptReviewSheet( modifier = Modifier.weight(1f) ) { Icon( - imageVector = Icons.Default.ReceiptLong, + imageVector = Icons.AutoMirrored.Filled.ReceiptLong, contentDescription = null, tint = MaterialTheme.colorScheme.primary ) diff --git a/app/src/test/java/com/example/PlanningPreferencesManagerTest.kt b/app/src/test/java/com/example/PlanningPreferencesManagerTest.kt new file mode 100644 index 0000000..3a6fd3b --- /dev/null +++ b/app/src/test/java/com/example/PlanningPreferencesManagerTest.kt @@ -0,0 +1,60 @@ +package com.example + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.example.data.preferences.PlanningPreferencesManager +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +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 PlanningPreferencesManagerTest { + + private lateinit var manager: PlanningPreferencesManager + + @Before + fun setup() { + val context = ApplicationProvider.getApplicationContext() + context.getSharedPreferences("satiea_planning_prefs", Context.MODE_PRIVATE) + .edit() + .clear() + .commit() + manager = PlanningPreferencesManager(context) + } + + @Test + fun checkedPlanKeys_persistsAndReadsBackAccurately() { + assertTrue(manager.getCheckedPlanKeys().isEmpty()) + + val keys = setOf("plan_tomate_g", "plan_lait_ml") + manager.setCheckedPlanKeys(keys) + + assertEquals(keys, manager.getCheckedPlanKeys()) + + manager.setCheckedPlanKeys(emptySet()) + assertTrue(manager.getCheckedPlanKeys().isEmpty()) + } + + @Test + fun checkedPlanKeys_providesDefensiveCopyIsolation() { + val mutableSource = mutableSetOf("plan_poulet_g") + manager.setCheckedPlanKeys(mutableSource) + + // Mutating original caller set must not affect persisted keys + mutableSource.add("plan_mutated_g") + val readBack = manager.getCheckedPlanKeys() + assertEquals(setOf("plan_poulet_g"), readBack) + assertFalse("plan_mutated_g" in readBack) + + // Mutating a mutable copy of the returned set must not affect subsequent reads + val callerCopy = readBack.toMutableSet() + callerCopy.add("plan_external_g") + assertEquals(setOf("plan_poulet_g"), manager.getCheckedPlanKeys()) + } +} diff --git a/app/src/test/java/com/example/PlanningViewModelTest.kt b/app/src/test/java/com/example/PlanningViewModelTest.kt new file mode 100644 index 0000000..ae66430 --- /dev/null +++ b/app/src/test/java/com/example/PlanningViewModelTest.kt @@ -0,0 +1,279 @@ +package com.example + +import android.app.Application +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import com.example.data.local.AppDatabase +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.ManualShoppingItem +import com.example.data.model.MealType +import com.example.data.model.PlannedMealEntry +import com.example.data.model.PredictedMealProposal +import com.example.data.model.PredictionMealScope +import com.example.data.model.ShoppingItemSource +import com.example.data.model.ShoppingListItem +import com.example.data.model.StorageLocation +import com.example.data.model.WeekPredictionUiState +import com.example.data.preferences.PlanningPreferencesManager +import com.example.data.repository.MealRepository +import com.example.ui.common.UiEvent +import com.example.ui.planning.PlanningViewModel +import com.example.ui.planning.WeekSlotPredictor +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.time.LocalDate + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [36]) +class PlanningViewModelTest { + + private lateinit var app: Application + private lateinit var db: AppDatabase + private lateinit var prefs: PlanningPreferencesManager + private val testDispatcher = UnconfinedTestDispatcher() + + @Before + fun setup() { + Dispatchers.setMain(testDispatcher) + app = ApplicationProvider.getApplicationContext() + app.getSharedPreferences("satiea_planning_prefs", Application.MODE_PRIVATE) + .edit() + .clear() + .commit() + db = Room.inMemoryDatabaseBuilder(app, AppDatabase::class.java) + .allowMainThreadQueries() + .setQueryExecutor(Runnable::run) + .setTransactionExecutor(Runnable::run) + .build() + prefs = PlanningPreferencesManager(app) + } + + @After + fun teardown() { + db.close() + Dispatchers.resetMain() + } + + @Test + fun finishShoppingAndAddToStock_preservesFailedItemsAndDeletesOnlySucceededOnes() = runTest { + val failingRepo = object : MealRepository(db.mealDao(), app) { + override suspend fun addOrMergeInventoryItem( + name: String, + quantityToAdd: Double, + unit: FoodUnit, + category: FoodCategory, + location: StorageLocation + ): Result { + return if (name.contains("Échec")) { + Result.failure(IllegalStateException("Simulated stock write error")) + } else { + super.addOrMergeInventoryItem(name, quantityToAdd, unit, category, location) + } + } + } + + // Seed 2 checked manual items in Room (one will succeed, one will fail) + val okManualId = failingRepo.upsertManualShoppingItem( + ManualShoppingItem( + id = "man_ok", + name = "Pommes", + quantity = 4.0, + unit = FoodUnit.PORTION, + category = FoodCategory.FRUIT, + isChecked = true + ) + ).getOrThrow() + val failManualId = failingRepo.upsertManualShoppingItem( + ManualShoppingItem( + id = "man_fail", + name = "Échec Beurre", + quantity = 250.0, + unit = FoodUnit.G, + category = FoodCategory.FAT_SEASONING, + isChecked = true + ) + ).getOrThrow() + + // Seed 2 checked plan keys in prefs (one will succeed, one will fail) + val okPlanKey = "plan_carotte_g" + val failPlanKey = "plan_echec_lait_ml" + prefs.setCheckedPlanKeys(setOf(okPlanKey, failPlanKey)) + + val vm = PlanningViewModel( + application = app, + repository = failingRepo, + planningPrefs = prefs, + weekSlotPredictor = WeekSlotPredictor { _, _, _, _, _, _, _ -> Result.success(emptyList()) } + ) + + val checkedItems = listOf( + ShoppingListItem( + key = "manual_$okManualId", + name = "Pommes", + normalizedName = "pomme", + missingQuantity = 4.0, + requiredQuantity = 4.0, + inStockQuantity = 0.0, + unit = FoodUnit.PORTION, + category = FoodCategory.FRUIT, + source = ShoppingItemSource.MANUAL, + manualItemId = okManualId, + isChecked = true + ), + ShoppingListItem( + key = "manual_$failManualId", + name = "Échec Beurre", + normalizedName = "echec beurre", + missingQuantity = 250.0, + requiredQuantity = 250.0, + inStockQuantity = 0.0, + unit = FoodUnit.G, + category = FoodCategory.FAT_SEASONING, + source = ShoppingItemSource.MANUAL, + manualItemId = failManualId, + isChecked = true + ), + ShoppingListItem( + key = okPlanKey, + name = "Carottes", + normalizedName = "carotte", + missingQuantity = 300.0, + requiredQuantity = 300.0, + inStockQuantity = 0.0, + unit = FoodUnit.G, + category = FoodCategory.VEGETABLE, + source = ShoppingItemSource.FROM_PLAN, + manualItemId = null, + isChecked = true + ), + ShoppingListItem( + key = failPlanKey, + name = "Échec Lait", + normalizedName = "echec lait", + missingQuantity = 1000.0, + requiredQuantity = 1000.0, + inStockQuantity = 0.0, + unit = FoodUnit.ML, + category = FoodCategory.DAIRY, + source = ShoppingItemSource.FROM_PLAN, + manualItemId = null, + isChecked = true + ) + ) + + vm.finishShoppingAndAddToStock(checkedItems, emptyMap()) + + // Succeeded items were added to stock; failed items were not + val stockNames = failingRepo.getInventorySnapshot().map { it.name }.toSet() + assertEquals(setOf("Pommes", "Carottes"), stockNames) + + // Failed manual item is preserved in Room; succeeded manual item was deleted + val remainingManualIds = failingRepo.getManualShoppingItemsSnapshot().map { it.id } + assertEquals(listOf(failManualId), remainingManualIds) + + // Failed plan key is preserved in preferences; succeeded plan key was removed + val remainingPlanKeys = prefs.getCheckedPlanKeys() + assertEquals(setOf(failPlanKey), remainingPlanKeys) + + // Explicit partial-failure snackbar emitted + val event = vm.uiEvents.first() as UiEvent.ShowSnackbar + assertTrue(event.message.contains("2 ajoutés au stock")) + assertTrue(event.message.contains("2 en échec")) + } + + @Test + fun dismissWeekPrediction_cancelsInFlightPredictionWithoutOverwritingIdle() = runTest { + val repo = MealRepository(db.mealDao(), app) + val gate = CompletableDeferred>>() + + val vm = PlanningViewModel( + application = app, + repository = repo, + planningPrefs = prefs, + weekSlotPredictor = WeekSlotPredictor { _, _, _, _, _, _, _ -> gate.await() } + ) + + vm.predictEmptyWeekMeals(PredictionMealScope.MAIN_MEALS, defaultServings = 2.0) + assertEquals(WeekPredictionUiState.Loading, vm.weekPredictionState.value) + + // User dismisses sheet while AI request is still in-flight + vm.dismissWeekPrediction() + assertEquals(WeekPredictionUiState.Idle, vm.weekPredictionState.value) + + // Even if the deferred completes later, the cancelled coroutine must never overwrite Idle + val lateProposal = PredictedMealProposal( + dateEpochDay = LocalDate.now().toEpochDay(), + mealType = MealType.LUNCH, + title = "Repas tardif" + ) + gate.complete(Result.success(listOf(lateProposal))) + + assertEquals(WeekPredictionUiState.Idle, vm.weekPredictionState.value) + } + + @Test + fun confirmPredictedMeals_keepsUnsavedProposalsInPreviewOnPartialFailure() = runTest { + val partiallyFailingRepo = object : MealRepository(db.mealDao(), app) { + override suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result { + return if (entry.customTitle.contains("Échec")) { + Result.failure(IllegalStateException("Simulated DB failure")) + } else { + super.upsertPlannedMeal(entry) + } + } + } + + val todayEpoch = LocalDate.now().toEpochDay() + val proposals = listOf( + PredictedMealProposal( + id = "p_ok", + dateEpochDay = todayEpoch, + mealType = MealType.LUNCH, + title = "Salade verte" + ), + PredictedMealProposal( + id = "p_fail", + dateEpochDay = todayEpoch, + mealType = MealType.DINNER, + title = "Échec Gratin" + ) + ) + + val vm = PlanningViewModel( + application = app, + repository = partiallyFailingRepo, + planningPrefs = prefs, + weekSlotPredictor = WeekSlotPredictor { _, _, _, _, _, _, _ -> Result.success(proposals) } + ) + + vm.predictEmptyWeekMeals(PredictionMealScope.MAIN_MEALS, defaultServings = 1.0) + assertTrue(vm.weekPredictionState.value is WeekPredictionUiState.Preview) + + vm.confirmPredictedMeals() + + // Must stay in Preview with ONLY the failed proposal so user can retry without losing it + val stateAfter = vm.weekPredictionState.value + assertTrue(stateAfter is WeekPredictionUiState.Preview) + val remaining = (stateAfter as WeekPredictionUiState.Preview).proposals + assertEquals(1, remaining.size) + assertEquals("p_fail", remaining[0].id) + assertFalse(remaining.any { it.id == "p_ok" }) + } +} diff --git a/app/src/test/java/com/example/WeeklyMealPredictorTest.kt b/app/src/test/java/com/example/WeeklyMealPredictorTest.kt index e4fa536..d29e778 100644 --- a/app/src/test/java/com/example/WeeklyMealPredictorTest.kt +++ b/app/src/test/java/com/example/WeeklyMealPredictorTest.kt @@ -115,4 +115,45 @@ class WeeklyMealPredictorTest { ) assertTrue(parsed.isEmpty()) } + + @Test + fun parsePredictionJson_rejectsInfinityNaNAndNegativeWeights() { + val monday = LocalDate.of(2026, 11, 23) + val slots = listOf(monday to MealType.DINNER) + val jsonWithNonFiniteNumbers = """ + { + "meals": [ + { + "slotIndex": 0, + "recipeId": "", + "title": "Bol équilibré", + "reason": "Test valeurs numériques", + "ingredients": [ + { "name": "Riz", "weight": Infinity, "unit": "g", "category": "STARCH" }, + { "name": "Carottes", "weight": -Infinity, "unit": "g", "category": "VEGETABLE" }, + { "name": "Poulet", "weight": NaN, "unit": "g", "category": "PROTEIN" }, + { "name": "Huile d'olive", "weight": -10, "unit": "ml", "category": "FAT_SEASONING" }, + { "name": "Brocolis", "weight": 200, "unit": "g", "category": "VEGETABLE" } + ] + } + ] + } + """.trimIndent() + + val proposals = WeeklyMealPredictor.parsePredictionJson( + jsonString = jsonWithNonFiniteNumbers, + emptySlots = slots, + recipesById = emptyMap(), + defaultServings = 1.0 + ) + + assertEquals(1, proposals.size) + val ingredients = proposals[0].items + assertEquals(5, ingredients.size) + assertNull(ingredients[0].weight) + assertNull(ingredients[1].weight) + assertNull(ingredients[2].weight) + assertNull(ingredients[3].weight) + assertEquals(200.0, ingredients[4].weight!!, 0.01) + } }