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:
bleackstorm committed 2026-11-08 16:57:11 +01:00
1 parent f13d46f778
commit fe69d7621a
31 files changed
+2972 -350

No files matched your search

@@ -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)
}
}
}