diff --git a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt index 50ba4ffa..471611d0 100644 --- a/app/src/main/java/com/pulseloop/PulseLoopApplication.kt +++ b/app/src/main/java/com/pulseloop/PulseLoopApplication.kt @@ -26,6 +26,7 @@ class PulseLoopApplication : Application() { override fun onCreate() { super.onCreate() CrashLogger.install(this) + com.pulseloop.service.DrinkPrefs.init(this) // Application-scoped so capture runs whether or not the Debug screen is open. DiagnosticsSubscriber(PulseLoopDatabase.getInstance(this)).start(appScope) // One-time cleanup of activity totals corrupted by the old bucket handling; runs off the diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt index 8c6e5739..09035be0 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachContextBuilder.kt @@ -106,6 +106,7 @@ object CoachContextBuilder { dataQualityWarnings = warnings, environment = environment, primaryGoal = runCatching { com.pulseloop.service.GoalPlan.load(db, now) }.getOrNull(), + drinks = com.pulseloop.service.DrinksContext.build(db, now), ) } diff --git a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt index 5bcac08a..7e1e0300 100644 --- a/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt +++ b/app/src/main/java/com/pulseloop/coach/context/CoachPromptBuilder.kt @@ -25,6 +25,7 @@ Core behavior: - Goals: when the context packet's `primaryGoal` is null, ask the user — once per conversation, early, and never instead of answering what they asked — what they want to achieve and by when. Offer the common ones briefly: lose weight, get stronger / build muscle, lose fat and keep muscle, sleep better, get fitter, move more, reduce stress, eat better. Map what they say to the closest kind ("get stronger" → build_muscle, "run a 5k" → get_fitter) and keep their own words in the description. When they answer, call set_goal, then tell them in one line what it changed in their Settings (its `settings_goals`), and that they can edit those numbers. If a weight goal needs more than 1% of body weight a week, say so plainly, propose a realistic date or target, and only save once they agree. - When a goal exists, tie advice to it. Call get_goal for anything about progress, calories or what to eat or do; start from its `levers` marked short, and use its numbers as given: the scale's trend, the suggested intake against what they burn and log, protein, sleep and steps. Name the one or two levers that matter most this week (e.g. "you average 2,350 eaten against a 1,950 target", "sleep under 6 h raises hunger"). Never go below its intake floor, never set weight targets the user didn't ask for, and never judge their body. - Meal suggestions: the Nutrition screen shows a next-meal idea (call suggest_next_meal to see the same one). When the user wants alternatives, offer two or three everyday Brazilian options or common fruits that fit the calories left and the protein gap, with rough kcal. When they push back with something they prefer, check it against the goal (get_goal) and the calories left: if it fits, agree and call save_food_preference so future suggestions use it; if it doesn't, say why and offer a version that fits (a smaller portion, a different time). Don't save a preference the user didn't agree to. +- Drinks: when the packet has a `drinks` block, the user is cutting down on alcohol and tracks it. Be warm and matter-of-fact, never moralising; no "relapse", "sober" or labels. Use their own numbers (this week against the limit, dry days, tonight's plan, what drinking did to their nights from `lastNightEffect`) and say these effects are a pattern in their data, not proof. Help them plan: a number for tonight decided in advance (set_drink_plan once they agree), alternating with water or something alcohol-free, eating first, a set time to stop, a first drink that isn't alcohol. Log a drink with log_drink only when they tell you they had one. If they describe drinking most days, heavy amounts, morning drinking, or shakes or sweating when they stop, tell them not to stop all at once (withdrawal can be dangerous) and to see a doctor; in Brazil, CAPS AD gives free care. Without a `drinks` block, don't bring alcohol up unless they do. - When the context packet includes an `environment` block (the user's city + current weather), use it to ground practical suggestions — outdoor vs indoor workouts, hydration on hot days, planning around rain. Never reference the user's location more precisely than the city. Data limitations: @@ -69,6 +70,8 @@ data class CoachContextPacket( val environment: EnvironmentContext? = null, /** The goal the user set with the coach, with progress; null when none is set yet. */ val primaryGoal: com.pulseloop.service.GoalPlan.Plan? = null, + /** Drinks, when the user tracks them (docs/drinks-plan.md); null otherwise. */ + val drinks: com.pulseloop.service.DrinksContext? = null, ) { @kotlinx.serialization.Serializable data class ProfileContext( diff --git a/app/src/main/java/com/pulseloop/coach/orchestration/PendingActionExecutor.kt b/app/src/main/java/com/pulseloop/coach/orchestration/PendingActionExecutor.kt index e87da0de..297df922 100644 --- a/app/src/main/java/com/pulseloop/coach/orchestration/PendingActionExecutor.kt +++ b/app/src/main/java/com/pulseloop/coach/orchestration/PendingActionExecutor.kt @@ -69,6 +69,7 @@ object PendingActionExecutor { PendingActionKind.DELETE_MEAL_ENTRY -> { val name = entry.name db.mealEntryDao().deleteById(entry.id) + com.pulseloop.service.DrinksRepository.onMealDeleted(db, entry.id) "Deleted \"$name\"." } PendingActionKind.UPDATE_MEAL_ENTRY -> { diff --git a/app/src/main/java/com/pulseloop/coach/tools/DrinkTools.kt b/app/src/main/java/com/pulseloop/coach/tools/DrinkTools.kt new file mode 100644 index 00000000..a2ff9cf0 --- /dev/null +++ b/app/src/main/java/com/pulseloop/coach/tools/DrinkTools.kt @@ -0,0 +1,137 @@ +package com.pulseloop.coach.tools + +import com.pulseloop.service.DrinkInsights +import com.pulseloop.service.DrinkPrefs +import com.pulseloop.service.DrinkType +import com.pulseloop.service.DrinksRepository +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put + +/** + * Drinks in chat (docs/drinks-plan.md): read the week, log a drink the user says they had, and set + * tonight's plan once they agree to a number. All three refuse while Drinks is off, so the coach + * never starts tracking alcohol for someone who didn't ask. + */ +object DrinkTools { + + val all: List get() = listOf(makeSummary(), makeLog(), makePlan()) + + private val TYPES = DrinkType.entries.map { it.key } + private const val OFF = """{"error":"Drinks tracking is off. The user can turn it on from Today's tiles, Settings → Drinks, or the Journal."}""" + + private fun noArgs() = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(emptyMap()), + "required" to JsonArray(emptyList()), + "additionalProperties" to JsonPrimitive(false), + )) + + private fun makeSummary() = CoachToolDef( + name = "get_drinks", + publicLabel = "Checking your drinks", + description = "The user's drinks: this week in standard drinks against their weekly limit, dry days against their " + + "target, the current and best dry streak, tonight's plan, the last 8 weeks, and what drinking did to their " + + "nights (last night, after 1–2 and after 3+ drinks, compared with their dry nights).", + parameters = noArgs(), + ) { _, ctx -> + val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true) + val s = kotlinx.coroutines.runBlocking { DrinksRepository.load(db) } + fun impact(i: DrinkInsights.Impact?) = i?.let { + buildJsonObject { + put("nights", it.nights) + it.hrvPct?.let { v -> put("hrv_pct_vs_dry", v) } + it.restingHr?.let { v -> put("resting_hr_bpm_vs_dry", v) } + it.asleepMinutes?.let { v -> put("asleep_min_vs_dry", v) } + } + } + ToolResult(buildJsonObject { + put("standard_drink_grams", s.gramsPerStandard) + put("week_standard_drinks", DrinkInsights.fmt(s.week.standardDrinks)) + put("weekly_limit", s.weeklyLimit) + put("dry_days_this_week", s.week.dryDays) + put("dry_days_target", s.dryDaysTarget) + put("heavy_days_this_week", s.week.heavyDays) + put("today_standard_drinks", DrinkInsights.fmt(s.todayStandard)) + s.planToday?.let { put("tonight_plan", it) } + put("dry_streak_current", s.streaks.current) + put("dry_streak_best", s.streaks.best) + put("last_8_weeks", JsonArray(s.weeks.map { JsonPrimitive(DrinkInsights.fmt(it.second)) })) + s.morningAfter?.let { put("last_night", DrinksRepository.morningAfterLine(it)) } + impact(s.dose.light)?.let { put("after_1_to_2_drinks", it) } + impact(s.dose.heavier)?.let { put("after_3_plus_drinks", it) } + put("dry_nights_compared", s.dose.dryNights) + s.recoveryNights?.let { put("nights_for_hrv_to_recover", "%.1f".format(it)) } + }.toString()) + } + + private fun makeLog() = CoachToolDef( + name = "log_drink", + publicLabel = "Logging your drink", + description = "Log drinks the user says they had. type: beer (350 ml can), beer_600, draft (chopp), wine (glass), " + + "spirit (shot), caipirinha, cocktail, or other. count: how many (1–12). hours_ago: when, 0 for now.", + parameters = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(mapOf( + "type" to JsonObject(mapOf("type" to JsonPrimitive("string"), "enum" to JsonArray(TYPES.map { JsonPrimitive(it) }))), + "count" to JsonObject(mapOf("type" to JsonPrimitive("integer"))), + "hours_ago" to JsonObject(mapOf("type" to JsonPrimitive("integer"))), + )), + "required" to JsonArray(listOf(JsonPrimitive("type"))), + "additionalProperties" to JsonPrimitive(false), + )), + strict = false, + ) { args, ctx -> + val db = ctx.db ?: return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true) + val p = runCatching { Json.parseToJsonElement(args).jsonObject }.getOrNull() + ?: return@CoachToolDef ToolResult("""{"error":"invalid arguments"}""", isError = true) + val key = p["type"]?.jsonPrimitive?.contentOrNull?.takeIf { it in TYPES } + ?: return@CoachToolDef ToolResult("""{"error":"type must be one of $TYPES"}""", isError = true) + val count = (p["count"]?.jsonPrimitive?.intOrNull ?: 1).coerceIn(1, 12) + val hoursAgo = (p["hours_ago"]?.jsonPrimitive?.intOrNull ?: 0).coerceIn(0, 36) + val type = DrinkType.of(key) + kotlinx.coroutines.runBlocking { + DrinksRepository.log(db, type, count, System.currentTimeMillis() - hoursAgo * 3_600_000L) + } + val s = kotlinx.coroutines.runBlocking { DrinksRepository.load(db) } + ToolResult(buildJsonObject { + put("ok", true) + put("logged", "$count × ${type.label}") + put("today_standard_drinks", DrinkInsights.fmt(s.todayStandard)) + put("week_standard_drinks", DrinkInsights.fmt(s.week.standardDrinks)) + put("weekly_limit", s.weeklyLimit) + s.planToday?.let { put("tonight_plan", it) } + }.toString()) + } + + private fun makePlan() = CoachToolDef( + name = "set_drink_plan", + publicLabel = "Setting tonight's plan", + description = "Save how many drinks the user plans to have tonight, once they have agreed to the number (0 for a " + + "dry night). The Drinks screen then tracks tonight against it.", + parameters = JsonObject(mapOf( + "type" to JsonPrimitive("object"), + "properties" to JsonObject(mapOf("drinks" to JsonObject(mapOf("type" to JsonPrimitive("integer"))))), + "required" to JsonArray(listOf(JsonPrimitive("drinks"))), + "additionalProperties" to JsonPrimitive(false), + )), + ) { args, ctx -> + if (ctx.db == null) return@CoachToolDef ToolResult("""{"error":"database not available"}""", isError = true) + if (!DrinkPrefs.enabled) return@CoachToolDef ToolResult(OFF, isError = true) + val n = runCatching { Json.parseToJsonElement(args).jsonObject["drinks"]?.jsonPrimitive?.intOrNull }.getOrNull() + ?.takeIf { it in 0..12 } + ?: return@CoachToolDef ToolResult("""{"error":"drinks must be 0–12"}""", isError = true) + val tonight = com.pulseloop.service.MealJournal.eveningOf(System.currentTimeMillis()) + DrinkPrefs.setPlan(tonight, n) + ToolResult(buildJsonObject { put("ok", true); put("tonight_plan", n) }.toString()) + } +} diff --git a/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt b/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt index e0562cf1..fd5f6ffa 100644 --- a/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt +++ b/app/src/main/java/com/pulseloop/coach/tools/ToolRegistry.kt @@ -13,7 +13,7 @@ class ToolRegistry(private val flags: CoachFeatureFlags) { // Nutrition read tools are grounding (always available, like the other read tools); // the write tools are gated on flags.writeToolsEnabled, mirroring iOS's // enableWriteTools split in NutritionTools.swift (iOS PR #96). - val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.all + val all = RetrievalTools.all + AnalysisTools.all + ChartTools.all + NutritionTools.all + GoalTools.all + MealSuggestionTools.all + DrinkTools.all val writable = if (flags.writeToolsEnabled) MemoryTools.all + ActionTools.writeTools + NutritionTools.writeTools else emptyList() val live = if (flags.liveMeasurementsEnabled) ActionTools.measurementTools else emptyList() tools = (all + writable + live).associateBy { it.name } diff --git a/app/src/main/java/com/pulseloop/data/DataArchive.kt b/app/src/main/java/com/pulseloop/data/DataArchive.kt index 0d1765fc..54daf5d6 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchive.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchive.kt @@ -47,6 +47,8 @@ data class PulseArchive( val coachGoals: List = emptyList(), /** Food preferences agreed with the coach (v31). */ val foodPreferences: List = emptyList(), + /** Drinks (v32). */ + val drinks: List = emptyList(), ) @Serializable data class FoodPreferenceDTO( @@ -56,6 +58,12 @@ data class PulseArchive( val timesAgreed: Int = 1, val createdAt: Long, val updatedAt: Long, ) +@Serializable data class DrinkEntryDTO( + val id: String, val timestamp: Long, val day: Long, val type: String, + val volumeMl: Double, val abvPct: Double, val grams: Double, val kcal: Double, + val price: Double? = null, val mealId: String? = null, val note: String? = null, val createdAt: Long, +) + @Serializable data class CoachGoalDTO( val id: String, val kind: String, val description: String, val startWeightKg: Double? = null, val targetWeightKg: Double? = null, diff --git a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt index cf05ddfa..2bf03ced 100644 --- a/app/src/main/java/com/pulseloop/data/DataArchiveService.kt +++ b/app/src/main/java/com/pulseloop/data/DataArchiveService.kt @@ -329,6 +329,15 @@ object DataArchiveService { timesAgreed = c.intOrNull("timesAgreed") ?: 1, createdAt = c.long("createdAt"), updatedAt = c.long("updatedAt"), ) }, + drinks = collect("drink_entries") { c -> + DrinkEntryDTO( + id = c.str("id"), timestamp = c.long("timestamp"), day = c.long("day"), type = c.str("type"), + volumeMl = c.dblOrNull("volumeMl") ?: 0.0, abvPct = c.dblOrNull("abvPct") ?: 0.0, + grams = c.dblOrNull("grams") ?: 0.0, kcal = c.dblOrNull("kcal") ?: 0.0, + price = c.dblOrNull("price"), mealId = c.strOrNull("mealId"), note = c.strOrNull("note"), + createdAt = c.long("createdAt"), + ) + }, coachGoals = collect("coach_goals") { c -> CoachGoalDTO( id = c.str("id"), kind = c.str("kind"), description = c.str("description"), @@ -419,6 +428,13 @@ object DataArchiveService { timesAgreed = f.timesAgreed, createdAt = f.createdAt, updatedAt = f.updatedAt, )) } + for (d in archive.drinks) { + db.drinkDao().upsert(DrinkEntryEntity( + id = d.id, timestamp = d.timestamp, day = d.day, type = d.type, volumeMl = d.volumeMl, + abvPct = d.abvPct, grams = d.grams, kcal = d.kcal, price = d.price, mealId = d.mealId, + note = d.note, createdAt = d.createdAt, + )) + } for (g in archive.coachGoals) { db.coachGoalDao().upsert(CoachGoalEntity( id = g.id, kind = g.kind, description = g.description, diff --git a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt index 496e4abb..618fc092 100644 --- a/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt +++ b/app/src/main/java/com/pulseloop/data/PulseLoopDatabase.kt @@ -47,8 +47,9 @@ import com.pulseloop.data.entity.* BodyMeasurementEntity::class, CoachGoalEntity::class, FoodPreferenceEntity::class, + DrinkEntryEntity::class, ], - version = 31, + version = 32, exportSchema = false, ) abstract class PulseLoopDatabase : RoomDatabase() { @@ -75,6 +76,8 @@ abstract class PulseLoopDatabase : RoomDatabase() { abstract fun bodyMeasurementDao(): BodyMeasurementDao abstract fun coachGoalDao(): CoachGoalDao abstract fun foodPreferenceDao(): FoodPreferenceDao + /** Drinks (docs/drinks-plan.md, v32). */ + abstract fun drinkDao(): DrinkDao abstract fun coachSummaryDao(): CoachSummaryDao abstract fun wearableLogDao(): WearableLogDao abstract fun rawPacketDao(): RawPacketDao @@ -125,6 +128,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { "body_measurements", "coach_goals", "food_preferences", + "drink_entries", ) @Volatile private var INSTANCE: PulseLoopDatabase? = null @@ -580,6 +584,19 @@ abstract class PulseLoopDatabase : RoomDatabase() { } } + /** v31 → v32: drinks (docs/drinks-plan.md). */ + private val MIGRATION_31_32 = object : Migration(31, 32) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `drink_entries` (`id` TEXT NOT NULL, `timestamp` INTEGER NOT NULL, " + + "`day` INTEGER NOT NULL, `type` TEXT NOT NULL, `volumeMl` REAL NOT NULL, `abvPct` REAL NOT NULL, " + + "`grams` REAL NOT NULL, `kcal` REAL NOT NULL, `price` REAL, `mealId` TEXT, `note` TEXT, " + + "`createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))" + ) + db.execSQL("CREATE INDEX IF NOT EXISTS `index_drink_entries_day` ON `drink_entries` (`day`)") + } + } + private fun adoptStableMeasurementIdentities(db: SupportSQLiteDatabase) { db.execSQL("DROP INDEX IF EXISTS `index_measurements_kindRaw_timestamp_sourceRaw`") db.execSQL( @@ -677,6 +694,7 @@ abstract class PulseLoopDatabase : RoomDatabase() { MIGRATION_28_29, MIGRATION_29_30, MIGRATION_30_31, + MIGRATION_31_32, ) // Downgrades only (sideloading an older APK). A blanket destructive // fallback would silently wipe every measurement, sleep session, and diff --git a/app/src/main/java/com/pulseloop/data/dao/Daos.kt b/app/src/main/java/com/pulseloop/data/dao/Daos.kt index b594d8f9..a993fd11 100644 --- a/app/src/main/java/com/pulseloop/data/dao/Daos.kt +++ b/app/src/main/java/com/pulseloop/data/dao/Daos.kt @@ -934,3 +934,34 @@ interface FoodPreferenceDao { @Query("DELETE FROM food_preferences WHERE id = :id") suspend fun delete(id: String) } + +@Dao +interface DrinkDao { + @Query("SELECT * FROM drink_entries ORDER BY timestamp DESC") + suspend fun all(): List + + @Query("SELECT * FROM drink_entries ORDER BY timestamp DESC") + fun allFlow(): Flow> + + /** Drinks whose evening starts in [from, to). */ + @Query("SELECT * FROM drink_entries WHERE day >= :from AND day < :to ORDER BY timestamp ASC") + suspend fun between(from: Long, to: Long): List + + @Query("SELECT * FROM drink_entries WHERE mealId = :mealId") + suspend fun byMeal(mealId: String): List + + @Query("SELECT * FROM drink_entries ORDER BY timestamp DESC LIMIT 1") + suspend fun latest(): DrinkEntryEntity? + + @Upsert + suspend fun upsert(entry: DrinkEntryEntity) + + @Query("DELETE FROM drink_entries WHERE id = :id") + suspend fun delete(id: String) + + @Query("DELETE FROM drink_entries WHERE mealId = :mealId") + suspend fun deleteByMeal(mealId: String) + + @Query("DELETE FROM drink_entries") + suspend fun clear() +} diff --git a/app/src/main/java/com/pulseloop/data/entity/NutritionEntities.kt b/app/src/main/java/com/pulseloop/data/entity/NutritionEntities.kt index f560581e..f7cf251a 100644 --- a/app/src/main/java/com/pulseloop/data/entity/NutritionEntities.kt +++ b/app/src/main/java/com/pulseloop/data/entity/NutritionEntities.kt @@ -60,3 +60,26 @@ data class CachedFoodProductEntity( val lastUsedAt: Long = System.currentTimeMillis(), val useCount: Int = 0, ) + +/** + * One drink (docs/drinks-plan.md). [day] is the local start of the *evening* it belongs to + * ([com.pulseloop.service.MealJournal.eveningOf]), so a 01:00 beer counts toward the night before. + * Alcohol is kept in grams; standard drinks are computed at read time from the user's chosen size. + * [mealId] links a drink created from a logged meal, so deleting the meal removes it. + */ +@Entity(tableName = "drink_entries", indices = [Index("day")]) +data class DrinkEntryEntity( + @PrimaryKey val id: String = java.util.UUID.randomUUID().toString(), + val timestamp: Long, + val day: Long, + /** A [com.pulseloop.service.DrinkType] key. */ + val type: String, + val volumeMl: Double, + val abvPct: Double, + val grams: Double, + val kcal: Double, + val price: Double? = null, + val mealId: String? = null, + val note: String? = null, + val createdAt: Long = System.currentTimeMillis(), +) diff --git a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt index bd12de94..8693f68c 100644 --- a/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt +++ b/app/src/main/java/com/pulseloop/notifications/GuidanceWorker.kt @@ -128,7 +128,14 @@ class GuidanceWorker(context: Context, params: WorkerParameters) : CoroutineWork } val thisWeek = WeeklyReport.summarize(thisWeekNights, stepsBetween(6, 0)) val lastWeek = WeeklyReport.summarize(lastWeekNights, stepsBetween(13, 7)).takeIf { it.nights >= 3 } - WeeklyReport.text(thisWeek, lastWeek, inputs.sleepGoalMinutes)?.let { (title, body) -> + WeeklyReport.text(thisWeek, lastWeek, inputs.sleepGoalMinutes)?.let { (title, report) -> + // Drinks, for users who track them: the week that is ending, in one line. + val drinks = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { + val d = com.pulseloop.service.DrinksRepository.load(db, now, zone) + " Drinks: ${com.pulseloop.service.DrinkInsights.fmt(d.week.standardDrinks)} of ${com.pulseloop.service.DrinkInsights.fmt(d.weeklyLimit)}, " + + "${d.week.dryDays} dry day${if (d.week.dryDays == 1) "" else "s"}." + }.getOrNull().orEmpty() else "" + val body = report + drinks notify(ctx, ID_WEEKLY, title, body) prefs.lastWeeklyReportWeek = weekKey } diff --git a/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt b/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt index d9639a09..89d6a78c 100644 --- a/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt +++ b/app/src/main/java/com/pulseloop/notifications/NotificationContextBuilder.kt @@ -144,6 +144,7 @@ object NotificationContextBuilder { nutrition = com.pulseloop.service.NutritionContext.build(db, now), body = com.pulseloop.service.BodyContext.build(db, now), primaryGoal = runCatching { com.pulseloop.service.GoalPlan.load(db, now) }.getOrNull(), + drinks = com.pulseloop.service.DrinksContext.build(db, now), ) } diff --git a/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt b/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt index 482b5fd1..d1e8f87e 100644 --- a/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt +++ b/app/src/main/java/com/pulseloop/notifications/NotificationModels.kt @@ -58,6 +58,8 @@ data class NotificationContextPacket( val body: com.pulseloop.service.BodyContext? = null, /** The goal set with the coach, with progress. */ val primaryGoal: com.pulseloop.service.GoalPlan.Plan? = null, + /** Drinks, when the user tracks them. */ + val drinks: com.pulseloop.service.DrinksContext? = null, ) { data class GoalContext( val stepsDaily: Int, @@ -140,6 +142,7 @@ data class NotificationContextPacket( nutrition = nutrition, body = body, primaryGoal = primaryGoal, + drinks = drinks, ) fun toJsonString(): String { @@ -169,6 +172,7 @@ data class NotificationContextPacket( val nutrition: com.pulseloop.service.NutritionContext? = null, val body: com.pulseloop.service.BodyContext? = null, val primaryGoal: com.pulseloop.service.GoalPlan.Plan? = null, + val drinks: com.pulseloop.service.DrinksContext? = null, ) { @kotlinx.serialization.Serializable data class SerializableGoalContext(val stepsDaily: Int, val activeMinutesDaily: Int, val sleepHours: Int, val exerciseDaysWeekly: Int) diff --git a/app/src/main/java/com/pulseloop/service/DrinkInsights.kt b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt new file mode 100644 index 00000000..2bf4eb0f --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/DrinkInsights.kt @@ -0,0 +1,289 @@ +package com.pulseloop.service + +import java.time.DayOfWeek +import java.time.LocalDate +import kotlin.math.roundToInt + +/* + * Drinks (docs/drinks-plan.md): what was drunk, against the user's own plan, and what it did to + * their nights. Everything here is pure so it can be tested without a device. Alcohol is counted + * in grams; a "standard drink" is the user's chosen size (10 g by default, WHO's). + */ + +/** 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), + 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); + + val grams: Double get() = DrinkInsights.grams(volumeMl, abvPct) + + companion object { + fun of(key: String?) = entries.firstOrNull { it.key == key } ?: OTHER + + private val PATTERNS = listOf( + CAIPIRINHA to Regex("\\b(caipirinha|caipiroska|caipivodka)s?\\b", RegexOption.IGNORE_CASE), + COCKTAIL to Regex("\\b(cocktail|drinque|margarita|mojito|spritz|aperol|negroni|martini|gin t[oô]nica|gin tonic|sangria)s?\\b", RegexOption.IGNORE_CASE), + DRAFT to Regex("\\b(chopp|chope|draft|pint)s?\\b", RegexOption.IGNORE_CASE), + BEER_600 to Regex("\\b600\\s?ml\\b|\\bgarrafa\\b", RegexOption.IGNORE_CASE), + BEER to Regex("\\b(beer|cerveja|ipa|lager|stout|pilsen|latinha|long neck)s?\\b", RegexOption.IGNORE_CASE), + WINE to Regex("\\b(wine|vinho|prosecco|champagne|espumante|ros[eé])s?\\b", RegexOption.IGNORE_CASE), + SPIRIT to Regex("\\b(vodka|whisk(e)?y|gin|rum|tequila|cacha[cç]a|bourbon|shot|dose|conhaque|brandy)s?\\b", RegexOption.IGNORE_CASE), + ) + + /** The closest type for a free-text drink ("2 taças de vinho" → WINE). */ + fun guess(text: String): DrinkType { + val beer = PATTERNS.first { it.first == BEER }.second.containsMatchIn(text) + for ((type, re) in PATTERNS) { + if (type == BEER_600 && !beer) continue + if (re.containsMatchIn(text)) return type + } + return OTHER + } + + private val WORD_NUMBERS = mapOf( + "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, + "um" to 1, "uma" to 1, "dois" to 2, "duas" to 2, "três" to 3, "tres" to 3, "quatro" to 4, + "cinco" to 5, "seis" to 6, + ) + + /** How many drinks a free-text entry names ("3 beers", "duas taças"), 1 when it doesn't say. */ + fun count(text: String): Int { + val t = text.trim().lowercase() + Regex("^(\\d{1,2})\\s*(x\\b)?").find(t)?.let { return it.groupValues[1].toInt().coerceIn(1, 12) } + val first = t.split(Regex("\\s+")).firstOrNull() + return WORD_NUMBERS[first] ?: 1 + } + } +} + +object DrinkInsights { + /** Density of ethanol, g/ml. */ + const val ETHANOL_DENSITY = 0.789 + /** WHO's heavy episodic drinking threshold: 60 g of pure alcohol on one occasion. */ + const val HEAVY_DAY_GRAMS = 60.0 + const val MIN_NIGHTS = 3 + + fun grams(volumeMl: Double, abvPct: Double): Double = volumeMl * abvPct / 100.0 * ETHANOL_DENSITY + + fun standardDrinks(grams: Double, gramsPerStandard: Double): Double = + if (gramsPerStandard <= 0) 0.0 else grams / gramsPerStandard + + /** "2", "1.5" — standard drinks to one decimal, without a trailing ".0". */ + fun fmt(std: Double): String { + val r = (std * 10).roundToInt() / 10.0 + return if (r == r.toLong().toDouble()) r.toLong().toString() else "%.1f".format(r) + } + + fun weekStart(day: LocalDate): LocalDate = day.minusDays((day.dayOfWeek.value - DayOfWeek.MONDAY.value).toLong()) + + // ── This week ──────────────────────────────────────────────────────────────────────────── + + data class Week( + val start: LocalDate, + val standardDrinks: Double, + val drinkingDays: Int, + /** Completed days this week (through yesterday) with no drinks, since tracking began. */ + val dryDays: Int, + val heavyDays: Int, + /** Whether anything has been logged for today's evening yet. */ + val drankToday: Boolean, + ) + + /** [gramsByDay] maps each evening to the alcohol logged for it. Days before [trackedSince] are unknown, not dry. */ + fun week(gramsByDay: Map, today: LocalDate, gramsPerStandard: Double, trackedSince: LocalDate): Week { + val start = weekStart(today) + val days = generateSequence(start) { it.plusDays(1) }.takeWhile { !it.isAfter(today) }.toList() + val grams = days.map { gramsByDay[it] ?: 0.0 } + val completedKnown = days.filter { it.isBefore(today) && !it.isBefore(trackedSince) } + return Week( + start = start, + standardDrinks = standardDrinks(grams.sum(), gramsPerStandard), + drinkingDays = grams.count { it > 0 }, + dryDays = completedKnown.count { (gramsByDay[it] ?: 0.0) <= 0 }, + heavyDays = grams.count { it >= HEAVY_DAY_GRAMS }, + drankToday = (gramsByDay[today] ?: 0.0) > 0, + ) + } + + /** Standard drinks per week, oldest first, for the [weeks] weeks ending with this one. */ + fun weeklyTotals(gramsByDay: Map, today: LocalDate, gramsPerStandard: Double, weeks: Int): List> { + val thisWeek = weekStart(today) + return (weeks - 1 downTo 0).map { w -> + val start = thisWeek.minusWeeks(w.toLong()) + val g = (0 until 7).sumOf { gramsByDay[start.plusDays(it.toLong())] ?: 0.0 } + start to standardDrinks(g, gramsPerStandard) + } + } + + // ── Streaks ────────────────────────────────────────────────────────────────────────────── + + data class Streaks(val current: Int, val best: Int) + + /** Runs of dry days through yesterday (today isn't over), counted from [trackedSince]. */ + fun streaks(drinkDays: Set, today: LocalDate, trackedSince: LocalDate): Streaks { + if (drinkDays.contains(today)) { + return Streaks(0, bestRun(drinkDays, today.minusDays(1), trackedSince)) + } + var current = 0 + var d = today.minusDays(1) + while (!d.isBefore(trackedSince) && d !in drinkDays) { current++; d = d.minusDays(1) } + return Streaks(current, maxOf(current, bestRun(drinkDays, today.minusDays(1), trackedSince))) + } + + private fun bestRun(drinkDays: Set, through: LocalDate, from: LocalDate): Int { + var best = 0; var run = 0 + var d = from + while (!d.isAfter(through)) { + if (d in drinkDays) run = 0 else { run++; best = maxOf(best, run) } + d = d.plusDays(1) + } + return best + } + + // ── Savings ────────────────────────────────────────────────────────────────────────────── + + data class Savings(val drinksAvoided: Double, val money: Double?, val kcal: Double) + + /** + * Against the user's typical week before tracking: each completed week counts what it came in + * under [baselinePerWeek]; a week over it doesn't count against the others. + */ + fun savings(completedWeeks: List, baselinePerWeek: Double, pricePerDrink: Double?, kcalPerDrink: Double): Savings { + val avoided = completedWeeks.sumOf { (baselinePerWeek - it).coerceAtLeast(0.0) } + return Savings(avoided, pricePerDrink?.let { it * avoided }, avoided * kcalPerDrink) + } + + // ── Nights ─────────────────────────────────────────────────────────────────────────────── + + data class Impact(val nights: Int, val hrvPct: Int?, val restingHr: Int?, val asleepMinutes: Int?) + + data class MorningAfter(val standardDrinks: Double, val impact: Impact, val dryNights: Int) + + private fun median(v: List): Double? { + if (v.isEmpty()) return null + val s = v.sorted(); val m = s.size / 2 + return if (s.size % 2 == 1) s[m] else (s[m - 1] + s[m]) / 2 + } + + /** Nights whose evening is known (on or after [trackedSince]) and had no drinks. */ + fun dryNights(nights: List, gramsByDay: Map, trackedSince: LocalDate): List = + nights.filter { n -> + val evening = n.day.minusDays(1) + !evening.isBefore(trackedSince) && (gramsByDay[evening] ?: 0.0) <= 0 + } + + /** How a set of nights compares with the dry ones: HRV %, resting HR bpm, minutes asleep. */ + fun compare(group: List, dry: List): Impact { + fun pct(a: Double?, b: Double?) = if (a == null || b == null || b <= 0) null else ((a - b) / b * 100).roundToInt() + fun diff(a: Double?, b: Double?) = if (a == null || b == null) null else (a - b).roundToInt() + return Impact( + nights = group.size, + hrvPct = pct(median(group.mapNotNull { it.hrv }), median(dry.mapNotNull { it.hrv })), + restingHr = diff(median(group.mapNotNull { it.restingHr }), median(dry.mapNotNull { it.restingHr })), + asleepMinutes = diff( + median(group.map { it.asleepMinutes.toDouble() }.filter { it > 0 }), + median(dry.map { it.asleepMinutes.toDouble() }.filter { it > 0 }), + ), + ) + } + + /** Last night against the user's dry nights, when last evening had drinks and there are enough dry nights. */ + fun morningAfter( + lastNight: NightSummary?, + history: List, + gramsByDay: Map, + gramsPerStandard: Double, + trackedSince: LocalDate, + ): MorningAfter? { + val night = lastNight ?: return null + val grams = gramsByDay[night.day.minusDays(1)] ?: 0.0 + if (grams <= 0) return null + val dry = dryNights(history.filter { it.day != night.day }, gramsByDay, trackedSince) + if (dry.size < MIN_NIGHTS) return MorningAfter(standardDrinks(grams, gramsPerStandard), Impact(1, null, null, null), dry.size) + return MorningAfter(standardDrinks(grams, gramsPerStandard), compare(listOf(night), dry), dry.size) + } + + data class Dose(val light: Impact?, val heavier: Impact?, val dryNights: Int) + + /** Nights after 1–2 and after more than 2 standard drinks, each against dry nights; a group needs [MIN_NIGHTS]. */ + fun dose(nights: List, gramsByDay: Map, gramsPerStandard: Double, trackedSince: LocalDate): Dose { + val dry = dryNights(nights, gramsByDay, trackedSince) + if (dry.size < MIN_NIGHTS) return Dose(null, null, dry.size) + fun stdOf(n: NightSummary) = standardDrinks(gramsByDay[n.day.minusDays(1)] ?: 0.0, gramsPerStandard) + val light = nights.filter { stdOf(it) > 0 && stdOf(it) <= 2.0 } + val heavier = nights.filter { stdOf(it) > 2.0 } + return Dose( + light = light.takeIf { it.size >= MIN_NIGHTS }?.let { compare(it, dry) }, + heavier = heavier.takeIf { it.size >= MIN_NIGHTS }?.let { compare(it, dry) }, + dryNights = dry.size, + ) + } + + /** + * Average nights for HRV to come back within 5 % of the dry-night median after a drinking + * evening, counting only stretches where the following evenings stayed dry. Null below two + * such stretches. + */ + fun recoveryNights(nights: List, gramsByDay: Map, trackedSince: LocalDate): Double? { + val byDay = nights.associateBy { it.day } + val dryHrv = median(dryNights(nights, gramsByDay, trackedSince).mapNotNull { it.hrv }) ?: return null + val episodes = mutableListOf() + gramsByDay.filter { it.value > 0 && !it.key.isBefore(trackedSince) }.keys.sorted().forEach { evening -> + for (k in 1..7) { + val night = byDay[evening.plusDays(k.toLong())] ?: return@forEach + val hrv = night.hrv ?: return@forEach + if (hrv >= dryHrv * 0.95) { episodes += k; return@forEach } + // A drink on a following evening starts a new stretch; this one is inconclusive. + if ((gramsByDay[evening.plusDays(k.toLong())] ?: 0.0) > 0) return@forEach + } + } + return episodes.takeIf { it.size >= 2 }?.average() + } +} + +/** + * AUDIT-C, the three-question alcohol screen (WHO AUDIT items 1–3). Each answer scores 0–4. + * A screen, not a diagnosis, and the result copy says so. + */ +object AuditC { + val QUESTIONS = listOf( + "How often do you have a drink containing alcohol?" to listOf( + "Never", "Monthly or less", "2–4 times a month", "2–3 times a week", "4 or more times a week", + ), + "How many standard drinks do you have on a typical day when you are drinking?" to listOf( + "1 or 2", "3 or 4", "5 or 6", "7 to 9", "10 or more", + ), + "How often do you have six or more drinks on one occasion?" to listOf( + "Never", "Less than monthly", "Monthly", "Weekly", "Daily or almost daily", + ), + ) + + enum class Level(val label: String) { LOW("Lower risk"), INCREASING("Increasing risk"), HIGHER("Higher risk") } + + /** Retake after this many days. */ + const val RETAKE_DAYS = 90L + + fun score(answers: List): Int = answers.take(3).sumOf { it.coerceIn(0, 4) } + + /** Positive at 4 for men, 3 for women or when sex isn't known; 8 and above is higher risk. */ + fun level(score: Int, sex: String?): Level { + val threshold = if (sex?.lowercase() == "male") 4 else 3 + return when { + score >= 8 -> Level.HIGHER + score >= threshold -> Level.INCREASING + else -> Level.LOW + } + } + + fun advice(level: Level): String = when (level) { + Level.LOW -> "Your answers suggest lower-risk drinking. Keeping some dry days each week helps keep it that way." + Level.INCREASING -> "Your answers suggest drinking at a level that raises health risks. Cutting down gradually, with a weekly limit and dry days, is the usual first step." + Level.HIGHER -> "Your answers suggest drinking at a level that is likely affecting your health. Please talk to a doctor. If you drink most days, don't stop all at once: stopping suddenly can be dangerous, and a doctor can help you cut down safely." + } +} diff --git a/app/src/main/java/com/pulseloop/service/DrinksRepository.kt b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt new file mode 100644 index 00000000..be3278fa --- /dev/null +++ b/app/src/main/java/com/pulseloop/service/DrinksRepository.kt @@ -0,0 +1,253 @@ +package com.pulseloop.service + +import android.content.Context +import android.content.SharedPreferences +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.DrinkEntryEntity +import com.pulseloop.data.entity.JournalEntryEntity +import com.pulseloop.data.entity.MealEntryEntity +import kotlinx.serialization.Serializable +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId + +/** + * The user's drinks settings (docs/drinks-plan.md). Initialised once from the Application, so the + * meal log and the coach tools, which have a database but no Context, can check whether Drinks is on. + */ +object DrinkPrefs { + @Volatile private var prefs: SharedPreferences? = null + + fun init(context: Context) { + if (prefs == null) prefs = context.applicationContext.getSharedPreferences("drinks", Context.MODE_PRIVATE) + } + + private fun p(): SharedPreferences? = prefs + + val enabled: Boolean get() = p()?.getBoolean("enabled", false) ?: false + + fun setEnabled(on: Boolean, today: LocalDate = LocalDate.now()) { + val e = p()?.edit() ?: return + e.putBoolean("enabled", on) + if (on && p()?.getString("trackedSince", null) == null) e.putString("trackedSince", today.toString()) + e.apply() + } + + /** The first day drinks were tracked; days before it are unknown rather than dry. */ + val trackedSince: LocalDate + get() = p()?.getString("trackedSince", null)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } ?: LocalDate.now() + + var weeklyLimit: Double + get() = p()?.getFloat("weeklyLimit", 7f)?.toDouble() ?: 7.0 + set(v) { p()?.edit()?.putFloat("weeklyLimit", v.toFloat())?.apply() } + + var dryDaysTarget: Int + get() = p()?.getInt("dryDaysTarget", 4) ?: 4 + set(v) { p()?.edit()?.putInt("dryDaysTarget", v)?.apply() } + + /** Grams of alcohol in one standard drink: 10 (WHO), 8 (UK unit) or 14 (US). */ + var gramsPerStandard: Double + get() = p()?.getFloat("gramsPerStandard", 10f)?.toDouble() ?: 10.0 + set(v) { p()?.edit()?.putFloat("gramsPerStandard", v.toFloat())?.apply() } + + /** The user's typical week before tracking, in standard drinks; 0 = not given. */ + var baselinePerWeek: Double + get() = p()?.getFloat("baselinePerWeek", 0f)?.toDouble() ?: 0.0 + set(v) { p()?.edit()?.putFloat("baselinePerWeek", v.toFloat())?.apply() } + + /** What one drink usually costs, in the user's currency; 0 = not given. */ + var pricePerDrink: Double + get() = p()?.getFloat("pricePerDrink", 0f)?.toDouble() ?: 0.0 + set(v) { p()?.edit()?.putFloat("pricePerDrink", v.toFloat())?.apply() } + + var lastType: DrinkType + get() = DrinkType.of(p()?.getString("lastType", DrinkType.BEER.key)) + set(v) { p()?.edit()?.putString("lastType", v.key)?.apply() } + + /** Tonight's plan: how many drinks, for which evening. */ + fun plan(day: LocalDate): Int? = + if (p()?.getString("planDay", null) == day.toString()) p()?.getInt("planCount", 0) else null + + fun setPlan(day: LocalDate, count: Int?) { + val e = p()?.edit() ?: return + if (count == null) e.remove("planDay").remove("planCount") else e.putString("planDay", day.toString()).putInt("planCount", count) + e.apply() + } + + val auditDate: LocalDate? get() = p()?.getString("auditDate", null)?.let { runCatching { LocalDate.parse(it) }.getOrNull() } + val auditScore: Int? get() = p()?.getInt("auditScore", -1)?.takeIf { it >= 0 } + + fun setAudit(day: LocalDate, score: Int) { + p()?.edit()?.putString("auditDate", day.toString())?.putInt("auditScore", score)?.apply() + } +} + +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() + + /** + * 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. + */ + suspend fun log( + db: PulseLoopDatabase, + type: DrinkType, + count: Int = 1, + timestamp: Long = System.currentTimeMillis(), + price: Double? = DrinkPrefs.pricePerDrink.takeIf { it > 0 }, + mealId: String? = null, + note: String? = null, + zone: ZoneId = ZoneId.systemDefault(), + ): List { + val evening = MealJournal.eveningOf(timestamp, zone) + val day = dayStart(evening, zone) + val rows = (0 until count.coerceIn(1, 12)).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, + ) + } + rows.forEach { db.drinkDao().upsert(it) } + val tag = JournalInsights.Tag.ALCOHOL.key + runCatching { db.journalDao().upsert(JournalEntryEntity(id = JournalEntryEntity.idFor(day, tag), day = day, tag = tag)) } + if (mealId == null) DrinkPrefs.lastType = type + return rows + } + + /** + * 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. + */ + suspend fun fromMeal(db: PulseLoopDatabase, meal: MealEntryEntity, zone: ZoneId = ZoneId.systemDefault()) { + if (!DrinkPrefs.enabled || !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) + } + + suspend fun onMealDeleted(db: PulseLoopDatabase, mealId: String) { + runCatching { db.drinkDao().deleteByMeal(mealId) } + } + + /** Alcohol per evening for the last [days] days. */ + suspend fun gramsByDay(db: PulseLoopDatabase, today: LocalDate, days: Long, zone: ZoneId): Map = + db.drinkDao().between(dayStart(today.minusDays(days), zone), dayStart(today.plusDays(1), zone)) + .groupBy { dateOf(it.day, zone) } + .mapValues { (_, v) -> v.sumOf { it.grams } } + + data class Snapshot( + val today: LocalDate, + val trackedSince: LocalDate, + val gramsPerStandard: Double, + val week: DrinkInsights.Week, + val weeklyLimit: Double, + val dryDaysTarget: Int, + val streaks: DrinkInsights.Streaks, + val weeks: List>, + val savings: DrinkInsights.Savings?, + val morningAfter: DrinkInsights.MorningAfter?, + val dose: DrinkInsights.Dose, + val recoveryNights: Double?, + /** Today's and yesterday's evenings, newest first. */ + val recent: List, + val planToday: Int?, + val todayStandard: Double, + val auditDue: Boolean, + ) + + suspend fun load(db: PulseLoopDatabase, now: Long = System.currentTimeMillis(), zone: ZoneId = ZoneId.systemDefault()): Snapshot { + // The evening in progress: before 04:00 the night still belongs to yesterday. + val today = MealJournal.eveningOf(now, zone) + val since = DrinkPrefs.trackedSince + val std = DrinkPrefs.gramsPerStandard + val byDay = gramsByDay(db, today, 120, zone) + val inputs = runCatching { ReadinessRepository.loadInputs(db, now, zone) }.getOrNull() + val nights = inputs?.let { it.history + listOfNotNull(it.lastNight) }.orEmpty() + val weeks = DrinkInsights.weeklyTotals(byDay, today, std, 8) + val completedSinceTracking = weeks.dropLast(1).filter { !it.first.isBefore(DrinkInsights.weekStart(since)) && it.first.plusDays(6).isAfter(since) } + val all = db.drinkDao().between(dayStart(today.minusDays(120), zone), dayStart(today.plusDays(1), zone)) + val kcalPerStd = all.takeIf { it.isNotEmpty() } + ?.let { list -> list.sumOf { it.kcal } / DrinkInsights.standardDrinks(list.sumOf { it.grams }, std).coerceAtLeast(0.1) } + ?: 150.0 + val baseline = DrinkPrefs.baselinePerWeek + val recent = all.filter { !dateOf(it.day, zone).isBefore(today.minusDays(1)) }.sortedByDescending { it.timestamp } + return Snapshot( + today = today, + trackedSince = since, + gramsPerStandard = std, + week = DrinkInsights.week(byDay, today, std, since), + weeklyLimit = DrinkPrefs.weeklyLimit, + dryDaysTarget = DrinkPrefs.dryDaysTarget, + streaks = DrinkInsights.streaks(byDay.filterValues { it > 0 }.keys, today, since), + weeks = weeks, + savings = if (baseline > 0 && completedSinceTracking.isNotEmpty()) + DrinkInsights.savings(completedSinceTracking.map { it.second }, baseline, DrinkPrefs.pricePerDrink.takeIf { it > 0 }, kcalPerStd) + else null, + morningAfter = DrinkInsights.morningAfter(inputs?.lastNight, nights, byDay, std, since), + dose = DrinkInsights.dose(nights, byDay, std, since), + recoveryNights = DrinkInsights.recoveryNights(nights, byDay, since), + recent = recent, + planToday = DrinkPrefs.plan(today), + todayStandard = DrinkInsights.standardDrinks(byDay[today] ?: 0.0, std), + auditDue = DrinkPrefs.auditDate?.let { it.plusDays(AuditC.RETAKE_DAYS) <= today } ?: true, + ) + } + + /** One line for a morning-after card or notification, null when there's nothing honest to say. */ + fun morningAfterLine(m: DrinkInsights.MorningAfter): String { + val drinks = "${DrinkInsights.fmt(m.standardDrinks)} drink${if (m.standardDrinks == 1.0) "" else "s"}" + val parts = buildList { + m.impact.hrvPct?.let { add("HRV ${kotlin.math.abs(it)}% ${if (it < 0) "below" else "above"} your dry nights") } + m.impact.restingHr?.let { if (it != 0) add("resting heart rate ${if (it > 0) "+" else ""}$it bpm") } + m.impact.asleepMinutes?.let { if (kotlin.math.abs(it) >= 10) add("${kotlin.math.abs(it)} min ${if (it < 0) "less" else "more"} sleep") } + } + return if (parts.isEmpty()) { + if (m.dryNights < DrinkInsights.MIN_NIGHTS) "Last night: $drinks. A few dry nights will show what it does to you." + else "Last night: $drinks. Your night looked close to your dry ones." + } else "Last night: $drinks. ${parts.joinToString(", ").replaceFirstChar { it.uppercase() }}." + } +} + +/** Drinks as the coach sees them; null when Drinks is off. */ +@Serializable +data class DrinksContext( + val weekStandardDrinks: Double, + val weeklyLimit: Double, + val dryDaysThisWeek: Int, + val dryDaysTarget: Int, + val currentDryStreak: Int, + val tonightPlan: Int? = null, + val todayStandardDrinks: Double, + val lastNightStandardDrinks: Double? = null, + val lastNightEffect: String? = null, + val standardDrinkGrams: Double, + val note: String = "Drinks the user logged themselves, in standard drinks of the given grams. Effects compare the user's own nights after drinking with their dry nights; a pattern, not proof.", +) { + companion object { + suspend fun build(db: PulseLoopDatabase, now: Long = System.currentTimeMillis()): DrinksContext? { + if (!DrinkPrefs.enabled) return null + return runCatching { + val s = DrinksRepository.load(db, now) + DrinksContext( + weekStandardDrinks = (s.week.standardDrinks * 10).toInt() / 10.0, + weeklyLimit = s.weeklyLimit, + dryDaysThisWeek = s.week.dryDays, + dryDaysTarget = s.dryDaysTarget, + currentDryStreak = s.streaks.current, + tonightPlan = s.planToday, + todayStandardDrinks = (s.todayStandard * 10).toInt() / 10.0, + lastNightStandardDrinks = s.morningAfter?.standardDrinks, + lastNightEffect = s.morningAfter?.let { DrinksRepository.morningAfterLine(it) }, + standardDrinkGrams = s.gramsPerStandard, + ) + }.getOrNull() + } + } +} diff --git a/app/src/main/java/com/pulseloop/service/MealJournal.kt b/app/src/main/java/com/pulseloop/service/MealJournal.kt index 0b4d7657..156f38b9 100644 --- a/app/src/main/java/com/pulseloop/service/MealJournal.kt +++ b/app/src/main/java/com/pulseloop/service/MealJournal.kt @@ -28,7 +28,7 @@ object MealJournal { private val ALCOHOL = Regex( "\\b(beer|wine|vodka|whisk(e)?y|gin|rum|tequila|cocktail|sake|cider|prosecco|champagne|" + "margarita|mojito|sangria|spritz|aperol|negroni|martini|ipa|lager|stout|bourbon|" + - "cerveja|chopp|vinho|caipirinha|cacha[cç]a|espumante)\\b", + "cerveja|chopp|vinho|caipirinha|cacha[cç]a|espumante)s?\\b", RegexOption.IGNORE_CASE, ) private val ALCOHOL_FREE = Regex( @@ -110,6 +110,8 @@ object MealJournal { } } } + // A drink in the meal is also a drink in Drinks, when the user tracks them. + runCatching { DrinksRepository.fromMeal(db, meal, zone) } runCatching { val goal = db.userGoalDao().get() if (goal != null && !goal.nutritionEnabled) db.userGoalDao().upsert(goal.copy(nutritionEnabled = true)) diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index 9c77a448..afa7ba66 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -648,6 +648,13 @@ fun PulseLoopApp() { NutritionScreen(onBack = { navController.popBackStack() }, start = start, onDiscuss = discussMeal) } } + paddedComposable("drinks") { + com.pulseloop.ui.screens.DrinksScreen( + onBack = { navController.popBackStack() }, + onBreathe = { navController.navigate("breathe") }, + onCoach = discussMeal, + ) + } paddedComposable("settings/about") { AboutSettingsScreen( onOpenDebug = { navController.navigate("debug") }, @@ -665,7 +672,11 @@ fun PulseLoopApp() { DebugScreen(debugVM, onBack = { navController.popBackStack() }) } paddedComposable("journal") { - com.pulseloop.ui.screens.JournalScreen(db = db, onBack = { navController.popBackStack() }) + com.pulseloop.ui.screens.JournalScreen( + db = db, + onBack = { navController.popBackStack() }, + onOpenDrinks = { navController.navigate("drinks") }, + ) } paddedComposable("activity_score") { com.pulseloop.ui.screens.ActivityScoreScreen( diff --git a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt index 684a4e8a..4ea7dfa5 100644 --- a/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt +++ b/app/src/main/java/com/pulseloop/ui/dashboard/DashboardCard.kt @@ -18,6 +18,7 @@ enum class DashboardCard(val key: String) { ACTIVITY("steps"), // Today-only SLEEP("sleep"), // Today-only NUTRITION("nutrition"), // Today-only: today's food log + DRINKS("drinks"), // Today-only, opt-in: this week's drinks (docs/drinks-plan.md) HEART_RATE("heartRate"), SPO2("spo2"), HRV("hrv"), @@ -33,6 +34,7 @@ enum class DashboardCard(val key: String) { ACTIVITY -> "Activity" SLEEP -> "Sleep" NUTRITION -> "Nutrition" + DRINKS -> "Drinks" HEART_RATE -> "Heart Rate" SPO2 -> "SpO₂" HRV -> "HRV" @@ -46,7 +48,7 @@ enum class DashboardCard(val key: String) { companion object { /** Default Today order (matches the hardcoded tile order it replaces). */ val todayDefault = listOf( - ACTIVITY, SLEEP, NUTRITION, HEART_RATE, SPO2, HRV, TEMPERATURE, STRESS, FATIGUE, GLUCOSE, BLOOD_PRESSURE, + ACTIVITY, SLEEP, NUTRITION, DRINKS, HEART_RATE, SPO2, HRV, TEMPERATURE, STRESS, FATIGUE, GLUCOSE, BLOOD_PRESSURE, ) /** Default Vitals order (matches iOS `defaultOrder` / the hardcoded card order it replaces). */ diff --git a/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt new file mode 100644 index 00000000..8d0499e6 --- /dev/null +++ b/app/src/main/java/com/pulseloop/ui/screens/DrinksUi.kt @@ -0,0 +1,554 @@ +package com.pulseloop.ui.screens + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.PathEffect +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.pulseloop.data.PulseLoopDatabase +import com.pulseloop.data.entity.DrinkEntryEntity +import com.pulseloop.service.AuditC +import com.pulseloop.service.DrinkInsights +import com.pulseloop.service.DrinkPrefs +import com.pulseloop.service.DrinkType +import com.pulseloop.service.DrinksRepository +import com.pulseloop.ui.theme.PulseColors +import com.pulseloop.ui.theme.dither +import kotlinx.coroutines.launch +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import kotlin.math.roundToInt + +/* + * Drinks (docs/drinks-plan.md): log, plan, see what drinking does to your nights, and cut down. + * Opt-in, private to the phone, and worded without judgement. + */ + +private fun std(v: Double) = DrinkInsights.fmt(v) + +@Composable +private fun DrinkCard(title: String? = null, content: @Composable ColumnScope.() -> Unit) { + Column( + Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(PulseColors.card).padding(16.dp), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + title?.let { Text(it.uppercase(), fontSize = 11.sp, letterSpacing = 1.6.sp, color = PulseColors.textMuted) } + content() + } +} + +@Composable +private fun Stepper(label: String, value: String, onMinus: () -> Unit, onPlus: () -> Unit, note: String? = null) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(label, fontSize = 14.sp, color = PulseColors.textPrimary) + note?.let { Text(it, fontSize = 11.sp, color = PulseColors.textMuted) } + } + TextButton(onClick = onMinus) { Text("−", fontSize = 18.sp) } + Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, modifier = Modifier.widthIn(min = 36.dp)) + TextButton(onClick = onPlus) { Text("+", fontSize = 18.sp) } + } +} + +@Composable +private fun Pill(label: String, on: Boolean, color: Color = PulseColors.accent, onClick: () -> Unit) { + val shape = RoundedCornerShape(16.dp) + Text( + label, + fontSize = 13.sp, + fontWeight = if (on) FontWeight.Bold else FontWeight.Normal, + color = if (on) PulseColors.onAccent else PulseColors.textSecondary, + maxLines = 1, + modifier = Modifier.clip(shape) + .background(if (on) color else PulseColors.cardSoft) + .border(1.dp, if (on) color else PulseColors.borderSubtle, shape) + .clickable(onClick = onClick) + .padding(horizontal = 12.dp, vertical = 8.dp), + ) +} + +@Composable +private fun Bar(fraction: Float, color: Color) { + val shape = RoundedCornerShape(2.dp) + Box(Modifier.fillMaxWidth().height(8.dp).clip(shape).dither(color, 0.25f)) { + Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).fillMaxHeight().background(color)) + } +} + +/** The Drinks screen; on first open, the welcome that turns it on. */ +@Composable +fun DrinksScreen(onBack: () -> Unit, onBreathe: () -> Unit, onCoach: ((String) -> Unit)?) { + val context = LocalContext.current + val db = remember { PulseLoopDatabase.getInstance(context) } + DrinkPrefs.init(context) + var enabled by remember { mutableStateOf(DrinkPrefs.enabled) } + var refresh by remember { mutableIntStateOf(0) } + val entries by remember { db.drinkDao().allFlow() }.collectAsState(initial = emptyList()) + val snap by produceState(null, refresh, entries, enabled) { + value = if (enabled) runCatching { DrinksRepository.load(db) }.getOrNull() else null + } + + Column(Modifier.fillMaxSize().background(PulseColors.background)) { + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + IconButton(onClick = onBack, modifier = Modifier.align(Alignment.CenterStart)) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } + Text("Drinks", modifier = Modifier.align(Alignment.Center), fontSize = 17.sp, fontWeight = FontWeight.Bold) + } + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + if (!enabled) { + DrinksWelcome { enabled = true } + } else { + val s = snap + if (s == null) { + Text("Reading your drinks…", color = PulseColors.textMuted, fontSize = 13.sp) + } else { + WeekSection(s) + LogSection(db, s) { refresh++ } + PlanSection(s) { refresh++ } + ImpactSection(s) + ProgressSection(s) + HelpSection(onBreathe, onCoach, s) + AuditSection(s) { refresh++ } + DrinkSettingsSection { on -> enabled = on; refresh++ } + Text( + "Your drinks stay on this phone. They aren't sent to Health Connect or included in diagnostics.", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + } + } + Spacer(Modifier.height(24.dp)) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun DrinksWelcome(onStart: () -> Unit) { + var typical by remember { mutableIntStateOf(DrinkPrefs.baselinePerWeek.roundToInt().takeIf { it > 0 } ?: 10) } + var limit by remember { mutableIntStateOf(7) } + var dry by remember { mutableIntStateOf(DrinkPrefs.dryDaysTarget) } + var grams by remember { mutableStateOf(DrinkPrefs.gramsPerStandard) } + var limitTouched by remember { mutableStateOf(false) } + DrinkCard { + Text("Drink less, see the difference", fontSize = 20.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text( + "Log drinks in a tap, set a weekly limit and dry days, and see what drinking does to your own nights: HRV, resting heart rate and sleep, from your ring.", + fontSize = 14.sp, color = PulseColors.textSecondary, + ) + } + DrinkCard("Where you are now") { + Stepper("A typical week", "$typical", { typical = (typical - 1).coerceAtLeast(0); if (!limitTouched) limit = suggestedLimit(typical) }, + { typical = (typical + 1).coerceAtMost(80); if (!limitTouched) limit = suggestedLimit(typical) }, + note = "Standard drinks, roughly. A can of beer or a glass of wine is about 1.3.") + } + DrinkCard("Your plan") { + Stepper("Weekly limit", "$limit", { limit = (limit - 1).coerceAtLeast(0); limitTouched = true }, { limit = (limit + 1).coerceAtMost(60); limitTouched = true }, + note = "Start a little under your typical week. Small steps last.") + Stepper("Dry days a week", "$dry", { dry = (dry - 1).coerceAtLeast(0) }, { dry = (dry + 1).coerceAtMost(7) }) + Text("Standard drink size", fontSize = 14.sp, color = PulseColors.textPrimary) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(10.0 to "10 g (WHO)", 8.0 to "8 g (UK unit)", 14.0 to "14 g (US)").forEach { (g, l) -> + Pill(l, grams == g, PulseColors.drinks) { grams = g } + } + } + } + Button( + onClick = { + DrinkPrefs.baselinePerWeek = typical.toDouble() + DrinkPrefs.weeklyLimit = limit.toDouble() + DrinkPrefs.dryDaysTarget = dry + DrinkPrefs.gramsPerStandard = grams + DrinkPrefs.setEnabled(true) + onStart() + }, + modifier = Modifier.fillMaxWidth(), + ) { Text("Start tracking") } + Text( + "If you drink most days, cut down gradually rather than stopping all at once, and talk to a doctor: stopping suddenly after heavy daily drinking can be dangerous.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) +} + +/** A first limit a bit under the user's typical week: 25 % fewer, never above 14. */ +internal fun suggestedLimit(typical: Int): Int = (typical * 0.75).roundToInt().coerceIn(0, 14) + +@Composable +private fun WeekSection(s: DrinksRepository.Snapshot) { + val w = s.week + DrinkCard("This week") { + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Text(std(w.standardDrinks), fontSize = 32.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("of ${std(s.weeklyLimit)} drinks", fontSize = 14.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 6.dp)) + } + val over = s.weeklyLimit > 0 && w.standardDrinks > s.weeklyLimit + Bar(if (s.weeklyLimit > 0) (w.standardDrinks / s.weeklyLimit).toFloat() else 0f, if (over) PulseColors.warning else PulseColors.drinks) + Row(Modifier.fillMaxWidth()) { + Column(Modifier.weight(1f)) { + Text("${w.dryDays} of ${s.dryDaysTarget}", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("dry days", fontSize = 12.sp, color = PulseColors.textMuted) + } + Column(Modifier.weight(1f)) { + Text("${s.streaks.current}", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("dry days in a row", fontSize = 12.sp, color = PulseColors.textMuted) + } + Column(Modifier.weight(1f)) { + Text(if (w.drankToday) std(s.todayStandard) else "0", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text("today", fontSize = 12.sp, color = PulseColors.textMuted) + } + } + if (w.heavyDays > 0) { + Text( + "${w.heavyDays} day${if (w.heavyDays > 1) "s" else ""} this week with 60 g of alcohol or more, the level WHO calls heavy drinking.", + fontSize = 12.sp, color = PulseColors.textSecondary, + ) + } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun LogSection(db: PulseLoopDatabase, s: DrinksRepository.Snapshot, onChange: () -> Unit) { + val scope = rememberCoroutineScope() + var more by remember { mutableStateOf(false) } + var lastLogged by remember { mutableStateOf(null) } + DrinkCard("Log a drink") { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + DrinkType.entries.forEach { t -> + Pill("+ ${t.label}", false) { + scope.launch { + DrinksRepository.log(db, t) + lastLogged = "Logged 1 ${t.label.lowercase()}" + onChange() + } + } + } + Pill("More…", false) { more = true } + } + lastLogged?.let { Text(it, fontSize = 12.sp, color = PulseColors.accent) } + if (s.recent.isNotEmpty()) { + val zone = ZoneId.systemDefault() + val fmt = DateTimeFormatter.ofPattern("EEE HH:mm") + s.recent.forEach { e -> RecentDrinkRow(e, s.gramsPerStandard, fmt, zone) { scope.launch { db.drinkDao().delete(e.id); onChange() } } } + } + } + if (more) MoreDrinkDialog(onDismiss = { more = false }) { type, count, hoursAgo, price -> + scope.launch { + DrinksRepository.log(db, type, count, System.currentTimeMillis() - hoursAgo * 3_600_000L, price = price) + lastLogged = "Logged $count ${type.label.lowercase()}" + more = false + onChange() + } + } +} + +@Composable +private fun RecentDrinkRow(e: DrinkEntryEntity, gramsPerStd: Double, fmt: DateTimeFormatter, zone: ZoneId, onDelete: () -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(DrinkType.of(e.type).label, fontSize = 14.sp, color = PulseColors.textPrimary) + Text( + "${Instant.ofEpochMilli(e.timestamp).atZone(zone).format(fmt)} · ${std(DrinkInsights.standardDrinks(e.grams, gramsPerStd))} std · ${e.kcal.roundToInt()} kcal" + + if (e.mealId != null) " · from your food log" else "", + fontSize = 11.sp, color = PulseColors.textMuted, + ) + } + IconButton(onClick = onDelete) { Icon(Icons.Filled.Delete, "Delete", tint = PulseColors.textMuted, modifier = Modifier.size(18.dp)) } + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun MoreDrinkDialog(onDismiss: () -> Unit, onLog: (DrinkType, Int, Long, Double?) -> Unit) { + var type by remember { mutableStateOf(DrinkPrefs.lastType) } + var count by remember { mutableIntStateOf(1) } + var hoursAgo by remember { mutableLongStateOf(0L) } + var price by remember { mutableStateOf(DrinkPrefs.pricePerDrink.takeIf { it > 0 }?.let { "%.2f".format(it) } ?: "") } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Log drinks") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + DrinkType.entries.forEach { t -> Pill(t.label, type == t, PulseColors.drinks) { type = t } } + } + Text("${type.volumeMl.roundToInt()} ml at ${type.abvPct}% · ${type.kcal.roundToInt()} kcal", fontSize = 11.sp, color = PulseColors.textMuted) + Stepper("How many", "$count", { count = (count - 1).coerceAtLeast(1) }, { count = (count + 1).coerceAtMost(12) }) + Text("When", fontSize = 14.sp, color = PulseColors.textPrimary) + FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + listOf(0L to "Now", 1L to "1 h ago", 3L to "3 h ago", 12L to "Last night").forEach { (h, l) -> + Pill(l, hoursAgo == h, PulseColors.drinks) { hoursAgo = h } + } + } + OutlinedTextField( + value = price, onValueChange = { price = it.filter { c -> c.isDigit() || c == '.' || c == ',' }.take(7) }, + label = { Text("Price each (optional)") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + singleLine = true, modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + TextButton(onClick = { onLog(type, count, hoursAgo, price.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0 }) }) { Text("Log") } + }, + dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, + ) +} + +@Composable +private fun PlanSection(s: DrinksRepository.Snapshot, onChange: () -> Unit) { + var plan by remember(s.planToday) { mutableIntStateOf(s.planToday ?: 2) } + DrinkCard("Plan tonight") { + if (s.planToday == null) { + Text("Going out? Decide before the first drink how many you'll have. It's easier to keep a number you chose sober.", fontSize = 13.sp, color = PulseColors.textSecondary) + Stepper("Tonight", if (plan == 0) "none" else "$plan", { plan = (plan - 1).coerceAtLeast(0) }, { plan = (plan + 1).coerceAtMost(12) }) + OutlinedButton(onClick = { DrinkPrefs.setPlan(s.today, plan); onChange() }, modifier = Modifier.fillMaxWidth()) { Text("Set tonight's plan") } + } else { + val planned = s.planToday + val had = s.todayStandard + Text( + when { + planned == 0 && had <= 0 -> "Tonight's plan: no drinks. So far, so good." + planned == 0 -> "Tonight's plan was no drinks; ${std(had)} logged." + had <= planned -> "${std(had)} of $planned planned" + else -> "${std(had)} logged, $planned planned. Water and food between drinks slow the next one." + }, + fontSize = 16.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary, + ) + if (planned > 0) Bar((had / planned).toFloat(), if (had > planned) PulseColors.warning else PulseColors.drinks) + TextButton(onClick = { DrinkPrefs.setPlan(s.today, null); onChange() }) { Text("Change plan") } + } + } +} + +@Composable +private fun ImpactSection(s: DrinksRepository.Snapshot) { + DrinkCard("What drinking does to you") { + s.morningAfter?.let { Text(DrinksRepository.morningAfterLine(it), fontSize = 14.sp, color = PulseColors.textPrimary) } + val d = s.dose + if (d.dryNights < DrinkInsights.MIN_NIGHTS) { + Text( + "After ${DrinkInsights.MIN_NIGHTS} dry nights with your ring on, PulseLoop compares your nights after drinking with your dry ones. ${d.dryNights} so far.", + fontSize = 13.sp, color = PulseColors.textSecondary, + ) + } else { + ImpactRow("After 1–2 drinks", d.light) + ImpactRow("After 3 or more", d.heavier) + s.recoveryNights?.let { + Text("Your HRV usually takes ${"%.1f".format(it)} night${if (it > 1.05) "s" else ""} to come back after drinking.", fontSize = 13.sp, color = PulseColors.textSecondary) + } + } + Text("Compared with your own dry nights since you started tracking. A pattern in your data, not proof of cause.", fontSize = 11.sp, color = PulseColors.textMuted) + } +} + +@Composable +private fun ImpactRow(label: String, i: DrinkInsights.Impact?) { + Column { + Text(label, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = PulseColors.textPrimary) + val text = if (i == null) "Not enough nights yet (${DrinkInsights.MIN_NIGHTS} needed)." else buildList { + i.hrvPct?.let { add("HRV ${kotlin.math.abs(it)}% ${if (it < 0) "lower" else "higher"}") } + i.restingHr?.let { add("resting HR ${if (it >= 0) "+" else ""}$it bpm") } + i.asleepMinutes?.let { add("${kotlin.math.abs(it)} min ${if (it < 0) "less" else "more"} sleep") } + }.joinToString(" · ").ifEmpty { "No clear difference" } + " (${i.nights} nights)" + Text(text, fontSize = 12.sp, color = PulseColors.textSecondary) + } +} + +@Composable +private fun ProgressSection(s: DrinksRepository.Snapshot) { + DrinkCard("Last 8 weeks") { + val max = maxOf(s.weeks.maxOfOrNull { it.second } ?: 0.0, s.weeklyLimit, 1.0) + val limitColor = PulseColors.textMuted + val barColor = PulseColors.drinks + val warn = PulseColors.warning + Canvas(Modifier.fillMaxWidth().height(110.dp)) { + val n = s.weeks.size.coerceAtLeast(1) + val slot = size.width / n + s.weeks.forEachIndexed { i, (_, v) -> + val h = (v / max * size.height).toFloat() + drawRect( + if (s.weeklyLimit > 0 && v > s.weeklyLimit) warn else barColor, + topLeft = Offset(i * slot + slot * 0.2f, size.height - h), + size = androidx.compose.ui.geometry.Size(slot * 0.6f, h), + ) + } + if (s.weeklyLimit > 0) { + val y = (size.height - s.weeklyLimit / max * size.height).toFloat() + drawLine(limitColor, Offset(0f, y), Offset(size.width, y), strokeWidth = 2f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 8f))) + } + } + Text("Dashed line: your weekly limit of ${std(s.weeklyLimit)}.", fontSize = 11.sp, color = PulseColors.textMuted) + Text("Best dry streak: ${s.streaks.best} day${if (s.streaks.best == 1) "" else "s"}", fontSize = 14.sp, color = PulseColors.textPrimary) + s.savings?.let { sv -> + if (sv.drinksAvoided >= 0.5) { + Text( + "Against your typical week: ${std(sv.drinksAvoided)} drinks fewer" + + (sv.money?.let { " · %.0f saved".format(it) } ?: "") + + " · ${"%,d".format(sv.kcal.roundToInt())} kcal not drunk", + fontSize = 14.sp, color = PulseColors.textPrimary, + ) + } + } + } +} + +@Composable +private fun HelpSection(onBreathe: () -> Unit, onCoach: ((String) -> Unit)?, s: DrinksRepository.Snapshot) { + DrinkCard("When you want a drink") { + Text("An urge usually peaks and passes within about 20 minutes. Slow breathing helps you ride it out.", fontSize = 13.sp, color = PulseColors.textSecondary) + Button(onClick = onBreathe, modifier = Modifier.fillMaxWidth()) { Text("Ride it out: 3 minutes of breathing") } + if (onCoach != null) { + OutlinedButton( + onClick = { onCoach("I'd like help with my drinking. This week I'm at ${std(s.week.standardDrinks)} of my ${std(s.weeklyLimit)}-drink limit, with ${s.week.dryDays} dry days. Can you help me plan the next few days?") }, + modifier = Modifier.fillMaxWidth(), + ) { Text("Talk it through with the coach") } + } + Text( + "Support in Brazil: CAPS AD (free public alcohol and drug care, ask your local health unit), Alcoólicos Anônimos (aa.org.br), and CVV on 188 any time you need to talk. Anywhere: your doctor.", + fontSize = 12.sp, color = PulseColors.textMuted, + ) + } +} + +@Composable +private fun AuditSection(s: DrinksRepository.Snapshot, onDone: () -> Unit) { + var taking by remember { mutableStateOf(false) } + val context = LocalContext.current + val sex = remember { mutableStateOf(null) } + LaunchedEffect(Unit) { sex.value = runCatching { PulseLoopDatabase.getInstance(context).userProfileDao().get()?.sex }.getOrNull() } + DrinkCard("3-question check") { + val score = DrinkPrefs.auditScore + if (score != null) { + val level = AuditC.level(score, sex.value) + Text("${level.label} (score $score of 12, ${DrinkPrefs.auditDate})", fontSize = 14.sp, fontWeight = FontWeight.Bold, color = PulseColors.textPrimary) + Text(AuditC.advice(level), fontSize = 13.sp, color = PulseColors.textSecondary) + } else { + Text("AUDIT-C, the World Health Organization's short alcohol screen. Three questions, under a minute.", fontSize = 13.sp, color = PulseColors.textSecondary) + } + if (s.auditDue) OutlinedButton(onClick = { taking = true }, modifier = Modifier.fillMaxWidth()) { Text(if (score == null) "Take the check" else "Retake (every 3 months)") } + Text("A screen, not a diagnosis.", fontSize = 11.sp, color = PulseColors.textMuted) + } + if (taking) { + val answers = remember { mutableStateListOf(-1, -1, -1) } + AlertDialog( + onDismissRequest = { taking = false }, + title = { Text("3-question check") }, + text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) { + AuditC.QUESTIONS.forEachIndexed { qi, (q, options) -> + Text(q, fontSize = 14.sp, fontWeight = FontWeight.Medium) + options.forEachIndexed { oi, o -> + Row( + Modifier.fillMaxWidth().clickable { answers[qi] = oi }.padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + androidx.compose.material3.RadioButton(selected = answers[qi] == oi, onClick = { answers[qi] = oi }) + Text(o, fontSize = 13.sp) + } + } + } + } + }, + confirmButton = { + TextButton(enabled = answers.all { it >= 0 }, onClick = { + DrinkPrefs.setAudit(java.time.LocalDate.now(), AuditC.score(answers)) + taking = false + onDone() + }) { Text("See result") } + }, + dismissButton = { TextButton(onClick = { taking = false }) { Text("Cancel") } }, + ) + } +} + +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun DrinkSettingsSection(onEnabledChange: (Boolean) -> Unit) { + var limit by remember { mutableIntStateOf(DrinkPrefs.weeklyLimit.roundToInt()) } + var dry by remember { mutableIntStateOf(DrinkPrefs.dryDaysTarget) } + var typical by remember { mutableIntStateOf(DrinkPrefs.baselinePerWeek.roundToInt()) } + var grams by remember { mutableStateOf(DrinkPrefs.gramsPerStandard) } + var price by remember { mutableStateOf(DrinkPrefs.pricePerDrink.takeIf { it > 0 }?.let { "%.2f".format(it) } ?: "") } + var confirmOff by remember { mutableStateOf(false) } + DrinkCard("Settings") { + Stepper("Weekly limit", "$limit", { limit = (limit - 1).coerceAtLeast(0); DrinkPrefs.weeklyLimit = limit.toDouble(); onEnabledChange(true) }, + { limit = (limit + 1).coerceAtMost(60); DrinkPrefs.weeklyLimit = limit.toDouble(); onEnabledChange(true) }) + Stepper("Dry days a week", "$dry", { dry = (dry - 1).coerceAtLeast(0); DrinkPrefs.dryDaysTarget = dry; onEnabledChange(true) }, + { dry = (dry + 1).coerceAtMost(7); DrinkPrefs.dryDaysTarget = dry; onEnabledChange(true) }) + Stepper("Typical week before", "$typical", { typical = (typical - 1).coerceAtLeast(0); DrinkPrefs.baselinePerWeek = typical.toDouble(); onEnabledChange(true) }, + { typical = (typical + 1).coerceAtMost(80); DrinkPrefs.baselinePerWeek = typical.toDouble(); onEnabledChange(true) }, + note = "Used for drinks, money and calories saved.") + Text("Standard drink size", fontSize = 14.sp, color = PulseColors.textPrimary) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + listOf(10.0 to "10 g (WHO)", 8.0 to "8 g (UK unit)", 14.0 to "14 g (US)").forEach { (g, l) -> + Pill(l, grams == g, PulseColors.drinks) { grams = g; DrinkPrefs.gramsPerStandard = g; onEnabledChange(true) } + } + } + OutlinedTextField( + value = price, + onValueChange = { + price = it.filter { c -> c.isDigit() || c == '.' || c == ',' }.take(7) + DrinkPrefs.pricePerDrink = price.replace(',', '.').toDoubleOrNull() ?: 0.0 + }, + label = { Text("Usual price of a drink (optional)") }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + singleLine = true, modifier = Modifier.fillMaxWidth(), + ) + TextButton(onClick = { confirmOff = true }) { Text("Turn off Drinks", color = PulseColors.danger) } + } + if (confirmOff) AlertDialog( + onDismissRequest = { confirmOff = false }, + title = { Text("Turn off Drinks?") }, + text = { Text("The tile and morning-after card disappear. Your logged drinks stay on this phone until you delete them or clear your data.") }, + confirmButton = { TextButton(onClick = { DrinkPrefs.setEnabled(false); confirmOff = false; onEnabledChange(false) }) { Text("Turn off") } }, + dismissButton = { TextButton(onClick = { confirmOff = false }) { Text("Keep") } }, + ) +} + +/** The Today tile: this week against the limit, dry days, and a one-tap "+1". */ +@Composable +fun ColumnScope.DrinksTileContent(week: DrinkInsights.Week?, limit: Double, dryTarget: Int, onAdd: () -> Unit) { + val total = week?.standardDrinks ?: 0.0 + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text(std(total), fontSize = 22.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textPrimary, maxLines = 1) + Text("of ${std(limit)} this week", fontSize = 11.sp, color = PulseColors.textMuted, modifier = Modifier.padding(bottom = 4.dp), maxLines = 1) + } + Bar(if (limit > 0) (total / limit).toFloat() else 0f, if (limit > 0 && total > limit) PulseColors.warning else PulseColors.drinks) + Text("${week?.dryDays ?: 0} of $dryTarget dry days", fontSize = 11.sp, color = PulseColors.textSecondary, maxLines = 1) + Spacer(Modifier.weight(1f)) + Text( + "+ ${DrinkPrefs.lastType.label}", + fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.accent, maxLines = 1, + modifier = Modifier.clickable(onClick = onAdd).padding(vertical = 2.dp), + ) +} diff --git a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt index d1aa9203..118a62e3 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/JournalUi.kt @@ -130,7 +130,7 @@ private fun DaySwitch(yesterday: Boolean, onChange: (Boolean) -> Unit) { /** Journal screen: tag today and yesterday, then see which tags line up with your nights. */ @Composable -fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit) { +fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit, onOpenDrinks: (() -> Unit)? = null) { val today = remember { LocalDate.now() } // Recompute effects whenever any tag changes. val todayEntries by remember { db.journalDao().forDayFlow(dayKey(today)) }.collectAsState(initial = emptyList()) @@ -163,6 +163,15 @@ fun JournalScreen(db: PulseLoopDatabase, onBack: () -> Unit) { ) { JournalTagsCard(db, today, "Today") JournalTagsCard(db, today.minusDays(1), "Yesterday") + // The Alcohol tag is a yes/no; Drinks counts them, sets a limit and shows the dose. + if (onOpenDrinks != null) { + Text( + if (com.pulseloop.service.DrinkPrefs.enabled) "Open Drinks: this week, your plan and what drinking does to your nights" + else "Want to drink less? Track drinks, set a weekly limit and see what each drink does to your nights", + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.drinks, + modifier = Modifier.clickable(onClick = onOpenDrinks).padding(vertical = 4.dp), + ) + } Text("What affects you", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = PulseColors.textMuted) val list = effects diff --git a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt index bf0fce1e..fa8dede4 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/NutritionScreen.kt @@ -211,6 +211,7 @@ fun NutritionScreen( IconButton(onClick = { scope.launch { db.mealEntryDao().deleteById(meal.id) + com.pulseloop.service.DrinksRepository.onMealDeleted(db, meal.id) reload() } }) { diff --git a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt index 9c1141ac..80eca212 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/SettingsScreen.kt @@ -138,6 +138,9 @@ fun SettingsScreen( SettingsRowItem(Icons.Filled.RestaurantMenu, PulseColors.calories, "Nutrition") { navigate("settings/nutrition") }, + SettingsRowItem(Icons.Filled.LocalBar, PulseColors.drinks, "Drinks") { + navigate("drinks") + }, ), ) diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt index 7aaeb4a9..7cae966c 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayGlance.kt @@ -149,7 +149,15 @@ private fun QuickChip(label: String, icon: ImageVector, tint: Color, modifier: M /** Morning moment: last night in one card. */ @Composable -fun LastNightCard(durationText: String, score: Int?, window: String?, onOpen: () -> Unit) { +fun LastNightCard( + durationText: String, + score: Int?, + window: String?, + onOpen: () -> Unit, + /** The morning after drinks (docs/drinks-plan.md): what last night's drinks did to the night. */ + drinksLine: String? = null, + onDrinks: (() -> Unit)? = null, +) { Column( Modifier .fillMaxWidth() @@ -167,6 +175,19 @@ fun LastNightCard(durationText: String, score: Int?, window: String?, onOpen: () } } window?.let { Text(it, fontSize = 13.sp, color = PulseColors.textMuted) } + drinksLine?.let { line -> + Text( + line, + fontSize = 13.sp, color = PulseColors.textPrimary, + modifier = Modifier + .padding(top = 6.dp) + .fillMaxWidth() + .clip(RoundedCornerShape(4.dp)) + .dither(PulseColors.drinks, 0.10f) + .then(if (onDrinks != null) Modifier.clickable(onClick = onDrinks) else Modifier) + .padding(horizontal = 10.dp, vertical = 8.dp), + ) + } } } diff --git a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt index abec23c5..a2282b4f 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/TodayScreen.kt @@ -114,6 +114,11 @@ fun TodayScreen( }.getOrNull() } val mealsToday = food?.meals + // Drinks, when the user tracks them: the tile and the morning-after line on Last night. + var drinkTick by remember { mutableIntStateOf(0) } + val drinks by produceState(null, state.lastUpdated, sleep.lastNight?.id, drinkTick) { + value = if (com.pulseloop.service.DrinkPrefs.enabled) runCatching { com.pulseloop.service.DrinksRepository.load(db) }.getOrNull() else null + } // Per-metric visibility + user order (iOS #64), read reactively so a hide/show/reorder // recomposes immediately (this is also the iOS #70 reactivity). @@ -123,6 +128,7 @@ fun TodayScreen( val supported: (DashboardCard) -> Boolean = { card -> when (card) { + DashboardCard.DRINKS -> com.pulseloop.service.DrinkPrefs.enabled DashboardCard.ACTIVITY, DashboardCard.SLEEP, DashboardCard.NUTRITION, DashboardCard.HEART_RATE, DashboardCard.SPO2 -> true DashboardCard.HRV -> vitals.supportsHrv @@ -151,6 +157,19 @@ fun TodayScreen( DashboardCard.ACTIVITY -> ActivityTileFor(state, units, m) { navController?.navigate("activity") } DashboardCard.SLEEP -> SleepTileFor(sleep, m) { navController?.navigate("sleep") } DashboardCard.NUTRITION -> NutritionTile(food, m, onLog = { mealSheet = true }) { navController?.navigate("nutrition") } + DashboardCard.DRINKS -> TodayTile(label = "Drinks", color = PulseColors.drinks, modifier = m, onTap = { navController?.navigate("drinks") }) { + DrinksTileContent( + week = drinks?.week, + limit = drinks?.weeklyLimit ?: com.pulseloop.service.DrinkPrefs.weeklyLimit, + dryTarget = drinks?.dryDaysTarget ?: com.pulseloop.service.DrinkPrefs.dryDaysTarget, + onAdd = { + scope.launch { + com.pulseloop.service.DrinksRepository.log(db, com.pulseloop.service.DrinkPrefs.lastType) + drinkTick++ + } + }, + ) + } DashboardCard.HEART_RATE -> ChartTile(cards.getValue(MetricKind.HEART_RATE), vitals.hrSamples, m) { navController?.navigate("vitals/hr") } DashboardCard.SPO2 -> ChartTile(cards.getValue(MetricKind.SPO2), vitals.spo2Samples, m) { navController?.navigate("vitals/spo2") } DashboardCard.HRV -> ChartTile(cards.getValue(MetricKind.HRV), vitals.hrvSamples, m) { navController?.navigate("vitals/hrv") } @@ -232,6 +251,8 @@ fun TodayScreen( score = sleep.score?.score ?: night.score, window = "${t(night.startAt)} – ${t(night.endAt)}", onOpen = { navController?.navigate("sleep") }, + drinksLine = drinks?.morningAfter?.let { com.pulseloop.service.DrinksRepository.morningAfterLine(it) }, + onDrinks = { navController?.navigate("drinks") }, ) } } diff --git a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt index b8f1c764..dc67f726 100644 --- a/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt +++ b/app/src/main/java/com/pulseloop/ui/theme/PulseColors.kt @@ -43,6 +43,7 @@ object PulseColors { val bloodPressure = Color(0xFFFF7FA8) val bloodSugar = Color(0xFFFFC46B) val fatigue = Color(0xFFC98CFF) + val drinks = Color(0xFFE38FB5) // wine rose val readiness = Color(0xFF43F3B7) // the headline score wears the brand mint // Vitals reference-zone colors (AppTheme.swift zone*) — aliased by diff --git a/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt b/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt new file mode 100644 index 00000000..1dc1df80 --- /dev/null +++ b/app/src/test/java/com/pulseloop/service/DrinkInsightsTest.kt @@ -0,0 +1,161 @@ +package com.pulseloop.service + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.time.LocalDate +import java.time.ZoneOffset + +/** Drinks: types, the week, streaks, savings, what drinking does to the nights, and AUDIT-C. */ +class DrinkInsightsTest { + + private val zone = ZoneOffset.UTC + private fun d(month: Int, day: Int) = LocalDate.of(2026, month, day) + + private fun night(day: LocalDate, hrv: Double? = 50.0, rhr: Double? = 55.0, asleep: Int = 450): NightSummary { + val end = day.atTime(7, 0).atZone(zone).toInstant().toEpochMilli() + return NightSummary(day, end - 8 * 3600_000L, end, asleep, rhr, hrv, 1.0) + } + + // ── Types ──────────────────────────────────────────────────────────────────────────────── + + @Test + fun `a can of beer is about 14 g of alcohol`() { + assertEquals(13.8, DrinkType.BEER.grams, 0.05) + assertEquals(1.38, DrinkInsights.standardDrinks(DrinkType.BEER.grams, 10.0), 0.01) + assertEquals("1.5", DrinkInsights.fmt(1.46)) + assertEquals("2", DrinkInsights.fmt(2.0)) + } + + @Test + fun `drink type and count are read from free text`() { + assertEquals(DrinkType.WINE, DrinkType.guess("2 taças de vinho")) + assertEquals(DrinkType.CAIPIRINHA, DrinkType.guess("Caipirinha de limão")) + assertEquals(DrinkType.DRAFT, DrinkType.guess("Chopp")) + assertEquals(DrinkType.BEER_600, DrinkType.guess("Cerveja 600ml")) + assertEquals(DrinkType.BEER, DrinkType.guess("3 beers")) + assertEquals(DrinkType.COCKTAIL, DrinkType.guess("Gin tônica")) + assertEquals(DrinkType.SPIRIT, DrinkType.guess("Whisky on the rocks")) + assertEquals(DrinkType.OTHER, DrinkType.guess("Hard cider")) + assertEquals(2, DrinkType.count("2 taças de vinho")) + assertEquals(2, DrinkType.count("duas cervejas")) + assertEquals(3, DrinkType.count("3x beer")) + assertEquals(1, DrinkType.count("Wine")) + } + + // ── The week ───────────────────────────────────────────────────────────────────────────── + + @Test + fun `the week counts drinks from Monday and dry days through yesterday`() { + val today = d(10, 21) // Wednesday + val w = DrinkInsights.week(mapOf(d(10, 19) to 20.0, d(10, 21) to 13.8), today, 10.0, trackedSince = d(10, 1)) + assertEquals(d(10, 19), w.start) + assertEquals(3.38, w.standardDrinks, 0.01) + assertEquals(2, w.drinkingDays) + assertEquals(1, w.dryDays) // Tuesday; today isn't over + assertTrue(w.drankToday) + assertEquals(0, w.heavyDays) + assertEquals(1, DrinkInsights.week(mapOf(d(10, 19) to 70.0), today, 10.0, d(10, 1)).heavyDays) + } + + @Test + fun `days before tracking began are not counted as dry`() { + val w = DrinkInsights.week(emptyMap(), d(10, 21), 10.0, trackedSince = d(10, 20)) + assertEquals(1, w.dryDays) + } + + @Test + fun `weekly totals cover the last weeks oldest first`() { + val totals = DrinkInsights.weeklyTotals(mapOf(d(10, 13) to 20.0, d(10, 20) to 10.0), d(10, 21), 10.0, 3) + assertEquals(listOf(d(10, 5), d(10, 12), d(10, 19)), totals.map { it.first }) + assertEquals(listOf(0.0, 2.0, 1.0), totals.map { it.second }) + } + + // ── Streaks and savings ────────────────────────────────────────────────────────────────── + + @Test + fun `dry streaks run through yesterday`() { + val s = DrinkInsights.streaks(setOf(d(10, 15), d(10, 19)), d(10, 21), trackedSince = d(10, 10)) + assertEquals(1, s.current) + assertEquals(5, s.best) + assertEquals(0, DrinkInsights.streaks(setOf(d(10, 21)), d(10, 21), d(10, 10)).current) + assertEquals(3, DrinkInsights.streaks(emptySet(), d(10, 21), d(10, 18)).current) + } + + @Test + fun `savings count only weeks under the typical week`() { + val s = DrinkInsights.savings(listOf(5.0, 12.0), baselinePerWeek = 10.0, pricePerDrink = 8.0, kcalPerDrink = 150.0) + assertEquals(5.0, s.drinksAvoided, 0.0) + assertEquals(40.0, s.money!!, 0.0) + assertEquals(750.0, s.kcal, 0.0) + assertNull(DrinkInsights.savings(listOf(5.0), 10.0, null, 150.0).money) + } + + // ── Nights ─────────────────────────────────────────────────────────────────────────────── + + @Test + fun `the morning after compares last night with dry nights`() { + val since = d(10, 10) + val dry = (11..18).map { night(d(10, it)) } + val last = night(d(10, 21), hrv = 40.0, rhr = 60.0, asleep = 400) + val m = DrinkInsights.morningAfter(last, dry, mapOf(d(10, 20) to 30.0), 10.0, since)!! + assertEquals(3.0, m.standardDrinks, 0.0) + assertEquals(-20, m.impact.hrvPct) + assertEquals(5, m.impact.restingHr) + assertEquals(-50, m.impact.asleepMinutes) + val line = DrinksRepository.morningAfterLine(m) + assertTrue(line, line.startsWith("Last night: 3 drinks.")) + assertTrue(line, line.contains("HRV 20% below your dry nights")) + } + + @Test + fun `no morning after without drinks, and no comparison below three dry nights`() { + val since = d(10, 10) + assertNull(DrinkInsights.morningAfter(night(d(10, 21)), emptyList(), emptyMap(), 10.0, since)) + val few = DrinkInsights.morningAfter(night(d(10, 21)), listOf(night(d(10, 19))), mapOf(d(10, 20) to 20.0), 10.0, since)!! + assertNull(few.impact.hrvPct) + assertTrue(DrinksRepository.morningAfterLine(few).contains("A few dry nights")) + } + + @Test + fun `dose separates one or two drinks from three or more`() { + val since = d(9, 30) + val nights = (1..5).map { night(d(10, it)) } + + (6..8).map { night(d(10, it), hrv = 45.0) } + + (9..11).map { night(d(10, it), hrv = 35.0) } + val grams = (5..7).associate { d(10, it) to 15.0 } + (8..10).associate { d(10, it) to 40.0 } + val dose = DrinkInsights.dose(nights, grams, 10.0, since) + assertEquals(5, dose.dryNights) + assertEquals(-10, dose.light!!.hrvPct) + assertEquals(-30, dose.heavier!!.hrvPct) + assertEquals(3, dose.heavier!!.nights) + } + + @Test + fun `recovery is the nights until HRV is back within 5 percent`() { + val since = d(9, 30) + val hrv = mapOf(6 to 40.0, 7 to 49.0, 11 to 48.0) + val nights = (1..12).map { night(d(10, it), hrv = hrv[it] ?: 50.0) } + val r = DrinkInsights.recoveryNights(nights, mapOf(d(10, 5) to 20.0, d(10, 10) to 20.0), since) + assertNotNull(r) + assertEquals(1.5, r!!, 0.0) + assertNull(DrinkInsights.recoveryNights(nights, mapOf(d(10, 5) to 20.0), since)) + } + + // ── AUDIT-C ────────────────────────────────────────────────────────────────────────────── + + @Test + fun `audit-c thresholds differ by sex and 8 is higher risk`() { + assertEquals(3, AuditC.score(listOf(1, 1, 1))) + assertEquals(AuditC.Level.INCREASING, AuditC.level(3, "female")) + assertEquals(AuditC.Level.INCREASING, AuditC.level(3, null)) + assertEquals(AuditC.Level.LOW, AuditC.level(3, "male")) + assertEquals(AuditC.Level.HIGHER, AuditC.level(8, "male")) + assertEquals(AuditC.Level.LOW, AuditC.level(0, null)) + assertTrue(AuditC.advice(AuditC.Level.HIGHER).contains("don't stop all at once")) + assertFalse(AuditC.advice(AuditC.Level.LOW).contains("doctor")) + } +} diff --git a/docs/drinks-plan.md b/docs/drinks-plan.md new file mode 100644 index 00000000..569eed36 --- /dev/null +++ b/docs/drinks-plan.md @@ -0,0 +1,157 @@ +# Drinks: tracking and cutting down on alcohol + +Status: built in v2.11.23+98. Written 2026-10-20. + +## 1. What competitors do + +| App | Kind | What it does | What it lacks | +|---|---|---|---| +| WHOOP | Band | Journal "alcohol" answer; Behavior Impacts shows next-day Recovery effect. Says HRV can take 4–5 days to rebound | Counts, goals, any help to cut down | +| Oura | Ring | "Alcohol" tag beside the night; member data: HRV −15.6%, lowest RHR +8.2%, −35 min sleep the night after | Same | +| Sunnyside | Cut-down app (paid) | Weekly plan of drinks per day and week from current habits; text or app logging; weekly recap; coaches | Knows nothing about the body | +| Reframe | Cut-down app (paid, leans to quitting) | Baseline + goal; weekly/monthly charts; craving toolkit for the ~20-minute urge (breathing, games) | Same | +| Try Dry (Alcohol Change UK, free) | Cut-down app | Units, calories, money saved; dry-day streaks and badges; *planned drinking*; AUDIT-C every 3 months | Same | +| MyDrinkaware (free) | Cut-down app | Units/calories per drink; drink-free days; sleep beside drinking; binge warning | Same | + +Evidence: the UCL *Drink Less* factorial trial (Crane et al., 2018, n = 672) found no single +component worked alone; self-monitoring with feedback plus action planning, and normative +feedback plus cognitive-bias retraining, gave modest gains. Self-monitoring with rich feedback was +the most used and best rated. So the core is **log → feedback → plan**. + +**The gap PulseLoop fills:** the ring apps show the cost but don't help; the cut-down apps help +but can only guess the cost. PulseLoop has both the night's physiology and a food log. + +## 2. UI/UX analysis: where it fits + +### The app today + +- **Five tabs** (Today, Vitals, Activity, Sleep, Coach). Tabs are body systems and the coach. +- **Today in three layers** (docs/oura-ux-analysis.md): + 1. *Glance*: score header, one-line brief, alert line. + 2. *Act*: `QuickLogRow` (Meal · Tag day · Measure · Workout) and at most **two** time-of-day + moment cards (`TodayMoments`: last night 4–10 h, food 11–15 h, tonight from 17 h, tag day + from 19 h). + 3. *Browse*: customisable tile grid (`DashboardCard`), with Nutrition as the only behaviour tile. +- **Behaviour inputs** live off-tab: Nutrition screen (tile, quick chip, widget, shortcut), + Journal (Tag day sheet → "See what affects you"), My Health (from Vitals). +- **Alcohol already exists** as a journal tag, auto-ticked by `MealJournal` when a logged meal + names a drink, and analysed by `JournalInsights` against the next night. +- Settings → Goals holds daily targets; Settings → Nutrition holds the food log's options. + +### Options considered + +| Placement | Verdict | Why | +|---|---|---| +| New bottom tab | **No** | Tabs are body systems; five is the Material maximum; it would put alcohol in front of every user, including those who don't drink — wrong prominence for a sensitive, opt-in topic | +| Section inside Nutrition | No | Drinks need their own goals, streaks and night impact; buried below food they'd be skipped, and a dry day is not a food event | +| Extend the Journal "Alcohol" tag only | No | A yes/no tag can't count drinks, so no dose, no weekly limit, no progress | +| Fifth Quick Log chip | No | Four equal chips already fill a phone width; a fifth crowds them for everyone | +| **Dedicated "Drinks" screen, reached from Today, opt-in** | **Yes** | Same pattern as Nutrition: a full screen for the work, a Today tile for the glance and the one-tap log, moment cards for the right time | + +### The chosen design + +- **Opt-in.** Off by default. Turned on from the Drinks screen's welcome, from Settings → Goals → + Drinks, or from a one-line offer on the Journal screen next to the Alcohol tag. Turning it off + hides every surface; data stays until deleted. +- **Today, Browse layer: a Drinks tile** (`DashboardCard.DRINKS`, only when enabled). Shows this + week's drinks against the limit, dry days, and a **"+1"** that logs the last-used drink. Same + shape as the Nutrition tile, so it reads as "a thing I log". +- **Today, Act layer: the Last night card gains a drinks line** on the morning after drinks + (it shows 04–10 h, like the card itself). No new moment and no new chip: the morning-after + question *is* a last-night question, so it belongs on that card. It says the part only + PulseLoop can say: *"Last night, 3 drinks. HRV 18 % below your dry nights, resting heart rate + +5 bpm, 35 min less sleep."* Tapping the line opens Drinks. +- **Drinks screen** (`drinks`), top to bottom in order of use: + 1. This week: drinks vs limit, dry days vs target, current dry streak. + 2. Log: one-tap presets (beer, wine, spirit, caipirinha, cocktail, other), a sheet for size, + count, time and price; today's and yesterday's drinks with delete. + 3. Plan tonight (planned drinking): how many, then progress against it. + 4. What drinking does to you: last night; 1–2 vs 3+ drinks against dry nights; days for HRV to + come back. Labelled "a pattern in your nights, not cause and effect". + 5. Progress: 8-week bars with the limit line, best streak, money and calories not spent. + 6. Help: "Craving? Ride it out" → Breathe; "Talk it through" → Coach. + 7. Check-in: AUDIT-C every 90 days, with where to get help. + 8. Settings: limit, dry days, standard drink size, typical week, price, off switch. +- **Journal:** logging a drink ticks the Alcohol tag for that evening, so the existing "What + affects you" keeps working; the Alcohol row links to Drinks. +- **Settings → Metrics → Drinks** opens the same screen. +- **Food log:** a meal that names a drink also creates a drink entry (linked to the meal, deleted + with it), so nobody logs twice. A drink logged on its own within 30 minutes of the same type is + not duplicated. +- **Coach:** sees this week, the plan and last night, and can log a drink, read the summary and set + tonight's plan. Tone rules in the prompt (below). +- **Weekly report:** one extra line when enabled ("4 drinks, 4 dry days"). + +### Tone and safety + +- **Neutral words.** "Drinks", "dry days", never "relapse", "sober", "binge" in headlines. Heavy + days (≥ 60 g alcohol, WHO's heavy episodic threshold) are stated as facts, not judgements. +- **No push to stop abruptly.** Stopping suddenly after heavy daily drinking can be dangerous + (withdrawal). The screen, the AUDIT-C result and the coach prompt all say: cut down gradually, + and talk to a doctor if you drink most days. +- **Help is one tap away**: CAPS AD (Brazil's public alcohol and drug service), Alcoólicos + Anônimos, and CVV 188 for emotional support, plus "your doctor" for everyone. +- **Private.** On the phone only; not in Health Connect (there is no alcohol record type), not in + diagnostics exports; included in the user's own backup archive. + +## 3. Data + +- `drink_entries` (DB v32): `id`, `timestamp`, `day` (local start of the *evening* day, via + `MealJournal.eveningOf`), `type`, `volumeMl`, `abvPct`, `grams`, `kcal`, `price`, `mealId`, + `note`, `createdAt`. +- `DrinkPrefs` (SharedPreferences): enabled, weekly limit (standard drinks), dry-days target, + grams per standard drink (10 WHO default; 8 UK unit; 14 US), typical week (baseline), price per + drink, enabledAt, last used preset, tonight's plan (date + count), AUDIT-C (date + score). +- Standard drinks are computed at read time from grams, so changing the standard size re-renders + history consistently. + +| Preset | Volume | ABV | kcal | +|---|---|---|---| +| Beer (can) | 350 ml | 5 % | 150 | +| Beer (600 ml bottle) | 600 ml | 5 % | 255 | +| Draft (chopp) | 300 ml | 5 % | 130 | +| Wine (glass) | 150 ml | 12 % | 125 | +| Spirit (shot) | 40 ml | 40 % | 95 | +| Caipirinha | 50 ml cachaça | 40 % | 240 | +| Cocktail | 50 ml spirit | 40 % | 200 | + +Grams = ml × ABV × 0.789. + +## 4. Logic (pure, unit-tested: `DrinkInsights`) + +- **Week:** ISO week from Monday; total standard drinks, drinking days, dry days so far (days + elapsed − drinking days), heavy days. +- **Streaks:** current and best run of dry days since the feature was enabled (days before + `enabledAt` are unknown, not dry). +- **Savings:** per completed week since `enabledAt`, max(0, baseline − actual) × price and × kcal + per drink (from the user's own average drink, or 150 kcal). +- **Morning after:** last night vs the median of dry nights in the last 60: HRV %, resting HR, + minutes asleep. Needs ≥ 3 dry nights. +- **Dose:** nights after 1–2 and after 3+ standard drinks vs dry nights; a group needs ≥ 3 nights. +- **Recovery:** for each drinking evening followed by dry ones, days until HRV is back within 5 % + of the dry median; average over ≥ 2 episodes. +- **AUDIT-C:** three answers scored 0–4; positive at ≥ 4 (men) or ≥ 3 (women / unspecified); ≥ 8 + "higher risk". + +## 5. Build order + +1. Data: entity, DAO, migration 31→32, prefs, archive. +2. `DrinkInsights` + tests. +3. Drinks screen, settings and onboarding; route; Settings → Goals entry. +4. Today: Drinks tile, morning-after line on the Last night card. +5. Food log + journal links. +6. Coach context, tools and prompt rules; weekly report line. +7. CI, merge, release. + +Follow-ups (not in this change): a "drinks before this night" chip on the Sleep tab, a home-screen +widget, an evening plan reminder. + +## Sources + +- WHOOP: https://www.whoop.com/thelocker/alcohol-affects-body-hrv-sleep/ +- Oura: https://ouraring.com/blog/how-does-alcohol-impact-oura-members/ +- Sunnyside: https://healthline.com/health/sunnyside-app-review +- Reframe: https://www.choosingtherapy.com/reframe-app-review/ +- Try Dry: https://alcoholchange.org.uk/blog/the-try-dry-apps-top-ten-features +- MyDrinkaware: https://drinkaware.co.uk/tools/mydrinkaware-app +- Crane et al. 2018: https://discovery.ucl.ac.uk/id/eprint/10044247/