mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
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:
1 parent
097d4b521e
commit
d4d5d77d71
41 files changed
+4897
-1534
No files matched your search
-141
@@ -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`.
|
||||
-6
@@ -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
|
||||
}
|
||||
@@ -93,7 +93,7 @@ googleServices { missingGoogleServicesStrategy = MissingGoogleServicesStrategy.W
|
||||
// This makes it easy to add them back in the future if needed.
|
||||
dependencies {
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(platform(libs.firebase.bom))
|
||||
// implementation(platform(libs.firebase.bom))
|
||||
// implementation(libs.accompanist.permissions)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
// implementation(libs.androidx.camera.camera2)
|
||||
@@ -117,14 +117,14 @@ dependencies {
|
||||
implementation(libs.coil.compose)
|
||||
// implementation(libs.converter.moshi)
|
||||
// implementation(libs.firebase.ai)
|
||||
implementation(libs.firebase.firestore)
|
||||
implementation(libs.firebase.auth)
|
||||
implementation(libs.androidx.credentials)
|
||||
implementation(libs.androidx.credentials.play.services)
|
||||
implementation(libs.googleid)
|
||||
// implementation(libs.firebase.firestore)
|
||||
// implementation(libs.firebase.auth)
|
||||
// implementation(libs.androidx.credentials)
|
||||
// implementation(libs.androidx.credentials.play.services)
|
||||
// implementation(libs.googleid)
|
||||
implementation(libs.play.services.auth)
|
||||
implementation(libs.firebase.appcheck.recaptcha)
|
||||
implementation(libs.firebase.appcheck.debug)
|
||||
// implementation(libs.firebase.appcheck.recaptcha)
|
||||
// implementation(libs.firebase.appcheck.debug)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.logging.interceptor)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.example
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
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.windowInsetsPadding
|
||||
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.Restaurant
|
||||
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.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.example.ui.common.UiEvent
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
@@ -53,34 +54,39 @@ import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.model.RecipeEntry
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.auth.AuthScreen
|
||||
import com.example.ui.common.UiEvent
|
||||
import com.example.ui.journal.JournalScreen
|
||||
import com.example.ui.journal.MealViewModel
|
||||
import com.example.ui.journal.MealsUiState
|
||||
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.stats.WeeklyStatsScreen
|
||||
import com.example.ui.theme.SatieaTheme
|
||||
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.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import com.google.firebase.auth.auth
|
||||
import com.example.widget.SatieaAppWidgetProvider
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.LocalTime
|
||||
|
||||
enum class MainTab(val title: String) {
|
||||
JOURNAL("Journal"),
|
||||
RECIPES("Recettes"),
|
||||
STATS("Statistiques"),
|
||||
SETTINGS("Réglages")
|
||||
}
|
||||
|
||||
private enum class PendingDriveAction {
|
||||
SYNC,
|
||||
RESTORE
|
||||
}
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
private val viewModel: MealViewModel by viewModels()
|
||||
@@ -113,7 +119,7 @@ class MainActivity : ComponentActivity() {
|
||||
if (intent?.action == MealNotificationManager.ACTION_LOG_MEAL) {
|
||||
val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
|
||||
MealType.fromString(it)
|
||||
} ?: SatieaAppWidgetProvider.suggestMealTypeForHour(java.time.LocalTime.now().hour)
|
||||
} ?: SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
|
||||
viewModel.requestQuickLogMeal(parsedType)
|
||||
}
|
||||
}
|
||||
@@ -124,21 +130,13 @@ class MainActivity : ComponentActivity() {
|
||||
fun AppRoot(
|
||||
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 pendingDriveAction by remember { mutableStateOf<PendingDriveAction?>(null) }
|
||||
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
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) {
|
||||
viewModel.uiEvents.collect { event ->
|
||||
@@ -158,10 +156,17 @@ fun AppRoot(
|
||||
}
|
||||
|
||||
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 editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
||||
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
|
||||
val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(quickLogMealType) {
|
||||
@@ -241,6 +246,7 @@ fun AppRoot(
|
||||
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
|
||||
val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
|
||||
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
|
||||
val recipes by viewModel.recipes.collectAsStateWithLifecycle()
|
||||
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
||||
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
|
||||
val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
|
||||
@@ -293,22 +299,31 @@ fun AppRoot(
|
||||
val sheetsAuthConsentLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
googleAccount = GoogleSheetsAuthHelper.getSignedInAccount(context)
|
||||
val actionToRun = pendingDriveAction
|
||||
pendingDriveAction = null
|
||||
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
viewModel.syncToGoogleSheets()
|
||||
when (actionToRun) {
|
||||
PendingDriveAction.RESTORE -> viewModel.restoreFromGoogleSheets()
|
||||
PendingDriveAction.SYNC, null -> viewModel.syncToGoogleSheets()
|
||||
}
|
||||
} else {
|
||||
viewModel.emitEvent(UiEvent.ShowSnackbar("Autorisation Google Sheets annulée"))
|
||||
viewModel.emitEvent(UiEvent.ShowSnackbar("Autorisation Google Drive annulée"))
|
||||
}
|
||||
}
|
||||
|
||||
val triggerGoogleSheetsSync = {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
if (email.isNullOrBlank()) {
|
||||
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)
|
||||
}
|
||||
)
|
||||
@@ -316,14 +331,16 @@ fun AppRoot(
|
||||
}
|
||||
|
||||
val triggerGoogleSheetsRestore = {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
if (email.isNullOrBlank()) {
|
||||
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)
|
||||
}
|
||||
)
|
||||
@@ -368,11 +385,23 @@ fun AppRoot(
|
||||
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("Statistiques") },
|
||||
label = { Text("Stats") },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
indicatorColor = MaterialTheme.colorScheme.primaryContainer
|
||||
@@ -403,9 +432,10 @@ fun AppRoot(
|
||||
MainTab.JOURNAL -> {
|
||||
JournalScreen(
|
||||
mealsUiState = mealsState,
|
||||
customFoods = customFoods,
|
||||
onAddMealClick = {
|
||||
editingMeal = null
|
||||
defaultMealType = MealType.LUNCH
|
||||
defaultMealType = SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
|
||||
showMealEntrySheet = true
|
||||
},
|
||||
onEditMeal = { meal ->
|
||||
@@ -425,6 +455,20 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
MainTab.RECIPES -> {
|
||||
RecipesScreen(
|
||||
recipes = recipes,
|
||||
customFoods = customFoods,
|
||||
onAddRecipeClick = {
|
||||
editingRecipe = null
|
||||
showRecipeEditor = true
|
||||
},
|
||||
onRecipeClick = { recipe ->
|
||||
selectedRecipeId = recipe.id
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
MainTab.STATS -> {
|
||||
WeeklyStatsScreen(
|
||||
weeklyStats = weeklyStats,
|
||||
@@ -437,6 +481,7 @@ fun AppRoot(
|
||||
|
||||
MainTab.SETTINGS -> {
|
||||
SettingsScreen(
|
||||
googleAccount = googleAccount,
|
||||
currentThemeMode = themeMode,
|
||||
totalMealsCount = currentMealsList.size,
|
||||
sheetsUiState = sheetsUiState,
|
||||
@@ -461,7 +506,7 @@ fun AppRoot(
|
||||
onSignInClick = { showAuthSheet = true },
|
||||
onSignOut = {
|
||||
viewModel.signOut(context) {
|
||||
currentUser = null
|
||||
googleAccount = null
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -473,8 +518,8 @@ fun AppRoot(
|
||||
initialMeal = editingMeal,
|
||||
defaultMealType = defaultMealType,
|
||||
customFoods = customFoods,
|
||||
onAddCustomFood = { name, unit ->
|
||||
viewModel.addCustomFoodDirectly(name, unit)
|
||||
onAddCustomFood = { name, unit, category ->
|
||||
viewModel.addCustomFoodDirectly(name, unit, category)
|
||||
},
|
||||
onDismiss = {
|
||||
showMealEntrySheet = false
|
||||
@@ -483,7 +528,7 @@ fun AppRoot(
|
||||
onSaveMeal = { type, timestamp, hunger, satiety, note, foodItems, photos ->
|
||||
showMealEntrySheet = false
|
||||
val currentEditing = editingMeal
|
||||
if (currentEditing != null) {
|
||||
if (currentEditing != null && currentEditing.id.isNotBlank()) {
|
||||
viewModel.updateMeal(
|
||||
meal = currentEditing.copy(
|
||||
mealType = type.name,
|
||||
@@ -511,15 +556,75 @@ fun AppRoot(
|
||||
)
|
||||
}
|
||||
|
||||
// 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 = {
|
||||
currentUser = Firebase.auth.currentUser
|
||||
onAuthSuccess = { connectedAccount ->
|
||||
googleAccount = connectedAccount
|
||||
showAuthSheet = false
|
||||
viewModel.syncCloudToLocal()
|
||||
viewModel.emitEvent(
|
||||
UiEvent.ShowSnackbar("Compte Google Drive connecté (${connectedAccount.email}) ✨")
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,8 +12,8 @@ import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.Types
|
||||
|
||||
@Database(
|
||||
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class],
|
||||
version = 3,
|
||||
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class, LocalRecipeEntity::class],
|
||||
version = 4,
|
||||
exportSchema = false
|
||||
)
|
||||
@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 {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it }
|
||||
@@ -104,7 +128,7 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
appContext,
|
||||
AppDatabase::class.java,
|
||||
"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
|
||||
if (BuildConfig.DEBUG) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.example.data.local
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.FoodUnit
|
||||
import java.text.Normalizer
|
||||
|
||||
@@ -11,19 +12,28 @@ data class LocalCustomFoodEntity(
|
||||
@PrimaryKey val slugId: String,
|
||||
val name: String,
|
||||
val defaultUnit: String = FoodUnit.G.code,
|
||||
val category: String = "",
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
fun toCustomFoodEntry(userId: String = ""): CustomFoodEntry {
|
||||
fun toCustomFoodEntry(): CustomFoodEntry {
|
||||
return CustomFoodEntry(
|
||||
id = slugId,
|
||||
userId = userId,
|
||||
name = name,
|
||||
defaultUnit = defaultUnit
|
||||
defaultUnit = defaultUnit,
|
||||
category = category
|
||||
)
|
||||
}
|
||||
|
||||
fun resolvedCategory(): FoodCategory {
|
||||
return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name)
|
||||
}
|
||||
|
||||
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 slugId = Normalizer.normalize(cleanName.lowercase(), Normalizer.Form.NFD)
|
||||
.replace(Regex("[^a-z0-9]+"), "_")
|
||||
@@ -35,6 +45,7 @@ data class LocalCustomFoodEntity(
|
||||
slugId = slugId,
|
||||
name = cleanName,
|
||||
defaultUnit = defaultUnit.code,
|
||||
category = category?.name ?: "",
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
}
|
||||
|
||||
@@ -38,4 +38,22 @@ interface LocalMealDao {
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
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 {
|
||||
return MealEntry(
|
||||
id = id,
|
||||
userId = userId,
|
||||
mealType = mealType,
|
||||
mealTimestamp = mealTimestamp,
|
||||
hungerBefore = hungerBefore,
|
||||
@@ -38,7 +37,7 @@ data class LocalMealEntity(
|
||||
fun fromMealEntry(meal: MealEntry): LocalMealEntity {
|
||||
return LocalMealEntity(
|
||||
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
|
||||
userId = meal.userId,
|
||||
userId = "",
|
||||
mealType = meal.mealType,
|
||||
mealTimestamp = meal.mealTimestamp,
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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(
|
||||
val name: String,
|
||||
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 {
|
||||
val cleanName = name.replace("|", " ").trim()
|
||||
val weightStr = if (weight != null && weight > 0.0) {
|
||||
@@ -30,7 +31,11 @@ data class MealFoodItem(
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "$cleanName|$weightStr|${unit.code}"
|
||||
return if (category != null) {
|
||||
"$cleanName|$weightStr|${unit.code}|${category.code}"
|
||||
} else {
|
||||
"$cleanName|$weightStr|${unit.code}"
|
||||
}
|
||||
}
|
||||
|
||||
fun formatWeight(): String? {
|
||||
@@ -67,25 +72,25 @@ data class MealFoodItem(
|
||||
if (name.isEmpty()) return null
|
||||
val weight = parts.getOrNull(1)?.trim()?.replace(",", ".")?.toDoubleOrNull()
|
||||
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(
|
||||
@DocumentId val id: String = "",
|
||||
val userId: String = "",
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val defaultUnit: String = FoodUnit.G.code,
|
||||
@ServerTimestamp val createdAt: Timestamp? = null,
|
||||
@ServerTimestamp val updatedAt: Timestamp? = null
|
||||
)
|
||||
val category: String = ""
|
||||
) {
|
||||
fun resolvedCategory(): FoodCategory {
|
||||
return FoodCategory.fromCode(category) ?: FoodCategory.inferFromName(name)
|
||||
}
|
||||
}
|
||||
|
||||
@IgnoreExtraProperties
|
||||
data class MealEntry(
|
||||
@DocumentId val id: String = "",
|
||||
val userId: String = "",
|
||||
val id: String = "",
|
||||
val mealType: String = MealType.LUNCH.name,
|
||||
val mealTimestamp: Long = System.currentTimeMillis(),
|
||||
val hungerBefore: Int = 5,
|
||||
@@ -93,9 +98,7 @@ data class MealEntry(
|
||||
val note: String = "",
|
||||
val foodItemsSerialized: List<String> = emptyList(),
|
||||
val photoUris: List<String> = emptyList(),
|
||||
val photosBase64: List<String> = emptyList(),
|
||||
@ServerTimestamp val createdAt: Timestamp? = null,
|
||||
@ServerTimestamp val updatedAt: Timestamp? = null
|
||||
val photosBase64: List<String> = emptyList()
|
||||
) {
|
||||
val displayPhotoUris: List<String>
|
||||
get() = photoUris.ifEmpty { photosBase64 }
|
||||
@@ -103,22 +106,6 @@ data class MealEntry(
|
||||
fun parsedFoodItems(): List<MealFoodItem> {
|
||||
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) {
|
||||
@@ -129,86 +116,119 @@ enum class MealType(val displayName: String, val defaultTime: String) {
|
||||
|
||||
companion object {
|
||||
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 {
|
||||
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(
|
||||
// Féculents & Céréales
|
||||
CatalogFood("Riz basmati", FoodUnit.G),
|
||||
CatalogFood("Riz complet", FoodUnit.G),
|
||||
CatalogFood("Pâtes complètes", FoodUnit.G),
|
||||
CatalogFood("Pâtes", FoodUnit.G),
|
||||
CatalogFood("Quinoa", FoodUnit.G),
|
||||
CatalogFood("Flocons d'avoine", FoodUnit.G),
|
||||
CatalogFood("Pain complet", FoodUnit.G),
|
||||
CatalogFood("Pain au levain", FoodUnit.G),
|
||||
CatalogFood("Patate douce", FoodUnit.G),
|
||||
CatalogFood("Pommes de terre", FoodUnit.G),
|
||||
CatalogFood("Semoule", FoodUnit.G),
|
||||
CatalogFood("Lentilles corail", FoodUnit.G),
|
||||
CatalogFood("Lentilles vertes", FoodUnit.G),
|
||||
CatalogFood("Pois chiches", FoodUnit.G),
|
||||
CatalogFood("Haricots rouges", FoodUnit.G),
|
||||
// Protéines
|
||||
CatalogFood("Blanc de poulet", FoodUnit.G),
|
||||
CatalogFood("Filet de dinde", FoodUnit.G),
|
||||
CatalogFood("Pavé de saumon", FoodUnit.G),
|
||||
CatalogFood("Cabillaud", FoodUnit.G),
|
||||
CatalogFood("Thon", FoodUnit.G),
|
||||
CatalogFood("Œufs", FoodUnit.PORTION),
|
||||
CatalogFood("Tofu ferme", FoodUnit.G),
|
||||
CatalogFood("Steak haché", FoodUnit.G),
|
||||
CatalogFood("Jambon blanc", FoodUnit.G),
|
||||
CatalogFood("Crevettes", FoodUnit.G),
|
||||
// Légumes
|
||||
CatalogFood("Brocoli", FoodUnit.G),
|
||||
CatalogFood("Courgettes", FoodUnit.G),
|
||||
CatalogFood("Haricots verts", FoodUnit.G),
|
||||
CatalogFood("Épinards", FoodUnit.G),
|
||||
CatalogFood("Tomates", FoodUnit.G),
|
||||
CatalogFood("Concombre", FoodUnit.G),
|
||||
CatalogFood("Carottes râpées", FoodUnit.G),
|
||||
CatalogFood("Salade verte", FoodUnit.G),
|
||||
CatalogFood("Avocat", FoodUnit.PORTION),
|
||||
CatalogFood("Poivrons", FoodUnit.G),
|
||||
CatalogFood("Champignons", FoodUnit.G),
|
||||
CatalogFood("Aubergine", FoodUnit.G),
|
||||
CatalogFood("Chou-fleur", FoodUnit.G),
|
||||
// Produits laitiers & Alternatives
|
||||
CatalogFood("Fromage blanc", FoodUnit.G),
|
||||
CatalogFood("Skyr", FoodUnit.G),
|
||||
CatalogFood("Yaourt nature", FoodUnit.PORTION),
|
||||
CatalogFood("Comté", FoodUnit.G),
|
||||
CatalogFood("Feta", FoodUnit.G),
|
||||
CatalogFood("Mozzarella", FoodUnit.G),
|
||||
CatalogFood("Lait demi-écrémé", FoodUnit.ML),
|
||||
CatalogFood("Lait d'amande", FoodUnit.ML),
|
||||
CatalogFood("Lait d'avoine", FoodUnit.ML),
|
||||
// Fruits & Oléagineux
|
||||
CatalogFood("Pomme", FoodUnit.PORTION),
|
||||
CatalogFood("Banane", FoodUnit.PORTION),
|
||||
CatalogFood("Poire", FoodUnit.PORTION),
|
||||
CatalogFood("Fraises", FoodUnit.G),
|
||||
CatalogFood("Myrtilles", FoodUnit.G),
|
||||
CatalogFood("Framboises", FoodUnit.G),
|
||||
CatalogFood("Kiwi", FoodUnit.PORTION),
|
||||
CatalogFood("Orange", FoodUnit.PORTION),
|
||||
CatalogFood("Amandes", FoodUnit.G),
|
||||
CatalogFood("Noix", FoodUnit.G),
|
||||
CatalogFood("Noix de cajou", FoodUnit.G),
|
||||
CatalogFood("Beurre de cacahuète", FoodUnit.G),
|
||||
CatalogFood("Chocolat noir", FoodUnit.G),
|
||||
// Boissons & Soupes
|
||||
CatalogFood("Soupe de légumes", FoodUnit.ML),
|
||||
CatalogFood("Café", FoodUnit.ML),
|
||||
CatalogFood("Thé vert", FoodUnit.ML),
|
||||
CatalogFood("Jus d'orange pressé", FoodUnit.ML),
|
||||
CatalogFood("Smoothie", FoodUnit.ML)
|
||||
// Viande, poisson, œufs (Rouge)
|
||||
CatalogFood("Blanc de poulet", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Filet de dinde", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Pavé de saumon", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Cabillaud", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Thon", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Œufs", FoodUnit.PORTION, FoodCategory.PROTEIN),
|
||||
CatalogFood("Tofu ferme", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Steak haché", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Jambon blanc", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
CatalogFood("Crevettes", FoodUnit.G, FoodCategory.PROTEIN),
|
||||
|
||||
// Légumes (Vert)
|
||||
CatalogFood("Brocoli", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Courgettes", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Haricots verts", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Épinards", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Tomates", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Concombre", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Carottes râpées", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Salade verte", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Avocat", FoodUnit.PORTION, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Poivrons", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Champignons", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Aubergine", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Chou-fleur", FoodUnit.G, FoodCategory.VEGETABLE),
|
||||
CatalogFood("Soupe de légumes", FoodUnit.ML, FoodCategory.VEGETABLE),
|
||||
|
||||
// Féculents & Légumineuses (Ambre doré)
|
||||
CatalogFood("Riz basmati", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Riz complet", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Pâtes complètes", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Pâtes", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Quinoa", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Flocons d'avoine", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Patate douce", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Pommes de terre", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Semoule", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Lentilles corail", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Lentilles vertes", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Pois chiches", FoodUnit.G, FoodCategory.STARCH),
|
||||
CatalogFood("Haricots rouges", FoodUnit.G, FoodCategory.STARCH),
|
||||
|
||||
// Pain (Ocre blé)
|
||||
CatalogFood("Pain complet", FoodUnit.G, FoodCategory.BREAD),
|
||||
CatalogFood("Pain au levain", FoodUnit.G, FoodCategory.BREAD),
|
||||
CatalogFood("Baguette tradition", FoodUnit.PORTION, FoodCategory.BREAD),
|
||||
CatalogFood("Tranche de pain", FoodUnit.PORTION, FoodCategory.BREAD),
|
||||
|
||||
// Fromage (Blanc ivoire)
|
||||
CatalogFood("Comté", FoodUnit.G, FoodCategory.CHEESE),
|
||||
CatalogFood("Feta", FoodUnit.G, FoodCategory.CHEESE),
|
||||
CatalogFood("Mozzarella", FoodUnit.G, FoodCategory.CHEESE),
|
||||
CatalogFood("Chèvre frais", FoodUnit.G, FoodCategory.CHEESE),
|
||||
CatalogFood("Camembert", FoodUnit.G, FoodCategory.CHEESE),
|
||||
|
||||
// Yaourt & Fromage blanc (Bleu lacté)
|
||||
CatalogFood("Fromage blanc", FoodUnit.G, FoodCategory.DAIRY),
|
||||
CatalogFood("Skyr", FoodUnit.G, FoodCategory.DAIRY),
|
||||
CatalogFood("Yaourt nature", FoodUnit.PORTION, FoodCategory.DAIRY),
|
||||
CatalogFood("Lait demi-écrémé", FoodUnit.ML, FoodCategory.DAIRY),
|
||||
CatalogFood("Lait d'amande", FoodUnit.ML, FoodCategory.DAIRY),
|
||||
CatalogFood("Lait d'avoine", FoodUnit.ML, FoodCategory.DAIRY),
|
||||
|
||||
// Fruits (Corail)
|
||||
CatalogFood("Pomme", FoodUnit.PORTION, FoodCategory.FRUIT),
|
||||
CatalogFood("Banane", FoodUnit.PORTION, FoodCategory.FRUIT),
|
||||
CatalogFood("Poire", FoodUnit.PORTION, FoodCategory.FRUIT),
|
||||
CatalogFood("Fraises", FoodUnit.G, FoodCategory.FRUIT),
|
||||
CatalogFood("Myrtilles", FoodUnit.G, FoodCategory.FRUIT),
|
||||
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.net.Uri
|
||||
import android.util.Log
|
||||
import com.example.R
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.local.LocalCustomFoodEntity
|
||||
import com.example.data.local.LocalMealDao
|
||||
import com.example.data.local.LocalMealEntity
|
||||
import com.example.data.local.LocalRecipeEntity
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.RecipeEntry
|
||||
import com.example.util.CsvImportResult
|
||||
import com.example.util.CsvImporter
|
||||
import com.example.util.ImageUtils
|
||||
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.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.tasks.await
|
||||
import java.text.Normalizer
|
||||
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(
|
||||
private val localMealDao: LocalMealDao?,
|
||||
private val db: FirebaseFirestore?,
|
||||
private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth,
|
||||
private val localMealDao: LocalMealDao,
|
||||
private val context: Context? = null
|
||||
) {
|
||||
|
||||
// Constructor used by ViewModel in app runtime
|
||||
constructor(context: Context) : this(
|
||||
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
|
||||
)
|
||||
|
||||
// Secondary constructor for Firestore rule tests without local DB
|
||||
constructor(db: FirebaseFirestore) : this(
|
||||
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.")
|
||||
}
|
||||
// ------------------------------------------------------------------------
|
||||
// Meals
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
fun observeMeals(): Flow<List<MealEntry>> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.observeAllMeals().map { entities ->
|
||||
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>> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.observeAllCustomFoods().map { entities ->
|
||||
entities.map { it.toCustomFoodEntry(getUserIdOrNull().orEmpty()) }
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
suspend fun getMealById(mealId: String): Result<MealEntry> {
|
||||
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)
|
||||
return if (local != null) {
|
||||
Result.success(local.toMealEntry())
|
||||
} 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> {
|
||||
val resolvedId = meal.id.ifBlank { "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}" }
|
||||
val resolvedId = meal.id.ifBlank {
|
||||
"meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}"
|
||||
}
|
||||
val mealWithId = meal.copy(id = resolvedId)
|
||||
|
||||
// 1. Always save to local SQLite Room first (Offline-First)
|
||||
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId))
|
||||
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}")
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(resolvedId)
|
||||
}
|
||||
|
||||
suspend fun updateMeal(meal: MealEntry): Result<Unit> {
|
||||
require(meal.id.isNotBlank()) { "Meal ID must not be blank for update" }
|
||||
|
||||
// 1. Update in local Room database
|
||||
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal))
|
||||
localMealDao.insertMeal(LocalMealEntity.fromMealEntry(meal))
|
||||
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)
|
||||
}
|
||||
|
||||
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 ->
|
||||
if (context != null) {
|
||||
ImageUtils.deletePhotoFile(context, uri)
|
||||
@@ -279,116 +81,110 @@ class MealRepository(
|
||||
ImageUtils.deletePhotoFile(uri)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Delete from local Room database
|
||||
localMealDao?.deleteMealById(mealId)
|
||||
localMealDao.deleteMealById(mealId)
|
||||
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)
|
||||
}
|
||||
|
||||
suspend fun getAllMealsSnapshot(): List<MealEntry> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.getAllMealsOnce().map { it.toMealEntry() }
|
||||
}
|
||||
val uid = getUserIdOrNull() ?: return emptyList()
|
||||
val firestore = db ?: return emptyList()
|
||||
return try {
|
||||
firestore.collection("users").document(uid).collection("meals")
|
||||
.orderBy("mealTimestamp", Query.Direction.DESCENDING)
|
||||
.get()
|
||||
.await()
|
||||
.toObjects(MealEntry::class.java)
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Custom Foods Catalog
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
fun observeCustomFoods(): Flow<List<CustomFoodEntry>> {
|
||||
return localMealDao.observeAllCustomFoods().map { entities ->
|
||||
entities.map { it.toCustomFoodEntry() }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveCustomFood(
|
||||
name: String,
|
||||
defaultUnit: FoodUnit,
|
||||
category: FoodCategory? = null
|
||||
): 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, category)
|
||||
localMealDao.insertCustomFood(localEntity)
|
||||
return Result.success(localEntity.slugId)
|
||||
}
|
||||
|
||||
suspend fun getAllCustomFoodsSnapshot(): List<LocalCustomFoodEntity> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.getAllCustomFoodsOnce()
|
||||
}
|
||||
val uid = getUserIdOrNull() ?: return emptyList()
|
||||
val firestore = db ?: return emptyList()
|
||||
return try {
|
||||
firestore.collection("users").document(uid).collection("custom_foods")
|
||||
.orderBy("name", Query.Direction.ASCENDING)
|
||||
.get()
|
||||
.await()
|
||||
.toObjects(CustomFoodEntry::class.java)
|
||||
.map {
|
||||
LocalCustomFoodEntity(
|
||||
slugId = it.id,
|
||||
name = it.name,
|
||||
defaultUnit = it.defaultUnit
|
||||
)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Recipes
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
fun observeRecipes(): Flow<List<RecipeEntry>> {
|
||||
return localMealDao.observeAllRecipes().map { entities ->
|
||||
entities.map { it.toRecipeEntry() }
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
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()
|
||||
|
||||
// 1. Insert new meals into Room
|
||||
val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) }
|
||||
localMealDao?.insertMeals(localEntities)
|
||||
localMealDao.insertMeals(localEntities)
|
||||
SatieaAppWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
// 2. Enrich custom foods catalog in Room
|
||||
val newCustomFoods = result.newFoodItems.map { item ->
|
||||
LocalCustomFoodEntity.create(item.name, item.unit)
|
||||
}
|
||||
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()
|
||||
LocalCustomFoodEntity.create(
|
||||
name = item.name,
|
||||
defaultUnit = item.unit,
|
||||
category = item.category ?: FoodCategory.inferFromName(item.name)
|
||||
)
|
||||
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}")
|
||||
}
|
||||
}
|
||||
if (newCustomFoods.isNotEmpty()) {
|
||||
localMealDao.insertCustomFoods(newCustomFoods)
|
||||
}
|
||||
|
||||
Result.success(result)
|
||||
@@ -398,69 +194,30 @@ class MealRepository(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun syncCloudToLocal(): 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 {
|
||||
// 1. Fetch remote meals
|
||||
val remoteMealsSnapshot = firestore.collection("users").document(uid).collection("meals").get().await()
|
||||
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(
|
||||
/**
|
||||
* Merges restored meals, custom foods, and recipes from Google Sheets into Room
|
||||
* without duplicating existing entries.
|
||||
*
|
||||
* @return Triple(newMealsCount, newFoodsCount, newRecipesCount)
|
||||
*/
|
||||
suspend fun insertRestoredData(
|
||||
meals: List<MealEntry>,
|
||||
foods: List<LocalCustomFoodEntity>
|
||||
): Pair<Int, Int> {
|
||||
foods: List<LocalCustomFoodEntity>,
|
||||
recipes: List<RecipeEntry> = emptyList()
|
||||
): Triple<Int, Int, Int> {
|
||||
var newMealsCount = 0
|
||||
var newFoodsCount = 0
|
||||
if (localMealDao != null) {
|
||||
val existing = localMealDao.getAllMealsOnce()
|
||||
val existingFingerprints = existing.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }.toSet()
|
||||
var newRecipesCount = 0
|
||||
|
||||
// 1. Merge meals (deduplicate by type + minute bucket)
|
||||
val existingMeals = localMealDao.getAllMealsOnce()
|
||||
val existingFingerprints = existingMeals
|
||||
.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }
|
||||
.toMutableSet()
|
||||
val toInsertMeals = mutableListOf<LocalMealEntity>()
|
||||
for (m in meals) {
|
||||
val fp = "${m.mealType.uppercase()}_${m.mealTimestamp / 60_000}"
|
||||
if (fp !in existingFingerprints) {
|
||||
if (existingFingerprints.add(fp)) {
|
||||
toInsertMeals.add(LocalMealEntity.fromMealEntry(m))
|
||||
newMealsCount++
|
||||
}
|
||||
@@ -470,72 +227,44 @@ class MealRepository(
|
||||
SatieaAppWidgetProvider.updateAllWidgets(context)
|
||||
}
|
||||
|
||||
val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet()
|
||||
// 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) {
|
||||
if (f.name.lowercase().trim() !in existingFoods) {
|
||||
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++
|
||||
}
|
||||
return Pair(newMealsCount, newFoodsCount)
|
||||
}
|
||||
if (toInsertRecipes.isNotEmpty()) {
|
||||
localMealDao.insertRecipes(toInsertRecipes)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
return Triple(newMealsCount, newFoodsCount, newRecipesCount)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
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.repository.MealRepository
|
||||
import com.example.util.AuthExpiredException
|
||||
@@ -19,13 +21,25 @@ import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
|
||||
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 Failure(val message: String) : SheetsSyncResult
|
||||
}
|
||||
|
||||
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 Failure(val message: String) : SheetsRestoreResult
|
||||
}
|
||||
@@ -111,19 +125,21 @@ class GoogleSheetsSyncUseCase(
|
||||
sheetsPrefs.spreadsheetId = id
|
||||
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 currentRecipes = repository.getAllRecipesSnapshot()
|
||||
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()
|
||||
var syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
|
||||
accessToken = token,
|
||||
spreadsheetId = id,
|
||||
meals = currentMeals,
|
||||
foods = currentFoods,
|
||||
recipes = currentRecipes,
|
||||
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
|
||||
)
|
||||
|
||||
@@ -137,6 +153,7 @@ class GoogleSheetsSyncUseCase(
|
||||
spreadsheetId = id,
|
||||
meals = currentMeals,
|
||||
foods = currentFoods,
|
||||
recipes = currentRecipes,
|
||||
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
|
||||
)
|
||||
}
|
||||
@@ -147,20 +164,32 @@ class GoogleSheetsSyncUseCase(
|
||||
sheetsPrefs.lastSyncTimestamp = res.timestamp
|
||||
sheetsPrefs.lastSyncCount = res.mealsCount
|
||||
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 {
|
||||
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation"
|
||||
SheetsSyncResult.Failure(err)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun uploadMealPhotosQuietly(
|
||||
private suspend fun uploadPhotosQuietly(
|
||||
accessToken: String,
|
||||
photosFolderId: String,
|
||||
meals: List<com.example.data.model.MealEntry>
|
||||
meals: List<MealEntry>,
|
||||
recipes: List<RecipeEntry>
|
||||
) {
|
||||
for (meal in meals) {
|
||||
for (photoUriStr in meal.displayPhotoUris) {
|
||||
val allPhotoUris = buildList {
|
||||
meals.forEach { addAll(it.displayPhotoUris) }
|
||||
recipes.forEach { it.photoUri?.let { uri -> add(uri) } }
|
||||
}.distinct()
|
||||
|
||||
for (photoUriStr in allPhotoUris) {
|
||||
if (photoUriStr.startsWith("http")) continue
|
||||
if (sheetsPrefs.getPhotoDriveUrl(photoUriStr) != null) continue
|
||||
try {
|
||||
val uri = Uri.parse(photoUriStr)
|
||||
@@ -177,7 +206,6 @@ class GoogleSheetsSyncUseCase(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? {
|
||||
if (!sheetsPrefs.isAutoSyncEnabled) return null
|
||||
@@ -187,18 +215,29 @@ class GoogleSheetsSyncUseCase(
|
||||
syncMutex.withLock {
|
||||
withContext(Dispatchers.IO) {
|
||||
val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null
|
||||
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId, sheetsPrefs.rootFolderId).getOrNull()
|
||||
?: return@withContext null
|
||||
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(
|
||||
token,
|
||||
sheetsPrefs.spreadsheetId,
|
||||
sheetsPrefs.rootFolderId
|
||||
).getOrNull() ?: return@withContext null
|
||||
|
||||
sheetsPrefs.spreadsheetId = id
|
||||
sheetsPrefs.spreadsheetUrl = url
|
||||
|
||||
val currentMeals = repository.getAllMealsSnapshot()
|
||||
val currentFoods = repository.getAllCustomFoodsSnapshot()
|
||||
val currentRecipes = repository.getAllRecipesSnapshot()
|
||||
val photosFolderId = sheetsPrefs.photosFolderId
|
||||
if (!photosFolderId.isNullOrBlank()) {
|
||||
uploadPhotosQuietly(token, photosFolderId, currentMeals, currentRecipes)
|
||||
}
|
||||
|
||||
val syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
|
||||
accessToken = token,
|
||||
spreadsheetId = id,
|
||||
meals = currentMeals,
|
||||
foods = currentFoods,
|
||||
recipes = currentRecipes,
|
||||
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
|
||||
)
|
||||
if (syncResult.isSuccess) {
|
||||
@@ -266,18 +305,23 @@ class GoogleSheetsSyncUseCase(
|
||||
}
|
||||
|
||||
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 (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
|
||||
try {
|
||||
repository.syncLocalToCloud()
|
||||
} catch (_: Exception) {}
|
||||
|
||||
SheetsRestoreResult.Success(mealsCount = restoredMeals, foodsCount = restoredFoods)
|
||||
SheetsRestoreResult.Success(
|
||||
mealsCount = restoredMeals,
|
||||
foodsCount = restoredFoods,
|
||||
recipesCount = restoredRecipes
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.example.domain
|
||||
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import com.example.ui.journal.DayStat
|
||||
@@ -11,7 +12,11 @@ import java.util.Locale
|
||||
|
||||
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 startOfPeriod = todayLocalDate.minusDays(6)
|
||||
val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli()
|
||||
@@ -69,13 +74,22 @@ object WeeklyStatsCalculator {
|
||||
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(
|
||||
dailyStats = daysList,
|
||||
averageSatiety = avgSatiety,
|
||||
averageHunger = avgHunger,
|
||||
optimalZonePercentage = optimalPercentage,
|
||||
totalMealsLast7Days = recentMeals.size,
|
||||
mealTypeDistribution = distribution
|
||||
mealTypeDistribution = distribution,
|
||||
categoryDistribution = categoryCounts
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,14 @@
|
||||
package com.example.ui.auth
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
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
|
||||
@@ -19,9 +18,9 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CloudDone
|
||||
import androidx.compose.material.icons.filled.Eco
|
||||
import androidx.compose.material.icons.filled.Restaurant
|
||||
import androidx.compose.material.icons.filled.Timeline
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
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.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.credentials.CredentialManager
|
||||
import androidx.credentials.CustomCredential
|
||||
import androidx.credentials.GetCredentialRequest
|
||||
import androidx.credentials.exceptions.GetCredentialCancellationException
|
||||
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 com.example.util.GoogleDriveAccount
|
||||
import com.example.util.GoogleSheetsAuthHelper
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.android.gms.common.api.ApiException
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.tasks.await
|
||||
|
||||
@Composable
|
||||
fun AuthScreen(
|
||||
onAuthSuccess: () -> Unit
|
||||
onAuthSuccess: (GoogleDriveAccount) -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val credentialManager = remember { CredentialManager.create(context) }
|
||||
var isLoading by remember { mutableStateOf(false) }
|
||||
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(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.surface)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 28.dp, vertical = 32.dp),
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
// Logo & Hero Section
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp)
|
||||
) {
|
||||
// Hero
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.size(88.dp)
|
||||
.size(72.dp)
|
||||
.clip(CircleShape),
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Restaurant,
|
||||
contentDescription = "Logo Satiéa",
|
||||
imageVector = Icons.Default.FolderShared,
|
||||
contentDescription = "Connexion Google Drive",
|
||||
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 = "Satiéa",
|
||||
style = MaterialTheme.typography.displayMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold
|
||||
text = "Sauvegarde sur Google Drive",
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
|
||||
Text(
|
||||
text = "Journal de repas & écoute de soi",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f),
|
||||
text = "Votre compte Google sert uniquement à enregistrer vos données dans votre Drive personnel.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
// Benefits cards
|
||||
// Benefits
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
FeaturePill(
|
||||
icon = Icons.Default.Eco,
|
||||
title = "Sensations de faim & satiété",
|
||||
subtitle = "Évaluez votre ressenti avant et après chaque repas en 10 secondes."
|
||||
icon = Icons.Default.PhoneAndroid,
|
||||
title = "100 % local par défaut",
|
||||
subtitle = "Toutes vos données restent enregistrées sur votre téléphone, sans serveur tiers."
|
||||
)
|
||||
FeaturePill(
|
||||
icon = Icons.Default.Timeline,
|
||||
title = "Statistiques 7 jours",
|
||||
subtitle = "Suivez votre équilibre digestif et la régularité de vos habitudes."
|
||||
icon = Icons.Default.TableChart,
|
||||
title = "Votre classeur Google Sheets",
|
||||
subtitle = "3 onglets clairs : Journal des repas, Aliments colorés et Recueil de recettes."
|
||||
)
|
||||
FeaturePill(
|
||||
icon = Icons.Default.CloudDone,
|
||||
title = "Synchronisation Cloud sécurisée",
|
||||
subtitle = "Vos repas et photos d'assiettes accessibles sur tous vos appareils."
|
||||
title = "Photos & restauration faciles",
|
||||
subtitle = "Vos photos sont archivées dans votre dossier Drive « Satiéa »."
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,28 +188,12 @@ fun AuthScreen(
|
||||
Button(
|
||||
onClick = {
|
||||
isLoading = true
|
||||
onGoogleSignInClicked(
|
||||
context = context,
|
||||
credentialManager = credentialManager,
|
||||
onAuthSuccess = {
|
||||
isLoading = false
|
||||
onAuthSuccess()
|
||||
},
|
||||
onAuthError = { errorMsg ->
|
||||
isLoading = false
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(errorMsg)
|
||||
}
|
||||
},
|
||||
scope = coroutineScope,
|
||||
onAuthCancelled = {
|
||||
isLoading = false
|
||||
}
|
||||
)
|
||||
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
|
||||
signInLauncher.launch(client.signInIntent)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(54.dp)
|
||||
.height(52.dp)
|
||||
.testTag("google_signin_button"),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
@@ -189,7 +204,7 @@ fun AuthScreen(
|
||||
) {
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(24.dp),
|
||||
modifier = Modifier.size(22.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
@@ -202,22 +217,24 @@ fun AuthScreen(
|
||||
)
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = "Continuer avec Google",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
text = "Connecter mon compte Google Drive",
|
||||
style = MaterialTheme.typography.titleSmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
Spacer(modifier = Modifier.height(10.dp))
|
||||
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
SnackbarHost(
|
||||
@@ -235,20 +252,20 @@ private fun FeaturePill(
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
.padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.size(38.dp),
|
||||
shape = RoundedCornerShape(11.dp),
|
||||
color = MaterialTheme.colorScheme.surface
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
@@ -256,12 +273,12 @@ private fun FeaturePill(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
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 {
|
||||
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
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.compose.foundation.Image
|
||||
import coil.compose.AsyncImage
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
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.Restaurant
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
@@ -55,16 +51,22 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.TextAlign
|
||||
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.MealEntry
|
||||
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.LocalDate
|
||||
import java.time.ZoneId
|
||||
@@ -74,6 +76,7 @@ import java.util.Locale
|
||||
@Composable
|
||||
fun JournalScreen(
|
||||
mealsUiState: MealsUiState,
|
||||
customFoods: List<CustomFoodEntry> = emptyList(),
|
||||
onAddMealClick: () -> Unit,
|
||||
onEditMeal: (MealEntry) -> Unit,
|
||||
onDeleteMeal: (String) -> Unit,
|
||||
@@ -81,6 +84,12 @@ fun JournalScreen(
|
||||
onSyncSheetsClick: (() -> Unit)? = 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(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
@@ -139,6 +148,14 @@ fun JournalScreen(
|
||||
DailyOverviewCard(todayMeals = todayMeals)
|
||||
}
|
||||
|
||||
item {
|
||||
DailyBenchmarksCard(
|
||||
todayMeals = todayMeals,
|
||||
customCategoryLookup = customCategoryLookup,
|
||||
onOpenGuideClick = { showDietaryGuide = true }
|
||||
)
|
||||
}
|
||||
|
||||
if (meals.isEmpty()) {
|
||||
item {
|
||||
EmptyMealsView(onAddMealClick = onAddMealClick)
|
||||
@@ -167,13 +184,13 @@ fun JournalScreen(
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.TableChart,
|
||||
contentDescription = "Synchroniser vers Google Sheets",
|
||||
contentDescription = "Sauvegarder sur Google Sheets",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = Color(0xFF0F9D58)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(
|
||||
text = "Sheets",
|
||||
text = "Drive",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = Color(0xFF0F9D58)
|
||||
)
|
||||
@@ -204,6 +221,7 @@ fun JournalScreen(
|
||||
items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal ->
|
||||
MealCardItem(
|
||||
meal = meal,
|
||||
customCategoryLookup = customCategoryLookup,
|
||||
onEdit = { onEditMeal(meal) },
|
||||
onDelete = { onDeleteMeal(meal.id) }
|
||||
)
|
||||
@@ -230,6 +248,10 @@ fun JournalScreen(
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showDietaryGuide) {
|
||||
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -331,6 +353,7 @@ private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
|
||||
@Composable
|
||||
private fun MealCardItem(
|
||||
meal: MealEntry,
|
||||
customCategoryLookup: Map<String, FoodCategory>,
|
||||
onEdit: () -> Unit,
|
||||
onDelete: () -> Unit
|
||||
) {
|
||||
@@ -511,7 +534,7 @@ private fun MealCardItem(
|
||||
}
|
||||
}
|
||||
|
||||
// Food Items Badges (with optional weights)
|
||||
// Color-Coded Food Items Badges
|
||||
if (parsedFoods.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
@@ -526,21 +549,13 @@ private fun MealCardItem(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
parsedFoods.forEach { food ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f)
|
||||
) {
|
||||
Text(
|
||||
FoodCategoryBadge(
|
||||
text = food.displayBadge(),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)
|
||||
category = food.resolvedCategory(customCategoryLookup)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Photos Carousel
|
||||
if (meal.displayPhotoUris.isNotEmpty()) {
|
||||
@@ -568,7 +583,7 @@ private fun MealCardItem(
|
||||
text = "Note globale : « ${meal.note} »",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
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(
|
||||
onDismissRequest = { showDeleteDialog = false },
|
||||
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 = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
@@ -633,7 +648,7 @@ private fun EmptyMealsView(onAddMealClick: () -> Unit) {
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
|
||||
textAlign = TextAlign.Center
|
||||
|
||||
@@ -8,21 +8,24 @@ import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.DefaultFoodCatalog
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.model.RecipeEntry
|
||||
import com.example.data.preferences.GoogleSheetsPreferencesManager
|
||||
import com.example.data.preferences.ThemePreferencesManager
|
||||
import com.example.data.repository.MealRepository
|
||||
import com.example.domain.CsvExportUseCase
|
||||
import com.example.domain.GoogleSheetsSyncUseCase
|
||||
import com.example.domain.SheetsRestoreResult
|
||||
import com.example.domain.SheetsSyncResult
|
||||
import com.example.domain.WeeklyStatsCalculator
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.common.UiEvent
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.example.util.CsvImportResult
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import com.google.firebase.firestore.FirebaseFirestoreException
|
||||
import com.example.util.GoogleSheetsAuthHelper
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
@@ -31,14 +34,13 @@ import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
sealed interface MealsUiState {
|
||||
@@ -69,7 +71,8 @@ data class WeeklyStats(
|
||||
val averageHunger: Float,
|
||||
val optimalZonePercentage: Int,
|
||||
val totalMealsLast7Days: Int,
|
||||
val mealTypeDistribution: Map<MealType, Int>
|
||||
val mealTypeDistribution: Map<MealType, Int>,
|
||||
val categoryDistribution: Map<FoodCategory, Int> = emptyMap()
|
||||
) {
|
||||
companion object {
|
||||
fun empty(): WeeklyStats = WeeklyStats(
|
||||
@@ -78,7 +81,8 @@ data class WeeklyStats(
|
||||
averageHunger = 0f,
|
||||
optimalZonePercentage = 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 context = application.applicationContext
|
||||
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
|
||||
private val themePrefs = ThemePreferencesManager(application)
|
||||
|
||||
// Domain Use Cases
|
||||
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
|
||||
@@ -106,12 +111,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
MealsUiState.Success(meals)
|
||||
}
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
val rootError = firestoreError ?: error
|
||||
emit(MealsUiState.Error(rootError.message ?: "Impossible de charger les repas"))
|
||||
if (error is CancellationException) throw error
|
||||
emit(MealsUiState.Error(error.message ?: "Impossible de charger les repas"))
|
||||
}
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
@@ -119,22 +120,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
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()
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
if (error is CancellationException) throw error
|
||||
emit(emptyList())
|
||||
}
|
||||
.stateIn(
|
||||
@@ -143,7 +131,36 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
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()
|
||||
|
||||
// Quick Log Action triggered from Widget or Notification
|
||||
@@ -178,6 +195,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val spreadsheetUrl: StateFlow<String?> = _spreadsheetUrl.asStateFlow()
|
||||
|
||||
fun setThemeMode(mode: AppThemeMode) {
|
||||
themePrefs.saveThemeMode(mode)
|
||||
_themeMode.value = mode
|
||||
}
|
||||
|
||||
@@ -193,25 +211,44 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) {
|
||||
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.map { it.name.lowercase(Locale.FRENCH) }.toSet()
|
||||
val existingCustom = customFoods.value.map { it.name.lowercase(Locale.FRENCH) }.toSet()
|
||||
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.associate {
|
||||
it.name.lowercase(Locale.FRENCH) to it.category
|
||||
}
|
||||
val existingCustom = customFoods.value.associateBy { it.name.lowercase(Locale.FRENCH) }
|
||||
|
||||
viewModelScope.launch {
|
||||
foodItems.forEach { item ->
|
||||
val cleanName = item.name.trim()
|
||||
val normalized = cleanName.lowercase(Locale.FRENCH)
|
||||
if (cleanName.isNotEmpty() && normalized !in existingBuiltIn && normalized !in existingCustom) {
|
||||
repository.saveCustomFood(cleanName, item.unit)
|
||||
if (cleanName.isEmpty()) return@forEach
|
||||
|
||||
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()
|
||||
if (cleanName.isEmpty()) return
|
||||
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(
|
||||
meal: MealEntry,
|
||||
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() {
|
||||
if (!sheetsPrefs.isAutoSyncEnabled) return
|
||||
viewModelScope.launch {
|
||||
@@ -318,8 +391,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
is SheetsSyncResult.Success -> {
|
||||
_spreadsheetUrl.value = result.url
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
|
||||
val foodsInfo = if (result.foodsCount > 0) " et ${result.foodsCount} aliments" else ""
|
||||
emitEvent(UiEvent.ShowSnackbar("Synchronisé vers Google Sheets (${result.count} repas$foodsInfo) 📊"))
|
||||
val summaryParts = buildList {
|
||||
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 -> {
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
|
||||
@@ -347,15 +424,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
when (val result = sheetsSyncUseCase.restoreFromSheets()) {
|
||||
is SheetsRestoreResult.Success -> {
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Idle
|
||||
val msg = buildString {
|
||||
append("Restauration réussie ✨ : ")
|
||||
append("${result.mealsCount} repas")
|
||||
if (result.foodsCount > 0) {
|
||||
append(" et ${result.foodsCount} aliments")
|
||||
}
|
||||
append(" restaurés")
|
||||
}
|
||||
emitEvent(UiEvent.ShowSnackbar(msg))
|
||||
val summaryParts = buildList {
|
||||
add("${result.mealsCount} repas")
|
||||
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
|
||||
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
|
||||
}.joinToString(", ")
|
||||
emitEvent(UiEvent.ShowSnackbar("Restauration réussie ✨ : $summaryParts"))
|
||||
}
|
||||
is SheetsRestoreResult.RecoverableAuth -> {
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
|
||||
@@ -375,6 +449,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// CSV Import / Export & Notifications
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
fun exportCsvToUri(
|
||||
targetUri: Uri,
|
||||
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>) {
|
||||
viewModelScope.launch {
|
||||
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 {
|
||||
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 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.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
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.MealDateTimePicker
|
||||
import com.example.ui.meal.components.MealHungerSatietySection
|
||||
@@ -85,13 +87,16 @@ fun MealEntrySheet(
|
||||
initialMeal: MealEntry? = null,
|
||||
defaultMealType: MealType = MealType.LUNCH,
|
||||
customFoods: List<CustomFoodEntry> = emptyList(),
|
||||
onAddCustomFood: (String, FoodUnit) -> Unit = { _, _ -> },
|
||||
onAddCustomFood: (String, FoodUnit, FoodCategory?) -> Unit = { _, _, _ -> },
|
||||
onDismiss: () -> Unit,
|
||||
onSaveMeal: (MealType, Long, Int, Int, String, List<MealFoodItem>, List<String>) -> Unit
|
||||
) {
|
||||
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
val context = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val isEditingExisting = initialMeal != null && initialMeal.id.isNotBlank()
|
||||
|
||||
var showDietaryGuide by remember { mutableStateOf(false) }
|
||||
|
||||
var selectedType by rememberSaveable {
|
||||
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
|
||||
@@ -133,17 +138,24 @@ fun MealEntrySheet(
|
||||
mutableStateListOf<String>()
|
||||
}
|
||||
|
||||
val customCategoryLookup = remember(customFoods) {
|
||||
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
|
||||
}
|
||||
|
||||
// Current food builder input state
|
||||
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) }
|
||||
|
||||
// Combine custom foods (user enriched) + built-in catalog
|
||||
val mergedCatalog = remember(customFoods) {
|
||||
val customMapped = customFoods.map {
|
||||
DefaultFoodCatalog.CatalogFood(
|
||||
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()
|
||||
@@ -175,10 +187,16 @@ fun MealEntrySheet(
|
||||
val cleanName = foodNameInput.trim()
|
||||
if (cleanName.isNotEmpty() && foodItemsList.size < 30) {
|
||||
val parsedWeight = foodWeightInput.trim().replace(",", ".").toDoubleOrNull()?.takeIf { it > 0.0 }
|
||||
val resolvedCat = if (hasUserOverriddenCategory) {
|
||||
selectedFoodCategory
|
||||
} else {
|
||||
FoodCategory.inferFromName(cleanName, customCategoryLookup)
|
||||
}
|
||||
val newItem = MealFoodItem(
|
||||
name = cleanName,
|
||||
weight = parsedWeight,
|
||||
unit = selectedFoodUnit
|
||||
unit = selectedFoodUnit,
|
||||
category = resolvedCat
|
||||
)
|
||||
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
|
||||
if (existingIndex >= 0) {
|
||||
@@ -186,12 +204,14 @@ fun MealEntrySheet(
|
||||
} else {
|
||||
foodItemsList.add(newItem)
|
||||
}
|
||||
if (isNewCustomFood) {
|
||||
onAddCustomFood(cleanName, selectedFoodUnit)
|
||||
if (isNewCustomFood || hasUserOverriddenCategory) {
|
||||
onAddCustomFood(cleanName, selectedFoodUnit, resolvedCat)
|
||||
}
|
||||
foodNameInput = ""
|
||||
foodWeightInput = ""
|
||||
selectedFoodUnit = FoodUnit.G
|
||||
selectedFoodCategory = FoodCategory.OTHER
|
||||
hasUserOverriddenCategory = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,7 +234,6 @@ fun MealEntrySheet(
|
||||
}
|
||||
|
||||
val handleDismiss = {
|
||||
// Clean up only uncommitted new photos; do NOT delete existing saved photos
|
||||
newlyCapturedPhotos.forEach { photoUri ->
|
||||
ImageUtils.deletePhotoFile(context, photoUri)
|
||||
}
|
||||
@@ -239,15 +258,15 @@ fun MealEntrySheet(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -309,16 +328,34 @@ fun MealEntrySheet(
|
||||
|
||||
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(
|
||||
foodItemsList = foodItemsList,
|
||||
matchingSuggestions = matchingSuggestions,
|
||||
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,
|
||||
onFoodWeightChange = { foodWeightInput = it },
|
||||
selectedFoodUnit = selectedFoodUnit,
|
||||
onFoodUnitSelected = { selectedFoodUnit = it },
|
||||
selectedFoodCategory = selectedFoodCategory,
|
||||
onFoodCategorySelected = { category ->
|
||||
selectedFoodCategory = category
|
||||
hasUserOverriddenCategory = true
|
||||
},
|
||||
isNewCustomFood = isNewCustomFood,
|
||||
onAddFoodItem = { addCurrentFoodItem() },
|
||||
onItemClickForEdit = { item ->
|
||||
@@ -327,11 +364,14 @@ fun MealEntrySheet(
|
||||
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
|
||||
} ?: ""
|
||||
selectedFoodUnit = item.unit
|
||||
selectedFoodCategory = item.resolvedCategory(customCategoryLookup)
|
||||
hasUserOverriddenCategory = true
|
||||
foodItemsList.remove(item)
|
||||
},
|
||||
onRemoveFoodItem = { item ->
|
||||
foodItemsList.remove(item)
|
||||
}
|
||||
},
|
||||
onOpenGuideClick = { showDietaryGuide = true }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
@@ -382,7 +422,6 @@ fun MealEntrySheet(
|
||||
if (foodNameInput.trim().isNotEmpty()) {
|
||||
addCurrentFoodItem()
|
||||
}
|
||||
// Physically delete only photos marked for deletion that were not re-added
|
||||
photosMarkedForDeletion.forEach { photoUri ->
|
||||
if (!photoUrisList.contains(photoUri)) {
|
||||
ImageUtils.deletePhotoFile(context, photoUri)
|
||||
@@ -408,7 +447,7 @@ fun MealEntrySheet(
|
||||
)
|
||||
) {
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -417,4 +456,8 @@ fun MealEntrySheet(
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (showDietaryGuide) {
|
||||
DietaryGuideSheet(onDismiss = { showDietaryGuide = false })
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.example.ui.meal.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.MenuBook
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
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.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.example.data.model.DefaultFoodCatalog
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.FoodUnit
|
||||
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)
|
||||
@Composable
|
||||
@@ -57,10 +60,16 @@ fun FoodItemBuilderSection(
|
||||
onFoodWeightChange: (String) -> Unit,
|
||||
selectedFoodUnit: FoodUnit,
|
||||
onFoodUnitSelected: (FoodUnit) -> Unit,
|
||||
selectedFoodCategory: FoodCategory,
|
||||
onFoodCategorySelected: (FoodCategory) -> Unit,
|
||||
isNewCustomFood: Boolean,
|
||||
onAddFoodItem: () -> Unit,
|
||||
onItemClickForEdit: (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
|
||||
) {
|
||||
Surface(
|
||||
@@ -78,7 +87,10 @@ fun FoodItemBuilderSection(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.RestaurantMenu,
|
||||
contentDescription = null,
|
||||
@@ -87,31 +99,53 @@ fun FoodItemBuilderSection(
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "3. Aliments & Poids (optionnel)",
|
||||
text = sectionTitle,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (onOpenGuideClick != null) {
|
||||
TextButton(
|
||||
onClick = onOpenGuideClick,
|
||||
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 = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}",
|
||||
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))
|
||||
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(10.dp))
|
||||
|
||||
// Auto-complete / Quick suggestions row
|
||||
// Auto-complete / Quick suggestions row with color dots
|
||||
if (matchingSuggestions.isNotEmpty()) {
|
||||
LazyRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
@@ -122,6 +156,10 @@ fun FoodItemBuilderSection(
|
||||
onClick = {
|
||||
onFoodNameChange(suggestion.name)
|
||||
onFoodUnitSelected(suggestion.defaultUnit)
|
||||
onFoodCategorySelected(suggestion.category)
|
||||
},
|
||||
icon = {
|
||||
FoodCategoryColorDot(category = suggestion.category, size = 9.dp)
|
||||
},
|
||||
label = {
|
||||
Text(
|
||||
@@ -147,7 +185,10 @@ fun FoodItemBuilderSection(
|
||||
.fillMaxWidth()
|
||||
.testTag("food_name_input"),
|
||||
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,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
@@ -167,7 +208,7 @@ fun FoodItemBuilderSection(
|
||||
if (isNewCustomFood) {
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
@@ -175,7 +216,21 @@ fun FoodItemBuilderSection(
|
||||
|
||||
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(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -251,19 +306,19 @@ fun FoodItemBuilderSection(
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = if (foodWeightInput.isNotBlank()) {
|
||||
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
|
||||
"$addButtonLabelPrefix (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
|
||||
} else {
|
||||
"Ajouter à l'assiette (sans poids)"
|
||||
"$addButtonLabelPrefix (sans poids)"
|
||||
},
|
||||
style = MaterialTheme.typography.labelLarge
|
||||
)
|
||||
}
|
||||
|
||||
// Added food items badges
|
||||
// Added color-coded food items badges
|
||||
if (foodItemsList.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
Text(
|
||||
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
|
||||
text = addedListCaption,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -275,33 +330,11 @@ fun FoodItemBuilderSection(
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
foodItemsList.forEach { item ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.clickable { onItemClickForEdit(item) }
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
FoodCategoryBadge(
|
||||
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)
|
||||
category = item.resolvedCategory(),
|
||||
onClick = { onItemClickForEdit(item) },
|
||||
onRemove = { onRemoveFoodItem(item) }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -309,5 +342,3 @@ fun FoodItemBuilderSection(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.NotificationRemindersSection
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
import com.example.util.GoogleDriveAccount
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
googleAccount: GoogleDriveAccount?,
|
||||
currentThemeMode: AppThemeMode,
|
||||
totalMealsCount: Int,
|
||||
sheetsUiState: GoogleSheetsUiState,
|
||||
@@ -48,8 +48,6 @@ fun SettingsScreen(
|
||||
onSignOut: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val currentUser = Firebase.auth.currentUser
|
||||
|
||||
LazyColumn(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
@@ -70,20 +68,19 @@ fun SettingsScreen(
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Local Database & CSV Management
|
||||
// 1. Google Drive Account
|
||||
item {
|
||||
DataExportImportSection(
|
||||
totalMealsCount = totalMealsCount,
|
||||
onImportCsvClick = onImportCsvClick,
|
||||
onSaveCsvClick = onSaveCsvClick,
|
||||
onShareCsvClick = onShareCsvClick
|
||||
AccountAndSecuritySection(
|
||||
googleAccount = googleAccount,
|
||||
onSignInClick = onSignInClick,
|
||||
onSignOut = onSignOut
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
NotificationRemindersSection(
|
||||
onScheduleReminder = onScheduleReminder,
|
||||
@@ -108,7 +115,7 @@ fun SettingsScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// 4. Theme Selector
|
||||
// 5. Theme Selector
|
||||
item {
|
||||
AppearanceThemeSection(
|
||||
currentThemeMode = currentThemeMode,
|
||||
@@ -116,15 +123,6 @@ fun SettingsScreen(
|
||||
)
|
||||
}
|
||||
|
||||
// 5. Account & Cloud Sync
|
||||
item {
|
||||
AccountAndSecuritySection(
|
||||
currentUser = currentUser,
|
||||
onSignInClick = onSignInClick,
|
||||
onSignOut = onSignOut
|
||||
)
|
||||
}
|
||||
|
||||
item {
|
||||
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.filled.AccountCircle
|
||||
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.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
@@ -32,11 +32,11 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.google.firebase.auth.FirebaseUser
|
||||
import com.example.util.GoogleDriveAccount
|
||||
|
||||
@Composable
|
||||
fun AccountAndSecuritySection(
|
||||
currentUser: FirebaseUser?,
|
||||
googleAccount: GoogleDriveAccount?,
|
||||
onSignInClick: () -> Unit,
|
||||
onSignOut: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
@@ -49,7 +49,7 @@ fun AccountAndSecuritySection(
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
if (currentUser != null) {
|
||||
if (googleAccount != null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
@@ -70,13 +70,13 @@ fun AccountAndSecuritySection(
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = currentUser.displayName ?: "Compte Google",
|
||||
text = googleAccount.displayName ?: "Compte Google Drive",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = currentUser.email ?: "Synchronisation Cloud Firestore active",
|
||||
text = googleAccount.email,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -103,7 +103,7 @@ fun AccountAndSecuritySection(
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -128,7 +128,7 @@ fun AccountAndSecuritySection(
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Passer en mode local uniquement (Déconnexion)")
|
||||
Text("Déconnecter Google Drive")
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
@@ -139,7 +139,7 @@ fun AccountAndSecuritySection(
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudOff,
|
||||
imageVector = Icons.Default.PhoneAndroid,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
@@ -151,13 +151,13 @@ fun AccountAndSecuritySection(
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Mode hors-ligne local actif",
|
||||
text = "Stockage 100 % local actif",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -167,7 +167,7 @@ fun AccountAndSecuritySection(
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -187,7 +187,7 @@ fun AccountAndSecuritySection(
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Se connecter avec Google (Optionnel)")
|
||||
Text("Connecter mon compte Google Drive")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -333,7 +333,7 @@ fun GoogleSheetsIntegrationSection(
|
||||
|
||||
OutlinedButton(
|
||||
onClick = { showRestoreConfirmDialog = true },
|
||||
enabled = spreadsheetUrl != null && sheetsUiState !is GoogleSheetsUiState.Syncing,
|
||||
enabled = sheetsUiState !is GoogleSheetsUiState.Syncing,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("restore_sheets_button"),
|
||||
@@ -345,13 +345,13 @@ fun GoogleSheetsIntegrationSection(
|
||||
modifier = Modifier.size(18.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))
|
||||
|
||||
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,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
|
||||
)
|
||||
@@ -370,7 +370,7 @@ fun GoogleSheetsIntegrationSection(
|
||||
},
|
||||
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
|
||||
)
|
||||
},
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
package com.example.ui.stats
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
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.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
@@ -34,6 +38,7 @@ 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.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
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.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.example.data.model.FoodCategory
|
||||
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.WeeklyStats
|
||||
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
|
||||
item {
|
||||
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
|
||||
private fun WeeklyChartCard(dailyStats: List<DayStat>) {
|
||||
val satietyColor = MaterialTheme.colorScheme.primary
|
||||
|
||||
@@ -106,7 +106,6 @@ object CsvImporter {
|
||||
|
||||
val newMeal = MealEntry(
|
||||
id = "local_imp_${UUID.randomUUID().toString().take(8)}",
|
||||
userId = "",
|
||||
mealType = mealType.name,
|
||||
mealTimestamp = timestamp,
|
||||
hungerBefore = hunger,
|
||||
|
||||
@@ -2,17 +2,25 @@ package com.example.util
|
||||
|
||||
import android.accounts.Account
|
||||
import android.content.Context
|
||||
import com.example.R
|
||||
import com.google.android.gms.auth.GoogleAuthUtil
|
||||
import com.google.android.gms.auth.UserRecoverableAuthException
|
||||
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.GoogleSignInOptions
|
||||
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.suspendCancellableCoroutine
|
||||
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 {
|
||||
|
||||
@@ -25,31 +33,30 @@ object GoogleSheetsAuthHelper {
|
||||
const val OAUTH_SCOPE_STRING = "oauth2:$SCOPE_SPREADSHEETS_URL $SCOPE_DRIVE_FILE_URL"
|
||||
|
||||
fun getGoogleSignInClient(context: Context): GoogleSignInClient {
|
||||
val serverClientId = try {
|
||||
context.getString(R.string.default_web_client_id)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||
.requestEmail()
|
||||
.requestScopes(SCOPE_SPREADSHEETS, SCOPE_DRIVE_FILE)
|
||||
.build()
|
||||
|
||||
if (!serverClientId.isNullOrBlank()) {
|
||||
gsoBuilder.requestIdToken(serverClientId)
|
||||
return GoogleSignIn.getClient(context, gso)
|
||||
}
|
||||
|
||||
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) {
|
||||
try {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
val email = GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
|
||||
if (email.isNullOrBlank()) {
|
||||
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)
|
||||
} 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
|
||||
|
||||
import com.example.data.local.LocalCustomFoodEntity
|
||||
import com.example.data.model.FoodCategory
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.HungerSatietyScale
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.model.RecipeCategoryTag
|
||||
import com.example.data.model.RecipeEntry
|
||||
import java.time.Instant
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
@@ -30,7 +33,19 @@ object GoogleSheetsDataFormatter {
|
||||
val HEADERS_CUSTOM_FOODS: List<String> = listOf(
|
||||
"Nom de l'aliment / Plat",
|
||||
"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
|
||||
@@ -39,6 +54,8 @@ object GoogleSheetsDataFormatter {
|
||||
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", 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 ingredientCategoryRegex = Regex("""^(.*?)\s*\[([^\]]+)]\s*$""")
|
||||
private val stepPrefixRegex = Regex("""^\d+\.\s*""")
|
||||
|
||||
fun formatMealsToRows(
|
||||
meals: List<MealEntry>,
|
||||
@@ -102,11 +119,53 @@ object GoogleSheetsDataFormatter {
|
||||
} catch (_: Exception) {
|
||||
""
|
||||
}
|
||||
val categoryLabel = food.resolvedCategory().displayName
|
||||
rows.add(
|
||||
listOf(
|
||||
food.name,
|
||||
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
|
||||
val unitStr = row.getOrNull(1)?.toString()?.trim() ?: "g"
|
||||
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
|
||||
}
|
||||
|
||||
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 com.example.data.local.LocalCustomFoodEntity
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.RecipeEntry
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
@@ -19,12 +20,14 @@ data class GoogleSheetsSyncResult(
|
||||
val spreadsheetUrl: String,
|
||||
val mealsCount: Int,
|
||||
val foodsCount: Int = 0,
|
||||
val recipesCount: Int = 0,
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
data class SpreadsheetRestoreData(
|
||||
val meals: List<MealEntry>,
|
||||
val foods: List<LocalCustomFoodEntity>
|
||||
val foods: List<LocalCustomFoodEntity>,
|
||||
val recipes: List<RecipeEntry> = emptyList()
|
||||
)
|
||||
|
||||
class AuthExpiredException(message: String) : IllegalStateException(message)
|
||||
@@ -35,6 +38,7 @@ object GoogleSheetsSyncService {
|
||||
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
|
||||
const val SHEET_TAB_MEALS = "Journal des repas"
|
||||
const val SHEET_TAB_FOODS = "Mes plats et aliments"
|
||||
const val SHEET_TAB_RECIPES = "Mes recettes"
|
||||
|
||||
// Backward compatibility
|
||||
const val SHEET_TAB_TITLE = SHEET_TAB_MEALS
|
||||
@@ -53,7 +57,7 @@ object GoogleSheetsSyncService {
|
||||
parentFolderId: String? = null
|
||||
): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
|
||||
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()) {
|
||||
val checkRequest = Request.Builder()
|
||||
.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 {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", SPREADSHEET_TITLE)
|
||||
})
|
||||
put("sheets", JSONArray().apply {
|
||||
listOf(SHEET_TAB_MEALS, SHEET_TAB_FOODS, SHEET_TAB_RECIPES).forEach { tabTitle ->
|
||||
put(JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", SHEET_TAB_MEALS)
|
||||
put("gridProperties", JSONObject().apply {
|
||||
put("frozenRowCount", 1)
|
||||
})
|
||||
})
|
||||
})
|
||||
put(JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", SHEET_TAB_FOODS)
|
||||
put("title", tabTitle)
|
||||
put("gridProperties", JSONObject().apply {
|
||||
put("frozenRowCount", 1)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -158,7 +156,6 @@ object GoogleSheetsSyncService {
|
||||
val id = json.getString("spreadsheetId")
|
||||
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||
|
||||
// Move new sheet into Satiéa Drive folder
|
||||
if (parentFolderId != null) {
|
||||
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
|
||||
}
|
||||
@@ -180,7 +177,7 @@ object GoogleSheetsSyncService {
|
||||
|
||||
/**
|
||||
* 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(
|
||||
accessToken: String,
|
||||
@@ -203,6 +200,7 @@ object GoogleSheetsSyncService {
|
||||
val sheets = json.optJSONArray("sheets") ?: return@withContext
|
||||
var hasMealsTab = false
|
||||
var hasFoodsTab = false
|
||||
var hasRecipesTab = false
|
||||
var legacySheetIdToRename: Int? = null
|
||||
|
||||
val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1")
|
||||
@@ -215,6 +213,7 @@ object GoogleSheetsSyncService {
|
||||
when {
|
||||
title == SHEET_TAB_MEALS -> hasMealsTab = true
|
||||
title == SHEET_TAB_FOODS -> hasFoodsTab = true
|
||||
title == SHEET_TAB_RECIPES -> hasRecipesTab = true
|
||||
legacySheetIdToRename == null && legacyTabNames.contains(title) && sId != -1 -> {
|
||||
legacySheetIdToRename = sId
|
||||
}
|
||||
@@ -223,7 +222,7 @@ object GoogleSheetsSyncService {
|
||||
|
||||
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 (legacySheetIdToRename != null) {
|
||||
batchRequests.put(JSONObject().apply {
|
||||
@@ -235,7 +234,6 @@ object GoogleSheetsSyncService {
|
||||
put("fields", "title")
|
||||
})
|
||||
})
|
||||
hasMealsTab = true
|
||||
} else {
|
||||
batchRequests.put(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) {
|
||||
batchRequests.put(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) {
|
||||
val batchPayload = JSONObject().apply {
|
||||
put("requests", batchRequests)
|
||||
@@ -298,19 +309,30 @@ object GoogleSheetsSyncService {
|
||||
spreadsheetId: String,
|
||||
meals: List<MealEntry>,
|
||||
foods: List<LocalCustomFoodEntity>,
|
||||
recipes: List<RecipeEntry> = emptyList(),
|
||||
photoLinkProvider: (String) -> String? = { null }
|
||||
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
|
||||
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)
|
||||
|
||||
// 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)
|
||||
|
||||
// 2. Sync Custom Foods on SHEET_TAB_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"
|
||||
Result.success(
|
||||
@@ -318,7 +340,8 @@ object GoogleSheetsSyncService {
|
||||
spreadsheetId = spreadsheetId,
|
||||
spreadsheetUrl = spreadsheetUrl,
|
||||
mealsCount = meals.size,
|
||||
foodsCount = foods.size
|
||||
foodsCount = foods.size,
|
||||
recipesCount = recipes.size
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
@@ -333,7 +356,7 @@ object GoogleSheetsSyncService {
|
||||
spreadsheetId: String,
|
||||
meals: List<MealEntry>
|
||||
): Result<GoogleSheetsSyncResult> {
|
||||
return syncMealsAndFoods(accessToken, spreadsheetId, meals, emptyList())
|
||||
return syncMealsAndFoods(accessToken, spreadsheetId, meals, emptyList(), emptyList())
|
||||
}
|
||||
|
||||
private suspend fun writeRowsToSheet(
|
||||
@@ -344,7 +367,6 @@ object GoogleSheetsSyncService {
|
||||
startCell: String,
|
||||
rows: List<List<Any>>
|
||||
) = withContext(Dispatchers.IO) {
|
||||
// Clear previous range with RFC 3986 encoding (%20 instead of +)
|
||||
val clearRange = encodePathRange("'$sheetTitle'!$clearRangeColumns")
|
||||
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
|
||||
val clearRequest = Request.Builder()
|
||||
@@ -362,7 +384,6 @@ object GoogleSheetsSyncService {
|
||||
Log.w(TAG, "Clear range '$sheetTitle' warning: ${e.message}")
|
||||
}
|
||||
|
||||
// Put values in RAW mode (neutralizes formula injection)
|
||||
val jsonValuesArray = JSONArray()
|
||||
for (row in rows) {
|
||||
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(
|
||||
accessToken: String,
|
||||
spreadsheetId: String
|
||||
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
|
||||
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)
|
||||
|
||||
// 1. Read Meals with RFC 3986 encoding (%20)
|
||||
val mealsRange = encodePathRange("'$SHEET_TAB_MEALS'!A1:Z")
|
||||
val mealsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$mealsRange"
|
||||
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 mealRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_MEALS'!A1:Z")
|
||||
val foodRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_FOODS'!A1:D")
|
||||
val recipeRows = readSheetRange(accessToken, spreadsheetId, "'$SHEET_TAB_RECIPES'!A1:H")
|
||||
|
||||
val parsedMeals = GoogleSheetsDataFormatter.parseRowsToMeals(mealRows)
|
||||
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) {
|
||||
Log.e(TAG, "Error in readSpreadsheetData", e)
|
||||
Result.failure(e)
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
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.MealFoodItem
|
||||
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.GoogleSheetsSyncService
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -60,18 +65,13 @@ class GoogleSheetsDataFormatterTest {
|
||||
photoUris = emptyList()
|
||||
)
|
||||
|
||||
// Pass in reverse order to test sorting
|
||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2), testZoneId)
|
||||
|
||||
// 1 header + 2 data rows
|
||||
assertEquals(3, rows.size)
|
||||
|
||||
// Row 0: Headers
|
||||
assertEquals(10, rows[0].size)
|
||||
assertEquals("Date", rows[0][0])
|
||||
assertEquals("Photos jointes", rows[0][9])
|
||||
|
||||
// Row 1: Most recent meal (DINNER at 20:00)
|
||||
val dinnerRow = rows[1]
|
||||
assertEquals("15/03/2026", dinnerRow[0])
|
||||
assertEquals("20:00", dinnerRow[1])
|
||||
@@ -82,7 +82,6 @@ class GoogleSheetsDataFormatterTest {
|
||||
assertEquals("Dîner léger en famille", dinnerRow[8])
|
||||
assertEquals(0, dinnerRow[9])
|
||||
|
||||
// Row 2: Earlier meal (LUNCH at 12:30)
|
||||
val lunchRow = rows[2]
|
||||
assertEquals("15/03/2026", lunchRow[0])
|
||||
assertEquals("12:30", lunchRow[1])
|
||||
@@ -97,20 +96,22 @@ class GoogleSheetsDataFormatterTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `formatCustomFoodsToRows formats headers and rows correctly`() {
|
||||
fun `formatCustomFoodsToRows formats 4 columns including category`() {
|
||||
val foods = listOf(
|
||||
com.example.data.local.LocalCustomFoodEntity(
|
||||
slugId = "houmous",
|
||||
name = "Houmous maison",
|
||||
LocalCustomFoodEntity(
|
||||
slugId = "comte_affine",
|
||||
name = "Comté affiné",
|
||||
defaultUnit = "g",
|
||||
category = FoodCategory.CHEESE.name,
|
||||
updatedAt = 1773574800000L
|
||||
)
|
||||
)
|
||||
val rows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods, testZoneId)
|
||||
assertEquals(2, rows.size)
|
||||
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(FoodCategory.CHEESE.displayName, rows[1][3])
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -130,12 +131,69 @@ class GoogleSheetsDataFormatterTest {
|
||||
|
||||
val foodRows = listOf(
|
||||
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)
|
||||
assertEquals(1, parsedFoods.size)
|
||||
assertEquals("Curry de lentilles", parsedFoods[0].name)
|
||||
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
|
||||
@@ -152,19 +210,16 @@ class GoogleSheetsDataFormatterTest {
|
||||
assertEquals("https://drive.google.com/file/1", rows[1][9])
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test
|
||||
fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() {
|
||||
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)
|
||||
|
||||
val foodRange = "'Mes plats et aliments'!A1:C"
|
||||
val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange)
|
||||
assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded)
|
||||
val foodRange = "'Mes plats et aliments'!A1:D"
|
||||
val foodEncoded = GoogleSheetsSyncService.encodePathRange(foodRange)
|
||||
assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AD", foodEncoded)
|
||||
assertTrue(!encoded.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.LocalMealDao
|
||||
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.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
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.test.runTest
|
||||
import org.junit.After
|
||||
@@ -54,7 +58,8 @@ class LocalDatabaseTest {
|
||||
satietyAfter = 7,
|
||||
note = "Repas calme",
|
||||
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")
|
||||
)
|
||||
@@ -69,8 +74,10 @@ class LocalDatabaseTest {
|
||||
assertEquals(6, readMeal.hungerBefore)
|
||||
assertEquals(7, readMeal.satietyAfter)
|
||||
assertEquals("Repas calme", readMeal.note)
|
||||
assertEquals(1, readMeal.parsedFoodItems().size)
|
||||
assertEquals(2, readMeal.parsedFoodItems().size)
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -91,15 +98,53 @@ class LocalDatabaseTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testInsertAndObserveCustomFoods() = runTest {
|
||||
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G)
|
||||
val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML)
|
||||
fun testInsertAndObserveCustomFoodsWithCategory() = runTest {
|
||||
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G, FoodCategory.STARCH)
|
||||
val food2 = LocalCustomFoodEntity.create("Tomme de brebis", FoodUnit.G, FoodCategory.CHEESE)
|
||||
|
||||
dao.insertCustomFoods(listOf(food1, food2))
|
||||
|
||||
val allFoods = dao.observeAllCustomFoods().first()
|
||||
assertEquals(2, allFoods.size)
|
||||
val names = allFoods.map { it.name }
|
||||
assertEquals(listOf("Granola maison", "Smoothie mangue"), names)
|
||||
assertEquals(listOf("Granola maison", "Tomme de brebis"), allFoods.map { it.name })
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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œûÿÿÿÿÿ | ||||