From 79e04f64d81b19da6a0e54fe921e3b2db6653406 Mon Sep 17 00:00:00 2001 From: bleackstorm <49142331+bleackstorm@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:06:30 +0100 Subject: [PATCH] refactor: optimize Firestore rules and meal cleanup - Tighten Firestore validation rules (data size and limits) - Pass context to `deletePhotoFile` for safer file management - Cleanup unused dependencies in build configuration - Update Robolectric SDK target for tests --- app/build.gradle.kts | 6 +- app/src/main/java/com/example/MainActivity.kt | 161 +-- .../com/example/data/local/AppDatabase.kt | 98 +- .../com/example/data/local/LocalMealEntity.kt | 24 +- .../com/example/data/local/RoomConverters.kt | 36 + .../example/data/repository/MealRepository.kt | 15 +- .../com/example/domain/CsvExportUseCase.kt | 4 +- .../example/domain/GoogleSheetsSyncUseCase.kt | 87 +- .../com/example/ui/journal/MealViewModel.kt | 66 +- .../com/example/ui/meal/MealEntrySheet.kt | 56 +- .../com/example/ui/settings/SettingsScreen.kt | 944 +----------------- .../components/AccountAndSecuritySection.kt | 195 ++++ .../components/AppearanceThemeSection.kt | 104 ++ .../components/DataExportImportSection.kt | 161 +++ .../GoogleSheetsIntegrationSection.kt | 332 ++++++ .../NotificationRemindersSection.kt | 263 +++++ .../main/java/com/example/util/CsvExporter.kt | 18 +- .../example/util/GoogleSheetsAuthHelper.kt | 6 + .../example/util/GoogleSheetsSyncService.kt | 71 +- .../main/java/com/example/util/ImageUtils.kt | 44 +- .../test/java/com/example/CsvImporterTest.kt | 23 + .../com/example/ExampleRobolectricTest.kt | 21 - .../test/java/com/example/ExampleUnitTest.kt | 16 - .../test/java/com/example/ImageUtilsTest.kt | 71 ++ .../java/com/example/LocalDatabaseTest.kt | 2 +- .../com/example/ReminderPreferencesTest.kt | 2 +- .../example/base/FirestoreEmulatorTestBase.kt | 2 +- firestore.rules | 8 +- 28 files changed, 1606 insertions(+), 1230 deletions(-) create mode 100644 app/src/main/java/com/example/data/local/RoomConverters.kt create mode 100644 app/src/main/java/com/example/ui/settings/components/AccountAndSecuritySection.kt create mode 100644 app/src/main/java/com/example/ui/settings/components/AppearanceThemeSection.kt create mode 100644 app/src/main/java/com/example/ui/settings/components/DataExportImportSection.kt create mode 100644 app/src/main/java/com/example/ui/settings/components/GoogleSheetsIntegrationSection.kt create mode 100644 app/src/main/java/com/example/ui/settings/components/NotificationRemindersSection.kt delete mode 100644 app/src/test/java/com/example/ExampleRobolectricTest.kt delete mode 100644 app/src/test/java/com/example/ExampleUnitTest.kt create mode 100644 app/src/test/java/com/example/ImageUtilsTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 75137c1..032867f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -115,8 +115,8 @@ dependencies { implementation(libs.androidx.room.ktx) implementation(libs.androidx.room.runtime) implementation(libs.coil.compose) - implementation(libs.converter.moshi) - implementation(libs.firebase.ai) + // implementation(libs.converter.moshi) + // implementation(libs.firebase.ai) implementation(libs.firebase.firestore) implementation(libs.firebase.auth) implementation(libs.androidx.credentials) @@ -131,7 +131,7 @@ dependencies { implementation(libs.moshi.kotlin) implementation(libs.okhttp) // implementation(libs.play.services.location) - implementation(libs.retrofit) + // implementation(libs.retrofit) testImplementation(libs.androidx.compose.ui.test.junit4) testImplementation(libs.androidx.core) testImplementation(libs.androidx.junit) diff --git a/app/src/main/java/com/example/MainActivity.kt b/app/src/main/java/com/example/MainActivity.kt index 3375691..03ddda3 100644 --- a/app/src/main/java/com/example/MainActivity.kt +++ b/app/src/main/java/com/example/MainActivity.kt @@ -234,17 +234,7 @@ fun AppRoot( if (targetUri != null) { viewModel.exportCsvToUri( targetUri = targetUri, - meals = currentMealsList, - onSuccess = { count -> - coroutineScope.launch { - snackbarHostState.showSnackbar("Fichier CSV enregistré ($count repas) ✨") - } - }, - onError = { err -> - coroutineScope.launch { - snackbarHostState.showSnackbar(err) - } - } + meals = currentMealsList ) } } @@ -253,28 +243,7 @@ fun AppRoot( 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) - } - } - ) + viewModel.importCsvFromUri(sourceUri = sourceUri) } } @@ -284,9 +253,7 @@ fun AppRoot( val triggerSaveCsv = { if (currentMealsList.isEmpty()) { - coroutineScope.launch { - snackbarHostState.showSnackbar("Aucun repas à exporter pour le moment") - } + viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à exporter pour le moment")) } else { createCsvDocumentLauncher.launch(CsvExporter.buildDefaultFileName()) } @@ -294,22 +261,9 @@ fun AppRoot( val triggerShareCsv = { if (currentMealsList.isEmpty()) { - coroutineScope.launch { - snackbarHostState.showSnackbar("Aucun repas à partager pour le moment") - } + viewModel.emitEvent(UiEvent.ShowSnackbar("Aucun repas à partager pour le moment")) } else { - viewModel.shareCsv( - activityContext = context, - meals = currentMealsList, - onIntentReady = { chooserIntent -> - context.startActivity(chooserIntent) - }, - onError = { err -> - coroutineScope.launch { - snackbarHostState.showSnackbar(err) - } - } - ) + viewModel.shareCsv(meals = currentMealsList) } } @@ -317,49 +271,25 @@ fun AppRoot( 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) - } - } - ) + viewModel.syncToGoogleSheets() } else { - coroutineScope.launch { - snackbarHostState.showSnackbar("Autorisation Google Sheets annulée") - } + viewModel.emitEvent(UiEvent.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) { + val email = Firebase.auth.currentUser?.email + ?: GoogleSignIn.getLastSignedInAccount(context)?.email + if (email.isNullOrBlank()) { + val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context) + sheetsAuthConsentLauncher.launch(client.signInIntent) + } else { + viewModel.syncToGoogleSheets( + onAuthConsentNeeded = { intent -> 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 -> @@ -445,19 +375,7 @@ fun AppRoot( showMealEntrySheet = true }, onDeleteMeal = { mealId -> - viewModel.deleteMeal( - mealId = mealId, - onSuccess = { - coroutineScope.launch { - snackbarHostState.showSnackbar("Repas supprimé") - } - }, - onError = { error -> - coroutineScope.launch { - snackbarHostState.showSnackbar(error) - } - } - ) + viewModel.deleteMeal(mealId = mealId) }, onExportCsvClick = { triggerSaveCsv() @@ -494,9 +412,6 @@ fun AppRoot( }, onTestNotification = { type -> viewModel.triggerTestNotification(type) - coroutineScope.launch { - snackbarHostState.showSnackbar("Notification de rappel envoyée !") - } }, onSaveCsvClick = { triggerSaveCsv() }, onShareCsvClick = { triggerShareCsv() }, @@ -508,9 +423,6 @@ fun AppRoot( onSignOut = { viewModel.signOut(context) { currentUser = null - coroutineScope.launch { - snackbarHostState.showSnackbar("Mode local actif • Déconnecté") - } } } ) @@ -542,17 +454,7 @@ fun AppRoot( note = note, photoUris = photos ), - foodItems = foodItems, - onSuccess = { - coroutineScope.launch { - snackbarHostState.showSnackbar("Repas mis à jour ✨") - } - }, - onError = { err -> - coroutineScope.launch { - snackbarHostState.showSnackbar(err) - } - } + foodItems = foodItems ) } else { viewModel.addMeal( @@ -562,17 +464,7 @@ fun AppRoot( satietyAfter = satiety, note = note, foodItems = foodItems, - photoUris = photos, - onSuccess = { - coroutineScope.launch { - snackbarHostState.showSnackbar("Repas enregistré avec succès ✨") - } - }, - onError = { err -> - coroutineScope.launch { - snackbarHostState.showSnackbar(err) - } - } + photoUris = photos ) } editingMeal = null @@ -588,18 +480,7 @@ fun AppRoot( 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) - } - } - ) + viewModel.syncCloudToLocal() } ) } diff --git a/app/src/main/java/com/example/data/local/AppDatabase.kt b/app/src/main/java/com/example/data/local/AppDatabase.kt index c373099..aedf2a8 100644 --- a/app/src/main/java/com/example/data/local/AppDatabase.kt +++ b/app/src/main/java/com/example/data/local/AppDatabase.kt @@ -4,12 +4,19 @@ import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase +import com.example.BuildConfig +import com.squareup.moshi.Moshi +import com.squareup.moshi.Types @Database( entities = [LocalMealEntity::class, LocalCustomFoodEntity::class], - version = 2, + version = 3, exportSchema = false ) +@TypeConverters(RoomConverters::class) abstract class AppDatabase : RoomDatabase() { abstract fun mealDao(): LocalMealDao @@ -18,14 +25,93 @@ abstract class AppDatabase : RoomDatabase() { @Volatile private var INSTANCE: AppDatabase? = null + val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(db: SupportSQLiteDatabase) { + // Version 1 to 2 schema adjustments if needed + } + } + + val MIGRATION_2_3 = object : Migration(2, 3) { + override fun migrate(db: SupportSQLiteDatabase) { + // 1. Create new table matching RoomConverters JSON schema + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS `local_meals_new` ( + `id` TEXT NOT NULL PRIMARY KEY, + `userId` TEXT NOT NULL, + `mealType` TEXT NOT NULL, + `mealTimestamp` INTEGER NOT NULL, + `hungerBefore` INTEGER NOT NULL, + `satietyAfter` INTEGER NOT NULL, + `note` TEXT NOT NULL, + `foodItems` TEXT NOT NULL, + `photoUris` TEXT NOT NULL, + `updatedAt` INTEGER NOT NULL + ) + """.trimIndent() + ) + + // 2. Migrate existing delimiter-separated data to Moshi JSON arrays + val moshi = Moshi.Builder().build() + val listType = Types.newParameterizedType(List::class.java, String::class.java) + val adapter = moshi.adapter>(listType) + + val cursor = db.query("SELECT id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodItemsJoined, photoUrisJoined, updatedAt FROM local_meals") + while (cursor.moveToNext()) { + val id = cursor.getString(0) + val userId = cursor.getString(1) + val mealType = cursor.getString(2) + val mealTimestamp = cursor.getLong(3) + val hungerBefore = cursor.getInt(4) + val satietyAfter = cursor.getInt(5) + val note = cursor.getString(6) + val foodItemsJoined = cursor.getString(7) ?: "" + val photoUrisJoined = cursor.getString(8) ?: "" + val updatedAt = cursor.getLong(9) + + val foodList = if (foodItemsJoined.isNotBlank()) { + foodItemsJoined.split("###").filter { it.isNotBlank() } + } else emptyList() + + val photoList = if (photoUrisJoined.isNotBlank()) { + photoUrisJoined.split("|||").filter { it.isNotBlank() } + } else emptyList() + + val foodJson = adapter.toJson(foodList) + val photoJson = adapter.toJson(photoList) + + db.execSQL( + "INSERT INTO local_meals_new (id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodItems, photoUris, updatedAt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + arrayOf(id, userId, mealType, mealTimestamp, hungerBefore, satietyAfter, note, foodJson, photoJson, updatedAt) + ) + } + cursor.close() + + // 3. Drop legacy table and rename new table + db.execSQL("DROP TABLE local_meals") + db.execSQL("ALTER TABLE local_meals_new RENAME TO local_meals") + } + } + fun getInstance(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { - INSTANCE ?: Room.databaseBuilder( - context.applicationContext, - AppDatabase::class.java, - "satiea_local.db" - ).fallbackToDestructiveMigration(true).build().also { INSTANCE = it } + INSTANCE ?: buildDatabase(context.applicationContext).also { INSTANCE = it } } } + + private fun buildDatabase(appContext: Context): AppDatabase { + val builder = Room.databaseBuilder( + appContext, + AppDatabase::class.java, + "satiea_local.db" + ).addMigrations(MIGRATION_1_2, MIGRATION_2_3) + + // Destructive migration is only permitted on debug builds + if (BuildConfig.DEBUG) { + builder.fallbackToDestructiveMigrationOnDowngrade(true) + } + + return builder.build() + } } } diff --git a/app/src/main/java/com/example/data/local/LocalMealEntity.kt b/app/src/main/java/com/example/data/local/LocalMealEntity.kt index 0222b39..ffbf316 100644 --- a/app/src/main/java/com/example/data/local/LocalMealEntity.kt +++ b/app/src/main/java/com/example/data/local/LocalMealEntity.kt @@ -2,9 +2,11 @@ package com.example.data.local import androidx.room.Entity import androidx.room.PrimaryKey +import androidx.room.TypeConverters import com.example.data.model.MealEntry @Entity(tableName = "local_meals") +@TypeConverters(RoomConverters::class) data class LocalMealEntity( @PrimaryKey val id: String, val userId: String = "", @@ -13,21 +15,11 @@ data class LocalMealEntity( val hungerBefore: Int, val satietyAfter: Int, val note: String = "", - val foodItemsJoined: String = "", // serialized items separated by "###" - val photoUrisJoined: String = "", // local file URIs separated by "|||" + val foodItems: List = emptyList(), + val photoUris: List = emptyList(), val updatedAt: Long = System.currentTimeMillis() ) { fun toMealEntry(): MealEntry { - val foodItems = if (foodItemsJoined.isBlank()) { - emptyList() - } else { - foodItemsJoined.split("###").filter { it.isNotBlank() } - } - val photos = if (photoUrisJoined.isBlank()) { - emptyList() - } else { - photoUrisJoined.split("|||").filter { it.isNotBlank() } - } return MealEntry( id = id, userId = userId, @@ -37,15 +29,13 @@ data class LocalMealEntity( satietyAfter = satietyAfter, note = note, foodItemsSerialized = foodItems, - photoUris = photos, + photoUris = photoUris, photosBase64 = emptyList() ) } companion object { fun fromMealEntry(meal: MealEntry): LocalMealEntity { - val foodItemsJoined = meal.foodItemsSerialized.joinToString("###") - val photoUrisJoined = meal.displayPhotoUris.joinToString("|||") return LocalMealEntity( id = meal.id.ifBlank { "local_${System.currentTimeMillis()}_${(1000..9999).random()}" }, userId = meal.userId, @@ -54,8 +44,8 @@ data class LocalMealEntity( hungerBefore = meal.hungerBefore, satietyAfter = meal.satietyAfter, note = meal.note, - foodItemsJoined = foodItemsJoined, - photoUrisJoined = photoUrisJoined, + foodItems = meal.foodItemsSerialized, + photoUris = meal.displayPhotoUris, updatedAt = System.currentTimeMillis() ) } diff --git a/app/src/main/java/com/example/data/local/RoomConverters.kt b/app/src/main/java/com/example/data/local/RoomConverters.kt new file mode 100644 index 0000000..b690821 --- /dev/null +++ b/app/src/main/java/com/example/data/local/RoomConverters.kt @@ -0,0 +1,36 @@ +package com.example.data.local + +import androidx.room.TypeConverter +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.Moshi +import com.squareup.moshi.Types + +class RoomConverters { + + private val moshi: Moshi = Moshi.Builder().build() + private val listType = Types.newParameterizedType(List::class.java, String::class.java) + private val adapter: JsonAdapter> = moshi.adapter(listType) + + @TypeConverter + fun fromStringList(list: List?): String { + return adapter.toJson(list ?: emptyList()) + } + + @TypeConverter + fun toStringList(json: String?): List { + if (json.isNullOrBlank()) return emptyList() + return try { + if (json.startsWith("[")) { + adapter.fromJson(json) ?: emptyList() + } else if (json.contains("###")) { + json.split("###").filter { it.isNotBlank() } + } else if (json.contains("|||")) { + json.split("|||").filter { it.isNotBlank() } + } else { + listOf(json) + } + } catch (_: Exception) { + emptyList() + } + } +} diff --git a/app/src/main/java/com/example/data/repository/MealRepository.kt b/app/src/main/java/com/example/data/repository/MealRepository.kt index a3b63f6..bcbc71d 100644 --- a/app/src/main/java/com/example/data/repository/MealRepository.kt +++ b/app/src/main/java/com/example/data/repository/MealRepository.kt @@ -35,7 +35,8 @@ import java.util.UUID class MealRepository( private val localMealDao: LocalMealDao?, private val db: FirebaseFirestore?, - private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth + private val auth: FirebaseAuth = db?.app?.let { FirebaseAuth.getInstance(it) } ?: Firebase.auth, + private val context: Context? = null ) { // Constructor used by ViewModel in app runtime @@ -47,14 +48,16 @@ class MealRepository( ) } catch (_: Exception) { null - } + }, + context = context.applicationContext ) // Secondary constructor for Firestore rule tests without local DB constructor(db: FirebaseFirestore) : this( localMealDao = null, db = db, - auth = FirebaseAuth.getInstance(db.app) + auth = FirebaseAuth.getInstance(db.app), + context = null ) private fun getUserIdOrNull(): String? { @@ -263,7 +266,11 @@ class MealRepository( // 1. Clean up local photo files val existingMeal = localMealDao?.getMealById(mealId)?.toMealEntry() existingMeal?.displayPhotoUris?.forEach { uri -> - ImageUtils.deletePhotoFile(uri) + if (context != null) { + ImageUtils.deletePhotoFile(context, uri) + } else { + ImageUtils.deletePhotoFile(uri) + } } // 2. Delete from local Room database diff --git a/app/src/main/java/com/example/domain/CsvExportUseCase.kt b/app/src/main/java/com/example/domain/CsvExportUseCase.kt index 20f7cc2..d33a766 100644 --- a/app/src/main/java/com/example/domain/CsvExportUseCase.kt +++ b/app/src/main/java/com/example/domain/CsvExportUseCase.kt @@ -12,8 +12,8 @@ class CsvExportUseCase(private val context: Context) { return CsvExporter.writeCsvToUri(context, targetUri, meals) } - suspend fun createShareIntent(activityContext: Context, meals: List): Result { - return CsvExporter.shareCsvFile(activityContext, meals) + suspend fun createShareIntent(meals: List): Result { + return CsvExporter.shareCsvFile(context, meals) } fun defaultFileName(): String { diff --git a/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt index a98ecba..188d21b 100644 --- a/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt +++ b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt @@ -2,14 +2,16 @@ package com.example.domain import android.content.Context import android.content.Intent -import com.example.data.model.MealEntry import com.example.data.preferences.GoogleSheetsPreferencesManager import com.example.data.repository.MealRepository +import com.example.util.AuthExpiredException import com.example.util.GoogleSheetsAuthHelper import com.example.util.GoogleSheetsSyncResult import com.example.util.GoogleSheetsSyncService import com.google.android.gms.auth.UserRecoverableAuthException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext sealed interface SheetsSyncResult { @@ -24,11 +26,19 @@ class GoogleSheetsSyncUseCase( private val sheetsPrefs: GoogleSheetsPreferencesManager ) { - suspend fun execute(): SheetsSyncResult = withContext(Dispatchers.IO) { + private val syncMutex = Mutex() + + suspend fun execute(): SheetsSyncResult = syncMutex.withLock { + withContext(Dispatchers.IO) { + executeInternal(retryOnAuthFailure = true) + } + } + + private suspend fun executeInternal(retryOnAuthFailure: Boolean): SheetsSyncResult { val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context) if (tokenResult.isFailure) { val exception = tokenResult.exceptionOrNull() - return@withContext if (exception is UserRecoverableAuthException) { + return if (exception is UserRecoverableAuthException) { SheetsSyncResult.RecoverableAuth( message = "Autorisation requise pour Google Sheets & Drive", intent = exception.intent @@ -38,20 +48,42 @@ class GoogleSheetsSyncUseCase( } } - val token = tokenResult.getOrThrow() - val spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) + var token = tokenResult.getOrThrow() + + // 1. Get or create spreadsheet + var spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) + if (spreadsheetResult.isFailure && spreadsheetResult.exceptionOrNull() is AuthExpiredException && retryOnAuthFailure) { + // Token expired, invalidate and retry once + GoogleSheetsAuthHelper.invalidateToken(context, token) + val refreshedTokenResult = GoogleSheetsAuthHelper.getAccessToken(context) + if (refreshedTokenResult.isSuccess) { + token = refreshedTokenResult.getOrThrow() + spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId) + } + } + if (spreadsheetResult.isFailure) { val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création du classeur" - return@withContext SheetsSyncResult.Failure(err) + return SheetsSyncResult.Failure(err) } val (id, url) = spreadsheetResult.getOrThrow() sheetsPrefs.spreadsheetId = id sheetsPrefs.spreadsheetUrl = url + // 2. Sync meals val currentMeals = repository.getAllMealsSnapshot() - val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) - if (syncResult.isSuccess) { + var syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) + if (syncResult.isFailure && syncResult.exceptionOrNull() is AuthExpiredException && retryOnAuthFailure) { + GoogleSheetsAuthHelper.invalidateToken(context, token) + val refreshedTokenResult = GoogleSheetsAuthHelper.getAccessToken(context) + if (refreshedTokenResult.isSuccess) { + token = refreshedTokenResult.getOrThrow() + syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) + } + } + + return if (syncResult.isSuccess) { val res = syncResult.getOrThrow() sheetsPrefs.lastSyncTimestamp = res.timestamp sheetsPrefs.lastSyncCount = res.mealsCount @@ -63,23 +95,30 @@ class GoogleSheetsSyncUseCase( } } - suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? = withContext(Dispatchers.IO) { - if (!sheetsPrefs.isAutoSyncEnabled) return@withContext null - try { - val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null - val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId).getOrNull() ?: return@withContext null - sheetsPrefs.spreadsheetId = id - sheetsPrefs.spreadsheetUrl = url + suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? { + if (!sheetsPrefs.isAutoSyncEnabled) return null + if (syncMutex.isLocked) return null // Drop redundant concurrent background trigger - val currentMeals = repository.getAllMealsSnapshot() - val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) - if (syncResult.isSuccess) { - val res = syncResult.getOrThrow() - sheetsPrefs.lastSyncTimestamp = res.timestamp - sheetsPrefs.lastSyncCount = res.mealsCount - sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement" - res - } else null + return try { + syncMutex.withLock { + withContext(Dispatchers.IO) { + val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null + val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId).getOrNull() + ?: return@withContext null + sheetsPrefs.spreadsheetId = id + sheetsPrefs.spreadsheetUrl = url + + val currentMeals = repository.getAllMealsSnapshot() + val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals) + if (syncResult.isSuccess) { + val res = syncResult.getOrThrow() + sheetsPrefs.lastSyncTimestamp = res.timestamp + sheetsPrefs.lastSyncCount = res.mealsCount + sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement" + res + } else null + } + } } catch (_: Exception) { null } diff --git a/app/src/main/java/com/example/ui/journal/MealViewModel.kt b/app/src/main/java/com/example/ui/journal/MealViewModel.kt index 49f9f3f..c9170be 100644 --- a/app/src/main/java/com/example/ui/journal/MealViewModel.kt +++ b/app/src/main/java/com/example/ui/journal/MealViewModel.kt @@ -210,9 +210,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { note: String, foodItems: List, photoUris: List = emptyList(), - photosBase64: List = emptyList(), - onSuccess: () -> Unit = {}, - onError: (String) -> Unit = {} + photosBase64: List = emptyList() ) { enrichCatalogWithFoodItems(foodItems) viewModelScope.launch { @@ -228,12 +226,10 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { ) val result = repository.addMeal(entry) if (result.isSuccess) { - onSuccess() emitEvent(UiEvent.ShowSnackbar("Repas enregistré avec succès ✨")) triggerAutoSheetsSyncIfNeeded() } else { val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement" - onError(err) emitEvent(UiEvent.ShowSnackbar(err)) } } @@ -257,9 +253,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { fun updateMeal( meal: MealEntry, - foodItems: List, - onSuccess: () -> Unit = {}, - onError: (String) -> Unit = {} + foodItems: List ) { enrichCatalogWithFoodItems(foodItems) viewModelScope.launch { @@ -270,31 +264,23 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { ) val result = repository.updateMeal(sanitizedMeal) if (result.isSuccess) { - onSuccess() emitEvent(UiEvent.ShowSnackbar("Repas mis à jour ✨")) triggerAutoSheetsSyncIfNeeded() } else { val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de mise à jour" - onError(err) emitEvent(UiEvent.ShowSnackbar(err)) } } } - fun deleteMeal( - mealId: String, - onSuccess: () -> Unit = {}, - onError: (String) -> Unit = {} - ) { + fun deleteMeal(mealId: String) { viewModelScope.launch { val result = repository.deleteMeal(mealId) if (result.isSuccess) { - onSuccess() emitEvent(UiEvent.ShowSnackbar("Repas supprimé")) triggerAutoSheetsSyncIfNeeded() } else { val err = result.exceptionOrNull()?.localizedMessage ?: "Erreur de suppression" - onError(err) emitEvent(UiEvent.ShowSnackbar(err)) } } @@ -311,8 +297,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { } fun syncToGoogleSheets( - onSuccess: (url: String, count: Int) -> Unit = { _, _ -> }, - onError: (message: String, recoverableIntent: Intent?) -> Unit = { _, _ -> } + onAuthConsentNeeded: ((Intent) -> Unit)? = null ) { viewModelScope.launch { _sheetsUiState.value = GoogleSheetsUiState.Syncing @@ -320,16 +305,20 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { is SheetsSyncResult.Success -> { _spreadsheetUrl.value = result.url _sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp) - onSuccess(result.url, result.count) emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊")) } is SheetsSyncResult.RecoverableAuth -> { _sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent) - onError(result.message, result.intent) + if (result.intent != null && onAuthConsentNeeded != null) { + onAuthConsentNeeded(result.intent) + } else if (result.intent != null) { + emitEvent(UiEvent.StartActivity(result.intent)) + } else { + emitEvent(UiEvent.ShowSnackbar(result.message)) + } } is SheetsSyncResult.Failure -> { _sheetsUiState.value = GoogleSheetsUiState.Error(result.message) - onError(result.message, null) emitEvent(UiEvent.ShowSnackbar(result.message)) } } @@ -338,36 +327,27 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { fun exportCsvToUri( targetUri: Uri, - meals: List, - onSuccess: (Int) -> Unit, - onError: (String) -> Unit + meals: List ) { viewModelScope.launch { val result = csvExportUseCase.writeToUri(targetUri, meals) result.fold( onSuccess = { count -> - onSuccess(count) emitEvent(UiEvent.ShowSnackbar("Fichier CSV enregistré ($count repas) ✨")) }, onFailure = { err -> val msg = err.localizedMessage ?: "Erreur lors de l'export CSV" - onError(msg) emitEvent(UiEvent.ShowSnackbar(msg)) } ) } } - fun importCsvFromUri( - sourceUri: Uri, - onSuccess: (CsvImportResult) -> Unit, - onError: (String) -> Unit - ) { + fun importCsvFromUri(sourceUri: Uri) { viewModelScope.launch { val result = repository.importMealsFromCsv(context, sourceUri) result.fold( onSuccess = { importResult -> - onSuccess(importResult) val count = importResult.importedMeals.size val skipped = importResult.skippedDuplicatesCount val newFoods = importResult.newFoodItems.size @@ -381,48 +361,36 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { }, onFailure = { err -> val msg = err.localizedMessage ?: "Erreur lors de l'import du fichier CSV" - onError(msg) emitEvent(UiEvent.ShowSnackbar(msg)) } ) } } - fun syncCloudToLocal( - onSuccess: (Int) -> Unit, - onError: (String) -> Unit - ) { + fun syncCloudToLocal() { viewModelScope.launch { val result = repository.syncCloudToLocal() result.fold( onSuccess = { count -> - onSuccess(count) emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️")) }, onFailure = { err -> val msg = err.localizedMessage ?: "Erreur lors de la synchronisation" - onError(msg) emitEvent(UiEvent.ShowSnackbar(msg)) } ) } } - fun shareCsv( - activityContext: Context, - meals: List, - onIntentReady: (Intent) -> Unit, - onError: (String) -> Unit - ) { + fun shareCsv(meals: List) { viewModelScope.launch { - val result = csvExportUseCase.createShareIntent(activityContext, meals) + val result = csvExportUseCase.createShareIntent(meals) result.fold( onSuccess = { chooserIntent -> - onIntentReady(chooserIntent) + emitEvent(UiEvent.StartActivity(chooserIntent)) }, onFailure = { err -> val msg = err.localizedMessage ?: "Impossible de préparer le partage CSV" - onError(msg) emitEvent(UiEvent.ShowSnackbar(msg)) } ) diff --git a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt index a10314e..a8bf38a 100644 --- a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt +++ b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt @@ -36,8 +36,10 @@ import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext @@ -59,6 +61,24 @@ import com.example.util.ImageUtils import kotlinx.coroutines.launch import java.util.Locale +private val FoodItemListSaver = listSaver, String>( + save = { stateList -> stateList.map { it.serialize() } }, + restore = { savedStrings -> + mutableStateListOf().apply { + addAll(savedStrings.mapNotNull { MealFoodItem.deserialize(it) }) + } + } +) + +private val StringListSaver = listSaver, String>( + save = { stateList -> stateList.toList() }, + restore = { savedStrings -> + mutableStateListOf().apply { + addAll(savedStrings) + } + } +) + @OptIn(ExperimentalMaterial3Api::class) @Composable fun MealEntrySheet( @@ -89,14 +109,15 @@ fun MealEntrySheet( mutableStateOf(initialMeal?.note ?: "") } - val foodItemsList = remember { + // Preserved across rotation via custom ListSaver + val foodItemsList = rememberSaveable(saver = FoodItemListSaver) { mutableStateListOf().apply { if (initialMeal != null) { addAll(initialMeal.parsedFoodItems()) } } } - val photoUrisList = remember { + val photoUrisList = rememberSaveable(saver = StringListSaver) { mutableStateListOf().apply { if (initialMeal != null) { addAll(initialMeal.displayPhotoUris) @@ -104,6 +125,14 @@ fun MealEntrySheet( } } + // Deferred photo management + val photosMarkedForDeletion = rememberSaveable(saver = StringListSaver) { + mutableStateListOf() + } + val newlyCapturedPhotos = rememberSaveable(saver = StringListSaver) { + mutableStateListOf() + } + // Current food builder input state var foodNameInput by rememberSaveable { mutableStateOf("") } var foodWeightInput by rememberSaveable { mutableStateOf("") } @@ -177,14 +206,23 @@ fun MealEntrySheet( val savedUri = ImageUtils.saveImageToPrivateStorage(context, uri) if (savedUri != null && photoUrisList.size < 4) { photoUrisList.add(savedUri) + newlyCapturedPhotos.add(savedUri) } isProcessingPhoto = false } } } + val handleDismiss = { + // Clean up only uncommitted new photos; do NOT delete existing saved photos + newlyCapturedPhotos.forEach { photoUri -> + ImageUtils.deletePhotoFile(context, photoUri) + } + onDismiss() + } + ModalBottomSheet( - onDismissRequest = onDismiss, + onDismissRequest = handleDismiss, sheetState = sheetState, containerColor = MaterialTheme.colorScheme.surface, dragHandle = null @@ -215,7 +253,7 @@ fun MealEntrySheet( ) } IconButton( - onClick = onDismiss, + onClick = handleDismiss, modifier = Modifier.testTag("dismiss_sheet_button") ) { Icon( @@ -254,8 +292,8 @@ fun MealEntrySheet( ) }, onDeletePhotoClick = { photoUri -> - ImageUtils.deletePhotoFile(photoUri) photoUrisList.remove(photoUri) + photosMarkedForDeletion.add(photoUri) } ) @@ -333,7 +371,7 @@ fun MealEntrySheet( verticalAlignment = Alignment.CenterVertically ) { TextButton( - onClick = onDismiss, + onClick = handleDismiss, modifier = Modifier.testTag("cancel_meal_button") ) { Text("Annuler") @@ -344,6 +382,12 @@ fun MealEntrySheet( if (foodNameInput.trim().isNotEmpty()) { addCurrentFoodItem() } + // Physically delete only photos marked for deletion that were not re-added + photosMarkedForDeletion.forEach { photoUri -> + if (!photoUrisList.contains(photoUri)) { + ImageUtils.deletePhotoFile(context, photoUri) + } + } onSaveMeal( selectedType, mealTimestamp, diff --git a/app/src/main/java/com/example/ui/settings/SettingsScreen.kt b/app/src/main/java/com/example/ui/settings/SettingsScreen.kt index 8e4b882..826488b 100644 --- a/app/src/main/java/com/example/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/example/ui/settings/SettingsScreen.kt @@ -1,95 +1,32 @@ package com.example.ui.settings -import android.Manifest -import android.os.Build -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts -import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.filled.ExitToApp -import androidx.compose.material.icons.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.time.Instant -import java.time.ZoneId -import java.time.format.DateTimeFormatter -import java.util.Locale -import androidx.compose.material3.Button -import androidx.compose.material3.ButtonDefaults -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.FilterChipDefaults -import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Surface -import androidx.compose.material3.Switch -import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.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.journal.GoogleSheetsUiState +import com.example.ui.settings.components.AccountAndSecuritySection +import com.example.ui.settings.components.AppearanceThemeSection +import com.example.ui.settings.components.DataExportImportSection +import com.example.ui.settings.components.GoogleSheetsIntegrationSection +import com.example.ui.settings.components.NotificationRemindersSection import com.example.ui.theme.AppThemeMode import com.google.firebase.Firebase import com.google.firebase.auth.auth -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -@OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( currentThemeMode: AppThemeMode, @@ -107,46 +44,26 @@ fun SettingsScreen( onAutoSyncSheetsChange: (Boolean) -> Unit, onOpenSheetsClick: (String) -> Unit, onSignInClick: () -> Unit, - onSignOut: () -> Unit + onSignOut: () -> Unit, + modifier: Modifier = Modifier ) { - 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().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 + modifier = modifier .fillMaxSize() - .background(MaterialTheme.colorScheme.background) - .testTag("settings_screen"), - contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp), - verticalArrangement = Arrangement.spacedBy(18.dp) + .testTag("settings_screen_list"), + contentPadding = PaddingValues(horizontal = 20.dp, vertical = 24.dp), + verticalArrangement = Arrangement.spacedBy(20.dp) ) { item { - Column { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(bottom = 4.dp) + ) { Text( - text = "Réglages & Préférences", + text = "Paramètres", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onBackground, fontWeight = FontWeight.Bold @@ -159,812 +76,51 @@ fun SettingsScreen( } } - // 1. Local Database & CSV Management Card + // 1. Local Database & CSV Management item { - Card( - modifier = Modifier - .fillMaxWidth() - .testTag("settings_csv_export_card"), - shape = RoundedCornerShape(22.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface - ) - ) { - Column(modifier = Modifier.padding(20.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Surface( - modifier = Modifier.size(40.dp), - shape = CircleShape, - color = MaterialTheme.colorScheme.primaryContainer - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - imageVector = Icons.Default.Storage, - contentDescription = null, - tint = MaterialTheme.colorScheme.onPrimaryContainer, - modifier = Modifier.size(22.dp) - ) - } - } - - Spacer(modifier = Modifier.width(12.dp)) - - Column { - Text( - text = "Base locale & Fichiers CSV", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - fontWeight = FontWeight.Bold - ) - Text( - text = "Base SQLite locale active • $totalMealsCount repas sur l'appareil", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - 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(1.1f) - .testTag("settings_save_csv_button"), - shape = RoundedCornerShape(12.dp), - colors = ButtonDefaults.buttonColors( - containerColor = MaterialTheme.colorScheme.primary, - contentColor = MaterialTheme.colorScheme.onPrimary - ) - ) { - Icon( - imageVector = Icons.Default.FileDownload, - contentDescription = null, - modifier = Modifier.size(18.dp) - ) - Spacer(modifier = Modifier.width(4.dp)) - Text("Sauver", maxLines = 1) - } - - OutlinedButton( - onClick = onShareCsvClick, - enabled = totalMealsCount > 0, - modifier = Modifier - .weight(1f) - .testTag("settings_share_csv_button"), - shape = RoundedCornerShape(12.dp) - ) { - Icon( - imageVector = Icons.Default.Share, - contentDescription = null, - modifier = Modifier.size(18.dp) - ) - Spacer(modifier = Modifier.width(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) - ) - } - } + DataExportImportSection( + totalMealsCount = totalMealsCount, + onImportCsvClick = onImportCsvClick, + onSaveCsvClick = onSaveCsvClick, + onShareCsvClick = onShareCsvClick + ) } - // 2. Google Sheets & Drive Sync Card + // 2. Google Sheets & Drive Sync 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 = DateTimeFormatter.ofPattern("dd/MM/yyyy 'à' HH:mm", Locale.FRENCH) - .format(Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault())) - 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) - ) - } - } + GoogleSheetsIntegrationSection( + sheetsUiState = sheetsUiState, + isAutoSyncSheets = isAutoSyncSheets, + spreadsheetUrl = spreadsheetUrl, + onSyncSheetsClick = onSyncSheetsClick, + onAutoSyncSheetsChange = onAutoSyncSheetsChange, + onOpenSheetsClick = onOpenSheetsClick + ) } - // 3. Reminders Card + // 3. Reminders item { - Card( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(22.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface - ) - ) { - Column(modifier = Modifier.padding(20.dp)) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - Surface( - modifier = Modifier.size(40.dp), - shape = CircleShape, - color = MaterialTheme.colorScheme.primaryContainer - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - imageVector = Icons.Default.NotificationsActive, - contentDescription = null, - tint = MaterialTheme.colorScheme.onPrimaryContainer, - modifier = Modifier.size(22.dp) - ) - } - } - - Spacer(modifier = Modifier.width(12.dp)) - - Column { - Text( - text = "Rappels push personnalisés", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - fontWeight = FontWeight.Bold - ) - Text( - text = "Une notification discrète au moment de manger", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - 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() - .padding(vertical = 8.dp), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column { - Text( - text = mealType.displayName, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - fontWeight = FontWeight.SemiBold - ) - Text( - text = "Heure de rappel: $formattedTime", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - Switch( - checked = isEnabled, - onCheckedChange = { checked -> - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && checked && !notificationsEnabledBySystem) { - permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) - } - reminderStates[mealType] = checked - prefs.setReminderEnabled(mealType, checked) - onScheduleReminder(mealType, hour, minute, checked) - }, - colors = SwitchDefaults.colors( - checkedThumbColor = MaterialTheme.colorScheme.primary, - checkedTrackColor = MaterialTheme.colorScheme.primaryContainer - ), - modifier = Modifier.testTag("switch_${mealType.name.lowercase()}") - ) - } - } - - Spacer(modifier = Modifier.height(12.dp)) - - OutlinedButton( - onClick = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationsEnabledBySystem) { - permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) - } else { - onTestNotification(MealType.LUNCH) - } - }, - modifier = Modifier - .fillMaxWidth() - .testTag("test_notification_button"), - shape = RoundedCornerShape(12.dp) - ) { - Icon( - imageVector = Icons.Default.Notifications, - contentDescription = null, - modifier = Modifier.size(18.dp) - ) - Spacer(modifier = Modifier.width(8.dp)) - Text("Tester une notification maintenant") - } - } - } + NotificationRemindersSection( + onScheduleReminder = onScheduleReminder, + onTestNotification = onTestNotification + ) } - // 3. Theme Selector Card + // 4. Theme Selector item { - Card( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(22.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface - ) - ) { - Column(modifier = Modifier.padding(20.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Surface( - modifier = Modifier.size(40.dp), - shape = CircleShape, - color = MaterialTheme.colorScheme.secondaryContainer - ) { - Box(contentAlignment = Alignment.Center) { - Icon( - imageVector = Icons.Default.Brightness4, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSecondaryContainer, - modifier = Modifier.size(22.dp) - ) - } - } - - Spacer(modifier = Modifier.width(12.dp)) - - Column { - Text( - text = "Apparence visuelle", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - fontWeight = FontWeight.Bold - ) - Text( - text = "Mode sombre élégant par défaut pour le repos des yeux", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - - Spacer(modifier = Modifier.height(16.dp)) - - AppThemeMode.entries.forEach { mode -> - val isSelected = currentThemeMode == mode - FilterChip( - selected = isSelected, - onClick = { onThemeModeChange(mode) }, - label = { - Text( - text = mode.displayName, - style = MaterialTheme.typography.bodyMedium - ) - }, - colors = FilterChipDefaults.filterChipColors( - selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, - selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer - ), - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp) - .testTag("theme_chip_${mode.name.lowercase()}") - ) - } - } - } + AppearanceThemeSection( + currentThemeMode = currentThemeMode, + onThemeModeChange = onThemeModeChange + ) } - // 4. Account & Cloud Sync Card (Optional) + // 5. Account & Cloud Sync item { - Card( - modifier = Modifier.fillMaxWidth(), - shape = RoundedCornerShape(22.dp), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surface - ) - ) { - Column(modifier = Modifier.padding(20.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.height(14.dp)) - - Row( - modifier = Modifier - .fillMaxWidth() - .background( - color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f), - shape = RoundedCornerShape(12.dp) - ) - .padding(12.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Icon( - imageVector = Icons.Default.CloudDone, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier.size(20.dp) - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = "Base de données cloud sécurisée • Synchronisation continue", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - - Spacer(modifier = Modifier.height(16.dp)) - - Button( - onClick = 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("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 = "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)) - - 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)") - } - } - } - } + AccountAndSecuritySection( + currentUser = currentUser, + onSignInClick = onSignInClick, + onSignOut = onSignOut + ) } item { diff --git a/app/src/main/java/com/example/ui/settings/components/AccountAndSecuritySection.kt b/app/src/main/java/com/example/ui/settings/components/AccountAndSecuritySection.kt new file mode 100644 index 0000000..5390b24 --- /dev/null +++ b/app/src/main/java/com/example/ui/settings/components/AccountAndSecuritySection.kt @@ -0,0 +1,195 @@ +package com.example.ui.settings.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.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.filled.AccountCircle +import androidx.compose.material.icons.filled.CloudDone +import androidx.compose.material.icons.filled.CloudOff +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.google.firebase.auth.FirebaseUser + +@Composable +fun AccountAndSecuritySection( + currentUser: FirebaseUser?, + onSignInClick: () -> Unit, + onSignOut: () -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(22.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) { + Column(modifier = Modifier.padding(20.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.height(14.dp)) + + Row( + modifier = Modifier + .fillMaxWidth() + .background( + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f), + shape = RoundedCornerShape(12.dp) + ) + .padding(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.CloudDone, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = "Base de données cloud sécurisée • Synchronisation continue", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + Button( + onClick = 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("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 = "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)) + + 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)") + } + } + } + } +} diff --git a/app/src/main/java/com/example/ui/settings/components/AppearanceThemeSection.kt b/app/src/main/java/com/example/ui/settings/components/AppearanceThemeSection.kt new file mode 100644 index 0000000..948836d --- /dev/null +++ b/app/src/main/java/com/example/ui/settings/components/AppearanceThemeSection.kt @@ -0,0 +1,104 @@ +package com.example.ui.settings.components + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Brightness4 +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.example.ui.theme.AppThemeMode + +@Composable +fun AppearanceThemeSection( + currentThemeMode: AppThemeMode, + onThemeModeChange: (AppThemeMode) -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(22.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) { + Column(modifier = Modifier.padding(20.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Surface( + modifier = Modifier.size(40.dp), + shape = CircleShape, + color = MaterialTheme.colorScheme.secondaryContainer + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Default.Brightness4, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Column { + Text( + text = "Apparence visuelle", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.Bold + ) + Text( + text = "Mode sombre élégant par défaut pour le repos des yeux", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + AppThemeMode.entries.forEach { mode -> + val isSelected = currentThemeMode == mode + FilterChip( + selected = isSelected, + onClick = { onThemeModeChange(mode) }, + label = { + Text( + text = mode.displayName, + style = MaterialTheme.typography.bodyMedium + ) + }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, + selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer + ), + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 4.dp) + .testTag("theme_chip_${mode.name.lowercase()}") + ) + } + } + } +} diff --git a/app/src/main/java/com/example/ui/settings/components/DataExportImportSection.kt b/app/src/main/java/com/example/ui/settings/components/DataExportImportSection.kt new file mode 100644 index 0000000..67dbeb7 --- /dev/null +++ b/app/src/main/java/com/example/ui/settings/components/DataExportImportSection.kt @@ -0,0 +1,161 @@ +package com.example.ui.settings.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.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.Storage +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp + +@Composable +fun DataExportImportSection( + totalMealsCount: Int, + onImportCsvClick: () -> Unit, + onSaveCsvClick: () -> Unit, + onShareCsvClick: () -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier + .fillMaxWidth() + .testTag("settings_csv_export_card"), + shape = RoundedCornerShape(22.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ) + ) { + Column(modifier = Modifier.padding(20.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Surface( + modifier = Modifier.size(40.dp), + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Default.Storage, + contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Column { + Text( + text = "Base locale & Fichiers CSV", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.Bold + ) + Text( + text = "Base SQLite locale active • $totalMealsCount repas sur l'appareil", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + 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(1.1f) + .testTag("settings_save_csv_button"), + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary + ) + ) { + Icon( + imageVector = Icons.Default.FileDownload, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text("Sauver", maxLines = 1) + } + + OutlinedButton( + onClick = onShareCsvClick, + enabled = totalMealsCount > 0, + modifier = Modifier + .weight(1f) + .testTag("settings_share_csv_button"), + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Default.Share, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(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) + ) + } + } +} diff --git a/app/src/main/java/com/example/ui/settings/components/GoogleSheetsIntegrationSection.kt b/app/src/main/java/com/example/ui/settings/components/GoogleSheetsIntegrationSection.kt new file mode 100644 index 0000000..bd00a9d --- /dev/null +++ b/app/src/main/java/com/example/ui/settings/components/GoogleSheetsIntegrationSection.kt @@ -0,0 +1,332 @@ +package com.example.ui.settings.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.OpenInNew +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material.icons.filled.ErrorOutline +import androidx.compose.material.icons.filled.Sync +import androidx.compose.material.icons.filled.TableChart +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.example.ui.journal.GoogleSheetsUiState +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale + +@Composable +fun GoogleSheetsIntegrationSection( + sheetsUiState: GoogleSheetsUiState, + isAutoSyncSheets: Boolean, + spreadsheetUrl: String?, + onSyncSheetsClick: () -> Unit, + onAutoSyncSheetsChange: (Boolean) -> Unit, + onOpenSheetsClick: (String) -> Unit, + modifier: Modifier = Modifier +) { + 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 { + Text( + text = "Google Sheets & Drive", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.Bold + ) + Text( + text = "Synchronisation automatique dans votre cloud", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // State 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 Google Sheets en cours...", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) + } + } + is GoogleSheetsUiState.Success -> { + val dateFormatted = try { + val zdt = Instant.ofEpochMilli(sheetsUiState.timestamp).atZone(ZoneId.systemDefault()) + DateTimeFormatter.ofPattern("dd/MM à HH:mm", Locale.FRENCH).format(zdt) + } catch (_: Exception) { + "" + } + Row( + modifier = Modifier + .fillMaxWidth() + .background( + color = Color(0xFF0F9D58).copy(alpha = 0.12f), + 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 = "${sheetsUiState.count} repas synchronisés ($dateFormatted)", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.Medium + ) + } + } + 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) + ) + } + } +} diff --git a/app/src/main/java/com/example/ui/settings/components/NotificationRemindersSection.kt b/app/src/main/java/com/example/ui/settings/components/NotificationRemindersSection.kt new file mode 100644 index 0000000..7163c41 --- /dev/null +++ b/app/src/main/java/com/example/ui/settings/components/NotificationRemindersSection.kt @@ -0,0 +1,263 @@ +package com.example.ui.settings.components + +import android.Manifest +import android.content.Intent +import android.os.Build +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Notifications +import androidx.compose.material.icons.filled.NotificationsActive +import androidx.compose.material.icons.filled.NotificationsOff +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.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.lifecycle.Lifecycle +import androidx.lifecycle.compose.LifecycleEventEffect +import com.example.data.model.MealType +import com.example.data.preferences.ReminderPreferencesManager + +@Composable +fun NotificationRemindersSection( + onScheduleReminder: (MealType, Int, Int, Boolean) -> Unit, + onTestNotification: (MealType) -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + 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 permissionLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission() + ) { isGranted -> + notificationsEnabledBySystem = isGranted || NotificationManagerCompat.from(context).areNotificationsEnabled() + } + + val reminderStates = remember { + mutableStateMapOf().apply { + MealType.entries.forEach { mealType -> + put(mealType, prefs.isReminderEnabled(mealType)) + } + } + } + + Card( + modifier = modifier + .fillMaxWidth() + .testTag("settings_reminders_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(40.dp), + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Default.NotificationsActive, + contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Column { + Text( + text = "Rappels push personnalisés", + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.Bold + ) + Text( + text = "Une notification discrète au moment de manger", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + 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() + .padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = mealType.displayName, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + fontWeight = FontWeight.SemiBold + ) + Text( + text = "Heure de rappel: $formattedTime", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Switch( + checked = isEnabled, + onCheckedChange = { checked -> + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && checked && !notificationsEnabledBySystem) { + permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + } + reminderStates[mealType] = checked + prefs.setReminderEnabled(mealType, checked) + onScheduleReminder(mealType, hour, minute, checked) + }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ), + modifier = Modifier.testTag("switch_${mealType.name.lowercase()}") + ) + } + } + + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedButton( + onClick = { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !notificationsEnabledBySystem) { + permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) + } else { + onTestNotification(MealType.LUNCH) + } + }, + modifier = Modifier + .fillMaxWidth() + .testTag("test_notification_button"), + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Default.Notifications, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text("Tester une notification maintenant") + } + } + } +} diff --git a/app/src/main/java/com/example/util/CsvExporter.kt b/app/src/main/java/com/example/util/CsvExporter.kt index 8d4b391..bb2b47f 100644 --- a/app/src/main/java/com/example/util/CsvExporter.kt +++ b/app/src/main/java/com/example/util/CsvExporter.kt @@ -60,12 +60,20 @@ object CsvExporter { return sb.toString() } - private fun escapeCsvField(value: String): String { - val sanitized = value.replace("\r\n", " ").replace("\n", " ").trim() - return if (sanitized.contains(",") || sanitized.contains("\"") || sanitized.contains(";")) { - "\"${sanitized.replace("\"", "\"\"")}\"" + fun escapeCsvField(value: String): String { + val rawWithoutNewlines = value.replace("\r\n", " ").replace("\n", " ") + val trimmed = rawWithoutNewlines.trim() + val formulaProtected = if (rawWithoutNewlines.isNotEmpty() && rawWithoutNewlines[0] in listOf('=', '+', '-', '@', '\t', '\r')) { + "'$rawWithoutNewlines" + } else if (trimmed.isNotEmpty() && trimmed[0] in listOf('=', '+', '-', '@')) { + "'$trimmed" } else { - sanitized + trimmed + } + return if (formulaProtected.contains(",") || formulaProtected.contains("\"") || formulaProtected.contains(";")) { + "\"${formulaProtected.replace("\"", "\"\"")}\"" + } else { + formulaProtected } } diff --git a/app/src/main/java/com/example/util/GoogleSheetsAuthHelper.kt b/app/src/main/java/com/example/util/GoogleSheetsAuthHelper.kt index 2c55cfd..2a3e19e 100644 --- a/app/src/main/java/com/example/util/GoogleSheetsAuthHelper.kt +++ b/app/src/main/java/com/example/util/GoogleSheetsAuthHelper.kt @@ -63,4 +63,10 @@ object GoogleSheetsAuthHelper { Result.failure(e) } } + + fun invalidateToken(context: Context, token: String) { + try { + GoogleAuthUtil.clearToken(context.applicationContext, token) + } catch (_: Exception) {} + } } diff --git a/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt b/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt index 329bf95..f8f6feb 100644 --- a/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt +++ b/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt @@ -20,10 +20,13 @@ data class GoogleSheetsSyncResult( val timestamp: Long = System.currentTimeMillis() ) +class AuthExpiredException(message: String) : IllegalStateException(message) + object GoogleSheetsSyncService { private const val TAG = "GoogleSheetsSync" const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas" + const val SHEET_TAB_TITLE = "Journal des repas" private val jsonMediaType = "application/json; charset=utf-8".toMediaType() @@ -38,7 +41,7 @@ object GoogleSheetsSyncService { cachedSpreadsheetId: String? = null ): Result> = withContext(Dispatchers.IO) { try { - // 1. If we have a cached spreadsheetId, verify it still exists and is accessible + // 1. If we have a cached spreadsheetId, verify it still exists if (!cachedSpreadsheetId.isNullOrBlank()) { val checkRequest = Request.Builder() .url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl") @@ -46,36 +49,37 @@ object GoogleSheetsSyncService { .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)) - } + okHttpClient.newCall(checkRequest).execute().use { response -> + if (response.code == 401) { + return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)")) + } + if (response.isSuccessful) { + val body = response.body?.string().orEmpty() + val json = JSONObject(body) + val id = json.getString("spreadsheetId") + 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" + // 2. Search Drive for existing "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 searchUrl = "https://www.googleapis.com/drive/v3/files?q=" + + URLEncoder.encode(query, "UTF-8") + + "&fields=" + URLEncoder.encode("files(id, name, webViewLink)", "UTF-8") + + "&spaces=drive" val searchRequest = Request.Builder() - .url(driveSearchUrl) + .url(searchUrl) .header("Authorization", "Bearer $accessToken") .get() .build() okHttpClient.newCall(searchRequest).execute().use { searchResponse -> + if (searchResponse.code == 401) { + return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)")) + } if (searchResponse.isSuccessful) { val body = searchResponse.body?.string().orEmpty() val json = JSONObject(body) @@ -89,7 +93,7 @@ object GoogleSheetsSyncService { } } - // 3. Not found, create a new Google Sheet + // 3. Not found, create a new Google Sheet with dedicated named tab val createPayload = JSONObject().apply { put("properties", JSONObject().apply { put("title", SPREADSHEET_TITLE) @@ -97,7 +101,7 @@ object GoogleSheetsSyncService { put("sheets", JSONArray().apply { put(JSONObject().apply { put("properties", JSONObject().apply { - put("title", "Journal") + put("title", SHEET_TAB_TITLE) put("gridProperties", JSONObject().apply { put("frozenRowCount", 1) }) @@ -114,6 +118,9 @@ object GoogleSheetsSyncService { okHttpClient.newCall(createRequest).execute().use { response -> val bodyStr = response.body?.string().orEmpty() + if (response.code == 401) { + return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)")) + } if (!response.isSuccessful) { val errorMsg = parseErrorMessage(bodyStr, response.code) return@withContext Result.failure(IllegalStateException("Création du classeur Google Sheets échouée: $errorMsg")) @@ -138,8 +145,9 @@ object GoogleSheetsSyncService { 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" + // 1. Clear previous content with explicit sheet range to remove stale deleted rows + val clearRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A:Z", "UTF-8") + val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear" val clearRequest = Request.Builder() .url(clearUrl) .header("Authorization", "Bearer $accessToken") @@ -147,12 +155,17 @@ object GoogleSheetsSyncService { .build() try { - okHttpClient.newCall(clearRequest).execute().close() + okHttpClient.newCall(clearRequest).execute().use { clearResp -> + if (clearResp.code == 401) { + return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)")) + } + } } catch (e: Exception) { + if (e is AuthExpiredException) throw e Log.w(TAG, "Clear range warning: ${e.message}") } - // 2. Put formatted values starting at A1 + // 2. Put formatted values starting at A1 using RAW input (neutralizes CWE-1236 Formula Injection) val jsonValuesArray = JSONArray() for (row in rows) { val rowArray = JSONArray() @@ -163,12 +176,13 @@ object GoogleSheetsSyncService { } val writePayload = JSONObject().apply { - put("range", "A1") + put("range", "'$SHEET_TAB_TITLE'!A1") put("majorDimension", "ROWS") put("values", jsonValuesArray) } - val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1?valueInputOption=USER_ENTERED" + val writeRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A1", "UTF-8") + val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW" val writeRequest = Request.Builder() .url(writeUrl) .header("Authorization", "Bearer $accessToken") @@ -177,6 +191,9 @@ object GoogleSheetsSyncService { okHttpClient.newCall(writeRequest).execute().use { response -> val bodyStr = response.body?.string().orEmpty() + if (response.code == 401) { + return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)")) + } if (!response.isSuccessful) { val errorMsg = parseErrorMessage(bodyStr, response.code) return@withContext Result.failure(IllegalStateException("Mise à jour de la feuille Google Sheets échouée: $errorMsg")) diff --git a/app/src/main/java/com/example/util/ImageUtils.kt b/app/src/main/java/com/example/util/ImageUtils.kt index 8462b48..87ee39c 100644 --- a/app/src/main/java/com/example/util/ImageUtils.kt +++ b/app/src/main/java/com/example/util/ImageUtils.kt @@ -96,19 +96,45 @@ object ImageUtils { } } + fun deletePhotoFile(context: Context, photoUriStr: String?): Boolean { + if (photoUriStr.isNullOrBlank()) return false + return try { + val uri = Uri.parse(photoUriStr) + val path = uri.path ?: return false + val targetFile = File(path).canonicalFile + val allowedDirectory = getPhotosDirectory(context).canonicalFile + + // Path Traversal Defense: Must strictly reside inside allowed directory + val isWithinAllowedDir = targetFile.path.startsWith(allowedDirectory.path + File.separator) + if (!isWithinAllowedDir) { + Log.w(TAG, "Security Alert: Refusing to delete photo outside allowed directory: ${targetFile.path}") + return false + } + + if (targetFile.exists()) { + targetFile.delete() + } else { + false + } + } catch (e: Exception) { + Log.w(TAG, "Could not delete photo file: ${e.message}") + false + } + } + + // Overload for backward-compatibility with traversal mitigation fun deletePhotoFile(photoUriStr: String?): Boolean { if (photoUriStr.isNullOrBlank()) return false return try { val uri = Uri.parse(photoUriStr) - val path = uri.path - if (path != null) { - val file = File(path) - if (file.exists()) { - file.delete() - } else false - } else false - } catch (e: Exception) { - Log.w(TAG, "Could not delete photo file: ${e.message}") + val path = uri.path ?: return false + if (path.contains("..") || !path.contains(PHOTOS_DIR_NAME)) { + Log.w(TAG, "Security Alert: Traversal attempt blocked in uncontextual delete: $path") + return false + } + val file = File(path) + if (file.exists()) file.delete() else false + } catch (_: Exception) { false } } diff --git a/app/src/test/java/com/example/CsvImporterTest.kt b/app/src/test/java/com/example/CsvImporterTest.kt index 82e4295..86dad0d 100644 --- a/app/src/test/java/com/example/CsvImporterTest.kt +++ b/app/src/test/java/com/example/CsvImporterTest.kt @@ -100,4 +100,27 @@ class CsvImporterTest { assertEquals(1, result.importedMeals[0].parsedFoodItems().size) assertEquals("Pavé de saumon", result.importedMeals[0].parsedFoodItems()[0].name) } + + @Test + fun testFormulaInjectionSanitization() { + val dangerousInputs = listOf( + "=SUM(A1:A10)", + "+cmd|' /C calc'!A0", + "-2+3*cmd|' /C calc'!A0", + "@SUM(1,2)", + "\tTAB_FORMULA" + ) + + for (input in dangerousInputs) { + val escaped = com.example.util.CsvExporter.escapeCsvField(input) + // Either escaped starts with "'=" or "\"\'=" + val isPrefixedWithQuote = escaped.startsWith("'") || escaped.startsWith("\"'") + org.junit.Assert.assertTrue("Input '$input' should be prefixed with single quote: $escaped", isPrefixedWithQuote) + } + + val safeInput = "Repas classique sans formule" + val safeEscaped = com.example.util.CsvExporter.escapeCsvField(safeInput) + assertEquals("Repas classique sans formule", safeEscaped) + } } + diff --git a/app/src/test/java/com/example/ExampleRobolectricTest.kt b/app/src/test/java/com/example/ExampleRobolectricTest.kt deleted file mode 100644 index 0e33103..0000000 --- a/app/src/test/java/com/example/ExampleRobolectricTest.kt +++ /dev/null @@ -1,21 +0,0 @@ -package com.example - -import android.content.Context -import androidx.test.core.app.ApplicationProvider -import org.junit.Assert.assertEquals -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 ExampleRobolectricTest { - - @Test - fun `read string from context`() { - val context = ApplicationProvider.getApplicationContext() - val appName = context.getString(R.string.app_name) - assertEquals("Satiéa", appName) - } -} diff --git a/app/src/test/java/com/example/ExampleUnitTest.kt b/app/src/test/java/com/example/ExampleUnitTest.kt deleted file mode 100644 index e8edd2c..0000000 --- a/app/src/test/java/com/example/ExampleUnitTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -package com.example - -import org.junit.Assert.* -import org.junit.Test - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} diff --git a/app/src/test/java/com/example/ImageUtilsTest.kt b/app/src/test/java/com/example/ImageUtilsTest.kt new file mode 100644 index 0000000..4bf8592 --- /dev/null +++ b/app/src/test/java/com/example/ImageUtilsTest.kt @@ -0,0 +1,71 @@ +package com.example + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import com.example.util.ImageUtils +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 +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [36]) +class ImageUtilsTest { + + private lateinit var context: Context + + @Before + fun setUp() { + context = ApplicationProvider.getApplicationContext() + } + + @Test + fun deletePhotoFile_validPhotoInsideAllowedDirectory_deletesSuccessfully() { + val photosDir = ImageUtils.getPhotosDirectory(context) + val testFile = File(photosDir, "test_photo.jpg").apply { + writeText("dummy content") + } + assertTrue(testFile.exists()) + + val deleted = ImageUtils.deletePhotoFile(context, "file://${testFile.absolutePath}") + assertTrue(deleted) + assertFalse(testFile.exists()) + } + + @Test + fun deletePhotoFile_pathTraversalAttempt_isBlockedAndFilePreserved() { + val sensitiveDir = File(context.filesDir, "databases").apply { mkdirs() } + val sensitiveFile = File(sensitiveDir, "app_database.db").apply { + writeText("sensitive data") + } + assertTrue(sensitiveFile.exists()) + + val maliciousUri = "file://${context.filesDir.absolutePath}/meal_photos/../databases/app_database.db" + val deleted = ImageUtils.deletePhotoFile(context, maliciousUri) + + assertFalse("Path traversal attempt should be rejected", deleted) + assertTrue("Sensitive file outside allowed folder must not be deleted", sensitiveFile.exists()) + } + + @Test + fun deletePhotoFile_externalAbsoluteFile_isBlocked() { + val otherFile = File(context.cacheDir, "cached_secret.txt").apply { + writeText("secret") + } + assertTrue(otherFile.exists()) + + val deleted = ImageUtils.deletePhotoFile(context, "file://${otherFile.absolutePath}") + assertFalse(deleted) + assertTrue(otherFile.exists()) + } + + @Test + fun deletePhotoFile_uncontextualMethod_blocksTraversal() { + assertFalse(ImageUtils.deletePhotoFile("/data/data/com.example/databases/secret.db")) + assertFalse(ImageUtils.deletePhotoFile("../meal_photos/secret.db")) + } +} diff --git a/app/src/test/java/com/example/LocalDatabaseTest.kt b/app/src/test/java/com/example/LocalDatabaseTest.kt index 34d67cd..21e48ec 100644 --- a/app/src/test/java/com/example/LocalDatabaseTest.kt +++ b/app/src/test/java/com/example/LocalDatabaseTest.kt @@ -24,7 +24,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) +@Config(sdk = [36]) class LocalDatabaseTest { private lateinit var db: AppDatabase diff --git a/app/src/test/java/com/example/ReminderPreferencesTest.kt b/app/src/test/java/com/example/ReminderPreferencesTest.kt index b737735..f4b1836 100644 --- a/app/src/test/java/com/example/ReminderPreferencesTest.kt +++ b/app/src/test/java/com/example/ReminderPreferencesTest.kt @@ -15,7 +15,7 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) +@Config(sdk = [36]) class ReminderPreferencesTest { private lateinit var context: Context diff --git a/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt b/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt index a5f224e..0e3ab1f 100644 --- a/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt +++ b/app/src/test/java/com/example/base/FirestoreEmulatorTestBase.kt @@ -22,7 +22,7 @@ import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode @RunWith(RobolectricTestRunner::class) -@Config(manifest = Config.NONE, sdk = [34]) +@Config(manifest = Config.NONE, sdk = [36]) @LooperMode(LooperMode.Mode.INSTRUMENTATION_TEST) abstract class FirestoreEmulatorTestBase { diff --git a/firestore.rules b/firestore.rules index eb028cc..06edf39 100644 --- a/firestore.rules +++ b/firestore.rules @@ -34,10 +34,10 @@ service cloud.firestore { data.mealTimestamp is int && data.mealTimestamp > 0 && data.hungerBefore is int && data.hungerBefore >= 1 && data.hungerBefore <= 10 && data.satietyAfter is int && data.satietyAfter >= 1 && data.satietyAfter <= 10 && - (!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 1000)) && - (!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || data.foodItemsSerialized[0] is string))) && - (!('photoUris' in data) || data.photoUris == null || (data.photoUris is list && data.photoUris.size() <= 6 && (data.photoUris.size() == 0 || data.photoUris[0] is string))) && - (!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 6 && (data.photosBase64.size() == 0 || data.photosBase64[0] is string))) && + (!('note' in data) || data.note == null || (data.note is string && data.note.size() <= 500)) && + (!('foodItemsSerialized' in data) || data.foodItemsSerialized == null || (data.foodItemsSerialized is list && data.foodItemsSerialized.size() <= 30 && (data.foodItemsSerialized.size() == 0 || (data.foodItemsSerialized[0] is string && data.foodItemsSerialized[0].size() <= 200)))) && + (!('photoUris' in data) || data.photoUris == null || (data.photoUris is list && data.photoUris.size() <= 4 && (data.photoUris.size() == 0 || (data.photoUris[0] is string && data.photoUris[0].size() <= 500)))) && + (!('photosBase64' in data) || data.photosBase64 == null || (data.photosBase64 is list && data.photosBase64.size() <= 4 && (data.photosBase64.size() == 0 || (data.photosBase64[0] is string && data.photosBase64[0].size() <= 200000)))) && (!('updatedAt' in data) || data.updatedAt == null || (data.updatedAt is timestamp && data.updatedAt <= request.time)); }