feat: add recipe management support

- Add `LocalRecipeEntity` and database migration 3->4
- Update `LocalCustomFoodEntity` with category support
- Include DAO methods for recipe persistence
This commit is contained in:
bleackstorm committed 2026-11-20 21:10:19 +01:00
1 parent 097d4b521e
commit d4d5d77d71
41 files changed
+5264 -1901

No files matched your search

@@ -1,141 +0,0 @@
# Synchronisation Automatique avec Google Sheets & Nouvelle Branche
Ce plan détaille la mise en place de la synchronisation des repas de **Satiéa** vers un classeur **Google Sheets** hébergé sur Google Drive. Le travail sera développé et isolé sur une nouvelle branche Git (`feat/google-sheets-sync`).
## User Review & Critical Decisions
> [!IMPORTANT]
> Les choix suivants ont été confirmés lors de la phase de clarification :
> - **Sens de synchronisation** : Export automatique vers Google Sheets (l'application Satiéa envoie et met à jour les données dans votre feuille de calcul).
> - **Emplacement dans Google Drive** : Création automatique d'un classeur dédié nommé **« Satiéa — Journal des Repas »** dans la racine de votre Google Drive, avec en-têtes formatés et colonnes structurées.
> - **Déclenchement** : Synchronisation automatique en arrière-plan dès qu'un repas est ajouté ou modifié, complétée par un bouton manuel **« Synchroniser vers Google Sheets »** dans les Réglages et sur le Journal.
> - **Autorisation Google OAuth** : Utilisation du flux OAuth Google Workspace avec les permissions ciblées `https://www.googleapis.com/auth/spreadsheets` et `https://www.googleapis.com/auth/drive.file` (accès restreint uniquement aux fichiers créés par l'application).
---
## 1. Overview & Core Concept
- **Problématique résolue** : Offrir aux utilisateurs la possibilité d'analyser, partager et archiver leurs repas directement dans Google Sheets en temps réel, sans avoir à exporter manuellement un fichier CSV à chaque fois.
- **Expérience utilisateur** :
1. Dans l'onglet **Réglages**, une nouvelle carte **« Synchronisation Google Sheets »** propose un bouton **« Activer la synchronisation Google Sheets »**.
2. L'application demande l'autorisation d'accès Google Sheets et Drive via l'interface OAuth sécurisée de Google.
3. Dès l'autorisation accordée, Satiéa recherche ou crée automatiquement le classeur **« Satiéa — Journal des Repas »** dans Google Drive.
4. L'ID du classeur est mémorisé, et un lien direct **« Ouvrir ma feuille Google Sheets ↗ »** permet d'y accéder en un clic depuis l'application.
5. À chaque repas enregistré ou modifié (ou lors d'un clic sur **« Synchroniser maintenant »**), la liste des repas est mise à jour dans le classeur.
---
## 2. User Experience & Visual Design
### Flux Utilisateur
```
┌────────────────────────────────────────────────────────┐
│ Écran Réglages : Carte "Google Sheets" │
│ "Synchronisez vos repas en direct vers Google Drive" │
│ [Activer la synchronisation Google Sheets] (Bouton) │
└──────────────────────────┬─────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Validation OAuth Google Sheets & Drive (Consent UI) │
│ Autoriser Satiéa à gérer sa feuille de calcul │
└──────────────────────────┬─────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Création automatique : "Satiéa — Journal des Repas" │
│ • En-têtes stylisés (Date, Heure, Type, Faim, Satiété,│
│ Aliments & Poids, Note globale) │
│ • Envoi de l'historique complet des repas │
└──────────────────────────┬─────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────┐
│ Statut actif dans les Réglages & Journal : │
│ • Badge "Synchronisé avec Google Sheets" │
│ • Bouton [Ouvrir dans Google Sheets ↗] │
│ • Bouton [Synchroniser maintenant 🔄] │
│ • Envoi automatique transparent à chaque nouveau repas│
└────────────────────────────────────────────────────────┘
```
### Visual Identity & Theme
- **Bannière Google Sheets** : Surface aux tonalités émeraude / sauge élégantes (`secondaryContainer`) avec icône feuille de calcul Google.
- **Accès rapide** : Lien direct externe ouvrant l'application Google Sheets ou le navigateur sur le document créé.
- **Feedback d'action** : Indicateur de chargement discret lors de la transmission, suivi d'un `Snackbar` confirmant : *« X repas synchronisés avec Google Sheets ✨ »*.
---
## 3. Key Product Decisions & Trade-Offs
### Décision 1 : Portée des permissions OAuth minimales
- **Scopes retenus** :
- `https://www.googleapis.com/auth/spreadsheets` : pour créer et écrire dans les feuilles de calcul.
- `https://www.googleapis.com/auth/drive.file` : permet uniquement à Satiéa d'accéder aux fichiers qu'elle a elle-même créés dans votre Drive (ne lit ni ne modifie aucun autre document personnel).
- **Pourquoi** : Respect strict du principe de moindre privilège et conformité aux règles de sécurité Google Play et Google Cloud.
### Décision 2 : Architecture de synchronisation et déduplication
- **Approche retenue** :
- La feuille Google Sheets est organisée avec une ligne d'en-tête figée et une ligne par repas, triée par ordre chronologique.
- Lors de la synchronisation complète ou à la demande, l'application réécrit l'ensemble des repas ordonnés de manière atomique via l'API Google Sheets `values.update` (ou ajoute les nouvelles lignes via `values.append`), garantissant qu'aucune ligne n'est dupliquée et que les modifications ou suppressions sont parfaitement répercutées.
### Décision 3 : Indépendance vis-à-vis du mode hors-ligne
- **Approche retenue** : La base locale SQLite Room reste la source primaire. Si le réseau est indisponible au moment de noter un repas, le repas est sauvegardé immédiatement dans Room, et synchronisé vers Sheets dès le retour de la connexion ou lors du prochain clic sur « Synchroniser ».
---
## 4. Technical Architecture & Data Strategy
### Diagramme d'Architecture
```
┌─────────────────────────────────────────────────────────────────────────┐
│ INTERFACE UTILISATEUR │
│ SettingsScreen (Carte Sheets) │ JournalScreen (Bouton Sync & Lien) │
└────────────────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────────────┐
│ MealViewModel │
│ • Gère l'état syncGoogleSheets (connecté / id classeur / dernière synchro│
│ • Déclenche la synchronisation automatique après addMeal / updateMeal │
│ • Exécute syncWithGoogleSheets() à la demande │
└──────────────────┬───────────────────────────────────┬──────────────────┘
│ │
▼ ▼
┌─────────────────────────────────────┐ ┌─────────────────────────────────┐
│ BASE LOCALE ROOM (SQLite) │ │ GoogleSheetsSyncManager │
│ • Source de données locale │ │ • Gestion du token OAuth │
│ • Fournit la liste des repas │ │ • Drive API: création classeur │
│ ordonnés pour l'export Sheets │ │ • Sheets API: values.update │
└─────────────────────────────────────┘ └─────────────────────────────────┘
```
### Format des colonnes dans le classeur Google Sheets
| Colonne | Titre | Format / Exemple |
|---|---|---|
| A | **Date** | `08/11/2026` |
| B | **Heure** | `12:30` |
| C | **Type de repas** | `Déjeuner` |
| D | **Faim avant (/10)** | `6` |
| E | **Ressenti faim** | `Faim bien présente` |
| F | **Satiété après (/10)** | `7` |
| G | **Ressenti satiété** | `Satiété idéale et confortable` |
| H | **Aliments & Poids** | `Saumon grillé (150 g) ; Riz basmati (180 g)` |
| I | **Note globale** | `Déjeuner au calme, bonne digestion` |
| J | **Nombre de photos** | `1` |
---
## Plan de Test et de Validation
1. **Tests unitaires et de formattage** :
- Validation du formateur de lignes Google Sheets (`GoogleSheetsDataFormatterTest`) pour s'assurer que toutes les données (échelles 1–10, aliments, poids, dates) sont converties au format attendu.
2. **Tests d'intégration OAuth et API** :
- Vérification de la création du classeur et de l'écriture des cellules via l'API Google Sheets.
3. **Tests de non-régression** :
- Exécution de l'ensemble de la suite de tests unitaires et Robolectric (`LocalDatabaseTest`, `CsvImporterTest`, `ReminderPreferencesTest`).
4. **Compilation finale** :
- Validation complète du build avec `compile_applet`.
@@ -1,6 +0,0 @@
{
"summary": "Plan d'implémentation pour la synchronisation automatique et manuelle des repas avec Google Sheets dans une nouvelle branche Git (feat/google-sheets-sync). Le plan inclut le provisionnement OAuth (Google Sheets & Google Drive), la création automatique d'un classeur Satiéa dédié dans Google Drive, l'envoi en arrière-plan à chaque repas enregistré, un bouton manuel de synchronisation et la persistance locale de l'ID du classeur.",
"updatedAt": "2026-11-08T13:11:44.882816550Z",
"requestFeedback": true,
"userFacing": true
}
+8 -8
View File
@@ -93,7 +93,7 @@ googleServices { missingGoogleServicesStrategy = MissingGoogleServicesStrategy.W
// This makes it easy to add them back in the future if needed. // This makes it easy to add them back in the future if needed.
dependencies { dependencies {
implementation(platform(libs.androidx.compose.bom)) implementation(platform(libs.androidx.compose.bom))
implementation(platform(libs.firebase.bom)) // implementation(platform(libs.firebase.bom))
// implementation(libs.accompanist.permissions) // implementation(libs.accompanist.permissions)
implementation(libs.androidx.activity.compose) implementation(libs.androidx.activity.compose)
// implementation(libs.androidx.camera.camera2) // implementation(libs.androidx.camera.camera2)
@@ -117,14 +117,14 @@ dependencies {
implementation(libs.coil.compose) implementation(libs.coil.compose)
// implementation(libs.converter.moshi) // implementation(libs.converter.moshi)
// implementation(libs.firebase.ai) // implementation(libs.firebase.ai)
implementation(libs.firebase.firestore) // implementation(libs.firebase.firestore)
implementation(libs.firebase.auth) // implementation(libs.firebase.auth)
implementation(libs.androidx.credentials) // implementation(libs.androidx.credentials)
implementation(libs.androidx.credentials.play.services) // implementation(libs.androidx.credentials.play.services)
implementation(libs.googleid) // implementation(libs.googleid)
implementation(libs.play.services.auth) implementation(libs.play.services.auth)
implementation(libs.firebase.appcheck.recaptcha) // implementation(libs.firebase.appcheck.recaptcha)
implementation(libs.firebase.appcheck.debug) // implementation(libs.firebase.appcheck.debug)
implementation(libs.kotlinx.coroutines.android) implementation(libs.kotlinx.coroutines.android)
implementation(libs.kotlinx.coroutines.core) implementation(libs.kotlinx.coroutines.core)
implementation(libs.logging.interceptor) implementation(libs.logging.interceptor)
+456 -351
View File
@@ -1,6 +1,8 @@
package com.example package com.example
import android.Manifest import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri import android.net.Uri
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
@@ -19,6 +21,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.BarChart import androidx.compose.material.icons.filled.BarChart
import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
@@ -37,14 +40,12 @@ import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import com.example.ui.common.UiEvent
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
@@ -53,34 +54,39 @@ import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.preferences.ReminderPreferencesManager import com.example.data.preferences.ReminderPreferencesManager
import com.example.notification.MealNotificationManager import com.example.notification.MealNotificationManager
import com.example.ui.auth.AuthScreen import com.example.ui.auth.AuthScreen
import com.example.ui.common.UiEvent
import com.example.ui.journal.JournalScreen import com.example.ui.journal.JournalScreen
import com.example.ui.journal.MealViewModel import com.example.ui.journal.MealViewModel
import com.example.ui.journal.MealsUiState import com.example.ui.journal.MealsUiState
import com.example.ui.meal.MealEntrySheet import com.example.ui.meal.MealEntrySheet
import com.example.ui.recipes.RecipeDetailSheet
import com.example.ui.recipes.RecipeEditorSheet
import com.example.ui.recipes.RecipesScreen
import com.example.ui.settings.SettingsScreen import com.example.ui.settings.SettingsScreen
import com.example.ui.stats.WeeklyStatsScreen import com.example.ui.stats.WeeklyStatsScreen
import com.example.ui.theme.SatieaTheme import com.example.ui.theme.SatieaTheme
import com.example.util.CsvExporter import com.example.util.CsvExporter
import com.example.widget.SatieaAppWidgetProvider
import android.app.Activity
import android.content.Intent
import com.example.ui.journal.GoogleSheetsUiState
import com.example.util.GoogleSheetsAuthHelper import com.example.util.GoogleSheetsAuthHelper
import com.google.android.gms.auth.api.signin.GoogleSignIn import com.example.widget.SatieaAppWidgetProvider
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.time.LocalTime
enum class MainTab(val title: String) { enum class MainTab(val title: String) {
JOURNAL("Journal"), JOURNAL("Journal"),
RECIPES("Recettes"),
STATS("Statistiques"), STATS("Statistiques"),
SETTINGS("Réglages") SETTINGS("Réglages")
} }
private enum class PendingDriveAction {
SYNC,
RESTORE
}
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private val viewModel: MealViewModel by viewModels() private val viewModel: MealViewModel by viewModels()
@@ -113,7 +119,7 @@ class MainActivity : ComponentActivity() {
if (intent?.action == MealNotificationManager.ACTION_LOG_MEAL) { if (intent?.action == MealNotificationManager.ACTION_LOG_MEAL) {
val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let { val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
MealType.fromString(it) MealType.fromString(it)
} ?: SatieaAppWidgetProvider.suggestMealTypeForHour(java.time.LocalTime.now().hour) } ?: SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
viewModel.requestQuickLogMeal(parsedType) viewModel.requestQuickLogMeal(parsedType)
} }
} }
@@ -124,21 +130,13 @@ class MainActivity : ComponentActivity() {
fun AppRoot( fun AppRoot(
viewModel: MealViewModel viewModel: MealViewModel
) { ) {
var currentUser by remember { mutableStateOf(Firebase.auth.currentUser) } val context = LocalContext.current
var googleAccount by remember { mutableStateOf(GoogleSheetsAuthHelper.getSignedInAccount(context)) }
var showAuthSheet by remember { mutableStateOf(false) } var showAuthSheet by remember { mutableStateOf(false) }
var pendingDriveAction by remember { mutableStateOf<PendingDriveAction?>(null) }
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
val context = LocalContext.current
DisposableEffect(Unit) {
val listener = FirebaseAuth.AuthStateListener { auth ->
currentUser = auth.currentUser
}
Firebase.auth.addAuthStateListener(listener)
onDispose {
Firebase.auth.removeAuthStateListener(listener)
}
}
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
viewModel.uiEvents.collect { event -> viewModel.uiEvents.collect { event ->
@@ -158,10 +156,17 @@ fun AppRoot(
} }
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) } var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
// Meal entry sheet state (supports editing existing meal OR pre-filling a new meal from a recipe)
var showMealEntrySheet by remember { mutableStateOf(false) } var showMealEntrySheet by remember { mutableStateOf(false) }
var editingMeal by remember { mutableStateOf<MealEntry?>(null) } var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
var defaultMealType by remember { mutableStateOf(MealType.LUNCH) } var defaultMealType by remember { mutableStateOf(MealType.LUNCH) }
// Recipe book sheets state
var selectedRecipeId by remember { mutableStateOf<String?>(null) }
var showRecipeEditor by remember { mutableStateOf(false) }
var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) }
// React to quick log meal requests from Widget or Notification // React to quick log meal requests from Widget or Notification
val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle() val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle()
LaunchedEffect(quickLogMealType) { LaunchedEffect(quickLogMealType) {
@@ -175,355 +180,455 @@ fun AppRoot(
} }
val prefs = remember { ReminderPreferencesManager.getInstance(context) } val prefs = remember { ReminderPreferencesManager.getInstance(context) }
var showPermissionRationaleDialog by remember { var showPermissionRationaleDialog by remember {
mutableStateOf( mutableStateOf(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
!NotificationManagerCompat.from(context).areNotificationsEnabled() && !NotificationManagerCompat.from(context).areNotificationsEnabled() &&
!prefs.hasPromptedNotificationPermission() !prefs.hasPromptedNotificationPermission()
) )
} }
val requestNotificationPermissionLauncher = rememberLauncherForActivityResult( val requestNotificationPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission() contract = ActivityResultContracts.RequestPermission()
) { isGranted -> ) { isGranted ->
if (isGranted) { if (isGranted) {
MealNotificationManager.scheduleAllActiveReminders(context) MealNotificationManager.scheduleAllActiveReminders(context)
coroutineScope.launch { coroutineScope.launch {
snackbarHostState.showSnackbar("Rappels de repas activés avec succès 🔔") snackbarHostState.showSnackbar("Rappels de repas activés avec succès 🔔")
}
} }
} }
}
if (showPermissionRationaleDialog) { if (showPermissionRationaleDialog) {
AlertDialog( AlertDialog(
onDismissRequest = { onDismissRequest = {
prefs.setPromptedNotificationPermission(true) prefs.setPromptedNotificationPermission(true)
showPermissionRationaleDialog = false showPermissionRationaleDialog = false
}, },
title = { title = {
Text( Text(
text = "Rappels bienveillants de repas 🔔", text = "Rappels bienveillants de repas 🔔",
style = MaterialTheme.typography.titleLarge style = MaterialTheme.typography.titleLarge
) )
}, },
text = { text = {
Text( Text(
text = "Pour vous aider à être à l'écoute de votre corps, Satiéa peut vous envoyer un rappel discret au moment de manger afin d'évaluer votre faim et votre satiété.", text = "Pour vous aider à être à l'écoute de votre corps, Satiéa peut vous envoyer un rappel discret au moment de manger afin d'évaluer votre faim et votre satiété.",
style = MaterialTheme.typography.bodyMedium style = MaterialTheme.typography.bodyMedium
) )
}, },
confirmButton = { confirmButton = {
Button( Button(
onClick = { onClick = {
prefs.setPromptedNotificationPermission(true) prefs.setPromptedNotificationPermission(true)
showPermissionRationaleDialog = false showPermissionRationaleDialog = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
requestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) requestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
}
} }
) {
Text("Activer les rappels")
} }
},
dismissButton = {
TextButton(
onClick = {
prefs.setPromptedNotificationPermission(true)
showPermissionRationaleDialog = false
}
) {
Text("Plus tard")
}
}
)
}
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle()
val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList()
LaunchedEffect(Unit) {
SatieaAppWidgetProvider.updateAllWidgets(context)
}
val createCsvDocumentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("text/csv")
) { targetUri: Uri? ->
if (targetUri != null) {
viewModel.exportCsvToUri(
targetUri = targetUri,
meals = currentMealsList
)
}
}
val importCsvLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { sourceUri: Uri? ->
if (sourceUri != null) {
viewModel.importCsvFromUri(sourceUri = sourceUri)
}
}
val triggerImportCsv = {
importCsvLauncher.launch(arrayOf("text/*", "text/csv", "application/csv", "*/*"))
}
val triggerSaveCsv = {
if (currentMealsList.isEmpty()) {
viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à exporter pour le moment"))
} else {
createCsvDocumentLauncher.launch(CsvExporter.buildDefaultFileName())
}
}
val triggerShareCsv = {
if (currentMealsList.isEmpty()) {
viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à partager pour le moment"))
} else {
viewModel.shareCsv(meals = currentMealsList)
}
}
val sheetsAuthConsentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
viewModel.syncToGoogleSheets()
} else {
viewModel.emitEvent(UiEvent.ShowSnackbar("Autorisation Google Sheets annulée"))
}
}
val triggerGoogleSheetsSync = {
val email = Firebase.auth.currentUser?.email
?: GoogleSignIn.getLastSignedInAccount(context)?.email
if (email.isNullOrBlank()) {
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
sheetsAuthConsentLauncher.launch(client.signInIntent)
} else {
viewModel.syncToGoogleSheets(
onAuthConsentNeeded = { intent ->
sheetsAuthConsentLauncher.launch(intent)
}
)
}
}
val triggerGoogleSheetsRestore = {
val email = Firebase.auth.currentUser?.email
?: GoogleSignIn.getLastSignedInAccount(context)?.email
if (email.isNullOrBlank()) {
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
sheetsAuthConsentLauncher.launch(client.signInIntent)
} else {
viewModel.restoreFromGoogleSheets(
onAuthConsentNeeded = { intent ->
sheetsAuthConsentLauncher.launch(intent)
}
)
}
}
val openGoogleSheets = { url: String ->
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(intent)
} catch (_: Exception) {
coroutineScope.launch {
snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : $url")
}
}
}
BackHandler(enabled = currentTab != MainTab.JOURNAL) {
currentTab = MainTab.JOURNAL
}
Scaffold(
contentWindowInsets = WindowInsets.safeDrawing,
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
bottomBar = {
NavigationBar(
modifier = Modifier
.windowInsetsPadding(WindowInsets.navigationBars)
.testTag("main_navigation_bar"),
containerColor = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp
) { ) {
NavigationBarItem( Text("Activer les rappels")
selected = currentTab == MainTab.JOURNAL, }
onClick = { currentTab = MainTab.JOURNAL }, },
icon = { Icon(Icons.Default.Restaurant, contentDescription = "Journal") }, dismissButton = {
label = { Text("Journal") }, TextButton(
colors = NavigationBarItemDefaults.colors( onClick = {
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, prefs.setPromptedNotificationPermission(true)
indicatorColor = MaterialTheme.colorScheme.primaryContainer showPermissionRationaleDialog = false
), }
modifier = Modifier.testTag("tab_journal") ) {
) Text("Plus tard")
}
}
)
}
NavigationBarItem( val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
selected = currentTab == MainTab.STATS, val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
onClick = { currentTab = MainTab.STATS }, val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
icon = { Icon(Icons.Default.BarChart, contentDescription = "Statistiques") }, val recipes by viewModel.recipes.collectAsStateWithLifecycle()
label = { Text("Statistiques") }, val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
colors = NavigationBarItemDefaults.colors( val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
indicatorColor = MaterialTheme.colorScheme.primaryContainer val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle()
), val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList()
modifier = Modifier.testTag("tab_stats")
)
NavigationBarItem( LaunchedEffect(Unit) {
selected = currentTab == MainTab.SETTINGS, SatieaAppWidgetProvider.updateAllWidgets(context)
onClick = { currentTab = MainTab.SETTINGS }, }
icon = { Icon(Icons.Default.Settings, contentDescription = "Réglages") },
label = { Text("Réglages") }, val createCsvDocumentLauncher = rememberLauncherForActivityResult(
colors = NavigationBarItemDefaults.colors( contract = ActivityResultContracts.CreateDocument("text/csv")
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, ) { targetUri: Uri? ->
indicatorColor = MaterialTheme.colorScheme.primaryContainer if (targetUri != null) {
), viewModel.exportCsvToUri(
modifier = Modifier.testTag("tab_settings") targetUri = targetUri,
meals = currentMealsList
)
}
}
val importCsvLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { sourceUri: Uri? ->
if (sourceUri != null) {
viewModel.importCsvFromUri(sourceUri = sourceUri)
}
}
val triggerImportCsv = {
importCsvLauncher.launch(arrayOf("text/*", "text/csv", "application/csv", "*/*"))
}
val triggerSaveCsv = {
if (currentMealsList.isEmpty()) {
viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à exporter pour le moment"))
} else {
createCsvDocumentLauncher.launch(CsvExporter.buildDefaultFileName())
}
}
val triggerShareCsv = {
if (currentMealsList.isEmpty()) {
viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à partager pour le moment"))
} else {
viewModel.shareCsv(meals = currentMealsList)
}
}
val sheetsAuthConsentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
googleAccount = GoogleSheetsAuthHelper.getSignedInAccount(context)
val actionToRun = pendingDriveAction
pendingDriveAction = null
if (result.resultCode == Activity.RESULT_OK) {
when (actionToRun) {
PendingDriveAction.RESTORE -> viewModel.restoreFromGoogleSheets()
PendingDriveAction.SYNC, null -> viewModel.syncToGoogleSheets()
}
} else {
viewModel.emitEvent(UiEvent.ShowSnackbar("Autorisation Google Drive annulée"))
}
}
val triggerGoogleSheetsSync = {
val account = GoogleSheetsAuthHelper.getSignedInAccount(context)
googleAccount = account
if (account == null) {
pendingDriveAction = PendingDriveAction.SYNC
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
sheetsAuthConsentLauncher.launch(client.signInIntent)
} else {
viewModel.syncToGoogleSheets(
onAuthConsentNeeded = { intent ->
pendingDriveAction = PendingDriveAction.SYNC
sheetsAuthConsentLauncher.launch(intent)
}
)
}
}
val triggerGoogleSheetsRestore = {
val account = GoogleSheetsAuthHelper.getSignedInAccount(context)
googleAccount = account
if (account == null) {
pendingDriveAction = PendingDriveAction.RESTORE
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
sheetsAuthConsentLauncher.launch(client.signInIntent)
} else {
viewModel.restoreFromGoogleSheets(
onAuthConsentNeeded = { intent ->
pendingDriveAction = PendingDriveAction.RESTORE
sheetsAuthConsentLauncher.launch(intent)
}
)
}
}
val openGoogleSheets = { url: String ->
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
context.startActivity(intent)
} catch (_: Exception) {
coroutineScope.launch {
snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : $url")
}
}
}
BackHandler(enabled = currentTab != MainTab.JOURNAL) {
currentTab = MainTab.JOURNAL
}
Scaffold(
contentWindowInsets = WindowInsets.safeDrawing,
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
bottomBar = {
NavigationBar(
modifier = Modifier
.windowInsetsPadding(WindowInsets.navigationBars)
.testTag("main_navigation_bar"),
containerColor = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp
) {
NavigationBarItem(
selected = currentTab == MainTab.JOURNAL,
onClick = { currentTab = MainTab.JOURNAL },
icon = { Icon(Icons.Default.Restaurant, contentDescription = "Journal") },
label = { Text("Journal") },
colors = NavigationBarItemDefaults.colors(
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
indicatorColor = MaterialTheme.colorScheme.primaryContainer
),
modifier = Modifier.testTag("tab_journal")
)
NavigationBarItem(
selected = currentTab == MainTab.RECIPES,
onClick = { currentTab = MainTab.RECIPES },
icon = { Icon(Icons.AutoMirrored.Filled.MenuBook, contentDescription = "Recettes") },
label = { Text("Recettes") },
colors = NavigationBarItemDefaults.colors(
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
indicatorColor = MaterialTheme.colorScheme.primaryContainer
),
modifier = Modifier.testTag("tab_recipes")
)
NavigationBarItem(
selected = currentTab == MainTab.STATS,
onClick = { currentTab = MainTab.STATS },
icon = { Icon(Icons.Default.BarChart, contentDescription = "Statistiques") },
label = { Text("Stats") },
colors = NavigationBarItemDefaults.colors(
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
indicatorColor = MaterialTheme.colorScheme.primaryContainer
),
modifier = Modifier.testTag("tab_stats")
)
NavigationBarItem(
selected = currentTab == MainTab.SETTINGS,
onClick = { currentTab = MainTab.SETTINGS },
icon = { Icon(Icons.Default.Settings, contentDescription = "Réglages") },
label = { Text("Réglages") },
colors = NavigationBarItemDefaults.colors(
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
indicatorColor = MaterialTheme.colorScheme.primaryContainer
),
modifier = Modifier.testTag("tab_settings")
)
}
}
) { innerPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
) {
when (currentTab) {
MainTab.JOURNAL -> {
JournalScreen(
mealsUiState = mealsState,
customFoods = customFoods,
onAddMealClick = {
editingMeal = null
defaultMealType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
showMealEntrySheet = true
},
onEditMeal = { meal ->
editingMeal = meal
showMealEntrySheet = true
},
onDeleteMeal = { mealId ->
viewModel.deleteMeal(mealId = mealId)
},
onExportCsvClick = {
triggerSaveCsv()
},
onSyncSheetsClick = {
triggerGoogleSheetsSync()
},
spreadsheetUrl = spreadsheetUrl
)
}
MainTab.RECIPES -> {
RecipesScreen(
recipes = recipes,
customFoods = customFoods,
onAddRecipeClick = {
editingRecipe = null
showRecipeEditor = true
},
onRecipeClick = { recipe ->
selectedRecipeId = recipe.id
}
)
}
MainTab.STATS -> {
WeeklyStatsScreen(
weeklyStats = weeklyStats,
totalMealsCount = currentMealsList.size,
onSaveCsvClick = { triggerSaveCsv() },
onShareCsvClick = { triggerShareCsv() },
onImportCsvClick = { triggerImportCsv() }
)
}
MainTab.SETTINGS -> {
SettingsScreen(
googleAccount = googleAccount,
currentThemeMode = themeMode,
totalMealsCount = currentMealsList.size,
sheetsUiState = sheetsUiState,
isAutoSyncSheets = isAutoSyncSheets,
spreadsheetUrl = spreadsheetUrl,
onThemeModeChange = { newMode ->
viewModel.setThemeMode(newMode)
},
onScheduleReminder = { type, hour, minute, enabled ->
viewModel.scheduleMealReminder(type, hour, minute, enabled)
},
onTestNotification = { type ->
viewModel.triggerTestNotification(type)
},
onSaveCsvClick = { triggerSaveCsv() },
onShareCsvClick = { triggerShareCsv() },
onImportCsvClick = { triggerImportCsv() },
onSyncSheetsClick = { triggerGoogleSheetsSync() },
onAutoSyncSheetsChange = { enabled -> viewModel.setAutoSyncSheets(enabled) },
onOpenSheetsClick = { url -> openGoogleSheets(url) },
onRestoreSheetsClick = { triggerGoogleSheetsRestore() },
onSignInClick = { showAuthSheet = true },
onSignOut = {
viewModel.signOut(context) {
googleAccount = null
}
}
) )
} }
} }
) { innerPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
) {
when (currentTab) {
MainTab.JOURNAL -> {
JournalScreen(
mealsUiState = mealsState,
onAddMealClick = {
editingMeal = null
defaultMealType = MealType.LUNCH
showMealEntrySheet = true
},
onEditMeal = { meal ->
editingMeal = meal
showMealEntrySheet = true
},
onDeleteMeal = { mealId ->
viewModel.deleteMeal(mealId = mealId)
},
onExportCsvClick = {
triggerSaveCsv()
},
onSyncSheetsClick = {
triggerGoogleSheetsSync()
},
spreadsheetUrl = spreadsheetUrl
)
}
MainTab.STATS -> { if (showMealEntrySheet) {
WeeklyStatsScreen( MealEntrySheet(
weeklyStats = weeklyStats, initialMeal = editingMeal,
totalMealsCount = currentMealsList.size, defaultMealType = defaultMealType,
onSaveCsvClick = { triggerSaveCsv() }, customFoods = customFoods,
onShareCsvClick = { triggerShareCsv() }, onAddCustomFood = { name, unit, category ->
onImportCsvClick = { triggerImportCsv() } viewModel.addCustomFoodDirectly(name, unit, category)
) },
} onDismiss = {
showMealEntrySheet = false
MainTab.SETTINGS -> { editingMeal = null
SettingsScreen( },
currentThemeMode = themeMode, onSaveMeal = { type, timestamp, hunger, satiety, note, foodItems, photos ->
totalMealsCount = currentMealsList.size, showMealEntrySheet = false
sheetsUiState = sheetsUiState, val currentEditing = editingMeal
isAutoSyncSheets = isAutoSyncSheets, if (currentEditing != null && currentEditing.id.isNotBlank()) {
spreadsheetUrl = spreadsheetUrl, viewModel.updateMeal(
onThemeModeChange = { newMode -> meal = currentEditing.copy(
viewModel.setThemeMode(newMode) mealType = type.name,
},
onScheduleReminder = { type, hour, minute, enabled ->
viewModel.scheduleMealReminder(type, hour, minute, enabled)
},
onTestNotification = { type ->
viewModel.triggerTestNotification(type)
},
onSaveCsvClick = { triggerSaveCsv() },
onShareCsvClick = { triggerShareCsv() },
onImportCsvClick = { triggerImportCsv() },
onSyncSheetsClick = { triggerGoogleSheetsSync() },
onAutoSyncSheetsChange = { enabled -> viewModel.setAutoSyncSheets(enabled) },
onOpenSheetsClick = { url -> openGoogleSheets(url) },
onRestoreSheetsClick = { triggerGoogleSheetsRestore() },
onSignInClick = { showAuthSheet = true },
onSignOut = {
viewModel.signOut(context) {
currentUser = null
}
}
)
}
}
if (showMealEntrySheet) {
MealEntrySheet(
initialMeal = editingMeal,
defaultMealType = defaultMealType,
customFoods = customFoods,
onAddCustomFood = { name, unit ->
viewModel.addCustomFoodDirectly(name, unit)
},
onDismiss = {
showMealEntrySheet = false
editingMeal = null
},
onSaveMeal = { type, timestamp, hunger, satiety, note, foodItems, photos ->
showMealEntrySheet = false
val currentEditing = editingMeal
if (currentEditing != null) {
viewModel.updateMeal(
meal = currentEditing.copy(
mealType = type.name,
mealTimestamp = timestamp,
hungerBefore = hunger,
satietyAfter = satiety,
note = note,
photoUris = photos
),
foodItems = foodItems
)
} else {
viewModel.addMeal(
mealType = type,
mealTimestamp = timestamp, mealTimestamp = timestamp,
hungerBefore = hunger, hungerBefore = hunger,
satietyAfter = satiety, satietyAfter = satiety,
note = note, note = note,
foodItems = foodItems,
photoUris = photos photoUris = photos
) ),
} foodItems = foodItems
editingMeal = null )
} else {
viewModel.addMeal(
mealType = type,
mealTimestamp = timestamp,
hungerBefore = hunger,
satietyAfter = satiety,
note = note,
foodItems = foodItems,
photoUris = photos
)
}
editingMeal = null
}
)
}
// Recipe Detail Sheet
val activeRecipe = selectedRecipeId?.let { id -> recipes.firstOrNull { it.id == id } }
if (activeRecipe != null) {
RecipeDetailSheet(
recipe = activeRecipe,
customFoods = customFoods,
onDismiss = { selectedRecipeId = null },
onEdit = {
selectedRecipeId = null
editingRecipe = activeRecipe
showRecipeEditor = true
},
onDelete = {
selectedRecipeId = null
viewModel.deleteRecipe(activeRecipe.id)
},
onLogAsMeal = { recipe, eatenServings ->
selectedRecipeId = null
val suggestedType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
val scaled = recipe.scaledIngredients(eatenServings.toDouble())
val prefilledMeal = MealEntry(
id = "",
mealType = suggestedType.name,
mealTimestamp = System.currentTimeMillis(),
hungerBefore = 5,
satietyAfter = 7,
note = "Recette : ${recipe.title}",
foodItemsSerialized = scaled.map { it.serialize() },
photoUris = listOfNotNull(recipe.photoUri)
)
currentTab = MainTab.JOURNAL
editingMeal = prefilledMeal
defaultMealType = suggestedType
showMealEntrySheet = true
}
)
}
// Recipe Editor Sheet
if (showRecipeEditor) {
RecipeEditorSheet(
initialRecipe = editingRecipe,
customFoods = customFoods,
onAddCustomFood = { name, unit, category ->
viewModel.addCustomFoodDirectly(name, unit, category)
},
onDismiss = {
showRecipeEditor = false
editingRecipe = null
},
onSaveRecipe = { recipe ->
showRecipeEditor = false
editingRecipe = null
viewModel.saveRecipe(recipe)
}
)
}
if (showAuthSheet) {
ModalBottomSheet(
onDismissRequest = { showAuthSheet = false }
) {
AuthScreen(
onAuthSuccess = { connectedAccount ->
googleAccount = connectedAccount
showAuthSheet = false
viewModel.emitEvent(
UiEvent.ShowSnackbar("Compte Google Drive connecté (${connectedAccount.email}) ✨")
)
} }
) )
} }
if (showAuthSheet) {
ModalBottomSheet(
onDismissRequest = { showAuthSheet = false }
) {
AuthScreen(
onAuthSuccess = {
currentUser = Firebase.auth.currentUser
showAuthSheet = false
viewModel.syncCloudToLocal()
}
)
}
}
} }
} }
} }
}
@@ -12,8 +12,8 @@ import com.squareup.moshi.Moshi
import com.squareup.moshi.Types import com.squareup.moshi.Types
@Database( @Database(
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class], entities = [LocalMealEntity::class, LocalCustomFoodEntity::class, LocalRecipeEntity::class],
version = 3, version = 4,
exportSchema = false exportSchema = false
) )
@TypeConverters(RoomConverters::class) @TypeConverters(RoomConverters::class)
@@ -93,6 +93,30 @@ abstract class AppDatabase : RoomDatabase() {
} }
} }
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"ALTER TABLE `local_custom_foods` ADD COLUMN `category` TEXT NOT NULL DEFAULT ''"
)
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS `local_recipes` (
`id` TEXT NOT NULL PRIMARY KEY,
`title` TEXT NOT NULL,
`categoryTag` TEXT NOT NULL,
`prepTimeMinutes` INTEGER NOT NULL,
`servings` INTEGER NOT NULL,
`ingredients` TEXT NOT NULL,
`steps` TEXT NOT NULL,
`notes` TEXT NOT NULL,
`photoUri` TEXT,
`updatedAt` INTEGER NOT NULL
)
""".trimIndent()
)
}
}
fun getInstance(context: Context): AppDatabase { fun getInstance(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) { return INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it }
@@ -104,7 +128,7 @@ abstract class AppDatabase : RoomDatabase() {
appContext, appContext,
AppDatabase::class.java, AppDatabase::class.java,
"satiea_local.db" "satiea_local.db"
).addMigrations(MIGRATION_1_2, MIGRATION_2_3) ).addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)
// Destructive migration is only permitted on debug builds // Destructive migration is only permitted on debug builds
if (BuildConfig.DEBUG) { if (BuildConfig.DEBUG) {
@@ -3,6 +3,7 @@ package com.example.data.local
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import java.text.Normalizer import java.text.Normalizer
@@ -11,19 +12,28 @@ data class LocalCustomFoodEntity(
@PrimaryKey val slugId: String, @PrimaryKey val slugId: String,
val name: String, val name: String,
val defaultUnit: String = FoodUnit.G.code, val defaultUnit: String = FoodUnit.G.code,
val category: String = "",
val updatedAt: Long = System.currentTimeMillis() val updatedAt: Long = System.currentTimeMillis()
) { ) {
fun toCustomFoodEntry(userId: String = ""): CustomFoodEntry { fun toCustomFoodEntry(): CustomFoodEntry {
return CustomFoodEntry( return CustomFoodEntry(
id = slugId, id = slugId,
userId = userId,
name = name, name = name,
defaultUnit = defaultUnit defaultUnit = defaultUnit,
category = category
) )
} }
fun resolvedCategory(): FoodCategory {
return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name)
}
companion object { companion object {
fun create(name: String, defaultUnit: FoodUnit): LocalCustomFoodEntity { fun create(
name: String,
defaultUnit: FoodUnit,
category: FoodCategory? = null
): LocalCustomFoodEntity {
val cleanName = name.trim().take(100) val cleanName = name.trim().take(100)
val slugId = Normalizer.normalize(cleanName.lowercase(), Normalizer.Form.NFD) val slugId = Normalizer.normalize(cleanName.lowercase(), Normalizer.Form.NFD)
.replace(Regex("[^a-z0-9]+"), "_") .replace(Regex("[^a-z0-9]+"), "_")
@@ -35,6 +45,7 @@ data class LocalCustomFoodEntity(
slugId = slugId, slugId = slugId,
name = cleanName, name = cleanName,
defaultUnit = defaultUnit.code, defaultUnit = defaultUnit.code,
category = category?.name ?: "",
updatedAt = System.currentTimeMillis() updatedAt = System.currentTimeMillis()
) )
} }
@@ -38,4 +38,22 @@ interface LocalMealDao {
@Insert(onConflict = OnConflictStrategy.REPLACE) @Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCustomFoods(foods: List<LocalCustomFoodEntity>) suspend fun insertCustomFoods(foods: List<LocalCustomFoodEntity>)
@Query("SELECT * FROM local_recipes ORDER BY updatedAt DESC")
fun observeAllRecipes(): Flow<List<LocalRecipeEntity>>
@Query("SELECT * FROM local_recipes ORDER BY updatedAt DESC")
suspend fun getAllRecipesOnce(): List<LocalRecipeEntity>
@Query("SELECT * FROM local_recipes WHERE id = :id LIMIT 1")
suspend fun getRecipeById(id: String): LocalRecipeEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRecipe(recipe: LocalRecipeEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertRecipes(recipes: List<LocalRecipeEntity>)
@Query("DELETE FROM local_recipes WHERE id = :id")
suspend fun deleteRecipeById(id: String)
} }
@@ -22,7 +22,6 @@ data class LocalMealEntity(
fun toMealEntry(): MealEntry { fun toMealEntry(): MealEntry {
return MealEntry( return MealEntry(
id = id, id = id,
userId = userId,
mealType = mealType, mealType = mealType,
mealTimestamp = mealTimestamp, mealTimestamp = mealTimestamp,
hungerBefore = hungerBefore, hungerBefore = hungerBefore,
@@ -38,7 +37,7 @@ data class LocalMealEntity(
fun fromMealEntry(meal: MealEntry): LocalMealEntity { fun fromMealEntry(meal: MealEntry): LocalMealEntity {
return LocalMealEntity( return LocalMealEntity(
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" }, id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
userId = meal.userId, userId = "",
mealType = meal.mealType, mealType = meal.mealType,
mealTimestamp = meal.mealTimestamp, mealTimestamp = meal.mealTimestamp,
hungerBefore = meal.hungerBefore, hungerBefore = meal.hungerBefore,
@@ -0,0 +1,58 @@
package com.example.data.local
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import java.util.UUID
@Entity(tableName = "local_recipes")
@TypeConverters(RoomConverters::class)
data class LocalRecipeEntity(
@PrimaryKey val id: String,
val title: String,
val categoryTag: String = RecipeCategoryTag.MAIN.name,
val prepTimeMinutes: Int = 0,
val servings: Int = 2,
val ingredients: List<String> = emptyList(),
val steps: List<String> = emptyList(),
val notes: String = "",
val photoUri: String? = null,
val updatedAt: Long = System.currentTimeMillis()
) {
fun toRecipeEntry(): RecipeEntry {
return RecipeEntry(
id = id,
title = title,
categoryTag = categoryTag,
prepTimeMinutes = prepTimeMinutes,
servings = servings.coerceAtLeast(1),
ingredientsSerialized = ingredients,
steps = steps,
notes = notes,
photoUri = photoUri,
updatedAt = updatedAt
)
}
companion object {
fun fromRecipeEntry(recipe: RecipeEntry): LocalRecipeEntity {
val resolvedId = recipe.id.ifBlank {
"recipe_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}"
}
return LocalRecipeEntity(
id = resolvedId,
title = recipe.title.trim().take(120),
categoryTag = recipe.categoryTag,
prepTimeMinutes = recipe.prepTimeMinutes.coerceAtLeast(0),
servings = recipe.servings.coerceAtLeast(1),
ingredients = recipe.ingredientsSerialized.take(40),
steps = recipe.steps.map { it.trim() }.filter { it.isNotBlank() }.take(30),
notes = recipe.notes.trim(),
photoUri = recipe.photoUri?.takeIf { it.isNotBlank() },
updatedAt = System.currentTimeMillis()
)
}
}
}
@@ -0,0 +1,329 @@
package com.example.data.model
import androidx.compose.ui.graphics.Color
import java.text.Normalizer
import java.util.Locale
/**
* Food categories aligned with the user's personal "Repères Alimentaires" reference sheet,
* each paired with an accessible semantic color palette for both Dark and Light themes.
*/
enum class FoodCategory(
val code: String,
val displayName: String,
val shortLabel: String,
val dailyGuide: String,
val alternativeNote: String? = null,
val darkDotColor: Color,
val lightDotColor: Color,
val darkContainerColor: Color,
val lightContainerColor: Color,
val darkContentColor: Color,
val lightContentColor: Color,
val darkBorderColor: Color,
val lightBorderColor: Color,
val showInBenchmarks: Boolean = true
) {
PROTEIN(
code = "PROTEIN",
displayName = "Viande, poisson, œufs",
shortLabel = "Viande / Œufs",
dailyGuide = "Env. 2 belles portions + 2 œufs / jour",
alternativeNote = "1 portion = 125–150 g",
darkDotColor = Color(0xFFE05A5A),
lightDotColor = Color(0xFFC62828),
darkContainerColor = Color(0xFF3A1D1D),
lightContainerColor = Color(0xFFFDECEC),
darkContentColor = Color(0xFFFFC5C5),
lightContentColor = Color(0xFF8E1B1B),
darkBorderColor = Color(0xFF703333),
lightBorderColor = Color(0xFFEFA9A9)
),
VEGETABLE(
code = "VEGETABLE",
displayName = "Légumes",
shortLabel = "Légumes",
dailyGuide = "Env. 200 g par repas",
darkDotColor = Color(0xFF5CC27E),
lightDotColor = Color(0xFF2E7D32),
darkContainerColor = Color(0xFF1A3524),
lightContainerColor = Color(0xFFE7F6EC),
darkContentColor = Color(0xFFBDF2CE),
lightContentColor = Color(0xFF1B5E20),
darkBorderColor = Color(0xFF2F6342),
lightBorderColor = Color(0xFFA5D6B7)
),
STARCH(
code = "STARCH",
displayName = "Féculents & légumineuses",
shortLabel = "Féculents",
dailyGuide = "Env. 90 g cru par repas",
alternativeNote = "Possibilité de réduire le pain et augmenter les féculents",
darkDotColor = Color(0xFFE5A84B),
lightDotColor = Color(0xFFB26A00),
darkContainerColor = Color(0xFF3A2C13),
lightContainerColor = Color(0xFFFEF4E2),
darkContentColor = Color(0xFFFCE0AD),
lightContentColor = Color(0xFF7A4700),
darkBorderColor = Color(0xFF6E5120),
lightBorderColor = Color(0xFFE8C482)
),
BREAD(
code = "BREAD",
displayName = "Pain",
shortLabel = "Pain",
dailyGuide = "Env. 3 à 4 morceaux par jour",
alternativeNote = "Équilibrable avec les féculents",
darkDotColor = Color(0xFFC99A6B),
lightDotColor = Color(0xFF8D5B2C),
darkContainerColor = Color(0xFF332417),
lightContainerColor = Color(0xFFF8EFE6),
darkContentColor = Color(0xFFF2D6BA),
lightContentColor = Color(0xFF663F1B),
darkBorderColor = Color(0xFF61452C),
lightBorderColor = Color(0xFFD9B898)
),
FRUIT(
code = "FRUIT",
displayName = "Fruits",
shortLabel = "Fruits",
dailyGuide = "1 ou 2 par jour",
darkDotColor = Color(0xFFF28B66),
lightDotColor = Color(0xFFD84315),
darkContainerColor = Color(0xFF3D2218),
lightContainerColor = Color(0xFFFEECE6),
darkContentColor = Color(0xFFFFCEBD),
lightContentColor = Color(0xFF9F2F0C),
darkBorderColor = Color(0xFF733E2B),
lightBorderColor = Color(0xFFF4B69F)
),
CHEESE(
code = "CHEESE",
displayName = "Fromage",
shortLabel = "Fromage",
dailyGuide = "Env. 30 g par jour",
darkDotColor = Color(0xFFFAF8F3),
lightDotColor = Color(0xFFFFFFFF),
darkContainerColor = Color(0xFF323330),
lightContainerColor = Color(0xFFFFFFFF),
darkContentColor = Color(0xFFF5F3EE),
lightContentColor = Color(0xFF3A3832),
darkBorderColor = Color(0xFFBDB8AC),
lightBorderColor = Color(0xFFBDB6A8)
),
DAIRY(
code = "DAIRY",
displayName = "Yaourt & fromage blanc",
shortLabel = "Laitages",
dailyGuide = "2 par jour",
alternativeNote = "Autres desserts (crèmes desserts…) OK dans un équilibre varié",
darkDotColor = Color(0xFFAED4F2),
lightDotColor = Color(0xFF4281B5),
darkContainerColor = Color(0xFF1D2C3A),
lightContainerColor = Color(0xFFECF5FC),
darkContentColor = Color(0xFFD7ECFC),
lightContentColor = Color(0xFF24527A),
darkBorderColor = Color(0xFF3B5A75),
lightBorderColor = Color(0xFFA7CBE8)
),
NUTS(
code = "NUTS",
displayName = "Fruits à coque",
shortLabel = "Fruits à coque",
dailyGuide = "Env. 30 g par jour",
darkDotColor = Color(0xFFA67B5B),
lightDotColor = Color(0xFF6D4C41),
darkContainerColor = Color(0xFF2E221A),
lightContainerColor = Color(0xFFF3EAE4),
darkContentColor = Color(0xFFE3C9B6),
lightContentColor = Color(0xFF4E342E),
darkBorderColor = Color(0xFF5C4232),
lightBorderColor = Color(0xFFCBB2A2)
),
FAT_SEASONING(
code = "FAT_SEASONING",
displayName = "Assaisonnement & cuisson",
shortLabel = "Huiles & beurre",
dailyGuide = "2–3 c.à.s d'huiles végétales + env. 20 g de beurre",
darkDotColor = Color(0xFFD9C54B),
lightDotColor = Color(0xFF9E8A0F),
darkContainerColor = Color(0xFF343014),
lightContainerColor = Color(0xFFFCF8DC),
darkContentColor = Color(0xFFF5EB9F),
lightContentColor = Color(0xFF6B5C00),
darkBorderColor = Color(0xFF696024),
lightBorderColor = Color(0xFFE0D27B)
),
PLEASURE(
code = "PLEASURE",
displayName = "Plaisir & douceurs",
shortLabel = "Plaisir",
dailyGuide = "Confitures, chocolat… Le plaisir fait partie de l'équilibre",
alternativeNote = "La restriction peut entraîner des fringales et déréguler le comportement alimentaire",
darkDotColor = Color(0xFFB88CE6),
lightDotColor = Color(0xFF7B43B8),
darkContainerColor = Color(0xFF2D1F3B),
lightContainerColor = Color(0xFFF4ECFC),
darkContentColor = Color(0xFFE3CEFA),
lightContentColor = Color(0xFF592A8C),
darkBorderColor = Color(0xFF5E3F7D),
lightBorderColor = Color(0xFFCDAEEB)
),
OTHER(
code = "OTHER",
displayName = "Boissons & divers",
shortLabel = "Autre",
dailyGuide = "Eau, infusions, café, divers",
darkDotColor = Color(0xFF98A69E),
lightDotColor = Color(0xFF607067),
darkContainerColor = Color(0xFF242B27),
lightContainerColor = Color(0xFFECEFED),
darkContentColor = Color(0xFFD0DAD4),
lightContentColor = Color(0xFF3C4741),
darkBorderColor = Color(0xFF4B5750),
lightBorderColor = Color(0xFFBDC7C1),
showInBenchmarks = false
);
fun dotColor(isDark: Boolean): Color = if (isDark) darkDotColor else lightDotColor
fun containerColor(isDark: Boolean): Color = if (isDark) darkContainerColor else lightContainerColor
fun contentColor(isDark: Boolean): Color = if (isDark) darkContentColor else lightContentColor
fun borderColor(isDark: Boolean): Color = if (isDark) darkBorderColor else lightBorderColor
companion object {
val benchmarkCategories: List<FoodCategory> = entries.filter { it.showInBenchmarks }
fun fromCode(code: String?): FoodCategory? {
if (code.isNullOrBlank()) return null
val cleaned = code.trim()
return entries.firstOrNull {
it.code.equals(cleaned, ignoreCase = true) ||
it.displayName.equals(cleaned, ignoreCase = true) ||
it.shortLabel.equals(cleaned, ignoreCase = true)
}
}
private fun normalize(text: String): String {
return Normalizer.normalize(text.lowercase(Locale.FRENCH).trim(), Normalizer.Form.NFD)
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
}
fun inferFromName(
name: String,
customCategoryLookup: Map<String, FoodCategory> = emptyMap()
): FoodCategory {
val trimmed = name.trim()
if (trimmed.isEmpty()) return OTHER
// 1. User-saved custom category takes highest precedence
val lowerExact = trimmed.lowercase(Locale.FRENCH)
customCategoryLookup[lowerExact]?.let { return it }
val norm = normalize(trimmed)
customCategoryLookup.entries.firstOrNull { normalize(it.key) == norm }?.value?.let { return it }
// 2. Exact match from built-in catalog
DefaultFoodCatalog.builtInFoods.firstOrNull {
normalize(it.name) == norm
}?.category?.let { return it }
// 3. Smart French keyword matching (ordered to avoid overlaps like "fromage blanc" vs "fromage", "beurre de cacahuete" vs "beurre")
return when {
// Nuts & nut butters first (before butter/fruits)
listOf("amande", "noix", "noisette", "pistache", "cacahuete", "cajou", "pecan", "macadamia", "pignon", "graine", "oleagineux", "fruit a coque", "fruits a coque", "puree d'amande", "beurre de cacahuete")
.any { norm.contains(it) } -> NUTS
// Dairy (before cheese so "fromage blanc" matches DAIRY, not CHEESE)
listOf("fromage blanc", "yaourt", "yogourt", "skyr", "petit suisse", "faisselle", "lait", "kefir", "creme dessert", "flan", "riz au lait", "danette", "activia")
.any { norm.contains(it) } -> DAIRY
// Cheese
listOf("fromage", "comte", "feta", "mozzarella", "camembert", "brie", "chevre", "emmental", "gruyere", "parmesan", "roquefort", "reblochon", "raclette", "cantal", "beaufort", "gouda", "cheddar", "burrata", "ricotta", "mascarpone", "kiri", "boursin", "st moret", "saint moret", "babybel", "morbier", "tome", "tomme", "munster", "bleu d'auvergne")
.any { norm.contains(it) } -> CHEESE
// Bread (before general starch)
listOf("pain", "baguette", "tartine", "biscotte", "wasa", "toast", "focaccia", "ciabatta", "miche", "seigle", "levain", "pita", "wrap", "tortilla", "naan")
.any { norm.contains(it) } -> BREAD
// Pleasure & sweets
listOf("chocolat", "confiture", "miel", "nutella", "pate a tartiner", "biscuit", "gateau", "patisserie", "croissant", "brioche", "glace", "sorbet", "bonbon", "cookie", "brownie", "tarte", "crepe", "gaufre", "muffin", "viennoiserie", "sucre", "caramel", "speculoos", "madeleine", "mousse au chocolat", "tiramisu")
.any { norm.contains(it) } -> PLEASURE
// Fats & seasoning
listOf("huile", "beurre", "margarine", "vinaigrette", "mayonnaise", "creme fraiche", "pesto", "sauce", "ghee", "graisse", "assaisonnement", "olive")
.any { norm.contains(it) } -> FAT_SEASONING
// Meat, Fish, Eggs, Plant Protein
listOf("poulet", "dinde", "boeuf", "steak", "veau", "porc", "agneau", "canard", "jambon", "lardon", "saucisse", "merguez", "viande", "bavette", "entrecote", "filet mignon", "escalope", "saumon", "cabillaud", "thon", "sardine", "maquereau", "truite", "colin", "merlu", "bar", "dorade", "crevette", "gambas", "moule", "huitre", "calamar", "poisson", "oeuf", "omelette", "tofu", "tempeh", "seitan", "boudin", "magret", "roti", "bacon", "charcuterie", "surimi")
.any { norm.contains(it) } -> PROTEIN
// Starches & Legumes
listOf("riz", "pate", "spaghetti", "tagliatelle", "penne", "macaroni", "coquillette", "quinoa", "avoine", "flocon", "patate", "pomme de terre", "frite", "puree", "semoule", "couscous", "boulgour", "ble", "ebly", "lentille", "pois chiche", "haricot rouge", "haricot blanc", "flageolet", "feve", "houmous", "polenta", "gnocchi", "ravioli", "lasagne", "muesli", "granola", "cereale", "sarrasin", "galette", "mais", "manioc", "feculent", "legumineuse")
.any { norm.contains(it) } -> STARCH
// Vegetables
listOf("brocoli", "courgette", "haricot vert", "epinard", "tomate", "concombre", "carotte", "salade", "laitue", "roquette", "mache", "endive", "avocat", "poivron", "champignon", "aubergine", "chou", "poireau", "oignon", "ail", "celeri", "radis", "betterave", "navet", "potiron", "courge", "butternut", "asperge", "artichaut", "petit pois", "fenouil", "ratatouille", "soupe", "veloute", "potage", "legume", "crudite", "confit d'oignon", "bette", "blette", "cresson", "panais", "topinambour")
.any { norm.contains(it) } -> VEGETABLE
// Fruits
listOf("pomme", "banane", "poire", "fraise", "myrtille", "framboise", "mure", "cassis", "groseille", "kiwi", "orange", "clementine", "mandarine", "pamplemousse", "citron", "raisin", "peche", "nectarine", "abricot", "prune", "cerise", "melon", "pasteque", "mangue", "ananas", "figue", "datte", "grenade", "litchi", "kaki", "compote", "salade de fruits", "fruit", "smoothie", "jus d'orange")
.any { norm.contains(it) } -> FRUIT
else -> OTHER
}
}
}
}
/**
* Personal dietary reference guide extracted from the user's "Repères Alimentaires" PDF.
*/
object DietaryReferenceGuide {
data class StarchEquivalence(val label: String, val amount: String)
data class SampleMealPlan(val mealTitle: String, val items: List<String>)
val starchEquivalences: List<StarchEquivalence> = listOf(
StarchEquivalence("Riz / pâtes crus", "Env. 90 g"),
StarchEquivalence("Riz / pâtes cuits", "Env. 220–270 g"),
StarchEquivalence("Pommes de terre crues", "Env. 390 g"),
StarchEquivalence("Légumineuses sèches (lentilles, pois chiches…)", "Env. 95 g"),
StarchEquivalence("Légumineuses en boîte", "Env. 330 g"),
StarchEquivalence("Pain", "Env. 120 g")
)
val sampleDayExamples: List<SampleMealPlan> = listOf(
SampleMealPlan(
mealTitle = "Petit-déjeuner",
items = listOf("1 pomme", "2 œufs", "1 tranche de pain")
),
SampleMealPlan(
mealTitle = "Déjeuner",
items = listOf(
"1 portion de viande, poisson ou œuf (125–150 g)",
"90 g de féculents (pesés crus)",
"200 g de légumes",
"Fromage (~30 g)",
"1 morceau de pain",
"Yaourt"
)
),
SampleMealPlan(
mealTitle = "Collation",
items = listOf("Fruits à coque (~30 g)")
),
SampleMealPlan(
mealTitle = "Dîner",
items = listOf(
"1 portion de viande, poisson ou œuf (125–150 g)",
"90 g de féculents (pesés crus)",
"200 g de légumes",
"1 morceau de pain",
"Yaourt",
"1 fruit"
)
)
)
const val PLEASURE_REMINDER =
"Le plaisir fait partie de l'équilibre alimentaire. La restriction peut entraîner des fringales et une alternance de contrôle / perte de contrôle qui dérégule le comportement alimentaire."
}
@@ -1,9 +1,5 @@
package com.example.data.model package com.example.data.model
import com.google.firebase.Timestamp
import com.google.firebase.firestore.DocumentId
import com.google.firebase.firestore.IgnoreExtraProperties
import com.google.firebase.firestore.ServerTimestamp
import java.util.Locale import java.util.Locale
enum class FoodUnit(val code: String, val label: String) { enum class FoodUnit(val code: String, val label: String) {
@@ -21,8 +17,13 @@ enum class FoodUnit(val code: String, val label: String) {
data class MealFoodItem( data class MealFoodItem(
val name: String, val name: String,
val weight: Double? = null, val weight: Double? = null,
val unit: FoodUnit = FoodUnit.G val unit: FoodUnit = FoodUnit.G,
val category: FoodCategory? = null
) { ) {
fun resolvedCategory(customCategoryLookup: Map<String, FoodCategory> = emptyMap()): FoodCategory {
return category ?: FoodCategory.inferFromName(name, customCategoryLookup)
}
fun serialize(): String { fun serialize(): String {
val cleanName = name.replace("|", " ").trim() val cleanName = name.replace("|", " ").trim()
val weightStr = if (weight != null && weight > 0.0) { val weightStr = if (weight != null && weight > 0.0) {
@@ -30,7 +31,11 @@ data class MealFoodItem(
} else { } else {
"" ""
} }
return "$cleanName|$weightStr|${unit.code}" return if (category != null) {
"$cleanName|$weightStr|${unit.code}|${category.code}"
} else {
"$cleanName|$weightStr|${unit.code}"
}
} }
fun formatWeight(): String? { fun formatWeight(): String? {
@@ -67,25 +72,25 @@ data class MealFoodItem(
if (name.isEmpty()) return null if (name.isEmpty()) return null
val weight = parts.getOrNull(1)?.trim()?.replace(",", ".")?.toDoubleOrNull() val weight = parts.getOrNull(1)?.trim()?.replace(",", ".")?.toDoubleOrNull()
val unit = FoodUnit.fromCode(parts.getOrNull(2) ?: "g") val unit = FoodUnit.fromCode(parts.getOrNull(2) ?: "g")
return MealFoodItem(name = name, weight = weight, unit = unit) val category = FoodCategory.fromCode(parts.getOrNull(3))
return MealFoodItem(name = name, weight = weight, unit = unit, category = category)
} }
} }
} }
@IgnoreExtraProperties
data class CustomFoodEntry( data class CustomFoodEntry(
@DocumentId val id: String = "", val id: String = "",
val userId: String = "",
val name: String = "", val name: String = "",
val defaultUnit: String = FoodUnit.G.code, val defaultUnit: String = FoodUnit.G.code,
@ServerTimestamp val createdAt: Timestamp? = null, val category: String = ""
@ServerTimestamp val updatedAt: Timestamp? = null ) {
) fun resolvedCategory(): FoodCategory {
return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name)
}
}
@IgnoreExtraProperties
data class MealEntry( data class MealEntry(
@DocumentId val id: String = "", val id: String = "",
val userId: String = "",
val mealType: String = MealType.LUNCH.name, val mealType: String = MealType.LUNCH.name,
val mealTimestamp: Long = System.currentTimeMillis(), val mealTimestamp: Long = System.currentTimeMillis(),
val hungerBefore: Int = 5, val hungerBefore: Int = 5,
@@ -93,9 +98,7 @@ data class MealEntry(
val note: String = "", val note: String = "",
val foodItemsSerialized: List<String> = emptyList(), val foodItemsSerialized: List<String> = emptyList(),
val photoUris: List<String> = emptyList(), val photoUris: List<String> = emptyList(),
val photosBase64: List<String> = emptyList(), val photosBase64: List<String> = emptyList()
@ServerTimestamp val createdAt: Timestamp? = null,
@ServerTimestamp val updatedAt: Timestamp? = null
) { ) {
val displayPhotoUris: List<String> val displayPhotoUris: List<String>
get() = photoUris.ifEmpty { photosBase64 } get() = photoUris.ifEmpty { photosBase64 }
@@ -103,22 +106,6 @@ data class MealEntry(
fun parsedFoodItems(): List<MealFoodItem> { fun parsedFoodItems(): List<MealFoodItem> {
return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) } return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) }
} }
fun toMap(): Map<String, Any?> {
val map = mutableMapOf<String, Any?>(
"userId" to userId,
"mealType" to mealType,
"mealTimestamp" to mealTimestamp,
"hungerBefore" to hungerBefore.coerceIn(1, 10),
"satietyAfter" to satietyAfter.coerceIn(1, 10),
"note" to note,
"foodItemsSerialized" to foodItemsSerialized.take(30),
"photoUris" to photoUris.take(6),
"createdAt" to createdAt,
"updatedAt" to updatedAt
)
return map.filterValues { it != null }
}
} }
enum class MealType(val displayName: String, val defaultTime: String) { enum class MealType(val displayName: String, val defaultTime: String) {
@@ -129,86 +116,119 @@ enum class MealType(val displayName: String, val defaultTime: String) {
companion object { companion object {
fun fromString(value: String): MealType { fun fromString(value: String): MealType {
return entries.firstOrNull { it.name.equals(value, ignoreCase = true) } ?: LUNCH return entries.firstOrNull {
it.name.equals(value.trim(), ignoreCase = true) ||
it.displayName.equals(value.trim(), ignoreCase = true)
} ?: LUNCH
} }
} }
} }
object DefaultFoodCatalog { object DefaultFoodCatalog {
data class CatalogFood(val name: String, val defaultUnit: FoodUnit = FoodUnit.G) data class CatalogFood(
val name: String,
val defaultUnit: FoodUnit = FoodUnit.G,
val category: FoodCategory = FoodCategory.OTHER
)
val builtInFoods: List<CatalogFood> = listOf( val builtInFoods: List<CatalogFood> = listOf(
// Féculents & Céréales // Viande, poisson, œufs (Rouge)
CatalogFood("Riz basmati", FoodUnit.G), CatalogFood("Blanc de poulet", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Riz complet", FoodUnit.G), CatalogFood("Filet de dinde", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Pâtes complètes", FoodUnit.G), CatalogFood("Pavé de saumon", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Pâtes", FoodUnit.G), CatalogFood("Cabillaud", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Quinoa", FoodUnit.G), CatalogFood("Thon", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Flocons d'avoine", FoodUnit.G), CatalogFood("Œufs", FoodUnit.PORTION, FoodCategory.PROTEIN),
CatalogFood("Pain complet", FoodUnit.G), CatalogFood("Tofu ferme", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Pain au levain", FoodUnit.G), CatalogFood("Steak haché", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Patate douce", FoodUnit.G), CatalogFood("Jambon blanc", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Pommes de terre", FoodUnit.G), CatalogFood("Crevettes", FoodUnit.G, FoodCategory.PROTEIN),
CatalogFood("Semoule", FoodUnit.G),
CatalogFood("Lentilles corail", FoodUnit.G), // Légumes (Vert)
CatalogFood("Lentilles vertes", FoodUnit.G), CatalogFood("Brocoli", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Pois chiches", FoodUnit.G), CatalogFood("Courgettes", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Haricots rouges", FoodUnit.G), CatalogFood("Haricots verts", FoodUnit.G, FoodCategory.VEGETABLE),
// Protéines CatalogFood("Épinards", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Blanc de poulet", FoodUnit.G), CatalogFood("Tomates", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Filet de dinde", FoodUnit.G), CatalogFood("Concombre", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Pavé de saumon", FoodUnit.G), CatalogFood("Carottes râpées", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Cabillaud", FoodUnit.G), CatalogFood("Salade verte", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Thon", FoodUnit.G), CatalogFood("Avocat", FoodUnit.PORTION, FoodCategory.VEGETABLE),
CatalogFood("Œufs", FoodUnit.PORTION), CatalogFood("Poivrons", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Tofu ferme", FoodUnit.G), CatalogFood("Champignons", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Steak haché", FoodUnit.G), CatalogFood("Aubergine", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Jambon blanc", FoodUnit.G), CatalogFood("Chou-fleur", FoodUnit.G, FoodCategory.VEGETABLE),
CatalogFood("Crevettes", FoodUnit.G), CatalogFood("Soupe de légumes", FoodUnit.ML, FoodCategory.VEGETABLE),
// Légumes
CatalogFood("Brocoli", FoodUnit.G), // Féculents & Légumineuses (Ambre doré)
CatalogFood("Courgettes", FoodUnit.G), CatalogFood("Riz basmati", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Haricots verts", FoodUnit.G), CatalogFood("Riz complet", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Épinards", FoodUnit.G), CatalogFood("Pâtes complètes", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Tomates", FoodUnit.G), CatalogFood("Pâtes", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Concombre", FoodUnit.G), CatalogFood("Quinoa", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Carottes râpées", FoodUnit.G), CatalogFood("Flocons d'avoine", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Salade verte", FoodUnit.G), CatalogFood("Patate douce", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Avocat", FoodUnit.PORTION), CatalogFood("Pommes de terre", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Poivrons", FoodUnit.G), CatalogFood("Semoule", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Champignons", FoodUnit.G), CatalogFood("Lentilles corail", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Aubergine", FoodUnit.G), CatalogFood("Lentilles vertes", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Chou-fleur", FoodUnit.G), CatalogFood("Pois chiches", FoodUnit.G, FoodCategory.STARCH),
// Produits laitiers & Alternatives CatalogFood("Haricots rouges", FoodUnit.G, FoodCategory.STARCH),
CatalogFood("Fromage blanc", FoodUnit.G),
CatalogFood("Skyr", FoodUnit.G), // Pain (Ocre blé)
CatalogFood("Yaourt nature", FoodUnit.PORTION), CatalogFood("Pain complet", FoodUnit.G, FoodCategory.BREAD),
CatalogFood("Comté", FoodUnit.G), CatalogFood("Pain au levain", FoodUnit.G, FoodCategory.BREAD),
CatalogFood("Feta", FoodUnit.G), CatalogFood("Baguette tradition", FoodUnit.PORTION, FoodCategory.BREAD),
CatalogFood("Mozzarella", FoodUnit.G), CatalogFood("Tranche de pain", FoodUnit.PORTION, FoodCategory.BREAD),
CatalogFood("Lait demi-écrémé", FoodUnit.ML),
CatalogFood("Lait d'amande", FoodUnit.ML), // Fromage (Blanc ivoire)
CatalogFood("Lait d'avoine", FoodUnit.ML), CatalogFood("Comté", FoodUnit.G, FoodCategory.CHEESE),
// Fruits & Oléagineux CatalogFood("Feta", FoodUnit.G, FoodCategory.CHEESE),
CatalogFood("Pomme", FoodUnit.PORTION), CatalogFood("Mozzarella", FoodUnit.G, FoodCategory.CHEESE),
CatalogFood("Banane", FoodUnit.PORTION), CatalogFood("Chèvre frais", FoodUnit.G, FoodCategory.CHEESE),
CatalogFood("Poire", FoodUnit.PORTION), CatalogFood("Camembert", FoodUnit.G, FoodCategory.CHEESE),
CatalogFood("Fraises", FoodUnit.G),
CatalogFood("Myrtilles", FoodUnit.G), // Yaourt & Fromage blanc (Bleu lacté)
CatalogFood("Framboises", FoodUnit.G), CatalogFood("Fromage blanc", FoodUnit.G, FoodCategory.DAIRY),
CatalogFood("Kiwi", FoodUnit.PORTION), CatalogFood("Skyr", FoodUnit.G, FoodCategory.DAIRY),
CatalogFood("Orange", FoodUnit.PORTION), CatalogFood("Yaourt nature", FoodUnit.PORTION, FoodCategory.DAIRY),
CatalogFood("Amandes", FoodUnit.G), CatalogFood("Lait demi-écrémé", FoodUnit.ML, FoodCategory.DAIRY),
CatalogFood("Noix", FoodUnit.G), CatalogFood("Lait d'amande", FoodUnit.ML, FoodCategory.DAIRY),
CatalogFood("Noix de cajou", FoodUnit.G), CatalogFood("Lait d'avoine", FoodUnit.ML, FoodCategory.DAIRY),
CatalogFood("Beurre de cacahuète", FoodUnit.G),
CatalogFood("Chocolat noir", FoodUnit.G), // Fruits (Corail)
// Boissons & Soupes CatalogFood("Pomme", FoodUnit.PORTION, FoodCategory.FRUIT),
CatalogFood("Soupe de légumes", FoodUnit.ML), CatalogFood("Banane", FoodUnit.PORTION, FoodCategory.FRUIT),
CatalogFood("Café", FoodUnit.ML), CatalogFood("Poire", FoodUnit.PORTION, FoodCategory.FRUIT),
CatalogFood("Thé vert", FoodUnit.ML), CatalogFood("Fraises", FoodUnit.G, FoodCategory.FRUIT),
CatalogFood("Jus d'orange pressé", FoodUnit.ML), CatalogFood("Myrtilles", FoodUnit.G, FoodCategory.FRUIT),
CatalogFood("Smoothie", FoodUnit.ML) CatalogFood("Framboises", FoodUnit.G, FoodCategory.FRUIT),
CatalogFood("Kiwi", FoodUnit.PORTION, FoodCategory.FRUIT),
CatalogFood("Orange", FoodUnit.PORTION, FoodCategory.FRUIT),
CatalogFood("Jus d'orange pressé", FoodUnit.ML, FoodCategory.FRUIT),
CatalogFood("Smoothie", FoodUnit.ML, FoodCategory.FRUIT),
// Fruits à coque (Brun noisette)
CatalogFood("Amandes", FoodUnit.G, FoodCategory.NUTS),
CatalogFood("Noix", FoodUnit.G, FoodCategory.NUTS),
CatalogFood("Noix de cajou", FoodUnit.G, FoodCategory.NUTS),
CatalogFood("Noisettes", FoodUnit.G, FoodCategory.NUTS),
CatalogFood("Beurre de cacahuète", FoodUnit.G, FoodCategory.NUTS),
// Assaisonnement & cuisson (Jaune huile d'olive)
CatalogFood("Huile d'olive", FoodUnit.PORTION, FoodCategory.FAT_SEASONING),
CatalogFood("Huile de colza", FoodUnit.PORTION, FoodCategory.FAT_SEASONING),
CatalogFood("Beurre", FoodUnit.G, FoodCategory.FAT_SEASONING),
CatalogFood("Vinaigrette", FoodUnit.PORTION, FoodCategory.FAT_SEASONING),
// Plaisir & douceurs (Prune)
CatalogFood("Chocolat noir", FoodUnit.G, FoodCategory.PLEASURE),
CatalogFood("Confiture", FoodUnit.PORTION, FoodCategory.PLEASURE),
CatalogFood("Miel", FoodUnit.PORTION, FoodCategory.PLEASURE),
// Boissons & divers
CatalogFood("Café", FoodUnit.ML, FoodCategory.OTHER),
CatalogFood("Thé vert", FoodUnit.ML, FoodCategory.OTHER)
) )
} }
@@ -0,0 +1,83 @@
package com.example.data.model
import java.util.Locale
enum class RecipeCategoryTag(val displayName: String) {
MAIN("Plat complet"),
BREAKFAST("Petit-déjeuner"),
SNACK("Collation"),
DESSERT("Dessert"),
SIDE("Accompagnement");
companion object {
fun fromString(raw: String?): RecipeCategoryTag {
if (raw.isNullOrBlank()) return MAIN
val trimmed = raw.trim()
return entries.firstOrNull {
it.name.equals(trimmed, ignoreCase = true) ||
it.displayName.equals(trimmed, ignoreCase = true)
} ?: MAIN
}
}
}
data class RecipeEntry(
val id: String = "",
val title: String = "",
val categoryTag: String = RecipeCategoryTag.MAIN.name,
val prepTimeMinutes: Int = 20,
val servings: Int = 2,
val ingredientsSerialized: List<String> = emptyList(),
val steps: List<String> = emptyList(),
val notes: String = "",
val photoUri: String? = null,
val updatedAt: Long = System.currentTimeMillis()
) {
fun parsedIngredients(): List<MealFoodItem> {
return ingredientsSerialized.mapNotNull { MealFoodItem.deserialize(it) }
}
/**
* Scales ingredient weights proportionally for a desired number of servings.
*/
fun scaledIngredients(targetServings: Double): List<MealFoodItem> {
val baseServings = servings.coerceAtLeast(1).toDouble()
val ratio = (targetServings / baseServings).coerceAtLeast(0.1)
return parsedIngredients().map { item ->
val scaledWeight = item.weight?.let { w ->
val raw = w * ratio
// Round nicely to 1 decimal or nearest integer for grams/ml
if (item.unit == FoodUnit.PORTION) {
Math.round(raw * 10.0) / 10.0
} else {
Math.round(raw).toDouble().coerceAtLeast(1.0)
}
}
item.copy(weight = scaledWeight)
}
}
fun categoryEnum(): RecipeCategoryTag = RecipeCategoryTag.fromString(categoryTag)
fun dominantCategories(customCategories: Map<String, FoodCategory> = emptyMap()): List<FoodCategory> {
return parsedIngredients()
.map { it.resolvedCategory(customCategories) }
.distinct()
.take(5)
}
fun formatServingsLabel(): String {
val s = servings.coerceAtLeast(1)
return if (s == 1) "1 portion" else "$s portions"
}
fun formatPrepTimeLabel(): String {
val m = prepTimeMinutes.coerceAtLeast(0)
return when {
m == 0 -> "Rapide"
m < 60 -> "$m min"
m % 60 == 0 -> "${m / 60} h"
else -> String.format(Locale.FRENCH, "%d h %02d", m / 60, m % 60)
}
}
}
@@ -0,0 +1,28 @@
package com.example.data.preferences
import android.content.Context
import android.content.SharedPreferences
import com.example.ui.theme.AppThemeMode
/**
* Persists the user's selected theme mode (Dark, Light, System) locally on device.
*/
class ThemePreferencesManager(context: Context) {
private val prefs: SharedPreferences =
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun loadThemeMode(): AppThemeMode {
val raw = prefs.getString(KEY_THEME_MODE, AppThemeMode.DARK.name)
return AppThemeMode.entries.firstOrNull { it.name == raw } ?: AppThemeMode.DARK
}
fun saveThemeMode(mode: AppThemeMode) {
prefs.edit().putString(KEY_THEME_MODE, mode.name).apply()
}
companion object {
private const val PREFS_NAME = "satiea_theme_prefs"
private const val KEY_THEME_MODE = "theme_mode"
}
}
@@ -1,51 +0,0 @@
package com.example.data.repository
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestoreException
import kotlinx.coroutines.CancellationException
import org.json.JSONArray
import org.json.JSONObject
enum class OperationType(val value: String) {
CREATE("create"),
UPDATE("update"),
DELETE("delete"),
LIST("list"),
GET("get"),
WRITE("write"),
}
fun handleFirestoreError(exception: Throwable, operationType: OperationType, path: String?): String {
val causes = generateSequence(exception) { it.cause }
val rootError = causes.firstOrNull { it is FirebaseFirestoreException }
?: causes.firstOrNull { it !is CancellationException }
?: exception
val auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser
val providerInfoList = currentUser?.providerData?.map { provider ->
JSONObject().apply {
put("providerId", provider.providerId)
}
} ?: emptyList()
val authInfoJson = JSONObject().apply {
put("userId", currentUser?.uid)
put("emailVerified", currentUser?.isEmailVerified)
put("tenantId", currentUser?.tenantId)
put("providerInfo", JSONArray(providerInfoList))
}
val errorInfoJson = JSONObject().apply {
put("error", rootError.message ?: rootError.toString())
put("operationType", operationType.value)
put("path", path)
put("authInfo", authInfoJson)
}
val jsonString = errorInfoJson.toString()
Log.e("FirestoreError", "Firestore Error: $jsonString")
return jsonString
}
@@ -2,276 +2,78 @@ package com.example.data.repository
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.util.Log
import com.example.R
import com.example.data.local.AppDatabase import com.example.data.local.AppDatabase
import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalMealDao import com.example.data.local.LocalMealDao
import com.example.data.local.LocalMealEntity import com.example.data.local.LocalMealEntity
import com.example.data.local.LocalRecipeEntity
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.RecipeEntry
import com.example.util.CsvImportResult import com.example.util.CsvImportResult
import com.example.util.CsvImporter import com.example.util.CsvImporter
import com.example.util.ImageUtils import com.example.util.ImageUtils
import com.example.widget.SatieaAppWidgetProvider import com.example.widget.SatieaAppWidgetProvider
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.Query
import com.google.firebase.firestore.snapshots
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.tasks.await
import java.text.Normalizer
import java.util.UUID import java.util.UUID
/**
* Pure local Room repository for Satiéa.
* All meals, custom foods, and recipes live locally on device, while optional
* backup and restoration use the user's personal Google Drive / Sheets.
*/
class MealRepository( class MealRepository(
private val localMealDao: LocalMealDao?, private val localMealDao: LocalMealDao,
private val db: FirebaseFirestore?,
private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth,
private val context: Context? = null private val context: Context? = null
) { ) {
// Constructor used by ViewModel in app runtime
constructor(context: Context) : this( constructor(context: Context) : this(
localMealDao = AppDatabase.getInstance(context).mealDao(), localMealDao = AppDatabase.getInstance(context).mealDao(),
db = try {
FirebaseFirestore.getInstance(
context.applicationContext.getString(R.string.firestore_database_id)
)
} catch (_: Exception) {
try {
FirebaseFirestore.getInstance()
} catch (_: Exception) {
null
}
},
context = context.applicationContext context = context.applicationContext
) )
// Secondary constructor for Firestore rule tests without local DB // ------------------------------------------------------------------------
constructor(db: FirebaseFirestore) : this( // Meals
localMealDao = null, // ------------------------------------------------------------------------
db = db,
auth = FirebaseAuth.getInstance(db.app),
context = null
)
private fun getUserIdOrNull(): String? {
return auth.currentUser?.uid
}
private fun requireUserId(): String {
return auth.currentUser?.uid
?: throw IllegalStateException("User must be signed in with Google before accessing Firestore.")
}
fun observeMeals(): Flow<List<MealEntry>> { fun observeMeals(): Flow<List<MealEntry>> {
if (localMealDao != null) { return localMealDao.observeAllMeals().map { entities ->
return localMealDao.observeAllMeals().map { entities -> entities.map { it.toMealEntry() }
entities.map { it.toMealEntry() }
}
}
// Fallback for tests or remote-only mode
return flow {
val uid = requireUserId()
val firestore = db ?: throw IllegalStateException("Firestore is null")
val path = "users/$uid/meals"
emitAll(
firestore.collection("users").document(uid).collection("meals")
.orderBy("mealTimestamp", Query.Direction.DESCENDING)
.snapshots()
.map { snapshot ->
snapshot.toObjects(MealEntry::class.java)
}
.catch { error ->
val firestoreError = generateSequence(error) { it.cause }
.filterIsInstance<FirebaseFirestoreException>()
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
val exceptionToLog = firestoreError ?: (error as? Exception)
if (exceptionToLog != null) {
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
}
throw error
}
)
} }
} }
fun observeCustomFoods(): Flow<List<CustomFoodEntry>> { suspend fun getMealById(mealId: String): Result<MealEntry> {
if (localMealDao != null) { val local = localMealDao.getMealById(mealId)
return localMealDao.observeAllCustomFoods().map { entities -> return if (local != null) {
entities.map { it.toCustomFoodEntry(getUserIdOrNull().orEmpty()) } Result.success(local.toMealEntry())
} } else {
} Result.failure(NoSuchElementException("Meal not found"))
return flow {
val uid = requireUserId()
val firestore = db ?: throw IllegalStateException("Firestore is null")
val path = "users/$uid/custom_foods"
emitAll(
firestore.collection("users").document(uid).collection("custom_foods")
.orderBy("name", Query.Direction.ASCENDING)
.snapshots()
.map { snapshot ->
snapshot.toObjects(CustomFoodEntry::class.java)
}
.catch { error ->
val firestoreError = generateSequence(error) { it.cause }
.filterIsInstance<FirebaseFirestoreException>()
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
val exceptionToLog = firestoreError ?: (error as? Exception)
if (exceptionToLog != null) {
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
}
throw error
}
)
}
}
suspend fun saveCustomFood(name: String, defaultUnit: FoodUnit): Result<String> {
val trimmedName = name.trim().take(100)
if (trimmedName.isBlank()) return Result.failure(IllegalArgumentException("Food name is blank"))
val localEntity = LocalCustomFoodEntity.create(trimmedName, defaultUnit)
localMealDao?.insertCustomFood(localEntity)
val uid = getUserIdOrNull()
if (uid != null && db != null) {
val slugId = localEntity.slugId
val docRef = db.collection("users").document(uid).collection("custom_foods").document(slugId)
try {
val payload = mapOf(
"userId" to uid,
"name" to trimmedName,
"defaultUnit" to defaultUnit.code,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
docRef.set(payload).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.CREATE, docRef.path)
return Result.failure(e)
}
Log.w("MealRepository", "Could not sync custom food to Firestore: ${e.message}")
}
}
return Result.success(localEntity.slugId)
}
suspend fun getMealById(mealId: String, ownerId: String? = null): Result<MealEntry> {
if (localMealDao != null) {
val local = localMealDao.getMealById(mealId)
if (local != null) return Result.success(local.toMealEntry())
}
val uid = ownerId ?: requireUserId()
val firestore = db ?: return Result.failure(NoSuchElementException("Meal not found"))
val path = "users/$uid/meals/$mealId"
return try {
val doc = firestore.collection("users").document(uid).collection("meals").document(mealId).get().await()
val entry = doc.toObject(MealEntry::class.java)
if (entry != null) {
Result.success(entry)
} else {
Result.failure(NoSuchElementException("Meal not found"))
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
handleFirestoreError(e, OperationType.GET, path)
Result.failure(e)
} }
} }
suspend fun addMeal(meal: MealEntry): Result<String> { suspend fun addMeal(meal: MealEntry): Result<String> {
val resolvedId = meal.id.ifBlank { "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}" } val resolvedId = meal.id.ifBlank {
val mealWithId = meal.copy(id = resolvedId) "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}"
// 1. Always save to local SQLite Room first (Offline-First)
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId))
SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. If user is signed in with Google, sync to Firestore
val uid = getUserIdOrNull()
if (uid != null && db != null) {
val path = "users/$uid/meals"
try {
val mealsRef = db.collection("users").document(uid).collection("meals")
val payload = mealWithId.toMap() + mapOf(
"userId" to uid,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
val docRef = mealsRef.document(resolvedId)
docRef.set(payload).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.CREATE, path)
return Result.failure(e)
}
Log.w("MealRepository", "Could not sync meal to Firestore: ${e.message}")
}
} }
val mealWithId = meal.copy(id = resolvedId)
localMealDao.insertMeal(LocalMealEntity.fromMealEntry(mealWithId))
SatieaAppWidgetProvider.updateAllWidgets(context)
return Result.success(resolvedId) return Result.success(resolvedId)
} }
suspend fun updateMeal(meal: MealEntry): Result<Unit> { suspend fun updateMeal(meal: MealEntry): Result<Unit> {
require(meal.id.isNotBlank()) { "Meal ID must not be blank for update" } require(meal.id.isNotBlank()) { "Meal ID must not be blank for update" }
localMealDao.insertMeal(LocalMealEntity.fromMealEntry(meal))
// 1. Update in local Room database
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal))
SatieaAppWidgetProvider.updateAllWidgets(context) SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. If signed in, update Firestore
val uid = getUserIdOrNull()
if (uid != null && db != null) {
val docRef = db.collection("users").document(uid).collection("meals").document(meal.id)
try {
val updates = mapOf(
"mealType" to meal.mealType,
"mealTimestamp" to meal.mealTimestamp,
"hungerBefore" to meal.hungerBefore.coerceIn(1, 10),
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
"note" to meal.note,
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
"photoUris" to meal.photoUris.take(6),
"updatedAt" to FieldValue.serverTimestamp()
)
docRef.update(updates).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
return Result.failure(e)
}
Log.w("MealRepository", "Could not sync meal update to Firestore: ${e.message}")
}
}
return Result.success(Unit) return Result.success(Unit)
} }
suspend fun deleteMeal(mealId: String): Result<Unit> { suspend fun deleteMeal(mealId: String): Result<Unit> {
// 1. Clean up local photo files val existingMeal = localMealDao.getMealById(mealId)?.toMealEntry()
val existingMeal = localMealDao?.getMealById(mealId)?.toMealEntry()
existingMeal?.displayPhotoUris?.forEach { uri -> existingMeal?.displayPhotoUris?.forEach { uri ->
if (context != null) { if (context != null) {
ImageUtils.deletePhotoFile(context, uri) ImageUtils.deletePhotoFile(context, uri)
@@ -279,116 +81,110 @@ class MealRepository(
ImageUtils.deletePhotoFile(uri) ImageUtils.deletePhotoFile(uri)
} }
} }
localMealDao.deleteMealById(mealId)
// 2. Delete from local Room database
localMealDao?.deleteMealById(mealId)
SatieaAppWidgetProvider.updateAllWidgets(context) SatieaAppWidgetProvider.updateAllWidgets(context)
// 3. If signed in, delete from Firestore
val uid = getUserIdOrNull()
if (uid != null && db != null) {
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
try {
docRef.delete().await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.DELETE, docRef.path)
return Result.failure(e)
}
Log.w("MealRepository", "Could not delete from Firestore: ${e.message}")
}
}
return Result.success(Unit) return Result.success(Unit)
} }
suspend fun getAllMealsSnapshot(): List<MealEntry> { suspend fun getAllMealsSnapshot(): List<MealEntry> {
if (localMealDao != null) { return localMealDao.getAllMealsOnce().map { it.toMealEntry() }
return localMealDao.getAllMealsOnce().map { it.toMealEntry() } }
// ------------------------------------------------------------------------
// Custom Foods Catalog
// ------------------------------------------------------------------------
fun observeCustomFoods(): Flow<List<CustomFoodEntry>> {
return localMealDao.observeAllCustomFoods().map { entities ->
entities.map { it.toCustomFoodEntry() }
} }
val uid = getUserIdOrNull() ?: return emptyList() }
val firestore = db ?: return emptyList()
return try { suspend fun saveCustomFood(
firestore.collection("users").document(uid).collection("meals") name: String,
.orderBy("mealTimestamp", Query.Direction.DESCENDING) defaultUnit: FoodUnit,
.get() category: FoodCategory? = null
.await() ): Result<String> {
.toObjects(MealEntry::class.java) val trimmedName = name.trim().take(100)
} catch (_: Exception) { if (trimmedName.isBlank()) {
emptyList() return Result.failure(IllegalArgumentException("Food name is blank"))
} }
val localEntity = LocalCustomFoodEntity.create(trimmedName, defaultUnit, category)
localMealDao.insertCustomFood(localEntity)
return Result.success(localEntity.slugId)
} }
suspend fun getAllCustomFoodsSnapshot(): List<LocalCustomFoodEntity> { suspend fun getAllCustomFoodsSnapshot(): List<LocalCustomFoodEntity> {
if (localMealDao != null) { return localMealDao.getAllCustomFoodsOnce()
return localMealDao.getAllCustomFoodsOnce() }
}
val uid = getUserIdOrNull() ?: return emptyList() // ------------------------------------------------------------------------
val firestore = db ?: return emptyList() // Recipes
return try { // ------------------------------------------------------------------------
firestore.collection("users").document(uid).collection("custom_foods")
.orderBy("name", Query.Direction.ASCENDING) fun observeRecipes(): Flow<List<RecipeEntry>> {
.get() return localMealDao.observeAllRecipes().map { entities ->
.await() entities.map { it.toRecipeEntry() }
.toObjects(CustomFoodEntry::class.java)
.map {
LocalCustomFoodEntity(
slugId = it.id,
name = it.name,
defaultUnit = it.defaultUnit
)
}
} catch (_: Exception) {
emptyList()
} }
} }
suspend fun getRecipeById(recipeId: String): Result<RecipeEntry> {
val local = localMealDao.getRecipeById(recipeId)
return if (local != null) {
Result.success(local.toRecipeEntry())
} else {
Result.failure(NoSuchElementException("Recipe not found"))
}
}
suspend fun saveRecipe(recipe: RecipeEntry): Result<String> {
if (recipe.title.isBlank()) {
return Result.failure(IllegalArgumentException("Recipe title is blank"))
}
val entity = LocalRecipeEntity.fromRecipeEntry(recipe)
localMealDao.insertRecipe(entity)
return Result.success(entity.id)
}
suspend fun deleteRecipe(recipeId: String): Result<Unit> {
val existing = localMealDao.getRecipeById(recipeId)
existing?.photoUri?.let { uri ->
if (context != null) {
ImageUtils.deletePhotoFile(context, uri)
} else {
ImageUtils.deletePhotoFile(uri)
}
}
localMealDao.deleteRecipeById(recipeId)
return Result.success(Unit)
}
suspend fun getAllRecipesSnapshot(): List<RecipeEntry> {
return localMealDao.getAllRecipesOnce().map { it.toRecipeEntry() }
}
// ------------------------------------------------------------------------
// CSV Import & Google Sheets Restoration
// ------------------------------------------------------------------------
suspend fun importMealsFromCsv(context: Context, uri: Uri): Result<CsvImportResult> { suspend fun importMealsFromCsv(context: Context, uri: Uri): Result<CsvImportResult> {
return try { return try {
val existingMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList() val existingMeals = localMealDao.getAllMealsOnce().map { it.toMealEntry() }
val result = CsvImporter.importFromUri(context, uri, existingMeals).getOrThrow() val result = CsvImporter.importFromUri(context, uri, existingMeals).getOrThrow()
// 1. Insert new meals into Room
val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) } val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) }
localMealDao?.insertMeals(localEntities) localMealDao.insertMeals(localEntities)
SatieaAppWidgetProvider.updateAllWidgets(context) SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. Enrich custom foods catalog in Room
val newCustomFoods = result.newFoodItems.map { item -> val newCustomFoods = result.newFoodItems.map { item ->
LocalCustomFoodEntity.create(item.name, item.unit) LocalCustomFoodEntity.create(
name = item.name,
defaultUnit = item.unit,
category = item.category ?: FoodCategory.inferFromName(item.name)
)
} }
localMealDao?.insertCustomFoods(newCustomFoods) if (newCustomFoods.isNotEmpty()) {
localMealDao.insertCustomFoods(newCustomFoods)
// 3. If signed in, sync newly imported meals and foods to Cloud
val uid = getUserIdOrNull()
if (uid != null && db != null) {
for (meal in result.importedMeals) {
try {
val payload = meal.toMap() + mapOf(
"userId" to uid,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
db.collection("users").document(uid).collection("meals").document(meal.id).set(payload).await()
} catch (e: Exception) {
Log.w("MealRepository", "Sync imported meal error: ${e.message}")
}
}
for (food in newCustomFoods) {
try {
val payload = mapOf(
"userId" to uid,
"name" to food.name,
"defaultUnit" to food.defaultUnit,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
db.collection("users").document(uid).collection("custom_foods").document(food.slugId).set(payload).await()
} catch (e: Exception) {
Log.w("MealRepository", "Sync imported food error: ${e.message}")
}
}
} }
Result.success(result) Result.success(result)
@@ -398,144 +194,77 @@ class MealRepository(
} }
} }
suspend fun syncCloudToLocal(): Result<Int> { /**
val uid = getUserIdOrNull() ?: return Result.failure(IllegalStateException("No Google account signed in")) * Merges restored meals, custom foods, and recipes from Google Sheets into Room
val firestore = db ?: return Result.failure(IllegalStateException("Firestore is not available")) * without duplicating existing entries.
*
return try { * @return Triple(newMealsCount, newFoodsCount, newRecipesCount)
// 1. Fetch remote meals */
val remoteMealsSnapshot = firestore.collection("users").document(uid).collection("meals").get().await() suspend fun insertRestoredData(
val remoteMeals = remoteMealsSnapshot.toObjects(MealEntry::class.java)
// 2. Fetch local meals
val localMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
val localFingerprints = localMeals.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }.toSet()
var importedCount = 0
val toInsertLocally = mutableListOf<LocalMealEntity>()
for (remoteMeal in remoteMeals) {
val fp = "${remoteMeal.mealType.uppercase()}_${remoteMeal.mealTimestamp / 60_000}"
if (!localFingerprints.contains(fp)) {
toInsertLocally.add(LocalMealEntity.fromMealEntry(remoteMeal))
importedCount++
}
}
if (toInsertLocally.isNotEmpty()) {
localMealDao?.insertMeals(toInsertLocally)
SatieaAppWidgetProvider.updateAllWidgets(context)
}
// 3. Fetch remote custom foods
val remoteFoodsSnapshot = firestore.collection("users").document(uid).collection("custom_foods").get().await()
val remoteFoods = remoteFoodsSnapshot.toObjects(CustomFoodEntry::class.java)
val foodsToInsert = remoteFoods.map { food ->
LocalCustomFoodEntity(
slugId = food.id.ifBlank { Normalizer.normalize(food.name.lowercase(), Normalizer.Form.NFD).replace(Regex("[^a-z0-9]+"), "_") },
name = food.name,
defaultUnit = food.defaultUnit
)
}
if (foodsToInsert.isNotEmpty()) {
localMealDao?.insertCustomFoods(foodsToInsert)
}
Result.success(importedCount)
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.failure(e)
}
}
suspend fun insertRestoredMealsAndFoods(
meals: List<MealEntry>, meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity> foods: List<LocalCustomFoodEntity>,
): Pair<Int, Int> { recipes: List<RecipeEntry> = emptyList()
): Triple<Int, Int, Int> {
var newMealsCount = 0 var newMealsCount = 0
var newFoodsCount = 0 var newFoodsCount = 0
if (localMealDao != null) { var newRecipesCount = 0
val existing = localMealDao.getAllMealsOnce()
val existingFingerprints = existing.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }.toSet()
val toInsertMeals = mutableListOf<LocalMealEntity>()
for (m in meals) {
val fp = "${m.mealType.uppercase()}_${m.mealTimestamp / 60_000}"
if (fp !in existingFingerprints) {
toInsertMeals.add(LocalMealEntity.fromMealEntry(m))
newMealsCount++
}
}
if (toInsertMeals.isNotEmpty()) {
localMealDao.insertMeals(toInsertMeals)
SatieaAppWidgetProvider.updateAllWidgets(context)
}
val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet() // 1. Merge meals (deduplicate by type + minute bucket)
val toInsertFoods = mutableListOf<LocalCustomFoodEntity>() val existingMeals = localMealDao.getAllMealsOnce()
for (f in foods) { val existingFingerprints = existingMeals
if (f.name.lowercase().trim() !in existingFoods) { .map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }
toInsertFoods.add(f) .toMutableSet()
newFoodsCount++ val toInsertMeals = mutableListOf<LocalMealEntity>()
} for (m in meals) {
} val fp = "${m.mealType.uppercase()}_${m.mealTimestamp / 60_000}"
if (toInsertFoods.isNotEmpty()) { if (existingFingerprints.add(fp)) {
localMealDao.insertCustomFoods(toInsertFoods) toInsertMeals.add(LocalMealEntity.fromMealEntry(m))
newMealsCount++
} }
} }
return Pair(newMealsCount, newFoodsCount) if (toInsertMeals.isNotEmpty()) {
} localMealDao.insertMeals(toInsertMeals)
SatieaAppWidgetProvider.updateAllWidgets(context)
suspend fun syncLocalToCloud(): Result<Int> {
val uid = getUserIdOrNull() ?: return Result.failure(IllegalStateException("No Google account signed in"))
val firestore = db ?: return Result.failure(IllegalStateException("Firestore is not available"))
return try {
val remoteMealsSnapshot = firestore.collection("users").document(uid).collection("meals").get().await()
val remoteMealIds = remoteMealsSnapshot.documents.map { it.id }.toSet()
val localMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
var uploadedCount = 0
for (meal in localMeals) {
if (!remoteMealIds.contains(meal.id)) {
val payload = mapOf(
"userId" to uid,
"mealType" to meal.mealType,
"mealTimestamp" to meal.mealTimestamp,
"hungerBefore" to meal.hungerBefore,
"satietyAfter" to meal.satietyAfter,
"note" to meal.note,
"foodItemsSerialized" to meal.foodItemsSerialized,
"photoUris" to meal.photoUris,
"photosBase64" to meal.photosBase64,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
firestore.collection("users").document(uid).collection("meals").document(meal.id).set(payload).await()
uploadedCount++
}
}
val remoteFoodsSnapshot = firestore.collection("users").document(uid).collection("custom_foods").get().await()
val remoteFoodIds = remoteFoodsSnapshot.documents.map { it.id }.toSet()
val localFoods = localMealDao?.getAllCustomFoodsOnce() ?: emptyList()
for (food in localFoods) {
if (!remoteFoodIds.contains(food.slugId)) {
val payload = mapOf(
"userId" to uid,
"name" to food.name,
"defaultUnit" to food.defaultUnit,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
firestore.collection("users").document(uid).collection("custom_foods").document(food.slugId).set(payload).await()
}
}
Result.success(uploadedCount)
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.failure(e)
} }
// 2. Merge custom foods (deduplicate by lowercase trimmed name; enrich missing category)
val existingFoodsByName = localMealDao.getAllCustomFoodsOnce()
.associateBy { it.name.lowercase().trim() }
.toMutableMap()
val toInsertFoods = mutableListOf<LocalCustomFoodEntity>()
for (f in foods) {
val key = f.name.lowercase().trim()
val existing = existingFoodsByName[key]
if (existing == null) {
toInsertFoods.add(f)
existingFoodsByName[key] = f
newFoodsCount++
} else if (existing.category.isBlank() && f.category.isNotBlank()) {
val updated = existing.copy(category = f.category, updatedAt = System.currentTimeMillis())
toInsertFoods.add(updated)
existingFoodsByName[key] = updated
}
}
if (toInsertFoods.isNotEmpty()) {
localMealDao.insertCustomFoods(toInsertFoods)
}
// 3. Merge recipes (deduplicate by lowercase trimmed title)
val existingRecipeTitles = localMealDao.getAllRecipesOnce()
.map { it.title.lowercase().trim() }
.toMutableSet()
val toInsertRecipes = mutableListOf<LocalRecipeEntity>()
for (r in recipes) {
val key = r.title.lowercase().trim()
if (key.isNotBlank() && existingRecipeTitles.add(key)) {
toInsertRecipes.add(LocalRecipeEntity.fromRecipeEntry(r))
newRecipesCount++
}
}
if (toInsertRecipes.isNotEmpty()) {
localMealDao.insertRecipes(toInsertRecipes)
}
return Triple(newMealsCount, newFoodsCount, newRecipesCount)
} }
} }
@@ -4,6 +4,8 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
import android.util.Log import android.util.Log
import com.example.data.model.MealEntry
import com.example.data.model.RecipeEntry
import com.example.data.preferences.GoogleSheetsPreferencesManager import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository import com.example.data.repository.MealRepository
import com.example.util.AuthExpiredException import com.example.util.AuthExpiredException
@@ -19,13 +21,25 @@ import kotlinx.coroutines.withContext
import java.io.File import java.io.File
sealed interface SheetsSyncResult { sealed interface SheetsSyncResult {
data class Success(val url: String, val count: Int, val foodsCount: Int, val timestamp: Long) : SheetsSyncResult data class Success(
val url: String,
val count: Int,
val foodsCount: Int,
val recipesCount: Int = 0,
val timestamp: Long
) : SheetsSyncResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsSyncResult data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsSyncResult
data class Failure(val message: String) : SheetsSyncResult data class Failure(val message: String) : SheetsSyncResult
} }
sealed interface SheetsRestoreResult { sealed interface SheetsRestoreResult {
data class Success(val mealsCount: Int, val foodsCount: Int) : SheetsRestoreResult data class Success(
val mealsCount: Int,
val foodsCount: Int,
val recipesCount: Int = 0
) : SheetsRestoreResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsRestoreResult data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsRestoreResult
data class Failure(val message: String) : SheetsRestoreResult data class Failure(val message: String) : SheetsRestoreResult
} }
@@ -111,19 +125,21 @@ class GoogleSheetsSyncUseCase(
sheetsPrefs.spreadsheetId = id sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url sheetsPrefs.spreadsheetUrl = url
// 3. Upload missing meal photos to Google Drive Photos folder // 3. Upload missing meal & recipe photos to Google Drive Photos folder
val currentMeals = repository.getAllMealsSnapshot() val currentMeals = repository.getAllMealsSnapshot()
val currentRecipes = repository.getAllRecipesSnapshot()
if (!photosFolderId.isNullOrBlank()) { if (!photosFolderId.isNullOrBlank()) {
uploadMealPhotosQuietly(token, photosFolderId, currentMeals) uploadPhotosQuietly(token, photosFolderId, currentMeals, currentRecipes)
} }
// 4. Sync meals and custom foods to the 2 spreadsheet tabs // 4. Sync meals, custom foods, and recipes to the 3 spreadsheet tabs
val currentFoods = repository.getAllCustomFoodsSnapshot() val currentFoods = repository.getAllCustomFoodsSnapshot()
var syncResult = GoogleSheetsSyncService.syncMealsAndFoods( var syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token, accessToken = token,
spreadsheetId = id, spreadsheetId = id,
meals = currentMeals, meals = currentMeals,
foods = currentFoods, foods = currentFoods,
recipes = currentRecipes,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) } photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
) )
@@ -137,6 +153,7 @@ class GoogleSheetsSyncUseCase(
spreadsheetId = id, spreadsheetId = id,
meals = currentMeals, meals = currentMeals,
foods = currentFoods, foods = currentFoods,
recipes = currentRecipes,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) } photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
) )
} }
@@ -147,34 +164,45 @@ class GoogleSheetsSyncUseCase(
sheetsPrefs.lastSyncTimestamp = res.timestamp sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès" sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.foodsCount, res.timestamp) SheetsSyncResult.Success(
url = res.spreadsheetUrl,
count = res.mealsCount,
foodsCount = res.foodsCount,
recipesCount = res.recipesCount,
timestamp = res.timestamp
)
} else { } else {
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation" val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation"
SheetsSyncResult.Failure(err) SheetsSyncResult.Failure(err)
} }
} }
private suspend fun uploadMealPhotosQuietly( private suspend fun uploadPhotosQuietly(
accessToken: String, accessToken: String,
photosFolderId: String, photosFolderId: String,
meals: List<com.example.data.model.MealEntry> meals: List<MealEntry>,
recipes: List<RecipeEntry>
) { ) {
for (meal in meals) { val allPhotoUris = buildList {
for (photoUriStr in meal.displayPhotoUris) { meals.forEach { addAll(it.displayPhotoUris) }
if (sheetsPrefs.getPhotoDriveUrl(photoUriStr) != null) continue recipes.forEach { it.photoUri?.let { uri -> add(uri) } }
try { }.distinct()
val uri = Uri.parse(photoUriStr)
val path = uri.path ?: continue for (photoUriStr in allPhotoUris) {
val file = File(path) if (photoUriStr.startsWith("http")) continue
if (file.exists() && file.isFile) { if (sheetsPrefs.getPhotoDriveUrl(photoUriStr) != null) continue
val uploadResult = GoogleDriveService.uploadPhoto(accessToken, file, photosFolderId) try {
if (uploadResult.isSuccess) { val uri = Uri.parse(photoUriStr)
sheetsPrefs.savePhotoDriveUrl(photoUriStr, uploadResult.getOrThrow()) val path = uri.path ?: continue
} val file = File(path)
if (file.exists() && file.isFile) {
val uploadResult = GoogleDriveService.uploadPhoto(accessToken, file, photosFolderId)
if (uploadResult.isSuccess) {
sheetsPrefs.savePhotoDriveUrl(photoUriStr, uploadResult.getOrThrow())
} }
} catch (e: Exception) {
Log.w("GoogleSheetsSync", "Photo upload skipped for $photoUriStr: ${e.message}")
} }
} catch (e: Exception) {
Log.w("GoogleSheetsSync", "Photo upload skipped for $photoUriStr: ${e.message}")
} }
} }
} }
@@ -187,18 +215,29 @@ class GoogleSheetsSyncUseCase(
syncMutex.withLock { syncMutex.withLock {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId, sheetsPrefs.rootFolderId).getOrNull() val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(
?: return@withContext null token,
sheetsPrefs.spreadsheetId,
sheetsPrefs.rootFolderId
).getOrNull() ?: return@withContext null
sheetsPrefs.spreadsheetId = id sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url sheetsPrefs.spreadsheetUrl = url
val currentMeals = repository.getAllMealsSnapshot() val currentMeals = repository.getAllMealsSnapshot()
val currentFoods = repository.getAllCustomFoodsSnapshot() val currentFoods = repository.getAllCustomFoodsSnapshot()
val currentRecipes = repository.getAllRecipesSnapshot()
val photosFolderId = sheetsPrefs.photosFolderId
if (!photosFolderId.isNullOrBlank()) {
uploadPhotosQuietly(token, photosFolderId, currentMeals, currentRecipes)
}
val syncResult = GoogleSheetsSyncService.syncMealsAndFoods( val syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token, accessToken = token,
spreadsheetId = id, spreadsheetId = id,
meals = currentMeals, meals = currentMeals,
foods = currentFoods, foods = currentFoods,
recipes = currentRecipes,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) } photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
) )
if (syncResult.isSuccess) { if (syncResult.isSuccess) {
@@ -266,18 +305,23 @@ class GoogleSheetsSyncUseCase(
} }
if (readResult.isFailure) { if (readResult.isFailure) {
return@withContext SheetsRestoreResult.Failure(readResult.exceptionOrNull()?.localizedMessage ?: "Erreur de lecture du classeur") return@withContext SheetsRestoreResult.Failure(
readResult.exceptionOrNull()?.localizedMessage ?: "Erreur de lecture du classeur"
)
} }
val data = readResult.getOrThrow() val data = readResult.getOrThrow()
val (restoredMeals, restoredFoods) = repository.insertRestoredMealsAndFoods(data.meals, data.foods) val (restoredMeals, restoredFoods, restoredRecipes) = repository.insertRestoredData(
meals = data.meals,
foods = data.foods,
recipes = data.recipes
)
// If user is logged in to Firestore, align remote database too SheetsRestoreResult.Success(
try { mealsCount = restoredMeals,
repository.syncLocalToCloud() foodsCount = restoredFoods,
} catch (_: Exception) {} recipesCount = restoredRecipes
)
SheetsRestoreResult.Success(mealsCount = restoredMeals, foodsCount = restoredFoods)
} }
} }
} }
@@ -1,5 +1,6 @@
package com.example.domain package com.example.domain
import com.example.data.model.FoodCategory
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.ui.journal.DayStat import com.example.ui.journal.DayStat
@@ -11,7 +12,11 @@ import java.util.Locale
object WeeklyStatsCalculator { object WeeklyStatsCalculator {
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { fun computeWeeklyStats(
meals: List<MealEntry>,
zoneId: ZoneId = ZoneId.systemDefault(),
customCategoryLookup: Map<String, FoodCategory> = emptyMap()
): WeeklyStats {
val todayLocalDate = LocalDate.now(zoneId) val todayLocalDate = LocalDate.now(zoneId)
val startOfPeriod = todayLocalDate.minusDays(6) val startOfPeriod = todayLocalDate.minusDays(6)
val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli() val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli()
@@ -69,13 +74,22 @@ object WeeklyStatsCalculator {
distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) } distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) }
} }
val categoryCounts = mutableMapOf<FoodCategory, Int>()
recentMeals.forEach { meal ->
meal.parsedFoodItems().forEach { item ->
val cat = item.resolvedCategory(customCategoryLookup)
categoryCounts[cat] = (categoryCounts[cat] ?: 0) + 1
}
}
return WeeklyStats( return WeeklyStats(
dailyStats = daysList, dailyStats = daysList,
averageSatiety = avgSatiety, averageSatiety = avgSatiety,
averageHunger = avgHunger, averageHunger = avgHunger,
optimalZonePercentage = optimalPercentage, optimalZonePercentage = optimalPercentage,
totalMealsLast7Days = recentMeals.size, totalMealsLast7Days = recentMeals.size,
mealTypeDistribution = distribution mealTypeDistribution = distribution,
categoryDistribution = categoryCounts
) )
} }
} }
@@ -1,15 +1,14 @@
package com.example.ui.auth package com.example.ui.auth
import android.app.Activity import android.app.Activity
import android.content.Context import androidx.activity.compose.rememberLauncherForActivityResult
import android.util.Log import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
@@ -19,9 +18,9 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CloudDone import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.Eco import androidx.compose.material.icons.filled.FolderShared
import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.Timeline import androidx.compose.material.icons.filled.TableChart
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card import androidx.compose.material3.Card
@@ -49,103 +48,135 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.credentials.CredentialManager import com.example.util.GoogleDriveAccount
import androidx.credentials.CustomCredential import com.example.util.GoogleSheetsAuthHelper
import androidx.credentials.GetCredentialRequest import com.google.android.gms.auth.api.signin.GoogleSignIn
import androidx.credentials.exceptions.GetCredentialCancellationException import com.google.android.gms.common.api.ApiException
import com.example.R
import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential.Companion.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
import com.google.firebase.Firebase
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.auth
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
@Composable @Composable
fun AuthScreen( fun AuthScreen(
onAuthSuccess: () -> Unit onAuthSuccess: (GoogleDriveAccount) -> Unit
) { ) {
val context = LocalContext.current val context = LocalContext.current
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
val credentialManager = remember { CredentialManager.create(context) }
var isLoading by remember { mutableStateOf(false) } var isLoading by remember { mutableStateOf(false) }
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
val signInLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
isLoading = false
if (result.resultCode == Activity.RESULT_OK) {
try {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
val signedIn = task.getResult(ApiException::class.java)
val email = signedIn?.email
if (!email.isNullOrBlank()) {
onAuthSuccess(
GoogleDriveAccount(
displayName = signedIn.displayName,
email = email
)
)
} else {
val fallback = GoogleSheetsAuthHelper.getSignedInAccount(context)
if (fallback != null) {
onAuthSuccess(fallback)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar("Impossible de récupérer l'adresse Google")
}
}
}
} catch (e: Exception) {
val fallback = GoogleSheetsAuthHelper.getSignedInAccount(context)
if (fallback != null) {
onAuthSuccess(fallback)
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar(
e.localizedMessage ?: "Échec de connexion au compte Google Drive"
)
}
}
}
} else {
coroutineScope.launch {
snackbarHostState.showSnackbar("Connexion Google Drive annulée")
}
}
}
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxWidth()
.background(MaterialTheme.colorScheme.background) .background(MaterialTheme.colorScheme.surface)
) { ) {
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxWidth()
.padding(horizontal = 28.dp, vertical = 32.dp), .padding(horizontal = 24.dp, vertical = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceBetween verticalArrangement = Arrangement.spacedBy(18.dp)
) { ) {
Spacer(modifier = Modifier.height(24.dp)) // Hero
Column(horizontalAlignment = Alignment.CenterHorizontally) {
// Logo & Hero Section
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface( Surface(
modifier = Modifier modifier = Modifier
.size(88.dp) .size(72.dp)
.clip(CircleShape), .clip(CircleShape),
color = MaterialTheme.colorScheme.primaryContainer color = MaterialTheme.colorScheme.primaryContainer
) { ) {
Box(contentAlignment = Alignment.Center) { Box(contentAlignment = Alignment.Center) {
Icon( Icon(
imageVector = Icons.Default.Restaurant, imageVector = Icons.Default.FolderShared,
contentDescription = "Logo Satiéa", contentDescription = "Connexion Google Drive",
tint = MaterialTheme.colorScheme.onPrimaryContainer, tint = MaterialTheme.colorScheme.onPrimaryContainer,
modifier = Modifier.size(44.dp) modifier = Modifier.size(36.dp)
) )
} }
} }
Spacer(modifier = Modifier.height(20.dp)) Spacer(modifier = Modifier.height(14.dp))
Text( Text(
text = "Satiéa", text = "Sauvegarde sur Google Drive",
style = MaterialTheme.typography.displayMedium, style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.primary, color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
) )
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(6.dp))
Text( Text(
text = "Journal de repas & écoute de soi", text = "Votre compte Google sert uniquement à enregistrer vos données dans votre Drive personnel.",
style = MaterialTheme.typography.bodyLarge, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f), color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center textAlign = TextAlign.Center
) )
} }
// Benefits cards // Benefits
Column( Column(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(14.dp) verticalArrangement = Arrangement.spacedBy(10.dp)
) { ) {
FeaturePill( FeaturePill(
icon = Icons.Default.Eco, icon = Icons.Default.PhoneAndroid,
title = "Sensations de faim & satiété", title = "100 % local par défaut",
subtitle = "Évaluez votre ressenti avant et après chaque repas en 10 secondes." subtitle = "Toutes vos données restent enregistrées sur votre téléphone, sans serveur tiers."
) )
FeaturePill( FeaturePill(
icon = Icons.Default.Timeline, icon = Icons.Default.TableChart,
title = "Statistiques 7 jours", title = "Votre classeur Google Sheets",
subtitle = "Suivez votre équilibre digestif et la régularité de vos habitudes." subtitle = "3 onglets clairs : Journal des repas, Aliments colorés et Recueil de recettes."
) )
FeaturePill( FeaturePill(
icon = Icons.Default.CloudDone, icon = Icons.Default.CloudDone,
title = "Synchronisation Cloud sécurisée", title = "Photos & restauration faciles",
subtitle = "Vos repas et photos d'assiettes accessibles sur tous vos appareils." subtitle = "Vos photos sont archivées dans votre dossier Drive « Satiéa »."
) )
} }
@@ -157,28 +188,12 @@ fun AuthScreen(
Button( Button(
onClick = { onClick = {
isLoading = true isLoading = true
onGoogleSignInClicked( val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
context = context, signInLauncher.launch(client.signInIntent)
credentialManager = credentialManager,
onAuthSuccess = {
isLoading = false
onAuthSuccess()
},
onAuthError = { errorMsg ->
isLoading = false
coroutineScope.launch {
snackbarHostState.showSnackbar(errorMsg)
}
},
scope = coroutineScope,
onAuthCancelled = {
isLoading = false
}
)
}, },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(54.dp) .height(52.dp)
.testTag("google_signin_button"), .testTag("google_signin_button"),
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors( colors = ButtonDefaults.buttonColors(
@@ -189,7 +204,7 @@ fun AuthScreen(
) { ) {
if (isLoading) { if (isLoading) {
CircularProgressIndicator( CircularProgressIndicator(
modifier = Modifier.size(24.dp), modifier = Modifier.size(22.dp),
color = MaterialTheme.colorScheme.onPrimary, color = MaterialTheme.colorScheme.onPrimary,
strokeWidth = 2.dp strokeWidth = 2.dp
) )
@@ -202,22 +217,24 @@ fun AuthScreen(
) )
Spacer(modifier = Modifier.width(10.dp)) Spacer(modifier = Modifier.width(10.dp))
Text( Text(
text = "Continuer avec Google", text = "Connecter mon compte Google Drive",
style = MaterialTheme.typography.titleMedium style = MaterialTheme.typography.titleSmall
) )
} }
} }
} }
Spacer(modifier = Modifier.height(14.dp)) Spacer(modifier = Modifier.height(10.dp))
Text( Text(
text = "Connexion sécurisée via Google • Sans publicité", text = "Accès limité uniquement aux fichiers créés par Satiéa dans votre Drive",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f), color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
textAlign = TextAlign.Center textAlign = TextAlign.Center
) )
} }
Spacer(modifier = Modifier.height(8.dp))
} }
SnackbarHost( SnackbarHost(
@@ -235,20 +252,20 @@ private fun FeaturePill(
) { ) {
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp), shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors( colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f) containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
) )
) { ) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(16.dp), .padding(14.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Surface( Surface(
modifier = Modifier.size(40.dp), modifier = Modifier.size(38.dp),
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(11.dp),
color = MaterialTheme.colorScheme.surface color = MaterialTheme.colorScheme.surface
) { ) {
Box(contentAlignment = Alignment.Center) { Box(contentAlignment = Alignment.Center) {
@@ -256,12 +273,12 @@ private fun FeaturePill(
imageVector = icon, imageVector = icon,
contentDescription = null, contentDescription = null,
tint = MaterialTheme.colorScheme.primary, tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(22.dp) modifier = Modifier.size(20.dp)
) )
} }
} }
Spacer(modifier = Modifier.width(14.dp)) Spacer(modifier = Modifier.width(12.dp))
Column { Column {
Text( Text(
@@ -279,48 +296,3 @@ private fun FeaturePill(
} }
} }
} }
fun onGoogleSignInClicked(
context: Context,
credentialManager: CredentialManager,
onAuthSuccess: () -> Unit,
onAuthError: (String) -> Unit,
scope: CoroutineScope,
onAuthCancelled: () -> Unit = {}
) {
val clientId = try {
context.getString(R.string.default_web_client_id)
} catch (e: Exception) {
onAuthError("Configuration Google manquante (default_web_client_id)")
return
}
val signInOption = GetSignInWithGoogleOption.Builder(serverClientId = clientId).build()
val request = GetCredentialRequest.Builder().addCredentialOption(signInOption).build()
scope.launch {
try {
val activity = context as? Activity
if (activity == null) {
onAuthError("Contexte invalide pour la connexion")
return@launch
}
val result = credentialManager.getCredential(activity, request)
val credential = result.credential
if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
val googleIdToken = GoogleIdTokenCredential.createFrom(credential.data).idToken
val authCredential = GoogleAuthProvider.getCredential(googleIdToken, null)
Firebase.auth.signInWithCredential(authCredential).await()
onAuthSuccess()
} else {
onAuthError("Type d'identifiant non reconnu")
}
} catch (e: GetCredentialCancellationException) {
Log.w("Auth", "Connexion Google annulée: ${e.message}", e)
onAuthCancelled()
} catch (e: Exception) {
Log.e("Auth", "Échec de la connexion Google", e)
onAuthError(e.localizedMessage ?: "Échec de connexion")
}
}
}
@@ -0,0 +1,185 @@
package com.example.ui.common
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
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.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
@Composable
fun isSatieaDarkTheme(): Boolean {
return MaterialTheme.colorScheme.background.luminance() < 0.5f
}
fun FoodCategory.accentColor(isDark: Boolean): Color = dotColor(isDark)
fun FoodCategory.dotFillColor(isDark: Boolean): Color = dotColor(isDark)
fun FoodCategory.badgeContainerColor(isDark: Boolean): Color = containerColor(isDark)
fun FoodCategory.badgeBorderColor(isDark: Boolean): Color = borderColor(isDark)
fun FoodCategory.badgeTextColor(isDark: Boolean): Color = contentColor(isDark)
@Composable
fun FoodCategoryColorDot(
category: FoodCategory,
modifier: Modifier = Modifier,
size: Dp = 10.dp
) {
val isDark = isSatieaDarkTheme()
val fill = category.dotFillColor(isDark)
val borderColor = if (category == FoodCategory.CHEESE) {
if (isDark) Color(0xFFD5D0BE) else Color(0xFF9C947C)
} else {
fill.copy(alpha = 0.85f)
}
Box(
modifier = modifier
.size(size)
.clip(CircleShape)
.background(fill)
.border(width = if (category == FoodCategory.CHEESE) 1.2.dp else 0.5.dp, color = borderColor, shape = CircleShape)
)
}
@Composable
fun FoodCategoryBadge(
text: String,
category: FoodCategory,
modifier: Modifier = Modifier,
onClick: (() -> Unit)? = null,
onRemove: (() -> Unit)? = null
) {
val isDark = isSatieaDarkTheme()
val shape = RoundedCornerShape(11.dp)
Surface(
shape = shape,
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark)),
modifier = modifier
.clip(shape)
.then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier)
) {
Row(
modifier = Modifier.padding(
start = 9.dp,
end = if (onRemove != null) 6.dp else 10.dp,
top = 5.dp,
bottom = 5.dp
),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = text,
style = MaterialTheme.typography.labelMedium,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
if (onRemove != null) {
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer $text",
tint = category.badgeTextColor(isDark).copy(alpha = 0.8f),
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable(onClick = onRemove)
.padding(2.dp)
)
}
}
}
}
@Composable
fun FoodCategorySelectorRow(
selectedCategory: FoodCategory,
onCategorySelected: (FoodCategory) -> Unit,
modifier: Modifier = Modifier
) {
val isDark = isSatieaDarkTheme()
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier
.fillMaxWidth()
.testTag("food_category_selector_row")
) {
items(FoodCategory.entries, key = { it.name }) { category ->
val isSelected = category == selectedCategory
val shape = RoundedCornerShape(12.dp)
val containerColor = if (isSelected) {
category.badgeContainerColor(isDark).copy(alpha = if (isDark) 0.34f else 0.24f)
} else {
MaterialTheme.colorScheme.surface
}
val borderColor = if (isSelected) {
if (category == FoodCategory.CHEESE) {
if (isDark) Color(0xFFF6F4EC) else Color(0xFF7B735B)
} else {
category.accentColor(isDark)
}
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)
}
Surface(
shape = shape,
color = containerColor,
border = BorderStroke(if (isSelected) 1.5.dp else 1.dp, borderColor),
modifier = Modifier
.clip(shape)
.clickable { onCategorySelected(category) }
.testTag("food_category_chip_${category.name.lowercase()}")
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 9.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = if (isSelected) category.badgeTextColor(isDark) else MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
)
}
}
}
}
}
@@ -1,8 +1,5 @@
package com.example.ui.journal package com.example.ui.journal
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import coil.compose.AsyncImage
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@@ -33,7 +30,6 @@ import androidx.compose.material.icons.filled.FileDownload
import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Restaurant import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.TableChart import androidx.compose.material.icons.filled.TableChart
import androidx.compose.ui.graphics.Color
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults import androidx.compose.material3.CardDefaults
@@ -55,16 +51,22 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp 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.HungerSatietyScale import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.util.ImageUtils import com.example.ui.common.FoodCategoryBadge
import com.example.ui.journal.components.DailyBenchmarksCard
import com.example.ui.journal.components.DietaryGuideSheet
import java.time.Instant import java.time.Instant
import java.time.LocalDate import java.time.LocalDate
import java.time.ZoneId import java.time.ZoneId
@@ -74,6 +76,7 @@ import java.util.Locale
@Composable @Composable
fun JournalScreen( fun JournalScreen(
mealsUiState: MealsUiState, mealsUiState: MealsUiState,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddMealClick: () -> Unit, onAddMealClick: () -> Unit,
onEditMeal: (MealEntry) -> Unit, onEditMeal: (MealEntry) -> Unit,
onDeleteMeal: (String) -> Unit, onDeleteMeal: (String) -> Unit,
@@ -81,6 +84,12 @@ fun JournalScreen(
onSyncSheetsClick: (() -> Unit)? = null, onSyncSheetsClick: (() -> Unit)? = null,
spreadsheetUrl: String? = null spreadsheetUrl: String? = null
) { ) {
var showDietaryGuide by remember { mutableStateOf(false) }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@@ -139,6 +148,14 @@ fun JournalScreen(
DailyOverviewCard(todayMeals = todayMeals) DailyOverviewCard(todayMeals = todayMeals)
} }
item {
DailyBenchmarksCard(
todayMeals = todayMeals,
customCategoryLookup = customCategoryLookup,
onOpenGuideClick = { showDietaryGuide = true }
)
}
if (meals.isEmpty()) { if (meals.isEmpty()) {
item { item {
EmptyMealsView(onAddMealClick = onAddMealClick) EmptyMealsView(onAddMealClick = onAddMealClick)
@@ -167,13 +184,13 @@ fun JournalScreen(
) { ) {
Icon( Icon(
imageVector = Icons.Default.TableChart, imageVector = Icons.Default.TableChart,
contentDescription = "Synchroniser vers Google Sheets", contentDescription = "Sauvegarder sur Google Sheets",
modifier = Modifier.size(18.dp), modifier = Modifier.size(18.dp),
tint = Color(0xFF0F9D58) tint = Color(0xFF0F9D58)
) )
Spacer(modifier = Modifier.width(4.dp)) Spacer(modifier = Modifier.width(4.dp))
Text( Text(
text = "Sheets", text = "Drive",
style = MaterialTheme.typography.labelLarge, style = MaterialTheme.typography.labelLarge,
color = Color(0xFF0F9D58) color = Color(0xFF0F9D58)
) )
@@ -204,6 +221,7 @@ fun JournalScreen(
items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal -> items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal ->
MealCardItem( MealCardItem(
meal = meal, meal = meal,
customCategoryLookup = customCategoryLookup,
onEdit = { onEditMeal(meal) }, onEdit = { onEditMeal(meal) },
onDelete = { onDeleteMeal(meal.id) } onDelete = { onDeleteMeal(meal.id) }
) )
@@ -230,6 +248,10 @@ fun JournalScreen(
) )
} }
} }
if (showDietaryGuide) {
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
}
} }
@Composable @Composable
@@ -331,6 +353,7 @@ private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
@Composable @Composable
private fun MealCardItem( private fun MealCardItem(
meal: MealEntry, meal: MealEntry,
customCategoryLookup: Map<String, FoodCategory>,
onEdit: () -> Unit, onEdit: () -> Unit,
onDelete: () -> Unit onDelete: () -> Unit
) { ) {
@@ -511,7 +534,7 @@ private fun MealCardItem(
} }
} }
// Food Items Badges (with optional weights) // Color-Coded Food Items Badges
if (parsedFoods.isNotEmpty()) { if (parsedFoods.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
Text( Text(
@@ -526,18 +549,10 @@ private fun MealCardItem(
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
parsedFoods.forEach { food -> parsedFoods.forEach { food ->
Surface( FoodCategoryBadge(
shape = RoundedCornerShape(10.dp), text = food.displayBadge(),
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) category = food.resolvedCategory(customCategoryLookup)
) { )
Text(
text = food.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)
)
}
} }
} }
} }
@@ -568,7 +583,7 @@ private fun MealCardItem(
text = "Note globale : « ${meal.note} »", text = "Note globale : « ${meal.note} »",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f), color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f),
fontStyle = androidx.compose.ui.text.font.FontStyle.Italic fontStyle = FontStyle.Italic
) )
} }
} }
@@ -578,7 +593,7 @@ private fun MealCardItem(
AlertDialog( AlertDialog(
onDismissRequest = { showDeleteDialog = false }, onDismissRequest = { showDeleteDialog = false },
title = { Text("Supprimer ce repas ?") }, title = { Text("Supprimer ce repas ?") },
text = { Text("Cette action est irréversible et supprimera le repas de votre historique synchronisé.") }, text = { Text("Cette action supprimera ce repas de votre journal local.") },
confirmButton = { confirmButton = {
TextButton( TextButton(
onClick = { onClick = {
@@ -633,7 +648,7 @@ private fun EmptyMealsView(onAddMealClick: () -> Unit) {
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(8.dp))
Text( Text(
text = "Prenez 15 secondes pour noter vos aliments (avec ou sans poids), votre faim et votre satiété sur 10.", text = "Prenez 15 secondes pour noter vos aliments (avec leur code couleur), votre faim et votre satiété sur 10.",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f), color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
textAlign = TextAlign.Center textAlign = TextAlign.Center
@@ -8,21 +8,24 @@ import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.preferences.GoogleSheetsPreferencesManager import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.preferences.ThemePreferencesManager
import com.example.data.repository.MealRepository import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase import com.example.domain.CsvExportUseCase
import com.example.domain.GoogleSheetsSyncUseCase import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsRestoreResult import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult import com.example.domain.SheetsSyncResult
import com.example.domain.WeeklyStatsCalculator
import com.example.notification.MealNotificationManager import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode import com.example.ui.theme.AppThemeMode
import com.example.util.CsvImportResult import com.example.util.GoogleSheetsAuthHelper
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestoreException
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel
@@ -31,14 +34,13 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.ZoneId import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale import java.util.Locale
sealed interface MealsUiState { sealed interface MealsUiState {
@@ -69,7 +71,8 @@ data class WeeklyStats(
val averageHunger: Float, val averageHunger: Float,
val optimalZonePercentage: Int, val optimalZonePercentage: Int,
val totalMealsLast7Days: Int, val totalMealsLast7Days: Int,
val mealTypeDistribution: Map<MealType, Int> val mealTypeDistribution: Map<MealType, Int>,
val categoryDistribution: Map<FoodCategory, Int> = emptyMap()
) { ) {
companion object { companion object {
fun empty(): WeeklyStats = WeeklyStats( fun empty(): WeeklyStats = WeeklyStats(
@@ -78,7 +81,8 @@ data class WeeklyStats(
averageHunger = 0f, averageHunger = 0f,
optimalZonePercentage = 0, optimalZonePercentage = 0,
totalMealsLast7Days = 0, totalMealsLast7Days = 0,
mealTypeDistribution = emptyMap() mealTypeDistribution = emptyMap(),
categoryDistribution = emptyMap()
) )
} }
} }
@@ -88,6 +92,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application) private val repository = MealRepository(application)
private val context = application.applicationContext private val context = application.applicationContext
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application) private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
private val themePrefs = ThemePreferencesManager(application)
// Domain Use Cases // Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs) private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
@@ -106,12 +111,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
MealsUiState.Success(meals) MealsUiState.Success(meals)
} }
.catch { error -> .catch { error ->
val firestoreError = generateSequence(error) { it.cause } if (error is CancellationException) throw error
.filterIsInstance<FirebaseFirestoreException>() emit(MealsUiState.Error(error.message ?: "Impossible de charger les repas"))
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
val rootError = firestoreError ?: error
emit(MealsUiState.Error(rootError.message ?: "Impossible de charger les repas"))
} }
.stateIn( .stateIn(
scope = viewModelScope, scope = viewModelScope,
@@ -119,22 +120,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = MealsUiState.Loading initialValue = MealsUiState.Loading
) )
// Asynchronous background computation of WeeklyStats via Dispatchers.Default
val weeklyStats: StateFlow<WeeklyStats> = repository.observeMeals()
.map { meals -> computeWeeklyStats(meals) }
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = WeeklyStats.empty()
)
val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods() val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods()
.catch { error -> .catch { error ->
val firestoreError = generateSequence(error) { it.cause } if (error is CancellationException) throw error
.filterIsInstance<FirebaseFirestoreException>()
.firstOrNull()
if (firestoreError == null && error is CancellationException) throw error
emit(emptyList()) emit(emptyList())
} }
.stateIn( .stateIn(
@@ -143,7 +131,36 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = emptyList() initialValue = emptyList()
) )
private val _themeMode = MutableStateFlow(AppThemeMode.DARK) val recipes: StateFlow<List<RecipeEntry>> = repository.observeRecipes()
.catch { error ->
if (error is CancellationException) throw error
emit(emptyList())
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
// Asynchronous background computation of WeeklyStats including food category diversity
val weeklyStats: StateFlow<WeeklyStats> = combine(
repository.observeMeals(),
repository.observeCustomFoods()
) { meals, foods ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
WeeklyStatsCalculator.computeWeeklyStats(
meals = meals,
customCategoryLookup = lookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = WeeklyStats.empty()
)
private val _themeMode = MutableStateFlow(themePrefs.loadThemeMode())
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow() val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
// Quick Log Action triggered from Widget or Notification // Quick Log Action triggered from Widget or Notification
@@ -178,6 +195,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val spreadsheetUrl: StateFlow<String?> = _spreadsheetUrl.asStateFlow() val spreadsheetUrl: StateFlow<String?> = _spreadsheetUrl.asStateFlow()
fun setThemeMode(mode: AppThemeMode) { fun setThemeMode(mode: AppThemeMode) {
themePrefs.saveThemeMode(mode)
_themeMode.value = mode _themeMode.value = mode
} }
@@ -193,25 +211,44 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) { private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) {
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.map { it.name.lowercase(Locale.FRENCH) }.toSet() val existingBuiltIn = DefaultFoodCatalog.builtInFoods.associate {
val existingCustom = customFoods.value.map { it.name.lowercase(Locale.FRENCH) }.toSet() it.name.lowercase(Locale.FRENCH) to it.category
}
val existingCustom = customFoods.value.associateBy { it.name.lowercase(Locale.FRENCH) }
viewModelScope.launch { viewModelScope.launch {
foodItems.forEach { item -> foodItems.forEach { item ->
val cleanName = item.name.trim() val cleanName = item.name.trim()
val normalized = cleanName.lowercase(Locale.FRENCH) val normalized = cleanName.lowercase(Locale.FRENCH)
if (cleanName.isNotEmpty() && normalized !in existingBuiltIn && normalized !in existingCustom) { if (cleanName.isEmpty()) return@forEach
repository.saveCustomFood(cleanName, item.unit)
val chosenCategory = item.category ?: item.resolvedCategory()
val builtInCategory = existingBuiltIn[normalized]
val existingEntry = existingCustom[normalized]
val shouldSave = when {
builtInCategory == null && existingEntry == null -> true
existingEntry != null && existingEntry.resolvedCategory() != chosenCategory -> true
builtInCategory != null && builtInCategory != chosenCategory -> true
else -> false
}
if (shouldSave) {
repository.saveCustomFood(cleanName, item.unit, chosenCategory)
} }
} }
} }
} }
fun addCustomFoodDirectly(name: String, unit: com.example.data.model.FoodUnit) { fun addCustomFoodDirectly(
name: String,
unit: FoodUnit,
category: FoodCategory? = null
) {
val cleanName = name.trim() val cleanName = name.trim()
if (cleanName.isEmpty()) return if (cleanName.isEmpty()) return
viewModelScope.launch { viewModelScope.launch {
repository.saveCustomFood(cleanName, unit) repository.saveCustomFood(cleanName, unit, category)
} }
} }
@@ -248,22 +285,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
fun signOut(context: Context, onComplete: () -> Unit = {}) {
viewModelScope.launch {
try {
FirebaseAuth.getInstance().signOut()
val credManager = androidx.credentials.CredentialManager.create(context)
credManager.clearCredentialState(androidx.credentials.ClearCredentialStateRequest())
} catch (e: Exception) {
if (e is CancellationException) throw e
} finally {
disconnectGoogleSheets()
onComplete()
emitEvent(UiEvent.ShowSnackbar("Mode local actif • Déconnecté"))
}
}
}
fun updateMeal( fun updateMeal(
meal: MealEntry, meal: MealEntry,
foodItems: List<MealFoodItem> foodItems: List<MealFoodItem>
@@ -299,6 +320,58 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
// ------------------------------------------------------------------------
// Recipes CRUD
// ------------------------------------------------------------------------
fun saveRecipe(recipe: RecipeEntry) {
val ingredients = recipe.parsedIngredients()
enrichCatalogWithFoodItems(ingredients)
viewModelScope.launch {
val isNew = recipe.id.isBlank()
val result = repository.saveRecipe(recipe)
if (result.isSuccess) {
val msg = if (isNew) "Recette ajoutée au recueil ✨" else "Recette mise à jour ✨"
emitEvent(UiEvent.ShowSnackbar(msg))
triggerAutoSheetsSyncIfNeeded()
} else {
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement de la recette"
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
fun deleteRecipe(recipeId: String) {
viewModelScope.launch {
val result = repository.deleteRecipe(recipeId)
if (result.isSuccess) {
emitEvent(UiEvent.ShowSnackbar("Recette supprimée"))
triggerAutoSheetsSyncIfNeeded()
} else {
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression"
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
// ------------------------------------------------------------------------
// Google Drive Account & Sheets Sync
// ------------------------------------------------------------------------
fun signOut(context: Context, onComplete: () -> Unit = {}) {
viewModelScope.launch {
try {
GoogleSheetsAuthHelper.signOut(context)
} catch (e: Exception) {
if (e is CancellationException) throw e
} finally {
disconnectGoogleSheets()
onComplete()
emitEvent(UiEvent.ShowSnackbar("Compte Google Drive déconnecté • Mode local actif"))
}
}
}
private fun triggerAutoSheetsSyncIfNeeded() { private fun triggerAutoSheetsSyncIfNeeded() {
if (!sheetsPrefs.isAutoSyncEnabled) return if (!sheetsPrefs.isAutoSyncEnabled) return
viewModelScope.launch { viewModelScope.launch {
@@ -318,8 +391,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
is SheetsSyncResult.Success -> { is SheetsSyncResult.Success -> {
_spreadsheetUrl.value = result.url _spreadsheetUrl.value = result.url
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp) _sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
val foodsInfo = if (result.foodsCount > 0) " et ${result.foodsCount} aliments" else "" val summaryParts = buildList {
emitEvent(UiEvent.ShowSnackbar("Synchronisé vers Google Sheets (${result.count} repas$foodsInfo) 📊")) add("${result.count} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Sauvegardé sur Google Drive ($summaryParts) 📊"))
} }
is SheetsSyncResult.RecoverableAuth -> { is SheetsSyncResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent) _sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
@@ -347,15 +424,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
when (val result = sheetsSyncUseCase.restoreFromSheets()) { when (val result = sheetsSyncUseCase.restoreFromSheets()) {
is SheetsRestoreResult.Success -> { is SheetsRestoreResult.Success -> {
_sheetsUiState.value = GoogleSheetsUiState.Idle _sheetsUiState.value = GoogleSheetsUiState.Idle
val msg = buildString { val summaryParts = buildList {
append("Restauration réussie ✨ : ") add("${result.mealsCount} repas")
append("${result.mealsCount} repas") if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.foodsCount > 0) { if (result.recipesCount > 0) add("${result.recipesCount} recettes")
append(" et ${result.foodsCount} aliments") }.joinToString(", ")
} emitEvent(UiEvent.ShowSnackbar("Restauration réussie ✨ : $summaryParts"))
append(" restaurés")
}
emitEvent(UiEvent.ShowSnackbar(msg))
} }
is SheetsRestoreResult.RecoverableAuth -> { is SheetsRestoreResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent) _sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
@@ -375,6 +449,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
// ------------------------------------------------------------------------
// CSV Import / Export & Notifications
// ------------------------------------------------------------------------
fun exportCsvToUri( fun exportCsvToUri(
targetUri: Uri, targetUri: Uri,
meals: List<MealEntry> meals: List<MealEntry>
@@ -417,29 +495,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
} }
fun syncCloudToLocal() {
viewModelScope.launch {
val result = repository.syncCloudToLocal()
result.fold(
onSuccess = { count ->
emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️"))
// Trigger uploading any local meals that were created offline
syncLocalToCloud()
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de la synchronisation"
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
fun syncLocalToCloud() {
viewModelScope.launch {
repository.syncLocalToCloud()
}
}
fun shareCsv(meals: List<MealEntry>) { fun shareCsv(meals: List<MealEntry>) {
viewModelScope.launch { viewModelScope.launch {
val result = csvExportUseCase.createShareIntent(meals) val result = csvExportUseCase.createShareIntent(meals)
@@ -476,6 +531,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
} }
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats { fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId) val lookup = customFoods.value.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
return WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId, lookup)
} }
} }
@@ -0,0 +1,565 @@
package com.example.ui.journal.components
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.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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material.icons.filled.Spa
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.DietaryReferenceGuide
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
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
private data class CategoryDaySummary(
val category: FoodCategory,
val count: Int,
val totalGrams: Double,
val totalPortions: Double
)
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun DailyBenchmarksCard(
todayMeals: List<MealEntry>,
customCategoryLookup: Map<String, FoodCategory>,
onOpenGuideClick: () -> Unit,
modifier: Modifier = Modifier
) {
var expanded by remember { mutableStateOf(false) }
val isDark = isSatieaDarkTheme()
val summariesByCategory = remember(todayMeals, customCategoryLookup) {
val map = mutableMapOf<FoodCategory, CategoryDaySummary>()
todayMeals.forEach { meal ->
meal.parsedFoodItems().forEach { item ->
val cat = item.resolvedCategory(customCategoryLookup)
val current = map[cat] ?: CategoryDaySummary(cat, 0, 0.0, 0.0)
val addG = if (item.unit == FoodUnit.G && item.weight != null) item.weight else 0.0
val addP = if (item.unit == FoodUnit.PORTION && item.weight != null) item.weight else 0.0
map[cat] = current.copy(
count = current.count + 1,
totalGrams = current.totalGrams + addG,
totalPortions = current.totalPortions + addP
)
}
}
map
}
val activeCoreCategories = remember(summariesByCategory) {
FoodCategory.benchmarkCategories.filter { (summariesByCategory[it]?.count ?: 0) > 0 }
}
Card(
modifier = modifier
.fillMaxWidth()
.testTag("daily_benchmarks_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable { expanded = !expanded }
.padding(vertical = 2.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
Icon(
imageVector = Icons.Default.Spa,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = "Mes repères du jour",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = if (activeCoreCategories.isEmpty()) {
"Code couleur & familles alimentaires"
} else {
"${activeCoreCategories.size} famille${if (activeCoreCategories.size > 1) "s" else ""} présentes aujourd'hui"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
TextButton(
onClick = onOpenGuideClick,
modifier = Modifier.testTag("open_dietary_guide_button")
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = "Ouvrir le guide des repères",
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Guide",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary
)
}
Icon(
imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
contentDescription = if (expanded) "Replier les repères" else "Afficher les repères",
tint = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
// Compact color strip of today's families when collapsed
if (!expanded && activeCoreCategories.isNotEmpty()) {
Spacer(modifier = Modifier.height(10.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth()
) {
activeCoreCategories.forEach { cat ->
val summary = summariesByCategory[cat]!!
val detail = formatObservedShort(summary)
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 = 8.dp)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "${cat.shortLabel} · $detail",
style = MaterialTheme.typography.labelSmall,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
AnimatedVisibility(visible = expanded) {
Column(modifier = Modifier.padding(top = 12.dp)) {
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f)
)
Spacer(modifier = Modifier.height(10.dp))
FoodCategory.benchmarkCategories.forEach { category ->
val summary = summariesByCategory[category]
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
FoodCategoryColorDot(category = category, size = 10.dp)
Spacer(modifier = Modifier.width(10.dp))
Column {
Text(
text = category.displayName,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Text(
text = "Repère : ${category.dailyGuide}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.width(8.dp))
if (summary != null && summary.count > 0) {
Surface(
shape = RoundedCornerShape(8.dp),
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark))
) {
Text(
text = formatObservedShort(summary),
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
} else {
Text(
text = "—",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Ces repères sont indicatifs et bienveillants : adaptez toujours selon votre faim et votre plaisir.",
style = MaterialTheme.typography.bodySmall,
fontStyle = FontStyle.Italic,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
private fun formatObservedShort(summary: CategoryDaySummary): String {
return when {
summary.totalGrams > 0.0 -> {
val gStr = if (summary.totalGrams % 1.0 == 0.0) {
summary.totalGrams.toInt().toString()
} else {
String.format(Locale.FRENCH, "%.1f", summary.totalGrams)
}
"${summary.count}× · $gStr g"
}
summary.totalPortions > 0.0 -> {
val pStr = if (summary.totalPortions % 1.0 == 0.0) {
summary.totalPortions.toInt().toString()
} else {
String.format(Locale.FRENCH, "%.1f", summary.totalPortions)
}
"$pStr port."
}
else -> "${summary.count}×"
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DietaryGuideSheet(
onDismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val isDark = isSatieaDarkTheme()
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("dietary_guide_sheet")
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Repères & Équivalences",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Votre mémo personnel, sans restriction ni culpabilité",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(
onClick = onDismiss,
modifier = Modifier.testTag("close_dietary_guide_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer le guide"
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Section 1: Starch Equivalences Card
Surface(
shape = RoundedCornerShape(18.dp),
color = FoodCategory.STARCH.badgeContainerColor(isDark),
border = BorderStroke(1.dp, FoodCategory.STARCH.badgeBorderColor(isDark)),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
tint = FoodCategory.STARCH.badgeTextColor(isDark),
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Équivalences féculents",
style = MaterialTheme.typography.titleSmall,
color = FoodCategory.STARCH.badgeTextColor(isDark),
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Base repère : env. 90 g crus par repas",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
DietaryReferenceGuide.starchEquivalences.forEach { eq ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 3.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = eq.label,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = eq.amount,
style = MaterialTheme.typography.labelMedium,
color = FoodCategory.STARCH.badgeTextColor(isDark),
fontWeight = FontWeight.Bold
)
}
}
}
}
Spacer(modifier = Modifier.height(18.dp))
// Section 2: Color Code & Daily Benchmarks
Text(
text = "Code couleur & Repères journaliers",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
FoodCategory.benchmarkCategories.forEach { category ->
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
verticalAlignment = Alignment.Top
) {
FoodCategoryColorDot(
category = category,
size = 12.dp,
modifier = Modifier.padding(top = 4.dp)
)
Spacer(modifier = Modifier.width(12.dp))
Column(modifier = Modifier.weight(1f)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = category.displayName,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
modifier = Modifier.weight(1f)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(3.dp))
Text(
text = category.dailyGuide,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
category.alternativeNote?.let { note ->
Spacer(modifier = Modifier.height(2.dp))
Text(
text = note,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
Spacer(modifier = Modifier.height(18.dp))
// Section 3: Sample Day Ideas from PDF
Text(
text = "Exemple de journée type",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Column(modifier = Modifier.padding(14.dp)) {
DietaryReferenceGuide.sampleDayExamples.forEach { mealPlan ->
SampleMealRow(
label = mealPlan.mealTitle,
content = mealPlan.items.joinToString(" • ")
)
}
}
}
Spacer(modifier = Modifier.height(14.dp))
// Section 4: Gentle Pleasure Reminder
Surface(
shape = RoundedCornerShape(14.dp),
color = FoodCategory.PLEASURE.badgeContainerColor(isDark),
border = BorderStroke(1.dp, FoodCategory.PLEASURE.badgeBorderColor(isDark)),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "💜 ${DietaryReferenceGuide.PLEASURE_REMINDER}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(14.dp)
)
}
Spacer(modifier = Modifier.height(24.dp))
}
}
}
@Composable
private fun SampleMealRow(label: String, content: String) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 2.dp)
) {
Text(
text = "$label : ",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.width(56.dp)
)
Text(
text = content,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f)
)
}
}
@@ -48,10 +48,12 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.ui.journal.components.DietaryGuideSheet
import com.example.ui.meal.components.FoodItemBuilderSection import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.ui.meal.components.MealDateTimePicker import com.example.ui.meal.components.MealDateTimePicker
import com.example.ui.meal.components.MealHungerSatietySection import com.example.ui.meal.components.MealHungerSatietySection
@@ -85,13 +87,16 @@ fun MealEntrySheet(
initialMeal: MealEntry? = null, initialMeal: MealEntry? = null,
defaultMealType: MealType = MealType.LUNCH, defaultMealType: MealType = MealType.LUNCH,
customFoods: List<CustomFoodEntry> = emptyList(), customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit) -> Unit = { _, _ -> }, onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit, onDismiss: () -> Unit,
onSaveMeal: (MealType, Long, Int, Int, String, List<MealFoodItem>, List<String>) -> Unit onSaveMeal: (MealType, Long, Int, Int, String, List<MealFoodItem>, List<String>) -> Unit
) { ) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current val context = LocalContext.current
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
val isEditingExisting = initialMeal != null && initialMeal.id.isNotBlank()
var showDietaryGuide by remember { mutableStateOf(false) }
var selectedType by rememberSaveable { var selectedType by rememberSaveable {
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType) mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
@@ -133,17 +138,24 @@ fun MealEntrySheet(
mutableStateListOf<String>() mutableStateListOf<String>()
} }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
// Current food builder input state // Current food builder input state
var foodNameInput by rememberSaveable { mutableStateOf("") } var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") } var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) } var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
// Combine custom foods (user enriched) + built-in catalog // Combine custom foods (user enriched) + built-in catalog
val mergedCatalog = remember(customFoods) { val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map { val customMapped = customFoods.map {
DefaultFoodCatalog.CatalogFood( DefaultFoodCatalog.CatalogFood(
name = it.name, name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit) defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
) )
} }
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet() val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
@@ -175,10 +187,16 @@ fun MealEntrySheet(
val cleanName = foodNameInput.trim() val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && foodItemsList.size < 30) { if (cleanName.isNotEmpty() && foodItemsList.size < 30) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 } val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
}
val newItem = MealFoodItem( val newItem = MealFoodItem(
name = cleanName, name = cleanName,
weight = parsedWeight, weight = parsedWeight,
unit = selectedFoodUnit unit = selectedFoodUnit,
category = resolvedCat
) )
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) } val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIndex >= 0) { if (existingIndex >= 0) {
@@ -186,12 +204,14 @@ fun MealEntrySheet(
} else { } else {
foodItemsList.add(newItem) foodItemsList.add(newItem)
} }
if (isNewCustomFood) { if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit) onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
} }
foodNameInput = "" foodNameInput = ""
foodWeightInput = "" foodWeightInput = ""
selectedFoodUnit = FoodUnit.G selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
hasUserOverriddenCategory = false
} }
} }
@@ -214,7 +234,6 @@ fun MealEntrySheet(
} }
val handleDismiss = { val handleDismiss = {
// Clean up only uncommitted new photos; do NOT delete existing saved photos
newlyCapturedPhotos.forEach { photoUri -> newlyCapturedPhotos.forEach { photoUri ->
ImageUtils.deletePhotoFile(context, photoUri) ImageUtils.deletePhotoFile(context, photoUri)
} }
@@ -239,15 +258,15 @@ fun MealEntrySheet(
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Column { Column(modifier = Modifier.weight(1f)) {
Text( Text(
text = if (initialMeal == null) "Noter un repas" else "Modifier / Corriger le repas", text = if (isEditingExisting) "Modifier / Corriger le repas" else "Noter un repas",
style = MaterialTheme.typography.headlineMedium, style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onSurface, color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = "Échelle sur 10, aliments pesés (optionnel) et note globale", text = "Échelle sur 10, aliments colorés (optionnel) et note globale",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -309,16 +328,34 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(22.dp)) Spacer(modifier = Modifier.height(22.dp))
// Subcomponent 5: Food items builder & flow-row chips // Subcomponent 5: Color-coded Food items builder & flow-row chips
FoodItemBuilderSection( FoodItemBuilderSection(
foodItemsList = foodItemsList, foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions, matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput, foodNameInput = foodNameInput,
onFoodNameChange = { foodNameInput = it }, onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
}
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
}
},
foodWeightInput = foodWeightInput, foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it }, onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit, selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it }, onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { category ->
selectedFoodCategory = category
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood, isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentFoodItem() }, onAddFoodItem = { addCurrentFoodItem() },
onItemClickForEdit = { item -> onItemClickForEdit = { item ->
@@ -327,11 +364,14 @@ fun MealEntrySheet(
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString() if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: "" } ?: ""
selectedFoodUnit = item.unit selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
hasUserOverriddenCategory = true
foodItemsList.remove(item) foodItemsList.remove(item)
}, },
onRemoveFoodItem = { item -> onRemoveFoodItem = { item ->
foodItemsList.remove(item) foodItemsList.remove(item)
} },
onOpenGuideClick = { showDietaryGuide = true }
) )
Spacer(modifier = Modifier.height(20.dp)) Spacer(modifier = Modifier.height(20.dp))
@@ -382,7 +422,6 @@ fun MealEntrySheet(
if (foodNameInput.trim().isNotEmpty()) { if (foodNameInput.trim().isNotEmpty()) {
addCurrentFoodItem() addCurrentFoodItem()
} }
// Physically delete only photos marked for deletion that were not re-added
photosMarkedForDeletion.forEach { photoUri -> photosMarkedForDeletion.forEach { photoUri ->
if (!photoUrisList.contains(photoUri)) { if (!photoUrisList.contains(photoUri)) {
ImageUtils.deletePhotoFile(context, photoUri) ImageUtils.deletePhotoFile(context, photoUri)
@@ -408,7 +447,7 @@ fun MealEntrySheet(
) )
) { ) {
Text( Text(
text = if (initialMeal == null) "Enregistrer le repas" else "Enregistrer le correctif", text = if (isEditingExisting) "Enregistrer le correctif" else "Enregistrer le repas",
style = MaterialTheme.typography.titleSmall style = MaterialTheme.typography.titleSmall
) )
} }
@@ -417,4 +456,8 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
} }
} }
if (showDietaryGuide) {
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
}
} }
@@ -1,6 +1,5 @@
package com.example.ui.meal.components package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.ExperimentalLayoutApi
@@ -14,10 +13,10 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu import androidx.compose.material.icons.filled.RestaurantMenu
@@ -34,17 +33,21 @@ import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.DefaultFoodCatalog import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.ui.common.FoodCategoryBadge
import com.example.ui.common.FoodCategoryColorDot
import com.example.ui.common.FoodCategorySelectorRow
@OptIn(ExperimentalLayoutApi::class) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
@@ -57,10 +60,16 @@ fun FoodItemBuilderSection(
onFoodWeightChange: (String) -> Unit, onFoodWeightChange: (String) -> Unit,
selectedFoodUnit: FoodUnit, selectedFoodUnit: FoodUnit,
onFoodUnitSelected: (FoodUnit) -> Unit, onFoodUnitSelected: (FoodUnit) -> Unit,
selectedFoodCategory: FoodCategory,
onFoodCategorySelected: (FoodCategory) -> Unit,
isNewCustomFood: Boolean, isNewCustomFood: Boolean,
onAddFoodItem: () -> Unit, onAddFoodItem: () -> Unit,
onItemClickForEdit: (MealFoodItem) -> Unit, onItemClickForEdit: (MealFoodItem) -> Unit,
onRemoveFoodItem: (MealFoodItem) -> Unit, onRemoveFoodItem: (MealFoodItem) -> Unit,
sectionTitle: String = "3. Aliments & Poids (optionnel)",
addButtonLabelPrefix: String = "Ajouter à l'assiette",
addedListCaption: String = "Aliments dans l'assiette (touchez pour modifier poids ou couleur) :",
onOpenGuideClick: (() -> Unit)? = null,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
Surface( Surface(
@@ -78,7 +87,10 @@ fun FoodItemBuilderSection(
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
Icon( Icon(
imageVector = Icons.Default.RestaurantMenu, imageVector = Icons.Default.RestaurantMenu,
contentDescription = null, contentDescription = null,
@@ -87,31 +99,53 @@ fun FoodItemBuilderSection(
) )
Spacer(modifier = Modifier.width(8.dp)) Spacer(modifier = Modifier.width(8.dp))
Text( Text(
text = "3. Aliments & Poids (optionnel)", text = sectionTitle,
style = MaterialTheme.typography.labelLarge, style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface color = MaterialTheme.colorScheme.onSurface
) )
} }
Text( Row(verticalAlignment = Alignment.CenterVertically) {
text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}", if (onOpenGuideClick != null) {
style = MaterialTheme.typography.labelSmall, TextButton(
color = MaterialTheme.colorScheme.primary, onClick = onOpenGuideClick,
fontWeight = FontWeight.SemiBold modifier = Modifier.testTag("builder_equivalences_button")
) ) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = "Voir les équivalences",
modifier = Modifier.size(15.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "Équivalences",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
}
Text(
text = "${foodItemsList.size}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
}
} }
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
Text( Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.", text = "Sélectionnez un aliment ou tapez-en un nouveau : sa couleur est détectée automatiquement et modifiable ci-dessous.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row // Auto-complete / Quick suggestions row with color dots
if (matchingSuggestions.isNotEmpty()) { if (matchingSuggestions.isNotEmpty()) {
LazyRow( LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
@@ -122,6 +156,10 @@ fun FoodItemBuilderSection(
onClick = { onClick = {
onFoodNameChange(suggestion.name) onFoodNameChange(suggestion.name)
onFoodUnitSelected(suggestion.defaultUnit) onFoodUnitSelected(suggestion.defaultUnit)
onFoodCategorySelected(suggestion.category)
},
icon = {
FoodCategoryColorDot(category = suggestion.category, size = 9.dp)
}, },
label = { label = {
Text( Text(
@@ -147,7 +185,10 @@ fun FoodItemBuilderSection(
.fillMaxWidth() .fillMaxWidth()
.testTag("food_name_input"), .testTag("food_name_input"),
placeholder = { placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)") Text("Nom de l'aliment (ex: Riz basmati, Saumon, Comté...)")
},
leadingIcon = {
FoodCategoryColorDot(category = selectedFoodCategory, size = 11.dp)
}, },
singleLine = true, singleLine = true,
shape = RoundedCornerShape(12.dp), shape = RoundedCornerShape(12.dp),
@@ -167,7 +208,7 @@ fun FoodItemBuilderSection(
if (isNewCustomFood) { if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
Text( Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments", text = "✨ « ${foodNameInput.trim()} » sera mémorisé avec sa couleur dans votre catalogue",
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary color = MaterialTheme.colorScheme.secondary
) )
@@ -175,7 +216,21 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.height(10.dp)) Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button // Food Category Color Selector
Text(
text = "Famille / Code couleur :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(6.dp))
FoodCategorySelectorRow(
selectedCategory = selectedFoodCategory,
onCategorySelected = onFoodCategorySelected
)
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
@@ -251,19 +306,19 @@ fun FoodItemBuilderSection(
Spacer(modifier = Modifier.width(6.dp)) Spacer(modifier = Modifier.width(6.dp))
Text( Text(
text = if (foodWeightInput.isNotBlank()) { text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})" "$addButtonLabelPrefix (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else { } else {
"Ajouter à l'assiette (sans poids)" "$addButtonLabelPrefix (sans poids)"
}, },
style = MaterialTheme.typography.labelLarge style = MaterialTheme.typography.labelLarge
) )
} }
// Added food items badges // Added color-coded food items badges
if (foodItemsList.isNotEmpty()) { if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp)) Spacer(modifier = Modifier.height(14.dp))
Text( Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :", text = addedListCaption,
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -275,36 +330,12 @@ fun FoodItemBuilderSection(
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
foodItemsList.forEach { item -> foodItemsList.forEach { item ->
Surface( FoodCategoryBadge(
shape = RoundedCornerShape(12.dp), text = item.displayBadge(),
color = MaterialTheme.colorScheme.surface, category = item.resolvedCategory(),
modifier = Modifier onClick = { onItemClickForEdit(item) },
.clip(RoundedCornerShape(12.dp)) onRemove = { onRemoveFoodItem(item) }
.clickable { onItemClickForEdit(item) } )
) {
Row(
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable { onRemoveFoodItem(item) }
.padding(2.dp)
)
}
}
} }
} }
} }
@@ -0,0 +1,473 @@
package com.example.ui.recipes
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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.RecipeEntry
import com.example.ui.common.FoodCategoryBadge
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun RecipeDetailSheet(
recipe: RecipeEntry,
customFoods: List<CustomFoodEntry>,
onDismiss: () -> Unit,
onEdit: () -> Unit,
onDelete: () -> Unit,
onLogAsMeal: (RecipeEntry, Int) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var displayServings by remember(recipe.id) { mutableIntStateOf(recipe.servings.coerceAtLeast(1)) }
var eatenServings by remember(recipe.id) { mutableIntStateOf(1) }
var showDeleteConfirm by remember { mutableStateOf(false) }
val checkedSteps = remember(recipe.id) { mutableStateListOf<Int>() }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val scaledIngredients = remember(recipe.ingredientsSerialized, displayServings) {
recipe.scaledIngredients(displayServings.toDouble())
}
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("recipe_detail_sheet")
) {
// Top bar: Tag + Edit/Delete/Close
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = onEdit,
modifier = Modifier.testTag("edit_recipe_button")
) {
Icon(
imageVector = Icons.Default.Edit,
contentDescription = "Modifier la recette",
tint = MaterialTheme.colorScheme.primary
)
}
IconButton(
onClick = { showDeleteConfirm = true },
modifier = Modifier.testTag("delete_recipe_button")
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Supprimer la recette",
tint = MaterialTheme.colorScheme.error
)
}
IconButton(
onClick = onDismiss,
modifier = Modifier.testTag("close_recipe_detail_button")
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer"
)
}
}
}
if (!recipe.photoUri.isNullOrBlank()) {
Spacer(modifier = Modifier.height(10.dp))
AsyncImage(
model = recipe.photoUri,
contentDescription = "Photo de ${recipe.title}",
modifier = Modifier
.fillMaxWidth()
.height(190.dp)
.clip(RoundedCornerShape(18.dp)),
contentScale = ContentScale.Crop
)
}
Spacer(modifier = Modifier.height(14.dp))
Text(
text = recipe.title,
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(6.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "Préparation : ${recipe.formatPrepTimeLabel()}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Spacer(modifier = Modifier.height(18.dp))
// Servings adjuster + Ingredients
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Ingrédients",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Row(verticalAlignment = Alignment.CenterVertically) {
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.size(34.dp)
.clip(CircleShape)
.clickable(enabled = displayServings > 1) {
if (displayServings > 1) displayServings--
}
.testTag("recipe_servings_minus")
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Réduire les portions",
modifier = Modifier.size(16.dp)
)
}
}
Text(
text = "$displayServings port.",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp)
)
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.size(34.dp)
.clip(CircleShape)
.clickable(enabled = displayServings < 20) {
if (displayServings < 20) displayServings++
}
.testTag("recipe_servings_plus")
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Augmenter les portions",
modifier = Modifier.size(16.dp)
)
}
}
}
}
Spacer(modifier = Modifier.height(12.dp))
if (scaledIngredients.isEmpty()) {
Text(
text = "Aucun ingrédient renseigné.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
scaledIngredients.forEach { item ->
FoodCategoryBadge(
text = item.displayBadge(),
category = item.resolvedCategory(customCategoryLookup)
)
}
}
}
}
}
// Steps checklist
if (recipe.steps.isNotEmpty()) {
Spacer(modifier = Modifier.height(18.dp))
Text(
text = "Étapes de préparation",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
recipe.steps.forEachIndexed { index, step ->
val isChecked = index in checkedSteps
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(12.dp))
.clickable {
if (isChecked) checkedSteps.remove(index) else checkedSteps.add(index)
}
.padding(vertical = 8.dp, horizontal = 4.dp),
verticalAlignment = Alignment.Top
) {
Icon(
imageVector = if (isChecked) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
contentDescription = if (isChecked) "Étape terminée" else "Marquer l'étape terminée",
tint = if (isChecked) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(top = 2.dp)
.size(20.dp)
)
Spacer(modifier = Modifier.width(10.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Étape ${index + 1}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Text(
text = step,
style = MaterialTheme.typography.bodyMedium,
color = if (isChecked) {
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
} else {
MaterialTheme.colorScheme.onSurface
},
textDecoration = if (isChecked) TextDecoration.LineThrough else TextDecoration.None
)
}
}
}
}
if (recipe.notes.isNotBlank()) {
Spacer(modifier = Modifier.height(16.dp))
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(14.dp)) {
Text(
text = "Astuces & Notes",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = recipe.notes,
style = MaterialTheme.typography.bodyMedium,
fontStyle = FontStyle.Italic,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
Spacer(modifier = Modifier.height(20.dp))
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f))
Spacer(modifier = Modifier.height(16.dp))
// Log recipe directly into Journal
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.3f)),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(14.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Portions mangées :",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(
onClick = { if (eatenServings > 1) eatenServings-- },
enabled = eatenServings > 1
) {
Icon(
imageVector = Icons.Default.Remove,
contentDescription = "Moins de portions mangées"
)
}
Text(
text = "$eatenServings",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 6.dp)
)
IconButton(
onClick = { if (eatenServings < 10) eatenServings++ },
enabled = eatenServings < 10
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Plus de portions mangées"
)
}
}
}
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = { onLogAsMeal(recipe, eatenServings) },
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.testTag("log_recipe_as_meal_button"),
shape = RoundedCornerShape(14.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Noter dans mon journal ($eatenServings part${if (eatenServings > 1) "s" else ""})",
style = MaterialTheme.typography.titleSmall
)
}
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
if (showDeleteConfirm) {
AlertDialog(
onDismissRequest = { showDeleteConfirm = false },
title = { Text("Supprimer cette recette ?") },
text = { Text("« ${recipe.title} » sera retirée de votre recueil local.") },
confirmButton = {
TextButton(
onClick = {
showDeleteConfirm = false
onDelete()
}
) {
Text("Supprimer", color = MaterialTheme.colorScheme.error)
}
},
dismissButton = {
TextButton(onClick = { showDeleteConfirm = false }) {
Text("Annuler")
}
}
)
}
}
@@ -0,0 +1,627 @@
package com.example.ui.recipes
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.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.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddPhotoAlternate
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecipeEditorSheet(
initialRecipe: RecipeEntry? = null,
customFoods: List<CustomFoodEntry> = emptyList(),
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
onDismiss: () -> Unit,
onSaveRecipe: (RecipeEntry) -> Unit
) {
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var title by rememberSaveable { mutableStateOf(initialRecipe?.title ?: "") }
var selectedTag by rememberSaveable {
mutableStateOf(initialRecipe?.categoryEnum() ?: RecipeCategoryTag.MAIN)
}
var prepTimeInput by rememberSaveable {
mutableStateOf(initialRecipe?.prepTimeMinutes?.takeIf { it > 0 }?.toString() ?: "")
}
var servingsInput by rememberSaveable {
mutableStateOf((initialRecipe?.servings ?: 2).toString())
}
var notes by rememberSaveable { mutableStateOf(initialRecipe?.notes ?: "") }
var photoUri by rememberSaveable { mutableStateOf(initialRecipe?.photoUri) }
var newlySavedPhotoUri by rememberSaveable { mutableStateOf<String?>(null) }
var isProcessingPhoto by remember { mutableStateOf(false) }
val ingredientsList = remember(initialRecipe?.id) {
mutableStateListOf<MealFoodItem>().apply {
if (initialRecipe != null) {
addAll(initialRecipe.parsedIngredients())
}
}
}
val stepsList = remember(initialRecipe?.id) {
mutableStateListOf<String>().apply {
if (initialRecipe != null) {
addAll(initialRecipe.steps)
}
}
}
// Ingredient builder state
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
var selectedFoodCategory by rememberSaveable { mutableStateOf(FoodCategory.OTHER) }
var hasUserOverriddenCategory by rememberSaveable { mutableStateOf(false) }
// Step builder state
var stepInput by rememberSaveable { mutableStateOf("") }
val mergedCatalog = remember(customFoods) {
val customMapped = customFoods.map {
DefaultFoodCatalog.CatalogFood(
name = it.name,
defaultUnit = FoodUnit.fromCode(it.defaultUnit),
category = it.resolvedCategory()
)
}
val customLowerSet = customMapped.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val builtInFiltered = DefaultFoodCatalog.builtInFoods.filter {
it.name.lowercase(Locale.FRENCH) !in customLowerSet
}
customMapped + builtInFiltered
}
val matchingSuggestions = remember(foodNameInput, mergedCatalog, ingredientsList.size) {
val addedNames = ingredientsList.map { it.name.lowercase(Locale.FRENCH) }.toSet()
val query = foodNameInput.trim().lowercase(Locale.FRENCH)
if (query.isEmpty()) {
mergedCatalog.filter { it.name.lowercase(Locale.FRENCH) !in addedNames }.take(10)
} else {
mergedCatalog.filter {
it.name.lowercase(Locale.FRENCH).contains(query) &&
it.name.lowercase(Locale.FRENCH) !in addedNames
}.take(8)
}
}
val isNewCustomFood = remember(foodNameInput, mergedCatalog) {
val clean = foodNameInput.trim()
clean.length >= 2 && mergedCatalog.none { it.name.equals(clean, ignoreCase = true) }
}
val addCurrentIngredient = {
val cleanName = foodNameInput.trim()
if (cleanName.isNotEmpty() && ingredientsList.size < 40) {
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
val resolvedCat = if (hasUserOverriddenCategory) {
selectedFoodCategory
} else {
FoodCategory.inferFromName(cleanName, customCategoryLookup)
}
val item = MealFoodItem(
name = cleanName,
weight = parsedWeight,
unit = selectedFoodUnit,
category = resolvedCat
)
val existingIdx = ingredientsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIdx >= 0) {
ingredientsList[existingIdx] = item
} else {
ingredientsList.add(item)
}
if (isNewCustomFood || hasUserOverriddenCategory) {
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
}
foodNameInput = ""
foodWeightInput = ""
selectedFoodUnit = FoodUnit.G
selectedFoodCategory = FoodCategory.OTHER
hasUserOverriddenCategory = false
}
}
val photoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri: Uri? ->
if (uri != null) {
isProcessingPhoto = true
coroutineScope.launch {
val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri)
if (savedUri != null) {
// Delete previous uncommitted new photo if replacing before save
newlySavedPhotoUri?.let { oldUnsaved ->
ImageUtils.deletePhotoFile(context, oldUnsaved)
}
photoUri = savedUri
newlySavedPhotoUri = savedUri
}
isProcessingPhoto = false
}
}
}
val handleDismiss = {
newlySavedPhotoUri?.let { ImageUtils.deletePhotoFile(context, it) }
onDismiss()
}
ModalBottomSheet(
onDismissRequest = handleDismiss,
sheetState = sheetState,
containerColor = MaterialTheme.colorScheme.surface,
dragHandle = null
) {
Column(
modifier = Modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(horizontal = 22.dp, vertical = 20.dp)
.testTag("recipe_editor_sheet")
) {
// Header
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = if (initialRecipe == null) "Nouvelle recette" else "Modifier la recette",
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Photo, ingrédients colorés et étapes simples",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
IconButton(onClick = handleDismiss) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Fermer"
)
}
}
Spacer(modifier = Modifier.height(14.dp))
// Cover Photo Picker (zero-permission PickVisualMedia)
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f)),
modifier = Modifier
.fillMaxWidth()
.height(140.dp)
.clip(RoundedCornerShape(16.dp))
.clickable {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
.testTag("recipe_pick_photo_button")
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(modifier = Modifier.size(28.dp))
} else if (!photoUri.isNullOrBlank()) {
AsyncImage(
model = photoUri,
contentDescription = "Photo de la recette",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
Surface(
shape = CircleShape,
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.85f),
modifier = Modifier
.align(Alignment.TopEnd)
.padding(8.dp)
.size(34.dp)
.clip(CircleShape)
.clickable { photoUri = null }
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = "Retirer la photo",
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(18.dp)
)
}
}
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddPhotoAlternate,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(30.dp)
)
Spacer(modifier = Modifier.height(6.dp))
Text(
text = "Ajouter une photo de couverture (optionnel)",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
Spacer(modifier = Modifier.height(14.dp))
// Title
OutlinedTextField(
value = title,
onValueChange = { if (it.length <= 120) title = it },
label = { Text("Nom de la recette *") },
placeholder = { Text("Ex: Dahl de lentilles corail, Bowl saumon avocat...") },
singleLine = true,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_title_input")
)
Spacer(modifier = Modifier.height(12.dp))
// Category Tag Chips
Text(
text = "Type de recette",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(6.dp))
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(RecipeCategoryTag.entries, key = { it.name }) { tag ->
FilterChip(
selected = selectedTag == tag,
onClick = { selectedTag = tag },
label = { Text(tag.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
Spacer(modifier = Modifier.height(12.dp))
// Prep Time & Servings Row
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = prepTimeInput,
onValueChange = { input ->
if (input.length <= 4 && input.all { it.isDigit() }) {
prepTimeInput = input
}
},
label = { Text("Temps (min)") },
placeholder = { Text("Ex: 25") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
)
OutlinedTextField(
value = servingsInput,
onValueChange = { input ->
if (input.length <= 2 && input.all { it.isDigit() }) {
servingsInput = input
}
},
label = { Text("Portions") },
placeholder = { Text("Ex: 2") },
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
)
}
Spacer(modifier = Modifier.height(18.dp))
// Color-Coded Ingredients Builder
FoodItemBuilderSection(
foodItemsList = ingredientsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { input ->
foodNameInput = input
if (!hasUserOverriddenCategory) {
selectedFoodCategory = if (input.isBlank()) {
FoodCategory.OTHER
} else {
FoodCategory.inferFromName(input, customCategoryLookup)
}
}
if (input.isBlank()) {
hasUserOverriddenCategory = false
selectedFoodCategory = FoodCategory.OTHER
}
},
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
selectedFoodCategory = selectedFoodCategory,
onFoodCategorySelected = { cat ->
selectedFoodCategory = cat
hasUserOverriddenCategory = true
},
isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentIngredient() },
onItemClickForEdit = { item ->
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
hasUserOverriddenCategory = true
ingredientsList.remove(item)
},
onRemoveFoodItem = { item -> ingredientsList.remove(item) },
sectionTitle = "Ingrédients colorés",
addButtonLabelPrefix = "Ajouter l'ingrédient",
addedListCaption = "Ingrédients de la recette (touchez pour modifier poids ou couleur) :"
)
Spacer(modifier = Modifier.height(18.dp))
// Preparation Steps Builder
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = "Étapes de préparation (${stepsList.size})",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(8.dp))
OutlinedTextField(
value = stepInput,
onValueChange = { if (it.length <= 300) stepInput = it },
placeholder = { Text("Ex: Faire revenir les oignons et les carottes 5 min...") },
maxLines = 3,
shape = RoundedCornerShape(12.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_step_input")
)
Spacer(modifier = Modifier.height(8.dp))
Button(
onClick = {
val cleanStep = stepInput.trim()
if (cleanStep.isNotEmpty() && stepsList.size < 30) {
stepsList.add(cleanStep)
stepInput = ""
}
},
enabled = stepInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_recipe_step_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Ajouter l'étape")
}
if (stepsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp))
stepsList.forEachIndexed { idx, step ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "${idx + 1}.",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = step,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
IconButton(
onClick = { stepsList.removeAt(idx) },
modifier = Modifier.size(32.dp)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer l'étape ${idx + 1}",
modifier = Modifier.size(16.dp)
)
}
}
}
}
}
}
}
Spacer(modifier = Modifier.height(16.dp))
// Notes
OutlinedTextField(
value = notes,
onValueChange = { if (it.length <= 400) notes = it },
label = { Text("Astuces / Notes (optionnel)") },
placeholder = { Text("Ex: Se conserve 3 jours au frais, délicieux avec du citron...") },
maxLines = 3,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(22.dp))
// Save / Cancel Actions
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically
) {
TextButton(onClick = handleDismiss) {
Text("Annuler")
}
Spacer(modifier = Modifier.width(10.dp))
Button(
onClick = {
if (foodNameInput.trim().isNotEmpty()) {
addCurrentIngredient()
}
if (stepInput.trim().isNotEmpty() && stepsList.size < 30) {
stepsList.add(stepInput.trim())
stepInput = ""
}
val oldPhoto = initialRecipe?.photoUri
if (!oldPhoto.isNullOrBlank() && oldPhoto != photoUri) {
ImageUtils.deletePhotoFile(context, oldPhoto)
}
val recipe = RecipeEntry(
id = initialRecipe?.id ?: "",
title = title.trim(),
categoryTag = selectedTag.name,
prepTimeMinutes = prepTimeInput.toIntOrNull()?.coerceAtLeast(0) ?: 0,
servings = (servingsInput.toIntOrNull() ?: 2).coerceIn(1, 30),
ingredientsSerialized = ingredientsList.map { it.serialize() },
steps = stepsList.toList(),
notes = notes.trim(),
photoUri = photoUri,
updatedAt = System.currentTimeMillis()
)
onSaveRecipe(recipe)
},
enabled = title.trim().isNotEmpty(),
modifier = Modifier
.height(48.dp)
.testTag("save_recipe_button"),
shape = RoundedCornerShape(14.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Text(
text = if (initialRecipe == null) "Enregistrer la recette" else "Mettre à jour",
style = MaterialTheme.typography.titleSmall
)
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@@ -0,0 +1,483 @@
package com.example.ui.recipes
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
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.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.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.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.example.data.model.CustomFoodEntry
import com.example.data.model.FoodCategory
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
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
@Composable
fun RecipesScreen(
recipes: List<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
onAddRecipeClick: () -> Unit,
onRecipeClick: (RecipeEntry) -> Unit
) {
var searchQuery by rememberSaveable { mutableStateOf("") }
var selectedTag by rememberSaveable { mutableStateOf<String?>(null) }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val filteredRecipes = remember(recipes, searchQuery, selectedTag) {
val query = searchQuery.trim().lowercase(Locale.FRENCH)
recipes.filter { recipe ->
val matchesTag = selectedTag == null || recipe.categoryTag.equals(selectedTag, ignoreCase = true)
val matchesQuery = query.isBlank() ||
recipe.title.lowercase(Locale.FRENCH).contains(query) ||
recipe.parsedIngredients().any { it.name.lowercase(Locale.FRENCH).contains(query) }
matchesTag && matchesQuery
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
.testTag("recipes_screen")
) {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.testTag("recipes_list"),
contentPadding = PaddingValues(
start = 20.dp,
end = 20.dp,
top = 16.dp,
bottom = 96.dp
),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
// Header
item {
Column {
Text(
text = "Mon Recueil de Recettes",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = 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"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
OutlinedTextField(
value = searchQuery,
onValueChange = { if (it.length <= 60) searchQuery = it },
modifier = Modifier
.fillMaxWidth()
.testTag("recipe_search_input"),
placeholder = { Text("Rechercher une recette ou un ingrédient...") },
leadingIcon = {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
},
trailingIcon = {
if (searchQuery.isNotEmpty()) {
IconButton(onClick = { searchQuery = "" }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer la recherche"
)
}
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
}
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
item {
FilterChip(
selected = selectedTag == null,
onClick = { selectedTag = null },
label = { Text("Toutes") },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
items(RecipeCategoryTag.entries, key = { it.name }) { tag ->
FilterChip(
selected = selectedTag == tag.name,
onClick = {
selectedTag = if (selectedTag == tag.name) null else tag.name
},
label = { Text(tag.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
}
// Content
if (recipes.isEmpty()) {
item {
EmptyRecipesView(onAddRecipeClick = onAddRecipeClick)
}
} else if (filteredRecipes.isEmpty()) {
item {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Aucune recette ne correspond à ce filtre",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.height(8.dp))
TextButton(
onClick = {
searchQuery = ""
selectedTag = null
}
) {
Text("Réinitialiser les filtres")
}
}
}
}
} else {
items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem(
recipe = recipe,
customCategoryLookup = customCategoryLookup,
onClick = { onRecipeClick(recipe) }
)
}
}
}
FloatingActionButton(
onClick = onAddRecipeClick,
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(24.dp)
.testTag("add_recipe_fab"),
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary,
shape = CircleShape
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Créer une recette",
modifier = Modifier.size(28.dp)
)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun RecipeCardItem(
recipe: RecipeEntry,
customCategoryLookup: Map<String, FoodCategory>,
onClick: () -> Unit
) {
val isDark = isSatieaDarkTheme()
val ingredients = remember(recipe.ingredientsSerialized) { recipe.parsedIngredients() }
val dominantCategories = remember(recipe.ingredientsSerialized, customCategoryLookup) {
recipe.dominantCategories(customCategoryLookup).take(4)
}
Card(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = onClick)
.testTag("recipe_card_${recipe.id}"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f))
) {
Column(modifier = Modifier.fillMaxWidth()) {
if (!recipe.photoUri.isNullOrBlank()) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(145.dp)
) {
AsyncImage(
model = recipe.photoUri,
contentDescription = "Photo de ${recipe.title}",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
)
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f),
modifier = Modifier
.align(Alignment.TopStart)
.padding(12.dp)
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp)
) {
if (recipe.photoUri.isNullOrBlank()) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = recipe.categoryEnum().displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
}
Text(
text = recipe.title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.height(8.dp))
// Metadata chips (prep time, servings, ingredient count)
Row(
horizontalArrangement = Arrangement.spacedBy(14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = recipe.formatPrepTimeLabel(),
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(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${recipe.servings} portion${if (recipe.servings > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Text(
text = "${ingredients.size} ingrédient${if (ingredients.size > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (dominantCategories.isNotEmpty()) {
Spacer(modifier = Modifier.height(12.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
dominantCategories.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
)
}
}
}
}
}
}
}
}
}
@Composable
private fun EmptyRecipesView(onAddRecipeClick: () -> Unit) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 44.dp, horizontal = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
modifier = Modifier.size(82.dp),
shape = CircleShape,
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
) {
Box(contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.AutoMirrored.Filled.MenuBook,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(38.dp)
)
}
}
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "Votre recueil est prêt",
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "Ajoutez vos plats maison avec photo, ingrédients colorés et étapes, puis notez une portion dans votre journal en un clic.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(20.dp))
TextButton(
onClick = onAddRecipeClick,
modifier = Modifier.testTag("empty_recipes_add_button")
) {
Text(
text = "+ Créer ma première recette",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary
)
}
}
}
@@ -24,11 +24,11 @@ import com.example.ui.settings.components.DataExportImportSection
import com.example.ui.settings.components.GoogleSheetsIntegrationSection import com.example.ui.settings.components.GoogleSheetsIntegrationSection
import com.example.ui.settings.components.NotificationRemindersSection import com.example.ui.settings.components.NotificationRemindersSection
import com.example.ui.theme.AppThemeMode import com.example.ui.theme.AppThemeMode
import com.google.firebase.Firebase import com.example.util.GoogleDriveAccount
import com.google.firebase.auth.auth
@Composable @Composable
fun SettingsScreen( fun SettingsScreen(
googleAccount: GoogleDriveAccount?,
currentThemeMode: AppThemeMode, currentThemeMode: AppThemeMode,
totalMealsCount: Int, totalMealsCount: Int,
sheetsUiState: GoogleSheetsUiState, sheetsUiState: GoogleSheetsUiState,
@@ -48,8 +48,6 @@ fun SettingsScreen(
onSignOut: () -> Unit, onSignOut: () -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val currentUser = Firebase.auth.currentUser
LazyColumn( LazyColumn(
modifier = modifier modifier = modifier
.fillMaxSize() .fillMaxSize()
@@ -70,20 +68,19 @@ fun SettingsScreen(
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = "Export CSV, rappels personnalisés, thème et compte", text = "Sauvegarde Google Drive, export CSV, rappels et thème",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f) color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
) )
} }
} }
// 1. Local Database & CSV Management // 1. Google Drive Account
item { item {
DataExportImportSection( AccountAndSecuritySection(
totalMealsCount = totalMealsCount, googleAccount = googleAccount,
onImportCsvClick = onImportCsvClick, onSignInClick = onSignInClick,
onSaveCsvClick = onSaveCsvClick, onSignOut = onSignOut
onShareCsvClick = onShareCsvClick
) )
} }
@@ -100,7 +97,17 @@ fun SettingsScreen(
) )
} }
// 3. Reminders // 3. Local Database & CSV Management
item {
DataExportImportSection(
totalMealsCount = totalMealsCount,
onImportCsvClick = onImportCsvClick,
onSaveCsvClick = onSaveCsvClick,
onShareCsvClick = onShareCsvClick
)
}
// 4. Reminders
item { item {
NotificationRemindersSection( NotificationRemindersSection(
onScheduleReminder = onScheduleReminder, onScheduleReminder = onScheduleReminder,
@@ -108,7 +115,7 @@ fun SettingsScreen(
) )
} }
// 4. Theme Selector // 5. Theme Selector
item { item {
AppearanceThemeSection( AppearanceThemeSection(
currentThemeMode = currentThemeMode, currentThemeMode = currentThemeMode,
@@ -116,15 +123,6 @@ fun SettingsScreen(
) )
} }
// 5. Account & Cloud Sync
item {
AccountAndSecuritySection(
currentUser = currentUser,
onSignInClick = onSignInClick,
onSignOut = onSignOut
)
}
item { item {
Spacer(modifier = Modifier.height(64.dp)) Spacer(modifier = Modifier.height(64.dp))
} }
@@ -17,7 +17,7 @@ import androidx.compose.material.icons.automirrored.filled.ExitToApp
import androidx.compose.material.icons.automirrored.filled.Login import androidx.compose.material.icons.automirrored.filled.Login
import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.CloudDone import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card import androidx.compose.material3.Card
@@ -32,11 +32,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.google.firebase.auth.FirebaseUser import com.example.util.GoogleDriveAccount
@Composable @Composable
fun AccountAndSecuritySection( fun AccountAndSecuritySection(
currentUser: FirebaseUser?, googleAccount: GoogleDriveAccount?,
onSignInClick: () -> Unit, onSignInClick: () -> Unit,
onSignOut: () -> Unit, onSignOut: () -> Unit,
modifier: Modifier = Modifier modifier: Modifier = Modifier
@@ -49,7 +49,7 @@ fun AccountAndSecuritySection(
) )
) { ) {
Column(modifier = Modifier.padding(20.dp)) { Column(modifier = Modifier.padding(20.dp)) {
if (currentUser != null) { if (googleAccount != null) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
Surface( Surface(
modifier = Modifier.size(40.dp), modifier = Modifier.size(40.dp),
@@ -70,13 +70,13 @@ fun AccountAndSecuritySection(
Column { Column {
Text( Text(
text = currentUser.displayName ?: "Compte Google", text = googleAccount.displayName ?: "Compte Google Drive",
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface, color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = currentUser.email ?: "Synchronisation Cloud Firestore active", text = googleAccount.email,
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -103,7 +103,7 @@ fun AccountAndSecuritySection(
) )
Spacer(modifier = Modifier.width(8.dp)) Spacer(modifier = Modifier.width(8.dp))
Text( Text(
text = "Base de données cloud sécurisée • Synchronisation continue", text = "Stockage local actif • Compte Google utilisé uniquement pour votre Google Drive personnel",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -128,7 +128,7 @@ fun AccountAndSecuritySection(
modifier = Modifier.size(18.dp) modifier = Modifier.size(18.dp)
) )
Spacer(modifier = Modifier.width(8.dp)) Spacer(modifier = Modifier.width(8.dp))
Text("Passer en mode local uniquement (Déconnexion)") Text("Déconnecter Google Drive")
} }
} else { } else {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
@@ -139,7 +139,7 @@ fun AccountAndSecuritySection(
) { ) {
Box(contentAlignment = Alignment.Center) { Box(contentAlignment = Alignment.Center) {
Icon( Icon(
imageVector = Icons.Default.CloudOff, imageVector = Icons.Default.PhoneAndroid,
contentDescription = null, contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondaryContainer, tint = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.size(22.dp) modifier = Modifier.size(22.dp)
@@ -151,13 +151,13 @@ fun AccountAndSecuritySection(
Column { Column {
Text( Text(
text = "Mode hors-ligne local actif", text = "Stockage 100 % local actif",
style = MaterialTheme.typography.titleMedium, style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface, color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = "Données stockées sur cet appareil sans aucun compte", text = "Repas, aliments et recettes enregistrés sur cet appareil",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -167,7 +167,7 @@ fun AccountAndSecuritySection(
Spacer(modifier = Modifier.height(14.dp)) Spacer(modifier = Modifier.height(14.dp))
Text( Text(
text = "Vous pouvez utiliser Satiéa librement en local. La connexion Google est optionnelle pour sauvegarder et synchroniser vos repas entre appareils.", text = "Aucun serveur externe ni base cloud tierce. Connectez votre compte Google uniquement si vous souhaitez sauvegarder et restaurer vos données sur votre propre Google Drive.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -187,7 +187,7 @@ fun AccountAndSecuritySection(
modifier = Modifier.size(18.dp) modifier = Modifier.size(18.dp)
) )
Spacer(modifier = Modifier.width(8.dp)) Spacer(modifier = Modifier.width(8.dp))
Text("Se connecter avec Google (Optionnel)") Text("Connecter mon compte Google Drive")
} }
} }
} }
@@ -333,7 +333,7 @@ fun GoogleSheetsIntegrationSection(
OutlinedButton( OutlinedButton(
onClick = { showRestoreConfirmDialog = true }, onClick = { showRestoreConfirmDialog = true },
enabled = spreadsheetUrl != null && sheetsUiState !is GoogleSheetsUiState.Syncing, enabled = sheetsUiState !is GoogleSheetsUiState.Syncing,
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.testTag("restore_sheets_button"), .testTag("restore_sheets_button"),
@@ -345,13 +345,13 @@ fun GoogleSheetsIntegrationSection(
modifier = Modifier.size(18.dp) modifier = Modifier.size(18.dp)
) )
Spacer(modifier = Modifier.width(6.dp)) Spacer(modifier = Modifier.width(6.dp))
Text("Restaurer mes données depuis Google Drive & Sheets") Text("Restaurer depuis Google Drive & Sheets")
} }
Spacer(modifier = Modifier.height(12.dp)) Spacer(modifier = Modifier.height(12.dp))
Text( Text(
text = "Un classeur dédié « Satiéa — Journal des Repas » est géré automatiquement dans votre Google Drive personnel avec en-têtes et données ordonnées.", text = "Votre dossier personnel « Satiéa » sur Google Drive contient vos photos ainsi que le classeur 3 onglets : Journal des repas, Mes plats et aliments, et Mes recettes.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f) color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
) )
@@ -370,7 +370,7 @@ fun GoogleSheetsIntegrationSection(
}, },
text = { text = {
Text( Text(
text = "Voulez-vous restaurer vos repas et plats personnalisés depuis votre classeur Google Sheets ?\n\nVos ajouts locaux récents seront conservés et fusionnés sans doublon.", text = "Voulez-vous restaurer vos repas, aliments colorés et recettes depuis votre classeur Google Sheets personnel ?\n\nVos ajouts locaux récents seront conservés et fusionnés sans doublon.",
style = MaterialTheme.typography.bodyMedium style = MaterialTheme.typography.bodyMedium
) )
}, },
@@ -1,13 +1,17 @@
package com.example.ui.stats package com.example.ui.stats
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Canvas import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column 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.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
@@ -34,6 +38,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
@@ -43,7 +48,14 @@ import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.testTag import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.example.data.model.FoodCategory
import com.example.data.model.MealType import com.example.data.model.MealType
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.dotFillColor
import com.example.ui.common.isSatieaDarkTheme
import com.example.ui.journal.DayStat import com.example.ui.journal.DayStat
import com.example.ui.journal.WeeklyStats import com.example.ui.journal.WeeklyStats
import java.util.Locale import java.util.Locale
@@ -258,6 +270,11 @@ fun WeeklyStatsScreen(
} }
} }
// Color-coded food diversity over last 7 days
item {
PlateDiversityCard(categoryDistribution = weeklyStats.categoryDistribution)
}
// Meal type breakdown // Meal type breakdown
item { item {
Card( Card(
@@ -321,6 +338,123 @@ fun WeeklyStatsScreen(
} }
} }
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun PlateDiversityCard(
categoryDistribution: Map<FoodCategory, Int>
) {
val isDark = isSatieaDarkTheme()
val sortedEntries = categoryDistribution.entries
.filter { it.value > 0 }
.sortedByDescending { it.value }
val totalItems = sortedEntries.sumOf { it.value }
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("stats_plate_diversity_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surface
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Diversité des assiettes (7 jours)",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
if (totalItems > 0) {
Text(
text = "${sortedEntries.size} famille${if (sortedEntries.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
}
Spacer(modifier = Modifier.height(6.dp))
if (totalItems == 0) {
Text(
text = "Ajoutez des aliments dans vos repas pour visualiser les couleurs de vos assiettes.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
} else {
Text(
text = "Présence des familles alimentaires sur vos repas récents",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(14.dp))
// Segmented proportional color bar
Row(
modifier = Modifier
.fillMaxWidth()
.height(12.dp)
.clip(RoundedCornerShape(6.dp))
.background(MaterialTheme.colorScheme.surfaceVariant),
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
sortedEntries.forEach { (category, count) ->
val weight = (count.toFloat() / totalItems.toFloat()).coerceAtLeast(0.03f)
Box(
modifier = Modifier
.weight(weight)
.fillMaxHeight()
.background(category.dotFillColor(isDark))
)
}
}
Spacer(modifier = Modifier.height(14.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
sortedEntries.forEach { (category, count) ->
Surface(
shape = RoundedCornerShape(10.dp),
color = category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, category.badgeBorderColor(isDark))
) {
Row(
modifier = Modifier.padding(horizontal = 9.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "${category.shortLabel} · $count",
style = MaterialTheme.typography.labelSmall,
color = category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
}
}
}
}
}
}
}
}
@Composable @Composable
private fun WeeklyChartCard(dailyStats: List<DayStat>) { private fun WeeklyChartCard(dailyStats: List<DayStat>) {
val satietyColor = MaterialTheme.colorScheme.primary val satietyColor = MaterialTheme.colorScheme.primary
@@ -106,7 +106,6 @@ object CsvImporter {
val newMeal = MealEntry( val newMeal = MealEntry(
id = "local_imp_${UUID.randomUUID().toString().take(8)}", id = "local_imp_${UUID.randomUUID().toString().take(8)}",
userId = "",
mealType = mealType.name, mealType = mealType.name,
mealTimestamp = timestamp, mealTimestamp = timestamp,
hungerBefore = hunger, hungerBefore = hunger,
@@ -2,17 +2,25 @@ package com.example.util
import android.accounts.Account import android.accounts.Account
import android.content.Context import android.content.Context
import com.example.R
import com.google.android.gms.auth.GoogleAuthUtil import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.UserRecoverableAuthException import com.google.android.gms.auth.UserRecoverableAuthException
import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.Scope import com.google.android.gms.common.api.Scope
import com.google.firebase.Firebase
import com.google.firebase.auth.auth
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
/**
* Lightweight representation of the Google account connected solely for
* personal Google Drive and Google Sheets backup/restore.
*/
data class GoogleDriveAccount(
val displayName: String?,
val email: String
)
object GoogleSheetsAuthHelper { object GoogleSheetsAuthHelper {
@@ -25,31 +33,30 @@ object GoogleSheetsAuthHelper {
const val OAUTH_SCOPE_STRING = "oauth2:$SCOPE_SPREADSHEETS_URL $SCOPE_DRIVE_FILE_URL" const val OAUTH_SCOPE_STRING = "oauth2:$SCOPE_SPREADSHEETS_URL $SCOPE_DRIVE_FILE_URL"
fun getGoogleSignInClient(context: Context): GoogleSignInClient { fun getGoogleSignInClient(context: Context): GoogleSignInClient {
val serverClientId = try { val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
context.getString(R.string.default_web_client_id)
} catch (_: Exception) {
null
}
val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail() .requestEmail()
.requestScopes(SCOPE_SPREADSHEETS, SCOPE_DRIVE_FILE) .requestScopes(SCOPE_SPREADSHEETS, SCOPE_DRIVE_FILE)
.build()
if (!serverClientId.isNullOrBlank()) { return GoogleSignIn.getClient(context, gso)
gsoBuilder.requestIdToken(serverClientId) }
}
return GoogleSignIn.getClient(context, gsoBuilder.build()) fun getSignedInAccount(context: Context): GoogleDriveAccount? {
val account = GoogleSignIn.getLastSignedInAccount(context) ?: return null
val email = account.email?.takeIf { it.isNotBlank() } ?: return null
return GoogleDriveAccount(
displayName = account.displayName?.takeIf { it.isNotBlank() },
email = email
)
} }
suspend fun getAccessToken(context: Context): Result<String> = withContext(Dispatchers.IO) { suspend fun getAccessToken(context: Context): Result<String> = withContext(Dispatchers.IO) {
try { try {
val email = Firebase.auth.currentUser?.email val email = GoogleSignIn.getLastSignedInAccount(context)?.email
?: GoogleSignIn.getLastSignedInAccount(context)?.email
if (email.isNullOrBlank()) { if (email.isNullOrBlank()) {
return@withContext Result.failure( return@withContext Result.failure(
IllegalStateException("Aucun compte Google connecté. Veuillez vous connecter pour synchroniser avec Google Sheets.") IllegalStateException("Aucun compte Google connecté. Connectez votre compte pour sauvegarder sur Google Drive.")
) )
} }
@@ -69,4 +76,20 @@ object GoogleSheetsAuthHelper {
GoogleAuthUtil.clearToken(context.applicationContext, token) GoogleAuthUtil.clearToken(context.applicationContext, token)
} catch (_: Exception) {} } catch (_: Exception) {}
} }
suspend fun signOut(context: Context) {
suspendCancellableCoroutine<Unit> { continuation ->
try {
getGoogleSignInClient(context).signOut().addOnCompleteListener {
if (continuation.isActive) {
continuation.resume(Unit)
}
}
} catch (_: Exception) {
if (continuation.isActive) {
continuation.resume(Unit)
}
}
}
}
} }
@@ -1,11 +1,14 @@
package com.example.util package com.example.util
import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalCustomFoodEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.HungerSatietyScale import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import java.time.Instant import java.time.Instant
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.ZoneId import java.time.ZoneId
@@ -30,7 +33,19 @@ object GoogleSheetsDataFormatter {
val HEADERS_CUSTOM_FOODS: List<String> = listOf( val HEADERS_CUSTOM_FOODS: List<String> = listOf(
"Nom de l'aliment / Plat", "Nom de l'aliment / Plat",
"Unité par défaut", "Unité par défaut",
"Date d'ajout" "Date d'ajout",
"Catégorie"
)
val HEADERS_RECIPES: List<String> = listOf(
"Titre",
"Type",
"Temps (min)",
"Portions",
"Ingrédients",
"Étapes",
"Notes",
"Photo"
) )
// Backward-compatibility alias // Backward-compatibility alias
@@ -39,6 +54,8 @@ object GoogleSheetsDataFormatter {
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH) private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH) private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
private val dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm", Locale.FRENCH) private val dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm", Locale.FRENCH)
private val ingredientCategoryRegex = Regex("""^(.*?)\s*\[([^\]]+)]\s*$""")
private val stepPrefixRegex = Regex("""^\d+\.\s*""")
fun formatMealsToRows( fun formatMealsToRows(
meals: List<MealEntry>, meals: List<MealEntry>,
@@ -102,11 +119,53 @@ object GoogleSheetsDataFormatter {
} catch (_: Exception) { } catch (_: Exception) {
"" ""
} }
val categoryLabel = food.resolvedCategory().displayName
rows.add( rows.add(
listOf( listOf(
food.name, food.name,
food.defaultUnit, food.defaultUnit,
dateStr dateStr,
categoryLabel
)
)
}
return rows
}
fun formatRecipesToRows(
recipes: List<RecipeEntry>,
photoLinkProvider: (String) -> String? = { null }
): List<List<Any>> {
val rows = mutableListOf<List<Any>>()
rows.add(HEADERS_RECIPES)
val sortedRecipes = recipes.sortedBy { it.title.lowercase(Locale.FRENCH) }
for (recipe in sortedRecipes) {
val ingredientsStr = recipe.parsedIngredients().joinToString(" ; ") { item ->
val catLabel = item.resolvedCategory().displayName
"${item.displayCsv()} [$catLabel]"
}
val stepsStr = recipe.steps
.map { it.replace("\r\n", " ").replace("\n", " ").trim() }
.filter { it.isNotBlank() }
.mapIndexed { idx, step -> "${idx + 1}. $step" }
.joinToString(" | ")
val cleanNotes = recipe.notes.replace("\r\n", " ").replace("\n", " ").trim()
val photoCell = recipe.photoUri?.let { uri ->
photoLinkProvider(uri) ?: uri.takeIf { it.startsWith("http") }
}.orEmpty()
rows.add(
listOf(
recipe.title,
recipe.categoryEnum().displayName,
recipe.prepTimeMinutes,
recipe.servings,
ingredientsStr,
stepsStr,
cleanNotes,
photoCell
) )
) )
} }
@@ -180,8 +239,81 @@ object GoogleSheetsDataFormatter {
if (name.isBlank()) continue if (name.isBlank()) continue
val unitStr = row.getOrNull(1)?.toString()?.trim() ?: "g" val unitStr = row.getOrNull(1)?.toString()?.trim() ?: "g"
val unit = FoodUnit.fromCode(unitStr) val unit = FoodUnit.fromCode(unitStr)
foods.add(LocalCustomFoodEntity.create(name, unit)) val categoryRaw = row.getOrNull(3)?.toString()?.trim().orEmpty()
val resolvedCategory = parseFoodCategory(categoryRaw) ?: FoodCategory.inferFromName(name)
foods.add(LocalCustomFoodEntity.create(name, unit, resolvedCategory))
} }
return foods return foods
} }
fun parseRowsToRecipes(rows: List<List<Any>>): List<RecipeEntry> {
if (rows.size <= 1) return emptyList()
val recipes = mutableListOf<RecipeEntry>()
for (i in 1 until rows.size) {
val row = rows[i]
if (row.isEmpty()) continue
try {
val title = row.getOrNull(0)?.toString()?.trim().orEmpty()
if (title.isBlank()) continue
val tagRaw = row.getOrNull(1)?.toString()?.trim().orEmpty()
val categoryTag = RecipeCategoryTag.fromString(tagRaw)
val prepTime = row.getOrNull(2)?.toString()?.toIntOrNull()?.coerceAtLeast(0) ?: 0
val servings = row.getOrNull(3)?.toString()?.toIntOrNull()?.coerceAtLeast(1) ?: 2
val ingredientsRaw = row.getOrNull(4)?.toString()?.trim().orEmpty()
val stepsRaw = row.getOrNull(5)?.toString()?.trim().orEmpty()
val notes = row.getOrNull(6)?.toString()?.trim().orEmpty()
val photoRaw = row.getOrNull(7)?.toString()?.trim().orEmpty()
val ingredients = parseRecipeIngredientsCell(ingredientsRaw).map { it.serialize() }
val steps = if (stepsRaw.isBlank()) {
emptyList()
} else {
stepsRaw.split("|")
.map { it.trim().replace(stepPrefixRegex, "") }
.filter { it.isNotBlank() }
}
val photoUri = photoRaw.takeIf { it.startsWith("http") }
recipes.add(
RecipeEntry(
id = "restored_recipe_${i}_${title.lowercase(Locale.ROOT).hashCode()}",
title = title,
categoryTag = categoryTag.name,
prepTimeMinutes = prepTime,
servings = servings,
ingredientsSerialized = ingredients,
steps = steps,
notes = notes,
photoUri = photoUri
)
)
} catch (_: Exception) {
// Ignore malformed individual rows
}
}
return recipes
}
private fun parseRecipeIngredientsCell(cell: String): List<MealFoodItem> {
if (cell.isBlank()) return emptyList()
return cell.split(";").mapNotNull { token ->
val trimmed = token.trim()
if (trimmed.isBlank()) return@mapNotNull null
val match = ingredientCategoryRegex.matchEntire(trimmed)
val baseText = match?.groupValues?.getOrNull(1)?.trim() ?: trimmed
val categoryLabel = match?.groupValues?.getOrNull(2)?.trim()
val explicitCategory = categoryLabel?.let { parseFoodCategory(it) }
val parsed = CsvImporter.parseFoodItems(baseText).firstOrNull() ?: return@mapNotNull null
parsed.copy(category = explicitCategory ?: parsed.resolvedCategory())
}
}
private fun parseFoodCategory(raw: String): FoodCategory? {
return FoodCategory.fromCode(raw)
}
} }
@@ -3,6 +3,7 @@ package com.example.util
import android.util.Log import android.util.Log
import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalCustomFoodEntity
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.RecipeEntry
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType import okhttp3.MediaType.Companion.toMediaType
@@ -19,12 +20,14 @@ data class GoogleSheetsSyncResult(
val spreadsheetUrl: String, val spreadsheetUrl: String,
val mealsCount: Int, val mealsCount: Int,
val foodsCount: Int = 0, val foodsCount: Int = 0,
val recipesCount: Int = 0,
val timestamp: Long = System.currentTimeMillis() val timestamp: Long = System.currentTimeMillis()
) )
data class SpreadsheetRestoreData( data class SpreadsheetRestoreData(
val meals: List<MealEntry>, val meals: List<MealEntry>,
val foods: List<LocalCustomFoodEntity> val foods: List<LocalCustomFoodEntity>,
val recipes: List<RecipeEntry> = emptyList()
) )
class AuthExpiredException(message: String) : IllegalStateException(message) class AuthExpiredException(message: String) : IllegalStateException(message)
@@ -35,6 +38,7 @@ object GoogleSheetsSyncService {
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas" const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
const val SHEET_TAB_MEALS = "Journal des repas" const val SHEET_TAB_MEALS = "Journal des repas"
const val SHEET_TAB_FOODS = "Mes plats et aliments" const val SHEET_TAB_FOODS = "Mes plats et aliments"
const val SHEET_TAB_RECIPES = "Mes recettes"
// Backward compatibility // Backward compatibility
const val SHEET_TAB_TITLE = SHEET_TAB_MEALS const val SHEET_TAB_TITLE = SHEET_TAB_MEALS
@@ -53,7 +57,7 @@ object GoogleSheetsSyncService {
parentFolderId: String? = null parentFolderId: String? = null
): Result<Pair<String, String>> = withContext(Dispatchers.IO) { ): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
try { try {
// 1. If we have a cached spreadsheetId, verify it still exists and ensure 2 tabs // 1. If we have a cached spreadsheetId, verify it still exists and ensure all 3 tabs
if (!cachedSpreadsheetId.isNullOrBlank()) { if (!cachedSpreadsheetId.isNullOrBlank()) {
val checkRequest = Request.Builder() val checkRequest = Request.Builder()
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl,sheets.properties") .url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl,sheets.properties")
@@ -113,28 +117,22 @@ object GoogleSheetsSyncService {
} }
} }
// 3. Not found: create a new Google Sheet with BOTH tabs (Meals + Custom Foods) // 3. Not found: create a new Google Sheet with all 3 tabs (Meals + Custom Foods + Recipes)
val createPayload = JSONObject().apply { val createPayload = JSONObject().apply {
put("properties", JSONObject().apply { put("properties", JSONObject().apply {
put("title", SPREADSHEET_TITLE) put("title", SPREADSHEET_TITLE)
}) })
put("sheets", JSONArray().apply { put("sheets", JSONArray().apply {
put(JSONObject().apply { listOf(SHEET_TAB_MEALS, SHEET_TAB_FOODS, SHEET_TAB_RECIPES).forEach { tabTitle ->
put("properties", JSONObject().apply { put(JSONObject().apply {
put("title", SHEET_TAB_MEALS) put("properties", JSONObject().apply {
put("gridProperties", JSONObject().apply { put("title", tabTitle)
put("frozenRowCount", 1) put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
}) })
}) })
}) }
put(JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_FOODS)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
})
})
}) })
} }
@@ -158,7 +156,6 @@ object GoogleSheetsSyncService {
val id = json.getString("spreadsheetId") val id = json.getString("spreadsheetId")
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit") val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
// Move new sheet into Satiéa Drive folder
if (parentFolderId != null) { if (parentFolderId != null) {
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId) GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
} }
@@ -180,7 +177,7 @@ object GoogleSheetsSyncService {
/** /**
* Inspects spreadsheet tabs, migrates legacy/default sheet titles ("Journal", "Feuille 1", "Sheet1") * Inspects spreadsheet tabs, migrates legacy/default sheet titles ("Journal", "Feuille 1", "Sheet1")
* to "Journal des repas", and creates "Mes plats et aliments" or "Journal des repas" if missing. * to "Journal des repas", and creates "Mes plats et aliments" and "Mes recettes" if missing.
*/ */
suspend fun ensureTabsExist( suspend fun ensureTabsExist(
accessToken: String, accessToken: String,
@@ -203,6 +200,7 @@ object GoogleSheetsSyncService {
val sheets = json.optJSONArray("sheets") ?: return@withContext val sheets = json.optJSONArray("sheets") ?: return@withContext
var hasMealsTab = false var hasMealsTab = false
var hasFoodsTab = false var hasFoodsTab = false
var hasRecipesTab = false
var legacySheetIdToRename: Int? = null var legacySheetIdToRename: Int? = null
val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1") val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1")
@@ -215,6 +213,7 @@ object GoogleSheetsSyncService {
when { when {
title == SHEET_TAB_MEALS -> hasMealsTab = true title == SHEET_TAB_MEALS -> hasMealsTab = true
title == SHEET_TAB_FOODS -> hasFoodsTab = true title == SHEET_TAB_FOODS -> hasFoodsTab = true
title == SHEET_TAB_RECIPES -> hasRecipesTab = true
legacySheetIdToRename == null && legacyTabNames.contains(title) && sId != -1 -> { legacySheetIdToRename == null && legacyTabNames.contains(title) && sId != -1 -> {
legacySheetIdToRename = sId legacySheetIdToRename = sId
} }
@@ -223,7 +222,7 @@ object GoogleSheetsSyncService {
val batchRequests = JSONArray() val batchRequests = JSONArray()
// 1. If "Journal des repas" does not exist: rename legacy sheet if present, else create it // 1. Ensure "Journal des repas"
if (!hasMealsTab) { if (!hasMealsTab) {
if (legacySheetIdToRename != null) { if (legacySheetIdToRename != null) {
batchRequests.put(JSONObject().apply { batchRequests.put(JSONObject().apply {
@@ -235,7 +234,6 @@ object GoogleSheetsSyncService {
put("fields", "title") put("fields", "title")
}) })
}) })
hasMealsTab = true
} else { } else {
batchRequests.put(JSONObject().apply { batchRequests.put(JSONObject().apply {
put("addSheet", JSONObject().apply { put("addSheet", JSONObject().apply {
@@ -248,11 +246,10 @@ object GoogleSheetsSyncService {
}) })
}) })
}) })
hasMealsTab = true
} }
} }
// 2. If "Mes plats et aliments" does not exist: create it // 2. Ensure "Mes plats et aliments"
if (!hasFoodsTab) { if (!hasFoodsTab) {
batchRequests.put(JSONObject().apply { batchRequests.put(JSONObject().apply {
put("addSheet", JSONObject().apply { put("addSheet", JSONObject().apply {
@@ -266,6 +263,20 @@ object GoogleSheetsSyncService {
}) })
} }
// 3. Ensure "Mes recettes"
if (!hasRecipesTab) {
batchRequests.put(JSONObject().apply {
put("addSheet", JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_RECIPES)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
})
})
})
}
if (batchRequests.length() > 0) { if (batchRequests.length() > 0) {
val batchPayload = JSONObject().apply { val batchPayload = JSONObject().apply {
put("requests", batchRequests) put("requests", batchRequests)
@@ -298,19 +309,30 @@ object GoogleSheetsSyncService {
spreadsheetId: String, spreadsheetId: String,
meals: List<MealEntry>, meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity>, foods: List<LocalCustomFoodEntity>,
recipes: List<RecipeEntry> = emptyList(),
photoLinkProvider: (String) -> String? = { null } photoLinkProvider: (String) -> String? = { null }
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) { ): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
try { try {
// Ensure both tabs exist and legacy tabs are migrated before writing // Ensure all 3 tabs exist and legacy tabs are migrated before writing
ensureTabsExist(accessToken, spreadsheetId) ensureTabsExist(accessToken, spreadsheetId)
// 1. Sync Meals on SHEET_TAB_MEALS // 1. Sync Meals on SHEET_TAB_MEALS
val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(meals = meals, photoLinkProvider = photoLinkProvider) val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(
meals = meals,
photoLinkProvider = photoLinkProvider
)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows) writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows)
// 2. Sync Custom Foods on SHEET_TAB_FOODS // 2. Sync Custom Foods on SHEET_TAB_FOODS
val foodRows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods) val foodRows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_FOODS, "A:C", "A1", foodRows) writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_FOODS, "A:D", "A1", foodRows)
// 3. Sync Recipes on SHEET_TAB_RECIPES
val recipeRows = GoogleSheetsDataFormatter.formatRecipesToRows(
recipes = recipes,
photoLinkProvider = photoLinkProvider
)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_RECIPES, "A:H", "A1", recipeRows)
val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit" val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit"
Result.success( Result.success(
@@ -318,7 +340,8 @@ object GoogleSheetsSyncService {
spreadsheetId = spreadsheetId, spreadsheetId = spreadsheetId,
spreadsheetUrl = spreadsheetUrl, spreadsheetUrl = spreadsheetUrl,
mealsCount = meals.size, mealsCount = meals.size,
foodsCount = foods.size foodsCount = foods.size,
recipesCount = recipes.size
) )
) )
} catch (e: Exception) { } catch (e: Exception) {
@@ -333,7 +356,7 @@ object GoogleSheetsSyncService {
spreadsheetId: String, spreadsheetId: String,
meals: List<MealEntry> meals: List<MealEntry>
): Result<GoogleSheetsSyncResult> { ): Result<GoogleSheetsSyncResult> {
return syncMealsAndFoods(accessToken, spreadsheetId, meals, emptyList()) return syncMealsAndFoods(accessToken, spreadsheetId, meals, emptyList(), emptyList())
} }
private suspend fun writeRowsToSheet( private suspend fun writeRowsToSheet(
@@ -344,7 +367,6 @@ object GoogleSheetsSyncService {
startCell: String, startCell: String,
rows: List<List<Any>> rows: List<List<Any>>
) = withContext(Dispatchers.IO) { ) = withContext(Dispatchers.IO) {
// Clear previous range with RFC 3986 encoding (%20 instead of +)
val clearRange = encodePathRange("'$sheetTitle'!$clearRangeColumns") val clearRange = encodePathRange("'$sheetTitle'!$clearRangeColumns")
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear" val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
val clearRequest = Request.Builder() val clearRequest = Request.Builder()
@@ -362,7 +384,6 @@ object GoogleSheetsSyncService {
Log.w(TAG, "Clear range '$sheetTitle' warning: ${e.message}") Log.w(TAG, "Clear range '$sheetTitle' warning: ${e.message}")
} }
// Put values in RAW mode (neutralizes formula injection)
val jsonValuesArray = JSONArray() val jsonValuesArray = JSONArray()
for (row in rows) { for (row in rows) {
val rowArray = JSONArray() val rowArray = JSONArray()
@@ -396,74 +417,63 @@ object GoogleSheetsSyncService {
} }
} }
private fun readSheetRange(
accessToken: String,
spreadsheetId: String,
range: String
): List<List<Any>> {
val encodedRange = encodePathRange(range)
val url = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$encodedRange"
val req = Request.Builder()
.url(url)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
val rows = mutableListOf<List<Any>>()
okHttpClient.newCall(req).execute().use { resp ->
if (resp.code == 401) throw AuthExpiredException("Token expiré")
if (resp.isSuccessful) {
val body = resp.body?.string().orEmpty()
val values = JSONObject(body).optJSONArray("values")
if (values != null) {
for (i in 0 until values.length()) {
val r = values.getJSONArray(i)
val rowList = mutableListOf<Any>()
for (j in 0 until r.length()) {
rowList.add(r.get(j))
}
rows.add(rowList)
}
}
}
}
return rows
}
suspend fun readSpreadsheetData( suspend fun readSpreadsheetData(
accessToken: String, accessToken: String,
spreadsheetId: String spreadsheetId: String
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) { ): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
try { try {
// Ensure tabs exist and any legacy tab is renamed before attempting to read // Ensure all 3 tabs exist and any legacy tab is renamed before attempting to read
ensureTabsExist(accessToken, spreadsheetId) ensureTabsExist(accessToken, spreadsheetId)
// 1. Read Meals with RFC 3986 encoding (%20) val mealRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_MEALS'!A1:Z")
val mealsRange = encodePathRange("'$SHEET_TAB_MEALS'!A1:Z") val foodRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_FOODS'!A1:D")
val mealsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$mealsRange" val recipeRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_RECIPES'!A1:H")
val mealsReq = Request.Builder()
.url(mealsUrl)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
val mealRows = mutableListOf<List<Any>>()
okHttpClient.newCall(mealsReq).execute().use { resp ->
if (resp.code == 401) throw AuthExpiredException("Token expiré")
if (resp.isSuccessful) {
val body = resp.body?.string().orEmpty()
val values = JSONObject(body).optJSONArray("values")
if (values != null) {
for (i in 0 until values.length()) {
val r = values.getJSONArray(i)
val rowList = mutableListOf<Any>()
for (j in 0 until r.length()) {
rowList.add(r.get(j))
}
mealRows.add(rowList)
}
}
}
}
// 2. Read Custom Foods with RFC 3986 encoding (%20)
val foodsRange = encodePathRange("'$SHEET_TAB_FOODS'!A1:C")
val foodsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$foodsRange"
val foodsReq = Request.Builder()
.url(foodsUrl)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
val foodRows = mutableListOf<List<Any>>()
okHttpClient.newCall(foodsReq).execute().use { resp ->
if (resp.code == 401) throw AuthExpiredException("Token expiré")
if (resp.isSuccessful) {
val body = resp.body?.string().orEmpty()
val values = JSONObject(body).optJSONArray("values")
if (values != null) {
for (i in 0 until values.length()) {
val r = values.getJSONArray(i)
val rowList = mutableListOf<Any>()
for (j in 0 until r.length()) {
rowList.add(r.get(j))
}
foodRows.add(rowList)
}
}
}
}
val parsedMeals = GoogleSheetsDataFormatter.parseRowsToMeals(mealRows) val parsedMeals = GoogleSheetsDataFormatter.parseRowsToMeals(mealRows)
val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows) val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows)
val parsedRecipes = GoogleSheetsDataFormatter.parseRowsToRecipes(recipeRows)
Result.success(SpreadsheetRestoreData(meals = parsedMeals, foods = parsedFoods)) Result.success(
SpreadsheetRestoreData(
meals = parsedMeals,
foods = parsedFoods,
recipes = parsedRecipes
)
)
} catch (e: Exception) { } catch (e: Exception) {
Log.e(TAG, "Error in readSpreadsheetData", e) Log.e(TAG, "Error in readSpreadsheetData", e)
Result.failure(e) Result.failure(e)
@@ -1,10 +1,15 @@
package com.example package com.example
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.FoodUnit import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.example.util.GoogleSheetsDataFormatter import com.example.util.GoogleSheetsDataFormatter
import com.example.util.GoogleSheetsSyncService
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
@@ -60,18 +65,13 @@ class GoogleSheetsDataFormatterTest {
photoUris = emptyList() photoUris = emptyList()
) )
// Pass in reverse order to test sorting
val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2), testZoneId) val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2), testZoneId)
// 1 header + 2 data rows
assertEquals(3, rows.size) assertEquals(3, rows.size)
// Row 0: Headers
assertEquals(10, rows[0].size) assertEquals(10, rows[0].size)
assertEquals("Date", rows[0][0]) assertEquals("Date", rows[0][0])
assertEquals("Photos jointes", rows[0][9]) assertEquals("Photos jointes", rows[0][9])
// Row 1: Most recent meal (DINNER at 20:00)
val dinnerRow = rows[1] val dinnerRow = rows[1]
assertEquals("15/03/2026", dinnerRow[0]) assertEquals("15/03/2026", dinnerRow[0])
assertEquals("20:00", dinnerRow[1]) assertEquals("20:00", dinnerRow[1])
@@ -82,7 +82,6 @@ class GoogleSheetsDataFormatterTest {
assertEquals("Dîner léger en famille", dinnerRow[8]) assertEquals("Dîner léger en famille", dinnerRow[8])
assertEquals(0, dinnerRow[9]) assertEquals(0, dinnerRow[9])
// Row 2: Earlier meal (LUNCH at 12:30)
val lunchRow = rows[2] val lunchRow = rows[2]
assertEquals("15/03/2026", lunchRow[0]) assertEquals("15/03/2026", lunchRow[0])
assertEquals("12:30", lunchRow[1]) assertEquals("12:30", lunchRow[1])
@@ -97,20 +96,22 @@ class GoogleSheetsDataFormatterTest {
} }
@Test @Test
fun `formatCustomFoodsToRows formats headers and rows correctly`() { fun `formatCustomFoodsToRows formats 4 columns including category`() {
val foods = listOf( val foods = listOf(
com.example.data.local.LocalCustomFoodEntity( LocalCustomFoodEntity(
slugId = "houmous", slugId = "comte_affine",
name = "Houmous maison", name = "Comté affiné",
defaultUnit = "g", defaultUnit = "g",
category = FoodCategory.CHEESE.name,
updatedAt = 1773574800000L updatedAt = 1773574800000L
) )
) )
val rows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods, testZoneId) val rows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods, testZoneId)
assertEquals(2, rows.size) assertEquals(2, rows.size)
assertEquals(GoogleSheetsDataFormatter.HEADERS_CUSTOM_FOODS, rows[0]) assertEquals(GoogleSheetsDataFormatter.HEADERS_CUSTOM_FOODS, rows[0])
assertEquals("Houmous maison", rows[1][0]) assertEquals("Comté affiné", rows[1][0])
assertEquals("g", rows[1][1]) assertEquals("g", rows[1][1])
assertEquals(FoodCategory.CHEESE.displayName, rows[1][3])
} }
@Test @Test
@@ -130,12 +131,69 @@ class GoogleSheetsDataFormatterTest {
val foodRows = listOf( val foodRows = listOf(
GoogleSheetsDataFormatter.HEADERS_CUSTOM_FOODS, GoogleSheetsDataFormatter.HEADERS_CUSTOM_FOODS,
listOf("Curry de lentilles", "portion", "15/03/2026 12:30") listOf("Curry de lentilles", "portion", "15/03/2026 12:30", FoodCategory.STARCH.displayName)
) )
val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows) val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows)
assertEquals(1, parsedFoods.size) assertEquals(1, parsedFoods.size)
assertEquals("Curry de lentilles", parsedFoods[0].name) assertEquals("Curry de lentilles", parsedFoods[0].name)
assertEquals("portion", parsedFoods[0].defaultUnit) assertEquals("portion", parsedFoods[0].defaultUnit)
assertEquals(FoodCategory.STARCH, parsedFoods[0].resolvedCategory())
}
@Test
fun `formatRecipesToRows and parseRowsToRecipes roundtrips correctly`() {
val recipe = RecipeEntry(
id = "rec-1",
title = "Poêlée poulet courgettes",
categoryTag = RecipeCategoryTag.MAIN.name,
prepTimeMinutes = 25,
servings = 2,
ingredientsSerialized = listOf(
MealFoodItem("Filet de poulet", 240.0, FoodUnit.G, FoodCategory.PROTEIN).serialize(),
MealFoodItem("Courgettes", 300.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize(),
MealFoodItem("Huile d'olive", 10.0, FoodUnit.ML, FoodCategory.FAT_SEASONING).serialize()
),
steps = listOf("Couper les courgettes", "Faire revenir le poulet", "Mélanger et servir"),
notes = "Très bon avec du basilic",
photoUri = "file:///local_recipe.jpg"
)
val rows = GoogleSheetsDataFormatter.formatRecipesToRows(
recipes = listOf(recipe),
photoLinkProvider = { if (it == "file:///local_recipe.jpg") "https://drive.google.com/file/rec1" else null }
)
assertEquals(2, rows.size)
assertEquals(GoogleSheetsDataFormatter.HEADERS_RECIPES, rows[0])
assertEquals("https://drive.google.com/file/rec1", rows[1][7])
val restored = GoogleSheetsDataFormatter.parseRowsToRecipes(rows)
assertEquals(1, restored.size)
val r = restored[0]
assertEquals("Poêlée poulet courgettes", r.title)
assertEquals(RecipeCategoryTag.MAIN, r.categoryEnum())
assertEquals(25, r.prepTimeMinutes)
assertEquals(2, r.servings)
assertEquals(3, r.parsedIngredients().size)
assertEquals(FoodCategory.PROTEIN, r.parsedIngredients()[0].category)
assertEquals(FoodCategory.VEGETABLE, r.parsedIngredients()[1].category)
assertEquals(FoodCategory.FAT_SEASONING, r.parsedIngredients()[2].category)
assertEquals(listOf("Couper les courgettes", "Faire revenir le poulet", "Mélanger et servir"), r.steps)
assertEquals("Très bon avec du basilic", r.notes)
assertEquals("https://drive.google.com/file/rec1", r.photoUri)
}
@Test
fun `foodCategory inference maps PDF categories accurately`() {
assertEquals(FoodCategory.PROTEIN, FoodCategory.inferFromName("Filet de poulet"))
assertEquals(FoodCategory.VEGETABLE, FoodCategory.inferFromName("Courgettes grillées"))
assertEquals(FoodCategory.STARCH, FoodCategory.inferFromName("Riz basmati"))
assertEquals(FoodCategory.BREAD, FoodCategory.inferFromName("Pain complet"))
assertEquals(FoodCategory.FRUIT, FoodCategory.inferFromName("Pomme bio"))
assertEquals(FoodCategory.CHEESE, FoodCategory.inferFromName("Comté affiné"))
assertEquals(FoodCategory.DAIRY, FoodCategory.inferFromName("Yaourt nature"))
assertEquals(FoodCategory.NUTS, FoodCategory.inferFromName("Amandes grillées"))
assertEquals(FoodCategory.FAT_SEASONING, FoodCategory.inferFromName("Huile d'olive"))
assertEquals(FoodCategory.PLEASURE, FoodCategory.inferFromName("Chocolat noir"))
} }
@Test @Test
@@ -152,19 +210,16 @@ class GoogleSheetsDataFormatterTest {
assertEquals("https://drive.google.com/file/1", rows[1][9]) assertEquals("https://drive.google.com/file/1", rows[1][9])
} }
@Test
@Test @Test
fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() { fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() {
val range = "'Journal des repas'!A1" val range = "'Journal des repas'!A1"
val encoded = com.example.util.GoogleSheetsSyncService.encodePathRange(range) val encoded = GoogleSheetsSyncService.encodePathRange(range)
assertEquals("%27Journal%20des%20repas%27%21A1", encoded) assertEquals("%27Journal%20des%20repas%27%21A1", encoded)
val foodRange = "'Mes plats et aliments'!A1:C" val foodRange = "'Mes plats et aliments'!A1:D"
val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange) val foodEncoded = GoogleSheetsSyncService.encodePathRange(foodRange)
assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded) assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AD", foodEncoded)
assertTrue(!encoded.contains("+")) assertTrue(!encoded.contains("+"))
assertTrue(!foodEncoded.contains("+")) assertTrue(!foodEncoded.contains("+"))
} }
}
} }
@@ -7,10 +7,14 @@ import com.example.data.local.AppDatabase
import com.example.data.local.LocalCustomFoodEntity import com.example.data.local.LocalCustomFoodEntity
import com.example.data.local.LocalMealDao import com.example.data.local.LocalMealDao
import com.example.data.local.LocalMealEntity import com.example.data.local.LocalMealEntity
import com.example.data.local.LocalRecipeEntity
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem import com.example.data.model.MealFoodItem
import com.example.data.model.MealType import com.example.data.model.MealType
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import org.junit.After import org.junit.After
@@ -54,7 +58,8 @@ class LocalDatabaseTest {
satietyAfter = 7, satietyAfter = 7,
note = "Repas calme", note = "Repas calme",
foodItemsSerialized = listOf( foodItemsSerialized = listOf(
MealFoodItem("Riz", 150.0, FoodUnit.G).serialize() MealFoodItem("Riz", 150.0, FoodUnit.G, FoodCategory.STARCH).serialize(),
MealFoodItem("Comté", 30.0, FoodUnit.G, FoodCategory.CHEESE).serialize()
), ),
photoUris = listOf("file:///test_photo.jpg") photoUris = listOf("file:///test_photo.jpg")
) )
@@ -69,8 +74,10 @@ class LocalDatabaseTest {
assertEquals(6, readMeal.hungerBefore) assertEquals(6, readMeal.hungerBefore)
assertEquals(7, readMeal.satietyAfter) assertEquals(7, readMeal.satietyAfter)
assertEquals("Repas calme", readMeal.note) assertEquals("Repas calme", readMeal.note)
assertEquals(1, readMeal.parsedFoodItems().size) assertEquals(2, readMeal.parsedFoodItems().size)
assertEquals("Riz", readMeal.parsedFoodItems()[0].name) assertEquals("Riz", readMeal.parsedFoodItems()[0].name)
assertEquals(FoodCategory.STARCH, readMeal.parsedFoodItems()[0].category)
assertEquals(FoodCategory.CHEESE, readMeal.parsedFoodItems()[1].category)
assertEquals(1, readMeal.displayPhotoUris.size) assertEquals(1, readMeal.displayPhotoUris.size)
} }
@@ -91,15 +98,53 @@ class LocalDatabaseTest {
} }
@Test @Test
fun testInsertAndObserveCustomFoods() = runTest { fun testInsertAndObserveCustomFoodsWithCategory() = runTest {
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G) val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G, FoodCategory.STARCH)
val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML) val food2 = LocalCustomFoodEntity.create("Tomme de brebis", FoodUnit.G, FoodCategory.CHEESE)
dao.insertCustomFoods(listOf(food1, food2)) dao.insertCustomFoods(listOf(food1, food2))
val allFoods = dao.observeAllCustomFoods().first() val allFoods = dao.observeAllCustomFoods().first()
assertEquals(2, allFoods.size) assertEquals(2, allFoods.size)
val names = allFoods.map { it.name } assertEquals(listOf("Granola maison", "Tomme de brebis"), allFoods.map { it.name })
assertEquals(listOf("Granola maison", "Smoothie mangue"), names) assertEquals(FoodCategory.STARCH, allFoods[0].resolvedCategory())
assertEquals(FoodCategory.CHEESE, allFoods[1].resolvedCategory())
}
@Test
fun testRecipeCrudAndServingsScaling() = runTest {
val recipe = RecipeEntry(
id = "rec_1",
title = "Dahl de lentilles corail",
categoryTag = RecipeCategoryTag.MAIN.name,
prepTimeMinutes = 30,
servings = 4,
ingredientsSerialized = listOf(
MealFoodItem("Lentilles corail", 200.0, FoodUnit.G, FoodCategory.STARCH).serialize(),
MealFoodItem("Carottes", 240.0, FoodUnit.G, FoodCategory.VEGETABLE).serialize()
),
steps = listOf("Rincer les lentilles", "Mijoter 20 minutes"),
notes = "Délicieux avec du cumin",
photoUri = "file:///recipe_cover.jpg"
)
dao.insertRecipe(LocalRecipeEntity.fromRecipeEntry(recipe))
val allRecipes = dao.observeAllRecipes().first()
assertEquals(1, allRecipes.size)
val loaded = allRecipes[0].toRecipeEntry()
assertEquals("Dahl de lentilles corail", loaded.title)
assertEquals(4, loaded.servings)
assertEquals(2, loaded.steps.size)
// Scale from 4 servings down to 1 serving
val scaledOne = loaded.scaledIngredients(1.0)
assertEquals(50.0, scaledOne[0].weight!!, 0.01)
assertEquals(60.0, scaledOne[1].weight!!, 0.01)
assertEquals(FoodCategory.STARCH, scaledOne[0].resolvedCategory())
assertEquals(FoodCategory.VEGETABLE, scaledOne[1].resolvedCategory())
dao.deleteRecipeById("rec_1")
assertNull(dao.getRecipeById("rec_1"))
} }
} }
@@ -1,112 +0,0 @@
package com.example.base
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidUserException
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.FirebaseFirestoreSettings
import com.google.firebase.firestore.MemoryCacheSettings
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.tasks.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Before
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE, sdk = [36])
@LooperMode(LooperMode.Mode.INSTRUMENTATION_TEST)
abstract class FirestoreEmulatorTestBase {
protected lateinit var firestore: FirebaseFirestore
protected lateinit var auth: FirebaseAuth
protected lateinit var databaseId: String
@Before
open fun setUpFirebase() {
val context = ApplicationProvider.getApplicationContext<Context>()
val resId = context.resources.getIdentifier("firestore_database_id", "string", context.packageName)
databaseId = if (resId != 0) context.getString(resId) else "demo-database"
val app = if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(
context,
FirebaseOptions.Builder()
.setApplicationId("com.example.app")
.setProjectId(PROJECT_ID)
.setApiKey("fake-api-key-for-emulator")
.build()
)
} else {
FirebaseApp.getInstance()
}
firestore = FirebaseFirestore.getInstance(app, databaseId)
try {
firestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT)
firestore.firestoreSettings = FirebaseFirestoreSettings.Builder()
.setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
.build()
} catch (_: IllegalStateException) {}
auth = FirebaseAuth.getInstance(app)
try {
auth.useEmulator(EMULATOR_HOST, AUTH_PORT)
} catch (_: IllegalStateException) {}
clearEmulatorData()
}
@After
open fun tearDownFirebase() {
auth.signOut()
clearEmulatorData()
}
private fun clearEmulatorData() {
try {
val url = java.net.URL("http://$EMULATOR_HOST:$FIRESTORE_PORT/emulator/v1/projects/$PROJECT_ID/databases/$databaseId/documents")
val conn = url.openConnection() as java.net.HttpURLConnection
conn.requestMethod = "DELETE"
conn.responseCode
conn.disconnect()
} catch (_: Exception) {}
}
protected suspend fun signInTestUser(email: String): String = withContext(Dispatchers.IO) {
withTimeout(AUTH_TIMEOUT_MS) {
val result = try {
auth.signInWithEmailAndPassword(email, DEFAULT_PASSWORD).await()
} catch (unused: FirebaseAuthInvalidUserException) {
auth.createUserWithEmailAndPassword(email, DEFAULT_PASSWORD).await()
}
checkNotNull(result.user?.uid) { "User auth failed" }
}
}
protected fun Throwable.unwrapFirestoreException(): FirebaseFirestoreException? {
var current: Throwable? = this
while (current != null) {
if (current is FirebaseFirestoreException) return current
current = current.cause
}
return null
}
private companion object {
const val EMULATOR_HOST = "127.0.0.1"
const val FIRESTORE_PORT = 8085
const val AUTH_PORT = 9099
const val PROJECT_ID = "demo-no-project"
const val DEFAULT_PASSWORD = "password123"
const val AUTH_TIMEOUT_MS = 5000L
}
}
@@ -1,157 +0,0 @@
package com.example.data.repository
import com.example.base.FirestoreEmulatorTestBase
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.google.firebase.firestore.FirebaseFirestoreException
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
class MealRepositoryRuleTest : FirestoreEmulatorTestBase() {
@Test
fun addMeal_validPayloadWithFoodsAndScale10_createsDocumentAndReturnsId() = runBlocking {
val uid = signInTestUser(ALICE_EMAIL)
val repository = MealRepository(firestore)
val foodItems = listOf(
MealFoodItem("Riz basmati", 150.0, FoodUnit.G).serialize(),
MealFoodItem("Avocat", 1.0, FoodUnit.PORTION).serialize()
)
val entry = MealEntry(
userId = uid,
mealType = MealType.LUNCH.name,
mealTimestamp = System.currentTimeMillis(),
hungerBefore = 7,
satietyAfter = 8,
note = "Note globale : déjeuner calme et équilibré",
foodItemsSerialized = foodItems,
photosBase64 = emptyList()
)
val createResult = withTimeout(DEFAULT_TIMEOUT_MS) { repository.addMeal(entry) }
assertTrue(createResult.isSuccess)
val mealId = createResult.getOrThrow()
assertTrue(mealId.isNotEmpty())
val fetched = withTimeout(DEFAULT_TIMEOUT_MS) { repository.getMealById(mealId).getOrThrow() }
assertEquals(2, fetched.parsedFoodItems().size)
assertEquals("Riz basmati", fetched.parsedFoodItems()[0].name)
}
@Test
fun saveCustomFood_andObserve_enrichesCloudCatalog() = runBlocking {
signInTestUser(ALICE_EMAIL)
val repository = MealRepository(firestore)
val saveResult = withTimeout(DEFAULT_TIMEOUT_MS) {
repository.saveCustomFood("Houmous maison", FoodUnit.G)
}
assertTrue(saveResult.isSuccess)
val customFoods = withTimeout(FLOW_TIMEOUT_MS) {
repository.observeCustomFoods().first { list -> list.any { it.name == "Houmous maison" } }
}
assertTrue(customFoods.any { it.name == "Houmous maison" && it.defaultUnit == "g" })
}
@Test
fun updateMeal_retroactiveDateAndScale10_updatesSuccessfully() = runBlocking {
val uid = signInTestUser(ALICE_EMAIL)
val repository = MealRepository(firestore)
val initialTimestamp = System.currentTimeMillis()
val entry = MealEntry(
userId = uid,
mealType = MealType.DINNER.name,
mealTimestamp = initialTimestamp,
hungerBefore = 6,
satietyAfter = 7,
note = "Soupe et tartine",
foodItemsSerialized = listOf(MealFoodItem("Soupe de légumes", 300.0, FoodUnit.ML).serialize())
)
val mealId = withTimeout(DEFAULT_TIMEOUT_MS) { repository.addMeal(entry).getOrThrow() }
val correctedTimestamp = initialTimestamp - 86_400_000L
val updatedEntry = entry.copy(
id = mealId,
mealTimestamp = correctedTimestamp,
hungerBefore = 8,
satietyAfter = 9,
note = "Soupe et tartine (date corrigée)",
foodItemsSerialized = listOf(
MealFoodItem("Soupe de légumes", 300.0, FoodUnit.ML).serialize(),
MealFoodItem("Pain au levain", 60.0, FoodUnit.G).serialize()
)
)
val updateResult = withTimeout(DEFAULT_TIMEOUT_MS) { repository.updateMeal(updatedEntry) }
assertTrue(updateResult.isSuccess)
val fetchResult = withTimeout(DEFAULT_TIMEOUT_MS) { repository.getMealById(mealId) }
assertTrue(fetchResult.isSuccess)
val fetched = fetchResult.getOrThrow()
assertEquals(correctedTimestamp, fetched.mealTimestamp)
assertEquals(2, fetched.parsedFoodItems().size)
}
@Test
fun getMealById_crossUserAccess_failsWithPermissionDenied() = runBlocking {
val aliceUid = signInTestUser(ALICE_EMAIL)
val aliceRepo = MealRepository(firestore)
val entry = MealEntry(
userId = aliceUid,
mealType = MealType.LUNCH.name,
mealTimestamp = System.currentTimeMillis(),
hungerBefore = 6,
satietyAfter = 8
)
val mealId = withTimeout(DEFAULT_TIMEOUT_MS) { aliceRepo.addMeal(entry).getOrThrow() }
signInTestUser(BOB_EMAIL)
val bobRepo = MealRepository(firestore)
try {
withTimeout(DEFAULT_TIMEOUT_MS) { bobRepo.getMealById(mealId = mealId, ownerId = aliceUid).getOrThrow() }
fail("Expected cross-user access to fail")
} catch (e: Exception) {
val firestoreException = e.unwrapFirestoreException()
assertNotNull("Expected nested FirebaseFirestoreException", firestoreException)
assertEquals(FirebaseFirestoreException.Code.PERMISSION_DENIED, firestoreException?.code)
}
}
@Test
fun observeMeals_unauthenticatedUser_failsWithPermissionDenied() = runBlocking {
auth.signOut()
val repository = MealRepository(firestore)
try {
withTimeout(FLOW_TIMEOUT_MS) { repository.observeMeals().first() }
fail("Expected unauthenticated query to fail")
} catch (e: Exception) {
assertTrue(
e is IllegalStateException || e.unwrapFirestoreException()?.code == FirebaseFirestoreException.Code.PERMISSION_DENIED
)
}
}
private companion object {
const val ALICE_EMAIL = "alice@test.com"
const val BOB_EMAIL = "bob@test.com"
const val DEFAULT_TIMEOUT_MS = 5000L
const val FLOW_TIMEOUT_MS = 4000L
}
}
Vendored Executable → Regular
View File
File mode changed.
@@ -0,0 +1,522 @@
%PDF-1.7
%€€€€
1 0 obj
<</Type/Pages/Count 3/Kids[71 0 R 72 0 R 73 0 R]>>
endobj
2 0 obj
<</Type/StructTreeRoot/RoleMap<</Datetime/Span/Terms/Part/Title/P/Strong/Span/Em/Span>>/K[58 0 R]/ParentTree<</Nums[0 3 0 R 1 4 0 R]>>/ParentTreeNextKey 2>>
endobj
3 0 obj
[5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 11 0 R 12 0 R 13 0 R 14 0 R 14 0 R 14 0 R 15 0 R 16 0 R 16 0 R 17 0 R 18 0 R 19 0 R 20 0 R 21 0 R 22 0 R 23 0 R 24 0 R 25 0 R 26 0 R 27 0 R 28 0 R 29 0 R 29 0 R 30 0 R 31 0 R 32 0 R 33 0 R 33 0 R 33 0 R 33 0 R 34 0 R 35 0 R 36 0 R 36 0 R 36 0 R]
endobj
4 0 obj
[37 0 R 38 0 R 39 0 R 40 0 R 41 0 R 42 0 R 43 0 R 44 0 R 45 0 R 46 0 R 47 0 R 48 0 R 49 0 R 50 0 R 51 0 R 52 0 R 53 0 R 54 0 R 55 0 R 56 0 R 57 0 R 57 0 R 57 0 R]
endobj
5 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[0]/Pg 71 0 R>>
endobj
6 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[1]/Pg 71 0 R>>
endobj
7 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[2]/Pg 71 0 R>>
endobj
8 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[3]/Pg 71 0 R>>
endobj
9 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[4]/Pg 71 0 R>>
endobj
10 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[5]/Pg 71 0 R>>
endobj
11 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[6 7]/Pg 71 0 R>>
endobj
12 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[8]/Pg 71 0 R>>
endobj
13 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[9]/Pg 71 0 R>>
endobj
14 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[10 11 12]/Pg 71 0 R>>
endobj
15 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[13]/Pg 71 0 R>>
endobj
16 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[14 15]/Pg 71 0 R>>
endobj
17 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[16]/Pg 71 0 R>>
endobj
18 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[17]/Pg 71 0 R>>
endobj
19 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[18]/Pg 71 0 R>>
endobj
20 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[19]/Pg 71 0 R>>
endobj
21 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[20]/Pg 71 0 R>>
endobj
22 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[21]/Pg 71 0 R>>
endobj
23 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[22]/Pg 71 0 R>>
endobj
24 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[23]/Pg 71 0 R>>
endobj
25 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[24]/Pg 71 0 R>>
endobj
26 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[25]/Pg 71 0 R>>
endobj
27 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[26]/Pg 71 0 R>>
endobj
28 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[27]/Pg 71 0 R>>
endobj
29 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[28 29]/Pg 71 0 R>>
endobj
30 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[30]/Pg 71 0 R>>
endobj
31 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[31]/Pg 71 0 R>>
endobj
32 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[32]/Pg 71 0 R>>
endobj
33 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[33 34 35 36]/Pg 71 0 R>>
endobj
34 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[37]/Pg 71 0 R>>
endobj
35 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[38]/Pg 71 0 R>>
endobj
36 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[39 40 41]/Pg 71 0 R>>
endobj
37 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[0]/Pg 72 0 R>>
endobj
38 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[1]/Pg 72 0 R>>
endobj
39 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[2]/Pg 72 0 R>>
endobj
40 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[3]/Pg 72 0 R>>
endobj
41 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[4]/Pg 72 0 R>>
endobj
42 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[5]/Pg 72 0 R>>
endobj
43 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[6]/Pg 72 0 R>>
endobj
44 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[7]/Pg 72 0 R>>
endobj
45 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[8]/Pg 72 0 R>>
endobj
46 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[9]/Pg 72 0 R>>
endobj
47 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[10]/Pg 72 0 R>>
endobj
48 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[11]/Pg 72 0 R>>
endobj
49 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[12]/Pg 72 0 R>>
endobj
50 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[13]/Pg 72 0 R>>
endobj
51 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[14]/Pg 72 0 R>>
endobj
52 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[15]/Pg 72 0 R>>
endobj
53 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[16]/Pg 72 0 R>>
endobj
54 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[17]/Pg 72 0 R>>
endobj
55 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[18]/Pg 72 0 R>>
endobj
56 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[19]/Pg 72 0 R>>
endobj
57 0 obj
<</Type/StructElem/S/P/P 58 0 R/K[20 21 22]/Pg 72 0 R>>
endobj
58 0 obj
<</Type/StructElem/S/Document/P 2 0 R/Lang(fr-FR)/K[5 0 R 6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R 19 0 R 20 0 R 21 0 R 22 0 R 23 0 R 24 0 R 25 0 R 26 0 R 27 0 R 28 0 R 29 0 R 30 0 R 31 0 R 32 0 R 33 0 R 34 0 R 35 0 R 36 0 R 37 0 R 38 0 R 39 0 R 40 0 R 41 0 R 42 0 R 43 0 R 44 0 R 45 0 R 46 0 R 47 0 R 48 0 R 49 0 R 50 0 R 51 0 R 52 0 R 53 0 R 54 0 R 55 0 R 56 0 R 57 0 R]>>
endobj
59 0 obj
<</ProcSet[/PDF/Text/ImageC/ImageB]/Font<</f0 62 0 R/f1 65 0 R/f2 68 0 R>>>>
endobj
60 0 obj
<</ProcSet[/PDF/Text/ImageC/ImageB]/Font<</f0 62 0 R/f1 65 0 R/f2 68 0 R>>>>
endobj
61 0 obj
<</ProcSet[/PDF/Text/ImageC/ImageB]/Font<</f0 62 0 R>>>>
endobj
62 0 obj
<</Type/Font/Subtype/Type0/BaseFont/JBWAJH+Carlito-Italic/Encoding/Identity-H/DescendantFonts[63 0 R]/ToUnicode 75 0 R>>
endobj
63 0 obj
<</Type/Font/Subtype/CIDFontType2/BaseFont/JBWAJH+Carlito-Italic/CIDSystemInfo<</Registry(Adobe)/Ordering(Identity)/Supplement 0>>/FontDescriptor 64 0 R/DW 0/CIDToGIDMap/Identity/W[0 0 506.83594 1 1 522.46094 2 2 477.53906 3 3 389.16016 4 4 226.07422 5 5 416.01562 6 6 513.1836 7 7 514.16016 8 9 229.49219 10 10 445.80078 11 11 514.16016 12 12 334.96094 13 13 514.16016 14 14 477.53906 15 16 514.16016 17 17 342.77344 18 18 557.1289 19 19 306.15234 20 20 303.22266 21 21 305.17578 22 22 303.22266 23 23 514.16016 24 24 791.0156 25 25 252.4414 26 26 251.95312 27 28 514.16016 29 29 477.53906 30 30 514.16016 31 31 477.53906 32 32 249.51172 33 33 498.04688 34 34 506.83594 35 35 814.4531]>>
endobj
64 0 obj
<</Type/FontDescriptor/FontName/JBWAJH+Carlito-Italic/Flags 131140/FontBBox[-12.207031 -171.38672 790.03906 730.46875]/ItalicAngle -7/Ascent 750/Descent -250/CapHeight 641.60156/StemV 95.4/CIDSet 74 0 R/FontFile2 76 0 R>>
endobj
65 0 obj
<</Type/Font/Subtype/Type0/BaseFont/ZRVUVQ+Carlito-Regular/Encoding/Identity-H/DescendantFonts[66 0 R]/ToUnicode 78 0 R>>
endobj
66 0 obj
<</Type/Font/Subtype/CIDFontType2/BaseFont/ZRVUVQ+Carlito-Regular/CIDSystemInfo<</Registry(Adobe)/Ordering(Identity)/Supplement 0>>/FontDescriptor 67 0 R/DW 0/CIDToGIDMap/Identity/W[0 0 506.83594 1 1 542.96875 2 2 488.28125 3 3 516.60156 4 4 459.47266 5 5 226.07422 6 6 578.6133 7 7 420.41016 8 8 251.95312 9 9 854.98047 10 10 645.5078 11 11 487.3047 12 12 641.60156 13 13 318.84766 14 14 662.1094 15 15 267.57812 16 16 567.3828 17 17 229.49219 18 18 479.0039 19 20 525.3906 21 21 497.5586 22 22 249.51172 23 23 525.3906 24 24 527.34375 25 25 391.11328 26 26 849.6094 27 27 525.3906 28 28 305.17578 29 29 451.66016 30 30 348.6328 31 31 506.83594 32 32 525.3906 33 33 229.49219 34 34 557.1289 35 35 239.25781 36 36 497.5586 37 37 506.83594 38 38 498.04688 39 39 506.83594 40 40 306.15234 41 41 506.83594 42 42 470.70312 43 43 459.47266 44 44 422.85156 45 45 334.96094 46 46 303.22266 47 47 395.01953 48 48 479.0039 49 49 525.3906 50 50 690.4297 51 51 303.22266 52 52 798.8281 53 53 525.3906 54 54 252.4414 55 57 506.83594 58 58 433.10547 59 59 479.0039 60 60 497.5586 61 61 249.51172 62 62 498.04688 63 63 487.3047 64 64 519.53125 65 65 529.2969 66 66 229.49219 67 67 527.34375 68 68 386.23047 69 69 519.04297 70 70 615.2344 71 71 533.2031 72 72 506.83594]>>
endobj
67 0 obj
<</Type/FontDescriptor/FontName/ZRVUVQ+Carlito-Regular/Flags 131076/FontBBox[-31.25 -171.875 811.52344 731.4453]/ItalicAngle 0/Ascent 750/Descent -250/CapHeight 641.60156/StemV 95.4/CIDSet 77 0 R/FontFile2 79 0 R>>
endobj
68 0 obj
<</Type/Font/Subtype/Type0/BaseFont/VCLGCC+Carlito-Bold/Encoding/Identity-H/DescendantFonts[69 0 R]/ToUnicode 81 0 R>>
endobj
69 0 obj
<</Type/Font/Subtype/CIDFontType2/BaseFont/VCLGCC+Carlito-Bold/CIDSystemInfo<</Registry(Adobe)/Ordering(Identity)/Supplement 0>>/FontDescriptor 70 0 R/DW 0/CIDToGIDMap/Identity/W[0 0 506.83594 1 1 495.1172 2 2 473.6328 3 3 536.6211 4 4 503.41797 5 5 398.92578 6 6 226.07422 7 7 536.6211 8 8 257.8125 9 9 493.65234 10 11 245.60547 12 12 813.47656 13 13 536.6211 14 14 346.6797 15 15 532.22656 16 16 605.95703 17 17 562.9883 18 18 331.0547 19 19 676.26953 20 20 652.83203 21 21 355.46875 22 22 585.4492 23 23 473.14453 24 24 487.79297 25 26 536.6211 27 27 418.45703 28 28 316.40625 29 29 503.41797]>>
endobj
70 0 obj
<</Type/FontDescriptor/FontName/VCLGCC+Carlito-Bold/Flags 131076/FontBBox[0 -157.22656 759.27734 727.53906]/ItalicAngle 0/Ascent 750/Descent -250/CapHeight 648.4375/StemV 168.6/CIDSet 80 0 R/FontFile2 82 0 R>>
endobj
71 0 obj
<</Type/Page/Resources 59 0 R/MediaBox[0 0 595.3 841.9]/StructParents 0/Parent 1 0 R/Contents 83 0 R>>
endobj
72 0 obj
<</Type/Page/Resources 60 0 R/MediaBox[0 0 595.3 841.9]/StructParents 1/Parent 1 0 R/Contents 84 0 R>>
endobj
73 0 obj
<</Type/Page/Resources 61 0 R/MediaBox[0 0 595.3 841.9]/Parent 1 0 R/Contents 85 0 R>>
endobj
74 0 obj
<</Length 14/Filter/FlateDecode>>
stream
xœûÿÿÿÿÿâì
endstream
endobj
75 0 obj
<</Length 505/Type/CMap/Filter/FlateDecode/WMode 0>>
stream
xœm“Moâ0@ïù³‡HôÀÆq ´!AH$ýP©¶ç4±#Ç9ðïWö ´Zí� ç™É̃qüëí0Ý(sÄiö[À;f´ N‹çº�âxgš±Cí^ª[tXBoM3 ƒb¿ÛëÖEq¼×ÍeTxËù_ÊÏ­þNð= gº(Ž?ZwÁ%LèÂL°W¨]ë® ¢8þƒvh�^BÅq©Ua:?Ü%Ü’7kš:8µZYîGß7J%¨¶qLáÙtuŠ×Áa·×'e©±çL€äÏíàì&a°Px¢È«Uh[}†ÉmØÁÃØ÷ôC‚§¨UøN¼üKÝ!$,|?eKH¿�>®=ò ’Ïg£n�Òˆ�Q8ôuƒ¶ÖgŒVB±†UUUÕÚwü'žÍ©ìxj¾jÒÓ5¬„˜eë@2P>'Ê-86 $Ñœ29–UD ¢’è‘è‰è‰¨ ÚP‡œhKÄÝ ¢ÑŽê˜Ê@%¿³¢Lš,õ?€yJD~ ID~‹Ù}ž”厈‰Ø‘¦KÉQr9–Ü“ù-ä(É?%ÇבcÎó°#ÏJŽ%w'Ç|ADŽå&�ôŽÒ7
DŽrKDŽu�Á/�gaø÷‹á÷ÿ¾‰Íh-jÖ?¬�ß±Vãýõ¦÷Uá.àí.{z­þp‰'Ç
endstream
endobj
76 0 obj
<</Length 7211/Filter/FlateDecode>>
stream
xœ­z t[×yæï} $ˆM$ò��Xˆ÷‚$H‚« €«HY¤HIµ⪅µP–dG¶,;¶h[v§^Æqâdšc§^.è¥Î¤õ¸uǧéiNReNwZÛs'�º3µ¦ž8¶Dι %Jršö:Âýß½ÿ½ïþß¿ÞK#Ü Âã'ŽKžA?€?€èÔÜôìß¾zþÀ0?}ðÔÔ·öTÜ`<PV>3™™0n<Q๚ff&3¦uº<o@õÌìñ“�ýYQ-€ç �g¾þîcßð>
c³™“s裂nï?€t(3;9õ³ÎøŠ¸¦¹ÃÇŽ/ þ@écãsG'çž<ÙPfà,\ÿ¡pžýç«ø{ÉE€¥×ħ¯¼Ã×-_âï%ï-_Ê=SP©”ž
R¤J}sˆrÞ1ÊuïHºe·s!)Ñ¡¡¤›ÆRN‰FM¥$jìÎLP?{4vK4̈0ãxs()MI ‰†’i§D%6f`T£šÒÎt*•rRPR)™ÂPr2•
R¬JÝå<™ ‰ò‰¡$åå8ä¸ÓíNQ”R¢ÊnÙ-Mdù½q‰�,¸%*$¤i�‚’ óž…ádzșْJÊ)·Dc#I
Š“í>ÿª åT*&”EÀ�Hǃ”W©(Çe‰‚ÏP¼wŠ¢qŠÒ” © JlW¸{üuöJlK§KºKÛ•˜ãEÎê8OZê^�3 EMhp2`¨ä¤±UQ)ñÈ™®Üd�šåùnŠ2]AªW)JKÕ'62F‰êåxŠØÓ–¤D r<¤U¢ÅÚ¥×9_�3Ô˜HK i‰å¸¤Fu`4™QWªšNÊ'ƒ´@NŒä:�îT5µhý…j
[“Ù‚‚E™85()
Š=ñ¬ž}°'N‘]–(ñ %³iÊyâ {­>à–)ʬÐÎÜ8›‚=ZOŠê½Ô�èMS¼¹/À3 `‘»(JPè\DiÊ1©Yà»G“@ 且¦(ója!#Äã él!¯ÐYÅY•
Ò"5 &%H‹Õ,b­YÍbÖ–¨YÂZ‹šåXkU³<kmjV`­]ÍŠ¬u¨YkשY=kKUªS~Ïw—©Y(U‚Ô©fkËÕ,f­KÍÖV¨Y޵•j–g­¤fÖºÕ¬ÈÚ*5«c­¬fõ¬­V¥vÍ><ª”¦…i)!S”fªÉ0츃ԫR�B=� õ©’Ô+}¨r&*K [“¿“ÃéN©id§¾E¶°&\͵@¬
¨R£¶OEJn²8å¦/eý`E R]�r4@¶@�ªªÔ.õ~Á>)$2Ñ ª!G{�†þ5VŠãÑ ­U³ì)$õ2ÿ¦ØÓ¿°Ð+÷Ê)¹×É"‹_ !d³‚4¬R°SÎC9�ÆB…ner!$KRûB4Hë®K¡Ü”cAª[‘hš¹ll8ù2–ˆä|{IY*΢Š.!-È·Ü“¦\âzoH³à‘‹—8‘ž�)Id&†’'2NJi0®Ÿ“‘%‰r^¹'uÊT—è¡ØCu í-iéf/aáM‘)—H3ìyO†ò7¬J9/“È£m“žJº�²;uõ]© ­gH’Dyo¹=¤ Z7ÕÉqI’zä^ö2¦­ˆ �(Œ&CR»ìv²ç;%¶—UÈ=”÷ôçL½{\Îiéff›W‹Ìl·1ÿúÄŠ^Ò,¡]/ߊ›TY
1Èz¶$¥öT(ëEV%H›W»‡®íŽ®å¾)O‹JÃÊMmUi�² IíÌR¢7á¡\"D½J�¶­š×
´Ì²d©]
ÉÑürí*Ë2ñ‡öþG™Û> *írÔé¾FÙîT~� Œù;™ün†<Ûb^ŽU‘׫l9Ï\æ„–UAû‚þ j�ÕBƒ� �«´6¤ †Z·,…¤ž9³‚S—Êl‘&” íVÚ• íQ1¢W]DZOŸºˆ´ž~ÆÓ¡éFÆÃˆÆÃˆAÆÃˆMŒ§E Ò[#63F 1F 3ž6%H·0FŒ0FŒ2Fle<�J�nc<ŒØÎx‘d<ŒH1žV%HÇ#v0Fìd<ŒØ¥ÒúU˜w³Ú¤é�jV‚4­ÙS½B£J�fTڰʽ—=hÜãŸ'4бNª4²Ê:Å4Öi�b¬3ÅX÷©´q•u?{ÐXhc=¨QŒuVU¨n’’ê¡“,Yèç@ ¿à§Á-Ðà¾Wa@ñV?Å"@0ÂÍâ0â¦À;€^Çñ;@¯†AL ÐéÄaÅB±Ë«¿~šzô©¦_�”Šnˆ™ÍV¿W”WÖ)–NÒP_�mV'вÏÛÉ5F¼r• ËU>K¤ç±\ÂÈmv7»Íî�×EãƒjÇDŸÏ¥DjÝœùÖB®Li Vv7ùš|eÆÒ‚=Å.ŸÃî+7›Ë}v‡ÏU¼ôyñò–zÒ}ùûÜ&›ÇU\Õ™jjl xªíGÜu5Þ`³/Üb¶™mWJí~—ÙìòÛ¹¸ñÏžh䮂mË—¸|„ ;/C¯1 ŽG<ÇpÁð<B¬ àÀ؆»x«+]vk�Aà „Bb‘â©g:‚ÀÄkŒ”451y¢ÖÁ1lÖ
Œ‡¶ÎõŠÌüú-¿¸0—=½aúåK ‰ƒ©þŠv]‰Éhwy›6Ö�¿pGxûÉó5õ5†ÁÝÓ#ðãÛŸG•?<º.¸Á߯/0—¹ÊÌ[¿ñ?˜øÆá6 mË—È“ä]ðC 4Ç"!„8 Ò„ApfxÄqšŽ\•"PSÓh xå€`Q�U8Q°Ú¬ö†¼(&’¥“c’xªLXìä#!Lžl}béÿþ�=·yÿ@¤ÔR¤6MïŸOìztº¹*¾çô£[·œØT½ôF÷ñÔúâ¹?<Öç7•øÖãÏ×ïÛºÞ¢3ëîYð×úÍ� k-û¿¶kà«_>2Z«Ä‡7Ôo?‘(p¹«ýG‰G²‚‚å�‰ž¼­ÐkmEˆ¯@˜ÃqD� "Ü Ä�Ï;Àq+ÒE›|ž*©¼L®Ì
Ê©%¯!g…^_³¦#&oc$Ä5j6jwà¿×šÜuÝõµ›š+=�·l¹¥Ó�~tÇøcá€ÙUì®hmØÒRËÉÄ"™û·í~°�DŒF{©}] ZYÕ�e_Ýú@â¶]ÑxcÜYîv–‡×W×wý�›;;Ž%[Aëò%²…¼Ah‰5•0�Çã8`ÂÌÏÏž›BÐ ¤É#`ƒ.Ù/{üÕ‚Mñ¬êHÛ¹¸FL¼¢Hâmعk¼uÛÝcµ÷~nüž†f¡Ä`r6ÔwÝ:)onŒ§:«Å¤Òh¿RÒ¶ÿÑÔ‰wž�èŽÇu†uëz¿ôݽí™n�7ä57†èò%ò ò>� j¬Ê§ù�4˜‹8K‹e³¬¡ 9'ÉÇ›ÕîXÝy.. ŸÜr&Uwúû>5¾ý‘}­Ã½udû#ûÚ¶<ôÖmƒg¾3v~aàÌŽ�à|tÿ{oûù3»£ûžÌœþù·ö è o’÷  ^X,‹PïP2fB`!€¢ÏaŒ q—3æö|Ý•‘T¬Ê L¶yÜ‚Ei°4ÔÛE1çÍ"‘-MÚöEÒ7¿ÝU‰ ‡~x0¶·Ãaì©¿¨m(<±kÈÙL~âªxóÜ=u»’W¾‚›­ßu×ð’0Œ 7ø³@ÀÞ˜ kÈ™B¨ˆ9g!tXK : @Ì|±‚ˆl±ä£æ
ZèK'^8ñ¿mUªÃp[­nÅáP«¬äâ幈êKÕ*«µJ-- ±6ȰI Ê_ëb60%0B¨uhï!ÅLP’ü£žç/|v4�æ÷ÈE(�²˜C§%˜„ ÁdV%R¢0l»ÝÑÔÔŒšš�ÜwÁê çuzltšQµ®Ü|~©ì«ä¢Ýtå!O¯,÷TãcE¶Ë!@�Z¾D.’‹P
¯#@L_ÕL_<‡ó`àQ‚VôµÒ‹q!"£@ˆ�äõU
¥Õn›Ìâ´Öli rUssÎ#š-hçFSûæÚ½;7—·¿tb{‚/ú«9Í‘‹W9z(œ:s úíåÐú—ï8[¿{!‰‚±å�q–/cõ^$p(<Ë…Ü T� Ìà‡ã"æžÂ‚M誖ýf³Ï+Ú•æÛ‰\å]�- âÝÄD® ²lÞgáùö#¦¬{j#o-ÞUƒ EKŸ´ñAá€ÓWaM¢7|ûúÌÜ›‚­ºÑ‹>´ZzlH-*YÊÞ¹$ûêÊ I¸ÖTb2�B3,'D–/qÀ_€RPápÌhG<–8ÌLe—fvÀóZ¼t$DÄ °f‚Θûºq–þ
5.Íal¨+³;ËTW•©Nu�C³ÙRTª+RÜUÞæf™¼¹äawXóýæf/óÎfµãOäu¸Ä;6~0zö‘ªÎÔì=·+‰ç_ZІÇwnvUx67îl«±o—K›Ùè�n~úáÛÆ"-ìüìè™Ö™ £ŸF”@oföD˱Ӱ¼¬åÁÿÎÏCxÚª³<
R`Slc-Bœ5—y�<™YÉ�:Ä
"ñ¦Y²­M ´uµ%b��V¥5à•}…Âv/½F~MÞƒRÀ\¬ˆGHæ¹uó${\yXsž“Ó–!f¢¡ÌVQuÜÈ“ŠYœeÀP8ÌÎý>·®D±ä«¸ì¬àbÙŒ ˜D»f[�¯ûIW%.öí˜<ÔòåGªÖ�:Û;x‡AoÕOîvUøµ Ÿ«K-½Æ»\?‰íÛèÿãìæ§º},ÒÚ¸´•{ºuæ¡­Ÿ4ÆziÛñ“€¡nùy‹¼ ¥Pc1c)â°Äc­ؔc%ý:<Z ºš59¯Ž°§ _µ£BgYµ»¬ÆYðIB‰â–Wìg¥ú°;�æÒšõ`›• íÔ¬g{f¶56Ýï«Ýzò‘ïîŒßÙ~åíÈDj“Ëï;ö<{¦?o9¡Ô¹­ÛþóWN'ë,e—/¶íxêçÉðùWÆÿ1éð�É{P RÌU`X"Žkz¹#‹¡Ø�‹‘9Ô¢WIß –Šü;§E+Ͻ½¾‘þ¿½­§Øñ\Ë.mX^†Ùå�¹{ø{™MÎ2› h6YƒŸ€‡b†„‰fV %cµ@FÏ€ °]?z½)Á#„ÄaE-·mÃï3ƒas#Àq6ŽBÍ�Ay‘×'{dÙl1º–)Òè3Ä ,CŬÁ&@Àu›‹±Y±¸E÷Qôý’¥n¼ð0 øæÒ‡xŽÿ8AxÙ¢G~Y+°Ã.ˆbˆ4FÊp³ÃnM5:}ÎKñPM‹Ç\¹å¡#½…FKï¡Az®÷ÉÿôhÌU©�d³/߇ñÈúTÐPé:ô·¿¾ ¢ËÅøgüí C{¬Å†°Z‰ͪL ñ<^Í¢y’åR�A¶5zìÕ¢UA„UH²Åçõ67743ïqˆ&œËè¢[Dó™:]�·çÜ>‹ ‹�âç;š‹q‘£¢$¸©Í/ C1ÙpùÝ·«½\­ Û­½»FÏ¥j-; :ŒÖ5mïLÞÁP¬\úýÿók0‰„°ÏÛÔÜ\AlVÙ: J™œþRcIñ°¿¥Ú\9üð\·Éhé94è#ÖÞ'Ÿ|tƒKÒ‡Féâ Ã÷--/}¾ôÑS!}¥ëÐûÿøÙòrÎsÑ®ŽYV±fY>¸ ÎÄŒeˆÃnáïô€Àc^À3:Äó¦ÕR™…þ5¾ZóE|š‰k<צ*åκZ%¢F<UÎ@y àsë]
hVîU·c1#‹�+{aqÑ.hq#ÌüL'ò„�BË4Çc£h„¹Ÿãê`*VAzlKµÇ­·_[œÙmÚ·V¡å*à5ä¦ùm•¸pðOfNlú‹Ù{çì_Ø(’ÒzhÇhyÇ ý"rÔûv�ôºÚ˜¿ö¥³çï:×]d\ËhÔØrjó•Ort8uçð’qyv.ÿ3�_3ìdèû—ïú< %±"æ8ùbÝïÁå ‘cè¿ñU@òãùrOs*·li@žÅg²ìO†—/‘´ì€;sê3Jóœ aÇ�«O„ÇñÔJFguÝõ¹D XKc¹\³fœe˜Â«ß�kÖù=f]‰V®I4̉®Ë5ÃÏ?¿Õ›LïkbÉ<9{gÏðÝJ_Z�ޯ߱ÙUé;Ý|G*¼�¿pe€%^ièëß>It¬/+%£­ÓF Œ=D·Ó2ÍÒk«™¦)ÖpM¦Y›br–È€4C—³¬ºêjA,‹X~gñª.åbÕ[wÏD¯Ï"ã©M®€£NË"K¯ËÑÿkK'<×%’™‡·¢AŽË%’|ýñä õ‡¾}Cý!ð„®­?˜§Ý¼þhoSÖ·uµw­©?Èò¯–žáxò´Á쀷b¦VÄ „ùJ$"V€”%cŠñ€�wQ‡ÄÀqE „•7étš¡2ühÝP2Ž„fnœzÓY1å‹'èt°}užÐ•JÅÖu´'· u'Ú:# u5¾
—µÄP¤ ++ +¸•K¢ÆH'©wx½�‘¦|Ÿ;9Ü¢ ˆ¢­9N¢ˆ×çÕ(f“dÚ!×T¯³JÕ’-þ¥Åé¯Î´6íºýÁ¯õ
Jþ=íû6§?<‚ÊEl)¹Ûºtkt{[å®ÑèöÖŠ]¨Æ¨»ÿç:ïœï>:¤â·Âƒñ––vÙYª�txºnß•ccM�{º›¡Äïpmð–:=}ûzî™Y_×j.%Žº¥ÿìÛY»5èÙÞ¾s)\Zc±B}�î~wtઽL­± Þ3÷ÄLqÄ‹+ôY1”Œ©âE"^S¹‚(šº›‹ä"/îOøýWMíf¼©X‰ØØß×ÓѶÆÊ¼OžBïò€„—y`™Ìnѧ)¥{YRCoT�`ª³Ö¨7Ø”Rd‹,ü‰/ß9__©+Ô™Œëº·ì®/*Ùzðù_Ü$!SÄ¿0Â8v„M¬¬A[B€z´_Íì£ånvv’-îf·?Ò€î/^š¯¿¿aéd1º¯�›\?»´=}}�! ¿åà Ùôz@],Dˆ Ì<�¥<ö2kÒŽp…¸ #�l³šM¨×ñeÌË ´|I`·4uÐ £0¨5,V:0Âì²FD"F3FEáõÀ‘0˜]‰pH;¡öö4Ô#èííh«ïnè*²Ûå´YLP‡ê
Š¤Ý°ë7Ít¹•»7¯ïZ£g‡l-~5]½àÑ‚p'awr¼Ôsd(ÐöøÒg½pºqdC½ß]l5©�ÓOt)Ð÷wR÷$ÕÔcuäÄÓžø®8·�k8Gã¶¶­çÓ ŽÆQòà†#ÉöÂgþú˜bö�÷ª:·EÚ§GÖ[ž|ÜRî.·˜úÃŽãó‡O·�ß½ñ©ÿóíÑ™];÷]~,qê¹)Ve÷žûÞ‘ðö„ÿSpôô&s8Ú!Ù•@à ïóa3¨ãïÐ;QZ-Å…Fa~Ùý‚›e{w3»mÈI­%wAðù: >?pfgCdìÖøÒYï Œž+sâ‚ËÏŠØbF?Ü0Ýç«hÚ¨„·vGŠ ÒÖuc§åÃê–#÷ß~¼cé놂ÊÒL³ÙS„žm?°ÿP,Ü_WZéSÜ6Þ4vÿ®0³Ý«q‘G|wº«üˆ›ÁŸóSPµ¯Š0Ê;kB€á+O™3ÞϪ¬Lês »>a)ÊçóúD­*mnÀŸÏ-|ZŠïìÆ¿zš›Ñ §D}Ñi^¿Õqãø6~ôP³³‚üF&èB p GzÂð²;ÚºèbE¹~*mu_áç­¶(0}
ÞáFÃß­
Ð2¨ ºüÕØÌðÚ{¦¿±ÊÁÒR•Ý1åî“xci�=KË‚«·K¿á¾†>àïý=×üÀá©+³{œÅvOm™ÝW^Ì—:ÃÕ6³ËgwÖyì%~¶&;75óEà�[c3¤äšS’gÍ™'wÒÑÝälTóÅ|7œˆØÆ=àÉ�†Jôv±Ò�¿Nbþ—»«Ys�Ã5MýÑô’¯OVK}åV�NÏûÃgb³ûL±ëœ'náìÅÛä�Û.ÿ)I\Y\ßVd.Ò醡;Oᔵ$aAaSÉÒK¬ŒáÆñsšvµ;:XlÒΟzÐɤXA9CijjÀÏ}l*·N>crWòóŸÿÁÆk û²oÖÇßSÔþ 8uš±¾}ê䇬}O~ìîË�_ùH÷�®0,ßhÀ~Ó`øæåÇ?íÔ} ø|ͯ¢TÎ
‚mä"´ iWp­œ¢œ úÐOa ý’ä+Ðǹ …_„1ÎÆÏ¹À͹ ¿}Ü<Ìâc�ƳðM|¢x*Ù˜0
›0;1Ç8 ³¾ÜÜå_±-Ãûä2tp&ˆ wCˆ|~>@jàGxÕ¡À;è§ðmýmˆÝq~éÑ ôúoÀà¿'e¤�L�×8 ÷ ÷|ÿ,ÿ3¡VèN ENßÿ‡xIwT÷C=§ÿ¥¡Ù°Çðˆá��)ãŸÿÒx¥ ² ¿àXÁG…¦^ Â/¡î0 Á.8¿4̯�šàE €8=|G»ce4|'Oc(€Wò4�zx3OsP—ò4eÈ”§(Gþ<-ÂêÊÓ:£ïæi=T wò´¢èÓ<]p ]ˆªp8O› ‰l�†98GaLà  êY¬†�`f`$H@ŽÂAØÇá0H0Gá0ì‡I×fl€y83pŽÂ1�À¯­tæà´B-Ô´6wæa/„`ìÖ{Ã4„I˜‚ÃpŽÃ1¨…ñ5﫹îýýp2ÚÓ8°¿áÕA"ÐÇá Á ´]Ç\3ãzY®Û“šû´½H׬þoYqŸ†A$8G!0 ³Ï�à0Li#l¯‡á dàL€ƒ0 Çà4HЧaL„֎Cèß<ãw�®è'§�[µ!8xÍœ‰v0 óšEääëÉëK‚M¦ãp«&#³—G�I8Ç´u$˜×vÎ0fälkúa$Ø sïµ+®YAé 4ÊÛêÍÞ{U' û4üöj'Á­y«Ìi«6À°F‡V�n°ác0®ùÉœf¥!m!¤Yý4ÔÂfè�Áç,%`ù·ËO°ß«ÞøxþrK2‹Ð…Ô÷t ƒq‰"¹‹yŽ:º%‰úÓSìgk«¿ÚK±ÜµhDB`±@‹VA¤9¿¾{K×b�N dÔ•­F÷ 'iì¾dV ]Y/{z�öˆºR©Têu´|åÌòÚeÚÿFúû1
endstream
endobj
77 0 obj
<</Length 13/Filter/FlateDecode>>
stream
xœûÿþAÈ
õ
endstream
endobj
78 0 obj
<</Length 665/Type/CMap/Filter/FlateDecode/WMode 0>>
stream
xœm”Ënâ@E÷þŠš…¥d‘ÁýÀN¢)[b‘‡B4³wÁX
mË�?꾉F³Ñqu»îé†J¼mn]»ãó3£wÚ©¯ùfù¼í’4]µõtd?¾0;vçêpO]ßÖ�´\¯Ö¾“4]ûúsr|^ó¿%O|hüׂЃ–Ó0¶Ç$M?šñ“ïé
(f¢µc?6㉲ë$Mq?4­¿'•¤iéݲ=†pC2“4{ëÛzÃ#íïzéD»Ð7Qš\S�Bñ³>n»¸ysF>®ý¾%ƒUnêd%Ñì�Í0ö'ºŠÁ®Éñ•×Þqßø]�Ã~+n¦®ûä’²ø”½‹ÿgAþe{dš‰ðå©X’úzôqêX^0ûýܺ3(D¬[ÇC·­¹ßú'Y–e z¨ªªZ„ŽÿÔ �m»}ýgÛÇåjAY6׋H:’�ƒ jÈ‚ hIK-Ç>*@KÐ-ètZ�A%è ,h ’,+¬|• 
TE2¨©pY6ÏAðËÑ]Á/GN¿ÝürtWðËÑ]ÁOÃHÁ¯€»‚_Ž,
~NIE?%g¦àWÈ;á—KNøBð+p+Jü@~¹�ø!™†_a/ÆZq6Ž¥ÔàhpŽ7£áh�UÃQK Žþw˜ 8Zxhq„¿Gœ°†£¾Á±@NÇŽŽršà¨CÜHðÓ02r‡ÈiäÑÁÈâ¶�øÉ>øä4⇜~…¼~%Ü üJ©­b2%ï¿'üæ¨YøYÔ¬Üa~¹5‹{,‘Õ±B G�ï›…ã ¬üe¥üaeűˆƒA&@a^fR=õ=û1Â8€Â´i<_&j×vaWü‹£ø<Õ½V“|�V
endstream
endobj
79 0 obj
<</Length 10658/Filter/FlateDecode>>
stream
xœ­| |Å™ïWUÝ=÷ŒznitôLkf¤¹tŒ4£ËÒxftØ’mÉ’m�ytZ–/á˃±1|¬ÁÃB „– �ÍBÈnÞfÉ&Y¿¼ä‘�“üò’¼ä½àä%°FïW=£Ã›d+~rUw}Õ]õÕwþ¿€@G�@åðíûw½uc“ÛvýðRèAø=€úÀ¶�‡Æ@¿Î Ù Pqïøèàˆ†?Ø Ðð[ˆŒ��j¿h,€Òñ]û§âÈñ @cÚ¼sÏð î½‚4=Ò®Á©IìÒ®XÖÂîÁ]£Û~òÐß,›`š'÷ìÛ?÷¼°üU:>¹wtòñ©†:€åÿî†^�ûé/ë`ï#—2—;û¶jî*{¹2w5ó½– é± „ˆ ½Ù-1ž�Óº©ß):Óý‚ÔÝÝï”b)‡ ÕÑ^]*%HšÖÁ©Œ^jZ©’v*)Å›Ýý˜0==(Hêîþ´C�:¦¦½íEÒŽt*•rHàO¥D ºûGS© „B« 1îÁAbÝý+Æ%NŒ;œÎ”„ÒA‰D§èFfØ¡¸@G.jö9‰KÓ´þ™JÖ=ÝÓŸîv ®Mõ‹)§ Åzû%ð;èês¯
JL@R$üC"Jl@RˆqQ�@ŒJxhLBÃJKŒ/(q�®
·¿ÊÀ�@Ÿ ÅÒ)J’NÊ«Rd)À/Î(wZh�)åMƒƒ2FRla«q‹ƒÉìde`†e[%4˜ Jª€„Ò‚ ©+)¡ ©ÄxJRÓ«µý‚¤ã© ¤Rž¼BáU†§ÅAI“H ÓiAÒˆq1(i�}ý3
”L•JºQq*(i�=ý�½Ù›gªT2É÷u�Ð&ÖõÏhµ Æ%µ?%ABÂîøŒŠþ£Æî¸„¬¢ wwÿ ‚DZbÜñéi�¾VåsŠœï;²ãt
vËwR’*Ñ.©íi _Ϲ�áç €ILJ(!AóE„�|8úÀ °­}ý iŸ�–Ðà+: ÄãÓéë—vù®TP2f@ïJy�D[>0ƒik ÌÚš3 mÍ�–¶–À G[k`FA[[`FI[{`FEÛü€¤ôÿ…ï.Ì@¾?(93ˆ¶…�LÛ¢À ¡mq`†¡mI`†¥­˜áhë Ì(hë
Ì(i+fT´- M²|¸BZÒ¥…„(¡4=šA*˜¥>gPò$·_rû‚’7 íÂÇ0U¬…éuýÿ!…Ù
Je œFVÉë“�¥RÞ\ùRF\?ä µò:ý�È-.�ÿ–/¥÷ÁúEÙH%›Åº²ø‚R 4 í³N ƒuA)Ùš‚RèÏ‘J(1\”*3¬n!$´Sý–°{Åôt»Ø.
ýCjYÄøÅB³/(U$°JŒ[bÜ2‰ÄµúG§C¢ 4M×¥ªÅa!”}†ÄP#Õê¤4UÙXOÿËX ‚ãeì!©8µ*Ê„0-ÊÔb[Zb7jCš�¬½Ä‰ôˆ(‘ÄàHw¿„ƒ‰$ÒÔ`Ü8gP‰ñˆmƒuQR&Ú$ì–” ù-iáV/¡æÍ/JL"MyϺ%ö¦§JŒ‡îÈ-/Â�éîw:Dgjñ]© TMy ‚Äzr<›ê‚RX¾-)Ÿ mb;}=­™et9ŽB_Hh�ºâÜM�®e�ån‰u¯ÈŠzë°˜=¥[‰mîXD*»µ¹×'æÏ%MÚ�û›?ÇH@B”emkû…¦ThƃÌþ ]¸Ý½ôvÝõÔ·¤©H•þ[>´! Uù§¡‰JÊtÝ-h$&’<þ Ô¸ ^󬥒%
MBH¬Ë=®)@½Lü?!‡íÿU¢G—O�J“Xçp.9lg*·Æe”óûo¦ûwRÎÓ%æö±°å–€–¬f^ª„¦�ð¥ØÇÜ_˜d6IA_PФ
_PJP®µŠBHh›çù” PY”þ Ô¸ÐäJm�‹€h§=pÉw:‘|g¥YæJ+) ítRÚé¢4´³ŠÒÔûƒÒjJC;k( ítSÚé¡4�þ ´–ÒÐN/¥¡�>JC;ë(M³?(­§4´³�ÒÐN?¥¡�¥ið¥�”†v6QÚÙLihgK@ª^`ó½�"þ ´UîEýA)-ËSµ_ªó¥Á€^ ¢2õ°Ü£Ô#r�’ޤšÒ1z!“n“{”t\îQÒí©v�t‚^Ȥ;ä%Ý)÷(鮀_RŽJ¤´{Šú� 5ý øÈ;ì6pC=,ƒåpò@P¼“ÆO± a‚Æ11c€ àMÀ«dØM Rq=Àqú(•ŠP(tФ#V}ã4TÀ©R7M_œ”Šé–ÇxÞ\æ}…¥j»ßÔLÂÕÅØbÖ3
…èõ43µ5ѥǢËkªiƹA,ºB9ygÔÉ;?°×Å»ËF:¼Eþš
'ÃÔ1þÚ`IkÄñhòµ[óм6«·�ç ½V›·(/ó"ùµµÕ¤õÚëÌ*‹»(ÏÕœŠÔvÕûÜ¥Ö‘ÛœUåž`Ô[YÏ[xËl¾µ¬ˆç‹Ê¬¶ì˜á?YË̆sLë‚|¡:V¡G„Aq`8D€!›€eQ/ ¤M` ƒ$€è,,€|°�¼ÂèG¼È;sûQX­6$º¼Èã½áêf\[ãÑŠKh|ê¥Û"å«&Ûùb=|º¢ ó ƒ(þ|Ç®•îÌO/b×ì�YWxë}}­SéV£Æašýw7ú®ÕtÜ�ÜZÿ¿œ ú@¡˜`‚0=¶‡C,«M!L0ŒŽIÊ9˜†§?
³Yœ¼“þ*œ<9;û%ôýL9^‰f�u=œé9�I>̺²\ ï³.ÐC>øb^ ,Â@èq3¹ýCnûù6ÞzÐ9yŽ¿n÷ó[öˆòžMÍì¯_vð¥}_ûZÛÎîSó5ô«Œ•u5L<ºeóc{–�)ëiºó@�»JFÙ*h‚e±†&„Ø"Ä@ ŒBl/°¬9 ƒ{c N6ÔyÝ.Á‘/:éb8*PTÎ,æb.+`o4¡ò–][ˆ«•åÏj#E†CycoC´7Zî�Ø=Ñ®ÛñÄÈ¡·Ûk½©¢m¸µac‹37T3|v`ûK1¦·°Ä]R]á‹v„=eáU“=�ŒmY³^£+¯*w5o¨mì
‹žªîÛû[��.kK%ó8ëX¡4æ4!†P  Ú„,ÈÏ‹&�5û�tÝÄI8NQ9‰Çãå8óøCö"åäìû{8§í!ô›/gÞBo½¦6«Ôf•݈š2ÿİ®k_Ǽ=æöÄìTn¦H#ëì1 `,Ÿ#Z éP’çóˆÑï¦âF1ôÑìšKŸü$Mx<€¶°. `Œ–œ?Ÿ‡y¿SäÃhË¥K¬+KÉU².p�'&Ú ¦0Q4Î m‚ ùmNK„/gÍ~dµÚ"‘(ŠDÂa^äk"QĉTk¬^äéÙ ’ÐYÔj‹}G[h?ñÁ¿Í_à·eî »C‡¾‡Þ³UæTZ‰Û¢úðÇä sUþµ./'Ñjÿµå¬Ke½ö. x€9ϺÀJwÏ œ] Æ:œämN[kö›èû<žZ>ÌS®#kv¿³Ù ø_0¹°ÙR¤Ÿ�`|a+ëÒ˜¯•Û+ÌäSþXo$ßµùL×Ò2ìä[¬  ÄŠèa’уÍò àyž5Êú(òÎZò­ÌÝ_Êe]�}t;3ýåùƒsÈ«Í1&P¦i”�ó²ŽÀlÒkä£|ÖàwS�æÃ|ÎŽÊÝbŒÏ®9²>x©ãø›SSoœè¸\äLtøäZR|íý½o�êé9õÖ^R|í§kïŽÒwºæ®â™CM�’«»?Æç!è $1; B θ<Ï¥^19½¥ŒÉ�rʉÈêf WGjù0.ôß³ÎÛåÃ,Á&“®Üµqàúo»¿p(¦ÑF
fÃÃÏ’­:殲 [&ðBqÌËfÇL ÛüÛÊÊÊßÂYM.ÆŠš¥—µœe6|ú½“÷ýäBÿ…ŸÜwò½Oox­q×§ÒéOínlÜMÛ]�øìø8<|ñŸûãËÃÃ/ÿñÜÔÇÛÛ�¿15õÆñ¶¶ãoÌÍÁé¹ß¢É)a%œ:¡ü£4"Ð b†ƒÂX>ÀˆÉEf•••¹™bj¡9æ^ÖF(ˆÙ”²cF²:@Vþ1úM²¸/Q$rçìÅ
Ôªµ©”-Jr‚í\Æô 벯m+YQV¶¢„<Æ|øc˜›ƒÝh”½\°r7€ Ö�:ñŸ¨.ƤÑ'„�!§ÀYLbcd~ÀÐ7÷Ù@~
åP÷Ç4bHƒ9Žg¢ ‚ ƒÇƒ‚ÊM@ˆlˆm â8èEJ,?Ù |<©’Z8y‚|®”LÅ
ü>U•¾z}©«Èa·šŒj%”£rµÁïty¼^=™?çèBáñz³ÝÂS ˆÖê =x¢*(d­žÝ›£õÃ�þ–S?ûÌà–æuÍA›±@)ô¼¾wíÑõÁL2°2ÞXtà™m¡|_C^þ&1ê1•,Œ7ìè«e:÷î<‚Q_·zUíÐÉÞÙÓ;�Ϊâa‹*——y¢"O5€|‰\;t]²q”c’ISz¾†Ë`ù„1Ðk DÞ³ma$Ó€ì¢ÅíäLþ°lõlóûyºYNÁ?¸Ýddž–'ƺ­õIã�÷DÈeÞ4Þ¶®vðþÞÙ³xÏ®Ãí-³•€aåÜUò {
là�ɘ֌X\è`ÃÒc,íî�É’,+›[B�z7vÎÆ9ùÀ(Õâ�Yóí„b»'ßcµó”Ø�M™;,Nö¾óî•óîêH”÷Ð�ÈÔh²ccóߎ÷Þ—®©ßù©¡Ô�URfUï'j+v'ŽŸq6oäM:7/¿óõÃ;_?¹º1Š‹>Ü{תVôNKø­/n=¹¡0tÎ]%3ä
¸!±V Tã@ÕÂqàmR"–…^°Q]cz�a,LÒëAà+÷„¼¡"‡ÙhЩàFn•Á�äø…�Å„šù(%ÏæâΚƶþó»›�öÙ½8Ô3ÙH„xMWíL�íª{áH[ËÁÏïþÄi#¶¸b[È•†É§·—;6ß¿1XTZ¤RƼõncòø×î›9¶òè™#�ÃíeTž2¢)ø9‚-f6 ÔB�3e·%ù¥8Ï].+¼žÚšh3‰Š.σ|±¿ 8XlȯHŠuzUqI§ ·LYËŠ�Vw¸È?°yƒ»P›§Õ«KCuB0<”¹D~E~*ËÈ®˜¶ÐÁ–±",ËH1•‘œPÈb</
–‡á‰,#t`A&l7Ó¤b¦|;ädl`+s;•F¿é:Ïù
Q·Ê¾¢&„¢ÂÎ7_ï;™®iØõDÖ© íIž8ëlÙ”¹Äò¦½TF^;¼óõûW7E2k™ ]m™²œˆ”ANF~C®Èž$+—“ºQ[‚E9¯bAI‹AI‘ÙkñjT`B&n^}‹)1.ø\´ã…©å˧^رãÅCË—zqGûD»(¶O´wì ír¥ýØkûö¿v¬½ýØkû÷½v¬ýÚãU'7l89P]�m«¨Ïm›û¿K®,�w1ó±ñ®í¿&ÞÅÏií±*ò6ìeñuýëâe¡Ô±uƒŸŽ–+­¼±4Ü %ÖòøºÔºxy ïŽîM×�J«5ßjõ„‹<Õ¥EÅe ½�É}}•ñÚ¸Nïp:
ü BY­»°Ä»¬¿¥~ÛêPS¬™»ÊÝI®@5$a Ä6…�ZYlŘõóʪDÔh“N…•Jèå4˜ž�V�©Â²HÖØ¶Öš0‚Ε­kÚÖ47…“5É€Ï%ä´·Uëo¡½YåõÜ`�š ºî8­È¥Ç²b3³kÚÖ˜—?ûS±jbù²Ôò o2T †'j¦ÞŒÖ~õþÑgÄb·?7vüjó;¶ì�jÛÞ*Š­ÛÛÚ··Š�ñæt›O�AhÚ@®4øìÎò w¯÷•ñ²Úß¶×Ô¼@ܾ#ÜÛ(\//~ÿ¼¬s"Ñ<±ŠÆ Gæ> ϓ˲�1(0 Ã28çÇqo.ŠuÄlów1ÖÑ!Ùå[È¢�q;M"gò#ÞL5-š‹sçÙãàðhçÝQiÂhÇy-Ÿ’] ¹<{v÷¡öfüo×B îkÀÃìP ÑX Ÿ‡i ÈRáÍ©–žJ+ôÙ„ÐÔTÇÒð·Šy‹ÛmU˜ýaÞëñÔÖ†çOFAW¢Ç MC>7l)ø›`ßTgI£ƒÅ·/QY€™9Ò¢ÃVsÇ–¾c©
µªßÆZkÖ5÷½ö&]“ €L“ËÙHK�(Çð’ˆ'à¤YŽSDôm¦l¬e¢±.þtæá³æBößtF¥Â¤ÿ.çà —­úÙSbÜåLˆx¯ÁŽà§ÉOÁvJÁîþ˜F‹0Ø8Ì`wÐ+2•ÊR=ž…xÉi¹#;7Ðñù  7+L‚™ñ£†,AjáD�¥7F ”‹¢KŽ�ü±ÑBÖïÝR±êI¾>\l�úŒä²µàÌà¤ÎpO¾ÆQÛU5{žF�›iDÃVÑr3�×Yªb¡ BD‹0¢
›³ŸfšÌàžlôŠ‘[´˜y=ªÂUl�ŸÚÝ3sWɯØS`&b*G�‰0,ƒÂýM®ƒ#X6kY×rÝ8u(ºECƒ&“ÝPRdí"XÁR&òJ#å½_QpâRÏâ9#5=>²îd:ܰóñtúîj5ãEËz>íŽßwæ({jöËí½ñ;f&¾õ@׊åÜd}Î¥¼yñy@A öšCR¹Ò/@!@€ð$OFAPBbO}¸—=E¹*Ì}À(Ù“”«�Ëû¨m‡Nü,œ‹é‹Rð#ÅqrÚ]±ÆpZ
É©zA¥Ò'X„�¢G�
YÇ¡�ž…±…ÿ’4ˆ£AP_6JÅLEj>äFn¯èEÞ¨qúannî™§ÐT6—ºæÞl.aùEŲZEA&MÑw`lHÌç=ù4­p‹Ž|dF戇+ôÏÍec5ö }^'}žEæÁZT@}‚=»)” TÀø�1œ)•ú„ZŽäT7Fr••e^Œ*ë+ëjÃ~Ÿ·¢¬¢¸ÐbÊÓ«•ȃ=ÚjEgÈEÖpÆŠUŒlF`<²Ñ‘$Ïçç1&ÔÉ×DœÇëEa>lqÎ!ž¼gªjÑ]'?œ]u”ôúþѬӭ@½m<Je}}†<Iö}>`š ’P†¬¢1\ @­<ÏÓç›düÍâ -×¾J±ï^ô�ãss°eî*yDÆNVn¡Üî1ÄbË8Ä¢`ÖŽ0Câ@X†%Ì8 ` b7€ŒÜj—F¦2ÑS&Š
'Ý}'úw\ŽBãÊ›VE!º¦Nô㌠?ôÝQíÜUòÎMþMÞé¸óóCCŸ;ÒÑqäsCCŸ¿³ã •= Û{*+{¶74LôTâ³/Ì>ÛÓóìì /Ì~¦§ç3³/œûŽH䎷ϟûŽÚÚ;Þ±Ìr�¼Qè„<ËS"…²’ÇXÑBñª7Ýý±€)ÞXް47PuX�Ž“%'ŸÙ
@ ¤¿yÚ-g¤b…«ºôöt¥V¥:Úš›D§Ý–§gDQTCëÍi1+Ö¬ùñrÜb0Fy‰z<óÿ6cTb²$2«�l rúÖ² ?‚²ñ’Ú�»WÅ"E…‘þÉ“ý‘¦ÛþnÛ¶ÇǪ×u–W65µ®©¸ívÇúƒUÍÅ-C‰øX[iæ'ƒÃÃ[‡ó«V�÷ –‹œ!ÖÕ±mÐ`ò[DW£2W­K¶Ü¾9êëwŒ™âQß@Iù‰TÇþÞÀG¿ùŽQ¬;ëÊíÁܸsCjûö”¿½¦hIÜ˺@e1÷šé¡JF u„E¨(öLcŽö,òdïì·Ñ�2â—(ê\ÿðì¿fQÆÖ¹«¤�\�ÔÇ"„Ø$‰ ‘05
K#áE#PæË(ãü(É,•Àù p1ü#HiЄÊÖêøhBt'ÓM +«�F³6,¬Þ8X½þüž–†=71r¾�¸4{‘=¼õäºþûªŠK‹³Q\òî×§v}ùDg¢IFÍ>ÀÓ¬\°"Ö¦Bˆ” –¨zÆ�*/ÇŽËX+^H"§SÐG“R $dÑ>Ï ãp!—Òàg]žZšÕÖf£™s4fË¥¤‡žºíð¤Áòx9¶ämDºÌï¢�w�I©Ò°5ÁÆ{á>³©ÍŒ‚cfæèì«MMz£^©êó…(¯Ïg~†µì;`îe^�ÊüÈl´Y9…"Dd„Åfµ*8Œ*¶�äåVwŒ¶µŒv¬6äå�lÇ[¿�ù„TäTUîùá¯8ð“w°§Bí,’2ŸMø7ä2r–c~ÇY‹#ÍÞ,[N�œ'Õä¬uâßèÔ™*ôýÙ�}'ÆçÉI“¨Ÿm½…Ε‡¿z?õ°2>Ån“ñ©•ðËX^2Ž•ê˜ŠäÊ]RªYµ’¿ „R«õT:s2¤Í‚V4á n4ë}àVª'THÉ*'>ĺaj,úÍÒÈH
�»€¤¤bžV®èhkj¸¦ûë0$�ÐJ�BÁ‰b4üŸ€ÄÐc·k¬šÛY«T4~çé¿$#×”š#ŒšÕ(î4ÍQ\*s‰<G~
VpÃ=ÙàXkB,vœrÈ—dþ2?-F‡Y¤*Ë9*R¼ VÑèp¢¸Íb´è¶»£E©]ŸF#at=Põœ´ì‰„ØùÄÐÖca�›y¥÷ŽÚàm ‡ —?üz§cÝ<T•XÖYzíEŠT-«Í"UssÐ:÷[¶~A={«ŒϽóQš¶è¿g1dòîGiš¯°Ó(ŠÁxÞÇ–•¹9�zñ±ÌÏÐ÷Ù€¸—M*ª±5ØëñD"Ñh1ÉB!‰FŒ¨yûˆ’pZå¢Ú*µQRÅý:.¬F-[9ùƒwràÀ•þpO%£ã­ §vá{…\?¬ÿ’OÏZþÌ*…•“á Lë&†„RÁÙÄ;br†BGQ/�ˆm‹ƒ©˜üà-¢Éãuª¬óy
­ Ó<<\-WX²Ò¼ì<7n¶aCá²¶îàè]Kk_ºúÂKÒø``u£( Ä&CûqFË­»·Dºªmo^¤èÞE�ëëiïÀÞDã,EÕNË9Í)°@0æ3¦•Ó‹›‘X9°±ˆ‘º«%©Äâ²NKËê>´¶\í<aOÍ~-¾z~íh™­¢ÿ‰¹ß¢#ð ¹Zp"íCÁGé\õl!‚rc96>@þ™­’©�Éqv· ¨_ehM�Ö3@mÈ|&¯Öã”yØú„­sWɛټm+�¿Æ°<ÖÜ‚VƒC£kBŸCp¶ˆ ½Е4o…0ŠÖ~ŸK0Q'4€üšé“EúäÕ¿ZM0Ë+cDk´0<_Ê0›©‹Ïʬ €¤Ée(¤¾Àb2_÷Èæ¼:œ,s•;©/Ȧãó¹8’ÍáÙ¢g{æGÏ›MÊo2*åçUfýS™wQÕgÍùÊo+Õ¯+m¦'ÑлzmæI�Eƒjôy™`Ùth¯-/óŠÞJw‘õröÑG³£ÌåU‡^Œiœˆ!•ì’GTJV©ºÙwhå<d©-—=€zÞ4ü¥Õ² ÓátWScÀ�Ñò–ÆdS²ºÊßhp‹Å…ù63­Ðø°O—=‘[gR«às×eRJM¦n‘I)›IUÉ™T¤¦²¾ªþã2©ód:Ä><p/³@­�ÕÊq
¯'mÆÚ py‘m岈�(óKÕæb�ÆÄ>ÓúØ#÷G\ªBUqÿèΰEPP[‚çÉ7™1ÐPd–C,`v3/R)
Q€�Å­7|Ã�‹"�µN'ÑÉÌÔ™Ìat‚ËŒÏ £'�£'èÓiBþsÖfZ›Ó óHÐ|ñ:àâIÖÜŒ­¾”¿`+R_á Ôê|þ=e±íi¬›ý֛͔aK¢G´]38ÁL>ë‚Bªþ‘ Á@6Ñì›~Ù"ïö¸¤Rè-[àãòG"ù+‘ÖšQuM‘G�z�Þ¢'2“‚r£'/8Kô™gòÜîÄ¥KøgF3ú?6Óì7ýƼªÙ3+m¦ÙçY•Z{~+‹5Ø©ttå°†­´Fb (¢¾UV}eÀP(º,;ש8,#M…¥.T„ŠxÞämjÁxîMla·3¬¿¤×b,;
{„ú¹ÐxXßhŒÁÌ•J<±tDöf“1�cd…Ëâ(îÔ�Ð=7†%äòµ¹|~i¬A²È?»MÎaëàÀ¥êJÌpókt³ˆá€c€Â%²fÎ׈”KÊŽ˜ 8†›`ÌÄÇ¥bvZ>¨‹Fj|eK‹ª?_D¸)Jû³U´ÿ¦Íÿuò›¥¼As¿Ÿû,ØS ”= ØAÁZ”t¹0ï·É67Z)Z‰Oä'Vš]NöÙ%Ô0…¬ P+ÐSj¾�½`ÐË :šó¬ˆs
šž‰èÑ̽¯˜�JäT¨�ZiÒ!sš~ÅlUf¾Ï*2?SZùÏá§ñQ½&¼½§3ÌNÏöYµØnPg�ÎBŠ*òZÈ_ŠPȉ§ì_u�t–9
§üa’ NÐn3fžßðä�NdÐ×OüèÉ ¯7ì|l ó2 <¶³Ÿ}øê‹¬kë ¿;7õ•{[¯1­Çþ$æ®2…l [nB„!ÔfÅ�0Àç° °có0Œ™jÓ¼” ðºiHÏ,P@A…ƒ¦qK£OÅÍÉk4B^Ók;Ú¿söè·Ï­é{ì»GïújGgÔóåñ¡ëOo«o¨§zM¢±(µ«ƇfþøÈ#¼8´qUŸJ[ê/m;þÆ¡ÃoÞÛ¦/
–èçæ`€|3‹2 Q/¸¢dR8—žá¼yD‘Q,c
©Ý÷úmKZ9ÊæE/Ãû‘…¦uYŠ:iKÖ+f§ ˆ‡±Õ^<;ÁÛY×J¡\ÿÑkv‘‰V¸ìy{sö:÷£¸È"¶5�¬;™3h˜= ¦¬¤fë¡zH–•bþ&ì ›Å`~~Ài6;ùùAÑÌjòƒô*˜_t™Í®`®jAþ–½
¡.V«GÔ',XD¸Á
*rV
¡P¶€V¥eIÙBÆÛiÉÉÅY²n‰iÜRðè™{ln¾ÐoÁ­Ræ¶\Åâ® Ï2\Ú Ü4~ôZŒÄ®½ N2ÃXÍäǬ’ÛAAI=Å8THE²¸’M¶($ºÓ#æýûìA‹õ—ZßC=ƒYòÀB}�éÏDgy²¢‹¦GN-Q˜ÔD‘“$ÿÁdüä¹Ù·Í �w?yŽËÔ¢B?Üj°džGý¾�ôd¾SY?{ èš»J^d« NcÍfİjDÛ_k"ˆÔü¾rg‰‰‡8ŠËʰðÑä¼ÁôF#V[¶Ž'ÛÌÚf2o;çõ6lï�‰–4¬ ¹3yà‰þ±3cqkGQ­V+6mn�Å�w�¬ÝÛ!8{*+×4û5J¯Ø¯ëØsš­ªì¿£«ehe8Ïõé©MgÇ"áÍw¬,Ѫó Ú—ƒmý¾šTKé!$6õU×õÖ9ŠÂí>—…Õoz` ’ÚŸIò
[%PE#uòg#u7ýÖ-‰.ÕøÜ–³Ú²XŒ¤;Æw›œ†ÊCÉŽ{†Zn{r`Ë£;,ž:Wæmm°èqœïNlŽ6lM¸ïÝ×2±¦ dó”W§Ü´þÑÉXómOÔ�¥Ã™0o%ŸZ6Üæö¶Ö9ékßVÏ]%'X„(ºÌ"ü˜°¶¿]v)¬Ã�diÅE>·%%g,º^““ k3ûê«S¾‘ÇÇkÛ�|n¨~|óªâ°Ña ÆÖ7Å'V–‰­ã­ƒ»ÆÇñóŽʼ Q/›8»nûg§b6Oua»½P, tßÖ¶l¨ÍS*àmT“{˜aôެ;ô{FêÇä’Œü��
”"­ÆP£*Ò28zç}½Ã¼ý´N؃2hi¥SäJG¹ &ú5¦J®l�ë`SÄMí[ö;�7ÚŒ³¶¡>¡uG§PëP#…!ßÔ'—?ú_�c�•z@¥Â¨m5“ˆV�Èû¬Já1}BŠ<„ ¿¤æã¾®‚“­Û(oQé)ÿxº›ê;Ôd–Bi¶¶Ã«¬ÙOt¯Å¡Fò¾”©¨õç‹ùFM L-ß3µ3Ïòh1óÉ›Ôt-ů‡é1´�§Ù*¨¤ÕÃBDóT”ºÌ¦<T¢Jv‰% ‘ƒ³ÚjÉ!„7k?×{j¼Ñ¿"]›yɳJDO9„kÏêyôhMoƒ 6­­¬èn¨•^qƒvÅîÓl †VÙ»+šyJ£-)­ç½yè™Ú¡á±úúõõ…×kx®ÒG./Vú W鈟Y†
.Ä©x«¡éÿ�C)»³¯:¼‘¶?]}Í:ûUÊbªV€sþпP_¸fýw‡ŠV%®ÿÙÀèÁÏôÃ9ò 8˸ày¢èÛÌS $[`3ð÷}xŽõÁÃäç`g]ð ~\ltàR8ÍL‡¾»Éÿ€>¦dj`%ù:ќ܈©ƒNâ„6î›°†©�#ø6°“'Á„ÿŽ1zØÌÔÀô=8Çýjît.£‡r =lÁûäëZò�#/Â4‚Vüpá]pž”CSî½+ÙЊwÁ7ç˜8�Y8Áèåwleô ’ƒ`£´¹µ�'× D~À”ÁLØÑ÷æÞ”×j›û=ã ókx€IB‚Ñù>v} vRZÜ'™2¨'¿†.&“äû°¯‡º~ºòkh§{€¿ƒ? AßEßÅF |ÿþq‘1òù6ƒ‘ù2˱‡Ø+œ�{€{WÑ¥øßÊå½Ê/ª\ªvÕ˪U{ÕkÔ§Ô_Q_Ñè4ÍmT;¨ýŠÎ¦Kêöé×ê¿¥ÿ­A4<høºáG†Lž?oeÞ©¼ßóa>ÅŸä¿b$ƨñ¤Éj
›šfÌfs…9mÞa~Äü®9c©·|Éj±¶>aýŽ­Íö¼í-Y:6Àï N�0tÃúí'üV}XyT_ ù.£€ÏÈòJûôð™\ƒ¾˜ë¨�·r}Šá¹> ÈœësPŒB¹¾ÆPW®¯„Jt1×WA1z?××@ž¯vI_‡\¸.××C„l„ì�I8{a;lƒqØTSËa ÆaHÀ ì…�°öàö˜€Q–g,‡°Æaì…} @™ü¤ý0 û * ¶ÉsÇá A†aì’ïî�=° vÂ(ŒÁØ ûaTÀðuï+¿áýka¶ÁØ)ß­‚P[W�°A7tAã 3‚7̹q?×�®‡QyÛå KÞð×=u»Ì‹A`?ì…A�QØ%ÓìöÀ˜<BW¼G~Ânºàì€A؇A€$†í0
#r; ¡¿zÆ<:NÙS:(ÿ‚�KæŒÜ´‚Q8 KFvm¹s WÞÓ~8(ï‘ÊM–‚rdFa7쓟#Àyå”Ë”Yë…Ь�I™vé“»®{B„�9£PNfoõÞÅó¸a»Ì¿!Yò8˜“ÎìiµÁrè‘ûû¡„›dy Ëú2)KkH^ÅNÉÒ¿ *` ´A×rÕTùgî“ôÿ�póOç«ðÏkûg:•ú²”0,HHLJDœ”l­‚ •¥ÇèŸI/üÝé�„ÅäE â|µç»hæ8_ê"S¦j]›¼¨U*|3JΔ¢“=ýRìdÿ G’3zõ*ô’VÈR©WÑÜq‰yh†•ðÿLmúE
endstream
endobj
80 0 obj
<</Length 13/Filter/FlateDecode>>
stream
xœûÿÿÿÿ×Ý
endstream
endobj
81 0 obj
<</Length 483/Type/CMap/Filter/FlateDecode/WMode 0>>
stream
xœm“M�Ú0†ïùÓC$ö@c‡@
BHl ‡ýвjÏÁh$bGŽsàßWö lUõ�D�çϼñ8ýö~œnµ=átö]Àvt
§ÕKÓ'iº³jìÐøWD�úVÐ;«ôPvÓú$MF]G�wÍÿ$ÏxiÍ— Ô€j¼í’4ýlýW0¡ˆ=ÁA£ñ­¿�xJÒô'º¡µf2IӽѕíBsC’q ÈÞ�UGôpn�v\ N¡n"sЭòLñ­º¦�ÉÇÛà±;˜³…©ôس ûÀK;xwƒIlì 4ž)òæ4ºÖ\`roö¯àqìû+†&AÄU4:~³`þµé26üXe— ¿–>o=òÙ¯«ï ©Ee5}£Ð5æ‚ÉZ!6°®ëºÞ„ŠÿÄó%¥�Îêwã¢\n`-ļØDÊ#•K¢‘ *"-æDsŠÍˆ‘rV–¤ä=l`� É{.)&‰¶DÑ3++¢ÑŽhO´§ê\¡&T]† DA$ûˉrŠm‰È_Q‘¿9ù“ì�óÈ_Y<º“ä±\�BœKKî€<–c�ôß${ä]Èã~�ŽÏ(b˜ÕÇÔ¨Ñ94>Žj‘0­ÁÇÌ÷¶Yñ‰—å~ï½Õ_ F
endstream
endobj
82 0 obj
<</Length 6243/Filter/FlateDecode>>
stream
xœ­z p[×yæwι÷ H� €ø¸—HàßEIêE=H‘rÉ@|ˆ’õ²^‘-gk%Ž­Ð^¿2IÇò8�k·³ÙÙrUoª¦™´]»i’f;ÙÔ�m£Ý´é¾º£ÄÙÔŽîœK€¢^‰›Yh¤óßs¾sÏþ÷€��!1}ê„ú Íø:€¡¹£ûýíÛñ§|T�Üwðá¹wþôéØž�æg 3v¿}̘ŸŸ-Tÿ¯hŸ?tâô§WÙ¼@à[ž>xdº°¿êpÐÇl:T8}”ü·ê)@ÿõpáÐìÌ—ÞôK€:z三ŗðM ü#±~ôØìÑOp·|ˆ‚oŠ¿r�ϳ+@é²ååëïËë*ŸgW¯–^ÏWós1N uFåßçRh7—F÷d5]ó/dU>>žÕx2çWù� †r9•ÛG 3¼C<ÚGUžDB ¾1žUçÔ……‚ʫƳy¿ÊU±V%¨A äýù\.ççˆær:Çxv6—‹qj¨£*—‚…•Ëéñ,—õWô”_Órœäcœº¦kêLQÞ›RÅÊ;¡MåJZ]P8¢Å„\˜ÈæÇý…�¹¬žÓTžœÌrDý‚ûòQ1.Ü’Ž^E:ŸŠqÙà=¥«zªÀéÞ9N¦9És)㊡
®èèô% {UñžÌç$Ÿ1¹²,!Õ‹V)˜WGô‚�¢yiø…`¸êçÉå«rÔ ™¥ÍV£(Ë£œ21n38É«*·¥· Êmz*Ç«ÄÓάʫôT.Æ« •×™ª—$L/ènOçÕ…¼ÊízJ�q»16•-ZH&×ÎkfõÓ1^mŒMdÇ&—&ýZ®�»Ìù£ˆêô®l±º:ÍI!Å«¢9Ž4§ÁTÑ&þ©¢Á']å,8ž-¤ó\
¦Tq¬-¢éœ*´i]l¡As&Çmé�¼*½1ÏéÍ’»‹<‹€KÏp’æX{�b*Ça!�NeÁ«õ”šç¤p±¦†ÀŽTj!_¬‘£üPÔÈÅx­Q„#ãuF‘ˆÑi©ë�"£Ë(Jbl0вÝFQ£Ç(ZÄè5ŠV16E›› n�~̳}FMÑ÷E"Æf£HÅØb™[�¢$Æ6£(‹Q5ŠŠ5£hcÀ(ZŨE›Û uÄ´� ¡æyM^Mëœä…j
Â0Û#ZŒ‡ Œò`$ÆÃ†ªnTï"T½0¤« »²¿á×r1Þ±,iâáá'î„y¹Î•‚¸y)b¨ý&ŸQœÝáåÑ;*æáyËŒR™µúP1BÜ‘7 uDÝx>9Ò…¡�qïHŒÇ”“ôôPŒwE
OP�«…sܼ°°QߨÔì^¿ˆ,zêBœwC$Ƈ‡KA.MWF£³ q]UG†b¼ûƲ_z—D��ª</\69‘}“ªLõ¿ICÌ—K‰¨bM« º‰Ö7ä¹”¾Õò"x,ÅKšÎÏ蜥 3ãYNÓ?gé¼·î)èªÊ¥�¾¡0ä×¹5½�Ó ·¦ÍSòê�á-ªs)�²—ƒ.ßöV.…Ä�‚&ÁüÌxVóëZîÆY¹ï2PU•Ë¡² ô‘¡ï5§¹UO©ªºAß(Úê3E&.P–(¦²quD×ü‚ãò¤*xYy�ËÁÍK¦>:­/iéNf[V‹.l·¿||º¢—¼Hh·Þ¯¢ÇCWãBdvfÕ‘\¼" Ñ\ž_9=t3úŽ˜UODïøÒaƒwGTuDXÊÂÐ0\JÇy(ã«—Í«"ZaYº:¢Æõ¡òëF ‘eR¿�nüÿez‚}TFô!¿¶BÙZ®Ìã!ŒÊý׊ûkBò‚Åò=–¯¼Îàp/yæ'tʉñä]æ×E��Eb<eð®HŒ§…ÔFu5®nXÐ 9e a‹<�ñQã0�ñ ÆAl4.sf“q�˜3›fM4Æ·Œ ÆF[FÛfU4Æ· Œ vŒ ÆF³:ã;F“#ˆ)�Ä.�Y�ñ{FŸAdF9�ŽÆøn�Ä�Ľ#ˆû Þ³,æûÅˆÆø&5�ñ¼iO=Q>�ñ‚Á{—Ñ{щž6)�ž1)�5xß2tN<˜Ð}&% ó&% û Þ¿ = Lèƒ&% MJ@Qn�å¬}ü´È1ú%Q¸²Eùt b5ÖáÜE
’ã¾ñl²ŒÊÈ<ˆD‰4€2Ð=� [%yl6eŠâHÃjµLÀb©±düÉž[·)°A±ånÛ~cS.Y³n­ÓÙÐÒ#Í�ªÆ¨k` ·§•º’Å¢‡Ck¥þ¾�pP=võ­¥åEªâ”hNmPsjÿ0ôLaÃá­¾ÎD4 {¾V¯¸ÃÝÑ–ÎH ¦ùjÛë6¹ƒ=­Í=A·;ØÓÜÚt—.±ÿ|­s=Ûzí-iWl$˜y`¸ëªN=àÞs¨½/¢‡»´¶Pumuëõ-•m-Ýbì–ò-ŒJÿ õû±œ€j²…€MH„±ê4©!XœN§\%nÍ©9µ~öãÒ‹¥�J/ʉüò5i÷@ÀJ—Ù7ØxàO6:d
BR”R›àDÆX}”(Š®»Ho�Çëòx¼ƒBL½ä?Ùuý�‹¥gÿ¾­Íúš½Îj­·ÅòþEég>?yŽ}¾¹¾äöø›ýä¿7øŠ3¥ËR5ûMˆà‹ÉZ…Hhm¡²ÔH¨ÌRc¼v<›l±IÂ$!@m²L'A©;­Æœ,ã_2‘;‚—AI bA€È$ñÞŽÉå’.¿¨¾ˆ?‚&4u„5k}Ôå÷ô®e7T
;]Åâôxz{ÖÒþ¾8=óR£&»[SÛr};Ï÷�þJ~âhì¯7î�†r½ÝÃm¾D¦tYÖ=ÞOhCžÌÙ˹üÔŽîHé˜thÕ@iS<?³kêäf 믲wÙU„Ð…3…õ–e#”0:„)d�•È2&-ð¦A©4 IrKÿÇC6J™\²±#L�„»:ºZ›= ÎZ» !²ÕFIåÆZ+7ííñzL˜zßZê (­/N©ÿþ—�%•¯óú×”ŽÔîÁÁ‰5 osýæÎ™÷î»ðøXê ?Q8\G^õvoaW×ý`KÐcÛt £ùÛüÞûë‚u™'ÿü3³o~vûŇöE·�èAïâUz�]ÅìOV­!Dn%T¢eA´„°y0‰0i„È“�eo’´d!4ãÿ°FšÉýA—îÒŠÛ´ì@œ
º¡U©8vxp)
”µ-‰Û‹g/ýz•×Yî �¤BëvLíXê)<{âþ{Æü«í­�žp<™hïm«MÍŸIÅ÷<¹»ûÞ‰´�59k\^×`¼­³Í×Ú9rÏȦG²=õšáË;[ëÛ:ÜFw{(u0·öÈTO½÷—­â»òyxÁñdm‘ik •d‰@¾nÆ˶í5 “D¡@ L7¸y]!@Í ·h$™\ÒÓÔHP#M�»¾ÎªÀK¼ÖÚ¨…ÃKòY€Çëìu{ÖÒAgÈŒ‰î†VÊz¼šìYý¥¹�? üà�ñ‡b¥RB_Ýs›¾°ªÍ—õzséȨ́ÿè‘#ôÔŽî(•?š~§¶¹ÓOÞNG˜Ú%gÙyMþ>œPÞ”A:¢ÄãQK840¸–†Ä@¦�æÜظ[¶7këÛëë|ò÷·¿þêG5áj϶½ ·6k6/^eŸc ýx:éP “cD±HJE|�e�…E¡–=`¬l/6¢(˜$ÖŠ$�»C­¦PņBõE#]ñH´¿=Ðâoô¸ê«¬è$�UeÁÞð«Áå 
‡ËéÇììw0wƒ‡¹ÛCvOhÃØ®¾ä�m‘¡'¯¼>>6´y(Ñê Úã÷|ïáO,ä{J‰Ìt÷ôg¶ki·šÒzN=3›<œ[-õçwûÚ|~×øøöUûžÙuýÙ—»{_‘šÂ}­#=BâŸÈù<“nú"ô×@dæduQâÔ�äLI>ÿÑ´|‹‹Ø �åó m7@"{«Öë%uPÊ&M³“*‰¤BÜ.»�HDª—ýQ<(.vv'í…Jˆfº»:žMzÓ�)¡"Œ[-2c¬FÄuŸ×Å*™Üzo,æ’µ º;à…5›'Ú{#–{*Ý©;ûLãDHqý1Í�þU©±ØgZ7Þó@bê3¹xé•öµ]þÒøÖÞlˆ]ñx74'ô†ÙÉî †»·ðtîú9zúMo,m"?�\��àQ€ýˆ]…ãÉ*…04Ê*×r�±JÒ’%Ji�Z^óN`¬œª*+¹d5|º;¬)®•·i]Éþ£&û­É-“=�NEKÛ·ÏÆÛ[»õ†¡™§v
wÝß»Þ×âUúº\ ßLVÙamr%ζ€ÒjSslŒ QË2¦DqC$_ç¯5š f3b+D&Š<++±ÉvPFT°w�år¹dA³Ïë®wÖÕ:ª ѬµQ9êwê�Pÿ k ·×ÙëÖ� fš6e¥(äõ³ »š»ßÖõøÏÒ]Mõµ6»Ãº­ï³µ_ø4mõûf[ˆÒYúÎ[×ftÛªmöê3QCÄ�ã€T#'àXäW™P0QF.ÏêeGñº�µp Fs*Î(µV%‘†{{„{ëä‘Ò‡ä÷ϾóÈðš3ï|êÕWO=vêUò—¥^9‘|è¥ûöþΉõßþ­Ãû…H?”¨�íIÍE$FR�@ ‘Ý%ž(÷j�q:u—*7D59˜ÆD•F4¢±P(¬(é‡ï鑪©’wÒÓþ’ü˜T—þ„{²ÚWSí³kMD.]óåĵ?'¯¶MvwOµ�â ’hB;z’]Â$q¶°c‰í�,—o^æh4ûЄƘæ´Ôßtw‹Çã%z ÌB!!‘I…þMé_ÈsŸ½üðPûèÌú&ÃE:ÿ÷ºÀOkƒ�ÜÉûFZN?zŽ,–ˆœX5÷Ì®õ' c^G¸¹ÔÜO^nlø�‘ÉîÂ~µ‹?¥ä<˜ã‘ñìE+¥«_Œ”¤rædÒY–!˜Ä’'Ae„Λk ´²”»èÖ‚í’+JÊ5ŸY,U|N�nè*|~:vO—ƒ6û¡–Žá�‹(äo�\|lÔ^óRƒ¿º%9»™Ý ŠÄâOåay\£5饦Є‡Wëèè¸qT%¿¶R¹OÔ"K‰U,ßûÆ??ÿü?ÿÞ}÷ýž߸·ôA_á©löéB__áélö©Býò ¾=7÷ö‡/<ÿáÅ}ûÞþ—ç¼~jݺS¯xð�“kמ|CÈëèâUé]S¯É%?¯gDèQ"À�êéÖIQ+% .GµEAi’k£¢èwjÎ
ë‚l¥ôü†CcDÙöÜwΞýîsÛˆ¥cìÐ_ǧNoa�×þéô{Ÿß¹óóï�ô–ÓSqè;ì4b"i·+”ÂK$*Â�(ï]ŒÍ”#%‘¤i9PŠ¥J¤\ZY
”�hÔÚƒ+¥ÐŸ×"*3¿Zœ‡¿n“kb§w¬�¸hƒ³v¨QŒìJ³>»koÛåúZ[Cx¨ýú—Q¿xU*ȯˆW/rœ(OTú]¥d•Jˆ¥žÀdX„Ä(JµhGm“°Ùi™b™¨"ËØR­YŽŽ]7Êõ»îÃÍÛDÁÒÅfµ)Öùåí¿~gràcnUŒè¦Ê�‚è�ì�EIˆ„BÁ ®;ëíšÈÞv€]fWà„/鵑›ÚÆd¢Z«�jz¹e\îiö'¥¿ß´<ßV_Õäü¢¥½é]vÅï*É÷Þß“ ¿]"Qˆ}UNÀŽxRœ&üUtñò„H4Õ‘¤ ˜ª7ÿ×ÎîKÃR§+þZ4'{åúß‘7JŸ :¹ö9ñW¥¯¾[zñ¯ä„¨¬K—Ù÷Ì.ÔÀ×– ®ÖMdª¶QIf„H,å7gØŠ™\%AŠbZa´Rn›¦è.÷Ë•îôŽ Æ
(©‰ôFßzL¥;mø ¿!"l‡î´Š«;WÖä­Ô+â¹µ*ÿ^iø¹B¥5��­ëo¬Q´ÆÒ_´÷žP®·g\ô¨£ìÊGÿ…üášÍ•Ò¼®5âëñz®ý�Cç—báåâœàAÑ�°+h•�…€Ô
aÿÂ0]²DËú§“Âà—*›Ê,¥5bÉ, Ù ‡ j.]qE‰™³�½"—/wN²ûöUs±’(pêW?»W”7ìÊõÏÝs¯A¿}­ÍëÝ´zËÐÌÂ$ý¤°›ÁÅ«,î"":È!²h¥ïÐA
'XÙ®ì£=L¸Æt„ôÐͤ¼çö®YxýÐîip©�ƒ‘¾m=Mîëîм-u[:v?PèšúÂC©á‡~÷ðüËë˜Õáôø=ÆÎS›¿ò»ÍZ³h•Cµ£�ÿñ#‡ÞùÜöͣ⎠=+?‹V &ûê%$EˆDÖWÒŒCtº˜`fäîR# 'iE«Ó z, Ñ^g8êïï­pgFHu»EíôÒÆ–ös=÷?±KnS¨á�tºÿñïXÈ!·6ïÝu.ßk³ýVK]}tSÿš·®½/ºóÛ ù )׉H)™‘²•ìðþŦßfôÃb…Õ‚ù[¾«¸×N¬VGºÊüÆÂvÛwcÜøÍ67
…ö؉Õb= ¾;pëÖ»lÊå’jwwg%ÝÃÝ«úŒhG¢3ÑÖâu××UW‘0 WûD\Ú&Íшülˆ-ñX-4ô ÙE‘Œ?YE 9 �KÚØ`ÕEC%D® ¿¥‘«®ö–/�«íè�Ÿ¸îªûŸ>?Ä/*˙ȣùL7vJÓäù¸Pov:KêF¦£�:o«$È >cDSWE›š¢«TmÄðÉD[zÒ´a1 ^E–”«Ä·“Um„Xœ+rZ«™›–R„õ®™,xS&[‰¾Cþ
B±(Ëj¸+8Ùywܲ”�FÁ¥ å´yÌ(©ÝÜ,”�‚4X*åƒzýr?ðøÆätFÏ6´|Qô
ìýk!ZÙ„7í[oö ÍÄÒYúN¥wfWnôεwë�Ù•kmâ‡Bæñ½ò•3�U?P;òsø­¦¢ÿìaǘ¤ÿöC¿¼~ýû¶ kÐÊ�:ñ›  ê•_^ÿÅwl7Ù‰øè’ìÿ¢ž½&�áŒdÁ:Ö�^ò]@Ã:Z‡³ìgØL~�O‘_`·òi<&�áQúgpI)—þ’t§èkpÈû‘�Wá(ý!Kÿõì]ØÙOpJ¼GÃ,‡Az â :�mòŸä¿b§ÀŠ÷ø*¾…käIZE_ /°jÖÃþ”ý½D¤CÒey§üŒümEU+—,Ä2aù‘µÖºÎú¾-j;oûǪéªg«^¬ú–}Úþ)ó–:®¢ÏÀŠqÜ'jGüCÕIÈæª_‘„ƒ½fJ^мV¦)¬x«L3Äñõ2-¡ÿ£LËð‰öΤ4’æ2mÁé+ÓV$È‹eÚ†Vò^™¶cˆüS™®^A×�UË´,…4Žà(Æ1ìÇ>ÌãTô �nôBÅæ1 ip ±'p*Æq Gp³˜6w¬ÇIœÀ<ŽàŽCE‡ù¦8ŠãFº°ÏÜ;�“Ø‹8¦q‡ÌÙ#8‚}8ˆYÌá㎣ Ó7�×yËù)ÁAÌ qt#�>¬Æ <ŒqlÅê[°±eô­w¨Ì߃Y“ëýæùꊷ~Ü7í7ï\€Š8†f0‹C&æA¨8‚9sEð'öp3P±'ñ
8ŽG "ƒG°³˜1ÇiÄÿÕ;~õjEKÚø¤ù'Žƒ+öÌÜÆÁ,Nš°t¿ eý¨˜4ïtŸ4ï(ìc !$2�YÆqó=*Nšœ ù
,ÙÒ$6c+TìÀQ»òÍ[ozƒõ.Ú‰—móNçÞÐÇ)°ß”ß^ÓÂT|²l…KÚÚ€õ˜0é†z›ÍÇ´éGM«Œ›\DÜ´ò}èÂlÀÖßp—ˆ
ægñËâwt·Æ.á?îÌ y&÷‡VX1­r¢g8Ó�r飯òŽüœø9Íòïörªg.؉¹P­(‘ ŠÉ]�:l£;3ª­–HQ!™b;97‘åÉsÙ¢Â2Å�xº$A<‘¸r—Èâg¹ôo‹²™2þ˜èç
endstream
endobj
83 0 obj
<</Length 3222/Filter/FlateDecode>>
stream
xœÍ]I�ݸ¾÷¯�==ÉÈé¦YÜ™ñ8ñ$€“i ‡Lö �¶‘1:H~~ …Y$µ´¨¨/ïµêIÅbñãWÅMýsC#€ØæS#­$|¼ú8^ÑæcC»Ï‹¿_üéâóÓ_îþqûþ§»æå»W?7ÐÿxÝ} Ïýô©—ÐæËß.^Þ4´¹ùòô–6@››ÛénM‰‘�îž š›OþæGJé�”ÂøÍÆo>~‹öa†Yc¥»Y¶†pJµ'Qã·F�ê>ôŸwÕ\K6èùÜ
­�R |ñáé7oLk‰VR±Ñð[\'ÆôðË—B5ÆoP…Ò%Óf,Æ{¿¡XZ±š·èQ¶`ðàW
ª•„k –�Öܶ@‰ Œv�–ÞD™Ó/Cm¾Tä'g9‡glÿ€JHÛ^SB)§´t>tð€0N…²ÅêÌø†2�šb+˜lA‹ô<2§Šñ©»ÛK-–Þ@È•ï ”8׬ã3jƺ\æØBë‘—kž\Ó� ši:N1àŠýõ/7¸xssñýnæ“’PÍeÀ|€á %6™i~ÊÃÞ®%±’YGŽ<º3â�þN®|CÉaTSž2ë ™!5®ˆ±g~XÕ‡£Aæ0ƒô{2ž¹‡‡eßa\—˽osŒºïb"‰ûH®<ÊîÄ7O¦÷œ•Iÿqè¬õ˜Ûx®}œ™X)_v6&ȱñîb÷¹þê#œëÇŽnùê’?dÜ0È>ÉêÍ./õCßzKÝ0ÀÂ`MR†0¡lÈ@kÒ)L¹ˆ·×Ï!‰J�ñ…áÄ%òL/€)õ|†îµJgáØ|”«b¤DOîË,V€%SæhÝÄ(õó=œ®®Å,³t7+i=µ,;4ÎQÃÞ²¾ÙófóU\•Õ ¿çŠ'ì°0fØ|ºàìlF“sl9ùÌÁodH_¿ì·qÑ‹ŽY“Œ(5¶ÆG¨·i^�è¦l&�T#9D0¦Y½�›Vi óõw-›íè™8R%c bÅTã7ï^ÅCìNðÿÞ~öìé»W¿ÝÐçÏ_¾^?ò††Åža”ܨÆXb,³zÍè›áßQïñ>³m\÷xàÍBÎÞjC`ÒòÊl‰±×B'ÁV'�ÈÀ'’!B‰ˆ-Õ§W2ÊTæYÌœ¬«•«Ì‹ŸîþýþãÍ_ÿ{÷ìí›·o)}AŸ÷U+JÖqOdüÔïoþÙùªø´¦„k!XîiÐýÓ9w³mîf @ìnEdFi…¶[¤<>^]«€HÆ…£â»w1ï-ÕZ´æ÷û–œé£sÿãïJdó‡)­ˆb²ùÔ0ÆE/~Ø«ÞR"…16PïE»Ô�ÈøAPEwgh¬|”,iÇ8ä;qȘ.t2L×QÈHætÐì”›bs$¿ÒM€Ä5'¢€œúA£úsy•öÎRH}Ó‰¶‚Hì׆È<ŠFÌ8Ré$‹K7î0'¹)6¦ñ/!î׌ØÈŸ’ "„µµk,!€[PÂÙ X¥¿³lì‘O¡t+ôäæ´%Gí‚“,Þ4x,‘”D“¸îZ£™7¤ÆßéEzÆ©?já¢NÀpiý
*ÜÃ"b¯ž)N¬µ{Éþp˜Þ ª¨Æ´ëˆxI9«Ú Ö!ØæÐ:-ð´ ˆ¢ •Ÿ;s€t€SÝ-|Ëa zìéðº ÿÈL]`Âa¾ ó4�óeâ‡}ÿp¿Gýâ^+lt§ƒ"8›bÓW¨rÈΡ^—ÎCeûÌ6ûhÁ>nˆ¤‚N¯Ga|{^|Ï0Ùrbi0Lœ&B*å_‡%H€eÐ~j§ßg‘c`™ 1|ìNx�¹WJ*_ïèÌÃC¿/¾)å—ÝÇTJÙvO*%a‡¦H] æ¦N†ÆÖ 9i�nÅÐ*˜Ä2&§iÇ_µ ˆFðq²´§Ò«�lQøa<Îí¯s�… –î|:—ÂQ¤5�ÄÅñ/Öƒâ˜Ï'9ê:}(ë?|'š™­ƒ*^7†pI™ 2 Ï‚xÛ·À“ðg?PG9¬sŠíùD�¬hËÇK9Çäó§±NãˆÖ“ËœÅ,‡¬+¼l0¸7 ÍÙÔlpå¬.v¯“ÿ• ÷Ê9DslÒ>‰vçÿ�éýuÕ(ð»L`Qy@^'MÈraÐF(wë; Q}ˆ½¡Üm¼« É0êC$£Q*+=Zk–ï¨40líçBkK*�òÈ•ÒÌtyË(¡`%OXM– ¤Ú„�‹$8_"Ø¢I›"\/ãûqðž�w<>Eå`ìãÀéï“hIüzEt“•š(“ø¾:D¡0ô—’¯™4);’/Ì!pÑ2A,eNñþ4pÆ…ªŽ 9H¨ÔÑ^Å,“fqRHÊUS]’ÝŽó1À²€­3Ö:|$túÚ8BU„Û9RWI/A�°Ó1$�`,”c�:¹ßqéÙ ž‘F«@»“ìÎýBÓA Õ8û½ <A‡©’ûeáqÏÜÏô½Ü†r�gzðPü
1n~½%S,N¢VÊ �KÛÁyÔ~&ä¶�*vL'Z�èû‰ÀQS�8¹>ƒDXB ÝJ¶J�ŒH,ZÒós4>Áª(bòA¹�D‚äaò¢ý�b2}¸®¢õQßi—”';Ãh�@‘ƒÈ=…_ l ³sBà(v ÑQû©0ÚD–±c:É”>DòïõMp²Ç¶†—ØI£p3yTYàR‘na(X�‰{u<²0Â~xA`P/-‚Ó`[é$ÚcãAݘ <=,iO€ÂêD™)hÙ8¿œ„·–œ>L8ŒÌCmT.6QòM'Zƒ¶‡Éæ} As%œí´­ùi”n&^%bhJ(�ŒÂЦ»{fY³R9Œãõ𮩠´;Éþ˜>j¨ÆüàcAy‚Q'|`Øì�̪³‰èpÚ„žQû™-¼‰Ý�c:Ñ
=L¾îK˜š"(à\�m ÈI£tk¿®²ŸžA¸èÅÝoüÐ}»bE o­ª5¢õA¹Ñ„Y#ÃQ�í�“éÃuÕˆA<¥,)OÐUg|
¯‡6âuÀðµŸÚÄ›H0vL'Yƒ ‡Hê½þ )‚NöØÖ°;inîØu–¾­!L3Pa¿V…�@xƒCé8U´%uiÓÊÚ]8Á"h²5¨hP¥àtXüèÕ f5 ù¤~íO�ñ½ ŽnÌU޽µ'8®´HŸr<áõmƒæ`5í|~¶¸œ2“F¥¨ôÅ膵¾Ç|×} =Ýñî;¹~“³U|,ˆ²6<+Ìeü‹a-4N/q—NÌ2»-íy¹v¼Îê�`’ÓªþêÝ“5;"££~éÙ¶Cv“žàæ·AýÉ´)@¾�äüp3œ®„°9¦NwÚÖ$
ùi�nŽ>¼Êâ�à–P)ù|~Ó*I³øt…³«×+WpÄÎ)Þ„pСÞ!u»ª“6—× ê #Ì2l‡™D»Ó¦ÐøAPE7f(ÏYKÚàÖYLL‘ûÐÖ �‹€Q4ª?·¡·ð,öM'Ú $^g~Ià˜‰?C=³
½^dñ¤‰ÏÑ[͈–Ü¿º8Þ•{½aÜ0“ÝV:$$#Âðð-öØgI›D§GÊg{¯
íN…2Jí¶É†äô°\j\­<ëË+ìJ ÔðäTÊo n@¯¼IÎæ 9–A~Y<ôü(Ó»fñ=ã“J'u„¶„s#C¢ˆ€°î°Sv¹áÀX?†CÛìK‡Š/ëÜ96÷îKâYPÂÙQgcv�ý4J7Ƕ*s¤Âr”šúðóµ'Ç$1Ò:h½ Œ¯Ž 1Çõ�
åûľ0ÝZ)Å?,ïÕK®»·óÚ½d‚˜Þ ª¨ÆIžKû–”'È­3+š@7øÙD �³YZf«¹hÁ’î?´äË]¯Q<žËµ²§}¿k;œtàÿ¦rü?‡¥™¨[gêVRE”4‹„øÿÚÌ“zÝ·ÏqÃJ^-¾¦(�ýŽRæ)Ÿ+xyáî˸Ìü)èrî™N·ÄM8è}ÒB—Ïeâ³ô†¶Ù®4ÛÁäŠß^K<Á³¶§•q)êLºKF 0ÐÓv´{œÄŽçÂ^%�ðº9µàÄy:ÀÐ…÷Åö\νG!:Ž–-cË1x1÷>²¢×®ü΀ ꀌs"EôODNbö*ÓTµÓz6$[S §&E[ ÈGƒtEæuñýÿ#öº
endstream
endobj
84 0 obj
<</Length 1864/Filter/FlateDecode>>
stream
xœíZÝo5¿¿b[Z`KãÌŒ¿EUDÚR@êC!”‡¦R©­h‰Ý®í³g×{{=G)‚—ÝÄg�çó73ö~è s
…ïÞuÚk!ÃoÃнí`ûÜü±ùeóþôÛ«ë?/_¿¹îÎ^<Ù|èpøñdû×½y7Œ@wõûæì¼ƒîüêô:„îür7Û‚pº³ÛØ�¿ûõËWð
ÛÂ[†·êOP rä�×q²î��Öa1ámÙò‘ÜÅð¼®�–VÓHç}¯„ôJK$FåÞÅ»ß3½ÖhC�ñK.‘¹ªˆÞh*»k².ìŽa.Axcu·ª˜—l)íaxÔ+ éµ�ÁËÀÍe� ¬"t6m: (Ò×9µ´+SB'É”#gx¿`;LÛŸ€� Ñê¨ÃÈ€ìIPÆWÅYÐ �b&Á’ Ò=j‘Übêô²`§âaÕuáÛû,6�‘¹PÜ?ºÐÔ�çÌÖ˜}ØúžÁBë=oÎ<s¦Nµ`: ÜáªñúÛù�›gç›—G#ŸÖ¬Ôò!wo¬¡É‚ùAæÑnµðš|GYÌ,0d˜)M2”î‘�9EÖ0cdâ!2/VÅÐÈ4ê9Ÿaô/Ì‘ùÞ×ܯëû~¬9íëHÊ™Ûh‚�|ò.ÁTó^är?‘;Ë=Ç„½6^²Od“•û•Í2ïºT_Œ×”ábG¸•«w¾˜QÃ8ö>ûûj–î<àÊZ&ëí ÃÌ'˜ ã)ãsZSNqÈe¸=Qý’'Ià\ÚŒ.…f†¹ˆ®ùÄæz£Tä0˜Bމ¤©fJ¶ò¸Êb…³Ìì¸Ûa+ýR„Ãj)‘e;ÙhŸ e¿BË5�–õfÏØ[¬W¹(« þ„5L8‚Écææ³eÏV4sŠ­Ÿsî2É7Û!pWµ‘uRM™­§ñàêý´®žÐC2~&‘49‡BäeÖ ã®7VHGIþhÙÙ@ŸÉ#M*¶,Wì$~öâIÙbo~þëõûG�N_<ùái�Ÿ=]ßyc‡8£‡B’42Gÿ�«g3¦Ü ”`Á“Tº%ç�åÜÝ!á@c‘·dO ½NÕ*i†w·�“^‚°-†�*ú´{ÛÇgq}^±×LãfÁdKþô¼¡»¿ƒµp5uï:´ d>ôvóó±äÉ «=éŒ|:Š<
,˜šÐÞ2Z#û¨s‡£#n[ŽÍyÜýèë%p� 9¸’*½eœù¸\&-û?V±T�R “Ú§ä‚UzO'ÉI „Þâ|„þX­ŒþüpûÐs¼îÎ.&ã12Ð#ylD ñ<$4)¡Z…D¤ŸÅD¤»~»Šú–Uš(‡�
Ù†+ɹßÝ„ÞÆ ä A8Ò&#¿:B3æ‡�6´¹ãEWÜK�;‹j¡oY„ÐØÝeí¾\‡P±ÏKÈÄ΋ùºtbYa&õ�ü]á+ !÷|µVÒmô®•@fwÁ2ŠÖ¯T¤êI $CÑ/%�(ŦJÙ{AÖÆ'syK°D¢óI÷æVÄ-ËS¡0IÖµhÚhÑX¡�+ke®Èáù`�Nï$䢰¹¼ÈE²mDr( ìò«Êh¢ÜõFYYcéïi¡ìwm8öJ(%ÍCˆâøÑ£F9%Cwú�9*‹ÅVUO.¸o"8�΢Þyß7½ÑB‘çGpàãå¤U]vcuÓH?O´�þ-'ÃCê2¦:<Õ"´(̈PXïÉ'wyž;Ç�´©ëIºmSŸÝ\5’'%¬–ÒgäÓÐÑõYÎü8Є6wÀä’û¨OœÛ€ÌÄkR>`E<VÓú×EÆæbôªX9±V€Ÿ}‚ègÎéß®C€Q\9ôîFM0JjaÉ•ÍãÙÍö‰7y FHônG=��BëÃ@ÒÜâÏí#>q
Ùƒ&^ñ“¸Ü$b›îœ”¨•ÕÿÑ.Û4ÛdHhGŸD—ˆm:_²Fý‹š.lÓ “óBIëM£®«`±MG,�„3ÚrÛÄïJéÖªÒº±Jh¤Ÿ¥Ó@þVsÞ!eÓ žP<9 ù;^iPX«|~É+�ÇhvžIå§d's¯‹�=Tþ9H
êt\¹¯ü¾½î²B[«tºîb7�A¶}™K²/ Τ¨Í-ºtJP‚ö@¤ßEé�§ÛÇÓý`Ï;Þà�L¿º(3ãªd'}ÎxÜåg4Âj“¾YÓ½#Ã�¿™¿Ë,^‘¿¯hæáêþ²³îãì´ÿ’·ä¶FiÉ€ÑVfrñ[Ò¨Øvž‘FjÄÿb•ÂÂÛ„�wÂj£TŠ»=Sª˜¢XPÌ+PÔ+Ø–w'gkŒÔ¡wL™¡‹Û¬¹ûqÍ€�üÆiøåÑò›ˆ/×¶â=Ê~¹(ùx—[àlOl6UÑý0çZª£Ïd† R()›Õú« ðÍËT¦.¼
endstream
endobj
85 0 obj
<</Length 748/Filter/FlateDecode>>
stream
xœ­WMoÛ0 ½ûWè8ª’¢õu\‹^ôP ÀëK�tÚ üÿ1$–™’l£í%JlФøŸ˜w (½xÚkIá×KøâEÀé³ûÛýìÞ®¿Ç‡?O£¸¹¿íÞž_^�–ißÓëù ˆãsw³ vÇë±;\¬-H§…=í@±{ýõí0¬*¬Ö¡¿ÂA*§¼ó:ëÞI°ãV˶OîöçϱᚬV“Ÿ·~�äM¨˜c¤ÕÍ—w)™ÞKk´Q!ñ?“Rvzsl#¬hѵ².DÇ`« ¬ØŒÖ<æ�mU+ Ou4½–d<…l=‚´ƒBg#h¥¨è_çÞRTV„ø\+Urß³Eaû+�­Ž5Œ P�(Á`|ó8 µ50Hpž…Ò=j™hQ’žfé4Hv�3n¯!VZdŠñ#…J×` {ÌB=l;f@h;ójðÔ ¤Z€Ž€®Ù¯¿w?º»]÷ðiåÓZ‚%�)rzcKMàÊ»ÝjéµòQif9Ó�³%™”îQI¨TÖ1cnbˆÐ™ûM=4%�ºÆæ?‰ñ‚ å±GÎëvÜ�Â|�s!™÷H-¨B;¹ñå‚iÞ{1Ë¢b¶š=ׄUŒ—ð‰ir§´^l.�¼q^¾Ø¯é†‹}å–6GÞWÊ0={˾«~ë‚K­>Lè­µaÆ ÆÁ¯ 㤌ÏhË8Å%—évQú%&‘p.ãƒË¬2g[D×ê|Ål½†˜a€‚¦‹È4oJ¶ós“ŲTb†ì.ZÁF¿Ôá°ù‹Êr26Ú'iY/è|FÍ»e;ìYz‹ó*?Êæ�?iEK>‘aAÌ>Û(vu¢©¶=|Öè2�¯ú�cܬbTÖb"*“m_ã�ê}9WþP_¹H¾LäÊAA>f�k,zc%9•Α­6zå™óâƒ[vW\N|w;ÿ‹}wÛ=ü !�Ý
endstream
endobj
86 0 obj
<</Author(Sam)/Creator(WordCraft)/Producer(WordCraft)/ModDate(D:20260720170600Z)/CreationDate(D:20260720170600Z)>>
endobj
87 0 obj
<</Length 1100/Type/Metadata/Subtype/XML>>
stream
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="xmp-writer"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:xmpTPg="http://ns.adobe.com/xap/1.0/t/pg/" xmlns:pdf="http://ns.adobe.com/pdf/1.3/" ><dc:creator><rdf:Seq><rdf:li>Sam</rdf:li></rdf:Seq></dc:creator><xmp:CreatorTool>WordCraft</xmp:CreatorTool><pdf:Producer>WordCraft</pdf:Producer><dc:language><rdf:Bag><rdf:li>fr-FR</rdf:li></rdf:Bag></dc:language><xmp:ModifyDate>2026-07-20T17:06:00+00:00</xmp:ModifyDate><xmp:CreateDate>2026-07-20T17:06:00+00:00</xmp:CreateDate><xmpTPg:NPages>3</xmpTPg:NPages><dc:format>application/pdf</dc:format><xmpMM:InstanceID>5huk5Pe6LZDwfze+e1IvaA==</xmpMM:InstanceID><xmpMM:DocumentID>5huk5Pe6LZDwfze+e1IvaA==</xmpMM:DocumentID><xmpMM:RenditionClass>default</xmpMM:RenditionClass><pdf:PDFVersion>1.7</pdf:PDFVersion></rdf:Description></rdf:RDF></x:xmpmeta><?xpacket end="r"?>
endstream
endobj
88 0 obj
<</Type/Catalog/Pages 1 0 R/Metadata 87 0 R/Lang(fr-FR)/StructTreeRoot 2 0 R/MarkInfo<</Marked true/Suspects false>>>>
endobj
xref
0 89
0000000000 65535 f
0000000016 00000 n
0000000082 00000 n
0000000254 00000 n
0000000560 00000 n
0000000738 00000 n
0000000802 00000 n
0000000866 00000 n
0000000930 00000 n
0000000994 00000 n
0000001058 00000 n
0000001123 00000 n
0000001190 00000 n
0000001255 00000 n
0000001320 00000 n
0000001392 00000 n
0000001458 00000 n
0000001527 00000 n
0000001593 00000 n
0000001659 00000 n
0000001725 00000 n
0000001791 00000 n
0000001857 00000 n
0000001923 00000 n
0000001989 00000 n
0000002055 00000 n
0000002121 00000 n
0000002187 00000 n
0000002253 00000 n
0000002319 00000 n
0000002388 00000 n
0000002454 00000 n
0000002520 00000 n
0000002586 00000 n
0000002661 00000 n
0000002727 00000 n
0000002793 00000 n
0000002865 00000 n
0000002930 00000 n
0000002995 00000 n
0000003060 00000 n
0000003125 00000 n
0000003190 00000 n
0000003255 00000 n
0000003320 00000 n
0000003385 00000 n
0000003450 00000 n
0000003515 00000 n
0000003581 00000 n
0000003647 00000 n
0000003713 00000 n
0000003779 00000 n
0000003845 00000 n
0000003911 00000 n
0000003977 00000 n
0000004043 00000 n
0000004109 00000 n
0000004175 00000 n
0000004247 00000 n
0000004684 00000 n
0000004777 00000 n
0000004870 00000 n
0000004943 00000 n
0000005080 00000 n
0000005785 00000 n
0000006023 00000 n
0000006161 00000 n
0000007435 00000 n
0000007666 00000 n
0000007801 00000 n
0000008416 00000 n
0000008642 00000 n
0000008761 00000 n
0000008880 00000 n
0000008983 00000 n
0000009065 00000 n
0000009657 00000 n
0000016938 00000 n
0000017019 00000 n
0000017771 00000 n
0000028500 00000 n
0000028581 00000 n
0000029151 00000 n
0000035464 00000 n
0000038756 00000 n
0000040690 00000 n
0000041507 00000 n
0000041638 00000 n
0000042815 00000 n
trailer
<</Size 89/Root 88 0 R/Info 86 0 R/ID[(5huk5Pe6LZDwfze+e1IvaA==)(5huk5Pe6LZDwfze+e1IvaA==)]>>
startxref
42950
%%EOF