From 1d6e9a37529dc880102b7490963536601a7e25c9 Mon Sep 17 00:00:00 2001 From: bleackstorm <49142331+bleackstorm@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:25:45 +0100 Subject: [PATCH] feat(widget): implement home screen widget and fix Google Sheets range synchronization - Add SatieaAppWidgetProvider with last meal recap, daily summary, and 1-tap logging shortcuts - Implement reactive UDF quick-log action in MealViewModel and MainActivity - Safeguard widget updates against concurrency with debounced SupervisorJob scope - Migrate Google Sheets tab names automatically and encode range URLs per RFC 3986 - Add unit tests for widget UI model formatting and range encoding --- app/src/main/AndroidManifest.xml | 12 + app/src/main/java/com/example/MainActivity.kt | 51 ++- .../example/data/repository/MealRepository.kt | 7 + .../example/domain/GoogleSheetsSyncUseCase.kt | 30 +- .../com/example/ui/journal/MealViewModel.kt | 12 + .../example/widget/SatieaAppWidgetProvider.kt | 294 ++++++++++++++++++ .../res/drawable/widget_add_button_bg.xml | 6 + .../main/res/drawable/widget_background.xml | 9 + .../res/drawable/widget_badge_optimal_bg.xml | 6 + .../res/drawable/widget_card_background.xml | 9 + .../res/drawable/widget_quick_chip_bg.xml | 9 + app/src/main/res/layout/widget_satiea.xml | 181 +++++++++++ app/src/main/res/values/strings.xml | 1 + app/src/main/res/xml/satiea_widget_info.xml | 14 + .../example/GoogleSheetsDataFormatterTest.kt | 4 + .../java/com/example/SatieaWidgetModelTest.kt | 86 +++++ gradlew | 0 17 files changed, 708 insertions(+), 23 deletions(-) create mode 100644 app/src/main/java/com/example/widget/SatieaAppWidgetProvider.kt create mode 100644 app/src/main/res/drawable/widget_add_button_bg.xml create mode 100644 app/src/main/res/drawable/widget_background.xml create mode 100644 app/src/main/res/drawable/widget_badge_optimal_bg.xml create mode 100644 app/src/main/res/drawable/widget_card_background.xml create mode 100644 app/src/main/res/drawable/widget_quick_chip_bg.xml create mode 100644 app/src/main/res/layout/widget_satiea.xml create mode 100644 app/src/main/res/xml/satiea_widget_info.xml create mode 100644 app/src/test/java/com/example/SatieaWidgetModelTest.kt mode change 100644 => 100755 gradlew diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 8e2e10c..f417dc6 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,6 +41,18 @@ + + + + + + + (null) } - var defaultMealType by remember { mutableStateOf(initialDefaultMealType) } + var defaultMealType by remember { mutableStateOf(MealType.LUNCH) } + + // React to quick log meal requests from Widget or Notification + val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle() + LaunchedEffect(quickLogMealType) { + quickLogMealType?.let { requestedType -> + currentTab = MainTab.JOURNAL + editingMeal = null + defaultMealType = requestedType + showMealEntrySheet = true + viewModel.consumeQuickLogMealRequest() + } + } val prefs = remember { ReminderPreferencesManager.getInstance(context) } var showPermissionRationaleDialog by remember { @@ -228,6 +247,10 @@ fun AppRoot( val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle() val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList() + LaunchedEffect(Unit) { + SatieaAppWidgetProvider.updateAllWidgets(context) + } + val createCsvDocumentLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.CreateDocument("text/csv") ) { targetUri: Uri? -> 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 da5819d..5c1ddf5 100644 --- a/app/src/main/java/com/example/data/repository/MealRepository.kt +++ b/app/src/main/java/com/example/data/repository/MealRepository.kt @@ -14,6 +14,7 @@ import com.example.data.model.MealEntry import com.example.util.CsvImportResult import com.example.util.CsvImporter import com.example.util.ImageUtils +import com.example.widget.SatieaAppWidgetProvider import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth @@ -204,6 +205,7 @@ class MealRepository( // 1. Always save to local SQLite Room first (Offline-First) localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId)) + SatieaAppWidgetProvider.updateAllWidgets(context) // 2. If user is signed in with Google, sync to Firestore val uid = getUserIdOrNull() @@ -236,6 +238,7 @@ class MealRepository( // 1. Update in local Room database localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal)) + SatieaAppWidgetProvider.updateAllWidgets(context) // 2. If signed in, update Firestore val uid = getUserIdOrNull() @@ -279,6 +282,7 @@ class MealRepository( // 2. Delete from local Room database localMealDao?.deleteMealById(mealId) + SatieaAppWidgetProvider.updateAllWidgets(context) // 3. If signed in, delete from Firestore val uid = getUserIdOrNull() @@ -348,6 +352,7 @@ class MealRepository( // 1. Insert new meals into Room val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) } localMealDao?.insertMeals(localEntities) + SatieaAppWidgetProvider.updateAllWidgets(context) // 2. Enrich custom foods catalog in Room val newCustomFoods = result.newFoodItems.map { item -> @@ -419,6 +424,7 @@ class MealRepository( if (toInsertLocally.isNotEmpty()) { localMealDao?.insertMeals(toInsertLocally) + SatieaAppWidgetProvider.updateAllWidgets(context) } // 3. Fetch remote custom foods @@ -461,6 +467,7 @@ class MealRepository( } if (toInsertMeals.isNotEmpty()) { localMealDao.insertMeals(toInsertMeals) + SatieaAppWidgetProvider.updateAllWidgets(context) } val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet() diff --git a/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt index 64d9d7a..cdc03dc 100644 --- a/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt +++ b/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt @@ -231,18 +231,30 @@ class GoogleSheetsSyncUseCase( } var token = tokenResult.getOrThrow() - val spreadsheetId = sheetsPrefs.spreadsheetId - if (spreadsheetId.isNullOrBlank()) { - // Try finding it on Drive - val findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, null, sheetsPrefs.rootFolderId) - if (findResult.isFailure) { - return@withContext SheetsRestoreResult.Failure("Aucun classeur Satiéa trouvé sur Google Drive") + var findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet( + accessToken = token, + cachedSpreadsheetId = sheetsPrefs.spreadsheetId, + parentFolderId = sheetsPrefs.rootFolderId + ) + if (findResult.isFailure && findResult.exceptionOrNull() is AuthExpiredException) { + GoogleSheetsAuthHelper.invalidateToken(context, token) + val refreshed = GoogleSheetsAuthHelper.getAccessToken(context) + if (refreshed.isSuccess) { + token = refreshed.getOrThrow() + findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet( + accessToken = token, + cachedSpreadsheetId = sheetsPrefs.spreadsheetId, + parentFolderId = sheetsPrefs.rootFolderId + ) } - sheetsPrefs.spreadsheetId = findResult.getOrThrow().first - sheetsPrefs.spreadsheetUrl = findResult.getOrThrow().second } + if (findResult.isFailure) { + return@withContext SheetsRestoreResult.Failure("Aucun classeur Satiéa accessible sur Google Drive") + } + val (targetId, targetUrl) = findResult.getOrThrow() + sheetsPrefs.spreadsheetId = targetId + sheetsPrefs.spreadsheetUrl = targetUrl - val targetId = sheetsPrefs.spreadsheetId ?: return@withContext SheetsRestoreResult.Failure("Classeur introuvable") var readResult = GoogleSheetsSyncService.readSpreadsheetData(token, targetId) if (readResult.isFailure && readResult.exceptionOrNull() is AuthExpiredException) { GoogleSheetsAuthHelper.invalidateToken(context, token) 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 cf0a9ef..a3a2dee 100644 --- a/app/src/main/java/com/example/ui/journal/MealViewModel.kt +++ b/app/src/main/java/com/example/ui/journal/MealViewModel.kt @@ -146,6 +146,18 @@ class MealViewModel(application: Application) : AndroidViewModel(application) { private val _themeMode = MutableStateFlow(AppThemeMode.DARK) val themeMode: StateFlow = _themeMode.asStateFlow() + // Quick Log Action triggered from Widget or Notification + private val _quickLogMealRequest = MutableStateFlow(null) + val quickLogMealRequest: StateFlow = _quickLogMealRequest.asStateFlow() + + fun requestQuickLogMeal(mealType: MealType) { + _quickLogMealRequest.value = mealType + } + + fun consumeQuickLogMealRequest() { + _quickLogMealRequest.value = null + } + private val _sheetsUiState = MutableStateFlow( if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) { GoogleSheetsUiState.Success( diff --git a/app/src/main/java/com/example/widget/SatieaAppWidgetProvider.kt b/app/src/main/java/com/example/widget/SatieaAppWidgetProvider.kt new file mode 100644 index 0000000..7f4e16d --- /dev/null +++ b/app/src/main/java/com/example/widget/SatieaAppWidgetProvider.kt @@ -0,0 +1,294 @@ +package com.example.widget + +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.util.Log +import android.widget.RemoteViews +import com.example.MainActivity +import com.example.R +import com.example.data.local.AppDatabase +import com.example.data.model.MealEntry +import com.example.data.model.MealType +import com.example.notification.MealNotificationManager +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.util.Locale + +data class SatieaWidgetUiModel( + val todaySubtitle: String, + val lastMealTitle: String, + val lastMealFoods: String, + val lastMealSatietyBadge: String, + val suggestedMealType: MealType +) + +class SatieaAppWidgetProvider : AppWidgetProvider() { + + override fun onUpdate( + context: Context, + appWidgetManager: AppWidgetManager, + appWidgetIds: IntArray + ) { + val pendingResult = goAsync() + widgetScope.launch { + try { + val meals = loadMealsFromDb(context) + val uiModel = buildWidgetUiModel(meals) + for (widgetId in appWidgetIds) { + val views = buildRemoteViews(context, widgetId, uiModel) + appWidgetManager.updateAppWidget(widgetId, views) + } + } catch (e: Exception) { + Log.w(TAG, "Failed to update Satiéa widget: ${e.message}") + } finally { + pendingResult.finish() + } + } + } + + companion object { + private const val TAG = "SatieaWidget" + private val widgetScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + @Volatile private var updateJob: Job? = null + + private val TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH) + private val SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("d MMM", Locale.FRENCH) + + fun suggestMealTypeForHour(hour: Int): MealType { + return when (hour) { + in 5..10 -> MealType.BREAKFAST + in 11..14 -> MealType.LUNCH + in 15..18 -> MealType.SNACK + else -> MealType.DINNER + } + } + + fun mealTypeEmoji(type: MealType): String { + return when (type) { + MealType.BREAKFAST -> "☕" + MealType.LUNCH -> "🥗" + MealType.SNACK -> "🍎" + MealType.DINNER -> "🍲" + } + } + + fun buildWidgetUiModel( + meals: List, + nowMillis: Long = System.currentTimeMillis(), + zoneId: ZoneId = ZoneId.systemDefault() + ): SatieaWidgetUiModel { + val nowZoned = Instant.ofEpochMilli(nowMillis).atZone(zoneId) + val todayDate = nowZoned.toLocalDate() + val suggestedType = suggestMealTypeForHour(nowZoned.hour) + + val startOfToday = todayDate.atStartOfDay(zoneId).toInstant().toEpochMilli() + val endOfToday = todayDate.plusDays(1).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1 + val todayMeals = meals.filter { it.mealTimestamp in startOfToday..endOfToday } + + val startOf7Days = todayDate.minusDays(6).atStartOfDay(zoneId).toInstant().toEpochMilli() + val recent7DaysMeals = meals.filter { it.mealTimestamp in startOf7Days..endOfToday } + + val todayCountLabel = when (todayMeals.size) { + 0 -> "Aujourd'hui : aucun repas" + 1 -> "Aujourd'hui : 1 repas" + else -> "Aujourd'hui : ${todayMeals.size} repas" + } + + val todaySubtitle = if (recent7DaysMeals.isNotEmpty()) { + val optimalCount = recent7DaysMeals.count { it.satietyAfter in 6..8 } + val optimalPct = ((optimalCount.toFloat() / recent7DaysMeals.size) * 100).toInt() + "$todayCountLabel • Zone optimale $optimalPct %" + } else { + "$todayCountLabel • Prêt à noter" + } + + val latestMeal = meals.maxByOrNull { it.mealTimestamp } + if (latestMeal == null) { + return SatieaWidgetUiModel( + todaySubtitle = todaySubtitle, + lastMealTitle = "Aucun repas enregistré", + lastMealFoods = "Touchez « + Repas » pour noter votre ressenti", + lastMealSatietyBadge = "Écoute corporelle Faim & Satiété", + suggestedMealType = suggestedType + ) + } + + val mealType = MealType.fromString(latestMeal.mealType) + val mealZoned = Instant.ofEpochMilli(latestMeal.mealTimestamp).atZone(zoneId) + val mealDate: LocalDate = mealZoned.toLocalDate() + val timeStr = TIME_FORMATTER.format(mealZoned) + + val dayPrefix = when (mealDate) { + todayDate -> "Aujourd'hui à $timeStr" + todayDate.minusDays(1) -> "Hier à $timeStr" + else -> "${SHORT_DATE_FORMATTER.format(mealDate)} à $timeStr" + } + + val lastMealTitle = "${mealTypeEmoji(mealType)} ${mealType.displayName} • $dayPrefix" + + val parsedFoods = latestMeal.parsedFoodItems() + val lastMealFoods = when { + parsedFoods.isNotEmpty() -> parsedFoods.joinToString(", ") { it.displayBadge() } + latestMeal.note.isNotBlank() -> latestMeal.note.trim() + else -> "Ressenti enregistré sans aliment détaillé" + } + + val isOptimal = latestMeal.satietyAfter in 6..8 + val optimalSuffix = if (isOptimal) " • Zone optimale ✨" else "" + val lastMealSatietyBadge = + "Faim ${latestMeal.hungerBefore}/10 → Satiété ${latestMeal.satietyAfter}/10$optimalSuffix" + + return SatieaWidgetUiModel( + todaySubtitle = todaySubtitle, + lastMealTitle = lastMealTitle, + lastMealFoods = lastMealFoods, + lastMealSatietyBadge = lastMealSatietyBadge, + suggestedMealType = suggestedType + ) + } + + fun updateAllWidgets(context: Context?) { + val appContext = context?.applicationContext ?: return + val previousJob = updateJob + updateJob = widgetScope.launch { + previousJob?.cancel() + try { + val manager = AppWidgetManager.getInstance(appContext) + val componentName = ComponentName(appContext, SatieaAppWidgetProvider::class.java) + val widgetIds = manager.getAppWidgetIds(componentName) + if (widgetIds.isEmpty()) return@launch + + val meals = loadMealsFromDb(appContext) + val uiModel = buildWidgetUiModel(meals) + for (widgetId in widgetIds) { + val views = buildRemoteViews(appContext, widgetId, uiModel) + manager.updateAppWidget(widgetId, views) + } + } catch (e: Exception) { + Log.w(TAG, "Skipped widget refresh: ${e.message}") + } + } + } + + private suspend fun loadMealsFromDb(context: Context): List { + return AppDatabase.getInstance(context) + .mealDao() + .getAllMealsOnce() + .map { it.toMealEntry() } + } + + private fun buildRemoteViews( + context: Context, + widgetId: Int, + model: SatieaWidgetUiModel + ): RemoteViews { + val views = RemoteViews(context.packageName, R.layout.widget_satiea) + + views.setTextViewText(R.id.widget_today_subtitle, model.todaySubtitle) + views.setTextViewText(R.id.widget_last_meal_title, model.lastMealTitle) + views.setTextViewText(R.id.widget_last_meal_foods, model.lastMealFoods) + views.setTextViewText(R.id.widget_last_meal_satiety, model.lastMealSatietyBadge) + + // Open Journal when clicking the card or header + val openJournalPendingIntent = createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10, + logMeal = false, + mealType = null + ) + views.setOnClickPendingIntent(R.id.widget_last_meal_card, openJournalPendingIntent) + views.setOnClickPendingIntent(R.id.widget_header_info, openJournalPendingIntent) + + // Main "+ Repas" button -> opens MealEntrySheet with smart hour-based MealType + views.setOnClickPendingIntent( + R.id.widget_btn_add_meal, + createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10 + 1, + logMeal = true, + mealType = model.suggestedMealType + ) + ) + + // Quick meal type chips + views.setOnClickPendingIntent( + R.id.widget_chip_breakfast, + createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10 + 2, + logMeal = true, + mealType = MealType.BREAKFAST + ) + ) + views.setOnClickPendingIntent( + R.id.widget_chip_lunch, + createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10 + 3, + logMeal = true, + mealType = MealType.LUNCH + ) + ) + views.setOnClickPendingIntent( + R.id.widget_chip_snack, + createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10 + 4, + logMeal = true, + mealType = MealType.SNACK + ) + ) + views.setOnClickPendingIntent( + R.id.widget_chip_dinner, + createOpenAppPendingIntent( + context = context, + requestCode = widgetId * 10 + 5, + logMeal = true, + mealType = MealType.DINNER + ) + ) + + return views + } + + private fun createOpenAppPendingIntent( + context: Context, + requestCode: Int, + logMeal: Boolean, + mealType: MealType? + ): PendingIntent { + val intent = Intent(context, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP + if (logMeal) { + action = MealNotificationManager.ACTION_LOG_MEAL + data = Uri.parse("satiea://widget/log/${mealType?.name ?: "default"}/$requestCode") + if (mealType != null) { + putExtra(MealNotificationManager.EXTRA_MEAL_TYPE, mealType.name) + } + } else { + action = Intent.ACTION_MAIN + addCategory(Intent.CATEGORY_LAUNCHER) + data = Uri.parse("satiea://widget/view/$requestCode") + } + } + return PendingIntent.getActivity( + context, + requestCode, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + } + } +} diff --git a/app/src/main/res/drawable/widget_add_button_bg.xml b/app/src/main/res/drawable/widget_add_button_bg.xml new file mode 100644 index 0000000..c462369 --- /dev/null +++ b/app/src/main/res/drawable/widget_add_button_bg.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/app/src/main/res/drawable/widget_background.xml b/app/src/main/res/drawable/widget_background.xml new file mode 100644 index 0000000..8e3846a --- /dev/null +++ b/app/src/main/res/drawable/widget_background.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/src/main/res/drawable/widget_badge_optimal_bg.xml b/app/src/main/res/drawable/widget_badge_optimal_bg.xml new file mode 100644 index 0000000..0b482f2 --- /dev/null +++ b/app/src/main/res/drawable/widget_badge_optimal_bg.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/app/src/main/res/drawable/widget_card_background.xml b/app/src/main/res/drawable/widget_card_background.xml new file mode 100644 index 0000000..7abf0b9 --- /dev/null +++ b/app/src/main/res/drawable/widget_card_background.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/src/main/res/drawable/widget_quick_chip_bg.xml b/app/src/main/res/drawable/widget_quick_chip_bg.xml new file mode 100644 index 0000000..6bd8f38 --- /dev/null +++ b/app/src/main/res/drawable/widget_quick_chip_bg.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/src/main/res/layout/widget_satiea.xml b/app/src/main/res/layout/widget_satiea.xml new file mode 100644 index 0000000..a32f560 --- /dev/null +++ b/app/src/main/res/layout/widget_satiea.xml @@ -0,0 +1,181 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index da233c4..655460d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,4 @@ Satiéa + Aperçu du dernier repas, bilan faim/satiété du jour et ajout rapide en un geste. diff --git a/app/src/main/res/xml/satiea_widget_info.xml b/app/src/main/res/xml/satiea_widget_info.xml new file mode 100644 index 0000000..f55dfc3 --- /dev/null +++ b/app/src/main/res/xml/satiea_widget_info.xml @@ -0,0 +1,14 @@ + + diff --git a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt index c784dd4..fe90953 100644 --- a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt +++ b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt @@ -152,6 +152,7 @@ class GoogleSheetsDataFormatterTest { assertEquals("https://drive.google.com/file/1", rows[1][9]) } + @Test @Test fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() { val range = "'Journal des repas'!A1" @@ -161,6 +162,9 @@ class GoogleSheetsDataFormatterTest { val foodRange = "'Mes plats et aliments'!A1:C" val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange) assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded) + assertTrue(!encoded.contains("+")) + assertTrue(!foodEncoded.contains("+")) + } } } diff --git a/app/src/test/java/com/example/SatieaWidgetModelTest.kt b/app/src/test/java/com/example/SatieaWidgetModelTest.kt new file mode 100644 index 0000000..810dc0e --- /dev/null +++ b/app/src/test/java/com/example/SatieaWidgetModelTest.kt @@ -0,0 +1,86 @@ +package com.example + +import com.example.data.model.FoodUnit +import com.example.data.model.MealEntry +import com.example.data.model.MealFoodItem +import com.example.data.model.MealType +import com.example.widget.SatieaAppWidgetProvider +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDateTime +import java.time.ZoneId + +class SatieaWidgetModelTest { + + private val testZone = ZoneId.of("Europe/Paris") + + @Test + fun `suggestMealTypeForHour returns right meal type for each time window`() { + assertEquals(MealType.BREAKFAST, SatieaAppWidgetProvider.suggestMealTypeForHour(8)) + assertEquals(MealType.LUNCH, SatieaAppWidgetProvider.suggestMealTypeForHour(12)) + assertEquals(MealType.SNACK, SatieaAppWidgetProvider.suggestMealTypeForHour(16)) + assertEquals(MealType.DINNER, SatieaAppWidgetProvider.suggestMealTypeForHour(20)) + assertEquals(MealType.DINNER, SatieaAppWidgetProvider.suggestMealTypeForHour(1)) + } + + @Test + fun `buildWidgetUiModel with empty meal list shows onboarding state`() { + val nowMillis = LocalDateTime.of(2026, 11, 9, 12, 45) + .atZone(testZone).toInstant().toEpochMilli() + + val model = SatieaAppWidgetProvider.buildWidgetUiModel( + meals = emptyList(), + nowMillis = nowMillis, + zoneId = testZone + ) + + assertEquals("Aujourd'hui : aucun repas • Prêt à noter", model.todaySubtitle) + assertEquals("Aucun repas enregistré", model.lastMealTitle) + assertEquals(MealType.LUNCH, model.suggestedMealType) + } + + @Test + fun `buildWidgetUiModel formats latest meal and daily optimal percentage`() { + val nowMillis = LocalDateTime.of(2026, 11, 9, 14, 0) + .atZone(testZone).toInstant().toEpochMilli() + + val breakfastMillis = LocalDateTime.of(2026, 11, 9, 8, 15) + .atZone(testZone).toInstant().toEpochMilli() + val lunchMillis = LocalDateTime.of(2026, 11, 9, 12, 30) + .atZone(testZone).toInstant().toEpochMilli() + + val breakfast = MealEntry( + id = "b1", + mealType = MealType.BREAKFAST.name, + mealTimestamp = breakfastMillis, + hungerBefore = 4, + satietyAfter = 7, + foodItemsSerialized = listOf(MealFoodItem("Flocons d'avoine", 60.0, FoodUnit.G).serialize()) + ) + + val lunch = MealEntry( + id = "l1", + mealType = MealType.LUNCH.name, + mealTimestamp = lunchMillis, + hungerBefore = 3, + satietyAfter = 7, + foodItemsSerialized = listOf( + MealFoodItem("Riz complet", 150.0, FoodUnit.G).serialize(), + MealFoodItem("Saumon", 120.0, FoodUnit.G).serialize() + ) + ) + + val model = SatieaAppWidgetProvider.buildWidgetUiModel( + meals = listOf(breakfast, lunch), + nowMillis = nowMillis, + zoneId = testZone + ) + + assertEquals("Aujourd'hui : 2 repas • Zone optimale 100 %", model.todaySubtitle) + assertEquals("🥗 Déjeuner • Aujourd'hui à 12:30", model.lastMealTitle) + assertTrue(model.lastMealFoods.contains("Riz complet")) + assertTrue(model.lastMealFoods.contains("Saumon")) + assertEquals("Faim 3/10 → Satiété 7/10 • Zone optimale ✨", model.lastMealSatietyBadge) + } +} diff --git a/gradlew b/gradlew old mode 100644 new mode 100755