Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions app/src/main/java/com/pulseloop/service/DrinkInsights.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
78 changes: 69 additions & 9 deletions app/src/main/java/com/pulseloop/service/DrinksRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -103,10 +114,26 @@ object DrinksRepository {
): List<DrinkEntryEntity> {
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) }
Expand All @@ -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) }
}
Expand Down Expand Up @@ -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) }),
)
}

Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pair<String, List<String>>?>(null) }
var lastLogged by remember { mutableStateOf<Pair<String, List<DrinkEntryEntity>>?>(null) }
var toDelete by remember { mutableStateOf<DrinkEntryEntity?>(null) }

DrinkCard("Log a drink", action = {
Expand All @@ -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()
}
}
Expand All @@ -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),
)
}
Expand Down Expand Up @@ -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") } },
Expand All @@ -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()
}
Expand Down
8 changes: 8 additions & 0 deletions app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}
}
Loading