build: initialize project structure
Set up Android project configuration, Gradle build scripts, typography, and default resource assets.
No files matched your search
@@ -0,0 +1,96 @@
|
||||
# Satiéa — Liste d'Aliments Enrichissable (Poids Optionnel) & Note Globale
|
||||
|
||||
Évolution du formulaire de repas, du journal et de l'export CSV de **Satiéa** pour remplacer le champ de note unique par :
|
||||
1. **Une liste enrichissable d'aliments** composant l'assiette, avec **autocomplétion intelligente** (catalogue de base + enrichissement automatique par vos propres saisies synchronisé dans le cloud) et **poids/quantité optionnel** (`g` par défaut, `ml` ou `portion`).
|
||||
2. **Une note globale du repas** dédiée au contexte, au ressenti ou à l'humeur.
|
||||
|
||||
## Revue Utilisateur & Décisions Clés
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Ce plan intègre vos réponses aux questions de clarification tout en conservant l'échelle de faim/satiété sur 10, la modification rétroactive de la date/heure, les photos d'assiettes et la synchronisation Cloud Firestore.
|
||||
|
||||
- **Catalogue d'aliments évolutif & Autocomplétion** : Pré-chargement d'un catalogue d'aliments courants (légumes, féculents, protéines, fruits, produits laitiers, boissons) qui **s'enrichit automatiquement** dès que vous saisissez un nouvel aliment. Vos aliments personnalisés sont sauvegardés dans votre espace Cloud Firestore (`/users/{userId}/custom_foods`) pour être suggérés sur tous vos appareils.
|
||||
- **Poids / Quantité optionnel multi-unités** : Chaque aliment ajouté au repas peut être enregistré **sans poids** (saisie ultra-rapide) ou **avec une quantité précise** accompagnée de l'unité **`g` (par défaut)**, **`ml`** ou **`portion`**.
|
||||
- **Affichage en badges & Export CSV enrichi** : Les aliments et leur poids s'affichent sous forme de **badges élégants** sur chaque carte de repas dans le journal, et sont exportés dans une colonne dédiée **`Aliments & Poids`** dans le fichier CSV.
|
||||
|
||||
---
|
||||
|
||||
## 1. Vue d'Ensemble & Concept Fondamental
|
||||
|
||||
- **Ce que fait cette mise à jour** :
|
||||
1. Distingue clairement **ce que contient l'assiette** (liste structurée d'aliments avec poids optionnel) du **ressenti global du repas** (note globale sur le contexte : repas pris au calme, au restaurant, fatigue, etc.).
|
||||
2. Accélère la saisie au fil du temps : plus vous utilisez l'application, plus le dictionnaire d'autocomplétion connaît vos plats et ingrédients habituels ainsi que leur unité favorite.
|
||||
3. Offre une traçabilité précise dans l'export CSV pour analyser le lien entre certains aliments, leurs quantités et votre satiété sur 10.
|
||||
|
||||
---
|
||||
|
||||
## 2. Expérience Utilisateur & Design Visuel
|
||||
|
||||
### Parcours Utilisateurs Mis à Jour
|
||||
1. **Bloc « Composition de l'assiette (Aliments & Poids optionnel) » dans `MealEntrySheet`** :
|
||||
- **Champ de recherche / ajout d'aliment avec suggestions instantanées** : Dès les premières lettres tapées (ou au clic sur le champ), une rangée de puces de suggestion affiche les aliments correspondants issus du catalogue de base et de vos saisies passées.
|
||||
- **Champ Poids / Quantité (Optionnel) + Sélecteur d'unité (`g` | `ml` | `portion`)** : Permet de préciser par exemple `150 g`, `250 ml` ou `1 portion`, ou de laisser le champ vide pour ajouter uniquement le nom de l'aliment en un tap sur le bouton **`+ Ajouter`**.
|
||||
- **Liste des aliments du repas en cours** : Affichage sous forme de puces interactives (ex. `🥗 Riz complet • 150 g`, `🥑 Avocat • 1 portion`, `🐟 Saumon grillé`) avec possibilité de modifier le poids ou de retirer un aliment d'un geste.
|
||||
2. **Bloc « Note globale du repas (Optionnel) »** :
|
||||
- Champ de texte multiligne dédié aux observations générales sur le repas (convivialité, vitesse de prise alimentaire, digestion, plaisir gustatif).
|
||||
3. **Affichage dans le Journal (`JournalScreen`)** :
|
||||
- Chaque carte de repas présente les **badges d'aliments** (avec leur poids s'il a été renseigné) juste au-dessus des photos d'assiettes et de la **note globale**.
|
||||
4. **Export CSV enrichi (`CsvExporter`)** :
|
||||
- Ajout de la colonne **`Aliments (avec poids)`** (ex. `Riz complet (150 g) | Saumon grillé (120 g) | Avocat`) distincte de la colonne **`Note globale`**.
|
||||
|
||||
---
|
||||
|
||||
## 3. Décisions Produit & Arbitrages Techniques
|
||||
|
||||
- **Décision 1 : Enrichissement automatique sans friction**
|
||||
- *Approche choisie* : Lorsqu'un utilisateur ajoute un aliment au repas qui ne figure pas encore dans le catalogue de base, cet aliment est automatiquement enregistré dans sa collection Cloud Firestore `/users/{userId}/custom_foods` avec son unité préférée.
|
||||
- *Pourquoi* : L'utilisateur n'a pas besoin de gérer manuellement une base de données d'aliments dans un écran séparé ; son catalogue grandit naturellement pendant qu'il note ses repas.
|
||||
|
||||
- **Décision 2 : Modélisation de la liste d'aliments dans `MealEntry`**
|
||||
- *Approche choisie* : Stockage de la liste `foodItems` dans le document `MealEntry` sous forme d'entrées structurées sérialisées (`MealFoodItem(name, weight, unit)`) validées par `firestore.rules` (jusqu'à 30 aliments par repas), tout en conservant le champ `note` pour la **Note globale**.
|
||||
- *Pourquoi* : Rétrocompatible à 100 % avec les repas déjà enregistrés et conforme aux règles de validation Zero-Trust de Firestore.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture Technique & Stratégie de Données
|
||||
|
||||
### Schéma des Composants Mis à Jour
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ INTERFACE JETPACK COMPOSE │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────────────────────────────────┐ │
|
||||
│ │ MealEntrySheet │ │
|
||||
│ │ ┌─────────────────────────────────────────────────────────────┐ │ │
|
||||
│ │ │ 3. Composition de l'assiette (Liste enrichissable) │ │ │
|
||||
│ │ │ - Saisie aliment + Autocomplétion (Base + Perso Cloud) │ │ │
|
||||
│ │ │ - Poids optionnel (ex: 150) + Unité [ g | ml | portion ] │ │ │
|
||||
│ │ │ - Badges des aliments ajoutés au repas │ │ │
|
||||
│ │ └──────────────────────────────┬──────────────────────────────┘ │ │
|
||||
│ │ ┌──────────────────────────────▼──────────────────────────────┐ │ │
|
||||
│ │ │ 4. Note globale du repas (Optionnel) │ │ │
|
||||
│ │ │ - Ressenti libre, contexte, plaisir, vitesse du repas │ │ │
|
||||
│ │ └─────────────────────────────────────────────────────────────┘ │ │
|
||||
│ └─────────────────────────────────┬─────────────────────────────────┘ │
|
||||
└────────────────────────────────────┼────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────────────┐
|
||||
│ MealViewModel & MealRepository │
|
||||
│ - Catalogue hybride : DefaultFoods (60+ aliments) + CustomFoods Cloud │
|
||||
│ - Sauvegarde automatique des nouveaux aliments dans /custom_foods │
|
||||
│ - Export CSV incluant la colonne "Aliments & Poids" + "Note globale" │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Modèle de Données Mis à Jour
|
||||
- **`MealFoodItem`** :
|
||||
- `name` (`String`) : Nom de l'aliment (ex. `"Riz basmati"`, `"Poulet rôti"`).
|
||||
- `weight` (`Double?`) : Poids ou quantité optionnelle (ex. `150.0`, `null` si non renseigné).
|
||||
- `unit` (`String`) : `"g"` (défaut), `"ml"` ou `"portion"`.
|
||||
- **`MealEntry`** (`/users/{userId}/meals/{mealId}`) :
|
||||
- Ajout de `foodItemsSerialized` (`List<String>`) : Liste des aliments du repas (format compact `"Nom|Poids|Unité"` permettant une validation stricte dans `firestore.rules` et une désérialisation typée vers `List<MealFoodItem>`).
|
||||
- `note` (`String`) : Représente désormais la **Note globale** du repas.
|
||||
- **`CustomFoodEntry`** (`/users/{userId}/custom_foods/{foodId}`) :
|
||||
- `userId` (`String`), `name` (`String`), `defaultUnit` (`String` : `"g"`, `"ml"`, `"portion"`), `createdAt` / `updatedAt` (`Timestamp?`).
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"summary": "Mise à jour du plan d'implémentation de Satiéa : restructuration du bloc de note en deux parties distinctes — une liste enrichissable d'aliments avec autocomplétion et poids/quantité optionnel (g, ml, portion) synchronisée dans le cloud, et une note globale sur le contexte du repas, avec affichage en badges et intégration dans l'export CSV.",
|
||||
"updatedAt": "2026-11-06T15:22:35.366873493Z",
|
||||
"requestFeedback": true,
|
||||
"userFacing": true
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# GEMINI_API_KEY: Required for Gemini AI API calls.
|
||||
# This is a placeholder key.
|
||||
# AI Studio automatically injects this at runtime from user secrets.
|
||||
# Users configure this via the Secrets panel in the AI Studio UI.
|
||||
# IMPORTANT: Uncomment the line below if your app uses the Gemini API.
|
||||
# If left commented out, the key will NOT be packaged in the APK.
|
||||
# GEMINI_API_KEY=MY_GEMINI_API_KEY
|
||||
@@ -0,0 +1,19 @@
|
||||
*.iml
|
||||
.gradle
|
||||
.kotlin
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
.DS_Store
|
||||
/build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
.env
|
||||
debug.keystore
|
||||
*-debug.log
|
||||
@@ -1,11 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
|
||||
|
||||
<h1>Built with AI Studio</h2>
|
||||
|
||||
<p>The fastest path from prompt to production with Gemini.</p>
|
||||
|
||||
<a href="https://aistudio.google.com/apps">Start building</a>
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1 @@
|
||||
/build
|
||||
@@ -0,0 +1,149 @@
|
||||
import com.google.gms.googleservices.GoogleServicesPlugin.MissingGoogleServicesStrategy
|
||||
import java.time.Duration
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.google.devtools.ksp)
|
||||
alias(libs.plugins.secrets)
|
||||
alias(libs.plugins.google.services)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example"
|
||||
compileSdk { version = release(36) { minorApiLevel = 1 } }
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.aistudio.satiea.jkmzpq"
|
||||
minSdk = 24
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
// Do not remove or modify these signingConfigs. They are necessary for building, installing,
|
||||
// and updating Android apps in AI Studio.
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
val keystorePath = System.getenv("KEYSTORE_PATH") ?: "${rootDir}/my-upload-key.jks"
|
||||
storeFile = file(keystorePath)
|
||||
storePassword = System.getenv("STORE_PASSWORD")
|
||||
keyAlias = "upload"
|
||||
keyPassword = System.getenv("KEY_PASSWORD")
|
||||
}
|
||||
create("debugConfig") {
|
||||
storeFile = file("${rootDir}/debug.keystore")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isCrunchPngs = false
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
// Do not remove or modify this signingConfig assignment. It is necessary for Android apps in
|
||||
// AI Studio.
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
debug {
|
||||
// Do not remove or modify this signingConfig assignment. It is necessary for Android apps in
|
||||
// AI Studio.
|
||||
signingConfig = signingConfigs.getByName("debugConfig")
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_11
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
testOptions { unitTests { isIncludeAndroidResources = true } }
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = true
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
failFast = true
|
||||
timeout.set(Duration.ofMinutes(2))
|
||||
testLogging {
|
||||
events("passed", "failed", "skipped")
|
||||
}
|
||||
}
|
||||
|
||||
// Configure the Secrets Gradle Plugin to use .env and .env.example files
|
||||
// to match the convention used in Web projects.
|
||||
secrets {
|
||||
propertiesFileName = ".env"
|
||||
defaultPropertiesFileName = ".env.example"
|
||||
ignoreList.add("FIREBASE_APPCHECK_DEBUG_TOKEN")
|
||||
}
|
||||
|
||||
googleServices { missingGoogleServicesStrategy = MissingGoogleServicesStrategy.WARN }
|
||||
|
||||
// Some unused dependencies are commented out below instead of being removed.
|
||||
// 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(libs.accompanist.permissions)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
// implementation(libs.androidx.camera.camera2)
|
||||
// implementation(libs.androidx.camera.core)
|
||||
// implementation(libs.androidx.camera.lifecycle)
|
||||
// implementation(libs.androidx.camera.view)
|
||||
implementation(libs.androidx.compose.material.icons.core)
|
||||
implementation(libs.androidx.compose.material.icons.extended)
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.graphics)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.core.ktx)
|
||||
// implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
// implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation(libs.androidx.room.runtime)
|
||||
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.appcheck.recaptcha)
|
||||
implementation(libs.firebase.appcheck.debug)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.logging.interceptor)
|
||||
implementation(libs.moshi.kotlin)
|
||||
implementation(libs.okhttp)
|
||||
// implementation(libs.play.services.location)
|
||||
implementation(libs.retrofit)
|
||||
testImplementation(libs.androidx.compose.ui.test.junit4)
|
||||
testImplementation(libs.androidx.core)
|
||||
testImplementation(libs.androidx.junit)
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
testImplementation(libs.robolectric)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
androidTestImplementation(libs.androidx.compose.ui.test.junit4)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.runner)
|
||||
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
"ksp"(libs.androidx.room.compiler)
|
||||
"ksp"(libs.moshi.kotlin.codegen)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.example
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Instrumented test, which will execute on an Android device.
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ExampleInstrumentedTest {
|
||||
@Test
|
||||
fun useAppContext() {
|
||||
// Context of the app under test.
|
||||
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
|
||||
assertEquals(BuildConfig.APPLICATION_ID, appContext.packageName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.MyApplication">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.MyApplication">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<receiver
|
||||
android:name=".receiver.MealReminderReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,378 @@
|
||||
package com.example
|
||||
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.viewModels
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBars
|
||||
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.filled.BarChart
|
||||
import androidx.compose.material.icons.filled.Restaurant
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.NavigationBar
|
||||
import androidx.compose.material3.NavigationBarItem
|
||||
import androidx.compose.material3.NavigationBarItemDefaults
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.auth.AuthScreen
|
||||
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.settings.SettingsScreen
|
||||
import com.example.ui.stats.WeeklyStatsScreen
|
||||
import com.example.ui.theme.SatieaTheme
|
||||
import com.example.util.CsvExporter
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import com.google.firebase.auth.auth
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
enum class MainTab(val title: String) {
|
||||
JOURNAL("Journal"),
|
||||
STATS("Statistiques"),
|
||||
SETTINGS("Réglages")
|
||||
}
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
private val viewModel: MealViewModel by viewModels()
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
val logMealRequested = intent?.action == MealNotificationManager.ACTION_LOG_MEAL
|
||||
val initialMealType = intent?.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
|
||||
MealType.fromString(it)
|
||||
} ?: MealType.LUNCH
|
||||
|
||||
setContent {
|
||||
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
||||
|
||||
SatieaTheme(themeMode = themeMode) {
|
||||
AppRoot(
|
||||
viewModel = viewModel,
|
||||
openAddMealInitially = logMealRequested,
|
||||
initialDefaultMealType = initialMealType
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
viewModel: MealViewModel,
|
||||
openAddMealInitially: Boolean,
|
||||
initialDefaultMealType: MealType
|
||||
) {
|
||||
var currentUser by remember { mutableStateOf(Firebase.auth.currentUser) }
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
if (currentUser == null) {
|
||||
AuthScreen(
|
||||
onAuthSuccess = {
|
||||
currentUser = Firebase.auth.currentUser
|
||||
}
|
||||
)
|
||||
} else {
|
||||
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
|
||||
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
|
||||
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
||||
var defaultMealType by remember { mutableStateOf(initialDefaultMealType) }
|
||||
|
||||
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
|
||||
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
|
||||
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
||||
val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList()
|
||||
|
||||
val createCsvDocumentLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.CreateDocument("text/csv")
|
||||
) { targetUri: Uri? ->
|
||||
if (targetUri != null) {
|
||||
viewModel.exportCsvToUri(
|
||||
targetUri = targetUri,
|
||||
meals = currentMealsList,
|
||||
onSuccess = { count ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Fichier CSV enregistré ($count repas) ✨")
|
||||
}
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val triggerSaveCsv = {
|
||||
if (currentMealsList.isEmpty()) {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Aucun repas à exporter pour le moment")
|
||||
}
|
||||
} else {
|
||||
createCsvDocumentLauncher.launch(CsvExporter.buildDefaultFileName())
|
||||
}
|
||||
}
|
||||
|
||||
val triggerShareCsv = {
|
||||
if (currentMealsList.isEmpty()) {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Aucun repas à partager pour le moment")
|
||||
}
|
||||
} else {
|
||||
viewModel.shareCsv(
|
||||
activityContext = context,
|
||||
meals = currentMealsList,
|
||||
onIntentReady = { chooserIntent ->
|
||||
context.startActivity(chooserIntent)
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
BackHandler(enabled = currentTab != MainTab.JOURNAL) {
|
||||
currentTab = MainTab.JOURNAL
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets.safeDrawing,
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||
bottomBar = {
|
||||
NavigationBar(
|
||||
modifier = Modifier
|
||||
.windowInsetsPadding(WindowInsets.navigationBars)
|
||||
.testTag("main_navigation_bar"),
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
NavigationBarItem(
|
||||
selected = currentTab == MainTab.JOURNAL,
|
||||
onClick = { currentTab = MainTab.JOURNAL },
|
||||
icon = { Icon(Icons.Default.Restaurant, contentDescription = "Journal") },
|
||||
label = { Text("Journal") },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
indicatorColor = MaterialTheme.colorScheme.primaryContainer
|
||||
),
|
||||
modifier = Modifier.testTag("tab_journal")
|
||||
)
|
||||
|
||||
NavigationBarItem(
|
||||
selected = currentTab == MainTab.STATS,
|
||||
onClick = { currentTab = MainTab.STATS },
|
||||
icon = { Icon(Icons.Default.BarChart, contentDescription = "Statistiques") },
|
||||
label = { Text("Statistiques") },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
indicatorColor = MaterialTheme.colorScheme.primaryContainer
|
||||
),
|
||||
modifier = Modifier.testTag("tab_stats")
|
||||
)
|
||||
|
||||
NavigationBarItem(
|
||||
selected = currentTab == MainTab.SETTINGS,
|
||||
onClick = { currentTab = MainTab.SETTINGS },
|
||||
icon = { Icon(Icons.Default.Settings, contentDescription = "Réglages") },
|
||||
label = { Text("Réglages") },
|
||||
colors = NavigationBarItemDefaults.colors(
|
||||
selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
indicatorColor = MaterialTheme.colorScheme.primaryContainer
|
||||
),
|
||||
modifier = Modifier.testTag("tab_settings")
|
||||
)
|
||||
}
|
||||
}
|
||||
) { innerPadding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding)
|
||||
) {
|
||||
when (currentTab) {
|
||||
MainTab.JOURNAL -> {
|
||||
JournalScreen(
|
||||
mealsUiState = mealsState,
|
||||
onAddMealClick = {
|
||||
editingMeal = null
|
||||
defaultMealType = MealType.LUNCH
|
||||
showMealEntrySheet = true
|
||||
},
|
||||
onEditMeal = { meal ->
|
||||
editingMeal = meal
|
||||
showMealEntrySheet = true
|
||||
},
|
||||
onDeleteMeal = { mealId ->
|
||||
viewModel.deleteMeal(
|
||||
mealId = mealId,
|
||||
onSuccess = {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Repas supprimé")
|
||||
}
|
||||
},
|
||||
onError = { error ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(error)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
onExportCsvClick = {
|
||||
triggerSaveCsv()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
MainTab.STATS -> {
|
||||
val weeklyStats = remember(currentMealsList) {
|
||||
viewModel.computeWeeklyStats(currentMealsList)
|
||||
}
|
||||
WeeklyStatsScreen(
|
||||
weeklyStats = weeklyStats,
|
||||
totalMealsCount = currentMealsList.size,
|
||||
onSaveCsvClick = { triggerSaveCsv() },
|
||||
onShareCsvClick = { triggerShareCsv() }
|
||||
)
|
||||
}
|
||||
|
||||
MainTab.SETTINGS -> {
|
||||
SettingsScreen(
|
||||
currentThemeMode = themeMode,
|
||||
totalMealsCount = currentMealsList.size,
|
||||
onThemeModeChange = { newMode ->
|
||||
viewModel.setThemeMode(newMode)
|
||||
},
|
||||
onScheduleReminder = { type, hour, minute, enabled ->
|
||||
viewModel.scheduleMealReminder(type, hour, minute, enabled)
|
||||
},
|
||||
onTestNotification = { type ->
|
||||
viewModel.triggerTestNotification(type)
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Notification de rappel envoyée !")
|
||||
}
|
||||
},
|
||||
onSaveCsvClick = { triggerSaveCsv() },
|
||||
onShareCsvClick = { triggerShareCsv() },
|
||||
onSignOut = {
|
||||
currentUser = null
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showMealEntrySheet) {
|
||||
MealEntrySheet(
|
||||
initialMeal = editingMeal,
|
||||
defaultMealType = defaultMealType,
|
||||
customFoods = customFoods,
|
||||
onAddCustomFood = { name, unit ->
|
||||
viewModel.addCustomFoodDirectly(name, unit)
|
||||
},
|
||||
onDismiss = {
|
||||
showMealEntrySheet = false
|
||||
editingMeal = null
|
||||
},
|
||||
onSaveMeal = { type, timestamp, hunger, satiety, note, foodItems, photos ->
|
||||
showMealEntrySheet = false
|
||||
val currentEditing = editingMeal
|
||||
if (currentEditing != null) {
|
||||
viewModel.updateMeal(
|
||||
meal = currentEditing.copy(
|
||||
mealType = type.name,
|
||||
mealTimestamp = timestamp,
|
||||
hungerBefore = hunger,
|
||||
satietyAfter = satiety,
|
||||
note = note,
|
||||
photosBase64 = photos
|
||||
),
|
||||
foodItems = foodItems,
|
||||
onSuccess = {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Repas mis à jour ✨")
|
||||
}
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
viewModel.addMeal(
|
||||
mealType = type,
|
||||
mealTimestamp = timestamp,
|
||||
hungerBefore = hunger,
|
||||
satietyAfter = satiety,
|
||||
note = note,
|
||||
foodItems = foodItems,
|
||||
photosBase64 = photos,
|
||||
onSuccess = {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Repas enregistré avec succès ✨")
|
||||
}
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
editingMeal = null
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
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) {
|
||||
G("g", "g"),
|
||||
ML("ml", "ml"),
|
||||
PORTION("portion", "portion");
|
||||
|
||||
companion object {
|
||||
fun fromCode(code: String): FoodUnit {
|
||||
return entries.firstOrNull { it.code.equals(code.trim(), ignoreCase = true) } ?: G
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class MealFoodItem(
|
||||
val name: String,
|
||||
val weight: Double? = null,
|
||||
val unit: FoodUnit = FoodUnit.G
|
||||
) {
|
||||
fun serialize(): String {
|
||||
val cleanName = name.replace("|", " ").trim()
|
||||
val weightStr = if (weight != null && weight > 0.0) {
|
||||
if (weight % 1.0 == 0.0) weight.toInt().toString() else String.format(Locale.US, "%.1f", weight)
|
||||
} else {
|
||||
""
|
||||
}
|
||||
return "$cleanName|$weightStr|${unit.code}"
|
||||
}
|
||||
|
||||
fun formatWeight(): String? {
|
||||
if (weight == null || weight <= 0.0) return null
|
||||
val numStr = if (weight % 1.0 == 0.0) {
|
||||
weight.toInt().toString()
|
||||
} else {
|
||||
String.format(Locale.FRENCH, "%.1f", weight)
|
||||
}
|
||||
return if (unit == FoodUnit.PORTION) {
|
||||
val plural = if (weight > 1.0) "portions" else "portion"
|
||||
"$numStr $plural"
|
||||
} else {
|
||||
"$numStr ${unit.label}"
|
||||
}
|
||||
}
|
||||
|
||||
fun displayBadge(): String {
|
||||
val w = formatWeight()
|
||||
return if (w != null) "$name • $w" else name
|
||||
}
|
||||
|
||||
fun displayCsv(): String {
|
||||
val w = formatWeight()
|
||||
return if (w != null) "$name ($w)" else name
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun deserialize(raw: String): MealFoodItem? {
|
||||
val trimmed = raw.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
val parts = trimmed.split("|")
|
||||
val name = parts.getOrNull(0)?.trim().orEmpty()
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@IgnoreExtraProperties
|
||||
data class CustomFoodEntry(
|
||||
@DocumentId val id: String = "",
|
||||
val userId: String = "",
|
||||
val name: String = "",
|
||||
val defaultUnit: String = FoodUnit.G.code,
|
||||
@ServerTimestamp val createdAt: Timestamp? = null,
|
||||
@ServerTimestamp val updatedAt: Timestamp? = null
|
||||
)
|
||||
|
||||
@IgnoreExtraProperties
|
||||
data class MealEntry(
|
||||
@DocumentId val id: String = "",
|
||||
val userId: String = "",
|
||||
val mealType: String = MealType.LUNCH.name,
|
||||
val mealTimestamp: Long = System.currentTimeMillis(),
|
||||
val hungerBefore: Int = 5,
|
||||
val satietyAfter: Int = 7,
|
||||
val note: String = "",
|
||||
val foodItemsSerialized: List<String> = emptyList(),
|
||||
val photosBase64: List<String> = emptyList(),
|
||||
@ServerTimestamp val createdAt: Timestamp? = null,
|
||||
@ServerTimestamp val updatedAt: Timestamp? = null
|
||||
) {
|
||||
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),
|
||||
"photosBase64" to photosBase64,
|
||||
"createdAt" to createdAt,
|
||||
"updatedAt" to updatedAt
|
||||
)
|
||||
return map.filterValues { it != null }
|
||||
}
|
||||
}
|
||||
|
||||
enum class MealType(val displayName: String, val defaultTime: String) {
|
||||
BREAKFAST("Petit-déjeuner", "08:00"),
|
||||
LUNCH("Déjeuner", "12:30"),
|
||||
SNACK("Collation", "16:30"),
|
||||
DINNER("Dîner", "20:00");
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String): MealType {
|
||||
return entries.firstOrNull { it.name.equals(value, ignoreCase = true) } ?: LUNCH
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object DefaultFoodCatalog {
|
||||
data class CatalogFood(val name: String, val defaultUnit: FoodUnit = FoodUnit.G)
|
||||
|
||||
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)
|
||||
)
|
||||
}
|
||||
|
||||
object HungerSatietyScale {
|
||||
const val MAX_SCALE = 10
|
||||
|
||||
val hungerDescriptions = mapOf(
|
||||
1 to "Aucune faim (envie émotionnelle ou habitude)",
|
||||
2 to "Très légère pensée pour la nourriture",
|
||||
3 to "Début de faim douce et calme",
|
||||
4 to "Petite faim agréable, bon moment pour préparer",
|
||||
5 to "Faim modérée et équilibrée",
|
||||
6 to "Faim bien présente, l'estomac réclame",
|
||||
7 to "Grande faim nette, baisse d'attention",
|
||||
8 to "Faim très forte, impatience de manger",
|
||||
9 to "Faim intense avec baisse d'énergie",
|
||||
10 to "Affamé / Hypoglycémie (faim extrême)"
|
||||
)
|
||||
|
||||
val satietyDescriptions = mapOf(
|
||||
1 to "Encore très faim, comme avant le repas",
|
||||
2 to "Très peu calé, faim encore marquée",
|
||||
3 to "À peine rassasié, besoin de continuer",
|
||||
4 to "Légèrement calé mais encore un petit creux",
|
||||
5 to "Neutre, ni faim ni vraiment rassasié",
|
||||
6 to "Agréablement calé, sensation légère (zone optimale)",
|
||||
7 to "Satiété idéale et confortable (zone optimale)",
|
||||
8 to "Bien rassasié et pleinement satisfait (zone optimale)",
|
||||
9 to "Un peu trop plein, lourdeur digestive",
|
||||
10 to "Trop plein inconfortable / ballonnements"
|
||||
)
|
||||
|
||||
fun getHungerLabel(level: Int): String =
|
||||
hungerDescriptions[level.coerceIn(1, 10)] ?: "Niveau $level/10"
|
||||
|
||||
fun getSatietyLabel(level: Int): String =
|
||||
satietyDescriptions[level.coerceIn(1, 10)] ?: "Niveau $level/10"
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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)
|
||||
put("email", provider.email)
|
||||
}
|
||||
} ?: emptyList()
|
||||
|
||||
val authInfoJson = JSONObject().apply {
|
||||
put("userId", currentUser?.uid)
|
||||
put("email", currentUser?.email)
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package com.example.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import com.example.R
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.google.firebase.Firebase
|
||||
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
|
||||
|
||||
class MealRepository(private val db: FirebaseFirestore) {
|
||||
|
||||
constructor(context: Context) : this(
|
||||
FirebaseFirestore.getInstance(
|
||||
context.applicationContext.getString(R.string.firestore_database_id)
|
||||
)
|
||||
)
|
||||
|
||||
private val auth = Firebase.auth
|
||||
|
||||
private fun requireUserId(): String {
|
||||
return auth.currentUser?.uid
|
||||
?: throw IllegalStateException("User must be signed in with Google before accessing Firestore.")
|
||||
}
|
||||
|
||||
fun observeMeals(): Flow<List<MealEntry>> = flow {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/meals"
|
||||
emitAll(
|
||||
db.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>> = flow {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/custom_foods"
|
||||
emitAll(
|
||||
db.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 uid = requireUserId()
|
||||
val trimmedName = name.trim().take(100)
|
||||
if (trimmedName.isBlank()) return Result.failure(IllegalArgumentException("Food name is blank"))
|
||||
|
||||
val slugId = Normalizer.normalize(trimmedName.lowercase(), Normalizer.Form.NFD)
|
||||
.replace(Regex("[^a-z0-9]+"), "_")
|
||||
.trim('_')
|
||||
.take(64)
|
||||
.ifEmpty { "food_${System.currentTimeMillis()}" }
|
||||
|
||||
val docRef = db.collection("users").document(uid).collection("custom_foods").document(slugId)
|
||||
return 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()
|
||||
Result.success(slugId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.CREATE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getMealById(mealId: String, ownerId: String = requireUserId()): Result<MealEntry> {
|
||||
val path = "users/$ownerId/meals/$mealId"
|
||||
return try {
|
||||
val doc = db.collection("users").document(ownerId).collection("meals").document(mealId).get().await()
|
||||
val entry = doc.toObject(MealEntry::class.java)
|
||||
if (entry != null) {
|
||||
Result.success(entry)
|
||||
} else {
|
||||
Result.failure(NoSuchElementException("Meal not found"))
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.GET, path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun addMeal(meal: MealEntry): Result<String> {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/meals"
|
||||
return try {
|
||||
val mealsRef = db.collection("users").document(uid).collection("meals")
|
||||
val payload = meal.toMap() + mapOf(
|
||||
"userId" to uid,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
val docRef = mealsRef.add(payload).await()
|
||||
Result.success(docRef.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.CREATE, path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun updateMeal(meal: MealEntry): Result<Unit> {
|
||||
val uid = requireUserId()
|
||||
require(meal.id.isNotBlank()) { "Meal ID must not be blank for update" }
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(meal.id)
|
||||
return 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),
|
||||
"photosBase64" to meal.photosBase64,
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
docRef.update(updates).await()
|
||||
Result.success(Unit)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteMeal(mealId: String): Result<Unit> {
|
||||
val uid = requireUserId()
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
|
||||
return try {
|
||||
docRef.delete().await()
|
||||
Result.success(Unit)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.DELETE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.example.notification
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.example.MainActivity
|
||||
import com.example.R
|
||||
import com.example.data.model.MealType
|
||||
import com.example.receiver.MealReminderReceiver
|
||||
import java.util.Calendar
|
||||
|
||||
object MealNotificationManager {
|
||||
|
||||
const val CHANNEL_ID = "meal_reminders_channel"
|
||||
const val CHANNEL_NAME = "Rappels de Repas"
|
||||
const val EXTRA_MEAL_TYPE = "extra_meal_type"
|
||||
const val ACTION_LOG_MEAL = "com.example.action.LOG_MEAL"
|
||||
|
||||
fun createNotificationChannel(context: Context) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val importance = NotificationManager.IMPORTANCE_DEFAULT
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
CHANNEL_NAME,
|
||||
importance
|
||||
).apply {
|
||||
description = "Rappels personnalisés pour noter vos sensations de faim et satiété à table."
|
||||
enableVibration(true)
|
||||
}
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
|
||||
fun showMealNotification(context: Context, mealType: MealType) {
|
||||
createNotificationChannel(context)
|
||||
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
|
||||
action = ACTION_LOG_MEAL
|
||||
putExtra(EXTRA_MEAL_TYPE, mealType.name)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
mealType.ordinal,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
|
||||
)
|
||||
|
||||
val (title, body) = when (mealType) {
|
||||
MealType.BREAKFAST -> Pair("C'est l'heure du petit-déjeuner ☀️", "Prenez 15 secondes pour évaluer votre faim et immortaliser votre assiette.")
|
||||
MealType.LUNCH -> Pair("Pause déjeuner bien méritée 🥗", "Comment est votre faim ? Prenez le temps de savourer et notez vos sensations.")
|
||||
MealType.SNACK -> Pair("Moment de la collation 🍎", "Envie gourmande ou vrai besoin énergétique ? Notez votre ressenti sur Satiéa.")
|
||||
MealType.DINNER -> Pair("C'est l'heure du dîner 🌙", "Terminez votre journée en douceur en notant votre niveau de faim et votre assiette.")
|
||||
}
|
||||
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(pendingIntent)
|
||||
.addAction(
|
||||
R.mipmap.ic_launcher,
|
||||
"Noter mon repas",
|
||||
pendingIntent
|
||||
)
|
||||
.build()
|
||||
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.notify(mealType.ordinal + 100, notification)
|
||||
}
|
||||
|
||||
fun scheduleDailyReminder(context: Context, mealType: MealType, hour: Int, minute: Int, enabled: Boolean) {
|
||||
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
|
||||
|
||||
val intent = Intent(context, MealReminderReceiver::class.java).apply {
|
||||
putExtra(EXTRA_MEAL_TYPE, mealType.name)
|
||||
}
|
||||
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
mealType.ordinal,
|
||||
intent,
|
||||
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
|
||||
)
|
||||
|
||||
if (!enabled) {
|
||||
alarmManager.cancel(pendingIntent)
|
||||
return
|
||||
}
|
||||
|
||||
val calendar = Calendar.getInstance().apply {
|
||||
timeInMillis = System.currentTimeMillis()
|
||||
set(Calendar.HOUR_OF_DAY, hour)
|
||||
set(Calendar.MINUTE, minute)
|
||||
set(Calendar.SECOND, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
if (timeInMillis <= System.currentTimeMillis()) {
|
||||
add(Calendar.DAY_OF_YEAR, 1)
|
||||
}
|
||||
}
|
||||
|
||||
alarmManager.setInexactRepeating(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
AlarmManager.INTERVAL_DAY,
|
||||
pendingIntent
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.receiver
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import com.example.data.model.MealType
|
||||
import com.example.notification.MealNotificationManager
|
||||
|
||||
class MealReminderReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val mealTypeName = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)
|
||||
val mealType = if (mealTypeName != null) {
|
||||
MealType.fromString(mealTypeName)
|
||||
} else {
|
||||
MealType.LUNCH
|
||||
}
|
||||
MealNotificationManager.showMealNotification(context, mealType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package com.example.ui.auth
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
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
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.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.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
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.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
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 kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.tasks.await
|
||||
|
||||
@Composable
|
||||
fun AuthScreen(
|
||||
onAuthSuccess: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val credentialManager = remember { CredentialManager.create(context) }
|
||||
var isLoading by remember { mutableStateOf(false) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 28.dp, vertical = 32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Spacer(modifier = Modifier.height(24.dp))
|
||||
|
||||
// Logo & Hero Section
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.size(88.dp)
|
||||
.clip(CircleShape),
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Restaurant,
|
||||
contentDescription = "Logo Satiéa",
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(44.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
Text(
|
||||
text = "Satiéa",
|
||||
style = MaterialTheme.typography.displayMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = "Journal de repas & écoute de soi",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
// Benefits cards
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(14.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."
|
||||
)
|
||||
FeaturePill(
|
||||
icon = Icons.Default.Timeline,
|
||||
title = "Statistiques 7 jours",
|
||||
subtitle = "Suivez votre équilibre digestif et la régularité de vos habitudes."
|
||||
)
|
||||
FeaturePill(
|
||||
icon = Icons.Default.CloudDone,
|
||||
title = "Synchronisation Cloud sécurisée",
|
||||
subtitle = "Vos repas et photos d'assiettes accessibles sur tous vos appareils."
|
||||
)
|
||||
}
|
||||
|
||||
// Sign In Button
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
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
|
||||
}
|
||||
)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(54.dp)
|
||||
.testTag("google_signin_button"),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||
),
|
||||
enabled = !isLoading
|
||||
) {
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(24.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudDone,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = "Continuer avec Google",
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Text(
|
||||
text = "Connexion sécurisée via Google • Sans publicité",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.5f),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
SnackbarHost(
|
||||
hostState = snackbarHostState,
|
||||
modifier = Modifier.align(Alignment.BottomCenter)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FeaturePill(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
subtitle: String
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surface
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(14.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 16.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,633 @@
|
||||
package com.example.ui.journal
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.compose.foundation.Image
|
||||
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.filled.Add
|
||||
import androidx.compose.material.icons.filled.CalendarMonth
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Restaurant
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
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.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.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.unit.dp
|
||||
import com.example.data.model.HungerSatietyScale
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import com.example.util.ImageUtils
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
@Composable
|
||||
fun JournalScreen(
|
||||
mealsUiState: MealsUiState,
|
||||
onAddMealClick: () -> Unit,
|
||||
onEditMeal: (MealEntry) -> Unit,
|
||||
onDeleteMeal: (String) -> Unit,
|
||||
onExportCsvClick: (List<MealEntry>) -> Unit
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
) {
|
||||
when (mealsUiState) {
|
||||
is MealsUiState.Loading -> {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.testTag("journal_loading_indicator")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MealsUiState.Error -> {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(
|
||||
text = mealsUiState.message,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MealsUiState.Success -> {
|
||||
val meals = mealsUiState.meals
|
||||
val todayCalendar = Calendar.getInstance().apply {
|
||||
set(Calendar.HOUR_OF_DAY, 0)
|
||||
set(Calendar.MINUTE, 0)
|
||||
set(Calendar.SECOND, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}
|
||||
val todayStartMillis = todayCalendar.timeInMillis
|
||||
val todayEndMillis = todayStartMillis + (24L * 60 * 60 * 1000) - 1
|
||||
val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis }
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.testTag("journal_meals_list"),
|
||||
contentPadding = PaddingValues(
|
||||
start = 20.dp,
|
||||
end = 20.dp,
|
||||
top = 16.dp,
|
||||
bottom = 96.dp
|
||||
),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
item {
|
||||
DailyOverviewCard(todayMeals = todayMeals)
|
||||
}
|
||||
|
||||
if (meals.isEmpty()) {
|
||||
item {
|
||||
EmptyMealsView(onAddMealClick = onAddMealClick)
|
||||
}
|
||||
} else {
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 6.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Historique des repas (${meals.size})",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
TextButton(
|
||||
onClick = { onExportCsvClick(meals) },
|
||||
modifier = Modifier.testTag("journal_export_csv_button")
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileDownload,
|
||||
contentDescription = "Exporter en CSV",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = "Export CSV",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items(meals, key = { it.id.ifEmpty { it.mealTimestamp.toString() } }) { meal ->
|
||||
MealCardItem(
|
||||
meal = meal,
|
||||
onEdit = { onEditMeal(meal) },
|
||||
onDelete = { onDeleteMeal(meal.id) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FloatingActionButton(
|
||||
onClick = onAddMealClick,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(24.dp)
|
||||
.testTag("add_meal_fab"),
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary,
|
||||
shape = CircleShape
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Add,
|
||||
contentDescription = "Ajouter un repas",
|
||||
modifier = Modifier.size(28.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
|
||||
val dateFormat = remember { SimpleDateFormat("EEEE d MMMM", Locale.FRENCH) }
|
||||
val todayFormatted = remember {
|
||||
dateFormat.format(Date()).replaceFirstChar {
|
||||
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
||||
}
|
||||
}
|
||||
|
||||
val avgSatiety = if (todayMeals.isNotEmpty()) {
|
||||
todayMeals.map { it.satietyAfter }.average().toFloat()
|
||||
} else 0f
|
||||
|
||||
val comfortStatus = when {
|
||||
todayMeals.isEmpty() -> "En attente du premier repas"
|
||||
avgSatiety in 5.5f..8.2f -> "Zone de confort optimale (6–8/10) ✨"
|
||||
avgSatiety > 8.2f -> "Tendance aux repas très copieux (>8/10)"
|
||||
else -> "Sensations de faim encore présentes (<6/10)"
|
||||
}
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("daily_overview_card"),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.7f)
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = todayFormatted,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Surface(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)
|
||||
) {
|
||||
Text(
|
||||
text = "${todayMeals.size} repas aujourd'hui",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp),
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.Bottom
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
text = "Satiété moyenne aujourd'hui",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = if (todayMeals.isNotEmpty()) String.format(Locale.FRENCH, "%.1f / 10", avgSatiety) else "— / 10",
|
||||
style = MaterialTheme.typography.displayMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = comfortStatus,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
fontWeight = FontWeight.Medium,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(160.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun MealCardItem(
|
||||
meal: MealEntry,
|
||||
onEdit: () -> Unit,
|
||||
onDelete: () -> Unit
|
||||
) {
|
||||
var showMenu by remember { mutableStateOf(false) }
|
||||
var showDeleteDialog by remember { mutableStateOf(false) }
|
||||
val dateTimeFormat = remember { SimpleDateFormat("EEE d MMM yyyy • HH:mm", Locale.FRENCH) }
|
||||
val mealType = MealType.fromString(meal.mealType)
|
||||
val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() }
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onEdit() }
|
||||
.testTag("meal_card_${meal.id}"),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(18.dp)
|
||||
) {
|
||||
// Top row: Type, Date & Time, Options
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Text(
|
||||
text = mealType.displayName,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable { onEdit() }
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CalendarMonth,
|
||||
contentDescription = "Modifier la date",
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(14.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(
|
||||
text = dateTimeFormat.format(Date(meal.mealTimestamp)).replaceFirstChar {
|
||||
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Box {
|
||||
IconButton(
|
||||
onClick = { showMenu = true },
|
||||
modifier = Modifier.size(32.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.MoreVert,
|
||||
contentDescription = "Options du repas",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
DropdownMenu(
|
||||
expanded = showMenu,
|
||||
onDismissRequest = { showMenu = false }
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Corriger date / aliments / note") },
|
||||
leadingIcon = { Icon(Icons.Default.Edit, contentDescription = null) },
|
||||
onClick = {
|
||||
showMenu = false
|
||||
onEdit()
|
||||
}
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Supprimer", color = MaterialTheme.colorScheme.error) },
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
showMenu = false
|
||||
showDeleteDialog = true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
// Dual Gauge: Hunger /10 -> Satiety /10
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(14.dp)
|
||||
)
|
||||
.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Faim avant",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Text(
|
||||
text = "${meal.hungerBefore} / 10",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.secondary,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = HungerSatietyScale.getHungerLabel(meal.hungerBefore),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "→",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 8.dp)
|
||||
)
|
||||
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalAlignment = Alignment.End
|
||||
) {
|
||||
Text(
|
||||
text = "Satiété après",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Text(
|
||||
text = "${meal.satietyAfter} / 10",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = HungerSatietyScale.getSatietyLabel(meal.satietyAfter),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.End
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Food Items Badges (with optional weights)
|
||||
if (parsedFoods.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
text = "Composition de l'assiette",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
FlowRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
parsedFoods.forEach { food ->
|
||||
Surface(
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.14f)
|
||||
) {
|
||||
Text(
|
||||
text = food.displayBadge(),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.Medium,
|
||||
modifier = Modifier.padding(horizontal = 10.dp, vertical = 5.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Photos Carousel
|
||||
if (meal.photosBase64.isNotEmpty()) {
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
LazyRow(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
items(meal.photosBase64) { b64 ->
|
||||
val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) }
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = "Photo assiette",
|
||||
modifier = Modifier
|
||||
.size(76.dp)
|
||||
.clip(RoundedCornerShape(12.dp)),
|
||||
contentScale = ContentScale.Crop
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Global Note
|
||||
if (meal.note.isNotBlank()) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Text(
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showDeleteDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDeleteDialog = false },
|
||||
title = { Text("Supprimer ce repas ?") },
|
||||
text = { Text("Cette action est irréversible et supprimera le repas de votre historique synchronisé.") },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
showDeleteDialog = false
|
||||
onDelete()
|
||||
}
|
||||
) {
|
||||
Text("Supprimer", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDeleteDialog = false }) {
|
||||
Text("Annuler")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EmptyMealsView(onAddMealClick: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 40.dp, horizontal = 20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(80.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Restaurant,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(38.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
Text(
|
||||
text = "Aucun repas pour le moment",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
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.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
TextButton(
|
||||
onClick = onAddMealClick,
|
||||
modifier = Modifier.testTag("empty_state_add_button")
|
||||
) {
|
||||
Text(
|
||||
text = "+ Noter mon premier repas",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package com.example.ui.journal
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
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.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.repository.MealRepository
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.example.util.CsvExporter
|
||||
import com.google.firebase.firestore.FirebaseFirestoreException
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Locale
|
||||
|
||||
sealed interface MealsUiState {
|
||||
object Loading : MealsUiState
|
||||
data class Success(val meals: List<MealEntry>) : MealsUiState
|
||||
data class Error(val message: String) : MealsUiState
|
||||
}
|
||||
|
||||
data class DayStat(
|
||||
val dayLabel: String,
|
||||
val dayShortName: String,
|
||||
val timestampMillis: Long,
|
||||
val avgSatiety: Float,
|
||||
val avgHunger: Float,
|
||||
val mealCount: Int
|
||||
)
|
||||
|
||||
data class WeeklyStats(
|
||||
val dailyStats: List<DayStat>,
|
||||
val averageSatiety: Float,
|
||||
val averageHunger: Float,
|
||||
val optimalZonePercentage: Int,
|
||||
val totalMealsLast7Days: Int,
|
||||
val mealTypeDistribution: Map<MealType, Int>
|
||||
)
|
||||
|
||||
class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private val repository = MealRepository(application)
|
||||
private val context = application.applicationContext
|
||||
|
||||
val mealsState: StateFlow<MealsUiState> = repository.observeMeals()
|
||||
.map<List<MealEntry>, MealsUiState> { meals ->
|
||||
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"))
|
||||
}
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000L),
|
||||
initialValue = MealsUiState.Loading
|
||||
)
|
||||
|
||||
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
|
||||
emit(emptyList())
|
||||
}
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000L),
|
||||
initialValue = emptyList()
|
||||
)
|
||||
|
||||
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
|
||||
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
|
||||
|
||||
fun setThemeMode(mode: AppThemeMode) {
|
||||
_themeMode.value = mode
|
||||
}
|
||||
|
||||
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()
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun addCustomFoodDirectly(name: String, unit: com.example.data.model.FoodUnit) {
|
||||
val cleanName = name.trim()
|
||||
if (cleanName.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
repository.saveCustomFood(cleanName, unit)
|
||||
}
|
||||
}
|
||||
|
||||
fun addMeal(
|
||||
mealType: MealType,
|
||||
mealTimestamp: Long,
|
||||
hungerBefore: Int,
|
||||
satietyAfter: Int,
|
||||
note: String,
|
||||
foodItems: List<MealFoodItem>,
|
||||
photosBase64: List<String>,
|
||||
onSuccess: () -> Unit = {},
|
||||
onError: (String) -> Unit = {}
|
||||
) {
|
||||
enrichCatalogWithFoodItems(foodItems)
|
||||
viewModelScope.launch {
|
||||
val entry = MealEntry(
|
||||
mealType = mealType.name,
|
||||
mealTimestamp = mealTimestamp,
|
||||
hungerBefore = hungerBefore.coerceIn(1, 10),
|
||||
satietyAfter = satietyAfter.coerceIn(1, 10),
|
||||
note = note.trim(),
|
||||
foodItemsSerialized = foodItems.map { it.serialize() }.take(30),
|
||||
photosBase64 = photosBase64
|
||||
)
|
||||
val result = repository.addMeal(entry)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun updateMeal(
|
||||
meal: MealEntry,
|
||||
foodItems: List<MealFoodItem>,
|
||||
onSuccess: () -> Unit = {},
|
||||
onError: (String) -> Unit = {}
|
||||
) {
|
||||
enrichCatalogWithFoodItems(foodItems)
|
||||
viewModelScope.launch {
|
||||
val sanitizedMeal = meal.copy(
|
||||
hungerBefore = meal.hungerBefore.coerceIn(1, 10),
|
||||
satietyAfter = meal.satietyAfter.coerceIn(1, 10),
|
||||
foodItemsSerialized = foodItems.map { it.serialize() }.take(30)
|
||||
)
|
||||
val result = repository.updateMeal(sanitizedMeal)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteMeal(
|
||||
mealId: String,
|
||||
onSuccess: () -> Unit = {},
|
||||
onError: (String) -> Unit = {}
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = repository.deleteMeal(mealId)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun exportCsvToUri(
|
||||
targetUri: Uri,
|
||||
meals: List<MealEntry>,
|
||||
onSuccess: (Int) -> Unit,
|
||||
onError: (String) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = CsvExporter.writeCsvToUri(context, targetUri, meals)
|
||||
result.fold(
|
||||
onSuccess = { count -> onSuccess(count) },
|
||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'export CSV") }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun shareCsv(
|
||||
activityContext: Context,
|
||||
meals: List<MealEntry>,
|
||||
onIntentReady: (Intent) -> Unit,
|
||||
onError: (String) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = CsvExporter.shareCsvFile(activityContext, meals)
|
||||
result.fold(
|
||||
onSuccess = { chooserIntent -> onIntentReady(chooserIntent) },
|
||||
onFailure = { err -> onError(err.localizedMessage ?: "Impossible de préparer le partage CSV") }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun scheduleMealReminder(mealType: MealType, hour: Int, minute: Int, enabled: Boolean) {
|
||||
MealNotificationManager.scheduleDailyReminder(context, mealType, hour, minute, enabled)
|
||||
}
|
||||
|
||||
fun triggerTestNotification(mealType: MealType) {
|
||||
MealNotificationManager.showMealNotification(context, mealType)
|
||||
}
|
||||
|
||||
fun computeWeeklyStats(meals: List<MealEntry>): WeeklyStats {
|
||||
val now = System.currentTimeMillis()
|
||||
val sevenDaysAgo = now - (7L * 24 * 60 * 60 * 1000)
|
||||
|
||||
val endOfToday = Calendar.getInstance().apply {
|
||||
set(Calendar.HOUR_OF_DAY, 23)
|
||||
set(Calendar.MINUTE, 59)
|
||||
set(Calendar.SECOND, 59)
|
||||
set(Calendar.MILLISECOND, 999)
|
||||
}.timeInMillis
|
||||
|
||||
val recentMeals = meals.filter { it.mealTimestamp in sevenDaysAgo..endOfToday }
|
||||
|
||||
val dayFormat = SimpleDateFormat("EEE", Locale.FRENCH)
|
||||
val fullDayFormat = SimpleDateFormat("d MMM", Locale.FRENCH)
|
||||
|
||||
val daysList = mutableListOf<DayStat>()
|
||||
|
||||
for (i in 6 downTo 0) {
|
||||
val dayCal = Calendar.getInstance().apply {
|
||||
timeInMillis = now
|
||||
add(Calendar.DAY_OF_YEAR, -i)
|
||||
set(Calendar.HOUR_OF_DAY, 0)
|
||||
set(Calendar.MINUTE, 0)
|
||||
set(Calendar.SECOND, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}
|
||||
val startOfDay = dayCal.timeInMillis
|
||||
val endOfDay = startOfDay + (24 * 60 * 60 * 1000) - 1
|
||||
|
||||
val dayMeals = meals.filter { it.mealTimestamp in startOfDay..endOfDay }
|
||||
|
||||
val avgSatiety = if (dayMeals.isNotEmpty()) {
|
||||
dayMeals.map { it.satietyAfter }.average().toFloat()
|
||||
} else 0f
|
||||
|
||||
val avgHunger = if (dayMeals.isNotEmpty()) {
|
||||
dayMeals.map { it.hungerBefore }.average().toFloat()
|
||||
} else 0f
|
||||
|
||||
daysList.add(
|
||||
DayStat(
|
||||
dayLabel = fullDayFormat.format(dayCal.time),
|
||||
dayShortName = dayFormat.format(dayCal.time).replace(".", "").replaceFirstChar {
|
||||
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
||||
},
|
||||
timestampMillis = startOfDay,
|
||||
avgSatiety = avgSatiety,
|
||||
avgHunger = avgHunger,
|
||||
mealCount = dayMeals.size
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
val allRecentSatieties = recentMeals.map { it.satietyAfter }
|
||||
val allRecentHungers = recentMeals.map { it.hungerBefore }
|
||||
|
||||
val avgSatiety = if (allRecentSatieties.isNotEmpty()) allRecentSatieties.average().toFloat() else 0f
|
||||
val avgHunger = if (allRecentHungers.isNotEmpty()) allRecentHungers.average().toFloat() else 0f
|
||||
|
||||
val optimalCount = recentMeals.count { it.satietyAfter in 6..8 }
|
||||
val optimalPercentage = if (recentMeals.isNotEmpty()) {
|
||||
((optimalCount.toFloat() / recentMeals.size) * 100).toInt()
|
||||
} else 0
|
||||
|
||||
val distribution = mutableMapOf<MealType, Int>()
|
||||
MealType.entries.forEach { type ->
|
||||
distribution[type] = recentMeals.count { it.mealType.equals(type.name, ignoreCase = true) }
|
||||
}
|
||||
|
||||
return WeeklyStats(
|
||||
dailyStats = daysList,
|
||||
averageSatiety = avgSatiety,
|
||||
averageHunger = avgHunger,
|
||||
optimalZonePercentage = optimalPercentage,
|
||||
totalMealsLast7Days = recentMeals.size,
|
||||
mealTypeDistribution = distribution
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
package com.example.ui.settings
|
||||
|
||||
import android.Manifest
|
||||
import android.os.Build
|
||||
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.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.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
||||
import androidx.compose.material.icons.filled.AccountCircle
|
||||
import androidx.compose.material.icons.filled.Brightness4
|
||||
import androidx.compose.material.icons.filled.CloudDone
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.SwitchDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.credentials.ClearCredentialStateRequest
|
||||
import androidx.credentials.CredentialManager
|
||||
import com.example.data.model.MealType
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
currentThemeMode: AppThemeMode,
|
||||
totalMealsCount: Int,
|
||||
onThemeModeChange: (AppThemeMode) -> Unit,
|
||||
onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit,
|
||||
onTestNotification: (MealType) -> Unit,
|
||||
onSaveCsvClick: () -> Unit,
|
||||
onShareCsvClick: () -> Unit,
|
||||
onSignOut: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val currentUser = Firebase.auth.currentUser
|
||||
|
||||
val reminderStates = remember {
|
||||
mutableStateMapOf(
|
||||
MealType.BREAKFAST to true,
|
||||
MealType.LUNCH to true,
|
||||
MealType.SNACK to false,
|
||||
MealType.DINNER to true
|
||||
)
|
||||
}
|
||||
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { _ -> }
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.testTag("settings_screen"),
|
||||
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(18.dp)
|
||||
) {
|
||||
item {
|
||||
Column {
|
||||
Text(
|
||||
text = "Réglages & Préférences",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Export CSV, rappels personnalisés, thème et compte",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 1. CSV Export Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("settings_csv_export_card"),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.TableChart,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Exporter mes repas (CSV)",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "$totalMealsCount repas prêts à être exportés vers Excel ou Sheets",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = onSaveCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.testTag("settings_save_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileDownload,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Enregistrer")
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = onShareCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.testTag("settings_share_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Share,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Partager")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Reminders Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.NotificationsActive,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Rappels push personnalisés",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Une notification discrète au moment de manger",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(18.dp))
|
||||
|
||||
MealType.entries.forEach { mealType ->
|
||||
val isEnabled = reminderStates[mealType] ?: false
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
text = mealType.displayName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
Text(
|
||||
text = "Heure conseillée: ${mealType.defaultTime}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Switch(
|
||||
checked = isEnabled,
|
||||
onCheckedChange = { checked ->
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && checked) {
|
||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
reminderStates[mealType] = checked
|
||||
val (hour, minute) = when (mealType) {
|
||||
MealType.BREAKFAST -> Pair(8, 0)
|
||||
MealType.LUNCH -> Pair(12, 30)
|
||||
MealType.SNACK -> Pair(16, 30)
|
||||
MealType.DINNER -> Pair(20, 0)
|
||||
}
|
||||
onScheduleReminder(mealType, hour, minute, checked)
|
||||
},
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = MaterialTheme.colorScheme.primary,
|
||||
checkedTrackColor = MaterialTheme.colorScheme.primaryContainer
|
||||
),
|
||||
modifier = Modifier.testTag("switch_${mealType.name.lowercase()}")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(10.dp))
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
onTestNotification(MealType.LUNCH)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("test_notification_button"),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Notifications,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Tester une notification maintenant")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Theme Selector Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.secondaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Brightness4,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Apparence visuelle",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Mode sombre élégant par défaut pour le repos des yeux",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
AppThemeMode.entries.forEach { mode ->
|
||||
val isSelected = currentThemeMode == mode
|
||||
FilterChip(
|
||||
selected = isSelected,
|
||||
onClick = { onThemeModeChange(mode) },
|
||||
label = {
|
||||
Text(
|
||||
text = mode.displayName,
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
},
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 4.dp)
|
||||
.testTag("theme_chip_${mode.name.lowercase()}")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Account & Cloud Sync Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.AccountCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = currentUser?.displayName ?: "Compte connecté",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = currentUser?.email ?: "Synchronisation Cloud Firestore active",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudDone,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Base de données cloud sécurisée • Sauvegarde continue",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
Firebase.auth.signOut()
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
val credManager = CredentialManager.create(context)
|
||||
credManager.clearCredentialState(ClearCredentialStateRequest())
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
onSignOut()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("signout_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error.copy(alpha = 0.15f),
|
||||
contentColor = MaterialTheme.colorScheme.error
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ExitToApp,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Se déconnecter")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(64.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
package com.example.ui.stats
|
||||
|
||||
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.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.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ThumbUp
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
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.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.Path
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
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.MealType
|
||||
import com.example.ui.journal.DayStat
|
||||
import com.example.ui.journal.WeeklyStats
|
||||
import java.util.Locale
|
||||
|
||||
@Composable
|
||||
fun WeeklyStatsScreen(
|
||||
weeklyStats: WeeklyStats,
|
||||
totalMealsCount: Int,
|
||||
onSaveCsvClick: () -> Unit,
|
||||
onShareCsvClick: () -> Unit
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background)
|
||||
.testTag("weekly_stats_screen"),
|
||||
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
item {
|
||||
Column {
|
||||
Text(
|
||||
text = "Suivi Hebdomadaire",
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Évolution de vos sensations (/10) sur les 7 derniers jours",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 7-day Line Chart Card (1 to 10 scale)
|
||||
item {
|
||||
WeeklyChartCard(dailyStats = weeklyStats.dailyStats)
|
||||
}
|
||||
|
||||
// Key metrics cards (/10)
|
||||
item {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
MetricCard(
|
||||
modifier = Modifier.weight(1f),
|
||||
title = "Satiété moyenne",
|
||||
value = if (weeklyStats.totalMealsLast7Days > 0) String.format(Locale.FRENCH, "%.1f", weeklyStats.averageSatiety) else "—",
|
||||
unit = "/ 10",
|
||||
subtitle = "Après repas",
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
|
||||
MetricCard(
|
||||
modifier = Modifier.weight(1f),
|
||||
title = "Faim moyenne",
|
||||
value = if (weeklyStats.totalMealsLast7Days > 0) String.format(Locale.FRENCH, "%.1f", weeklyStats.averageHunger) else "—",
|
||||
unit = "/ 10",
|
||||
subtitle = "Avant repas",
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Optimal Comfort Zone Card (6 to 8 / 10)
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(54.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ThumbUp,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "${weeklyStats.optimalZonePercentage}% en zone de confort",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Part des repas terminés agréablement rassasié (entre 6 et 8 / 10), sans lourdeur ni faim résiduelle.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CSV Export Card (Save to device & Share)
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("stats_csv_export_card"),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Exporter les résultats en CSV",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = "Exportez vos $totalMealsCount repas enregistrés (dates, heures, notes sur 10 et commentaires) au format tableur CSV.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = onSaveCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.testTag("stats_save_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileDownload,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Enregistrer")
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = onShareCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.testTag("stats_share_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Share,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Partager")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Meal type breakdown
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
) {
|
||||
Text(
|
||||
text = "Répartition des repas sur 7 jours",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
MealType.entries.forEach { type ->
|
||||
val count = weeklyStats.mealTypeDistribution[type] ?: 0
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Surface(
|
||||
modifier = Modifier.size(44.dp),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = count.toString(),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
Text(
|
||||
text = type.displayName.take(7),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
item {
|
||||
Spacer(modifier = Modifier.height(64.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WeeklyChartCard(dailyStats: List<DayStat>) {
|
||||
val satietyColor = MaterialTheme.colorScheme.primary
|
||||
val hungerColor = MaterialTheme.colorScheme.secondary
|
||||
val gridColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
||||
val optimalZoneColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.08f)
|
||||
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("weekly_chart_card"),
|
||||
shape = RoundedCornerShape(22.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 = "Courbe 7 jours (sur 10)",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
LegendItem(color = satietyColor, label = "Satiété")
|
||||
LegendItem(color = hungerColor, label = "Faim")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(18.dp))
|
||||
|
||||
// Canvas Chart on 1..10 scale
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(180.dp)
|
||||
) {
|
||||
Canvas(modifier = Modifier.fillMaxSize()) {
|
||||
val width = size.width
|
||||
val height = size.height
|
||||
val bottomPadding = 30f
|
||||
val chartHeight = height - bottomPadding
|
||||
val stepX = if (dailyStats.size > 1) width / (dailyStats.size - 1) else width
|
||||
|
||||
// Draw Optimal Zone band (level 6 to 8 out of 10)
|
||||
val y8 = chartHeight - (8f / 10f) * chartHeight
|
||||
val y6 = chartHeight - (6f / 10f) * chartHeight
|
||||
drawRect(
|
||||
color = optimalZoneColor,
|
||||
topLeft = Offset(0f, y8),
|
||||
size = Size(width, y6 - y8)
|
||||
)
|
||||
|
||||
// Draw horizontal grid lines at 2, 4, 6, 8, 10
|
||||
for (level in listOf(2, 4, 6, 8, 10)) {
|
||||
val y = chartHeight - (level.toFloat() / 10f) * chartHeight
|
||||
drawLine(
|
||||
color = gridColor,
|
||||
start = Offset(0f, y),
|
||||
end = Offset(width, y),
|
||||
strokeWidth = 1.dp.toPx()
|
||||
)
|
||||
}
|
||||
|
||||
val satietyPath = Path()
|
||||
val hungerPath = Path()
|
||||
|
||||
var hasStartedSatiety = false
|
||||
var hasStartedHunger = false
|
||||
|
||||
dailyStats.forEachIndexed { index, stat ->
|
||||
val x = index * stepX
|
||||
|
||||
if (stat.mealCount > 0) {
|
||||
val ySat = chartHeight - (stat.avgSatiety.coerceIn(1f, 10f) / 10f) * chartHeight
|
||||
if (!hasStartedSatiety) {
|
||||
satietyPath.moveTo(x, ySat)
|
||||
hasStartedSatiety = true
|
||||
} else {
|
||||
satietyPath.lineTo(x, ySat)
|
||||
}
|
||||
drawCircle(
|
||||
color = satietyColor,
|
||||
radius = 4.dp.toPx(),
|
||||
center = Offset(x, ySat)
|
||||
)
|
||||
|
||||
val yHunger = chartHeight - (stat.avgHunger.coerceIn(1f, 10f) / 10f) * chartHeight
|
||||
if (!hasStartedHunger) {
|
||||
hungerPath.moveTo(x, yHunger)
|
||||
hasStartedHunger = true
|
||||
} else {
|
||||
hungerPath.lineTo(x, yHunger)
|
||||
}
|
||||
drawCircle(
|
||||
color = hungerColor,
|
||||
radius = 4.dp.toPx(),
|
||||
center = Offset(x, yHunger)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (hasStartedSatiety) {
|
||||
drawPath(
|
||||
path = satietyPath,
|
||||
color = satietyColor,
|
||||
style = Stroke(width = 3.dp.toPx(), cap = StrokeCap.Round)
|
||||
)
|
||||
}
|
||||
|
||||
if (hasStartedHunger) {
|
||||
drawPath(
|
||||
path = hungerPath,
|
||||
color = hungerColor,
|
||||
style = Stroke(width = 2.5.dp.toPx(), cap = StrokeCap.Round)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
dailyStats.forEach { stat ->
|
||||
Text(
|
||||
text = stat.dayShortName,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LegendItem(color: Color, label: String) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(8.dp),
|
||||
shape = CircleShape,
|
||||
color = color
|
||||
) {}
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MetricCard(
|
||||
modifier: Modifier = Modifier,
|
||||
title: String,
|
||||
value: String,
|
||||
unit: String,
|
||||
subtitle: String,
|
||||
color: Color
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(16.dp)) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.height(6.dp))
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
Text(
|
||||
text = value,
|
||||
style = MaterialTheme.typography.displaySmall,
|
||||
color = color,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = " $unit",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = color.copy(alpha = 0.8f),
|
||||
modifier = Modifier.padding(bottom = 4.dp)
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
// Dark Palette (Default & Organic Elegant)
|
||||
val DarkPrimary = Color(0xFF8CD4A8)
|
||||
val DarkOnPrimary = Color(0xFF0F3820)
|
||||
val DarkPrimaryContainer = Color(0xFF1E482E)
|
||||
val DarkOnPrimaryContainer = Color(0xFFC5F2D7)
|
||||
|
||||
val DarkSecondary = Color(0xFFF0B87A)
|
||||
val DarkOnSecondary = Color(0xFF452B07)
|
||||
val DarkSecondaryContainer = Color(0xFF5D3E10)
|
||||
val DarkOnSecondaryContainer = Color(0xFFFCE7CB)
|
||||
|
||||
val DarkTertiary = Color(0xFF8DCED8)
|
||||
val DarkOnTertiary = Color(0xFF00363D)
|
||||
|
||||
val DarkBackground = Color(0xFF111513)
|
||||
val DarkOnBackground = Color(0xFFE2E7E2)
|
||||
val DarkSurface = Color(0xFF191F1C)
|
||||
val DarkOnSurface = Color(0xFFE2E7E2)
|
||||
val DarkSurfaceVariant = Color(0xFF242C27)
|
||||
val DarkOnSurfaceVariant = Color(0xFFBAC3BC)
|
||||
val DarkOutline = Color(0xFF536056)
|
||||
val DarkOutlineVariant = Color(0xFF2C362F)
|
||||
|
||||
// Light Palette (Warm Linen & Forest)
|
||||
val LightPrimary = Color(0xFF246944)
|
||||
val LightOnPrimary = Color(0xFFFFFFFF)
|
||||
val LightPrimaryContainer = Color(0xFFC5F2D7)
|
||||
val LightOnPrimaryContainer = Color(0xFF062112)
|
||||
|
||||
val LightSecondary = Color(0xFF865306)
|
||||
val LightOnSecondary = Color(0xFFFFFFFF)
|
||||
val LightSecondaryContainer = Color(0xFFFCE7CB)
|
||||
val LightOnSecondaryContainer = Color(0xFF2C1700)
|
||||
|
||||
val LightTertiary = Color(0xFF1A6773)
|
||||
val LightOnTertiary = Color(0xFFFFFFFF)
|
||||
|
||||
val LightBackground = Color(0xFFF8F9F5)
|
||||
val LightOnBackground = Color(0xFF191F1C)
|
||||
val LightSurface = Color(0xFFFFFFFF)
|
||||
val LightOnSurface = Color(0xFF191F1C)
|
||||
val LightSurfaceVariant = Color(0xFFE3E9E3)
|
||||
val LightOnSurfaceVariant = Color(0xFF424A44)
|
||||
val LightOutline = Color(0xFF727A73)
|
||||
val LightOutlineVariant = Color(0xFFC2C9C2)
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
|
||||
enum class AppThemeMode(val displayName: String) {
|
||||
DARK("Sombre élégant (défaut)"),
|
||||
LIGHT("Clair lin & forêt"),
|
||||
SYSTEM("Suivre le système")
|
||||
}
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = DarkPrimary,
|
||||
onPrimary = DarkOnPrimary,
|
||||
primaryContainer = DarkPrimaryContainer,
|
||||
onPrimaryContainer = DarkOnPrimaryContainer,
|
||||
secondary = DarkSecondary,
|
||||
onSecondary = DarkOnSecondary,
|
||||
secondaryContainer = DarkSecondaryContainer,
|
||||
onSecondaryContainer = DarkOnSecondaryContainer,
|
||||
tertiary = DarkTertiary,
|
||||
onTertiary = DarkOnTertiary,
|
||||
background = DarkBackground,
|
||||
onBackground = DarkOnBackground,
|
||||
surface = DarkSurface,
|
||||
onSurface = DarkOnSurface,
|
||||
surfaceVariant = DarkSurfaceVariant,
|
||||
onSurfaceVariant = DarkOnSurfaceVariant,
|
||||
outline = DarkOutline,
|
||||
outlineVariant = DarkOutlineVariant
|
||||
)
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = LightPrimary,
|
||||
onPrimary = LightOnPrimary,
|
||||
primaryContainer = LightPrimaryContainer,
|
||||
onPrimaryContainer = LightOnPrimaryContainer,
|
||||
secondary = LightSecondary,
|
||||
onSecondary = LightOnSecondary,
|
||||
secondaryContainer = LightSecondaryContainer,
|
||||
onSecondaryContainer = LightOnSecondaryContainer,
|
||||
tertiary = LightTertiary,
|
||||
onTertiary = LightOnTertiary,
|
||||
background = LightBackground,
|
||||
onBackground = LightOnBackground,
|
||||
surface = LightSurface,
|
||||
onSurface = LightOnSurface,
|
||||
surfaceVariant = LightSurfaceVariant,
|
||||
onSurfaceVariant = LightOnSurfaceVariant,
|
||||
outline = LightOutline,
|
||||
outlineVariant = LightOutlineVariant
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SatieaTheme(
|
||||
themeMode: AppThemeMode = AppThemeMode.DARK,
|
||||
dynamicColor: Boolean = false,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val darkTheme = when (themeMode) {
|
||||
AppThemeMode.DARK -> true
|
||||
AppThemeMode.LIGHT -> false
|
||||
AppThemeMode.SYSTEM -> isSystemInDarkTheme()
|
||||
}
|
||||
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = Typography,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example.ui.theme
|
||||
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.Font
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.example.R
|
||||
|
||||
val FrauncesFontFamily = FontFamily(
|
||||
Font(R.font.fraunces, FontWeight.Normal),
|
||||
Font(R.font.fraunces, FontWeight.SemiBold),
|
||||
Font(R.font.fraunces, FontWeight.Bold)
|
||||
)
|
||||
|
||||
val PlusJakartaSansFontFamily = FontFamily(
|
||||
Font(R.font.plus_jakarta_sans, FontWeight.Normal),
|
||||
Font(R.font.plus_jakarta_sans, FontWeight.Medium),
|
||||
Font(R.font.plus_jakarta_sans, FontWeight.SemiBold),
|
||||
Font(R.font.plus_jakarta_sans, FontWeight.Bold)
|
||||
)
|
||||
|
||||
val Typography = Typography(
|
||||
displayLarge = TextStyle(
|
||||
fontFamily = FrauncesFontFamily,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 40.sp,
|
||||
lineHeight = 48.sp,
|
||||
letterSpacing = (-0.5).sp
|
||||
),
|
||||
displayMedium = TextStyle(
|
||||
fontFamily = FrauncesFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 32.sp,
|
||||
lineHeight = 38.sp
|
||||
),
|
||||
headlineLarge = TextStyle(
|
||||
fontFamily = FrauncesFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 26.sp,
|
||||
lineHeight = 32.sp
|
||||
),
|
||||
headlineMedium = TextStyle(
|
||||
fontFamily = FrauncesFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 22.sp,
|
||||
lineHeight = 28.sp
|
||||
),
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FrauncesFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 19.sp,
|
||||
lineHeight = 24.sp
|
||||
),
|
||||
titleMedium = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 22.sp
|
||||
),
|
||||
titleSmall = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp
|
||||
),
|
||||
bodyLarge = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp
|
||||
),
|
||||
bodyMedium = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp
|
||||
),
|
||||
bodySmall = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp
|
||||
),
|
||||
labelLarge = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp
|
||||
),
|
||||
labelMedium = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = PlusJakartaSansFontFamily,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 14.sp
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.example.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.core.content.FileProvider
|
||||
import com.example.data.model.HungerSatietyScale
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object CsvExporter {
|
||||
|
||||
fun buildDefaultFileName(): String {
|
||||
val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(Date())
|
||||
return "satiea_repas_$dateStr.csv"
|
||||
}
|
||||
|
||||
fun generateCsvContent(meals: List<MealEntry>): String {
|
||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
||||
|
||||
val sb = StringBuilder()
|
||||
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
|
||||
sb.append('\uFEFF')
|
||||
sb.appendLine("Date,Heure,Type de repas,Faim avant (/10),Ressenti faim,Satiété après (/10),Ressenti satiété,Aliments & Poids,Note globale,Photos jointes")
|
||||
|
||||
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
||||
for (meal in sortedMeals) {
|
||||
val dateObj = Date(meal.mealTimestamp)
|
||||
val dateStr = dateFormat.format(dateObj)
|
||||
val timeStr = timeFormat.format(dateObj)
|
||||
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
||||
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
||||
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
||||
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
||||
val cleanNote = escapeCsvField(meal.note)
|
||||
val photoCount = meal.photosBase64.size
|
||||
|
||||
sb.append(escapeCsvField(dateStr)).append(',')
|
||||
sb.append(escapeCsvField(timeStr)).append(',')
|
||||
sb.append(escapeCsvField(mealTypeLabel)).append(',')
|
||||
sb.append(meal.hungerBefore).append(',')
|
||||
sb.append(escapeCsvField(hungerLabel)).append(',')
|
||||
sb.append(meal.satietyAfter).append(',')
|
||||
sb.append(escapeCsvField(satietyLabel)).append(',')
|
||||
sb.append(escapeCsvField(foodsFormatted)).append(',')
|
||||
sb.append(cleanNote).append(',')
|
||||
sb.append(photoCount)
|
||||
sb.appendLine()
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
private fun escapeCsvField(value: String): String {
|
||||
val sanitized = value.replace("\r\n", " ").replace("\n", " ").trim()
|
||||
return if (sanitized.contains(",") || sanitized.contains("\"") || sanitized.contains(";")) {
|
||||
"\"${sanitized.replace("\"", "\"\"")}\""
|
||||
} else {
|
||||
sanitized
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun writeCsvToUri(context: Context, targetUri: Uri, meals: List<MealEntry>): Result<Int> =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val csvContent = generateCsvContent(meals)
|
||||
context.contentResolver.openOutputStream(targetUri)?.use { outputStream ->
|
||||
outputStream.write(csvContent.toByteArray(Charsets.UTF_8))
|
||||
outputStream.flush()
|
||||
} ?: return@withContext Result.failure(IllegalStateException("Impossible d'ouvrir le fichier de destination"))
|
||||
Result.success(meals.size)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun shareCsvFile(context: Context, meals: List<MealEntry>): Result<Intent> =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val csvContent = generateCsvContent(meals)
|
||||
val exportDir = File(context.cacheDir, "exports").apply { mkdirs() }
|
||||
val csvFile = File(exportDir, buildDefaultFileName())
|
||||
csvFile.writeText(csvContent, Charsets.UTF_8)
|
||||
|
||||
val authority = "${context.packageName}.fileprovider"
|
||||
val contentUri = FileProvider.getUriForFile(context, authority, csvFile)
|
||||
|
||||
val shareIntent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = "text/csv"
|
||||
putExtra(Intent.EXTRA_SUBJECT, "Export Satiéa — Journal des repas")
|
||||
putExtra(Intent.EXTRA_STREAM, contentUri)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
Result.success(Intent.createChooser(shareIntent, "Partager le fichier CSV"))
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.example.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.InputStream
|
||||
|
||||
object ImageUtils {
|
||||
|
||||
suspend fun uriToBase64(context: Context, uri: Uri, maxWidth: Int = 480, maxHeight: Int = 480): String? =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
var inputStream: InputStream? = context.contentResolver.openInputStream(uri) ?: return@withContext null
|
||||
|
||||
// Decode bounds first
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
inputStream?.close()
|
||||
|
||||
// Calculate inSampleSize
|
||||
var inSampleSize = 1
|
||||
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
|
||||
val halfHeight = options.outHeight / 2
|
||||
val halfWidth = options.outWidth / 2
|
||||
while (halfHeight / inSampleSize >= maxHeight && halfWidth / inSampleSize >= maxWidth) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
|
||||
// Decode actual bitmap
|
||||
val decodeOptions = BitmapFactory.Options().apply {
|
||||
this.inSampleSize = inSampleSize
|
||||
}
|
||||
inputStream = context.contentResolver.openInputStream(uri)
|
||||
val originalBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
|
||||
inputStream?.close()
|
||||
|
||||
if (originalBitmap == null) return@withContext null
|
||||
|
||||
// Scale to exact target bounds
|
||||
val scaledBitmap = if (originalBitmap.width > maxWidth || originalBitmap.height > maxHeight) {
|
||||
val ratio = minOf(
|
||||
maxWidth.toFloat() / originalBitmap.width,
|
||||
maxHeight.toFloat() / originalBitmap.height
|
||||
)
|
||||
val targetW = (originalBitmap.width * ratio).toInt().coerceAtLeast(1)
|
||||
val targetH = (originalBitmap.height * ratio).toInt().coerceAtLeast(1)
|
||||
Bitmap.createScaledBitmap(originalBitmap, targetW, targetH, true)
|
||||
} else {
|
||||
originalBitmap
|
||||
}
|
||||
|
||||
val outputStream = ByteArrayOutputStream()
|
||||
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream)
|
||||
val bytes = outputStream.toByteArray()
|
||||
Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun base64ToBitmap(base64Str: String): Bitmap? {
|
||||
return try {
|
||||
val bytes = Base64.decode(base64Str, Base64.DEFAULT)
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 366 KiB |
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<color xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:color="#1A1F1C"/>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item
|
||||
android:width="66dp"
|
||||
android:height="66dp"
|
||||
android:drawable="@drawable/ic_app_icon_fg_1793975344228"
|
||||
android:gravity="center" />
|
||||
</layer-list>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 8.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 39 KiB |
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<resources>
|
||||
<string name="firestore_database_id" translatable="false">ai-studio-android-satia-b3e22121-687b-4d8f-aa0b-476e2d80fc24</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,3 @@
|
||||
<resources>
|
||||
<string name="app_name">Satiéa</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
|
||||
<style name="Theme.MyApplication" parent="android:Theme.DeviceDefault.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample backup rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/guide/topics/data/autobackup
|
||||
for details.
|
||||
Note: This file is ignored for devices older than API 31
|
||||
See https://developer.android.com/about/versions/12/backup-restore
|
||||
-->
|
||||
<full-backup-content>
|
||||
<!--
|
||||
<include domain="sharedpref" path="."/>
|
||||
<exclude domain="sharedpref" path="device.xml"/>
|
||||
-->
|
||||
</full-backup-content>
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="utf-8"?><!--
|
||||
Sample data extraction rules file; uncomment and customize as necessary.
|
||||
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
|
||||
for details.
|
||||
-->
|
||||
<data-extraction-rules>
|
||||
<cloud-backup>
|
||||
<!-- TODO: Use <include> and <exclude> to control what is backed up.
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
-->
|
||||
</cloud-backup>
|
||||
<!--
|
||||
<device-transfer>
|
||||
<include .../>
|
||||
<exclude .../>
|
||||
</device-transfer>
|
||||
-->
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths>
|
||||
<cache-path name="exported_csv" path="exports/" />
|
||||
</paths>
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.example
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [36])
|
||||
class ExampleRobolectricTest {
|
||||
|
||||
@Test
|
||||
fun `read string from context`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val appName = context.getString(R.string.app_name)
|
||||
assertEquals("My Application", appName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.example
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Example local unit test, which will execute on the development machine (host).
|
||||
*
|
||||
* See [testing documentation](http://d.android.com/tools/testing).
|
||||
*/
|
||||
class ExampleUnitTest {
|
||||
@Test
|
||||
fun addition_isCorrect() {
|
||||
assertEquals(4, 2 + 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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)
|
||||
@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()) {
|
||||
val newApp = FirebaseApp.initializeApp(
|
||||
context,
|
||||
FirebaseOptions.Builder()
|
||||
.setApplicationId("com.example.app")
|
||||
.setProjectId(PROJECT_ID)
|
||||
.setApiKey("fake-api-key-for-emulator")
|
||||
.build()
|
||||
)
|
||||
val newFirestore = FirebaseFirestore.getInstance(newApp, databaseId)
|
||||
newFirestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT)
|
||||
newFirestore.firestoreSettings = FirebaseFirestoreSettings.Builder()
|
||||
.setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
|
||||
.build()
|
||||
|
||||
val newAuth = FirebaseAuth.getInstance(newApp)
|
||||
newAuth.useEmulator(EMULATOR_HOST, AUTH_PORT)
|
||||
newApp
|
||||
} else {
|
||||
FirebaseApp.getInstance()
|
||||
}
|
||||
|
||||
firestore = FirebaseFirestore.getInstance(app, databaseId)
|
||||
auth = FirebaseAuth.getInstance(app)
|
||||
}
|
||||
|
||||
@After
|
||||
open fun tearDownFirebase() {
|
||||
auth.signOut()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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,8 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
plugins {
|
||||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.kotlin.compose) apply false
|
||||
alias(libs.plugins.google.devtools.ksp) apply false
|
||||
alias(libs.plugins.secrets) apply false
|
||||
alias(libs.plugins.google.services) apply false
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"entities": {
|
||||
"MealEntry": {
|
||||
"title": "MealEntry",
|
||||
"description": "Repas saisi par l'utilisateur avec son niveau de faim et de satiété sur 10, liste d'aliments avec poids optionnel, photos et note globale.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"userId": {
|
||||
"type": "string",
|
||||
"description": "ID de l'utilisateur propriétaire"
|
||||
},
|
||||
"mealType": {
|
||||
"type": "string",
|
||||
"description": "Type de repas",
|
||||
"enum": ["BREAKFAST", "LUNCH", "SNACK", "DINNER"]
|
||||
},
|
||||
"mealTimestamp": {
|
||||
"type": "integer",
|
||||
"description": "Horodatage sélectionné pour le repas en millisecondes"
|
||||
},
|
||||
"hungerBefore": {
|
||||
"type": "integer",
|
||||
"description": "Niveau de faim avant le repas (1 à 10)"
|
||||
},
|
||||
"satietyAfter": {
|
||||
"type": "integer",
|
||||
"description": "Niveau de satiété après le repas (1 à 10)"
|
||||
},
|
||||
"note": {
|
||||
"type": "string",
|
||||
"description": "Note globale optionnelle sur le repas"
|
||||
},
|
||||
"foodItemsSerialized": {
|
||||
"type": "array",
|
||||
"description": "Liste des aliments du repas avec leur poids et unité optionnels (Nom|Poids|Unité)"
|
||||
},
|
||||
"photosBase64": {
|
||||
"type": "array",
|
||||
"description": "Liste de miniatures d'assiettes encodées en base64"
|
||||
},
|
||||
"createdAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Horodatage serveur de création"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Horodatage serveur de mise à jour"
|
||||
}
|
||||
},
|
||||
"required": ["userId", "mealType", "mealTimestamp", "hungerBefore", "satietyAfter", "createdAt"]
|
||||
},
|
||||
"CustomFoodEntry": {
|
||||
"title": "CustomFoodEntry",
|
||||
"description": "Aliment personnalisé ajouté par l'utilisateur pour enrichir le catalogue d'autocomplétion.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"userId": {
|
||||
"type": "string",
|
||||
"description": "ID de l'utilisateur propriétaire"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Nom de l'aliment"
|
||||
},
|
||||
"defaultUnit": {
|
||||
"type": "string",
|
||||
"description": "Unité par défaut pour cet aliment",
|
||||
"enum": ["g", "ml", "portion"]
|
||||
},
|
||||
"createdAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Horodatage serveur de création"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Horodatage serveur de mise à jour"
|
||||
}
|
||||
},
|
||||
"required": ["userId", "name", "defaultUnit", "createdAt"]
|
||||
},
|
||||
"UserSettings": {
|
||||
"title": "UserSettings",
|
||||
"description": "Préférences utilisateur (thème, rappels).",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"userId": {
|
||||
"type": "string",
|
||||
"description": "ID utilisateur"
|
||||
},
|
||||
"themeMode": {
|
||||
"type": "string",
|
||||
"enum": ["DARK", "LIGHT", "SYSTEM"]
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"description": "Horodatage serveur de mise à jour"
|
||||
}
|
||||
},
|
||||
"required": ["userId", "themeMode"]
|
||||
}
|
||||
},
|
||||
"firestore": {
|
||||
"/users/{userId}/meals/{mealId}": {
|
||||
"schema": "MealEntry",
|
||||
"description": "Collection des repas de l'utilisateur"
|
||||
},
|
||||
"/users/{userId}/custom_foods/{foodId}": {
|
||||
"schema": "CustomFoodEntry",
|
||||
"description": "Catalogue d'aliments enrichi par l'utilisateur"
|
||||
},
|
||||
"/users/{userId}/settings/{settingId}": {
|
||||
"schema": "UserSettings",
|
||||
"description": "Préférences utilisateur"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"firestore": [
|
||||
{
|
||||
"database": "ai-studio-android-satia-b3e22121-687b-4d8f-aa0b-476e2d80fc24",
|
||||
"rules": "firestore.rules"
|
||||
}
|
||||
],
|
||||
"emulators": {
|
||||
"firestore": {
|
||||
"host": "127.0.0.1",
|
||||
"port": 8085
|
||||
},
|
||||
"auth": {
|
||||
"host": "127.0.0.1",
|
||||
"port": 9099
|
||||
},
|
||||
"ui": {
|
||||
"enabled": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
rules_version = '2';
|
||||
service cloud.firestore {
|
||||
match /databases/{database}/documents {
|
||||
|
||||
// Default deny all access
|
||||
match /{document=**} {
|
||||
allow read, write: if false;
|
||||
}
|
||||
|
||||
function isSignedIn() {
|
||||
return request.auth != null;
|
||||
}
|
||||
|
||||
function isOwner(userId) {
|
||||
return isSignedIn() && request.auth.uid == userId;
|
||||
}
|
||||
|
||||
function incoming() {
|
||||
return request.resource.data;
|
||||
}
|
||||
|
||||
function existing() {
|
||||
return resource.data;
|
||||
}
|
||||
|
||||
function isValidId(id) {
|
||||
return id is string && id.size() >= 1 && id.size() <= 128 && id.matches('^[a-zA-Z0-9_\\-]+$');
|
||||
}
|
||||
|
||||
function isValidMealEntry(data) {
|
||||
return data.userId is string &&
|
||||
data.userId == request.auth.uid &&
|
||||
data.mealType in ['BREAKFAST', 'LUNCH', 'SNACK', 'DINNER'] &&
|
||||
data.mealTimestamp is int && data.mealTimestamp > 0 &&
|
||||
data.hungerBefore is int && data.hungerBefore >= 1 && data.hungerBefore <= 10 &&
|
||||
data.satietyAfter is int && data.satietyAfter >= 1 && data.satietyAfter <= 10 &&
|
||||
(!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 1000)) &&
|
||||
(!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || data.foodItemsSerialized[0] is string))) &&
|
||||
(!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 6 && (data.photosBase64.size() == 0 || data.photosBase64[0] is string))) &&
|
||||
(!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time));
|
||||
}
|
||||
|
||||
function isValidCustomFood(data) {
|
||||
return data.userId is string &&
|
||||
data.userId == request.auth.uid &&
|
||||
data.name is string && data.name.size() >= 1 && data.name.size() <= 100 &&
|
||||
data.defaultUnit in ['g', 'ml', 'portion'] &&
|
||||
(!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time));
|
||||
}
|
||||
|
||||
match /users/{userId} {
|
||||
allow get: if isOwner(userId);
|
||||
|
||||
match /meals/{mealId} {
|
||||
allow get, list: if isOwner(userId);
|
||||
|
||||
allow create: if isOwner(userId) &&
|
||||
isValidId(mealId) &&
|
||||
incoming().keys().hasAll(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'createdAt']) &&
|
||||
incoming().keys().hasOnly(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'createdAt', 'updatedAt']) &&
|
||||
incoming().createdAt is timestamp &&
|
||||
incoming().createdAt <= request.time &&
|
||||
isValidMealEntry(incoming());
|
||||
|
||||
allow update: if isOwner(userId) &&
|
||||
isValidId(mealId) &&
|
||||
incoming().userId == existing().userId &&
|
||||
incoming().createdAt == existing().createdAt &&
|
||||
isValidMealEntry(incoming()) &&
|
||||
incoming().diff(existing()).affectedKeys().hasOnly(['mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'updatedAt']);
|
||||
|
||||
allow delete: if isOwner(userId) && isValidId(mealId);
|
||||
}
|
||||
|
||||
match /custom_foods/{foodId} {
|
||||
allow get, list: if isOwner(userId);
|
||||
|
||||
allow create: if isOwner(userId) &&
|
||||
isValidId(foodId) &&
|
||||
incoming().keys().hasAll(['userId', 'name', 'defaultUnit', 'createdAt']) &&
|
||||
incoming().keys().hasOnly(['userId', 'name', 'defaultUnit', 'createdAt', 'updatedAt']) &&
|
||||
incoming().createdAt is timestamp &&
|
||||
incoming().createdAt <= request.time &&
|
||||
isValidCustomFood(incoming());
|
||||
|
||||
allow update: if isOwner(userId) &&
|
||||
isValidId(foodId) &&
|
||||
incoming().userId == existing().userId &&
|
||||
incoming().createdAt == existing().createdAt &&
|
||||
isValidCustomFood(incoming()) &&
|
||||
incoming().diff(existing()).affectedKeys().hasOnly(['name', 'defaultUnit', 'updatedAt']);
|
||||
|
||||
allow delete: if isOwner(userId) && isValidId(foodId);
|
||||
}
|
||||
|
||||
match /settings/{settingId} {
|
||||
allow get, list: if isOwner(userId);
|
||||
|
||||
allow create, update: if isOwner(userId) &&
|
||||
isValidId(settingId) &&
|
||||
incoming().userId == request.auth.uid &&
|
||||
incoming().themeMode in ['DARK', 'LIGHT', 'SYSTEM'] &&
|
||||
(!('updatedAt' in incoming()) || incoming().updatedAt is timestamp);
|
||||
|
||||
allow delete: if isOwner(userId) && isValidId(settingId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
const {
|
||||
initializeTestEnvironment,
|
||||
assertFails,
|
||||
assertSucceeds,
|
||||
} = require("@firebase/rules-unit-testing");
|
||||
const { test, before, after, beforeEach } = require("node:test");
|
||||
const fs = require("node:fs");
|
||||
|
||||
let testEnv;
|
||||
const PROJECT_ID = process.env.GCP_PROJECT || "demo-no-project";
|
||||
const ALICE_UID = "alice_123";
|
||||
const BOB_UID = "bob_456";
|
||||
|
||||
const [emulatorHost, emulatorPortStr] = (process.env.FIRESTORE_EMULATOR_HOST || "127.0.0.1:8085").split(":");
|
||||
const emulatorPort = parseInt(emulatorPortStr, 10);
|
||||
|
||||
before(async () => {
|
||||
const rules = fs.readFileSync("./firestore.rules", "utf8");
|
||||
testEnv = await initializeTestEnvironment({
|
||||
projectId: PROJECT_ID,
|
||||
firestore: {
|
||||
rules,
|
||||
host: emulatorHost,
|
||||
port: emulatorPort,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (testEnv) {
|
||||
await testEnv.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
if (testEnv) {
|
||||
await testEnv.clearFirestore();
|
||||
}
|
||||
});
|
||||
|
||||
// 1. Unauthenticated checks
|
||||
test("Unauthenticated: cannot read or write meals or custom_foods", async () => {
|
||||
const unauthDb = testEnv.unauthenticatedContext().firestore();
|
||||
await assertFails(unauthDb.collection("users").doc(ALICE_UID).collection("meals").get());
|
||||
await assertFails(unauthDb.collection("users").doc(ALICE_UID).collection("custom_foods").get());
|
||||
});
|
||||
|
||||
// 2. Cross-user isolation
|
||||
test("Cross-user: Bob cannot read Alice's meals or custom_foods", async () => {
|
||||
await testEnv.withSecurityRulesDisabled(async (context) => {
|
||||
await context.firestore().collection("users").doc(ALICE_UID).collection("meals").doc("meal_1").set({
|
||||
userId: ALICE_UID,
|
||||
mealType: "DINNER",
|
||||
mealTimestamp: Date.now(),
|
||||
hungerBefore: 7,
|
||||
satietyAfter: 8,
|
||||
foodItemsSerialized: ["Saumon grillé|150|g"],
|
||||
createdAt: new Date(),
|
||||
});
|
||||
await context.firestore().collection("users").doc(ALICE_UID).collection("custom_foods").doc("food_1").set({
|
||||
userId: ALICE_UID,
|
||||
name: "Quinoa rouge",
|
||||
defaultUnit: "g",
|
||||
createdAt: new Date(),
|
||||
});
|
||||
});
|
||||
|
||||
const bobDb = testEnv.authenticatedContext(BOB_UID).firestore();
|
||||
await assertFails(bobDb.collection("users").doc(ALICE_UID).collection("meals").doc("meal_1").get());
|
||||
await assertFails(bobDb.collection("users").doc(ALICE_UID).collection("custom_foods").doc("food_1").get());
|
||||
});
|
||||
|
||||
// 3. Authenticated owner can create and update meals with foodItemsSerialized and custom_foods
|
||||
test("Owner: Alice can create/update meals with foodItemsSerialized and enrich custom_foods", async () => {
|
||||
const aliceDb = testEnv.authenticatedContext(ALICE_UID).firestore();
|
||||
const createdAtDate = new Date();
|
||||
await assertSucceeds(
|
||||
aliceDb.collection("users").doc(ALICE_UID).collection("meals").doc("meal_1").set({
|
||||
userId: ALICE_UID,
|
||||
mealType: "BREAKFAST",
|
||||
mealTimestamp: Date.now() - 86400000,
|
||||
hungerBefore: 8,
|
||||
satietyAfter: 9,
|
||||
note: "Petit-déjeuner complet au calme",
|
||||
foodItemsSerialized: ["Flocons d'avoine|60|g", "Lait d'amande|200|ml", "Banane||portion"],
|
||||
photosBase64: [],
|
||||
createdAt: createdAtDate,
|
||||
})
|
||||
);
|
||||
|
||||
await assertSucceeds(
|
||||
aliceDb.collection("users").doc(ALICE_UID).collection("meals").doc("meal_1").update({
|
||||
foodItemsSerialized: ["Flocons d'avoine|70|g", "Banane|1|portion"],
|
||||
note: "Note globale modifiée",
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
);
|
||||
|
||||
await assertSucceeds(
|
||||
aliceDb.collection("users").doc(ALICE_UID).collection("custom_foods").doc("quinoa_rouge").set({
|
||||
userId: ALICE_UID,
|
||||
name: "Quinoa rouge",
|
||||
defaultUnit: "g",
|
||||
createdAt: createdAtDate,
|
||||
})
|
||||
);
|
||||
|
||||
await assertSucceeds(aliceDb.collection("users").doc(ALICE_UID).collection("custom_foods").get());
|
||||
});
|
||||
|
||||
// 4. Invalid fields rejected
|
||||
test("Invalid payload: Invalid unit in custom_foods or >10 hunger rejected", async () => {
|
||||
const aliceDb = testEnv.authenticatedContext(ALICE_UID).firestore();
|
||||
await assertFails(
|
||||
aliceDb.collection("users").doc(ALICE_UID).collection("custom_foods").doc("bad_food").set({
|
||||
userId: ALICE_UID,
|
||||
name: "Aliment test",
|
||||
defaultUnit: "invalid_unit",
|
||||
createdAt: new Date(),
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. For more details, visit
|
||||
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
|
||||
org.gradle.parallel=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
org.gradle.caching=true
|
||||
org.gradle.configuration-cache=true
|
||||
# Set the maximum number of workers to 4 to avoid overloading the machine.
|
||||
org.gradle.workers.max=4
|
||||
# Set the Kotlin compiler execution strategy to in-process to avoid "Could not
|
||||
# connect to Kotlin compile daemon" error.
|
||||
kotlin.compiler.execution.strategy=in-process
|
||||
# Allow the google-services plugin to work even if the google-services.json is not present.
|
||||
googleServices.missing.passthrough=true
|
||||
@@ -0,0 +1,104 @@
|
||||
[versions]
|
||||
agp = "9.1.1"
|
||||
coreKtx = "1.18.0"
|
||||
junit = "4.13.2"
|
||||
junitVersion = "1.3.0"
|
||||
espressoCore = "3.7.0"
|
||||
lifecycleRuntimeKtx = "2.8.7"
|
||||
lifecycleViewmodelCompose = "2.8.7"
|
||||
lifecycleRuntimeCompose = "2.8.7"
|
||||
activityCompose = "1.10.1"
|
||||
kotlin = "2.2.10"
|
||||
composeBom = "2024.09.00"
|
||||
googleDevtoolsKsp = "2.3.5"
|
||||
navigationCompose = "2.8.9"
|
||||
roomRuntime = "2.7.0"
|
||||
roomKtx = "2.7.0"
|
||||
roomCompiler = "2.7.0"
|
||||
kotlinxCoroutinesTest = "1.10.2"
|
||||
core = "1.6.1"
|
||||
runner = "1.6.2"
|
||||
coilCompose = "2.7.0"
|
||||
retrofit = "2.12.0"
|
||||
converterMoshi = "2.12.0"
|
||||
kotlinxCoroutinesAndroid = "1.10.2"
|
||||
kotlinxCoroutinesCore = "1.10.2"
|
||||
accompanistPermissions = "0.37.3"
|
||||
playServicesLocation = "21.3.0"
|
||||
cameraCamera2 = "1.5.0"
|
||||
cameraLifecycle = "1.5.0"
|
||||
cameraView = "1.5.0"
|
||||
cameraCore = "1.5.0"
|
||||
loggingInterceptor = "4.10.0"
|
||||
okhttp = "4.10.0"
|
||||
moshiKotlin = "1.15.2"
|
||||
moshiKotlinCodegen = "1.15.2"
|
||||
datastorePreferences = "1.1.7"
|
||||
robolectric = "4.16.1"
|
||||
firebaseBom = "34.17.0"
|
||||
secretsGradlePlugin = "2.0.1"
|
||||
googleServices = "4.5.0"
|
||||
credentials = "1.5.0"
|
||||
googleid = "1.1.1"
|
||||
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
junit = { group = "junit", name = "junit", version.ref = "junit" }
|
||||
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
|
||||
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
|
||||
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
|
||||
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" }
|
||||
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycleRuntimeCompose" }
|
||||
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
|
||||
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
||||
androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
|
||||
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
||||
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "roomRuntime" }
|
||||
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "roomKtx" }
|
||||
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "roomCompiler" }
|
||||
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "kotlinxCoroutinesTest" }
|
||||
androidx-core = { group = "androidx.test", name = "core", version.ref = "core" }
|
||||
androidx-runner = { group = "androidx.test", name = "runner", version.ref = "runner" }
|
||||
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||
androidx-compose-material-icons-core = { group = "androidx.compose.material", name = "material-icons-core" }
|
||||
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
|
||||
coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coilCompose" }
|
||||
retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
|
||||
converter-moshi = { group = "com.squareup.retrofit2", name = "converter-moshi", version.ref = "converterMoshi" }
|
||||
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "kotlinxCoroutinesAndroid" }
|
||||
kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutinesCore" }
|
||||
accompanist-permissions = { group = "com.google.accompanist", name = "accompanist-permissions", version.ref = "accompanistPermissions" }
|
||||
play-services-location = { group = "com.google.android.gms", name = "play-services-location", version.ref = "playServicesLocation" }
|
||||
androidx-camera-camera2 = { group = "androidx.camera", name = "camera-camera2", version.ref = "cameraCamera2" }
|
||||
androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "cameraLifecycle" }
|
||||
androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "cameraView" }
|
||||
androidx-camera-core = { group = "androidx.camera", name = "camera-core", version.ref = "cameraCore" }
|
||||
logging-interceptor = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "loggingInterceptor" }
|
||||
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
|
||||
moshi-kotlin = { group = "com.squareup.moshi", name = "moshi-kotlin", version.ref = "moshiKotlin" }
|
||||
moshi-kotlin-codegen = { group = "com.squareup.moshi", name = "moshi-kotlin-codegen", version.ref = "moshiKotlinCodegen" }
|
||||
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }
|
||||
robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" }
|
||||
firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }
|
||||
firebase-ai = { group = "com.google.firebase", name = "firebase-ai" }
|
||||
firebase-appcheck-recaptcha = { group = "com.google.firebase", name = "firebase-appcheck-recaptcha" }
|
||||
firebase-appcheck-debug = { group = "com.google.firebase", name = "firebase-appcheck-debug" }
|
||||
firebase-firestore = { group = "com.google.firebase", name = "firebase-firestore" }
|
||||
firebase-auth = { group = "com.google.firebase", name = "firebase-auth" }
|
||||
androidx-credentials = { group = "androidx.credentials", name = "credentials", version.ref = "credentials" }
|
||||
androidx-credentials-play-services = { group = "androidx.credentials", name = "credentials-play-services-auth", version.ref = "credentials" }
|
||||
googleid = { group = "com.google.android.libraries.identity.googleid", name = "googleid", version.ref = "googleid" }
|
||||
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||
google-devtools-ksp = { id = "com.google.devtools.ksp", version.ref = "googleDevtoolsKsp" }
|
||||
secrets = { id = "com.google.android.libraries.mapsplatform.secrets-gradle-plugin", version.ref = "secretsGradlePlugin" }
|
||||
google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" }
|
||||
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "Satiéa",
|
||||
"description": "Journal minimaliste de repas, suivi de faim et satiété, photos d'assiettes et statistiques hebdomadaires.",
|
||||
"requestFramePermissions": [],
|
||||
"majorCapabilities": ["MAJOR_CAPABILITY_SERVER_SIDE_GEMINI_API"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google {
|
||||
content {
|
||||
includeGroupByRegex("com\\.android.*")
|
||||
includeGroupByRegex("com\\.google.*")
|
||||
includeGroupByRegex("androidx.*")
|
||||
}
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
plugins { id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" }
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "Satiéa"
|
||||
|
||||
include(":app")
|
||||