mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
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
This commit is contained in:
1 parent
a2f59f15d4
commit
8260dba5a5
10 files changed
+537
-66
No files matched your search
@@ -6,7 +6,7 @@ import android.content.Context
|
|||||||
* Stores lightweight planning & shopping session state (such as checked plan-derived
|
* Stores lightweight planning & shopping session state (such as checked plan-derived
|
||||||
* shopping items) so in-store progress survives backgrounding or app restarts.
|
* 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)
|
private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ data class RestoredDataCounts(
|
|||||||
* All meals, custom foods, and recipes live locally on device, while optional
|
* All meals, custom foods, and recipes live locally on device, while optional
|
||||||
* backup and restoration use the user's personal Google Drive / Sheets.
|
* backup and restoration use the user's personal Google Drive / Sheets.
|
||||||
*/
|
*/
|
||||||
class MealRepository(
|
open class MealRepository(
|
||||||
private val localMealDao: LocalMealDao,
|
private val localMealDao: LocalMealDao,
|
||||||
private val context: Context? = null
|
private val context: Context? = null
|
||||||
) {
|
) {
|
||||||
@@ -363,7 +363,7 @@ class MealRepository(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result<String> {
|
open suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result<String> {
|
||||||
val entity = LocalPlannedMealEntity.fromDomain(entry)
|
val entity = LocalPlannedMealEntity.fromDomain(entry)
|
||||||
localMealDao.upsertPlannedMeal(entity)
|
localMealDao.upsertPlannedMeal(entity)
|
||||||
return Result.success(entity.id)
|
return Result.success(entity.id)
|
||||||
@@ -413,7 +413,7 @@ class MealRepository(
|
|||||||
* Adds quantity into stock, automatically merging with an existing stock entry if one
|
* Adds quantity into stock, automatically merging with an existing stock entry if one
|
||||||
* already exists with the same normalized name and unit.
|
* already exists with the same normalized name and unit.
|
||||||
*/
|
*/
|
||||||
suspend fun addOrMergeInventoryItem(
|
open suspend fun addOrMergeInventoryItem(
|
||||||
name: String,
|
name: String,
|
||||||
quantityToAdd: Double,
|
quantityToAdd: Double,
|
||||||
unit: FoodUnit,
|
unit: FoodUnit,
|
||||||
@@ -502,7 +502,7 @@ class MealRepository(
|
|||||||
return Result.success(Unit)
|
return Result.success(Unit)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteManualShoppingItem(itemId: String): Result<Unit> {
|
open suspend fun deleteManualShoppingItem(itemId: String): Result<Unit> {
|
||||||
localMealDao.deleteManualShoppingItemById(itemId)
|
localMealDao.deleteManualShoppingItemById(itemId)
|
||||||
return Result.success(Unit)
|
return Result.success(Unit)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,12 +62,8 @@ object IngredientMatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun formatQuantity(quantity: Double?, unit: FoodUnit): String {
|
fun formatQuantity(quantity: Double?, unit: FoodUnit): String {
|
||||||
if (quantity == null || quantity <= 0.0) return unit.label
|
if (quantity == null || !quantity.isFinite() || quantity <= 0.0) return unit.label
|
||||||
val rounded = if (unit == FoodUnit.PORTION) {
|
val rounded = Math.round(quantity * 10.0) / 10.0
|
||||||
Math.round(quantity * 10.0) / 10.0
|
|
||||||
} else {
|
|
||||||
Math.round(quantity * 10.0) / 10.0
|
|
||||||
}
|
|
||||||
val numStr = if (rounded % 1.0 == 0.0) {
|
val numStr = if (rounded % 1.0 == 0.0) {
|
||||||
rounded.toInt().toString()
|
rounded.toInt().toString()
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -231,11 +231,7 @@ object ShoppingListCalculator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun roundClean(value: Double, unit: FoodUnit): Double {
|
private fun roundClean(value: Double, unit: FoodUnit): Double {
|
||||||
if (value <= 0.0) return 0.0
|
if (!value.isFinite() || value <= 0.0) return 0.0
|
||||||
return if (unit == FoodUnit.PORTION) {
|
return Math.round(value * 10.0) / 10.0
|
||||||
Math.round(value * 10.0) / 10.0
|
|
||||||
} else {
|
|
||||||
Math.round(value * 10.0) / 10.0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,8 +16,8 @@ import com.google.firebase.Firebase
|
|||||||
import com.google.firebase.ai.ai
|
import com.google.firebase.ai.ai
|
||||||
import com.google.firebase.ai.type.Schema
|
import com.google.firebase.ai.type.Schema
|
||||||
import com.google.firebase.ai.type.generationConfig
|
import com.google.firebase.ai.type.generationConfig
|
||||||
|
import com.squareup.moshi.JsonClass
|
||||||
import com.squareup.moshi.Moshi
|
import com.squareup.moshi.Moshi
|
||||||
import com.squareup.moshi.Types
|
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.TimeoutCancellationException
|
import kotlinx.coroutines.TimeoutCancellationException
|
||||||
import kotlinx.coroutines.withTimeout
|
import kotlinx.coroutines.withTimeout
|
||||||
@@ -262,15 +262,12 @@ RÈGLES STRICTES :
|
|||||||
private const val TAG = "WeeklyMealPredictor"
|
private const val TAG = "WeeklyMealPredictor"
|
||||||
|
|
||||||
private val moshi: Moshi = Moshi.Builder().build()
|
private val moshi: Moshi = Moshi.Builder().build()
|
||||||
private val mapAdapter = moshi.adapter<Map<String, Any>>(
|
private val responseAdapter = moshi.adapter(PredictionResponseDto::class.java).lenient()
|
||||||
Types.newParameterizedType(Map::class.java, String::class.java, Any::class.java)
|
|
||||||
)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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.
|
* of Gemini structured JSON responses.
|
||||||
*/
|
*/
|
||||||
@Suppress("UNCHECKED_CAST")
|
|
||||||
fun parsePredictionJson(
|
fun parsePredictionJson(
|
||||||
jsonString: String,
|
jsonString: String,
|
||||||
emptySlots: List<Pair<LocalDate, MealType>>,
|
emptySlots: List<Pair<LocalDate, MealType>>,
|
||||||
@@ -279,47 +276,40 @@ RÈGLES STRICTES :
|
|||||||
): List<PredictedMealProposal> {
|
): List<PredictedMealProposal> {
|
||||||
if (jsonString.isBlank() || emptySlots.isEmpty()) return emptyList()
|
if (jsonString.isBlank() || emptySlots.isEmpty()) return emptyList()
|
||||||
val root = try {
|
val root = try {
|
||||||
mapAdapter.fromJson(jsonString)
|
responseAdapter.fromJson(jsonString)
|
||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
} ?: return emptyList()
|
} ?: return emptyList()
|
||||||
|
|
||||||
val mealsList = root["meals"] as? List<*> ?: return emptyList()
|
val mealsList = root.meals ?: return emptyList()
|
||||||
val usedSlotIndices = mutableSetOf<Int>()
|
val usedSlotIndices = mutableSetOf<Int>()
|
||||||
val proposals = mutableListOf<PredictedMealProposal>()
|
val proposals = mutableListOf<PredictedMealProposal>()
|
||||||
|
|
||||||
for (rawEntry in mealsList) {
|
for (mealDto in mealsList) {
|
||||||
val obj = rawEntry as? Map<*, *> ?: continue
|
val slotIndex = mealDto.slotIndex ?: continue
|
||||||
val slotIndex = (obj["slotIndex"] as? Number)?.toInt() ?: continue
|
|
||||||
if (slotIndex !in emptySlots.indices || !usedSlotIndices.add(slotIndex)) continue
|
if (slotIndex !in emptySlots.indices || !usedSlotIndices.add(slotIndex)) continue
|
||||||
|
|
||||||
val (date, mealType) = emptySlots[slotIndex]
|
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 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 {
|
val resolvedTitle = when {
|
||||||
matchedRecipe != null && rawTitle.isBlank() -> matchedRecipe.title
|
|
||||||
matchedRecipe != null -> matchedRecipe.title
|
matchedRecipe != null -> matchedRecipe.title
|
||||||
rawTitle.isNotBlank() -> rawTitle
|
rawTitle.isNotBlank() -> rawTitle
|
||||||
else -> continue
|
else -> continue
|
||||||
}
|
}
|
||||||
|
|
||||||
val reason = (obj["reason"] as? String)?.trim().orEmpty()
|
val reason = mealDto.reason?.trim().orEmpty()
|
||||||
val safeServings = defaultServings.coerceAtLeast(0.5)
|
val safeServings = defaultServings.takeIf { it.isFinite() }?.coerceAtLeast(0.5) ?: 1.0
|
||||||
|
|
||||||
val parsedIngredients = mutableListOf<MealFoodItem>()
|
val parsedIngredients = mealDto.ingredients.orEmpty().mapNotNull { ingDto ->
|
||||||
val rawIngredients = obj["ingredients"] as? List<*>
|
val ingName = ingDto.name?.trim().orEmpty()
|
||||||
if (rawIngredients != null) {
|
if (ingName.isBlank()) return@mapNotNull null
|
||||||
for (rawIng in rawIngredients) {
|
val weight = ingDto.weight?.takeIf { it.isFinite() && it > 0.0 }
|
||||||
val ingObj = rawIng as? Map<*, *> ?: continue
|
val unit = FoodUnit.fromCode(ingDto.unit ?: "portion")
|
||||||
val ingName = (ingObj["name"] as? String)?.trim().orEmpty()
|
val category = FoodCategory.fromCode(ingDto.category)
|
||||||
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)
|
?: FoodCategory.inferFromName(ingName)
|
||||||
parsedIngredients.add(
|
|
||||||
MealFoodItem(
|
MealFoodItem(
|
||||||
name = ingName,
|
name = ingName,
|
||||||
weight = weight,
|
weight = weight,
|
||||||
@@ -327,8 +317,6 @@ RÈGLES STRICTES :
|
|||||||
category = category,
|
category = category,
|
||||||
categories = listOf(category)
|
categories = listOf(category)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val resolvedItems = if (matchedRecipe != null) {
|
val resolvedItems = if (matchedRecipe != null) {
|
||||||
@@ -359,3 +347,26 @@ RÈGLES STRICTES :
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
internal data class PredictionResponseDto(
|
||||||
|
val meals: List<PredictedMealDto>? = 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<PredictedIngredientDto>? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
@JsonClass(generateAdapter = true)
|
||||||
|
internal data class PredictedIngredientDto(
|
||||||
|
val name: String? = null,
|
||||||
|
val weight: Double? = null,
|
||||||
|
val unit: String? = null,
|
||||||
|
val category: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
@@ -6,10 +6,13 @@ import androidx.lifecycle.AndroidViewModel
|
|||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.example.data.model.CustomFoodEntry
|
import com.example.data.model.CustomFoodEntry
|
||||||
import com.example.data.model.FoodCategory
|
import com.example.data.model.FoodCategory
|
||||||
|
import com.example.data.model.FoodPreferenceEntry
|
||||||
import com.example.data.model.FoodUnit
|
import com.example.data.model.FoodUnit
|
||||||
import com.example.data.model.InventoryItem
|
import com.example.data.model.InventoryItem
|
||||||
import com.example.data.model.ManualShoppingItem
|
import com.example.data.model.ManualShoppingItem
|
||||||
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealFoodItem
|
import com.example.data.model.MealFoodItem
|
||||||
|
import com.example.data.model.MealType
|
||||||
import com.example.data.model.PlannedMealEntry
|
import com.example.data.model.PlannedMealEntry
|
||||||
import com.example.data.model.PredictedMealProposal
|
import com.example.data.model.PredictedMealProposal
|
||||||
import com.example.data.model.PredictionMealScope
|
import com.example.data.model.PredictionMealScope
|
||||||
@@ -30,6 +33,7 @@ import com.example.ui.common.UiEvent
|
|||||||
import com.example.util.ImageUtils
|
import com.example.util.ImageUtils
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
@@ -42,19 +46,66 @@ import kotlinx.coroutines.flow.flowOn
|
|||||||
import kotlinx.coroutines.flow.receiveAsFlow
|
import kotlinx.coroutines.flow.receiveAsFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.flow.updateAndGet
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import java.time.DayOfWeek
|
import java.time.DayOfWeek
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.temporal.TemporalAdjusters
|
import java.time.temporal.TemporalAdjusters
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
|
internal fun interface WeekSlotPredictor {
|
||||||
|
suspend fun predictEmptySlots(
|
||||||
|
emptySlots: List<Pair<LocalDate, MealType>>,
|
||||||
|
existingWeekMeals: List<PlannedMealEntry>,
|
||||||
|
inventory: List<InventoryItem>,
|
||||||
|
recipes: List<RecipeEntry>,
|
||||||
|
preferences: List<FoodPreferenceEntry>,
|
||||||
|
recentJournalMeals: List<MealEntry>,
|
||||||
|
defaultServings: Double
|
||||||
|
): Result<List<PredictedMealProposal>>
|
||||||
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@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<Pair<LocalDate, MealType>>,
|
||||||
|
existingWeekMeals: List<PlannedMealEntry>,
|
||||||
|
inventory: List<InventoryItem>,
|
||||||
|
recipes: List<RecipeEntry>,
|
||||||
|
preferences: List<FoodPreferenceEntry>,
|
||||||
|
recentJournalMeals: List<MealEntry>,
|
||||||
|
defaultServings: Double
|
||||||
|
): Result<List<PredictedMealProposal>> {
|
||||||
|
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 receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
|
||||||
private val weeklyMealPredictor by lazy { WeeklyMealPredictor() }
|
private val checkedKeysMutex = Mutex()
|
||||||
|
private var predictionJob: Job? = null
|
||||||
|
|
||||||
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
|
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
|
||||||
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
|
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
|
||||||
@@ -140,11 +191,12 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
|||||||
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
|
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
|
||||||
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
|
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
|
||||||
|
|
||||||
private fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
|
private suspend fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
|
||||||
val updated = transform(_checkedPlanKeys.value)
|
checkedKeysMutex.withLock {
|
||||||
_checkedPlanKeys.value = updated
|
val updated = _checkedPlanKeys.updateAndGet(transform)
|
||||||
planningPrefs.setCheckedPlanKeys(updated)
|
planningPrefs.setCheckedPlanKeys(updated)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------------
|
// ------------------------------------------------------------------------
|
||||||
// Week Navigation
|
// Week Navigation
|
||||||
@@ -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,
|
* Batch-transfers checked shopping items into kitchen inventory at the end of a shopping trip.
|
||||||
* clears checked manual items, and removes processed plan-derived checked keys.
|
* Only items whose stock addition succeeded are removed from checked plan keys / manual items,
|
||||||
|
* preventing data loss on partial failures.
|
||||||
*/
|
*/
|
||||||
fun finishShoppingAndAddToStock(
|
fun finishShoppingAndAddToStock(
|
||||||
checkedItems: List<ShoppingListItem>,
|
checkedItems: List<ShoppingListItem>,
|
||||||
@@ -367,10 +420,12 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
|||||||
if (checkedItems.isEmpty()) return
|
if (checkedItems.isEmpty()) return
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
var addedCount = 0
|
var addedCount = 0
|
||||||
|
var failedCount = 0
|
||||||
val processedPlanKeys = mutableSetOf<String>()
|
val processedPlanKeys = mutableSetOf<String>()
|
||||||
|
val processedManualIds = mutableSetOf<String>()
|
||||||
|
|
||||||
checkedItems.forEach { item ->
|
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 location = locationsByKey[item.key] ?: StorageLocation.defaultForCategory(item.category)
|
||||||
val result = repository.addOrMergeInventoryItem(
|
val result = repository.addOrMergeInventoryItem(
|
||||||
name = item.name,
|
name = item.name,
|
||||||
@@ -381,19 +436,30 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
|||||||
)
|
)
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
addedCount++
|
addedCount++
|
||||||
}
|
|
||||||
if (item.key.startsWith("plan_")) {
|
if (item.key.startsWith("plan_")) {
|
||||||
processedPlanKeys.add(item.key)
|
processedPlanKeys.add(item.key)
|
||||||
}
|
}
|
||||||
|
item.manualItemId?.let { processedManualIds.add(it) }
|
||||||
|
} else {
|
||||||
|
failedCount++
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
repository.clearCheckedManualShoppingItems()
|
processedManualIds.forEach { manualId ->
|
||||||
|
repository.deleteManualShoppingItem(manualId)
|
||||||
|
}
|
||||||
if (processedPlanKeys.isNotEmpty()) {
|
if (processedPlanKeys.isNotEmpty()) {
|
||||||
updateCheckedPlanKeys { it - processedPlanKeys }
|
updateCheckedPlanKeys { it - processedPlanKeys }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (addedCount > 0) {
|
when {
|
||||||
emitSnackbar(
|
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"
|
"$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,
|
scope: PredictionMealScope,
|
||||||
defaultServings: Double
|
defaultServings: Double
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
predictionJob?.cancel()
|
||||||
|
predictionJob = viewModelScope.launch {
|
||||||
val start = _weekStartDate.value
|
val start = _weekStartDate.value
|
||||||
val existingMeals = weekPlannedMeals.value
|
val existingMeals = weekPlannedMeals.value
|
||||||
val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet()
|
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 preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() }
|
||||||
val recentMeals = repository.getAllMealsSnapshot()
|
val recentMeals = repository.getAllMealsSnapshot()
|
||||||
|
|
||||||
val result = weeklyMealPredictor.predictEmptySlots(
|
val result = weekSlotPredictor.predictEmptySlots(
|
||||||
emptySlots = emptySlots,
|
emptySlots = emptySlots,
|
||||||
existingWeekMeals = existingMeals,
|
existingWeekMeals = existingMeals,
|
||||||
inventory = inventory,
|
inventory = inventory,
|
||||||
@@ -533,17 +600,38 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
|||||||
}
|
}
|
||||||
|
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
|
var savedCount = 0
|
||||||
|
val failedProposals = mutableListOf<PredictedMealProposal>()
|
||||||
|
|
||||||
selectedProposals.forEach { proposal ->
|
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
|
_weekPredictionState.value = WeekPredictionUiState.Idle
|
||||||
emitSnackbar(
|
emitSnackbar(
|
||||||
"${selectedProposals.size} repas ajouté${if (selectedProposals.size > 1) "s" else ""} au planning • courses mises à jour"
|
"$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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun dismissWeekPrediction() {
|
fun dismissWeekPrediction() {
|
||||||
|
predictionJob?.cancel()
|
||||||
|
predictionJob = null
|
||||||
_weekPredictionState.value = WeekPredictionUiState.Idle
|
_weekPredictionState.value = WeekPredictionUiState.Idle
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ import androidx.compose.foundation.lazy.items
|
|||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
import androidx.compose.material.icons.Icons
|
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.Add
|
||||||
import androidx.compose.material.icons.filled.DeleteOutline
|
import androidx.compose.material.icons.filled.DeleteOutline
|
||||||
import androidx.compose.material.icons.filled.ErrorOutline
|
import androidx.compose.material.icons.filled.ErrorOutline
|
||||||
import androidx.compose.material.icons.filled.ReceiptLong
|
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.Card
|
import androidx.compose.material3.Card
|
||||||
import androidx.compose.material3.CardDefaults
|
import androidx.compose.material3.CardDefaults
|
||||||
@@ -181,7 +181,7 @@ fun ReceiptReviewSheet(
|
|||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f)
|
||||||
) {
|
) {
|
||||||
Icon(
|
Icon(
|
||||||
imageVector = Icons.Default.ReceiptLong,
|
imageVector = Icons.AutoMirrored.Filled.ReceiptLong,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
tint = MaterialTheme.colorScheme.primary
|
tint = MaterialTheme.colorScheme.primary
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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>()
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String> {
|
||||||
|
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<Result<List<PredictedMealProposal>>>()
|
||||||
|
|
||||||
|
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<String> {
|
||||||
|
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" })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -115,4 +115,45 @@ class WeeklyMealPredictorTest {
|
|||||||
)
|
)
|
||||||
assertTrue(parsed.isEmpty())
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user