From 3f070129c704d28fa42db5fe7031edd7842cc7e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 19:20:15 +0000 Subject: [PATCH] Drinks and meals count each other A meal that names a drink now always becomes drink entries, whether or not Drinks is switched on. A drink logged on the Drinks card, the Today tile or by the coach also lands in the meal log as a snack with its calories and carbs, so the day's calorie count includes it. Removing one of those drinks shrinks or removes its snack; a meal the user typed is left alone. Claude-Session: https://claude.ai/code/session_01P1t1aUqSUPd3whKXmgVm7w --- .../com/pulseloop/service/DrinkInsights.kt | 17 ++-- .../com/pulseloop/service/DrinksRepository.kt | 78 ++++++++++++++++--- .../java/com/pulseloop/ui/screens/DrinksUi.kt | 10 +-- .../pulseloop/service/DrinkInsightsTest.kt | 8 ++ 4 files changed, 91 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/com/pulseloop/service/DrinkInsights.kt b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt index d78af141..976f80a1 100644 --- a/app/src/main/java/com/pulseloop/service/DrinkInsights.kt +++ b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt @@ -11,15 +11,16 @@ import kotlin.math.roundToInt */ /** A drink as logged, with typical Brazilian and international sizes. */ -enum class DrinkType(val key: String, val label: String, val volumeMl: Double, val abvPct: Double, val kcal: Double) { - BEER("beer", "Beer (can)", 350.0, 5.0, 150.0), - BEER_600("beer_600", "Beer (600 ml)", 600.0, 5.0, 255.0), - DRAFT("draft", "Chopp", 300.0, 5.0, 130.0), - WINE("wine", "Wine", 150.0, 12.0, 125.0), +/** [carbsG] per drink, rough label values, so a drink logged from the Drinks card fills the meal log's macros too. */ +enum class DrinkType(val key: String, val label: String, val volumeMl: Double, val abvPct: Double, val kcal: Double, val carbsG: Double = 0.0) { + BEER("beer", "Beer (can)", 350.0, 5.0, 150.0, 12.0), + BEER_600("beer_600", "Beer (600 ml)", 600.0, 5.0, 255.0, 21.0), + DRAFT("draft", "Chopp", 300.0, 5.0, 130.0, 11.0), + WINE("wine", "Wine", 150.0, 12.0, 125.0, 4.0), SPIRIT("spirit", "Spirit (shot)", 40.0, 40.0, 95.0), - CAIPIRINHA("caipirinha", "Caipirinha", 50.0, 40.0, 240.0), - COCKTAIL("cocktail", "Cocktail", 50.0, 40.0, 200.0), - OTHER("other", "Cider / other", 330.0, 4.5, 140.0); + CAIPIRINHA("caipirinha", "Caipirinha", 50.0, 40.0, 240.0, 25.0), + COCKTAIL("cocktail", "Cocktail", 50.0, 40.0, 200.0, 15.0), + OTHER("other", "Cider / other", 330.0, 4.5, 140.0, 12.0); val grams: Double get() = DrinkInsights.grams(volumeMl, abvPct) diff --git a/app/src/main/java/com/pulseloop/service/DrinksRepository.kt b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt index d766495f..d4ef813e 100644 --- a/app/src/main/java/com/pulseloop/service/DrinksRepository.kt +++ b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt @@ -87,9 +87,20 @@ object DrinksRepository { private fun dayStart(d: LocalDate, zone: ZoneId) = d.atStartOfDay(zone).toInstant().toEpochMilli() private fun dateOf(ms: Long, zone: ZoneId) = Instant.ofEpochMilli(ms).atZone(zone).toLocalDate() + /** Marks a meal the Drinks card created, so removing one of its drinks can restate it. */ + const val MEAL_NOTE = "Logged from Drinks" + + /** The meal-log name for [count] drinks of [type]: "Beer (can)" or "2 × Wine". */ + fun mealName(type: DrinkType, count: Int): String = if (count <= 1) type.label else "$count × ${type.label}" + /** * Log [count] drinks of [type] at [timestamp]. Each drink is its own row, so one can be removed. * Ticks the journal's Alcohol tag for that evening, so "What affects you" keeps working. + * + * A drink logged on its own (no [mealId]) also lands in the meal log as a snack carrying its + * calories, so the day's calorie count includes it. That meal is written straight to the table + * rather than through [MealJournal.afterLog]: logging a beer must not switch nutrition tracking + * on, and the drinks already point at the meal, so [fromMeal] has nothing to add. */ suspend fun log( db: PulseLoopDatabase, @@ -103,10 +114,26 @@ object DrinksRepository { ): List { val evening = MealJournal.eveningOf(timestamp, zone) val day = dayStart(evening, zone) - val rows = (0 until count.coerceIn(1, 12)).map { + val n = count.coerceIn(1, 12) + val linkedMeal = mealId ?: runCatching { + val meal = MealEntryEntity( + date = dayStart(dateOf(timestamp, zone), zone), + timestamp = timestamp, + name = mealName(type, n), + mealTypeRaw = "snack", + calories = type.kcal * n, + carbsG = type.carbsG * n, + servingDescription = type.label, + quantity = n.toDouble(), + notes = MEAL_NOTE, + ) + db.mealEntryDao().upsert(meal) + meal.id + }.getOrNull() + val rows = (0 until n).map { DrinkEntryEntity( timestamp = timestamp, day = day, type = type.key, volumeMl = type.volumeMl, abvPct = type.abvPct, - grams = type.grams, kcal = type.kcal, price = price, mealId = mealId, note = note, + grams = type.grams, kcal = type.kcal, price = price, mealId = linkedMeal, note = note, ) } rows.forEach { db.drinkDao().upsert(it) } @@ -117,21 +144,54 @@ object DrinksRepository { } /** - * A logged meal that names a drink becomes drink entries too, so nobody logs twice. Skipped - * when Drinks is off, when the meal already has drinks, or when the same kind of drink was - * logged on its own within 30 minutes. + * Remove one drink. When the Drinks card created its meal, the meal shrinks with it (and goes + * once its last drink does), so the calorie count follows. A meal the user logged themselves + * ("2 beers and fries") is left alone: its calories aren't only the drink's. + */ + suspend fun delete(db: PulseLoopDatabase, entry: DrinkEntryEntity) { + db.drinkDao().delete(entry.id) + val mealId = entry.mealId ?: return + runCatching { + val meal = db.mealEntryDao().byId(mealId) ?: return + if (meal.notes != MEAL_NOTE) return + val left = db.drinkDao().byMeal(mealId) + if (left.isEmpty()) { + db.mealEntryDao().deleteById(mealId) + } else { + val type = DrinkType.of(left.first().type) + db.mealEntryDao().upsert( + meal.copy( + name = mealName(type, left.size), + calories = left.sumOf { it.kcal }, + carbsG = type.carbsG * left.size, + quantity = left.size.toDouble(), + updatedAt = System.currentTimeMillis(), + ) + ) + } + } + } + + /** + * A logged meal that names a drink becomes drink entries too, so nobody logs twice and the + * week's count is right even before Drinks is switched on. Skipped when the meal already has + * drinks, or when the same kind of drink was logged on its own within 30 minutes. */ suspend fun fromMeal(db: PulseLoopDatabase, meal: MealEntryEntity, zone: ZoneId = ZoneId.systemDefault()) { - if (!DrinkPrefs.enabled || !MealJournal.isAlcohol(meal.name, meal.notes)) return + if (!MealJournal.isAlcohol(meal.name, meal.notes)) return if (db.drinkDao().byMeal(meal.id).isNotEmpty()) return val text = listOfNotNull(meal.name, meal.notes).joinToString(" ") val type = DrinkType.guess(text) val evening = MealJournal.eveningOf(meal.timestamp, zone) val recent = db.drinkDao().between(dayStart(evening, zone), dayStart(evening.plusDays(1), zone)) - if (recent.any { it.mealId == null && it.type == type.key && kotlin.math.abs(it.timestamp - meal.timestamp) <= 30 * 60_000L }) return - log(db, type, DrinkType.count(meal.name), meal.timestamp, mealId = meal.id, zone = zone) + // Logged on the Drinks card: no meal, or the snack the card made for it. + val near = recent.filter { it.type == type.key && it.note != FROM_MEAL && kotlin.math.abs(it.timestamp - meal.timestamp) <= 30 * 60_000L } + if (near.any { d -> d.mealId == null || db.mealEntryDao().byId(d.mealId)?.notes == MEAL_NOTE }) return + log(db, type, DrinkType.count(meal.name), meal.timestamp, mealId = meal.id, note = FROM_MEAL, zone = zone) } + private const val FROM_MEAL = "from_meal" + suspend fun onMealDeleted(db: PulseLoopDatabase, mealId: String) { runCatching { db.drinkDao().deleteByMeal(mealId) } } @@ -202,7 +262,7 @@ object DrinksRepository { todayStandard = DrinkInsights.standardDrinks(byDay[today] ?: 0.0, std), auditDue = DrinkPrefs.auditDate?.let { it.plusDays(AuditC.RETAKE_DAYS) <= today } ?: true, weekDays = (0L until 7L).map { DrinkInsights.weekStart(today).plusDays(it) }.map { it to (byDay[it] ?: 0.0) }, - topTypes = topTypes(all.filter { it.mealId == null }.map { DrinkType.of(it.type) }), + topTypes = topTypes(all.filter { it.note != FROM_MEAL }.map { DrinkType.of(it.type) }), ) } diff --git a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt index 00ed1860..a33642a8 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -428,7 +428,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang var more by remember { mutableStateOf(false) } var planOpen by remember { mutableStateOf(false) } var showTonight by remember { mutableStateOf(false) } - var lastLogged by remember { mutableStateOf>?>(null) } + var lastLogged by remember { mutableStateOf>?>(null) } var toDelete by remember { mutableStateOf(null) } DrinkCard("Log a drink", action = { @@ -448,7 +448,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang .clickable { scope.launch { val rows = DrinksRepository.log(db, t) - lastLogged = "+1 ${t.short.lowercase()}" to rows.map { it.id } + lastLogged = "+1 ${t.short.lowercase()}" to rows onChange() } } @@ -468,7 +468,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang "Undo", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, modifier = Modifier.clickable { - scope.launch { ids.forEach { db.drinkDao().delete(it) }; lastLogged = null; onChange() } + scope.launch { ids.forEach { DrinksRepository.delete(db, it) }; lastLogged = null; onChange() } }.padding(4.dp), ) } @@ -505,7 +505,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang confirmButton = { TextButton(onClick = { toDelete = null - scope.launch { db.drinkDao().delete(e.id); onChange() } + scope.launch { DrinksRepository.delete(db, e); onChange() } }) { Text("Delete", color = PulseColors.danger) } }, dismissButton = { TextButton(onClick = { toDelete = null }) { Text("Cancel") } }, @@ -521,7 +521,7 @@ private fun LogCard(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChang MoreDrinkSheet { type, count, hoursAgo, price -> scope.launch { val rows = DrinksRepository.log(db, type, count, System.currentTimeMillis() - hoursAgo * 3_600_000L, price = price) - lastLogged = "$count ${type.short.lowercase()}" to rows.map { it.id } + lastLogged = "$count ${type.short.lowercase()}" to rows more = false onChange() } diff --git a/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt b/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt index e41c8b8f..d6f4edba 100644 --- a/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt +++ b/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt @@ -179,4 +179,12 @@ class DrinkInsightsTest { assertTrue(AuditC.advice(AuditC.Level.HIGHER).contains("don't stop all at once")) assertFalse(AuditC.advice(AuditC.Level.LOW).contains("doctor")) } + + @Test + fun `a drink logged on the card names its meal and carries carbs`() { + assertEquals("Beer (can)", DrinksRepository.mealName(DrinkType.BEER, 1)) + assertEquals("3 × Wine", DrinksRepository.mealName(DrinkType.WINE, 3)) + assertEquals(0.0, DrinkType.SPIRIT.carbsG, 0.0) + assertTrue(DrinkType.entries.filter { it != DrinkType.SPIRIT }.all { it.carbsG > 0 }) + } }