mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
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:
1 parent
f0487453c9
commit
87bbb448c2
34 files changed
+1975
-1119
No files matched your search
@@ -6,7 +6,6 @@
|
|||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.VIBRATE" />
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
|
|||||||
@@ -38,11 +38,13 @@ import androidx.compose.material3.Text
|
|||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.example.ui.common.UiEvent
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.testTag
|
import androidx.compose.ui.platform.testTag
|
||||||
@@ -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 currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
|
||||||
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
|
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
|
||||||
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
||||||
@@ -201,6 +220,7 @@ fun AppRoot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
|
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
|
||||||
|
val weeklyStats by viewModel.weeklyStats.collectAsStateWithLifecycle()
|
||||||
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
|
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
|
||||||
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
||||||
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
|
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
|
||||||
@@ -450,9 +470,6 @@ fun AppRoot(
|
|||||||
}
|
}
|
||||||
|
|
||||||
MainTab.STATS -> {
|
MainTab.STATS -> {
|
||||||
val weeklyStats = remember(currentMealsList) {
|
|
||||||
viewModel.computeWeeklyStats(currentMealsList)
|
|
||||||
}
|
|
||||||
WeeklyStatsScreen(
|
WeeklyStatsScreen(
|
||||||
weeklyStats = weeklyStats,
|
weeklyStats = weeklyStats,
|
||||||
totalMealsCount = currentMealsList.size,
|
totalMealsCount = currentMealsList.size,
|
||||||
@@ -489,12 +506,13 @@ fun AppRoot(
|
|||||||
onOpenSheetsClick = { url -> openGoogleSheets(url) },
|
onOpenSheetsClick = { url -> openGoogleSheets(url) },
|
||||||
onSignInClick = { showAuthSheet = true },
|
onSignInClick = { showAuthSheet = true },
|
||||||
onSignOut = {
|
onSignOut = {
|
||||||
|
viewModel.signOut(context) {
|
||||||
currentUser = null
|
currentUser = null
|
||||||
viewModel.disconnectGoogleSheets()
|
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
snackbarHostState.showSnackbar("Mode local actif • Déconnecté")
|
snackbarHostState.showSnackbar("Mode local actif • Déconnecté")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -522,7 +540,7 @@ fun AppRoot(
|
|||||||
hungerBefore = hunger,
|
hungerBefore = hunger,
|
||||||
satietyAfter = satiety,
|
satietyAfter = satiety,
|
||||||
note = note,
|
note = note,
|
||||||
photosBase64 = photos
|
photoUris = photos
|
||||||
),
|
),
|
||||||
foodItems = foodItems,
|
foodItems = foodItems,
|
||||||
onSuccess = {
|
onSuccess = {
|
||||||
@@ -544,7 +562,7 @@ fun AppRoot(
|
|||||||
satietyAfter = satiety,
|
satietyAfter = satiety,
|
||||||
note = note,
|
note = note,
|
||||||
foodItems = foodItems,
|
foodItems = foodItems,
|
||||||
photosBase64 = photos,
|
photoUris = photos,
|
||||||
onSuccess = {
|
onSuccess = {
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
snackbarHostState.showSnackbar("Repas enregistré avec succès ✨")
|
snackbarHostState.showSnackbar("Repas enregistré avec succès ✨")
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import androidx.room.RoomDatabase
|
|||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class],
|
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class],
|
||||||
version = 1,
|
version = 2,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class AppDatabase : RoomDatabase() {
|
abstract class AppDatabase : RoomDatabase() {
|
||||||
@@ -24,7 +24,7 @@ abstract class AppDatabase : RoomDatabase() {
|
|||||||
context.applicationContext,
|
context.applicationContext,
|
||||||
AppDatabase::class.java,
|
AppDatabase::class.java,
|
||||||
"satiea_local.db"
|
"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.Entity
|
||||||
import androidx.room.PrimaryKey
|
import androidx.room.PrimaryKey
|
||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealFoodItem
|
|
||||||
|
|
||||||
@Entity(tableName = "local_meals")
|
@Entity(tableName = "local_meals")
|
||||||
data class LocalMealEntity(
|
data class LocalMealEntity(
|
||||||
@@ -15,7 +14,7 @@ data class LocalMealEntity(
|
|||||||
val satietyAfter: Int,
|
val satietyAfter: Int,
|
||||||
val note: String = "",
|
val note: String = "",
|
||||||
val foodItemsJoined: String = "", // serialized items separated by "###"
|
val foodItemsJoined: String = "", // serialized items separated by "###"
|
||||||
val photosJoined: String = "", // Base64 photos separated by "|||"
|
val photoUrisJoined: String = "", // local file URIs separated by "|||"
|
||||||
val updatedAt: Long = System.currentTimeMillis()
|
val updatedAt: Long = System.currentTimeMillis()
|
||||||
) {
|
) {
|
||||||
fun toMealEntry(): MealEntry {
|
fun toMealEntry(): MealEntry {
|
||||||
@@ -24,10 +23,10 @@ data class LocalMealEntity(
|
|||||||
} else {
|
} else {
|
||||||
foodItemsJoined.split("###").filter { it.isNotBlank() }
|
foodItemsJoined.split("###").filter { it.isNotBlank() }
|
||||||
}
|
}
|
||||||
val photos = if (photosJoined.isBlank()) {
|
val photos = if (photoUrisJoined.isBlank()) {
|
||||||
emptyList()
|
emptyList()
|
||||||
} else {
|
} else {
|
||||||
photosJoined.split("|||").filter { it.isNotBlank() }
|
photoUrisJoined.split("|||").filter { it.isNotBlank() }
|
||||||
}
|
}
|
||||||
return MealEntry(
|
return MealEntry(
|
||||||
id = id,
|
id = id,
|
||||||
@@ -38,14 +37,15 @@ data class LocalMealEntity(
|
|||||||
satietyAfter = satietyAfter,
|
satietyAfter = satietyAfter,
|
||||||
note = note,
|
note = note,
|
||||||
foodItemsSerialized = foodItems,
|
foodItemsSerialized = foodItems,
|
||||||
photosBase64 = photos
|
photoUris = photos,
|
||||||
|
photosBase64 = emptyList()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun fromMealEntry(meal: MealEntry): LocalMealEntity {
|
fun fromMealEntry(meal: MealEntry): LocalMealEntity {
|
||||||
val foodItemsJoined = meal.foodItemsSerialized.joinToString("###")
|
val foodItemsJoined = meal.foodItemsSerialized.joinToString("###")
|
||||||
val photosJoined = meal.photosBase64.joinToString("|||")
|
val photoUrisJoined = meal.displayPhotoUris.joinToString("|||")
|
||||||
return LocalMealEntity(
|
return LocalMealEntity(
|
||||||
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
|
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
|
||||||
userId = meal.userId,
|
userId = meal.userId,
|
||||||
@@ -55,7 +55,7 @@ data class LocalMealEntity(
|
|||||||
satietyAfter = meal.satietyAfter,
|
satietyAfter = meal.satietyAfter,
|
||||||
note = meal.note,
|
note = meal.note,
|
||||||
foodItemsJoined = foodItemsJoined,
|
foodItemsJoined = foodItemsJoined,
|
||||||
photosJoined = photosJoined,
|
photoUrisJoined = photoUrisJoined,
|
||||||
updatedAt = System.currentTimeMillis()
|
updatedAt = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -92,10 +92,14 @@ data class MealEntry(
|
|||||||
val satietyAfter: Int = 7,
|
val satietyAfter: Int = 7,
|
||||||
val note: String = "",
|
val note: String = "",
|
||||||
val foodItemsSerialized: List<String> = emptyList(),
|
val foodItemsSerialized: List<String> = emptyList(),
|
||||||
|
val photoUris: List<String> = emptyList(),
|
||||||
val photosBase64: List<String> = emptyList(),
|
val photosBase64: List<String> = emptyList(),
|
||||||
@ServerTimestamp val createdAt: Timestamp? = null,
|
@ServerTimestamp val createdAt: Timestamp? = null,
|
||||||
@ServerTimestamp val updatedAt: Timestamp? = null
|
@ServerTimestamp val updatedAt: Timestamp? = null
|
||||||
) {
|
) {
|
||||||
|
val displayPhotoUris: List<String>
|
||||||
|
get() = photoUris.ifEmpty { photosBase64 }
|
||||||
|
|
||||||
fun parsedFoodItems(): List<MealFoodItem> {
|
fun parsedFoodItems(): List<MealFoodItem> {
|
||||||
return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) }
|
return foodItemsSerialized.mapNotNull { MealFoodItem.deserialize(it) }
|
||||||
}
|
}
|
||||||
@@ -109,7 +113,7 @@ data class MealEntry(
|
|||||||
"satietyAfter" to satietyAfter.coerceIn(1, 10),
|
"satietyAfter" to satietyAfter.coerceIn(1, 10),
|
||||||
"note" to note,
|
"note" to note,
|
||||||
"foodItemsSerialized" to foodItemsSerialized.take(30),
|
"foodItemsSerialized" to foodItemsSerialized.take(30),
|
||||||
"photosBase64" to photosBase64,
|
"photoUris" to photoUris.take(6),
|
||||||
"createdAt" to createdAt,
|
"createdAt" to createdAt,
|
||||||
"updatedAt" to updatedAt
|
"updatedAt" to updatedAt
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -28,13 +28,11 @@ fun handleFirestoreError(exception: Throwable, operationType: OperationType, pat
|
|||||||
val providerInfoList = currentUser?.providerData?.map { provider ->
|
val providerInfoList = currentUser?.providerData?.map { provider ->
|
||||||
JSONObject().apply {
|
JSONObject().apply {
|
||||||
put("providerId", provider.providerId)
|
put("providerId", provider.providerId)
|
||||||
put("email", provider.email)
|
|
||||||
}
|
}
|
||||||
} ?: emptyList()
|
} ?: emptyList()
|
||||||
|
|
||||||
val authInfoJson = JSONObject().apply {
|
val authInfoJson = JSONObject().apply {
|
||||||
put("userId", currentUser?.uid)
|
put("userId", currentUser?.uid)
|
||||||
put("email", currentUser?.email)
|
|
||||||
put("emailVerified", currentUser?.isEmailVerified)
|
put("emailVerified", currentUser?.isEmailVerified)
|
||||||
put("tenantId", currentUser?.tenantId)
|
put("tenantId", currentUser?.tenantId)
|
||||||
put("providerInfo", JSONArray(providerInfoList))
|
put("providerInfo", JSONArray(providerInfoList))
|
||||||
|
|||||||
@@ -13,7 +13,9 @@ import com.example.data.model.FoodUnit
|
|||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.util.CsvImportResult
|
import com.example.util.CsvImportResult
|
||||||
import com.example.util.CsvImporter
|
import com.example.util.CsvImporter
|
||||||
|
import com.example.util.ImageUtils
|
||||||
import com.google.firebase.Firebase
|
import com.google.firebase.Firebase
|
||||||
|
import com.google.firebase.auth.FirebaseAuth
|
||||||
import com.google.firebase.auth.auth
|
import com.google.firebase.auth.auth
|
||||||
import com.google.firebase.firestore.FieldValue
|
import com.google.firebase.firestore.FieldValue
|
||||||
import com.google.firebase.firestore.FirebaseFirestore
|
import com.google.firebase.firestore.FirebaseFirestore
|
||||||
@@ -32,7 +34,8 @@ import java.util.UUID
|
|||||||
|
|
||||||
class MealRepository(
|
class MealRepository(
|
||||||
private val localMealDao: LocalMealDao?,
|
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
|
// Constructor used by ViewModel in app runtime
|
||||||
@@ -50,11 +53,10 @@ class MealRepository(
|
|||||||
// Secondary constructor for Firestore rule tests without local DB
|
// Secondary constructor for Firestore rule tests without local DB
|
||||||
constructor(db: FirebaseFirestore) : this(
|
constructor(db: FirebaseFirestore) : this(
|
||||||
localMealDao = null,
|
localMealDao = null,
|
||||||
db = db
|
db = db,
|
||||||
|
auth = FirebaseAuth.getInstance(db.app)
|
||||||
)
|
)
|
||||||
|
|
||||||
private val auth = Firebase.auth
|
|
||||||
|
|
||||||
private fun getUserIdOrNull(): String? {
|
private fun getUserIdOrNull(): String? {
|
||||||
return auth.currentUser?.uid
|
return auth.currentUser?.uid
|
||||||
}
|
}
|
||||||
@@ -152,6 +154,7 @@ class MealRepository(
|
|||||||
)
|
)
|
||||||
docRef.set(payload).await()
|
docRef.set(payload).await()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
if (localMealDao == null) {
|
if (localMealDao == null) {
|
||||||
handleFirestoreError(e, OperationType.CREATE, docRef.path)
|
handleFirestoreError(e, OperationType.CREATE, docRef.path)
|
||||||
return Result.failure(e)
|
return Result.failure(e)
|
||||||
@@ -209,6 +212,7 @@ class MealRepository(
|
|||||||
val docRef = mealsRef.document(resolvedId)
|
val docRef = mealsRef.document(resolvedId)
|
||||||
docRef.set(payload).await()
|
docRef.set(payload).await()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
if (localMealDao == null) {
|
if (localMealDao == null) {
|
||||||
handleFirestoreError(e, OperationType.CREATE, path)
|
handleFirestoreError(e, OperationType.CREATE, path)
|
||||||
return Result.failure(e)
|
return Result.failure(e)
|
||||||
@@ -238,11 +242,12 @@ class MealRepository(
|
|||||||
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
|
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
|
||||||
"note" to meal.note,
|
"note" to meal.note,
|
||||||
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
|
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
|
||||||
"photosBase64" to meal.photosBase64,
|
"photoUris" to meal.photoUris.take(6),
|
||||||
"updatedAt" to FieldValue.serverTimestamp()
|
"updatedAt" to FieldValue.serverTimestamp()
|
||||||
)
|
)
|
||||||
docRef.update(updates).await()
|
docRef.update(updates).await()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
if (localMealDao == null) {
|
if (localMealDao == null) {
|
||||||
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
|
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
|
||||||
return Result.failure(e)
|
return Result.failure(e)
|
||||||
@@ -255,16 +260,23 @@ class MealRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun deleteMeal(mealId: String): Result<Unit> {
|
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)
|
localMealDao?.deleteMealById(mealId)
|
||||||
|
|
||||||
// 2. If signed in, delete from Firestore
|
// 3. If signed in, delete from Firestore
|
||||||
val uid = getUserIdOrNull()
|
val uid = getUserIdOrNull()
|
||||||
if (uid != null && db != null) {
|
if (uid != null && db != null) {
|
||||||
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
|
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
|
||||||
try {
|
try {
|
||||||
docRef.delete().await()
|
docRef.delete().await()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
if (localMealDao == null) {
|
if (localMealDao == null) {
|
||||||
handleFirestoreError(e, OperationType.DELETE, docRef.path)
|
handleFirestoreError(e, OperationType.DELETE, docRef.path)
|
||||||
return Result.failure(e)
|
return Result.failure(e)
|
||||||
@@ -341,6 +353,7 @@ class MealRepository(
|
|||||||
|
|
||||||
Result.success(result)
|
Result.success(result)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -389,6 +402,7 @@ class MealRepository(
|
|||||||
|
|
||||||
Result.success(importedCount)
|
Result.success(importedCount)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
Result.failure(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.model.MealType
|
||||||
import com.example.data.preferences.ReminderPreferencesManager
|
import com.example.data.preferences.ReminderPreferencesManager
|
||||||
import com.example.receiver.MealReminderReceiver
|
import com.example.receiver.MealReminderReceiver
|
||||||
import java.util.Calendar
|
import java.time.ZoneId
|
||||||
|
import java.time.ZonedDateTime
|
||||||
|
|
||||||
object MealNotificationManager {
|
object MealNotificationManager {
|
||||||
|
|
||||||
@@ -111,55 +112,31 @@ object MealNotificationManager {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val calendar = Calendar.getInstance().apply {
|
val zoneId = ZoneId.systemDefault()
|
||||||
timeInMillis = System.currentTimeMillis()
|
val nowZoned = ZonedDateTime.now(zoneId)
|
||||||
set(Calendar.HOUR_OF_DAY, hour)
|
var triggerZoned = nowZoned.withHour(hour).withMinute(minute).withSecond(0).withNano(0)
|
||||||
set(Calendar.MINUTE, minute)
|
if (!triggerZoned.isAfter(nowZoned)) {
|
||||||
set(Calendar.SECOND, 0)
|
triggerZoned = triggerZoned.plusDays(1)
|
||||||
set(Calendar.MILLISECOND, 0)
|
|
||||||
if (timeInMillis <= System.currentTimeMillis()) {
|
|
||||||
add(Calendar.DAY_OF_YEAR, 1)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
val triggerMillis = triggerZoned.toInstant().toEpochMilli()
|
||||||
|
|
||||||
try {
|
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) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
alarmManager.setAndAllowWhileIdle(
|
alarmManager.setAndAllowWhileIdle(
|
||||||
AlarmManager.RTC_WAKEUP,
|
AlarmManager.RTC_WAKEUP,
|
||||||
calendar.timeInMillis,
|
triggerMillis,
|
||||||
|
pendingIntent
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
alarmManager.set(
|
||||||
|
AlarmManager.RTC_WAKEUP,
|
||||||
|
triggerMillis,
|
||||||
pendingIntent
|
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 android.graphics.Bitmap
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
|
import coil.compose.AsyncImage
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
@@ -64,9 +65,10 @@ import com.example.data.model.HungerSatietyScale
|
|||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
import com.example.util.ImageUtils
|
import com.example.util.ImageUtils
|
||||||
import java.text.SimpleDateFormat
|
import java.time.Instant
|
||||||
import java.util.Calendar
|
import java.time.LocalDate
|
||||||
import java.util.Date
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
@@ -115,14 +117,10 @@ fun JournalScreen(
|
|||||||
|
|
||||||
is MealsUiState.Success -> {
|
is MealsUiState.Success -> {
|
||||||
val meals = mealsUiState.meals
|
val meals = mealsUiState.meals
|
||||||
val todayCalendar = Calendar.getInstance().apply {
|
val zoneId = ZoneId.systemDefault()
|
||||||
set(Calendar.HOUR_OF_DAY, 0)
|
val todayLocalDate = LocalDate.now(zoneId)
|
||||||
set(Calendar.MINUTE, 0)
|
val todayStartMillis = todayLocalDate.atStartOfDay(zoneId).toInstant().toEpochMilli()
|
||||||
set(Calendar.SECOND, 0)
|
val todayEndMillis = todayLocalDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1
|
||||||
set(Calendar.MILLISECOND, 0)
|
|
||||||
}
|
|
||||||
val todayStartMillis = todayCalendar.timeInMillis
|
|
||||||
val todayEndMillis = todayStartMillis + (24L * 60 * 60 * 1000) - 1
|
|
||||||
val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis }
|
val todayMeals = meals.filter { it.mealTimestamp in todayStartMillis..todayEndMillis }
|
||||||
|
|
||||||
LazyColumn(
|
LazyColumn(
|
||||||
@@ -236,9 +234,9 @@ fun JournalScreen(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun DailyOverviewCard(todayMeals: List<MealEntry>) {
|
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 {
|
val todayFormatted = remember {
|
||||||
dateFormat.format(Date()).replaceFirstChar {
|
dateFormatter.format(LocalDate.now()).replaceFirstChar {
|
||||||
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,7 +336,8 @@ private fun MealCardItem(
|
|||||||
) {
|
) {
|
||||||
var showMenu by remember { mutableStateOf(false) }
|
var showMenu by remember { mutableStateOf(false) }
|
||||||
var showDeleteDialog 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 mealType = MealType.fromString(meal.mealType)
|
||||||
val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() }
|
val parsedFoods = remember(meal.foodItemsSerialized) { meal.parsedFoodItems() }
|
||||||
|
|
||||||
@@ -397,7 +396,7 @@ private fun MealCardItem(
|
|||||||
)
|
)
|
||||||
Spacer(modifier = Modifier.width(4.dp))
|
Spacer(modifier = Modifier.width(4.dp))
|
||||||
Text(
|
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()
|
if (it.isLowerCase()) it.titlecase(Locale.FRENCH) else it.toString()
|
||||||
},
|
},
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
@@ -544,17 +543,15 @@ private fun MealCardItem(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Photos Carousel
|
// Photos Carousel
|
||||||
if (meal.photosBase64.isNotEmpty()) {
|
if (meal.displayPhotoUris.isNotEmpty()) {
|
||||||
Spacer(modifier = Modifier.height(14.dp))
|
Spacer(modifier = Modifier.height(14.dp))
|
||||||
LazyRow(
|
LazyRow(
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
) {
|
) {
|
||||||
items(meal.photosBase64) { b64 ->
|
items(meal.displayPhotoUris) { photoUri ->
|
||||||
val bitmap: Bitmap? = remember(b64) { ImageUtils.base64ToBitmap(b64) }
|
AsyncImage(
|
||||||
if (bitmap != null) {
|
model = photoUri,
|
||||||
Image(
|
contentDescription = "Photo du repas",
|
||||||
bitmap = bitmap.asImageBitmap(),
|
|
||||||
contentDescription = "Photo assiette",
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.size(76.dp)
|
.size(76.dp)
|
||||||
.clip(RoundedCornerShape(12.dp)),
|
.clip(RoundedCornerShape(12.dp)),
|
||||||
@@ -563,7 +560,6 @@ private fun MealCardItem(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Global Note
|
// Global Note
|
||||||
if (meal.note.isNotBlank()) {
|
if (meal.note.isNotBlank()) {
|
||||||
|
|||||||
@@ -11,26 +11,33 @@ import com.example.data.model.DefaultFoodCatalog
|
|||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealFoodItem
|
import com.example.data.model.MealFoodItem
|
||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
import com.example.data.repository.MealRepository
|
|
||||||
import com.example.data.preferences.GoogleSheetsPreferencesManager
|
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.notification.MealNotificationManager
|
||||||
|
import com.example.ui.common.UiEvent
|
||||||
import com.example.ui.theme.AppThemeMode
|
import com.example.ui.theme.AppThemeMode
|
||||||
import com.example.util.CsvExporter
|
import com.example.util.CsvImportResult
|
||||||
import com.example.util.GoogleSheetsAuthHelper
|
import com.google.firebase.auth.FirebaseAuth
|
||||||
import com.example.util.GoogleSheetsSyncService
|
|
||||||
import com.google.android.gms.auth.UserRecoverableAuthException
|
|
||||||
import com.google.firebase.firestore.FirebaseFirestoreException
|
import com.google.firebase.firestore.FirebaseFirestoreException
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.catch
|
import kotlinx.coroutines.flow.catch
|
||||||
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.receiveAsFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalDate
|
||||||
import java.util.Calendar
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
sealed interface MealsUiState {
|
sealed interface MealsUiState {
|
||||||
@@ -62,12 +69,36 @@ data class WeeklyStats(
|
|||||||
val optimalZonePercentage: Int,
|
val optimalZonePercentage: Int,
|
||||||
val totalMealsLast7Days: Int,
|
val totalMealsLast7Days: Int,
|
||||||
val mealTypeDistribution: Map<MealType, 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) {
|
class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
|
|
||||||
private val repository = MealRepository(application)
|
private val repository = MealRepository(application)
|
||||||
private val context = application.applicationContext
|
private val context = application.applicationContext
|
||||||
|
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
|
||||||
|
|
||||||
|
// 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()
|
val mealsState: StateFlow<MealsUiState> = repository.observeMeals()
|
||||||
.map<List<MealEntry>, MealsUiState> { meals ->
|
.map<List<MealEntry>, MealsUiState> { meals ->
|
||||||
@@ -87,6 +118,16 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
initialValue = MealsUiState.Loading
|
initialValue = MealsUiState.Loading
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Asynchronous background computation of WeeklyStats via Dispatchers.Default
|
||||||
|
val weeklyStats: StateFlow<WeeklyStats> = repository.observeMeals()
|
||||||
|
.map { meals -> computeWeeklyStats(meals) }
|
||||||
|
.flowOn(Dispatchers.Default)
|
||||||
|
.stateIn(
|
||||||
|
scope = viewModelScope,
|
||||||
|
started = SharingStarted.WhileSubscribed(5000L),
|
||||||
|
initialValue = WeeklyStats.empty()
|
||||||
|
)
|
||||||
|
|
||||||
val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods()
|
val customFoods: StateFlow<List<CustomFoodEntry>> = repository.observeCustomFoods()
|
||||||
.catch { error ->
|
.catch { error ->
|
||||||
val firestoreError = generateSequence(error) { it.cause }
|
val firestoreError = generateSequence(error) { it.cause }
|
||||||
@@ -104,8 +145,6 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
|
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
|
||||||
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
|
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
|
||||||
|
|
||||||
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
|
|
||||||
|
|
||||||
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
|
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
|
||||||
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
|
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
|
||||||
GoogleSheetsUiState.Success(
|
GoogleSheetsUiState.Success(
|
||||||
@@ -170,7 +209,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
satietyAfter: Int,
|
satietyAfter: Int,
|
||||||
note: String,
|
note: String,
|
||||||
foodItems: List<MealFoodItem>,
|
foodItems: List<MealFoodItem>,
|
||||||
photosBase64: List<String>,
|
photoUris: List<String> = emptyList(),
|
||||||
|
photosBase64: List<String> = emptyList(),
|
||||||
onSuccess: () -> Unit = {},
|
onSuccess: () -> Unit = {},
|
||||||
onError: (String) -> Unit = {}
|
onError: (String) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
@@ -183,14 +223,34 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
satietyAfter = satietyAfter.coerceIn(1, 10),
|
satietyAfter = satietyAfter.coerceIn(1, 10),
|
||||||
note = note.trim(),
|
note = note.trim(),
|
||||||
foodItemsSerialized = foodItems.map { it.serialize() }.take(30),
|
foodItemsSerialized = foodItems.map { it.serialize() }.take(30),
|
||||||
photosBase64 = photosBase64
|
photoUris = photoUris.ifEmpty { photosBase64 },
|
||||||
|
photosBase64 = emptyList()
|
||||||
)
|
)
|
||||||
val result = repository.addMeal(entry)
|
val result = repository.addMeal(entry)
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
onSuccess()
|
onSuccess()
|
||||||
|
emitEvent(UiEvent.ShowSnackbar("Repas enregistré avec succès ✨"))
|
||||||
triggerAutoSheetsSyncIfNeeded()
|
triggerAutoSheetsSyncIfNeeded()
|
||||||
} else {
|
} 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)
|
val result = repository.updateMeal(sanitizedMeal)
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
onSuccess()
|
onSuccess()
|
||||||
|
emitEvent(UiEvent.ShowSnackbar("Repas mis à jour ✨"))
|
||||||
triggerAutoSheetsSyncIfNeeded()
|
triggerAutoSheetsSyncIfNeeded()
|
||||||
} else {
|
} 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)
|
val result = repository.deleteMeal(mealId)
|
||||||
if (result.isSuccess) {
|
if (result.isSuccess) {
|
||||||
onSuccess()
|
onSuccess()
|
||||||
|
emitEvent(UiEvent.ShowSnackbar("Repas supprimé"))
|
||||||
triggerAutoSheetsSyncIfNeeded()
|
triggerAutoSheetsSyncIfNeeded()
|
||||||
} else {
|
} else {
|
||||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression")
|
val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression"
|
||||||
|
onError(err)
|
||||||
|
emitEvent(UiEvent.ShowSnackbar(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -237,27 +303,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
private fun triggerAutoSheetsSyncIfNeeded() {
|
private fun triggerAutoSheetsSyncIfNeeded() {
|
||||||
if (!sheetsPrefs.isAutoSyncEnabled) return
|
if (!sheetsPrefs.isAutoSyncEnabled) return
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
try {
|
sheetsSyncUseCase.executeAutoSyncQuietly()?.let { res ->
|
||||||
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
|
_spreadsheetUrl.value = res.spreadsheetUrl
|
||||||
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)
|
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
|
||||||
}
|
}
|
||||||
} catch (_: Exception) {
|
|
||||||
// Non-blocking background sync
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,51 +316,22 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
_sheetsUiState.value = GoogleSheetsUiState.Syncing
|
_sheetsUiState.value = GoogleSheetsUiState.Syncing
|
||||||
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
|
when (val result = sheetsSyncUseCase.execute()) {
|
||||||
if (tokenResult.isFailure) {
|
is SheetsSyncResult.Success -> {
|
||||||
val exception = tokenResult.exceptionOrNull()
|
_spreadsheetUrl.value = result.url
|
||||||
if (exception is UserRecoverableAuthException) {
|
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
|
||||||
val intent = exception.intent
|
onSuccess(result.url, result.count)
|
||||||
_sheetsUiState.value = GoogleSheetsUiState.Error(
|
emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊"))
|
||||||
"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)
|
|
||||||
}
|
}
|
||||||
return@launch
|
is SheetsSyncResult.RecoverableAuth -> {
|
||||||
|
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
|
||||||
|
onError(result.message, result.intent)
|
||||||
}
|
}
|
||||||
|
is SheetsSyncResult.Failure -> {
|
||||||
val token = tokenResult.getOrThrow()
|
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message)
|
||||||
val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
|
onError(result.message, null)
|
||||||
if (spreadsheetResult.isFailure) {
|
emitEvent(UiEvent.ShowSnackbar(result.message))
|
||||||
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
|
onError: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val result = CsvExporter.writeCsvToUri(context, targetUri, meals)
|
val result = csvExportUseCase.writeToUri(targetUri, meals)
|
||||||
result.fold(
|
result.fold(
|
||||||
onSuccess = { count -> onSuccess(count) },
|
onSuccess = { count ->
|
||||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'export CSV") }
|
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(
|
fun importCsvFromUri(
|
||||||
sourceUri: Uri,
|
sourceUri: Uri,
|
||||||
onSuccess: (com.example.util.CsvImportResult) -> Unit,
|
onSuccess: (CsvImportResult) -> Unit,
|
||||||
onError: (String) -> Unit
|
onError: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val result = repository.importMealsFromCsv(context, sourceUri)
|
val result = repository.importMealsFromCsv(context, sourceUri)
|
||||||
result.fold(
|
result.fold(
|
||||||
onSuccess = { importResult -> onSuccess(importResult) },
|
onSuccess = { importResult ->
|
||||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'import du fichier CSV") }
|
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 {
|
viewModelScope.launch {
|
||||||
val result = repository.syncCloudToLocal()
|
val result = repository.syncCloudToLocal()
|
||||||
result.fold(
|
result.fold(
|
||||||
onSuccess = { count -> onSuccess(count) },
|
onSuccess = { count ->
|
||||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de la synchronisation") }
|
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
|
onError: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val result = CsvExporter.shareCsvFile(activityContext, meals)
|
val result = csvExportUseCase.createShareIntent(activityContext, meals)
|
||||||
result.fold(
|
result.fold(
|
||||||
onSuccess = { chooserIntent -> onIntentReady(chooserIntent) },
|
onSuccess = { chooserIntent ->
|
||||||
onFailure = { err -> onError(err.localizedMessage ?: "Impossible de préparer le partage CSV") }
|
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) {
|
fun triggerTestNotification(mealType: MealType) {
|
||||||
MealNotificationManager.showMealNotification(context, mealType)
|
MealNotificationManager.showMealNotification(context, mealType)
|
||||||
|
emitEvent(UiEvent.ShowSnackbar("Notification de rappel envoyée !"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun computeWeeklyStats(meals: List<MealEntry>): WeeklyStats {
|
fun computeWeeklyStats(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): WeeklyStats {
|
||||||
val now = System.currentTimeMillis()
|
return com.example.domain.WeeklyStatsCalculator.computeWeeklyStats(meals, zoneId)
|
||||||
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
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,67 +1,33 @@
|
|||||||
package com.example.ui.meal
|
package com.example.ui.meal
|
||||||
|
|
||||||
import android.graphics.Bitmap
|
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.PickVisualMediaRequest
|
import androidx.activity.result.PickVisualMediaRequest
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
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.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
|
||||||
import androidx.compose.foundation.layout.FlowRow
|
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
import androidx.compose.foundation.layout.Spacer
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
import androidx.compose.foundation.lazy.LazyRow
|
|
||||||
import androidx.compose.foundation.lazy.items
|
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.CircleShape
|
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
import androidx.compose.foundation.text.KeyboardOptions
|
|
||||||
import androidx.compose.foundation.verticalScroll
|
import androidx.compose.foundation.verticalScroll
|
||||||
import androidx.compose.material.icons.Icons
|
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.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.Button
|
||||||
import androidx.compose.material3.ButtonDefaults
|
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.ExperimentalMaterial3Api
|
||||||
import androidx.compose.material3.FilterChip
|
|
||||||
import androidx.compose.material3.FilterChipDefaults
|
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
import androidx.compose.material3.OutlinedTextField
|
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.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TimePicker
|
|
||||||
import androidx.compose.material3.rememberDatePickerState
|
|
||||||
import androidx.compose.material3.rememberModalBottomSheetState
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
import androidx.compose.material3.rememberTimePickerState
|
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
@@ -70,36 +36,30 @@ import androidx.compose.runtime.mutableStateListOf
|
|||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.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.LocalContext
|
||||||
import androidx.compose.ui.platform.testTag
|
import androidx.compose.ui.platform.testTag
|
||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.text.input.KeyboardType
|
|
||||||
import androidx.compose.ui.text.style.TextAlign
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.example.data.model.CustomFoodEntry
|
import com.example.data.model.CustomFoodEntry
|
||||||
import com.example.data.model.DefaultFoodCatalog
|
import com.example.data.model.DefaultFoodCatalog
|
||||||
import com.example.data.model.FoodUnit
|
import com.example.data.model.FoodUnit
|
||||||
import com.example.data.model.HungerSatietyScale
|
|
||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealFoodItem
|
import com.example.data.model.MealFoodItem
|
||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
|
import com.example.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 com.example.util.ImageUtils
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.text.SimpleDateFormat
|
|
||||||
import java.util.Calendar
|
|
||||||
import java.util.Date
|
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.TimeZone
|
|
||||||
import kotlin.math.roundToInt
|
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun MealEntrySheet(
|
fun MealEntrySheet(
|
||||||
initialMeal: MealEntry? = null,
|
initialMeal: MealEntry? = null,
|
||||||
@@ -113,21 +73,22 @@ fun MealEntrySheet(
|
|||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val coroutineScope = rememberCoroutineScope()
|
val coroutineScope = rememberCoroutineScope()
|
||||||
|
|
||||||
var selectedType by remember {
|
var selectedType by rememberSaveable {
|
||||||
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
|
mutableStateOf(if (initialMeal != null) MealType.fromString(initialMeal.mealType) else defaultMealType)
|
||||||
}
|
}
|
||||||
var mealTimestamp by remember {
|
var mealTimestamp by rememberSaveable {
|
||||||
mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis())
|
mutableLongStateOf(initialMeal?.mealTimestamp ?: System.currentTimeMillis())
|
||||||
}
|
}
|
||||||
var hungerLevel by remember {
|
var hungerLevel by rememberSaveable {
|
||||||
mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10))
|
mutableIntStateOf((initialMeal?.hungerBefore ?: 5).coerceIn(1, 10))
|
||||||
}
|
}
|
||||||
var satietyLevel by remember {
|
var satietyLevel by rememberSaveable {
|
||||||
mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10))
|
mutableIntStateOf((initialMeal?.satietyAfter ?: 7).coerceIn(1, 10))
|
||||||
}
|
}
|
||||||
var globalNoteText by remember {
|
var globalNoteText by rememberSaveable {
|
||||||
mutableStateOf(initialMeal?.note ?: "")
|
mutableStateOf(initialMeal?.note ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
val foodItemsList = remember {
|
val foodItemsList = remember {
|
||||||
mutableStateListOf<MealFoodItem>().apply {
|
mutableStateListOf<MealFoodItem>().apply {
|
||||||
if (initialMeal != null) {
|
if (initialMeal != null) {
|
||||||
@@ -135,18 +96,18 @@ fun MealEntrySheet(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val photosBase64List = remember {
|
val photoUrisList = remember {
|
||||||
mutableStateListOf<String>().apply {
|
mutableStateListOf<String>().apply {
|
||||||
if (initialMeal != null) {
|
if (initialMeal != null) {
|
||||||
addAll(initialMeal.photosBase64)
|
addAll(initialMeal.displayPhotoUris)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Current food builder state
|
// Current food builder input state
|
||||||
var foodNameInput by remember { mutableStateOf("") }
|
var foodNameInput by rememberSaveable { mutableStateOf("") }
|
||||||
var foodWeightInput by remember { mutableStateOf("") }
|
var foodWeightInput by rememberSaveable { mutableStateOf("") }
|
||||||
var selectedFoodUnit by remember { mutableStateOf(FoodUnit.G) }
|
var selectedFoodUnit by rememberSaveable { mutableStateOf(FoodUnit.G) }
|
||||||
|
|
||||||
// Combine custom foods (user enriched) + built-in catalog
|
// Combine custom foods (user enriched) + built-in catalog
|
||||||
val mergedCatalog = remember(customFoods) {
|
val mergedCatalog = remember(customFoods) {
|
||||||
@@ -190,7 +151,6 @@ fun MealEntrySheet(
|
|||||||
weight = parsedWeight,
|
weight = parsedWeight,
|
||||||
unit = selectedFoodUnit
|
unit = selectedFoodUnit
|
||||||
)
|
)
|
||||||
// Replace if same food already added, or append
|
|
||||||
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
|
val existingIndex = foodItemsList.indexOfFirst { it.name.equals(cleanName, ignoreCase = true) }
|
||||||
if (existingIndex >= 0) {
|
if (existingIndex >= 0) {
|
||||||
foodItemsList[existingIndex] = newItem
|
foodItemsList[existingIndex] = newItem
|
||||||
@@ -207,8 +167,6 @@ fun MealEntrySheet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var isProcessingPhoto by remember { mutableStateOf(false) }
|
var isProcessingPhoto by remember { mutableStateOf(false) }
|
||||||
var showDatePicker by remember { mutableStateOf(false) }
|
|
||||||
var showTimePicker by remember { mutableStateOf(false) }
|
|
||||||
|
|
||||||
val photoPickerLauncher = rememberLauncherForActivityResult(
|
val photoPickerLauncher = rememberLauncherForActivityResult(
|
||||||
contract = ActivityResultContracts.PickVisualMedia()
|
contract = ActivityResultContracts.PickVisualMedia()
|
||||||
@@ -216,18 +174,15 @@ fun MealEntrySheet(
|
|||||||
if (uri != null) {
|
if (uri != null) {
|
||||||
isProcessingPhoto = true
|
isProcessingPhoto = true
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
val b64 = ImageUtils.uriToBase64(context, uri)
|
val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri)
|
||||||
if (b64 != null && photosBase64List.size < 4) {
|
if (savedUri != null && photoUrisList.size < 4) {
|
||||||
photosBase64List.add(b64)
|
photoUrisList.add(savedUri)
|
||||||
}
|
}
|
||||||
isProcessingPhoto = false
|
isProcessingPhoto = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val dateFormat = remember { SimpleDateFormat("EEE d MMM yyyy", Locale.FRENCH) }
|
|
||||||
val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.FRENCH) }
|
|
||||||
|
|
||||||
ModalBottomSheet(
|
ModalBottomSheet(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onDismiss,
|
||||||
sheetState = sheetState,
|
sheetState = sheetState,
|
||||||
@@ -273,518 +228,77 @@ fun MealEntrySheet(
|
|||||||
|
|
||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
// Meal Type Chips
|
// Subcomponent 1: Meal Type Chips
|
||||||
Text(
|
MealTypeSelector(
|
||||||
text = "Type de repas",
|
selectedType = selectedType,
|
||||||
style = MaterialTheme.typography.labelLarge,
|
onTypeSelected = { selectedType = it }
|
||||||
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 = { 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))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
// Date & Time Picker Section
|
// Subcomponent 2: Date & Time Picker
|
||||||
Row(
|
MealDateTimePicker(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
mealTimestamp = mealTimestamp,
|
||||||
horizontalArrangement = Arrangement.SpaceBetween,
|
onTimestampChanged = { mealTimestamp = it }
|
||||||
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
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(20.dp))
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
|
||||||
// Photos Section
|
// Subcomponent 3: Photos Section
|
||||||
Text(
|
MealPhotosSection(
|
||||||
text = "Photos de l'assiette (${photosBase64List.size}/4)",
|
photoUris = photoUrisList,
|
||||||
style = MaterialTheme.typography.labelLarge,
|
isProcessingPhoto = isProcessingPhoto,
|
||||||
color = MaterialTheme.colorScheme.primary
|
onAddPhotoClick = {
|
||||||
)
|
|
||||||
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(
|
photoPickerLauncher.launch(
|
||||||
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
|
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
|
||||||
)
|
)
|
||||||
|
},
|
||||||
|
onDeletePhotoClick = { photoUri ->
|
||||||
|
ImageUtils.deletePhotoFile(photoUri)
|
||||||
|
photoUrisList.remove(photoUri)
|
||||||
}
|
}
|
||||||
.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(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))
|
Spacer(modifier = Modifier.height(22.dp))
|
||||||
|
|
||||||
// 3. Enrichable Food List + Optional Weight Section
|
// Subcomponent 4: Hunger & Satiety Sliders (1 to 10)
|
||||||
Surface(
|
MealHungerSatietySection(
|
||||||
shape = RoundedCornerShape(18.dp),
|
hungerLevel = hungerLevel,
|
||||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
|
satietyLevel = satietyLevel,
|
||||||
modifier = Modifier.fillMaxWidth()
|
onHungerChange = { hungerLevel = it },
|
||||||
) {
|
onSatietyChange = { satietyLevel = it }
|
||||||
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))
|
Spacer(modifier = Modifier.height(22.dp))
|
||||||
|
|
||||||
// Auto-complete / Quick suggestions row
|
// Subcomponent 5: Food items builder & flow-row chips
|
||||||
if (matchingSuggestions.isNotEmpty()) {
|
FoodItemBuilderSection(
|
||||||
LazyRow(
|
foodItemsList = foodItemsList,
|
||||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
matchingSuggestions = matchingSuggestions,
|
||||||
modifier = Modifier.fillMaxWidth()
|
foodNameInput = foodNameInput,
|
||||||
) {
|
onFoodNameChange = { foodNameInput = it },
|
||||||
items(matchingSuggestions, key = { it.name }) { suggestion ->
|
foodWeightInput = foodWeightInput,
|
||||||
SuggestionChip(
|
onFoodWeightChange = { foodWeightInput = it },
|
||||||
onClick = {
|
selectedFoodUnit = selectedFoodUnit,
|
||||||
foodNameInput = suggestion.name
|
onFoodUnitSelected = { selectedFoodUnit = it },
|
||||||
selectedFoodUnit = suggestion.defaultUnit
|
isNewCustomFood = isNewCustomFood,
|
||||||
},
|
onAddFoodItem = { addCurrentFoodItem() },
|
||||||
label = {
|
onItemClickForEdit = { item ->
|
||||||
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
|
foodNameInput = item.name
|
||||||
foodWeightInput = item.weight?.let {
|
foodWeightInput = item.weight?.let {
|
||||||
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
|
if (it % 1.0 == 0.0) it.toInt().toString() else it.toString()
|
||||||
} ?: ""
|
} ?: ""
|
||||||
selectedFoodUnit = item.unit
|
selectedFoodUnit = item.unit
|
||||||
foodItemsList.remove(item)
|
foodItemsList.remove(item)
|
||||||
|
},
|
||||||
|
onRemoveFoodItem = { item ->
|
||||||
|
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)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(20.dp))
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
|
||||||
// 4. Global Note Field
|
// Global Note Field
|
||||||
Text(
|
Text(
|
||||||
text = "4. Note globale du repas (optionnel)",
|
text = "4. Note globale du repas (optionnel)",
|
||||||
style = MaterialTheme.typography.labelLarge,
|
style = MaterialTheme.typography.labelLarge,
|
||||||
@@ -827,7 +341,6 @@ fun MealEntrySheet(
|
|||||||
Spacer(modifier = Modifier.width(10.dp))
|
Spacer(modifier = Modifier.width(10.dp))
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
// Automatically commit any pending typed food name so user input is never lost
|
|
||||||
if (foodNameInput.trim().isNotEmpty()) {
|
if (foodNameInput.trim().isNotEmpty()) {
|
||||||
addCurrentFoodItem()
|
addCurrentFoodItem()
|
||||||
}
|
}
|
||||||
@@ -838,7 +351,7 @@ fun MealEntrySheet(
|
|||||||
satietyLevel.coerceIn(1, 10),
|
satietyLevel.coerceIn(1, 10),
|
||||||
globalNoteText,
|
globalNoteText,
|
||||||
foodItemsList.toList(),
|
foodItemsList.toList(),
|
||||||
photosBase64List.toList()
|
photoUrisList.toList()
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
@@ -860,189 +373,4 @@ fun MealEntrySheet(
|
|||||||
Spacer(modifier = Modifier.height(16.dp))
|
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.graphics.Color
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.example.ui.journal.GoogleSheetsUiState
|
import com.example.ui.journal.GoogleSheetsUiState
|
||||||
import java.text.SimpleDateFormat
|
import java.time.Instant
|
||||||
import java.util.Date
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
import androidx.compose.material3.ButtonDefaults
|
import androidx.compose.material3.ButtonDefaults
|
||||||
@@ -357,8 +358,8 @@ fun SettingsScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
is GoogleSheetsUiState.Success -> {
|
is GoogleSheetsUiState.Success -> {
|
||||||
val timeStr = SimpleDateFormat("dd/MM/yyyy à HH:mm", Locale.FRENCH)
|
val timeStr = DateTimeFormatter.ofPattern("dd/MM/yyyy 'à' HH:mm", Locale.FRENCH)
|
||||||
.format(Date(sheetsUiState.timestamp))
|
.format(Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault()))
|
||||||
Column(
|
Column(
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
@@ -884,16 +885,7 @@ fun SettingsScreen(
|
|||||||
Spacer(modifier = Modifier.height(16.dp))
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = onSignOut,
|
||||||
Firebase.auth.signOut()
|
|
||||||
CoroutineScope(Dispatchers.IO).launch {
|
|
||||||
try {
|
|
||||||
val credManager = CredentialManager.create(context)
|
|
||||||
credManager.clearCredentialState(ClearCredentialStateRequest())
|
|
||||||
} catch (_: Exception) {}
|
|
||||||
}
|
|
||||||
onSignOut()
|
|
||||||
},
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.testTag("signout_button"),
|
.testTag("signout_button"),
|
||||||
|
|||||||
@@ -10,21 +10,24 @@ import com.example.data.model.MealType
|
|||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.text.SimpleDateFormat
|
import java.time.Instant
|
||||||
import java.util.Date
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
object CsvExporter {
|
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 {
|
fun buildDefaultFileName(): String {
|
||||||
val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(Date())
|
val dateStr = fileDateFormatter.format(LocalDate.now())
|
||||||
return "satiea_repas_$dateStr.csv"
|
return "satiea_repas_$dateStr.csv"
|
||||||
}
|
}
|
||||||
|
|
||||||
fun generateCsvContent(meals: List<MealEntry>): String {
|
fun generateCsvContent(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): String {
|
||||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
|
||||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
|
||||||
|
|
||||||
val sb = StringBuilder()
|
val sb = StringBuilder()
|
||||||
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
|
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
|
||||||
sb.append('\uFEFF')
|
sb.append('\uFEFF')
|
||||||
@@ -32,15 +35,15 @@ object CsvExporter {
|
|||||||
|
|
||||||
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
||||||
for (meal in sortedMeals) {
|
for (meal in sortedMeals) {
|
||||||
val dateObj = Date(meal.mealTimestamp)
|
val zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
|
||||||
val dateStr = dateFormat.format(dateObj)
|
val dateStr = dateFormatter.format(zonedDateTime)
|
||||||
val timeStr = timeFormat.format(dateObj)
|
val timeStr = timeFormatter.format(zonedDateTime)
|
||||||
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
||||||
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
||||||
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
||||||
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
||||||
val cleanNote = escapeCsvField(meal.note)
|
val cleanNote = escapeCsvField(meal.note)
|
||||||
val photoCount = meal.photosBase64.size
|
val photoCount = meal.displayPhotoUris.size
|
||||||
|
|
||||||
sb.append(escapeCsvField(dateStr)).append(',')
|
sb.append(escapeCsvField(dateStr)).append(',')
|
||||||
sb.append(escapeCsvField(timeStr)).append(',')
|
sb.append(escapeCsvField(timeStr)).append(',')
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ import kotlinx.coroutines.withContext
|
|||||||
import java.io.BufferedReader
|
import java.io.BufferedReader
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalDate
|
||||||
import java.util.Calendar
|
import java.time.LocalDateTime
|
||||||
import java.util.Date
|
import java.time.LocalTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
@@ -25,17 +27,18 @@ data class CsvImportResult(
|
|||||||
|
|
||||||
object CsvImporter {
|
object CsvImporter {
|
||||||
|
|
||||||
private val supportedDateFormats = listOf(
|
private val supportedDatePatterns = listOf(
|
||||||
SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH),
|
"dd/MM/yyyy",
|
||||||
SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH),
|
"yyyy-MM-dd",
|
||||||
SimpleDateFormat("dd-MM-yyyy", Locale.FRENCH),
|
"dd-MM-yyyy",
|
||||||
SimpleDateFormat("d/M/yyyy", Locale.FRENCH)
|
"d/M/yyyy"
|
||||||
)
|
)
|
||||||
|
|
||||||
private val supportedTimeFormats = listOf(
|
private val supportedTimePatterns = listOf(
|
||||||
SimpleDateFormat("HH:mm", Locale.FRENCH),
|
"HH:mm",
|
||||||
SimpleDateFormat("H:mm", Locale.FRENCH),
|
"H:mm",
|
||||||
SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
|
"HH:mm:ss",
|
||||||
|
"H:mm:ss"
|
||||||
)
|
)
|
||||||
|
|
||||||
suspend fun importFromUri(
|
suspend fun importFromUri(
|
||||||
@@ -157,36 +160,32 @@ object CsvImporter {
|
|||||||
return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else ""
|
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
|
if (dateStr.isBlank()) return null
|
||||||
|
|
||||||
var parsedDate: Date? = null
|
var parsedLocalDate: LocalDate? = null
|
||||||
for (df in supportedDateFormats) {
|
for (pattern in supportedDatePatterns) {
|
||||||
try {
|
try {
|
||||||
parsedDate = df.parse(dateStr.trim())
|
parsedLocalDate = LocalDate.parse(dateStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
|
||||||
if (parsedDate != null) break
|
if (parsedLocalDate != null) break
|
||||||
} catch (_: Exception) {}
|
} catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
if (parsedDate == null) return null
|
if (parsedLocalDate == null) return null
|
||||||
|
|
||||||
val cal = Calendar.getInstance().apply { time = parsedDate }
|
|
||||||
|
|
||||||
|
var parsedLocalTime = LocalTime.NOON
|
||||||
if (timeStr.isNotBlank()) {
|
if (timeStr.isNotBlank()) {
|
||||||
for (tf in supportedTimeFormats) {
|
for (pattern in supportedTimePatterns) {
|
||||||
try {
|
try {
|
||||||
val parsedTime = tf.parse(timeStr.trim())
|
parsedLocalTime = LocalTime.parse(timeStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
|
||||||
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
|
break
|
||||||
}
|
|
||||||
} catch (_: Exception) {}
|
} catch (_: Exception) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return cal.timeInMillis
|
|
||||||
|
return LocalDateTime.of(parsedLocalDate, parsedLocalTime)
|
||||||
|
.atZone(zoneId)
|
||||||
|
.toInstant()
|
||||||
|
.toEpochMilli()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseMealType(raw: String): MealType {
|
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.HungerSatietyScale
|
||||||
import com.example.data.model.MealEntry
|
import com.example.data.model.MealEntry
|
||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
import java.text.SimpleDateFormat
|
import java.time.Instant
|
||||||
import java.util.Date
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
object GoogleSheetsDataFormatter {
|
object GoogleSheetsDataFormatter {
|
||||||
@@ -22,10 +23,10 @@ object GoogleSheetsDataFormatter {
|
|||||||
"Photos jointes"
|
"Photos jointes"
|
||||||
)
|
)
|
||||||
|
|
||||||
fun formatMealsToRows(meals: List<MealEntry>): List<List<Any>> {
|
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
|
||||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
|
||||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
|
||||||
|
|
||||||
|
fun formatMealsToRows(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): List<List<Any>> {
|
||||||
val rows = mutableListOf<List<Any>>()
|
val rows = mutableListOf<List<Any>>()
|
||||||
// Header row
|
// Header row
|
||||||
rows.add(HEADERS)
|
rows.add(HEADERS)
|
||||||
@@ -34,15 +35,15 @@ object GoogleSheetsDataFormatter {
|
|||||||
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
||||||
|
|
||||||
for (meal in sortedMeals) {
|
for (meal in sortedMeals) {
|
||||||
val dateObj = Date(meal.mealTimestamp)
|
val zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
|
||||||
val dateStr = dateFormat.format(dateObj)
|
val dateStr = dateFormatter.format(zonedDateTime)
|
||||||
val timeStr = timeFormat.format(dateObj)
|
val timeStr = timeFormatter.format(zonedDateTime)
|
||||||
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
||||||
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
||||||
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
||||||
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
||||||
val cleanNote = meal.note.replace("\r\n", " ").replace("\n", " ").trim()
|
val cleanNote = meal.note.replace("\r\n", " ").replace("\n", " ").trim()
|
||||||
val photosCount = meal.photosBase64.size
|
val photosCount = meal.displayPhotoUris.size
|
||||||
|
|
||||||
rows.add(
|
rows.add(
|
||||||
listOf(
|
listOf(
|
||||||
|
|||||||
@@ -5,72 +5,120 @@ import android.graphics.Bitmap
|
|||||||
import android.graphics.BitmapFactory
|
import android.graphics.BitmapFactory
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.util.Base64
|
import android.util.Base64
|
||||||
|
import android.util.Log
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
object ImageUtils {
|
object ImageUtils {
|
||||||
|
|
||||||
suspend fun uriToBase64(context: Context, uri: Uri, maxWidth: Int = 480, maxHeight: Int = 480): String? =
|
private const val TAG = "ImageUtils"
|
||||||
withContext(Dispatchers.IO) {
|
private const val PHOTOS_DIR_NAME = "meal_photos"
|
||||||
try {
|
private const val MAX_DIMENSION = 960
|
||||||
var inputStream: InputStream? = context.contentResolver.openInputStream(uri) ?: return@withContext null
|
private const val JPEG_QUALITY = 80
|
||||||
|
|
||||||
// Decode bounds first
|
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 {
|
val options = BitmapFactory.Options().apply {
|
||||||
inJustDecodeBounds = true
|
inJustDecodeBounds = true
|
||||||
}
|
}
|
||||||
BitmapFactory.decodeStream(inputStream, null, options)
|
BitmapFactory.decodeStream(inputStream, null, options)
|
||||||
inputStream?.close()
|
inputStream?.close()
|
||||||
|
|
||||||
// Calculate inSampleSize
|
// 2. Calculate inSampleSize for memory safety
|
||||||
var inSampleSize = 1
|
var inSampleSize = 1
|
||||||
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
|
if (options.outHeight > MAX_DIMENSION || options.outWidth > MAX_DIMENSION) {
|
||||||
val halfHeight = options.outHeight / 2
|
val halfHeight = options.outHeight / 2
|
||||||
val halfWidth = options.outWidth / 2
|
val halfWidth = options.outWidth / 2
|
||||||
while (halfHeight / inSampleSize >= maxHeight && halfWidth / inSampleSize >= maxWidth) {
|
while (halfHeight / inSampleSize >= MAX_DIMENSION && halfWidth / inSampleSize >= MAX_DIMENSION) {
|
||||||
inSampleSize *= 2
|
inSampleSize *= 2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode actual bitmap
|
// 3. Decode actual bitmap
|
||||||
val decodeOptions = BitmapFactory.Options().apply {
|
val decodeOptions = BitmapFactory.Options().apply {
|
||||||
this.inSampleSize = inSampleSize
|
this.inSampleSize = inSampleSize
|
||||||
}
|
}
|
||||||
inputStream = context.contentResolver.openInputStream(uri)
|
inputStream = context.contentResolver.openInputStream(sourceUri)
|
||||||
val originalBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
|
val decodedBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
|
||||||
inputStream?.close()
|
inputStream?.close()
|
||||||
|
|
||||||
if (originalBitmap == null) return@withContext null
|
if (decodedBitmap == null) return@withContext null
|
||||||
|
|
||||||
// Scale to exact target bounds
|
// 4. Scale to max dimension while preserving aspect ratio
|
||||||
val scaledBitmap = if (originalBitmap.width > maxWidth || originalBitmap.height > maxHeight) {
|
val scaledBitmap = if (decodedBitmap.width > MAX_DIMENSION || decodedBitmap.height > MAX_DIMENSION) {
|
||||||
val ratio = minOf(
|
val ratio = minOf(
|
||||||
maxWidth.toFloat() / originalBitmap.width,
|
MAX_DIMENSION.toFloat() / decodedBitmap.width,
|
||||||
maxHeight.toFloat() / originalBitmap.height
|
MAX_DIMENSION.toFloat() / decodedBitmap.height
|
||||||
)
|
)
|
||||||
val targetW = (originalBitmap.width * ratio).toInt().coerceAtLeast(1)
|
val targetW = (decodedBitmap.width * ratio).toInt().coerceAtLeast(1)
|
||||||
val targetH = (originalBitmap.height * ratio).toInt().coerceAtLeast(1)
|
val targetH = (decodedBitmap.height * ratio).toInt().coerceAtLeast(1)
|
||||||
Bitmap.createScaledBitmap(originalBitmap, targetW, targetH, true)
|
Bitmap.createScaledBitmap(decodedBitmap, targetW, targetH, true).also {
|
||||||
|
if (it != decodedBitmap) decodedBitmap.recycle()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
originalBitmap
|
decodedBitmap
|
||||||
}
|
}
|
||||||
|
|
||||||
val outputStream = ByteArrayOutputStream()
|
// 5. Write directly to private JPEG file
|
||||||
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream)
|
val targetDir = getPhotosDirectory(context)
|
||||||
val bytes = outputStream.toByteArray()
|
val uniqueFileName = "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg"
|
||||||
Base64.encodeToString(bytes, Base64.NO_WRAP)
|
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) {
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Error saving image to private storage: ${e.message}", e)
|
||||||
null
|
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? {
|
fun base64ToBitmap(base64Str: String): Bitmap? {
|
||||||
return try {
|
return try {
|
||||||
val bytes = Base64.decode(base64Str, Base64.DEFAULT)
|
val bytes = Base64.decode(base64Str, Base64.DEFAULT)
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||||
} catch (e: Exception) {
|
} catch (_: Exception) {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ import com.example.data.model.MealFoodItem
|
|||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
import com.example.util.CsvImporter
|
import com.example.util.CsvImporter
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertTrue
|
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
import java.text.SimpleDateFormat
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
class CsvImporterTest {
|
class CsvImporterTest {
|
||||||
@@ -57,8 +58,11 @@ class CsvImporterTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testDeduplicationIgnoresExistingMeal() {
|
fun testDeduplicationIgnoresExistingMeal() {
|
||||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.FRENCH)
|
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm", Locale.FRENCH)
|
||||||
val timestamp = dateFormat.parse("08/11/2026 12:30")!!.time
|
val timestamp = LocalDateTime.parse("08/11/2026 12:30", formatter)
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toInstant()
|
||||||
|
.toEpochMilli()
|
||||||
|
|
||||||
val existingMeal = MealEntry(
|
val existingMeal = MealEntry(
|
||||||
id = "existing_1",
|
id = "existing_1",
|
||||||
|
|||||||
@@ -8,32 +8,35 @@ import com.example.util.GoogleSheetsDataFormatter
|
|||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertTrue
|
import org.junit.Assert.assertTrue
|
||||||
import org.junit.Test
|
import org.junit.Test
|
||||||
import java.util.Calendar
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
|
||||||
class GoogleSheetsDataFormatterTest {
|
class GoogleSheetsDataFormatterTest {
|
||||||
|
|
||||||
|
private val testZoneId = ZoneId.of("Europe/Paris")
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `formatMealsToRows with empty list returns only header row`() {
|
fun `formatMealsToRows with empty list returns only header row`() {
|
||||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(emptyList())
|
val rows = GoogleSheetsDataFormatter.formatMealsToRows(emptyList(), testZoneId)
|
||||||
assertEquals(1, rows.size)
|
assertEquals(1, rows.size)
|
||||||
assertEquals(GoogleSheetsDataFormatter.HEADERS, rows[0])
|
assertEquals(GoogleSheetsDataFormatter.HEADERS, rows[0])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `formatMealsToRows formats meal fields accurately and sorts chronologically descending`() {
|
fun `formatMealsToRows formats meal fields accurately and sorts chronologically descending`() {
|
||||||
val cal1 = Calendar.getInstance().apply {
|
val time1 = LocalDateTime.of(2026, 3, 15, 12, 30, 0)
|
||||||
set(2026, Calendar.MARCH, 15, 12, 30, 0)
|
.atZone(testZoneId)
|
||||||
set(Calendar.MILLISECOND, 0)
|
.toInstant()
|
||||||
}
|
.toEpochMilli()
|
||||||
val cal2 = Calendar.getInstance().apply {
|
val time2 = LocalDateTime.of(2026, 3, 15, 20, 0, 0)
|
||||||
set(2026, Calendar.MARCH, 15, 20, 0, 0)
|
.atZone(testZoneId)
|
||||||
set(Calendar.MILLISECOND, 0)
|
.toInstant()
|
||||||
}
|
.toEpochMilli()
|
||||||
|
|
||||||
val meal1 = MealEntry(
|
val meal1 = MealEntry(
|
||||||
id = "meal-1",
|
id = "meal-1",
|
||||||
mealType = MealType.LUNCH.name,
|
mealType = MealType.LUNCH.name,
|
||||||
mealTimestamp = cal1.timeInMillis,
|
mealTimestamp = time1,
|
||||||
hungerBefore = 3,
|
hungerBefore = 3,
|
||||||
satietyAfter = 7,
|
satietyAfter = 7,
|
||||||
note = "Repas calme et savoureux",
|
note = "Repas calme et savoureux",
|
||||||
@@ -41,24 +44,24 @@ class GoogleSheetsDataFormatterTest {
|
|||||||
MealFoodItem("Riz complet", 150.0, FoodUnit.G).serialize(),
|
MealFoodItem("Riz complet", 150.0, FoodUnit.G).serialize(),
|
||||||
MealFoodItem("Saumon", 120.0, FoodUnit.G).serialize()
|
MealFoodItem("Saumon", 120.0, FoodUnit.G).serialize()
|
||||||
),
|
),
|
||||||
photosBase64 = listOf("photo1")
|
photoUris = listOf("file:///photo1.jpg")
|
||||||
)
|
)
|
||||||
|
|
||||||
val meal2 = MealEntry(
|
val meal2 = MealEntry(
|
||||||
id = "meal-2",
|
id = "meal-2",
|
||||||
mealType = MealType.DINNER.name,
|
mealType = MealType.DINNER.name,
|
||||||
mealTimestamp = cal2.timeInMillis,
|
mealTimestamp = time2,
|
||||||
hungerBefore = 4,
|
hungerBefore = 4,
|
||||||
satietyAfter = 8,
|
satietyAfter = 8,
|
||||||
note = "Dîner léger en famille",
|
note = "Dîner léger en famille",
|
||||||
foodItemsSerialized = listOf(
|
foodItemsSerialized = listOf(
|
||||||
MealFoodItem("Soupe de légumes", 250.0, FoodUnit.ML).serialize()
|
MealFoodItem("Soupe de légumes", 250.0, FoodUnit.ML).serialize()
|
||||||
),
|
),
|
||||||
photosBase64 = emptyList()
|
photoUris = emptyList()
|
||||||
)
|
)
|
||||||
|
|
||||||
// Pass in reverse order to test sorting
|
// Pass in reverse order to test sorting
|
||||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2))
|
val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2), testZoneId)
|
||||||
|
|
||||||
// 1 header + 2 data rows
|
// 1 header + 2 data rows
|
||||||
assertEquals(3, rows.size)
|
assertEquals(3, rows.size)
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import com.example.data.model.MealEntry
|
|||||||
import com.example.data.model.MealFoodItem
|
import com.example.data.model.MealFoodItem
|
||||||
import com.example.data.model.MealType
|
import com.example.data.model.MealType
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.test.runTest
|
||||||
import org.junit.After
|
import org.junit.After
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
import org.junit.Assert.assertNotNull
|
import org.junit.Assert.assertNotNull
|
||||||
@@ -45,7 +45,7 @@ class LocalDatabaseTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testInsertAndObserveMeal() = runBlocking {
|
fun testInsertAndObserveMeal() = runTest {
|
||||||
val meal = MealEntry(
|
val meal = MealEntry(
|
||||||
id = "local_test_1",
|
id = "local_test_1",
|
||||||
mealType = MealType.LUNCH.name,
|
mealType = MealType.LUNCH.name,
|
||||||
@@ -55,9 +55,9 @@ class LocalDatabaseTest {
|
|||||||
note = "Repas calme",
|
note = "Repas calme",
|
||||||
foodItemsSerialized = listOf(
|
foodItemsSerialized = listOf(
|
||||||
MealFoodItem("Riz", 150.0, FoodUnit.G).serialize()
|
MealFoodItem("Riz", 150.0, FoodUnit.G).serialize()
|
||||||
|
),
|
||||||
|
photoUris = listOf("file:///test_photo.jpg")
|
||||||
)
|
)
|
||||||
)
|
|
||||||
|
|
||||||
val entity = LocalMealEntity.fromMealEntry(meal)
|
val entity = LocalMealEntity.fromMealEntry(meal)
|
||||||
dao.insertMeal(entity)
|
dao.insertMeal(entity)
|
||||||
|
|
||||||
@@ -71,10 +71,11 @@ class LocalDatabaseTest {
|
|||||||
assertEquals("Repas calme", readMeal.note)
|
assertEquals("Repas calme", readMeal.note)
|
||||||
assertEquals(1, readMeal.parsedFoodItems().size)
|
assertEquals(1, readMeal.parsedFoodItems().size)
|
||||||
assertEquals("Riz", readMeal.parsedFoodItems()[0].name)
|
assertEquals("Riz", readMeal.parsedFoodItems()[0].name)
|
||||||
|
assertEquals(1, readMeal.displayPhotoUris.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testDeleteMeal() = runBlocking {
|
fun testDeleteMeal() = runTest {
|
||||||
val entity = LocalMealEntity(
|
val entity = LocalMealEntity(
|
||||||
id = "to_delete",
|
id = "to_delete",
|
||||||
mealType = MealType.DINNER.name,
|
mealType = MealType.DINNER.name,
|
||||||
@@ -90,7 +91,7 @@ class LocalDatabaseTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testInsertAndObserveCustomFoods() = runBlocking {
|
fun testInsertAndObserveCustomFoods() = runTest {
|
||||||
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G)
|
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G)
|
||||||
val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML)
|
val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package com.example
|
||||||
|
|
||||||
|
import com.example.data.model.MealEntry
|
||||||
|
import com.example.data.model.MealType
|
||||||
|
import com.example.domain.WeeklyStatsCalculator
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
import java.time.LocalDate
|
||||||
|
import java.time.ZoneId
|
||||||
|
|
||||||
|
class MealWeeklyStatsTest {
|
||||||
|
|
||||||
|
private val testZoneId = ZoneId.of("Europe/Paris")
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `computeWeeklyStats returns 7 daily slots and correct distribution`() {
|
||||||
|
val today = LocalDate.now(testZoneId)
|
||||||
|
val todayMillis = today.atTime(12, 30).atZone(testZoneId).toInstant().toEpochMilli()
|
||||||
|
val twoDaysAgoMillis = today.minusDays(2).atTime(20, 0).atZone(testZoneId).toInstant().toEpochMilli()
|
||||||
|
|
||||||
|
val meals = listOf(
|
||||||
|
MealEntry(
|
||||||
|
id = "m1",
|
||||||
|
mealType = MealType.LUNCH.name,
|
||||||
|
mealTimestamp = todayMillis,
|
||||||
|
hungerBefore = 5,
|
||||||
|
satietyAfter = 7
|
||||||
|
),
|
||||||
|
MealEntry(
|
||||||
|
id = "m2",
|
||||||
|
mealType = MealType.DINNER.name,
|
||||||
|
mealTimestamp = twoDaysAgoMillis,
|
||||||
|
hungerBefore = 3,
|
||||||
|
satietyAfter = 6
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val stats = WeeklyStatsCalculator.computeWeeklyStats(meals, testZoneId)
|
||||||
|
|
||||||
|
assertEquals(7, stats.dailyStats.size)
|
||||||
|
assertEquals(2, stats.totalMealsLast7Days)
|
||||||
|
assertEquals(6.5f, stats.averageSatiety, 0.01f)
|
||||||
|
assertEquals(4.0f, stats.averageHunger, 0.01f)
|
||||||
|
assertEquals(100, stats.optimalZonePercentage) // Both 7 and 6 are in 6..8
|
||||||
|
assertEquals(1, stats.mealTypeDistribution[MealType.LUNCH])
|
||||||
|
assertEquals(1, stats.mealTypeDistribution[MealType.DINNER])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ import org.robolectric.annotation.Config
|
|||||||
import org.robolectric.annotation.LooperMode
|
import org.robolectric.annotation.LooperMode
|
||||||
|
|
||||||
@RunWith(RobolectricTestRunner::class)
|
@RunWith(RobolectricTestRunner::class)
|
||||||
@Config(manifest = Config.NONE)
|
@Config(manifest = Config.NONE, sdk = [34])
|
||||||
@LooperMode(LooperMode.Mode.INSTRUMENTATION_TEST)
|
@LooperMode(LooperMode.Mode.INSTRUMENTATION_TEST)
|
||||||
abstract class FirestoreEmulatorTestBase {
|
abstract class FirestoreEmulatorTestBase {
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ abstract class FirestoreEmulatorTestBase {
|
|||||||
databaseId = if (resId != 0) context.getString(resId) else "demo-database"
|
databaseId = if (resId != 0) context.getString(resId) else "demo-database"
|
||||||
|
|
||||||
val app = if (FirebaseApp.getApps(context).isEmpty()) {
|
val app = if (FirebaseApp.getApps(context).isEmpty()) {
|
||||||
val newApp = FirebaseApp.initializeApp(
|
FirebaseApp.initializeApp(
|
||||||
context,
|
context,
|
||||||
FirebaseOptions.Builder()
|
FirebaseOptions.Builder()
|
||||||
.setApplicationId("com.example.app")
|
.setApplicationId("com.example.app")
|
||||||
@@ -45,21 +45,22 @@ abstract class FirestoreEmulatorTestBase {
|
|||||||
.setApiKey("fake-api-key-for-emulator")
|
.setApiKey("fake-api-key-for-emulator")
|
||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
val newFirestore = FirebaseFirestore.getInstance(newApp, databaseId)
|
|
||||||
newFirestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT)
|
|
||||||
newFirestore.firestoreSettings = FirebaseFirestoreSettings.Builder()
|
|
||||||
.setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
|
|
||||||
.build()
|
|
||||||
|
|
||||||
val newAuth = FirebaseAuth.getInstance(newApp)
|
|
||||||
newAuth.useEmulator(EMULATOR_HOST, AUTH_PORT)
|
|
||||||
newApp
|
|
||||||
} else {
|
} else {
|
||||||
FirebaseApp.getInstance()
|
FirebaseApp.getInstance()
|
||||||
}
|
}
|
||||||
|
|
||||||
firestore = FirebaseFirestore.getInstance(app, databaseId)
|
firestore = FirebaseFirestore.getInstance(app, databaseId)
|
||||||
|
try {
|
||||||
|
firestore.useEmulator(EMULATOR_HOST, FIRESTORE_PORT)
|
||||||
|
firestore.firestoreSettings = FirebaseFirestoreSettings.Builder()
|
||||||
|
.setLocalCacheSettings(MemoryCacheSettings.newBuilder().build())
|
||||||
|
.build()
|
||||||
|
} catch (_: IllegalStateException) {}
|
||||||
|
|
||||||
auth = FirebaseAuth.getInstance(app)
|
auth = FirebaseAuth.getInstance(app)
|
||||||
|
try {
|
||||||
|
auth.useEmulator(EMULATOR_HOST, AUTH_PORT)
|
||||||
|
} catch (_: IllegalStateException) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
@After
|
||||||
|
|||||||
+3
-2
@@ -36,6 +36,7 @@ service cloud.firestore {
|
|||||||
data.satietyAfter is int && data.satietyAfter >= 1 && data.satietyAfter <= 10 &&
|
data.satietyAfter is int && data.satietyAfter >= 1 && data.satietyAfter <= 10 &&
|
||||||
(!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 1000)) &&
|
(!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 1000)) &&
|
||||||
(!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || data.foodItemsSerialized[0] is string))) &&
|
(!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || data.foodItemsSerialized[0] is string))) &&
|
||||||
|
(!('photoUris' in data) || data.photoUris == null || (data.photoUris is list && data.photoUris.size() <= 6 && (data.photoUris.size() == 0 || data.photoUris[0] is string))) &&
|
||||||
(!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 6 && (data.photosBase64.size() == 0 || data.photosBase64[0] is string))) &&
|
(!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 6 && (data.photosBase64.size() == 0 || data.photosBase64[0] is string))) &&
|
||||||
(!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time));
|
(!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time));
|
||||||
}
|
}
|
||||||
@@ -57,7 +58,7 @@ service cloud.firestore {
|
|||||||
allow create: if isOwner(userId) &&
|
allow create: if isOwner(userId) &&
|
||||||
isValidId(mealId) &&
|
isValidId(mealId) &&
|
||||||
incoming().keys().hasAll(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'createdAt']) &&
|
incoming().keys().hasAll(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'createdAt']) &&
|
||||||
incoming().keys().hasOnly(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'createdAt', 'updatedAt']) &&
|
incoming().keys().hasOnly(['userId', 'mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photoUris', 'photosBase64', 'createdAt', 'updatedAt']) &&
|
||||||
incoming().createdAt is timestamp &&
|
incoming().createdAt is timestamp &&
|
||||||
incoming().createdAt <= request.time &&
|
incoming().createdAt <= request.time &&
|
||||||
isValidMealEntry(incoming());
|
isValidMealEntry(incoming());
|
||||||
@@ -67,7 +68,7 @@ service cloud.firestore {
|
|||||||
incoming().userId == existing().userId &&
|
incoming().userId == existing().userId &&
|
||||||
incoming().createdAt == existing().createdAt &&
|
incoming().createdAt == existing().createdAt &&
|
||||||
isValidMealEntry(incoming()) &&
|
isValidMealEntry(incoming()) &&
|
||||||
incoming().diff(existing()).affectedKeys().hasOnly(['mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photosBase64', 'updatedAt']);
|
incoming().diff(existing()).affectedKeys().hasOnly(['mealType', 'mealTimestamp', 'hungerBefore', 'satietyAfter', 'note', 'foodItemsSerialized', 'photoUris', 'photosBase64', 'updatedAt']);
|
||||||
|
|
||||||
allow delete: if isOwner(userId) && isValidId(mealId);
|
allow delete: if isOwner(userId) && isValidId(mealId);
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,248 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+93
@@ -0,0 +1,93 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
Reference in new issue
Block a user