feat: support meal photo URIs and improve UI events

- Add `photoUris` field to `MealEntry` and update Firestore rules.
- Implement `UiEvent` handling in `MainActivity` for navigation/links.
- Remove sensitive email data from error logs and clean up manifest.
This commit is contained in:
bleackstorm committed 2026-11-08 19:25:03 +01:00
1 parent f0487453c9
commit 87bbb448c2
34 files changed
+2026 -1170

No files matched your search

+27 -9
View File
@@ -38,11 +38,13 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import com.example.ui.common.UiEvent
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
@@ -131,6 +133,23 @@ fun AppRoot(
}
}
LaunchedEffect(Unit) {
viewModel.uiEvents.collect { event ->
when (event) {
is UiEvent.ShowSnackbar -> snackbarHostState.showSnackbar(event.message)
is UiEvent.OpenUrl -> {
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(event.url))
context.startActivity(intent)
} catch (_: Exception) {
snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : ${event.url}")
}
}
is UiEvent.StartActivity -> context.startActivity(event.intent)
}
}
}
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
@@ -201,6 +220,7 @@ fun AppRoot(
}
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
@@ -450,9 +470,6 @@ fun AppRoot(
}
MainTab.STATS -> {
val weeklyStats = remember(currentMealsList) {
viewModel.computeWeeklyStats(currentMealsList)
}
WeeklyStatsScreen(
weeklyStats = weeklyStats,
totalMealsCount = currentMealsList.size,
@@ -489,10 +506,11 @@ fun AppRoot(
onOpenSheetsClick = { url -> openGoogleSheets(url) },
onSignInClick = { showAuthSheet = true },
onSignOut = {
currentUser = null
viewModel.disconnectGoogleSheets()
coroutineScope.launch {
snackbarHostState.showSnackbar("Mode local actif • Déconnecté")
viewModel.signOut(context) {
currentUser = null
coroutineScope.launch {
snackbarHostState.showSnackbar("Mode local actif • Déconnecté")
}
}
}
)
@@ -522,7 +540,7 @@ fun AppRoot(
hungerBefore = hunger,
satietyAfter = satiety,
note = note,
photosBase64 = photos
photoUris = photos
),
foodItems = foodItems,
onSuccess = {
@@ -544,7 +562,7 @@ fun AppRoot(
satietyAfter = satiety,
note = note,
foodItems = foodItems,
photosBase64 = photos,
photoUris = photos,
onSuccess = {
coroutineScope.launch {
snackbarHostState.showSnackbar("Repas enregistré avec succès ✨")
@@ -7,7 +7,7 @@ import androidx.room.RoomDatabase
@Database(
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class],
version = 1,
version = 2,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
@@ -24,7 +24,7 @@ abstract class AppDatabase : RoomDatabase() {
context.applicationContext,
AppDatabase::class.java,
"satiea_local.db"
).fallbackToDestructiveMigration().build().also { INSTANCE = it }
).fallbackToDestructiveMigration(true).build().also { INSTANCE = it }
}
}
}
@@ -3,7 +3,6 @@ package com.example.data.local
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
@Entity(tableName = "local_meals")
data class LocalMealEntity(
@@ -14,8 +13,8 @@ data class LocalMealEntity(
val hungerBefore: Int,
val satietyAfter: Int,
val note: String = "",
val foodItemsJoined: String = "", // serialized items separated by "###"
val photosJoined: String = "", // Base64 photos separated by "|||"
val foodItemsJoined: String = "", // serialized items separated by "###"
val photoUrisJoined: String = "", // local file URIs separated by "|||"
val updatedAt: Long = System.currentTimeMillis()
) {
fun toMealEntry(): MealEntry {
@@ -24,10 +23,10 @@ data class LocalMealEntity(
} else {
foodItemsJoined.split("###").filter { it.isNotBlank() }
}
val photos = if (photosJoined.isBlank()) {
val photos = if (photoUrisJoined.isBlank()) {
emptyList()
} else {
photosJoined.split("|||").filter { it.isNotBlank() }
photoUrisJoined.split("|||").filter { it.isNotBlank() }
}
return MealEntry(
id = id,
@@ -38,14 +37,15 @@ data class LocalMealEntity(
satietyAfter = satietyAfter,
note = note,
foodItemsSerialized = foodItems,
photosBase64 = photos
photoUris = photos,
photosBase64 = emptyList()
)
}
companion object {
fun fromMealEntry(meal: MealEntry): LocalMealEntity {
val foodItemsJoined = meal.foodItemsSerialized.joinToString("###")
val photosJoined = meal.photosBase64.joinToString("|||")
val photoUrisJoined = meal.displayPhotoUris.joinToString("|||")
return LocalMealEntity(
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
userId = meal.userId,
@@ -55,7 +55,7 @@ data class LocalMealEntity(
satietyAfter = meal.satietyAfter,
note = meal.note,
foodItemsJoined = foodItemsJoined,
photosJoined = photosJoined,
photoUrisJoined = photoUrisJoined,
updatedAt = System.currentTimeMillis()
)
}
@@ -92,10 +92,14 @@ data class MealEntry(
val satietyAfter: Int = 7,
val note: String = "",
val foodItemsSerialized: List<String> = emptyList(),
val photoUris: List<String> = emptyList(),
val photosBase64: List<String> = emptyList(),
@ServerTimestamp val createdAt: Timestamp? = null,
@ServerTimestamp val updatedAt: Timestamp? = null
) {
val displayPhotoUris: List<String>
get() = photoUris.ifEmpty { photosBase64 }
fun parsedFoodItems(): List<MealFoodItem> {
return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) }
}
@@ -109,7 +113,7 @@ data class MealEntry(
"satietyAfter" to satietyAfter.coerceIn(1, 10),
"note" to note,
"foodItemsSerialized" to foodItemsSerialized.take(30),
"photosBase64" to photosBase64,
"photoUris" to photoUris.take(6),
"createdAt" to createdAt,
"updatedAt" to updatedAt
)
@@ -28,13 +28,11 @@ fun handleFirestoreError(exception: Throwable, operationType: OperationType, pat
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))
@@ -13,7 +13,9 @@ import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.util.CsvImportResult
import com.example.util.CsvImporter
import com.example.util.ImageUtils
import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
@@ -32,7 +34,8 @@ import java.util.UUID
class MealRepository(
private val localMealDao: LocalMealDao?,
private val db: FirebaseFirestore?
private val db: FirebaseFirestore?,
private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth
) {
// Constructor used by ViewModel in app runtime
@@ -50,11 +53,10 @@ class MealRepository(
// Secondary constructor for Firestore rule tests without local DB
constructor(db: FirebaseFirestore) : this(
localMealDao = null,
db = db
db = db,
auth = FirebaseAuth.getInstance(db.app)
)
private val auth = Firebase.auth
private fun getUserIdOrNull(): String? {
return auth.currentUser?.uid
}
@@ -152,6 +154,7 @@ class MealRepository(
)
docRef.set(payload).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.CREATE, docRef.path)
return Result.failure(e)
@@ -209,6 +212,7 @@ class MealRepository(
val docRef = mealsRef.document(resolvedId)
docRef.set(payload).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.CREATE, path)
return Result.failure(e)
@@ -238,11 +242,12 @@ class MealRepository(
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
"note" to meal.note,
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
"photosBase64" to meal.photosBase64,
"photoUris" to meal.photoUris.take(6),
"updatedAt" to FieldValue.serverTimestamp()
)
docRef.update(updates).await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
return Result.failure(e)
@@ -255,16 +260,23 @@ class MealRepository(
}
suspend fun deleteMeal(mealId: String): Result<Unit> {
// 1. Delete from local Room database
// 1. Clean up local photo files
val existingMeal = localMealDao?.getMealById(mealId)?.toMealEntry()
existingMeal?.displayPhotoUris?.forEach { uri ->
ImageUtils.deletePhotoFile(uri)
}
// 2. Delete from local Room database
localMealDao?.deleteMealById(mealId)
// 2. If signed in, delete from Firestore
// 3. If signed in, delete from Firestore
val uid = getUserIdOrNull()
if (uid != null && db != null) {
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
try {
docRef.delete().await()
} catch (e: Exception) {
if (e is CancellationException) throw e
if (localMealDao == null) {
handleFirestoreError(e, OperationType.DELETE, docRef.path)
return Result.failure(e)
@@ -341,6 +353,7 @@ class MealRepository(
Result.success(result)
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.failure(e)
}
}
@@ -389,6 +402,7 @@ class MealRepository(
Result.success(importedCount)
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.failure(e)
}
}
@@ -0,0 +1,22 @@
package com.example.domain
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.example.data.model.MealEntry
import com.example.util.CsvExporter
class CsvExportUseCase(private val context: Context) {
suspend fun writeToUri(targetUri: Uri, meals: List<MealEntry>): Result<Int> {
return CsvExporter.writeCsvToUri(context, targetUri, meals)
}
suspend fun createShareIntent(activityContext: Context, meals: List<MealEntry>): Result<Intent> {
return CsvExporter.shareCsvFile(activityContext, meals)
}
fun defaultFileName(): String {
return CsvExporter.buildDefaultFileName()
}
}
@@ -0,0 +1,87 @@
package com.example.domain
import android.content.Context
import android.content.Intent
import com.example.data.model.MealEntry
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.GoogleSheetsSyncResult
import com.example.util.GoogleSheetsSyncService
import com.google.android.gms.auth.UserRecoverableAuthException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
sealed interface SheetsSyncResult {
data class Success(val url: String, val count: Int, val timestamp: Long) : SheetsSyncResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsSyncResult
data class Failure(val message: String) : SheetsSyncResult
}
class GoogleSheetsSyncUseCase(
private val context: Context,
private val repository: MealRepository,
private val sheetsPrefs: GoogleSheetsPreferencesManager
) {
suspend fun execute(): SheetsSyncResult = withContext(Dispatchers.IO) {
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (tokenResult.isFailure) {
val exception = tokenResult.exceptionOrNull()
return@withContext if (exception is UserRecoverableAuthException) {
SheetsSyncResult.RecoverableAuth(
message = "Autorisation requise pour Google Sheets & Drive",
intent = exception.intent
)
} else {
SheetsSyncResult.Failure(exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google")
}
}
val token = tokenResult.getOrThrow()
val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
if (spreadsheetResult.isFailure) {
val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création du classeur"
return@withContext SheetsSyncResult.Failure(err)
}
val (id, url) = spreadsheetResult.getOrThrow()
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
} else {
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas"
SheetsSyncResult.Failure(err)
}
}
suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? = withContext(Dispatchers.IO) {
if (!sheetsPrefs.isAutoSyncEnabled) return@withContext null
try {
val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId).getOrNull() ?: return@withContext null
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement"
res
} else null
} catch (_: Exception) {
null
}
}
}
@@ -0,0 +1,81 @@
package com.example.domain
import com.example.data.model.MealEntry
import com.example.data.model.MealType
import com.example.ui.journal.DayStat
import com.example.ui.journal.WeeklyStats
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
object WeeklyStatsCalculator {
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
val todayLocalDate = LocalDate.now(zoneId)
val startOfPeriod = todayLocalDate.minusDays(6)
val startOfPeriodMillis = startOfPeriod.atStartOfDay(zoneId).toInstant().toEpochMilli()
val endOfTodayMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1
val recentMeals = meals.filter { it.mealTimestamp in startOfPeriodMillis..endOfTodayMillis }
val dayFormat = DateTimeFormatter.ofPattern("EEE", Locale.FRENCH)
val fullDayFormat = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH)
val daysList = mutableListOf<DayStat>()
for (i in 6 downTo 0) {
val currentDay = todayLocalDate.minusDays(i.toLong())
val startOfDay = currentDay.atStartOfDay(zoneId).toInstant().toEpochMilli()
val endOfDay = currentDay.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 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(currentDay),
dayShortName = dayFormat.format(currentDay).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
)
}
}
@@ -15,7 +15,8 @@ import com.example.R
import com.example.data.model.MealType
import com.example.data.preferences.ReminderPreferencesManager
import com.example.receiver.MealReminderReceiver
import java.util.Calendar
import java.time.ZoneId
import java.time.ZonedDateTime
object MealNotificationManager {
@@ -111,55 +112,31 @@ object MealNotificationManager {
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)
}
val zoneId = ZoneId.systemDefault()
val nowZoned = ZonedDateTime.now(zoneId)
var triggerZoned = nowZoned.withHour(hour).withMinute(minute).withSecond(0).withNano(0)
if (!triggerZoned.isAfter(nowZoned)) {
triggerZoned = triggerZoned.plusDays(1)
}
val triggerMillis = triggerZoned.toInstant().toEpochMilli()
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (alarmManager.canScheduleExactAlarms()) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
} else {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
} else {
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
pendingIntent
)
}
Log.d(TAG, "Scheduled exact reminder for ${mealType.name} at ${calendar.time}")
} catch (e: SecurityException) {
Log.w(TAG, "Exact alarm permission not granted, falling back to setAndAllowWhileIdle", e)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
triggerMillis,
pendingIntent
)
} else {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
triggerMillis,
pendingIntent
)
}
Log.d(TAG, "Scheduled reminder for ${mealType.name} at $triggerZoned")
} catch (e: Exception) {
Log.w(TAG, "Could not schedule reminder: ${e.message}")
}
}
@@ -0,0 +1,9 @@
package com.example.ui.common
import android.content.Intent
sealed interface UiEvent {
data class ShowSnackbar(val message: String) : UiEvent
data class OpenUrl(val url: String) : UiEvent
data class StartActivity(val intent: Intent) : UiEvent
}
@@ -2,6 +2,7 @@ package com.example.ui.journal
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import coil.compose.AsyncImage
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
@@ -64,9 +65,10 @@ 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.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
@Composable
@@ -115,14 +117,10 @@ fun JournalScreen(
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 zoneId = ZoneId.systemDefault()
val todayLocalDate = LocalDate.now(zoneId)
val todayStartMillis = todayLocalDate.atStartOfDay(zoneId).toInstant().toEpochMilli()
val todayEndMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1
val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis }
LazyColumn(
@@ -236,9 +234,9 @@ fun JournalScreen(
@Composable
private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
val dateFormat = remember { SimpleDateFormat("EEEE d MMMM", Locale.FRENCH) }
val dateFormatter = remember { DateTimeFormatter.ofPattern("EEEE d MMMM", Locale.FRENCH) }
val todayFormatted = remember {
dateFormat.format(Date()).replaceFirstChar {
dateFormatter.format(LocalDate.now()).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
}
}
@@ -338,7 +336,8 @@ private fun MealCardItem(
) {
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 dateTimeFormatter = remember { DateTimeFormatter.ofPattern("EEE d MMM yyyy • HH:mm", Locale.FRENCH) }
val zoneId = remember { ZoneId.systemDefault() }
val mealType = MealType.fromString(meal.mealType)
val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() }
@@ -397,7 +396,7 @@ private fun MealCardItem(
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = dateTimeFormat.format(Date(meal.mealTimestamp)).replaceFirstChar {
text = dateTimeFormatter.format(Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodySmall,
@@ -544,23 +543,20 @@ private fun MealCardItem(
}
// Photos Carousel
if (meal.photosBase64.isNotEmpty()) {
if (meal.displayPhotoUris.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
)
}
items(meal.displayPhotoUris) { photoUri ->
AsyncImage(
model = photoUri,
contentDescription = "Photo du repas",
modifier = Modifier
.size(76.dp)
.clip(RoundedCornerShape(12.dp)),
contentScale = ContentScale.Crop
)
}
}
}
@@ -11,26 +11,33 @@ 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.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsSyncResult
import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.CsvExporter
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.GoogleSheetsSyncService
import com.google.android.gms.auth.UserRecoverableAuthException
import com.example.util.CsvImportResult
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestoreException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
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.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
sealed interface MealsUiState {
@@ -62,12 +69,36 @@ data class WeeklyStats(
val optimalZonePercentage: Int,
val totalMealsLast7Days: Int,
val mealTypeDistribution: Map<MealType, Int>
)
) {
companion object {
fun empty(): WeeklyStats = WeeklyStats(
dailyStats = emptyList(),
averageSatiety = 0f,
averageHunger = 0f,
optimalZonePercentage = 0,
totalMealsLast7Days = 0,
mealTypeDistribution = emptyMap()
)
}
}
class MealViewModel(application: Application) : AndroidViewModel(application) {
private val repository = MealRepository(application)
private val context = application.applicationContext
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
// Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
private val csvExportUseCase = CsvExportUseCase(context)
// UDF Event Channel
private val _uiEventChannel = Channel<UiEvent>(Channel.BUFFERED)
val uiEvents = _uiEventChannel.receiveAsFlow()
fun emitEvent(event: UiEvent) {
viewModelScope.launch { _uiEventChannel.send(event) }
}
val mealsState: StateFlow<MealsUiState> = repository.observeMeals()
.map<List<MealEntry>, MealsUiState> { meals ->
@@ -87,6 +118,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = MealsUiState.Loading
)
// Asynchronous background computation of WeeklyStats via Dispatchers.Default
val weeklyStats: StateFlow<WeeklyStats> = repository.observeMeals()
.map { meals -> computeWeeklyStats(meals) }
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = WeeklyStats.empty()
)
val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods()
.catch { error ->
val firestoreError = generateSequence(error) { it.cause }
@@ -104,8 +145,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
GoogleSheetsUiState.Success(
@@ -170,7 +209,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
satietyAfter: Int,
note: String,
foodItems: List<MealFoodItem>,
photosBase64: List<String>,
photoUris: List<String> = emptyList(),
photosBase64: List<String> = emptyList(),
onSuccess: () -> Unit = {},
onError: (String) -> Unit = {}
) {
@@ -183,14 +223,34 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
satietyAfter = satietyAfter.coerceIn(1, 10),
note = note.trim(),
foodItemsSerialized = foodItems.map { it.serialize() }.take(30),
photosBase64 = photosBase64
photoUris = photoUris.ifEmpty { photosBase64 },
photosBase64 = emptyList()
)
val result = repository.addMeal(entry)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas enregistré avec succès ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
fun signOut(context: Context, onComplete: () -> Unit = {}) {
viewModelScope.launch {
try {
FirebaseAuth.getInstance().signOut()
val credManager = androidx.credentials.CredentialManager.create(context)
credManager.clearCredentialState(androidx.credentials.ClearCredentialStateRequest())
} catch (e: Exception) {
if (e is CancellationException) throw e
} finally {
disconnectGoogleSheets()
onComplete()
emitEvent(UiEvent.ShowSnackbar("Mode local actif • Déconnecté"))
}
}
}
@@ -211,9 +271,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val result = repository.updateMeal(sanitizedMeal)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas mis à jour ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
@@ -227,9 +290,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
val result = repository.deleteMeal(mealId)
if (result.isSuccess) {
onSuccess()
emitEvent(UiEvent.ShowSnackbar("Repas supprimé"))
triggerAutoSheetsSyncIfNeeded()
} else {
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression")
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression"
onError(err)
emitEvent(UiEvent.ShowSnackbar(err))
}
}
}
@@ -237,26 +303,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private fun triggerAutoSheetsSyncIfNeeded() {
if (!sheetsPrefs.isAutoSyncEnabled) return
viewModelScope.launch {
try {
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
val token = tokenResult.getOrNull() ?: return@launch
val sheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
val (id, url) = sheetResult.getOrNull() ?: return@launch
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
_spreadsheetUrl.value = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement"
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
}
} catch (_: Exception) {
// Non-blocking background sync
sheetsSyncUseCase.executeAutoSyncQuietly()?.let { res ->
_spreadsheetUrl.value = res.spreadsheetUrl
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
}
}
}
@@ -267,51 +316,22 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
) {
viewModelScope.launch {
_sheetsUiState.value = GoogleSheetsUiState.Syncing
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (tokenResult.isFailure) {
val exception = tokenResult.exceptionOrNull()
if (exception is UserRecoverableAuthException) {
val intent = exception.intent
_sheetsUiState.value = GoogleSheetsUiState.Error(
"Autorisation requise pour Google Sheets & Drive",
recoverableIntent = intent
)
onError("Autorisation requise pour Google Sheets & Drive", intent)
} else {
val msg = exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google"
_sheetsUiState.value = GoogleSheetsUiState.Error(msg)
onError(msg, null)
when (val result = sheetsSyncUseCase.execute()) {
is SheetsSyncResult.Success -> {
_spreadsheetUrl.value = result.url
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
onSuccess(result.url, result.count)
emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊"))
}
is SheetsSyncResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
onError(result.message, result.intent)
}
is SheetsSyncResult.Failure -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message)
onError(result.message, null)
emitEvent(UiEvent.ShowSnackbar(result.message))
}
return@launch
}
val token = tokenResult.getOrThrow()
val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
if (spreadsheetResult.isFailure) {
val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création de la feuille"
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
onError(err, null)
return@launch
}
val (id, url) = spreadsheetResult.getOrThrow()
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
_spreadsheetUrl.value = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
onSuccess(res.spreadsheetUrl, res.mealsCount)
} else {
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas"
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
onError(err, null)
}
}
}
@@ -323,24 +343,47 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = CsvExporter.writeCsvToUri(context, targetUri, meals)
val result = csvExportUseCase.writeToUri(targetUri, meals)
result.fold(
onSuccess = { count -> onSuccess(count) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'export CSV") }
onSuccess = { count ->
onSuccess(count)
emitEvent(UiEvent.ShowSnackbar("Fichier CSV enregistré ($count repas) ✨"))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de l'export CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
fun importCsvFromUri(
sourceUri: Uri,
onSuccess: (com.example.util.CsvImportResult) -> Unit,
onSuccess: (CsvImportResult) -> Unit,
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = repository.importMealsFromCsv(context, sourceUri)
result.fold(
onSuccess = { importResult -> onSuccess(importResult) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'import du fichier CSV") }
onSuccess = { importResult ->
onSuccess(importResult)
val count = importResult.importedMeals.size
val skipped = importResult.skippedDuplicatesCount
val newFoods = importResult.newFoodItems.size
val msg = buildString {
append("$count repas importé${if (count > 1) "s" else ""}")
if (skipped > 0) append(" ($skipped doublon${if (skipped > 1) "s" else ""} ignoré${if (skipped > 1) "s" else ""})")
if (newFoods > 0) append(" • $newFoods nouvel aliment ajouté")
append(" ✨")
}
emitEvent(UiEvent.ShowSnackbar(msg))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de l'import du fichier CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -352,8 +395,15 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch {
val result = repository.syncCloudToLocal()
result.fold(
onSuccess = { count -> onSuccess(count) },
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de la synchronisation") }
onSuccess = { count ->
onSuccess(count)
emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️"))
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de la synchronisation"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -365,10 +415,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
onError: (String) -> Unit
) {
viewModelScope.launch {
val result = CsvExporter.shareCsvFile(activityContext, meals)
val result = csvExportUseCase.createShareIntent(activityContext, meals)
result.fold(
onSuccess = { chooserIntent -> onIntentReady(chooserIntent) },
onFailure = { err -> onError(err.localizedMessage ?: "Impossible de préparer le partage CSV") }
onSuccess = { chooserIntent ->
onIntentReady(chooserIntent)
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Impossible de préparer le partage CSV"
onError(msg)
emitEvent(UiEvent.ShowSnackbar(msg))
}
)
}
}
@@ -390,85 +446,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
fun triggerTestNotification(mealType: MealType) {
MealNotificationManager.showMealNotification(context, mealType)
emitEvent(UiEvent.ShowSnackbar("Notification de rappel envoyée !"))
}
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
)
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId)
}
}
@@ -1,67 +1,33 @@
package com.example.ui.meal
import android.graphics.Bitmap
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddAPhoto
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
@@ -70,36 +36,30 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodUnit
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.ui.meal.components.FoodItemBuilderSection
import com.example.ui.meal.components.MealDateTimePicker
import com.example.ui.meal.components.MealHungerSatietySection
import com.example.ui.meal.components.MealPhotosSection
import com.example.ui.meal.components.MealTypeSelector
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import kotlin.math.roundToInt
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MealEntrySheet(
initialMeal: MealEntry? = null,
@@ -113,21 +73,22 @@ fun MealEntrySheet(
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var selectedType by remember {
var selectedType by rememberSaveable {
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
}
var mealTimestamp by remember {
var mealTimestamp by rememberSaveable {
mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis())
}
var hungerLevel by remember {
var hungerLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10))
}
var satietyLevel by remember {
var satietyLevel by rememberSaveable {
mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10))
}
var globalNoteText by remember {
var globalNoteText by rememberSaveable {
mutableStateOf(initialMeal?.note ?: "")
}
val foodItemsList = remember {
mutableStateListOf<MealFoodItem>().apply {
if (initialMeal != null) {
@@ -135,18 +96,18 @@ fun MealEntrySheet(
}
}
}
val photosBase64List = remember {
val photoUrisList = remember {
mutableStateListOf<String>().apply {
if (initialMeal != null) {
addAll(initialMeal.photosBase64)
addAll(initialMeal.displayPhotoUris)
}
}
}
// Current food builder state
var foodNameInput by remember { mutableStateOf("") }
var foodWeightInput by remember { mutableStateOf("") }
var selectedFoodUnit by remember { mutableStateOf(FoodUnit.G) }
// Current food builder input state
var foodNameInput by rememberSaveable { mutableStateOf("") }
var foodWeightInput by rememberSaveable { mutableStateOf("") }
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
// Combine custom foods (user enriched) + built-in catalog
val mergedCatalog = remember(customFoods) {
@@ -190,7 +151,6 @@ fun MealEntrySheet(
weight = parsedWeight,
unit = selectedFoodUnit
)
// Replace if same food already added, or append
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
if (existingIndex >= 0) {
foodItemsList[existingIndex] = newItem
@@ -207,8 +167,6 @@ fun MealEntrySheet(
}
var isProcessingPhoto by remember { mutableStateOf(false) }
var showDatePicker by remember { mutableStateOf(false) }
var showTimePicker by remember { mutableStateOf(false) }
val photoPickerLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
@@ -216,18 +174,15 @@ fun MealEntrySheet(
if (uri != null) {
isProcessingPhoto = true
coroutineScope.launch {
val b64 = ImageUtils.uriToBase64(context, uri)
if (b64 != null && photosBase64List.size < 4) {
photosBase64List.add(b64)
val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri)
if (savedUri != null && photoUrisList.size < 4) {
photoUrisList.add(savedUri)
}
isProcessingPhoto = false
}
}
}
val dateFormat = remember { SimpleDateFormat("EEE d MMM yyyy", Locale.FRENCH) }
val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.FRENCH) }
ModalBottomSheet(
onDismissRequest = onDismiss,
sheetState = sheetState,
@@ -273,518 +228,77 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp))
// Meal Type Chips
Text(
text = "Type de repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
// Subcomponent 1: Meal Type Chips
MealTypeSelector(
selectedType = selectedType,
onTypeSelected = { selectedType = it }
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
MealType.entries.forEach { type ->
val isSelected = selectedType == type
FilterChip(
selected = isSelected,
onClick = { selectedType = type },
label = {
Text(
text = type.displayName,
style = MaterialTheme.typography.labelMedium
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Date & Time Picker Section
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Date et heure du repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Maintenant",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable { mealTimestamp = System.currentTimeMillis() }
.padding(horizontal = 6.dp, vertical = 2.dp)
)
Text(
text = "Hier",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable {
val cal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
add(Calendar.DAY_OF_YEAR, -1)
}
mealTimestamp = cal.timeInMillis
}
.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = { showDatePicker = true },
modifier = Modifier
.weight(1.3f)
.testTag("edit_date_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = "Changer la date",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = dateFormat.format(Date(mealTimestamp)).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
OutlinedButton(
onClick = { showTimePicker = true },
modifier = Modifier
.weight(0.9f)
.testTag("edit_time_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = "Changer l'heure",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = timeFormat.format(Date(mealTimestamp)),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
// Subcomponent 2: Date & Time Picker
MealDateTimePicker(
mealTimestamp = mealTimestamp,
onTimestampChanged = { mealTimestamp = it }
)
Spacer(modifier = Modifier.height(20.dp))
// Photos Section
Text(
text = "Photos de l'assiette (${photosBase64List.size}/4)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (photosBase64List.size < 4) {
item {
Surface(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape = RoundedCornerShape(14.dp)
)
.clickable(enabled = !isProcessingPhoto) {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
}
.testTag("add_photo_button"),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddAPhoto,
contentDescription = "Ajouter une photo",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Ajouter",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
// Subcomponent 3: Photos Section
MealPhotosSection(
photoUris = photoUrisList,
isProcessingPhoto = isProcessingPhoto,
onAddPhotoClick = {
photoPickerLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
onDeletePhotoClick = { photoUri ->
ImageUtils.deletePhotoFile(photoUri)
photoUrisList.remove(photoUri)
}
items(photosBase64List) { b64 ->
val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) }
Box(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
) {
if (bitmap != null) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Photo assiette",
modifier = Modifier.matchParentSize(),
contentScale = ContentScale.Crop
)
} else {
Box(
modifier = Modifier
.matchParentSize()
.background(MaterialTheme.colorScheme.surfaceVariant)
)
}
Surface(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(4.dp)
.size(22.dp)
.clip(CircleShape)
.clickable { photosBase64List.remove(b64) },
color = Color.Black.copy(alpha = 0.7f)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Supprimer photo",
tint = Color.White,
modifier = Modifier.padding(2.dp)
)
}
}
}
}
Spacer(modifier = Modifier.height(22.dp))
// 1. Hunger Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "1. Faim avant le repas",
currentValue = hungerLevel,
accentColor = MaterialTheme.colorScheme.secondary,
onValueChange = { hungerLevel = it },
description = HungerSatietyScale.getHungerLabel(hungerLevel),
sliderTag = "hunger_slider_10"
)
Spacer(modifier = Modifier.height(18.dp))
// 2. Satiety Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "2. Satiété après le repas",
currentValue = satietyLevel,
accentColor = MaterialTheme.colorScheme.primary,
onValueChange = { satietyLevel = it },
description = HungerSatietyScale.getSatietyLabel(satietyLevel),
sliderTag = "satiety_slider_10"
)
Spacer(modifier = Modifier.height(22.dp))
// 3. Enrichable Food List + Optional Weight Section
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.RestaurantMenu,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "3. Aliments & Poids (optionnel)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
// Subcomponent 4: Hunger & Satiety Sliders (1 to 10)
MealHungerSatietySection(
hungerLevel = hungerLevel,
satietyLevel = satietyLevel,
onHungerChange = { hungerLevel = it },
onSatietyChange = { satietyLevel = it }
)
Text(
text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(22.dp))
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
items(matchingSuggestions, key = { it.name }) { suggestion ->
SuggestionChip(
onClick = {
foodNameInput = suggestion.name
selectedFoodUnit = suggestion.defaultUnit
},
label = {
Text(
text = "${suggestion.name} (${suggestion.defaultUnit.label})",
style = MaterialTheme.typography.labelSmall
)
},
colors = SuggestionChipDefaults.suggestionChipColors(
containerColor = MaterialTheme.colorScheme.surface,
labelColor = MaterialTheme.colorScheme.onSurface
)
)
}
}
Spacer(modifier = Modifier.height(10.dp))
}
// Food Name Input
OutlinedTextField(
value = foodNameInput,
onValueChange = { if (it.length <= 80) foodNameInput = it },
modifier = Modifier
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)")
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
trailingIcon = {
if (foodNameInput.isNotEmpty()) {
IconButton(onClick = { foodNameInput = "" }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer",
modifier = Modifier.size(18.dp)
)
}
}
}
)
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = foodWeightInput,
onValueChange = { input ->
if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) {
foodWeightInput = input
}
},
modifier = Modifier
.weight(1f)
.testTag("food_weight_input"),
placeholder = {
Text("Poids opt.")
},
leadingIcon = {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp)
)
// Unit Selector Chips (g, ml, portion)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FoodUnit.entries.forEach { unit ->
val isUnitSelected = selectedFoodUnit == unit
FilterChip(
selected = isUnitSelected,
onClick = { selectedFoodUnit = unit },
label = {
Text(
text = unit.label,
style = MaterialTheme.typography.labelSmall
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
Spacer(modifier = Modifier.height(10.dp))
Button(
onClick = { addCurrentFoodItem() },
enabled = foodNameInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_food_item_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else {
"Ajouter à l'assiette (sans poids)"
},
style = MaterialTheme.typography.labelLarge
)
}
// Added food items badges
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
foodItemsList.forEach { item ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.clickable {
// Load back into inputs for quick weight edit
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
foodItemsList.remove(item)
}
) {
Row(
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable { foodItemsList.remove(item) }
.padding(2.dp)
)
}
}
}
}
}
// Subcomponent 5: Food items builder & flow-row chips
FoodItemBuilderSection(
foodItemsList = foodItemsList,
matchingSuggestions = matchingSuggestions,
foodNameInput = foodNameInput,
onFoodNameChange = { foodNameInput = it },
foodWeightInput = foodWeightInput,
onFoodWeightChange = { foodWeightInput = it },
selectedFoodUnit = selectedFoodUnit,
onFoodUnitSelected = { selectedFoodUnit = it },
isNewCustomFood = isNewCustomFood,
onAddFoodItem = { addCurrentFoodItem() },
onItemClickForEdit = { item ->
foodNameInput = item.name
foodWeightInput = item.weight?.let {
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
} ?: ""
selectedFoodUnit = item.unit
foodItemsList.remove(item)
},
onRemoveFoodItem = { item ->
foodItemsList.remove(item)
}
}
)
Spacer(modifier = Modifier.height(20.dp))
// 4. Global Note Field
// Global Note Field
Text(
text = "4. Note globale du repas (optionnel)",
style = MaterialTheme.typography.labelLarge,
@@ -827,7 +341,6 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.width(10.dp))
Button(
onClick = {
// Automatically commit any pending typed food name so user input is never lost
if (foodNameInput.trim().isNotEmpty()) {
addCurrentFoodItem()
}
@@ -838,7 +351,7 @@ fun MealEntrySheet(
satietyLevel.coerceIn(1, 10),
globalNoteText,
foodItemsList.toList(),
photosBase64List.toList()
photoUrisList.toList()
)
},
modifier = Modifier
@@ -860,189 +373,4 @@ fun MealEntrySheet(
Spacer(modifier = Modifier.height(16.dp))
}
}
// Material 3 DatePickerDialog
if (showDatePicker) {
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = mealTimestamp
)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
val selectedUtcMillis = datePickerState.selectedDateMillis
if (selectedUtcMillis != null) {
val utcCal = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
timeInMillis = selectedUtcMillis
}
val localCal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
set(Calendar.YEAR, utcCal.get(Calendar.YEAR))
set(Calendar.MONTH, utcCal.get(Calendar.MONTH))
set(Calendar.DAY_OF_MONTH, utcCal.get(Calendar.DAY_OF_MONTH))
}
mealTimestamp = localCal.timeInMillis
}
showDatePicker = false
},
modifier = Modifier.testTag("confirm_date_button")
) {
Text("Valider la date")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
}
}
// Material 3 TimePicker Dialog
if (showTimePicker) {
val currentCal = remember(mealTimestamp) {
Calendar.getInstance().apply { timeInMillis = mealTimestamp }
}
val timePickerState = rememberTimePickerState(
initialHour = currentCal.get(Calendar.HOUR_OF_DAY),
initialMinute = currentCal.get(Calendar.MINUTE),
is24Hour = true
)
AlertDialog(
onDismissRequest = { showTimePicker = false },
title = { Text("Modifier l'heure du repas") },
text = {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
TimePicker(state = timePickerState)
}
},
confirmButton = {
TextButton(
onClick = {
val updatedCal = Calendar.getInstance().apply {
timeInMillis = mealTimestamp
set(Calendar.HOUR_OF_DAY, timePickerState.hour)
set(Calendar.MINUTE, timePickerState.minute)
set(Calendar.SECOND, 0)
}
mealTimestamp = updatedCal.timeInMillis
showTimePicker = false
},
modifier = Modifier.testTag("confirm_time_button")
) {
Text("Valider l'heure")
}
},
dismissButton = {
TextButton(onClick = { showTimePicker = false }) {
Text("Annuler")
}
}
)
}
}
@Composable
private fun SteppedScaleTenSlider(
title: String,
currentValue: Int,
accentColor: Color,
onValueChange: (Int) -> Unit,
description: String,
sliderTag: String
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Surface(
shape = RoundedCornerShape(10.dp),
color = accentColor.copy(alpha = 0.2f)
) {
Text(
text = "$currentValue / 10",
style = MaterialTheme.typography.titleMedium,
color = accentColor,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
)
}
}
Spacer(modifier = Modifier.height(6.dp))
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = accentColor,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(4.dp))
Slider(
value = currentValue.toFloat(),
onValueChange = { newValue ->
onValueChange(newValue.roundToInt().coerceIn(1, 10))
},
valueRange = 1f..10f,
steps = 8,
colors = SliderDefaults.colors(
thumbColor = accentColor,
activeTrackColor = accentColor,
inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant,
activeTickColor = MaterialTheme.colorScheme.surface,
inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
),
modifier = Modifier
.fillMaxWidth()
.testTag(sliderTag)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
(1..10).forEach { num ->
val isSelected = num == currentValue
Text(
text = num.toString(),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(CircleShape)
.clickable { onValueChange(num) }
.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
}
}
}
}
@@ -0,0 +1,313 @@
package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.RestaurantMenu
import androidx.compose.material.icons.filled.Scale
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.SuggestionChipDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FoodItemBuilderSection(
foodItemsList: List<MealFoodItem>,
matchingSuggestions: List<DefaultFoodCatalog.CatalogFood>,
foodNameInput: String,
onFoodNameChange: (String) -> Unit,
foodWeightInput: String,
onFoodWeightChange: (String) -> Unit,
selectedFoodUnit: FoodUnit,
onFoodUnitSelected: (FoodUnit) -> Unit,
isNewCustomFood: Boolean,
onAddFoodItem: () -> Unit,
onItemClickForEdit: (MealFoodItem) -> Unit,
onRemoveFoodItem: (MealFoodItem) -> Unit,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.RestaurantMenu,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "3. Aliments & Poids (optionnel)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
}
Text(
text = "${foodItemsList.size} aliment${if (foodItemsList.size > 1) "s" else ""}",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Sélectionnez un aliment suggéré ou tapez un nouvel aliment pour enrichir votre catalogue.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(10.dp))
// Auto-complete / Quick suggestions row
if (matchingSuggestions.isNotEmpty()) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
items(matchingSuggestions, key = { it.name }) { suggestion ->
SuggestionChip(
onClick = {
onFoodNameChange(suggestion.name)
onFoodUnitSelected(suggestion.defaultUnit)
},
label = {
Text(
text = "${suggestion.name} (${suggestion.defaultUnit.label})",
style = MaterialTheme.typography.labelSmall
)
},
colors = SuggestionChipDefaults.suggestionChipColors(
containerColor = MaterialTheme.colorScheme.surface,
labelColor = MaterialTheme.colorScheme.onSurface
)
)
}
}
Spacer(modifier = Modifier.height(10.dp))
}
// Food Name Input
OutlinedTextField(
value = foodNameInput,
onValueChange = { if (it.length <= 80) onFoodNameChange(it) },
modifier = Modifier
.fillMaxWidth()
.testTag("food_name_input"),
placeholder = {
Text("Nom de l'aliment (ex: Riz basmati, Saumon, Pomme...)")
},
singleLine = true,
shape = RoundedCornerShape(12.dp),
trailingIcon = {
if (foodNameInput.isNotEmpty()) {
IconButton(onClick = { onFoodNameChange("") }) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Effacer",
modifier = Modifier.size(18.dp)
)
}
}
}
)
if (isNewCustomFood) {
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "✨ « ${foodNameInput.trim()} » sera ajouté automatiquement à votre catalogue d'aliments",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary
)
}
Spacer(modifier = Modifier.height(10.dp))
// Optional Weight + Unit Selector + Add Button
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = foodWeightInput,
onValueChange = { input ->
if (input.length <= 7 && input.all { it.isDigit() || it == '.' || it == ',' }) {
onFoodWeightChange(input)
}
},
modifier = Modifier
.weight(1f)
.testTag("food_weight_input"),
placeholder = {
Text("Poids opt.")
},
leadingIcon = {
Icon(
imageVector = Icons.Default.Scale,
contentDescription = null,
modifier = Modifier.size(16.dp),
tint = MaterialTheme.colorScheme.primary
)
},
singleLine = true,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
shape = RoundedCornerShape(12.dp)
)
// Unit Selector Chips (g, ml, portion)
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
FoodUnit.entries.forEach { unit ->
val isUnitSelected = selectedFoodUnit == unit
FilterChip(
selected = isUnitSelected,
onClick = { onFoodUnitSelected(unit) },
label = {
Text(
text = unit.label,
style = MaterialTheme.typography.labelSmall
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
Spacer(modifier = Modifier.height(10.dp))
Button(
onClick = onAddFoodItem,
enabled = foodNameInput.trim().isNotEmpty(),
modifier = Modifier
.fillMaxWidth()
.testTag("add_food_item_button"),
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = if (foodWeightInput.isNotBlank()) {
"Ajouter à l'assiette (${foodWeightInput.trim()} ${selectedFoodUnit.label})"
} else {
"Ajouter à l'assiette (sans poids)"
},
style = MaterialTheme.typography.labelLarge
)
}
// Added food items badges
if (foodItemsList.isNotEmpty()) {
Spacer(modifier = Modifier.height(14.dp))
Text(
text = "Aliments dans l'assiette (touchez pour modifier le poids) :",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(8.dp))
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
foodItemsList.forEach { item ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surface,
modifier = Modifier
.clip(RoundedCornerShape(12.dp))
.clickable { onItemClickForEdit(item) }
) {
Row(
modifier = Modifier.padding(start = 12.dp, end = 6.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(6.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${item.name}",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.size(18.dp)
.clip(CircleShape)
.clickable { onRemoveFoodItem(item) }
.padding(2.dp)
)
}
}
}
}
}
}
}
}
@@ -0,0 +1,239 @@
package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.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.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CalendarMonth
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MealDateTimePicker(
mealTimestamp: Long,
onTimestampChanged: (Long) -> Unit,
modifier: Modifier = Modifier
) {
var showDatePicker by remember { mutableStateOf(false) }
var showTimePicker by remember { mutableStateOf(false) }
val zoneId = remember { ZoneId.systemDefault() }
val zonedDateTime = remember(mealTimestamp) {
Instant.ofEpochMilli(mealTimestamp).atZone(zoneId)
}
val dateFormatter = remember {
DateTimeFormatter.ofPattern("EEE d MMM yyyy", Locale.FRENCH)
}
val timeFormatter = remember {
DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
}
Column(modifier = modifier.fillMaxWidth()) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Date et heure du repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Maintenant",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable { onTimestampChanged(System.currentTimeMillis()) }
.padding(horizontal = 6.dp, vertical = 2.dp)
)
Text(
text = "Hier",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.secondary,
modifier = Modifier
.clip(RoundedCornerShape(6.dp))
.clickable {
val yesterdayMillis = zonedDateTime.minusDays(1).toInstant().toEpochMilli()
onTimestampChanged(yesterdayMillis)
}
.padding(horizontal = 6.dp, vertical = 2.dp)
)
}
}
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = { showDatePicker = true },
modifier = Modifier
.weight(1.3f)
.testTag("edit_date_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.CalendarMonth,
contentDescription = "Changer la date",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = dateFormatter.format(zonedDateTime).replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
OutlinedButton(
onClick = { showTimePicker = true },
modifier = Modifier
.weight(0.9f)
.testTag("edit_time_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = "Changer l'heure",
modifier = Modifier.size(18.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = timeFormatter.format(zonedDateTime),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
// Material 3 DatePickerDialog
if (showDatePicker) {
val datePickerState = rememberDatePickerState(
initialSelectedDateMillis = mealTimestamp
)
DatePickerDialog(
onDismissRequest = { showDatePicker = false },
confirmButton = {
TextButton(
onClick = {
val selectedUtcMillis = datePickerState.selectedDateMillis
if (selectedUtcMillis != null) {
// Extract year, month, day from the UTC date picker
val selectedLocalDate = Instant.ofEpochMilli(selectedUtcMillis)
.atZone(ZoneId.of("UTC"))
.toLocalDate()
val updatedZoned = zonedDateTime
.withYear(selectedLocalDate.year)
.withMonth(selectedLocalDate.monthValue)
.withDayOfMonth(selectedLocalDate.dayOfMonth)
onTimestampChanged(updatedZoned.toInstant().toEpochMilli())
}
showDatePicker = false
},
modifier = Modifier.testTag("confirm_date_button")
) {
Text("Valider la date")
}
},
dismissButton = {
TextButton(onClick = { showDatePicker = false }) {
Text("Annuler")
}
}
) {
DatePicker(state = datePickerState)
}
}
// Material 3 TimePicker Dialog
if (showTimePicker) {
val timePickerState = rememberTimePickerState(
initialHour = zonedDateTime.hour,
initialMinute = zonedDateTime.minute,
is24Hour = true
)
AlertDialog(
onDismissRequest = { showTimePicker = false },
title = { Text("Modifier l'heure du repas") },
text = {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
TimePicker(state = timePickerState)
}
},
confirmButton = {
TextButton(
onClick = {
val updatedZoned = zonedDateTime
.withHour(timePickerState.hour)
.withMinute(timePickerState.minute)
.withSecond(0)
onTimestampChanged(updatedZoned.toInstant().toEpochMilli())
showTimePicker = false
},
modifier = Modifier.testTag("confirm_time_button")
) {
Text("Valider l'heure")
}
},
dismissButton = {
TextButton(onClick = { showTimePicker = false }) {
Text("Annuler")
}
}
)
}
}
@@ -0,0 +1,161 @@
package com.example.ui.meal.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.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 kotlin.math.roundToInt
@Composable
fun MealHungerSatietySection(
hungerLevel: Int,
satietyLevel: Int,
onHungerChange: (Int) -> Unit,
onSatietyChange: (Int) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
// 1. Hunger Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "1. Faim avant le repas",
currentValue = hungerLevel,
accentColor = MaterialTheme.colorScheme.secondary,
onValueChange = onHungerChange,
description = HungerSatietyScale.getHungerLabel(hungerLevel),
sliderTag = "hunger_slider_10"
)
Spacer(modifier = Modifier.height(18.dp))
// 2. Satiety Stepped Slider (1 to 10)
SteppedScaleTenSlider(
title = "2. Satiété après le repas",
currentValue = satietyLevel,
accentColor = MaterialTheme.colorScheme.primary,
onValueChange = onSatietyChange,
description = HungerSatietyScale.getSatietyLabel(satietyLevel),
sliderTag = "satiety_slider_10"
)
}
}
@Composable
fun SteppedScaleTenSlider(
title: String,
currentValue: Int,
accentColor: Color,
onValueChange: (Int) -> Unit,
description: String,
sliderTag: String,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = modifier.fillMaxWidth()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 14.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurface
)
Surface(
shape = RoundedCornerShape(10.dp),
color = accentColor.copy(alpha = 0.2f)
) {
Text(
text = "$currentValue / 10",
style = MaterialTheme.typography.titleMedium,
color = accentColor,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp)
)
}
}
Spacer(modifier = Modifier.height(6.dp))
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = accentColor,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(4.dp))
Slider(
value = currentValue.toFloat(),
onValueChange = { newValue ->
onValueChange(newValue.roundToInt().coerceIn(1, 10))
},
valueRange = 1f..10f,
steps = 8,
colors = SliderDefaults.colors(
thumbColor = accentColor,
activeTrackColor = accentColor,
inactiveTrackColor = MaterialTheme.colorScheme.outlineVariant,
activeTickColor = MaterialTheme.colorScheme.surface,
inactiveTickColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
),
modifier = Modifier
.fillMaxWidth()
.testTag(sliderTag)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
(1..10).forEach { num ->
val isSelected = num == currentValue
Text(
text = num.toString(),
style = MaterialTheme.typography.labelSmall,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
color = if (isSelected) accentColor else MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
modifier = Modifier
.clip(CircleShape)
.clickable { onValueChange(num) }
.padding(horizontal = 4.dp, vertical = 2.dp)
)
}
}
}
}
}
@@ -0,0 +1,133 @@
package com.example.ui.meal.components
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.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.AddAPhoto
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
@Composable
fun MealPhotosSection(
photoUris: List<String>,
isProcessingPhoto: Boolean,
onAddPhotoClick: () -> Unit,
onDeletePhotoClick: (String) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
Text(
text = "Photos de l'assiette (${photoUris.size}/4)",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
LazyRow(
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (photoUris.size < 4) {
item {
Surface(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
.border(
width = 1.dp,
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
shape = RoundedCornerShape(14.dp)
)
.clickable(enabled = !isProcessingPhoto) {
onAddPhotoClick()
}
.testTag("add_photo_button"),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f)
) {
Box(contentAlignment = Alignment.Center) {
if (isProcessingPhoto) {
CircularProgressIndicator(
modifier = Modifier.size(24.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
} else {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Icon(
imageVector = Icons.Default.AddAPhoto,
contentDescription = "Ajouter une photo",
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = "Ajouter",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
}
items(photoUris) { photoUri ->
Box(
modifier = Modifier
.size(84.dp)
.clip(RoundedCornerShape(14.dp))
) {
AsyncImage(
model = photoUri,
contentDescription = "Photo de l'assiette",
modifier = Modifier.matchParentSize(),
contentScale = ContentScale.Crop
)
Surface(
modifier = Modifier
.align(Alignment.TopEnd)
.padding(4.dp)
.size(22.dp)
.clip(CircleShape)
.clickable { onDeletePhotoClick(photoUri) },
color = Color.Black.copy(alpha = 0.7f)
) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Supprimer photo",
tint = Color.White,
modifier = Modifier.padding(2.dp)
)
}
}
}
}
}
}
@@ -0,0 +1,54 @@
package com.example.ui.meal.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.data.model.MealType
@Composable
fun MealTypeSelector(
selectedType: MealType,
onTypeSelected: (MealType) -> Unit,
modifier: Modifier = Modifier
) {
Column(modifier = modifier.fillMaxWidth()) {
Text(
text = "Type de repas",
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(8.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
MealType.entries.forEach { type ->
val isSelected = selectedType == type
FilterChip(
selected = isSelected,
onClick = { onTypeSelected(type) },
label = {
Text(
text = type.displayName,
style = MaterialTheme.typography.labelMedium
)
},
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
)
)
}
}
}
}
@@ -45,8 +45,9 @@ import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.sp
import com.example.ui.journal.GoogleSheetsUiState
import java.text.SimpleDateFormat
import java.util.Date
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
@@ -357,8 +358,8 @@ fun SettingsScreen(
}
}
is GoogleSheetsUiState.Success -> {
val timeStr = SimpleDateFormat("dd/MM/yyyy à HH:mm", Locale.FRENCH)
.format(Date(sheetsUiState.timestamp))
val timeStr = DateTimeFormatter.ofPattern("dd/MM/yyyy 'à' HH:mm", Locale.FRENCH)
.format(Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault()))
Column(
modifier = Modifier
.fillMaxWidth()
@@ -884,16 +885,7 @@ fun SettingsScreen(
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()
},
onClick = onSignOut,
modifier = Modifier
.fillMaxWidth()
.testTag("signout_button"),
@@ -10,21 +10,24 @@ 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.time.Instant
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
object CsvExporter {
private val fileDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.FRENCH)
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
fun buildDefaultFileName(): String {
val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(Date())
val dateStr = fileDateFormatter.format(LocalDate.now())
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)
fun generateCsvContent(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): String {
val sb = StringBuilder()
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
sb.append('\uFEFF')
@@ -32,15 +35,15 @@ object CsvExporter {
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 zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
val dateStr = dateFormatter.format(zonedDateTime)
val timeStr = timeFormatter.format(zonedDateTime)
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
val photoCount = meal.displayPhotoUris.size
sb.append(escapeCsvField(dateStr)).append(',')
sb.append(escapeCsvField(timeStr)).append(',')
@@ -11,9 +11,11 @@ import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.UUID
@@ -25,17 +27,18 @@ data class CsvImportResult(
object CsvImporter {
private val supportedDateFormats = listOf(
SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH),
SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH),
SimpleDateFormat("dd-MM-yyyy", Locale.FRENCH),
SimpleDateFormat("d/M/yyyy", Locale.FRENCH)
private val supportedDatePatterns = listOf(
"dd/MM/yyyy",
"yyyy-MM-dd",
"dd-MM-yyyy",
"d/M/yyyy"
)
private val supportedTimeFormats = listOf(
SimpleDateFormat("HH:mm", Locale.FRENCH),
SimpleDateFormat("H:mm", Locale.FRENCH),
SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
private val supportedTimePatterns = listOf(
"HH:mm",
"H:mm",
"HH:mm:ss",
"H:mm:ss"
)
suspend fun importFromUri(
@@ -157,36 +160,32 @@ object CsvImporter {
return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else ""
}
private fun parseTimestamp(dateStr: String, timeStr: String): Long? {
private fun parseTimestamp(dateStr: String, timeStr: String, zoneId: ZoneId = ZoneId.systemDefault()): Long? {
if (dateStr.isBlank()) return null
var parsedDate: Date? = null
for (df in supportedDateFormats) {
var parsedLocalDate: LocalDate? = null
for (pattern in supportedDatePatterns) {
try {
parsedDate = df.parse(dateStr.trim())
if (parsedDate != null) break
parsedLocalDate = LocalDate.parse(dateStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
if (parsedLocalDate != null) break
} catch (_: Exception) {}
}
if (parsedDate == null) return null
val cal = Calendar.getInstance().apply { time = parsedDate }
if (parsedLocalDate == null) return null
var parsedLocalTime = LocalTime.NOON
if (timeStr.isNotBlank()) {
for (tf in supportedTimeFormats) {
for (pattern in supportedTimePatterns) {
try {
val parsedTime = tf.parse(timeStr.trim())
if (parsedTime != null) {
val timeCal = Calendar.getInstance().apply { time = parsedTime }
cal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY))
cal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE))
cal.set(Calendar.SECOND, 0)
cal.set(Calendar.MILLISECOND, 0)
break
}
parsedLocalTime = LocalTime.parse(timeStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
break
} catch (_: Exception) {}
}
}
return cal.timeInMillis
return LocalDateTime.of(parsedLocalDate, parsedLocalTime)
.atZone(zoneId)
.toInstant()
.toEpochMilli()
}
private fun parseMealType(raw: String): MealType {
@@ -3,8 +3,9 @@ package com.example.util
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealType
import java.text.SimpleDateFormat
import java.util.Date
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
object GoogleSheetsDataFormatter {
@@ -22,10 +23,10 @@ object GoogleSheetsDataFormatter {
"Photos jointes"
)
fun formatMealsToRows(meals: List<MealEntry>): List<List<Any>> {
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
fun formatMealsToRows(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): List<List<Any>> {
val rows = mutableListOf<List<Any>>()
// Header row
rows.add(HEADERS)
@@ -34,15 +35,15 @@ object GoogleSheetsDataFormatter {
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 zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
val dateStr = dateFormatter.format(zonedDateTime)
val timeStr = timeFormatter.format(zonedDateTime)
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 = meal.note.replace("\r\n", " ").replace("\n", " ").trim()
val photosCount = meal.photosBase64.size
val photosCount = meal.displayPhotoUris.size
rows.add(
listOf(
+100 -52
View File
@@ -5,72 +5,120 @@ import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Base64
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.util.UUID
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
private const val TAG = "ImageUtils"
private const val PHOTOS_DIR_NAME = "meal_photos"
private const val MAX_DIMENSION = 960
private const val JPEG_QUALITY = 80
// 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 getPhotosDirectory(context: Context): File {
return File(context.applicationContext.filesDir, PHOTOS_DIR_NAME).apply {
if (!exists()) {
mkdirs()
}
}
}
suspend fun saveImageToPrivateStorage(
context: Context,
sourceUri: Uri
): String? = withContext(Dispatchers.IO) {
try {
var inputStream: InputStream? = context.contentResolver.openInputStream(sourceUri)
?: return@withContext null
// 1. Decode bounds
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(inputStream, null, options)
inputStream?.close()
// 2. Calculate inSampleSize for memory safety
var inSampleSize = 1
if (options.outHeight > MAX_DIMENSION || options.outWidth > MAX_DIMENSION) {
val halfHeight = options.outHeight / 2
val halfWidth = options.outWidth / 2
while (halfHeight / inSampleSize >= MAX_DIMENSION && halfWidth / inSampleSize >= MAX_DIMENSION) {
inSampleSize *= 2
}
}
// 3. Decode actual bitmap
val decodeOptions = BitmapFactory.Options().apply {
this.inSampleSize = inSampleSize
}
inputStream = context.contentResolver.openInputStream(sourceUri)
val decodedBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
inputStream?.close()
if (decodedBitmap == null) return@withContext null
// 4. Scale to max dimension while preserving aspect ratio
val scaledBitmap = if (decodedBitmap.width > MAX_DIMENSION || decodedBitmap.height > MAX_DIMENSION) {
val ratio = minOf(
MAX_DIMENSION.toFloat() / decodedBitmap.width,
MAX_DIMENSION.toFloat() / decodedBitmap.height
)
val targetW = (decodedBitmap.width * ratio).toInt().coerceAtLeast(1)
val targetH = (decodedBitmap.height * ratio).toInt().coerceAtLeast(1)
Bitmap.createScaledBitmap(decodedBitmap, targetW, targetH, true).also {
if (it != decodedBitmap) decodedBitmap.recycle()
}
} else {
decodedBitmap
}
// 5. Write directly to private JPEG file
val targetDir = getPhotosDirectory(context)
val uniqueFileName = "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg"
val targetFile = File(targetDir, uniqueFileName)
FileOutputStream(targetFile).use { outStream ->
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, outStream)
outStream.flush()
}
scaledBitmap.recycle()
Uri.fromFile(targetFile).toString()
} catch (e: Exception) {
Log.e(TAG, "Error saving image to private storage: ${e.message}", e)
null
}
}
fun deletePhotoFile(photoUriStr: String?): Boolean {
if (photoUriStr.isNullOrBlank()) return false
return try {
val uri = Uri.parse(photoUriStr)
val path = uri.path
if (path != null) {
val file = File(path)
if (file.exists()) {
file.delete()
} else false
} else false
} catch (e: Exception) {
Log.w(TAG, "Could not delete photo file: ${e.message}")
false
}
}
// Retained for backward-compatibility if old Base64 entries need temporary conversion
fun base64ToBitmap(base64Str: String): Bitmap? {
return try {
val bytes = Base64.decode(base64Str, Base64.DEFAULT)
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
} catch (e: Exception) {
} catch (_: Exception) {
null
}
}