mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
feat: implement meal notification system
Add necessary permissions, services, and receivers to support scheduled meal notifications and boot completion handling. Also includes dependency updates and minor test fixes.
This commit is contained in:
1 parent
f13d46f778
commit
fe69d7621a
31 files changed
+2972
-350
No files matched your search
@@ -4,6 +4,9 @@
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
|
||||
|
||||
<application
|
||||
android:allowBackup="true"
|
||||
@@ -30,6 +33,15 @@
|
||||
android:name=".receiver.MealReminderReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver
|
||||
android:name=".receiver.BootReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.example
|
||||
|
||||
import android.Manifest
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
@@ -20,8 +22,12 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.BarChart
|
||||
import androidx.compose.material.icons.filled.Restaurant
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.NavigationBar
|
||||
import androidx.compose.material3.NavigationBarItem
|
||||
import androidx.compose.material3.NavigationBarItemDefaults
|
||||
@@ -29,6 +35,7 @@ import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -40,9 +47,11 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.auth.AuthScreen
|
||||
import com.example.ui.journal.JournalScreen
|
||||
@@ -53,6 +62,11 @@ import com.example.ui.settings.SettingsScreen
|
||||
import com.example.ui.stats.WeeklyStatsScreen
|
||||
import com.example.ui.theme.SatieaTheme
|
||||
import com.example.util.CsvExporter
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import com.example.ui.journal.GoogleSheetsUiState
|
||||
import com.example.util.GoogleSheetsAuthHelper
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import com.google.firebase.auth.auth
|
||||
@@ -72,6 +86,9 @@ class MainActivity : ComponentActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
enableEdgeToEdge()
|
||||
|
||||
MealNotificationManager.createNotificationChannel(this)
|
||||
MealNotificationManager.scheduleAllActiveReminders(this)
|
||||
|
||||
val logMealRequested = intent?.action == MealNotificationManager.ACTION_LOG_MEAL
|
||||
val initialMealType = intent?.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
|
||||
MealType.fromString(it)
|
||||
@@ -91,6 +108,7 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AppRoot(
|
||||
viewModel: MealViewModel,
|
||||
@@ -98,6 +116,7 @@ fun AppRoot(
|
||||
initialDefaultMealType: MealType
|
||||
) {
|
||||
var currentUser by remember { mutableStateOf(Firebase.auth.currentUser) }
|
||||
var showAuthSheet by remember { mutableStateOf(false) }
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val context = LocalContext.current
|
||||
@@ -112,21 +131,81 @@ fun AppRoot(
|
||||
}
|
||||
}
|
||||
|
||||
if (currentUser == null) {
|
||||
AuthScreen(
|
||||
onAuthSuccess = {
|
||||
currentUser = Firebase.auth.currentUser
|
||||
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
|
||||
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
|
||||
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
||||
var defaultMealType by remember { mutableStateOf(initialDefaultMealType) }
|
||||
|
||||
val prefs = remember { ReminderPreferencesManager.getInstance(context) }
|
||||
var showPermissionRationaleDialog by remember {
|
||||
mutableStateOf(
|
||||
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
!NotificationManagerCompat.from(context).areNotificationsEnabled() &&
|
||||
!prefs.hasPromptedNotificationPermission()
|
||||
)
|
||||
}
|
||||
|
||||
val requestNotificationPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { isGranted ->
|
||||
if (isGranted) {
|
||||
MealNotificationManager.scheduleAllActiveReminders(context)
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Rappels de repas activés avec succès 🔔")
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
|
||||
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) }
|
||||
var editingMeal by remember { mutableStateOf<MealEntry?>(null) }
|
||||
var defaultMealType by remember { mutableStateOf(initialDefaultMealType) }
|
||||
}
|
||||
|
||||
if (showPermissionRationaleDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = {
|
||||
prefs.setPromptedNotificationPermission(true)
|
||||
showPermissionRationaleDialog = false
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
text = "Rappels bienveillants de repas 🔔",
|
||||
style = MaterialTheme.typography.titleLarge
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Text(
|
||||
text = "Pour vous aider à être à l'écoute de votre corps, Satiéa peut vous envoyer un rappel discret au moment de manger afin d'évaluer votre faim et votre satiété.",
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
prefs.setPromptedNotificationPermission(true)
|
||||
showPermissionRationaleDialog = false
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
requestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text("Activer les rappels")
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
prefs.setPromptedNotificationPermission(true)
|
||||
showPermissionRationaleDialog = false
|
||||
}
|
||||
) {
|
||||
Text("Plus tard")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
val mealsState by viewModel.mealsState.collectAsStateWithLifecycle()
|
||||
val customFoods by viewModel.customFoods.collectAsStateWithLifecycle()
|
||||
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
|
||||
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
|
||||
val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
|
||||
val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle()
|
||||
val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList()
|
||||
|
||||
val createCsvDocumentLauncher = rememberLauncherForActivityResult(
|
||||
@@ -150,6 +229,39 @@ fun AppRoot(
|
||||
}
|
||||
}
|
||||
|
||||
val importCsvLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocument()
|
||||
) { sourceUri: Uri? ->
|
||||
if (sourceUri != null) {
|
||||
viewModel.importCsvFromUri(
|
||||
sourceUri = sourceUri,
|
||||
onSuccess = { result ->
|
||||
coroutineScope.launch {
|
||||
val count = result.importedMeals.size
|
||||
val skipped = result.skippedDuplicatesCount
|
||||
val newFoods = result.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(" ✨")
|
||||
}
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val triggerImportCsv = {
|
||||
importCsvLauncher.launch(arrayOf("text/*", "text/csv", "application/csv", "*/*"))
|
||||
}
|
||||
|
||||
val triggerSaveCsv = {
|
||||
if (currentMealsList.isEmpty()) {
|
||||
coroutineScope.launch {
|
||||
@@ -181,6 +293,66 @@ fun AppRoot(
|
||||
}
|
||||
}
|
||||
|
||||
val sheetsAuthConsentLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
if (result.resultCode == Activity.RESULT_OK) {
|
||||
viewModel.syncToGoogleSheets(
|
||||
onSuccess = { _, count ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Synchronisé avec succès vers Google Sheets ($count repas) 📊")
|
||||
}
|
||||
},
|
||||
onError = { err, _ ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
} else {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Autorisation Google Sheets annulée")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val triggerGoogleSheetsSync = {
|
||||
viewModel.syncToGoogleSheets(
|
||||
onSuccess = { _, count ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Synchronisé avec succès vers Google Sheets ($count repas) 📊")
|
||||
}
|
||||
},
|
||||
onError = { message, intent ->
|
||||
if (intent != null) {
|
||||
sheetsAuthConsentLauncher.launch(intent)
|
||||
} else {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
if (email.isNullOrBlank()) {
|
||||
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
|
||||
sheetsAuthConsentLauncher.launch(client.signInIntent)
|
||||
} else {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
val openGoogleSheets = { url: String ->
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
context.startActivity(intent)
|
||||
} catch (_: Exception) {
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Impossible d'ouvrir le lien : $url")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BackHandler(enabled = currentTab != MainTab.JOURNAL) {
|
||||
currentTab = MainTab.JOURNAL
|
||||
}
|
||||
@@ -269,7 +441,11 @@ fun AppRoot(
|
||||
},
|
||||
onExportCsvClick = {
|
||||
triggerSaveCsv()
|
||||
}
|
||||
},
|
||||
onSyncSheetsClick = {
|
||||
triggerGoogleSheetsSync()
|
||||
},
|
||||
spreadsheetUrl = spreadsheetUrl
|
||||
)
|
||||
}
|
||||
|
||||
@@ -281,7 +457,8 @@ fun AppRoot(
|
||||
weeklyStats = weeklyStats,
|
||||
totalMealsCount = currentMealsList.size,
|
||||
onSaveCsvClick = { triggerSaveCsv() },
|
||||
onShareCsvClick = { triggerShareCsv() }
|
||||
onShareCsvClick = { triggerShareCsv() },
|
||||
onImportCsvClick = { triggerImportCsv() }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -289,6 +466,9 @@ fun AppRoot(
|
||||
SettingsScreen(
|
||||
currentThemeMode = themeMode,
|
||||
totalMealsCount = currentMealsList.size,
|
||||
sheetsUiState = sheetsUiState,
|
||||
isAutoSyncSheets = isAutoSyncSheets,
|
||||
spreadsheetUrl = spreadsheetUrl,
|
||||
onThemeModeChange = { newMode ->
|
||||
viewModel.setThemeMode(newMode)
|
||||
},
|
||||
@@ -303,8 +483,17 @@ fun AppRoot(
|
||||
},
|
||||
onSaveCsvClick = { triggerSaveCsv() },
|
||||
onShareCsvClick = { triggerShareCsv() },
|
||||
onImportCsvClick = { triggerImportCsv() },
|
||||
onSyncSheetsClick = { triggerGoogleSheetsSync() },
|
||||
onAutoSyncSheetsChange = { enabled -> viewModel.setAutoSyncSheets(enabled) },
|
||||
onOpenSheetsClick = { url -> openGoogleSheets(url) },
|
||||
onSignInClick = { showAuthSheet = true },
|
||||
onSignOut = {
|
||||
currentUser = null
|
||||
viewModel.disconnectGoogleSheets()
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Mode local actif • Déconnecté")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -372,7 +561,31 @@ fun AppRoot(
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (showAuthSheet) {
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { showAuthSheet = false }
|
||||
) {
|
||||
AuthScreen(
|
||||
onAuthSuccess = {
|
||||
currentUser = Firebase.auth.currentUser
|
||||
showAuthSheet = false
|
||||
viewModel.syncCloudToLocal(
|
||||
onSuccess = { count ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️")
|
||||
}
|
||||
},
|
||||
onError = { err ->
|
||||
coroutineScope.launch {
|
||||
snackbarHostState.showSnackbar(err)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.example.data.local
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
|
||||
@Database(
|
||||
entities = [LocalMealEntity::class, LocalCustomFoodEntity::class],
|
||||
version = 1,
|
||||
exportSchema = false
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun mealDao(): LocalMealDao
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
private var INSTANCE: AppDatabase? = null
|
||||
|
||||
fun getInstance(context: Context): AppDatabase {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: Room.databaseBuilder(
|
||||
context.applicationContext,
|
||||
AppDatabase::class.java,
|
||||
"satiea_local.db"
|
||||
).fallbackToDestructiveMigration().build().also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.example.data.local
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.FoodUnit
|
||||
import java.text.Normalizer
|
||||
|
||||
@Entity(tableName = "local_custom_foods")
|
||||
data class LocalCustomFoodEntity(
|
||||
@PrimaryKey val slugId: String,
|
||||
val name: String,
|
||||
val defaultUnit: String = FoodUnit.G.code,
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
fun toCustomFoodEntry(userId: String = ""): CustomFoodEntry {
|
||||
return CustomFoodEntry(
|
||||
id = slugId,
|
||||
userId = userId,
|
||||
name = name,
|
||||
defaultUnit = defaultUnit
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun create(name: String, defaultUnit: FoodUnit): LocalCustomFoodEntity {
|
||||
val cleanName = name.trim().take(100)
|
||||
val slugId = Normalizer.normalize(cleanName.lowercase(), Normalizer.Form.NFD)
|
||||
.replace(Regex("[^a-z0-9]+"), "_")
|
||||
.trim('_')
|
||||
.take(64)
|
||||
.ifEmpty { "food_${System.currentTimeMillis()}" }
|
||||
|
||||
return LocalCustomFoodEntity(
|
||||
slugId = slugId,
|
||||
name = cleanName,
|
||||
defaultUnit = defaultUnit.code,
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.data.local
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface LocalMealDao {
|
||||
|
||||
@Query("SELECT * FROM local_meals ORDER BY mealTimestamp DESC")
|
||||
fun observeAllMeals(): Flow<List<LocalMealEntity>>
|
||||
|
||||
@Query("SELECT * FROM local_meals ORDER BY mealTimestamp DESC")
|
||||
suspend fun getAllMealsOnce(): List<LocalMealEntity>
|
||||
|
||||
@Query("SELECT * FROM local_meals WHERE id = :id LIMIT 1")
|
||||
suspend fun getMealById(id: String): LocalMealEntity?
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertMeal(meal: LocalMealEntity)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertMeals(meals: List<LocalMealEntity>)
|
||||
|
||||
@Query("DELETE FROM local_meals WHERE id = :id")
|
||||
suspend fun deleteMealById(id: String)
|
||||
|
||||
@Query("SELECT * FROM local_custom_foods ORDER BY name ASC")
|
||||
fun observeAllCustomFoods(): Flow<List<LocalCustomFoodEntity>>
|
||||
|
||||
@Query("SELECT * FROM local_custom_foods ORDER BY name ASC")
|
||||
suspend fun getAllCustomFoodsOnce(): List<LocalCustomFoodEntity>
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertCustomFood(food: LocalCustomFoodEntity)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertCustomFoods(foods: List<LocalCustomFoodEntity>)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.example.data.local
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
|
||||
@Entity(tableName = "local_meals")
|
||||
data class LocalMealEntity(
|
||||
@PrimaryKey val id: String,
|
||||
val userId: String = "",
|
||||
val mealType: String,
|
||||
val mealTimestamp: Long,
|
||||
val hungerBefore: Int,
|
||||
val satietyAfter: Int,
|
||||
val note: String = "",
|
||||
val foodItemsJoined: String = "", // serialized items separated by "###"
|
||||
val photosJoined: String = "", // Base64 photos separated by "|||"
|
||||
val updatedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
fun toMealEntry(): MealEntry {
|
||||
val foodItems = if (foodItemsJoined.isBlank()) {
|
||||
emptyList()
|
||||
} else {
|
||||
foodItemsJoined.split("###").filter { it.isNotBlank() }
|
||||
}
|
||||
val photos = if (photosJoined.isBlank()) {
|
||||
emptyList()
|
||||
} else {
|
||||
photosJoined.split("|||").filter { it.isNotBlank() }
|
||||
}
|
||||
return MealEntry(
|
||||
id = id,
|
||||
userId = userId,
|
||||
mealType = mealType,
|
||||
mealTimestamp = mealTimestamp,
|
||||
hungerBefore = hungerBefore,
|
||||
satietyAfter = satietyAfter,
|
||||
note = note,
|
||||
foodItemsSerialized = foodItems,
|
||||
photosBase64 = photos
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun fromMealEntry(meal: MealEntry): LocalMealEntity {
|
||||
val foodItemsJoined = meal.foodItemsSerialized.joinToString("###")
|
||||
val photosJoined = meal.photosBase64.joinToString("|||")
|
||||
return LocalMealEntity(
|
||||
id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" },
|
||||
userId = meal.userId,
|
||||
mealType = meal.mealType,
|
||||
mealTimestamp = meal.mealTimestamp,
|
||||
hungerBefore = meal.hungerBefore,
|
||||
satietyAfter = meal.satietyAfter,
|
||||
note = meal.note,
|
||||
foodItemsJoined = foodItemsJoined,
|
||||
photosJoined = photosJoined,
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.example.data.preferences
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
|
||||
class GoogleSheetsPreferencesManager private constructor(context: Context) {
|
||||
|
||||
private val prefs: SharedPreferences =
|
||||
context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||
|
||||
var spreadsheetId: String?
|
||||
get() = prefs.getString(KEY_SPREADSHEET_ID, null)
|
||||
set(value) {
|
||||
prefs.edit().putString(KEY_SPREADSHEET_ID, value).apply()
|
||||
}
|
||||
|
||||
var spreadsheetUrl: String?
|
||||
get() = prefs.getString(KEY_SPREADSHEET_URL, null)
|
||||
set(value) {
|
||||
prefs.edit().putString(KEY_SPREADSHEET_URL, value).apply()
|
||||
}
|
||||
|
||||
var isAutoSyncEnabled: Boolean
|
||||
get() = prefs.getBoolean(KEY_AUTO_SYNC, true)
|
||||
set(value) {
|
||||
prefs.edit().putBoolean(KEY_AUTO_SYNC, value).apply()
|
||||
}
|
||||
|
||||
var lastSyncTimestamp: Long
|
||||
get() = prefs.getLong(KEY_LAST_SYNC_TIMESTAMP, 0L)
|
||||
set(value) {
|
||||
prefs.edit().putLong(KEY_LAST_SYNC_TIMESTAMP, value).apply()
|
||||
}
|
||||
|
||||
var lastSyncCount: Int
|
||||
get() = prefs.getInt(KEY_LAST_SYNC_COUNT, 0)
|
||||
set(value) {
|
||||
prefs.edit().putInt(KEY_LAST_SYNC_COUNT, value).apply()
|
||||
}
|
||||
|
||||
var lastSyncStatus: String?
|
||||
get() = prefs.getString(KEY_LAST_SYNC_STATUS, null)
|
||||
set(value) {
|
||||
prefs.edit().putString(KEY_LAST_SYNC_STATUS, value).apply()
|
||||
}
|
||||
|
||||
var lastSyncError: String?
|
||||
get() = prefs.getString(KEY_LAST_SYNC_ERROR, null)
|
||||
set(value) {
|
||||
prefs.edit().putString(KEY_LAST_SYNC_ERROR, value).apply()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
prefs.edit().clear().apply()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREFS_NAME = "satiea_google_sheets_prefs"
|
||||
private const val KEY_SPREADSHEET_ID = "spreadsheet_id"
|
||||
private const val KEY_SPREADSHEET_URL = "spreadsheet_url"
|
||||
private const val KEY_AUTO_SYNC = "auto_sync_enabled"
|
||||
private const val KEY_LAST_SYNC_TIMESTAMP = "last_sync_timestamp"
|
||||
private const val KEY_LAST_SYNC_COUNT = "last_sync_count"
|
||||
private const val KEY_LAST_SYNC_STATUS = "last_sync_status"
|
||||
private const val KEY_LAST_SYNC_ERROR = "last_sync_error"
|
||||
|
||||
@Volatile
|
||||
private var INSTANCE: GoogleSheetsPreferencesManager? = null
|
||||
|
||||
fun getInstance(context: Context): GoogleSheetsPreferencesManager {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: GoogleSheetsPreferencesManager(context).also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.example.data.preferences
|
||||
|
||||
import android.content.Context
|
||||
import android.content.SharedPreferences
|
||||
import com.example.data.model.MealType
|
||||
|
||||
class ReminderPreferencesManager(context: Context) {
|
||||
|
||||
private val prefs: SharedPreferences = context.getSharedPreferences(
|
||||
PREFS_NAME,
|
||||
Context.MODE_PRIVATE
|
||||
)
|
||||
|
||||
fun isReminderEnabled(mealType: MealType): Boolean {
|
||||
val defaultEnabled = when (mealType) {
|
||||
MealType.BREAKFAST -> true
|
||||
MealType.LUNCH -> true
|
||||
MealType.SNACK -> false
|
||||
MealType.DINNER -> true
|
||||
}
|
||||
return prefs.getBoolean(KEY_PREFIX_ENABLED + mealType.name, defaultEnabled)
|
||||
}
|
||||
|
||||
fun setReminderEnabled(mealType: MealType, enabled: Boolean) {
|
||||
prefs.edit().putBoolean(KEY_PREFIX_ENABLED + mealType.name, enabled).apply()
|
||||
}
|
||||
|
||||
fun getReminderTime(mealType: MealType): Pair<Int, Int> {
|
||||
val (defaultHour, defaultMinute) = when (mealType) {
|
||||
MealType.BREAKFAST -> Pair(8, 0)
|
||||
MealType.LUNCH -> Pair(12, 30)
|
||||
MealType.SNACK -> Pair(16, 30)
|
||||
MealType.DINNER -> Pair(20, 0)
|
||||
}
|
||||
val hour = prefs.getInt(KEY_PREFIX_HOUR + mealType.name, defaultHour)
|
||||
val minute = prefs.getInt(KEY_PREFIX_MINUTE + mealType.name, defaultMinute)
|
||||
return Pair(hour, minute)
|
||||
}
|
||||
|
||||
fun setReminderTime(mealType: MealType, hour: Int, minute: Int) {
|
||||
prefs.edit()
|
||||
.putInt(KEY_PREFIX_HOUR + mealType.name, hour)
|
||||
.putInt(KEY_PREFIX_MINUTE + mealType.name, minute)
|
||||
.apply()
|
||||
}
|
||||
|
||||
fun hasPromptedNotificationPermission(): Boolean {
|
||||
return prefs.getBoolean(KEY_PROMPTED_PERMISSION, false)
|
||||
}
|
||||
|
||||
fun setPromptedNotificationPermission(prompted: Boolean) {
|
||||
prefs.edit().putBoolean(KEY_PROMPTED_PERMISSION, prompted).apply()
|
||||
}
|
||||
|
||||
fun clearAll() {
|
||||
prefs.edit().clear().commit()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val PREFS_NAME = "satiea_meal_reminders_prefs"
|
||||
private const val KEY_PREFIX_ENABLED = "reminder_enabled_"
|
||||
private const val KEY_PREFIX_HOUR = "reminder_hour_"
|
||||
private const val KEY_PREFIX_MINUTE = "reminder_minute_"
|
||||
private const val KEY_PROMPTED_PERMISSION = "has_prompted_notification_permission"
|
||||
|
||||
@Volatile
|
||||
private var INSTANCE: ReminderPreferencesManager? = null
|
||||
|
||||
fun getInstance(context: Context): ReminderPreferencesManager {
|
||||
return INSTANCE ?: synchronized(this) {
|
||||
INSTANCE ?: ReminderPreferencesManager(context.applicationContext).also { INSTANCE = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
package com.example.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import com.example.R
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.local.LocalCustomFoodEntity
|
||||
import com.example.data.local.LocalMealDao
|
||||
import com.example.data.local.LocalMealEntity
|
||||
import com.example.data.model.CustomFoodEntry
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.util.CsvImportResult
|
||||
import com.example.util.CsvImporter
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
import com.google.firebase.firestore.FieldValue
|
||||
@@ -20,104 +28,152 @@ import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.tasks.await
|
||||
import java.text.Normalizer
|
||||
import java.util.UUID
|
||||
|
||||
class MealRepository(private val db: FirebaseFirestore) {
|
||||
class MealRepository(
|
||||
private val localMealDao: LocalMealDao?,
|
||||
private val db: FirebaseFirestore?
|
||||
) {
|
||||
|
||||
// Constructor used by ViewModel in app runtime
|
||||
constructor(context: Context) : this(
|
||||
FirebaseFirestore.getInstance(
|
||||
context.applicationContext.getString(R.string.firestore_database_id)
|
||||
)
|
||||
localMealDao = AppDatabase.getInstance(context).mealDao(),
|
||||
db = try {
|
||||
FirebaseFirestore.getInstance(
|
||||
context.applicationContext.getString(R.string.firestore_database_id)
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
)
|
||||
|
||||
// Secondary constructor for Firestore rule tests without local DB
|
||||
constructor(db: FirebaseFirestore) : this(
|
||||
localMealDao = null,
|
||||
db = db
|
||||
)
|
||||
|
||||
private val auth = Firebase.auth
|
||||
|
||||
private fun getUserIdOrNull(): String? {
|
||||
return auth.currentUser?.uid
|
||||
}
|
||||
|
||||
private fun requireUserId(): String {
|
||||
return auth.currentUser?.uid
|
||||
?: throw IllegalStateException("User must be signed in with Google before accessing Firestore.")
|
||||
}
|
||||
|
||||
fun observeMeals(): Flow<List<MealEntry>> = flow {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/meals"
|
||||
emitAll(
|
||||
db.collection("users").document(uid).collection("meals")
|
||||
.orderBy("mealTimestamp", Query.Direction.DESCENDING)
|
||||
.snapshots()
|
||||
.map { snapshot ->
|
||||
snapshot.toObjects(MealEntry::class.java)
|
||||
}
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
val exceptionToLog = firestoreError ?: (error as? Exception)
|
||||
if (exceptionToLog != null) {
|
||||
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
|
||||
fun observeMeals(): Flow<List<MealEntry>> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.observeAllMeals().map { entities ->
|
||||
entities.map { it.toMealEntry() }
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for tests or remote-only mode
|
||||
return flow {
|
||||
val uid = requireUserId()
|
||||
val firestore = db ?: throw IllegalStateException("Firestore is null")
|
||||
val path = "users/$uid/meals"
|
||||
emitAll(
|
||||
firestore.collection("users").document(uid).collection("meals")
|
||||
.orderBy("mealTimestamp", Query.Direction.DESCENDING)
|
||||
.snapshots()
|
||||
.map { snapshot ->
|
||||
snapshot.toObjects(MealEntry::class.java)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fun observeCustomFoods(): Flow<List<CustomFoodEntry>> = flow {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/custom_foods"
|
||||
emitAll(
|
||||
db.collection("users").document(uid).collection("custom_foods")
|
||||
.orderBy("name", Query.Direction.ASCENDING)
|
||||
.snapshots()
|
||||
.map { snapshot ->
|
||||
snapshot.toObjects(CustomFoodEntry::class.java)
|
||||
}
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
val exceptionToLog = firestoreError ?: (error as? Exception)
|
||||
if (exceptionToLog != null) {
|
||||
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
val exceptionToLog = firestoreError ?: (error as? Exception)
|
||||
if (exceptionToLog != null) {
|
||||
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
throw error
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun saveCustomFood(name: String, defaultUnit: FoodUnit): Result<String> {
|
||||
val uid = requireUserId()
|
||||
val trimmedName = name.trim().take(100)
|
||||
if (trimmedName.isBlank()) return Result.failure(IllegalArgumentException("Food name is blank"))
|
||||
|
||||
val slugId = Normalizer.normalize(trimmedName.lowercase(), Normalizer.Form.NFD)
|
||||
.replace(Regex("[^a-z0-9]+"), "_")
|
||||
.trim('_')
|
||||
.take(64)
|
||||
.ifEmpty { "food_${System.currentTimeMillis()}" }
|
||||
|
||||
val docRef = db.collection("users").document(uid).collection("custom_foods").document(slugId)
|
||||
return try {
|
||||
val payload = mapOf(
|
||||
"userId" to uid,
|
||||
"name" to trimmedName,
|
||||
"defaultUnit" to defaultUnit.code,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
docRef.set(payload).await()
|
||||
Result.success(slugId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.CREATE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getMealById(mealId: String, ownerId: String = requireUserId()): Result<MealEntry> {
|
||||
val path = "users/$ownerId/meals/$mealId"
|
||||
fun observeCustomFoods(): Flow<List<CustomFoodEntry>> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.observeAllCustomFoods().map { entities ->
|
||||
entities.map { it.toCustomFoodEntry(getUserIdOrNull().orEmpty()) }
|
||||
}
|
||||
}
|
||||
|
||||
return flow {
|
||||
val uid = requireUserId()
|
||||
val firestore = db ?: throw IllegalStateException("Firestore is null")
|
||||
val path = "users/$uid/custom_foods"
|
||||
emitAll(
|
||||
firestore.collection("users").document(uid).collection("custom_foods")
|
||||
.orderBy("name", Query.Direction.ASCENDING)
|
||||
.snapshots()
|
||||
.map { snapshot ->
|
||||
snapshot.toObjects(CustomFoodEntry::class.java)
|
||||
}
|
||||
.catch { error ->
|
||||
val firestoreError = generateSequence(error) { it.cause }
|
||||
.filterIsInstance<FirebaseFirestoreException>()
|
||||
.firstOrNull()
|
||||
if (firestoreError == null && error is CancellationException) throw error
|
||||
val exceptionToLog = firestoreError ?: (error as? Exception)
|
||||
if (exceptionToLog != null) {
|
||||
handleFirestoreError(exceptionToLog, OperationType.LIST, path)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveCustomFood(name: String, defaultUnit: FoodUnit): Result<String> {
|
||||
val trimmedName = name.trim().take(100)
|
||||
if (trimmedName.isBlank()) return Result.failure(IllegalArgumentException("Food name is blank"))
|
||||
|
||||
val localEntity = LocalCustomFoodEntity.create(trimmedName, defaultUnit)
|
||||
localMealDao?.insertCustomFood(localEntity)
|
||||
|
||||
val uid = getUserIdOrNull()
|
||||
if (uid != null && db != null) {
|
||||
val slugId = localEntity.slugId
|
||||
val docRef = db.collection("users").document(uid).collection("custom_foods").document(slugId)
|
||||
try {
|
||||
val payload = mapOf(
|
||||
"userId" to uid,
|
||||
"name" to trimmedName,
|
||||
"defaultUnit" to defaultUnit.code,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
docRef.set(payload).await()
|
||||
} catch (e: Exception) {
|
||||
if (localMealDao == null) {
|
||||
handleFirestoreError(e, OperationType.CREATE, docRef.path)
|
||||
return Result.failure(e)
|
||||
}
|
||||
Log.w("MealRepository", "Could not sync custom food to Firestore: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(localEntity.slugId)
|
||||
}
|
||||
|
||||
suspend fun getMealById(mealId: String, ownerId: String? = null): Result<MealEntry> {
|
||||
if (localMealDao != null) {
|
||||
val local = localMealDao.getMealById(mealId)
|
||||
if (local != null) return Result.success(local.toMealEntry())
|
||||
}
|
||||
|
||||
val uid = ownerId ?: requireUserId()
|
||||
val firestore = db ?: return Result.failure(NoSuchElementException("Meal not found"))
|
||||
val path = "users/$uid/meals/$mealId"
|
||||
return try {
|
||||
val doc = db.collection("users").document(ownerId).collection("meals").document(mealId).get().await()
|
||||
val doc = firestore.collection("users").document(uid).collection("meals").document(mealId).get().await()
|
||||
val entry = doc.toObject(MealEntry::class.java)
|
||||
if (entry != null) {
|
||||
Result.success(entry)
|
||||
@@ -133,60 +189,206 @@ class MealRepository(private val db: FirebaseFirestore) {
|
||||
}
|
||||
|
||||
suspend fun addMeal(meal: MealEntry): Result<String> {
|
||||
val uid = requireUserId()
|
||||
val path = "users/$uid/meals"
|
||||
return try {
|
||||
val mealsRef = db.collection("users").document(uid).collection("meals")
|
||||
val payload = meal.toMap() + mapOf(
|
||||
"userId" to uid,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
val docRef = mealsRef.add(payload).await()
|
||||
Result.success(docRef.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.CREATE, path)
|
||||
Result.failure(e)
|
||||
val resolvedId = meal.id.ifBlank { "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}" }
|
||||
val mealWithId = meal.copy(id = resolvedId)
|
||||
|
||||
// 1. Always save to local SQLite Room first (Offline-First)
|
||||
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId))
|
||||
|
||||
// 2. If user is signed in with Google, sync to Firestore
|
||||
val uid = getUserIdOrNull()
|
||||
if (uid != null && db != null) {
|
||||
val path = "users/$uid/meals"
|
||||
try {
|
||||
val mealsRef = db.collection("users").document(uid).collection("meals")
|
||||
val payload = mealWithId.toMap() + mapOf(
|
||||
"userId" to uid,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
val docRef = mealsRef.document(resolvedId)
|
||||
docRef.set(payload).await()
|
||||
} catch (e: Exception) {
|
||||
if (localMealDao == null) {
|
||||
handleFirestoreError(e, OperationType.CREATE, path)
|
||||
return Result.failure(e)
|
||||
}
|
||||
Log.w("MealRepository", "Could not sync meal to Firestore: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(resolvedId)
|
||||
}
|
||||
|
||||
suspend fun updateMeal(meal: MealEntry): Result<Unit> {
|
||||
val uid = requireUserId()
|
||||
require(meal.id.isNotBlank()) { "Meal ID must not be blank for update" }
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(meal.id)
|
||||
|
||||
// 1. Update in local Room database
|
||||
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal))
|
||||
|
||||
// 2. If signed in, update Firestore
|
||||
val uid = getUserIdOrNull()
|
||||
if (uid != null && db != null) {
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(meal.id)
|
||||
try {
|
||||
val updates = mapOf(
|
||||
"mealType" to meal.mealType,
|
||||
"mealTimestamp" to meal.mealTimestamp,
|
||||
"hungerBefore" to meal.hungerBefore.coerceIn(1, 10),
|
||||
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
|
||||
"note" to meal.note,
|
||||
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
|
||||
"photosBase64" to meal.photosBase64,
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
docRef.update(updates).await()
|
||||
} catch (e: Exception) {
|
||||
if (localMealDao == null) {
|
||||
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
|
||||
return Result.failure(e)
|
||||
}
|
||||
Log.w("MealRepository", "Could not sync meal update to Firestore: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
suspend fun deleteMeal(mealId: String): Result<Unit> {
|
||||
// 1. Delete from local Room database
|
||||
localMealDao?.deleteMealById(mealId)
|
||||
|
||||
// 2. If signed in, delete from Firestore
|
||||
val uid = getUserIdOrNull()
|
||||
if (uid != null && db != null) {
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
|
||||
try {
|
||||
docRef.delete().await()
|
||||
} catch (e: Exception) {
|
||||
if (localMealDao == null) {
|
||||
handleFirestoreError(e, OperationType.DELETE, docRef.path)
|
||||
return Result.failure(e)
|
||||
}
|
||||
Log.w("MealRepository", "Could not delete from Firestore: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
return Result.success(Unit)
|
||||
}
|
||||
|
||||
suspend fun getAllMealsSnapshot(): List<MealEntry> {
|
||||
if (localMealDao != null) {
|
||||
return localMealDao.getAllMealsOnce().map { it.toMealEntry() }
|
||||
}
|
||||
val uid = getUserIdOrNull() ?: return emptyList()
|
||||
val firestore = db ?: return emptyList()
|
||||
return try {
|
||||
val updates = mapOf(
|
||||
"mealType" to meal.mealType,
|
||||
"mealTimestamp" to meal.mealTimestamp,
|
||||
"hungerBefore" to meal.hungerBefore.coerceIn(1, 10),
|
||||
"satietyAfter" to meal.satietyAfter.coerceIn(1, 10),
|
||||
"note" to meal.note,
|
||||
"foodItemsSerialized" to meal.foodItemsSerialized.take(30),
|
||||
"photosBase64" to meal.photosBase64,
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
docRef.update(updates).await()
|
||||
Result.success(Unit)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
firestore.collection("users").document(uid).collection("meals")
|
||||
.orderBy("mealTimestamp", Query.Direction.DESCENDING)
|
||||
.get()
|
||||
.await()
|
||||
.toObjects(MealEntry::class.java)
|
||||
} catch (_: Exception) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun importMealsFromCsv(context: Context, uri: Uri): Result<CsvImportResult> {
|
||||
return try {
|
||||
val existingMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
|
||||
val result = CsvImporter.importFromUri(context, uri, existingMeals).getOrThrow()
|
||||
|
||||
// 1. Insert new meals into Room
|
||||
val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) }
|
||||
localMealDao?.insertMeals(localEntities)
|
||||
|
||||
// 2. Enrich custom foods catalog in Room
|
||||
val newCustomFoods = result.newFoodItems.map { item ->
|
||||
LocalCustomFoodEntity.create(item.name, item.unit)
|
||||
}
|
||||
localMealDao?.insertCustomFoods(newCustomFoods)
|
||||
|
||||
// 3. If signed in, sync newly imported meals and foods to Cloud
|
||||
val uid = getUserIdOrNull()
|
||||
if (uid != null && db != null) {
|
||||
for (meal in result.importedMeals) {
|
||||
try {
|
||||
val payload = meal.toMap() + mapOf(
|
||||
"userId" to uid,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
db.collection("users").document(uid).collection("meals").document(meal.id).set(payload).await()
|
||||
} catch (e: Exception) {
|
||||
Log.w("MealRepository", "Sync imported meal error: ${e.message}")
|
||||
}
|
||||
}
|
||||
for (food in newCustomFoods) {
|
||||
try {
|
||||
val payload = mapOf(
|
||||
"userId" to uid,
|
||||
"name" to food.name,
|
||||
"defaultUnit" to food.defaultUnit,
|
||||
"createdAt" to FieldValue.serverTimestamp(),
|
||||
"updatedAt" to FieldValue.serverTimestamp()
|
||||
)
|
||||
db.collection("users").document(uid).collection("custom_foods").document(food.slugId).set(payload).await()
|
||||
} catch (e: Exception) {
|
||||
Log.w("MealRepository", "Sync imported food error: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result.success(result)
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.UPDATE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteMeal(mealId: String): Result<Unit> {
|
||||
val uid = requireUserId()
|
||||
val docRef = db.collection("users").document(uid).collection("meals").document(mealId)
|
||||
suspend fun syncCloudToLocal(): Result<Int> {
|
||||
val uid = getUserIdOrNull() ?: return Result.failure(IllegalStateException("No Google account signed in"))
|
||||
val firestore = db ?: return Result.failure(IllegalStateException("Firestore is not available"))
|
||||
|
||||
return try {
|
||||
docRef.delete().await()
|
||||
Result.success(Unit)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
// 1. Fetch remote meals
|
||||
val remoteMealsSnapshot = firestore.collection("users").document(uid).collection("meals").get().await()
|
||||
val remoteMeals = remoteMealsSnapshot.toObjects(MealEntry::class.java)
|
||||
|
||||
// 2. Fetch local meals
|
||||
val localMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
|
||||
val localFingerprints = localMeals.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }.toSet()
|
||||
|
||||
var importedCount = 0
|
||||
val toInsertLocally = mutableListOf<LocalMealEntity>()
|
||||
|
||||
for (remoteMeal in remoteMeals) {
|
||||
val fp = "${remoteMeal.mealType.uppercase()}_${remoteMeal.mealTimestamp / 60_000}"
|
||||
if (!localFingerprints.contains(fp)) {
|
||||
toInsertLocally.add(LocalMealEntity.fromMealEntry(remoteMeal))
|
||||
importedCount++
|
||||
}
|
||||
}
|
||||
|
||||
if (toInsertLocally.isNotEmpty()) {
|
||||
localMealDao?.insertMeals(toInsertLocally)
|
||||
}
|
||||
|
||||
// 3. Fetch remote custom foods
|
||||
val remoteFoodsSnapshot = firestore.collection("users").document(uid).collection("custom_foods").get().await()
|
||||
val remoteFoods = remoteFoodsSnapshot.toObjects(CustomFoodEntry::class.java)
|
||||
val foodsToInsert = remoteFoods.map { food ->
|
||||
LocalCustomFoodEntity(
|
||||
slugId = food.id.ifBlank { Normalizer.normalize(food.name.lowercase(), Normalizer.Form.NFD).replace(Regex("[^a-z0-9]+"), "_") },
|
||||
name = food.name,
|
||||
defaultUnit = food.defaultUnit
|
||||
)
|
||||
}
|
||||
if (foodsToInsert.isNotEmpty()) {
|
||||
localMealDao?.insertCustomFoods(foodsToInsert)
|
||||
}
|
||||
|
||||
Result.success(importedCount)
|
||||
} catch (e: Exception) {
|
||||
handleFirestoreError(e, OperationType.DELETE, docRef.path)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,31 +6,38 @@ import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.RingtoneManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.example.MainActivity
|
||||
import com.example.R
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.receiver.MealReminderReceiver
|
||||
import java.util.Calendar
|
||||
|
||||
object MealNotificationManager {
|
||||
|
||||
const val CHANNEL_ID = "meal_reminders_channel"
|
||||
const val CHANNEL_NAME = "Rappels de Repas"
|
||||
private const val TAG = "MealNotificationManager"
|
||||
const val CHANNEL_ID = "meal_reminders_channel_v2"
|
||||
const val CHANNEL_NAME = "Rappels de Repas Satiéa"
|
||||
const val EXTRA_MEAL_TYPE = "extra_meal_type"
|
||||
const val ACTION_LOG_MEAL = "com.example.action.LOG_MEAL"
|
||||
|
||||
fun createNotificationChannel(context: Context) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val importance = NotificationManager.IMPORTANCE_DEFAULT
|
||||
val importance = NotificationManager.IMPORTANCE_HIGH
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
CHANNEL_NAME,
|
||||
importance
|
||||
).apply {
|
||||
description = "Rappels personnalisés pour noter vos sensations de faim et satiété à table."
|
||||
description = "Rappels prioritaires pour évaluer votre faim et noter vos repas à table."
|
||||
enableVibration(true)
|
||||
vibrationPattern = longArrayOf(0, 250, 200, 250)
|
||||
setShowBadge(true)
|
||||
setBypassDnd(false)
|
||||
}
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
@@ -54,22 +61,27 @@ object MealNotificationManager {
|
||||
)
|
||||
|
||||
val (title, body) = when (mealType) {
|
||||
MealType.BREAKFAST -> Pair("C'est l'heure du petit-déjeuner ☀️", "Prenez 15 secondes pour évaluer votre faim et immortaliser votre assiette.")
|
||||
MealType.LUNCH -> Pair("Pause déjeuner bien méritée 🥗", "Comment est votre faim ? Prenez le temps de savourer et notez vos sensations.")
|
||||
MealType.SNACK -> Pair("Moment de la collation 🍎", "Envie gourmande ou vrai besoin énergétique ? Notez votre ressenti sur Satiéa.")
|
||||
MealType.DINNER -> Pair("C'est l'heure du dîner 🌙", "Terminez votre journée en douceur en notant votre niveau de faim et votre assiette.")
|
||||
MealType.BREAKFAST -> Pair("C'est l'heure du petit-déjeuner ☀️", "Prenez un instant pour évaluer votre faim et immortaliser votre assiette.")
|
||||
MealType.LUNCH -> Pair("Pause déjeuner bien méritée 🥗", "Quel est votre niveau de faim ? Savourez et notez vos sensations.")
|
||||
MealType.SNACK -> Pair("Moment de la collation 🍎", "Envie gourmande ou vrai besoin d'énergie ? Notez votre ressenti sur Satiéa.")
|
||||
MealType.DINNER -> Pair("C'est l'heure du dîner 🌙", "Terminez votre journée en douceur en notant votre faim et votre repas.")
|
||||
}
|
||||
|
||||
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
|
||||
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setSmallIcon(R.drawable.ic_notification_bell)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setDefaults(NotificationCompat.DEFAULT_ALL)
|
||||
.setSound(defaultSoundUri)
|
||||
.setVibrate(longArrayOf(0, 250, 200, 250))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(pendingIntent)
|
||||
.addAction(
|
||||
R.mipmap.ic_launcher,
|
||||
R.drawable.ic_notification_bell,
|
||||
"Noter mon repas",
|
||||
pendingIntent
|
||||
)
|
||||
@@ -95,6 +107,7 @@ object MealNotificationManager {
|
||||
|
||||
if (!enabled) {
|
||||
alarmManager.cancel(pendingIntent)
|
||||
Log.d(TAG, "Cancelled reminder for ${mealType.name}")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -109,11 +122,53 @@ object MealNotificationManager {
|
||||
}
|
||||
}
|
||||
|
||||
alarmManager.setInexactRepeating(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
AlarmManager.INTERVAL_DAY,
|
||||
pendingIntent
|
||||
)
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
if (alarmManager.canScheduleExactAlarms()) {
|
||||
alarmManager.setExactAndAllowWhileIdle(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
pendingIntent
|
||||
)
|
||||
} else {
|
||||
alarmManager.setAndAllowWhileIdle(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
pendingIntent
|
||||
)
|
||||
}
|
||||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setExactAndAllowWhileIdle(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
pendingIntent
|
||||
)
|
||||
} else {
|
||||
alarmManager.setExact(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
pendingIntent
|
||||
)
|
||||
}
|
||||
Log.d(TAG, "Scheduled exact reminder for ${mealType.name} at ${calendar.time}")
|
||||
} catch (e: SecurityException) {
|
||||
Log.w(TAG, "Exact alarm permission not granted, falling back to setAndAllowWhileIdle", e)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
alarmManager.setAndAllowWhileIdle(
|
||||
AlarmManager.RTC_WAKEUP,
|
||||
calendar.timeInMillis,
|
||||
pendingIntent
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun scheduleAllActiveReminders(context: Context) {
|
||||
val prefs = ReminderPreferencesManager.getInstance(context)
|
||||
for (mealType in MealType.entries) {
|
||||
val enabled = prefs.isReminderEnabled(mealType)
|
||||
val (hour, minute) = prefs.getReminderTime(mealType)
|
||||
scheduleDailyReminder(context, mealType, hour, minute, enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.example.receiver
|
||||
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import com.example.notification.MealNotificationManager
|
||||
|
||||
class BootReceiver : BroadcastReceiver() {
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val action = intent.action
|
||||
if (action == Intent.ACTION_BOOT_COMPLETED || action == Intent.ACTION_MY_PACKAGE_REPLACED) {
|
||||
Log.d("BootReceiver", "Device rebooted or app updated ($action). Rescheduling active meal reminders.")
|
||||
MealNotificationManager.createNotificationChannel(context)
|
||||
MealNotificationManager.scheduleAllActiveReminders(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,17 +3,28 @@ package com.example.receiver
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.notification.MealNotificationManager
|
||||
|
||||
class MealReminderReceiver : BroadcastReceiver() {
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val mealTypeName = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)
|
||||
val mealType = if (mealTypeName != null) {
|
||||
MealType.fromString(mealTypeName)
|
||||
} else {
|
||||
MealType.LUNCH
|
||||
}
|
||||
val mealType = mealTypeName?.let { MealType.fromString(it) } ?: MealType.LUNCH
|
||||
|
||||
Log.d("MealReminderReceiver", "Alarm triggered for meal: ${mealType.name}")
|
||||
|
||||
// 1. Show high-priority notification with heads-up banner
|
||||
MealNotificationManager.showMealNotification(context, mealType)
|
||||
|
||||
// 2. Reschedule exact alarm for the following day if still enabled
|
||||
val prefs = ReminderPreferencesManager.getInstance(context)
|
||||
if (prefs.isReminderEnabled(mealType)) {
|
||||
val (hour, minute) = prefs.getReminderTime(mealType)
|
||||
MealNotificationManager.scheduleDailyReminder(context, mealType, hour, minute, true)
|
||||
Log.d("MealReminderReceiver", "Rescheduled next day alarm for ${mealType.name} at $hour:$minute")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Restaurant
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
@@ -73,7 +75,9 @@ fun JournalScreen(
|
||||
onAddMealClick: () -> Unit,
|
||||
onEditMeal: (MealEntry) -> Unit,
|
||||
onDeleteMeal: (String) -> Unit,
|
||||
onExportCsvClick: (List<MealEntry>) -> Unit
|
||||
onExportCsvClick: (List<MealEntry>) -> Unit,
|
||||
onSyncSheetsClick: (() -> Unit)? = null,
|
||||
spreadsheetUrl: String? = null
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
@@ -157,22 +161,44 @@ fun JournalScreen(
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
|
||||
TextButton(
|
||||
onClick = { onExportCsvClick(meals) },
|
||||
modifier = Modifier.testTag("journal_export_csv_button")
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileDownload,
|
||||
contentDescription = "Exporter en CSV",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = "Export CSV",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (onSyncSheetsClick != null) {
|
||||
TextButton(
|
||||
onClick = onSyncSheetsClick,
|
||||
modifier = Modifier.testTag("journal_sync_sheets_button")
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.TableChart,
|
||||
contentDescription = "Synchroniser vers Google Sheets",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = Color(0xFF0F9D58)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(
|
||||
text = "Sheets",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = Color(0xFF0F9D58)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
TextButton(
|
||||
onClick = { onExportCsvClick(meals) },
|
||||
modifier = Modifier.testTag("journal_export_csv_button")
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileDownload,
|
||||
contentDescription = "Exporter en CSV",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text(
|
||||
text = "CSV",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,13 @@ import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.repository.MealRepository
|
||||
import com.example.data.preferences.GoogleSheetsPreferencesManager
|
||||
import com.example.notification.MealNotificationManager
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.example.util.CsvExporter
|
||||
import com.example.util.GoogleSheetsAuthHelper
|
||||
import com.example.util.GoogleSheetsSyncService
|
||||
import com.google.android.gms.auth.UserRecoverableAuthException
|
||||
import com.google.firebase.firestore.FirebaseFirestoreException
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -35,6 +39,13 @@ sealed interface MealsUiState {
|
||||
data class Error(val message: String) : MealsUiState
|
||||
}
|
||||
|
||||
sealed interface GoogleSheetsUiState {
|
||||
object Idle : GoogleSheetsUiState
|
||||
object Syncing : GoogleSheetsUiState
|
||||
data class Success(val url: String, val count: Int, val timestamp: Long) : GoogleSheetsUiState
|
||||
data class Error(val message: String, val recoverableIntent: Intent? = null) : GoogleSheetsUiState
|
||||
}
|
||||
|
||||
data class DayStat(
|
||||
val dayLabel: String,
|
||||
val dayShortName: String,
|
||||
@@ -93,10 +104,42 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
|
||||
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
|
||||
|
||||
private val sheetsPrefs = GoogleSheetsPreferencesManager.getInstance(application)
|
||||
|
||||
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
|
||||
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
|
||||
GoogleSheetsUiState.Success(
|
||||
url = sheetsPrefs.spreadsheetUrl!!,
|
||||
count = sheetsPrefs.lastSyncCount,
|
||||
timestamp = sheetsPrefs.lastSyncTimestamp
|
||||
)
|
||||
} else {
|
||||
GoogleSheetsUiState.Idle
|
||||
}
|
||||
)
|
||||
val sheetsUiState: StateFlow<GoogleSheetsUiState> = _sheetsUiState.asStateFlow()
|
||||
|
||||
private val _isAutoSyncSheets = MutableStateFlow(sheetsPrefs.isAutoSyncEnabled)
|
||||
val isAutoSyncSheets: StateFlow<Boolean> = _isAutoSyncSheets.asStateFlow()
|
||||
|
||||
private val _spreadsheetUrl = MutableStateFlow(sheetsPrefs.spreadsheetUrl)
|
||||
val spreadsheetUrl: StateFlow<String?> = _spreadsheetUrl.asStateFlow()
|
||||
|
||||
fun setThemeMode(mode: AppThemeMode) {
|
||||
_themeMode.value = mode
|
||||
}
|
||||
|
||||
fun setAutoSyncSheets(enabled: Boolean) {
|
||||
sheetsPrefs.isAutoSyncEnabled = enabled
|
||||
_isAutoSyncSheets.value = enabled
|
||||
}
|
||||
|
||||
fun disconnectGoogleSheets() {
|
||||
sheetsPrefs.clear()
|
||||
_spreadsheetUrl.value = null
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Idle
|
||||
}
|
||||
|
||||
private fun enrichCatalogWithFoodItems(foodItems: List<MealFoodItem>) {
|
||||
val existingBuiltIn = DefaultFoodCatalog.builtInFoods.map { it.name.lowercase(Locale.FRENCH) }.toSet()
|
||||
val existingCustom = customFoods.value.map { it.name.lowercase(Locale.FRENCH) }.toSet()
|
||||
@@ -145,6 +188,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val result = repository.addMeal(entry)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
triggerAutoSheetsSyncIfNeeded()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement")
|
||||
}
|
||||
@@ -167,6 +211,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val result = repository.updateMeal(sanitizedMeal)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
triggerAutoSheetsSyncIfNeeded()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour")
|
||||
}
|
||||
@@ -182,12 +227,95 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val result = repository.deleteMeal(mealId)
|
||||
if (result.isSuccess) {
|
||||
onSuccess()
|
||||
triggerAutoSheetsSyncIfNeeded()
|
||||
} else {
|
||||
onError(result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun triggerAutoSheetsSyncIfNeeded() {
|
||||
if (!sheetsPrefs.isAutoSyncEnabled) return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
|
||||
val token = tokenResult.getOrNull() ?: return@launch
|
||||
val sheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
|
||||
val (id, url) = sheetResult.getOrNull() ?: return@launch
|
||||
sheetsPrefs.spreadsheetId = id
|
||||
sheetsPrefs.spreadsheetUrl = url
|
||||
_spreadsheetUrl.value = url
|
||||
|
||||
val currentMeals = repository.getAllMealsSnapshot()
|
||||
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
|
||||
if (syncResult.isSuccess) {
|
||||
val res = syncResult.getOrThrow()
|
||||
sheetsPrefs.lastSyncTimestamp = res.timestamp
|
||||
sheetsPrefs.lastSyncCount = res.mealsCount
|
||||
sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement"
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Non-blocking background sync
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun syncToGoogleSheets(
|
||||
onSuccess: (url: String, count: Int) -> Unit = { _, _ -> },
|
||||
onError: (message: String, recoverableIntent: Intent?) -> Unit = { _, _ -> }
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Syncing
|
||||
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
|
||||
if (tokenResult.isFailure) {
|
||||
val exception = tokenResult.exceptionOrNull()
|
||||
if (exception is UserRecoverableAuthException) {
|
||||
val intent = exception.intent
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(
|
||||
"Autorisation requise pour Google Sheets & Drive",
|
||||
recoverableIntent = intent
|
||||
)
|
||||
onError("Autorisation requise pour Google Sheets & Drive", intent)
|
||||
} else {
|
||||
val msg = exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google"
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(msg)
|
||||
onError(msg, null)
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
val token = tokenResult.getOrThrow()
|
||||
val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
|
||||
if (spreadsheetResult.isFailure) {
|
||||
val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création de la feuille"
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
|
||||
onError(err, null)
|
||||
return@launch
|
||||
}
|
||||
|
||||
val (id, url) = spreadsheetResult.getOrThrow()
|
||||
sheetsPrefs.spreadsheetId = id
|
||||
sheetsPrefs.spreadsheetUrl = url
|
||||
_spreadsheetUrl.value = url
|
||||
|
||||
val currentMeals = repository.getAllMealsSnapshot()
|
||||
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
|
||||
if (syncResult.isSuccess) {
|
||||
val res = syncResult.getOrThrow()
|
||||
sheetsPrefs.lastSyncTimestamp = res.timestamp
|
||||
sheetsPrefs.lastSyncCount = res.mealsCount
|
||||
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
|
||||
onSuccess(res.spreadsheetUrl, res.mealsCount)
|
||||
} else {
|
||||
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas"
|
||||
_sheetsUiState.value = GoogleSheetsUiState.Error(err)
|
||||
onError(err, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun exportCsvToUri(
|
||||
targetUri: Uri,
|
||||
meals: List<MealEntry>,
|
||||
@@ -203,6 +331,33 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
fun importCsvFromUri(
|
||||
sourceUri: Uri,
|
||||
onSuccess: (com.example.util.CsvImportResult) -> Unit,
|
||||
onError: (String) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = repository.importMealsFromCsv(context, sourceUri)
|
||||
result.fold(
|
||||
onSuccess = { importResult -> onSuccess(importResult) },
|
||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de l'import du fichier CSV") }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun syncCloudToLocal(
|
||||
onSuccess: (Int) -> Unit,
|
||||
onError: (String) -> Unit
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val result = repository.syncCloudToLocal()
|
||||
result.fold(
|
||||
onSuccess = { count -> onSuccess(count) },
|
||||
onFailure = { err -> onError(err.localizedMessage ?: "Erreur lors de la synchronisation") }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun shareCsv(
|
||||
activityContext: Context,
|
||||
meals: List<MealEntry>,
|
||||
@@ -219,9 +374,20 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
|
||||
fun scheduleMealReminder(mealType: MealType, hour: Int, minute: Int, enabled: Boolean) {
|
||||
val prefs = com.example.data.preferences.ReminderPreferencesManager.getInstance(context)
|
||||
prefs.setReminderEnabled(mealType, enabled)
|
||||
prefs.setReminderTime(mealType, hour, minute)
|
||||
MealNotificationManager.scheduleDailyReminder(context, mealType, hour, minute, enabled)
|
||||
}
|
||||
|
||||
fun isReminderEnabled(mealType: MealType): Boolean {
|
||||
return com.example.data.preferences.ReminderPreferencesManager.getInstance(context).isReminderEnabled(mealType)
|
||||
}
|
||||
|
||||
fun getReminderTime(mealType: MealType): Pair<Int, Int> {
|
||||
return com.example.data.preferences.ReminderPreferencesManager.getInstance(context).getReminderTime(mealType)
|
||||
}
|
||||
|
||||
fun triggerTestNotification(mealType: MealType) {
|
||||
MealNotificationManager.showMealNotification(context, mealType)
|
||||
}
|
||||
|
||||
@@ -22,14 +22,32 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ExitToApp
|
||||
import androidx.compose.material.icons.automirrored.filled.Login
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
import androidx.compose.material.icons.filled.AccountCircle
|
||||
import androidx.compose.material.icons.filled.Brightness4
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.CloudDone
|
||||
import androidx.compose.material.icons.filled.CloudOff
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.FileUpload
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material.icons.filled.NotificationsOff
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.Storage
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.example.ui.journal.GoogleSheetsUiState
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
@@ -45,17 +63,24 @@ import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.SwitchDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateMapOf
|
||||
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.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.credentials.ClearCredentialStateRequest
|
||||
import androidx.credentials.CredentialManager
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.ui.theme.AppThemeMode
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
@@ -68,28 +93,46 @@ import kotlinx.coroutines.launch
|
||||
fun SettingsScreen(
|
||||
currentThemeMode: AppThemeMode,
|
||||
totalMealsCount: Int,
|
||||
sheetsUiState: GoogleSheetsUiState,
|
||||
isAutoSyncSheets: Boolean,
|
||||
spreadsheetUrl: String?,
|
||||
onThemeModeChange: (AppThemeMode) -> Unit,
|
||||
onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit,
|
||||
onTestNotification: (MealType) -> Unit,
|
||||
onSaveCsvClick: () -> Unit,
|
||||
onShareCsvClick: () -> Unit,
|
||||
onImportCsvClick: () -> Unit,
|
||||
onSyncSheetsClick: () -> Unit,
|
||||
onAutoSyncSheetsChange: (Boolean) -> Unit,
|
||||
onOpenSheetsClick: (String) -> Unit,
|
||||
onSignInClick: () -> Unit,
|
||||
onSignOut: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val currentUser = Firebase.auth.currentUser
|
||||
val prefs = remember { ReminderPreferencesManager.getInstance(context) }
|
||||
|
||||
var notificationsEnabledBySystem by remember {
|
||||
mutableStateOf(NotificationManagerCompat.from(context).areNotificationsEnabled())
|
||||
}
|
||||
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
|
||||
notificationsEnabledBySystem = NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
}
|
||||
|
||||
val reminderStates = remember {
|
||||
mutableStateMapOf(
|
||||
MealType.BREAKFAST to true,
|
||||
MealType.LUNCH to true,
|
||||
MealType.SNACK to false,
|
||||
MealType.DINNER to true
|
||||
)
|
||||
mutableStateMapOf<MealType, Boolean>().apply {
|
||||
MealType.entries.forEach { type ->
|
||||
put(type, prefs.isReminderEnabled(type))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val permissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { _ -> }
|
||||
) { isGranted ->
|
||||
notificationsEnabledBySystem = isGranted || NotificationManagerCompat.from(context).areNotificationsEnabled()
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
@@ -115,7 +158,7 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 1. CSV Export Card
|
||||
// 1. Local Database & CSV Management Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
@@ -135,7 +178,7 @@ fun SettingsScreen(
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.TableChart,
|
||||
imageVector = Icons.Default.Storage,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
@@ -147,13 +190,13 @@ fun SettingsScreen(
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Exporter mes repas (CSV)",
|
||||
text = "Base locale & Fichiers CSV",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "$totalMealsCount repas prêts à être exportés vers Excel ou Sheets",
|
||||
text = "Base SQLite locale active • $totalMealsCount repas sur l'appareil",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -164,13 +207,33 @@ fun SettingsScreen(
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = onImportCsvClick,
|
||||
modifier = Modifier
|
||||
.weight(1.1f)
|
||||
.testTag("settings_import_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileUpload,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Importer", maxLines = 1)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = onSaveCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.weight(1.1f)
|
||||
.testTag("settings_save_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
@@ -183,8 +246,8 @@ fun SettingsScreen(
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Enregistrer")
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Sauver", maxLines = 1)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
@@ -200,15 +263,305 @@ fun SettingsScreen(
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Partager")
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Partager", maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Text(
|
||||
text = "L'importation lit vos fichiers CSV (Excel/Sheets), fusionne les repas sans doublon et enrichit automatiquement votre catalogue d'aliments.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Reminders Card
|
||||
// 2. Google Sheets & Drive Sync Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("google_sheets_card"),
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(42.dp),
|
||||
shape = CircleShape,
|
||||
color = Color(0xFF0F9D58).copy(alpha = 0.15f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.TableChart,
|
||||
contentDescription = null,
|
||||
tint = Color(0xFF0F9D58),
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Google Sheets & Drive",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Classeur « Satiéa — Journal des Repas »",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
// Status display
|
||||
when (sheetsUiState) {
|
||||
is GoogleSheetsUiState.Syncing -> {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Text(
|
||||
text = "Synchronisation vers Google Sheets...",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
fontWeight = FontWeight.Medium
|
||||
)
|
||||
}
|
||||
}
|
||||
is GoogleSheetsUiState.Success -> {
|
||||
val timeStr = SimpleDateFormat("dd/MM/yyyy à HH:mm", Locale.FRENCH)
|
||||
.format(Date(sheetsUiState.timestamp))
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = Color(0xFF0F9D58).copy(alpha = 0.12f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = Color(0xFF0F9D58),
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Synchronisé (${sheetsUiState.count} repas enregistrés)",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = Color(0xFF0F9D58),
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Text(
|
||||
text = "Dernier envoi : $timeStr",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
is GoogleSheetsUiState.Error -> {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.5f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = sheetsUiState.message,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
}
|
||||
}
|
||||
GoogleSheetsUiState.Idle -> {
|
||||
if (spreadsheetUrl != null) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = Color(0xFF0F9D58),
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = "Classeur associé et prêt",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Classeur non encore créé ou synchronisé",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
// Auto sync toggle
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
|
||||
shape = RoundedCornerShape(14.dp)
|
||||
)
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Envoi automatique à chaque repas",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
text = "Met à jour votre Google Sheet à l'ajout ou la modification d'un repas",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 16.sp
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
|
||||
Switch(
|
||||
checked = isAutoSyncSheets,
|
||||
onCheckedChange = onAutoSyncSheetsChange,
|
||||
modifier = Modifier.testTag("switch_auto_sync_sheets"),
|
||||
colors = SwitchDefaults.colors(
|
||||
checkedThumbColor = Color(0xFF0F9D58),
|
||||
checkedTrackColor = Color(0xFF0F9D58).copy(alpha = 0.4f)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
// Buttons row
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = onSyncSheetsClick,
|
||||
enabled = sheetsUiState !is GoogleSheetsUiState.Syncing,
|
||||
modifier = Modifier
|
||||
.weight(1.2f)
|
||||
.testTag("sync_sheets_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF0F9D58),
|
||||
contentColor = Color.White
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Sync,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Synchroniser", maxLines = 1)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = { spreadsheetUrl?.let { onOpenSheetsClick(it) } },
|
||||
enabled = spreadsheetUrl != null,
|
||||
modifier = Modifier
|
||||
.weight(1.1f)
|
||||
.testTag("open_sheets_button"),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.OpenInNew,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Ouvrir ↗", maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Text(
|
||||
text = "Un classeur dédié « Satiéa — Journal des Repas » est géré automatiquement dans votre Google Drive personnel avec en-têtes et données ordonnées.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Reminders Card
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -254,10 +607,73 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (!notificationsEnabledBySystem) {
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.45f)
|
||||
),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.NotificationsOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(10.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = "Notifications bloquées",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Autorisez les notifications pour recevoir les alertes de repas.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
try {
|
||||
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).apply {
|
||||
putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
},
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error
|
||||
),
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
Text("Activer")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(18.dp))
|
||||
|
||||
MealType.entries.forEach { mealType ->
|
||||
val isEnabled = reminderStates[mealType] ?: false
|
||||
val (hour, minute) = prefs.getReminderTime(mealType)
|
||||
val formattedTime = String.format("%02dh%02d", hour, minute)
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -273,7 +689,7 @@ fun SettingsScreen(
|
||||
fontWeight = FontWeight.SemiBold
|
||||
)
|
||||
Text(
|
||||
text = "Heure conseillée: ${mealType.defaultTime}",
|
||||
text = "Heure de rappel: $formattedTime",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -282,16 +698,11 @@ fun SettingsScreen(
|
||||
Switch(
|
||||
checked = isEnabled,
|
||||
onCheckedChange = { checked ->
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && checked) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && checked && !notificationsEnabledBySystem) {
|
||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
reminderStates[mealType] = checked
|
||||
val (hour, minute) = when (mealType) {
|
||||
MealType.BREAKFAST -> Pair(8, 0)
|
||||
MealType.LUNCH -> Pair(12, 30)
|
||||
MealType.SNACK -> Pair(16, 30)
|
||||
MealType.DINNER -> Pair(20, 0)
|
||||
}
|
||||
prefs.setReminderEnabled(mealType, checked)
|
||||
onScheduleReminder(mealType, hour, minute, checked)
|
||||
},
|
||||
colors = SwitchDefaults.colors(
|
||||
@@ -303,14 +714,15 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(10.dp))
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationsEnabledBySystem) {
|
||||
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
onTestNotification(MealType.LUNCH)
|
||||
}
|
||||
onTestNotification(MealType.LUNCH)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -399,7 +811,7 @@ fun SettingsScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Account & Cloud Sync Card
|
||||
// 4. Account & Cloud Sync Card (Optional)
|
||||
item {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -409,94 +821,155 @@ fun SettingsScreen(
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.AccountCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
if (currentUser != null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.AccountCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = currentUser.displayName ?: "Compte Google",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = currentUser.email ?: "Synchronisation Cloud Firestore active",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = currentUser?.displayName ?: "Compte connecté",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudDone,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = currentUser?.email ?: "Synchronisation Cloud Firestore active",
|
||||
text = "Base de données cloud sécurisée • Synchronisation continue",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
Button(
|
||||
onClick = {
|
||||
Firebase.auth.signOut()
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
val credManager = CredentialManager.create(context)
|
||||
credManager.clearCredentialState(ClearCredentialStateRequest())
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
onSignOut()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("signout_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error.copy(alpha = 0.15f),
|
||||
contentColor = MaterialTheme.colorScheme.error
|
||||
)
|
||||
.padding(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudDone,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ExitToApp,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Passer en mode local uniquement (Déconnexion)")
|
||||
}
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.secondaryContainer
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CloudOff,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSecondaryContainer,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.width(12.dp))
|
||||
|
||||
Column {
|
||||
Text(
|
||||
text = "Mode hors-ligne local actif",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Text(
|
||||
text = "Données stockées sur cet appareil sans aucun compte",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(14.dp))
|
||||
|
||||
Text(
|
||||
text = "Base de données cloud sécurisée • Sauvegarde continue",
|
||||
text = "Vous pouvez utiliser Satiéa librement en local. La connexion Google est optionnelle pour sauvegarder et synchroniser vos repas entre appareils.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
Firebase.auth.signOut()
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
val credManager = CredentialManager.create(context)
|
||||
credManager.clearCredentialState(ClearCredentialStateRequest())
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
onSignOut()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("signout_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error.copy(alpha = 0.15f),
|
||||
contentColor = MaterialTheme.colorScheme.error
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ExitToApp,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Se déconnecter")
|
||||
Button(
|
||||
onClick = onSignInClick,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.testTag("signin_google_optional_button"),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.Login,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Se connecter avec Google (Optionnel)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.FileDownload
|
||||
import androidx.compose.material.icons.filled.FileUpload
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ThumbUp
|
||||
import androidx.compose.material3.Button
|
||||
@@ -52,7 +53,8 @@ fun WeeklyStatsScreen(
|
||||
weeklyStats: WeeklyStats,
|
||||
totalMealsCount: Int,
|
||||
onSaveCsvClick: () -> Unit,
|
||||
onShareCsvClick: () -> Unit
|
||||
onShareCsvClick: () -> Unit,
|
||||
onImportCsvClick: () -> Unit = {}
|
||||
) {
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
@@ -192,13 +194,33 @@ fun WeeklyStatsScreen(
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
Button(
|
||||
onClick = onImportCsvClick,
|
||||
modifier = Modifier
|
||||
.weight(1.1f)
|
||||
.testTag("stats_import_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.secondaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onSecondaryContainer
|
||||
)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.FileUpload,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Importer", maxLines = 1)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = onSaveCsvClick,
|
||||
enabled = totalMealsCount > 0,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.weight(1.1f)
|
||||
.testTag("stats_save_csv_button"),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
@@ -211,8 +233,8 @@ fun WeeklyStatsScreen(
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Enregistrer")
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Sauver", maxLines = 1)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
@@ -228,8 +250,8 @@ fun WeeklyStatsScreen(
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text("Partager")
|
||||
Spacer(modifier = Modifier.width(4.dp))
|
||||
Text("Partager", maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
package com.example.util
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
|
||||
data class CsvImportResult(
|
||||
val importedMeals: List<MealEntry>,
|
||||
val skippedDuplicatesCount: Int,
|
||||
val newFoodItems: List<MealFoodItem>
|
||||
)
|
||||
|
||||
object CsvImporter {
|
||||
|
||||
private val supportedDateFormats = listOf(
|
||||
SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH),
|
||||
SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH),
|
||||
SimpleDateFormat("dd-MM-yyyy", Locale.FRENCH),
|
||||
SimpleDateFormat("d/M/yyyy", Locale.FRENCH)
|
||||
)
|
||||
|
||||
private val supportedTimeFormats = listOf(
|
||||
SimpleDateFormat("HH:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("H:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
|
||||
)
|
||||
|
||||
suspend fun importFromUri(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
existingMeals: List<MealEntry>
|
||||
): Result<CsvImportResult> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
context.contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||
parseCsvStream(inputStream, existingMeals)
|
||||
} ?: Result.failure(IllegalStateException("Impossible d'ouvrir le fichier CSV"))
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
fun parseCsvStream(
|
||||
inputStream: InputStream,
|
||||
existingMeals: List<MealEntry>
|
||||
): Result<CsvImportResult> {
|
||||
return try {
|
||||
val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))
|
||||
val lines = parseCsvRecords(reader)
|
||||
if (lines.isEmpty()) {
|
||||
return Result.failure(IllegalArgumentException("Le fichier CSV est vide"))
|
||||
}
|
||||
|
||||
val headerRow = lines[0]
|
||||
val colIndexMap = mapHeaders(headerRow)
|
||||
|
||||
val parsedMeals = mutableListOf<MealEntry>()
|
||||
var skippedDuplicates = 0
|
||||
val discoveredFoodItems = mutableListOf<MealFoodItem>()
|
||||
|
||||
// Index existing meals by (minuteTimestamp, mealType)
|
||||
val existingFingerprints = existingMeals.map { meal ->
|
||||
buildFingerprint(meal.mealTimestamp, meal.mealType)
|
||||
}.toMutableSet()
|
||||
|
||||
for (rowIndex in 1 until lines.size) {
|
||||
val row = lines[rowIndex]
|
||||
if (row.all { it.isBlank() }) continue
|
||||
|
||||
val dateStr = getColValue(row, colIndexMap["date"])
|
||||
val timeStr = getColValue(row, colIndexMap["time"])
|
||||
val mealTypeRaw = getColValue(row, colIndexMap["meal_type"])
|
||||
val hungerRaw = getColValue(row, colIndexMap["hunger"])
|
||||
val satietyRaw = getColValue(row, colIndexMap["satiety"])
|
||||
val foodsRaw = getColValue(row, colIndexMap["foods"])
|
||||
val note = getColValue(row, colIndexMap["note"])
|
||||
|
||||
val timestamp = parseTimestamp(dateStr, timeStr) ?: System.currentTimeMillis()
|
||||
val mealType = parseMealType(mealTypeRaw)
|
||||
val hunger = hungerRaw.toIntOrNull()?.coerceIn(1, 10) ?: 5
|
||||
val satiety = satietyRaw.toIntOrNull()?.coerceIn(1, 10) ?: 7
|
||||
|
||||
val fingerprint = buildFingerprint(timestamp, mealType.name)
|
||||
if (existingFingerprints.contains(fingerprint)) {
|
||||
skippedDuplicates++
|
||||
continue
|
||||
}
|
||||
|
||||
val foodItems = parseFoodItems(foodsRaw)
|
||||
discoveredFoodItems.addAll(foodItems)
|
||||
|
||||
val newMeal = MealEntry(
|
||||
id = "local_imp_${UUID.randomUUID().toString().take(8)}",
|
||||
userId = "",
|
||||
mealType = mealType.name,
|
||||
mealTimestamp = timestamp,
|
||||
hungerBefore = hunger,
|
||||
satietyAfter = satiety,
|
||||
note = note,
|
||||
foodItemsSerialized = foodItems.map { it.serialize() },
|
||||
photosBase64 = emptyList()
|
||||
)
|
||||
|
||||
parsedMeals.add(newMeal)
|
||||
existingFingerprints.add(fingerprint)
|
||||
}
|
||||
|
||||
Result.success(
|
||||
CsvImportResult(
|
||||
importedMeals = parsedMeals,
|
||||
skippedDuplicatesCount = skippedDuplicates,
|
||||
newFoodItems = discoveredFoodItems.distinctBy { it.name.lowercase().trim() }
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildFingerprint(timestamp: Long, mealType: String): String {
|
||||
val minute = timestamp / 60_000
|
||||
return "${mealType.uppercase()}_$minute"
|
||||
}
|
||||
|
||||
private fun mapHeaders(headerRow: List<String>): Map<String, Int> {
|
||||
val map = mutableMapOf<String, Int>()
|
||||
for ((index, rawCol) in headerRow.withIndex()) {
|
||||
val col = java.text.Normalizer.normalize(rawCol.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD)
|
||||
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
|
||||
|
||||
when {
|
||||
col == "date" -> map["date"] = index
|
||||
col.contains("heure") || col == "time" -> map["time"] = index
|
||||
col.contains("type") -> map["meal_type"] = index
|
||||
col.contains("faim") && !col.contains("ressenti") -> map["hunger"] = index
|
||||
col.contains("satiete") && !col.contains("ressenti") -> map["satiety"] = index
|
||||
col.contains("aliment") || col.contains("plat") -> map["foods"] = index
|
||||
col.contains("note") || col.contains("commentaire") -> map["note"] = index
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
private fun getColValue(row: List<String>, colIndex: Int?): String {
|
||||
return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else ""
|
||||
}
|
||||
|
||||
private fun parseTimestamp(dateStr: String, timeStr: String): Long? {
|
||||
if (dateStr.isBlank()) return null
|
||||
|
||||
var parsedDate: Date? = null
|
||||
for (df in supportedDateFormats) {
|
||||
try {
|
||||
parsedDate = df.parse(dateStr.trim())
|
||||
if (parsedDate != null) break
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
if (parsedDate == null) return null
|
||||
|
||||
val cal = Calendar.getInstance().apply { time = parsedDate }
|
||||
|
||||
if (timeStr.isNotBlank()) {
|
||||
for (tf in supportedTimeFormats) {
|
||||
try {
|
||||
val parsedTime = tf.parse(timeStr.trim())
|
||||
if (parsedTime != null) {
|
||||
val timeCal = Calendar.getInstance().apply { time = parsedTime }
|
||||
cal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY))
|
||||
cal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE))
|
||||
cal.set(Calendar.SECOND, 0)
|
||||
cal.set(Calendar.MILLISECOND, 0)
|
||||
break
|
||||
}
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
return cal.timeInMillis
|
||||
}
|
||||
|
||||
private fun parseMealType(raw: String): MealType {
|
||||
val clean = java.text.Normalizer.normalize(raw.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD)
|
||||
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
|
||||
|
||||
return when {
|
||||
clean.contains("petit") || clean.contains("breakfast") -> MealType.BREAKFAST
|
||||
clean.contains("dej") || clean.contains("lunch") || clean.contains("midi") -> MealType.LUNCH
|
||||
clean.contains("collat") || clean.contains("gout") || clean.contains("snack") -> MealType.SNACK
|
||||
clean.contains("din") || clean.contains("dinner") || clean.contains("soir") || clean.contains("souper") -> MealType.DINNER
|
||||
else -> MealType.LUNCH
|
||||
}
|
||||
}
|
||||
|
||||
fun parseFoodItems(raw: String): List<MealFoodItem> {
|
||||
val trimmed = raw.trim()
|
||||
if (trimmed.isEmpty()) return emptyList()
|
||||
|
||||
// Delimiters between items can be ';' or '|' (or ',' if not surrounded by parenthesis)
|
||||
val tokens = if (trimmed.contains(";")) {
|
||||
trimmed.split(";").map { it.trim() }
|
||||
} else if (trimmed.contains("|") && !trimmed.contains("•")) {
|
||||
// Check if serialized pipe format (name|weight|unit) or multi items
|
||||
if (trimmed.count { it == '|' } in 1..2 && !trimmed.contains("g") && !trimmed.contains("ml")) {
|
||||
listOf(trimmed)
|
||||
} else {
|
||||
trimmed.split("|").map { it.trim() }
|
||||
}
|
||||
} else {
|
||||
listOf(trimmed)
|
||||
}
|
||||
|
||||
val items = mutableListOf<MealFoodItem>()
|
||||
for (token in tokens) {
|
||||
val itemStr = token.trim()
|
||||
if (itemStr.isEmpty()) continue
|
||||
|
||||
// 1. Try serialized format "name|weight|unit"
|
||||
val deserialized = MealFoodItem.deserialize(itemStr)
|
||||
if (deserialized != null && deserialized.name != itemStr) {
|
||||
items.add(deserialized)
|
||||
continue
|
||||
}
|
||||
|
||||
// 2. Parse formatted string like "Saumon grillé (150 g)" or "Riz basmati • 200 g" or "Pomme (1 portion)"
|
||||
val regex = Regex("""^(.*?)(?:\s*(?:\(|\•|-)\s*(\d+(?:[.,]\d+)?)\s*(g|ml|portions?|portion)?\s*\)?)?$""", RegexOption.IGNORE_CASE)
|
||||
val match = regex.find(itemStr)
|
||||
if (match != null) {
|
||||
val name = match.groupValues[1].trim()
|
||||
val weightStr = match.groupValues.getOrNull(2)?.replace(",", ".")?.trim()
|
||||
val weight = weightStr?.toDoubleOrNull()
|
||||
val unitRaw = match.groupValues.getOrNull(3)?.lowercase(Locale.FRENCH)?.trim().orEmpty()
|
||||
val unit = when {
|
||||
unitRaw.startsWith("ml") -> FoodUnit.ML
|
||||
unitRaw.startsWith("portion") -> FoodUnit.PORTION
|
||||
else -> FoodUnit.G
|
||||
}
|
||||
if (name.isNotEmpty()) {
|
||||
items.add(MealFoodItem(name = name, weight = weight, unit = unit))
|
||||
}
|
||||
} else {
|
||||
items.add(MealFoodItem(name = itemStr, weight = null, unit = FoodUnit.G))
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
/**
|
||||
* Robust CSV record splitter supporting quotes, commas, semicolons, and UTF-8 BOM.
|
||||
*/
|
||||
fun parseCsvRecords(reader: BufferedReader): List<List<String>> {
|
||||
val records = mutableListOf<List<String>>()
|
||||
var detectedDelimiter = ','
|
||||
|
||||
var firstLine: String? = reader.readLine() ?: return emptyList()
|
||||
// Strip BOM if present
|
||||
if (firstLine != null && firstLine.startsWith("\uFEFF")) {
|
||||
firstLine = firstLine.substring(1)
|
||||
}
|
||||
|
||||
// Auto-detect delimiter from the first line (count ; vs , outside quotes)
|
||||
val semicolonCount = firstLine?.count { it == ';' } ?: 0
|
||||
val commaCount = firstLine?.count { it == ',' } ?: 0
|
||||
if (semicolonCount > commaCount) {
|
||||
detectedDelimiter = ';'
|
||||
}
|
||||
|
||||
val fullText = StringBuilder()
|
||||
if (firstLine != null) {
|
||||
fullText.append(firstLine).append('\n')
|
||||
}
|
||||
var line: String? = reader.readLine()
|
||||
while (line != null) {
|
||||
fullText.append(line).append('\n')
|
||||
line = reader.readLine()
|
||||
}
|
||||
|
||||
val text = fullText.toString()
|
||||
val currentField = StringBuilder()
|
||||
val currentRecord = mutableListOf<String>()
|
||||
var inQuotes = false
|
||||
var i = 0
|
||||
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
|
||||
if (c == '"') {
|
||||
if (inQuotes && i + 1 < text.length && text[i + 1] == '"') {
|
||||
// Escaped quote ("")
|
||||
currentField.append('"')
|
||||
i++
|
||||
} else {
|
||||
inQuotes = !inQuotes
|
||||
}
|
||||
} else if (c == detectedDelimiter && !inQuotes) {
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
currentField.clear()
|
||||
} else if ((c == '\r' || c == '\n') && !inQuotes) {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') {
|
||||
i++
|
||||
}
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
currentField.clear()
|
||||
if (currentRecord.any { it.isNotEmpty() }) {
|
||||
records.add(currentRecord.toList())
|
||||
}
|
||||
currentRecord.clear()
|
||||
} else {
|
||||
currentField.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (currentField.isNotEmpty() || currentRecord.isNotEmpty()) {
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
if (currentRecord.any { it.isNotEmpty() }) {
|
||||
records.add(currentRecord.toList())
|
||||
}
|
||||
}
|
||||
|
||||
return records
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.example.util
|
||||
|
||||
import android.accounts.Account
|
||||
import android.content.Context
|
||||
import com.example.R
|
||||
import com.google.android.gms.auth.GoogleAuthUtil
|
||||
import com.google.android.gms.auth.UserRecoverableAuthException
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignInClient
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
||||
import com.google.android.gms.common.api.Scope
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
object GoogleSheetsAuthHelper {
|
||||
|
||||
const val SCOPE_SPREADSHEETS_URL = "https://www.googleapis.com/auth/spreadsheets"
|
||||
const val SCOPE_DRIVE_FILE_URL = "https://www.googleapis.com/auth/drive.file"
|
||||
|
||||
val SCOPE_SPREADSHEETS = Scope(SCOPE_SPREADSHEETS_URL)
|
||||
val SCOPE_DRIVE_FILE = Scope(SCOPE_DRIVE_FILE_URL)
|
||||
|
||||
const val OAUTH_SCOPE_STRING = "oauth2:$SCOPE_SPREADSHEETS_URL $SCOPE_DRIVE_FILE_URL"
|
||||
|
||||
fun getGoogleSignInClient(context: Context): GoogleSignInClient {
|
||||
val serverClientId = try {
|
||||
context.getString(R.string.default_web_client_id)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||
.requestEmail()
|
||||
.requestScopes(SCOPE_SPREADSHEETS, SCOPE_DRIVE_FILE)
|
||||
|
||||
if (!serverClientId.isNullOrBlank()) {
|
||||
gsoBuilder.requestIdToken(serverClientId)
|
||||
}
|
||||
|
||||
return GoogleSignIn.getClient(context, gsoBuilder.build())
|
||||
}
|
||||
|
||||
suspend fun getAccessToken(context: Context): Result<String> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
|
||||
if (email.isNullOrBlank()) {
|
||||
return@withContext Result.failure(
|
||||
IllegalStateException("Aucun compte Google connecté. Veuillez vous connecter pour synchroniser avec Google Sheets.")
|
||||
)
|
||||
}
|
||||
|
||||
val account = Account(email, "com.google")
|
||||
val token = GoogleAuthUtil.getToken(context, account, OAUTH_SCOPE_STRING)
|
||||
Result.success(token)
|
||||
} catch (e: UserRecoverableAuthException) {
|
||||
// Must be handled by prompting user via e.intent
|
||||
Result.failure(e)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.example.util
|
||||
|
||||
import com.example.data.model.HungerSatietyScale
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object GoogleSheetsDataFormatter {
|
||||
|
||||
val HEADERS: List<String> = listOf(
|
||||
"Date",
|
||||
"Heure",
|
||||
"Type de repas",
|
||||
"Faim avant (/10)",
|
||||
"Ressenti faim",
|
||||
"Satiété après (/10)",
|
||||
"Ressenti satiété",
|
||||
"Aliments & Poids",
|
||||
"Note globale",
|
||||
"Photos jointes"
|
||||
)
|
||||
|
||||
fun formatMealsToRows(meals: List<MealEntry>): List<List<Any>> {
|
||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
||||
|
||||
val rows = mutableListOf<List<Any>>()
|
||||
// Header row
|
||||
rows.add(HEADERS)
|
||||
|
||||
// Sorted by descending timestamp (most recent first)
|
||||
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
||||
|
||||
for (meal in sortedMeals) {
|
||||
val dateObj = Date(meal.mealTimestamp)
|
||||
val dateStr = dateFormat.format(dateObj)
|
||||
val timeStr = timeFormat.format(dateObj)
|
||||
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
||||
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
||||
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
||||
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
||||
val cleanNote = meal.note.replace("\r\n", " ").replace("\n", " ").trim()
|
||||
val photosCount = meal.photosBase64.size
|
||||
|
||||
rows.add(
|
||||
listOf(
|
||||
dateStr,
|
||||
timeStr,
|
||||
mealTypeLabel,
|
||||
meal.hungerBefore,
|
||||
hungerLabel,
|
||||
meal.satietyAfter,
|
||||
satietyLabel,
|
||||
foodsFormatted,
|
||||
cleanNote,
|
||||
photosCount
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.example.util
|
||||
|
||||
import android.util.Log
|
||||
import com.example.data.model.MealEntry
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
data class GoogleSheetsSyncResult(
|
||||
val spreadsheetId: String,
|
||||
val spreadsheetUrl: String,
|
||||
val mealsCount: Int,
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
object GoogleSheetsSyncService {
|
||||
|
||||
private const val TAG = "GoogleSheetsSync"
|
||||
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
|
||||
|
||||
private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
||||
|
||||
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.readTimeout(20, TimeUnit.SECONDS)
|
||||
.writeTimeout(20, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
suspend fun getOrCreateSpreadsheet(
|
||||
accessToken: String,
|
||||
cachedSpreadsheetId: String? = null
|
||||
): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
// 1. If we have a cached spreadsheetId, verify it still exists and is accessible
|
||||
if (!cachedSpreadsheetId.isNullOrBlank()) {
|
||||
val checkRequest = Request.Builder()
|
||||
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl")
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(checkRequest).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
val bodyStr = response.body?.string().orEmpty()
|
||||
val json = JSONObject(bodyStr)
|
||||
val id = json.optString("spreadsheetId", cachedSpreadsheetId)
|
||||
val url = json.optString(
|
||||
"spreadsheetUrl",
|
||||
"https://docs.google.com/spreadsheets/d/$id/edit"
|
||||
)
|
||||
return@withContext Result.success(Pair(id, url))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Cached spreadsheet check failed, searching Drive: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Search Drive for existing spreadsheet named "Satiéa — Journal des Repas"
|
||||
val query = "name = '$SPREADSHEET_TITLE' and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false"
|
||||
val encodedQuery = URLEncoder.encode(query, "UTF-8")
|
||||
val driveSearchUrl = "https://www.googleapis.com/drive/v3/files?q=$encodedQuery&fields=files(id,name,webViewLink)"
|
||||
|
||||
val searchRequest = Request.Builder()
|
||||
.url(driveSearchUrl)
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
okHttpClient.newCall(searchRequest).execute().use { searchResponse ->
|
||||
if (searchResponse.isSuccessful) {
|
||||
val body = searchResponse.body?.string().orEmpty()
|
||||
val json = JSONObject(body)
|
||||
val files = json.optJSONArray("files")
|
||||
if (files != null && files.length() > 0) {
|
||||
val firstFile = files.getJSONObject(0)
|
||||
val id = firstFile.getString("id")
|
||||
val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||
return@withContext Result.success(Pair(id, link))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Not found, create a new Google Sheet
|
||||
val createPayload = JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", SPREADSHEET_TITLE)
|
||||
})
|
||||
put("sheets", JSONArray().apply {
|
||||
put(JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", "Journal")
|
||||
put("gridProperties", JSONObject().apply {
|
||||
put("frozenRowCount", 1)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
val createRequest = Request.Builder()
|
||||
.url("https://sheets.googleapis.com/v4/spreadsheets")
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.post(createPayload.toString().toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
|
||||
okHttpClient.newCall(createRequest).execute().use { response ->
|
||||
val bodyStr = response.body?.string().orEmpty()
|
||||
if (!response.isSuccessful) {
|
||||
val errorMsg = parseErrorMessage(bodyStr, response.code)
|
||||
return@withContext Result.failure(IllegalStateException("Création du classeur Google Sheets échouée: $errorMsg"))
|
||||
}
|
||||
|
||||
val json = JSONObject(bodyStr)
|
||||
val id = json.getString("spreadsheetId")
|
||||
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||
Result.success(Pair(id, url))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error in getOrCreateSpreadsheet", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun syncMeals(
|
||||
accessToken: String,
|
||||
spreadsheetId: String,
|
||||
meals: List<MealEntry>
|
||||
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(meals)
|
||||
|
||||
// 1. Clear previous content to remove stale deleted rows
|
||||
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1:Z:clear"
|
||||
val clearRequest = Request.Builder()
|
||||
.url(clearUrl)
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.post("{}".toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(clearRequest).execute().close()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Clear range warning: ${e.message}")
|
||||
}
|
||||
|
||||
// 2. Put formatted values starting at A1
|
||||
val jsonValuesArray = JSONArray()
|
||||
for (row in rows) {
|
||||
val rowArray = JSONArray()
|
||||
for (item in row) {
|
||||
rowArray.put(item)
|
||||
}
|
||||
jsonValuesArray.put(rowArray)
|
||||
}
|
||||
|
||||
val writePayload = JSONObject().apply {
|
||||
put("range", "A1")
|
||||
put("majorDimension", "ROWS")
|
||||
put("values", jsonValuesArray)
|
||||
}
|
||||
|
||||
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1?valueInputOption=USER_ENTERED"
|
||||
val writeRequest = Request.Builder()
|
||||
.url(writeUrl)
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.put(writePayload.toString().toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
|
||||
okHttpClient.newCall(writeRequest).execute().use { response ->
|
||||
val bodyStr = response.body?.string().orEmpty()
|
||||
if (!response.isSuccessful) {
|
||||
val errorMsg = parseErrorMessage(bodyStr, response.code)
|
||||
return@withContext Result.failure(IllegalStateException("Mise à jour de la feuille Google Sheets échouée: $errorMsg"))
|
||||
}
|
||||
|
||||
val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit"
|
||||
Result.success(
|
||||
GoogleSheetsSyncResult(
|
||||
spreadsheetId = spreadsheetId,
|
||||
spreadsheetUrl = spreadsheetUrl,
|
||||
mealsCount = meals.size
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error in syncMeals", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseErrorMessage(body: String, statusCode: Int): String {
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val error = json.optJSONObject("error")
|
||||
val message = error?.optString("message")
|
||||
if (!message.isNullOrBlank()) message else "Code HTTP $statusCode"
|
||||
} catch (_: Exception) {
|
||||
"Code HTTP $statusCode"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.9,2 2,2zM18,16v-5c0,-3.07 -1.63,-5.64 -4.5,-6.32V4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.64,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2zM16,17H8v-6c0,-2.48 1.51,-4.5 4,-4.5s4,2.02 4,4.5v6z"/>
|
||||
</vector>
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.example
|
||||
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.util.CsvImporter
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Locale
|
||||
|
||||
class CsvImporterTest {
|
||||
|
||||
@Test
|
||||
fun testParseFoodItemsFormatted() {
|
||||
val raw = "Saumon grillé (150 g) ; Riz basmati (180 g) ; Pomme (1 portion)"
|
||||
val parsed = CsvImporter.parseFoodItems(raw)
|
||||
|
||||
assertEquals(3, parsed.size)
|
||||
assertEquals("Saumon grillé", parsed[0].name)
|
||||
assertEquals(150.0, parsed[0].weight ?: 0.0, 0.001)
|
||||
assertEquals(FoodUnit.G, parsed[0].unit)
|
||||
|
||||
assertEquals("Riz basmati", parsed[1].name)
|
||||
assertEquals(180.0, parsed[1].weight ?: 0.0, 0.001)
|
||||
assertEquals(FoodUnit.G, parsed[1].unit)
|
||||
|
||||
assertEquals("Pomme", parsed[2].name)
|
||||
assertEquals(1.0, parsed[2].weight ?: 0.0, 0.001)
|
||||
assertEquals(FoodUnit.PORTION, parsed[2].unit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testParseCsvStreamStandard() {
|
||||
val csv = """
|
||||
Date,Heure,Type de repas,Faim avant (/10),Ressenti faim,Satiété après (/10),Ressenti satiété,Aliments & Poids,Note globale,Photos jointes
|
||||
08/11/2026,12:30,Déjeuner,6,"Faim présente",7,"Idéale","Riz basmati (150 g) ; Poulet (120 g)","Déjeuner au calme",0
|
||||
08/11/2026,20:00,Dîner,4,"Petite faim",6,"Légère","Soupe de légumes (250 ml)","Repas léger",0
|
||||
""".trimIndent()
|
||||
|
||||
val stream = ByteArrayInputStream(csv.toByteArray(Charsets.UTF_8))
|
||||
val result = CsvImporter.parseCsvStream(stream, emptyList()).getOrThrow()
|
||||
|
||||
assertEquals(2, result.importedMeals.size)
|
||||
assertEquals(0, result.skippedDuplicatesCount)
|
||||
assertEquals(3, result.newFoodItems.size) // Riz basmati, Poulet, Soupe de légumes
|
||||
|
||||
val firstMeal = result.importedMeals[0]
|
||||
assertEquals(MealType.LUNCH.name, firstMeal.mealType)
|
||||
assertEquals(6, firstMeal.hungerBefore)
|
||||
assertEquals(7, firstMeal.satietyAfter)
|
||||
assertEquals(2, firstMeal.parsedFoodItems().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDeduplicationIgnoresExistingMeal() {
|
||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.FRENCH)
|
||||
val timestamp = dateFormat.parse("08/11/2026 12:30")!!.time
|
||||
|
||||
val existingMeal = MealEntry(
|
||||
id = "existing_1",
|
||||
mealType = MealType.LUNCH.name,
|
||||
mealTimestamp = timestamp
|
||||
)
|
||||
|
||||
val csv = """
|
||||
Date,Heure,Type de repas,Faim avant (/10),Satiété après (/10),Aliments & Poids,Note globale
|
||||
08/11/2026,12:30,Déjeuner,6,7,"Riz basmati (150 g)","Déjeuner",0
|
||||
08/11/2026,20:00,Dîner,4,6,"Soupe (250 ml)","Repas",0
|
||||
""".trimIndent()
|
||||
|
||||
val stream = ByteArrayInputStream(csv.toByteArray(Charsets.UTF_8))
|
||||
val result = CsvImporter.parseCsvStream(stream, listOf(existingMeal)).getOrThrow()
|
||||
|
||||
// 1 duplicate skipped, 1 imported
|
||||
assertEquals(1, result.importedMeals.size)
|
||||
assertEquals(1, result.skippedDuplicatesCount)
|
||||
assertEquals(MealType.DINNER.name, result.importedMeals[0].mealType)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFrenchSemicolonCsvDelimiter() {
|
||||
val csv = """
|
||||
Date;Heure;Type de repas;Faim avant (/10);Satiété après (/10);Aliments & Poids;Note globale
|
||||
08/11/2026;12:30;Déjeuner;7;8;Pavé de saumon (150 g);Très bon
|
||||
""".trimIndent()
|
||||
|
||||
val stream = ByteArrayInputStream(csv.toByteArray(Charsets.UTF_8))
|
||||
val result = CsvImporter.parseCsvStream(stream, emptyList()).getOrThrow()
|
||||
|
||||
assertEquals(1, result.importedMeals.size)
|
||||
assertEquals("Très bon", result.importedMeals[0].note)
|
||||
assertEquals(1, result.importedMeals[0].parsedFoodItems().size)
|
||||
assertEquals("Pavé de saumon", result.importedMeals[0].parsedFoodItems()[0].name)
|
||||
}
|
||||
}
|
||||
@@ -9,13 +9,13 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [36])
|
||||
@Config(sdk = [34])
|
||||
class ExampleRobolectricTest {
|
||||
|
||||
@Test
|
||||
fun `read string from context`() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val appName = context.getString(R.string.app_name)
|
||||
assertEquals("My Application", appName)
|
||||
assertEquals("Satiéa", appName)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.example
|
||||
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.util.GoogleSheetsDataFormatter
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.util.Calendar
|
||||
|
||||
class GoogleSheetsDataFormatterTest {
|
||||
|
||||
@Test
|
||||
fun `formatMealsToRows with empty list returns only header row`() {
|
||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(emptyList())
|
||||
assertEquals(1, rows.size)
|
||||
assertEquals(GoogleSheetsDataFormatter.HEADERS, rows[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `formatMealsToRows formats meal fields accurately and sorts chronologically descending`() {
|
||||
val cal1 = Calendar.getInstance().apply {
|
||||
set(2026, Calendar.MARCH, 15, 12, 30, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}
|
||||
val cal2 = Calendar.getInstance().apply {
|
||||
set(2026, Calendar.MARCH, 15, 20, 0, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}
|
||||
|
||||
val meal1 = MealEntry(
|
||||
id = "meal-1",
|
||||
mealType = MealType.LUNCH.name,
|
||||
mealTimestamp = cal1.timeInMillis,
|
||||
hungerBefore = 3,
|
||||
satietyAfter = 7,
|
||||
note = "Repas calme et savoureux",
|
||||
foodItemsSerialized = listOf(
|
||||
MealFoodItem("Riz complet", 150.0, FoodUnit.G).serialize(),
|
||||
MealFoodItem("Saumon", 120.0, FoodUnit.G).serialize()
|
||||
),
|
||||
photosBase64 = listOf("photo1")
|
||||
)
|
||||
|
||||
val meal2 = MealEntry(
|
||||
id = "meal-2",
|
||||
mealType = MealType.DINNER.name,
|
||||
mealTimestamp = cal2.timeInMillis,
|
||||
hungerBefore = 4,
|
||||
satietyAfter = 8,
|
||||
note = "Dîner léger en famille",
|
||||
foodItemsSerialized = listOf(
|
||||
MealFoodItem("Soupe de légumes", 250.0, FoodUnit.ML).serialize()
|
||||
),
|
||||
photosBase64 = emptyList()
|
||||
)
|
||||
|
||||
// Pass in reverse order to test sorting
|
||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(listOf(meal1, meal2))
|
||||
|
||||
// 1 header + 2 data rows
|
||||
assertEquals(3, rows.size)
|
||||
|
||||
// Row 0: Headers
|
||||
assertEquals(10, rows[0].size)
|
||||
assertEquals("Date", rows[0][0])
|
||||
assertEquals("Photos jointes", rows[0][9])
|
||||
|
||||
// Row 1: Most recent meal (DINNER at 20:00)
|
||||
val dinnerRow = rows[1]
|
||||
assertEquals("15/03/2026", dinnerRow[0])
|
||||
assertEquals("20:00", dinnerRow[1])
|
||||
assertEquals("Dîner", dinnerRow[2])
|
||||
assertEquals(4, dinnerRow[3])
|
||||
assertEquals(8, dinnerRow[5])
|
||||
assertTrue((dinnerRow[7] as String).contains("Soupe de légumes"))
|
||||
assertEquals("Dîner léger en famille", dinnerRow[8])
|
||||
assertEquals(0, dinnerRow[9])
|
||||
|
||||
// Row 2: Earlier meal (LUNCH at 12:30)
|
||||
val lunchRow = rows[2]
|
||||
assertEquals("15/03/2026", lunchRow[0])
|
||||
assertEquals("12:30", lunchRow[1])
|
||||
assertEquals("Déjeuner", lunchRow[2])
|
||||
assertEquals(3, lunchRow[3])
|
||||
assertEquals(7, lunchRow[5])
|
||||
val lunchFoods = lunchRow[7] as String
|
||||
assertTrue(lunchFoods.contains("Riz complet"))
|
||||
assertTrue(lunchFoods.contains("Saumon"))
|
||||
assertEquals("Repas calme et savoureux", lunchRow[8])
|
||||
assertEquals(1, lunchRow[9])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.example
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.example.data.local.AppDatabase
|
||||
import com.example.data.local.LocalCustomFoodEntity
|
||||
import com.example.data.local.LocalMealDao
|
||||
import com.example.data.local.LocalMealEntity
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class LocalDatabaseTest {
|
||||
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var dao: LocalMealDao
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
dao = db.mealDao()
|
||||
}
|
||||
|
||||
@After
|
||||
fun teardown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testInsertAndObserveMeal() = runBlocking {
|
||||
val meal = MealEntry(
|
||||
id = "local_test_1",
|
||||
mealType = MealType.LUNCH.name,
|
||||
mealTimestamp = 1700000000000L,
|
||||
hungerBefore = 6,
|
||||
satietyAfter = 7,
|
||||
note = "Repas calme",
|
||||
foodItemsSerialized = listOf(
|
||||
MealFoodItem("Riz", 150.0, FoodUnit.G).serialize()
|
||||
)
|
||||
)
|
||||
|
||||
val entity = LocalMealEntity.fromMealEntry(meal)
|
||||
dao.insertMeal(entity)
|
||||
|
||||
val allMeals = dao.observeAllMeals().first()
|
||||
assertEquals(1, allMeals.size)
|
||||
val readMeal = allMeals[0].toMealEntry()
|
||||
assertEquals("local_test_1", readMeal.id)
|
||||
assertEquals(MealType.LUNCH.name, readMeal.mealType)
|
||||
assertEquals(6, readMeal.hungerBefore)
|
||||
assertEquals(7, readMeal.satietyAfter)
|
||||
assertEquals("Repas calme", readMeal.note)
|
||||
assertEquals(1, readMeal.parsedFoodItems().size)
|
||||
assertEquals("Riz", readMeal.parsedFoodItems()[0].name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDeleteMeal() = runBlocking {
|
||||
val entity = LocalMealEntity(
|
||||
id = "to_delete",
|
||||
mealType = MealType.DINNER.name,
|
||||
mealTimestamp = System.currentTimeMillis(),
|
||||
hungerBefore = 5,
|
||||
satietyAfter = 6
|
||||
)
|
||||
dao.insertMeal(entity)
|
||||
assertNotNull(dao.getMealById("to_delete"))
|
||||
|
||||
dao.deleteMealById("to_delete")
|
||||
assertNull(dao.getMealById("to_delete"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testInsertAndObserveCustomFoods() = runBlocking {
|
||||
val food1 = LocalCustomFoodEntity.create("Granola maison", FoodUnit.G)
|
||||
val food2 = LocalCustomFoodEntity.create("Smoothie mangue", FoodUnit.ML)
|
||||
|
||||
dao.insertCustomFoods(listOf(food1, food2))
|
||||
|
||||
val allFoods = dao.observeAllCustomFoods().first()
|
||||
assertEquals(2, allFoods.size)
|
||||
val names = allFoods.map { it.name }
|
||||
assertEquals(listOf("Granola maison", "Smoothie mangue"), names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.example
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.example.data.model.MealType
|
||||
import com.example.data.preferences.ReminderPreferencesManager
|
||||
import com.example.notification.MealNotificationManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class ReminderPreferencesTest {
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var prefs: ReminderPreferencesManager
|
||||
|
||||
@Before
|
||||
fun setup() {
|
||||
context = ApplicationProvider.getApplicationContext()
|
||||
prefs = ReminderPreferencesManager.getInstance(context)
|
||||
prefs.clearAll()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDefaultReminderValues() {
|
||||
assertTrue(prefs.isReminderEnabled(MealType.BREAKFAST))
|
||||
assertTrue(prefs.isReminderEnabled(MealType.LUNCH))
|
||||
assertFalse(prefs.isReminderEnabled(MealType.SNACK))
|
||||
assertTrue(prefs.isReminderEnabled(MealType.DINNER))
|
||||
|
||||
val (lunchHour, lunchMinute) = prefs.getReminderTime(MealType.LUNCH)
|
||||
assertEquals(12, lunchHour)
|
||||
assertEquals(30, lunchMinute)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testUpdateAndPersistReminderValues() {
|
||||
prefs.setReminderEnabled(MealType.SNACK, true)
|
||||
assertTrue(prefs.isReminderEnabled(MealType.SNACK))
|
||||
|
||||
prefs.setReminderTime(MealType.SNACK, 16, 45)
|
||||
val (hour, minute) = prefs.getReminderTime(MealType.SNACK)
|
||||
assertEquals(16, hour)
|
||||
assertEquals(45, minute)
|
||||
|
||||
prefs.setPromptedNotificationPermission(true)
|
||||
assertTrue(prefs.hasPromptedNotificationPermission())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCreateNotificationChannel() {
|
||||
MealNotificationManager.createNotificationChannel(context)
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager
|
||||
val channel = notificationManager.getNotificationChannel(MealNotificationManager.CHANNEL_ID)
|
||||
assertEquals(MealNotificationManager.CHANNEL_NAME, channel.name)
|
||||
assertEquals(android.app.NotificationManager.IMPORTANCE_HIGH, channel.importance)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user