diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 21d97a1..4938f2f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -96,10 +96,11 @@ dependencies { implementation(platform(libs.firebase.bom)) // implementation(libs.accompanist.permissions) implementation(libs.androidx.activity.compose) - // implementation(libs.androidx.camera.camera2) - // implementation(libs.androidx.camera.core) - // implementation(libs.androidx.camera.lifecycle) - // implementation(libs.androidx.camera.view) + implementation(libs.androidx.camera.camera2) + implementation(libs.androidx.camera.core) + implementation(libs.androidx.camera.lifecycle) + implementation(libs.androidx.camera.view) + implementation(libs.mlkit.barcode.scanning) implementation(libs.androidx.compose.material.icons.core) implementation(libs.androidx.compose.material.icons.extended) implementation(libs.androidx.compose.material3) diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt index 4df2e1f..c6f0bbe 100644 --- a/app/src/main/java/com/example/MainActivity.kt +++ b/app/src/main/java/com/example/MainActivity.kt @@ -315,6 +315,8 @@ fun AppRoot( val inventoryItems by planningViewModel.inventoryItems.collectAsStateWithLifecycle() val computedShoppingList by planningViewModel.computedShoppingList.collectAsStateWithLifecycle() val receiptScanState by planningViewModel.receiptScanState.collectAsStateWithLifecycle() + val barcodeScanItems by planningViewModel.barcodeScanItems.collectAsStateWithLifecycle() + val barcodeScanFeedback by planningViewModel.barcodeScanFeedback.collectAsStateWithLifecycle() val weekPredictionState by planningViewModel.weekPredictionState.collectAsStateWithLifecycle() val expiringSoonItems by planningViewModel.expiringSoonItems.collectAsStateWithLifecycle() val expirationAlertDays by planningViewModel.expirationAlertDays.collectAsStateWithLifecycle() @@ -672,6 +674,18 @@ fun AppRoot( planningViewModel.confirmScannedReceiptImport(items, alsoCheckShopping) }, onDismissReceiptScan = { planningViewModel.dismissReceiptScan() }, + barcodeScanItems = barcodeScanItems, + barcodeScanFeedback = barcodeScanFeedback, + onBarcodeDetected = { code -> planningViewModel.onBarcodeScanned(code) }, + onAdjustBarcodePacks = { id, delta -> + planningViewModel.adjustBarcodeItemPacks(id, delta) + }, + onUpdateBarcodeItem = { item -> planningViewModel.updateBarcodeItem(item) }, + onRemoveBarcodeItem = { id -> planningViewModel.removeBarcodeItem(id) }, + onConfirmBarcodeImport = { alsoCheckShopping -> + planningViewModel.confirmBarcodeBurstImport(alsoCheckShopping) + }, + onClearBarcodeScanSession = { planningViewModel.clearBarcodeScanSession() }, onShowMessage = { msg -> viewModel.emitEvent(UiEvent.ShowSnackbar(msg)) } ) } diff --git a/app/src/main/java/com/example/data/model/MealPlanModels.kt b/app/src/main/java/com/example/data/model/MealPlanModels.kt index 5c09568..8da5dfa 100644 --- a/app/src/main/java/com/example/data/model/MealPlanModels.kt +++ b/app/src/main/java/com/example/data/model/MealPlanModels.kt @@ -226,6 +226,29 @@ data class ScannedReceiptItem( val selected: Boolean = true ) +data class ScannedBarcodeItem( + val id: String = "bc_${UUID.randomUUID().toString().take(8)}", + val barcode: String, + val name: String, + val brand: String? = null, + val unitQuantity: Double = 1.0, + val packCount: Int = 1, + val unit: FoodUnit = FoodUnit.PORTION, + val category: FoodCategory = FoodCategory.OTHER, + val location: StorageLocation = StorageLocation.PANTRY, + val expirationDateEpochDay: Long? = null, + val imageUrl: String? = null, + val isFoundInCatalog: Boolean = true, + val isLoading: Boolean = false +) { + val totalQuantity: Double + get() = unitQuantity * packCount.coerceAtLeast(1) + + fun formatTotalQuantity(): String = IngredientMatcher.formatQuantity(totalQuantity, unit) + + fun formatPackageQuantity(): String = IngredientMatcher.formatQuantity(unitQuantity, unit) +} + data class StockDeductionProposal( val inventoryItem: InventoryItem, val deductAmount: Double, diff --git a/app/src/main/java/com/example/domain/OpenFoodFactsClient.kt b/app/src/main/java/com/example/domain/OpenFoodFactsClient.kt new file mode 100644 index 0000000..d969a39 --- /dev/null +++ b/app/src/main/java/com/example/domain/OpenFoodFactsClient.kt @@ -0,0 +1,274 @@ +package com.example.domain + +import android.util.Log +import com.example.data.model.ExpirationDefaults +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.ScannedBarcodeItem +import com.example.data.model.StorageLocation +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import okhttp3.Request +import org.json.JSONArray +import org.json.JSONObject +import java.time.LocalDate +import java.util.Locale +import java.util.concurrent.TimeUnit + +/** + * Looks up packaged food products by barcode (EAN-13, EAN-8, UPC-A, etc.) + * against the public Open Food Facts v2 API. + */ +class OpenFoodFactsClient( + private val httpClient: OkHttpClient = defaultHttpClient() +) { + suspend fun lookupProduct( + barcode: String, + today: LocalDate = LocalDate.now() + ): Result = withContext(Dispatchers.IO) { + val cleanedBarcode = barcode.filter { it.isDigit() } + if (cleanedBarcode.length < 4) { + return@withContext Result.success(null) + } + + val url = "https://world.openfoodfacts.org/api/v2/product/$cleanedBarcode.json" + + "?fields=product_name,product_name_fr,generic_name_fr,brands,quantity,product_quantity,product_quantity_unit,categories_tags,image_front_small_url" + + val request = Request.Builder() + .url(url) + .header("User-Agent", USER_AGENT) + .header("Accept", "application/json") + .get() + .build() + + try { + httpClient.newCall(request).execute().use { response -> + if (response.code == 404) { + return@withContext Result.success(null) + } + if (!response.isSuccessful) { + return@withContext Result.failure( + IllegalStateException("Open Food Facts indisponible (HTTP ${response.code})") + ) + } + val body = response.body?.string().orEmpty() + if (body.isBlank()) { + return@withContext Result.success(null) + } + val parsed = parseProductJson(cleanedBarcode, body, today) + Result.success(parsed) + } + } catch (e: Exception) { + Log.w(TAG, "OpenFoodFacts lookup failed for $cleanedBarcode", e) + Result.failure(e) + } + } + + companion object { + private const val TAG = "OpenFoodFactsClient" + private const val USER_AGENT = "Satiea-Android/1.0 (https://satiea.app)" + + private fun defaultHttpClient(): OkHttpClient { + return OkHttpClient.Builder() + .connectTimeout(8, TimeUnit.SECONDS) + .readTimeout(10, TimeUnit.SECONDS) + .build() + } + + fun parseProductJson( + barcode: String, + jsonString: String, + today: LocalDate = LocalDate.now() + ): ScannedBarcodeItem? { + val root = runCatching { JSONObject(jsonString) }.getOrNull() ?: return null + val status = root.optInt("status", 0) + if (status != 1) return null + + val product = root.optJSONObject("product") ?: return null + + val rawName = listOf( + product.optString("product_name_fr", ""), + product.optString("product_name", ""), + product.optString("generic_name_fr", "") + ).firstOrNull { it.isNotBlank() }?.trim() ?: return null + + val brand = product.optString("brands", "") + .split(",") + .firstOrNull { it.isNotBlank() } + ?.trim() + ?.takeIf { it.isNotBlank() } + + val rawQuantityText = product.optString("quantity", "").trim() + val productQuantity = when { + product.has("product_quantity") && !product.isNull("product_quantity") -> { + product.optString("product_quantity", "").replace(',', '.').toDoubleOrNull() + } + else -> null + } + val productQuantityUnit = product.optString("product_quantity_unit", "").trim() + + val (parsedQty, parsedUnit) = parseQuantityAndUnit( + productQuantity = productQuantity, + productQuantityUnit = productQuantityUnit, + rawQuantityText = rawQuantityText + ) + + val categoryTags = extractStringList(product.optJSONArray("categories_tags")) + val category = inferCategory(rawName, categoryTags) + val location = inferLocation(category, categoryTags) + val expirationEpochDay = ExpirationDefaults.suggestedExpirationEpochDay(category, location, today) + val imageUrl = product.optString("image_front_small_url", "").trim().takeIf { it.isNotBlank() } + + return ScannedBarcodeItem( + barcode = barcode, + name = rawName, + brand = brand, + unitQuantity = parsedQty, + packCount = 1, + unit = parsedUnit, + category = category, + location = location, + expirationDateEpochDay = expirationEpochDay, + imageUrl = imageUrl, + isFoundInCatalog = true, + isLoading = false + ) + } + + /** + * Parses package quantity and unit into Satiea's canonical units (g, ml, portion). + * Supports multipacks like "6 x 125 g" -> (750.0, G), "4x100ml" -> (400.0, ML), + * "1,5 L" -> (1500.0, ML), "6 œufs" -> (6.0, PORTION). + */ + fun parseQuantityAndUnit( + productQuantity: Double?, + productQuantityUnit: String?, + rawQuantityText: String? + ): Pair { + // 1. Prefer structured product_quantity + product_quantity_unit when valid + if (productQuantity != null && productQuantity > 0.0 && !productQuantityUnit.isNullOrBlank()) { + convertAmountAndUnit(productQuantity, productQuantityUnit)?.let { return it } + } + + // 2. Parse raw quantity text (handles "6 x 125 g", "1.5 L", "500g", "12 pièces", etc.) + val text = rawQuantityText?.trim().orEmpty() + if (text.isNotBlank()) { + val multiPackRegex = Regex( + """(\d+)\s*[x×*]\s*(\d+(?:[.,]\d+)?)\s*(kg|g|gr|mg|l|litre|litres|dl|cl|ml)\b""", + RegexOption.IGNORE_CASE + ) + multiPackRegex.find(text)?.let { match -> + val count = match.groupValues[1].toIntOrNull() ?: 1 + val perItem = match.groupValues[2].replace(',', '.').toDoubleOrNull() + val unitStr = match.groupValues[3] + if (perItem != null && perItem > 0.0 && count > 0) { + convertAmountAndUnit(count * perItem, unitStr)?.let { return it } + } + } + + val singleUnitRegex = Regex( + """(\d+(?:[.,]\d+)?)\s*(kg|g|gr|mg|l|litre|litres|dl|cl|ml)\b""", + RegexOption.IGNORE_CASE + ) + singleUnitRegex.find(text)?.let { match -> + val amount = match.groupValues[1].replace(',', '.').toDoubleOrNull() + val unitStr = match.groupValues[2] + if (amount != null && amount > 0.0) { + convertAmountAndUnit(amount, unitStr)?.let { return it } + } + } + + val countOnlyRegex = Regex( + """(\d+)\s*(?:pi[eè]ces?|unit[eé]s?|œufs?|oeufs?|tranches?|pots?|bouteilles?|sachets?|tablettes?)""", + RegexOption.IGNORE_CASE + ) + countOnlyRegex.find(text)?.let { match -> + val count = match.groupValues[1].toDoubleOrNull() + if (count != null && count > 0.0) { + return count to FoodUnit.PORTION + } + } + } + + // 3. Fallback if productQuantity exists without unit (Open Food Facts defaults to g) + if (productQuantity != null && productQuantity > 0.0) { + return productQuantity to FoodUnit.G + } + + return 1.0 to FoodUnit.PORTION + } + + private fun convertAmountAndUnit(amount: Double, rawUnit: String): Pair? { + val normalized = rawUnit.trim().lowercase(Locale.ROOT) + return when (normalized) { + "g", "gr", "gram", "grams", "gramme", "grammes" -> amount to FoodUnit.G + "kg", "kilogram", "kilograms", "kilogramme", "kilogrammes" -> (amount * 1000.0) to FoodUnit.G + "ml", "millilitre", "millilitres", "milliliter", "milliliters" -> amount to FoodUnit.ML + "cl", "centilitre", "centilitres" -> (amount * 10.0) to FoodUnit.ML + "dl", "decilitre", "decilitres" -> (amount * 100.0) to FoodUnit.ML + "l", "litre", "litres", "liter", "liters" -> (amount * 1000.0) to FoodUnit.ML + else -> null + } + } + + fun inferCategory(name: String, categoryTags: List): FoodCategory { + val fromName = FoodCategory.inferFromName(name) + if (fromName != FoodCategory.OTHER) { + return fromName + } + + val joined = categoryTags.joinToString(" ").lowercase(Locale.ROOT) + return when { + containsAny(joined, "nuts", "almonds", "walnuts", "hazelnuts", "peanuts", "pistachios", "seeds", "nut-butters") -> + FoodCategory.NUTS + containsAny(joined, "cheeses", "fromages", "mozzarella", "camembert", "comte", "emmental", "parmesan") -> + FoodCategory.CHEESE + containsAny(joined, "yogurts", "yaourts", "dairies", "milks", "fermented-milk", "dairy-desserts", "fromages-blancs") -> + FoodCategory.DAIRY + containsAny(joined, "breads", "pains", "baguettes", "rusks", "biscottes", "tortillas", "wraps") -> + FoodCategory.BREAD + containsAny(joined, "meats", "poultry", "chicken", "beef", "pork", "fishes", "seafood", "eggs", "tofu", "charcuterie", "hams", "sausages") -> + FoodCategory.PROTEIN + containsAny(joined, "pastas", "rices", "cereals", "legumes", "lentils", "chickpeas", "potatoes", "flours", "grains", "quinoa", "couscous", "oats") -> + FoodCategory.STARCH + containsAny(joined, "vegetables", "legumes-et-derives", "salads", "soups", "tomatoes", "carrots", "mushrooms") -> + FoodCategory.VEGETABLE + containsAny(joined, "fruits", "compotes", "apples", "bananas", "berries", "citrus", "fruit-juices") -> + FoodCategory.FRUIT + containsAny(joined, "oils", "fats", "butters", "margarines", "sauces", "condiments", "dressings", "mayonnaises", "pestos", "olives") -> + FoodCategory.FAT_SEASONING + containsAny(joined, "chocolates", "biscuits", "cakes", "sweets", "candies", "jams", "honeys", "spreads", "ice-creams", "desserts", "pastries", "snacks", "sweet-snacks") -> + FoodCategory.PLEASURE + else -> FoodCategory.OTHER + } + } + + fun inferLocation(category: FoodCategory, categoryTags: List): StorageLocation { + val joined = categoryTags.joinToString(" ").lowercase(Locale.ROOT) + return when { + containsAny(joined, "frozen", "surgel", "ice-cream", "sorbet", "glaces") -> + StorageLocation.FREEZER + containsAny(joined, "canned", "conserves", "dried", "uht", "dry-", "pastas", "rices", "biscuits", "chocolates", "oils", "jams", "honeys", "cereals") -> + StorageLocation.PANTRY + containsAny(joined, "fresh", "frais", "refrigerated", "chilled", "yogurts", "yaourts", "cheeses", "fromages", "meats", "fishes", "charcuterie") -> + StorageLocation.FRIDGE + else -> StorageLocation.defaultForCategory(category) + } + } + + private fun containsAny(haystack: String, vararg needles: String): Boolean { + return needles.any { haystack.contains(it) } + } + + private fun extractStringList(array: JSONArray?): List { + if (array == null) return emptyList() + val list = ArrayList(array.length()) + for (i in 0 until array.length()) { + val item = array.optString(i, "").trim() + if (item.isNotBlank()) list.add(item) + } + return list + } + } +} diff --git a/app/src/main/java/com/example/ui/planning/BarcodeScannerScreen.kt b/app/src/main/java/com/example/ui/planning/BarcodeScannerScreen.kt new file mode 100644 index 0000000..e2af22d --- /dev/null +++ b/app/src/main/java/com/example/ui/planning/BarcodeScannerScreen.kt @@ -0,0 +1,937 @@ +package com.example.ui.planning + +import android.annotation.SuppressLint +import android.os.SystemClock +import android.util.Log +import androidx.activity.compose.BackHandler +import androidx.camera.core.Camera +import androidx.camera.core.CameraSelector +import androidx.camera.core.ImageAnalysis +import androidx.camera.core.Preview +import androidx.camera.lifecycle.ProcessCameraProvider +import androidx.camera.view.PreviewView +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.CalendarMonth +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.FlashOff +import androidx.compose.material.icons.filled.FlashOn +import androidx.compose.material.icons.filled.Keyboard +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.QrCodeScanner +import androidx.compose.material.icons.filled.Remove +import androidx.compose.material3.AlertDialog +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.FilterChip +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +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.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LocalLifecycleOwner +import coil.compose.AsyncImage +import com.example.data.model.ExpirationDefaults +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.ScannedBarcodeItem +import com.example.data.model.StorageLocation +import com.example.ui.common.FoodCategoryColorDot +import com.google.mlkit.vision.barcode.BarcodeScannerOptions +import com.google.mlkit.vision.barcode.BarcodeScanning +import com.google.mlkit.vision.barcode.common.Barcode +import com.google.mlkit.vision.common.InputImage +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.util.Locale +import java.util.concurrent.Executors + +@Composable +fun BarcodeScannerScreen( + scannedItems: List, + lastFeedback: String?, + onBarcodeDetected: (String) -> Unit, + onAdjustPacks: (itemId: String, delta: Int) -> Unit, + onUpdateItem: (ScannedBarcodeItem) -> Unit, + onRemoveItem: (itemId: String) -> Unit, + onConfirmImport: (alsoCheckShoppingList: Boolean) -> Unit, + onClearAll: () -> Unit, + onDismiss: () -> Unit +) { + val haptic = LocalHapticFeedback.current + var torchEnabled by rememberSaveable { mutableStateOf(false) } + var isScanningPaused by rememberSaveable { mutableStateOf(false) } + var alsoCheckShoppingList by rememberSaveable { mutableStateOf(true) } + var showManualBarcodeDialog by remember { mutableStateOf(false) } + var expandedItemId by remember { mutableStateOf(null) } + + val validItemsCount = remember(scannedItems) { + scannedItems.count { !it.isLoading && it.name.isNotBlank() && it.totalQuantity > 0.0 } + } + val totalPacksCount = remember(scannedItems) { + scannedItems.sumOf { it.packCount } + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties( + usePlatformDefaultWidth = false, + decorFitsSystemWindows = false + ) + ) { + BackHandler(onBack = onDismiss) + + Surface( + modifier = Modifier + .fillMaxSize() + .testTag("barcode_scanner_screen"), + color = Color.Black + ) { + Column(modifier = Modifier.fillMaxSize()) { + // Top camera preview section + Box( + modifier = Modifier + .fillMaxWidth() + .weight(0.46f) + .background(Color.Black) + ) { + CameraBarcodePreview( + torchEnabled = torchEnabled, + isPaused = isScanningPaused || showManualBarcodeDialog, + onBarcodeScanned = { code -> + haptic.performHapticFeedback(HapticFeedbackType.LongPress) + onBarcodeDetected(code) + }, + modifier = Modifier.fillMaxSize() + ) + + // Top controls bar + Row( + modifier = Modifier + .fillMaxWidth() + .statusBarsPadding() + .padding(horizontal = 12.dp, vertical = 8.dp) + .align(Alignment.TopCenter), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Surface( + shape = CircleShape, + color = Color.Black.copy(alpha = 0.55f) + ) { + IconButton( + onClick = onDismiss, + modifier = Modifier.testTag("barcode_scanner_close") + ) { + Icon( + imageVector = Icons.Default.Close, + contentDescription = "Fermer le scanner", + tint = Color.White + ) + } + } + + Surface( + shape = RoundedCornerShape(20.dp), + color = Color.Black.copy(alpha = 0.55f) + ) { + Text( + text = if (isScanningPaused) "Scan en pause" else "Mode rafale actif", + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = Color.White, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp) + ) + } + + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Surface( + shape = CircleShape, + color = Color.Black.copy(alpha = 0.55f) + ) { + IconButton( + onClick = { showManualBarcodeDialog = true }, + modifier = Modifier.testTag("barcode_manual_entry_button") + ) { + Icon( + imageVector = Icons.Default.Keyboard, + contentDescription = "Saisir un code-barres", + tint = Color.White + ) + } + } + Surface( + shape = CircleShape, + color = Color.Black.copy(alpha = 0.55f) + ) { + IconButton( + onClick = { isScanningPaused = !isScanningPaused }, + modifier = Modifier.testTag("barcode_pause_button") + ) { + Icon( + imageVector = if (isScanningPaused) Icons.Default.PlayArrow else Icons.Default.Pause, + contentDescription = if (isScanningPaused) "Reprendre le scan" else "Mettre en pause", + tint = Color.White + ) + } + } + Surface( + shape = CircleShape, + color = Color.Black.copy(alpha = 0.55f) + ) { + IconButton( + onClick = { torchEnabled = !torchEnabled }, + modifier = Modifier.testTag("barcode_torch_button") + ) { + Icon( + imageVector = if (torchEnabled) Icons.Default.FlashOn else Icons.Default.FlashOff, + contentDescription = "Lampe torche", + tint = if (torchEnabled) Color(0xFFFFD54F) else Color.White + ) + } + } + } + } + + // Viewfinder reticle + Box( + modifier = Modifier + .align(Alignment.Center) + .width(260.dp) + .height(130.dp) + .border( + width = 2.dp, + color = if (isScanningPaused) Color.White.copy(alpha = 0.4f) else MaterialTheme.colorScheme.primary, + shape = RoundedCornerShape(16.dp) + ) + ) + + // Live scan feedback pill + if (!lastFeedback.isNullOrBlank()) { + Surface( + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.94f), + modifier = Modifier + .align(Alignment.BottomCenter) + .padding(horizontal = 16.dp, vertical = 12.dp) + ) { + Text( + text = lastFeedback, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onPrimaryContainer, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 14.dp, vertical = 7.dp) + ) + } + } + } + + // Bottom scanned products tray + Surface( + modifier = Modifier + .fillMaxWidth() + .weight(0.54f), + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp), + color = MaterialTheme.colorScheme.surface + ) { + Column( + modifier = Modifier + .fillMaxSize() + .navigationBarsPadding() + ) { + // Tray header + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 18.dp, vertical = 12.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = if (scannedItems.isEmpty()) { + "Scannez vos produits" + } else { + "${scannedItems.size} produit${if (scannedItems.size > 1) "s" else ""} ($totalPacksCount unité${if (totalPacksCount > 1) "s" else ""})" + }, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + text = "Rescannez le même produit pour faire +1", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + if (scannedItems.isNotEmpty()) { + TextButton(onClick = onClearAll) { + Text("Vider") + } + } + } + + HorizontalDivider() + + if (scannedItems.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .padding(24.dp), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + imageVector = Icons.Default.QrCodeScanner, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(40.dp) + ) + Text( + text = "Visez un code-barres EAN pour l'ajouter", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + textAlign = TextAlign.Center + ) + Text( + text = "Nom, quantité, catégorie et date estimée sont remplis automatiquement via Open Food Facts.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + } + } + } else { + LazyColumn( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + .testTag("barcode_scanned_list"), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + items(scannedItems, key = { it.id }) { item -> + ScannedBarcodeItemCard( + item = item, + isExpanded = expandedItemId == item.id || !item.isFoundInCatalog, + onToggleExpand = { + expandedItemId = if (expandedItemId == item.id) null else item.id + }, + onAdjustPacks = { delta -> onAdjustPacks(item.id, delta) }, + onUpdate = onUpdateItem, + onRemove = { onRemoveItem(item.id) } + ) + } + } + } + + // Sticky footer + Surface( + tonalElevation = 3.dp, + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + if (scannedItems.isNotEmpty()) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { alsoCheckShoppingList = !alsoCheckShoppingList }, + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = alsoCheckShoppingList, + onCheckedChange = { alsoCheckShoppingList = it } + ) + Text( + text = "Cocher aussi sur la liste de courses", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Button( + onClick = { + onConfirmImport(alsoCheckShoppingList) + onDismiss() + }, + enabled = validItemsCount > 0, + shape = RoundedCornerShape(14.dp), + modifier = Modifier + .fillMaxWidth() + .height(48.dp) + .testTag("barcode_confirm_import_button") + ) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = if (validItemsCount > 0) { + "Ajouter au stock ($validItemsCount)" + } else { + "Ajouter au stock" + }, + fontWeight = FontWeight.SemiBold + ) + } + } + } + } + } + } + } + } + + if (showManualBarcodeDialog) { + ManualBarcodeInputDialog( + onDismiss = { showManualBarcodeDialog = false }, + onSubmit = { code -> + showManualBarcodeDialog = false + onBarcodeDetected(code) + } + ) + } +} + +@SuppressLint("UnsafeOptInUsageError") +@Composable +private fun CameraBarcodePreview( + torchEnabled: Boolean, + isPaused: Boolean, + onBarcodeScanned: (String) -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnScanned by rememberUpdatedState(onBarcodeScanned) + val currentIsPaused by rememberUpdatedState(isPaused) + + var boundCamera by remember { mutableStateOf(null) } + var cameraError by remember { mutableStateOf(null) } + + val previewView = remember { + PreviewView(context).apply { + scaleType = PreviewView.ScaleType.FILL_CENTER + } + } + + DisposableEffect(torchEnabled, boundCamera) { + boundCamera?.cameraControl?.enableTorch(torchEnabled) + onDispose {} + } + + DisposableEffect(lifecycleOwner) { + val executor = Executors.newSingleThreadExecutor() + val scannerOptions = BarcodeScannerOptions.Builder() + .setBarcodeFormats( + Barcode.FORMAT_EAN_13, + Barcode.FORMAT_EAN_8, + Barcode.FORMAT_UPC_A, + Barcode.FORMAT_UPC_E, + Barcode.FORMAT_CODE_128 + ) + .build() + val barcodeScanner = BarcodeScanning.getClient(scannerOptions) + val cameraProviderFuture = ProcessCameraProvider.getInstance(context) + + var lastCode: String? = null + var lastScanTimeMs = 0L + + val listener = Runnable { + try { + val cameraProvider = cameraProviderFuture.get() + val preview = Preview.Builder().build().also { + it.surfaceProvider = previewView.surfaceProvider + } + val analysis = ImageAnalysis.Builder() + .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) + .build() + + analysis.setAnalyzer(executor) { imageProxy -> + if (currentIsPaused) { + imageProxy.close() + return@setAnalyzer + } + val mediaImage = imageProxy.image + if (mediaImage == null) { + imageProxy.close() + return@setAnalyzer + } + val inputImage = InputImage.fromMediaImage( + mediaImage, + imageProxy.imageInfo.rotationDegrees + ) + barcodeScanner.process(inputImage) + .addOnSuccessListener { barcodes -> + val rawValue = barcodes + .firstOrNull { !it.rawValue.isNullOrBlank() } + ?.rawValue + ?.trim() + if (!rawValue.isNullOrBlank()) { + val now = SystemClock.elapsedRealtime() + val cooldownMs = if (rawValue == lastCode) 1800L else 600L + if (now - lastScanTimeMs >= cooldownMs) { + lastCode = rawValue + lastScanTimeMs = now + ContextCompat.getMainExecutor(context).execute { + currentOnScanned(rawValue) + } + } + } + } + .addOnCompleteListener { + imageProxy.close() + } + } + + cameraProvider.unbindAll() + val camera = cameraProvider.bindToLifecycle( + lifecycleOwner, + CameraSelector.DEFAULT_BACK_CAMERA, + preview, + analysis + ) + boundCamera = camera + camera.cameraControl.enableTorch(torchEnabled) + } catch (e: Exception) { + Log.e("BarcodeScannerScreen", "Failed to bind CameraX", e) + cameraError = "Caméra indisponible sur cet appareil. Utilisez le bouton clavier en haut à droite." + } + } + + cameraProviderFuture.addListener(listener, ContextCompat.getMainExecutor(context)) + + onDispose { + runCatching { cameraProviderFuture.get().unbindAll() } + barcodeScanner.close() + executor.shutdown() + } + } + + Box(modifier = modifier) { + AndroidView( + factory = { previewView }, + modifier = Modifier.fillMaxSize() + ) + if (cameraError != null) { + Box( + modifier = Modifier + .fillMaxSize() + .background(Color.Black.copy(alpha = 0.78f)) + .padding(24.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = cameraError.orEmpty(), + style = MaterialTheme.typography.bodyMedium, + color = Color.White, + textAlign = TextAlign.Center + ) + } + } + } +} + +@Composable +private fun ScannedBarcodeItemCard( + item: ScannedBarcodeItem, + isExpanded: Boolean, + onToggleExpand: () -> Unit, + onAdjustPacks: (Int) -> Unit, + onUpdate: (ScannedBarcodeItem) -> Unit, + onRemove: () -> Unit +) { + val today = remember { LocalDate.now() } + val dateFormatter = remember { DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) } + + Card( + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = if (!item.isFoundInCatalog && item.name.isBlank()) { + MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.25f) + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f) + } + ), + border = BorderStroke( + width = 1.dp, + color = if (!item.isFoundInCatalog && item.name.isBlank()) { + MaterialTheme.colorScheme.error.copy(alpha = 0.45f) + } else { + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + } + ), + modifier = Modifier + .fillMaxWidth() + .testTag("barcode_item_${item.barcode}") + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(enabled = !item.isLoading, onClick = onToggleExpand), + verticalAlignment = Alignment.CenterVertically + ) { + if (item.isLoading) { + CircularProgressIndicator( + modifier = Modifier.size(22.dp), + strokeWidth = 2.dp + ) + Spacer(modifier = Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = "Recherche Open Food Facts...", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold + ) + Text( + text = item.barcode, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + if (!item.imageUrl.isNullOrBlank()) { + AsyncImage( + model = item.imageUrl, + contentDescription = item.name, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(40.dp) + .clip(RoundedCornerShape(10.dp)) + ) + } else { + FoodCategoryColorDot(category = item.category, size = 12.dp) + } + + Spacer(modifier = Modifier.width(10.dp)) + + Column(modifier = Modifier.weight(1f)) { + Text( + text = item.name.ifBlank { "Produit inconnu (${item.barcode})" }, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = item.formatTotalQuantity(), + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) + Text("•", style = MaterialTheme.typography.labelSmall) + Text( + text = item.location.displayName, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + item.expirationDateEpochDay?.let { epoch -> + Text("•", style = MaterialTheme.typography.labelSmall) + Text( + text = LocalDate.ofEpochDay(epoch).format(dateFormatter), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + if (!item.brand.isNullOrBlank()) { + Text( + text = item.brand, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } + + // Pack counter - / xN / + + Row(verticalAlignment = Alignment.CenterVertically) { + IconButton( + onClick = { onAdjustPacks(-1) }, + modifier = Modifier.size(34.dp) + ) { + Icon( + imageVector = Icons.Default.Remove, + contentDescription = "Retirer 1 unité", + modifier = Modifier.size(18.dp) + ) + } + Text( + text = "×${item.packCount}", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 2.dp) + ) + IconButton( + onClick = { onAdjustPacks(1) }, + modifier = Modifier.size(34.dp) + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = "Ajouter 1 unité", + modifier = Modifier.size(18.dp) + ) + } + IconButton( + onClick = onToggleExpand, + modifier = Modifier.size(32.dp) + ) { + Icon( + imageVector = Icons.Default.Edit, + contentDescription = "Ajuster emplacement ou date", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(16.dp) + ) + } + } + } + } + + // Expandable quick-edit section (Name if unknown + Location + Expiration chips) + AnimatedVisibility(visible = isExpanded && !item.isLoading) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(top = 4.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedTextField( + value = item.name, + onValueChange = { updatedName -> + val inferredCat = if (updatedName.isNotBlank()) { + FoodCategory.inferFromName(updatedName) + } else { + item.category + } + onUpdate( + item.copy( + name = updatedName, + category = inferredCat + ) + ) + }, + label = { Text("Nom de l'aliment") }, + placeholder = { Text("Ex. Lait demi-écrémé, Yaourt...") }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth() + ) + + // Quick location chips + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + StorageLocation.entries.forEach { loc -> + FilterChip( + selected = item.location == loc, + onClick = { + val suggestedExp = ExpirationDefaults.suggestedExpirationEpochDay( + item.category, + loc, + today + ) + onUpdate( + item.copy( + location = loc, + expirationDateEpochDay = suggestedExp + ) + ) + }, + label = { Text(loc.displayName, maxLines = 1) }, + modifier = Modifier.weight(1f) + ) + } + } + + // Quick expiration chips + LazyRow( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + item { + Icon( + imageVector = Icons.Default.CalendarMonth, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(16.dp) + ) + } + val presets = listOf( + 3L to "+3 j", + 7L to "+1 sem", + 14L to "+2 sem", + 30L to "+1 mois", + 180L to "+6 mois", + 365L to "+1 an" + ) + items(presets) { (days, label) -> + val targetEpoch = today.plusDays(days).toEpochDay() + FilterChip( + selected = item.expirationDateEpochDay == targetEpoch, + onClick = { + onUpdate(item.copy(expirationDateEpochDay = targetEpoch)) + }, + label = { Text(label) } + ) + } + item { + FilterChip( + selected = item.expirationDateEpochDay == null, + onClick = { + onUpdate(item.copy(expirationDateEpochDay = null)) + }, + label = { Text("Sans date") } + ) + } + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.End + ) { + TextButton(onClick = onRemove) { + Icon( + imageVector = Icons.Default.DeleteOutline, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text("Retirer de la liste") + } + } + } + } + } + } +} + +@Composable +private fun ManualBarcodeInputDialog( + onDismiss: () -> Unit, + onSubmit: (String) -> Unit +) { + var codeText by remember { mutableStateOf("") } + val digitsOnly = codeText.filter { it.isDigit() } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = "Saisir un code-barres", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + }, + text = { + OutlinedTextField( + value = codeText, + onValueChange = { codeText = it }, + label = { Text("Code EAN / UPC") }, + placeholder = { Text("Ex. 3017620422003") }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth() + ) + }, + confirmButton = { + Button( + onClick = { onSubmit(digitsOnly) }, + enabled = digitsOnly.length >= 4 + ) { + Text("Rechercher") + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text("Annuler") + } + } + ) +} diff --git a/app/src/main/java/com/example/ui/planning/InventoryTab.kt b/app/src/main/java/com/example/ui/planning/InventoryTab.kt index 1ba2620..c3d2c9c 100644 --- a/app/src/main/java/com/example/ui/planning/InventoryTab.kt +++ b/app/src/main/java/com/example/ui/planning/InventoryTab.kt @@ -25,6 +25,7 @@ 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.QrCodeScanner import androidx.compose.material.icons.filled.Remove import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Search @@ -66,6 +67,7 @@ import java.util.Locale fun InventoryTab( inventoryItems: List, alertThresholdDays: Int = 3, + onScanBarcodeClick: () -> Unit = {}, onScanReceiptClick: () -> Unit, onAddManualClick: () -> Unit, onAdaptMenusForExpiringClick: () -> Unit = {}, @@ -176,11 +178,29 @@ fun InventoryTab( Row( modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(10.dp) + horizontalArrangement = Arrangement.spacedBy(8.dp) ) { Button( + onClick = onScanBarcodeClick, + shape = RoundedCornerShape(12.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 10.dp), + modifier = Modifier + .weight(1f) + .testTag("scan_barcode_button") + ) { + Icon( + imageVector = Icons.Default.QrCodeScanner, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text("Code-barres", maxLines = 1, overflow = TextOverflow.Ellipsis) + } + + FilledTonalButton( onClick = onScanReceiptClick, shape = RoundedCornerShape(12.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 10.dp), modifier = Modifier .weight(1f) .testTag("scan_receipt_button") @@ -191,21 +211,20 @@ fun InventoryTab( modifier = Modifier.size(18.dp) ) Spacer(modifier = Modifier.width(6.dp)) - Text("Scanner un ticket", maxLines = 1, overflow = TextOverflow.Ellipsis) + Text("Ticket", maxLines = 1, overflow = TextOverflow.Ellipsis) } FilledTonalButton( onClick = onAddManualClick, shape = RoundedCornerShape(12.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 10.dp), modifier = Modifier.testTag("add_inventory_button") ) { Icon( imageVector = Icons.Default.Add, - contentDescription = null, + contentDescription = "Ajouter manuellement", modifier = Modifier.size(18.dp) ) - Spacer(modifier = Modifier.width(4.dp)) - Text("Ajouter") } } } diff --git a/app/src/main/java/com/example/ui/planning/PlanningScreen.kt b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt index 8df7a75..7514c2d 100644 --- a/app/src/main/java/com/example/ui/planning/PlanningScreen.kt +++ b/app/src/main/java/com/example/ui/planning/PlanningScreen.kt @@ -65,6 +65,7 @@ import com.example.data.model.PlannedMealEntry import com.example.data.model.PredictionMealScope import com.example.data.model.ReceiptScanUiState import com.example.data.model.RecipeEntry +import com.example.data.model.ScannedBarcodeItem import com.example.data.model.ScannedReceiptItem import com.example.data.model.ShoppingListItem import com.example.data.model.StorageLocation @@ -124,6 +125,14 @@ fun PlanningScreen( onAddBlankScannedItem: () -> Unit, onConfirmReceiptImport: (List, Boolean) -> Unit, onDismissReceiptScan: () -> Unit, + barcodeScanItems: List = emptyList(), + barcodeScanFeedback: String? = null, + onBarcodeDetected: (String) -> Unit = {}, + onAdjustBarcodePacks: (itemId: String, delta: Int) -> Unit = { _, _ -> }, + onUpdateBarcodeItem: (ScannedBarcodeItem) -> Unit = {}, + onRemoveBarcodeItem: (String) -> Unit = {}, + onConfirmBarcodeImport: (Boolean) -> Unit = {}, + onClearBarcodeScanSession: () -> Unit = {}, onShowMessage: (String) -> Unit ) { val context = LocalContext.current @@ -144,6 +153,7 @@ fun PlanningScreen( var shoppingItemForStockPrompt by remember { mutableStateOf(null) } var showPredictWeekSheet by rememberSaveable { mutableStateOf(false) } var showShoppingMode by rememberSaveable { mutableStateOf(false) } + var showBarcodeScanner by rememberSaveable { mutableStateOf(false) } val recipesById = remember(recipes) { recipes.associateBy { it.id } } @@ -220,6 +230,29 @@ fun PlanningScreen( ) } + val barcodeCameraPermissionLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + showBarcodeScanner = true + } else { + onShowMessage("Autorisation caméra nécessaire pour scanner les codes-barres (vous pouvez aussi les saisir au clavier)") + showBarcodeScanner = true + } + } + + val triggerBarcodeScanner = { + val hasCameraPerm = ContextCompat.checkSelfPermission( + context, + Manifest.permission.CAMERA + ) == PackageManager.PERMISSION_GRANTED + if (hasCameraPerm) { + showBarcodeScanner = true + } else { + barcodeCameraPermissionLauncher.launch(Manifest.permission.CAMERA) + } + } + val uncheckedShoppingCount = shoppingItems.count { !it.isChecked } Box( @@ -332,6 +365,7 @@ fun PlanningScreen( InventoryTab( inventoryItems = inventoryItems, alertThresholdDays = expirationAlertDays, + onScanBarcodeClick = triggerBarcodeScanner, onScanReceiptClick = { showReceiptSourceDialog = true }, onAddManualClick = { editingInventoryItem = null @@ -550,6 +584,21 @@ fun PlanningScreen( onDismiss = { showShoppingMode = false } ) } + + // Fullscreen Burst Barcode Scanner (Open Food Facts) + if (showBarcodeScanner) { + BarcodeScannerScreen( + scannedItems = barcodeScanItems, + lastFeedback = barcodeScanFeedback, + onBarcodeDetected = onBarcodeDetected, + onAdjustPacks = onAdjustBarcodePacks, + onUpdateItem = onUpdateBarcodeItem, + onRemoveItem = onRemoveBarcodeItem, + onConfirmImport = onConfirmBarcodeImport, + onClearAll = onClearBarcodeScanSession, + onDismiss = { showBarcodeScanner = false } + ) + } } @Composable diff --git a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt index 5345fc7..3fc594d 100644 --- a/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt +++ b/app/src/main/java/com/example/ui/planning/PlanningViewModel.kt @@ -22,6 +22,7 @@ import com.example.data.model.PredictedMealProposal import com.example.data.model.PredictionMealScope import com.example.data.model.ReceiptScanUiState import com.example.data.model.RecipeEntry +import com.example.data.model.ScannedBarcodeItem import com.example.data.model.ScannedReceiptItem import com.example.data.model.ShoppingListItem import com.example.data.model.StockDeductionProposal @@ -30,6 +31,7 @@ import com.example.data.model.WeekPredictionUiState import com.example.data.preferences.PlanningPreferencesManager import com.example.data.repository.MealRepository import com.example.domain.IngredientMatcher +import com.example.domain.OpenFoodFactsClient import com.example.domain.ReceiptScannerAnalyzer import com.example.domain.ShoppingListCalculator import com.example.domain.WeeklyMealPredictor @@ -83,6 +85,10 @@ internal fun interface ExpiringMenuAdapter { ): Result> } +internal fun interface BarcodeProductLookup { + suspend fun lookupProduct(barcode: String): Result +} + @OptIn(ExperimentalCoroutinesApi::class) class PlanningViewModel internal constructor( application: Application, @@ -99,6 +105,9 @@ class PlanningViewModel internal constructor( preferences = preferences, defaultServings = defaultServings ) + }, + private val barcodeProductLookup: BarcodeProductLookup = BarcodeProductLookup { barcode -> + OpenFoodFactsClient().lookupProduct(barcode) } ) : AndroidViewModel(application) { @@ -213,6 +222,12 @@ class PlanningViewModel internal constructor( private val _receiptScanState = MutableStateFlow(ReceiptScanUiState.Idle) val receiptScanState: StateFlow = _receiptScanState.asStateFlow() + private val _barcodeScanItems = MutableStateFlow>(emptyList()) + val barcodeScanItems: StateFlow> = _barcodeScanItems.asStateFlow() + + private val _barcodeScanFeedback = MutableStateFlow(null) + val barcodeScanFeedback: StateFlow = _barcodeScanFeedback.asStateFlow() + private val _weekPredictionState = MutableStateFlow(WeekPredictionUiState.Idle) val weekPredictionState: StateFlow = _weekPredictionState.asStateFlow() @@ -956,6 +971,167 @@ class PlanningViewModel internal constructor( _receiptScanState.value = ReceiptScanUiState.Idle } + // ------------------------------------------------------------------------ + // Barcode Scanning (Burst Mode + Open Food Facts) + // ------------------------------------------------------------------------ + + fun onBarcodeScanned(rawBarcode: String) { + val barcode = rawBarcode.filter { it.isDigit() } + if (barcode.length < 4) return + + val existing = _barcodeScanItems.value.firstOrNull { it.barcode == barcode } + if (existing != null) { + val newPacks = existing.packCount + 1 + _barcodeScanItems.update { list -> + val updatedItem = existing.copy(packCount = newPacks) + listOf(updatedItem) + list.filterNot { it.id == existing.id } + } + val displayName = existing.name.ifBlank { "Produit $barcode" } + _barcodeScanFeedback.value = "✓ $displayName (×$newPacks)" + return + } + + val placeholderId = "bc_${UUID.randomUUID().toString().take(8)}" + val placeholder = ScannedBarcodeItem( + id = placeholderId, + barcode = barcode, + name = "Recherche...", + unitQuantity = 1.0, + packCount = 1, + unit = FoodUnit.PORTION, + category = FoodCategory.OTHER, + location = StorageLocation.PANTRY, + isFoundInCatalog = true, + isLoading = true + ) + _barcodeScanItems.update { listOf(placeholder) + it } + _barcodeScanFeedback.value = "Recherche du code $barcode..." + + viewModelScope.launch { + val result = barcodeProductLookup.lookupProduct(barcode) + result.fold( + onSuccess = { found -> + if (found != null) { + _barcodeScanItems.update { list -> + list.map { item -> + if (item.id == placeholderId) { + found.copy( + id = placeholderId, + packCount = item.packCount + ) + } else { + item + } + } + } + val currentPacks = _barcodeScanItems.value + .firstOrNull { it.id == placeholderId }?.packCount ?: 1 + val suffix = if (currentPacks > 1) " (×$currentPacks)" else " • ${found.formatPackageQuantity()}" + _barcodeScanFeedback.value = "✓ ${found.name}$suffix" + } else { + _barcodeScanItems.update { list -> + list.map { item -> + if (item.id == placeholderId) { + item.copy( + name = "", + isFoundInCatalog = false, + isLoading = false + ) + } else { + item + } + } + } + _barcodeScanFeedback.value = "Produit inconnu ($barcode) — nommez-le ci-dessous" + } + }, + onFailure = { + _barcodeScanItems.update { list -> + list.map { item -> + if (item.id == placeholderId) { + item.copy( + name = "", + isFoundInCatalog = false, + isLoading = false + ) + } else { + item + } + } + } + _barcodeScanFeedback.value = "Connexion impossible — complétez le nom manuellement" + } + ) + } + } + + fun adjustBarcodeItemPacks(itemId: String, delta: Int) { + _barcodeScanItems.update { list -> + list.mapNotNull { item -> + if (item.id != itemId) { + item + } else { + val next = item.packCount + delta + if (next <= 0) null else item.copy(packCount = next) + } + } + } + } + + fun updateBarcodeItem(updated: ScannedBarcodeItem) { + _barcodeScanItems.update { list -> + list.map { if (it.id == updated.id) updated else it } + } + } + + fun removeBarcodeItem(itemId: String) { + _barcodeScanItems.update { list -> list.filterNot { it.id == itemId } } + } + + fun confirmBarcodeBurstImport(alsoCheckShoppingList: Boolean) { + val currentItems = _barcodeScanItems.value + val validItems = currentItems.filter { !it.isLoading && it.name.isNotBlank() && it.totalQuantity > 0.0 } + if (validItems.isEmpty()) { + emitSnackbar("Scannez ou nommez au moins un produit valide") + return + } + + viewModelScope.launch { + validItems.forEach { scanned -> + repository.addOrMergeInventoryItem( + name = scanned.name.trim(), + quantityToAdd = scanned.totalQuantity, + unit = scanned.unit, + category = scanned.category, + location = scanned.location, + expirationDateEpochDay = scanned.expirationDateEpochDay + ) + } + + if (alsoCheckShoppingList) { + val scannedNorms = validItems.map { IngredientMatcher.normalize(it.name) }.toSet() + val manualItems = repository.getManualShoppingItemsSnapshot() + manualItems.forEach { manual -> + val manualNorm = IngredientMatcher.normalize(manual.name) + if (!manual.isChecked && scannedNorms.any { IngredientMatcher.matches(it, manualNorm) }) { + repository.setManualShoppingItemChecked(manual.id, true) + } + } + } + + _barcodeScanItems.value = emptyList() + _barcodeScanFeedback.value = null + emitSnackbar( + "${validItems.size} produit${if (validItems.size > 1) "s" else ""} ajouté${if (validItems.size > 1) "s" else ""} au stock" + ) + } + } + + fun clearBarcodeScanSession() { + _barcodeScanItems.value = emptyList() + _barcodeScanFeedback.value = null + } + private fun emitSnackbar(message: String) { _uiEvents.trySend(UiEvent.ShowSnackbar(message)) } diff --git a/app/src/test/java/com/example/OpenFoodFactsClientTest.kt b/app/src/test/java/com/example/OpenFoodFactsClientTest.kt new file mode 100644 index 0000000..d5c3d22 --- /dev/null +++ b/app/src/test/java/com/example/OpenFoodFactsClientTest.kt @@ -0,0 +1,110 @@ +package com.example + +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.StorageLocation +import com.example.domain.OpenFoodFactsClient +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.time.LocalDate + +@RunWith(RobolectricTestRunner::class) +class OpenFoodFactsClientTest { + + @Test + fun parseProductJson_parsesFrenchDairyProductWithStructuredQuantity() { + val today = LocalDate.of(2026, 11, 28) + val json = """ + { + "status": 1, + "product": { + "product_name": "Semi-skimmed milk", + "product_name_fr": "Lait demi-écrémé", + "brands": "Lactel, Lactalis", + "quantity": "1 L", + "product_quantity": "1000", + "product_quantity_unit": "ml", + "categories_tags": ["en:dairies", "en:milks", "en:fresh-foods"], + "image_front_small_url": "https://images.openfoodfacts.org/milk.jpg" + } + } + """.trimIndent() + + val item = OpenFoodFactsClient.parseProductJson("3428273700013", json, today) + assertNotNull(item) + item!! + assertEquals("Lait demi-écrémé", item.name) + assertEquals("Lactel", item.brand) + assertEquals(1000.0, item.unitQuantity, 0.01) + assertEquals(FoodUnit.ML, item.unit) + assertEquals(1, item.packCount) + assertEquals(FoodCategory.DAIRY, item.category) + assertEquals(StorageLocation.FRIDGE, item.location) + assertEquals(today.plusDays(7).toEpochDay(), item.expirationDateEpochDay) + assertTrue(item.isFoundInCatalog) + } + + @Test + fun parseProductJson_parsesFrozenProductToFreezerWithoutShortExpiration() { + val today = LocalDate.of(2026, 11, 28) + val json = """ + { + "status": 1, + "product": { + "product_name_fr": "Haricots verts extra-fins", + "brands": "Picard", + "quantity": "1 kg", + "categories_tags": ["en:frozen-foods", "en:frozen-vegetables"] + } + } + """.trimIndent() + + val item = OpenFoodFactsClient.parseProductJson("3270160000001", json, today) + assertNotNull(item) + item!! + assertEquals(1000.0, item.unitQuantity, 0.01) + assertEquals(FoodUnit.G, item.unit) + assertEquals(FoodCategory.VEGETABLE, item.category) + assertEquals(StorageLocation.FREEZER, item.location) + assertNull(item.expirationDateEpochDay) + } + + @Test + fun parseProductJson_returnsNullWhenStatusIsNotFound() { + val json = """{"status": 0, "status_verbose": "product not found"}""" + val item = OpenFoodFactsClient.parseProductJson("0000000000000", json) + assertNull(item) + } + + @Test + fun parseQuantityAndUnit_handlesMultipacksAndDecimalLitres() { + val (yogurtQty, yogurtUnit) = OpenFoodFactsClient.parseQuantityAndUnit( + productQuantity = null, + productQuantityUnit = null, + rawQuantityText = "6 x 125 g" + ) + assertEquals(750.0, yogurtQty, 0.01) + assertEquals(FoodUnit.G, yogurtUnit) + + val (waterQty, waterUnit) = OpenFoodFactsClient.parseQuantityAndUnit( + productQuantity = null, + productQuantityUnit = null, + rawQuantityText = "1,5 L" + ) + assertEquals(1500.0, waterQty, 0.01) + assertEquals(FoodUnit.ML, waterUnit) + + val (eggsQty, eggsUnit) = OpenFoodFactsClient.parseQuantityAndUnit( + productQuantity = null, + productQuantityUnit = null, + rawQuantityText = "6 œufs" + ) + assertEquals(6.0, eggsQty, 0.01) + assertEquals(FoodUnit.PORTION, eggsUnit) + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 3ba8844..369c112 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -41,6 +41,7 @@ googleServices = "4.5.0" credentials = "1.5.0" googleid = "1.1.1" playServicesAuth = "21.1.1" +mlkitBarcodeScanning = "17.3.0" [libraries] @@ -96,6 +97,7 @@ androidx-credentials = { group = "androidx.credentials", name = "credentials", v androidx-credentials-play-services = { group = "androidx.credentials", name = "credentials-play-services-auth", version.ref = "credentials" } googleid = { group = "com.google.android.libraries.identity.googleid", name = "googleid", version.ref = "googleid" } play-services-auth = { group = "com.google.android.gms", name = "play-services-auth", version.ref = "playServicesAuth" } +mlkit-barcode-scanning = { group = "com.google.mlkit", name = "barcode-scanning", version.ref = "mlkitBarcodeScanning" } [plugins]