feat: integrate Firebase AI and food preferences

- Enable Firebase AI and App Check dependencies
- Configure App Check in MainActivity
- Add FoodPreference entity and DAO methods
- Bump Room database version to 5 for new table migration
This commit is contained in:
bleackstorm committed 2026-11-21 23:30:54 +01:00
1 parent d4d5d77d71
commit 1331fae119
23 files changed
+2954 -38

No files matched your search

+1 -7
View File
@@ -1,7 +1 @@
# GEMINI_API_KEY: Required for Gemini AI API calls.
# This is a placeholder key.
# AI Studio automatically injects this at runtime from user secrets.
# Users configure this via the Secrets panel in the AI Studio UI.
# IMPORTANT: Uncomment the line below if your app uses the Gemini API.
# If left commented out, the key will NOT be packaged in the APK.
# GEMINI_API_KEY=MY_GEMINI_API_KEY
# Environment variables for third-party integrations (none required for Firebase AI Logic).
+4 -4
View File
@@ -93,7 +93,7 @@ googleServices { missingGoogleServicesStrategy = MissingGoogleServicesStrategy.W
// This makes it easy to add them back in the future if needed.
dependencies {
implementation(platform(libs.androidx.compose.bom))
// implementation(platform(libs.firebase.bom))
implementation(platform(libs.firebase.bom))
// implementation(libs.accompanist.permissions)
implementation(libs.androidx.activity.compose)
// implementation(libs.androidx.camera.camera2)
@@ -116,15 +116,15 @@ dependencies {
implementation(libs.androidx.room.runtime)
implementation(libs.coil.compose)
// implementation(libs.converter.moshi)
// implementation(libs.firebase.ai)
implementation(libs.firebase.ai)
// implementation(libs.firebase.firestore)
// implementation(libs.firebase.auth)
// implementation(libs.androidx.credentials)
// implementation(libs.androidx.credentials.play.services)
// implementation(libs.googleid)
implementation(libs.play.services.auth)
// implementation(libs.firebase.appcheck.recaptcha)
// implementation(libs.firebase.appcheck.debug)
implementation(libs.firebase.appcheck.recaptcha)
implementation(libs.firebase.appcheck.debug)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.logging.interceptor)
@@ -71,6 +71,7 @@ import com.example.ui.stats.WeeklyStatsScreen
import com.example.ui.theme.SatieaTheme
import com.example.util.CsvExporter
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.configureAppCheck
import com.example.widget.SatieaAppWidgetProvider
import kotlinx.coroutines.launch
import java.time.LocalTime
@@ -93,6 +94,10 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Configure Firebase App Check with launch intent before UI, ViewModels, or Firebase AI calls
configureAppCheck(this, intent)
enableEdgeToEdge()
MealNotificationManager.createNotificationChannel(this)
@@ -247,6 +252,11 @@ fun AppRoot(
val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
val recipes by viewModel.recipes.collectAsStateWithLifecycle()
val foodPreferences by viewModel.foodPreferences.collectAsStateWithLifecycle()
val selectedIdeaMealType by viewModel.selectedIdeaMealType.collectAsStateWithLifecycle()
val dailyBenchmarkGap by viewModel.dailyBenchmarkGap.collectAsStateWithLifecycle()
val suggestionUiState by viewModel.suggestionUiState.collectAsStateWithLifecycle()
val savedSuggestionIds by viewModel.savedSuggestionIds.collectAsStateWithLifecycle()
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
@@ -459,12 +469,46 @@ fun AppRoot(
RecipesScreen(
recipes = recipes,
customFoods = customFoods,
foodPreferences = foodPreferences,
selectedIdeaMealType = selectedIdeaMealType,
dailyBenchmarkGap = dailyBenchmarkGap,
suggestionUiState = suggestionUiState,
savedSuggestionIds = savedSuggestionIds,
onAddRecipeClick = {
editingRecipe = null
showRecipeEditor = true
},
onRecipeClick = { recipe ->
selectedRecipeId = recipe.id
},
onSavePreference = { name, status, category ->
viewModel.setFoodPreference(
name = name,
status = status,
category = category
)
},
onRemovePreference = { slugId ->
viewModel.removeFoodPreference(slugId)
},
onSelectIdeaMealType = { mealType ->
viewModel.setIdeaMealType(mealType)
},
onGenerateIdeas = { cravingNote ->
viewModel.generateCulinaryIdeas(cravingNote)
},
onSaveSuggestedRecipe = { suggestion ->
viewModel.saveSuggestedRecipe(suggestion)
},
onLogSuggestedRecipe = { suggestion, targetMealType ->
val prefilled = suggestion.toPrefilledMeal(targetMealType)
currentTab = MainTab.JOURNAL
editingMeal = prefilled
defaultMealType = targetMealType
showMealEntrySheet = true
},
onLikeSuggestedRecipeIngredients = { suggestion ->
viewModel.likeSuggestedRecipeIngredients(suggestion)
}
)
}
@@ -12,8 +12,13 @@ import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
@Database(
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class, LocalRecipeEntity::class],
version = 4,
entities = [
LocalMealEntity::class,
LocalCustomFoodEntity::class,
LocalRecipeEntity::class,
LocalFoodPreferenceEntity::class
],
version = 5,
exportSchema = false
)
@TypeConverters(RoomConverters::class)
@@ -117,6 +122,23 @@ abstract class AppDatabase : RoomDatabase() {
}
}
val MIGRATION_4_5 = object : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS `local_food_preferences` (
`slugId` TEXT NOT NULL PRIMARY KEY,
`name` TEXT NOT NULL,
`status` TEXT NOT NULL,
`category` TEXT NOT NULL,
`note` TEXT NOT NULL,
`updatedAt` INTEGER NOT NULL
)
""".trimIndent()
)
}
}
fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it }
@@ -128,7 +150,7 @@ abstract class AppDatabase : RoomDatabase() {
appContext,
AppDatabase::class.java,
"satiea_local.db"
).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5)
// Destructive migration is only permitted on debug builds
if (BuildConfig.DEBUG) {
@@ -0,0 +1,58 @@
package com.example.data.local
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
@Entity(tableName = "local_food_preferences")
data class LocalFoodPreferenceEntity(
@PrimaryKey val slugId: String,
val name: String,
val status: String,
val category: String = "",
val note: String = "",
val updatedAt: Long = System.currentTimeMillis()
) {
fun resolvedCategory(): FoodCategory {
return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name)
}
fun resolvedStatus(): FoodPreferenceStatus {
return FoodPreferenceStatus.fromString(status)
}
fun toDomain(): FoodPreferenceEntry {
return FoodPreferenceEntry(
slugId = slugId,
name = name,
status = resolvedStatus(),
category = resolvedCategory(),
note = note,
updatedAt = updatedAt
)
}
companion object {
fun create(
name: String,
status: FoodPreferenceStatus,
category: FoodCategory? = null,
note: String = "",
updatedAt: Long = System.currentTimeMillis()
): LocalFoodPreferenceEntity {
val cleanName = name.trim().take(100)
val slug = FoodPreferenceEntry.buildSlugId(cleanName)
val resolvedCat = category ?: FoodCategory.inferFromName(cleanName)
return LocalFoodPreferenceEntity(
slugId = slug,
name = cleanName,
status = status.code,
category = resolvedCat.code,
note = note.trim().take(240),
updatedAt = updatedAt
)
}
}
}
@@ -56,4 +56,19 @@ interface LocalMealDao {
@Query("DELETE FROM local_recipes WHERE id = :id")
suspend fun deleteRecipeById(id: String)
@Query("SELECT * FROM local_food_preferences ORDER BY updatedAt DESC, name ASC")
fun observeAllFoodPreferences(): Flow<List<LocalFoodPreferenceEntity>>
@Query("SELECT * FROM local_food_preferences ORDER BY name ASC")
suspend fun getAllFoodPreferencesOnce(): List<LocalFoodPreferenceEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFoodPreference(preference: LocalFoodPreferenceEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFoodPreferences(preferences: List<LocalFoodPreferenceEntity>)
@Query("DELETE FROM local_food_preferences WHERE slugId = :slugId")
suspend fun deleteFoodPreferenceBySlug(slugId: String)
}
@@ -0,0 +1,79 @@
package com.example.data.model
import kotlin.math.roundToInt
data class RecipeSuggestion(
val id: String,
val title: String,
val categoryTag: RecipeCategoryTag,
val prepTimeMinutes: Int,
val servings: Int,
val whyItFits: String,
val completedCategories: List<FoodCategory>,
val ingredients: List<MealFoodItem>,
val steps: List<String>
) {
fun toRecipeEntry(): RecipeEntry {
val safeServings = servings.coerceAtLeast(1)
return RecipeEntry(
id = "",
title = title.trim(),
categoryTag = categoryTag.name,
prepTimeMinutes = prepTimeMinutes.coerceAtLeast(0),
servings = safeServings,
ingredientsSerialized = ingredients.map { it.serialize() },
steps = steps.filter { it.isNotBlank() },
notes = whyItFits.trim(),
photoUri = null
)
}
/**
* Scales ingredients down to 1 portion for instant logging into the meal journal.
*/
fun toPrefilledMeal(mealType: MealType): MealEntry {
val baseServings = servings.coerceAtLeast(1).toDouble()
val singleServingIngredients = ingredients.map { item ->
val scaledWeight = item.weight?.let { w ->
val raw = w / baseServings
when (item.unit) {
FoodUnit.G, FoodUnit.ML -> raw.roundToInt().toDouble().coerceAtLeast(1.0)
FoodUnit.PORTION -> ((raw * 2.0).roundToInt() / 2.0).coerceAtLeast(0.5)
}
}
item.copy(weight = scaledWeight)
}
return MealEntry(
id = "",
mealType = mealType.name,
mealTimestamp = System.currentTimeMillis(),
hungerBefore = 5,
satietyAfter = 7,
note = "Idée recette : $title",
foodItemsSerialized = singleServingIngredients.map { it.serialize() },
photoUris = emptyList()
)
}
}
data class DiscoverySuggestion(
val id: String,
val foodName: String,
val category: FoodCategory,
val benchmarkReason: String,
val pairingIdea: String
)
sealed interface SuggestionUiState {
data object Idle : SuggestionUiState
data object Loading : SuggestionUiState
data class Success(
val recipes: List<RecipeSuggestion>,
val discoveries: List<DiscoverySuggestion>,
val targetMealType: MealType,
val contextSummary: String,
val generatedAt: Long = System.currentTimeMillis()
) : SuggestionUiState
data class Error(val message: String) : SuggestionUiState
}
@@ -0,0 +1,69 @@
package com.example.data.model
import java.text.Normalizer
import java.util.Locale
enum class FoodPreferenceStatus(
val code: String,
val displayName: String,
val shortLabel: String
) {
LIKED("LIKED", "J'aime", "Aimés"),
DISLIKED("DISLIKED", "J'évite", "Évités"),
TO_TRY("TO_TRY", "À tester", "À tester");
companion object {
fun fromString(raw: String?): FoodPreferenceStatus {
val cleaned = raw?.trim().orEmpty()
return entries.firstOrNull {
it.code.equals(cleaned, ignoreCase = true) ||
it.displayName.equals(cleaned, ignoreCase = true) ||
it.shortLabel.equals(cleaned, ignoreCase = true)
} ?: when {
cleaned.contains("evit", ignoreCase = true) ||
cleaned.contains("évit", ignoreCase = true) ||
cleaned.contains("allerg", ignoreCase = true) -> DISLIKED
cleaned.contains("test", ignoreCase = true) ||
cleaned.contains("decouv", ignoreCase = true) ||
cleaned.contains("découv", ignoreCase = true) -> TO_TRY
else -> LIKED
}
}
}
}
data class FoodPreferenceEntry(
val slugId: String = "",
val name: String = "",
val status: FoodPreferenceStatus = FoodPreferenceStatus.LIKED,
val category: FoodCategory = FoodCategory.OTHER,
val note: String = "",
val updatedAt: Long = System.currentTimeMillis()
) {
companion object {
fun buildSlugId(name: String): String {
val normalized = Normalizer.normalize(name.lowercase(Locale.FRENCH).trim(), Normalizer.Form.NFD)
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
.replace(Regex("[^a-z0-9]+"), "_")
.trim('_')
return normalized.ifBlank { "pref_${System.currentTimeMillis()}" }
}
val quickStartLikedPicks: List<Pair<String, FoodCategory>> = listOf(
"Poulet" to FoodCategory.PROTEIN,
"Saumon" to FoodCategory.PROTEIN,
"Œufs" to FoodCategory.PROTEIN,
"Courgettes" to FoodCategory.VEGETABLE,
"Brocolis" to FoodCategory.VEGETABLE,
"Tomates" to FoodCategory.VEGETABLE,
"Riz complet" to FoodCategory.STARCH,
"Lentilles corail" to FoodCategory.STARCH,
"Pain complet" to FoodCategory.BREAD,
"Pomme" to FoodCategory.FRUIT,
"Comté" to FoodCategory.CHEESE,
"Yaourt nature" to FoodCategory.DAIRY,
"Amandes" to FoodCategory.NUTS,
"Huile d'olive" to FoodCategory.FAT_SEASONING
)
}
}
@@ -4,11 +4,14 @@ import android.content.Context
import android.net.Uri
import com.example.data.local.AppDatabase
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalFoodPreferenceEntity
import com.example.data.local.LocalMealDao
import com.example.data.local.LocalMealEntity
import com.example.data.local.LocalRecipeEntity
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.RecipeEntry
@@ -21,6 +24,13 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import java.util.UUID
data class RestoredDataCounts(
val mealsCount: Int,
val foodsCount: Int,
val recipesCount: Int,
val preferencesCount: Int
)
/**
* Pure local Room repository for Satiéa.
* All meals, custom foods, and recipes live locally on device, while optional
@@ -163,6 +173,45 @@ class MealRepository(
return localMealDao.getAllRecipesOnce().map { it.toRecipeEntry() }
}
// ------------------------------------------------------------------------
// Food Preferences (Liked, Disliked, To Try)
// ------------------------------------------------------------------------
fun observeFoodPreferences(): Flow<List<FoodPreferenceEntry>> {
return localMealDao.observeAllFoodPreferences().map { entities ->
entities.map { it.toDomain() }
}
}
suspend fun saveFoodPreference(
name: String,
status: FoodPreferenceStatus,
category: FoodCategory? = null,
note: String = ""
): Result<String> {
val cleanName = name.trim().take(100)
if (cleanName.isBlank()) {
return Result.failure(IllegalArgumentException("Le nom de l'aliment est vide"))
}
val entity = LocalFoodPreferenceEntity.create(
name = cleanName,
status = status,
category = category,
note = note
)
localMealDao.insertFoodPreference(entity)
return Result.success(entity.slugId)
}
suspend fun deleteFoodPreference(slugId: String): Result<Unit> {
localMealDao.deleteFoodPreferenceBySlug(slugId)
return Result.success(Unit)
}
suspend fun getAllFoodPreferencesSnapshot(): List<LocalFoodPreferenceEntity> {
return localMealDao.getAllFoodPreferencesOnce()
}
// ------------------------------------------------------------------------
// CSV Import & Google Sheets Restoration
// ------------------------------------------------------------------------
@@ -195,19 +244,19 @@ class MealRepository(
}
/**
* Merges restored meals, custom foods, and recipes from Google Sheets into Room
* without duplicating existing entries.
*
* @return Triple(newMealsCount, newFoodsCount, newRecipesCount)
* Merges restored meals, custom foods, recipes, and food preferences from Google Sheets
* into Room without duplicating existing entries.
*/
suspend fun insertRestoredData(
meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity>,
recipes: List<RecipeEntry> = emptyList()
): Triple<Int, Int, Int> {
recipes: List<RecipeEntry> = emptyList(),
preferences: List<LocalFoodPreferenceEntity> = emptyList()
): RestoredDataCounts {
var newMealsCount = 0
var newFoodsCount = 0
var newRecipesCount = 0
var newPreferencesCount = 0
// 1. Merge meals (deduplicate by type + minute bucket)
val existingMeals = localMealDao.getAllMealsOnce()
@@ -265,6 +314,26 @@ class MealRepository(
localMealDao.insertRecipes(toInsertRecipes)
}
return Triple(newMealsCount, newFoodsCount, newRecipesCount)
// 4. Merge food preferences (deduplicate by slugId)
val existingPrefSlugs = localMealDao.getAllFoodPreferencesOnce()
.map { it.slugId }
.toMutableSet()
val toInsertPrefs = mutableListOf<LocalFoodPreferenceEntity>()
for (pref in preferences) {
if (pref.slugId.isNotBlank() && existingPrefSlugs.add(pref.slugId)) {
toInsertPrefs.add(pref)
newPreferencesCount++
}
}
if (toInsertPrefs.isNotEmpty()) {
localMealDao.insertFoodPreferences(toInsertPrefs)
}
return RestoredDataCounts(
mealsCount = newMealsCount,
foodsCount = newFoodsCount,
recipesCount = newRecipesCount,
preferencesCount = newPreferencesCount
)
}
}
@@ -0,0 +1,363 @@
package com.example.domain
import android.util.Log
import com.example.data.model.DietaryReferenceGuide
import com.example.data.model.DiscoverySuggestion
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeSuggestion
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.Schema
import com.google.firebase.ai.type.generationConfig
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout
import org.json.JSONObject
import java.util.UUID
data class GeneratedCulinaryBundle(
val contextSummary: String,
val recipes: List<RecipeSuggestion>,
val discoveries: List<DiscoverySuggestion>
)
/**
* Generates personalized recipe ideas and new food discoveries using Firebase AI Logic
* (gemini-3.8-flash with strict JSON responseSchema) grounded in the user's liked/disliked foods
* and today's missing dietary benchmark categories.
*/
class CulinaryIdeasGenerator {
private val allowedCategoryCodes = FoodCategory.entries.map { it.code }
private val allowedUnitCodes = listOf("g", "ml", "portion")
private val allowedRecipeTags = RecipeCategoryTag.entries.map { it.name }
private val responseSchema by lazy {
val ingredientSchema = Schema.obj(
properties = mapOf(
"name" to Schema.string(description = "Nom simple de l'ingrédient en français"),
"weight" to Schema.double(description = "Quantité numérique pour le nombre total de portions"),
"unit" to Schema.enumeration(
values = allowedUnitCodes,
description = "Unité : g, ml ou portion"
),
"category" to Schema.enumeration(
values = allowedCategoryCodes,
description = "Catégorie alimentaire exacte parmi les codes fournis"
)
)
)
val recipeSchema = Schema.obj(
properties = mapOf(
"title" to Schema.string(description = "Titre appétissant et clair en français"),
"categoryTag" to Schema.enumeration(
values = allowedRecipeTags,
description = "Type de recette"
),
"prepTimeMinutes" to Schema.integer(description = "Temps de préparation en minutes"),
"servings" to Schema.integer(description = "Nombre de portions (généralement 1 ou 2)"),
"whyItFits" to Schema.string(description = "Courte phrase bienveillante expliquant comment la recette s'appuie sur les goûts aimés et complète les repères du jour"),
"completedCategories" to Schema.array(
items = Schema.enumeration(values = allowedCategoryCodes),
description = "Codes des catégories de repères alimentaires apportées par cette recette"
),
"ingredients" to Schema.array(
items = ingredientSchema,
description = "Liste structurée des ingrédients avec quantités réalistes"
),
"steps" to Schema.array(
items = Schema.string(),
description = "3 à 5 étapes simples, concrètes et rapides"
)
)
)
val discoverySchema = Schema.obj(
properties = mapOf(
"foodName" to Schema.string(description = "Nom d'un nouvel aliment ou ingrédient simple à découvrir"),
"category" to Schema.enumeration(
values = allowedCategoryCodes,
description = "Catégorie de repère alimentaire de cet aliment"
),
"benchmarkReason" to Schema.string(description = "Courte explication bienveillante du repère alimentaire qu'il aide à remplir"),
"pairingIdea" to Schema.string(description = "Idée très simple pour l'associer à un aliment déjà aimé")
)
)
Schema.obj(
properties = mapOf(
"contextSummary" to Schema.string(description = "Phrase courte et chaleureuse résumant les repères ciblés pour ce repas"),
"recipes" to Schema.array(
items = recipeSchema,
description = "2 à 3 idées de recettes variées et réalistes"
),
"discoveries" to Schema.array(
items = discoverySchema,
description = "3 à 4 suggestions de nouveaux aliments à tester pour enrichir les repères alimentaires"
)
)
)
}
private val model by lazy {
val config = generationConfig {
responseMimeType = "application/json"
responseSchema = this@CulinaryIdeasGenerator.responseSchema
temperature = 0.7f
}
Firebase.ai.generativeModel(
modelName = "gemini-3.8-flash",
generationConfig = config
)
}
suspend fun generateIdeas(
preferences: List<FoodPreferenceEntry>,
benchmarkGap: DailyBenchmarkGap,
cravingNote: String,
existingRecipeTitles: List<String>
): Result<GeneratedCulinaryBundle> {
val prompt = buildPrompt(
preferences = preferences,
benchmarkGap = benchmarkGap,
cravingNote = cravingNote,
existingRecipeTitles = existingRecipeTitles
)
return try {
val response = withTimeout(60_000L) {
model.generateContent(prompt)
}
val jsonText = response.text
if (jsonText.isNullOrBlank()) {
Result.failure(IllegalStateException("Le service d'idées a renvoyé une réponse vide. Réessayez."))
} else {
val parsed = parseSuggestionsJson(jsonText)
if (parsed.recipes.isEmpty() && parsed.discoveries.isEmpty()) {
Result.failure(IllegalStateException("Aucune idée exploitable n'a pu être générée. Réessayez."))
} else {
Result.success(parsed)
}
}
} catch (e: TimeoutCancellationException) {
Log.e(TAG, "AI culinary suggestion generation timed out", e)
Result.failure(
IllegalStateException("La génération a pris trop de temps (60 s). Vérifiez votre connexion et réessayez.")
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Firebase AI culinary suggestion failed", e)
Result.failure(
IllegalStateException(
e.localizedMessage ?: "Impossible de générer des idées pour le moment."
)
)
}
}
private fun buildPrompt(
preferences: List<FoodPreferenceEntry>,
benchmarkGap: DailyBenchmarkGap,
cravingNote: String,
existingRecipeTitles: List<String>
): String {
val liked = preferences.filter { it.status == FoodPreferenceStatus.LIKED }
val disliked = preferences.filter { it.status == FoodPreferenceStatus.DISLIKED }
val toTry = preferences.filter { it.status == FoodPreferenceStatus.TO_TRY }
val likedText = if (liked.isEmpty()) {
"Aucun aliment encore renseigné (propose des ingrédients simples, accessibles et variés)"
} else {
liked.joinToString(", ") { "${it.name} [${it.category.code}]" }
}
val dislikedText = if (disliked.isEmpty()) {
"Aucun"
} else {
disliked.joinToString(", ") { it.name }
}
val toTryText = if (toTry.isEmpty()) {
"Aucun"
} else {
toTry.joinToString(", ") { "${it.name} [${it.category.code}]" }
}
val presentTodayText = if (benchmarkGap.presentTodayCounts.isEmpty()) {
"Aucun repas enregistré aujourd'hui"
} else {
benchmarkGap.presentTodayCounts.entries.joinToString(", ") { (cat, count) ->
"${cat.displayName} (${cat.code}): $count fois"
}
}
val priorityMissingText = if (benchmarkGap.priorityMissingCategories.isEmpty()) {
"Tous les principaux repères du jour sont déjà présents ; proposer de la variété en douceur"
} else {
benchmarkGap.priorityMissingCategories.joinToString(", ") { "${it.displayName} (${it.code} — ${it.dailyGuide})" }
}
val categoriesCatalog = FoodCategory.benchmarkCategories.joinToString("\n") { cat ->
"- ${cat.code}: ${cat.displayName} (${cat.dailyGuide})"
}
val avoidDuplicates = existingRecipeTitles.take(15).joinToString(", ")
return """
Tu es un compagnon culinaire bienveillant intégré à l'application Satiéa (alimentation intuitive, zéro calcul de calories, zéro culpabilité).
Réponds exclusivement en français naturel et chaleureux, conformément au schéma JSON demandé.
OBJECTIF :
1. Proposer 3 idées de recettes simples, savoureuses et réalistes adaptées au moment du repas : ${benchmarkGap.targetMealType.displayName}.
2. Proposer 4 nouvelles découvertes d'aliments à tester (qui ne sont PAS déjà dans les listes Aimés, Évités ou À tester) pour aider à remplir les repères alimentaires manquants du jour.
PROFIL GUSTATIF DE L'UTILISATEUR :
- Aliments aimés (à utiliser en priorité dans les recettes) : $likedText
- Aliments évités / allergies (INTERDICTION ABSOLUE dans les recettes ET les découvertes) : $dislikedText
- Découvertes déjà notées « À tester » (tu peux en glisser 1 dans une recette si pertinent) : $toTryText
- Envie du moment : ${cravingNote.ifBlank { "Aucune contrainte particulière, cuisine du quotidien" }}
REPÈRES ALIMENTAIRES DU JOUR :
- Déjà consommé aujourd'hui : $presentTodayText
- Repères prioritaires à compléter pour ce ${benchmarkGap.targetMealType.displayName} : $priorityMissingText
- Rappel philosophie : ${DietaryReferenceGuide.PLEASURE_REMINDER}
CODES DE CATÉGORIES VALIDES ET REPÈRES QUOTIDIENS :
$categoriesCatalog
RÈGLES STRICTES :
- N'inclus JAMAIS un aliment évité ni ses dérivés évidents.
- Ne mentionne jamais de calories, de régime, ni de restriction.
- Donne des quantités cohérentes avec la fiche repères (ex. ~125-150 g de protéine par portion, ~200 g de légumes, ~90 g de féculents crus / ~240 g cuits, ~30 g de fromage ou fruits à coque).
- Utilise servings = 2 (ou 1 pour petit-déjeuner / collation) et adapte les poids des ingrédients au nombre total de servings.
- Évite de répéter ces recettes déjà présentes dans le recueil : ${avoidDuplicates.ifBlank { "aucune" }}.
""".trimIndent()
}
companion object {
private const val TAG = "CulinaryIdeasGenerator"
fun parseSuggestionsJson(jsonString: String): GeneratedCulinaryBundle {
val root = JSONObject(jsonString)
val contextSummary = root.optString("contextSummary", "").trim()
val recipesArray = root.optJSONArray("recipes")
val recipes = mutableListOf<RecipeSuggestion>()
if (recipesArray != null) {
for (i in 0 until recipesArray.length()) {
val obj = recipesArray.optJSONObject(i) ?: continue
val title = obj.optString("title", "").trim()
if (title.isBlank()) continue
val tag = RecipeCategoryTag.fromString(obj.optString("categoryTag", "MAIN"))
val prepTime = obj.optInt("prepTimeMinutes", 20).coerceIn(5, 240)
val servings = obj.optInt("servings", 2).coerceIn(1, 12)
val whyItFits = obj.optString("whyItFits", "").trim()
val completedCats = mutableListOf<FoodCategory>()
val catsArr = obj.optJSONArray("completedCategories")
if (catsArr != null) {
for (j in 0 until catsArr.length()) {
FoodCategory.fromCode(catsArr.optString(j))?.let { cat ->
if (cat != FoodCategory.OTHER && !completedCats.contains(cat)) {
completedCats.add(cat)
}
}
}
}
val ingredients = mutableListOf<MealFoodItem>()
val ingArr = obj.optJSONArray("ingredients")
if (ingArr != null) {
for (j in 0 until ingArr.length()) {
val ingObj = ingArr.optJSONObject(j) ?: continue
val ingName = ingObj.optString("name", "").trim()
if (ingName.isBlank()) continue
val weightRaw = ingObj.optDouble("weight", Double.NaN)
val weight = if (!weightRaw.isNaN() && weightRaw > 0.0) weightRaw else null
val unit = FoodUnit.fromCode(ingObj.optString("unit", "g"))
val explicitCat = FoodCategory.fromCode(ingObj.optString("category"))
?: FoodCategory.inferFromName(ingName)
ingredients.add(
MealFoodItem(
name = ingName,
weight = weight,
unit = unit,
category = explicitCat
)
)
}
}
val steps = mutableListOf<String>()
val stepsArr = obj.optJSONArray("steps")
if (stepsArr != null) {
for (j in 0 until stepsArr.length()) {
val step = stepsArr.optString(j, "").trim()
if (step.isNotBlank()) steps.add(step)
}
}
val effectiveCompleted = completedCats.ifEmpty {
ingredients.map { it.resolvedCategory() }
.filter { it.showInBenchmarks }
.distinct()
.take(4)
}
recipes.add(
RecipeSuggestion(
id = "idea_rec_${i}_${UUID.randomUUID().toString().take(6)}",
title = title,
categoryTag = tag,
prepTimeMinutes = prepTime,
servings = servings,
whyItFits = whyItFits,
completedCategories = effectiveCompleted,
ingredients = ingredients,
steps = steps
)
)
}
}
val discoveriesArray = root.optJSONArray("discoveries")
val discoveries = mutableListOf<DiscoverySuggestion>()
if (discoveriesArray != null) {
for (i in 0 until discoveriesArray.length()) {
val obj = discoveriesArray.optJSONObject(i) ?: continue
val foodName = obj.optString("foodName", "").trim()
if (foodName.isBlank()) continue
val category = FoodCategory.fromCode(obj.optString("category"))
?: FoodCategory.inferFromName(foodName)
val reason = obj.optString("benchmarkReason", "").trim()
val pairing = obj.optString("pairingIdea", "").trim()
discoveries.add(
DiscoverySuggestion(
id = "idea_disc_${i}_${UUID.randomUUID().toString().take(6)}",
foodName = foodName,
category = category,
benchmarkReason = reason,
pairingIdea = pairing
)
)
}
}
return GeneratedCulinaryBundle(
contextSummary = contextSummary,
recipes = recipes,
discoveries = discoveries
)
}
}
}
@@ -0,0 +1,143 @@
package com.example.domain
import com.example.data.model.FoodCategory
import com.example.data.model.MealEntry
import com.example.data.model.MealType
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
data class DailyBenchmarkGap(
val targetMealType: MealType,
val mealsLoggedTodayCount: Int,
val presentTodayCounts: Map<FoodCategory, Int>,
val expectedForMeal: List<FoodCategory>,
val priorityMissingCategories: List<FoodCategory>,
val allMissingTodayCategories: List<FoodCategory>,
val gentleSummary: String
)
/**
* Computes which dietary benchmark categories from the user's "Repères Alimentaires" sheet
* are already represented today vs. still gently available to complete for a target meal.
*/
object DailyBenchmarkAnalyzer {
private val coreDailyBenchmarkCategories = listOf(
FoodCategory.PROTEIN,
FoodCategory.VEGETABLE,
FoodCategory.STARCH,
FoodCategory.BREAD,
FoodCategory.FRUIT,
FoodCategory.CHEESE,
FoodCategory.DAIRY,
FoodCategory.NUTS,
FoodCategory.FAT_SEASONING
)
fun expectedCategoriesForMeal(mealType: MealType): List<FoodCategory> {
return when (mealType) {
MealType.BREAKFAST -> listOf(
FoodCategory.FRUIT,
FoodCategory.PROTEIN,
FoodCategory.BREAD,
FoodCategory.DAIRY,
FoodCategory.FAT_SEASONING
)
MealType.LUNCH -> listOf(
FoodCategory.PROTEIN,
FoodCategory.VEGETABLE,
FoodCategory.STARCH,
FoodCategory.CHEESE,
FoodCategory.BREAD,
FoodCategory.DAIRY,
FoodCategory.FAT_SEASONING
)
MealType.SNACK -> listOf(
FoodCategory.NUTS,
FoodCategory.FRUIT,
FoodCategory.DAIRY,
FoodCategory.PLEASURE
)
MealType.DINNER -> listOf(
FoodCategory.PROTEIN,
FoodCategory.VEGETABLE,
FoodCategory.STARCH,
FoodCategory.BREAD,
FoodCategory.DAIRY,
FoodCategory.FRUIT,
FoodCategory.FAT_SEASONING
)
}
}
fun analyzeToday(
meals: List<MealEntry>,
targetMealType: MealType,
customCategoryLookup: Map<String, FoodCategory> = emptyMap(),
today: LocalDate = LocalDate.now(),
zoneId: ZoneId = ZoneId.systemDefault()
): DailyBenchmarkGap {
val todayMeals = meals.filter { meal ->
Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId).toLocalDate() == today
}
val counts = mutableMapOf<FoodCategory, Int>()
todayMeals.forEach { meal ->
meal.parsedFoodItems().forEach { item ->
val cat = item.resolvedCategory(customCategoryLookup)
if (cat.showInBenchmarks) {
counts[cat] = (counts[cat] ?: 0) + 1
}
}
}
val expected = expectedCategoriesForMeal(targetMealType)
// Categories not yet represented today across core benchmarks
val allMissingToday = coreDailyBenchmarkCategories.filter { (counts[it] ?: 0) == 0 }
// Categories suited for this meal that are missing today OR expected at both main meals (protein, veg, starch)
val priorityMissing = expected.filter { cat ->
val countToday = counts[cat] ?: 0
when (cat) {
FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.STARCH -> {
if (targetMealType == MealType.LUNCH || targetMealType == MealType.DINNER) {
countToday < 2
} else {
countToday == 0
}
}
FoodCategory.FRUIT, FoodCategory.DAIRY -> countToday < 2
FoodCategory.PLEASURE -> false // Pleasure is always welcome, never marked as "missing"
else -> countToday == 0
}
}.ifEmpty {
// If everything for this meal is already well represented, surface any remaining daily benchmark
allMissingToday.take(4)
}
val gentleSummary = when {
todayMeals.isEmpty() -> {
"Aucun repas noté aujourd'hui : vos idées équilibreront votre ${targetMealType.displayName.lowercase()} selon vos repères."
}
priorityMissing.isEmpty() -> {
"Vos repères du jour sont déjà très variés ✨ Voici de quoi prolonger le plaisir en douceur."
}
else -> {
val labels = priorityMissing.take(4).joinToString(", ") { it.shortLabel }
"Pour votre ${targetMealType.displayName.lowercase()}, pistes douces à compléter : $labels."
}
}
return DailyBenchmarkGap(
targetMealType = targetMealType,
mealsLoggedTodayCount = todayMeals.size,
presentTodayCounts = counts.toMap(),
expectedForMeal = expected,
priorityMissingCategories = priorityMissing,
allMissingTodayCategories = allMissingToday,
gentleSummary = gentleSummary
)
}
}
@@ -26,6 +26,7 @@ sealed interface SheetsSyncResult {
val count: Int,
val foodsCount: Int,
val recipesCount: Int = 0,
val preferencesCount: Int = 0,
val timestamp: Long
) : SheetsSyncResult
@@ -37,7 +38,8 @@ sealed interface SheetsRestoreResult {
data class Success(
val mealsCount: Int,
val foodsCount: Int,
val recipesCount: Int = 0
val recipesCount: Int = 0,
val preferencesCount: Int = 0
) : SheetsRestoreResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsRestoreResult
@@ -132,14 +134,16 @@ class GoogleSheetsSyncUseCase(
uploadPhotosQuietly(token, photosFolderId, currentMeals, currentRecipes)
}
// 4. Sync meals, custom foods, and recipes to the 3 spreadsheet tabs
// 4. Sync meals, custom foods, recipes, and food preferences to the 4 spreadsheet tabs
val currentFoods = repository.getAllCustomFoodsSnapshot()
val currentPreferences = repository.getAllFoodPreferencesSnapshot()
var syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token,
spreadsheetId = id,
meals = currentMeals,
foods = currentFoods,
recipes = currentRecipes,
preferences = currentPreferences,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
@@ -154,6 +158,7 @@ class GoogleSheetsSyncUseCase(
meals = currentMeals,
foods = currentFoods,
recipes = currentRecipes,
preferences = currentPreferences,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
}
@@ -169,6 +174,7 @@ class GoogleSheetsSyncUseCase(
count = res.mealsCount,
foodsCount = res.foodsCount,
recipesCount = res.recipesCount,
preferencesCount = res.preferencesCount,
timestamp = res.timestamp
)
} else {
@@ -227,6 +233,7 @@ class GoogleSheetsSyncUseCase(
val currentMeals = repository.getAllMealsSnapshot()
val currentFoods = repository.getAllCustomFoodsSnapshot()
val currentRecipes = repository.getAllRecipesSnapshot()
val currentPreferences = repository.getAllFoodPreferencesSnapshot()
val photosFolderId = sheetsPrefs.photosFolderId
if (!photosFolderId.isNullOrBlank()) {
uploadPhotosQuietly(token, photosFolderId, currentMeals, currentRecipes)
@@ -238,6 +245,7 @@ class GoogleSheetsSyncUseCase(
meals = currentMeals,
foods = currentFoods,
recipes = currentRecipes,
preferences = currentPreferences,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
if (syncResult.isSuccess) {
@@ -311,16 +319,18 @@ class GoogleSheetsSyncUseCase(
}
val data = readResult.getOrThrow()
val (restoredMeals, restoredFoods, restoredRecipes) = repository.insertRestoredData(
val counts = repository.insertRestoredData(
meals = data.meals,
foods = data.foods,
recipes = data.recipes
recipes = data.recipes,
preferences = data.preferences
)
SheetsRestoreResult.Success(
mealsCount = restoredMeals,
foodsCount = restoredFoods,
recipesCount = restoredRecipes
mealsCount = counts.mealsCount,
foodsCount = counts.foodsCount,
recipesCount = counts.recipesCount,
preferencesCount = counts.preferencesCount
)
}
}
@@ -9,15 +9,22 @@ import androidx.lifecycle.viewModelScope
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.preferences.ThemePreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.CulinaryIdeasGenerator
import com.example.domain.DailyBenchmarkAnalyzer
import com.example.domain.DailyBenchmarkGap
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult
@@ -26,6 +33,7 @@ import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.GoogleSheetsAuthHelper
import com.example.widget.SatieaAppWidgetProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
@@ -40,6 +48,7 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.time.LocalTime
import java.time.ZoneId
import java.util.Locale
@@ -97,6 +106,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
// Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
private val csvExportUseCase = CsvExportUseCase(context)
private val culinaryIdeasGenerator by lazy { CulinaryIdeasGenerator() }
// UDF Event Channel
private val _uiEventChannel = Channel<UiEvent>(Channel.BUFFERED)
@@ -142,6 +152,50 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = emptyList()
)
val foodPreferences: StateFlow<List<FoodPreferenceEntry>> = repository.observeFoodPreferences()
.catch { error ->
if (error is CancellationException) throw error
emit(emptyList())
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
private val _selectedIdeaMealType = MutableStateFlow(
SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
)
val selectedIdeaMealType: StateFlow<MealType> = _selectedIdeaMealType.asStateFlow()
val dailyBenchmarkGap: StateFlow<DailyBenchmarkGap> = combine(
repository.observeMeals(),
repository.observeCustomFoods(),
_selectedIdeaMealType
) { meals, foods, mealType ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
DailyBenchmarkAnalyzer.analyzeToday(
meals = meals,
targetMealType = mealType,
customCategoryLookup = lookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = DailyBenchmarkAnalyzer.analyzeToday(
meals = emptyList(),
targetMealType = _selectedIdeaMealType.value
)
)
private val _suggestionUiState = MutableStateFlow<SuggestionUiState>(SuggestionUiState.Idle)
val suggestionUiState: StateFlow<SuggestionUiState> = _suggestionUiState.asStateFlow()
private val _savedSuggestionIds = MutableStateFlow<Set<String>>(emptySet())
val savedSuggestionIds: StateFlow<Set<String>> = _savedSuggestionIds.asStateFlow()
// Asynchronous background computation of WeeklyStats including food category diversity
val weeklyStats: StateFlow<WeeklyStats> = combine(
repository.observeMeals(),
@@ -354,6 +408,146 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
// ------------------------------------------------------------------------
// Food Preferences & AI Culinary Ideas
// ------------------------------------------------------------------------
fun setFoodPreference(
name: String,
status: FoodPreferenceStatus,
category: FoodCategory? = null,
note: String = "",
showFeedback: Boolean = true
) {
val cleanName = name.trim()
if (cleanName.isBlank()) return
viewModelScope.launch {
val result = repository.saveFoodPreference(
name = cleanName,
status = status,
category = category,
note = note
)
if (result.isSuccess) {
if (showFeedback) {
val label = when (status) {
FoodPreferenceStatus.LIKED -> "ajouté à vos aliments aimés"
FoodPreferenceStatus.DISLIKED -> "ajouté à vos aliments évités"
FoodPreferenceStatus.TO_TRY -> "ajouté à vos découvertes à tester"
}
emitEvent(UiEvent.ShowSnackbar("« $cleanName » $label ✨"))
}
triggerAutoSheetsSyncIfNeeded()
} else {
emitEvent(UiEvent.ShowSnackbar(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement"))
}
}
}
fun removeFoodPreference(slugId: String) {
viewModelScope.launch {
repository.deleteFoodPreference(slugId)
triggerAutoSheetsSyncIfNeeded()
}
}
fun setIdeaMealType(mealType: MealType) {
_selectedIdeaMealType.value = mealType
}
fun generateCulinaryIdeas(cravingNote: String = "") {
viewModelScope.launch {
_suggestionUiState.value = SuggestionUiState.Loading
val targetType = _selectedIdeaMealType.value
val currentMeals = repository.getAllMealsSnapshot()
val lookup = customFoods.value.associate {
it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory()
}
val gap = DailyBenchmarkAnalyzer.analyzeToday(
meals = currentMeals,
targetMealType = targetType,
customCategoryLookup = lookup
)
val currentPrefs = foodPreferences.value
val existingTitles = recipes.value.map { it.title }
val result = culinaryIdeasGenerator.generateIdeas(
preferences = currentPrefs,
benchmarkGap = gap,
cravingNote = cravingNote.trim(),
existingRecipeTitles = existingTitles
)
result.fold(
onSuccess = { bundle ->
_savedSuggestionIds.value = emptySet()
_suggestionUiState.value = SuggestionUiState.Success(
recipes = bundle.recipes,
discoveries = bundle.discoveries,
targetMealType = targetType,
contextSummary = bundle.contextSummary.ifBlank { gap.gentleSummary }
)
},
onFailure = { error ->
_suggestionUiState.value = SuggestionUiState.Error(
error.localizedMessage ?: "Impossible de générer des idées pour le moment."
)
}
)
}
}
fun saveSuggestedRecipe(suggestion: RecipeSuggestion) {
viewModelScope.launch {
val recipeEntry = suggestion.toRecipeEntry()
enrichCatalogWithFoodItems(suggestion.ingredients)
val result = repository.saveRecipe(recipeEntry)
if (result.isSuccess) {
_savedSuggestionIds.value = _savedSuggestionIds.value + suggestion.id
emitEvent(UiEvent.ShowSnackbar("« ${suggestion.title} » enregistrée dans Mes recettes ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
emitEvent(UiEvent.ShowSnackbar("Erreur lors de l'enregistrement de la recette"))
}
}
}
fun likeSuggestedRecipeIngredients(suggestion: RecipeSuggestion) {
val dislikedSlugs = foodPreferences.value
.filter { it.status == FoodPreferenceStatus.DISLIKED }
.map { it.slugId }
.toSet()
val candidates = suggestion.ingredients
.filter { it.resolvedCategory() != FoodCategory.FAT_SEASONING && it.resolvedCategory() != FoodCategory.OTHER }
.take(4)
if (candidates.isEmpty()) return
viewModelScope.launch {
var addedCount = 0
candidates.forEach { item ->
val slug = FoodPreferenceEntry.buildSlugId(item.name)
if (slug !in dislikedSlugs) {
repository.saveFoodPreference(
name = item.name,
status = FoodPreferenceStatus.LIKED,
category = item.resolvedCategory()
)
addedCount++
}
}
if (addedCount > 0) {
emitEvent(
UiEvent.ShowSnackbar(
"$addedCount ingrédient${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} à vos aliments aimés ♥"
)
)
triggerAutoSheetsSyncIfNeeded()
}
}
}
// ------------------------------------------------------------------------
// Google Drive Account & Sheets Sync
// ------------------------------------------------------------------------
@@ -395,6 +589,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
add("${result.count} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
if (result.preferencesCount > 0) add("${result.preferencesCount} goûts")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Sauvegardé sur Google Drive ($summaryParts) 📊"))
}
@@ -428,6 +623,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
add("${result.mealsCount} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
if (result.preferencesCount > 0) add("${result.preferencesCount} goûts")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Restauration réussie ✨ : $summaryParts"))
}
@@ -0,0 +1,822 @@
package com.example.ui.recipes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
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.PaddingValues
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.lazy.LazyListScope
import androidx.compose.foundation.lazy.LazyRow
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.Block
import androidx.compose.material.icons.filled.BookmarkAdded
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
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.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DiscoverySuggestion
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.MealType
import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.domain.DailyBenchmarkGap
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
import com.example.ui.common.isSatieaDarkTheme
fun LazyListScope.ideasAndTastesItems(
preferences: List<FoodPreferenceEntry>,
customFoods: List<CustomFoodEntry>,
selectedMealType: MealType,
benchmarkGap: DailyBenchmarkGap,
suggestionUiState: SuggestionUiState,
savedSuggestionIds: Set<String>,
cravingNote: String,
onCravingNoteChange: (String) -> Unit,
onSelectMealType: (MealType) -> Unit,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit,
onGenerateIdeas: () -> Unit,
onSaveSuggestedRecipe: (RecipeSuggestion) -> Unit,
onLogSuggestedRecipe: (RecipeSuggestion, MealType) -> Unit,
onLikeRecipeIngredients: (RecipeSuggestion) -> Unit
) {
// 1. Taste Profile Editor Card
item(key = "taste_profile_card") {
TasteProfileCard(
preferences = preferences,
customFoods = customFoods,
onSavePreference = onSavePreference,
onRemovePreference = onRemovePreference
)
}
// 2. Daily Benchmarks Context & Generator Card
item(key = "benchmark_generator_card") {
BenchmarkGeneratorCard(
selectedMealType = selectedMealType,
benchmarkGap = benchmarkGap,
cravingNote = cravingNote,
isLoading = suggestionUiState is SuggestionUiState.Loading,
onCravingNoteChange = onCravingNoteChange,
onSelectMealType = onSelectMealType,
onGenerateIdeas = onGenerateIdeas
)
}
// 3. Results Section
when (suggestionUiState) {
is SuggestionUiState.Idle -> {
item(key = "ideas_idle_hint") {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Text(
text = "Votre inspiration sur mesure",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Satiéa croise vos aliments aimés, vos exclusions et vos repères manquants du jour pour imaginer des recettes simples et de nouvelles idées à goûter — sans calcul de calories.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
is SuggestionUiState.Loading -> {
item(key = "ideas_loading_card") {
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("ideas_loading_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f)
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
CircularProgressIndicator(
modifier = Modifier.size(28.dp),
strokeWidth = 3.dp,
color = MaterialTheme.colorScheme.primary
)
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Préparation de vos idées…",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Analyse de vos goûts et de vos repères pour ce ${selectedMealType.displayName.lowercase()}.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
is SuggestionUiState.Error -> {
item(key = "ideas_error_card") {
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("ideas_error_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.65f)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.onErrorContainer
)
Text(
text = "Génération interrompue",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onErrorContainer,
fontWeight = FontWeight.Bold
)
}
Text(
text = suggestionUiState.message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer
)
FilledTonalButton(
onClick = onGenerateIdeas,
modifier = Modifier.testTag("ideas_retry_button")
) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Réessayer")
}
}
}
}
}
is SuggestionUiState.Success -> {
if (suggestionUiState.contextSummary.isNotBlank()) {
item(key = "ideas_context_summary") {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = suggestionUiState.contextSummary,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(14.dp)
)
}
}
}
if (suggestionUiState.recipes.isNotEmpty()) {
item(key = "ideas_recipes_header") {
Text(
text = "Idées de recettes sur mesure",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 4.dp)
)
}
items(suggestionUiState.recipes, key = { it.id }) { suggestion ->
SuggestedRecipeCard(
suggestion = suggestion,
isSaved = suggestion.id in savedSuggestionIds,
onSaveToBook = { onSaveSuggestedRecipe(suggestion) },
onLogToJournal = { onLogSuggestedRecipe(suggestion, suggestionUiState.targetMealType) },
onLikeIngredients = { onLikeRecipeIngredients(suggestion) }
)
}
}
if (suggestionUiState.discoveries.isNotEmpty()) {
item(key = "ideas_discoveries_header") {
Column(modifier = Modifier.padding(top = 6.dp)) {
Text(
text = "Nouvelles découvertes à tester",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = "Pour varier vos assiettes et enrichir vos repères en douceur",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
items(suggestionUiState.discoveries, key = { it.id }) { discovery ->
val slug = FoodPreferenceEntry.buildSlugId(discovery.foodName)
val existingStatus = preferences.firstOrNull { it.slugId == slug }?.status
DiscoverySuggestionCard(
discovery = discovery,
currentStatus = existingStatus,
onSetStatus = { newStatus ->
onSavePreference(discovery.foodName, newStatus, discovery.category)
}
)
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun BenchmarkGeneratorCard(
selectedMealType: MealType,
benchmarkGap: DailyBenchmarkGap,
cravingNote: String,
isLoading: Boolean,
onCravingNoteChange: (String) -> Unit,
onSelectMealType: (MealType) -> Unit,
onGenerateIdeas: () -> Unit
) {
val isDark = isSatieaDarkTheme()
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("benchmark_generator_card"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.3f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Repères du jour à compléter",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = benchmarkGap.gentleSummary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Meal type selector row
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(MealType.entries, key = { it.name }) { type ->
FilterChip(
selected = selectedMealType == type,
onClick = { onSelectMealType(type) },
label = { Text(type.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
),
modifier = Modifier.testTag("idea_meal_type_${type.name.lowercase()}")
)
}
}
// Visual badges of priority categories to complete
if (benchmarkGap.priorityMissingCategories.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Pistes ciblées pour ce repas :",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.SemiBold
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
benchmarkGap.priorityMissingCategories.forEach { cat ->
Surface(
shape = RoundedCornerShape(10.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 7.dp)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = cat.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
}
// Optional craving / mood input
OutlinedTextField(
value = cravingNote,
onValueChange = { if (it.length <= 100) onCravingNoteChange(it) },
modifier = Modifier
.fillMaxWidth()
.testTag("idea_craving_input"),
placeholder = { Text("Envie du moment (optionnel : rapide 15 min, chaud, sucré-salé…)") },
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
// Primary Generate CTA
Button(
onClick = onGenerateIdeas,
enabled = !isLoading,
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.testTag("generate_ideas_button"),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.onPrimary
)
Spacer(modifier = Modifier.width(10.dp))
Text("Recherche d'idées en cours…")
} else {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Proposer des idées & découvertes",
style = MaterialTheme.typography.labelLarge
)
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SuggestedRecipeCard(
suggestion: RecipeSuggestion,
isSaved: Boolean,
onSaveToBook: () -> Unit,
onLogToJournal: () -> Unit,
onLikeIngredients: () -> Unit
) {
val isDark = isSatieaDarkTheme()
var stepsExpanded by rememberSaveable(suggestion.id) { mutableStateOf(false) }
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("suggested_recipe_card_${suggestion.id}"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
// Tag + Time + Servings row
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Surface(
shape = RoundedCornerShape(9.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = suggestion.categoryTag.displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(14.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${suggestion.prepTimeMinutes} min",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.People,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(14.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${suggestion.servings} portion${if (suggestion.servings > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Text(
text = suggestion.title,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
if (suggestion.whyItFits.isNotBlank()) {
Text(
text = suggestion.whyItFits,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Completed dietary benchmark badges
if (suggestion.completedCategories.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
suggestion.completedCategories.forEach { cat ->
Surface(
shape = RoundedCornerShape(9.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 7.dp)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = cat.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
// Color-coded ingredients list
if (suggestion.ingredients.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
text = "Ingrédients (${suggestion.servings} portion${if (suggestion.servings > 1) "s" else ""})",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
suggestion.ingredients.forEach { item ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FoodCategoryColorDot(category = item.resolvedCategory(), size = 8.dp)
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
}
// Expandable steps
if (suggestion.steps.isNotEmpty()) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { stepsExpanded = !stepsExpanded }
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = if (stepsExpanded) "Masquer les étapes" else "Voir les ${suggestion.steps.size} étapes de préparation",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Icon(
imageVector = if (stepsExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
}
AnimatedVisibility(visible = stepsExpanded) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
suggestion.steps.forEachIndexed { idx, step ->
Text(
text = "${idx + 1}. $step",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f)
)
}
}
}
}
// Action buttons row
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
FilledTonalButton(
onClick = onSaveToBook,
enabled = !isSaved,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("save_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = if (isSaved) Icons.Default.BookmarkAdded else Icons.Default.BookmarkBorder,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(if (isSaved) "Enregistrée ✓" else "Enregistrer")
}
Button(
onClick = onLogToJournal,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("log_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Noter au journal")
}
OutlinedButton(
onClick = onLikeIngredients,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("like_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Aimer")
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun DiscoverySuggestionCard(
discovery: DiscoverySuggestion,
currentStatus: FoodPreferenceStatus?,
onSetStatus: (FoodPreferenceStatus) -> Unit
) {
val isDark = isSatieaDarkTheme()
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("discovery_card_${discovery.id}"),
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, discovery.category.badgeBorderColor(isDark).copy(alpha = 0.7f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
FoodCategoryColorDot(category = discovery.category, size = 11.dp)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = discovery.foodName,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
}
Surface(
shape = RoundedCornerShape(8.dp),
color = discovery.category.badgeContainerColor(isDark)
) {
Text(
text = discovery.category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = discovery.category.badgeTextColor(isDark),
fontWeight = FontWeight.Medium,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
}
if (discovery.benchmarkReason.isNotBlank()) {
Text(
text = discovery.benchmarkReason,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (discovery.pairingIdea.isNotBlank()) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "Idée simple : ${discovery.pairingIdea}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp)
)
}
}
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
val isToTry = currentStatus == FoodPreferenceStatus.TO_TRY
val isLiked = currentStatus == FoodPreferenceStatus.LIKED
val isDisliked = currentStatus == FoodPreferenceStatus.DISLIKED
FilledTonalButton(
onClick = { onSetStatus(FoodPreferenceStatus.TO_TRY) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = if (isToTry) Icons.Default.Check else Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(if (isToTry) "À tester ✓" else "+ À tester")
}
OutlinedButton(
onClick = { onSetStatus(FoodPreferenceStatus.LIKED) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = if (isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(if (isLiked) "Aimé ✓" else "J'aime")
}
TextButton(
onClick = { onSetStatus(FoodPreferenceStatus.DISLIKED) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = Icons.Default.Block,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(if (isDisliked) "Évité ✓" else "J'évite")
}
}
}
}
}
@@ -25,6 +25,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
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.People
import androidx.compose.material.icons.filled.Schedule
@@ -59,8 +60,14 @@ import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.domain.DailyBenchmarkGap
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
@@ -68,15 +75,34 @@ import com.example.ui.common.badgeTextColor
import com.example.ui.common.isSatieaDarkTheme
import java.util.Locale
private enum class RecipesSubTab(val label: String) {
BOOK("Mes recettes"),
IDEAS("Idées & Goûts")
}
@Composable
fun RecipesScreen(
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
foodPreferences: List<FoodPreferenceEntry>,
selectedIdeaMealType: MealType,
dailyBenchmarkGap: DailyBenchmarkGap,
suggestionUiState: SuggestionUiState,
savedSuggestionIds: Set<String>,
onAddRecipeClick: () -> Unit,
onRecipeClick: (RecipeEntry) -> Unit
onRecipeClick: (RecipeEntry) -> Unit,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit,
onSelectIdeaMealType: (MealType) -> Unit,
onGenerateIdeas: (cravingNote: String) -> Unit,
onSaveSuggestedRecipe: (RecipeSuggestion) -> Unit,
onLogSuggestedRecipe: (RecipeSuggestion, MealType) -> Unit,
onLikeSuggestedRecipeIngredients: (RecipeSuggestion) -> Unit
) {
var activeSubTab by rememberSaveable { mutableStateOf(RecipesSubTab.BOOK) }
var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedTag by rememberSaveable { mutableStateOf<String?>(null) }
var cravingNote by rememberSaveable { mutableStateOf("") }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
@@ -113,25 +139,119 @@ fun RecipesScreen(
) {
// Header
item {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Column {
Text(
text = "Mon Recueil de Recettes",
text = if (activeSubTab == RecipesSubTab.BOOK) {
"Mon Recueil de Recettes"
} else {
"Idées & Mes Goûts"
},
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = if (recipes.isEmpty()) {
text = if (activeSubTab == RecipesSubTab.BOOK) {
if (recipes.isEmpty()) {
"Conservez vos recettes préférées et notez-les en 1 clic"
} else {
"${recipes.size} recette${if (recipes.size > 1) "s" else ""} • ingrédients colorés & portions ajustables"
}
} else {
"Vos envies & vos repères alimentaires du jour réunis"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
// Segmented sub-tab switcher
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
modifier = Modifier
.fillMaxWidth()
.testTag("recipes_subtab_switcher")
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
RecipesSubTab.entries.forEach { tab ->
val isSelected = activeSubTab == tab
Surface(
onClick = { activeSubTab = tab },
modifier = Modifier
.weight(1f)
.height(48.dp)
.testTag("recipes_subtab_${tab.name.lowercase()}"),
shape = RoundedCornerShape(12.dp),
color = if (isSelected) {
MaterialTheme.colorScheme.surface
} else {
MaterialTheme.colorScheme.surface.copy(alpha = 0f)
},
tonalElevation = if (isSelected) 3.dp else 0.dp
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = if (tab == RecipesSubTab.BOOK) {
Icons.AutoMirrored.Filled.MenuBook
} else {
Icons.Default.AutoAwesome
},
contentDescription = null,
tint = if (isSelected) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
modifier = Modifier.size(17.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = tab.label,
style = MaterialTheme.typography.labelLarge,
color = if (isSelected) {
MaterialTheme.colorScheme.onSurface
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
)
}
}
}
}
}
}
}
if (activeSubTab == RecipesSubTab.IDEAS) {
ideasAndTastesItems(
preferences = foodPreferences,
customFoods = customFoods,
selectedMealType = selectedIdeaMealType,
benchmarkGap = dailyBenchmarkGap,
suggestionUiState = suggestionUiState,
savedSuggestionIds = savedSuggestionIds,
cravingNote = cravingNote,
onCravingNoteChange = { cravingNote = it },
onSelectMealType = onSelectIdeaMealType,
onSavePreference = onSavePreference,
onRemovePreference = onRemovePreference,
onGenerateIdeas = { onGenerateIdeas(cravingNote) },
onSaveSuggestedRecipe = onSaveSuggestedRecipe,
onLogSuggestedRecipe = onLogSuggestedRecipe,
onLikeRecipeIngredients = onLikeSuggestedRecipeIngredients
)
} else {
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
@@ -243,7 +363,9 @@ fun RecipesScreen(
}
}
}
}
if (activeSubTab == RecipesSubTab.BOOK) {
FloatingActionButton(
onClick = onAddRecipeClick,
modifier = Modifier
@@ -262,6 +384,7 @@ fun RecipesScreen(
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
@@ -0,0 +1,523 @@
package com.example.ui.recipes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
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.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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
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.AutoAwesome
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
import com.example.ui.common.badgeTextColor
import com.example.ui.common.isSatieaDarkTheme
import java.util.Locale
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun TasteProfileCard(
preferences: List<FoodPreferenceEntry>,
customFoods: List<CustomFoodEntry>,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit
) {
val isDark = isSatieaDarkTheme()
var activeStatus by rememberSaveable { mutableStateOf(FoodPreferenceStatus.LIKED) }
var inputText by rememberSaveable { mutableStateOf("") }
var manualCategoryOverride by remember { mutableStateOf<FoodCategory?>(null) }
var showCategoryPicker by remember { mutableStateOf(false) }
val customLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val inferredCategory = remember(inputText, customLookup) {
if (inputText.isBlank()) FoodCategory.OTHER
else FoodCategory.inferFromName(inputText, customLookup)
}
val effectiveCategory = manualCategoryOverride ?: inferredCategory
val likedList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.LIKED } }
val dislikedList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.DISLIKED } }
val toTryList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.TO_TRY } }
val activeList = when (activeStatus) {
FoodPreferenceStatus.LIKED -> likedList
FoodPreferenceStatus.DISLIKED -> dislikedList
FoodPreferenceStatus.TO_TRY -> toTryList
}
val allSavedSlugs = remember(preferences) { preferences.map { it.slugId }.toSet() }
val autocompleteSuggestions = remember(inputText, customFoods, allSavedSlugs) {
val query = inputText.trim().lowercase(Locale.FRENCH)
if (query.length < 2) emptyList()
else {
val pool = buildList {
customFoods.forEach { add(it.name to it.resolvedCategory()) }
DefaultFoodCatalog.builtInFoods.forEach { add(it.name to it.category) }
}.distinctBy { it.first.lowercase(Locale.FRENCH) }
pool.filter { (name, _) ->
name.lowercase(Locale.FRENCH).contains(query) &&
FoodPreferenceEntry.buildSlugId(name) !in allSavedSlugs
}.take(5)
}
}
fun submitInput() {
val cleaned = inputText.trim()
if (cleaned.isNotBlank()) {
onSavePreference(cleaned, activeStatus, effectiveCategory)
inputText = ""
manualCategoryOverride = null
showCategoryPicker = false
}
}
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("taste_profile_card"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Mes goûts alimentaires",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Indiquez ce que vous aimez, évitez ou souhaitez découvrir",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Status switcher pills with live counters
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
StatusTabPill(
label = "J'aime",
count = likedList.size,
icon = Icons.Default.Favorite,
selected = activeStatus == FoodPreferenceStatus.LIKED,
onClick = { activeStatus = FoodPreferenceStatus.LIKED },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_liked")
)
StatusTabPill(
label = "J'évite",
count = dislikedList.size,
icon = Icons.Default.Block,
selected = activeStatus == FoodPreferenceStatus.DISLIKED,
onClick = { activeStatus = FoodPreferenceStatus.DISLIKED },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_disliked")
)
StatusTabPill(
label = "À tester",
count = toTryList.size,
icon = Icons.Default.AutoAwesome,
selected = activeStatus == FoodPreferenceStatus.TO_TRY,
onClick = { activeStatus = FoodPreferenceStatus.TO_TRY },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_to_try")
)
}
// Quick-add input row with live category color dot
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = inputText,
onValueChange = {
if (it.length <= 60) {
inputText = it
manualCategoryOverride = null
}
},
modifier = Modifier
.weight(1f)
.testTag("taste_food_input"),
placeholder = {
Text(
text = when (activeStatus) {
FoodPreferenceStatus.LIKED -> "Ajouter un aliment aimé (ex. saumon, comté…)"
FoodPreferenceStatus.DISLIKED -> "Aliment évité ou allergie…"
FoodPreferenceStatus.TO_TRY -> "Aliment à découvrir…"
},
maxLines = 1
)
},
leadingIcon = {
Box(
modifier = Modifier
.minimumInteractiveComponentSize()
.clickable { showCategoryPicker = !showCategoryPicker },
contentAlignment = Alignment.Center
) {
FoodCategoryColorDot(category = effectiveCategory, size = 12.dp)
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { submitInput() })
)
FilledIconButton(
onClick = { submitInput() },
enabled = inputText.isNotBlank(),
modifier = Modifier
.size(48.dp)
.testTag("taste_add_button"),
colors = IconButtonDefaults.filledIconButtonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Ajouter cet aliment"
)
}
}
// Optional category override strip
AnimatedVisibility(visible = showCategoryPicker || inputText.isNotBlank()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Catégorie : ${effectiveCategory.displayName} (appuyez pour modifier)",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
if (showCategoryPicker) {
LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
items(FoodCategory.entries, key = { it.code }) { cat ->
FilterChip(
selected = effectiveCategory == cat,
onClick = {
manualCategoryOverride = cat
showCategoryPicker = false
},
leadingIcon = { FoodCategoryColorDot(category = cat, size = 8.dp) },
label = { Text(cat.shortLabel, style = MaterialTheme.typography.labelSmall) }
)
}
}
}
}
}
// Autocomplete suggestions row
if (autocompleteSuggestions.isNotEmpty()) {
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(autocompleteSuggestions, key = { it.first }) { (name, cat) ->
Surface(
shape = RoundedCornerShape(12.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark)),
modifier = Modifier.clickable {
onSavePreference(name, activeStatus, cat)
inputText = ""
manualCategoryOverride = null
showCategoryPicker = false
}
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "+ $name",
style = MaterialTheme.typography.labelMedium,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
// Current preferences list for active tab
if (activeList.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
activeList.forEach { pref ->
PreferenceFoodChip(
entry = pref,
isDark = isDark,
onChangeStatus = { newStatus ->
onSavePreference(pref.name, newStatus, pref.category)
},
onRemove = { onRemovePreference(pref.slugId) }
)
}
}
} else {
// Friendly empty state + quick starter picks for LIKED
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = when (activeStatus) {
FoodPreferenceStatus.LIKED -> "Ajoutez quelques aliments que vous aimez (ou choisissez ci-dessous) :"
FoodPreferenceStatus.DISLIKED -> "Aucun aliment évité renseigné. Vos allergies ou aversions seront strictement exclues."
FoodPreferenceStatus.TO_TRY -> "Aucune découverte en attente. Générez des idées ci-dessous pour en ajouter en 1 clic !"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
if (activeStatus == FoodPreferenceStatus.LIKED) {
val starterPicks = remember(allSavedSlugs) {
FoodPreferenceEntry.quickStartLikedPicks
.filter { FoodPreferenceEntry.buildSlugId(it.first) !in allSavedSlugs }
.take(10)
}
if (starterPicks.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
starterPicks.forEach { (foodName, cat) ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark).copy(alpha = 0.6f)),
modifier = Modifier.clickable {
onSavePreference(foodName, FoodPreferenceStatus.LIKED, cat)
}
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 7.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "+ $foodName",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
}
}
}
}
}
}
}
}
@Composable
private fun StatusTabPill(
label: String,
count: Int,
icon: androidx.compose.ui.graphics.vector.ImageVector,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val containerColor = if (selected) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)
}
val contentColor = if (selected) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
Surface(
onClick = onClick,
modifier = modifier.height(48.dp),
shape = RoundedCornerShape(14.dp),
color = containerColor,
border = if (selected) BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)) else null
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = contentColor,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "$label ($count)",
style = MaterialTheme.typography.labelMedium,
color = contentColor,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
maxLines = 1
)
}
}
}
@Composable
private fun PreferenceFoodChip(
entry: FoodPreferenceEntry,
isDark: Boolean,
onChangeStatus: (FoodPreferenceStatus) -> Unit,
onRemove: () -> Unit
) {
var menuExpanded by remember { mutableStateOf(false) }
Box {
Surface(
shape = RoundedCornerShape(12.dp),
color = entry.category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, entry.category.badgeBorderColor(isDark)),
modifier = Modifier.clickable { menuExpanded = true }
) {
Row(
modifier = Modifier.padding(start = 10.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = entry.category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = entry.name,
style = MaterialTheme.typography.labelMedium,
color = entry.category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(4.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${entry.name}",
tint = entry.category.badgeTextColor(isDark).copy(alpha = 0.75f),
modifier = Modifier
.size(20.dp)
.clickable { onRemove() }
.padding(2.dp)
)
}
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false }
) {
if (entry.status != FoodPreferenceStatus.LIKED) {
DropdownMenuItem(
text = { Text("Déplacer dans « J'aime »") },
leadingIcon = { Icon(Icons.Default.Favorite, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.LIKED)
}
)
}
if (entry.status != FoodPreferenceStatus.TO_TRY) {
DropdownMenuItem(
text = { Text("Déplacer dans « À tester »") },
leadingIcon = { Icon(Icons.Default.AutoAwesome, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.TO_TRY)
}
)
}
if (entry.status != FoodPreferenceStatus.DISLIKED) {
DropdownMenuItem(
text = { Text("Déplacer dans « J'évite »") },
leadingIcon = { Icon(Icons.Default.Block, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.DISLIKED)
}
)
}
DropdownMenuItem(
text = { Text("Supprimer") },
leadingIcon = { Icon(Icons.Default.Close, contentDescription = null) },
onClick = {
menuExpanded = false
onRemove()
}
)
}
}
}
@@ -0,0 +1,74 @@
package com.example.util
import android.content.Context
import android.content.Intent
import android.util.Log
import com.example.BuildConfig
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import com.google.firebase.appcheck.recaptcha.RecaptchaAppCheckProviderFactory
private const val TAG = "AppCheckInit"
private const val DEBUG_TOKEN_EXTRA = "FIREBASE_APPCHECK_DEBUG_TOKEN"
private const val DEBUG_STORE_PREFIX = "com.google.firebase.appcheck.debug.store."
private const val DEBUG_SECRET_KEY = "com.google.firebase.appcheck.debug.DEBUG_SECRET"
private const val RECAPTCHA_SITE_KEY_RES = "recaptcha_site_key"
/**
* Configures Firebase App Check for Firebase AI Logic attestation.
* Must be invoked at the start of MainActivity.onCreate() before UI, ViewModels, or Firebase calls.
*/
fun configureAppCheck(context: Context, intent: Intent?) {
try {
if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(context)
}
if (BuildConfig.DEBUG) {
val debugToken = intent?.getStringExtra(DEBUG_TOKEN_EXTRA)
if (!debugToken.isNullOrEmpty()) {
val persistenceKey = FirebaseApp.getInstance().persistenceKey
val prefs = context.getSharedPreferences(
"$DEBUG_STORE_PREFIX$persistenceKey",
Context.MODE_PRIVATE
)
// Synchronous commit() ensures the secret is written before DebugAppCheckProviderFactory reads it.
prefs.edit()
.putString(DEBUG_SECRET_KEY, debugToken)
.commit()
Log.d(TAG, "App Check debug secret configured successfully.")
} else {
Log.w(TAG, "No debug token found in Intent extra.")
}
FirebaseAppCheck.getInstance().installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance()
)
Log.d(TAG, "DebugAppCheckProviderFactory installed.")
} else {
val resId = context.resources.getIdentifier(
RECAPTCHA_SITE_KEY_RES,
"string",
context.packageName
)
if (resId != 0) {
val siteKey = context.getString(resId)
if (siteKey.isNotBlank()) {
FirebaseAppCheck.getInstance().installAppCheckProviderFactory(
RecaptchaAppCheckProviderFactory.getInstance(siteKey)
)
Log.d(TAG, "RecaptchaAppCheckProviderFactory installed.")
} else {
Log.e(TAG, "recaptcha_site_key resource string is blank.")
}
} else {
Log.e(TAG, "recaptcha_site_key string resource not found in package.")
}
}
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize Firebase App Check", e)
}
}
@@ -1,7 +1,9 @@
package com.example.util
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalFoodPreferenceEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
@@ -48,6 +50,14 @@ object GoogleSheetsDataFormatter {
"Photo"
)
val HEADERS_PREFERENCES: List<String> = listOf(
"Aliment",
"Statut",
"Catégorie",
"Note",
"Date de mise à jour"
)
// Backward-compatibility alias
val HEADERS = HEADERS_MEALS
@@ -173,6 +183,37 @@ object GoogleSheetsDataFormatter {
return rows
}
fun formatPreferencesToRows(
preferences: List<LocalFoodPreferenceEntity>,
zoneId: ZoneId = ZoneId.systemDefault()
): List<List<Any>> {
val rows = mutableListOf<List<Any>>()
rows.add(HEADERS_PREFERENCES)
val sorted = preferences.sortedWith(
compareBy<LocalFoodPreferenceEntity> { it.resolvedStatus().ordinal }
.thenBy { it.name.lowercase(Locale.FRENCH) }
)
for (pref in sorted) {
val dateStr = try {
val zdt = Instant.ofEpochMilli(pref.updatedAt).atZone(zoneId)
dateTimeFormatter.format(zdt)
} catch (_: Exception) {
""
}
rows.add(
listOf(
pref.name,
pref.resolvedStatus().displayName,
pref.resolvedCategory().displayName,
pref.note.replace("\r\n", " ").replace("\n", " ").trim(),
dateStr
)
)
}
return rows
}
fun parseRowsToMeals(rows: List<List<Any>>, zoneId: ZoneId = ZoneId.systemDefault()): List<MealEntry> {
if (rows.size <= 1) return emptyList()
@@ -297,6 +338,32 @@ object GoogleSheetsDataFormatter {
return recipes
}
fun parseRowsToPreferences(rows: List<List<Any>>): List<LocalFoodPreferenceEntity> {
if (rows.size <= 1) return emptyList()
val prefs = mutableListOf<LocalFoodPreferenceEntity>()
for (i in 1 until rows.size) {
val row = rows[i]
if (row.isEmpty()) continue
val name = row.getOrNull(0)?.toString()?.trim().orEmpty()
if (name.isBlank()) continue
val statusRaw = row.getOrNull(1)?.toString()?.trim().orEmpty()
val status = FoodPreferenceStatus.fromString(statusRaw)
val categoryRaw = row.getOrNull(2)?.toString()?.trim().orEmpty()
val category = parseFoodCategory(categoryRaw) ?: FoodCategory.inferFromName(name)
val note = row.getOrNull(3)?.toString()?.trim().orEmpty()
prefs.add(
LocalFoodPreferenceEntity.create(
name = name,
status = status,
category = category,
note = note
)
)
}
return prefs
}
private fun parseRecipeIngredientsCell(cell: String): List<MealFoodItem> {
if (cell.isBlank()) return emptyList()
return cell.split(";").mapNotNull { token ->
@@ -2,6 +2,7 @@ package com.example.util
import android.util.Log
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalFoodPreferenceEntity
import com.example.data.model.MealEntry
import com.example.data.model.RecipeEntry
import kotlinx.coroutines.Dispatchers
@@ -21,13 +22,15 @@ data class GoogleSheetsSyncResult(
val mealsCount: Int,
val foodsCount: Int = 0,
val recipesCount: Int = 0,
val preferencesCount: Int = 0,
val timestamp: Long = System.currentTimeMillis()
)
data class SpreadsheetRestoreData(
val meals: List<MealEntry>,
val foods: List<LocalCustomFoodEntity>,
val recipes: List<RecipeEntry> = emptyList()
val recipes: List<RecipeEntry> = emptyList(),
val preferences: List<LocalFoodPreferenceEntity> = emptyList()
)
class AuthExpiredException(message: String) : IllegalStateException(message)
@@ -39,6 +42,7 @@ object GoogleSheetsSyncService {
const val SHEET_TAB_MEALS = "Journal des repas"
const val SHEET_TAB_FOODS = "Mes plats et aliments"
const val SHEET_TAB_RECIPES = "Mes recettes"
const val SHEET_TAB_PREFERENCES = "Mes goûts"
// Backward compatibility
const val SHEET_TAB_TITLE = SHEET_TAB_MEALS
@@ -117,13 +121,18 @@ object GoogleSheetsSyncService {
}
}
// 3. Not found: create a new Google Sheet with all 3 tabs (Meals + Custom Foods + Recipes)
// 3. Not found: create a new Google Sheet with all 4 tabs
val createPayload = JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SPREADSHEET_TITLE)
})
put("sheets", JSONArray().apply {
listOf(SHEET_TAB_MEALS, SHEET_TAB_FOODS, SHEET_TAB_RECIPES).forEach { tabTitle ->
listOf(
SHEET_TAB_MEALS,
SHEET_TAB_FOODS,
SHEET_TAB_RECIPES,
SHEET_TAB_PREFERENCES
).forEach { tabTitle ->
put(JSONObject().apply {
put("properties", JSONObject().apply {
put("title", tabTitle)
@@ -201,6 +210,7 @@ object GoogleSheetsSyncService {
var hasMealsTab = false
var hasFoodsTab = false
var hasRecipesTab = false
var hasPreferencesTab = false
var legacySheetIdToRename: Int? = null
val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1")
@@ -214,6 +224,7 @@ object GoogleSheetsSyncService {
title == SHEET_TAB_MEALS -> hasMealsTab = true
title == SHEET_TAB_FOODS -> hasFoodsTab = true
title == SHEET_TAB_RECIPES -> hasRecipesTab = true
title == SHEET_TAB_PREFERENCES -> hasPreferencesTab = true
legacySheetIdToRename == null && legacyTabNames.contains(title) && sId != -1 -> {
legacySheetIdToRename = sId
}
@@ -277,6 +288,20 @@ object GoogleSheetsSyncService {
})
}
// 4. Ensure "Mes goûts"
if (!hasPreferencesTab) {
batchRequests.put(JSONObject().apply {
put("addSheet", JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_PREFERENCES)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
})
})
})
}
if (batchRequests.length() > 0) {
val batchPayload = JSONObject().apply {
put("requests", batchRequests)
@@ -310,10 +335,11 @@ object GoogleSheetsSyncService {
meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity>,
recipes: List<RecipeEntry> = emptyList(),
preferences: List<LocalFoodPreferenceEntity> = emptyList(),
photoLinkProvider: (String) -> String? = { null }
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
try {
// Ensure all 3 tabs exist and legacy tabs are migrated before writing
// Ensure all 4 tabs exist and legacy tabs are migrated before writing
ensureTabsExist(accessToken, spreadsheetId)
// 1. Sync Meals on SHEET_TAB_MEALS
@@ -334,6 +360,10 @@ object GoogleSheetsSyncService {
)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_RECIPES, "A:H", "A1", recipeRows)
// 4. Sync Food Preferences on SHEET_TAB_PREFERENCES
val prefRows = GoogleSheetsDataFormatter.formatPreferencesToRows(preferences)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_PREFERENCES, "A:E", "A1", prefRows)
val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit"
Result.success(
GoogleSheetsSyncResult(
@@ -341,7 +371,8 @@ object GoogleSheetsSyncService {
spreadsheetUrl = spreadsheetUrl,
mealsCount = meals.size,
foodsCount = foods.size,
recipesCount = recipes.size
recipesCount = recipes.size,
preferencesCount = preferences.size
)
)
} catch (e: Exception) {
@@ -456,22 +487,25 @@ object GoogleSheetsSyncService {
spreadsheetId: String
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
try {
// Ensure all 3 tabs exist and any legacy tab is renamed before attempting to read
// Ensure all 4 tabs exist and any legacy tab is renamed before attempting to read
ensureTabsExist(accessToken, spreadsheetId)
val mealRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_MEALS'!A1:Z")
val foodRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_FOODS'!A1:D")
val recipeRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_RECIPES'!A1:H")
val prefRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_PREFERENCES'!A1:E")
val parsedMeals = GoogleSheetsDataFormatter.parseRowsToMeals(mealRows)
val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows)
val parsedRecipes = GoogleSheetsDataFormatter.parseRowsToRecipes(recipeRows)
val parsedPrefs = GoogleSheetsDataFormatter.parseRowsToPreferences(prefRows)
Result.success(
SpreadsheetRestoreData(
meals = parsedMeals,
foods = parsedFoods,
recipes = parsedRecipes
recipes = parsedRecipes,
preferences = parsedPrefs
)
)
} catch (e: Exception) {
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
<string name="firestore_database_id" translatable="false">ai-studio-android-satia-b3e22121-687b-4d8f-aa0b-476e2d80fc24</string>
<string name="recaptcha_site_key" translatable="false">6LdwHCouAAAAABnF1BlE5Vm-yaaXDG6cNvj2Pv1o</string>
</resources>
@@ -0,0 +1,157 @@
package com.example
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag
import com.example.domain.CulinaryIdeasGenerator
import com.example.domain.DailyBenchmarkAnalyzer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [36])
class CulinaryIdeasAndBenchmarksTest {
private val parisZone = ZoneId.of("Europe/Paris")
@Test
fun `analyzeToday identifies present and missing benchmark categories for dinner`() {
val today = LocalDate.of(2026, 11, 20)
val breakfastTs = LocalDateTime.of(2026, 11, 20, 8, 15).atZone(parisZone).toInstant().toEpochMilli()
val lunchTs = LocalDateTime.of(2026, 11, 20, 12, 30).atZone(parisZone).toInstant().toEpochMilli()
val yesterdayTs = LocalDateTime.of(2026, 11, 19, 19, 30).atZone(parisZone).toInstant().toEpochMilli()
val meals = listOf(
MealEntry(
id = "m_breakfast",
mealType = MealType.BREAKFAST.name,
mealTimestamp = breakfastTs,
foodItemsSerialized = listOf(
MealFoodItem("Pomme", 1.0, FoodUnit.PORTION, FoodCategory.FRUIT).serialize(),
MealFoodItem("Pain complet", 2.0, FoodUnit.PORTION, FoodCategory.BREAD).serialize()
)
),
MealEntry(
id = "m_lunch",
mealType = MealType.LUNCH.name,
mealTimestamp = lunchTs,
foodItemsSerialized = listOf(
MealFoodItem("Poulet", 140.0, FoodUnit.G, FoodCategory.PROTEIN).serialize(),
MealFoodItem("Riz complet", 90.0, FoodUnit.G, FoodCategory.STARCH).serialize(),
MealFoodItem("Comté", 30.0, FoodUnit.G, FoodCategory.CHEESE).serialize()
)
),
// Yesterday meal should be ignored
MealEntry(
id = "m_yesterday",
mealType = MealType.DINNER.name,
mealTimestamp = yesterdayTs,
foodItemsSerialized = listOf(
MealFoodItem("Brocolis", 200.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize()
)
)
)
val gap = DailyBenchmarkAnalyzer.analyzeToday(
meals = meals,
targetMealType = MealType.DINNER,
today = today,
zoneId = parisZone
)
assertEquals(2, gap.mealsLoggedTodayCount)
assertEquals(1, gap.presentTodayCounts[FoodCategory.FRUIT])
assertEquals(1, gap.presentTodayCounts[FoodCategory.PROTEIN])
assertEquals(null, gap.presentTodayCounts[FoodCategory.VEGETABLE])
// Vegetables, dairy, protein/starch (2nd portion), fruit (2nd portion) should be suggested for dinner
assertTrue(FoodCategory.VEGETABLE in gap.priorityMissingCategories)
assertTrue(FoodCategory.DAIRY in gap.priorityMissingCategories)
assertTrue(FoodCategory.PROTEIN in gap.priorityMissingCategories)
// Bread is already eaten once today
assertFalse(FoodCategory.BREAD in gap.priorityMissingCategories)
// Nuts were not eaten today -> present in global missing
assertTrue(FoodCategory.NUTS in gap.allMissingTodayCategories)
assertTrue(gap.gentleSummary.contains("dîner"))
}
@Test
fun `parseSuggestionsJson parses structured recipes and discoveries accurately`() {
val rawJson = """
{
"contextSummary": "Pour votre dîner, voici des idées riches en légumes et protéines douces.",
"recipes": [
{
"title": "Poêlée saumon, courgettes et quinoa",
"categoryTag": "MAIN",
"prepTimeMinutes": 20,
"servings": 2,
"whyItFits": "Utilise votre saumon aimé et apporte légumes et féculents.",
"completedCategories": ["PROTEIN", "VEGETABLE", "STARCH"],
"ingredients": [
{"name": "Pavé de saumon", "weight": 280, "unit": "g", "category": "PROTEIN"},
{"name": "Courgettes", "weight": 400, "unit": "g", "category": "VEGETABLE"},
{"name": "Quinoa cru", "weight": 180, "unit": "g", "category": "STARCH"}
],
"steps": [
"Cuire le quinoa 12 minutes dans l'eau bouillante.",
"Faire revenir les courgettes puis ajouter le saumon."
]
}
],
"discoveries": [
{
"foodName": "Graines de courge",
"category": "NUTS",
"benchmarkReason": "Complète le repère fruits à coque (~30 g/jour).",
"pairingIdea": "Saupoudrées sur vos courgettes chaudes ou un yaourt."
}
]
}
""".trimIndent()
val bundle = CulinaryIdeasGenerator.parseSuggestionsJson(rawJson)
assertEquals(1, bundle.recipes.size)
val recipe = bundle.recipes[0]
assertEquals("Poêlée saumon, courgettes et quinoa", recipe.title)
assertEquals(RecipeCategoryTag.MAIN, recipe.categoryTag)
assertEquals(20, recipe.prepTimeMinutes)
assertEquals(2, recipe.servings)
assertEquals(3, recipe.ingredients.size)
assertEquals(FoodCategory.PROTEIN, recipe.ingredients[0].category)
assertEquals(2, recipe.steps.size)
// Conversion to RecipeEntry preserves all ingredients & steps
val entry = recipe.toRecipeEntry()
assertEquals(recipe.title, entry.title)
assertEquals(3, entry.parsedIngredients().size)
assertEquals(2, entry.steps.size)
// Conversion to prefilled MealEntry scales 2 servings down to 1 serving
val meal = recipe.toPrefilledMeal(MealType.DINNER)
assertEquals(MealType.DINNER.name, meal.mealType)
val mealItems = meal.parsedFoodItems()
assertEquals(140.0, mealItems[0].weight!!, 0.01)
assertEquals(200.0, mealItems[1].weight!!, 0.01)
assertEquals(90.0, mealItems[2].weight!!, 0.01)
// Discoveries parsed cleanly
assertEquals(1, bundle.discoveries.size)
val discovery = bundle.discoveries[0]
assertEquals("Graines de courge", discovery.foodName)
assertEquals(FoodCategory.NUTS, discovery.category)
assertTrue(discovery.pairingIdea.contains("courgettes"))
}
}
@@ -1,7 +1,9 @@
package com.example
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalFoodPreferenceEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
@@ -222,4 +224,26 @@ class GoogleSheetsDataFormatterTest {
assertTrue(!encoded.contains("+"))
assertTrue(!foodEncoded.contains("+"))
}
@Test
fun `formatPreferencesToRows and parseRowsToPreferences roundtrips correctly`() {
val prefs = listOf(
LocalFoodPreferenceEntity.create("Saumon", FoodPreferenceStatus.LIKED, FoodCategory.PROTEIN, "Rôti au four"),
LocalFoodPreferenceEntity.create("Céleri", FoodPreferenceStatus.DISLIKED, FoodCategory.VEGETABLE),
LocalFoodPreferenceEntity.create("Noix de pécan", FoodPreferenceStatus.TO_TRY, FoodCategory.NUTS, "Pour la collation")
)
val rows = GoogleSheetsDataFormatter.formatPreferencesToRows(prefs, testZoneId)
assertEquals(4, rows.size)
assertEquals(GoogleSheetsDataFormatter.HEADERS_PREFERENCES, rows[0])
val restored = GoogleSheetsDataFormatter.parseRowsToPreferences(rows).map { it.toDomain() }
assertEquals(3, restored.size)
assertEquals(FoodPreferenceStatus.LIKED, restored.first { it.name == "Saumon" }.status)
assertEquals(FoodCategory.PROTEIN, restored.first { it.name == "Saumon" }.category)
assertEquals("Rôti au four", restored.first { it.name == "Saumon" }.note)
assertEquals(FoodPreferenceStatus.DISLIKED, restored.first { it.name == "Céleri" }.status)
assertEquals(FoodPreferenceStatus.TO_TRY, restored.first { it.name == "Noix de pécan" }.status)
assertEquals(FoodCategory.NUTS, restored.first { it.name == "Noix de pécan" }.category)
}
}
@@ -5,10 +5,12 @@ import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.example.data.local.AppDatabase
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalFoodPreferenceEntity
import com.example.data.local.LocalMealDao
import com.example.data.local.LocalMealEntity
import com.example.data.local.LocalRecipeEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
@@ -147,4 +149,31 @@ class LocalDatabaseTest {
dao.deleteRecipeById("rec_1")
assertNull(dao.getRecipeById("rec_1"))
}
@Test
fun testFoodPreferencesCrudAndStatusUpdate() = runTest {
val liked = LocalFoodPreferenceEntity.create("Saumon", FoodPreferenceStatus.LIKED, FoodCategory.PROTEIN)
val disliked = LocalFoodPreferenceEntity.create("Coriandre", FoodPreferenceStatus.DISLIKED, FoodCategory.VEGETABLE)
val toTry = LocalFoodPreferenceEntity.create("Graines de courge", FoodPreferenceStatus.TO_TRY, FoodCategory.NUTS)
dao.insertFoodPreferences(listOf(liked, disliked, toTry))
val initial = dao.observeAllFoodPreferences().first().map { it.toDomain() }
assertEquals(3, initial.size)
assertEquals(FoodPreferenceStatus.LIKED, initial.first { it.name == "Saumon" }.status)
assertEquals(FoodPreferenceStatus.DISLIKED, initial.first { it.name == "Coriandre" }.status)
assertEquals(FoodPreferenceStatus.TO_TRY, initial.first { it.name == "Graines de courge" }.status)
// Promote "Graines de courge" from TO_TRY -> LIKED (same slugId replaces cleanly)
val promoted = LocalFoodPreferenceEntity.create("Graines de courge", FoodPreferenceStatus.LIKED, FoodCategory.NUTS)
dao.insertFoodPreference(promoted)
val updated = dao.getAllFoodPreferencesOnce().map { it.toDomain() }
assertEquals(3, updated.size)
assertEquals(FoodPreferenceStatus.LIKED, updated.first { it.name == "Graines de courge" }.status)
dao.deleteFoodPreferenceBySlug(disliked.slugId)
val afterDelete = dao.getAllFoodPreferencesOnce()
assertEquals(2, afterDelete.size)
}
}