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
+551
-80
No files matched your search
@@ -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
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user