feat: implement weekly meal planning and inventory

- Add Planning module with UI and ViewModel
- Update database schema to support planned meals and inventory
- Add camera permission for future features
- Refactor food category handling to support multiple tags
This commit is contained in:
bleackstorm committed 2026-11-22 12:24:47 +01:00
1 parent 1331fae119
commit 8e794e6da7
46 files changed
+6335 -192

No files matched your search

@@ -0,0 +1,485 @@
package com.example.ui.planning
import android.app.Application
import android.net.Uri
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.FoodUnit
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.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.repository.MealRepository
import com.example.domain.IngredientMatcher
import com.example.domain.ReceiptScannerAnalyzer
import com.example.domain.ShoppingListCalculator
import com.example.ui.common.UiEvent
import com.example.util.ImageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.temporal.TemporalAdjusters
import java.util.UUID
@OptIn(ExperimentalCoroutinesApi::class)
class PlanningViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
private val _weekStartDate = MutableStateFlow(currentMonday())
val weekStartDate: StateFlow<LocalDate> = _weekStartDate.asStateFlow()
val weekPlannedMeals: StateFlow<List<PlannedMealEntry>> = _weekStartDate
.flatMapLatest { startDate ->
val startEpoch = startDate.toEpochDay()
val endEpoch = startDate.plusDays(6).toEpochDay()
repository.observePlannedMealsForWeek(startEpoch, endEpoch)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
val inventoryItems: StateFlow<List<InventoryItem>> = repository.observeInventory()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
val manualShoppingItems: StateFlow<List<ManualShoppingItem>> = repository.observeManualShoppingItems()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
private val recipesFlow: Flow<List<RecipeEntry>> = repository.observeRecipes()
private val customFoodsFlow: Flow<List<CustomFoodEntry>> = repository.observeCustomFoods()
private val _checkedPlanKeys = MutableStateFlow<Set<String>>(emptySet())
private data class ShoppingInputs(
val planned: List<PlannedMealEntry>,
val recipes: List<RecipeEntry>,
val inventory: List<InventoryItem>,
val manual: List<ManualShoppingItem>,
val checkedKeys: Set<String>
)
val computedShoppingList: StateFlow<List<ShoppingListItem>> = combine(
combine(
weekPlannedMeals,
recipesFlow,
inventoryItems,
manualShoppingItems,
_checkedPlanKeys
) { planned, recipes, inventory, manual, checkedKeys ->
ShoppingInputs(planned, recipes, inventory, manual, checkedKeys)
},
customFoodsFlow
) { inputs, customFoods ->
val recipesById = inputs.recipes.associateBy { it.id }
val customLookup = CustomFoodEntry.buildCategoriesLookup(customFoods)
ShoppingListCalculator.computeShoppingList(
plannedMeals = inputs.planned,
recipesById = recipesById,
inventory = inputs.inventory,
manualItems = inputs.manual,
checkedPlanKeys = inputs.checkedKeys,
customCategoriesLookup = customLookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
private val _receiptScanState = MutableStateFlow<ReceiptScanUiState>(ReceiptScanUiState.Idle)
val receiptScanState: StateFlow<ReceiptScanUiState> = _receiptScanState.asStateFlow()
private val _pendingStockDeductions = MutableStateFlow<List<StockDeductionProposal>?>(null)
val pendingStockDeductions: StateFlow<List<StockDeductionProposal>?> = _pendingStockDeductions.asStateFlow()
// ------------------------------------------------------------------------
// Week Navigation
// ------------------------------------------------------------------------
fun previousWeek() {
_weekStartDate.update { it.minusWeeks(1) }
}
fun nextWeek() {
_weekStartDate.update { it.plusWeeks(1) }
}
fun goToCurrentWeek() {
_weekStartDate.value = currentMonday()
}
// ------------------------------------------------------------------------
// Weekly Meal Planning
// ------------------------------------------------------------------------
fun savePlannedMeal(entry: PlannedMealEntry) {
viewModelScope.launch {
repository.upsertPlannedMeal(entry).fold(
onSuccess = {
val label = if (entry.id.isBlank()) "Repas ajouté au planning" else "Repas planifié mis à jour"
emitSnackbar(label)
},
onFailure = {
emitSnackbar("Impossible d'enregistrer le repas planifié")
}
)
}
}
fun deletePlannedMeal(id: String) {
viewModelScope.launch {
repository.deletePlannedMeal(id)
emitSnackbar("Repas retiré du planning")
}
}
fun togglePlannedMealConsumed(id: String, consumed: Boolean) {
viewModelScope.launch {
repository.markPlannedMealConsumed(id, consumed)
}
}
/**
* Marks an optional planned meal as consumed and computes stock deduction proposals
* for the eaten foods that match current inventory items.
*/
fun onMealLoggedCheckStock(
eatenItems: List<MealFoodItem>,
plannedMealId: String? = null
) {
viewModelScope.launch {
if (!plannedMealId.isNullOrBlank()) {
repository.markPlannedMealConsumed(plannedMealId, consumed = true)
}
val currentStock = repository.getInventorySnapshot()
val proposals = ShoppingListCalculator.computeStockDeductionProposals(
eatenItems = eatenItems,
inventory = currentStock
)
if (proposals.isNotEmpty()) {
_pendingStockDeductions.value = proposals
}
}
}
fun confirmStockDeductions(selectedProposals: List<StockDeductionProposal>) {
viewModelScope.launch {
val active = selectedProposals.filter { it.selected && it.deductAmount > 0.0 }
active.forEach { proposal ->
repository.adjustInventoryQuantity(
itemId = proposal.inventoryItem.id,
delta = -proposal.deductAmount
)
}
_pendingStockDeductions.value = null
if (active.isNotEmpty()) {
emitSnackbar(
"Stock mis à jour (${active.size} article${if (active.size > 1) "s" else ""} déduit${if (active.size > 1) "s" else ""})"
)
}
}
}
fun dismissStockDeductions() {
_pendingStockDeductions.value = null
}
// ------------------------------------------------------------------------
// Kitchen Inventory (Stock)
// ------------------------------------------------------------------------
fun saveInventoryItem(item: InventoryItem) {
viewModelScope.launch {
val result = if (item.id.isBlank()) {
repository.addOrMergeInventoryItem(
name = item.name,
quantityToAdd = item.quantity,
unit = item.unit,
category = item.category,
location = item.location
)
} else {
repository.upsertInventoryItem(item)
}
result.fold(
onSuccess = {
val message = if (item.id.isBlank()) {
"${item.name.trim()} ajouté au stock"
} else {
"${item.name.trim()} mis à jour"
}
emitSnackbar(message)
},
onFailure = {
emitSnackbar("Veuillez renseigner un nom et une quantité valide")
}
)
}
}
fun adjustInventoryQuantity(itemId: String, delta: Double) {
viewModelScope.launch {
repository.adjustInventoryQuantity(itemId, delta)
}
}
fun deleteInventoryItem(itemId: String) {
viewModelScope.launch {
repository.deleteInventoryItem(itemId)
emitSnackbar("Article retiré du stock")
}
}
// ------------------------------------------------------------------------
// Shopping List (Courses)
// ------------------------------------------------------------------------
fun addManualShoppingItem(
name: String,
quantity: Double?,
unit: FoodUnit,
category: FoodCategory
) {
val cleanName = name.trim()
if (cleanName.isBlank()) return
viewModelScope.launch {
repository.upsertManualShoppingItem(
ManualShoppingItem(
name = cleanName,
quantity = quantity?.takeIf { it > 0.0 },
unit = unit,
category = category,
isChecked = false
)
).fold(
onSuccess = { emitSnackbar("$cleanName ajouté à la liste de courses") },
onFailure = { emitSnackbar("Impossible d'ajouter cet article") }
)
}
}
fun toggleShoppingItemChecked(item: ShoppingListItem, checked: Boolean) {
viewModelScope.launch {
if (item.manualItemId != null) {
repository.setManualShoppingItemChecked(item.manualItemId, checked)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { current ->
if (checked) current + item.key else current - item.key
}
}
}
}
fun addShoppingItemToStock(
item: ShoppingListItem,
quantity: Double,
unit: FoodUnit,
location: StorageLocation
) {
viewModelScope.launch {
val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0
repository.addOrMergeInventoryItem(
name = item.name,
quantityToAdd = safeQty,
unit = unit,
category = item.category,
location = location
).fold(
onSuccess = {
if (item.manualItemId != null) {
repository.setManualShoppingItemChecked(item.manualItemId, true)
}
if (item.key.startsWith("plan_")) {
_checkedPlanKeys.update { it - item.key }
}
emitSnackbar("${item.name} ajouté au stock (${IngredientMatcher.formatQuantity(safeQty, unit)})")
},
onFailure = {
emitSnackbar("Impossible d'ajouter ${item.name} au stock")
}
)
}
}
fun deleteManualShoppingItem(manualItemId: String) {
viewModelScope.launch {
repository.deleteManualShoppingItem(manualItemId)
}
}
fun clearCheckedShoppingItems() {
viewModelScope.launch {
repository.clearCheckedManualShoppingItems()
_checkedPlanKeys.value = emptySet()
emitSnackbar("Articles cochés nettoyés")
}
}
// ------------------------------------------------------------------------
// Receipt Scanning (Firebase AI Logic Multimodal)
// ------------------------------------------------------------------------
fun scanReceiptFromUri(uri: Uri) {
viewModelScope.launch {
_receiptScanState.value = ReceiptScanUiState.Scanning
val bitmap = ImageUtils.loadResizedBitmapForAi(getApplication(), uri, maxDimension = 1440)
if (bitmap == null) {
_receiptScanState.value = ReceiptScanUiState.Error(
"Impossible de lire cette image. Essayez de reprendre la photo du ticket."
)
return@launch
}
try {
val result = receiptAnalyzer.analyzeReceipt(bitmap)
result.fold(
onSuccess = { items ->
_receiptScanState.value = ReceiptScanUiState.Preview(items)
},
onFailure = { error ->
_receiptScanState.value = ReceiptScanUiState.Error(
error.message ?: "Impossible d'analyser ce ticket pour le moment."
)
}
)
} finally {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
}
}
fun updateScannedItem(updated: ScannedReceiptItem) {
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(
items = state.items.map { if (it.id == updated.id) updated else it }
)
} else {
state
}
}
}
fun removeScannedItem(itemId: String) {
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(items = state.items.filterNot { it.id == itemId })
} else {
state
}
}
}
fun addBlankScannedItem() {
val newItem = ScannedReceiptItem(
id = "manual_${UUID.randomUUID().toString().take(6)}",
rawLabel = "Ajout manuel",
name = "",
quantity = 1.0,
unit = FoodUnit.PORTION,
category = FoodCategory.OTHER,
location = StorageLocation.PANTRY,
selected = true
)
_receiptScanState.update { state ->
if (state is ReceiptScanUiState.Preview) {
state.copy(items = state.items + newItem)
} else {
state
}
}
}
fun confirmScannedReceiptImport(
items: List<ScannedReceiptItem>,
alsoCheckShoppingList: Boolean
) {
viewModelScope.launch {
val selectedValid = items.filter { it.selected && it.name.isNotBlank() && it.quantity > 0.0 }
if (selectedValid.isEmpty()) {
emitSnackbar("Sélectionnez au moins un article valide à ajouter")
return@launch
}
selectedValid.forEach { scanned ->
repository.addOrMergeInventoryItem(
name = scanned.name.trim(),
quantityToAdd = scanned.quantity,
unit = scanned.unit,
category = scanned.category,
location = scanned.location
)
}
if (alsoCheckShoppingList) {
val scannedNorms = selectedValid.map { IngredientMatcher.normalize(it.name) }.toSet()
val manualItems = repository.getManualShoppingItemsSnapshot()
manualItems.forEach { manual ->
val manualNorm = IngredientMatcher.normalize(manual.name)
if (!manual.isChecked && scannedNorms.any { IngredientMatcher.matches(it, manualNorm) }) {
repository.setManualShoppingItemChecked(manual.id, true)
}
}
}
_receiptScanState.value = ReceiptScanUiState.Idle
emitSnackbar(
"${selectedValid.size} article${if (selectedValid.size > 1) "s" else ""} ajouté${if (selectedValid.size > 1) "s" else ""} au stock"
)
}
}
fun dismissReceiptScan() {
_receiptScanState.value = ReceiptScanUiState.Idle
}
private fun emitSnackbar(message: String) {
_uiEvents.trySend(UiEvent.ShowSnackbar(message))
}
companion object {
fun currentMonday(): LocalDate {
return LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
}
}
}