mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
feat(planning): implement meal plan prediction engine
Introduce WeeklyMealPredictor and related data models to suggest meals, add prediction state management to the ViewModel, and update the UI to support meal planning automation.
This commit is contained in:
1 parent
8e794e6da7
commit
a2f59f15d4
13 files changed
+2247
-17
No files matched your search
@@ -11,16 +11,21 @@ import com.example.data.model.InventoryItem
|
||||
import com.example.data.model.ManualShoppingItem
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.PlannedMealEntry
|
||||
import com.example.data.model.PredictedMealProposal
|
||||
import com.example.data.model.PredictionMealScope
|
||||
import com.example.data.model.ReceiptScanUiState
|
||||
import com.example.data.model.RecipeEntry
|
||||
import com.example.data.model.ScannedReceiptItem
|
||||
import com.example.data.model.ShoppingListItem
|
||||
import com.example.data.model.StockDeductionProposal
|
||||
import com.example.data.model.StorageLocation
|
||||
import com.example.data.model.WeekPredictionUiState
|
||||
import com.example.data.preferences.PlanningPreferencesManager
|
||||
import com.example.data.repository.MealRepository
|
||||
import com.example.domain.IngredientMatcher
|
||||
import com.example.domain.ReceiptScannerAnalyzer
|
||||
import com.example.domain.ShoppingListCalculator
|
||||
import com.example.domain.WeeklyMealPredictor
|
||||
import com.example.ui.common.UiEvent
|
||||
import com.example.util.ImageUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -47,7 +52,9 @@ import java.util.UUID
|
||||
class PlanningViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
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 _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
|
||||
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
|
||||
@@ -84,7 +91,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
||||
private val recipesFlow: Flow<List<RecipeEntry>> = repository.observeRecipes()
|
||||
private val customFoodsFlow: Flow<List<CustomFoodEntry>> = repository.observeCustomFoods()
|
||||
|
||||
private val _checkedPlanKeys = MutableStateFlow<Set<String>>(emptySet())
|
||||
private val _checkedPlanKeys = MutableStateFlow(planningPrefs.getCheckedPlanKeys())
|
||||
|
||||
private data class ShoppingInputs(
|
||||
val planned: List<PlannedMealEntry>,
|
||||
@@ -127,9 +134,18 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
||||
private val _receiptScanState = MutableStateFlow<ReceiptScanUiState>(ReceiptScanUiState.Idle)
|
||||
val receiptScanState: StateFlow<ReceiptScanUiState> = _receiptScanState.asStateFlow()
|
||||
|
||||
private val _weekPredictionState = MutableStateFlow<WeekPredictionUiState>(WeekPredictionUiState.Idle)
|
||||
val weekPredictionState: StateFlow<WeekPredictionUiState> = _weekPredictionState.asStateFlow()
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Week Navigation
|
||||
// ------------------------------------------------------------------------
|
||||
@@ -302,7 +318,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
||||
repository.setManualShoppingItemChecked(item.manualItemId, checked)
|
||||
}
|
||||
if (item.key.startsWith("plan_")) {
|
||||
_checkedPlanKeys.update { current ->
|
||||
updateCheckedPlanKeys { current ->
|
||||
if (checked) current + item.key else current - item.key
|
||||
}
|
||||
}
|
||||
@@ -329,7 +345,7 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
||||
repository.setManualShoppingItemChecked(item.manualItemId, true)
|
||||
}
|
||||
if (item.key.startsWith("plan_")) {
|
||||
_checkedPlanKeys.update { it - item.key }
|
||||
updateCheckedPlanKeys { it - item.key }
|
||||
}
|
||||
emitSnackbar("${item.name} ajouté au stock (${IngredientMatcher.formatQuantity(safeQty, unit)})")
|
||||
},
|
||||
@@ -340,6 +356,50 @@ 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.
|
||||
*/
|
||||
fun finishShoppingAndAddToStock(
|
||||
checkedItems: List<ShoppingListItem>,
|
||||
locationsByKey: Map<String, StorageLocation>
|
||||
) {
|
||||
if (checkedItems.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
var addedCount = 0
|
||||
val processedPlanKeys = mutableSetOf<String>()
|
||||
|
||||
checkedItems.forEach { item ->
|
||||
val qtyToAdd = item.missingQuantity?.takeIf { it > 0.0 } ?: 1.0
|
||||
val location = locationsByKey[item.key] ?: StorageLocation.defaultForCategory(item.category)
|
||||
val result = repository.addOrMergeInventoryItem(
|
||||
name = item.name,
|
||||
quantityToAdd = qtyToAdd,
|
||||
unit = item.unit,
|
||||
category = item.category,
|
||||
location = location
|
||||
)
|
||||
if (result.isSuccess) {
|
||||
addedCount++
|
||||
}
|
||||
if (item.key.startsWith("plan_")) {
|
||||
processedPlanKeys.add(item.key)
|
||||
}
|
||||
}
|
||||
|
||||
repository.clearCheckedManualShoppingItems()
|
||||
if (processedPlanKeys.isNotEmpty()) {
|
||||
updateCheckedPlanKeys { it - processedPlanKeys }
|
||||
}
|
||||
|
||||
if (addedCount > 0) {
|
||||
emitSnackbar(
|
||||
"$addedCount article${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} au stock"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteManualShoppingItem(manualItemId: String) {
|
||||
viewModelScope.launch {
|
||||
repository.deleteManualShoppingItem(manualItemId)
|
||||
@@ -349,11 +409,144 @@ class PlanningViewModel(application: Application) : AndroidViewModel(application
|
||||
fun clearCheckedShoppingItems() {
|
||||
viewModelScope.launch {
|
||||
repository.clearCheckedManualShoppingItems()
|
||||
_checkedPlanKeys.value = emptySet()
|
||||
updateCheckedPlanKeys { emptySet() }
|
||||
emitSnackbar("Articles cochés nettoyés")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Weekly Meal Prediction (Firebase AI Logic)
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
fun predictEmptyWeekMeals(
|
||||
scope: PredictionMealScope,
|
||||
defaultServings: Double
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val start = _weekStartDate.value
|
||||
val existingMeals = weekPlannedMeals.value
|
||||
val occupiedSlots = existingMeals.map { it.dateEpochDay to it.mealType }.toSet()
|
||||
|
||||
val emptySlots = (0L..6L).flatMap { offset ->
|
||||
val day = start.plusDays(offset)
|
||||
val epochDay = day.toEpochDay()
|
||||
scope.mealTypes.mapNotNull { mealType ->
|
||||
if ((epochDay to mealType) !in occupiedSlots) {
|
||||
day to mealType
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (emptySlots.isEmpty()) {
|
||||
_weekPredictionState.value = WeekPredictionUiState.Error(
|
||||
message = "Tous les créneaux de cette semaine pour « ${scope.displayName} » sont déjà planifiés.",
|
||||
scope = scope,
|
||||
defaultServings = defaultServings
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
_weekPredictionState.value = WeekPredictionUiState.Loading
|
||||
|
||||
val inventory = repository.getInventorySnapshot()
|
||||
val recipes = repository.getAllRecipesSnapshot()
|
||||
val preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() }
|
||||
val recentMeals = repository.getAllMealsSnapshot()
|
||||
|
||||
val result = weeklyMealPredictor.predictEmptySlots(
|
||||
emptySlots = emptySlots,
|
||||
existingWeekMeals = existingMeals,
|
||||
inventory = inventory,
|
||||
recipes = recipes,
|
||||
preferences = preferences,
|
||||
recentJournalMeals = recentMeals,
|
||||
defaultServings = defaultServings
|
||||
)
|
||||
|
||||
result.fold(
|
||||
onSuccess = { proposals ->
|
||||
_weekPredictionState.value = WeekPredictionUiState.Preview(
|
||||
proposals = proposals,
|
||||
scope = scope,
|
||||
defaultServings = defaultServings
|
||||
)
|
||||
},
|
||||
onFailure = { error ->
|
||||
_weekPredictionState.value = WeekPredictionUiState.Error(
|
||||
message = error.message ?: "Impossible de générer des suggestions pour le moment.",
|
||||
scope = scope,
|
||||
defaultServings = defaultServings
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun togglePredictedMeal(proposalId: String) {
|
||||
_weekPredictionState.update { state ->
|
||||
if (state is WeekPredictionUiState.Preview) {
|
||||
state.copy(
|
||||
proposals = state.proposals.map { proposal ->
|
||||
if (proposal.id == proposalId) proposal.copy(selected = !proposal.selected) else proposal
|
||||
}
|
||||
)
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updatePredictedMealServings(proposalId: String, newServings: Double) {
|
||||
val clamped = newServings.coerceIn(0.5, 20.0)
|
||||
_weekPredictionState.update { state ->
|
||||
if (state is WeekPredictionUiState.Preview) {
|
||||
state.copy(
|
||||
proposals = state.proposals.map { proposal ->
|
||||
if (proposal.id == proposalId) {
|
||||
val ratio = if (proposal.servings > 0.0) clamped / proposal.servings else 1.0
|
||||
val scaledItems = proposal.items.map { item ->
|
||||
val scaledWeight = item.weight?.let { w ->
|
||||
Math.round(w * ratio * 10.0) / 10.0
|
||||
}
|
||||
item.copy(weight = scaledWeight)
|
||||
}
|
||||
proposal.copy(servings = clamped, items = scaledItems)
|
||||
} else {
|
||||
proposal
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun confirmPredictedMeals() {
|
||||
val preview = _weekPredictionState.value as? WeekPredictionUiState.Preview ?: return
|
||||
val selectedProposals = preview.proposals.filter { it.selected }
|
||||
if (selectedProposals.isEmpty()) {
|
||||
emitSnackbar("Sélectionnez au moins un repas à ajouter au planning")
|
||||
return
|
||||
}
|
||||
|
||||
viewModelScope.launch {
|
||||
selectedProposals.forEach { proposal ->
|
||||
repository.upsertPlannedMeal(proposal.toPlannedMealEntry())
|
||||
}
|
||||
_weekPredictionState.value = WeekPredictionUiState.Idle
|
||||
emitSnackbar(
|
||||
"${selectedProposals.size} repas ajouté${if (selectedProposals.size > 1) "s" else ""} au planning • courses mises à jour"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun dismissWeekPrediction() {
|
||||
_weekPredictionState.value = WeekPredictionUiState.Idle
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Receipt Scanning (Firebase AI Logic Multimodal)
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user