feat(planning): add expiration dates, alerts, and AI menu adaptation

This commit is contained in:
bleack committed 2026-11-28 13:29:35 +01:00
1 parent e534cfa7b0
commit 381fe9ab72
24 files changed
+2244 -45

No files matched your search

+4
View File
@@ -43,6 +43,10 @@
android:name=".receiver.MealReminderReceiver" android:name=".receiver.MealReminderReceiver"
android:exported="false" /> android:exported="false" />
<receiver
android:name=".receiver.ExpirationAlertReceiver"
android:exported="false" />
<receiver <receiver
android:name=".receiver.BootReceiver" android:name=".receiver.BootReceiver"
android:exported="true"> android:exported="true">
+34 -3
View File
@@ -98,6 +98,7 @@ class MainActivity : ComponentActivity() {
private val viewModel: MealViewModel by viewModels() private val viewModel: MealViewModel by viewModels()
private val planningViewModel: PlanningViewModel by viewModels() private val planningViewModel: PlanningViewModel by viewModels()
private val openPlanningRequest = mutableStateOf(false)
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@@ -118,7 +119,9 @@ class MainActivity : ComponentActivity() {
SatieaTheme(themeMode = themeMode) { SatieaTheme(themeMode = themeMode) {
AppRoot( AppRoot(
viewModel = viewModel, viewModel = viewModel,
planningViewModel = planningViewModel planningViewModel = planningViewModel,
openPlanningRequested = openPlanningRequest.value,
onConsumeOpenPlanningRequest = { openPlanningRequest.value = false }
) )
} }
} }
@@ -131,12 +134,17 @@ class MainActivity : ComponentActivity() {
} }
private fun handleIncomingIntent(intent: Intent?) { private fun handleIncomingIntent(intent: Intent?) {
if (intent?.action == MealNotificationManager.ACTION_LOG_MEAL) { when (intent?.action) {
MealNotificationManager.ACTION_LOG_MEAL -> {
val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let { val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
MealType.fromString(it) MealType.fromString(it)
} ?: SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour) } ?: SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
viewModel.requestQuickLogMeal(parsedType) viewModel.requestQuickLogMeal(parsedType)
} }
MealNotificationManager.ACTION_OPEN_PLANNING_EXPIRING -> {
openPlanningRequest.value = true
}
}
} }
} }
@@ -144,7 +152,9 @@ class MainActivity : ComponentActivity() {
@Composable @Composable
fun AppRoot( fun AppRoot(
viewModel: MealViewModel, viewModel: MealViewModel,
planningViewModel: PlanningViewModel planningViewModel: PlanningViewModel,
openPlanningRequested: Boolean = false,
onConsumeOpenPlanningRequest: () -> Unit = {}
) { ) {
val context = LocalContext.current val context = LocalContext.current
var googleAccount by remember { mutableStateOf(GoogleSheetsAuthHelper.getSignedInAccount(context)) } var googleAccount by remember { mutableStateOf(GoogleSheetsAuthHelper.getSignedInAccount(context)) }
@@ -201,6 +211,13 @@ fun AppRoot(
var showRecipeEditor by remember { mutableStateOf(false) } var showRecipeEditor by remember { mutableStateOf(false) }
var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) } var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) }
LaunchedEffect(openPlanningRequested) {
if (openPlanningRequested) {
currentTab = MainTab.PLANNING
onConsumeOpenPlanningRequest()
}
}
// React to quick log meal requests from Widget or Notification // React to quick log meal requests from Widget or Notification
val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle() val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle()
LaunchedEffect(quickLogMealType) { LaunchedEffect(quickLogMealType) {
@@ -299,6 +316,9 @@ fun AppRoot(
val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle() val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle()
val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle() val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle()
val weekPredictionState by planningViewModel.weekPredictionState.collectAsStateWithLifecycle() val weekPredictionState by planningViewModel.weekPredictionState.collectAsStateWithLifecycle()
val expiringSoonItems by planningViewModel.expiringSoonItems.collectAsStateWithLifecycle()
val expirationAlertDays by planningViewModel.expirationAlertDays.collectAsStateWithLifecycle()
val menuAdaptationState by planningViewModel.menuAdaptationState.collectAsStateWithLifecycle()
val pendingStockDeductions by planningViewModel.pendingStockDeductions.collectAsStateWithLifecycle() val pendingStockDeductions by planningViewModel.pendingStockDeductions.collectAsStateWithLifecycle()
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
@@ -574,6 +594,9 @@ fun AppRoot(
customFoods = customFoods, customFoods = customFoods,
receiptScanState = receiptScanState, receiptScanState = receiptScanState,
weekPredictionState = weekPredictionState, weekPredictionState = weekPredictionState,
expiringSoonItems = expiringSoonItems,
expirationAlertDays = expirationAlertDays,
menuAdaptationState = menuAdaptationState,
onPreviousWeek = { planningViewModel.previousWeek() }, onPreviousWeek = { planningViewModel.previousWeek() },
onNextWeek = { planningViewModel.nextWeek() }, onNextWeek = { planningViewModel.nextWeek() },
onGoToCurrentWeek = { planningViewModel.goToCurrentWeek() }, onGoToCurrentWeek = { planningViewModel.goToCurrentWeek() },
@@ -637,6 +660,10 @@ fun AppRoot(
}, },
onConfirmPredictedMeals = { planningViewModel.confirmPredictedMeals() }, onConfirmPredictedMeals = { planningViewModel.confirmPredictedMeals() },
onDismissWeekPrediction = { planningViewModel.dismissWeekPrediction() }, onDismissWeekPrediction = { planningViewModel.dismissWeekPrediction() },
onAdaptMenusForExpiring = { planningViewModel.adaptMenusForExpiringItems() },
onToggleMenuAdaptation = { id -> planningViewModel.toggleMenuAdaptation(id) },
onConfirmMenuAdaptations = { planningViewModel.confirmMenuAdaptations() },
onDismissMenuAdaptation = { planningViewModel.dismissMenuAdaptation() },
onScanReceiptUri = { uri -> planningViewModel.scanReceiptFromUri(uri) }, onScanReceiptUri = { uri -> planningViewModel.scanReceiptFromUri(uri) },
onUpdateScannedItem = { item -> planningViewModel.updateScannedItem(item) }, onUpdateScannedItem = { item -> planningViewModel.updateScannedItem(item) },
onRemoveScannedItem = { id -> planningViewModel.removeScannedItem(id) }, onRemoveScannedItem = { id -> planningViewModel.removeScannedItem(id) },
@@ -676,6 +703,10 @@ fun AppRoot(
onTestNotification = { type -> onTestNotification = { type ->
viewModel.triggerTestNotification(type) viewModel.triggerTestNotification(type)
}, },
expirationAlertDays = expirationAlertDays,
onExpirationAlertDaysChange = { days ->
planningViewModel.updateExpirationAlertDays(days)
},
onSaveCsvClick = { triggerSaveCsv() }, onSaveCsvClick = { triggerSaveCsv() },
onShareCsvClick = { triggerShareCsv() }, onShareCsvClick = { triggerShareCsv() },
onImportCsvClick = { triggerImportCsv() }, onImportCsvClick = { triggerImportCsv() },
@@ -21,7 +21,7 @@ import com.squareup.moshi.Types
LocalInventoryItemEntity::class, LocalInventoryItemEntity::class,
LocalShoppingItemEntity::class LocalShoppingItemEntity::class
], ],
version = 6, version = 7,
exportSchema = false exportSchema = false
) )
@TypeConverters(RoomConverters::class) @TypeConverters(RoomConverters::class)
@@ -189,6 +189,14 @@ abstract class AppDatabase : RoomDatabase() {
} }
} }
val MIGRATION_6_7 = object : Migration(6, 7) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `local_inventory_items` ADD COLUMN `expirationDateEpochDay` INTEGER"
)
}
}
fun getInstance(context: Context): AppDatabase { fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) { return INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it }
@@ -200,7 +208,7 @@ abstract class AppDatabase : RoomDatabase() {
appContext, appContext,
AppDatabase::class.java, AppDatabase::class.java,
"satiea_local.db" "satiea_local.db"
).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6) ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7)
// Destructive migration is only permitted on debug builds // Destructive migration is only permitted on debug builds
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
@@ -18,6 +18,7 @@ data class LocalInventoryItemEntity(
val unit: String = FoodUnit.G.code, val unit: String = FoodUnit.G.code,
val category: String = FoodCategory.OTHER.code, val category: String = FoodCategory.OTHER.code,
val location: String = StorageLocation.PANTRY.name, val location: String = StorageLocation.PANTRY.name,
val expirationDateEpochDay: Long? = null,
val updatedAt: Long = System.currentTimeMillis() val updatedAt: Long = System.currentTimeMillis()
) { ) {
fun toDomain(): InventoryItem { fun toDomain(): InventoryItem {
@@ -29,6 +30,7 @@ data class LocalInventoryItemEntity(
unit = FoodUnit.fromCode(unit), unit = FoodUnit.fromCode(unit),
category = FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name), category = FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name),
location = StorageLocation.fromString(location), location = StorageLocation.fromString(location),
expirationDateEpochDay = expirationDateEpochDay,
updatedAt = updatedAt updatedAt = updatedAt
) )
} }
@@ -48,6 +50,7 @@ data class LocalInventoryItemEntity(
unit = item.unit.code, unit = item.unit.code,
category = item.category.code, category = item.category.code,
location = item.location.name, location = item.location.name,
expirationDateEpochDay = item.expirationDateEpochDay,
updatedAt = System.currentTimeMillis() updatedAt = System.currentTimeMillis()
) )
} }
@@ -107,6 +107,21 @@ interface LocalMealDao {
@Query("SELECT * FROM local_inventory_items WHERE normalizedName = :normalizedName AND unit = :unit LIMIT 1") @Query("SELECT * FROM local_inventory_items WHERE normalizedName = :normalizedName AND unit = :unit LIMIT 1")
suspend fun findInventoryItemByNormalizedAndUnit(normalizedName: String, unit: String): LocalInventoryItemEntity? suspend fun findInventoryItemByNormalizedAndUnit(normalizedName: String, unit: String): LocalInventoryItemEntity?
@Query(
"""
SELECT * FROM local_inventory_items
WHERE normalizedName = :normalizedName
AND unit = :unit
AND ((expirationDateEpochDay IS NULL AND :expirationDateEpochDay IS NULL) OR expirationDateEpochDay = :expirationDateEpochDay)
LIMIT 1
"""
)
suspend fun findInventoryItemByBatch(
normalizedName: String,
unit: String,
expirationDateEpochDay: Long?
): LocalInventoryItemEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertInventoryItem(item: LocalInventoryItemEntity) suspend fun upsertInventoryItem(item: LocalInventoryItemEntity)
@@ -1,8 +1,59 @@
package com.example.data.model package com.example.data.model
import com.example.domain.IngredientMatcher import com.example.domain.IngredientMatcher
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.UUID import java.util.UUID
enum class ExpirationStatus {
EXPIRED,
URGENT,
SOON,
FRESH,
NONE
}
object ExpirationDefaults {
/**
* Suggests a realistic shelf-life in days based on category and storage location,
* or null for long-shelf-life pantry/frozen items where no short-term alert is needed.
*/
fun suggestedShelfLifeDays(category: FoodCategory, location: StorageLocation): Long? {
return when (location) {
StorageLocation.FRIDGE -> when (category) {
FoodCategory.PROTEIN -> 3L
FoodCategory.VEGETABLE -> 5L
FoodCategory.FRUIT -> 5L
FoodCategory.DAIRY -> 7L
FoodCategory.CHEESE -> 14L
FoodCategory.BREAD -> 4L
FoodCategory.STARCH -> 4L
FoodCategory.OTHER -> 5L
FoodCategory.FAT_SEASONING,
FoodCategory.NUTS,
FoodCategory.PLEASURE -> 14L
}
StorageLocation.PANTRY -> when (category) {
FoodCategory.BREAD -> 3L
FoodCategory.FRUIT -> 5L
FoodCategory.VEGETABLE -> 7L
else -> null
}
StorageLocation.FREEZER -> null
}
}
fun suggestedExpirationEpochDay(
category: FoodCategory,
location: StorageLocation,
today: LocalDate = LocalDate.now()
): Long? {
val days = suggestedShelfLifeDays(category, location) ?: return null
return today.plusDays(days).toEpochDay()
}
}
enum class StorageLocation(val displayName: String) { enum class StorageLocation(val displayName: String) {
FRIDGE("Frigo"), FRIDGE("Frigo"),
FREEZER("Congélateur"), FREEZER("Congélateur"),
@@ -79,9 +130,45 @@ data class InventoryItem(
val unit: FoodUnit = FoodUnit.G, val unit: FoodUnit = FoodUnit.G,
val category: FoodCategory = FoodCategory.OTHER, val category: FoodCategory = FoodCategory.OTHER,
val location: StorageLocation = StorageLocation.PANTRY, val location: StorageLocation = StorageLocation.PANTRY,
val expirationDateEpochDay: Long? = null,
val updatedAt: Long = System.currentTimeMillis() val updatedAt: Long = System.currentTimeMillis()
) { ) {
fun formatQuantity(): String = IngredientMatcher.formatQuantity(quantity, unit) fun formatQuantity(): String = IngredientMatcher.formatQuantity(quantity, unit)
fun daysUntilExpiration(today: LocalDate = LocalDate.now()): Long? {
val exp = expirationDateEpochDay ?: return null
return exp - today.toEpochDay()
}
fun expirationStatus(
alertThresholdDays: Int = 3,
today: LocalDate = LocalDate.now()
): ExpirationStatus {
val days = daysUntilExpiration(today) ?: return ExpirationStatus.NONE
val safeThreshold = alertThresholdDays.coerceIn(1, 7).toLong()
return when {
days < 0L -> ExpirationStatus.EXPIRED
days <= 1L -> ExpirationStatus.URGENT
days <= safeThreshold -> ExpirationStatus.SOON
else -> ExpirationStatus.FRESH
}
}
fun formatExpirationBadge(today: LocalDate = LocalDate.now()): String? {
val exp = expirationDateEpochDay ?: return null
val days = exp - today.toEpochDay()
return when {
days < -1L -> "Périmé (${-days} j)"
days == -1L -> "Périmé hier"
days == 0L -> "Aujourd'hui"
days == 1L -> "Demain"
days <= 7L -> "Dans $days j"
else -> {
val fmt = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH)
LocalDate.ofEpochDay(exp).format(fmt)
}
}
}
} }
data class ManualShoppingItem( data class ManualShoppingItem(
@@ -135,6 +222,7 @@ data class ScannedReceiptItem(
val unit: FoodUnit = FoodUnit.PORTION, val unit: FoodUnit = FoodUnit.PORTION,
val category: FoodCategory = FoodCategory.OTHER, val category: FoodCategory = FoodCategory.OTHER,
val location: StorageLocation = StorageLocation.PANTRY, val location: StorageLocation = StorageLocation.PANTRY,
val expirationDateEpochDay: Long? = null,
val selected: Boolean = true val selected: Boolean = true
) )
@@ -204,3 +292,45 @@ sealed interface WeekPredictionUiState {
) : WeekPredictionUiState ) : WeekPredictionUiState
} }
data class MenuAdaptationProposal(
val id: String = "adapt_${UUID.randomUUID().toString().take(8)}",
val dateEpochDay: Long,
val mealType: MealType,
val existingPlannedMealId: String? = null,
val existingMealTitle: String? = null,
val recipeId: String? = null,
val title: String,
val servings: Double = 1.0,
val items: List<MealFoodItem> = emptyList(),
val usedExpiringNames: List<String> = emptyList(),
val reason: String = "",
val selected: Boolean = true
) {
fun toPlannedMealEntry(): PlannedMealEntry {
return PlannedMealEntry(
id = existingPlannedMealId.orEmpty(),
dateEpochDay = dateEpochDay,
mealType = mealType,
recipeId = recipeId,
customTitle = title.trim(),
servings = servings.coerceAtLeast(0.5),
itemsSerialized = if (recipeId.isNullOrBlank()) {
items.map { it.serialize() }
} else {
emptyList()
},
isConsumed = false
)
}
}
sealed interface MenuAdaptationUiState {
data object Idle : MenuAdaptationUiState
data object Loading : MenuAdaptationUiState
data class Preview(
val proposals: List<MenuAdaptationProposal>,
val expiringItems: List<InventoryItem>
) : MenuAdaptationUiState
data class Error(val message: String) : MenuAdaptationUiState
}
@@ -18,9 +18,46 @@ class PlanningPreferencesManager internal constructor(context: Context) {
prefs.edit().putStringSet(KEY_CHECKED_PLAN_KEYS, keys.toSet()).apply() prefs.edit().putStringSet(KEY_CHECKED_PLAN_KEYS, keys.toSet()).apply()
} }
fun getExpirationAlertDays(): Int {
return prefs.getInt(KEY_EXPIRATION_ALERT_DAYS, DEFAULT_EXPIRATION_ALERT_DAYS).coerceIn(1, 7)
}
fun setExpirationAlertDays(days: Int) {
prefs.edit().putInt(KEY_EXPIRATION_ALERT_DAYS, days.coerceIn(1, 7)).apply()
}
fun isExpirationNotifEnabled(): Boolean {
return prefs.getBoolean(KEY_EXPIRATION_NOTIF_ENABLED, true)
}
fun setExpirationNotifEnabled(enabled: Boolean) {
prefs.edit().putBoolean(KEY_EXPIRATION_NOTIF_ENABLED, enabled).apply()
}
fun getExpirationNotifTime(): Pair<Int, Int> {
val hour = prefs.getInt(KEY_EXPIRATION_NOTIF_HOUR, DEFAULT_EXPIRATION_NOTIF_HOUR).coerceIn(0, 23)
val minute = prefs.getInt(KEY_EXPIRATION_NOTIF_MINUTE, DEFAULT_EXPIRATION_NOTIF_MINUTE).coerceIn(0, 59)
return hour to minute
}
fun setExpirationNotifTime(hour: Int, minute: Int) {
prefs.edit()
.putInt(KEY_EXPIRATION_NOTIF_HOUR, hour.coerceIn(0, 23))
.putInt(KEY_EXPIRATION_NOTIF_MINUTE, minute.coerceIn(0, 59))
.apply()
}
companion object { companion object {
private const val PREFS_NAME = "satiea_planning_prefs" private const val PREFS_NAME = "satiea_planning_prefs"
private const val KEY_CHECKED_PLAN_KEYS = "checked_plan_keys" private const val KEY_CHECKED_PLAN_KEYS = "checked_plan_keys"
private const val KEY_EXPIRATION_ALERT_DAYS = "expiration_alert_days"
private const val KEY_EXPIRATION_NOTIF_ENABLED = "expiration_notif_enabled"
private const val KEY_EXPIRATION_NOTIF_HOUR = "expiration_notif_hour"
private const val KEY_EXPIRATION_NOTIF_MINUTE = "expiration_notif_minute"
const val DEFAULT_EXPIRATION_ALERT_DAYS = 3
const val DEFAULT_EXPIRATION_NOTIF_HOUR = 9
const val DEFAULT_EXPIRATION_NOTIF_MINUTE = 0
@Volatile @Volatile
private var instance: PlanningPreferencesManager? = null private var instance: PlanningPreferencesManager? = null
@@ -410,22 +410,23 @@ open class MealRepository(
} }
/** /**
* Adds quantity into stock, automatically merging with an existing stock entry if one * Adds quantity into stock, merging with an existing batch ONLY if normalized name,
* already exists with the same normalized name and unit. * unit, and expiration date match. Different expiration dates create separate batch rows.
*/ */
open suspend fun addOrMergeInventoryItem( open suspend fun addOrMergeInventoryItem(
name: String, name: String,
quantityToAdd: Double, quantityToAdd: Double,
unit: FoodUnit, unit: FoodUnit,
category: FoodCategory, category: FoodCategory,
location: StorageLocation location: StorageLocation,
expirationDateEpochDay: Long? = null
): Result<String> { ): Result<String> {
val cleanName = name.trim() val cleanName = name.trim()
if (cleanName.isBlank() || quantityToAdd <= 0.0) { if (cleanName.isBlank() || quantityToAdd <= 0.0) {
return Result.failure(IllegalArgumentException("Article invalide")) return Result.failure(IllegalArgumentException("Article invalide"))
} }
val norm = IngredientMatcher.normalize(cleanName) val norm = IngredientMatcher.normalize(cleanName)
val existing = localMealDao.findInventoryItemByNormalizedAndUnit(norm, unit.code) val existing = localMealDao.findInventoryItemByBatch(norm, unit.code, expirationDateEpochDay)
return if (existing != null) { return if (existing != null) {
val updated = existing.copy( val updated = existing.copy(
quantity = existing.quantity + quantityToAdd, quantity = existing.quantity + quantityToAdd,
@@ -443,7 +444,8 @@ open class MealRepository(
quantity = quantityToAdd, quantity = quantityToAdd,
unit = unit, unit = unit,
category = category, category = category,
location = location location = location,
expirationDateEpochDay = expirationDateEpochDay
) )
) )
localMealDao.upsertInventoryItem(created) localMealDao.upsertInventoryItem(created)
@@ -2,6 +2,7 @@ package com.example.domain
import android.graphics.Bitmap import android.graphics.Bitmap
import android.util.Log import android.util.Log
import com.example.data.model.ExpirationDefaults
import com.example.data.model.FoodCategory import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.ScannedReceiptItem import com.example.data.model.ScannedReceiptItem
@@ -15,6 +16,7 @@ import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeout
import org.json.JSONObject import org.json.JSONObject
import java.time.LocalDate
import java.util.UUID import java.util.UUID
/** /**
@@ -45,6 +47,10 @@ class ReceiptScannerAnalyzer {
"location" to Schema.enumeration( "location" to Schema.enumeration(
values = allowedLocations, values = allowedLocations,
description = "Emplacement de conservation conseillé : FRIDGE, FREEZER ou PANTRY" description = "Emplacement de conservation conseillé : FRIDGE, FREEZER ou PANTRY"
),
"estimatedShelfLifeDays" to Schema.integer(
description = "Durée de conservation typique estimée en jours pour les produits frais/périssables (ex: 3 pour viande/poisson frais ou pain, 5 pour légumes/fruits frais, 7 pour lait/yaourts, 14 pour fromage), ou 0/null pour les produits secs longue conservation et surgelés",
nullable = true
) )
) )
) )
@@ -86,7 +92,8 @@ RÈGLES STRICTES :
4. Choisis la catégorie la plus juste parmi ces codes : 4. Choisis la catégorie la plus juste parmi ces codes :
$categoriesHelp $categoriesHelp
5. Choisis l'emplacement conseillé : FRIDGE (produits frais, viande, fromage, yaourts, légumes frais), FREEZER (surgelés, glaces), PANTRY (sec, pâtes, riz, conserves, huiles, pain, fruits à coque, chocolat). 5. Choisis l'emplacement conseillé : FRIDGE (produits frais, viande, fromage, yaourts, légumes frais), FREEZER (surgelés, glaces), PANTRY (sec, pâtes, riz, conserves, huiles, pain, fruits à coque, chocolat).
6. Si l'image n'est pas un ticket de caisse ou ne contient aucun aliment lisible, renvoie une liste items vide. 6. Estime `estimatedShelfLifeDays` (nombre de jours avant péremption) pour les produits frais/périssables (ex: viande/poisson frais = 3, légumes/fruits frais = 5, yaourts/lait = 7, fromage = 14, pain = 3) ; mets null ou 0 pour les surgelés et produits secs longue conservation.
7. Si l'image n'est pas un ticket de caisse ou ne contient aucun aliment lisible, renvoie une liste items vide.
""".trimIndent() """.trimIndent()
return try { return try {
@@ -129,7 +136,10 @@ $categoriesHelp
companion object { companion object {
private const val TAG = "ReceiptScannerAnalyzer" private const val TAG = "ReceiptScannerAnalyzer"
fun parseReceiptJson(jsonString: String): List<ScannedReceiptItem> { fun parseReceiptJson(
jsonString: String,
today: LocalDate = LocalDate.now()
): List<ScannedReceiptItem> {
val root = JSONObject(jsonString) val root = JSONObject(jsonString)
val itemsArr = root.optJSONArray("items") ?: return emptyList() val itemsArr = root.optJSONArray("items") ?: return emptyList()
val results = mutableListOf<ScannedReceiptItem>() val results = mutableListOf<ScannedReceiptItem>()
@@ -146,6 +156,14 @@ $categoriesHelp
?: FoodCategory.inferFromName(name) ?: FoodCategory.inferFromName(name)
val location = StorageLocation.fromString(obj.optString("location", "PANTRY")) val location = StorageLocation.fromString(obj.optString("location", "PANTRY"))
val estimatedDays = if (obj.has("estimatedShelfLifeDays") && !obj.isNull("estimatedShelfLifeDays")) {
obj.optInt("estimatedShelfLifeDays", 0).takeIf { it in 1..365 }?.toLong()
} else {
null
}
val expirationEpochDay = estimatedDays?.let { today.plusDays(it).toEpochDay() }
?: ExpirationDefaults.suggestedExpirationEpochDay(category, location, today)
results.add( results.add(
ScannedReceiptItem( ScannedReceiptItem(
id = "scan_${i}_${UUID.randomUUID().toString().take(6)}", id = "scan_${i}_${UUID.randomUUID().toString().take(6)}",
@@ -155,6 +173,7 @@ $categoriesHelp
unit = unit, unit = unit,
category = category, category = category,
location = location, location = location,
expirationDateEpochDay = expirationEpochDay,
selected = true selected = true
) )
) )
@@ -187,6 +187,7 @@ object ShoppingListCalculator {
/** /**
* Proposes stock deductions for foods just eaten in a meal or marked consumed from the weekly plan. * Proposes stock deductions for foods just eaten in a meal or marked consumed from the weekly plan.
* Uses FIFO order: batches with the earliest expiration date are deducted first.
*/ */
fun computeStockDeductionProposals( fun computeStockDeductionProposals(
eatenItems: List<MealFoodItem>, eatenItems: List<MealFoodItem>,
@@ -195,24 +196,34 @@ object ShoppingListCalculator {
if (eatenItems.isEmpty() || inventory.isEmpty()) return emptyList() if (eatenItems.isEmpty() || inventory.isEmpty()) return emptyList()
// Aggregate eaten quantities per (normalizedName, unit) // Aggregate eaten quantities per (normalizedName, unit)
val eatenByKey = linkedMapOf<NeedKey, Double>() val remainingNeededByKey = linkedMapOf<NeedKey, Double>()
eatenItems.forEach { food -> eatenItems.forEach { food ->
val norm = IngredientMatcher.normalize(food.name) val norm = IngredientMatcher.normalize(food.name)
if (norm.isBlank()) return@forEach if (norm.isBlank()) return@forEach
val qty = food.weight?.takeIf { it > 0.0 } ?: if (food.unit == FoodUnit.PORTION) 1.0 else 0.0 val qty = food.weight?.takeIf { it > 0.0 } ?: if (food.unit == FoodUnit.PORTION) 1.0 else 0.0
if (qty <= 0.0) return@forEach if (qty <= 0.0) return@forEach
val key = NeedKey(norm, food.unit) val key = NeedKey(norm, food.unit)
eatenByKey[key] = (eatenByKey[key] ?: 0.0) + qty remainingNeededByKey[key] = (remainingNeededByKey[key] ?: 0.0) + qty
} }
// Process inventory batches in FIFO order (earliest expiration date first)
val fifoInventory = inventory.sortedWith(
compareBy<InventoryItem> { it.expirationDateEpochDay ?: Long.MAX_VALUE }
.thenBy { it.updatedAt }
)
val proposals = mutableListOf<StockDeductionProposal>() val proposals = mutableListOf<StockDeductionProposal>()
inventory.forEach { stockItem -> fifoInventory.forEach { stockItem ->
if (stockItem.quantity <= 0.0) return@forEach if (stockItem.quantity <= 0.0) return@forEach
val stockNorm = stockItem.normalizedName.ifBlank { IngredientMatcher.normalize(stockItem.name) } val stockNorm = stockItem.normalizedName.ifBlank { IngredientMatcher.normalize(stockItem.name) }
val matchedQty = eatenByKey[NeedKey(stockNorm, stockItem.unit)] ?: return@forEach val key = NeedKey(stockNorm, stockItem.unit)
val deduct = roundClean(min(stockItem.quantity, matchedQty), stockItem.unit) val neededQty = remainingNeededByKey[key] ?: return@forEach
if (neededQty <= 0.0) return@forEach
val deduct = roundClean(min(stockItem.quantity, neededQty), stockItem.unit)
if (deduct > 0.0) { if (deduct > 0.0) {
val remaining = roundClean(max(0.0, stockItem.quantity - deduct), stockItem.unit) val remaining = roundClean(max(0.0, stockItem.quantity - deduct), stockItem.unit)
remainingNeededByKey[key] = max(0.0, neededQty - deduct)
proposals.add( proposals.add(
StockDeductionProposal( StockDeductionProposal(
inventoryItem = stockItem, inventoryItem = stockItem,
@@ -223,7 +234,10 @@ object ShoppingListCalculator {
) )
} }
} }
return proposals.sortedBy { it.inventoryItem.name.lowercase(Locale.FRENCH) } return proposals.sortedWith(
compareBy<StockDeductionProposal> { it.inventoryItem.name.lowercase(Locale.FRENCH) }
.thenBy { it.inventoryItem.expirationDateEpochDay ?: Long.MAX_VALUE }
)
} }
fun buildPlanItemKey(normalizedName: String, unit: FoodUnit): String { fun buildPlanItemKey(normalizedName: String, unit: FoodUnit): String {
@@ -9,6 +9,7 @@ import com.example.data.model.InventoryItem
import com.example.data.model.MealEntry 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.MealType
import com.example.data.model.MenuAdaptationProposal
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.RecipeEntry import com.example.data.model.RecipeEntry
@@ -183,11 +184,24 @@ class WeeklyMealPredictor {
} }
} }
val stockText = if (inventory.isEmpty()) { val today = LocalDate.now()
val usableInventory = inventory
.filter { (it.daysUntilExpiration(today) ?: Long.MAX_VALUE) >= 0L }
.sortedBy { it.expirationDateEpochDay ?: Long.MAX_VALUE }
val stockText = if (usableInventory.isEmpty()) {
"Stock vide." "Stock vide."
} else { } else {
inventory.take(40).joinToString(", ") { item -> usableInventory.take(40).joinToString(", ") { item ->
"${item.name} (${item.formatQuantity()}, ${item.location.displayName})" val expDays = item.daysUntilExpiration(today)
val expTag = when {
expDays == null -> ""
expDays == 0L -> " — URGENT : EXPIRE AUJOURD'HUI !"
expDays == 1L -> " — URGENT : EXPIRE DEMAIN !"
expDays <= 5L -> " — expire dans $expDays j"
else -> ""
}
"${item.name} (${item.formatQuantity()}, ${item.location.displayName}$expTag)"
} }
} }
@@ -250,7 +264,7 @@ $recentMealsText
RÈGLES STRICTES : RÈGLES STRICTES :
1. Respecte absolument les aliments à éviter (ne les utilise jamais). 1. Respecte absolument les aliments à éviter (ne les utilise jamais).
2. Priorise les ingrédients déjà présents dans le stock (notamment produits frais du Frigo) en gardant les mêmes noms simples pour que le calcul des courses les reconnaisse. 2. Priorise en PREMIER les ingrédients marqués URGENT ou avec une date de péremption proche (place-les sur les premiers jours avant leur date limite), puis le reste du stock (notamment produits frais du Frigo) en gardant les mêmes noms simples pour que le calcul des courses les reconnaisse.
3. Réutilise volontiers 1 à 4 recettes existantes (en mettant leur `recipeId` exact) si elles s'accordent avec la semaine et le stock, et complète avec des repas simples et variés (`recipeId` = ""). 3. Réutilise volontiers 1 à 4 recettes existantes (en mettant leur `recipeId` exact) si elles s'accordent avec la semaine et le stock, et complète avec des repas simples et variés (`recipeId` = "").
4. Adapte chaque repas à son moment de la journée (Petit-déjeuner, Déjeuner, Collation, Dîner) et assure une belle variété sur la semaine (équilibre légumes, protéines, féculents, laitages/fruits). 4. Adapte chaque repas à son moment de la journée (Petit-déjeuner, Déjeuner, Collation, Dîner) et assure une belle variété sur la semaine (équilibre légumes, protéines, féculents, laitages/fruits).
5. Pour CHAQUE repas, fournis une liste `ingredients` avec des quantités réalistes pour $formattedServings portion(s), en utilisant UNIQUEMENT les unités "g", "ml" ou "portion", et les codes catégories : $categoriesHelp. 5. Pour CHAQUE repas, fournis une liste `ingredients` avec des quantités réalistes pour $formattedServings portion(s), en utilisant UNIQUEMENT les unités "g", "ml" ou "portion", et les codes catégories : $categoriesHelp.
@@ -258,11 +272,199 @@ RÈGLES STRICTES :
""".trimIndent() """.trimIndent()
} }
private val adaptationResponseSchema by lazy {
val ingredientSchema = Schema.obj(
properties = mapOf(
"name" to Schema.string(description = "Nom français simple de l'ingrédient"),
"weight" to Schema.double(description = "Quantité numérique réaliste pour le nombre de portions"),
"unit" to Schema.enumeration(
values = allowedUnitCodes,
description = "Unité : g, ml ou portion"
),
"category" to Schema.enumeration(
values = allowedCategoryCodes,
description = "Code exact de catégorie alimentaire"
)
)
)
val adaptationSchema = Schema.obj(
properties = mapOf(
"slotIndex" to Schema.integer(description = "Index entier exact (0..N-1) du créneau candidat à adapter ou remplir"),
"recipeId" to Schema.string(
description = "ID exact d'une recette existante si pertinente, ou chaîne vide \"\" pour un repas libre",
nullable = true
),
"title" to Schema.string(description = "Nom clair et appétissant du repas proposé en français"),
"reason" to Schema.string(description = "Courte raison bienveillante (max 10 mots, ex: 'Sauve votre poulet et courgettes avant demain')"),
"usedExpiringNames" to Schema.array(
items = Schema.string(),
description = "Noms des aliments proches de la péremption utilisés dans ce repas"
),
"ingredients" to Schema.array(
items = ingredientSchema,
description = "Liste complète des ingrédients avec quantités pour le nombre de portions"
)
)
)
Schema.obj(
properties = mapOf(
"adaptations" to Schema.array(
items = adaptationSchema,
description = "1 à 4 adaptations ciblées (remplissage de créneaux vides ou remplacement de repas à venir) pour consommer les aliments avant leur DLC"
)
)
)
}
private val adaptationModel by lazy {
val config = generationConfig {
responseMimeType = "application/json"
responseSchema = this@WeeklyMealPredictor.adaptationResponseSchema
temperature = 0.5f
}
Firebase.ai.generativeModel(
modelName = "gemini-3.8-flash",
generationConfig = config
)
}
/**
* Proposes targeted menu adaptations (filling empty slots or swapping unconsumed upcoming meals)
* before the expiration dates of soon-to-expire stock items.
*/
suspend fun adaptMenusForExpiringItems(
expiringItems: List<InventoryItem>,
candidateSlots: List<Pair<LocalDate, MealType>>,
existingMealsBySlot: Map<Pair<LocalDate, MealType>, PlannedMealEntry>,
allInventory: List<InventoryItem>,
recipes: List<RecipeEntry>,
preferences: List<FoodPreferenceEntry>,
defaultServings: Double = 2.0
): Result<List<MenuAdaptationProposal>> {
if (expiringItems.isEmpty() || candidateSlots.isEmpty()) {
return Result.failure(
IllegalStateException("Aucun créneau ou aliment proche de la péremption à adapter.")
)
}
val recipesById = recipes.associateBy { it.id }
val today = LocalDate.now()
val dayFmt = DateTimeFormatter.ofPattern("EEEE d MMM", Locale.FRENCH)
val expiringText = expiringItems.joinToString("\n") { item ->
val badge = item.formatExpirationBadge(today) ?: "bientôt"
"- ${item.name} (${item.formatQuantity()}, ${item.location.displayName}) — DLC : $badge"
}
val slotsText = candidateSlots.mapIndexed { idx, (date, type) ->
val existing = existingMealsBySlot[date to type]
val currentLabel = if (existing != null) {
"ACTUELLEMENT PLANIFIÉ : « ${existing.resolvedTitle(recipesById)} » (${existing.servings} part(s))"
} else {
"CRÉNEAU VIDE"
}
"[$idx] ${date.format(dayFmt)} — ${type.displayName} | $currentLabel"
}.joinToString("\n")
val otherStockText = allInventory
.filter { item ->
(item.daysUntilExpiration(today) ?: Long.MAX_VALUE) >= 0L &&
expiringItems.none { it.id == item.id }
}
.take(25)
.joinToString(", ") { "${it.name} (${it.formatQuantity()})" }
.ifBlank { "Aucun autre aliment." }
val recipesText = recipes.take(25).joinToString("\n") { r ->
val ingNames = r.parsedIngredients().take(6).joinToString(", ") { it.name }
"- id=\"${r.id}\" | ${r.title} (${r.servings} parts) | ingrédients: $ingNames"
}.ifBlank { "Aucune recette enregistrée." }
val disliked = preferences.filter { it.status == FoodPreferenceStatus.DISLIKED }.map { it.name }
val categoriesHelp = FoodCategory.entries.joinToString(", ") { "${it.code} (${it.shortLabel})" }
val formattedServings = if (defaultServings % 1.0 == 0.0) {
defaultServings.toInt().toString()
} else {
defaultServings.toString()
}
val prompt = """
Tu es l'assistant anti-gaspillage bienveillant de Satiéa.
Propose entre 1 et 4 adaptations de menus ciblées pour consommer les aliments proches de leur date de péremption AVANT leur date limite, pour $formattedServings portion(s) par repas.
ALIMENTS À CONSOMMER EN PRIORITÉ (proches de leur DLC) :
$expiringText
CRÉNEAUX À VENIR DISPONIBLES (choisis les créneaux les plus pertinents AVANT la DLC de chaque aliment) :
$slotsText
AUTRES ALIMENTS DISPONIBLES EN STOCK :
$otherStockText
RECETTES DE L'UTILISATEUR :
$recipesText
ALIMENTS À ÉVITER ABSOLUMENT :
${disliked.ifEmpty { listOf("Aucun") }.joinToString(", ")}
RÈGLES STRICTES :
1. Ne propose que les créneaux nécessaires (1 à 4 adaptations maximum) pour écouler au mieux les aliments urgents AVANT leur date limite.
2. Privilégie d'abord les créneaux vides ; si nécessaire, propose de remplacer un repas déjà planifié qui n'utilise pas les aliments urgents.
3. Respecte absolument les aliments à éviter.
4. Utilise exactement les mêmes noms simples pour les ingrédients du stock.
5. Pour chaque adaptation, fournis `usedExpiringNames` (liste des aliments urgents consommés par ce repas) et `ingredients` complets avec unités "g", "ml" ou "portion" et catégories parmi : $categoriesHelp.
""".trimIndent()
return try {
val response = withTimeout(60_000L) {
adaptationModel.generateContent(prompt)
}
val jsonText = response.text
if (jsonText.isNullOrBlank()) {
Result.failure(
IllegalStateException("Aucune proposition d'adaptation n'a été générée. Réessayez dans un instant.")
)
} else {
val parsed = parseAdaptationJson(
jsonString = jsonText,
candidateSlots = candidateSlots,
existingMealsBySlot = existingMealsBySlot,
recipesById = recipesById,
defaultServings = defaultServings
)
if (parsed.isEmpty()) {
Result.failure(
IllegalStateException("Impossible d'extraire une adaptation exploitable. Veuillez réessayer.")
)
} else {
Result.success(parsed)
}
}
} catch (e: TimeoutCancellationException) {
Log.e(TAG, "Menu adaptation timed out", e)
Result.failure(
IllegalStateException("L'adaptation des menus a dépassé le délai (60 s). Vérifiez votre connexion et réessayez.")
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Menu adaptation failed", e)
Result.failure(
IllegalStateException(
e.localizedMessage ?: "Impossible d'adapter les menus pour le moment."
)
)
}
}
companion object { companion object {
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 responseAdapter = moshi.adapter(PredictionResponseDto::class.java).lenient() private val responseAdapter = moshi.adapter(PredictionResponseDto::class.java).lenient()
private val adaptationAdapter = moshi.adapter(MenuAdaptationResponseDto::class.java).lenient()
/** /**
* Pure JVM JSON parser (typed Moshi DTOs) for offline testability and resilient handling * Pure JVM JSON parser (typed Moshi DTOs) for offline testability and resilient handling
@@ -345,8 +547,114 @@ RÈGLES STRICTES :
.thenBy { it.mealType.ordinal } .thenBy { it.mealType.ordinal }
) )
} }
fun parseAdaptationJson(
jsonString: String,
candidateSlots: List<Pair<LocalDate, MealType>>,
existingMealsBySlot: Map<Pair<LocalDate, MealType>, PlannedMealEntry>,
recipesById: Map<String, RecipeEntry>,
defaultServings: Double
): List<MenuAdaptationProposal> {
if (jsonString.isBlank() || candidateSlots.isEmpty()) return emptyList()
val root = try {
adaptationAdapter.fromJson(jsonString)
} catch (_: Exception) {
null
} ?: return emptyList()
val list = root.adaptations ?: return emptyList()
val usedSlotIndices = mutableSetOf<Int>()
val proposals = mutableListOf<MenuAdaptationProposal>()
for (dto in list) {
val slotIndex = dto.slotIndex ?: continue
if (slotIndex !in candidateSlots.indices || !usedSlotIndices.add(slotIndex)) continue
val slot = candidateSlots[slotIndex]
val (date, mealType) = slot
val existing = existingMealsBySlot[slot]
val rawRecipeId = dto.recipeId?.trim().orEmpty()
val matchedRecipe = rawRecipeId.takeIf { it.isNotBlank() }?.let { recipesById[it] }
val rawTitle = dto.title?.trim().orEmpty()
val resolvedTitle = when {
matchedRecipe != null -> matchedRecipe.title
rawTitle.isNotBlank() -> rawTitle
else -> continue
}
val safeServings = existing?.servings?.takeIf { it.isFinite() && it >= 0.5 }
?: defaultServings.takeIf { it.isFinite() }?.coerceAtLeast(0.5)
?: 1.0
val parsedIngredients = dto.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) {
matchedRecipe.scaledIngredients(safeServings)
} else {
parsedIngredients
}
val usedExpiring = dto.usedExpiringNames.orEmpty()
.map { it.trim() }
.filter { it.isNotBlank() }
.distinct()
proposals.add(
MenuAdaptationProposal(
id = "adapt_${slotIndex}_${UUID.randomUUID().toString().take(6)}",
dateEpochDay = date.toEpochDay(),
mealType = mealType,
existingPlannedMealId = existing?.id?.takeIf { it.isNotBlank() },
existingMealTitle = existing?.resolvedTitle(recipesById),
recipeId = matchedRecipe?.id,
title = resolvedTitle,
servings = safeServings,
items = resolvedItems,
usedExpiringNames = usedExpiring,
reason = dto.reason?.trim().orEmpty(),
selected = true
)
)
}
return proposals.sortedWith(
compareBy<MenuAdaptationProposal> { it.dateEpochDay }
.thenBy { it.mealType.ordinal }
)
} }
} }
}
@JsonClass(generateAdapter = true)
internal data class MenuAdaptationResponseDto(
val adaptations: List<MenuAdaptationDto>? = null
)
@JsonClass(generateAdapter = true)
internal data class MenuAdaptationDto(
val slotIndex: Int? = null,
val recipeId: String? = null,
val title: String? = null,
val reason: String? = null,
val usedExpiringNames: List<String>? = null,
val ingredients: List<PredictedIngredientDto>? = null
)
@JsonClass(generateAdapter = true) @JsonClass(generateAdapter = true)
internal data class PredictionResponseDto( internal data class PredictionResponseDto(
@@ -12,8 +12,11 @@ import android.util.Log
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import com.example.MainActivity import com.example.MainActivity
import com.example.R import com.example.R
import com.example.data.model.InventoryItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.preferences.PlanningPreferencesManager
import com.example.data.preferences.ReminderPreferencesManager import com.example.data.preferences.ReminderPreferencesManager
import com.example.receiver.ExpirationAlertReceiver
import com.example.receiver.MealReminderReceiver import com.example.receiver.MealReminderReceiver
import java.time.ZoneId import java.time.ZoneId
import java.time.ZonedDateTime import java.time.ZonedDateTime
@@ -23,16 +26,22 @@ object MealNotificationManager {
private const val TAG = "MealNotificationManager" private const val TAG = "MealNotificationManager"
const val CHANNEL_ID = "meal_reminders_channel_v2" const val CHANNEL_ID = "meal_reminders_channel_v2"
const val CHANNEL_NAME = "Rappels de Repas Satiéa" const val CHANNEL_NAME = "Rappels de Repas Satiéa"
const val EXPIRATION_CHANNEL_ID = "expiration_alerts_channel_v1"
const val EXPIRATION_CHANNEL_NAME = "Alertes de Péremption Satiéa"
const val EXTRA_MEAL_TYPE = "extra_meal_type" const val EXTRA_MEAL_TYPE = "extra_meal_type"
const val ACTION_LOG_MEAL = "com.example.action.LOG_MEAL" const val ACTION_LOG_MEAL = "com.example.action.LOG_MEAL"
const val ACTION_OPEN_PLANNING_EXPIRING = "com.example.action.OPEN_PLANNING_EXPIRING"
private const val EXPIRATION_ALARM_REQUEST_CODE = 401
private const val EXPIRATION_NOTIFICATION_ID = 402
fun createNotificationChannel(context: Context) { fun createNotificationChannel(context: Context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
val mealChannel = NotificationChannel(
CHANNEL_ID, CHANNEL_ID,
CHANNEL_NAME, CHANNEL_NAME,
importance NotificationManager.IMPORTANCE_HIGH
).apply { ).apply {
description = "Rappels prioritaires pour évaluer votre faim et noter vos repas à table." description = "Rappels prioritaires pour évaluer votre faim et noter vos repas à table."
enableVibration(true) enableVibration(true)
@@ -40,8 +49,17 @@ object MealNotificationManager {
setShowBadge(true) setShowBadge(true)
setBypassDnd(false) setBypassDnd(false)
} }
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(mealChannel)
notificationManager.createNotificationChannel(channel)
val expirationChannel = NotificationChannel(
EXPIRATION_CHANNEL_ID,
EXPIRATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Alertes quotidiennes pour consommer vos aliments proches de leur date limite et adapter vos menus."
setShowBadge(true)
}
notificationManager.createNotificationChannel(expirationChannel)
} }
} }
@@ -147,5 +165,116 @@ object MealNotificationManager {
val (hour, minute) = prefs.getReminderTime(mealType) val (hour, minute) = prefs.getReminderTime(mealType)
scheduleDailyReminder(context, mealType, hour, minute, enabled) scheduleDailyReminder(context, mealType, hour, minute, enabled)
} }
val planningPrefs = PlanningPreferencesManager.getInstance(context)
val (expHour, expMinute) = planningPrefs.getExpirationNotifTime()
scheduleExpirationDailyCheck(
context = context,
hour = expHour,
minute = expMinute,
enabled = planningPrefs.isExpirationNotifEnabled()
)
}
fun scheduleExpirationDailyCheck(
context: Context,
hour: Int,
minute: Int,
enabled: Boolean
) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
val intent = Intent(context, ExpirationAlertReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context,
EXPIRATION_ALARM_REQUEST_CODE,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
if (!enabled) {
alarmManager.cancel(pendingIntent)
Log.d(TAG, "Cancelled daily expiration check alarm")
return
}
val zoneId = ZoneId.systemDefault()
val nowZoned = ZonedDateTime.now(zoneId)
var triggerZoned = nowZoned.withHour(hour.coerceIn(0, 23))
.withMinute(minute.coerceIn(0, 59))
.withSecond(0)
.withNano(0)
if (!triggerZoned.isAfter(nowZoned)) {
triggerZoned = triggerZoned.plusDays(1)
}
val triggerMillis = triggerZoned.toInstant().toEpochMilli()
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
triggerMillis,
pendingIntent
)
} else {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
triggerMillis,
pendingIntent
)
}
Log.d(TAG, "Scheduled daily expiration check at $triggerZoned")
} catch (e: Exception) {
Log.w(TAG, "Could not schedule expiration check: ${e.message}")
}
}
fun showExpirationAlertNotification(
context: Context,
expiringItems: List<InventoryItem>
) {
if (expiringItems.isEmpty()) return
createNotificationChannel(context)
val intent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
action = ACTION_OPEN_PLANNING_EXPIRING
}
val pendingIntent = PendingIntent.getActivity(
context,
EXPIRATION_NOTIFICATION_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
val count = expiringItems.size
val title = if (count == 1) {
"1 aliment à consommer bientôt"
} else {
"$count aliments à consommer bientôt"
}
val summaryNames = expiringItems.take(4).joinToString(", ") { item ->
val badge = item.formatExpirationBadge()
if (badge != null) "${item.name} ($badge)" else item.name
}
val moreSuffix = if (count > 4) " et ${count - 4} autre(s)" else ""
val body = "$summaryNames$moreSuffix. Adaptez vos menus pour éviter le gaspillage."
val notification = NotificationCompat.Builder(context, EXPIRATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification_bell)
.setContentTitle(title)
.setContentText(body)
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.addAction(
R.drawable.ic_notification_bell,
"Adapter mes menus",
pendingIntent
)
.build()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(EXPIRATION_NOTIFICATION_ID, notification)
} }
} }
@@ -0,0 +1,54 @@
package com.example.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import com.example.data.local.AppDatabase
import com.example.data.model.ExpirationStatus
import com.example.data.preferences.PlanningPreferencesManager
import com.example.notification.MealNotificationManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class ExpirationAlertReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pendingResult = goAsync()
val appContext = context.applicationContext
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
try {
val prefs = PlanningPreferencesManager.getInstance(appContext)
if (!prefs.isExpirationNotifEnabled()) return@launch
val thresholdDays = prefs.getExpirationAlertDays()
val allItems = AppDatabase.getInstance(appContext)
.mealDao()
.getAllInventoryItemsOnce()
.map { it.toDomain() }
val alertItems = allItems
.filter { item ->
val status = item.expirationStatus(alertThresholdDays = thresholdDays)
status == ExpirationStatus.URGENT || status == ExpirationStatus.SOON
}
.sortedBy { it.expirationDateEpochDay ?: Long.MAX_VALUE }
if (alertItems.isNotEmpty()) {
MealNotificationManager.showExpirationAlertNotification(appContext, alertItems)
}
// Reschedule for tomorrow
val (hour, minute) = prefs.getExpirationNotifTime()
MealNotificationManager.scheduleExpirationDailyCheck(appContext, hour, minute, true)
} catch (e: Exception) {
Log.e("ExpirationAlertReceiver", "Failed to check expiring inventory items", e)
} finally {
pendingResult.finish()
}
}
}
}
@@ -0,0 +1,349 @@
package com.example.ui.planning
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.MenuAdaptationProposal
import com.example.data.model.MenuAdaptationUiState
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdaptMenusForExpiringSheet(
adaptationState: MenuAdaptationUiState,
onToggleProposal: (String) -> Unit,
onConfirm: () -> Unit,
onRetry: () -> Unit,
onDismiss: () -> Unit
) {
if (adaptationState is MenuAdaptationUiState.Idle) return
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val dayFmt = remember { DateTimeFormatter.ofPattern("EEEE d MMM", Locale.FRENCH) }
ModalBottomSheet(
onDismissRequest = {
if (adaptationState !is MenuAdaptationUiState.Loading) {
onDismiss()
}
},
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.padding(horizontal = 20.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
when (adaptationState) {
MenuAdaptationUiState.Idle -> Unit
MenuAdaptationUiState.Loading -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 32.dp)
.testTag("menu_adaptation_loading"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
CircularProgressIndicator()
Text(
text = "Adaptation de vos menus en cours...",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Text(
text = "Satiéa cherche les meilleurs créneaux avant la date limite pour consommer vos aliments urgents.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
is MenuAdaptationUiState.Error -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 20.dp)
.testTag("menu_adaptation_error"),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(40.dp)
)
Text(
text = "Adaptation impossible",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
text = adaptationState.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
modifier = Modifier.weight(1f)
) {
Text("Fermer")
}
Button(
onClick = onRetry,
modifier = Modifier.weight(1f)
) {
Text("Réessayer")
}
}
}
}
is MenuAdaptationUiState.Preview -> {
val selectedCount = adaptationState.proposals.count { it.selected }
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Column {
Text(
text = "Menus adaptés anti-gaspi",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "Cochez les changements que vous souhaitez appliquer à votre planning",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 420.dp)
.testTag("menu_adaptation_list"),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(adaptationState.proposals, key = { it.id }) { proposal ->
MenuAdaptationProposalCard(
proposal = proposal,
dayFormatter = dayFmt,
onToggle = { onToggleProposal(proposal.id) }
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(14.dp),
modifier = Modifier.weight(0.4f)
) {
Text("Annuler")
}
Button(
onClick = onConfirm,
enabled = selectedCount > 0,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(0.6f)
.testTag("confirm_menu_adaptation_button")
) {
Text("Appliquer $selectedCount menu${if (selectedCount > 1) "s" else ""}")
}
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun MenuAdaptationProposalCard(
proposal: MenuAdaptationProposal,
dayFormatter: DateTimeFormatter,
onToggle: () -> Unit
) {
val dateLabel = LocalDate.ofEpochDay(proposal.dateEpochDay)
.format(dayFormatter)
.replaceFirstChar { it.titlecase(Locale.FRENCH) }
val isReplacement = !proposal.existingMealTitle.isNullOrBlank()
Card(
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(
containerColor = if (proposal.selected) {
MaterialTheme.colorScheme.surface
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f)
}
),
border = BorderStroke(
width = 1.dp,
color = if (proposal.selected) {
MaterialTheme.colorScheme.primary.copy(alpha = 0.45f)
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)
}
),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalAlignment = Alignment.Top
) {
Checkbox(
checked = proposal.selected,
onCheckedChange = { onToggle() }
)
Spacer(modifier = Modifier.width(4.dp))
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Text(
text = "$dateLabel • ${proposal.mealType.displayName}",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
if (isReplacement) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
Icon(
imageVector = Icons.Default.SwapHoriz,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(16.dp)
)
Text(
text = proposal.existingMealTitle.orEmpty(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textDecoration = TextDecoration.LineThrough,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
} else {
Text(
text = "Créneau libre",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text(
text = proposal.title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
if (proposal.reason.isNotBlank()) {
Text(
text = proposal.reason,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (proposal.usedExpiringNames.isNotEmpty()) {
Spacer(modifier = Modifier.height(2.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
proposal.usedExpiringNames.forEach { usedName ->
Surface(
shape = RoundedCornerShape(8.dp),
color = MaterialTheme.colorScheme.secondaryContainer
) {
Text(
text = "Sauve : $usedName",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
}
}
}
}
}
}
}
@@ -15,8 +15,13 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -25,6 +30,8 @@ import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -37,11 +44,17 @@ import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.ExpirationDefaults
import com.example.data.model.FoodCategory import com.example.data.model.FoodCategory
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.StorageLocation import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategorySelectorRow import com.example.ui.common.FoodCategorySelectorRow
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -70,6 +83,23 @@ fun InventoryItemEditorSheet(
var selectedLocation by remember(initialItem) { var selectedLocation by remember(initialItem) {
mutableStateOf(initialItem?.location ?: StorageLocation.PANTRY) mutableStateOf(initialItem?.location ?: StorageLocation.PANTRY)
} }
var expirationEpochDay by remember(initialItem) {
mutableStateOf(
if (isEditing) {
initialItem?.expirationDateEpochDay
} else {
ExpirationDefaults.suggestedExpirationEpochDay(
initialItem?.category ?: FoodCategory.OTHER,
initialItem?.location ?: StorageLocation.PANTRY
)
}
)
}
var hasManualExpiration by remember(initialItem) { mutableStateOf(isEditing) }
var showDatePicker by remember { mutableStateOf(false) }
val dateFormatter = remember { DateTimeFormatter.ofPattern("d MMM yyyy", Locale.FRENCH) }
val today = remember { LocalDate.now() }
val parsedQty = quantityText.replace(',', '.').toDoubleOrNull() val parsedQty = quantityText.replace(',', '.').toDoubleOrNull()
val canSave = name.isNotBlank() && parsedQty != null && parsedQty > 0.0 val canSave = name.isNotBlank() && parsedQty != null && parsedQty > 0.0
@@ -99,7 +129,11 @@ fun InventoryItemEditorSheet(
onValueChange = { updated -> onValueChange = { updated ->
name = updated name = updated
if (!hasManualCategory && updated.isNotBlank()) { if (!hasManualCategory && updated.isNotBlank()) {
selectedCategory = FoodCategory.inferFromName(updated) val inferredCat = FoodCategory.inferFromName(updated)
selectedCategory = inferredCat
if (!hasManualExpiration) {
expirationEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(inferredCat, selectedLocation, today)
}
} }
}, },
label = { Text("Nom de l'aliment") }, label = { Text("Nom de l'aliment") },
@@ -153,7 +187,12 @@ fun InventoryItemEditorSheet(
StorageLocation.entries.forEach { loc -> StorageLocation.entries.forEach { loc ->
FilterChip( FilterChip(
selected = selectedLocation == loc, selected = selectedLocation == loc,
onClick = { selectedLocation = loc }, onClick = {
selectedLocation = loc
if (!hasManualExpiration) {
expirationEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(selectedCategory, loc, today)
}
},
label = { Text(loc.displayName) }, label = { Text(loc.displayName) },
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
@@ -174,10 +213,75 @@ fun InventoryItemEditorSheet(
onCategorySelected = { cat -> onCategorySelected = { cat ->
selectedCategory = cat selectedCategory = cat
hasManualCategory = true hasManualCategory = true
if (!hasManualExpiration) {
expirationEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(cat, selectedLocation, today)
}
} }
) )
} }
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Date de péremption (optionnelle)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedButton(
onClick = { showDatePicker = true },
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.weight(1f)
.testTag("inventory_expiration_picker_button")
) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = null
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = expirationEpochDay?.let {
LocalDate.ofEpochDay(it).format(dateFormatter)
} ?: "Choisir une date"
)
}
if (expirationEpochDay != null) {
AssistChip(
onClick = {
expirationEpochDay = null
hasManualExpiration = true
},
label = { Text("Effacer") },
leadingIcon = {
Icon(Icons.Default.Close, contentDescription = null)
},
modifier = Modifier.testTag("inventory_expiration_clear_button")
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
listOf(3L to "+3 j", 7L to "+7 j", 14L to "+14 j").forEach { (days, label) ->
val targetEpoch = today.plusDays(days).toEpochDay()
FilterChip(
selected = expirationEpochDay == targetEpoch,
onClick = {
expirationEpochDay = targetEpoch
hasManualExpiration = true
},
label = { Text(label) },
modifier = Modifier.weight(1f)
)
}
}
}
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
Row( Row(
@@ -209,7 +313,8 @@ fun InventoryItemEditorSheet(
quantity = qty, quantity = qty,
unit = selectedUnit, unit = selectedUnit,
category = selectedCategory, category = selectedCategory,
location = selectedLocation location = selectedLocation,
expirationDateEpochDay = expirationEpochDay
) )
) )
}, },
@@ -226,4 +331,35 @@ fun InventoryItemEditorSheet(
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
} }
} }
if (showDatePicker) {
val initialMillis = (expirationEpochDay ?: today.plusDays(3).toEpochDay()) * 86_400_000L
val datePickerState = rememberDatePickerState(initialSelectedDateMillis = initialMillis)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
datePickerState.selectedDateMillis?.let { millis ->
expirationEpochDay = Instant.ofEpochMilli(millis)
.atZone(ZoneOffset.UTC)
.toLocalDate()
.toEpochDay()
hasManualExpiration = true
}
showDatePicker = false
}
) {
Text("Valider")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
}
}
} }
@@ -20,12 +20,15 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.DeleteOutline import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.DocumentScanner import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Kitchen import androidx.compose.material.icons.filled.Kitchen
import androidx.compose.material.icons.filled.Remove import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.WarningAmber
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
@@ -45,29 +48,36 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.ExpirationStatus
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.StorageLocation import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategoryColorDot import com.example.ui.common.FoodCategoryColorDot
import java.time.LocalDate
import java.util.Locale import java.util.Locale
@Composable @Composable
fun InventoryTab( fun InventoryTab(
inventoryItems: List<InventoryItem>, inventoryItems: List<InventoryItem>,
alertThresholdDays: Int = 3,
onScanReceiptClick: () -> Unit, onScanReceiptClick: () -> Unit,
onAddManualClick: () -> Unit, onAddManualClick: () -> Unit,
onAdaptMenusForExpiringClick: () -> Unit = {},
onEditItem: (InventoryItem) -> Unit, onEditItem: (InventoryItem) -> Unit,
onAdjustQuantity: (itemId: String, delta: Double) -> Unit, onAdjustQuantity: (itemId: String, delta: Double) -> Unit,
onDeleteItem: (itemId: String) -> Unit onDeleteItem: (itemId: String) -> Unit
) { ) {
var searchQuery by rememberSaveable { mutableStateOf("") } var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedLocationName by rememberSaveable { mutableStateOf<String?>(null) } var selectedLocationName by rememberSaveable { mutableStateOf<String?>(null) }
var filterExpiringOnly by rememberSaveable { mutableStateOf(false) }
val today = remember { LocalDate.now() }
val selectedLocation = selectedLocationName?.let { StorageLocation.fromString(it) } val selectedLocation = selectedLocationName?.let { StorageLocation.fromString(it) }
val countsByLocation = remember(inventoryItems) { val countsByLocation = remember(inventoryItems) {
@@ -76,15 +86,40 @@ fun InventoryTab(
} }
} }
val filteredItems = remember(inventoryItems, searchQuery, selectedLocation) { val urgentOrExpiredCount = remember(inventoryItems, alertThresholdDays, today) {
inventoryItems.count { item ->
val st = item.expirationStatus(alertThresholdDays, today)
st == ExpirationStatus.EXPIRED || st == ExpirationStatus.URGENT || st == ExpirationStatus.SOON
}
}
val expiringSoonConsumableCount = remember(inventoryItems, alertThresholdDays, today) {
inventoryItems.count { item ->
val st = item.expirationStatus(alertThresholdDays, today)
st == ExpirationStatus.URGENT || st == ExpirationStatus.SOON
}
}
val filteredItems = remember(inventoryItems, searchQuery, selectedLocation, filterExpiringOnly, alertThresholdDays, today) {
val query = searchQuery.trim().lowercase(Locale.FRENCH) val query = searchQuery.trim().lowercase(Locale.FRENCH)
inventoryItems.filter { item -> inventoryItems
.filter { item ->
val matchesLoc = selectedLocation == null || item.location == selectedLocation val matchesLoc = selectedLocation == null || item.location == selectedLocation
val matchesQuery = query.isBlank() || val matchesQuery = query.isBlank() ||
item.name.lowercase(Locale.FRENCH).contains(query) || item.name.lowercase(Locale.FRENCH).contains(query) ||
item.category.displayName.lowercase(Locale.FRENCH).contains(query) item.category.displayName.lowercase(Locale.FRENCH).contains(query)
matchesLoc && matchesQuery val status = item.expirationStatus(alertThresholdDays, today)
val matchesExp = !filterExpiringOnly ||
status == ExpirationStatus.EXPIRED ||
status == ExpirationStatus.URGENT ||
status == ExpirationStatus.SOON
matchesLoc && matchesQuery && matchesExp
} }
.sortedWith(
compareBy<InventoryItem> { it.expirationStatus(alertThresholdDays, today).ordinal }
.thenBy { it.expirationDateEpochDay ?: Long.MAX_VALUE }
.thenBy { it.name.lowercase(Locale.FRENCH) }
)
} }
LazyColumn( LazyColumn(
@@ -199,7 +234,64 @@ fun InventoryTab(
) )
} }
// Location filter chips // Expiring soon quick alert banner
if (expiringSoonConsumableCount > 0) {
item {
Card(
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.45f)
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.35f)),
modifier = Modifier
.fillMaxWidth()
.testTag("inventory_expiring_banner")
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Icon(
imageVector = Icons.Default.WarningAmber,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(22.dp)
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = "$expiringSoonConsumableCount aliment${if (expiringSoonConsumableCount > 1) "s" else ""} à consommer bientôt",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onErrorContainer
)
Text(
text = "Adaptez vos prochains menus pour éviter le gaspillage",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.85f)
)
}
FilledTonalButton(
onClick = onAdaptMenusForExpiringClick,
shape = RoundedCornerShape(10.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text("Menus", maxLines = 1)
}
}
}
}
}
// Location & expiration filter chips
item { item {
LazyRow( LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -207,12 +299,32 @@ fun InventoryTab(
) { ) {
item { item {
FilterChip( FilterChip(
selected = selectedLocation == null, selected = selectedLocation == null && !filterExpiringOnly,
onClick = { selectedLocationName = null }, onClick = {
selectedLocationName = null
filterExpiringOnly = false
},
label = { Text("Tous (${inventoryItems.size})") }, label = { Text("Tous (${inventoryItems.size})") },
modifier = Modifier.testTag("inventory_filter_all") modifier = Modifier.testTag("inventory_filter_all")
) )
} }
if (urgentOrExpiredCount > 0) {
item {
FilterChip(
selected = filterExpiringOnly,
onClick = { filterExpiringOnly = !filterExpiringOnly },
leadingIcon = {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
label = { Text("À consommer vite ($urgentOrExpiredCount)") },
modifier = Modifier.testTag("inventory_filter_expiring")
)
}
}
items(StorageLocation.entries) { loc -> items(StorageLocation.entries) { loc ->
val count = countsByLocation[loc] ?: 0 val count = countsByLocation[loc] ?: 0
FilterChip( FilterChip(
@@ -271,6 +383,8 @@ fun InventoryTab(
items(filteredItems, key = { it.id }) { item -> items(filteredItems, key = { it.id }) { item ->
InventoryItemCard( InventoryItemCard(
item = item, item = item,
alertThresholdDays = alertThresholdDays,
today = today,
onClick = { onEditItem(item) }, onClick = { onEditItem(item) },
onStepChange = { delta -> onAdjustQuantity(item.id, delta) }, onStepChange = { delta -> onAdjustQuantity(item.id, delta) },
onDelete = { onDeleteItem(item.id) } onDelete = { onDeleteItem(item.id) }
@@ -283,6 +397,8 @@ fun InventoryTab(
@Composable @Composable
private fun InventoryItemCard( private fun InventoryItemCard(
item: InventoryItem, item: InventoryItem,
alertThresholdDays: Int,
today: LocalDate,
onClick: () -> Unit, onClick: () -> Unit,
onStepChange: (Double) -> Unit, onStepChange: (Double) -> Unit,
onDelete: () -> Unit onDelete: () -> Unit
@@ -292,11 +408,19 @@ private fun InventoryItemCard(
FoodUnit.ML -> 100.0 FoodUnit.ML -> 100.0
FoodUnit.PORTION -> 1.0 FoodUnit.PORTION -> 1.0
} }
val expStatus = item.expirationStatus(alertThresholdDays, today)
val expBadge = item.formatExpirationBadge(today)
val borderColor = when (expStatus) {
ExpirationStatus.EXPIRED -> MaterialTheme.colorScheme.error.copy(alpha = 0.65f)
ExpirationStatus.URGENT -> Color(0xFFD84315).copy(alpha = 0.55f)
ExpirationStatus.SOON -> Color(0xFFEF6C00).copy(alpha = 0.45f)
else -> MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
}
Card( Card(
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)), border = BorderStroke(1.dp, borderColor),
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.clickable(onClick = onClick) .clickable(onClick = onClick)
@@ -341,6 +465,27 @@ private fun InventoryItemCard(
overflow = TextOverflow.Ellipsis overflow = TextOverflow.Ellipsis
) )
} }
if (expBadge != null) {
Spacer(modifier = Modifier.height(4.dp))
val (badgeBg, badgeFg) = when (expStatus) {
ExpirationStatus.EXPIRED -> MaterialTheme.colorScheme.errorContainer to MaterialTheme.colorScheme.onErrorContainer
ExpirationStatus.URGENT -> Color(0xFFFFE0B2) to Color(0xFFBF360C)
ExpirationStatus.SOON -> Color(0xFFFFF3E0) to Color(0xFFE65100)
else -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
}
Surface(
shape = RoundedCornerShape(8.dp),
color = badgeBg
) {
Text(
text = expBadge,
style = MaterialTheme.typography.labelSmall,
fontWeight = FontWeight.SemiBold,
color = badgeFg,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
}
} }
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
@@ -60,6 +60,7 @@ import com.example.data.model.FoodCategory
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.MealType import com.example.data.model.MealType
import com.example.data.model.MenuAdaptationUiState
import com.example.data.model.PlannedMealEntry import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictionMealScope import com.example.data.model.PredictionMealScope
import com.example.data.model.ReceiptScanUiState import com.example.data.model.ReceiptScanUiState
@@ -89,6 +90,9 @@ fun PlanningScreen(
customFoods: List<CustomFoodEntry>, customFoods: List<CustomFoodEntry>,
receiptScanState: ReceiptScanUiState, receiptScanState: ReceiptScanUiState,
weekPredictionState: WeekPredictionUiState, weekPredictionState: WeekPredictionUiState,
expiringSoonItems: List<InventoryItem> = emptyList(),
expirationAlertDays: Int = 3,
menuAdaptationState: MenuAdaptationUiState = MenuAdaptationUiState.Idle,
onPreviousWeek: () -> Unit, onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit, onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit, onGoToCurrentWeek: () -> Unit,
@@ -110,6 +114,10 @@ fun PlanningScreen(
onUpdatePredictedMealServings: (String, Double) -> Unit, onUpdatePredictedMealServings: (String, Double) -> Unit,
onConfirmPredictedMeals: () -> Unit, onConfirmPredictedMeals: () -> Unit,
onDismissWeekPrediction: () -> Unit, onDismissWeekPrediction: () -> Unit,
onAdaptMenusForExpiring: () -> Unit = {},
onToggleMenuAdaptation: (String) -> Unit = {},
onConfirmMenuAdaptations: () -> Unit = {},
onDismissMenuAdaptation: () -> Unit = {},
onScanReceiptUri: (Uri) -> Unit, onScanReceiptUri: (Uri) -> Unit,
onUpdateScannedItem: (ScannedReceiptItem) -> Unit, onUpdateScannedItem: (ScannedReceiptItem) -> Unit,
onRemoveScannedItem: (String) -> Unit, onRemoveScannedItem: (String) -> Unit,
@@ -299,10 +307,12 @@ fun PlanningScreen(
plannedMeals = plannedMeals, plannedMeals = plannedMeals,
recipesById = recipesById, recipesById = recipesById,
customFoods = customFoods, customFoods = customFoods,
expiringSoonItems = expiringSoonItems,
onPreviousWeek = onPreviousWeek, onPreviousWeek = onPreviousWeek,
onNextWeek = onNextWeek, onNextWeek = onNextWeek,
onGoToCurrentWeek = onGoToCurrentWeek, onGoToCurrentWeek = onGoToCurrentWeek,
onPredictWeekClick = { showPredictWeekSheet = true }, onPredictWeekClick = { showPredictWeekSheet = true },
onAdaptMenusForExpiringClick = onAdaptMenusForExpiring,
onPlanMealClick = { date, mealType -> onPlanMealClick = { date, mealType ->
editingPlannedMeal = null editingPlannedMeal = null
planTargetDate = date planTargetDate = date
@@ -321,11 +331,13 @@ fun PlanningScreen(
PlanningSubTab.STOCK -> { PlanningSubTab.STOCK -> {
InventoryTab( InventoryTab(
inventoryItems = inventoryItems, inventoryItems = inventoryItems,
alertThresholdDays = expirationAlertDays,
onScanReceiptClick = { showReceiptSourceDialog = true }, onScanReceiptClick = { showReceiptSourceDialog = true },
onAddManualClick = { onAddManualClick = {
editingInventoryItem = null editingInventoryItem = null
showInventoryEditor = true showInventoryEditor = true
}, },
onAdaptMenusForExpiringClick = onAdaptMenusForExpiring,
onEditItem = { item -> onEditItem = { item ->
editingInventoryItem = item editingInventoryItem = item
showInventoryEditor = true showInventoryEditor = true
@@ -516,6 +528,15 @@ fun PlanningScreen(
) )
} }
// AI Expiring-Stock Menu Adaptation Sheet
AdaptMenusForExpiringSheet(
adaptationState = menuAdaptationState,
onToggleProposal = onToggleMenuAdaptation,
onConfirm = onConfirmMenuAdaptations,
onRetry = onAdaptMenusForExpiring,
onDismiss = onDismissMenuAdaptation
)
// Fullscreen In-Store Shopping Mode // Fullscreen In-Store Shopping Mode
if (showShoppingMode) { if (showShoppingMode) {
ShoppingModeScreen( ShoppingModeScreen(
@@ -5,6 +5,8 @@ import android.net.Uri
import androidx.lifecycle.AndroidViewModel 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.ExpirationDefaults
import com.example.data.model.ExpirationStatus
import com.example.data.model.FoodCategory import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
@@ -13,6 +15,8 @@ import com.example.data.model.ManualShoppingItem
import com.example.data.model.MealEntry 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.MealType
import com.example.data.model.MenuAdaptationProposal
import com.example.data.model.MenuAdaptationUiState
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
@@ -67,12 +71,35 @@ internal fun interface WeekSlotPredictor {
): Result<List<PredictedMealProposal>> ): Result<List<PredictedMealProposal>>
} }
internal fun interface ExpiringMenuAdapter {
suspend fun adaptMenusForExpiringItems(
expiringItems: List<InventoryItem>,
candidateSlots: List<Pair<LocalDate, MealType>>,
existingMealsBySlot: Map<Pair<LocalDate, MealType>, PlannedMealEntry>,
allInventory: List<InventoryItem>,
recipes: List<RecipeEntry>,
preferences: List<FoodPreferenceEntry>,
defaultServings: Double
): Result<List<MenuAdaptationProposal>>
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
class PlanningViewModel internal constructor( class PlanningViewModel internal constructor(
application: Application, application: Application,
private val repository: MealRepository, private val repository: MealRepository,
private val planningPrefs: PlanningPreferencesManager, private val planningPrefs: PlanningPreferencesManager,
private val weekSlotPredictor: WeekSlotPredictor private val weekSlotPredictor: WeekSlotPredictor,
private val expiringMenuAdapter: ExpiringMenuAdapter = ExpiringMenuAdapter { expiringItems, candidateSlots, existingMealsBySlot, allInventory, recipes, preferences, defaultServings ->
WeeklyMealPredictor().adaptMenusForExpiringItems(
expiringItems = expiringItems,
candidateSlots = candidateSlots,
existingMealsBySlot = existingMealsBySlot,
allInventory = allInventory,
recipes = recipes,
preferences = preferences,
defaultServings = defaultServings
)
}
) : AndroidViewModel(application) { ) : AndroidViewModel(application) {
constructor(application: Application) : this( constructor(application: Application) : this(
@@ -106,6 +133,7 @@ class PlanningViewModel internal constructor(
private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() } private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
private val checkedKeysMutex = Mutex() private val checkedKeysMutex = Mutex()
private var predictionJob: Job? = null private var predictionJob: Job? = null
private var adaptationJob: 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()
@@ -188,9 +216,36 @@ class PlanningViewModel internal constructor(
private val _weekPredictionState = MutableStateFlow<WeekPredictionUiState>(WeekPredictionUiState.Idle) private val _weekPredictionState = MutableStateFlow<WeekPredictionUiState>(WeekPredictionUiState.Idle)
val weekPredictionState: StateFlow<WeekPredictionUiState> = _weekPredictionState.asStateFlow() val weekPredictionState: StateFlow<WeekPredictionUiState> = _weekPredictionState.asStateFlow()
private val _menuAdaptationState = MutableStateFlow<MenuAdaptationUiState>(MenuAdaptationUiState.Idle)
val menuAdaptationState: StateFlow<MenuAdaptationUiState> = _menuAdaptationState.asStateFlow()
private val _expirationAlertDays = MutableStateFlow(planningPrefs.getExpirationAlertDays())
val expirationAlertDays: StateFlow<Int> = _expirationAlertDays.asStateFlow()
val expiringSoonItems: StateFlow<List<InventoryItem>> = combine(
inventoryItems,
_expirationAlertDays
) { items, threshold ->
val today = LocalDate.now()
items.filter { item ->
val status = item.expirationStatus(alertThresholdDays = threshold, today = today)
status == ExpirationStatus.URGENT || status == ExpirationStatus.SOON
}.sortedBy { it.expirationDateEpochDay ?: Long.MAX_VALUE }
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = emptyList()
)
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()
fun updateExpirationAlertDays(days: Int) {
val clamped = days.coerceIn(1, 7)
planningPrefs.setExpirationAlertDays(clamped)
_expirationAlertDays.value = clamped
}
private suspend fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) { private suspend fun updateCheckedPlanKeys(transform: (Set<String>) -> Set<String>) {
checkedKeysMutex.withLock { checkedKeysMutex.withLock {
val updated = _checkedPlanKeys.updateAndGet(transform) val updated = _checkedPlanKeys.updateAndGet(transform)
@@ -302,7 +357,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = item.quantity, quantityToAdd = item.quantity,
unit = item.unit, unit = item.unit,
category = item.category, category = item.category,
location = item.location location = item.location,
expirationDateEpochDay = item.expirationDateEpochDay
) )
} else { } else {
repository.upsertInventoryItem(item) repository.upsertInventoryItem(item)
@@ -381,7 +437,8 @@ class PlanningViewModel internal constructor(
item: ShoppingListItem, item: ShoppingListItem,
quantity: Double, quantity: Double,
unit: FoodUnit, unit: FoodUnit,
location: StorageLocation location: StorageLocation,
expirationDateEpochDay: Long? = ExpirationDefaults.suggestedExpirationEpochDay(item.category, location)
) { ) {
viewModelScope.launch { viewModelScope.launch {
val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0 val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0
@@ -390,7 +447,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = safeQty, quantityToAdd = safeQty,
unit = unit, unit = unit,
category = item.category, category = item.category,
location = location location = location,
expirationDateEpochDay = expirationDateEpochDay
).fold( ).fold(
onSuccess = { onSuccess = {
if (item.manualItemId != null) { if (item.manualItemId != null) {
@@ -432,7 +490,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = qtyToAdd, quantityToAdd = qtyToAdd,
unit = item.unit, unit = item.unit,
category = item.category, category = item.category,
location = location location = location,
expirationDateEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(item.category, location)
) )
if (result.isSuccess) { if (result.isSuccess) {
addedCount++ addedCount++
@@ -635,6 +694,148 @@ class PlanningViewModel internal constructor(
_weekPredictionState.value = WeekPredictionUiState.Idle _weekPredictionState.value = WeekPredictionUiState.Idle
} }
// ------------------------------------------------------------------------
// Expiring-Stock Menu Adaptation (Firebase AI Logic)
// ------------------------------------------------------------------------
fun adaptMenusForExpiringItems(defaultServings: Double = 2.0) {
adaptationJob?.cancel()
adaptationJob = viewModelScope.launch {
val today = LocalDate.now()
val threshold = _expirationAlertDays.value
val allInventory = repository.getInventorySnapshot()
val expiring = allInventory
.filter { item ->
val status = item.expirationStatus(alertThresholdDays = threshold, today = today)
status == ExpirationStatus.URGENT || status == ExpirationStatus.SOON
}
.sortedBy { it.expirationDateEpochDay ?: Long.MAX_VALUE }
if (expiring.isEmpty()) {
_menuAdaptationState.value = MenuAdaptationUiState.Error(
"Aucun aliment proche de sa date de péremption à écouler pour le moment."
)
return@launch
}
_menuAdaptationState.value = MenuAdaptationUiState.Loading
val maxExpDay = expiring.mapNotNull { it.expirationDateEpochDay }.maxOrNull()
?: today.plusDays(threshold.toLong()).toEpochDay()
val windowEndEpoch = maxOf(today.plusDays(2).toEpochDay(), minOf(maxExpDay, today.plusDays(6).toEpochDay()))
val existingUpcoming = weekPlannedMeals.value.filter {
it.dateEpochDay in today.toEpochDay()..windowEndEpoch
}
val consumedSlots = existingUpcoming
.filter { it.isConsumed }
.map { LocalDate.ofEpochDay(it.dateEpochDay) to it.mealType }
.toSet()
val existingBySlot = existingUpcoming
.filterNot { it.isConsumed }
.associateBy { LocalDate.ofEpochDay(it.dateEpochDay) to it.mealType }
val candidateSlots = mutableListOf<Pair<LocalDate, MealType>>()
var cursor = today
val endDate = LocalDate.ofEpochDay(windowEndEpoch)
while (!cursor.isAfter(endDate)) {
listOf(MealType.LUNCH, MealType.DINNER).forEach { mealType ->
val slot = cursor to mealType
if (slot !in consumedSlots) {
candidateSlots.add(slot)
}
}
cursor = cursor.plusDays(1)
}
if (candidateSlots.isEmpty()) {
_menuAdaptationState.value = MenuAdaptationUiState.Error(
"Tous les repas jusqu'à la date limite sont déjà marqués comme consommés."
)
return@launch
}
val recipes = repository.getAllRecipesSnapshot()
val preferences = repository.getAllFoodPreferencesSnapshot().map { it.toDomain() }
val result = expiringMenuAdapter.adaptMenusForExpiringItems(
expiringItems = expiring,
candidateSlots = candidateSlots,
existingMealsBySlot = existingBySlot,
allInventory = allInventory,
recipes = recipes,
preferences = preferences,
defaultServings = defaultServings
)
result.fold(
onSuccess = { proposals ->
_menuAdaptationState.value = MenuAdaptationUiState.Preview(
proposals = proposals,
expiringItems = expiring
)
},
onFailure = { error ->
_menuAdaptationState.value = MenuAdaptationUiState.Error(
error.message ?: "Impossible d'adapter les menus pour le moment."
)
}
)
}
}
fun toggleMenuAdaptation(proposalId: String) {
_menuAdaptationState.update { state ->
if (state is MenuAdaptationUiState.Preview) {
state.copy(
proposals = state.proposals.map { proposal ->
if (proposal.id == proposalId) proposal.copy(selected = !proposal.selected) else proposal
}
)
} else {
state
}
}
}
fun confirmMenuAdaptations() {
val preview = _menuAdaptationState.value as? MenuAdaptationUiState.Preview ?: return
val selected = preview.proposals.filter { it.selected }
if (selected.isEmpty()) {
emitSnackbar("Sélectionnez au moins une adaptation à appliquer")
return
}
viewModelScope.launch {
var savedCount = 0
val failed = mutableListOf<MenuAdaptationProposal>()
selected.forEach { proposal ->
val result = repository.upsertPlannedMeal(proposal.toPlannedMealEntry())
if (result.isSuccess) {
savedCount++
} else {
failed.add(proposal)
}
}
if (failed.isEmpty()) {
_menuAdaptationState.value = MenuAdaptationUiState.Idle
emitSnackbar(
"$savedCount menu${if (savedCount > 1) "s" else ""} adapté${if (savedCount > 1) "s" else ""} pour vos produits à consommer"
)
} else {
_menuAdaptationState.value = preview.copy(proposals = failed)
emitSnackbar("Certains changements n'ont pas pu être enregistrés (${failed.size} en échec)")
}
}
}
fun dismissMenuAdaptation() {
adaptationJob?.cancel()
adaptationJob = null
_menuAdaptationState.value = MenuAdaptationUiState.Idle
}
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Receipt Scanning (Firebase AI Logic Multimodal) // Receipt Scanning (Firebase AI Logic Multimodal)
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@@ -728,7 +929,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = scanned.quantity, quantityToAdd = scanned.quantity,
unit = scanned.unit, unit = scanned.unit,
category = scanned.category, category = scanned.category,
location = scanned.location location = scanned.location,
expirationDateEpochDay = scanned.expirationDateEpochDay
) )
} }
@@ -20,13 +20,18 @@ 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.automirrored.filled.ReceiptLong
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close
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.material3.AssistChip
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
import androidx.compose.material3.Checkbox import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -39,6 +44,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -58,6 +64,11 @@ import com.example.data.model.ReceiptScanUiState
import com.example.data.model.ScannedReceiptItem import com.example.data.model.ScannedReceiptItem
import com.example.data.model.StorageLocation import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategorySelectorRow import com.example.ui.common.FoodCategorySelectorRow
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -279,6 +290,7 @@ fun ReceiptReviewSheet(
} }
} }
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun ScannedItemReviewCard( private fun ScannedItemReviewCard(
item: ScannedReceiptItem, item: ScannedReceiptItem,
@@ -290,6 +302,9 @@ private fun ScannedItemReviewCard(
if (item.quantity % 1.0 == 0.0) item.quantity.toInt().toString() else item.quantity.toString() if (item.quantity % 1.0 == 0.0) item.quantity.toInt().toString() else item.quantity.toString()
) )
} }
var showDatePicker by remember { mutableStateOf(false) }
val today = remember { LocalDate.now() }
val dateFmt = remember { DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) }
Card( Card(
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
@@ -402,6 +417,84 @@ private fun ScannedItemReviewCard(
selectedCategory = item.category, selectedCategory = item.category,
onCategorySelected = { cat -> onUpdate(item.copy(category = cat)) } onCategorySelected = { cat -> onUpdate(item.copy(category = cat)) }
) )
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically
) {
AssistChip(
onClick = { showDatePicker = true },
leadingIcon = {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
},
label = {
Text(
text = item.expirationDateEpochDay?.let {
"DLC : ${LocalDate.ofEpochDay(it).format(dateFmt)}"
} ?: "DLC : aucune",
maxLines = 1
)
}
)
FilterChip(
selected = item.expirationDateEpochDay == today.plusDays(3).toEpochDay(),
onClick = { onUpdate(item.copy(expirationDateEpochDay = today.plusDays(3).toEpochDay())) },
label = { Text("+3 j") }
)
FilterChip(
selected = item.expirationDateEpochDay == today.plusDays(7).toEpochDay(),
onClick = { onUpdate(item.copy(expirationDateEpochDay = today.plusDays(7).toEpochDay())) },
label = { Text("+7 j") }
)
if (item.expirationDateEpochDay != null) {
IconButton(
onClick = { onUpdate(item.copy(expirationDateEpochDay = null)) },
modifier = Modifier.size(32.dp)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer la DLC",
modifier = Modifier.size(16.dp)
)
}
}
}
}
}
if (showDatePicker) {
val initialMillis = (item.expirationDateEpochDay ?: today.plusDays(5).toEpochDay()) * 86_400_000L
val datePickerState = rememberDatePickerState(initialSelectedDateMillis = initialMillis)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
datePickerState.selectedDateMillis?.let { millis ->
val pickedEpoch = Instant.ofEpochMilli(millis)
.atZone(ZoneOffset.UTC)
.toLocalDate()
.toEpochDay()
onUpdate(item.copy(expirationDateEpochDay = pickedEpoch))
}
showDatePicker = false
}
) {
Text("Valider")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
} }
} }
} }
@@ -25,6 +25,7 @@ import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Today import androidx.compose.material.icons.filled.Today
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.AssistChip import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.Card import androidx.compose.material3.Card
@@ -47,6 +48,7 @@ import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.InventoryItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry import com.example.data.model.PlannedMealEntry
import com.example.data.model.RecipeEntry import com.example.data.model.RecipeEntry
@@ -61,10 +63,12 @@ fun WeeklyPlanTab(
plannedMeals: List<PlannedMealEntry>, plannedMeals: List<PlannedMealEntry>,
recipesById: Map<String, RecipeEntry>, recipesById: Map<String, RecipeEntry>,
customFoods: List<CustomFoodEntry>, customFoods: List<CustomFoodEntry>,
expiringSoonItems: List<InventoryItem> = emptyList(),
onPreviousWeek: () -> Unit, onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit, onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit, onGoToCurrentWeek: () -> Unit,
onPredictWeekClick: () -> Unit, onPredictWeekClick: () -> Unit,
onAdaptMenusForExpiringClick: () -> Unit = {},
onPlanMealClick: (date: LocalDate, mealType: MealType) -> Unit, onPlanMealClick: (date: LocalDate, mealType: MealType) -> Unit,
onEditPlannedMeal: (PlannedMealEntry) -> Unit, onEditPlannedMeal: (PlannedMealEntry) -> Unit,
onDeletePlannedMeal: (String) -> Unit, onDeletePlannedMeal: (String) -> Unit,
@@ -197,6 +201,73 @@ fun WeeklyPlanTab(
} }
} }
// Expiring soon items banner with one-tap AI menu adaptation
if (expiringSoonItems.isNotEmpty()) {
item {
val summary = expiringSoonItems.take(4).joinToString(", ") { item ->
val badge = item.formatExpirationBadge(today)
if (badge != null) "${item.name} ($badge)" else item.name
}
val extra = if (expiringSoonItems.size > 4) " +${expiringSoonItems.size - 4}" else ""
Card(
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.45f)
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error.copy(alpha = 0.35f)),
modifier = Modifier
.fillMaxWidth()
.testTag("weekly_expiring_alert_banner")
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(14.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.WarningAmber,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(20.dp)
)
Text(
text = "${expiringSoonItems.size} aliment${if (expiringSoonItems.size > 1) "s" else ""} à consommer bientôt",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onErrorContainer
)
}
Text(
text = "$summary$extra",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.9f)
)
FilledTonalButton(
onClick = onAdaptMenusForExpiringClick,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("adapt_menus_expiring_button")
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Adapter mes menus (IA)")
}
}
}
}
}
// 7 Day Cards // 7 Day Cards
items(weekDays, key = { it.toEpochDay() }) { day -> items(weekDays, key = { it.toEpochDay() }) { day ->
val isToday = day == today val isToday = day == today
@@ -21,6 +21,7 @@ import com.example.ui.journal.GoogleSheetsUiState
import com.example.ui.settings.components.AccountAndSecuritySection import com.example.ui.settings.components.AccountAndSecuritySection
import com.example.ui.settings.components.AppearanceThemeSection import com.example.ui.settings.components.AppearanceThemeSection
import com.example.ui.settings.components.DataExportImportSection import com.example.ui.settings.components.DataExportImportSection
import com.example.ui.settings.components.ExpirationAlertsSettingsSection
import com.example.ui.settings.components.GoogleSheetsIntegrationSection import com.example.ui.settings.components.GoogleSheetsIntegrationSection
import com.example.ui.settings.components.NotificationRemindersSection import com.example.ui.settings.components.NotificationRemindersSection
import com.example.ui.theme.AppThemeMode import com.example.ui.theme.AppThemeMode
@@ -37,6 +38,8 @@ fun SettingsScreen(
onThemeModeChange: (AppThemeMode) -> Unit, onThemeModeChange: (AppThemeMode) -> Unit,
onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit, onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit,
onTestNotification: (MealType) -> Unit, onTestNotification: (MealType) -> Unit,
expirationAlertDays: Int = 3,
onExpirationAlertDaysChange: (Int) -> Unit = {},
onSaveCsvClick: () -> Unit, onSaveCsvClick: () -> Unit,
onShareCsvClick: () -> Unit, onShareCsvClick: () -> Unit,
onImportCsvClick: () -> Unit, onImportCsvClick: () -> Unit,
@@ -115,6 +118,14 @@ fun SettingsScreen(
) )
} }
// 4b. Expiration Alerts
item {
ExpirationAlertsSettingsSection(
alertThresholdDays = expirationAlertDays,
onAlertThresholdDaysChange = onExpirationAlertDaysChange
)
}
// 5. Theme Selector // 5. Theme Selector
item { item {
AppearanceThemeSection( AppearanceThemeSection(
@@ -0,0 +1,187 @@
package com.example.ui.settings.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.preferences.PlanningPreferencesManager
import com.example.notification.MealNotificationManager
@Composable
fun ExpirationAlertsSettingsSection(
alertThresholdDays: Int,
onAlertThresholdDaysChange: (Int) -> Unit,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val prefs = remember { PlanningPreferencesManager.getInstance(context) }
var notifEnabled by remember { mutableStateOf(prefs.isExpirationNotifEnabled()) }
var notifHour by remember { mutableStateOf(prefs.getExpirationNotifTime().first) }
Card(
modifier = modifier
.fillMaxWidth()
.testTag("settings_expiration_alerts_card"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
)
) {
Column(
modifier = Modifier.padding(20.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Surface(
modifier = Modifier.size(40.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.secondaryContainer
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.size(22.dp)
)
}
}
Spacer(modifier = Modifier.width(12.dp))
Column {
Text(
text = "Alertes de péremption",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Anticipez les dates limites pour adapter vos menus",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Prévenir à l'avance",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
listOf(1, 2, 3, 5, 7).forEach { days ->
FilterChip(
selected = alertThresholdDays == days,
onClick = { onAlertThresholdDaysChange(days) },
label = { Text("${days}j") },
modifier = Modifier
.weight(1f)
.testTag("expiration_threshold_${days}d")
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Notification quotidienne",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
Text(
text = "Envoyée uniquement si un aliment approche de sa DLC",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch(
checked = notifEnabled,
onCheckedChange = { enabled ->
notifEnabled = enabled
prefs.setExpirationNotifEnabled(enabled)
MealNotificationManager.scheduleExpirationDailyCheck(
context = context,
hour = notifHour,
minute = 0,
enabled = enabled
)
},
modifier = Modifier.testTag("expiration_notif_switch")
)
}
if (notifEnabled) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Heure de vérification",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(6.dp)
) {
listOf(8, 9, 11, 18).forEach { hour ->
FilterChip(
selected = notifHour == hour,
onClick = {
notifHour = hour
prefs.setExpirationNotifTime(hour, 0)
MealNotificationManager.scheduleExpirationDailyCheck(
context = context,
hour = hour,
minute = 0,
enabled = true
)
},
label = { Text("${hour}h") },
modifier = Modifier.weight(1f)
)
}
}
}
}
}
}
}
@@ -0,0 +1,229 @@
package com.example
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.example.data.model.ExpirationDefaults
import com.example.data.model.ExpirationStatus
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry
import com.example.data.model.StorageLocation
import com.example.data.preferences.PlanningPreferencesManager
import com.example.domain.ReceiptScannerAnalyzer
import com.example.domain.ShoppingListCalculator
import com.example.domain.WeeklyMealPredictor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.time.LocalDate
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [36])
class ExpirationAndAdaptationTest {
private val today = LocalDate.of(2026, 11, 28)
@Test
fun inventoryItem_expirationStatusAndBadges_coverAllStates() {
val expired = InventoryItem(
id = "1",
name = "Yaourt",
quantity = 2.0,
unit = FoodUnit.PORTION,
expirationDateEpochDay = today.minusDays(2).toEpochDay()
)
val urgentToday = expired.copy(id = "2", expirationDateEpochDay = today.toEpochDay())
val urgentTomorrow = expired.copy(id = "3", expirationDateEpochDay = today.plusDays(1).toEpochDay())
val soon = expired.copy(id = "4", expirationDateEpochDay = today.plusDays(3).toEpochDay())
val fresh = expired.copy(id = "5", expirationDateEpochDay = today.plusDays(10).toEpochDay())
val noDate = expired.copy(id = "6", expirationDateEpochDay = null)
assertEquals(ExpirationStatus.EXPIRED, expired.expirationStatus(3, today))
assertEquals("Périmé (2 j)", expired.formatExpirationBadge(today))
assertEquals(ExpirationStatus.URGENT, urgentToday.expirationStatus(3, today))
assertEquals("Aujourd'hui", urgentToday.formatExpirationBadge(today))
assertEquals(ExpirationStatus.URGENT, urgentTomorrow.expirationStatus(3, today))
assertEquals("Demain", urgentTomorrow.formatExpirationBadge(today))
assertEquals(ExpirationStatus.SOON, soon.expirationStatus(3, today))
assertEquals(ExpirationStatus.FRESH, soon.expirationStatus(2, today))
assertEquals("Dans 3 j", soon.formatExpirationBadge(today))
assertEquals(ExpirationStatus.FRESH, fresh.expirationStatus(3, today))
assertEquals(ExpirationStatus.NONE, noDate.expirationStatus(3, today))
assertNull(noDate.formatExpirationBadge(today))
}
@Test
fun expirationDefaults_suggestsShelfLifeForFridgeAndNullForFreezerAndDryPantry() {
assertEquals(3L, ExpirationDefaults.suggestedShelfLifeDays(FoodCategory.PROTEIN, StorageLocation.FRIDGE))
assertEquals(7L, ExpirationDefaults.suggestedShelfLifeDays(FoodCategory.DAIRY, StorageLocation.FRIDGE))
assertEquals(3L, ExpirationDefaults.suggestedShelfLifeDays(FoodCategory.BREAD, StorageLocation.PANTRY))
assertNull(ExpirationDefaults.suggestedShelfLifeDays(FoodCategory.STARCH, StorageLocation.PANTRY))
assertNull(ExpirationDefaults.suggestedShelfLifeDays(FoodCategory.PROTEIN, StorageLocation.FREEZER))
}
@Test
fun computeStockDeductionProposals_deductsFifoAcrossMultipleBatches() {
val earlyBatch = InventoryItem(
id = "milk_early",
name = "Lait",
quantity = 300.0,
unit = FoodUnit.ML,
category = FoodCategory.DAIRY,
location = StorageLocation.FRIDGE,
expirationDateEpochDay = today.plusDays(1).toEpochDay()
)
val lateBatch = InventoryItem(
id = "milk_late",
name = "Lait",
quantity = 1000.0,
unit = FoodUnit.ML,
category = FoodCategory.DAIRY,
location = StorageLocation.FRIDGE,
expirationDateEpochDay = today.plusDays(7).toEpochDay()
)
val eaten = listOf(
MealFoodItem(name = "Lait", weight = 500.0, unit = FoodUnit.ML, category = FoodCategory.DAIRY)
)
// Pass late batch first to verify FIFO sorting
val proposals = ShoppingListCalculator.computeStockDeductionProposals(
eatenItems = eaten,
inventory = listOf(lateBatch, earlyBatch)
)
assertEquals(2, proposals.size)
assertEquals("milk_early", proposals[0].inventoryItem.id)
assertEquals(300.0, proposals[0].deductAmount, 0.01)
assertEquals(0.0, proposals[0].remainingAfter, 0.01)
assertEquals("milk_late", proposals[1].inventoryItem.id)
assertEquals(200.0, proposals[1].deductAmount, 0.01)
assertEquals(800.0, proposals[1].remainingAfter, 0.01)
}
@Test
fun receiptScanner_parsesEstimatedShelfLifeDays() {
val json = """
{
"items": [
{
"rawLabel": "FILET POUL",
"name": "Blanc de poulet",
"quantity": 400,
"unit": "g",
"category": "PROTEIN",
"location": "FRIDGE",
"estimatedShelfLifeDays": 2
},
{
"rawLabel": "PATES PENNE",
"name": "Pâtes",
"quantity": 500,
"unit": "g",
"category": "STARCH",
"location": "PANTRY",
"estimatedShelfLifeDays": 0
}
]
}
""".trimIndent()
val parsed = ReceiptScannerAnalyzer.parseReceiptJson(json, today)
assertEquals(2, parsed.size)
assertEquals(today.plusDays(2).toEpochDay(), parsed[0].expirationDateEpochDay)
assertNull(parsed[1].expirationDateEpochDay)
}
@Test
fun weeklyMealPredictor_parseAdaptationJson_handlesReplacementAndEmptySlot() {
val slot0 = today to MealType.DINNER
val slot1 = today.plusDays(1) to MealType.LUNCH
val existingDinner = PlannedMealEntry(
id = "existing_dinner_1",
dateEpochDay = today.toEpochDay(),
mealType = MealType.DINNER,
customTitle = "Pâtes au pesto",
servings = 2.0
)
val json = """
{
"adaptations": [
{
"slotIndex": 0,
"recipeId": "",
"title": "Poêlée de poulet aux courgettes",
"reason": "Sauve votre poulet avant demain",
"usedExpiringNames": ["Blanc de poulet", "Courgettes"],
"ingredients": [
{"name": "Blanc de poulet", "weight": 300, "unit": "g", "category": "PROTEIN"},
{"name": "Courgettes", "weight": 250, "unit": "g", "category": "VEGETABLE"}
]
},
{
"slotIndex": 1,
"recipeId": "",
"title": "Omelette aux épinards",
"reason": "Utilise vos épinards frais",
"usedExpiringNames": ["Épinards"],
"ingredients": [
{"name": "Épinards", "weight": 150, "unit": "g", "category": "VEGETABLE"}
]
}
]
}
""".trimIndent()
val proposals = WeeklyMealPredictor.parseAdaptationJson(
jsonString = json,
candidateSlots = listOf(slot0, slot1),
existingMealsBySlot = mapOf(slot0 to existingDinner),
recipesById = emptyMap(),
defaultServings = 2.0
)
assertEquals(2, proposals.size)
// Slot 0 replaces existing meal preserving its ID
assertEquals("existing_dinner_1", proposals[0].existingPlannedMealId)
assertEquals("Pâtes au pesto", proposals[0].existingMealTitle)
assertEquals("existing_dinner_1", proposals[0].toPlannedMealEntry().id)
assertEquals(listOf("Blanc de poulet", "Courgettes"), proposals[0].usedExpiringNames)
// Slot 1 fills empty slot
assertNull(proposals[1].existingPlannedMealId)
assertTrue(proposals[1].toPlannedMealEntry().id.isBlank())
}
@Test
fun planningPreferences_persistsAndClampsExpirationSettings() {
val context = ApplicationProvider.getApplicationContext<Context>()
val prefs = PlanningPreferencesManager(context)
prefs.setExpirationAlertDays(10)
assertEquals(7, prefs.getExpirationAlertDays())
prefs.setExpirationAlertDays(0)
assertEquals(1, prefs.getExpirationAlertDays())
prefs.setExpirationAlertDays(5)
assertEquals(5, prefs.getExpirationAlertDays())
prefs.setExpirationNotifEnabled(false)
assertEquals(false, prefs.isExpirationNotifEnabled())
prefs.setExpirationNotifTime(18, 30)
assertEquals(18 to 30, prefs.getExpirationNotifTime())
}
}
@@ -79,12 +79,13 @@ class PlanningViewModelTest {
quantityToAdd: Double, quantityToAdd: Double,
unit: FoodUnit, unit: FoodUnit,
category: FoodCategory, category: FoodCategory,
location: StorageLocation location: StorageLocation,
expirationDateEpochDay: Long?
): Result<String> { ): Result<String> {
return if (name.contains("Échec")) { return if (name.contains("Échec")) {
Result.failure(IllegalStateException("Simulated stock write error")) Result.failure(IllegalStateException("Simulated stock write error"))
} else { } else {
super.addOrMergeInventoryItem(name, quantityToAdd, unit, category, location) super.addOrMergeInventoryItem(name, quantityToAdd, unit, category, location, expirationDateEpochDay)
} }
} }
} }