├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── ic_launcher_background.xml
│ │ │ │ ├── themes.xml
│ │ │ │ └── colors.xml
│ │ │ ├── drawable
│ │ │ │ ├── add_icon.png
│ │ │ │ ├── ic_google.png
│ │ │ │ ├── google_logo.png
│ │ │ │ ├── timer_play.png
│ │ │ │ ├── timer_stop.png
│ │ │ │ ├── pause.xml
│ │ │ │ ├── habit_icon.xml
│ │ │ │ ├── timer_icon.xml
│ │ │ │ ├── timer.xml
│ │ │ │ ├── checklist_icon.xml
│ │ │ │ ├── visible.xml
│ │ │ │ └── no_visible.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ └── ic_launcher_round.webp
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.webp
│ │ │ │ ├── ic_launcher_round.webp
│ │ │ │ └── ic_launcher_foreground.webp
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ └── xml
│ │ │ │ ├── backup_rules.xml
│ │ │ │ └── data_extraction_rules.xml
│ │ ├── ic_launcher-playstore.png
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── mundocode
│ │ │ │ └── pomodoro
│ │ │ │ ├── data
│ │ │ │ ├── pointsDB
│ │ │ │ │ ├── UserPoints.kt
│ │ │ │ │ ├── PointsDatabase.kt
│ │ │ │ │ ├── PointsDao.kt
│ │ │ │ │ ├── PointsRepository.kt
│ │ │ │ │ └── di
│ │ │ │ │ │ └── PointsModule.kt
│ │ │ │ ├── habitsDB
│ │ │ │ │ ├── HabitsDatabase.kt
│ │ │ │ │ ├── HabitsEntity.kt
│ │ │ │ │ ├── domain
│ │ │ │ │ │ ├── AddTaskUserCase.kt
│ │ │ │ │ │ ├── GetTasksUserCase.kt
│ │ │ │ │ │ ├── DeleteTaskUseCase.kt
│ │ │ │ │ │ └── UpdateTaskUseCase.kt
│ │ │ │ │ ├── di
│ │ │ │ │ │ └── DatabaseModule.kt
│ │ │ │ │ ├── HabitsDao.kt
│ │ │ │ │ └── HabitsRepository.kt
│ │ │ │ ├── sessionDb
│ │ │ │ │ ├── SessionDatabase.kt
│ │ │ │ │ ├── SessionEntity.kt
│ │ │ │ │ ├── SessionDao.kt
│ │ │ │ │ └── DatabaseModule.kt
│ │ │ │ └── storeDB
│ │ │ │ │ ├── PurchasedItem.kt
│ │ │ │ │ └── PurchasedItemsDao.kt
│ │ │ │ ├── PomodoroApp.kt
│ │ │ │ ├── model
│ │ │ │ └── local
│ │ │ │ │ ├── StoreItem.kt
│ │ │ │ │ └── Timer.kt
│ │ │ │ ├── ui
│ │ │ │ ├── screens
│ │ │ │ │ ├── habits
│ │ │ │ │ │ ├── model
│ │ │ │ │ │ │ └── HabitsModel.kt
│ │ │ │ │ │ ├── HabitsUIState.kt
│ │ │ │ │ │ ├── HabitsViewModel.kt
│ │ │ │ │ │ └── HabitsScreen.kt
│ │ │ │ │ ├── timer
│ │ │ │ │ │ ├── TimerState.kt
│ │ │ │ │ │ ├── ReminderReceiver.kt
│ │ │ │ │ │ ├── TimerViewModel.kt
│ │ │ │ │ │ └── TimerScreen.kt
│ │ │ │ │ ├── SharedPointsViewModel.kt
│ │ │ │ │ ├── setupSessionScreen
│ │ │ │ │ │ ├── SetupSessionViewModel.kt
│ │ │ │ │ │ └── SetupSessionScreen.kt
│ │ │ │ │ ├── points
│ │ │ │ │ │ ├── PointsViewModel.kt
│ │ │ │ │ │ ├── StoreViewModel.kt
│ │ │ │ │ │ └── StoreScreen.kt
│ │ │ │ │ ├── splashScreen
│ │ │ │ │ │ └── SplashScreen.kt
│ │ │ │ │ ├── loginScreen
│ │ │ │ │ │ ├── LoginViewModel.kt
│ │ │ │ │ │ ├── RegisterScreen.kt
│ │ │ │ │ │ └── LoginScreen.kt
│ │ │ │ │ ├── settings
│ │ │ │ │ │ └── SettingsScreen.kt
│ │ │ │ │ ├── homeScreen
│ │ │ │ │ │ └── HomeViewModel.kt
│ │ │ │ │ └── taskScreen
│ │ │ │ │ │ └── TaskScreen.kt
│ │ │ │ ├── theme
│ │ │ │ │ ├── ThemeModule.kt
│ │ │ │ │ ├── Type.kt
│ │ │ │ │ ├── ThemePreferences.kt
│ │ │ │ │ ├── ThemeViewModel.kt
│ │ │ │ │ ├── Theme.kt
│ │ │ │ │ └── Color.kt
│ │ │ │ └── components
│ │ │ │ │ ├── SwipeBox.kt
│ │ │ │ │ ├── CustomTopAppBar.kt
│ │ │ │ │ └── DialogPopUp.kt
│ │ │ │ ├── di
│ │ │ │ ├── ApplicationModule.kt
│ │ │ │ └── FirebaseModule.kt
│ │ │ │ ├── core
│ │ │ │ └── navigation
│ │ │ │ │ ├── Destinations.kt
│ │ │ │ │ └── NavigationRoot.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── mundocode
│ │ │ └── pomodoro
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── mundocode
│ │ └── pomodoro
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle.kts
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── settings.gradle.kts
├── LICENSE
├── .editorconfig
├── gradle.properties
├── README.md
├── gradlew.bat
├── .gitignore
└── gradlew
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Pomodoro
3 |
4 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/ic_launcher-playstore.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/ic_launcher-playstore.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/add_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/drawable/add_icon.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_google.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/drawable/ic_google.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/google_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/drawable/google_logo.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/timer_play.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/drawable/timer_play.png
--------------------------------------------------------------------------------
/app/src/main/res/drawable/timer_stop.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/drawable/timer_stop.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juanppdev/Proyecto_1_Pomodoro/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp
--------------------------------------------------------------------------------
/app/src/main/res/values/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #25312D
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jan 05 12:17:23 CET 2025
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/pointsDB/UserPoints.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.pointsDB
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 |
6 | @Entity(tableName = "user_points")
7 | data class UserPoints(@PrimaryKey val userId: String, val points: Int)
8 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/PomodoroApp.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro
2 |
3 | import android.app.Application
4 | import dagger.hilt.android.HiltAndroidApp
5 |
6 | @HiltAndroidApp
7 | class PomodoroApp : Application() {
8 | override fun onCreate() {
9 | super.onCreate()
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/HabitsDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 |
6 | @Database(entities = [HabitsEntity::class], version = 1) // ✅ Incrementa la versión
7 | abstract class HabitsDatabase : RoomDatabase() {
8 | abstract fun habitsDao(): HabitsDao
9 | }
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/sessionDb/SessionDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.sessionDb
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 |
6 | @Database(entities = [SessionEntity::class], version = 1, exportSchema = false)
7 | abstract class SessionDatabase : RoomDatabase() {
8 | abstract fun sessionDao(): SessionDao
9 | }
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/HabitsEntity.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 |
6 | @Entity
7 | data class HabitsEntity(
8 | @PrimaryKey(autoGenerate = true) val id: Int = 0, // ✅ Auto-generar IDs únicos en Room
9 | val title: String,
10 | val description: String,
11 | )
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/model/local/StoreItem.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.model.local
2 |
3 | import kotlinx.serialization.Serializable
4 |
5 | @Serializable
6 | data class StoreItem(val id: Int, val name: String, val price: Int, val description: String)
7 |
8 | @Serializable
9 | data class StoreTheme(val id: Int, val name: String, val price: Int, val description: String)
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/habits/model/HabitsModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.habits.model
2 |
3 | data class HabitsModel(
4 | val id: Int = System.currentTimeMillis().hashCode(),
5 | val title: String = "",
6 | val description: String = "",
7 | ) {
8 | // Firestore necesita un constructor vacío
9 | constructor() : this(0, "", "")
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/habits/HabitsUIState.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.habits
2 |
3 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
4 |
5 | sealed interface HabitsUIState {
6 |
7 | object Loading : HabitsUIState
8 | data class Error(val throwable: Throwable) : HabitsUIState
9 | data class Success(val tasks: List) : HabitsUIState
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/timer/TimerState.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.timer
2 |
3 | data class TimerState(
4 | val sessionName: String = "",
5 | val mode: String = "",
6 | val remainingTime: Long = 25 * 60 * 1000L,
7 | val workDuration: Long = 25 * 60 * 1000L,
8 | val breakDuration: Long = 5 * 60 * 1000L,
9 | val isRunning: Boolean = false,
10 | val isWorking: Boolean = true,
11 | )
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/mundocode/pomodoro/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro
2 |
3 | import junit.framework.TestCase.assertEquals
4 | import org.junit.Test
5 |
6 | /**
7 | * Example local unit test, which will execute on the development machine (host).
8 | *
9 | * See [testing documentation](http://d.android.com/tools/testing).
10 | */
11 | class ExampleUnitTest {
12 | @Test
13 | fun addition_isCorrect() {
14 | assertEquals(4, 2 + 2)
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/pause.xml:
--------------------------------------------------------------------------------
1 |
6 |
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/domain/AddTaskUserCase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB.domain
2 |
3 | import com.mundocode.pomodoro.data.habitsDB.HabitsRepository
4 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
5 | import javax.inject.Inject
6 |
7 | class AddTaskUserCase @Inject constructor(private val habitRepository: HabitsRepository) {
8 |
9 | suspend operator fun invoke(habitModel: HabitsModel) {
10 | habitRepository.addHabit(habitModel)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/domain/GetTasksUserCase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB.domain
2 |
3 | import com.mundocode.pomodoro.data.habitsDB.HabitsRepository
4 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
5 | import kotlinx.coroutines.flow.Flow
6 | import javax.inject.Inject
7 |
8 | class GetTasksUserCase @Inject constructor(private val habitRepository: HabitsRepository) {
9 |
10 | operator fun invoke(): Flow> = habitRepository.habits
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/domain/DeleteTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB.domain
2 |
3 | import com.mundocode.pomodoro.data.habitsDB.HabitsRepository
4 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
5 | import javax.inject.Inject
6 |
7 | class DeleteTaskUseCase @Inject constructor(private val habitsRepository: HabitsRepository) {
8 |
9 | suspend operator fun invoke(habitModel: HabitsModel) {
10 | habitsRepository.deleteHabit(habitModel)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/domain/UpdateTaskUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB.domain
2 |
3 | import com.mundocode.pomodoro.data.habitsDB.HabitsRepository
4 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
5 | import javax.inject.Inject
6 |
7 | class UpdateTaskUseCase @Inject constructor(private val habitRepository: HabitsRepository) {
8 |
9 | suspend operator fun invoke(habitModel: HabitsModel) {
10 | habitRepository.updateHabit(habitModel)
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/sessionDb/SessionEntity.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.sessionDb
2 |
3 | import androidx.room.Entity
4 | import androidx.room.PrimaryKey
5 |
6 | @Entity(tableName = "sessions")
7 | data class SessionEntity(
8 | @PrimaryKey(autoGenerate = true) val id: Int = 0, // Este es opcional y debe ser el único Int
9 | val type: String, // "Trabajo" o "Descanso"
10 | val duration: String, // Duración en formato mm:ss
11 | val date: String, // Fecha en formato yyyy-MM-dd HH:mm:ss
12 | )
13 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/habit_icon.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/backup_rules.xml:
--------------------------------------------------------------------------------
1 |
8 |
9 |
13 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/di/ApplicationModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.di
2 |
3 | import android.content.Context
4 | import dagger.Module
5 | import dagger.Provides
6 | import dagger.hilt.InstallIn
7 | import dagger.hilt.android.qualifiers.ApplicationContext
8 | import dagger.hilt.components.SingletonComponent
9 | import javax.inject.Singleton
10 |
11 | @Module
12 | @InstallIn(SingletonComponent::class)
13 | object ApplicationModule {
14 |
15 | @Provides
16 | @Singleton
17 | fun provideContext(@ApplicationContext context: Context): Context = context
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/model/local/Timer.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.model.local
2 |
3 | import kotlinx.serialization.encodeToString
4 | import kotlinx.serialization.json.Json
5 | import kotlinx.serialization.Serializable
6 |
7 | @Serializable
8 | data class Timer(val sessionName: String, val mode: String, val timer: String, val pause: String) {
9 | fun toJson(): String = Json.encodeToString(this)
10 |
11 | companion object {
12 | fun fromJson(json: String): Timer = Json.decodeFromString(json) // ✅ Función para convertir JSON a Timer
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/pointsDB/PointsDatabase.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.pointsDB
2 |
3 | import androidx.room.Database
4 | import androidx.room.RoomDatabase
5 | import com.mundocode.pomodoro.data.storeDB.PurchasedItem
6 | import com.mundocode.pomodoro.data.storeDB.PurchasedItemsDao
7 | import com.mundocode.pomodoro.data.storeDB.PurchasedTheme
8 |
9 | @Database(entities = [UserPoints::class, PurchasedItem::class, PurchasedTheme::class], version = 2)
10 | abstract class PointsDatabase : RoomDatabase() {
11 | abstract fun pointsDao(): PointsDao
12 | abstract fun purchasedItemsDao(): PurchasedItemsDao
13 | }
14 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/data_extraction_rules.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
12 |
13 |
19 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/ThemeModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import android.content.Context
4 | import com.mundocode.pomodoro.ui.theme.ThemePreferences
5 | import dagger.Module
6 | import dagger.Provides
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.android.qualifiers.ApplicationContext
9 | import dagger.hilt.components.SingletonComponent
10 | import javax.inject.Singleton
11 |
12 | @Module
13 | @InstallIn(SingletonComponent::class)
14 | object ThemeModule {
15 |
16 | @Provides
17 | @Singleton
18 | fun provideThemePreferences(@ApplicationContext context: Context): ThemePreferences = ThemePreferences(context)
19 | }
20 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | google {
4 | content {
5 | includeGroupByRegex("com\\.android.*")
6 | includeGroupByRegex("com\\.google.*")
7 | includeGroupByRegex("androidx.*")
8 | }
9 | }
10 | mavenCentral()
11 | gradlePluginPortal()
12 | }
13 | }
14 | dependencyResolutionManagement {
15 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
16 | repositories {
17 | google()
18 | mavenCentral()
19 | maven { url = uri("https://jitpack.io") }
20 | }
21 | }
22 |
23 | rootProject.name = "Pomodoro"
24 | include(":app")
25 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/timer_icon.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/timer.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/checklist_icon.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/visible.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/mundocode/pomodoro/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro
2 |
3 | import androidx.test.ext.junit.runners.AndroidJUnit4
4 | import androidx.test.platform.app.InstrumentationRegistry
5 | import junit.framework.TestCase.assertEquals
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | /**
10 | * Instrumented test, which will execute on an Android device.
11 | *
12 | * See [testing documentation](http://d.android.com/tools/testing).
13 | */
14 | @RunWith(AndroidJUnit4::class)
15 | class ExampleInstrumentedTest {
16 | @Test
17 | fun useAppContext() {
18 | // Context of the app under test.
19 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
20 | assertEquals("com.mundocode.pomodoro", appContext.packageName)
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/sessionDb/SessionDao.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.sessionDb
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Insert
5 | import androidx.room.OnConflictStrategy
6 | import androidx.room.Query
7 | import kotlinx.coroutines.flow.Flow
8 |
9 | @Dao
10 | interface SessionDao {
11 | @Query("SELECT * FROM sessions WHERE date BETWEEN :startDate AND :endDate")
12 | fun getSessionsBetweenDatesFlow(startDate: String, endDate: String): Flow>
13 |
14 | @Query("SELECT COUNT(*) FROM sessions WHERE type = 'Trabajo' AND date BETWEEN :startDate AND :endDate")
15 | fun getPomodoroCountBetweenDates(startDate: String, endDate: String): Flow
16 |
17 | @Insert(onConflict = OnConflictStrategy.REPLACE)
18 | suspend fun insertSession(session: SessionEntity)
19 | }
20 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/storeDB/PurchasedItem.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.storeDB
2 |
3 | import androidx.room.ColumnInfo
4 | import androidx.room.Entity
5 | import androidx.room.PrimaryKey
6 |
7 | @Entity(tableName = "purchased_items")
8 | data class PurchasedItem(
9 | @PrimaryKey(autoGenerate = true) val id: Int = 0,
10 | val userId: String,
11 | val itemName: String,
12 | val itemDescription: String,
13 | val price: Int,
14 | )
15 |
16 | @Entity(tableName = "purchased_themes")
17 | data class PurchasedTheme(
18 | @PrimaryKey(autoGenerate = true) val id: Int = 0,
19 | @ColumnInfo(name = "userId") val userId: String,
20 | @ColumnInfo(name = "themeName") val themeName: String,
21 | @ColumnInfo(name = "themeDescription") val themeDescription: String,
22 | @ColumnInfo(name = "price") val price: Int,
23 | )
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/sessionDb/DatabaseModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.sessionDb
2 |
3 | import android.content.Context
4 | import androidx.room.Room
5 | import dagger.Module
6 | import dagger.Provides
7 | import dagger.hilt.InstallIn
8 | import dagger.hilt.components.SingletonComponent
9 | import javax.inject.Singleton
10 |
11 | @Module
12 | @InstallIn(SingletonComponent::class)
13 | object DatabaseModule {
14 |
15 | @Provides
16 | @Singleton
17 | fun provideDatabase(@dagger.hilt.android.qualifiers.ApplicationContext appContext: Context): SessionDatabase =
18 | Room.databaseBuilder(
19 | appContext,
20 | SessionDatabase::class.java,
21 | "session_database",
22 | ).build()
23 |
24 | @Provides
25 | fun provideSessionDao(database: SessionDatabase): SessionDao = database.sessionDao()
26 | }
27 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/no_visible.xml:
--------------------------------------------------------------------------------
1 |
6 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/pointsDB/PointsDao.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.pointsDB
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Insert
5 | import androidx.room.OnConflictStrategy
6 | import androidx.room.Query
7 | import kotlinx.coroutines.flow.Flow
8 |
9 | @Dao
10 | interface PointsDao {
11 | @Query("SELECT * FROM user_points WHERE userId = :userId")
12 | fun getUserPoints(userId: String): Flow
13 |
14 | @Insert(onConflict = OnConflictStrategy.REPLACE)
15 | suspend fun insertOrUpdatePoints(userPoints: UserPoints)
16 |
17 | @Query("UPDATE user_points SET points = points + :points WHERE userId = :userId")
18 | suspend fun addPoints(userId: String, points: Int)
19 |
20 | @Query("UPDATE user_points SET points = points - :points WHERE userId = :userId AND points >= :points")
21 | suspend fun spendPoints(userId: String, points: Int)
22 | }
23 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
23 | -keep class com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel { *; }
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/di/DatabaseModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB.di
2 |
3 | import android.content.Context
4 | import androidx.room.Room
5 | import com.mundocode.pomodoro.data.habitsDB.HabitsDao
6 | import com.mundocode.pomodoro.data.habitsDB.HabitsDatabase
7 | import dagger.Module
8 | import dagger.Provides
9 | import dagger.hilt.InstallIn
10 | import dagger.hilt.android.qualifiers.ApplicationContext
11 | import dagger.hilt.components.SingletonComponent
12 | import javax.inject.Singleton
13 |
14 | @Module
15 | @InstallIn(SingletonComponent::class)
16 | class DatabaseModule {
17 |
18 | @Provides
19 | fun provideTaskDao(habitsDatabase: HabitsDatabase): HabitsDao = habitsDatabase.habitsDao()
20 |
21 | @Provides
22 | @Singleton
23 | fun provideTodoDatabase(@ApplicationContext appContext: Context): HabitsDatabase =
24 | Room.databaseBuilder(appContext, HabitsDatabase::class.java, "HabitsDatabase").build()
25 | }
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/HabitsDao.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Delete
5 | import androidx.room.Insert
6 | import androidx.room.OnConflictStrategy
7 | import androidx.room.Query
8 | import androidx.room.Update
9 | import kotlinx.coroutines.flow.Flow
10 |
11 | @Dao
12 | interface HabitsDao {
13 |
14 | @Query("SELECT * FROM HabitsEntity")
15 | fun getHabits(): Flow> // ✅ Asegurar que devuelve un Flow
16 |
17 | @Query("SELECT * FROM HabitsEntity WHERE id = :id LIMIT 1")
18 | suspend fun getHabitById(id: Int): HabitsEntity?
19 |
20 | @Insert(onConflict = OnConflictStrategy.REPLACE) // ✅ Evita duplicados reemplazando registros existentes
21 | suspend fun addHabit(habit: HabitsEntity)
22 |
23 | @Update
24 | suspend fun updateHabit(habit: HabitsEntity)
25 |
26 | @Delete
27 | suspend fun deleteHabit(habit: HabitsEntity)
28 |
29 | @Query("DELETE FROM HabitsEntity")
30 | suspend fun clearHabits()
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/storeDB/PurchasedItemsDao.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.storeDB
2 |
3 | import androidx.room.Dao
4 | import androidx.room.Insert
5 | import androidx.room.OnConflictStrategy
6 | import androidx.room.Query
7 | import kotlinx.coroutines.flow.Flow
8 |
9 | @Dao
10 | interface PurchasedItemsDao {
11 | @Query("SELECT * FROM purchased_items WHERE userId = :userId")
12 | fun getUserPurchasedItems(userId: String): Flow>
13 |
14 | @Query("SELECT * FROM purchased_themes WHERE userId = :userId")
15 | fun getUserPurchasedThemes(userId: String): Flow>
16 |
17 | @Query("SELECT COUNT(*) FROM purchased_themes WHERE userId = :userId")
18 | suspend fun countUserPurchasedThemes(userId: String): Int // ✅ Verifica si los temas realmente existen
19 |
20 | @Insert(onConflict = OnConflictStrategy.REPLACE)
21 | suspend fun insertPurchasedItem(item: PurchasedItem)
22 |
23 | @Insert(onConflict = OnConflictStrategy.REPLACE)
24 | suspend fun insertPurchasedTheme(item: PurchasedTheme)
25 | }
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2025 Juan Pablo Patino Lopez
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/core/navigation/Destinations.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.core.navigation
2 |
3 | import com.kiwi.navigationcompose.typed.Destination
4 | import com.mundocode.pomodoro.model.local.Timer
5 | import kotlinx.serialization.Contextual
6 | import kotlinx.serialization.Serializable
7 |
8 | sealed interface Destinations : Destination {
9 |
10 | @Serializable
11 | data object Splash : Destinations
12 |
13 | @Serializable
14 | data object Login : Destinations
15 |
16 | @Serializable
17 | data object Register : Destinations
18 |
19 | @Serializable
20 | data object HomeScreen : Destinations
21 |
22 | @Serializable
23 | data object SetupSessionScreen : Destinations
24 |
25 | @Serializable
26 | data class TimerScreen(@Contextual val timer: Timer) : Destinations
27 |
28 | @Serializable
29 | data object TaskScreen : Destinations
30 |
31 | @Serializable
32 | data object HabitsScreen : Destinations
33 |
34 | @Serializable
35 | data object StoreScreen : Destinations
36 |
37 | @Serializable
38 | data object SettingsScreen : Destinations
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/Type.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import androidx.compose.material3.Typography
4 | import androidx.compose.ui.text.TextStyle
5 | import androidx.compose.ui.text.font.FontFamily
6 | import androidx.compose.ui.text.font.FontWeight
7 | import androidx.compose.ui.unit.sp
8 |
9 | // Set of Material typography styles to start with
10 | val Typography = Typography(
11 | bodyLarge = TextStyle(
12 | fontFamily = FontFamily.Default,
13 | fontWeight = FontWeight.Normal,
14 | fontSize = 16.sp,
15 | lineHeight = 24.sp,
16 | letterSpacing = 0.5.sp,
17 | ),
18 | /* Other default text styles to override
19 | titleLarge = TextStyle(
20 | fontFamily = FontFamily.Default,
21 | fontWeight = FontWeight.Normal,
22 | fontSize = 22.sp,
23 | lineHeight = 28.sp,
24 | letterSpacing = 0.sp
25 | ),
26 | labelSmall = TextStyle(
27 | fontFamily = FontFamily.Default,
28 | fontWeight = FontWeight.Medium,
29 | fontSize = 11.sp,
30 | lineHeight = 16.sp,
31 | letterSpacing = 0.5.sp
32 | )
33 | */
34 | )
35 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/di/FirebaseModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.di
2 |
3 | import android.content.Context
4 | import androidx.credentials.CredentialManager
5 | import com.google.firebase.auth.FirebaseAuth
6 | import com.google.firebase.auth.ktx.auth
7 | import com.google.firebase.firestore.FirebaseFirestore
8 | import com.google.firebase.firestore.ktx.firestore
9 | import com.google.firebase.ktx.Firebase
10 | import dagger.Module
11 | import dagger.Provides
12 | import dagger.hilt.InstallIn
13 | import dagger.hilt.android.qualifiers.ApplicationContext
14 | import dagger.hilt.components.SingletonComponent
15 |
16 | @Module
17 | @InstallIn(SingletonComponent::class)
18 | object FirebaseModule {
19 |
20 | @Provides
21 | fun providesFirebaseFirestore(): FirebaseFirestore = Firebase.firestore
22 |
23 | @Provides
24 | fun provideFirebaseAuth(): FirebaseAuth = Firebase.auth
25 |
26 | @Provides
27 | fun provideCredentialManager(@ApplicationContext context: Context): CredentialManager =
28 | CredentialManager.create(context)
29 |
30 | @Provides
31 | fun provideApplicationContext(@ApplicationContext context: Context): Context = context
32 | }
33 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/ThemePreferences.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import android.content.Context
4 | import androidx.datastore.core.DataStore
5 | import androidx.datastore.preferences.core.Preferences
6 | import androidx.datastore.preferences.core.stringPreferencesKey
7 | import androidx.datastore.preferences.core.edit
8 | import androidx.datastore.preferences.preferencesDataStore
9 | import kotlinx.coroutines.flow.Flow
10 | import kotlinx.coroutines.flow.map
11 | import timber.log.Timber
12 |
13 | val Context.dataStore: DataStore by preferencesDataStore(name = "theme_prefs")
14 |
15 | class ThemePreferences(private val context: Context) {
16 |
17 | companion object {
18 | private val THEME_KEY = stringPreferencesKey("theme_key") // ✅ Se asegura de usar la clave correcta
19 | }
20 |
21 | val selectedTheme: Flow = context.dataStore.data.map { preferences ->
22 | preferences[THEME_KEY] ?: "Claro"
23 | }
24 |
25 | suspend fun saveTheme(theme: String) {
26 | context.dataStore.edit { preferences ->
27 | preferences[THEME_KEY] = theme
28 | }
29 | Timber.tag("ThemePreferences").d("✅ Tema guardado: $theme")
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/pointsDB/PointsRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.pointsDB
2 |
3 | import kotlinx.coroutines.flow.Flow
4 | import kotlinx.coroutines.flow.filterNotNull
5 | import kotlinx.coroutines.flow.firstOrNull
6 |
7 | class PointsRepository(private val pointsDao: PointsDao) {
8 |
9 | fun getUserPoints(userId: String): Flow = pointsDao.getUserPoints(userId).filterNotNull()
10 |
11 | suspend fun addPoints(userId: String, points: Int) {
12 | val currentPoints = pointsDao.getUserPoints(userId).firstOrNull()
13 | if (currentPoints == null) {
14 | pointsDao.insertOrUpdatePoints(UserPoints(userId = userId, points = points)) // Inserta un nuevo usuario
15 | } else {
16 | pointsDao.addPoints(userId, points) // Actualiza si ya existe
17 | }
18 | }
19 |
20 | suspend fun spendPoints(userId: String, points: Int): Boolean {
21 | val currentPoints = pointsDao.getUserPoints(userId).firstOrNull() // Obtiene el valor actual
22 | return if (currentPoints != null && currentPoints.points >= points) {
23 | pointsDao.spendPoints(userId, points)
24 | true
25 | } else {
26 | false
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | insert_final_newline = true
6 | trim_trailing_whitespace = true
7 |
8 | [*.{kt,kts}]
9 | ktlint_code_style = android_studio
10 | max_line_length = 120
11 | indent_size = 4
12 | ktlint_standard_import-ordering = disabled
13 | ktlint_standard_value-argument-comment = disabled
14 |
15 | ij_kotlin_allow_trailing_comma_on_call_site = true
16 | ij_kotlin_allow_trailing_comma = true
17 | ij_kotlin_packages_to_use_import_on_demand = unset
18 | ij_kotlin_name_count_to_use_star_import = 999
19 | ij_kotlin_name_count_to_use_star_import_for_members = 999
20 |
21 | # Compose
22 | ktlint_function_naming_ignore_when_annotated_with=Composable
23 | ktlint_compose_modifier-missing-check = disabled
24 | ktlint_compose_unstable-collections = disabled
25 |
26 | [*.{yml,yaml}]
27 | indent_size = 2
28 |
29 |
30 | # An individual rule can be enabled or disabled with a rule property.
31 | # The name of the rule property consists of the ktlint_ prefix followed by the rule set id followed by a _ and the rule id.
32 | # Examples:
33 | # ktlint_standard_final-newline = disabled # Disables the `final-newline` rule provided by KtLint
34 | # ktlint_standard_some-experimental-rule = enabled # Enables the (experimental) `some-experimental-rule` in the `standard` rule set provided by KtLint
35 | # ktlint_custom-rule-set_custom-rule = disabled # Disables the `custom-rule` rule in the `custom-rule-set` rule set (not provided by KtLint)
36 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/pointsDB/di/PointsModule.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.pointsDB.di
2 |
3 | import android.content.Context
4 | import androidx.room.Room
5 | import com.mundocode.pomodoro.data.pointsDB.PointsDao
6 | import com.mundocode.pomodoro.data.pointsDB.PointsDatabase
7 | import com.mundocode.pomodoro.data.pointsDB.PointsRepository
8 | import com.mundocode.pomodoro.data.storeDB.PurchasedItemsDao
9 | import dagger.Module
10 | import dagger.Provides
11 | import dagger.hilt.InstallIn
12 | import dagger.hilt.android.qualifiers.ApplicationContext
13 | import dagger.hilt.components.SingletonComponent
14 | import javax.inject.Singleton
15 |
16 | @Module
17 | @InstallIn(SingletonComponent::class)
18 | object PointsModule {
19 | @Provides
20 | @Singleton
21 | fun providePointsDatabase(@ApplicationContext context: Context): PointsDatabase = Room.databaseBuilder(
22 | context.applicationContext,
23 | PointsDatabase::class.java,
24 | "points_database",
25 | ).fallbackToDestructiveMigration().build()
26 |
27 | @Provides
28 | fun providePointsDao(pointsDatabase: PointsDatabase): PointsDao = pointsDatabase.pointsDao()
29 |
30 | @Provides
31 | fun providePurchasedItemsDao(pointsDatabase: PointsDatabase): PurchasedItemsDao = pointsDatabase.purchasedItemsDao()
32 |
33 | @Provides
34 | fun providePointsRepository(pointsDao: PointsDao): PointsRepository = PointsRepository(pointsDao)
35 | }
36 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/ThemeViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import dagger.hilt.android.lifecycle.HiltViewModel
6 | import kotlinx.coroutines.flow.MutableStateFlow
7 | import kotlinx.coroutines.flow.StateFlow
8 | import kotlinx.coroutines.flow.asStateFlow
9 | import kotlinx.coroutines.launch
10 | import timber.log.Timber
11 | import javax.inject.Inject
12 |
13 | @HiltViewModel
14 | class ThemeViewModel @Inject constructor(private val themePreferences: ThemePreferences) : ViewModel() {
15 |
16 | private val _selectedTheme = MutableStateFlow("Tema Claro")
17 | val selectedTheme: StateFlow = _selectedTheme.asStateFlow()
18 |
19 | private val _currentTheme = MutableStateFlow("Tema Claro") // Valor por defecto
20 | val currentTheme: StateFlow = _currentTheme.asStateFlow()
21 |
22 | init {
23 | viewModelScope.launch {
24 | themePreferences.selectedTheme.collect { theme ->
25 | _selectedTheme.value = theme
26 | Timber.tag("ThemeViewModel").d("🎨 Tema cargado: $theme")
27 | }
28 | }
29 | }
30 |
31 | fun changeTheme(themeName: String) {
32 | viewModelScope.launch {
33 | themePreferences.saveTheme(themeName)
34 | _selectedTheme.value = themeName
35 | Timber.tag("ThemeViewModel").d("🎨 Tema cambiado a: $themeName")
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. For more details, visit
12 | # https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 | # Enables namespacing of each library's R class so that its R class includes only the
21 | # resources declared in the library itself and none from the library's dependencies,
22 | # thereby reducing the size of the R class for that library
23 | android.nonTransitiveRClass=true
24 |
25 | web_client_id=847345547294-tklmbpje1pi9d4hr2bg569nsodq84k30.apps.googleusercontent.com
26 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/SharedPointsViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.mundocode.pomodoro.data.pointsDB.PointsRepository
6 | import dagger.hilt.android.lifecycle.HiltViewModel
7 | import kotlinx.coroutines.flow.MutableStateFlow
8 | import kotlinx.coroutines.flow.StateFlow
9 | import kotlinx.coroutines.flow.collectLatest
10 | import kotlinx.coroutines.launch
11 | import javax.inject.Inject
12 | import com.google.firebase.auth.FirebaseAuth
13 |
14 | @HiltViewModel
15 | class SharedPointsViewModel @Inject constructor(private val pointsRepository: PointsRepository) : ViewModel() {
16 |
17 | private val _userPoints = MutableStateFlow(0)
18 | val userPoints: StateFlow = _userPoints
19 |
20 | fun spendPoints(points: Int) {
21 | _userPoints.value -= points
22 | }
23 |
24 | private val userId = FirebaseAuth.getInstance().currentUser?.uid ?: ""
25 |
26 | init {
27 | loadUserPoints()
28 | }
29 |
30 | fun loadUserPoints() {
31 | viewModelScope.launch {
32 | pointsRepository.getUserPoints(userId).collectLatest { userPoints ->
33 | _userPoints.value = userPoints?.points ?: 0
34 | }
35 | }
36 | }
37 |
38 | fun addPoints(points: Int) {
39 | viewModelScope.launch {
40 | pointsRepository.addPoints(userId, points)
41 | loadUserPoints() // Recargar puntos después de actualizarlos
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/Theme.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import androidx.compose.material3.MaterialTheme
4 | import androidx.compose.runtime.Composable
5 | import androidx.compose.runtime.getValue
6 | import androidx.compose.runtime.collectAsState
7 | import androidx.hilt.navigation.compose.hiltViewModel
8 |
9 | // private val DarkColorScheme = darkColorScheme(
10 | // primary = Purple80,
11 | // secondary = PurpleGrey80,
12 | // tertiary = Pink80,
13 | // )
14 |
15 | // private val LightColorScheme = lightColorScheme(
16 | // primary = Purple40,
17 | // secondary = PurpleGrey40,
18 | // tertiary = Pink40,
19 | //
20 | // /* Other default colors to override
21 | // background = Color(0xFFFFFBFE),
22 | // surface = Color(0xFFFFFBFE),
23 | // onPrimary = Color.White,
24 | // onSecondary = Color.White,
25 | // onTertiary = Color.White,
26 | // onBackground = Color(0xFF1C1B1F),
27 | // onSurface = Color(0xFF1C1B1F),
28 | // */
29 | // )
30 |
31 | @Composable
32 | fun PomodoroTheme(themeViewModel: ThemeViewModel = hiltViewModel(), content: @Composable () -> Unit) {
33 | val selectedTheme by themeViewModel.selectedTheme.collectAsState()
34 |
35 | val colors = when (selectedTheme) {
36 | "Tema Oscuro" -> DarkColorScheme
37 | // "Tema Azul" -> BlueColorScheme
38 | // "Tema Rojo" -> RedColorScheme
39 | else -> LightColorScheme
40 | }
41 |
42 | MaterialTheme(
43 | colorScheme = colors,
44 | typography = Typography,
45 | content = content,
46 | )
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
21 |
22 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/setupSessionScreen/SetupSessionViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.setupSessionScreen
2 |
3 | import androidx.lifecycle.ViewModel
4 | import com.mundocode.pomodoro.model.local.Timer
5 | import dagger.hilt.android.lifecycle.HiltViewModel
6 | import kotlinx.coroutines.flow.MutableStateFlow
7 | import kotlinx.coroutines.flow.StateFlow
8 | import kotlinx.coroutines.flow.update
9 | import javax.inject.Inject
10 |
11 | @HiltViewModel
12 | class SetupSessionViewModel @Inject constructor() : ViewModel() {
13 |
14 | val sessionState: StateFlow
15 | field: MutableStateFlow = MutableStateFlow(SessionState())
16 |
17 | fun updateSessionName(sessionName: String) {
18 | sessionState.update {
19 | it.copy(
20 | timer = it.timer.copy(
21 | sessionName = sessionName,
22 | ),
23 | )
24 | }
25 | }
26 |
27 | fun updateMode(mode: String) {
28 | sessionState.update {
29 | it.copy(
30 | timer = it.timer.copy(
31 | mode = mode,
32 | ),
33 | )
34 | }
35 | }
36 |
37 | fun updateTimer(timer: String) {
38 | sessionState.update {
39 | it.copy(
40 | timer = it.timer.copy(
41 | timer = timer,
42 | ),
43 | )
44 | }
45 | }
46 |
47 | fun updatePause(pause: String) {
48 | sessionState.update {
49 | it.copy(
50 | timer = it.timer.copy(
51 | pause = pause,
52 | ),
53 | )
54 | }
55 | }
56 | }
57 |
58 | data class SessionState(val timer: Timer) {
59 | constructor() : this(
60 | timer = Timer(
61 | sessionName = "",
62 | mode = "",
63 | timer = "30:00",
64 | pause = "05:00",
65 | ),
66 | )
67 | }
68 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/theme/Color.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.theme
2 |
3 | import androidx.compose.material3.darkColorScheme
4 | import androidx.compose.material3.lightColorScheme
5 | import androidx.compose.ui.graphics.Color
6 |
7 | // Modo Claro
8 | val LightColorScheme = lightColorScheme(
9 | primary = Color(0xFFB51C1C), // Fondo
10 | onPrimary = Color(0xFFFFFFFF), // Texto
11 | secondary = Color(0xFF06B6D4), // Fondo
12 | onSecondary = Color(0xFFFFFFFF), // Texto
13 | tertiary = Color(0xFF6366F1), // Fondo
14 | onTertiary = Color(0xFFFFFFFF), // Texto
15 | background = Color(0xFFEFEFEF), // Fondo
16 | surface = Color(0xFFFFFFFF), // Fondo
17 | inverseSurface = Color(0xFF000000),
18 | onSurface = Color(0xFF000000), // Texto
19 | onSurfaceVariant = Color(0xFF000000), // Texto
20 | )
21 |
22 | // Modo Oscuro
23 | val DarkColorScheme = darkColorScheme(
24 | primary = Color(0xFF6366F1), // Fondo
25 | onPrimary = Color(0xFFFFFFFF), // Texto
26 | secondary = Color(0xFF6366F1), // Fondo
27 | onSecondary = Color(0xFFFFFFFF), // Texto
28 | tertiary = Color(0xFF6366F1), // Fondo
29 | onTertiary = Color(0xFFFFFFFF), // Texto
30 | background = Color(0xFF192229), // Fondo
31 | surface = Color(0xFF6366F1), // Fondo
32 | inverseSurface = Color(0xFFFFFFFF),
33 | onSurface = Color(0xFFFFFFFF), // Texto
34 | onSurfaceVariant = Color(0xFF000000), // Texto
35 | )
36 |
37 | // // Modo Azul
38 | // val BlueColorScheme = lightColorScheme(
39 | // primary = Color(), // Fondo
40 | // onPrimary = Color(), // Texto
41 | // secondary = Color(), // Fondo
42 | // onSecondary = Color(), // Texto
43 | // tertiary = Color(), // Fondo
44 | // onTertiary = Color(), // Texto
45 | // background = Color(0xFF2196F3), // Fondo
46 | // surface = Color(), // Fondo
47 | // onSurface = Color(), // Texto
48 | // )
49 | //
50 | // // Modo Rojo
51 | // val RedColorScheme = lightColorScheme(
52 | // primary = Color(), // Fondo
53 | // onPrimary = Color(), // Texto
54 | // secondary = Color(), // Fondo
55 | // onSecondary = Color(), // Texto
56 | // tertiary = Color(), // Fondo
57 | // onTertiary = Color(), // Texto
58 | // background = Color(0xFFD2362D), // Fondo
59 | // surface = Color(), // Fondo
60 | // onSurface = Color(), // Texto
61 | // )
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro
2 |
3 | import android.content.Intent
4 | import android.os.Bundle
5 | import androidx.activity.ComponentActivity
6 | import androidx.activity.compose.setContent
7 | import androidx.activity.enableEdgeToEdge
8 | import androidx.hilt.navigation.compose.hiltViewModel
9 | import com.google.firebase.auth.FirebaseAuth
10 | import com.google.android.gms.auth.api.identity.Identity
11 | import com.google.android.gms.auth.api.identity.SignInClient
12 | import com.mundocode.pomodoro.core.navigation.NavigationRoot
13 | import com.mundocode.pomodoro.ui.theme.PomodoroTheme
14 | import com.mundocode.pomodoro.ui.theme.ThemeViewModel
15 | import dagger.hilt.android.AndroidEntryPoint
16 | import timber.log.Timber
17 | import javax.inject.Inject
18 |
19 | @AndroidEntryPoint
20 | class MainActivity : ComponentActivity() {
21 |
22 | private lateinit var signInClient: SignInClient
23 |
24 | @Inject
25 | lateinit var auth: FirebaseAuth
26 |
27 | override fun onCreate(savedInstanceState: Bundle?) {
28 | super.onCreate(savedInstanceState)
29 | enableEdgeToEdge()
30 | signInClient = Identity.getSignInClient(this)
31 |
32 | handleNotificationIntent(intent)
33 |
34 | setContent {
35 | val themeViewModel: ThemeViewModel = hiltViewModel()
36 | PomodoroTheme(themeViewModel) {
37 | // ✅ Pasamos el `ThemeViewModel`
38 | NavigationRoot()
39 | }
40 | }
41 | }
42 |
43 | override fun onNewIntent(intent: Intent) {
44 | super.onNewIntent(intent)
45 | handleNotificationIntent(intent)
46 | }
47 |
48 | private fun handleNotificationIntent(intent: Intent) {
49 | intent.extras?.let {
50 | if (it.getBoolean("fromReminder", false)) {
51 | // 🚀 Aquí puedes redirigir al usuario al Pomodoro
52 | Timber.tag("MainActivity").i("Notificación de recordatorio presionada. Redirigiendo al Pomodoro...")
53 | }
54 | }
55 | }
56 |
57 | override fun onStart() {
58 | super.onStart()
59 | val currentUser = auth.currentUser
60 |
61 | if (currentUser != null) {
62 | Timber.tag("MainActivity").i("Usuario autenticado: ${currentUser.email}")
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/points/PointsViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.points
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.ViewModelProvider
5 | import androidx.lifecycle.viewModelScope
6 | import com.mundocode.pomodoro.data.pointsDB.PointsRepository
7 | import dagger.assisted.Assisted
8 | import dagger.assisted.AssistedFactory
9 | import dagger.assisted.AssistedInject
10 | import dagger.hilt.android.lifecycle.HiltViewModel
11 | import kotlinx.coroutines.flow.SharingStarted
12 | import kotlinx.coroutines.flow.StateFlow
13 | import kotlinx.coroutines.flow.map
14 | import kotlinx.coroutines.flow.stateIn
15 | import kotlinx.coroutines.launch
16 | import javax.inject.Inject
17 |
18 | class PointsViewModel @AssistedInject constructor(
19 | private val pointsRepository: PointsRepository,
20 | @Assisted private val userId: String,
21 | ) : ViewModel() {
22 |
23 | val userPoints: StateFlow = pointsRepository.getUserPoints(userId).map { it.points }.stateIn(
24 | scope = viewModelScope,
25 | started = SharingStarted.WhileSubscribed(5_000),
26 | initialValue = 0,
27 | )
28 |
29 | fun addPoints(userId: String, points: Int) {
30 | viewModelScope.launch {
31 | pointsRepository.addPoints(userId, points)
32 | }
33 | }
34 |
35 | fun spendPoints(userId: String, points: Int): Boolean {
36 | var success = false
37 | viewModelScope.launch {
38 | success = pointsRepository.spendPoints(userId, points)
39 | }
40 | return success
41 | }
42 |
43 | @AssistedFactory
44 | interface PointsViewModelFactory {
45 | fun create(userId: String): PointsViewModel
46 | }
47 |
48 | companion object {
49 | fun provideFactory(assistedFactory: PointsViewModelFactory, userId: String): ViewModelProvider.Factory =
50 | object : ViewModelProvider.Factory {
51 | @Suppress("UNCHECKED_CAST")
52 | override fun create(modelClass: Class): T = assistedFactory.create(userId) as T
53 | }
54 | }
55 | }
56 |
57 | // Esta clase es necesaria para exponer la factory a Hilt
58 | @HiltViewModel
59 | class PointsViewModelFactoryProvider @Inject constructor(
60 | val pointsViewModelFactory: PointsViewModel.PointsViewModelFactory,
61 | ) : ViewModel()
62 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/timer/ReminderReceiver.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.timer
2 |
3 | import android.app.NotificationChannel
4 | import android.app.NotificationManager
5 | import android.app.PendingIntent
6 | import android.content.BroadcastReceiver
7 | import android.content.Context
8 | import android.content.Intent
9 | import android.os.Build
10 | import androidx.core.app.NotificationCompat
11 | import com.mundocode.pomodoro.MainActivity
12 | import com.mundocode.pomodoro.R
13 |
14 | class ReminderReceiver : BroadcastReceiver() {
15 | override fun onReceive(context: Context, intent: Intent?) {
16 | showReminderNotification(context)
17 | }
18 |
19 | private fun showReminderNotification(context: Context) {
20 | val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
21 |
22 | // Crear el canal de notificación en Android 8+
23 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
24 | val channel = NotificationChannel(
25 | "pomodoro_reminder_channel",
26 | "Recordatorio de Pomodoro",
27 | NotificationManager.IMPORTANCE_HIGH,
28 | )
29 | notificationManager.createNotificationChannel(channel)
30 | }
31 |
32 | // Intent para abrir la app cuando se toque la notificación
33 | val openIntent = Intent(context, MainActivity::class.java).apply {
34 | flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
35 | putExtra("fromReminder", true) // ✅ Detectar si se abrió desde la notificación
36 | }
37 | val pendingIntent = PendingIntent.getActivity(
38 | context,
39 | 0,
40 | openIntent,
41 | PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
42 | )
43 |
44 | // Construir la notificación
45 | val notification = NotificationCompat.Builder(context, "pomodoro_reminder_channel")
46 | .setSmallIcon(R.drawable.timer)
47 | .setContentTitle("¡Hora de un Pomodoro! 🍅")
48 | .setContentText("No has iniciado un Pomodoro en un tiempo. ¡Empieza uno ahora!")
49 | .setPriority(NotificationCompat.PRIORITY_HIGH)
50 | .setContentIntent(pendingIntent)
51 | .setAutoCancel(true)
52 | .build()
53 |
54 | notificationManager.notify(1001, notification) // ✅ Mostrar la notificación
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/splashScreen/SplashScreen.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.splashScreen
2 |
3 | import androidx.compose.foundation.layout.Box
4 | import androidx.compose.foundation.layout.fillMaxSize
5 | import androidx.compose.material3.Text
6 | import androidx.compose.runtime.Composable
7 | import androidx.compose.runtime.LaunchedEffect
8 | import androidx.compose.runtime.collectAsState
9 | import androidx.compose.runtime.getValue
10 | import androidx.compose.runtime.setValue
11 | import androidx.compose.runtime.mutableStateOf
12 | import androidx.compose.runtime.remember
13 | import androidx.compose.ui.Alignment
14 | import androidx.compose.ui.Modifier
15 | import androidx.compose.ui.graphics.Color
16 | import androidx.compose.ui.text.font.FontWeight
17 | import androidx.compose.ui.unit.sp
18 | import androidx.hilt.navigation.compose.hiltViewModel
19 | import androidx.navigation.NavController
20 | import com.mundocode.pomodoro.core.navigation.Destinations
21 | import com.mundocode.pomodoro.ui.screens.loginScreen.LoginViewModel
22 | import kotlinx.coroutines.delay
23 | import kotlinx.serialization.ExperimentalSerializationApi
24 | import com.kiwi.navigationcompose.typed.navigate as kiwiNavigation
25 |
26 | @OptIn(ExperimentalSerializationApi::class)
27 | @Composable
28 | fun SplashScreen(navController: NavController, viewModel: LoginViewModel = hiltViewModel()) {
29 | val loginSuccess by viewModel.loginSuccess.collectAsState()
30 |
31 | var dots by remember { mutableStateOf("") }
32 |
33 | LaunchedEffect(Unit) {
34 | while (true) {
35 | dots = when (dots) {
36 | "" -> "."
37 | "." -> ".."
38 | ".." -> "..."
39 | else -> ""
40 | }
41 | delay(500) // Cambia los puntos cada 500ms
42 | }
43 | }
44 |
45 | LaunchedEffect(loginSuccess) {
46 | delay(1000) // Retraso opcional para una mejor transición
47 | if (loginSuccess) {
48 | navController.kiwiNavigation(Destinations.HomeScreen) {
49 | popUpTo("splash") { inclusive = true }
50 | }
51 | } else {
52 | navController.kiwiNavigation(Destinations.Login) {
53 | popUpTo("splash") { inclusive = true }
54 | }
55 | }
56 | }
57 |
58 | Box(
59 | modifier = Modifier.fillMaxSize(),
60 | contentAlignment = Alignment.Center,
61 | ) {
62 | Text(
63 | text = "Cargando$dots",
64 | fontSize = 20.sp,
65 | fontWeight = FontWeight.Bold,
66 | color = Color.Gray,
67 | )
68 | // CircularProgressIndicator() // Muestra un loading mientras decide
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PomodoroApp
2 |
3 | Proyecto colaborativo para desarrollar una aplicación de Pomodoro con métricas y estadísticas. Este proyecto es parte de la iniciativa de MoureDev para practicar y mejorar nuestras habilidades en Kotlin y trabajo colaborativo.
4 |
5 | ## 🚀 Objetivo
6 |
7 | Crear una aplicación funcional que permita a los usuarios:
8 |
9 | * Gestionar su tiempo con la técnica Pomodoro.
10 | * Visualizar métricas y estadísticas de su progreso.
11 | * En futuras iteraciones, gestionar tareas y hábitos.
12 |
13 | ## 🛠️ Tecnologías
14 |
15 | * **Kotlin**: Lenguaje principal para la implementación de la app.
16 | * **Jetpack Compose**: Para construir la interfaz de usuario.
17 | * **GitHub**: Plataforma para la colaboración y gestión del repositorio.
18 |
19 | ## 📂 Estructura de Ramas
20 |
21 | * **`main`**: Versión estable del código.
22 | * **`develop`**: Rama principal de desarrollo.
23 | * **Ramas de tareas**: Cada tarea/issue se desarrollará en su propia rama, siguiendo el formato: `feature/nombre-de-la-tarea`.
24 |
25 | ## 🗂️ Backlog y Gestión de Tareas
26 |
27 | Utilizamos la pestaña de **Projects** en GitHub para gestionar el avance del proyecto. Las tareas estarán organizadas en columnas:
28 |
29 | 1. **To Do**: Tareas pendientes.
30 | 2. **In Progress**: Tareas en desarrollo.
31 | 3. **In Review**: Pull Requests abiertos.
32 | 4. **Done**: Tareas completadas.
33 |
34 | ## 📜 Licencia
35 |
36 | Este proyecto está licenciado bajo la [MIT License](LICENSE).
37 |
38 | ## 👥 Equipo
39 |
40 | * **Gestor de Kotlin**: [juanppdev](https://github.com/juanppdev)
41 | * **Colaboradores**:
42 | * [Rickmij](https://github.com/Rickmij),
43 | * [MOTHINK (mo_22)](https://github.com/MOTHINK),
44 | * [Rusalka](https://github.com/rcellas),
45 | * [AndroidZen](https://github.com/hgarciaalberto),
46 | * [jaennova](https://github.com/jaennova),
47 | * [aromeros1992](https://github.com/aromeros1992).
48 |
49 | # 🎨 Diseño del Proyecto
50 |
51 | * **Diseñadores**:
52 | * [Rusalka](https://github.com/rcellas)
53 | * [Rick](https://github.com/Rickmij)
54 |
55 | Puedes consultar el diseño preliminar del proyecto en Figma:[Diseño en Figma](https://www.figma.com/design/GdZmsgDPXeJGc9zLgesPaD/App-Habitos?node-id=15-43&p=f&t=Q08Jbj7W5ixDp4Qq-0)
56 |
57 | ## 🎯 Próximos Pasos
58 |
59 | * [x] Completar el diseño en Figma.
60 | * [x] Dividir el backlog en tareas concretas.
61 | * [ ] Comenzar con el primer sprint.
62 |
63 | * * *
64 |
65 | 🌐 Proyectos Paralelos
66 |
67 | Este proyecto está acompañado por dos desarrollos paralelos que comparten la misma funcionalidad básica, pero en diferentes plataformas:
68 |
69 | * [Proyecto Swift](https://github.com/kontroldev/Proyecto_1_Pomodoro)
70 | * [Proyecto Web](https://github.com/ProyectosWebComunidadMoureDev/PomodoroWeb/tree/main)
71 |
72 | ¡Gracias por contribuir y formar parte de este proyecto! 💪
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/core/navigation/NavigationRoot.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.core.navigation
2 |
3 | import androidx.compose.runtime.Composable
4 | import androidx.navigation.compose.NavHost
5 | import androidx.navigation.compose.rememberNavController
6 | import com.kiwi.navigationcompose.typed.composable
7 | import com.kiwi.navigationcompose.typed.createRoutePattern
8 | import com.mundocode.pomodoro.ui.screens.splashScreen.SplashScreen
9 | import com.mundocode.pomodoro.ui.screens.habits.HabitsScreen
10 | import com.mundocode.pomodoro.ui.screens.homeScreen.HomeScreen
11 | import com.mundocode.pomodoro.ui.screens.loginScreen.LoginScreen
12 | import com.mundocode.pomodoro.ui.screens.loginScreen.RegisterScreen
13 | import com.mundocode.pomodoro.ui.screens.setupSessionScreen.SetupSessionScreen
14 | import com.mundocode.pomodoro.ui.screens.taskScreen.TaskScreen
15 | import com.mundocode.pomodoro.ui.screens.points.StoreScreen
16 | import com.mundocode.pomodoro.ui.screens.settings.SettingsScreen
17 | import com.mundocode.pomodoro.ui.screens.timer.TimerScreen
18 | import kotlinx.serialization.ExperimentalSerializationApi
19 |
20 | @OptIn(ExperimentalSerializationApi::class)
21 | @Composable
22 | fun NavigationRoot() {
23 | val navController = rememberNavController()
24 |
25 | NavHost(
26 | navController = navController,
27 | startDestination = createRoutePattern(),
28 | ) {
29 | composable {
30 | SplashScreen(
31 | navController = navController,
32 | )
33 | }
34 |
35 | composable {
36 | LoginScreen(
37 | navController = navController,
38 | )
39 | }
40 | composable {
41 | RegisterScreen(
42 | navController = navController,
43 | )
44 | }
45 | composable {
46 | HomeScreen(navController = navController)
47 | }
48 | composable {
49 | SetupSessionScreen(
50 | navController = navController,
51 | )
52 | }
53 | composable {
54 | HabitsScreen(navController = navController)
55 | }
56 |
57 | composable {
58 | TaskScreen(navController = navController)
59 | }
60 |
61 | composable {
62 | TimerScreen(navController = navController)
63 | }
64 | composable {
65 | StoreScreen(navController = navController)
66 | }
67 | composable {
68 | SettingsScreen(navController = navController)
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/habits/HabitsViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.habits
2 |
3 | import androidx.lifecycle.LiveData
4 | import androidx.lifecycle.MutableLiveData
5 | import androidx.lifecycle.ViewModel
6 | import androidx.lifecycle.viewModelScope
7 | import com.mundocode.pomodoro.data.habitsDB.HabitsRepository
8 | import com.mundocode.pomodoro.data.habitsDB.domain.AddTaskUserCase
9 | import com.mundocode.pomodoro.data.habitsDB.domain.DeleteTaskUseCase
10 | import com.mundocode.pomodoro.data.habitsDB.domain.GetTasksUserCase
11 | import com.mundocode.pomodoro.data.habitsDB.domain.UpdateTaskUseCase
12 | import com.mundocode.pomodoro.ui.screens.habits.HabitsUIState.Loading
13 | import com.mundocode.pomodoro.ui.screens.habits.HabitsUIState.Success
14 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
15 | import dagger.hilt.android.lifecycle.HiltViewModel
16 | import kotlinx.coroutines.FlowPreview
17 | import kotlinx.coroutines.flow.MutableStateFlow
18 | import kotlinx.coroutines.flow.SharingStarted
19 | import kotlinx.coroutines.flow.StateFlow
20 | import kotlinx.coroutines.flow.catch
21 | import kotlinx.coroutines.flow.collectLatest
22 | import kotlinx.coroutines.flow.debounce
23 | import kotlinx.coroutines.flow.map
24 | import kotlinx.coroutines.flow.stateIn
25 | import kotlinx.coroutines.launch
26 | import javax.inject.Inject
27 |
28 | @OptIn(FlowPreview::class)
29 | @HiltViewModel
30 | class HabitsViewModel @Inject constructor(
31 | private val addTaskUserCase: AddTaskUserCase,
32 | private val updateTaskUseCase: UpdateTaskUseCase,
33 | private val deleteTaskUseCase: DeleteTaskUseCase,
34 | private val habitsRepository: HabitsRepository,
35 | getTasksUserCase: GetTasksUserCase,
36 | ) : ViewModel() {
37 |
38 | val uiState: StateFlow = getTasksUserCase().map(::Success)
39 | .catch { Error(it) }
40 | .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), Loading)
41 |
42 | init {
43 | habitsRepository.syncFromFirestore(viewModelScope, "")
44 | }
45 |
46 | val showDialog: LiveData
47 | field = MutableLiveData()
48 |
49 | val searchQuery: StateFlow
50 | field = MutableStateFlow("")
51 |
52 | init {
53 | viewModelScope.launch {
54 | searchQuery
55 | .debounce(500) // Espera 500ms después del último cambio antes de consultar Firestore
56 | .collectLatest { query ->
57 | habitsRepository.syncFromFirestore(viewModelScope, query)
58 | }
59 | }
60 | }
61 |
62 | fun onSearchQueryChanged(query: String) {
63 | searchQuery.value = query // Se actualiza el StateFlow, lo que dispara la búsqueda con debounce
64 | }
65 |
66 | fun onDialogClose() {
67 | showDialog.value = false
68 | }
69 |
70 | fun onTaskCreated(title: String, description: String) {
71 | showDialog.value = false
72 |
73 | viewModelScope.launch {
74 | addTaskUserCase(HabitsModel(title = title, description = description))
75 | }
76 | }
77 |
78 | fun onShowDialogSelected() {
79 | showDialog.value = true
80 | }
81 |
82 | fun onItemRemove(taskModel: HabitsModel) {
83 | viewModelScope.launch {
84 | deleteTaskUseCase(taskModel)
85 | }
86 | }
87 |
88 | fun onTaskUpdated(taskModel: HabitsModel) {
89 | viewModelScope.launch {
90 | updateTaskUseCase(taskModel)
91 | }
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/components/SwipeBox.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.components
2 |
3 | import androidx.compose.animation.animateContentSize
4 | import androidx.compose.foundation.background
5 | import androidx.compose.foundation.layout.Box
6 | import androidx.compose.foundation.layout.fillMaxSize
7 | import androidx.compose.foundation.layout.padding
8 | import androidx.compose.material.icons.Icons
9 | import androidx.compose.material.icons.outlined.Delete
10 | import androidx.compose.material.icons.outlined.Edit
11 | import androidx.compose.material3.Icon
12 | import androidx.compose.material3.MaterialTheme
13 | import androidx.compose.material3.SwipeToDismissBox
14 | import androidx.compose.material3.SwipeToDismissBoxValue
15 | import androidx.compose.material3.minimumInteractiveComponentSize
16 | import androidx.compose.material3.rememberSwipeToDismissBoxState
17 | import androidx.compose.runtime.Composable
18 | import androidx.compose.runtime.LaunchedEffect
19 | import androidx.compose.ui.Alignment
20 | import androidx.compose.ui.Modifier
21 | import androidx.compose.ui.graphics.Color
22 | import androidx.compose.ui.graphics.vector.ImageVector
23 | import androidx.compose.ui.unit.Dp
24 | import androidx.compose.ui.unit.dp
25 |
26 | @Composable
27 | fun SwipeBox(modifier: Modifier = Modifier, onDelete: () -> Unit, content: @Composable () -> Unit) {
28 | val swipeState = rememberSwipeToDismissBoxState()
29 |
30 | lateinit var icon: ImageVector
31 | lateinit var alignment: Alignment
32 | val color: Color
33 | val padding: Dp = 0.dp
34 |
35 | when (swipeState.dismissDirection) {
36 | SwipeToDismissBoxValue.EndToStart -> {
37 | icon = Icons.Outlined.Delete
38 | alignment = Alignment.CenterEnd
39 | color = MaterialTheme.colorScheme.errorContainer
40 | }
41 |
42 | SwipeToDismissBoxValue.StartToEnd -> {
43 | icon = Icons.Outlined.Edit
44 | alignment = Alignment.CenterStart
45 | color =
46 | Color.Green.copy(alpha = 0.3f) // You can generate theme for successContainer in themeBuilder
47 | }
48 |
49 | SwipeToDismissBoxValue.Settled -> {
50 | icon = Icons.Outlined.Delete
51 | alignment = Alignment.CenterEnd
52 | color = MaterialTheme.colorScheme.errorContainer
53 | }
54 | }
55 |
56 | SwipeToDismissBox(
57 | modifier = modifier.animateContentSize().padding(padding),
58 | state = swipeState,
59 | backgroundContent = {
60 | Box(
61 | contentAlignment = alignment,
62 | modifier = Modifier
63 | .fillMaxSize()
64 | .padding(horizontal = 16.dp)
65 | .padding(vertical = 8.dp)
66 | .animateContentSize()
67 | .background(color),
68 | ) {
69 | Icon(
70 | modifier = Modifier.minimumInteractiveComponentSize(),
71 | imageVector = icon,
72 | contentDescription = null,
73 | )
74 | }
75 | },
76 | ) {
77 | content()
78 | }
79 |
80 | when (swipeState.currentValue) {
81 | SwipeToDismissBoxValue.EndToStart -> {
82 | onDelete()
83 | }
84 |
85 | SwipeToDismissBoxValue.StartToEnd -> {
86 | LaunchedEffect(swipeState) {
87 | swipeState.snapTo(SwipeToDismissBoxValue.Settled)
88 | }
89 | }
90 |
91 | SwipeToDismissBoxValue.Settled -> {
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/components/CustomTopAppBar.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.components
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.fillMaxSize
6 | import androidx.compose.foundation.layout.padding
7 | import androidx.compose.material3.TopAppBar
8 | import androidx.compose.material3.Text
9 | import androidx.compose.material3.IconButton
10 | import androidx.compose.material3.DropdownMenu
11 | import androidx.compose.material3.DropdownMenuItem
12 | import androidx.compose.runtime.Composable
13 | import androidx.compose.runtime.remember
14 | import androidx.compose.runtime.mutableStateOf
15 | import androidx.compose.runtime.getValue
16 | import androidx.compose.runtime.setValue
17 | import androidx.navigation.NavController
18 | import androidx.compose.material3.ExperimentalMaterial3Api
19 | import androidx.compose.material3.MaterialTheme
20 | import androidx.compose.material3.TopAppBarDefaults
21 | import androidx.compose.ui.Modifier
22 | import androidx.compose.ui.layout.ContentScale
23 | import androidx.compose.ui.platform.LocalContext
24 | import androidx.compose.ui.tooling.preview.Preview
25 | import androidx.compose.ui.unit.DpOffset
26 | import androidx.compose.ui.unit.dp
27 | import coil.compose.AsyncImage
28 | import com.mundocode.pomodoro.core.navigation.Destinations
29 | import kotlinx.serialization.ExperimentalSerializationApi
30 | import com.kiwi.navigationcompose.typed.navigate as kiwiNavigation
31 |
32 | @OptIn(ExperimentalMaterial3Api::class, ExperimentalSerializationApi::class)
33 | @Composable
34 | fun CustomTopAppBar(
35 | navController: NavController,
36 | title: String,
37 | image: String,
38 | navigationIcon: @Composable () -> Unit = {},
39 | texto: String,
40 | onNavPoints: () -> Unit = {},
41 | ) {
42 | var isMenuExpanded by remember { mutableStateOf(false) }
43 |
44 | TopAppBar(
45 | title = {
46 | Text(
47 | text = title,
48 | color = MaterialTheme.colorScheme.inverseSurface,
49 | )
50 | },
51 | navigationIcon = navigationIcon,
52 | actions = {
53 | Text(
54 | text = texto,
55 | modifier = Modifier.padding(horizontal = 30.dp).clickable(
56 | onClick = {
57 | onNavPoints()
58 | },
59 | ),
60 | color = MaterialTheme.colorScheme.inverseSurface,
61 | )
62 |
63 | IconButton(onClick = { isMenuExpanded = true }) {
64 | AsyncImage(
65 | model = image,
66 | contentDescription = "Avatar de usuario",
67 | modifier = Modifier.fillMaxSize(),
68 | contentScale = ContentScale.Crop,
69 | )
70 | }
71 | DropdownMenu(
72 | expanded = isMenuExpanded,
73 | onDismissRequest = { isMenuExpanded = false },
74 | offset = DpOffset(250.dp, 0.dp), // 🔹 Ajuste para mover el menú a la derecha si es necesario
75 | modifier = Modifier.background(MaterialTheme.colorScheme.surface),
76 | ) {
77 | DropdownMenuItem(
78 | onClick = {
79 | isMenuExpanded = false
80 | navController.kiwiNavigation(Destinations.SettingsScreen)
81 | },
82 | text = {
83 | Text("Configuración")
84 | },
85 | )
86 | }
87 | },
88 | colors = TopAppBarDefaults.topAppBarColors(
89 | containerColor = MaterialTheme.colorScheme.primaryContainer,
90 | titleContentColor = MaterialTheme.colorScheme.primary,
91 | ),
92 | )
93 | }
94 |
95 | @Preview
96 | @Composable
97 | fun PreviewCustomTopAppBar() {
98 | CustomTopAppBar(
99 | navController = NavController(LocalContext.current),
100 | title = "Custom Top App Bar",
101 | image = "https://example.com/avatar.jpg",
102 | texto = "Puntos: 50",
103 | )
104 | }
105 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Created by https://www.toptal.com/developers/gitignore/api/android,androidstudio,macos,windows,gradle,maven,firebase,kotlin,git,jenv
2 | # Edit at https://www.toptal.com/developers/gitignore?templates=android,androidstudio,macos,windows,gradle,maven,firebase,kotlin,git,jenv
3 |
4 | ### Android ###
5 | # Gradle files
6 | .gradle/
7 | build/
8 |
9 | # Local configuration file (sdk path, etc)
10 | local.properties
11 |
12 | # Log/OS Files
13 | *.log
14 |
15 | # Android Studio generated files and folders
16 | captures/
17 | .externalNativeBuild/
18 | .cxx/
19 | *.apk
20 | output.json
21 |
22 | # IntelliJ
23 | *.iml
24 | .idea/
25 | misc.xml
26 | deploymentTargetDropDown.xml
27 | render.experimental.xml
28 |
29 | # Keystore files
30 | *.jks
31 | *.keystore
32 |
33 | # Google Services (e.g. APIs or Firebase)
34 | google-services.json
35 |
36 | # Android Profiling
37 | *.hprof
38 |
39 | ### Android Patch ###
40 | gen-external-apklibs
41 |
42 | # Replacement of .externalNativeBuild directories introduced
43 | # with Android Studio 3.5.
44 |
45 | ### Firebase ###
46 | .idea
47 | **/node_modules/*
48 | **/.firebaserc
49 |
50 | ### Firebase Patch ###
51 | .runtimeconfig.json
52 | .firebase/
53 |
54 | ### Git ###
55 | # Created by git for backups. To disable backups in Git:
56 | # $ git config --global mergetool.keepBackup false
57 | *.orig
58 |
59 | # Created by git when using merge tools for conflicts
60 | *.BACKUP.*
61 | *.BASE.*
62 | *.LOCAL.*
63 | *.REMOTE.*
64 | *_BACKUP_*.txt
65 | *_BASE_*.txt
66 | *_LOCAL_*.txt
67 | *_REMOTE_*.txt
68 |
69 | ### JEnv ###
70 | # JEnv local Java version configuration file
71 | .java-version
72 |
73 | # Used by previous versions of JEnv
74 | .jenv-version
75 |
76 | *.msp
77 |
78 | # Windows shortcuts
79 | *.lnk
80 |
81 | ### Gradle ###
82 | .gradle
83 | **/build/
84 | !src/**/build/
85 |
86 | # Ignore Gradle GUI config
87 | gradle-app.setting
88 |
89 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
90 | !gradle-wrapper.jar
91 |
92 | # Avoid ignore Gradle wrappper properties
93 | !gradle-wrapper.properties
94 |
95 | # Cache of project
96 | .gradletasknamecache
97 |
98 | # Eclipse Gradle plugin generated files
99 | # Eclipse Core
100 | # JDT-specific (Eclipse Java Development Tools)
101 |
102 | ### Gradle Patch ###
103 | # Java heap dump
104 |
105 | ### AndroidStudio ###
106 | # Covers files to be ignored for android development using Android Studio.
107 |
108 | # Built application files
109 | *.ap_
110 | *.aab
111 |
112 | # Files for the ART/Dalvik VM
113 | *.dex
114 |
115 | # Java class files
116 |
117 | # Generated files
118 | bin/
119 | gen/
120 | out/
121 |
122 | # Gradle files
123 |
124 | # Signing files
125 | .signing/
126 |
127 | # Local configuration file (sdk path, etc)
128 |
129 | # Google Services (e.g. APIs or Firebase)
130 | # google-services.json
131 |
132 | # Android Patch
133 |
134 | # External native build folder generated in Android Studio 2.2 and later
135 | .externalNativeBuild
136 |
137 | # NDK
138 | obj/
139 |
140 | # IntelliJ IDEA
141 | *.iws
142 | /out/
143 |
144 | # User-specific configurations
145 | .idea/caches/
146 | .idea/libraries/
147 | .idea/shelf/
148 | .idea/workspace.xml
149 | .idea/tasks.xml
150 | .idea/.name
151 | .idea/compiler.xml
152 | .idea/copyright/profiles_settings.xml
153 | .idea/encodings.xml
154 | .idea/misc.xml
155 | .idea/modules.xml
156 | .idea/scopes/scope_settings.xml
157 | .idea/dictionaries
158 | .idea/vcs.xml
159 | .idea/jsLibraryMappings.xml
160 | .idea/datasources.xml
161 | .idea/dataSources.ids
162 | .idea/sqlDataSources.xml
163 | .idea/dynamic.xml
164 | .idea/uiDesigner.xml
165 | .idea/assetWizardSettings.xml
166 | .idea/gradle.xml
167 | .idea/jarRepositories.xml
168 | .idea/navEditor.xml
169 |
170 | # Legacy Eclipse project files
171 | .cproject
172 | .settings/
173 |
174 | # Mobile Tools for Java (J2ME)
175 |
176 | # Package Files #
177 |
178 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
179 |
180 | ## Plugin-specific files:
181 |
182 | # mpeltonen/sbt-idea plugin
183 | .idea_modules/
184 |
185 | # JIRA plugin
186 | atlassian-ide-plugin.xml
187 |
188 | # Mongo Explorer plugin
189 | .idea/mongoSettings.xml
190 |
191 | # Crashlytics plugin (for Android Studio and IntelliJ)
192 | com_crashlytics_export_strings.xml
193 | crashlytics.properties
194 | crashlytics-build.properties
195 | fabric.properties
196 |
197 | ### AndroidStudio Patch ###
198 |
199 | !/gradle/wrapper/gradle-wrapper.jar
200 |
201 | # End of https://www.toptal.com/developers/gitignore/api/android,androidstudio,macos,windows,gradle,maven,firebase,kotlin,git,jenv
202 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/data/habitsDB/HabitsRepository.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.data.habitsDB
2 |
3 | import com.google.firebase.auth.FirebaseAuth
4 | import com.google.firebase.firestore.FirebaseFirestore
5 | import com.google.firebase.firestore.Query
6 | import com.mundocode.pomodoro.ui.screens.habits.model.HabitsModel
7 | import javax.inject.Inject
8 | import kotlinx.coroutines.CoroutineScope
9 | import kotlinx.coroutines.flow.Flow
10 | import kotlinx.coroutines.flow.firstOrNull
11 | import kotlinx.coroutines.flow.map
12 | import kotlinx.coroutines.launch
13 |
14 | class HabitsRepository @Inject constructor(
15 | private val habitsDao: HabitsDao,
16 | private val firestore: FirebaseFirestore,
17 | private val auth: FirebaseAuth,
18 | ) {
19 | private val userId: String? get() = auth.currentUser?.uid
20 |
21 | val habits: Flow> = habitsDao.getHabits().map { habitsEntityList ->
22 | habitsEntityList.map { habitsEntity ->
23 | HabitsModel(
24 | id = habitsEntity.id,
25 | title = habitsEntity.title,
26 | description = habitsEntity.description,
27 | )
28 | }
29 | }
30 |
31 | suspend fun addHabit(habit: HabitsModel) {
32 | val existingHabit = habitsDao.getHabitById(habit.id) // ✅ Método correcto en DAO
33 | if (existingHabit == null) { // ✅ Solo insertar si el hábito no existe
34 | habitsDao.addHabit(habit.toData())
35 | syncHabitWithFirestore(habit)
36 | }
37 | }
38 |
39 | suspend fun updateHabit(habit: HabitsModel) {
40 | habitsDao.updateHabit(habit.toData())
41 | syncHabitWithFirestore(habit)
42 | }
43 |
44 | suspend fun deleteHabit(habit: HabitsModel) {
45 | habitsDao.deleteHabit(habit.toData())
46 | deleteHabitFromFirestore(habit)
47 | }
48 |
49 | private fun syncHabitWithFirestore(habit: HabitsModel) {
50 | userId?.let { uid ->
51 | val habitRef = firestore.collection("users").document(uid)
52 | .collection("habits").document(habit.id.toString())
53 | habitRef.set(habit)
54 | .addOnSuccessListener {
55 | println("Habit successfully added to Firestore")
56 | }
57 | .addOnFailureListener { e ->
58 | println("Error adding habit to Firestore: $e")
59 | }
60 | }
61 | }
62 |
63 | private fun deleteHabitFromFirestore(habit: HabitsModel) {
64 | userId?.let { uid ->
65 | val habitRef = firestore.collection("users").document(uid)
66 | .collection("habits").document(habit.id.toString())
67 | habitRef.delete()
68 | .addOnSuccessListener {
69 | println("Habit successfully deleted from Firestore")
70 | }
71 | .addOnFailureListener { e ->
72 | println("Error deleting habit from Firestore: $e")
73 | }
74 | }
75 | }
76 |
77 | fun syncFromFirestore(scope: CoroutineScope, searchQuery: String) {
78 | userId?.let { uid ->
79 | val collectionRef = firestore.collection("users").document(uid).collection("habits")
80 | var query: Query = collectionRef.orderBy("title", Query.Direction.ASCENDING)
81 |
82 | if (searchQuery.isNotEmpty()) {
83 | query = query.whereGreaterThanOrEqualTo("title", searchQuery)
84 | .whereLessThanOrEqualTo("title", searchQuery + "\uf8ff")
85 | }
86 |
87 | query.addSnapshotListener { snapshot, e ->
88 | if (e != null || snapshot == null) return@addSnapshotListener
89 |
90 | scope.launch {
91 | val habitsList = snapshot.documents.mapNotNull { it.toObject(HabitsModel::class.java) }
92 |
93 | habitsList.forEach { habit ->
94 | val existingHabit = habitsDao.getHabits().firstOrNull()?.find { it.id == habit.id }
95 | if (existingHabit == null) { // ✅ Solo insertar si no existe
96 | habitsDao.addHabit(habit.toData())
97 | } else {
98 | habitsDao.updateHabit(habit.toData()) // ✅ Si existe, actualizarlo en lugar de insertarlo
99 | }
100 | }
101 | }
102 | }
103 | }
104 | }
105 | }
106 |
107 | fun HabitsModel.toData(): HabitsEntity = HabitsEntity(this.id, this.title, this.description)
108 |
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.android.application)
3 | alias(libs.plugins.kotlin.android)
4 | alias(libs.plugins.google.services)
5 | alias(libs.plugins.kotlin.compose)
6 | alias(libs.plugins.kotlin.parcelize)
7 | alias(libs.plugins.kotlin.serialize)
8 | alias(libs.plugins.ktlint.jlleitschuh)
9 | alias(libs.plugins.ksp)
10 | alias(libs.plugins.google.dagger.hilt)
11 | alias(libs.plugins.crashlytics)
12 | }
13 |
14 | android {
15 | namespace = "com.mundocode.pomodoro"
16 | compileSdk = 35
17 |
18 | defaultConfig {
19 | applicationId = "com.mundocode.pomodoro"
20 | minSdk = 25
21 | targetSdk = 35
22 | versionCode = 1
23 | versionName = "1.0"
24 |
25 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
26 | android.buildFeatures.buildConfig = true
27 | }
28 |
29 | buildTypes {
30 |
31 | forEach { buildType ->
32 | buildType.buildConfigField(
33 | "String",
34 | "WEB_CLIENT_ID",
35 | "\"${providers.gradleProperty("web_client_id").get()}\"",
36 | )
37 | }
38 |
39 | release {
40 | isMinifyEnabled = false
41 | proguardFiles(
42 | getDefaultProguardFile("proguard-android-optimize.txt"),
43 | "proguard-rules.pro",
44 | )
45 | }
46 | }
47 | compileOptions {
48 | sourceCompatibility = JavaVersion.VERSION_11
49 | targetCompatibility = JavaVersion.VERSION_11
50 | }
51 | kotlinOptions {
52 | jvmTarget = "11"
53 | }
54 | buildFeatures {
55 | compose = true
56 | }
57 | }
58 |
59 | dependencies {
60 | implementation(libs.kotlinx.serialization.core)
61 |
62 | // Android
63 | implementation(platform(libs.androidx.compose.bom))
64 | implementation(libs.bundles.androidBundle)
65 |
66 | // Livedata
67 |
68 | // Dagger Hilt
69 | implementation(libs.hilt.android)
70 | implementation(libs.hilt.android.navigation.compose)
71 | ksp(libs.hilt.android.compiler)
72 |
73 | // Firebase
74 | implementation(platform(libs.firebase.bom))
75 | implementation(libs.bundles.firebaseBundle)
76 |
77 | // Google
78 | implementation(libs.bundles.googleBundle)
79 |
80 | // Kiwi
81 | implementation(libs.core)
82 | // Icons
83 | implementation("androidx.compose.material:material-icons-extended:1.7.6")
84 |
85 | implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
86 |
87 | // Room
88 | implementation(libs.androidx.room.runtime)
89 | ksp(libs.androidx.room.compiler)
90 | implementation(libs.androidx.room.ktx)
91 |
92 | implementation("androidx.compose.ui:ui:1.7.8") // Asegúrate de usar la última versión de Compose
93 | implementation("com.google.accompanist:accompanist-appcompat-theme:0.30.1")
94 |
95 | // coil
96 | implementation("io.coil-kt:coil-compose:2.5.0")
97 |
98 | implementation("com.github.PhilJay:MPAndroidChart:v3.1.0") // Librería para gráficos
99 |
100 | // Timber
101 | implementation("com.jakewharton.timber:timber:5.0.1")
102 |
103 | implementation("com.airbnb.android:lottie-compose:6.1.0")
104 |
105 | implementation("com.google.code.gson:gson:2.11.0")
106 |
107 | implementation("androidx.datastore:datastore-preferences:1.1.3")
108 | implementation("androidx.datastore:datastore-core:1.1.3")
109 | implementation("androidx.datastore:datastore:1.1.3")
110 |
111 | testImplementation(libs.junit)
112 | androidTestImplementation(libs.androidx.ui.test.junit4)
113 | debugImplementation(libs.androidx.ui.tooling)
114 | debugImplementation(libs.androidx.ui.test.manifest)
115 | }
116 |
117 | ktlint {
118 | version.set("1.5.0")
119 | debug.set(true)
120 | verbose.set(true)
121 | android.set(false)
122 | outputToConsole.set(true)
123 | outputColorName.set("RED")
124 | ignoreFailures.set(false)
125 | enableExperimentalRules.set(true)
126 | // baseline.set(file("ktlint-baseline.xml"))
127 | reporters {
128 | reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.PLAIN)
129 | reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.CHECKSTYLE)
130 | reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.JSON)
131 | }
132 | filter {
133 | exclude("**/generated/**")
134 | include("**/kotlin/**")
135 | }
136 | }
137 |
138 | kotlin {
139 | sourceSets.configureEach {
140 | languageSettings.enableLanguageFeature("ExplicitBackingFields")
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/components/DialogPopUp.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.components
2 |
3 | import androidx.compose.foundation.layout.Arrangement
4 | import androidx.compose.foundation.layout.Column
5 | import androidx.compose.foundation.layout.Row
6 | import androidx.compose.foundation.layout.Spacer
7 | import androidx.compose.foundation.layout.fillMaxWidth
8 | import androidx.compose.foundation.layout.height
9 | import androidx.compose.foundation.layout.padding
10 | import androidx.compose.foundation.shape.RoundedCornerShape
11 | import androidx.compose.material3.Button
12 | import androidx.compose.material3.MaterialTheme
13 | import androidx.compose.material3.Surface
14 | import androidx.compose.material3.Text
15 | import androidx.compose.material3.TextField
16 | import androidx.compose.runtime.Composable
17 | import androidx.compose.runtime.getValue
18 | import androidx.compose.runtime.mutableStateOf
19 | import androidx.compose.runtime.saveable.rememberSaveable
20 | import androidx.compose.runtime.setValue
21 | import androidx.compose.ui.Alignment
22 | import androidx.compose.ui.Modifier
23 | import androidx.compose.ui.tooling.preview.Preview
24 | import androidx.compose.ui.unit.dp
25 | import androidx.compose.ui.window.Dialog
26 | import com.mundocode.pomodoro.ui.theme.PomodoroTheme
27 |
28 | @Composable
29 | fun DialogPopUp(show: Boolean, onDismiss: () -> Unit = {}, onTaskAdded: (String, String) -> Unit = { _, _ -> }) {
30 | var title by rememberSaveable { mutableStateOf("") }
31 | var description by rememberSaveable { mutableStateOf("") }
32 |
33 | if (show) {
34 | Dialog(onDismissRequest = { onDismiss() }) {
35 | Surface(shape = RoundedCornerShape(8.dp), shadowElevation = 8.dp) {
36 | Column(modifier = Modifier.padding(16.dp)) {
37 | Text(text = "Nuevo hábito")
38 |
39 | TextField(
40 | value = title,
41 | onValueChange = { title = it },
42 | singleLine = true,
43 | maxLines = 1,
44 | label = { Text("Title", color = MaterialTheme.colorScheme.inverseSurface) },
45 | )
46 |
47 | Spacer(modifier = Modifier.height(4.dp))
48 |
49 | TextField(
50 | value = description,
51 | onValueChange = { description = it },
52 | maxLines = 20,
53 | label = { Text("Description", color = MaterialTheme.colorScheme.inverseSurface) },
54 | )
55 |
56 | Spacer(modifier = Modifier.height(4.dp))
57 |
58 | Row(
59 | modifier = Modifier.fillMaxWidth(),
60 | horizontalArrangement = Arrangement.Center,
61 | ) {
62 | Column(
63 | modifier = Modifier
64 | .weight(1f)
65 | .padding(8.dp),
66 | verticalArrangement = Arrangement.Center,
67 | horizontalAlignment = Alignment.CenterHorizontally,
68 | ) {
69 | Button(
70 | onClick = {
71 | onTaskAdded(title, description)
72 | title = ""
73 | description = ""
74 | onDismiss()
75 | },
76 | modifier = Modifier.padding(end = 8.dp),
77 | ) {
78 | Text("Guardar")
79 | }
80 | }
81 | Column(
82 | modifier = Modifier
83 | .weight(1f)
84 | .padding(8.dp),
85 | verticalArrangement = Arrangement.Center,
86 | horizontalAlignment = Alignment.CenterHorizontally,
87 | ) {
88 | Button(onClick = { onDismiss() }) {
89 | Text("Cancelar")
90 | }
91 | }
92 | }
93 | }
94 | }
95 | }
96 | }
97 | }
98 |
99 | @Preview(showBackground = true)
100 | @Composable
101 | private fun DialogPopUpPreview() {
102 | PomodoroTheme {
103 | DialogPopUp(show = true)
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | agp = "8.9.0"
3 | coilCompose = "2.7.0"
4 | firebaseDatabaseKtx = "21.0.0"
5 | googleid = "1.1.1"
6 | googleServices = "4.4.2"
7 | kotlin = "2.1.0"
8 | ktlintJlleitschuh = "12.1.2"
9 | credentials = "1.3.0"
10 | coreKtx = "1.15.0"
11 | core = "0.10.0"
12 | junit = "4.13.2"
13 | junitVersion = "1.2.1"
14 | espressoCore = "3.6.1"
15 | firebaseBom = "33.10.0"
16 | googlePlayServicesAuth = "21.3.0"
17 | lifecycleRuntimeKtx = "2.8.7"
18 | activityCompose = "1.10.1"
19 | composeBom = "2025.02.00"
20 | navigationCompose = "2.8.8"
21 | hiltVersion = "2.55"
22 | runtimeLivedata = "1.7.8"
23 | androidHiltVersion = "1.2.0"
24 | kspVersion = "2.1.0-1.0.29"
25 | kotlinxSerializationCore = "1.7.3"
26 | roomRuntime = "2.6.1"
27 | crashlytics = "3.0.3"
28 | timber = "5.0.1"
29 |
30 | [libraries]
31 | androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
32 | androidx-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "runtimeLivedata" }
33 | androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
34 | androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
35 | androidx-runtime-livedata = { module = "androidx.compose.runtime:runtime-livedata", version.ref = "runtimeLivedata" }
36 | androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
37 | androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
38 | androidx-credentials = { module = " androidx.credentials:credentials-play-services-auth", version.ref = "credentials" }
39 | androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "roomRuntime" }
40 | androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "roomRuntime" }
41 | androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "roomRuntime" }
42 | androidx-ui = { group = "androidx.compose.ui", name = "ui" }
43 | androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
44 | androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
45 | androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
46 | androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
47 | androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
48 | androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
49 | androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigationCompose" }
50 | androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
51 | coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" }
52 | core = { module = "com.kiwi.navigation-compose.typed:core", version.ref = "core" }
53 | credentials = { module = "androidx.credentials:credentials", version.ref = "credentials" }
54 | firebase-bom = { module = "com.google.firebase:firebase-bom", version.ref = "firebaseBom" }
55 | firebase-analytics = { module = "com.google.firebase:firebase-analytics" }
56 | firebase-auth-ktx = { module = "com.google.firebase:firebase-auth-ktx" }
57 | firebase-crashlytics = { module = "com.google.firebase:firebase-crashlytics" }
58 | firebase-database-ktx = { module = "com.google.firebase:firebase-database-ktx", version.ref = "firebaseDatabaseKtx" }
59 | firebase-firestore = { module = "com.google.firebase:firebase-firestore" }
60 | firebase-messaging = { module = "com.google.firebase:firebase-messaging" }
61 | googleid = { module = "com.google.android.libraries.identity.googleid:googleid", version.ref = "googleid" }
62 | google-firebase-auth-ktx = { module = "com.google.firebase:firebase-auth-ktx" }
63 | hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hiltVersion" }
64 | hilt-android-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hiltVersion" }
65 | hilt-android-navigation-compose = { group = "androidx.hilt", name = "hilt-navigation-compose", version.ref = "androidHiltVersion" }
66 | junit = { group = "junit", name = "junit", version.ref = "junit" }
67 | kotlinx-serialization-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-core", version.ref = "kotlinxSerializationCore" }
68 | play-services-auth = { module = "com.google.android.gms:play-services-auth", version.ref = "googlePlayServicesAuth" }
69 | timber = { module = "com.jakewharton.timber:timber", version.ref = "timber" }
70 |
71 | [bundles]
72 | androidBundle = [
73 | "androidx-junit",
74 | "androidx-junit4",
75 | "androidx-espresso-core",
76 | "androidx-lifecycle-runtime-ktx",
77 | "androidx-activity-compose",
78 | "androidx-credentials",
79 | "androidx-core-ktx",
80 | "androidx-ui",
81 | "androidx-ui-graphics",
82 | "androidx-ui-tooling-preview",
83 | "androidx-material3",
84 | "androidx-navigation-compose",
85 | "credentials",
86 | "androidx-runtime-livedata"
87 | ]
88 | firebaseBundle = [
89 | "firebase-analytics",
90 | "firebase-auth-ktx",
91 | "firebase-firestore",
92 | "firebase-messaging",
93 | "firebase-crashlytics"
94 | ]
95 | googleBundle = [
96 | "google-firebase-auth-ktx",
97 | "googleid",
98 | "play-services-auth",
99 | ]
100 |
101 | [plugins]
102 | android-application = { id = "com.android.application", version.ref = "agp" }
103 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
104 | google-services = { id = "com.google.gms.google-services", version.ref = "googleServices" }
105 | kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
106 | kotlin-parcelize = { id = "org.jetbrains.kotlin.plugin.parcelize", version.ref = "kotlin" }
107 | kotlin-serialize = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
108 | ktlint-jlleitschuh = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlintJlleitschuh" }
109 | ksp = { id = "com.google.devtools.ksp", version.ref = "kspVersion" }
110 | google-dagger-hilt = { id = "com.google.dagger.hilt.android", version.ref = "hiltVersion" }
111 | crashlytics = { id = "com.google.firebase.crashlytics", version.ref = "crashlytics" }
112 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/loginScreen/LoginViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.loginScreen
2 |
3 | import androidx.activity.ComponentActivity
4 | import androidx.credentials.CredentialManager
5 | import androidx.credentials.CustomCredential
6 | import androidx.credentials.GetCredentialRequest
7 | import androidx.credentials.exceptions.GetCredentialCancellationException
8 | import androidx.lifecycle.ViewModel
9 | import androidx.lifecycle.viewModelScope
10 | import com.google.android.libraries.identity.googleid.GetGoogleIdOption
11 | import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
12 | import com.google.firebase.auth.AuthResult
13 | import com.google.firebase.auth.FirebaseAuth
14 | import com.google.firebase.auth.GoogleAuthProvider
15 | import com.google.firebase.auth.userProfileChangeRequest
16 | import com.mundocode.pomodoro.BuildConfig
17 | import dagger.hilt.android.lifecycle.HiltViewModel
18 | import kotlinx.coroutines.channels.awaitClose
19 | import kotlinx.coroutines.flow.Flow
20 | import kotlinx.coroutines.flow.MutableStateFlow
21 | import kotlinx.coroutines.flow.StateFlow
22 | import kotlinx.coroutines.flow.callbackFlow
23 | import kotlinx.coroutines.launch
24 | import kotlinx.coroutines.tasks.await
25 | import timber.log.Timber
26 | import java.security.MessageDigest
27 | import java.util.UUID
28 | import javax.inject.Inject
29 |
30 | @HiltViewModel
31 | class LoginViewModel @Inject constructor(
32 | private val firebaseAuth: FirebaseAuth,
33 | private val credentialManager: CredentialManager,
34 | ) : ViewModel() {
35 |
36 | val loginSuccess: StateFlow
37 | field = MutableStateFlow(false)
38 |
39 | val errorMessage: StateFlow
40 | field = MutableStateFlow(null)
41 |
42 | init {
43 | checkUserSession() // Verifica si hay una sesión activa al iniciar
44 | }
45 |
46 | fun registerWithEmail(name: String, email: String, password: String) {
47 | firebaseAuth.createUserWithEmailAndPassword(email, password)
48 | .addOnSuccessListener { authResult ->
49 | val user = authResult.user
50 | user?.updateProfile(
51 | userProfileChangeRequest {
52 | displayName = name // ✅ Guardar el nombre del usuario
53 | },
54 | )?.addOnCompleteListener {
55 | if (it.isSuccessful) {
56 | loginSuccess.value = true
57 | } else {
58 | errorMessage.value = it.exception?.message
59 | }
60 | }
61 | }
62 | .addOnFailureListener { exception ->
63 | errorMessage.value = exception.message
64 | }
65 | }
66 |
67 | fun loginWithEmail(email: String, password: String) {
68 | firebaseAuth.signInWithEmailAndPassword(email, password)
69 | .addOnSuccessListener {
70 | loginSuccess.value = true
71 | }
72 | .addOnFailureListener { exception ->
73 | errorMessage.value = exception.message
74 | }
75 | }
76 |
77 | private fun checkUserSession() {
78 | val currentUser = firebaseAuth.currentUser
79 | loginSuccess.value = currentUser != null
80 | if (currentUser != null) {
81 | Timber.tag("LoginViewModel").d("Usuario autenticado: ${currentUser.email}")
82 | } else {
83 | Timber.tag("LoginViewModel").d("No hay sesión activa")
84 | }
85 | }
86 |
87 | fun handleGoogleSignIn(activity: ComponentActivity) {
88 | viewModelScope.launch {
89 | googleSignIn(activity).collect { result ->
90 | result.fold(
91 | onSuccess = {
92 | Timber.tag("LoginViewModel").d("Google sign-in successful")
93 | loginSuccess.value = true
94 | },
95 | onFailure = { e ->
96 | Timber.tag("LoginViewModel").e(e, "Google sign-in failed")
97 | loginSuccess.value = false
98 | },
99 | )
100 | }
101 | }
102 | }
103 |
104 | private fun googleSignIn(activity: ComponentActivity): Flow> = callbackFlow {
105 | try {
106 | val ranNonce: String = UUID.randomUUID().toString()
107 | val bytes: ByteArray = ranNonce.toByteArray()
108 | val md: MessageDigest = MessageDigest.getInstance("SHA-256")
109 | val digest: ByteArray = md.digest(bytes)
110 | val hashedNonce: String = digest.fold("") { str, it -> str + "%02x".format(it) }
111 |
112 | val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
113 | .setFilterByAuthorizedAccounts(false)
114 | .setServerClientId(BuildConfig.WEB_CLIENT_ID)
115 | .setAutoSelectEnabled(true)
116 | .setNonce(hashedNonce)
117 | .build()
118 |
119 | val request: GetCredentialRequest = GetCredentialRequest.Builder()
120 | .addCredentialOption(googleIdOption)
121 | .build()
122 |
123 | val result = credentialManager.getCredential(activity, request)
124 | val credential = result.credential
125 |
126 | if (credential is CustomCredential &&
127 | credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL
128 | ) {
129 | val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
130 | val authCredential = GoogleAuthProvider.getCredential(googleIdTokenCredential.idToken, null)
131 | val authResult = firebaseAuth.signInWithCredential(authCredential).await()
132 | trySend(Result.success(authResult))
133 | } else {
134 | throw RuntimeException("Received an invalid credential type")
135 | }
136 | } catch (_: GetCredentialCancellationException) {
137 | trySend(Result.failure(Exception("Sign-in was canceled. Please try again.")))
138 | } catch (e: Exception) {
139 | trySend(Result.failure(e))
140 | }
141 | awaitClose { }
142 | }
143 | }
144 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/points/StoreViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.points
2 |
3 | import androidx.lifecycle.ViewModel
4 | import androidx.lifecycle.viewModelScope
5 | import com.google.firebase.Firebase
6 | import com.google.firebase.auth.auth
7 | import com.mundocode.pomodoro.data.pointsDB.PointsRepository
8 | import com.mundocode.pomodoro.data.storeDB.PurchasedItem
9 | import com.mundocode.pomodoro.data.storeDB.PurchasedItemsDao
10 | import com.mundocode.pomodoro.data.storeDB.PurchasedTheme
11 | import com.mundocode.pomodoro.model.local.StoreItem
12 | import com.mundocode.pomodoro.model.local.StoreTheme
13 | import com.mundocode.pomodoro.ui.theme.ThemePreferences
14 | import dagger.hilt.android.lifecycle.HiltViewModel
15 | import kotlinx.coroutines.flow.MutableStateFlow
16 | import kotlinx.coroutines.flow.StateFlow
17 | import kotlinx.coroutines.flow.collectLatest
18 | import kotlinx.coroutines.flow.map
19 | import kotlinx.coroutines.flow.stateIn
20 | import kotlinx.coroutines.launch
21 | import timber.log.Timber
22 | import javax.inject.Inject
23 |
24 | @HiltViewModel
25 | class StoreViewModel @Inject constructor(
26 | private val pointsRepository: PointsRepository,
27 | private val purchasedItemsDao: PurchasedItemsDao,
28 | private val themePreferences: ThemePreferences,
29 | ) : ViewModel() {
30 |
31 | val storeItems: StateFlow>
32 | field = MutableStateFlow(
33 | listOf(
34 | StoreItem(1, "Sonido Especial", 30, "Activa un sonido único al terminar un Pomodoro"),
35 | StoreItem(2, "Fondo Personalizado", 70, "Elige un fondo exclusivo para la app"),
36 | ),
37 | )
38 |
39 | val storeThemes: StateFlow>
40 | field = MutableStateFlow(
41 | listOf(
42 | StoreTheme(1, "Tema Oscuro", 50, "Tema oscuro para la app"),
43 | StoreTheme(2, "Tema Azul", 100, "Tema azul para la app"),
44 | StoreTheme(3, "Tema Rojo", 150, "Tema rojo para la app"),
45 | StoreTheme(4, "Tema Claro", 0, "Tema Claro para la app"),
46 | ),
47 | )
48 |
49 | val userPoints: StateFlow
50 | field = MutableStateFlow(0)
51 |
52 | val purchasedItems: StateFlow>
53 | field = MutableStateFlow>(emptyList())
54 |
55 | val purchasedThemes: StateFlow>
56 | field = MutableStateFlow>(emptyList())
57 |
58 | val unlockedThemes: StateFlow>
59 | field = MutableStateFlow(setOf())
60 |
61 | val selectedTheme: StateFlow
62 | field = MutableStateFlow("Tema Claro")
63 |
64 | init {
65 | viewModelScope.launch {
66 | themePreferences.selectedTheme.collect { theme ->
67 | selectedTheme.value = theme
68 | }
69 | }
70 | }
71 |
72 | fun loadUserPoints(userId: String) {
73 | viewModelScope.launch {
74 | pointsRepository.getUserPoints(userId).map { it.points }.stateIn(
75 | scope = viewModelScope,
76 | started = kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5_000),
77 | initialValue = 0,
78 | )
79 | }
80 | }
81 |
82 | fun loadPurchasedItems(userId: String) {
83 | viewModelScope.launch {
84 | // ✅ Verifica si existen temas en la base de datos
85 | val count = purchasedItemsDao.countUserPurchasedThemes(userId)
86 | Timber.tag("StoreViewModel").d("🔍 Temas comprados en la BD: $count") // ✅ Debug
87 |
88 | purchasedItemsDao.getUserPurchasedThemes(userId).collectLatest { themes ->
89 | Timber.tag("StoreViewModel").d("📌 Temas cargados desde la BD: $themes") // ✅ Debug
90 | purchasedThemes.value = themes
91 | unlockedThemes.value = themes.map { it.themeName }.toSet()
92 | }
93 | }
94 | }
95 |
96 | fun loadPurchasedThemes() {
97 | viewModelScope.launch {
98 | purchasedItemsDao.getUserPurchasedThemes(Firebase.auth.currentUser?.uid ?: "").collectLatest { themes ->
99 | val updatedThemes = themes.map { it.themeName }.toSet()
100 | unlockedThemes.value = updatedThemes + "Tema Claro" // ✅ Siempre incluir el tema "Claro"
101 | Timber.tag("StoreViewModel").d("🔓 Temas desbloqueados: $updatedThemes")
102 | }
103 | }
104 | }
105 |
106 | fun purchaseItem(userId: String, item: StoreItem): Boolean {
107 | if (userPoints.value >= item.price) {
108 | viewModelScope.launch {
109 | pointsRepository.spendPoints(userId, item.price)
110 | val purchasedItem = PurchasedItem(
111 | userId = userId,
112 | itemName = item.name,
113 | itemDescription = item.description,
114 | price = item.price,
115 | )
116 | purchasedItemsDao.insertPurchasedItem(purchasedItem)
117 | userPoints.value -= item.price
118 | loadPurchasedItems(userId)
119 | }
120 | return true
121 | }
122 | return false
123 | }
124 |
125 | fun purchaseTheme(userId: String, item: StoreTheme): Boolean {
126 | if (userPoints.value >= item.price) {
127 | viewModelScope.launch {
128 | pointsRepository.spendPoints(userId, item.price)
129 | val purchasedTheme = PurchasedTheme(
130 | userId = userId,
131 | themeName = item.name,
132 | price = item.price,
133 | themeDescription = item.description,
134 | )
135 | purchasedItemsDao.insertPurchasedTheme(purchasedTheme)
136 |
137 | userPoints.value -= item.price
138 |
139 | // ✅ Actualizar `unlockedThemes` inmediatamente en la UI antes de cargar de Room
140 | unlockedThemes.value = unlockedThemes.value + item.name
141 |
142 | // ✅ Asegurar que los datos persistan en la base de datos
143 | loadPurchasedItems(userId)
144 | }
145 | return true
146 | }
147 | return false
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/settings/SettingsScreen.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.settings
2 |
3 | import androidx.compose.foundation.background
4 | import androidx.compose.foundation.clickable
5 | import androidx.compose.foundation.layout.Arrangement
6 | import androidx.compose.foundation.layout.Box
7 | import androidx.compose.foundation.layout.Column
8 | import androidx.compose.foundation.layout.Row
9 | import androidx.compose.foundation.layout.fillMaxSize
10 | import androidx.compose.foundation.layout.fillMaxWidth
11 | import androidx.compose.foundation.layout.padding
12 | import androidx.compose.material.icons.Icons
13 | import androidx.compose.material.icons.automirrored.filled.ArrowBack
14 | import androidx.compose.material.icons.filled.ArrowBack
15 | import androidx.compose.material.icons.filled.KeyboardArrowDown
16 | import androidx.compose.material3.ButtonDefaults
17 | import androidx.compose.material3.DropdownMenu
18 | import androidx.compose.material3.DropdownMenuItem
19 | import androidx.compose.material3.Icon
20 | import androidx.compose.material3.MaterialTheme
21 | import androidx.compose.material3.OutlinedButton
22 | import androidx.compose.material3.Scaffold
23 | import androidx.compose.material3.Text
24 | import androidx.compose.runtime.Composable
25 | import androidx.compose.runtime.LaunchedEffect
26 | import androidx.compose.runtime.collectAsState
27 | import androidx.compose.runtime.getValue
28 | import androidx.compose.runtime.mutableStateOf
29 | import androidx.compose.runtime.remember
30 | import androidx.compose.runtime.setValue
31 | import androidx.compose.ui.Alignment
32 | import androidx.compose.ui.Modifier
33 | import androidx.compose.ui.unit.DpOffset
34 | import androidx.compose.ui.unit.dp
35 | import androidx.hilt.navigation.compose.hiltViewModel
36 | import androidx.navigation.NavHostController
37 | import com.google.firebase.auth.ktx.auth
38 | import com.google.firebase.ktx.Firebase
39 | import com.kiwi.navigationcompose.typed.navigate as kiwiNavigation
40 | import com.mundocode.pomodoro.core.navigation.Destinations
41 | import com.mundocode.pomodoro.ui.components.CustomTopAppBar
42 | import com.mundocode.pomodoro.ui.screens.SharedPointsViewModel
43 | import com.mundocode.pomodoro.ui.screens.points.StoreViewModel
44 | import com.mundocode.pomodoro.ui.theme.ThemeViewModel
45 | import kotlinx.serialization.ExperimentalSerializationApi
46 |
47 | @OptIn(ExperimentalSerializationApi::class)
48 | @Composable
49 | fun SettingsScreen(
50 | navController: NavHostController,
51 | sharedPointsViewModel: SharedPointsViewModel = hiltViewModel(),
52 | storeViewModel: StoreViewModel = hiltViewModel(),
53 | themeViewModel: ThemeViewModel = hiltViewModel(),
54 | ) {
55 | val user = Firebase.auth.currentUser
56 | val userPoints by sharedPointsViewModel.userPoints.collectAsState()
57 | // ✅ Asegurar que los temas desbloqueados se actualicen
58 | val unlockedThemes by storeViewModel.unlockedThemes.collectAsState()
59 | val currentTheme by themeViewModel.currentTheme.collectAsState()
60 | var expanded by remember { mutableStateOf(false) }
61 | var selectedOption by remember { mutableStateOf(currentTheme) }
62 |
63 | LaunchedEffect(Unit) {
64 | storeViewModel.loadPurchasedThemes() // ✅ Recargar los temas desbloqueados
65 | }
66 |
67 | Scaffold(
68 | topBar = {
69 | CustomTopAppBar(
70 | navController = navController,
71 | title = "Configuración",
72 | image = user?.photoUrl.toString(),
73 | navigationIcon = {
74 | Icon(
75 | imageVector = Icons.AutoMirrored.Filled.ArrowBack,
76 | contentDescription = "Back",
77 | modifier = Modifier.clickable {
78 | navController.popBackStack()
79 | },
80 | )
81 | },
82 | texto = "Puntos: $userPoints",
83 | onNavPoints = {
84 | navController.kiwiNavigation(Destinations.StoreScreen)
85 | },
86 | )
87 | },
88 | ) { padding ->
89 | Column(
90 | modifier = Modifier
91 | .padding(padding)
92 | .fillMaxSize(),
93 | ) {
94 | Row(
95 | modifier = Modifier
96 | .fillMaxWidth()
97 | .padding(10.dp),
98 | horizontalArrangement = Arrangement.SpaceBetween,
99 | verticalAlignment = Alignment.CenterVertically,
100 | ) {
101 | Text("Tema")
102 | ThemeSelector(
103 | unlockedThemes = unlockedThemes,
104 | currentTheme = currentTheme,
105 | onThemeSelected = { theme ->
106 | themeViewModel.changeTheme(theme)
107 | },
108 | )
109 | }
110 | }
111 | }
112 | }
113 |
114 | @Composable
115 | fun ThemeSelector(unlockedThemes: Set, currentTheme: String, onThemeSelected: (String) -> Unit) {
116 | var expanded by remember { mutableStateOf(false) }
117 | var selectedOption by remember { mutableStateOf(currentTheme) }
118 |
119 | Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
120 | // 🔹 Asegurar alineación correcta
121 | OutlinedButton(
122 | modifier = Modifier.padding(10.dp),
123 | colors = ButtonDefaults.buttonColors(MaterialTheme.colorScheme.surface),
124 | onClick = { expanded = true },
125 | ) {
126 | Row {
127 | Text(selectedOption, color = MaterialTheme.colorScheme.onSurface)
128 | Icon(Icons.Default.KeyboardArrowDown, contentDescription = "Dropdown")
129 | }
130 | }
131 |
132 | DropdownMenu(
133 | expanded = expanded,
134 | onDismissRequest = { expanded = false },
135 | offset = DpOffset(250.dp, 0.dp), // 🔹 Ajuste para mover el menú a la derecha si es necesario
136 | modifier = Modifier.background(MaterialTheme.colorScheme.surface),
137 | ) {
138 | unlockedThemes.forEach { theme ->
139 | DropdownMenuItem(
140 | text = { Text(theme) },
141 | onClick = {
142 | selectedOption = theme
143 | onThemeSelected(theme)
144 | expanded = false
145 | },
146 | )
147 | }
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/app/src/main/java/com/mundocode/pomodoro/ui/screens/homeScreen/HomeViewModel.kt:
--------------------------------------------------------------------------------
1 | package com.mundocode.pomodoro.ui.screens.homeScreen
2 |
3 | import android.util.Log
4 | import androidx.lifecycle.ViewModel
5 | import androidx.lifecycle.viewModelScope
6 | import com.mundocode.pomodoro.data.sessionDb.SessionDao
7 | import com.mundocode.pomodoro.data.sessionDb.SessionEntity
8 | import dagger.hilt.android.lifecycle.HiltViewModel
9 | import kotlinx.coroutines.flow.MutableStateFlow
10 | import kotlinx.coroutines.flow.StateFlow
11 | import kotlinx.coroutines.launch
12 | import timber.log.Timber
13 | import java.text.SimpleDateFormat
14 | import java.util.Calendar
15 | import java.util.Date
16 | import java.util.Locale
17 | import javax.inject.Inject
18 |
19 | @HiltViewModel
20 | class HomeViewModel @Inject constructor(private val sessionDao: SessionDao) : ViewModel() {
21 |
22 | val filter: StateFlow
23 | field = MutableStateFlow("Weekly")
24 |
25 | val sessionsData: StateFlow