content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.dktechh.noteclassic.di
import okhttp3.Interceptor
import okhttp3.Response
class AuthInterceptor() : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var req = chain.request()
// DONT INCLUDE API KEYS IN YOUR SOURCE CODE
val url = req.url().newBuilder().addQueryParameter("APPID", "your_key_here").build()
req = req.newBuilder().url(url).build()
return chain.proceed(req)
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/di/AuthInterceptor.kt | 3008030100 |
package com.dktechh.noteclassic.di
import android.app.Application
import androidx.room.Room
import com.dktechh.noteclassic.BuildConfig
import com.dktechh.noteclassic.domain.interactors.GetRemoteConfigUseCase
import com.dktechh.noteclassic.domain.repository.RepositoryImpl
import com.dktechh.noteclassic.data.repository.IRepository
import com.dktechh.noteclassic.data.repository.IRoomRepository
import com.dktechh.noteclassic.data.repository.RemoteConfigRepo
import com.dktechh.noteclassic.data.repository.RemoteConfigRepoImpl
import com.dktechh.noteclassic.data.room.NoteDatabase
import com.dktechh.noteclassic.data.room.dao.NoteDao
import com.dktechh.noteclassic.domain.interactors.DeleteNoteUseCase
import com.dktechh.noteclassic.domain.interactors.GetNoteByIdUseCase
import com.dktechh.noteclassic.domain.interactors.GetNotesUseCase
import com.dktechh.noteclassic.domain.interactors.InsertNoteUseCase
import com.dktechh.noteclassic.domain.interactors.UpdateNoteUseCase
import com.dktechh.noteclassic.domain.repository.RoomRepositoryImpl
import com.dktechh.noteclassic.presentation.MainViewModel
import com.dktechh.noteclassic.presentation.ui.addnote.AddNoteViewModel
import com.dktechh.noteclassic.presentation.ui.home.HomeViewModel
import kotlinx.coroutines.Dispatchers
import okhttp3.OkHttpClient
import org.koin.core.module.dsl.factoryOf
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
val viewModelModule = module {
singleOf(::MainViewModel)
singleOf(::HomeViewModel)
factoryOf(::AddNoteViewModel)
}
val repositoryModule = module {
single<RemoteConfigRepo> { RemoteConfigRepoImpl() }
single<IRepository> { RepositoryImpl(get(), get()) }
single<IRoomRepository> { RoomRepositoryImpl(get()) }
}
val useCaseModule = module {
factory { GetRemoteConfigUseCase(get(), get()) }
factory { GetNotesUseCase(get(), get()) }
factory { InsertNoteUseCase(get(), get()) }
factory { UpdateNoteUseCase(get(), get()) }
factory { DeleteNoteUseCase(get(), get()) }
factory { GetNoteByIdUseCase(get(), get()) }
}
val dispatcherModule = module {
factory { Dispatchers.Default }
}
fun provideDataBase(application: Application): NoteDatabase =
Room.databaseBuilder(
application,
NoteDatabase::class.java,
"note_database"
).allowMainThreadQueries().fallbackToDestructiveMigration().build()
fun provideDao(noteDatabase: NoteDatabase): NoteDao = noteDatabase.noteDao()
val dataBaseModule = module {
single { provideDataBase(get()) }
single { provideDao(get()) }
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/di/Module.kt | 4230080278 |
package com.dktechh.noteclassic.utils
val Any.TAG: String
get() {
val tag = javaClass.simpleName
return if (tag.length <= 23) tag else tag.substring(0, 23)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/utils/Extension.kt | 3870134437 |
package com.dktechh.noteclassic.utils
enum class TypeSort {
VERTICAL,
GRID,
STAGGERED_GRID,
}
enum class TypeChooseItem{
DELETE,
NORMAL
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/utils/Enums.kt | 2615259695 |
package com.dktechh.noteclassic.utils
/**
* @Author Mbuodile Obiosio
* https://linktr.ee/mbobiosio
*/
object DefaultConfigs {
fun getDefaultParams(): Map<String, Any> {
return hashMapOf(
ConfigKeys.FORCE_UPDATE to false,
ConfigKeys.DESCRIPTION to "Check update"
)
}
object ConfigKeys {
const val FORCE_UPDATE = "force_update"
const val DESCRIPTION = "message"
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/utils/DefaultConfigs.kt | 3675754283 |
package com.dktechh.noteclassic.utils
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
object Constants {
fun convertMillisToFormattedDate(timestamp: Long): String {
val formatter = SimpleDateFormat("dd-MM-yyyy hh:mm aaa", Locale.US)
val date = Date(timestamp)
return formatter.format(date)
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/utils/Constants.kt | 2464272797 |
package com.dktechh.noteclassic.data.repository
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.model.RemoteConfigs
import kotlinx.coroutines.flow.Flow
interface IRepository {
fun initConfigs()
fun getConfigs(): Flow<RemoteConfigs>
suspend fun getAllNote(): Flow<List<Note>>
suspend fun insertNote(note: Note): Long
suspend fun updateNote(note: Note)
suspend fun deleteNote(id: Long)
suspend fun getNoteById(id: Long): Flow<List<Note>>
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/repository/IRepository.kt | 593365592 |
package com.dktechh.noteclassic.data.repository
import android.util.Log
import com.dktechh.noteclassic.BuildConfig
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
import com.dktechh.noteclassic.utils.DefaultConfigs
import com.dktechh.noteclassic.utils.TAG
import com.dktechh.noteclassic.data.model.RemoteConfigs
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.update
class RemoteConfigRepoImpl : RemoteConfigRepo {
// Get remote config instance
private val remoteConfig = Firebase.remoteConfig
private val _configs = MutableStateFlow(RemoteConfigs())
private val configs = _configs.asStateFlow()
init {
initConfigs()
}
override fun initConfigs() {
/**
* [cacheInterval] defines the interval of fetches per hour.
* Use [remoteConfigSettings] to set the minimum fetch interval
* */
val cacheInterval = 3000L // 3000 milliseconds Long equivalent of 3 seconds
val minFetchInterval: Long = if (BuildConfig.DEBUG) {
0
} else {
cacheInterval
}
val configSettings = remoteConfigSettings {
fetchTimeoutInSeconds = 20L
minimumFetchIntervalInSeconds = minFetchInterval
}
// [END config settings]
/*
* Set the default parameters for Remote Config
* Your app will use these default values until there's a change in the firebase console
* */
remoteConfig.apply {
setConfigSettingsAsync(configSettings)
setDefaultsAsync(DefaultConfigs.getDefaultParams())
}
// [END default config]
/**
* Fetch updates from Firebase console
* */
remoteConfig.fetchAndActivate()
.addOnCompleteListener { taskResult ->
if (taskResult.isSuccessful) {
Log.d(TAG, "Successful: ${taskResult.result}")
_configs.update {
it.copy(
isShowTypeNote = remoteConfig.getBoolean("is_show_type_note")
)
}
} else {
Log.d(TAG, "Fail: ${taskResult.result}")
}
}.addOnFailureListener {
Log.d(TAG, "Exception: ${it.message}")
}
// [End fetch and activate]
}
/**
* @return [RemoteConfigs] remote values
* */
override fun getConfigs() = flow {
configs.collect {
emit(it)
}
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/repository/RemoteConfigRepoImpl.kt | 1253452509 |
package com.dktechh.noteclassic.data.repository
import com.dktechh.noteclassic.data.model.Note
import kotlinx.coroutines.flow.Flow
interface IRoomRepository {
suspend fun getAllNote(): Flow<List<Note>>
suspend fun insertNote(note: Note): Long
suspend fun updateNote(note: Note)
suspend fun deleteNote(id: Long)
suspend fun getNoteById(id: Long): Flow<List<Note>>
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/repository/IRoomRepository.kt | 3457867330 |
package com.dktechh.noteclassic.data.repository
import com.dktechh.noteclassic.data.model.RemoteConfigs
import kotlinx.coroutines.flow.Flow
interface RemoteConfigRepo {
fun initConfigs()
fun getConfigs(): Flow<RemoteConfigs>
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/repository/RemoteConfigRepo.kt | 1624478366 |
package com.dktechh.noteclassic.data.room.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.dktechh.noteclassic.data.model.Note
import kotlinx.coroutines.flow.Flow
@Dao
interface NoteDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(note: Note): Long
@Update
suspend fun update(note: Note)
@Delete
suspend fun delete(note: Note)
@Query("SELECT * from notes ORDER BY createTime DESC")
fun getAllNotes(): Flow<List<Note>>
@Query("SELECT * from notes WHERE id = :id")
fun getNoteById(id: Long): Flow<List<Note>>
@Query("DELETE from notes WHERE id = :id")
fun deleteNoteById(id: Long)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/room/dao/NoteDao.kt | 3380689030 |
package com.dktechh.noteclassic.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.room.dao.NoteDao
@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class NoteDatabase: RoomDatabase(){
abstract fun noteDao(): NoteDao
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/room/NoteDatabase.kt | 2434154834 |
package com.dktechh.noteclassic.data.model
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val title: String?,
val content: String?,
val createTime: Long,
val argbColor: Long?,
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/model/Note.kt | 2326198694 |
package com.dktechh.noteclassic.data.model
data class RemoteConfigs(
val isShowTypeNote: Boolean = true,
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/data/model/RemoteConfigs.kt | 910856329 |
package com.dktechh.noteclassic.domain.repository
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRoomRepository
import com.dktechh.noteclassic.data.room.dao.NoteDao
import kotlinx.coroutines.flow.Flow
class RoomRepositoryImpl(
private val noteDao: NoteDao
) : IRoomRepository {
override suspend fun getAllNote(): Flow<List<Note>> = noteDao.getAllNotes()
override suspend fun insertNote(note: Note): Long = noteDao.insert(note)
override suspend fun updateNote(note: Note) = noteDao.update(note)
override suspend fun deleteNote(id: Long) = noteDao.deleteNoteById(id)
override suspend fun getNoteById(id: Long): Flow<List<Note>> = noteDao.getNoteById(id)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/repository/RoomRepositoryImpl.kt | 50813634 |
package com.dktechh.noteclassic.domain.repository
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRepository
import com.dktechh.noteclassic.data.repository.IRoomRepository
import com.dktechh.noteclassic.data.repository.RemoteConfigRepo
import kotlinx.coroutines.flow.Flow
class RepositoryImpl(
private val remoteConfigRepo: RemoteConfigRepo,
private val iRoomRepository: IRoomRepository
): IRepository {
override fun initConfigs() = remoteConfigRepo.initConfigs()
override fun getConfigs() = remoteConfigRepo.getConfigs()
override suspend fun getAllNote(): Flow<List<Note>> = iRoomRepository.getAllNote()
override suspend fun insertNote(note: Note): Long = iRoomRepository.insertNote(note)
override suspend fun updateNote(note: Note) = iRoomRepository.updateNote(note)
override suspend fun deleteNote(id: Long) = iRoomRepository.deleteNote(id)
override suspend fun getNoteById(id: Long): Flow<List<Note>> = iRoomRepository.getNoteById(id)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/repository/RepositoryImpl.kt | 52776681 |
package com.dktechh.noteclassic.domain.navigation
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NamedNavArgument
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavDeepLink
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
@Composable
fun NavHostNoteApp(
navController: NavHostController,
startDestination: Destination,
modifier: Modifier = Modifier,
route: String? = null,
builder: NavGraphBuilder.() -> Unit
) {
androidx.navigation.compose.NavHost(
navController = navController,
startDestination = startDestination.fullRoute,
modifier = modifier,
route = route,
builder = builder
)
}
fun NavGraphBuilder.composable(
destination: Destination,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable AnimatedContentScope.(NavBackStackEntry) -> Unit
) {
composable(
route = destination.fullRoute,
arguments = arguments,
deepLinks = deepLinks,
content = content
)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/navigation/NavigationComposables.kt | 3453949175 |
package com.dktechh.noteclassic.domain.navigation
sealed class Destination(protected val route: String, vararg params: String) {
val fullRoute: String = if (params.isEmpty()) route else {
val builder = StringBuilder(route)
params.forEach { builder.append("/{${it}}") }
builder.toString()
}
sealed class NoArgumentsDestination(route: String) : Destination(route) {
operator fun invoke(): String = route
}
data object HomeScreen : NoArgumentsDestination("home")
data object AddNoteScreen : Destination("add_note", "id"){
private const val FIST_NAME_KEY = "id"
operator fun invoke(id: Long?): String = route.appendParams(
FIST_NAME_KEY to id
)
}
}
internal fun String.appendParams(vararg params: Pair<String, Any?>): String {
val builder = StringBuilder(this)
params.forEach {
it.second?.toString()?.let { arg ->
builder.append("/$arg")
}
}
return builder.toString()
}
| NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/navigation/MainGraph.kt | 631803777 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.repository.IRepository
import com.dktechh.noteclassic.data.model.RemoteConfigs
import domain.interactors.type.BaseUseCaseFlow
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
class GetRemoteConfigUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCaseFlow<Unit, RemoteConfigs>(dispatcher) {
override suspend fun build(param: Unit): Flow<RemoteConfigs> = repository.getConfigs()
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/GetRemoteConfigUseCase.kt | 3157712411 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRepository
import domain.interactors.type.BaseUseCase
import kotlinx.coroutines.CoroutineDispatcher
class UpdateNoteUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCase<Note, Unit>(dispatcher) {
override suspend fun block(param: Note): Unit = repository.updateNote(param)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/UpdateNoteUseCase.kt | 1193837154 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRepository
import domain.interactors.type.BaseUseCase
import kotlinx.coroutines.CoroutineDispatcher
class InsertNoteUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCase<Note, Long>(dispatcher) {
override suspend fun block(param: Note): Long = repository.insertNote(param)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/InsertNoteUseCase.kt | 3108953355 |
package domain.interactors.type
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
abstract class BaseUseCase<IN, OUT>(
private val dispatcher: CoroutineDispatcher,
) {
suspend operator fun invoke(param: IN): Result<OUT> = withContext(dispatcher) {
try {
Result.success(block(param))
} catch (ex: Exception) {
Result.failure(ex)
}
}
abstract suspend fun block(param: IN): OUT
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/type/BaseUseCase.kt | 320299150 |
package domain.interactors.type
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
abstract class BaseUseCaseFlow<IN, OUT>(
private val dispatcher: CoroutineDispatcher,
) {
suspend operator fun invoke(param: IN): Flow<Result<OUT>> = build(param)
.flowOn(dispatcher)
.map {
Result.success(it)
}.catch { emit(Result.failure(it)) }
protected abstract suspend fun build(param: IN): Flow<OUT>
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/type/BaseUseCaseFlow.kt | 1533529031 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRepository
import domain.interactors.type.BaseUseCaseFlow
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
class GetNotesUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCaseFlow<Unit, List<Note>>(dispatcher) {
override suspend fun build(param: Unit): Flow<List<Note>> = repository.getAllNote()
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/GetNotesUseCase.kt | 1936955022 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.data.repository.IRepository
import domain.interactors.type.BaseUseCaseFlow
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
class GetNoteByIdUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCaseFlow<Long, List<Note>>(dispatcher) {
override suspend fun build(param: Long): Flow<List<Note>> = repository.getNoteById(param)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/GetNoteByIdUseCase.kt | 616128100 |
package com.dktechh.noteclassic.domain.interactors
import com.dktechh.noteclassic.data.repository.IRepository
import domain.interactors.type.BaseUseCase
import kotlinx.coroutines.CoroutineDispatcher
class DeleteNoteUseCase(
private val repository: IRepository,
dispatcher: CoroutineDispatcher,
) : BaseUseCase<Long, Unit>(dispatcher) {
override suspend fun block(param: Long): Unit = repository.deleteNote(param)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/domain/interactors/DeleteNoteUseCase.kt | 1692734477 |
package com.dktechh.noteclassic.presentation
import androidx.lifecycle.ViewModel
class MainViewModel(
) : ViewModel() {
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/MainViewModel.kt | 371429539 |
package com.dktechh.noteclassic.presentation.ui.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.domain.interactors.DeleteNoteUseCase
import com.dktechh.noteclassic.domain.interactors.GetNotesUseCase
import com.dktechh.noteclassic.domain.interactors.GetRemoteConfigUseCase
import com.dktechh.noteclassic.utils.TypeChooseItem
import com.dktechh.noteclassic.utils.TypeSort
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class HomeViewModel(
val getNotesUseCase: GetNotesUseCase,
val deleteNoteUseCase: DeleteNoteUseCase,
val getRemoteConfigUseCase: GetRemoteConfigUseCase,
) : ViewModel() {
private val _uiState = MutableStateFlow(HomeUiState())
val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()
init {
viewModelScope.launch {
withContext(Dispatchers.IO) {
getRemoteConfigUseCase(Unit).collectLatest {
it.onSuccess { remoteConfigs ->
_uiState.update { state ->
state.copy(
isShowTypeNote = remoteConfigs.isShowTypeNote
)
}
}
}
}
}
getAllNote()
}
private fun getAllNote() {
viewModelScope.launch {
getNotesUseCase(Unit).collectLatest { result ->
result.onSuccess { notes ->
_uiState.update {
it.copy(
notes = notes
)
}
}
}
}
}
fun changeTypeSort() {
_uiState.update {
it.copy(
typeSort = when (uiState.value.typeSort) {
TypeSort.VERTICAL -> TypeSort.GRID
TypeSort.GRID -> TypeSort.STAGGERED_GRID
TypeSort.STAGGERED_GRID -> TypeSort.VERTICAL
}
)
}
}
fun changeTypeChooseItem(note: Note?) {
note?.let {
_uiState.update {
it.copy(
notesDelete = arrayListOf(note)
)
}
}
when (uiState.value.typeChooseItem) {
TypeChooseItem.DELETE -> {
_uiState.update {
it.copy(
typeChooseItem = TypeChooseItem.NORMAL
)
}
}
TypeChooseItem.NORMAL -> {
_uiState.update {
it.copy(
typeChooseItem = TypeChooseItem.DELETE
)
}
}
}
}
fun chooseItemNote(note: Note) {
val listNoteDelete = uiState.value.notesDelete.toMutableList()
if (listNoteDelete.contains(note)) {
listNoteDelete.remove(note)
} else {
listNoteDelete.add(note)
}
_uiState.update {
if (listNoteDelete.isEmpty()) {
it.copy(
notesDelete = listNoteDelete,
typeChooseItem = TypeChooseItem.NORMAL
)
} else {
it.copy(
notesDelete = listNoteDelete
)
}
}
}
fun deleteNote(notes: List<Note>) {
_uiState.update {
it.copy(
isProcessing = true
)
}
viewModelScope.launch {
notes.forEach {
deleteNoteUseCase(it.id)
}
getAllNote()
_uiState.update {
it.copy(
isProcessing = false,
typeChooseItem = TypeChooseItem.NORMAL,
)
}
}
}
}
data class HomeUiState(
val notes: List<Note> = arrayListOf(),
val typeSort: TypeSort = TypeSort.VERTICAL,
val typeChooseItem: TypeChooseItem = TypeChooseItem.NORMAL,
val notesDelete: List<Note> = arrayListOf(),
val isProcessing: Boolean = false,
val isShowTypeNote: Boolean = true,
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/home/HomeViewModel.kt | 3113001609 |
package com.dktechh.noteclassic.presentation.ui.home
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.navigation.NavHostController
import com.dktechh.noteclassic.R
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.domain.navigation.Destination
import com.dktechh.noteclassic.presentation.ui.component.Note
import com.dktechh.noteclassic.presentation.ui.theme.NoteClassicTheme
import com.dktechh.noteclassic.utils.TypeChooseItem
import com.dktechh.noteclassic.utils.TypeSort
import org.koin.androidx.compose.koinViewModel
@Composable
fun HomeScreen(navController: NavHostController) {
val homeViewModel: HomeViewModel = koinViewModel()
val uiState by homeViewModel.uiState.collectAsState()
HomeScreen(
notes = uiState.notes,
notesDelete = uiState.notesDelete,
onClickAddNote = {
navController.navigate(Destination.AddNoteScreen(-1))
},
onClickNote = { navController.navigate(Destination.AddNoteScreen(it.id)) },
onClickNoteDelete = homeViewModel::chooseItemNote,
onLongClickNote = homeViewModel::changeTypeChooseItem,
onClickChangeTypeSort = homeViewModel::changeTypeSort,
onClickDelete = homeViewModel::deleteNote,
onClickCloseDelete = { homeViewModel.changeTypeChooseItem(null) },
typeSort = uiState.typeSort,
modifier = Modifier.fillMaxSize(),
typeChooseItem = uiState.typeChooseItem,
isShowTypeSortNote = uiState.isShowTypeNote,
)
if (uiState.isProcessing) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Gray.copy(alpha = 0.5f)),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier.fillMaxSize(0.3f)
)
}
}
}
@Composable
fun HomeScreen(
modifier: Modifier = Modifier,
notes: List<Note>,
notesDelete: List<Note>,
onClickAddNote: () -> Unit,
onClickCloseDelete: () -> Unit,
onClickNote: (Note) -> Unit,
onClickNoteDelete: (Note) -> Unit,
onLongClickNote: (Note) -> Unit,
onClickDelete: (List<Note>) -> Unit,
onClickChangeTypeSort: () -> Unit,
typeSort: TypeSort = TypeSort.GRID,
typeChooseItem: TypeChooseItem = TypeChooseItem.NORMAL,
isShowTypeSortNote: Boolean = true,
) {
var openDialog by remember { mutableStateOf(false) }
ConstraintLayout(
modifier = modifier.background(color = colorResource(id = R.color.background_home))
) {
val (header, body) = createRefs()
Row(
modifier = Modifier
.fillMaxWidth()
.constrainAs(header) {
top.linkTo(parent.top)
}
.padding(5.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
if (notes.isNotEmpty()) {
IconButton(
modifier = Modifier.size(48.dp),
onClick = when (typeChooseItem) {
TypeChooseItem.DELETE -> onClickCloseDelete
TypeChooseItem.NORMAL -> onClickAddNote
}
) {
Icon(
imageVector = when (typeChooseItem) {
TypeChooseItem.DELETE -> Icons.Default.Close
TypeChooseItem.NORMAL -> Icons.Default.AddCircle
},
contentDescription = null
)
}
}
Text(
modifier = Modifier.weight(1f),
text = stringResource(id = R.string.app_name),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
fontWeight = FontWeight.W700
)
if (notes.isNotEmpty()) {
if (typeChooseItem == TypeChooseItem.NORMAL) {
if (isShowTypeSortNote) {
IconButton(
modifier = Modifier.size(48.dp),
onClick = { onClickChangeTypeSort() }
) {
Icon(
imageVector = Icons.Default.Menu,
contentDescription = null
)
}
}
} else {
IconButton(
modifier = Modifier.size(48.dp),
onClick = {
openDialog = true
}
) {
Icon(
imageVector = Icons.Default.Delete,
contentDescription = null
)
}
}
}
}
Box(modifier = Modifier
.padding(10.dp, 0.dp, 10.dp, 0.dp)
.constrainAs(body) {
bottom.linkTo(parent.bottom)
top.linkTo(header.bottom)
height = Dimension.fillToConstraints
}) {
if (notes.isNotEmpty()) {
LazyVerticalStaggeredGrid(
modifier = Modifier.fillMaxSize(),
columns = StaggeredGridCells.Fixed(
count = when (typeSort) {
TypeSort.VERTICAL -> 1
TypeSort.GRID -> 2
TypeSort.STAGGERED_GRID -> 2
}
),
verticalItemSpacing = 5.dp,
horizontalArrangement = Arrangement.spacedBy(5.dp)
) {
itemsIndexed(notes) { index, note ->
Note(
modifier = when (typeSort) {
TypeSort.VERTICAL -> Modifier.height(150.dp)
TypeSort.GRID -> Modifier.height(200.dp)
TypeSort.STAGGERED_GRID -> Modifier
}.padding(bottom = if (index == notes.size - 1 && typeSort == TypeSort.VERTICAL) 10.dp else 0.dp),
onClickNote = {
when (typeChooseItem) {
TypeChooseItem.DELETE -> {
onClickNoteDelete(it)
}
TypeChooseItem.NORMAL -> {
onClickNote(it)
}
}
}, note = note,
onLongClickNote = onLongClickNote,
typeChooseItem = typeChooseItem,
isSelected = notesDelete.contains(note)
)
}
}
} else {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 30.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
Text(
text = stringResource(id = R.string.title_empty_list_home_screen),
style = MaterialTheme.typography.titleMedium
)
FilledIconButton(
modifier = Modifier.size(48.dp),
onClick = onClickAddNote
) {
Icon(
imageVector = Icons.Default.AddCircle,
contentDescription = null
)
}
Spacer(modifier = Modifier.height(30.dp))
Image(
modifier = Modifier.fillMaxSize(),
painter = painterResource(id = R.drawable.img_empty_list),
contentDescription = null
)
}
}
}
}
if (openDialog) {
AlertDialog(
onDismissRequest = { openDialog = false },
title = { Text(stringResource(id = R.string.label_confirm_delete)) },
text = { Text(stringResource(id = R.string.detail_dialog_delete)) },
confirmButton = {
TextButton(
onClick = {
// Delete the note
onClickDelete(notesDelete)
openDialog = false
},
) {
Text(stringResource(id = R.string.label_delete))
}
},
dismissButton = {
TextButton(
onClick = { openDialog = false },
) {
Text(stringResource(id = R.string.label_cancel))
}
},
)
}
}
@Composable
@Preview(showSystemUi = true)
fun HomeScreenPreview() {
NoteClassicTheme {
HomeScreen(
notes = notesList,
notesDelete = notesList,
onClickAddNote = {/* no-op */ },
onClickNote = {/* no-op */ },
onClickNoteDelete = {/* no-op */ },
onClickDelete = {/* no-op */ },
onClickCloseDelete = {/* no-op */ },
onLongClickNote = {/* no-op */ },
onClickChangeTypeSort = {/* no-op */ },
modifier = Modifier.fillMaxSize()
)
}
}
val notesList = listOf(
Note(
title = "Sample Note 1",
content = "This is the first sample note content.",
createTime = System.currentTimeMillis(),
argbColor = 0xFF00FFFF
),
Note(
title = "Sample Note 2",
content = "Here's some more sample content for the second note.",
createTime = System.currentTimeMillis(),
argbColor = 0xFFFF0000
),
Note(
title = "Reminder",
content = "Don't forget to buy milk!",
createTime = System.currentTimeMillis(),
argbColor = 0xFFC0C0C0
),
Note(
title = " Idea",
content = "Write a blog post about time management techniques.",
createTime = System.currentTimeMillis(),
argbColor = 0xFFFFFF00
),
Note(
title = " Celebration",
content = "Let's celebrate Friday!",
createTime = System.currentTimeMillis(),
argbColor = 0xFFFFA500
),
Note(
title = "Shopping List",
content = "- Bread\n- Eggs\n- Cheese",
createTime = System.currentTimeMillis(),
argbColor = 0xFF800080
),
Note(
title = " Quote",
content = "\"The only way to do great work is to love what you do.\" - Steve Jobs",
createTime = System.currentTimeMillis(),
argbColor = 0xFFA020F0
),
Note(
title = "️♀️ Workout",
content = "Bicep curls, squats, lunges",
createTime = System.currentTimeMillis(),
argbColor = 0xFF00FF00
),
Note(
title = " Call Mom",
content = "Don't forget to call mom today!",
createTime = System.currentTimeMillis(),
argbColor = 0xFF808080
),
Note(
title = "✈️ Travel Plans",
content = "Start planning your next trip!",
createTime = System.currentTimeMillis(),
argbColor = 0xFFFF00FF
),
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/home/HomeScreen.kt | 2023457183 |
package com.dktechh.noteclassic.presentation.ui.addnote
import android.util.Log
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavHostController
import com.dktechh.noteclassic.R
import com.dktechh.noteclassic.presentation.ui.component.ColorCircleCard
import com.dktechh.noteclassic.presentation.ui.component.ComposableLifecycle
import com.dktechh.noteclassic.presentation.ui.component.colors
import com.dktechh.noteclassic.utils.Constants
import kotlinx.datetime.Clock
import org.koin.androidx.compose.koinViewModel
@Composable
fun AddNoteScreen(
navController: NavHostController
) {
val addNoteViewModel: AddNoteViewModel = koinViewModel()
val uiState by addNoteViewModel.uiState.collectAsState()
val TAG = "AddNoteScreen"
ComposableLifecycle { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> {
Log.d(TAG, "onCreate")
}
Lifecycle.Event.ON_START -> {
Log.d(TAG, "On Start")
}
Lifecycle.Event.ON_RESUME -> {
Log.d(TAG, "On Resume")
}
Lifecycle.Event.ON_PAUSE -> {
Log.d(TAG, "On Pause")
addNoteViewModel.insertOrUpdate()
}
Lifecycle.Event.ON_STOP -> {
Log.d(TAG, "On Stop")
}
Lifecycle.Event.ON_DESTROY -> {
Log.d(TAG, "On Destroy")
}
else -> {}
}
}
AddNoteScreen(
onBack = { navController.navigateUp() },
modifier = Modifier.fillMaxSize(),
titleString = uiState.titleString ?: "",
contentString = uiState.contentString ?: "",
onChangeValueTitle = addNoteViewModel::onChangeValueTitle,
onChangeValueContent = addNoteViewModel::onChangeValueContent,
listColorArgb = uiState.colors,
onClickColor = addNoteViewModel::selectedColorArgb,
colorArgbSelected = uiState.colorsArgbSelected,
createTime = uiState.timeCreate
)
}
@Composable
fun AddNoteScreen(
onBack: () -> Unit,
onChangeValueTitle: (String) -> Unit,
onChangeValueContent: (String) -> Unit,
modifier: Modifier = Modifier,
titleString: String,
contentString: String,
listColorArgb: List<Long>,
onClickColor: (Long) -> Unit,
colorArgbSelected: Long?,
createTime: Long? = null,
) {
Card(
modifier = modifier
.imePadding()
.animateContentSize(),
colors = CardDefaults.cardColors(
containerColor = colorArgbSelected?.let { Color(it) } ?: run { Color.White }
)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(10.dp),
verticalArrangement = Arrangement.SpaceBetween,
) {
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
IconButton(
modifier = Modifier.size(48.dp),
onClick = onBack
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = null
)
}
}
Column(
modifier = Modifier
.weight(1f),
) {
TextField(
modifier = Modifier.fillMaxWidth(),
value = titleString,
onValueChange = onChangeValueTitle,
colors = TextFieldDefaults.colors(
unfocusedContainerColor = Color.Transparent,
focusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
textStyle = MaterialTheme.typography.titleLarge.copy(
fontWeight = FontWeight.W700,
fontSize = 25.sp
),
placeholder = {
Text(
text = stringResource(id = R.string.title_hint),
style = MaterialTheme.typography.titleLarge.copy(
fontWeight = FontWeight.W700,
fontSize = 25.sp,
color = Color.Gray.copy(alpha = 0.7f)
)
)
},
singleLine = true,
keyboardOptions = KeyboardOptions.Default.copy(
capitalization = KeyboardCapitalization.Sentences
)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = createTime?.let {
Constants.convertMillisToFormattedDate(
it
)
} ?: run {
Constants.convertMillisToFormattedDate(
Clock.System.now().toEpochMilliseconds()
)
},
style = TextStyle(
color = Color.Gray
)
)
VerticalDivider(modifier = Modifier.height(10.dp))
Text(
text = stringResource(
id = R.string.regex_label_characters,
titleString.length + contentString.length
),
style = TextStyle(
color = Color.Gray
)
)
}
TextField(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.padding(top = 10.dp),
value = contentString,
onValueChange = onChangeValueContent,
colors = TextFieldDefaults.colors(
unfocusedContainerColor = Color.Transparent,
focusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
textStyle = MaterialTheme.typography.labelSmall.copy(
fontSize = 20.sp
),
placeholder = {
Text(
text = stringResource(id = R.string.content_hint),
style = MaterialTheme.typography.labelSmall.copy(
fontSize = 20.sp,
color = Color.Gray.copy(alpha = 0.7f)
)
)
},
keyboardOptions = KeyboardOptions.Default.copy(
capitalization = KeyboardCapitalization.Sentences
)
)
}
ColorCircleCard(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
listColorArgb = listColorArgb,
colorArgbSelected = colorArgbSelected,
onClickCircle = onClickColor
)
}
}
}
@Composable
@Preview(name = "AddNote")
private fun AddNoteScreenPreview() {
AddNoteScreen(
onBack = {/* no-op */ },
modifier = Modifier.fillMaxSize(),
titleString = "",
contentString = "",
onChangeValueTitle = {/* no-op */ },
onChangeValueContent = {/* no-op */ },
listColorArgb = colors,
colorArgbSelected = null,
onClickColor = {/* no-op */ }
)
}
| NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/addnote/AddNoteScreen.kt | 3808858058 |
package com.dktechh.noteclassic.presentation.ui.addnote
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.domain.interactors.DeleteNoteUseCase
import com.dktechh.noteclassic.domain.interactors.GetNoteByIdUseCase
import com.dktechh.noteclassic.domain.interactors.InsertNoteUseCase
import com.dktechh.noteclassic.domain.interactors.UpdateNoteUseCase
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
class AddNoteViewModel(
savedStateHandle: SavedStateHandle,
val insertNoteUseCase: InsertNoteUseCase,
val updateNoteUseCase: UpdateNoteUseCase,
val deleteNoteUseCase: DeleteNoteUseCase,
val getNoteByIdUseCase: GetNoteByIdUseCase,
) : ViewModel() {
private val _uiState = MutableStateFlow(AddNoteUiState())
val uiState: StateFlow<AddNoteUiState> = _uiState.asStateFlow()
init {
val idNote: String = checkNotNull(savedStateHandle["id"])
idNote.toLongOrNull()?.let {
viewModelScope.launch {
getNoteByIdUseCase(it).collectLatest {
it.onSuccess { notes ->
if (notes.isNotEmpty()) {
val note = notes[0]
_uiState.update { addNoteUiState ->
addNoteUiState.copy(
idNote = note.id,
titleString = note.title,
contentString = note.content,
timeCreate = note.createTime,
colorsArgbSelected = note.argbColor,
originalNote = note,
)
}
}
}
}
}
}
}
fun selectedColorArgb(colorArgb: Long) {
_uiState.update {
it.copy(
colorsArgbSelected = colorArgb
)
}
}
fun onChangeValueTitle(title: String) {
_uiState.update {
it.copy(
titleString = title
)
}
}
fun onChangeValueContent(content: String) {
_uiState.update {
it.copy(
contentString = content
)
}
}
private fun toNote(): Note {
return Note(
id = uiState.value.idNote ?: 0L,
title = uiState.value.titleString,
content = uiState.value.contentString,
argbColor = uiState.value.colorsArgbSelected,
createTime = Clock.System.now().toEpochMilliseconds()
)
}
fun insertOrUpdate() {
viewModelScope.launch {
if (uiState.value.titleString?.isNotEmpty() == true || uiState.value.contentString?.isNotEmpty() == true) {
val note = toNote()
uiState.value.idNote?.let {
if (uiState.value.originalNote?.title != note.title ||
uiState.value.originalNote?.content != note.content ||
uiState.value.originalNote?.argbColor != note.argbColor
) updateNoteUseCase(note)
} ?: run {
insertNoteUseCase(note).onSuccess { id ->
_uiState.update {
it.copy(
idNote = id
)
}
}
}
} else {
uiState.value.idNote?.let {
deleteNoteUseCase(it)
}
}
}
}
}
data class AddNoteUiState(
val idNote: Long? = null,
val titleString: String? = null,
val contentString: String? = null,
val colors: List<Long> = listOf(
0xFFFF9800L, // Cam
0xFF03A9F4L, // Xanh lam
0xFFE91E63L, // Hồng
0xFF673AB7L, // Tím đậm
0xFF3F51B5L, // Xanh lam đậm
0xFF4CAF50L, // Xanh lá cây đậm
0xFF9C27B0L, // Tím
0xFF00BCD4L, // Xanh lam nhạt
0xFFFFC107L, // Vàng
0xFF777777L, // Xám
),
val colorsArgbSelected: Long? = null,
val timeCreate: Long? = null,
val originalNote: Note? = null,
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/addnote/AddNoteViewModel.kt | 188267041 |
package com.dktechh.noteclassic.presentation.ui.component
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
@Composable
fun ComposableLifecycle(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit
) {
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { source, event ->
onEvent(source, event)
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/component/ComposableLifecycle.kt | 4044304584 |
package com.dktechh.noteclassic.presentation.ui.component
import androidx.compose.foundation.background
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import com.dktechh.noteclassic.R
@Composable
fun CircleCheckbox(selected: Boolean) {
val color = MaterialTheme.colorScheme
val imageVector =
if (selected) Icons.Filled.CheckCircle else ImageVector.vectorResource(id = R.drawable.ic_checkbox_24)
val tint = if (selected) color.primary.copy(alpha = 0.8f) else Color.White.copy(alpha = 0.8f)
val background = if (selected) Color.White else Color.Transparent
Icon(
imageVector = imageVector, tint = tint,
modifier = Modifier.background(background, shape = CircleShape),
contentDescription = "checkbox"
)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/component/CircleCheckbox.kt | 2850727078 |
package com.dktechh.noteclassic.presentation.ui.component
import android.graphics.Rect
import android.view.ViewTreeObserver
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalView
internal enum class Keyboard {
Opened, Closed
}
@Composable
internal fun keyboardAsState(): State<Keyboard> {
val keyboardState = remember { mutableStateOf(Keyboard.Closed) }
val view = LocalView.current
DisposableEffect(view) {
val onGlobalListener = ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect()
view.getWindowVisibleDisplayFrame(rect)
val screenHeight = view.rootView.height
val keypadHeight = screenHeight - rect.bottom
keyboardState.value = if (keypadHeight > screenHeight * 0.15) {
Keyboard.Opened
} else {
Keyboard.Closed
}
}
view.viewTreeObserver.addOnGlobalLayoutListener(onGlobalListener)
onDispose {
view.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalListener)
}
}
return keyboardState
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/component/StateConstant.kt | 4264583288 |
package com.dktechh.noteclassic.presentation.ui.component
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.dktechh.noteclassic.data.model.Note
import com.dktechh.noteclassic.utils.Constants
import com.dktechh.noteclassic.utils.TypeChooseItem
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Note(
modifier: Modifier = Modifier,
onClickNote: (Note) -> Unit,
note: Note,
onLongClickNote: (Note) -> Unit,
isSelected: Boolean = false,
typeChooseItem: TypeChooseItem = TypeChooseItem.NORMAL,
) {
Card(
modifier = modifier
.animateContentSize()
.clip(RoundedCornerShape(10.dp))
.combinedClickable(
onClick = { onClickNote(note) },
onLongClick = { onLongClickNote(note) }
),
colors = CardDefaults.cardColors(
containerColor = Color(note.argbColor ?: 0xFFDFDFDF)
)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(15.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.7f)
) {
note.title?.let {
if (it.isNotBlank()) {
Text(
text = it,
style = MaterialTheme.typography.titleLarge
)
}
}
Spacer(modifier = Modifier.height(5.dp))
Text(
text = note.content ?: "",
style = MaterialTheme.typography.bodySmall.copy(
fontWeight = FontWeight.Normal
),
maxLines = 7,
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.padding(bottom = 10.dp)
.fillMaxHeight()
)
}
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
contentAlignment = Alignment.BottomCenter
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Bottom
) {
Text(
modifier = Modifier.weight(1f),
text = Constants.convertMillisToFormattedDate(note.createTime),
style = MaterialTheme.typography.labelSmall,
)
if (typeChooseItem == TypeChooseItem.DELETE) {
CircleCheckbox(selected = isSelected)
}
}
}
}
}
}
@Preview(
name = "Note",
showSystemUi = true,
backgroundColor = 0xFFFFFF,
showBackground = true,
)
@Composable
private fun PreviewNote() {
Note(
onClickNote = {/* no-op */ },
note = Note(
title = "Grocery list",
content = "Milk, bread, eggs, cheese, bananasMilk, bread, eggs, cheese, bananasMilk, bread, eggs, cheese, bananasMilk, bread, eggs, cheese, bananasMilk, bread, eggs, cheese, bananasMilk, bread, eggs, cheese, bananas",
createTime = System.currentTimeMillis(),
argbColor = 0xFF800080
),
onLongClickNote = {/* no-op */ }
)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/component/CardNote.kt | 1961750927 |
package com.dktechh.noteclassic.presentation.ui.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun ColorCircleCard(
modifier: Modifier = Modifier,
listColorArgb: List<Long>,
colorArgbSelected: Long?,
onClickCircle: (Long) -> Unit,
paddingEveryCircle: Dp = 15.dp,
shape: RoundedCornerShape = RoundedCornerShape(40.dp)
) {
Card(
modifier = modifier,
shape = shape,
colors = CardDefaults.cardColors(
containerColor = Color.LightGray
)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
LazyRow(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.7f)
.padding(horizontal = 20.dp),
) {
items(listColorArgb) {
ColorCircle(
modifier = Modifier.padding(horizontal = paddingEveryCircle),
colorArgb = it,
isSelected = it == colorArgbSelected,
onClick = onClickCircle
)
}
}
}
}
}
@Composable
fun ColorCircle(
modifier: Modifier = Modifier,
colorArgb: Long,
isSelected: Boolean = false,
onClick: (Long) -> Unit,
) {
Card(
modifier = modifier.aspectRatio(1f),
onClick = { onClick(colorArgb) },
shape = CircleShape,
colors = CardDefaults.cardColors(
containerColor = Color(colorArgb)
),
border = BorderStroke(1.dp, Color.White)
) {
if (isSelected) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Image(
modifier = Modifier.fillMaxSize(fraction = 0.8f),
imageVector = Icons.Default.Check,
contentDescription = null,
)
}
}
}
}
@Preview(
name = "ColorCircleCard",
showSystemUi = true,
backgroundColor = 0xFF000000,
showBackground = true
)
@Composable
private fun PreviewColorCircleCard() {
ColorCircleCard(
modifier = Modifier
.fillMaxWidth()
.height(100.dp),
listColorArgb = colors,
colorArgbSelected = 0xFF4CAF50L,
onClickCircle = {/* no-op */ }
)
}
val colors = listOf(
0xFF777777L, // Xám
0xFF4CAF50L, // Xanh lá cây đậm
0xFFFF9800L, // Cam
0xFF9C27B0L, // Tím
0xFF00BCD4L, // Xanh lam nhạt
0xFFE91E63L, // Hồng
0xFF673AB7L, // Tím đậm
0xFF3F51B5L, // Xanh lam đậm
0xFFFFC107L, // Vàng
0xFF03A9F4L, // Xanh lam
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/component/ColorCircle.kt | 3290139080 |
package com.dktechh.noteclassic.presentation.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/theme/Color.kt | 3080637442 |
package com.dktechh.noteclassic.presentation.ui.theme
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun NoteClassicTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/theme/Theme.kt | 2574590197 |
package com.dktechh.noteclassic.presentation.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
),
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
) | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/ui/theme/Type.kt | 2433165810 |
package com.dktechh.noteclassic.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.dktechh.noteclassic.domain.navigation.Destination
import com.dktechh.noteclassic.domain.navigation.NavHostNoteApp
import com.dktechh.noteclassic.presentation.ui.home.HomeScreen
import com.dktechh.noteclassic.presentation.ui.theme.NoteClassicTheme
import com.dktechh.noteclassic.domain.navigation.composable
import com.dktechh.noteclassic.presentation.ui.addnote.AddNoteScreen
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
WindowCompat.setDecorFitsSystemWindows(window, false)
enableEdgeToEdge()
setContent {
val navController: NavHostController = rememberNavController()
NoteClassicTheme {
Scaffold(
contentWindowInsets = WindowInsets(0, 0, 0, 0)
) { scaffoldPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(scaffoldPadding)
.systemBarsPadding(),
color = MaterialTheme.colorScheme.background
) {
SetupNavigation(navController = navController)
}
}
}
}
}
}
@Composable
private fun SetupNavigation(navController: NavHostController) {
NavHostNoteApp(navController = navController, startDestination = Destination.HomeScreen) {
composable(Destination.HomeScreen) { HomeScreen(navController) }
composable(Destination.AddNoteScreen) { AddNoteScreen(navController) }
}
} | NoteClassic/app/src/main/java/com/dktechh/noteclassic/presentation/MainActivity.kt | 4033384476 |
package com.crestinfosystems_jinay.crestcentralsystems
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.crestinfosystems_jinay.crestcentralsystems", appContext.packageName)
}
} | Crest_Central_Systems/app/src/androidTest/java/com/crestinfosystems_jinay/crestcentralsystems/ExampleInstrumentedTest.kt | 3283452795 |
package com.crestinfosystems_jinay.crestcentralsystems
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Crest_Central_Systems/app/src/test/java/com/crestinfosystems_jinay/crestcentralsystems/ExampleUnitTest.kt | 4160473212 |
package com.crestinfosystems_jinay.crestcentralsystems
import android.app.Application
import com.crestinfosystems_jinay.crestcentralsystems.utils.SharedPreferencesManager
class CrestCentralSystem : Application() {
companion object {
lateinit var sharedPreferencesManager: SharedPreferencesManager
}
override fun onCreate() {
super.onCreate()
sharedPreferencesManager = SharedPreferencesManager(this)
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/CrestCentralSystem.kt | 3631826374 |
package com.crestinfosystems_jinay.crestcentralsystems.viewModel
import androidx.lifecycle.ViewModel
import com.crestinfosystems_jinay.crestcentralsystems.model.ReportingTo
import com.crestinfosystems_jinay.crestcentralsystems.model.user
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class HRMSUsersScreenViewModel : ViewModel() {
fun fetchDataFromApi(onSuccess: (MutableList<user>) -> Unit) {
CoroutineScope(Dispatchers.IO).launch {
val apiUrl =
"https://hrms.crestinfosystems.net/api/users?query=&status=active&filter=&timezone=Asia%2FCalcutta"
try {
lateinit var resultMap: Map<String, Any>
runBlocking {
resultMap = ApiUtils.get(apiUrl) as Map<String, Any>
}
if (resultMap != null && resultMap["status"] as Boolean) {
val applicationDetails =
(resultMap["data"] as Map<String, Any>)["Allusers"] as List<Map<String, Any>>
println(applicationDetails)
val listApplication = mutableListOf<user>()
for (i in applicationDetails) {
listApplication.add(
user(
id = (i["id"] as Double).toInt(),
first_name = i["first_name"].toString(),
last_name = i["last_name"].toString(),
reportingTo = ReportingTo(
first_name = (i["reportingTo"] as Map<String, Any>)["first_name"].toString(),
last_name = (i["reportingTo"] as Map<String, Any>)["last_name"].toString(),
id = ((i["reportingTo"] as Map<String, Any>)["id"] as Double).toInt()
),
designation_id = (i["designation_id"] as Double).toInt(),
email = i["email"].toString(),
status = i["status"].toString(),
employee_number = i["employee_number"].toString(),
contact_number = i["contact_number"].toString(),
alternate_contact_number = i["alternate_contact_number"].toString(),
role = (i["role"] as Double).toInt(),
joining_date = i["joining_date"].toString(),
designation_name = i["designation_name"].toString(),
role_name = i["role_name"].toString(),
onboarding_status = i["onboarding_status"].toString()
)
)
}
withContext(Dispatchers.Main) {
onSuccess(listApplication)
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
}
// {id=1.0,
// first_name=super,
// last_name=admin,
// designation_id=34.0,
// [email protected], status=active, employee_number=E001, contact_number=9925787865, alternate_contact_number=8511869145, role=11.0, joining_date=2010-01-04, reportingTo={id=1.0, first_name=super, last_name=admin}, designation_name=Admin Manager, role_name=Admin, onboarding_status=complete}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/viewModel/HRMSUsersScreenViewModel.kt | 1735822595 |
package com.crestinfosystems_jinay.crestcentralsystems.viewModel
import androidx.lifecycle.ViewModel
class HRMSDashboardViewModel : ViewModel() {
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/viewModel/HRMSDashboardViewModel.kt | 283199061 |
package com.crestinfosystems_jinay.crestcentralsystems.viewModel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.crestinfosystems_jinay.crestcentralsystems.Network.AuthApi
class LoginViewModel : ViewModel() {
val email = MutableLiveData<String>()
val password = MutableLiveData<String>()
val isCorrect = MutableLiveData(false)
fun SignIn(onSuccess: (Map<String, Any>?) -> Unit, onApiFail: (String) -> Unit) {
if (isCorrect.value ?: false) {
Log.d("Email", email.value.toString())
Log.d("Password", password.value.toString())
AuthApi.login(email = email.value.toString(),
password = password.value.toString(),
onError = {},
onSuccess = {
onSuccess(it)
},
onApiFail = {
onApiFail(it)
}
)
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/viewModel/LoginViewModel.kt | 205046351 |
package com.crestinfosystems_jinay.crestcentralsystems.viewModel
import androidx.lifecycle.ViewModel
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.model.dashboard_application
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class DashboardViewModel : ViewModel() {
fun fetchData(onSuccess: (MutableList<dashboard_application>) -> Unit) {
CoroutineScope(Dispatchers.IO).launch {
val id = CrestCentralSystem.sharedPreferencesManager.id
val apiUrl =
"https://central.crestinfosystems.net/api/users/${id.toString()}/applications"
try {
lateinit var resultMap: Map<String, Any>
runBlocking {
resultMap = ApiUtils.get(apiUrl) as Map<String, Any>
}
if (resultMap != null && resultMap["status"] as Boolean) {
val applicationDetails =
(resultMap["data"] as Map<String, Any>)["application_details"] as List<Map<String, Any>>
println(applicationDetails)
val listApplication = mutableListOf<dashboard_application>()
for (i in applicationDetails) {
listApplication.add(
dashboard_application(
app_id = (i["app_id"] as Double).toInt(),
application_name = i["application_name"].toString(),
app_key = i["app_key"].toString(),
app_url = i["app_url"].toString(),
designation = i["designation"],
img_path = i["img_path"].toString()
)
)
}
withContext(Dispatchers.Main) {
onSuccess(listApplication)
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/viewModel/DashboardViewModel.kt | 1888995741 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.Auth
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.crestinfosystems_jinay.crestcentralsystems.R
import com.crestinfosystems_jinay.crestcentralsystems.databinding.ActivityLoginBinding
import com.crestinfosystems_jinay.crestcentralsystems.ui.dashboard.Dashboard
import com.crestinfosystems_jinay.crestcentralsystems.viewModel.LoginViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
@Suppress("UNCHECKED_CAST")
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private val viewModel: LoginViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_login)
binding.lifecycleOwner = this
binding.viewModel = viewModel
binding.updateBtn.setOnClickListener {
if (viewModel.isCorrect.value!!) {
viewModel.SignIn(
onApiFail = { errormessage ->
runOnUiThread {
val bottomSheetDialog = BottomSheetDialog(this)
bottomSheetDialog.setContentView(R.layout.bottom_sheet_error_view)
bottomSheetDialog.findViewById<TextView>(R.id.error_message)?.text =
errormessage
bottomSheetDialog.findViewById<androidx.cardview.widget.CardView>(R.id.cancel_button)
?.setOnClickListener {
bottomSheetDialog.cancel()
binding.textInputLayoutEmailEdit.setText("")
binding.textInputLayoutPassEdit.setText("")
}
bottomSheetDialog.show()
}
},
onSuccess = {
val intent = Intent(this, Dashboard::class.java)
startActivity(intent)
this.finish()
}
)
} else {
Toast.makeText(this, "Please Enter Correct Value", Toast.LENGTH_SHORT).show()
}
}
onTextEdit()
}
fun runOnUiThread(action: () -> Unit) {
Handler(Looper.getMainLooper()).post(action)
}
private fun isValidEmail(mobile: String): Boolean {
val pattern = Regex("^[a-zA-Z0-9_.+-]+@crestinfosystems\\.com\$")
return pattern.containsMatchIn(mobile)
}
private fun onTextEdit() {
// binding?.textInputLayoutMobilenumEdit?.setOnFocusChangeListener { v, hasFocus ->
// binding?.textInputLayoutMobilenum?.isHintEnabled = !hasFocus
// }
// binding?.textInputLayoutOrganizationEdit?.setOnFocusChangeListener { v, hasFocus ->
// binding?.textInputLayoutOrganization?.isHintEnabled = !hasFocus
// }
binding.textInputLayoutEmailEdit.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
viewModel.email.value = s.toString()
if (!isValidEmail(s.toString())) {
viewModel.isCorrect.value = false
binding.textInputLayoutEmail.error = "Invalid EMAIL"
} else {
viewModel.isCorrect.value = true
binding.textInputLayoutEmail.error = null
}
}
})
binding.textInputLayoutPassEdit.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
override fun afterTextChanged(s: Editable?) {
viewModel.password.value = s.toString()
if (s.toString().length > 1) {
binding?.textInputLayoutPass?.error = null
viewModel.isCorrect.value = true
} else {
binding?.textInputLayoutPass?.error = "Enter Correct Organization Name"
viewModel.isCorrect.value = false
}
}
})
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/Auth/LoginActivity.kt | 4136577309 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.dashboard
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.R
import com.crestinfosystems_jinay.crestcentralsystems.databinding.ActivityHrmsDashboardBinding
import com.crestinfosystems_jinay.crestcentralsystems.ui.Auth.LoginActivity
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment.HrmsHomeScreen
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment.HrmsLeavesScreen
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment.HrmsPoliciesScreen
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment.HrmsUsersScreen
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.subscreens.hrms_holidays_screen
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.subscreens.hrms_important_contacts
import com.crestinfosystems_jinay.crestcentralsystems.viewModel.HRMSDashboardViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
class HRMS_Dashboard : AppCompatActivity() {
private lateinit var binding: ActivityHrmsDashboardBinding
private val homeFragment = HrmsHomeScreen()
private val leavesFragment = HrmsLeavesScreen()
private val policiesFragment = HrmsPoliciesScreen()
private val usersFragment = HrmsUsersScreen()
private val viewModel: HRMSDashboardViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_hrms_dashboard)
binding.lifecycleOwner = this
binding.hrmsDashboardViewModel = viewModel
setBottomNavBarListner()
setnavDrawer()
setCurrentFragment(homeFragment)
binding.drawerIcon.setOnClickListener {
binding.drawerLayout.openDrawer(GravityCompat.START)
}
}
private fun setBottomNavBarListner() {
binding.tab1.setOnClickListener {
setCurrentFragment(homeFragment)
setScreenIndicator(1)
}
binding.tab2.setOnClickListener {
setCurrentFragment(leavesFragment)
setScreenIndicator(2)
}
binding.tab3.setOnClickListener {
setCurrentFragment(policiesFragment)
setScreenIndicator(3)
}
binding.tab4.setOnClickListener {
setCurrentFragment(usersFragment)
setScreenIndicator(4)
}
}
private fun setScreenIndicator(currentScreen: Int) {
when (currentScreen) {
1 -> {
binding.tab1.setColorFilter(
ContextCompat.getColor(this, R.color.selected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab2.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab3.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab4.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
}
2 -> {
binding.tab2.setColorFilter(
ContextCompat.getColor(this, R.color.selected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab1.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab3.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab4.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
}
3 -> {
binding.tab3.setColorFilter(
ContextCompat.getColor(this, R.color.selected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab2.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab1.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab4.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
}
4 -> {
binding.tab4.setColorFilter(
ContextCompat.getColor(this, R.color.selected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab2.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab3.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
binding.tab1.setColorFilter(
ContextCompat.getColor(this, R.color.unselected_icon),
PorterDuff.Mode.SRC_IN
)
}
}
}
private fun setnavDrawer() {
val headerView = binding.navView.getHeaderView(0)
val username = headerView.findViewById<TextView>(R.id.user_name)
username.text = CrestCentralSystem.sharedPreferencesManager.userName
val useremail = headerView.findViewById<TextView>(R.id.user_email)
useremail.text = CrestCentralSystem.sharedPreferencesManager.email
binding.navView.setNavigationItemSelectedListener { menuItem ->
when (menuItem.itemId) {
R.id.hrms_drawer_signout -> {
signOut()
false
}
R.id.hrms_drawer_holiday -> {
val intent = Intent(this, hrms_holidays_screen::class.java)
startActivity(intent)
false
}
R.id.hrms_drawer_imp_contects -> {
val intent = Intent(this, hrms_important_contacts::class.java)
startActivity(intent)
false
}
else -> false
}
}
}
private fun signOut() {
try {
val builder = AlertDialog.Builder(this@HRMS_Dashboard)
builder.setMessage("")
builder.setTitle("Alert !")
builder.setCancelable(false)
builder.setPositiveButton(
"Yes"
) { dialog: DialogInterface?, which: Int ->
CrestCentralSystem.sharedPreferencesManager.accessToken = null
val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
}
builder.setNegativeButton(
"No"
) { dialog: DialogInterface, which: Int ->
dialog.cancel()
}
val alertDialog = builder.create()
alertDialog.show()
} catch (e: Exception) {
val bottomSheetDialog = BottomSheetDialog(this)
bottomSheetDialog.setContentView(R.layout.bottom_sheet_error_view)
bottomSheetDialog.findViewById<TextView>(R.id.error_message)?.text =
"Failed to Signout! Try again."
bottomSheetDialog.findViewById<androidx.cardview.widget.CardView>(R.id.cancel_button)
?.setOnClickListener {
bottomSheetDialog.cancel()
}
bottomSheetDialog.show()
}
}
private fun setCurrentFragment(fragment: Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.flFragment, fragment)
commit()
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/dashboard/HRMS_Dashboard.kt | 3582970908 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.adapter.HRMSPoliciesAdapter
import com.crestinfosystems_jinay.crestcentralsystems.databinding.FragmentHrmsPoliciesScreenBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.Policies
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class HrmsPoliciesScreen : Fragment() {
lateinit var binding: FragmentHrmsPoliciesScreenBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHrmsPoliciesScreenBinding.inflate(layoutInflater)
val layoutManager: RecyclerView.LayoutManager =
LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
binding.recyclerViewAdapter.layoutManager = layoutManager
fetchData()
return binding.root
}
private fun fetchData() {
CoroutineScope(Dispatchers.IO).launch {
val apiUrl =
"https://hrms.crestinfosystems.net/api/users/policies?policy_category=Company+Policies&timezone=Asia%2FCalcutta"
try {
lateinit var resultMap: Map<String, Any>
runBlocking {
resultMap = ApiUtils.get(apiUrl) as Map<String, Any>
}
if (resultMap != null && resultMap["status"] as Boolean) {
val applicationDetails =
(resultMap["data"] as List<Map<String, Any>>)
println(applicationDetails)
val listApplication = mutableListOf<Policies>()
for (i in applicationDetails) {
listApplication.add(
Policies(
title = i["policy_title"].toString(),
details = i["policy_detail"].toString()
)
)
}
withContext(Dispatchers.Main) {
val dashboardAdapter = context?.let { context ->
HRMSPoliciesAdapter(listApplication, context)
}
binding.recyclerViewAdapter.adapter = dashboardAdapter
binding.progressCircular.visibility = View.GONE
binding.recyclerViewAdapter.visibility = View.VISIBLE
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/Fragment/HrmsPoliciesScreen.kt | 1463551255 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.anychart.AnyChart
import com.anychart.chart.common.dataentry.DataEntry
import com.anychart.chart.common.dataentry.ValueDataEntry
import com.anychart.chart.common.listener.Event
import com.anychart.chart.common.listener.ListenersInterface
import com.anychart.enums.Align
import com.anychart.enums.LegendLayout
import com.crestinfosystems_jinay.crestcentralsystems.databinding.FragmentHrmsHomeScreenBinding
class HrmsHomeScreen : Fragment() {
lateinit var binding: FragmentHrmsHomeScreenBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentHrmsHomeScreenBinding.inflate(layoutInflater)
// val entries = listOf(
// PieEntry(187f, "Developer"),
// PieEntry(4f, "Designer"),
// PieEntry(14f, "QA"),
// PieEntry(10f, "Marketing and Sales"),
// PieEntry(5f, "HR"),
// PieEntry(4f, "Management"),
// PieEntry(2f, "Account")
// )
// val dataSet = PieDataSet(entries, "Election Results")
// dataSet.colors = ColorTemplate.COLORFUL_COLORS.toList()
// dataSet.valueTextSize = 15f
// binding.pieChart.setDrawEntryLabels(false)
// binding.pieChart.setUsePercentValues(true)
// binding.pieChart.getDescription().setEnabled(true)
// binding.pieChart.description.text = "Total User of HRMS"
// binding.pieChart.setExtraOffsets(5f, 10f, 5f, 5f)
//
// // on below line we are setting drag for our pie chart
// binding.pieChart.setDragDecelerationFrictionCoef(0.95f)
//
// // on below line we are setting hole
// // and hole color for pie chart
// binding.pieChart.setDrawHoleEnabled(true)
// binding.pieChart.setHoleColor(Color.WHITE)
//
// // on below line we are setting circle color and alpha
// binding.pieChart.setTransparentCircleColor(Color.WHITE)
// binding.pieChart.setTransparentCircleAlpha(110)
//
// // on below line we are setting hole radius
// binding.pieChart.setHoleRadius(58f)
// binding.pieChart.setTransparentCircleRadius(61f)
//
// // on below line we are setting center text
// binding.pieChart.setDrawCenterText(true)
//
// // on below line we are setting
// // rotation for our pie chart
// binding.pieChart.setRotationAngle(0f)
//
// // enable rotation of the pieChart by touch
// binding.pieChart.setRotationEnabled(true)
// binding.pieChart.setHighlightPerTapEnabled(true)
//
// // on below line we are setting animation for our pie chart
// binding.pieChart.animateY(1400, Easing.EaseInOutQuad)
//
// // on below line we are disabling our legend for pie chart
// binding.pieChart.legend.isEnabled = true
// binding.pieChart.setEntryLabelColor(Color.BLACK)
// binding.pieChart.setEntryLabelTextSize(15f)
// val data = PieData(dataSet)
// binding.pieChart.data = data
// binding.pieChart.invalidate() // Refreshes the chart
val pie = AnyChart.pie()
pie.setOnClickListener(object :
ListenersInterface.OnClickListener(arrayOf<String>("x", "value")) {
override fun onClick(event: Event) {
}
})
val data: MutableList<DataEntry> = ArrayList()
data.add(ValueDataEntry("Developer", 187))
data.add(ValueDataEntry("Designer", 4))
data.add(ValueDataEntry("QA", 14))
data.add(ValueDataEntry("Marketing and Sales", 10))
data.add(ValueDataEntry("HR", 5))
data.add(ValueDataEntry("Management", 4))
data.add(ValueDataEntry("Account", 2))
pie.data(data)
pie.title("Active Users of HRMS")
pie.labels().position("outside")
pie.legend().title().enabled(true)
pie.legend().title()
.text("Total Users (226)")
.padding(0.0, 0.0, 10.0, 0.0)
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL)
.align(Align.CENTER)
binding.anyChartView.setChart(pie)
return binding.root
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/Fragment/HrmsHomeScreen.kt | 3279983812 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.adapter.HRMSUsersListAdapter
import com.crestinfosystems_jinay.crestcentralsystems.databinding.DetsilsUserViewBinding
import com.crestinfosystems_jinay.crestcentralsystems.databinding.FragmentHrmsUsersScreenBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.user
import com.crestinfosystems_jinay.crestcentralsystems.viewModel.HRMSUsersScreenViewModel
class HrmsUsersScreen : Fragment() {
private lateinit var binding: FragmentHrmsUsersScreenBinding
private lateinit var viewModel: HRMSUsersScreenViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(
inflater,
com.crestinfosystems_jinay.crestcentralsystems.R.layout.fragment_hrms_users_screen,
container,
false
)
viewModel = HRMSUsersScreenViewModel()
val view: View = binding.root
binding.hrmsUsersScreen = viewModel
val layoutManager: RecyclerView.LayoutManager =
LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
binding.recyclerViewAdapter.layoutManager = layoutManager
viewModel.fetchDataFromApi { list ->
addDataInAdapter(list)
}
return view
}
@SuppressLint("SetTextI18n")
private fun addDataInAdapter(list: MutableList<user>) {
val dashboardAdapter = context?.let { context ->
HRMSUsersListAdapter(list, context) { user ->
dialogBox(user)
}
}
binding.recyclerViewAdapter.adapter = dashboardAdapter
binding.progressCircular.visibility = View.GONE
binding.recyclerViewAdapter.visibility = View.VISIBLE
}
private fun dialogBox(user: user) {
val builder = AlertDialog.Builder(context)
builder.setTitle(user.first_name + " " + user.last_name)
val daialogBinding: DetsilsUserViewBinding =
DetsilsUserViewBinding.inflate(layoutInflater)
builder.setView(daialogBinding.root)
daialogBinding.empCall.setOnClickListener {
var intent = Intent(Intent.ACTION_VIEW, Uri.parse("tel:${user.contact_number}"))
startActivity(intent)
}
daialogBinding.empEmail.setOnClickListener {
var intent = Intent(Intent.ACTION_VIEW, Uri.parse("mailto:${user.email}"))
startActivity(intent)
}
daialogBinding.designationName.text = user.designation_name.toString()
daialogBinding.employeeId.text = "Employee Id - ${user.employee_number}"
daialogBinding.reportingTo.text =
"Reporting to - ${user.reportingTo.first_name} ${user.reportingTo.last_name}"
builder.setPositiveButton("Ok") { dialog: DialogInterface?, which: Int ->
dialog?.cancel()
}
val dialog = builder.create()
dialog.show()
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/Fragment/HrmsUsersScreen.kt | 2978476027 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.Fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.crestinfosystems_jinay.crestcentralsystems.R
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [HrmsLeavesScreen.newInstance] factory method to
* create an instance of this fragment.
*/
class HrmsLeavesScreen : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_hrms_leaves_screen, container, false)
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment HrmsLeavesScreen.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
HrmsLeavesScreen().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/Fragment/HrmsLeavesScreen.kt | 3002483008 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.subscreens
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.crestinfosystems_jinay.crestcentralsystems.R
class hrms_important_contacts : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hrms_important_contacts)
var popUpBack = findViewById<ImageView?>(R.id.back_pressed_icon)
popUpBack.setOnClickListener {
onBackPressed()
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/subscreens/hrms_important_contacts.kt | 1267713345 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.subscreens
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.adapter.HolidayListAdapter
import com.crestinfosystems_jinay.crestcentralsystems.databinding.ActivityHrmsHolidaysScreenBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.holiday
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class hrms_holidays_screen : AppCompatActivity() {
private lateinit var binding: ActivityHrmsHolidaysScreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHrmsHolidaysScreenBinding.inflate(layoutInflater)
val layoutManager: RecyclerView.LayoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
binding.recyclerViewAdapter.layoutManager = layoutManager
fetchData()
binding.backPressedIcon.setOnClickListener {
onBackPressed()
}
setContentView(binding.root)
}
private fun fetchData() {
CoroutineScope(Dispatchers.IO).launch {
val id = CrestCentralSystem.sharedPreferencesManager.id
val apiUrl =
"https://hrms.crestinfosystems.net/api/users/policies?policy_category=holidays&timezone=Asia%2FCalcutta"
try {
lateinit var resultMap: Map<String, Any>
runBlocking {
resultMap = ApiUtils.get(apiUrl) as Map<String, Any>
}
if (resultMap != null && resultMap["status"] as Boolean) {
val applicationDetails =
(resultMap["data"] as List<Map<String, Any>>)
println(applicationDetails)
val listApplication = mutableListOf<holiday>()
for (i in applicationDetails) {
listApplication.add(
holiday(
id = (i["id"] as Double).toInt(),
holiday_reason = i["holiday_reason"].toString(),
holiday_date = i["holiday_date"].toString(),
createdBy = (i["createdBy"] as Double).toInt(),
updatedBy = null,
createdAt = i["createdAt"].toString(),
updatedAt = i["updatedAt"].toString()
)
)
}
withContext(Dispatchers.Main) {
binding.progressCircular.visibility = View.GONE
binding.recyclerViewAdapter.visibility = View.VISIBLE
var adap = HolidayListAdapter(
listApplication, this@hrms_holidays_screen
)
binding.recyclerViewAdapter.adapter = adap
}
}
} catch (exception: Exception) {
exception.printStackTrace()
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/HRMS/subscreens/hrms_holidays_screen.kt | 1341628773 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.dashboard
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.R
import com.crestinfosystems_jinay.crestcentralsystems.adapter.DashboardAdapter
import com.crestinfosystems_jinay.crestcentralsystems.databinding.ActivityDashboardBinding
import com.crestinfosystems_jinay.crestcentralsystems.ui.Profile.UserProfile
import com.crestinfosystems_jinay.crestcentralsystems.viewModel.DashboardViewModel
class Dashboard : AppCompatActivity() {
private lateinit var binding: ActivityDashboardBinding
private val viewModel: DashboardViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_dashboard)
binding.lifecycleOwner = this
binding.dashboardViewModel = viewModel
binding.floatingActionButton.text = CrestCentralSystem.sharedPreferencesManager.userName
val layoutManager: RecyclerView.LayoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
binding.recyclerViewAdapter.layoutManager = layoutManager
binding.floatingActionButton.setOnClickListener {
val intent = Intent(this, UserProfile::class.java)
startActivity(intent)
}
viewModel.fetchData { list ->
binding.progressCircular.visibility = View.GONE
binding.recyclerViewAdapter.visibility = View.VISIBLE
val dashboardAdapter = DashboardAdapter(list, this@Dashboard)
binding.recyclerViewAdapter.adapter = dashboardAdapter
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/dashboard/Dashboard.kt | 741475223 |
package com.crestinfosystems_jinay.crestcentralsystems.ui.Profile
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.crestinfosystems_jinay.crestcentralsystems.ui.Auth.LoginActivity
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.databinding.ActivityUserProfileBinding
class UserProfile : AppCompatActivity() {
var binding: ActivityUserProfileBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityUserProfileBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding?.root)
binding?.logout?.setOnClickListener {
CrestCentralSystem.sharedPreferencesManager.accessToken = null
val intent = Intent(this, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
startActivity(intent)
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/ui/Profile/UserProfile.kt | 3037971756 |
package com.crestinfosystems_jinay.crestcentralsystems
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.crestinfosystems_jinay.crestcentralsystems.ui.Auth.LoginActivity
import com.crestinfosystems_jinay.crestcentralsystems.ui.dashboard.Dashboard
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
val sh = getSharedPreferences("MySharedPref", MODE_PRIVATE)
println(CrestCentralSystem.sharedPreferencesManager.accessToken)
val token = sh.getString("auth_token", "")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Handler(Looper.getMainLooper()).postDelayed(
Runnable {
if (CrestCentralSystem.sharedPreferencesManager.accessToken == null) {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
this.finish()
} else {
val intent = Intent(this, Dashboard::class.java)
startActivity(intent)
this.finish()
}
},
2000
)
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/MainActivity.kt | 625285843 |
package com.crestinfosystems_jinay.crestcentralsystems.Network
import android.util.Log
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import okhttp3.FormBody
class AuthApi {
companion object {
fun login(
email: String,
password: String,
onSuccess: (Map<String, Any>?) -> Unit,
onError: () -> Unit,
onApiFail: (String) -> Unit
) {
val apiUrl = "https://hrms.crestinfosystems.net/api/users/login"
val requestBody = FormBody.Builder()
.add("email", email.trim())
.add("password", password.trim())
.add("rememberMe", false.toString())
.build()
ApiUtils.post(apiUrl, requestBody) { resultMap, exception ->
if (exception != null) {
onError()
exception.printStackTrace()
} else {
// Process response data
if (resultMap != null && resultMap["status_code"] == 200.0) {
Log.d("Login Data", "Login Success")
var dataList: List<Any> = resultMap["data"] as List<Any>
var data: Map<String, Any> = dataList[0] as Map<String, Any>
CrestCentralSystem.sharedPreferencesManager.accessToken =
data["access_token"].toString()
CrestCentralSystem.sharedPreferencesManager.id =
(data["user"] as Map<String, Any>)["id"].toString()
CrestCentralSystem.sharedPreferencesManager.email =
(data["user"] as Map<String, Any>)["email"].toString()
CrestCentralSystem.sharedPreferencesManager.userName =
((data["user"] as Map<String, Any>)["first_name"].toString() + " " + (data["user"] as Map<String, Any>)["last_name"].toString())
onSuccess(resultMap)
} else {
println(resultMap!!["message"].toString())
onApiFail(resultMap["message"].toString())
}
}
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/Network/AuthApi.kt | 2277758820 |
package com.crestinfosystems_jinay.crestcentralsystems.utils
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import com.crestinfosystems_jinay.crestcentralsystems.CrestCentralSystem
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class ApiUtils {
companion object {
private val client = OkHttpClient()
private val gson = Gson()
private val authCode = CrestCentralSystem.sharedPreferencesManager.accessToken
suspend fun get(url: String): Map<String, Any>? {
return withContext(Dispatchers.IO) {
suspendCoroutine { continuation ->
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.header("Authorization", "Bearer $authCode")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
try {
val responseData = response.body?.string()
val resultMap = gson.fromJson(
responseData,
Map::class.java
) as Map<String, Any>?
continuation.resume(resultMap)
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
})
}
}
}
suspend fun launchUrlWithHeaders(
context: Context,
urlString: String,
) {
val uri = Uri.parse(urlString)
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
withContext(Dispatchers.IO) {
try {
// Open a connection to the URL
val url = URL(urlString)
val connection = url.openConnection() as HttpURLConnection
connection.setRequestProperty("Authorization", "Bearer $authCode")
val responseCode = connection.responseCode
println(responseCode)
if (responseCode in 200..299) {
context.startActivity(intent)
} else {
// TODO Some thing Went Wrong
}
connection.disconnect()
} catch (e: IOException) {
e.printStackTrace()
// Handle exception, such as network error
}
}
}
fun post(
url: String,
requestBody: RequestBody,
callback: (Map<String, Any>?, Exception?) -> Unit
) {
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
try {
val responseData = response.body?.string()
Log.d("Response", responseData.toString())
val resultMap =
gson.fromJson(responseData, Map::class.java) as Map<String, Any>?
callback(resultMap, null)
} catch (e: Exception) {
callback(null, e)
}
}
override fun onFailure(call: Call, e: IOException) {
callback(null, e)
}
})
}
}
}
| Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/utils/ApiUtils.kt | 3509950889 |
package com.crestinfosystems_jinay.crestcentralsystems.utils
import android.content.Context
import android.content.SharedPreferences
class SharedPreferencesManager(context: Context) {
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
private val editor: SharedPreferences.Editor = sharedPreferences.edit()
companion object {
private const val ACCESS_TOKEN_KEY = "access_token"
private const val EMAIL = "email"
private const val USER_NAME = "user_name"
private const val ID = "id"
// Define other keys for your shared preferences here
}
var accessToken: String?
get() = sharedPreferences.getString(ACCESS_TOKEN_KEY, null)
set(value) {
editor.putString(ACCESS_TOKEN_KEY, value)
editor.apply()
}
var email: String?
get() = sharedPreferences.getString(EMAIL, null)
set(value) {
editor.putString(EMAIL, value)
editor.apply()
}
var userName: String?
get() = sharedPreferences.getString(USER_NAME, null)
set(value) {
editor.putString(USER_NAME, value)
editor.apply()
}
var id: String?
get() = sharedPreferences.getString(ID, null)
set(value) {
editor.putString(ID, value)
editor.apply()
}
// Define other shared preferences properties and functions as needed
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/utils/SharedPreferencesManager.kt | 2717172967 |
package com.crestinfosystems_jinay.crestcentralsystems.adapter
import android.content.Context
import android.graphics.Color
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.databinding.HrmsPoliciesTileBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.Policies
class HRMSPoliciesAdapter(
private var items: List<Policies>,
var context: Context,
) :
RecyclerView.Adapter<HRMSPoliciesAdapter.ViewHolder>() {
lateinit var binding:
HrmsPoliciesTileBinding
inner class ViewHolder(var binding: HrmsPoliciesTileBinding) :
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
binding =
HrmsPoliciesTileBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
}
with(holder)
{
with(items[position]) {
binding.title.text = items[position].title
binding.details.text = Html.fromHtml(items[position].details)
binding.titleLayout.setOnClickListener {
if (binding.details.visibility == View.VISIBLE) {
binding.details.visibility = View.GONE
binding.titleLayout.setBackgroundColor(Color.WHITE)
binding.title.setTextColor(Color.BLACK)
} else {
binding.details.visibility = View.VISIBLE
binding.titleLayout.setBackgroundColor(Color.parseColor("#7CB900"))
binding.title.setTextColor(Color.WHITE)
}
}
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/adapter/HRMSPoliciesAdapter.kt | 2860164767 |
package com.crestinfosystems_jinay.crestcentralsystems.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.databinding.HolidayListTileBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.holiday
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
class HolidayListAdapter(
private var items: List<holiday>,
var context: Context,
) :
RecyclerView.Adapter<HolidayListAdapter.ViewHolder>() {
inner class ViewHolder(var binding: HolidayListTileBinding) :
RecyclerView.ViewHolder(binding.root) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding =
HolidayListTileBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
}
with(holder)
{
with(items[position]) {
val dateTime = LocalDateTime.parse(
items[position].holiday_date,
DateTimeFormatter.ISO_DATE_TIME
)
binding.dateText.text = dateTime.dayOfMonth.toString()
binding.dayName.text = dateTime.dayOfWeek.name
binding.holidayNameText.text = items[position].holiday_reason
binding.monthText.text =
dateTime.month.getDisplayName(TextStyle.SHORT, Locale.getDefault())
}
}
}
fun submitList(newData: List<holiday>) {
items = newData
notifyDataSetChanged()
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/adapter/HolidayListAdapter.kt | 3609260210 |
package com.crestinfosystems_jinay.crestcentralsystems.adapter
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.R
import com.crestinfosystems_jinay.crestcentralsystems.databinding.HrmsUsersTileBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.user
class HRMSUsersListAdapter(
private var items: List<user>,
var context: Context,
var onClick: (user) -> Unit
) :
RecyclerView.Adapter<HRMSUsersListAdapter.ViewHolder>() {
inner class ViewHolder(var binding: HrmsUsersTileBinding) :
RecyclerView.ViewHolder(binding.root) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding =
HrmsUsersTileBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
onClick(items[position])
}
with(holder)
{
with(items[position]) {
binding.name.text = items[position].first_name + " " + items[position].last_name
binding.designationName.text = items[position].designation_name
}
}
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/adapter/HRMSUsersListAdapter.kt | 4094289029 |
package com.crestinfosystems_jinay.crestcentralsystems.adapter
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.crestinfosystems_jinay.crestcentralsystems.databinding.DashboardAppliactionTileBinding
import com.crestinfosystems_jinay.crestcentralsystems.model.dashboard_application
import com.crestinfosystems_jinay.crestcentralsystems.ui.HRMS.dashboard.HRMS_Dashboard
import com.crestinfosystems_jinay.crestcentralsystems.utils.ApiUtils
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DashboardAdapter(
private var items: List<dashboard_application>,
var context: Context,
) :
RecyclerView.Adapter<DashboardAdapter.ViewHolder>() {
inner class ViewHolder(var binding: DashboardAppliactionTileBinding) :
RecyclerView.ViewHolder(binding.root) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding =
DashboardAppliactionTileBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
if (items[position].app_key == "hrms") {
var intent = Intent(context, HRMS_Dashboard::class.java)
startActivity(context, intent, null)
}
// else if (items[position].app_key == "timetracker") {
//
// }
// else if (items[position].app_key == "assettracker") {
// }
else {
dialog(items[position].app_url)
}
}
with(holder)
{
with(items[position]) {
binding.title.text = items[position].application_name
Picasso.get().load(items[position].img_path).into(binding.icon)
}
}
}
fun submitList(newData: List<dashboard_application>) {
items = newData
notifyDataSetChanged()
}
private fun dialog(url: String) {
val builder = AlertDialog.Builder(context)
builder.setMessage("This Feature currently not available on App. Want to processed with WebView?")
builder.setTitle("Alert !")
builder.setCancelable(false)
builder.setPositiveButton(
"Yes"
) { dialog: DialogInterface?, which: Int ->
CoroutineScope(Dispatchers.Main).launch {
ApiUtils.launchUrlWithHeaders(context, url)
}
}
builder.setNegativeButton(
"No"
) { dialog: DialogInterface, which: Int ->
dialog.cancel()
}
val alertDialog = builder.create()
alertDialog.show()
}
} | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/adapter/DashboardAdapter.kt | 3066463634 |
package com.crestinfosystems_jinay.crestcentralsystems.model
data class Policies(var title: String, var details: String)
| Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/model/Policies.kt | 3767666522 |
package com.crestinfosystems_jinay.crestcentralsystems.model
data class holiday(
val createdAt: String,
val createdBy: Int,
val holiday_date: String,
val holiday_reason: String,
val id: Int,
val updatedAt: String,
val updatedBy: Any?
) | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/model/holiday.kt | 2303394177 |
package com.crestinfosystems_jinay.crestcentralsystems.model
data class user(
val alternate_contact_number: String = "",
val contact_number: String= "",
val designation_id: Int= 0,
val designation_name: String= "",
val email: String= "",
val employee_number: String= "",
val first_name: String= "",
val id: Int= 0,
val joining_date: String= "",
val last_name: String= "",
val onboarding_status: String= "",
val reportingTo: ReportingTo,
val role: Int= 0,
val role_name: String= "",
val status: String= ""
)
data class ReportingTo(
val first_name: String,
val id: Int,
val last_name: String
) | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/model/user.kt | 3301072224 |
package com.crestinfosystems_jinay.crestcentralsystems.model
data class dashboard_application(
val app_id: Int,
val app_key: String,
val app_url: String,
val application_name: String,
val designation: Any?,
val img_path: String
) | Crest_Central_Systems/app/src/main/java/com/crestinfosystems_jinay/crestcentralsystems/model/dashboard_application.kt | 3140338834 |
package com.countries.graphql
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.countries.graphql", appContext.packageName)
}
} | Countries-GraphQl/app/src/androidTest/java/com/countries/graphql/ExampleInstrumentedTest.kt | 3559142833 |
package com.countries.graphql
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Countries-GraphQl/app/src/test/java/com/countries/graphql/ExampleUnitTest.kt | 1799333895 |
package com.countries.graphql.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Countries-GraphQl/app/src/main/java/com/countries/graphql/ui/theme/Color.kt | 3689428745 |
package com.countries.graphql.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun CountriesGraphQlTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/ui/theme/Theme.kt | 2376124348 |
package com.countries.graphql.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Countries-GraphQl/app/src/main/java/com/countries/graphql/ui/theme/Type.kt | 1857067174 |
package com.countries.graphql.core.di
import com.countries.graphql.core.connectivity.di.connectivityManagerModule
import com.countries.graphql.core.error_handling.error_type_converter.di.errorTypeConverterModule
import com.countries.graphql.core.network.provideApolloClient
import com.countries.graphql.features.country_details_screen.di.detailedCountryDataSourceModule
import com.countries.graphql.features.country_details_screen.di.detailedCountryRepositoryModule
import com.countries.graphql.features.country_details_screen.di.detailedCountryUseCaseModule
import com.countries.graphql.features.country_details_screen.di.detailedCountryViewModelModule
import com.countries.graphql.features.home_screen.di.homeDataSourceModule
import com.countries.graphql.features.home_screen.di.homeRepositoryModule
import com.countries.graphql.features.home_screen.di.homeUseCaseModule
import com.countries.graphql.features.home_screen.di.homeViewModelModule
import org.koin.dsl.module
val appModule = module {
includes(errorTypeConverterModule)
}
val networkModule = module {
single { provideApolloClient(get()) }
}
val viewModelsModule = module {
includes(homeViewModelModule)
includes(detailedCountryViewModelModule)
}
val dataSourceModule = module {
includes(homeDataSourceModule)
includes(detailedCountryDataSourceModule)
}
val repositoriesModule = module {
includes(homeRepositoryModule)
includes(detailedCountryRepositoryModule)
}
val useCaseModule = module {
includes(homeUseCaseModule)
includes(detailedCountryUseCaseModule)
}
val singletonModule = module {
includes(connectivityManagerModule)
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/di/AppModule.kt | 2072442770 |
package com.countries.graphql.core.connectivity.di
import android.app.Activity
import com.countries.graphql.core.connectivity.connectivity_manager.ConnectivityManager
import com.countries.graphql.core.connectivity.internet_access_observer.InternetAccessObserver
import org.koin.dsl.module
val connectivityManagerModule = module {
single { (activity: Activity) ->
val internetAccessObserver = InternetAccessObserver(activity)
ConnectivityManager(activity, internetAccessObserver)
}
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/connectivity/di/NetworkManagerModule.kt | 3512021128 |
package com.countries.graphql.core.connectivity.connectivity_manager
import android.app.Activity
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkCapabilities.*
import android.net.NetworkRequest
import androidx.activity.ComponentActivity
import androidx.lifecycle.*
import com.yabraa.medical.core.connectivity.connectivity_manager.NetworkAwareComponent
import com.countries.graphql.core.connectivity.internet_access_observer.InternetAccessObserver
import kotlinx.coroutines.launch
class ConnectivityManager (
private val activity: Activity,
private val internetAccessObserver: InternetAccessObserver
) {
private var _isNetworkConnected = MutableLiveData<Boolean>()
val isNetworkConnected: LiveData<Boolean> = _isNetworkConnected
private var networkCapabilities: NetworkCapabilities? = null
private var getNetworkRequest = getNetworkRequest()
private var networkCallback = getNetworkCallBack()
private val componentActivity get() = (activity as ComponentActivity)
private val networkManagerHolder = (activity as? NetworkAwareComponent)
init {
handleNetworkCallbackRegistration()
}
private fun handleNetworkCallbackRegistration() {
componentActivity.lifecycle.addObserver(object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
getConnectivityManager().registerNetworkCallback(getNetworkRequest, networkCallback)
handleUnregisteredNetworkState()
componentActivity.lifecycleScope.launch {
observeOnIsInternetAvailable()
}
}
override fun onDestroy(owner: LifecycleOwner) {
super.onDestroy(owner)
getConnectivityManager().unregisterNetworkCallback(networkCallback)
}
})
}
private fun observeOnIsInternetAvailable() {
internetAccessObserver.isInternetAvailable.observe(componentActivity) {
_isNetworkConnected.postValue(it)
}
}
private fun getNetworkRequest(): NetworkRequest {
return NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
.addTransportType(TRANSPORT_CELLULAR)
.addTransportType(TRANSPORT_ETHERNET)
.build()
}
private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
return object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
networkManagerHolder?.onNetworkAvailable(network)
networkCapabilities = getConnectivityManager().getNetworkCapabilities(network)
checkConnectInternetType()
}
override fun onLost(network: Network) {
super.onLost(network)
networkManagerHolder?.onNetworkLost(network)
getInternetAccessResponse()
}
}
}
private fun handleUnregisteredNetworkState() {
if (getActiveNetwork() == null)
getInternetAccessResponse()
}
private fun getActiveNetwork() =
getConnectivityManager().getNetworkCapabilities(getConnectivityManager().activeNetwork)
private fun getConnectivityManager() =
activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private fun checkConnectInternetType() {
networkCapabilities?.let {
when {
it.hasTransport(TRANSPORT_CELLULAR) -> getInternetAccessResponse()
it.hasTransport(TRANSPORT_WIFI) -> getInternetAccessResponse()
it.hasTransport(TRANSPORT_ETHERNET) -> getInternetAccessResponse()
}
}
}
private fun getInternetAccessResponse() = internetAccessObserver.getInternetAccessResponse()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/connectivity/connectivity_manager/ConnectivityManager.kt | 2497922516 |
package com.yabraa.medical.core.connectivity.connectivity_manager
import android.net.Network
interface NetworkAwareComponent {
fun onNetworkAvailable(network: Network)
fun onNetworkLost(network: Network)
}
| Countries-GraphQl/app/src/main/java/com/countries/graphql/core/connectivity/connectivity_manager/NetworkAwareComponent.kt | 3755132283 |
package com.countries.graphql.core.connectivity.internet_access_observer
import android.app.Activity
import android.os.Build
import androidx.activity.ComponentActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.SocketTimeoutException
import java.net.URL
import java.net.UnknownHostException
import javax.net.ssl.SSLHandshakeException
const val READ_TIME_OUT = 500
const val CONNECT_TIME_OUT = 5000
const val REQUEST_METHOD = "GET"
const val PING_URL = "www.google.com"
open class InternetAccessObserver(private val activity: Activity) {
private val internetAccessErrorHandler = (activity as? InternetAccessErrorHandler)
private val _isInternetAvailable = MutableLiveData<Boolean>()
val isInternetAvailable: LiveData<Boolean> = _isInternetAvailable
fun getInternetAccessResponse() {
(activity as ComponentActivity).lifecycleScope.launch {
withContext(Dispatchers.IO) {
_isInternetAvailable.postValue(isInternetAccess())
}
}
}
private fun isInternetAccess(): Boolean {
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
return InetAddress.getByName(PING_URL).isReachable(CONNECT_TIME_OUT)
}
val httpConnection = URL("https://$PING_URL").openConnection() as HttpURLConnection
httpConnection.apply {
readTimeout = READ_TIME_OUT
connectTimeout = CONNECT_TIME_OUT
requestMethod = REQUEST_METHOD
connect()
return responseCode == 200
}
} catch (e: SocketTimeoutException) {
getInternetExceptionError(SOCKET_TIME_OUT_EXCEPTION, e)
} catch (e: SSLHandshakeException) {
getInternetExceptionError(SSL_HANDSHAKE_EXCEPTION, e)
} catch (e: UnknownHostException) {
getInternetExceptionError(UNKNOWN_HOST_EXCEPTION, e)
} catch (e: Exception) {
getInternetExceptionError(GENERAL_EXCEPTION, e)
}
return false
}
private fun getInternetExceptionError(errorType: String, exception: Exception) =
internetAccessErrorHandler?.readInternetAccessExceptionError(errorType, exception)
companion object {
const val SOCKET_TIME_OUT_EXCEPTION = "SOCKET_TIME_OUT_EXCEPTION"
const val SSL_HANDSHAKE_EXCEPTION = "SSL_HANDSHAKE_EXCEPTION"
const val UNKNOWN_HOST_EXCEPTION = "UNKNOWN_HOST_EXCEPTION"
const val GENERAL_EXCEPTION = "GENERAL_EXCEPTION"
}
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/connectivity/internet_access_observer/InternetAccessObserver.kt | 4065489703 |
package com.countries.graphql.core.connectivity.internet_access_observer
interface InternetAccessErrorHandler {
fun readInternetAccessExceptionError(errorType: String, exception: Exception) {}
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/connectivity/internet_access_observer/InternetAccessErrorHandler.kt | 2537180638 |
package com.countries.graphql.core.network
import android.content.Context
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.network.okHttpClient
import com.countries.graphql.R
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import timber.log.Timber
import zerobranch.androidremotedebugger.logging.NetLoggingInterceptor
import java.util.concurrent.TimeUnit
private val provideAuthInterceptor: Interceptor =
Interceptor { chain ->
val newBuilder = chain.request().newBuilder()
newBuilder.addHeader("Authorization", "BearerYOUR_ACCESS_TOKEN")
newBuilder.build().let { chain.proceed(it) }
}
private val httpLoggingInterceptor = HttpLoggingInterceptor { message ->
Timber.tag("OkHttp").d(message)
}.setLevel(HttpLoggingInterceptor.Level.BODY)
private val okHttpClient = OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
//.addInterceptor(provideAuthInterceptor)
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(NetLoggingInterceptor())
.build()
fun provideApolloClient(context: Context) = ApolloClient.Builder()
.serverUrl(context.getString(R.string.base_url))
.okHttpClient(okHttpClient)
.build()
| Countries-GraphQl/app/src/main/java/com/countries/graphql/core/network/ApolloNetwork.kt | 3203635380 |
package com.countries.graphql.core.state.network_state
import com.countries.graphql.core.error_handling.error_type.ErrorType
sealed class State<T> {
data class Success<T>(val data: T? = null, val error: T? = null) : State<T>()
data class Error<T>(val error: ErrorType) : State<T>()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/state/network_state/State.kt | 4045279064 |
package com.countries.graphql.core.state.ui_data_state
import com.countries.graphql.core.error_handling.ui_error.error_text.ErrorText
sealed class UiDataState<T> {
class Loading<T>: UiDataState<T>()
data class Error<T>(val error: ErrorText) : UiDataState<T>()
data class Loaded<T>(val data: T): UiDataState<T>()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/state/ui_data_state/UiDataState.kt | 467290338 |
package com.countries.graphql.core.error_handling.throwable
import com.apollographql.apollo3.exception.ApolloHttpException
import com.countries.graphql.core.error_handling.error_type.ErrorType
import java.io.IOException
const val INTERNAL_SERVER = 501
const val SERVER_UNAVAILABLE = 503
const val RESOURCE_NOT_FOUND = 404
fun Throwable.toErrorType() = when (this) {
is IOException -> ErrorType.Network
is ApolloHttpException -> when (statusCode) {
RESOURCE_NOT_FOUND -> ErrorType.NotFound
INTERNAL_SERVER -> ErrorType.Server
SERVER_UNAVAILABLE -> ErrorType.ServiceUnavailable
else -> ErrorType.Unknown
}
else -> ErrorType.Unknown
}
| Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/throwable/Throwable.kt | 2578423090 |
package com.countries.graphql.core.error_handling.ui_error.error_text
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
sealed class ErrorText {
class StringResource(@StringRes val id: Int): ErrorText()
@Composable
fun asString() = when(this) {
is StringResource -> stringResource(id)
}
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/ui_error/error_text/ErrorText.kt | 37219598 |
package com.countries.graphql.core.error_handling.error_type
sealed class ErrorType {
data object Network : ErrorType()
data object ServiceUnavailable : ErrorType()
data object NotFound : ErrorType()
data object Server : ErrorType()
data object Unknown : ErrorType()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/error_type/ErrorType.kt | 3968411352 |
package com.countries.graphql.core.error_handling.error_type_converter
import com.countries.graphql.core.error_handling.error_type.ErrorType
import com.countries.graphql.core.error_handling.ui_error.error_text.ErrorText
interface ErrorTypeConverterHandler {
fun convert(errorType: ErrorType): ErrorText
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/error_type_converter/ErrorTypeConverterHandler.kt | 3540237067 |
package com.countries.graphql.core.error_handling.error_type_converter.di
import com.countries.graphql.core.error_handling.error_type_converter.ErrorTypeConverterHandler
import com.countries.graphql.core.error_handling.error_type_converter.ErrorTypeConverterImpl
import org.koin.dsl.module
val errorTypeConverterModule = module {
single<ErrorTypeConverterHandler> { ErrorTypeConverterImpl() }
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/error_type_converter/di/ErrorTypeConverterModule.kt | 3156376386 |
package com.countries.graphql.core.error_handling.error_type_converter
import com.countries.graphql.R
import com.countries.graphql.core.error_handling.error_type.ErrorType
import com.countries.graphql.core.error_handling.ui_error.error_text.ErrorText
class ErrorTypeConverterImpl : ErrorTypeConverterHandler {
override fun convert(errorType: ErrorType) = when (errorType) {
ErrorType.NotFound -> ErrorText.StringResource(R.string.errorResourceNotFound)
ErrorType.ServiceUnavailable -> ErrorText.StringResource(R.string.errorServiceUnavailable)
ErrorType.Server -> ErrorText.StringResource(R.string.errorServer)
ErrorType.Network -> ErrorText.StringResource(R.string.errorNetworkUnavailable)
ErrorType.Unknown -> ErrorText.StringResource(R.string.errorGeneral)
}
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/error_handling/error_type_converter/ErrorTypeConverter.kt | 3593644388 |
package com.countries.graphql.core.uitls.error_view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.countries.graphql.R
import com.countries.graphql.core.error_handling.ui_error.error_text.ErrorText
@Composable
fun ErrorView(errorText: ErrorText, action: () -> Unit) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = errorText.asString())
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = {
action()
}
) {
Text(text = "Retry")
}
}
}
@Composable
@Preview
fun PreviewErrorView() {
ErrorView(ErrorText.StringResource(R.string.errorGeneral)) { }
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/uitls/error_view/ErrorView.kt | 1741577796 |
package com.countries.graphql.core.uitls.loading_view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
@Composable
fun LoadingView() {
Column (
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator()
}
}
@Composable
@Preview(widthDp = 200, heightDp = 200)
fun PreviewLoadingView() {
LoadingView()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/core/uitls/loading_view/LoadingView.kt | 3877558873 |
package com.countries.graphql.core.uitls
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
fun Context.handleOpenConnectionSetting() =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startActivity(Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY))
} else {
startActivity(Intent(Settings.ACTION_WIRELESS_SETTINGS))
}
| Countries-GraphQl/app/src/main/java/com/countries/graphql/core/uitls/Extinctions.kt | 2099981828 |
package com.countries.graphql.features.country_details_screen.di
import com.countries.graphql.features.country_details_screen.data.data_source.DetailedCountryDataSourceImpl
import com.countries.graphql.features.country_details_screen.data.repository.DetailedCountryRepositoryImpl
import com.countries.graphql.features.country_details_screen.domain.data_source.DetailedCountryDataSource
import com.countries.graphql.features.country_details_screen.domain.repository.DetailedCountryRepository
import com.countries.graphql.features.country_details_screen.domain.usecase.DetailedCountryUseCase
import com.countries.graphql.features.country_details_screen.domain.viewmodel.DetailedCountryViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val detailedCountryViewModelModule = module {
viewModel { DetailedCountryViewModel(get()) }
}
val detailedCountryDataSourceModule = module {
single<DetailedCountryDataSource> { DetailedCountryDataSourceImpl(get()) }
}
val detailedCountryRepositoryModule = module {
single<DetailedCountryRepository> { DetailedCountryRepositoryImpl(get()) }
}
val detailedCountryUseCaseModule = module {
single { DetailedCountryUseCase() }
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/di/DetailedCountryModule.kt | 1436149573 |
package com.countries.graphql.features.country_details_screen.data.repository
import com.countries.graphql.core.error_handling.throwable.toErrorType
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.features.country_details_screen.domain.data_source.DetailedCountryDataSource
import com.countries.graphql.features.country_details_screen.domain.repository.DetailedCountryRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
class DetailedCountryRepositoryImpl(private val detailedCountryDataSource: DetailedCountryDataSource) :
DetailedCountryRepository {
override suspend fun getCountry(code: String) =
detailedCountryDataSource.fetchCountry(code).catch {
emit(State.Error(it.toErrorType()))
}.flowOn(Dispatchers.IO)
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/data/repository/DetailedCountryRepositoryImpl.kt | 66917070 |
package com.countries.graphql.features.country_details_screen.data.data_source
import com.apollographql.apollo3.ApolloClient
import com.countries.graphql.CountryQuery
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.features.country_details_screen.data.mappers.toDetailedCountry
import com.countries.graphql.features.country_details_screen.domain.data_source.DetailedCountryDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
class DetailedCountryDataSourceImpl(private val apolloNetwork: ApolloClient) :
DetailedCountryDataSource {
override suspend fun fetchCountry(code: String) = flow {
val response = apolloNetwork.query(CountryQuery(code)).execute()
val data = response.data?.country?.toDetailedCountry()
if (response.errors.isNullOrEmpty()) emit(State.Success(data))
}.flowOn(Dispatchers.IO)
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/data/data_source/DetailedCountryDataSourceImpl.kt | 2060952769 |
package com.countries.graphql.features.country_details_screen.data.mappers
import com.countries.graphql.CountryQuery
import com.countries.graphql.features.home_screen.domain.model.DetailedCountry
import com.countries.graphql.features.home_screen.domain.model.Languages
fun CountryQuery.Country.toDetailedCountry() = DetailedCountry(
name = name,
capital = capital ?: "No Capital",
code = code,
currency = currency ?: "No Currency",
emoji = emoji,
native = native,
phone = phone,
languages = languages.map { it.toLanguage() },
continent = continent.name
)
fun CountryQuery.Language.toLanguage() = Languages(
native = native,
name = name,
code = code,
rtl = rtl
) | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/data/mappers/CountryMapper.kt | 2608233115 |
package com.countries.graphql.features.country_details_screen.domain.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.countries.graphql.core.error_handling.error_type.ErrorType
import com.countries.graphql.core.error_handling.error_type_converter.ErrorTypeConverterHandler
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.core.state.ui_data_state.UiDataState
import com.countries.graphql.features.country_details_screen.domain.usecase.DetailedCountryUseCase
import com.countries.graphql.features.home_screen.domain.model.DetailedCountry
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class DetailedCountryViewModel(
private val stateHandle: SavedStateHandle
) : ViewModel(), KoinComponent {
private val detailedCountryUseCase: DetailedCountryUseCase by inject()
private val errorTypeConverterHandler: ErrorTypeConverterHandler by inject()
private val _detailedCountryResponseState =
MutableStateFlow<UiDataState<DetailedCountry>>(UiDataState.Loading())
val detailedCountryResponseState = _detailedCountryResponseState.asStateFlow()
init {
getDetailedCountry()
}
fun getDetailedCountry() {
val code = stateHandle.get<String>("code") ?: ""
getDetailedCountry(code)
}
private fun getDetailedCountry(code: String) = viewModelScope.launch {
detailedCountryUseCase(code).collect {
when (it) {
is State.Error -> it.error.handleDetailedCountryErrorState()
is State.Success -> it.data?.handleDetailedCountrySuccessState()
}
}
}
private suspend fun DetailedCountry.handleDetailedCountrySuccessState() {
_detailedCountryResponseState.emit(UiDataState.Loaded(this))
}
private suspend fun ErrorType.handleDetailedCountryErrorState() {
_detailedCountryResponseState.emit(UiDataState.Error(errorTypeConverterHandler.convert(this)))
}
fun getCountry() = detailedCountryUseCase.getDetailedCountry()
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/domain/viewmodel/DetailedCountryViewModel.kt | 3133560670 |
package com.countries.graphql.features.country_details_screen.domain.repository
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.features.home_screen.domain.model.DetailedCountry
import kotlinx.coroutines.flow.Flow
interface DetailedCountryRepository {
suspend fun getCountry(code: String): Flow<State<DetailedCountry>>
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/domain/repository/DetailedCountryRepository.kt | 42544023 |
package com.countries.graphql.features.country_details_screen.domain.data_source
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.features.home_screen.domain.model.DetailedCountry
import kotlinx.coroutines.flow.Flow
interface DetailedCountryDataSource {
suspend fun fetchCountry(code: String): Flow<State<DetailedCountry>>
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/domain/data_source/DetailedCountryDataSource.kt | 3144639863 |
package com.countries.graphql.features.country_details_screen.domain.usecase
import com.countries.graphql.core.state.network_state.State
import com.countries.graphql.features.home_screen.domain.model.DetailedCountry
import com.countries.graphql.features.country_details_screen.domain.repository.DetailedCountryRepository
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.channelFlow
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class DetailedCountryUseCase : KoinComponent {
private val detailedCountryRepository: DetailedCountryRepository by inject()
private var detailedCountry: DetailedCountry? = null
suspend operator fun invoke(code: String) = channelFlow {
val response = async { detailedCountryRepository.getCountry(code) }
response.await().collect {
if (it is State.Success) {
detailedCountry = it.data
}
send(it)
}
}
fun getDetailedCountry() = detailedCountry
} | Countries-GraphQl/app/src/main/java/com/countries/graphql/features/country_details_screen/domain/usecase/DetailedCountryUseCase.kt | 2559885991 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.