build: initialize project structure

Set up Android project configuration, Gradle build scripts, typography, and default resource assets.
This commit is contained in:
bleackstorm committed 2026-11-06 16:40:04 +01:00
1 parent 0a595f619a
commit f13d46f778
65 files changed
+6056 -11

No files matched your search

@@ -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
)
}
}
File diff suppressed because it is too large. Load diff
@@ -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
}
}
}