mirror of
https://github.com/mudabbir-ahmad/Kotlin-TB2P1.git
synced 2026-12-06 20:13:10 +00:00
Refactor habit management: update habit card display to use name instead of activity type, streamline habit creation and update logic, and remove unused methods for date normalization
This commit is contained in:
1 parent
db39671a2f
commit
849ed06fb1
12 files changed
+104
-205
No files matched your search
@@ -1,7 +0,0 @@
|
|||||||
package com.example.madwellbeingapp.data
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Room type converters. Currently empty since HabitCategory enum was removed.
|
|
||||||
* Kept in case future types need conversion.
|
|
||||||
*/
|
|
||||||
class Converters
|
|
||||||
@@ -13,7 +13,7 @@ import com.example.madwellbeingapp.data.model.HabitLog
|
|||||||
|
|
||||||
@Database(
|
@Database(
|
||||||
entities = [Habit::class, HabitLog::class, ActivityType::class],
|
entities = [Habit::class, HabitLog::class, ActivityType::class],
|
||||||
version = 3,
|
version = 4,
|
||||||
exportSchema = false
|
exportSchema = false
|
||||||
)
|
)
|
||||||
abstract class HabitDatabase : RoomDatabase() {
|
abstract class HabitDatabase : RoomDatabase() {
|
||||||
|
|||||||
@@ -21,8 +21,6 @@ interface HabitLogDao {
|
|||||||
@Query("DELETE FROM habit_logs WHERE habitId = :habitId AND date = :date")
|
@Query("DELETE FROM habit_logs WHERE habitId = :habitId AND date = :date")
|
||||||
suspend fun deleteLogForDate(habitId: Int, date: Long): Int
|
suspend fun deleteLogForDate(habitId: Int, date: Long): Int
|
||||||
|
|
||||||
@Query("SELECT COUNT(*) FROM habit_logs WHERE habitId = :habitId AND completed = 1")
|
|
||||||
fun getCompletedCount(habitId: Int): Flow<Int>
|
|
||||||
|
|
||||||
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId AND completed = 1 ORDER BY date DESC")
|
@Query("SELECT * FROM habit_logs WHERE habitId = :habitId AND completed = 1 ORDER BY date DESC")
|
||||||
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog>
|
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog>
|
||||||
|
|||||||
@@ -5,30 +5,29 @@ import androidx.room.PrimaryKey
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a habit tracked by the user.
|
* Represents a habit tracked by the user.
|
||||||
* [name] is the activity type name in FULL CAPS (e.g. "GYM").
|
* [name] is the activity type in FULL CAPS (e.g. "GYM").
|
||||||
* [details] is optional extra info with first-char uppercase (e.g. "Legs", "5k").
|
* [details] is optional extra info with first-char uppercase (e.g. "Legs").
|
||||||
* The display name combines them: "GYM(Legs)" when details is present, or just "GYM".
|
* Display: "GYM(Legs)" when details present, or just "GYM".
|
||||||
*/
|
*/
|
||||||
@Entity(tableName = "habits")
|
@Entity(tableName = "habits")
|
||||||
data class Habit(
|
data class Habit(
|
||||||
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
@PrimaryKey(autoGenerate = true) val id: Int = 0,
|
||||||
val name: String,
|
val name: String,
|
||||||
val details: String = "",
|
val details: String = "",
|
||||||
val activityType: String = "", // the user-created activity type name
|
val startDate: Long,
|
||||||
val startDate: Long, // epoch millis – auto-set on creation
|
val targetFrequency: Int,
|
||||||
val targetFrequency: Int, // times per week the user wants to complete this habit
|
|
||||||
val reminderEnabled: Boolean = true,
|
val reminderEnabled: Boolean = true,
|
||||||
val reminderHour: Int = 9, // default 09:00
|
val reminderHour: Int = 9,
|
||||||
val reminderMinute: Int = 0,
|
val reminderMinute: Int = 0,
|
||||||
val isActive: Boolean = true
|
val isActive: Boolean = true
|
||||||
) {
|
) {
|
||||||
/** Returns the formatted display name: "NAME(Details)" or just "NAME". */
|
/** Formatted display name: "NAME(Details)" or just "NAME". */
|
||||||
val displayName: String
|
val displayName: String
|
||||||
get() {
|
get() {
|
||||||
val upperName = name.uppercase()
|
val upperName = name.uppercase()
|
||||||
if (details.isBlank()) return upperName
|
if (details.isBlank()) return upperName
|
||||||
val formattedDetails = if (details.length <= 1) details.uppercase()
|
val fmt = if (details.length <= 1) details.uppercase()
|
||||||
else details[0].uppercaseChar() + details.substring(1).lowercase()
|
else details[0].uppercaseChar() + details.substring(1).lowercase()
|
||||||
return "$upperName($formattedDetails)"
|
return "$upperName($fmt)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Single source of truth for habit, log, and activity-type data.
|
* Single source of truth for habit, log, and activity-type data.
|
||||||
* Abstracts the data sources away from the ViewModels.
|
* Abstracts the DAOs away from the ViewModel.
|
||||||
*/
|
*/
|
||||||
class HabitRepository(
|
class HabitRepository(
|
||||||
private val habitDao: HabitDao,
|
private val habitDao: HabitDao,
|
||||||
@@ -24,21 +24,15 @@ class HabitRepository(
|
|||||||
|
|
||||||
suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id)
|
suspend fun getHabitByIdOnce(id: Int): Habit? = habitDao.getHabitByIdOnce(id)
|
||||||
|
|
||||||
suspend fun insertHabit(habit: Habit): Long = habitDao.upsert(habit)
|
suspend fun upsertHabit(habit: Habit): Long = habitDao.upsert(habit)
|
||||||
|
|
||||||
suspend fun updateHabit(habit: Habit) = habitDao.upsert(habit)
|
|
||||||
|
|
||||||
|
|
||||||
/** Returns an existing habit with the same name+details (case-insensitive), or null. */
|
|
||||||
suspend fun findDuplicate(name: String, details: String): Habit? =
|
suspend fun findDuplicate(name: String, details: String): Habit? =
|
||||||
habitDao.findDuplicate(name, details)
|
habitDao.findDuplicate(name, details)
|
||||||
|
|
||||||
// ── Activity Types ──────────────────────────────────────
|
// ── Activity Types ──────────────────────────────────────
|
||||||
val allActivityTypes: Flow<List<ActivityType>> = activityTypeDao.getAll()
|
val allActivityTypes: Flow<List<ActivityType>> = activityTypeDao.getAll()
|
||||||
|
|
||||||
suspend fun addActivityType(activityType: ActivityType): Long =
|
suspend fun addActivityType(type: ActivityType): Long = activityTypeDao.upsert(type)
|
||||||
activityTypeDao.upsert(activityType)
|
|
||||||
|
|
||||||
|
|
||||||
suspend fun findActivityTypeByName(name: String): ActivityType? =
|
suspend fun findActivityTypeByName(name: String): ActivityType? =
|
||||||
activityTypeDao.findByName(name)
|
activityTypeDao.findByName(name)
|
||||||
@@ -50,21 +44,15 @@ class HabitRepository(
|
|||||||
fun getLogsForDate(date: Long): Flow<List<HabitLog>> =
|
fun getLogsForDate(date: Long): Flow<List<HabitLog>> =
|
||||||
habitLogDao.getLogsForDate(date)
|
habitLogDao.getLogsForDate(date)
|
||||||
|
|
||||||
suspend fun getLogForDate(habitId: Int, date: Long): HabitLog? =
|
|
||||||
habitLogDao.getLogForDate(habitId, date)
|
|
||||||
|
|
||||||
suspend fun toggleLog(habitId: Int, date: Long) {
|
suspend fun toggleLog(habitId: Int, date: Long) {
|
||||||
val existing = habitLogDao.getLogForDate(habitId, date)
|
val existing = habitLogDao.getLogForDate(habitId, date)
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
habitLogDao.deleteLogForDate(habitId, date)
|
habitLogDao.deleteLogForDate(habitId, date)
|
||||||
} else {
|
} else {
|
||||||
habitLogDao.upsert(HabitLog(habitId = habitId, date = date, completed = true))
|
habitLogDao.upsert(HabitLog(habitId = habitId, date = date))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getCompletedCount(habitId: Int): Flow<Int> =
|
|
||||||
habitLogDao.getCompletedCount(habitId)
|
|
||||||
|
|
||||||
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> =
|
suspend fun getCompletedLogsDesc(habitId: Int): List<HabitLog> =
|
||||||
habitLogDao.getCompletedLogsDesc(habitId)
|
habitLogDao.getCompletedLogsDesc(habitId)
|
||||||
|
|
||||||
|
|||||||
-1
@@ -4,7 +4,6 @@ import android.app.AlarmManager
|
|||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -52,9 +52,8 @@ fun ActiveOnlyScreen(
|
|||||||
items(activeHabits, key = { it.id }) { habit ->
|
items(activeHabits, key = { it.id }) { habit ->
|
||||||
HabitCard(
|
HabitCard(
|
||||||
habit = habit,
|
habit = habit,
|
||||||
viewModel = viewModel,
|
|
||||||
onClick = { onHabitClick(habit.id) },
|
onClick = { onHabitClick(habit.id) },
|
||||||
circleText = if (habit.activityType.isNotBlank()) habit.activityType.first().toString() else "•",
|
circleText = if (habit.name.isNotBlank()) habit.name.first().toString() else "•",
|
||||||
circleTextColor = MaterialTheme.colorScheme.primary
|
circleTextColor = MaterialTheme.colorScheme.primary
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -327,12 +327,11 @@ fun AddEditHabitScreen(
|
|||||||
if (selectedActivityName.isBlank()) { nameError = true; return@Button }
|
if (selectedActivityName.isBlank()) { nameError = true; return@Button }
|
||||||
val freq = targetFrequency.toIntOrNull() ?: 7
|
val freq = targetFrequency.toIntOrNull() ?: 7
|
||||||
|
|
||||||
if (isEditing) {
|
if (existingHabit != null) {
|
||||||
viewModel.updateHabit(
|
viewModel.updateHabit(
|
||||||
existingHabit!!.copy(
|
existingHabit.copy(
|
||||||
name = selectedActivityName.trim(),
|
name = selectedActivityName.trim(),
|
||||||
details = details.trim(),
|
details = details.trim(),
|
||||||
activityType = selectedActivityName.trim(),
|
|
||||||
targetFrequency = freq,
|
targetFrequency = freq,
|
||||||
reminderEnabled = reminderEnabled,
|
reminderEnabled = reminderEnabled,
|
||||||
reminderHour = reminderHour,
|
reminderHour = reminderHour,
|
||||||
@@ -344,7 +343,6 @@ fun AddEditHabitScreen(
|
|||||||
viewModel.addHabit(
|
viewModel.addHabit(
|
||||||
name = selectedActivityName.trim(),
|
name = selectedActivityName.trim(),
|
||||||
details = details.trim(),
|
details = details.trim(),
|
||||||
activityType = selectedActivityName.trim(),
|
|
||||||
targetFrequency = freq,
|
targetFrequency = freq,
|
||||||
reminderEnabled = reminderEnabled,
|
reminderEnabled = reminderEnabled,
|
||||||
reminderHour = reminderHour,
|
reminderHour = reminderHour,
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ fun CalendarScreen(
|
|||||||
val dayCompletionMap = remember(monthLogs) {
|
val dayCompletionMap = remember(monthLogs) {
|
||||||
val map = mutableMapOf<Long, MutableSet<Int>>() // dayMillis -> set of habitIds
|
val map = mutableMapOf<Long, MutableSet<Int>>() // dayMillis -> set of habitIds
|
||||||
for (log in monthLogs) {
|
for (log in monthLogs) {
|
||||||
val dayMillis = normaliseDay(log.date)
|
val dayMillis = HabitViewModel.startOfDay(log.date)
|
||||||
map.getOrPut(dayMillis) { mutableSetOf() }.add(log.habitId)
|
map.getOrPut(dayMillis) { mutableSetOf() }.add(log.habitId)
|
||||||
}
|
}
|
||||||
map
|
map
|
||||||
@@ -173,7 +173,7 @@ fun CalendarScreen(
|
|||||||
dayCal.set(Calendar.MILLISECOND, 0)
|
dayCal.set(Calendar.MILLISECOND, 0)
|
||||||
val dayMillis = dayCal.timeInMillis
|
val dayMillis = dayCal.timeInMillis
|
||||||
val count = dayCompletionMap[dayMillis]?.size ?: 0
|
val count = dayCompletionMap[dayMillis]?.size ?: 0
|
||||||
val today = isToday(dayMillis)
|
val today = dayMillis == HabitViewModel.todayMillis()
|
||||||
val intensity = if (totalActive > 0) (count.toFloat() / totalActive).coerceIn(0f, 1f) else 0f
|
val intensity = if (totalActive > 0) (count.toFloat() / totalActive).coerceIn(0f, 1f) else 0f
|
||||||
|
|
||||||
Box(
|
Box(
|
||||||
@@ -312,16 +312,3 @@ private fun StreakCard(habit: Habit, streak: Int, onClick: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun normaliseDay(millis: Long): Long {
|
|
||||||
val c = Calendar.getInstance(); c.timeInMillis = millis
|
|
||||||
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
|
|
||||||
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
|
|
||||||
return c.timeInMillis
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun isToday(millis: Long): Boolean {
|
|
||||||
val todayCal = Calendar.getInstance()
|
|
||||||
todayCal.set(Calendar.HOUR_OF_DAY, 0); todayCal.set(Calendar.MINUTE, 0)
|
|
||||||
todayCal.set(Calendar.SECOND, 0); todayCal.set(Calendar.MILLISECOND, 0)
|
|
||||||
return millis == todayCal.timeInMillis
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,6 @@ import androidx.compose.ui.text.font.FontWeight
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
|
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Calendar
|
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
@@ -84,7 +83,7 @@ fun HabitDetailScreen(
|
|||||||
elevation = CardDefaults.cardElevation(2.dp)
|
elevation = CardDefaults.cardElevation(2.dp)
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.padding(16.dp)) {
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
Text(h.activityType, style = MaterialTheme.typography.labelLarge,
|
Text(h.name, style = MaterialTheme.typography.labelLarge,
|
||||||
color = MaterialTheme.colorScheme.primary)
|
color = MaterialTheme.colorScheme.primary)
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
Text("Started: ${fmt.format(Date(h.startDate))}",
|
Text("Started: ${fmt.format(Date(h.startDate))}",
|
||||||
@@ -141,8 +140,8 @@ fun HabitDetailScreen(
|
|||||||
// Last 14 days
|
// Last 14 days
|
||||||
Text("Last 14 Days", style = MaterialTheme.typography.titleMedium,
|
Text("Last 14 Days", style = MaterialTheme.typography.titleMedium,
|
||||||
fontWeight = FontWeight.SemiBold)
|
fontWeight = FontWeight.SemiBold)
|
||||||
val logDates = logs.filter { it.completed }.map { normalise(it.date) }.toSet()
|
val logDates = logs.filter { it.completed }.map { HabitViewModel.startOfDay(it.date) }.toSet()
|
||||||
val today = todayMillis()
|
val today = HabitViewModel.todayMillis()
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth(),
|
modifier = Modifier.fillMaxWidth(),
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
horizontalArrangement = Arrangement.spacedBy(4.dp)
|
||||||
@@ -212,16 +211,3 @@ private fun StatCard(title: String, value: String, modifier: Modifier = Modifier
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun normalise(millis: Long): Long {
|
|
||||||
val c = Calendar.getInstance(); c.timeInMillis = millis
|
|
||||||
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
|
|
||||||
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
|
|
||||||
return c.timeInMillis
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun todayMillis(): Long {
|
|
||||||
val c = Calendar.getInstance()
|
|
||||||
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
|
|
||||||
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
|
|
||||||
return c.timeInMillis
|
|
||||||
}
|
|
||||||
@@ -22,7 +22,6 @@ import androidx.compose.ui.Modifier
|
|||||||
import androidx.compose.ui.text.font.FontWeight
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.example.madwellbeingapp.data.model.Habit
|
import com.example.madwellbeingapp.data.model.Habit
|
||||||
import com.example.madwellbeingapp.ui.viewmodel.HabitViewModel
|
|
||||||
|
|
||||||
/** Standard header bar with a back button and a title. */
|
/** Standard header bar with a back button and a title. */
|
||||||
@Composable
|
@Composable
|
||||||
@@ -69,7 +68,6 @@ fun ScreenHeader(
|
|||||||
@Composable
|
@Composable
|
||||||
fun HabitCard(
|
fun HabitCard(
|
||||||
habit: Habit,
|
habit: Habit,
|
||||||
viewModel: HabitViewModel,
|
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
circleColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surfaceVariant,
|
circleColor: androidx.compose.ui.graphics.Color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
circleText: String = "",
|
circleText: String = "",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.example.madwellbeingapp.ui.viewmodel
|
package com.example.madwellbeingapp.ui.viewmodel
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import android.util.Log
|
||||||
import androidx.lifecycle.AndroidViewModel
|
import androidx.lifecycle.AndroidViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
import com.example.madwellbeingapp.HabitApp
|
import com.example.madwellbeingapp.HabitApp
|
||||||
@@ -22,89 +23,71 @@ import kotlinx.coroutines.flow.stateIn
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
|
|
||||||
|
private const val TAG = "HabitViewModel"
|
||||||
|
private const val DAY_MS = 86_400_000L
|
||||||
|
|
||||||
class HabitViewModel(application: Application) : AndroidViewModel(application) {
|
class HabitViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
|
|
||||||
private val repository: HabitRepository =
|
private val repository: HabitRepository =
|
||||||
(application as HabitApp).repository
|
(application as HabitApp).repository
|
||||||
|
|
||||||
|
// ── Text formatting helpers (static) ────────────────────
|
||||||
companion object {
|
companion object {
|
||||||
/**
|
/** Activity name → FULL CAPS. "gym" → "GYM" */
|
||||||
* Formats the activity name: FULL CAPS for the main name.
|
fun formatName(input: String): String = input.trim().uppercase()
|
||||||
* e.g. "gym" → "GYM", "running" → "RUNNING"
|
|
||||||
*/
|
|
||||||
fun formatName(input: String): String {
|
|
||||||
return input.trim().uppercase()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** Detail text → first char upper, rest lower. "LEGS" → "Legs" */
|
||||||
* Formats the details/type text: first character uppercase, rest lowercase.
|
|
||||||
* e.g. "LEGS" → "Legs", "upper body" → "Upper body"
|
|
||||||
*/
|
|
||||||
fun formatDetails(input: String): String {
|
fun formatDetails(input: String): String {
|
||||||
val trimmed = input.trim()
|
val t = input.trim()
|
||||||
if (trimmed.isBlank()) return trimmed
|
if (t.isBlank()) return t
|
||||||
return trimmed[0].uppercaseChar() + trimmed.substring(1).lowercase()
|
return t[0].uppercaseChar() + t.substring(1).lowercase()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Normalise epoch millis to the start-of-day (00:00:00.000). */
|
||||||
* Legacy helper – kept for activity type names which use title-case.
|
fun startOfDay(millis: Long): Long {
|
||||||
* Converts text so first character is uppercase, rest lowercase.
|
val c = Calendar.getInstance()
|
||||||
*/
|
c.timeInMillis = millis
|
||||||
fun toTitleCase(input: String): String {
|
c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0)
|
||||||
return formatDetails(input)
|
c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0)
|
||||||
|
return c.timeInMillis
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Today at 00:00:00.000. */
|
||||||
|
fun todayMillis(): Long = startOfDay(System.currentTimeMillis())
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Activity Types (user-created, stored in Room) ───────
|
// ── Activity Types ──────────────────────────────────────
|
||||||
val allActivityTypes: StateFlow<List<ActivityType>> = repository.allActivityTypes
|
val allActivityTypes: StateFlow<List<ActivityType>> = repository.allActivityTypes
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
/**
|
|
||||||
* Adds a new activity type. [onResult] returns true on success, false if duplicate.
|
|
||||||
*/
|
|
||||||
fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) {
|
fun addActivityType(name: String, onResult: (Boolean) -> Unit = {}) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val formatted = formatName(name.trim())
|
val formatted = formatName(name)
|
||||||
if (formatted.isBlank()) {
|
if (formatted.isBlank()) { onResult(false); return@launch }
|
||||||
onResult(false)
|
if (repository.findActivityTypeByName(formatted) != null) {
|
||||||
return@launch
|
onResult(false); return@launch
|
||||||
}
|
|
||||||
val existing = repository.findActivityTypeByName(formatted)
|
|
||||||
if (existing != null) {
|
|
||||||
onResult(false)
|
|
||||||
return@launch
|
|
||||||
}
|
}
|
||||||
repository.addActivityType(ActivityType(name = formatted))
|
repository.addActivityType(ActivityType(name = formatted))
|
||||||
|
Log.d(TAG, "Activity type created: $formatted")
|
||||||
onResult(true)
|
onResult(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ── All habits ──────────────────────────────────────────
|
// ── All habits ──────────────────────────────────────────
|
||||||
val allHabits: StateFlow<List<Habit>> = repository.allHabits
|
val allHabits: StateFlow<List<Habit>> = repository.allHabits
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
// ── Today's logs ────────────────────────────────────────
|
// ── Today's logs ────────────────────────────────────────
|
||||||
private val todayStart: Long
|
private val todayStart: Long get() = todayMillis()
|
||||||
get() {
|
|
||||||
val cal = Calendar.getInstance()
|
|
||||||
cal.set(Calendar.HOUR_OF_DAY, 0)
|
|
||||||
cal.set(Calendar.MINUTE, 0)
|
|
||||||
cal.set(Calendar.SECOND, 0)
|
|
||||||
cal.set(Calendar.MILLISECOND, 0)
|
|
||||||
return cal.timeInMillis
|
|
||||||
}
|
|
||||||
|
|
||||||
val todayLogs: StateFlow<List<HabitLog>> = repository.getLogsForDate(todayStart)
|
val todayLogs: StateFlow<List<HabitLog>> = repository.getLogsForDate(todayStart)
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
/**
|
/** Active habits not yet completed today. */
|
||||||
* Active habits still to-do today.
|
|
||||||
*/
|
|
||||||
val activeHabitsNotCompletedToday: StateFlow<List<Habit>> =
|
val activeHabitsNotCompletedToday: StateFlow<List<Habit>> =
|
||||||
combine(allHabits, todayLogs) { habits, logs ->
|
combine(allHabits, todayLogs) { habits, logs ->
|
||||||
val completedIds = logs.filter { it.completed }.map { it.habitId }.toSet()
|
val doneIds = logs.filter { it.completed }.map { it.habitId }.toSet()
|
||||||
habits.filter { it.isActive && !completedIds.contains(it.id) }
|
habits.filter { it.isActive && it.id !in doneIds }
|
||||||
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
// ── Selected habit detail ───────────────────────────────
|
// ── Selected habit detail ───────────────────────────────
|
||||||
@@ -112,19 +95,15 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
val selectedHabit: StateFlow<Habit?> = _selectedHabitId
|
val selectedHabit: StateFlow<Habit?> = _selectedHabitId
|
||||||
.flatMapLatest { id ->
|
.flatMapLatest { id -> if (id != null) repository.getHabitById(id) else flowOf(null) }
|
||||||
if (id != null) repository.getHabitById(id) else flowOf(null)
|
|
||||||
}
|
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
val selectedHabitLogs: StateFlow<List<HabitLog>> = _selectedHabitId
|
val selectedHabitLogs: StateFlow<List<HabitLog>> = _selectedHabitId
|
||||||
.flatMapLatest { id ->
|
.flatMapLatest { id -> if (id != null) repository.getLogsForHabit(id) else flowOf(emptyList()) }
|
||||||
if (id != null) repository.getLogsForHabit(id) else flowOf(emptyList())
|
|
||||||
}
|
|
||||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||||
|
|
||||||
// ── Streak for selected habit ───────────────────────────
|
// ── Streaks ─────────────────────────────────────────────
|
||||||
private val _currentStreak = MutableStateFlow(0)
|
private val _currentStreak = MutableStateFlow(0)
|
||||||
val currentStreak: StateFlow<Int> = _currentStreak.asStateFlow()
|
val currentStreak: StateFlow<Int> = _currentStreak.asStateFlow()
|
||||||
|
|
||||||
@@ -134,62 +113,56 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
fun selectHabit(habitId: Int) {
|
fun selectHabit(habitId: Int) {
|
||||||
_selectedHabitId.value = habitId
|
_selectedHabitId.value = habitId
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val (current, longest) = computeStreakPair(habitId)
|
val (cur, lng) = computeStreaks(habitId)
|
||||||
_currentStreak.value = current
|
_currentStreak.value = cur
|
||||||
_longestStreak.value = longest
|
_longestStreak.value = lng
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Returns (currentStreak, longestStreak) for a habit. */
|
suspend fun computeStreakForHabit(habitId: Int): Int = computeStreaks(habitId).first
|
||||||
private suspend fun computeStreakPair(habitId: Int): Pair<Int, Int> {
|
|
||||||
|
private suspend fun computeStreaks(habitId: Int): Pair<Int, Int> {
|
||||||
val logs = repository.getCompletedLogsDesc(habitId)
|
val logs = repository.getCompletedLogsDesc(habitId)
|
||||||
if (logs.isEmpty()) return 0 to 0
|
if (logs.isEmpty()) return 0 to 0
|
||||||
val days = logs.map { normaliseToDay(it.date) }.distinct().sortedDescending()
|
val days = logs.map { startOfDay(it.date) }.distinct().sortedDescending()
|
||||||
|
|
||||||
// Current streak
|
// Current streak
|
||||||
var current = 0
|
var current = 0
|
||||||
val today = todayStart
|
val today = todayStart
|
||||||
if (days.first() == today || days.first() == today - 86_400_000L) {
|
if (days.first() == today || days.first() == today - DAY_MS) {
|
||||||
var expected = days.first()
|
var expected = days.first()
|
||||||
for (day in days) {
|
for (day in days) {
|
||||||
if (day == expected) { current++; expected -= 86_400_000L } else break
|
if (day == expected) { current++; expected -= DAY_MS } else break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Longest streak
|
// Longest streak
|
||||||
var longest = 1; var streak = 1
|
var longest = 1; var run = 1
|
||||||
for (i in 1 until days.size) {
|
for (i in 1 until days.size) {
|
||||||
if (days[i] == days[i - 1] - 86_400_000L) {
|
if (days[i] == days[i - 1] - DAY_MS) { run++; if (run > longest) longest = run }
|
||||||
streak++; if (streak > longest) longest = streak
|
else run = 1
|
||||||
} else streak = 1
|
|
||||||
}
|
}
|
||||||
return current to longest
|
return current to longest
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Public accessor for calendar/other screens needing just current streak. */
|
// ── Weekly progress ─────────────────────────────────────
|
||||||
suspend fun computeStreakForHabit(habitId: Int): Int = computeStreakPair(habitId).first
|
fun weeklyProgress(habitId: Int): Flow<Float> =
|
||||||
|
repository.getLogsForHabit(habitId).map { logs ->
|
||||||
// ── Weekly progress for a habit ─────────────────────────
|
val weekAgo = todayStart - 6 * DAY_MS
|
||||||
fun weeklyProgress(habitId: Int): Flow<Float> {
|
val count = logs.count { it.completed && it.date >= weekAgo }
|
||||||
return repository.getLogsForHabit(habitId).map { logs ->
|
val target = repository.getHabitByIdOnce(habitId)?.targetFrequency ?: 7
|
||||||
val weekAgo = todayStart - 6 * 86_400_000L
|
(count.toFloat() / target).coerceIn(0f, 1f)
|
||||||
val thisWeekCount = logs.count { it.completed && it.date >= weekAgo }
|
|
||||||
val habit = repository.getHabitByIdOnce(habitId)
|
|
||||||
val target = habit?.targetFrequency ?: 7
|
|
||||||
(thisWeekCount.toFloat() / target).coerceIn(0f, 1f)
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// ── Duplicate check ─────────────────────────────────────
|
// ── Duplicate check ─────────────────────────────────────
|
||||||
suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean {
|
private suspend fun isDuplicate(name: String, details: String, excludeId: Int? = null): Boolean {
|
||||||
val existing = repository.findDuplicate(name.trim(), details.trim())
|
val existing = repository.findDuplicate(name, details)
|
||||||
return existing != null && existing.id != excludeId
|
return existing != null && existing.id != excludeId
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── CRUD operations ─────────────────────────────────────
|
// ── CRUD ────────────────────────────────────────────────
|
||||||
|
|
||||||
fun addHabit(
|
fun addHabit(
|
||||||
name: String,
|
name: String,
|
||||||
details: String = "",
|
details: String = "",
|
||||||
activityType: String = "",
|
|
||||||
targetFrequency: Int,
|
targetFrequency: Int,
|
||||||
reminderEnabled: Boolean = true,
|
reminderEnabled: Boolean = true,
|
||||||
reminderHour: Int = 9,
|
reminderHour: Int = 9,
|
||||||
@@ -197,77 +170,58 @@ class HabitViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
onResult: (Boolean) -> Unit = {}
|
onResult: (Boolean) -> Unit = {}
|
||||||
) {
|
) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val formattedName = formatName(name.trim())
|
val fmtName = formatName(name)
|
||||||
val formattedDetails = formatDetails(details.trim())
|
val fmtDetails = formatDetails(details)
|
||||||
val formattedType = formatName(activityType.trim())
|
|
||||||
|
|
||||||
if (isDuplicate(formattedName, formattedDetails)) {
|
if (isDuplicate(fmtName, fmtDetails)) { onResult(false); return@launch }
|
||||||
onResult(false)
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
|
|
||||||
val habit = Habit(
|
repository.upsertHabit(
|
||||||
name = formattedName,
|
Habit(
|
||||||
details = formattedDetails,
|
name = fmtName, details = fmtDetails,
|
||||||
activityType = formattedType,
|
startDate = System.currentTimeMillis(),
|
||||||
startDate = System.currentTimeMillis(),
|
targetFrequency = targetFrequency,
|
||||||
targetFrequency = targetFrequency,
|
reminderEnabled = reminderEnabled,
|
||||||
reminderEnabled = reminderEnabled,
|
reminderHour = reminderHour, reminderMinute = reminderMinute
|
||||||
reminderHour = reminderHour,
|
)
|
||||||
reminderMinute = reminderMinute
|
|
||||||
)
|
)
|
||||||
repository.insertHabit(habit)
|
Log.d(TAG, "Habit created: $fmtName($fmtDetails)")
|
||||||
onResult(true)
|
onResult(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun updateHabit(habit: Habit) {
|
fun updateHabit(habit: Habit) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val updated = habit.copy(
|
repository.upsertHabit(
|
||||||
name = formatName(habit.name.trim()),
|
habit.copy(
|
||||||
details = formatDetails(habit.details.trim()),
|
name = formatName(habit.name),
|
||||||
activityType = formatName(habit.activityType.trim())
|
details = formatDetails(habit.details)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
repository.updateHabit(updated)
|
Log.d(TAG, "Habit updated: ${habit.displayName}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun disableHabit(habit: Habit) {
|
fun disableHabit(habit: Habit) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch { repository.upsertHabit(habit.copy(isActive = false)) }
|
||||||
val updated = habit.copy(isActive = false)
|
|
||||||
repository.updateHabit(updated)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun enableHabit(habit: Habit) {
|
fun enableHabit(habit: Habit) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch { repository.upsertHabit(habit.copy(isActive = true)) }
|
||||||
val updated = habit.copy(isActive = true)
|
|
||||||
repository.updateHabit(updated)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Daily logging ───────────────────────────────────────
|
// ── Daily logging ───────────────────────────────────────
|
||||||
fun toggleTodayLog(habitId: Int) {
|
fun toggleTodayLog(habitId: Int) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
repository.toggleLog(habitId, todayStart)
|
repository.toggleLog(habitId, todayStart)
|
||||||
|
Log.d(TAG, "Toggled today's log for habit id=$habitId")
|
||||||
if (_selectedHabitId.value == habitId) {
|
if (_selectedHabitId.value == habitId) {
|
||||||
val (c, l) = computeStreakPair(habitId)
|
val (c, l) = computeStreaks(habitId)
|
||||||
_currentStreak.value = c
|
_currentStreak.value = c; _longestStreak.value = l
|
||||||
_longestStreak.value = l
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Helpers ──────────────────────────────────────────────
|
|
||||||
private fun normaliseToDay(millis: Long): Long {
|
|
||||||
val cal = Calendar.getInstance()
|
|
||||||
cal.timeInMillis = millis
|
|
||||||
cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0)
|
|
||||||
cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0)
|
|
||||||
return cal.timeInMillis
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Calendar support ────────────────────────────────────
|
// ── Calendar support ────────────────────────────────────
|
||||||
fun getLogsBetween(startDate: Long, endDate: Long): Flow<List<HabitLog>> =
|
fun getLogsBetween(start: Long, end: Long): Flow<List<HabitLog>> =
|
||||||
repository.getLogsBetween(startDate, endDate)
|
repository.getLogsBetween(start, end)
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user