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
This commit is contained in:
bleackstorm committed 2026-11-11 09:48:50 +01:00
1 parent 3d1d0f43e7
commit 1d6e9a3752
17 files changed
+708 -23

No files matched your search

+12
View File
@@ -41,6 +41,18 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver
android:name=".widget.SatieaAppWidgetProvider"
android:exported="true"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/satiea_widget_info" />
</receiver>
<provider <provider
android:name="androidx.core.content.FileProvider" android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider" android:authorities="${applicationId}.fileprovider"
+37 -14
View File
@@ -64,6 +64,7 @@ import com.example.ui.settings.SettingsScreen
import com.example.ui.stats.WeeklyStatsScreen import com.example.ui.stats.WeeklyStatsScreen
import com.example.ui.theme.SatieaTheme import com.example.ui.theme.SatieaTheme
import com.example.util.CsvExporter import com.example.util.CsvExporter
import com.example.widget.SatieaAppWidgetProvider
import android.app.Activity import android.app.Activity
import android.content.Intent import android.content.Intent
import com.example.ui.journal.GoogleSheetsUiState import com.example.ui.journal.GoogleSheetsUiState
@@ -91,31 +92,37 @@ class MainActivity : ComponentActivity() {
MealNotificationManager.createNotificationChannel(this) MealNotificationManager.createNotificationChannel(this)
MealNotificationManager.scheduleAllActiveReminders(this) MealNotificationManager.scheduleAllActiveReminders(this)
val logMealRequested = intent?.action == MealNotificationManager.ACTION_LOG_MEAL handleIncomingIntent(intent)
val initialMealType = intent?.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
MealType.fromString(it)
} ?: MealType.LUNCH
setContent { setContent {
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle() val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
SatieaTheme(themeMode = themeMode) { SatieaTheme(themeMode = themeMode) {
AppRoot( AppRoot(viewModel = viewModel)
viewModel = viewModel,
openAddMealInitially = logMealRequested,
initialDefaultMealType = initialMealType
)
} }
} }
} }
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIncomingIntent(intent)
}
private fun handleIncomingIntent(intent: Intent?) {
if (intent?.action == MealNotificationManager.ACTION_LOG_MEAL) {
val parsedType = intent.getStringExtra(MealNotificationManager.EXTRA_MEAL_TYPE)?.let {
MealType.fromString(it)
} ?: SatieaAppWidgetProvider.suggestMealTypeForHour(java.time.LocalTime.now().hour)
viewModel.requestQuickLogMeal(parsedType)
}
}
} }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun AppRoot( fun AppRoot(
viewModel: MealViewModel, viewModel: MealViewModel
openAddMealInitially: Boolean,
initialDefaultMealType: MealType
) { ) {
var currentUser by remember { mutableStateOf(Firebase.auth.currentUser) } var currentUser by remember { mutableStateOf(Firebase.auth.currentUser) }
var showAuthSheet by remember { mutableStateOf(false) } var showAuthSheet by remember { mutableStateOf(false) }
@@ -151,9 +158,21 @@ fun AppRoot(
} }
var currentTab by remember { mutableStateOf(MainTab.JOURNAL) } var currentTab by remember { mutableStateOf(MainTab.JOURNAL) }
var showMealEntrySheet by remember { mutableStateOf(openAddMealInitially) } var showMealEntrySheet by remember { mutableStateOf(false) }
var editingMeal by remember { mutableStateOf<MealEntry?>(null) } var editingMeal by remember { mutableStateOf<MealEntry?>(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) } val prefs = remember { ReminderPreferencesManager.getInstance(context) }
var showPermissionRationaleDialog by remember { var showPermissionRationaleDialog by remember {
@@ -228,6 +247,10 @@ fun AppRoot(
val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle() val spreadsheetUrl by viewModel.spreadsheetUrl.collectAsStateWithLifecycle()
val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList() val currentMealsList = (mealsState as? MealsUiState.Success)?.meals ?: emptyList()
LaunchedEffect(Unit) {
SatieaAppWidgetProvider.updateAllWidgets(context)
}
val createCsvDocumentLauncher = rememberLauncherForActivityResult( val createCsvDocumentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("text/csv") contract = ActivityResultContracts.CreateDocument("text/csv")
) { targetUri: Uri? -> ) { targetUri: Uri? ->
@@ -14,6 +14,7 @@ import com.example.data.model.MealEntry
import com.example.util.CsvImportResult import com.example.util.CsvImportResult
import com.example.util.CsvImporter import com.example.util.CsvImporter
import com.example.util.ImageUtils import com.example.util.ImageUtils
import com.example.widget.SatieaAppWidgetProvider
import com.google.firebase.Firebase import com.google.firebase.Firebase
import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.auth import com.google.firebase.auth.auth
@@ -204,6 +205,7 @@ class MealRepository(
// 1. Always save to local SQLite Room first (Offline-First) // 1. Always save to local SQLite Room first (Offline-First)
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId)) localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(mealWithId))
SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. If user is signed in with Google, sync to Firestore // 2. If user is signed in with Google, sync to Firestore
val uid = getUserIdOrNull() val uid = getUserIdOrNull()
@@ -236,6 +238,7 @@ class MealRepository(
// 1. Update in local Room database // 1. Update in local Room database
localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal)) localMealDao?.insertMeal(LocalMealEntity.fromMealEntry(meal))
SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. If signed in, update Firestore // 2. If signed in, update Firestore
val uid = getUserIdOrNull() val uid = getUserIdOrNull()
@@ -279,6 +282,7 @@ class MealRepository(
// 2. Delete from local Room database // 2. Delete from local Room database
localMealDao?.deleteMealById(mealId) localMealDao?.deleteMealById(mealId)
SatieaAppWidgetProvider.updateAllWidgets(context)
// 3. If signed in, delete from Firestore // 3. If signed in, delete from Firestore
val uid = getUserIdOrNull() val uid = getUserIdOrNull()
@@ -348,6 +352,7 @@ class MealRepository(
// 1. Insert new meals into Room // 1. Insert new meals into Room
val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) } val localEntities = result.importedMeals.map { LocalMealEntity.fromMealEntry(it) }
localMealDao?.insertMeals(localEntities) localMealDao?.insertMeals(localEntities)
SatieaAppWidgetProvider.updateAllWidgets(context)
// 2. Enrich custom foods catalog in Room // 2. Enrich custom foods catalog in Room
val newCustomFoods = result.newFoodItems.map { item -> val newCustomFoods = result.newFoodItems.map { item ->
@@ -419,6 +424,7 @@ class MealRepository(
if (toInsertLocally.isNotEmpty()) { if (toInsertLocally.isNotEmpty()) {
localMealDao?.insertMeals(toInsertLocally) localMealDao?.insertMeals(toInsertLocally)
SatieaAppWidgetProvider.updateAllWidgets(context)
} }
// 3. Fetch remote custom foods // 3. Fetch remote custom foods
@@ -461,6 +467,7 @@ class MealRepository(
} }
if (toInsertMeals.isNotEmpty()) { if (toInsertMeals.isNotEmpty()) {
localMealDao.insertMeals(toInsertMeals) localMealDao.insertMeals(toInsertMeals)
SatieaAppWidgetProvider.updateAllWidgets(context)
} }
val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet() val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet()
@@ -231,18 +231,30 @@ class GoogleSheetsSyncUseCase(
} }
var token = tokenResult.getOrThrow() var token = tokenResult.getOrThrow()
val spreadsheetId = sheetsPrefs.spreadsheetId var findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(
if (spreadsheetId.isNullOrBlank()) { accessToken = token,
// Try finding it on Drive cachedSpreadsheetId = sheetsPrefs.spreadsheetId,
val findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, null, sheetsPrefs.rootFolderId) parentFolderId = sheetsPrefs.rootFolderId
if (findResult.isFailure) { )
return@withContext SheetsRestoreResult.Failure("Aucun classeur Satiéa trouvé sur Google Drive") 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) var readResult = GoogleSheetsSyncService.readSpreadsheetData(token, targetId)
if (readResult.isFailure && readResult.exceptionOrNull() is AuthExpiredException) { if (readResult.isFailure && readResult.exceptionOrNull() is AuthExpiredException) {
GoogleSheetsAuthHelper.invalidateToken(context, token) GoogleSheetsAuthHelper.invalidateToken(context, token)
@@ -146,6 +146,18 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val _themeMode = MutableStateFlow(AppThemeMode.DARK) private val _themeMode = MutableStateFlow(AppThemeMode.DARK)
val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow() val themeMode: StateFlow<AppThemeMode> = _themeMode.asStateFlow()
// Quick Log Action triggered from Widget or Notification
private val _quickLogMealRequest = MutableStateFlow<MealType?>(null)
val quickLogMealRequest: StateFlow<MealType?> = _quickLogMealRequest.asStateFlow()
fun requestQuickLogMeal(mealType: MealType) {
_quickLogMealRequest.value = mealType
}
fun consumeQuickLogMealRequest() {
_quickLogMealRequest.value = null
}
private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>( private val _sheetsUiState = MutableStateFlow<GoogleSheetsUiState>(
if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) { if (sheetsPrefs.lastSyncTimestamp > 0 && sheetsPrefs.spreadsheetUrl != null) {
GoogleSheetsUiState.Success( GoogleSheetsUiState.Success(
@@ -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<MealEntry>,
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<MealEntry> {
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
)
}
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#8CD4A8" />
<corners android:radius="999dp" />
</shape>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#191F1C" />
<corners android:radius="24dp" />
<stroke
android:width="1dp"
android:color="#2C362F" />
</shape>
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#1E482E" />
<corners android:radius="8dp" />
</shape>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#242C27" />
<corners android:radius="16dp" />
<stroke
android:width="1dp"
android:color="#2C362F" />
</shape>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#242C27" />
<corners android:radius="999dp" />
<stroke
android:width="1dp"
android:color="#36423A" />
</shape>
+181
View File
@@ -0,0 +1,181 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/widget_background"
android:orientation="vertical"
android:padding="14dp">
<!-- Header Row: Satiéa Title + Daily Summary + Add Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/widget_header_info"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/widget_brand_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Satiéa • Journal"
android:textColor="#8CD4A8"
android:textSize="13sp"
android:textStyle="bold" />
<TextView
android:id="@+id/widget_today_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Aujourd'hui : 0 repas"
android:textColor="#BAC3BC"
android:textSize="11sp" />
</LinearLayout>
<TextView
android:id="@+id/widget_btn_add_meal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/widget_add_button_bg"
android:paddingStart="12dp"
android:paddingTop="6dp"
android:paddingEnd="12dp"
android:paddingBottom="6dp"
android:text="+ Repas"
android:textColor="#0F3820"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
<!-- Last Meal Card -->
<LinearLayout
android:id="@+id/widget_last_meal_card"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="@drawable/widget_card_background"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingStart="12dp"
android:paddingTop="8dp"
android:paddingEnd="12dp"
android:paddingBottom="8dp">
<TextView
android:id="@+id/widget_last_meal_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:text="Aucun repas enregistré"
android:textColor="#E2E7E2"
android:textSize="13sp"
android:textStyle="bold" />
<TextView
android:id="@+id/widget_last_meal_foods"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:ellipsize="end"
android:maxLines="1"
android:text="Touchez « + Repas » pour noter votre ressenti"
android:textColor="#BAC3BC"
android:textSize="12sp" />
<TextView
android:id="@+id/widget_last_meal_satiety"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@drawable/widget_badge_optimal_bg"
android:ellipsize="end"
android:maxLines="1"
android:paddingStart="8dp"
android:paddingTop="2dp"
android:paddingEnd="8dp"
android:paddingBottom="2dp"
android:text="Écoute corporelle Faim &amp; Satiété"
android:textColor="#C5F2D7"
android:textSize="11sp" />
</LinearLayout>
<!-- Quick Meal Type Shortcuts Row -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/widget_chip_breakfast"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:layout_weight="1"
android:background="@drawable/widget_quick_chip_bg"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="☕ Matin"
android:textColor="#E2E7E2"
android:textSize="11sp" />
<TextView
android:id="@+id/widget_chip_lunch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginEnd="2dp"
android:layout_weight="1"
android:background="@drawable/widget_quick_chip_bg"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="🥗 Midi"
android:textColor="#E2E7E2"
android:textSize="11sp" />
<TextView
android:id="@+id/widget_chip_snack"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="2dp"
android:layout_marginEnd="2dp"
android:layout_weight="1"
android:background="@drawable/widget_quick_chip_bg"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="🍎 Goûter"
android:textColor="#E2E7E2"
android:textSize="11sp" />
<TextView
android:id="@+id/widget_chip_dinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_weight="1"
android:background="@drawable/widget_quick_chip_bg"
android:gravity="center"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:text="🍲 Soir"
android:textColor="#E2E7E2"
android:textSize="11sp" />
</LinearLayout>
</LinearLayout>
+1
View File
@@ -1,3 +1,4 @@
<resources> <resources>
<string name="app_name">Satiéa</string> <string name="app_name">Satiéa</string>
<string name="widget_description">Aperçu du dernier repas, bilan faim/satiété du jour et ajout rapide en un geste.</string>
</resources> </resources>
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_description"
android:initialLayout="@layout/widget_satiea"
android:minWidth="250dp"
android:minHeight="140dp"
android:minResizeWidth="180dp"
android:minResizeHeight="110dp"
android:previewLayout="@layout/widget_satiea"
android:resizeMode="horizontal|vertical"
android:targetCellWidth="4"
android:targetCellHeight="2"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen" />
@@ -152,6 +152,7 @@ class GoogleSheetsDataFormatterTest {
assertEquals("https://drive.google.com/file/1", rows[1][9]) assertEquals("https://drive.google.com/file/1", rows[1][9])
} }
@Test
@Test @Test
fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() { fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() {
val range = "'Journal des repas'!A1" val range = "'Journal des repas'!A1"
@@ -161,6 +162,9 @@ class GoogleSheetsDataFormatterTest {
val foodRange = "'Mes plats et aliments'!A1:C" val foodRange = "'Mes plats et aliments'!A1:C"
val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange) val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange)
assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded) assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded)
assertTrue(!encoded.contains("+"))
assertTrue(!foodEncoded.contains("+"))
}
} }
} }
@@ -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)
}
}
Vendored Regular → Executable
View File
File mode changed.