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
+2253 -54

No files matched your search

@@ -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.verticalScroll
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.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
@@ -25,6 +30,8 @@ import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
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.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.example.data.model.ExpirationDefaults
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.StorageLocation
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)
@Composable
@@ -70,6 +83,23 @@ fun InventoryItemEditorSheet(
var selectedLocation by remember(initialItem) {
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 canSave = name.isNotBlank() && parsedQty != null && parsedQty > 0.0
@@ -99,7 +129,11 @@ fun InventoryItemEditorSheet(
onValueChange = { updated ->
name = updated
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") },
@@ -153,7 +187,12 @@ fun InventoryItemEditorSheet(
StorageLocation.entries.forEach { loc ->
FilterChip(
selected = selectedLocation == loc,
onClick = { selectedLocation = loc },
onClick = {
selectedLocation = loc
if (!hasManualExpiration) {
expirationEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(selectedCategory, loc, today)
}
},
label = { Text(loc.displayName) },
modifier = Modifier
.weight(1f)
@@ -174,10 +213,75 @@ fun InventoryItemEditorSheet(
onCategorySelected = { cat ->
selectedCategory = cat
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))
Row(
@@ -209,7 +313,8 @@ fun InventoryItemEditorSheet(
quantity = qty,
unit = selectedUnit,
category = selectedCategory,
location = selectedLocation
location = selectedLocation,
expirationDateEpochDay = expirationEpochDay
)
)
},
@@ -226,4 +331,35 @@ fun InventoryItemEditorSheet(
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.material.icons.Icons
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.DeleteOutline
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Kitchen
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.WarningAmber
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
@@ -45,29 +48,36 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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.TextOverflow
import androidx.compose.ui.unit.dp
import com.example.data.model.ExpirationStatus
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.StorageLocation
import com.example.ui.common.FoodCategoryColorDot
import java.time.LocalDate
import java.util.Locale
@Composable
fun InventoryTab(
inventoryItems: List<InventoryItem>,
alertThresholdDays: Int = 3,
onScanReceiptClick: () -> Unit,
onAddManualClick: () -> Unit,
onAdaptMenusForExpiringClick: () -> Unit = {},
onEditItem: (InventoryItem) -> Unit,
onAdjustQuantity: (itemId: String, delta: Double) -> Unit,
onDeleteItem: (itemId: String) -> Unit
) {
var searchQuery by rememberSaveable { mutableStateOf("") }
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 countsByLocation = remember(inventoryItems) {
@@ -76,17 +86,42 @@ fun InventoryTab(
}
}
val filteredItems = remember(inventoryItems, searchQuery, selectedLocation) {
val query = searchQuery.trim().lowercase(Locale.FRENCH)
inventoryItems.filter { item ->
val matchesLoc = selectedLocation == null || item.location == selectedLocation
val matchesQuery = query.isBlank() ||
item.name.lowercase(Locale.FRENCH).contains(query) ||
item.category.displayName.lowercase(Locale.FRENCH).contains(query)
matchesLoc && matchesQuery
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)
inventoryItems
.filter { item ->
val matchesLoc = selectedLocation == null || item.location == selectedLocation
val matchesQuery = query.isBlank() ||
item.name.lowercase(Locale.FRENCH).contains(query) ||
item.category.displayName.lowercase(Locale.FRENCH).contains(query)
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(
modifier = Modifier
.fillMaxSize()
@@ -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 {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -207,12 +299,32 @@ fun InventoryTab(
) {
item {
FilterChip(
selected = selectedLocation == null,
onClick = { selectedLocationName = null },
selected = selectedLocation == null && !filterExpiringOnly,
onClick = {
selectedLocationName = null
filterExpiringOnly = false
},
label = { Text("Tous (${inventoryItems.size})") },
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 ->
val count = countsByLocation[loc] ?: 0
FilterChip(
@@ -271,6 +383,8 @@ fun InventoryTab(
items(filteredItems, key = { it.id }) { item ->
InventoryItemCard(
item = item,
alertThresholdDays = alertThresholdDays,
today = today,
onClick = { onEditItem(item) },
onStepChange = { delta -> onAdjustQuantity(item.id, delta) },
onDelete = { onDeleteItem(item.id) }
@@ -283,6 +397,8 @@ fun InventoryTab(
@Composable
private fun InventoryItemCard(
item: InventoryItem,
alertThresholdDays: Int,
today: LocalDate,
onClick: () -> Unit,
onStepChange: (Double) -> Unit,
onDelete: () -> Unit
@@ -292,11 +408,19 @@ private fun InventoryItemCard(
FoodUnit.ML -> 100.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(
shape = RoundedCornerShape(16.dp),
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
.fillMaxWidth()
.clickable(onClick = onClick)
@@ -341,6 +465,27 @@ private fun InventoryItemCard(
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) {
@@ -60,6 +60,7 @@ import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.InventoryItem
import com.example.data.model.MealType
import com.example.data.model.MenuAdaptationUiState
import com.example.data.model.PlannedMealEntry
import com.example.data.model.PredictionMealScope
import com.example.data.model.ReceiptScanUiState
@@ -89,6 +90,9 @@ fun PlanningScreen(
customFoods: List<CustomFoodEntry>,
receiptScanState: ReceiptScanUiState,
weekPredictionState: WeekPredictionUiState,
expiringSoonItems: List<InventoryItem> = emptyList(),
expirationAlertDays: Int = 3,
menuAdaptationState: MenuAdaptationUiState = MenuAdaptationUiState.Idle,
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
@@ -110,6 +114,10 @@ fun PlanningScreen(
onUpdatePredictedMealServings: (String, Double) -> Unit,
onConfirmPredictedMeals: () -> Unit,
onDismissWeekPrediction: () -> Unit,
onAdaptMenusForExpiring: () -> Unit = {},
onToggleMenuAdaptation: (String) -> Unit = {},
onConfirmMenuAdaptations: () -> Unit = {},
onDismissMenuAdaptation: () -> Unit = {},
onScanReceiptUri: (Uri) -> Unit,
onUpdateScannedItem: (ScannedReceiptItem) -> Unit,
onRemoveScannedItem: (String) -> Unit,
@@ -299,10 +307,12 @@ fun PlanningScreen(
plannedMeals = plannedMeals,
recipesById = recipesById,
customFoods = customFoods,
expiringSoonItems = expiringSoonItems,
onPreviousWeek = onPreviousWeek,
onNextWeek = onNextWeek,
onGoToCurrentWeek = onGoToCurrentWeek,
onPredictWeekClick = { showPredictWeekSheet = true },
onAdaptMenusForExpiringClick = onAdaptMenusForExpiring,
onPlanMealClick = { date, mealType ->
editingPlannedMeal = null
planTargetDate = date
@@ -321,11 +331,13 @@ fun PlanningScreen(
PlanningSubTab.STOCK -> {
InventoryTab(
inventoryItems = inventoryItems,
alertThresholdDays = expirationAlertDays,
onScanReceiptClick = { showReceiptSourceDialog = true },
onAddManualClick = {
editingInventoryItem = null
showInventoryEditor = true
},
onAdaptMenusForExpiringClick = onAdaptMenusForExpiring,
onEditItem = { item ->
editingInventoryItem = item
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
if (showShoppingMode) {
ShoppingModeScreen(
@@ -5,6 +5,8 @@ import android.net.Uri
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
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.FoodPreferenceEntry
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.MealFoodItem
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.PredictedMealProposal
import com.example.data.model.PredictionMealScope
@@ -67,12 +71,35 @@ internal fun interface WeekSlotPredictor {
): 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)
class PlanningViewModel internal constructor(
application: Application,
private val repository: MealRepository,
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) {
constructor(application: Application) : this(
@@ -106,6 +133,7 @@ class PlanningViewModel internal constructor(
private val receiptAnalyzer by lazy { ReceiptScannerAnalyzer() }
private val checkedKeysMutex = Mutex()
private var predictionJob: Job? = null
private var adaptationJob: Job? = null
private val _uiEvents = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents: Flow<UiEvent> = _uiEvents.receiveAsFlow()
@@ -188,9 +216,36 @@ class PlanningViewModel internal constructor(
private val _weekPredictionState = MutableStateFlow<WeekPredictionUiState>(WeekPredictionUiState.Idle)
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)
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>) {
checkedKeysMutex.withLock {
val updated = _checkedPlanKeys.updateAndGet(transform)
@@ -302,7 +357,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = item.quantity,
unit = item.unit,
category = item.category,
location = item.location
location = item.location,
expirationDateEpochDay = item.expirationDateEpochDay
)
} else {
repository.upsertInventoryItem(item)
@@ -381,7 +437,8 @@ class PlanningViewModel internal constructor(
item: ShoppingListItem,
quantity: Double,
unit: FoodUnit,
location: StorageLocation
location: StorageLocation,
expirationDateEpochDay: Long? = ExpirationDefaults.suggestedExpirationEpochDay(item.category, location)
) {
viewModelScope.launch {
val safeQty = quantity.takeIf { it > 0.0 } ?: 1.0
@@ -390,7 +447,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = safeQty,
unit = unit,
category = item.category,
location = location
location = location,
expirationDateEpochDay = expirationDateEpochDay
).fold(
onSuccess = {
if (item.manualItemId != null) {
@@ -432,7 +490,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = qtyToAdd,
unit = item.unit,
category = item.category,
location = location
location = location,
expirationDateEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(item.category, location)
)
if (result.isSuccess) {
addedCount++
@@ -635,6 +694,148 @@ class PlanningViewModel internal constructor(
_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)
// ------------------------------------------------------------------------
@@ -728,7 +929,8 @@ class PlanningViewModel internal constructor(
quantityToAdd = scanned.quantity,
unit = scanned.unit,
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.automirrored.filled.ReceiptLong
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.ErrorOutline
import androidx.compose.material3.AssistChip
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.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
@@ -39,6 +44,7 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
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.StorageLocation
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)
@Composable
@@ -279,6 +290,7 @@ fun ReceiptReviewSheet(
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ScannedItemReviewCard(
item: ScannedReceiptItem,
@@ -290,6 +302,9 @@ private fun ScannedItemReviewCard(
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(
shape = RoundedCornerShape(16.dp),
@@ -402,6 +417,84 @@ private fun ScannedItemReviewCard(
selectedCategory = item.category,
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.Restaurant
import androidx.compose.material.icons.filled.Today
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
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.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.InventoryItem
import com.example.data.model.MealType
import com.example.data.model.PlannedMealEntry
import com.example.data.model.RecipeEntry
@@ -61,10 +63,12 @@ fun WeeklyPlanTab(
plannedMeals: List<PlannedMealEntry>,
recipesById: Map<String, RecipeEntry>,
customFoods: List<CustomFoodEntry>,
expiringSoonItems: List<InventoryItem> = emptyList(),
onPreviousWeek: () -> Unit,
onNextWeek: () -> Unit,
onGoToCurrentWeek: () -> Unit,
onPredictWeekClick: () -> Unit,
onAdaptMenusForExpiringClick: () -> Unit = {},
onPlanMealClick: (date: LocalDate, mealType: MealType) -> Unit,
onEditPlannedMeal: (PlannedMealEntry) -> 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
items(weekDays, key = { it.toEpochDay() }) { day ->
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.AppearanceThemeSection
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.NotificationRemindersSection
import com.example.ui.theme.AppThemeMode
@@ -37,6 +38,8 @@ fun SettingsScreen(
onThemeModeChange: (AppThemeMode) -> Unit,
onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit,
onTestNotification: (MealType) -> Unit,
expirationAlertDays: Int = 3,
onExpirationAlertDaysChange: (Int) -> Unit = {},
onSaveCsvClick: () -> Unit,
onShareCsvClick: () -> Unit,
onImportCsvClick: () -> Unit,
@@ -115,6 +118,14 @@ fun SettingsScreen(
)
}
// 4b. Expiration Alerts
item {
ExpirationAlertsSettingsSection(
alertThresholdDays = expirationAlertDays,
onAlertThresholdDaysChange = onExpirationAlertDaysChange
)
}
// 5. Theme Selector
item {
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)
)
}
}
}
}
}
}
}