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:
bleackstorm committed 2026-11-23 22:56:44 +01:00
1 parent a2f59f15d4
commit 8260dba5a5
10 files changed
+551 -80

No files matched your search

@@ -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)
@@ -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<String> {
open suspend fun upsertPlannedMeal(entry: PlannedMealEntry): Result<String> {
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<Unit> {
open suspend fun deleteManualShoppingItem(itemId: String): Result<Unit> {
localMealDao.deleteManualShoppingItemById(itemId)
return Result.success(Unit)
}
@@ -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 {
@@ -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
}
}
@@ -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<Map<String, Any>>(
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<Pair<LocalDate, MealType>>,
@@ -279,56 +276,47 @@ RÈGLES STRICTES :
): List<PredictedMealProposal> {
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<Int>()
val proposals = mutableListOf<PredictedMealProposal>()
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<MealFoodItem>()
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<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 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<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)
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 weeklyMealPredictor by lazy { WeeklyMealPredictor() }
private val checkedKeysMutex = Mutex()
private var predictionJob: Job? = null
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
@@ -140,10 +191,11 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
private fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
val updated = transform(_checkedPlanKeys.value)
_checkedPlanKeys.value = updated
planningPrefs.setCheckedPlanKeys(updated)
private suspend fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
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<ShoppingListItem>,
@@ -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<String>()
val processedManualIds = mutableSetOf<String>()
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<PredictedMealProposal>()
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
}
@@ -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
)