content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package lista fun main() { print("Digite um número de 1 até 10: ") val n = readln().toInt() for (i in 1..10) { println("$n x $i = ${n * i}") } }
lista-exercicios-kotlin/src/lista/Ex16.kt
191221203
/* ler codgo do usuario ler o ano de nascimento ler o ano de ingresso na empresa imprimir idade o tempo trabalhado do em pregador imprimir Requerer aposentadoria ou Nao requerer aposentadoria */ package lista import java.time.LocalDate fun main() { print("Digite seu código da empresa: ") val codigo = readln().toInt() print("Digite seu ano de nascimento: ") val idade = readln().toInt() print("Digite o ano que ingresso na empresa: ") val anoIngresso = readln().toInt() val anoAtual = LocalDate.now().year val idadeAtual = anoAtual - idade val tempoIngresso = anoAtual - anoIngresso println("Seu código da empresa é: $codigo ") println("Sua idade atual é: $idadeAtual ") println("Seu tempo de ingresso é: $tempoIngresso ") when { idadeAtual >= 65 -> println("requer aposentadoria") tempoIngresso >= 30 -> println("requer aposentadoria") idadeAtual >= 60 && tempoIngresso >= 25 -> println("requer aposentadoria") else -> println("Não requerer aposentadoria") } // TODO: refatorar para função. }
lista-exercicios-kotlin/src/lista/Ex06.kt
3548814703
package lista fun main() { val totalNumeros = 10 var negativoConte = 0 println("Digite $totalNumeros números:") for (i in 1..totalNumeros) { print("Número $i: ") val numero = readLine()!!.toDouble() if (numero < 0) { negativoConte++ } } println("Quantidade de números negativos: $negativoConte") }
lista-exercicios-kotlin/src/lista/Ex12.kt
3076638930
package lista fun main() { print("Digite a quantidade de maçãs que deseja comprar: ") val quantidade = readln().toInt() val precoFinal = calculaPrecoTotal(quantidade) println("Valor total a apargar: $precoFinal") } fun calculaPrecoTotal(quantidade: Int): Double { val pcNormal = 1.30 val pcPromocao = 1.00 val resultado: Double if (quantidade >= 12) { resultado = pcPromocao * quantidade } else { resultado = pcNormal * quantidade } return resultado }
lista-exercicios-kotlin/src/lista/Ex02.kt
1213340505
package lista fun main() { for (linha in 1..10) { print("Linha $linha: ") for (coluna in 1..linha) { print("$coluna ") } println() } }
lista-exercicios-kotlin/src/lista/Ex19.kt
3075809340
package lista fun main() { println("Digite quantidade de alunos: ") val quantidadeDeAlunos = readln().toInt() if (quantidadeDeAlunos <= 0 || quantidadeDeAlunos > 10) { println("Encerrando o programa!") return } var somaDasNotas = 0.0 for (i in 1..quantidadeDeAlunos) { println("Digite a nota do aluno $i: ") val nota = readln().toDouble() somaDasNotas += nota } val mediaDasNotas = somaDasNotas / quantidadeDeAlunos println(mediaDasNotas) }
lista-exercicios-kotlin/src/lista/Ex13.1.kt
2678126987
package lista fun main() { var c = 10 while (c != 0) { print("$c ") c-- } println() for (i in 10 downTo 1) { print("$i ") } }
lista-exercicios-kotlin/src/lista/Ex09.kt
494368148
package lista fun main() { for (linha in 1..10) { print("Linha $linha: ") for (coluna in 1..10) { print("$coluna ") } println() } }
lista-exercicios-kotlin/src/lista/Ex18.kt
4284906587
package lista fun main() { var x = 1 while (x <= 10) { println("$x") x++ } println() for (i in 1..10) { println(i) } }
lista-exercicios-kotlin/src/lista/Ex08.kt
3607420951
package lista fun main() { print("Digite um número: ") val numero = readln().toInt() if (numero < 0) { print("Este número $numero é negativo.") } else { if (numero >= 0) { print("Este número $numero é positivo.") } } }
lista-exercicios-kotlin/src/lista/Main.kt
1908454167
package lista fun main() { print("Digite um número da tabuada do 5: ") val n = readln().toInt() val m = 10 for (x in 1..m) { println("$n x $x = ${n * x}") } }
lista-exercicios-kotlin/src/lista/Ex15.kt
3487450598
/* ler descricao do produto nome ler quantidadeAdquirida ler precoUnitario valorTotal = quantidadeAdquirida * preco unitario se quantidade for <= 5 percDesconto de 2% se quantidade for > 5 e quantidade <= 10 o percDesconto sera de 3% se quantidade for > 10 o percDesconto sera de 5% valorDesconto = valorTotal * percDesconto / 100 valorTotalFinal = valorTotal - valorDesconto */ package lista fun main() { println("Digite a descrição do produto, calcular um por vez: ") val descricao = readln() print("Digite o preço unitário do produto: ") val precoUnitario = readln().toDouble() println("digite a quantidade ") val quantidadeAdquirida = readln().toDouble() val precoFinal = calculaValorFinal(precoUnitario, quantidadeAdquirida) println("Descricao: $descricao") println("Valor total final é: $precoFinal") } fun calculaValorFinal(precoUnitario: Double, quantidadeAdquirida: Double): Double { val valorTotal = quantidadeAdquirida * precoUnitario val percDesconto: Double = when { quantidadeAdquirida <= 5 -> 2.0 quantidadeAdquirida <= 10 -> 3.0 else -> 5.0 } val valorDesconto = valorTotal * percDesconto / 100 val valorTotalFinal = valorTotal - valorDesconto return valorTotalFinal }
lista-exercicios-kotlin/src/lista/Ex05.kt
807325713
package lista fun main() { println("Digite o valor de N: ") var n = readln().toInt() for (i in 1..n) { println("$i") } }
lista-exercicios-kotlin/src/lista/Ex11.kt
2392881110
package lista fun main() { var x = 100 while (x <= 110) { println("$x") x++ } println() for (d in 100..110) { println(d) } }
lista-exercicios-kotlin/src/lista/Ex10.kt
3374791762
package lista fun main() { println("Digite a quantidade de números que você deseja digitar: ") val quntidadeNumeros = readln().toInt() if (quntidadeNumeros <= 0) return var maior = 0 var menor = Int.MAX_VALUE for (i in 1..quntidadeNumeros) { print("Qual número você deseja informar? ") val numeroInformado = readln().toInt() if (numeroInformado > maior) { maior = numeroInformado } // Alternativa: maior = max(numeroInformado, maior) if (numeroInformado < menor) { menor = numeroInformado } // Alternativa: menor = min(numeroInformado, menor) } println("O maior número é: $maior") println("O menor número é: $menor") }
lista-exercicios-kotlin/src/lista/Ex14.kt
536487283
package lista fun main() { for (linha in 1..10) { print("Linha $linha: ") for (coluna in linha..10) { print("$coluna ") } println() } }
lista-exercicios-kotlin/src/lista/Ex20.kt
3428740556
package lista fun main() { println("Digite um número: ") val numero1 = readln().toInt() println("Digite um número: ") val numero2 = readln().toInt() println("Digite um número: ") val numero3 = readln().toInt() val resulatdoFun = maior(numero1, numero2, numero3) println("O número maior e: $resulatdoFun") } fun maior(numero1: Int, numero2: Int, numero3: Int): Int { if (numero1 > numero2) { if (numero1 > numero3) { return numero1 } else { return numero3 } } else if (numero2 > numero3) { return numero2 } else { return numero3 } }
lista-exercicios-kotlin/src/lista/Ex04.kt
3388249146
package com.bangkit.edims 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.example.myproject", appContext.packageName) } }
Edims/EDIMS/src/androidTest/java/com/bangkit/edims/ExampleInstrumentedTest.kt
4171059568
package com.bangkit.edims 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) } }
Edims/EDIMS/src/test/java/com/bangkit/edims/ExampleUnitTest.kt
363515092
package com.bangkit.edims.database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "product") data class Product( @PrimaryKey(autoGenerate = true) @ColumnInfo("id") val id: Int = 0, @ColumnInfo("name") val name: String, @ColumnInfo("image") val image: String, @ColumnInfo("category") val category: String, @ColumnInfo("dueDateMillis") val dueDateMillis: Long, )
Edims/EDIMS/src/main/java/com/bangkit/edims/database/Product.kt
1473693052
package com.bangkit.edims.database import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [Product::class], version = 1, exportSchema = false) abstract class ProductDatabase : RoomDatabase() { abstract fun productDao(): ProductDao }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/ProductDatabase.kt
2305354235
package com.bangkit.edims.database import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.RawQuery import androidx.sqlite.db.SupportSQLiteQuery import kotlinx.coroutines.flow.Flow @Dao interface ProductDao { @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(product: Product) @Delete suspend fun delete(product: Product) @Query("DELETE FROM product") suspend fun deleteAll() @RawQuery(observedEntities = [Product::class]) fun getItems(query: SupportSQLiteQuery): Flow<List<Product>> @Query("SELECT * FROM product WHERE id=:productId") fun getItemsById(productId: Int): Flow<Product> @Query("SELECT * FROM product WHERE dueDateMillis <= :dueDateMillis AND dueDateMillis > :currentTime ORDER BY dueDateMillis ASC") fun getNearestItems(dueDateMillis : Long, currentTime : Long) : List<Product> }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/ProductDao.kt
14185902
package com.bangkit.edims.database import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.bangkit.edims.data.User import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class UserPreference (private val context : Context) { companion object { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_data") val USER_ID_DATA = intPreferencesKey("user_id_data") val USERNAME_DATA = stringPreferencesKey("username_data") val EMAIL_DATA = stringPreferencesKey("email_data") val IMAGE_PROFILE_DATA = stringPreferencesKey("image_profile_data") val TOKEN_KEY = stringPreferencesKey("token_key") } suspend fun saveLoginData(user : User) { context.dataStore.edit { preferences -> preferences[USER_ID_DATA] = user.userId ?: 0 preferences[USERNAME_DATA] = user.username ?: "" preferences[EMAIL_DATA] = user.email ?: "" preferences[IMAGE_PROFILE_DATA] = user.imageProfile ?: "" preferences[TOKEN_KEY] = user.token ?: "" } } suspend fun clearLoginData() { context.dataStore.edit { preferences -> preferences.remove(USER_ID_DATA) preferences.remove(USERNAME_DATA) preferences.remove(EMAIL_DATA) preferences.remove(IMAGE_PROFILE_DATA) preferences.remove(TOKEN_KEY) } } val getUserData: Flow<User> = context.dataStore.data .map { preferences -> User( userId = preferences[USER_ID_DATA], username = preferences[USERNAME_DATA], email = preferences[EMAIL_DATA], imageProfile = preferences[IMAGE_PROFILE_DATA], token = preferences[TOKEN_KEY] ) } val token: Flow<String> = context.dataStore.data.map { preferences -> preferences[TOKEN_KEY] ?: "" } fun isTokenAvailable(): Flow<Boolean> { return context.dataStore.data.map { preferences -> preferences.contains(TOKEN_KEY) } } suspend fun changeImageProfile (imageProfile: String) { context.dataStore.edit { preferences -> preferences.remove(IMAGE_PROFILE_DATA) preferences[IMAGE_PROFILE_DATA] = imageProfile } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/UserPreference.kt
1475778141
package com.bangkit.edims.database import com.bangkit.edims.core.utils.ProductFilterType import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.data.retrofit.ErrorResponse import com.bangkit.edims.data.retrofit.ItemsResponse import com.bangkit.edims.data.retrofit.LoginResponse import com.bangkit.edims.data.retrofit.SignupResponse import com.bangkit.edims.data.retrofit.UploadResponse import kotlinx.coroutines.flow.Flow import okhttp3.MultipartBody import okhttp3.RequestBody interface ProductRepository{ fun isDataFetched() : Boolean fun login(email: String, password: String) : Flow<Result<LoginResponse>> fun signup(email: String, username : String, password: String) : Flow<Result<SignupResponse>> fun getAllData() : Flow<Result<ItemsResponse>> fun uploadProductApi(name: RequestBody, imageFile: MultipartBody.Part, category: RequestBody, date: RequestBody) : Flow<Result<UploadResponse>> fun deleteProductApi(id : Int) : Flow<Result<ErrorResponse>> suspend fun logout() suspend fun insert(product: Product) suspend fun insertAll(listProduct: List<Product>) suspend fun delete(product: Product) fun getItems(filter: ProductFilterType) : Flow<List<Product>> fun getItemsById(id: Int) : Flow<Product> fun getNearestItems() : List<Product> suspend fun saveNotificationSettings(status: Boolean) fun getNotificationSettings() : Flow<Boolean> suspend fun saveLoginData(user : User) suspend fun clearLoginData() fun getUserData() : Flow<User> fun getToken() : Flow<String> }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/ProductRepository.kt
1893285439
package com.bangkit.edims.database import com.bangkit.edims.core.utils.DateConverter import com.bangkit.edims.core.utils.Filter import com.bangkit.edims.core.utils.ProductFilterType import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.data.retrofit.ApiConfig import com.bangkit.edims.data.retrofit.ApiService import com.bangkit.edims.data.retrofit.ErrorResponse import com.bangkit.edims.data.retrofit.ItemsResponse import com.bangkit.edims.data.retrofit.LoginRequest import com.bangkit.edims.data.retrofit.LoginResponse import com.bangkit.edims.data.retrofit.SignupRequest import com.bangkit.edims.data.retrofit.SignupResponse import com.bangkit.edims.data.retrofit.UploadResponse import com.bangkit.edims.data.wrapEspressoIdlingResource import com.google.gson.Gson import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.HttpException import java.io.IOException class ProductRepositoryImpl( private val apiService: ApiService, private val productDao: ProductDao, private val preference: SettingPreference, private val userPreference: UserPreference, ) : ProductRepository { companion object { private var isDataFetched = false } override fun isDataFetched(): Boolean = isDataFetched override fun login(email: String, password: String): Flow<Result<LoginResponse>> = flow { emit(Result.Loading) wrapEspressoIdlingResource { try { val loginRequest = LoginRequest(email, password) val response = apiService.login(loginRequest) if (response.isSuccessful) { val loginResponse = response.body() if (loginResponse != null) { emit(Result.Success(loginResponse)) } } else { val jsonString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } catch (e: IOException) { emit(Result.Error("Network error. Please check your internet connection.")) } } } override fun signup( email: String, username: String, password: String ): Flow<Result<SignupResponse>> = flow { emit(Result.Loading) try { val signupRequest = SignupRequest(email, username, password) val response = apiService.signup(signupRequest) if (response.isSuccessful) { val signupResponse = response.body() if (signupResponse != null) { val message = "Sign up successful" emit(Result.Success(SignupResponse(message))) } } else { val jsonString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } catch (e: IOException) { emit(Result.Error("Network error. Please check your internet connection.")) } } override fun getAllData(): Flow<Result<ItemsResponse>> = flow { emit(Result.Loading) try { val apiService = ApiConfig.getApiService(userPreference) val response = apiService.getProducts() if (response.isSuccessful) { val result = response.body() if (result != null) { emit(Result.Success(result)) } else { val jsonString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } isDataFetched = true } else { val jsonString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } catch (e: IOException) { emit(Result.Error("Network error. Please check your internet connection.")) } } override fun uploadProductApi( name: RequestBody, imageFile: MultipartBody.Part, category: RequestBody, date: RequestBody, ): Flow<Result<UploadResponse>> = flow { emit(Result.Loading) try { val apiService = ApiConfig.getApiService(userPreference) val response = apiService.uploadProduct(name, imageFile, category, date) if (response.isSuccessful) { val result = response.body() if (result != null) { emit((Result.Success(result))) } } else { val errorMessage = "error" emit(Result.Error(errorMessage)) } } catch (e: HttpException) { val jsonInString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonInString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } catch (e: IOException) { emit(Result.Error("Network error. Please check your internet connection.")) } } override fun deleteProductApi(id: Int): Flow<Result<ErrorResponse>> = flow { emit(Result.Loading) try { val apiService = ApiConfig.getApiService(userPreference) val response = apiService.deleteProducts(id) if (response.isSuccessful) { val result = response.body() if (result != null) { emit(Result.Success(result)) } } else { val jsonString = response.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } } catch (e: HttpException) { val jsonString = e.response()?.errorBody()?.string() val errorBody = Gson().fromJson(jsonString, ErrorResponse::class.java) val errorMessage = errorBody.message emit(Result.Error(errorMessage)) } catch (e: IOException) { emit(Result.Error("Network error. Please check your internet connection.")) } } override suspend fun logout() { productDao.deleteAll() userPreference.clearLoginData() isDataFetched = false } override suspend fun insert(product: Product) { productDao.insert(product) } override suspend fun insertAll(listProduct: List<Product>) { for (data in listProduct) { productDao.insert(data) } } override suspend fun delete(product: Product) { productDao.delete(product) } override fun getItems(filter: ProductFilterType): Flow<List<Product>> { val filterQuery = Filter.getFilterQuery(filter) return productDao.getItems(filterQuery) } override fun getItemsById(id: Int): Flow<Product> { return productDao.getItemsById(id) } override fun getNearestItems(): List<Product> { val currentTime = System.currentTimeMillis() val dueDateMillis: Long = currentTime + DateConverter.dayToMillis(3) return productDao.getNearestItems(dueDateMillis, currentTime) } override suspend fun saveNotificationSettings(status: Boolean) { preference.saveNotificationSettings(status) } override fun getNotificationSettings(): Flow<Boolean> { return preference.getNotificationSettings } override suspend fun saveLoginData(user: User) { userPreference.saveLoginData(user) } override suspend fun clearLoginData() { userPreference.clearLoginData() } override fun getUserData(): Flow<User> { return userPreference.getUserData } override fun getToken(): Flow<String> { return userPreference.token } }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/ProductRepositoryImpl.kt
4048150887
package com.bangkit.edims.database import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.preferencesDataStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class SettingPreference(private val context: Context) { companion object { private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") val NOTIFICATION_SETTINGS = booleanPreferencesKey("notification_settings") } val getNotificationSettings: Flow<Boolean> = context.dataStore.data .map { preferences -> preferences[NOTIFICATION_SETTINGS] ?: false } suspend fun saveNotificationSettings(status: Boolean) { context.dataStore.edit { preferences -> preferences[NOTIFICATION_SETTINGS] = status } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/database/SettingPreference.kt
422677732
package com.bangkit.edims import android.app.Application import com.bangkit.edims.di.appModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MyApplication) modules(appModule) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/MyApplication.kt
1686994406
package com.bangkit.edims.di import androidx.room.Room import com.bangkit.edims.data.retrofit.ApiConfig import com.bangkit.edims.database.ProductDatabase import com.bangkit.edims.database.ProductRepository import com.bangkit.edims.database.ProductRepositoryImpl import com.bangkit.edims.database.SettingPreference import com.bangkit.edims.database.UserPreference import com.bangkit.edims.presentation.ui.add.AddViewModel import com.bangkit.edims.presentation.ui.detail.DetailViewModel import com.bangkit.edims.presentation.ui.home.HomeViewModel import com.bangkit.edims.presentation.ui.login.LoginViewModel import com.bangkit.edims.presentation.ui.profile.ProfileViewModel import com.bangkit.edims.presentation.ui.settings.SettingsViewModel import com.bangkit.edims.presentation.ui.signup.SignUpViewModel import org.koin.android.ext.koin.androidApplication import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module val appModule = module { single { Room.databaseBuilder( androidApplication(), ProductDatabase::class.java, "product_database" ).build() } single { get<ProductRepository>().getToken() } single { SettingPreference(androidContext()) } single { UserPreference(androidContext()) } single { ApiConfig.getApiService(get()) } single { get<ProductDatabase>().productDao() } single<ProductRepository> { ProductRepositoryImpl(get(), get(), get(), get()) } viewModel { HomeViewModel(get()) } viewModel { AddViewModel(get()) } viewModel { DetailViewModel(get()) } viewModel { SettingsViewModel(get()) } viewModel { ProfileViewModel(get()) } viewModel{ LoginViewModel(get()) } viewModel{ SignUpViewModel(get()) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/di/AppModule.kt
1744647859
package com.bangkit.edims.core.utils import androidx.compose.material3.Button import androidx.compose.material3.DatePicker import androidx.compose.material3.DatePickerDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.SelectableDates import androidx.compose.material3.Text import androidx.compose.material3.rememberDatePickerState import androidx.compose.runtime.Composable @OptIn(ExperimentalMaterial3Api::class) @Composable fun DatePickerDialog( initialDateMillis: Long, onDateSelected: (String) -> Unit, onDateMillisSelected: (Long) -> Unit, onDismiss: () -> Unit, ) { val datePickerState = rememberDatePickerState( selectableDates = object : SelectableDates { override fun isSelectableDate(utcTimeMillis: Long): Boolean { return true } }, initialSelectedDateMillis = initialDateMillis ) val selectableDateMillis = datePickerState.selectedDateMillis ?: initialDateMillis val selectableDate = DateConverter.convertMillisToString(selectableDateMillis) DatePickerDialog( onDismissRequest = { onDismiss() }, confirmButton = { Button( onClick = { onDateSelected(selectableDate) onDateMillisSelected(selectableDateMillis) onDismiss() } ) { Text("Ok") } }, dismissButton = { Button(onClick = { onDismiss() }) { Text("Cancel") } } ) { DatePicker(state = datePickerState) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/DatePicker.kt
511624461
package com.bangkit.edims.core.utils import androidx.sqlite.db.SimpleSQLiteQuery import com.bangkit.edims.core.utils.DateConverter.dayToMillis object Filter { fun getFilterQuery(filter: ProductFilterType): SimpleSQLiteQuery { val currentTime = System.currentTimeMillis() val almostFilter = currentTime + dayToMillis(30) val goodFilter = currentTime + dayToMillis(90) val simpleQuery = StringBuilder().append("SELECT * FROM product ") when (filter) { ProductFilterType.BAD_PRODUCTS -> { simpleQuery.append("WHERE dueDateMillis <= $currentTime ") } ProductFilterType.ALMOST_PRODUCTS -> { simpleQuery.append("WHERE dueDateMillis <= $almostFilter AND dueDateMillis > $currentTime ") } ProductFilterType.GOOD_PRODUCTS -> { simpleQuery.append("WHERE dueDateMillis <= $goodFilter AND dueDateMillis > $almostFilter ") } ProductFilterType.FRESH_PRODUCTS -> { simpleQuery.append("WHERE dueDateMillis > $goodFilter ") } } simpleQuery.append("ORDER BY dueDateMillis ASC") return SimpleSQLiteQuery(simpleQuery.toString()) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/Filter.kt
2052214750
package com.bangkit.edims.core.utils class Validation { companion object { fun validateEmail(email: String): Boolean { return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches() } fun validatePassword(password: String): Boolean { return password.length >= 8 } fun validateUsername(username: String): Boolean { return username.length >= 6 } fun validateEmpty(text: String) : Boolean { return text.isNotEmpty() } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/Validation.kt
3773564377
package com.bangkit.edims.core.utils import java.util.concurrent.Executors const val NOTIFICATION_CHANNEL_NAME = "EDIMS Channel" const val NOTIFICATION_CHANNEL_ID = "notify-schedule" const val NOTIFICATION_ID = 51 const val ID_REPEATING = 140 private val SINGLE_EXECUTOR = Executors.newSingleThreadExecutor() fun executeThread(f: () -> Unit) { SINGLE_EXECUTOR.execute(f) }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/Constant.kt
3452745160
package com.bangkit.edims.core.utils import android.app.Activity import android.content.Context import android.content.ContextWrapper import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.ui.platform.LocalContext @Composable fun LockScreenOrientation(orientation: Int) { val context = LocalContext.current DisposableEffect(Unit) { val activity = context.findActivity() ?: return@DisposableEffect onDispose {} val originalOrientation = activity.requestedOrientation activity.requestedOrientation = orientation onDispose { activity.requestedOrientation = originalOrientation } } } fun Context.findActivity(): Activity? = when (this) { is Activity -> this is ContextWrapper -> baseContext.findActivity() else -> null }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/LockScreenOrientation.kt
859471201
package com.bangkit.edims.core.utils import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.PermissionRequired import com.google.accompanist.permissions.rememberPermissionState @OptIn(ExperimentalPermissionsApi::class) @Composable fun Permission( permission: String = android.Manifest.permission.CAMERA, rationale: String = "Please grant the permission.", permissionNotAvailableContent: @Composable () -> Unit = { }, content: @Composable () -> Unit = { } ) { val permissionState = rememberPermissionState(permission) PermissionRequired( permissionState = permissionState, permissionNotGrantedContent = { Rationale( text = rationale, onRequestPermission = { permissionState.launchPermissionRequest() } ) }, permissionNotAvailableContent = permissionNotAvailableContent, content = content ) } @Composable private fun Rationale( text: String, onRequestPermission: () -> Unit ) { AlertDialog( onDismissRequest = {}, title = { Text(text = "Permission request") }, text = { Text(text) }, confirmButton = { Button(onClick = onRequestPermission) { Text("Ok") } } ) }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/Permission.kt
2926865634
package com.bangkit.edims.core.utils import android.icu.util.Calendar import java.text.SimpleDateFormat import java.util.Locale object DateConverter { fun convertMillisToString(timeMillis: Long): String { val calendar = Calendar.getInstance() calendar.timeInMillis = timeMillis val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) return dateFormat.format(calendar.time) } private fun remainingTime(timeMillis: Long): Long { val currentTime = System.currentTimeMillis() val calendar = Calendar.getInstance() calendar.timeInMillis = timeMillis return calendar.timeInMillis - currentTime } fun remainingHours(timeMillis: Long): Long { val diffMillis = remainingTime(timeMillis) return diffMillis / (60 * 60 * 1000) } fun remainingDays(timeMillis: Long): Long { val diffMillis = remainingTime(timeMillis) return diffMillis / (24 * 60 * 60 * 1000) } fun dayToMillis(days: Long): Long { val millisInDay = 24 * 60 * 60 * 1000 return days * millisInDay } }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/DateConverter.kt
1462879096
package com.bangkit.edims.core.utils enum class ProductFilterType { FRESH_PRODUCTS, GOOD_PRODUCTS, ALMOST_PRODUCTS, BAD_PRODUCTS }
Edims/EDIMS/src/main/java/com/bangkit/edims/core/utils/ProductFilterType.kt
3139634201
package com.bangkit.edims.notification import android.app.AlarmManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.icu.util.Calendar import com.bangkit.edims.core.utils.ID_REPEATING class NotificationWorker : BroadcastReceiver() { private val notificationHelper: NotificationHelper by lazy { NotificationHelper() } override fun onReceive(context: Context, intent: Intent) { notificationHelper.onReceive(context) } fun setDailyReminder(context: Context) { val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager val intent = Intent(context, NotificationWorker::class.java) val pendingIntent = PendingIntent.getBroadcast( context, ID_REPEATING, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) val calendar = Calendar.getInstance().apply { timeInMillis = System.currentTimeMillis() set(Calendar.HOUR_OF_DAY, 8) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) } alarmManager.setRepeating( AlarmManager.RTC, calendar.timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent ) } fun cancelAlarm(context: Context) { val intent = Intent(context, NotificationWorker::class.java) val pendingIntent = PendingIntent.getBroadcast( context, ID_REPEATING, intent, PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(pendingIntent) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/notification/NotificationWorker.kt
2339835826
package com.bangkit.edims.notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import com.bangkit.edims.R import com.bangkit.edims.core.utils.DateConverter import com.bangkit.edims.core.utils.NOTIFICATION_CHANNEL_ID import com.bangkit.edims.core.utils.NOTIFICATION_CHANNEL_NAME import com.bangkit.edims.core.utils.NOTIFICATION_ID import com.bangkit.edims.core.utils.executeThread import com.bangkit.edims.database.Product import com.bangkit.edims.database.ProductRepository import com.bangkit.edims.presentation.main.MainActivity import org.koin.core.component.KoinComponent import org.koin.core.component.inject class NotificationHelper : KoinComponent { private val repository : ProductRepository by inject() fun onReceive(context: Context) { executeThread { val listProduct = repository.getNearestItems() showNotification(context, listProduct) } } private fun showNotification(context: Context, content: List<Product>) { val notificationStyle = NotificationCompat.InboxStyle() content.forEach { val date = DateConverter.convertMillisToString(it.dueDateMillis) val message = ("$date - ${it.name}") notificationStyle.addLine(message) } val notificationIntent = Intent(context, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity( context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("Almost Expired Product") .setContentIntent(pendingIntent) .setStyle(notificationStyle) .setPriority(NotificationManager.IMPORTANCE_DEFAULT) .setAutoCancel(true) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "Product Reminder" enableVibration(true) vibrationPattern = longArrayOf(100, 200, 300) } notification.setChannelId(NOTIFICATION_CHANNEL_ID) notificationManager.createNotificationChannel(channel) } notificationManager.notify(NOTIFICATION_ID, notification.build()) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/notification/NotificationHelper.kt
889391124
package com.bangkit.edims.data sealed class Result<out T : Any?> { object Loading : Result<Nothing>() data class Success<out T : Any>(val data: T) : Result<T>() data class Error(val errorMessage: String) : Result<Nothing>() }
Edims/EDIMS/src/main/java/com/bangkit/edims/data/Result.kt
4070620577
package com.bangkit.edims.data import androidx.test.espresso.idling.CountingIdlingResource object EspressoIdlingResource { private const val RESOURCE = "GLOBAL" @JvmField val countingIdlingResource = CountingIdlingResource(RESOURCE) fun increment() { countingIdlingResource.increment() } fun decrement() { if (!countingIdlingResource.isIdleNow) { countingIdlingResource.decrement() } } } inline fun <T> wrapEspressoIdlingResource(function: () -> T): T { EspressoIdlingResource.increment() return try { function() } finally { EspressoIdlingResource.decrement() } }
Edims/EDIMS/src/main/java/com/bangkit/edims/data/EspressoIdlingResource.kt
3002226924
package com.bangkit.edims.data.retrofit data class SignupRequest( val email : String, val username : String, val password : String, )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/SignupRequest.kt
3823597779
package com.bangkit.edims.data.retrofit import com.google.gson.annotations.SerializedName data class UploadResponse( @field:SerializedName("item") val item: Item? = null, @field:SerializedName("message") val message: String? = null ) data class Item( @field:SerializedName("date") val date: String? = null, @field:SerializedName("image") val image: String? = null, @field:SerializedName("name") val name: String? = null, @field:SerializedName("id") val id: Int? = null, @field:SerializedName("category") val category: String? = null, @field:SerializedName("userid") val userid: Int? = null )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/UploadResponse.kt
3198583589
package com.bangkit.edims.data.retrofit import com.google.gson.annotations.SerializedName data class ErrorResponse( @field:SerializedName("message") val message: String, )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/ErrorResponse.kt
3798906666
package com.bangkit.edims.data.retrofit import com.google.gson.annotations.SerializedName data class ItemsResponse ( @field:SerializedName("message") val message : String, @field:SerializedName("items") val items : List<Items> ) data class Items( @field:SerializedName("userId") val userId: Int, @field:SerializedName("id") val id : Int, @field:SerializedName("name") val name : String, @field:SerializedName("image") val image : String, @field:SerializedName("category") val category : String, @field:SerializedName("dueDateMillis") val dueDataMillis : String, )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/ItemsResponse.kt
1216290288
package com.bangkit.edims.data.retrofit data class LoginRequest( val email : String, val password : String )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/LoginRequest.kt
822499780
package com.bangkit.edims.data.retrofit import com.bangkit.edims.database.UserPreference import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class ApiConfig { companion object { fun getApiService(userPreference: UserPreference): ApiService { val token = runBlocking { userPreference.token.first() } val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY) val authInterceptor = Interceptor { chain -> val req = chain.request() val requestHeaders = req.newBuilder() .addHeader("Authorization", "Bearer $token") .build() chain.proceed(requestHeaders) } val client = OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .addInterceptor(authInterceptor) .build() val retrofit = Retrofit.Builder() .baseUrl("https://edims-capstone-project-407010.et.r.appspot.com/") .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() return retrofit.create(ApiService::class.java) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/ApiConfig.kt
885628211
package com.bangkit.edims.data.retrofit import okhttp3.MultipartBody import okhttp3.RequestBody import retrofit2.Response import retrofit2.http.Body import retrofit2.http.DELETE import retrofit2.http.FormUrlEncoded import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Path interface ApiService { @POST("register") suspend fun signup( @Body signupRequest: SignupRequest ) : Response<SignupResponse> @POST("login") suspend fun login( @Body loginRequest: LoginRequest ) : Response<LoginResponse> @GET("items") suspend fun getProducts() : Response<ItemsResponse> @FormUrlEncoded @POST("item") suspend fun uploadProduct( @Part("name") name: RequestBody, @Part file : MultipartBody.Part, @Part("category") category: RequestBody, @Part("date") date : RequestBody ) : Response<UploadResponse> @DELETE("item/{id}") suspend fun deleteProducts( @Path("id") id : Int ) : Response<ErrorResponse> }
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/ApiService.kt
1155492107
package com.bangkit.edims.data.retrofit import com.google.gson.annotations.SerializedName data class LoginResponse( @field:SerializedName("message") val message: String, @field:SerializedName("user") val user: UserData, @field:SerializedName("token") val token: String ) data class UserData( @field:SerializedName("id") val id: Int, @field:SerializedName("username") val username: String, @field:SerializedName("email") val email: String, )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/LoginResponse.kt
3153385383
package com.bangkit.edims.data.retrofit import com.google.gson.annotations.SerializedName data class SignupResponse( @field:SerializedName("message") val message : String )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/retrofit/SignupResponse.kt
3700214545
package com.bangkit.edims.data data class User( val userId: Int?, val username: String?, val email: String?, val imageProfile: String?, val token: String?, )
Edims/EDIMS/src/main/java/com/bangkit/edims/data/User.kt
4236741698
package com.bangkit.edims.presentation.ui.settings import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.unit.dp import com.bangkit.edims.R import com.bangkit.edims.core.utils.Permission import com.bangkit.edims.notification.NotificationWorker import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.PaleLeaf import com.bangkit.edims.presentation.theme.Tacao @Composable fun SettingsScreen( modifier: Modifier = Modifier, context : Context, settingsViewModel: SettingsViewModel, navigateBack: () -> Unit ) { val notificationSettings by settingsViewModel.getNotificationSettings().collectAsState(initial = false) LaunchedEffect(notificationSettings) { val notif = NotificationWorker() if (notificationSettings) { notif.setDailyReminder(context) } else { notif.cancelAlarm(context) } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Permission( permission = Manifest.permission.POST_NOTIFICATIONS, rationale = "Please grant the permission.", permissionNotAvailableContent = { Column(modifier) { Text("No notifications") Spacer(modifier = Modifier.height(8.dp)) Button(onClick = { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.fromParts("package", context.packageName, null) }) }) { Text("Open Settings") } } } ) } SettingsContent( modifier = modifier, saveNotificationSettings = settingsViewModel::saveNotificationSettings, notificationSettings = notificationSettings, navigateBack = navigateBack ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun SettingsContent( modifier: Modifier = Modifier, saveNotificationSettings: (Boolean) -> Unit, notificationSettings: Boolean, navigateBack: () -> Unit ) { Scaffold( topBar = { TopAppBar( title = { Text( text = "Settings", style = MaterialTheme.typography.headlineSmall ) }, navigationIcon = { Icon( imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = "Back", modifier = Modifier .clickable { navigateBack() } ) }, colors = TopAppBarDefaults.topAppBarColors(containerColor = PaleLeaf) ) } ) { innerPadding -> Column( modifier = modifier .fillMaxSize() .background(Beige) .padding(innerPadding), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(20.dp)) NotificationSettings( saveNotificationSettings = saveNotificationSettings, notificationSettings = notificationSettings ) } } } @Composable private fun NotificationSettings( modifier: Modifier = Modifier, saveNotificationSettings: (Boolean) -> Unit, notificationSettings: Boolean, ) { Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) ) { Row( modifier = modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Text( text = stringResource(id = R.string.settings_turn_on_notif), style = MaterialTheme.typography.titleMedium, color = Color.Black ) Spacer(modifier = Modifier.weight(1f)) Switch( checked = notificationSettings, onCheckedChange = { saveNotificationSettings(!notificationSettings) }, colors = SwitchDefaults.colors( checkedBorderColor = Color.Transparent, checkedThumbColor = Color.White, checkedTrackColor = Tacao, uncheckedBorderColor = Tacao, uncheckedThumbColor = Tacao, uncheckedTrackColor = Color.White ) ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/settings/SettingsScreen.kt
2806999085
package com.bangkit.edims.presentation.ui.settings import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch class SettingsViewModel(private val repository: ProductRepository) : ViewModel() { fun saveNotificationSettings(status: Boolean) { viewModelScope.launch { repository.saveNotificationSettings(status) } } fun getNotificationSettings() : Flow<Boolean> { return repository.getNotificationSettings() } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/settings/SettingsViewModel.kt
2033981760
package com.bangkit.edims.presentation.ui.home import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.core.utils.ProductFilterType import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.data.retrofit.ItemsResponse import com.bangkit.edims.database.Product import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class HomeViewModel(private val repository: ProductRepository) : ViewModel() { private val _result: MutableStateFlow<Result<User>> = MutableStateFlow(Result.Loading) val result: StateFlow<Result<User>> get() = _result private val _resultApi: MutableStateFlow<Result<ItemsResponse>> = MutableStateFlow(Result.Loading) val resultApi: StateFlow<Result<ItemsResponse>> get() = _resultApi val isDataFetched = repository.isDataFetched() fun getFilteredProducts(filter: ProductFilterType): Flow<List<Product>> { return repository.getItems(filter) } fun getUserData() { viewModelScope.launch { repository.getUserData() .catch { _result.value = Result.Error(it.message.toString()) } .collect { _result.value = Result.Success(it) } } } fun getAllData() { viewModelScope.launch { if (!repository.isDataFetched()) { repository.getAllData() .collect { _resultApi.value = it } } } } fun addData(listProduct: List<Product>) { viewModelScope.launch { repository.insertAll(listProduct) } } fun resetResultApi() { _resultApi.value = Result.Loading } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/home/HomeViewModel.kt
4276040376
package com.bangkit.edims.presentation.ui.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row 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.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue 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.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.bangkit.edims.R import com.bangkit.edims.core.utils.ProductFilterType import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.database.Product import com.bangkit.edims.presentation.components.card.CardItem import com.bangkit.edims.presentation.components.card.ExpandableCard import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.MyProjectTheme import com.bangkit.edims.presentation.theme.PaleLeaf @Composable fun HomeScreen( modifier: Modifier = Modifier, homeViewModel: HomeViewModel, navigateToDetail: (Int) -> Unit, ) { val isFetched = homeViewModel.isDataFetched if (!isFetched) { val resultApi by homeViewModel.resultApi.collectAsState() LaunchedEffect(resultApi) { when (resultApi) { Result.Loading -> { homeViewModel.getAllData() } is Result.Success -> { val resultGet = (resultApi as Result.Success).data val resultItem = resultGet.items val listProduct = resultItem.map { Product(it.id, it.name, it.image, it.category, System.currentTimeMillis()) } homeViewModel.addData(listProduct) } is Result.Error -> { homeViewModel.resetResultApi() } } } } val badProducts by homeViewModel.getFilteredProducts(ProductFilterType.BAD_PRODUCTS) .collectAsState( initial = emptyList() ) val almostProducts by homeViewModel.getFilteredProducts(ProductFilterType.ALMOST_PRODUCTS) .collectAsState( initial = emptyList() ) val goodProducts by homeViewModel.getFilteredProducts(ProductFilterType.GOOD_PRODUCTS) .collectAsState( initial = emptyList() ) val freshProducts by homeViewModel.getFilteredProducts(ProductFilterType.FRESH_PRODUCTS) .collectAsState( initial = emptyList() ) val result by homeViewModel.result.collectAsState() when (result) { Result.Loading -> { homeViewModel.getUserData() } is Result.Success -> { val userData = (result as Result.Success).data HomeContent( modifier = modifier, userData = userData, badProducts = badProducts, almostProducts = almostProducts, goodProducts = goodProducts, freshProducts = freshProducts, navigateToDetail = navigateToDetail, ) } is Result.Error -> { val errorMessage = (result as Result.Error).errorMessage Box( modifier = Modifier.fillMaxSize() ) { Text( text = errorMessage, style = MaterialTheme.typography.bodyLarge, modifier = Modifier .align(Alignment.Center) ) } } } } @Composable private fun HomeContent( modifier: Modifier = Modifier, userData: User, badProducts: List<Product>, almostProducts: List<Product>, goodProducts: List<Product>, freshProducts: List<Product>, navigateToDetail: (Int) -> Unit, ) { val imageProfile = userData.imageProfile val profileUsername = userData.username Column( modifier = modifier .fillMaxSize() .background(PaleLeaf) ) { ProfileBar( profileIcon = imageProfile, profileUsername = profileUsername, ) CardContent( modifier = Modifier .fillMaxHeight(), badProducts = badProducts, almostProducts = almostProducts, goodProducts = goodProducts, freshProducts = freshProducts, navigateToDetail = navigateToDetail ) } } @Composable private fun ProfileBar( modifier: Modifier = Modifier, profileIcon: String?, profileUsername: String?, ) { Box( modifier = modifier .fillMaxWidth() .height(100.dp) .background(PaleLeaf) ) { Row( modifier = Modifier .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(80.dp) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(profileIcon) .crossfade(true) .build(), contentDescription = "Profile Image", placeholder = painterResource(R.drawable.ic_user), modifier = Modifier .fillMaxSize() .padding(8.dp) .clip(CircleShape), contentScale = ContentScale.Fit, error = painterResource(R.drawable.ic_user), ) } Column( modifier = Modifier .padding(8.dp) .weight(1f), ) { Text( text = stringResource(id = R.string.home_greeting), style = MaterialTheme.typography.titleMedium ) Text( text = profileUsername ?: stringResource(id = R.string.home_default_name), style = MaterialTheme.typography.titleMedium ) } } } } @Composable private fun CardContent( modifier : Modifier = Modifier, badProducts: List<Product>, almostProducts: List<Product>, goodProducts: List<Product>, freshProducts: List<Product>, navigateToDetail: (Int) -> Unit, ) { val cardItems = listOf( CardItem( id = 1, title = stringResource(id = R.string.card_status_bad), icon = R.drawable.ic_status_bad, color = Color.Red, listItem = badProducts ), CardItem( id = 2, title = stringResource(id = R.string.card_status_soon), icon = R.drawable.ic_status_almost, color = Color.Yellow, listItem = almostProducts ), CardItem( id = 3, title = stringResource(id = R.string.card_status_good), icon = R.drawable.ic_status_good, color = Color.Cyan, listItem = goodProducts ), CardItem( id = 4, title = stringResource(id = R.string.card_status_good), icon = R.drawable.ic_status_fresh, color = Color.Green, listItem = freshProducts ) ) Column( modifier = modifier .fillMaxSize() .clip(RoundedCornerShape(30.dp, 30.dp, 0.dp, 0.dp)) .background(Beige), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.home_title), style = MaterialTheme.typography.titleLarge.copy( fontWeight = FontWeight.Bold ), modifier = Modifier .padding(16.dp) ) LazyColumn { items(cardItems){item -> ExpandableCard( listItem = item.listItem, icon = painterResource(item.icon), title = item.title, color = item.color, navigateToDetail = navigateToDetail ) } } } } @Preview(showBackground = true) @Composable fun CardPreview() { val fakeList = listOf( Product( id = 1, name = "haha", image = "haha", category = "haha", dueDateMillis = 1701849080356, ), Product( id = 2, name = "haha", image = "haha", category = "haha", dueDateMillis = 1702449080356, ) ) MyProjectTheme { HomeContent( userData = User( userId = null, username = null, email = null, imageProfile = null, token = null ), badProducts = emptyList(), almostProducts = fakeList, goodProducts = emptyList(), freshProducts = emptyList(), navigateToDetail = {}, ) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/home/HomeScreen.kt
3084295041
package com.bangkit.edims.presentation.ui.splash import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.res.stringResource import com.bangkit.edims.R import com.bangkit.edims.presentation.theme.PaleLeaf import com.bangkit.edims.presentation.theme.Sulu import com.bangkit.edims.presentation.theme.White import kotlinx.coroutines.delay @Composable fun SplashScreen( modifier: Modifier = Modifier, navigateNext: () -> Unit ) { val gradiantBackground = Brush.horizontalGradient( 0.0f to PaleLeaf, 1.0f to Sulu, startX = 0.0f, endX = 1000.0f ) Box( modifier = modifier .fillMaxSize() .background(gradiantBackground), contentAlignment = Alignment.Center ) { Text(text = stringResource(R.string.app_name), style = MaterialTheme.typography.displayLarge, color = White) } LaunchedEffect(Unit) { delay(2000) navigateNext() } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/splash/SplashScreen.kt
3149352022
package com.bangkit.edims.presentation.ui.signup import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.verticalScroll import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.bangkit.edims.R import com.bangkit.edims.core.utils.Validation import com.bangkit.edims.data.Result import com.bangkit.edims.presentation.components.button.CustomContainedButton import com.bangkit.edims.presentation.components.loading.ShowLoading import com.bangkit.edims.presentation.components.text.CustomTextField import com.bangkit.edims.presentation.theme.PaleLeaf @Composable fun SignUpScreen( viewModel: SignUpViewModel, showSnackbar: (String, SnackbarDuration) -> Unit, navigateToLogin: () -> Unit, ) { val result by viewModel.result.collectAsState() var showLoading by remember { mutableStateOf(false) } if (showLoading) { ShowLoading( modifier = Modifier .zIndex(2f) .background(Color.Gray.copy(alpha = 0.2f)) ) } LaunchedEffect(result) { when (result) { Result.Loading -> {} is Result.Success -> { val signupResult = (result as Result.Success).data showSnackbar(signupResult.message, SnackbarDuration.Short) showLoading = false navigateToLogin() } is Result.Error -> { val errorMessage = (result as Result.Error).errorMessage showSnackbar(errorMessage, SnackbarDuration.Short) showLoading = false viewModel.resetResult() } } } var username by remember { mutableStateOf("") } var usernameValid by remember { mutableStateOf(true) } var email by remember { mutableStateOf("") } var emailValid by remember { mutableStateOf(true) } var password by remember { mutableStateOf("") } var passwordValid by remember { mutableStateOf(true) } var confirmPassword by remember { mutableStateOf("") } var confirmPasswordValid by remember { mutableStateOf(true) } var isPasswordVisible by remember { mutableStateOf(false) } var isConfirmPasswordVisible by remember { mutableStateOf(false) } Column( modifier = Modifier .padding(all = 16.dp) .verticalScroll(rememberScrollState()), ) { Image( painterResource(R.drawable.signup_logo), "Logo Sign Up", modifier = Modifier .size(250.dp) .align(Alignment.CenterHorizontally) ) Text(text = "Sign Up", style = MaterialTheme.typography.headlineLarge) Spacer(modifier = Modifier.height(16.dp)) CustomTextField( placeholder = "Username", text = username, errorMessage = stringResource(R.string.username_validation), onValueChange = { username = it usernameValid = Validation.validateUsername(username) }, isError = !usernameValid ) CustomTextField( placeholder = "Email", text = email, errorMessage = stringResource(R.string.email_validation), onValueChange = { email = it emailValid = Validation.validateEmail(email) }, isError = !emailValid ) CustomTextField(placeholder = "Password", text = password, errorMessage = stringResource(R.string.password_validation), onValueChange = { password = it passwordValid = Validation.validatePassword(password) }, isError = !passwordValid, isVisible = isPasswordVisible, trailingIcon = { IconButton( onClick = { isPasswordVisible = !isPasswordVisible } ) { if (isPasswordVisible) { Image( painterResource(R.drawable.ic_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } else { Image( painterResource(R.drawable.ic_non_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } } }) CustomTextField(placeholder = "Confirm Password", text = confirmPassword, errorMessage = stringResource(R.string.confirm_password_validation), onValueChange = { confirmPassword = it confirmPasswordValid = confirmPassword == password }, isError = !confirmPasswordValid, isVisible = isConfirmPasswordVisible, trailingIcon = { IconButton( onClick = { isConfirmPasswordVisible = !isConfirmPasswordVisible } ) { if (isConfirmPasswordVisible) { Image( painterResource(R.drawable.ic_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } else { Image( painterResource(R.drawable.ic_non_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } } }) CustomContainedButton( isEnabled = usernameValid && emailValid && passwordValid && confirmPasswordValid && (username != "") && (email != "") && (password != "") && (confirmPassword != ""), text = "Sign Up", onClick = { viewModel.signUp(username, email, password) showLoading = true }) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier.align(Alignment.CenterHorizontally) ) { Text(text = "Already have an account? ", style = MaterialTheme.typography.bodyLarge) ClickableText( modifier = Modifier.drawBehind { val strokeWidthPx = 1.dp.toPx() val verticalOffset = size.height - size.height / 3 drawLine( color = PaleLeaf, strokeWidth = strokeWidthPx, start = Offset(0f, verticalOffset), end = Offset(size.width, verticalOffset) ) }, text = AnnotatedString("Login"), onClick = { navigateToLogin() }, style = MaterialTheme.typography.bodyLarge.copy(color = PaleLeaf) ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/signup/SignUpScreen.kt
745238986
package com.bangkit.edims.presentation.ui.signup import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.data.Result import com.bangkit.edims.data.retrofit.SignupResponse import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch class SignUpViewModel(private val repository: ProductRepository) : ViewModel() { private val _result: MutableStateFlow<Result<SignupResponse>> = MutableStateFlow(Result.Loading) val result: MutableStateFlow<Result<SignupResponse>> get() = _result fun signUp(username: String, email: String, password: String) { viewModelScope.launch { repository.signup(email, username, password) .collect { _result.value = it } } } fun resetResult() { _result.value = Result.Loading } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/signup/SignUpViewModel.kt
2404493412
package com.bangkit.edims.presentation.ui.detail import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.data.Result import com.bangkit.edims.data.retrofit.ErrorResponse import com.bangkit.edims.database.Product import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class DetailViewModel(private val repository: ProductRepository) : ViewModel() { private val _result: MutableStateFlow<Result<Product>> = MutableStateFlow(Result.Loading) val result: StateFlow<Result<Product>> get() = _result private val _resultApi: MutableStateFlow<Result<ErrorResponse>> = MutableStateFlow(Result.Loading) val resultApi: StateFlow<Result<ErrorResponse>> get() = _resultApi suspend fun delete(product: Product) { repository.delete(product) repository.deleteProductApi(product.id) .collect{ _resultApi.value = it } } fun getProductById(id: Int) { viewModelScope.launch { repository.getItemsById(id) .catch { _result.value = Result.Error(it.message.toString()) } .collect { _result.value = Result.Success(it) } } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/detail/DetailViewModel.kt
2808588373
package com.bangkit.edims.presentation.ui.detail import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.scrollable 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.rememberScrollState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft import androidx.compose.material.icons.filled.Category import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.graphics.vector.ImageVector import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import coil.compose.AsyncImage import coil.request.ImageRequest import com.bangkit.edims.R import com.bangkit.edims.core.utils.DateConverter import com.bangkit.edims.data.Result import com.bangkit.edims.database.Product import com.bangkit.edims.presentation.components.loading.ShowLoading import com.bangkit.edims.presentation.components.shimmer.AnimatedShimmer import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.PaleLeaf import kotlinx.coroutines.delay @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailScreen( modifier: Modifier = Modifier, detailViewModel: DetailViewModel, id: Int, showSnackbar: (String, SnackbarDuration) -> Unit, navigateBack: (Product?) -> Unit, ) { val result by detailViewModel.result.collectAsState() var buttonStatus by remember { mutableStateOf(false) } Scaffold( topBar = { TopAppBar( title = { Text(text = stringResource(id = R.string.detail_title)) }, navigationIcon = { Icon( imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft, contentDescription = "Back", modifier = Modifier .clickable{ navigateBack(null) } ) }, actions = { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete", modifier = Modifier .padding(end = 8.dp) .clickable( enabled = buttonStatus ) { val product = (result as Result.Success<Product>).data showSnackbar("Deleting...", SnackbarDuration.Short) navigateBack(product) } ) }, colors = TopAppBarDefaults.topAppBarColors(PaleLeaf) ) } ) { innerPadding -> when (result) { Result.Loading -> { buttonStatus = false ShowLoading(modifier.fillMaxSize()) LaunchedEffect(key1 = Unit) { delay(500) detailViewModel.getProductById(id) } } is Result.Success -> { buttonStatus = true val item = (result as Result.Success<Product>).data val image = item.image val name = item.name val category = item.category val date = DateConverter.convertMillisToString(item.dueDateMillis) DetailContent( modifier = modifier.padding(innerPadding), image = image, name = name, date = date, category = category, ) } is Result.Error -> { buttonStatus = false val errorMessage = (result as Result.Error).errorMessage Box( modifier = Modifier.fillMaxSize() ) { Text( text = errorMessage, style = MaterialTheme.typography.bodyLarge, modifier = Modifier .align(Alignment.Center) ) } } } } } @Composable private fun DetailContent( modifier: Modifier = Modifier, image: String, name: String, date: String, category: String, ) { var showShimmer by remember { mutableStateOf(true) } var isDialogVisible by remember { mutableStateOf(false) } Column( modifier = modifier .fillMaxSize() .background(Beige) .scrollable(orientation = Orientation.Horizontal, state = rememberScrollState()) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(image) .crossfade(true) .build(), contentDescription = "Product Image", modifier = Modifier .background(AnimatedShimmer(showShimmer = showShimmer)) .height(200.dp) .fillMaxWidth() .clickable { isDialogVisible = true }, contentScale = ContentScale.Crop, placeholder = painterResource(R.drawable.ic_placeholder), onSuccess = { showShimmer = false }, onError = { showShimmer = false }, error = painterResource(R.drawable.ic_placeholder) ) Column( modifier = Modifier .padding(16.dp), horizontalAlignment = Alignment.Start ) { Text( text = name, style = MaterialTheme.typography.titleLarge, modifier = Modifier .padding(start = 8.dp) ) ProductInfo( icon = Icons.Default.Category, label = stringResource(id = R.string.detail_label_category), value = category, style = MaterialTheme.typography.bodyLarge ) ProductInfo( icon = Icons.Default.DateRange, label = stringResource(id = R.string.detail_label_date_expired), value = date, style = MaterialTheme.typography.bodyLarge ) } } if (isDialogVisible) { ShowFullImage( image = image, onDismiss = { isDialogVisible = false } ) } } @Composable private fun ShowFullImage( image: String, onDismiss: () -> Unit, ) { Dialog( onDismissRequest = { onDismiss() }, properties = DialogProperties( dismissOnClickOutside = true, dismissOnBackPress = true ), content = { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(image) .crossfade(true) .build(), contentDescription = "Product Image", modifier = Modifier .fillMaxSize() .padding(8.dp) .clickable { onDismiss() }, error = painterResource(R.drawable.ic_placeholder) ) } ) } @Composable private fun ProductInfo(icon: ImageVector, label: String, value: String, style: TextStyle) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = icon, contentDescription = null, modifier = Modifier .padding(8.dp) ) Column { Text( text = label, color = Color.Gray, style = style ) Spacer(modifier = Modifier.height(4.dp)) Text( text = value, color = Color.Black, style = style ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/detail/DetailScreen.kt
3611824936
package com.bangkit.edims.presentation.ui.add import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.data.Result import com.bangkit.edims.data.retrofit.UploadResponse import com.bangkit.edims.database.Product import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import okhttp3.MultipartBody import okhttp3.RequestBody class AddViewModel(private val repository: ProductRepository) : ViewModel() { private val _resultApi: MutableStateFlow<Result<UploadResponse>> = MutableStateFlow(Result.Loading) val resultApi: StateFlow<Result<UploadResponse>> get() = _resultApi fun insert(product : Product) { viewModelScope.launch { repository.insert(product) } } fun uploadProduct(name: RequestBody, imageFile: MultipartBody.Part, category: RequestBody, date: RequestBody) { viewModelScope.launch { repository.uploadProductApi(name, imageFile, category, date) .collect{ _resultApi.value = it } } } fun resetResult() { _resultApi.value = Result.Loading } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/add/AddViewModel.kt
4095586771
package com.bangkit.edims.presentation.ui.add import android.net.Uri import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.PhotoCamera import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.Text 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.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.core.net.toUri import coil.compose.AsyncImage import com.bangkit.edims.R import com.bangkit.edims.core.utils.DatePickerDialog import com.bangkit.edims.data.Result import com.bangkit.edims.database.Product import com.bangkit.edims.presentation.components.camera.CameraCapture import com.bangkit.edims.presentation.components.category.CategoryItem import com.bangkit.edims.presentation.components.loading.ShowLoading import com.bangkit.edims.presentation.components.shimmer.AnimatedShimmer import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.MyProjectTheme import com.bangkit.edims.presentation.theme.PaleLeaf import com.bangkit.edims.presentation.theme.Shapes import com.bangkit.edims.presentation.theme.Tacao @Composable fun AddScreen( addViewModel: AddViewModel, navigateToHome: () -> Unit, showSnackbar: (String, SnackbarDuration) -> Unit ) { val resultApi by addViewModel.resultApi.collectAsState() var showLoading by remember { mutableStateOf(false) } if (showLoading) { ShowLoading() } when (resultApi) { Result.Loading -> { showLoading = false } is Result.Success -> { val uploadResult = (resultApi as Result.Success).data val resultMessage = uploadResult.message showSnackbar(resultMessage.toString(), SnackbarDuration.Short) showLoading = false navigateToHome() } is Result.Error -> { val errorMessage = (resultApi as Result.Error).errorMessage showSnackbar(errorMessage, SnackbarDuration.Short) showLoading = false addViewModel.resetResult() } } Box( modifier = Modifier .fillMaxSize() .background(Beige) ) { AddContent( onSaveDataClick = addViewModel::insert, navigateToHome = navigateToHome, showLoading = { showLoading = it }, showSnackbar = showSnackbar ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddContent( onSaveDataClick: (Product) -> Unit, navigateToHome: () -> Unit, showLoading: (Boolean) -> Unit, showSnackbar: (String, SnackbarDuration) -> Unit ) { LocalContext.current var showShimmer by remember { mutableStateOf(true) } var inputName by remember { mutableStateOf("") } var inputDate by remember { mutableStateOf("") } var dueDateMillis by remember { mutableStateOf(System.currentTimeMillis()) } var selectedCategory by remember { mutableStateOf("") } var expanded by remember { mutableStateOf(false) } var imageUri by remember { mutableStateOf<Uri?>(null) } var cameraSelect by remember { mutableStateOf(false) } var showDatePicker by remember { mutableStateOf(false) } if (!cameraSelect) { Column( modifier = Modifier .padding(12.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Box( Modifier.fillMaxWidth() ) { Icon( imageVector = Icons.Default.Close, contentDescription = "Close", modifier = Modifier .padding(8.dp) .clickable { navigateToHome() } .align(Alignment.TopStart) ) Text( text = stringResource(id = R.string.add_title), style = MaterialTheme.typography.headlineSmall.copy( fontWeight = FontWeight.Bold ), modifier = Modifier .padding(16.dp) .align(Alignment.Center), ) } Box( modifier = Modifier .fillMaxWidth() .height(240.dp) .border(1.dp, Color.Black) ) { AsyncImage( model = imageUri, contentDescription = "Preview Image", modifier = Modifier .fillMaxSize() .padding(30.dp) .align(Alignment.Center) .background(AnimatedShimmer(showShimmer = showShimmer)), placeholder = painterResource(R.drawable.ic_placeholder), onSuccess = { showShimmer = false }, onError = { showShimmer = false }, error = painterResource(R.drawable.ic_placeholder) ) FloatingActionButton( onClick = { cameraSelect = true }, modifier = Modifier .padding(15.dp) .size(50.dp) .align(Alignment.BottomEnd), shape = CircleShape, containerColor = PaleLeaf, contentColor = Color.White ) { Icon( imageVector = Icons.Default.PhotoCamera, contentDescription = "Camera", modifier = Modifier .size(30.dp), ) } } OutlinedTextField( value = inputName, label = { Text(text = stringResource(id = R.string.add_text_field_name)) }, onValueChange = { newInput -> inputName = newInput }, shape = Shapes.medium, modifier = Modifier .fillMaxWidth() ) Row( modifier = Modifier .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { OutlinedTextField( value = inputDate, label = { Text(text = stringResource(id = R.string.add_text_field_date)) }, onValueChange = {}, readOnly = true, shape = Shapes.medium, modifier = Modifier .weight(1f) ) Icon( imageVector = Icons.Default.CalendarMonth, contentDescription = "Choose Date", modifier = Modifier .clickable { showDatePicker = true } .padding(8.dp) ) } ExposedDropdownMenuBox( expanded = expanded, onExpandedChange = { expanded = it }, modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp) ) { OutlinedTextField( value = selectedCategory.ifEmpty { stringResource(id = R.string.add_category_label) }, onValueChange = {}, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, modifier = Modifier .menuAnchor() .fillMaxWidth() ) ExposedDropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { val categoryItem = CategoryItem.items categoryItem.map { item -> DropdownMenuItem( text = { Text(item.name) }, onClick = { selectedCategory = item.name expanded = false }, leadingIcon = { Icon( imageVector = item.icon, contentDescription = null, ) } ) } } } Button( onClick = { showLoading(true) if (inputName.isNotEmpty() && selectedCategory.isNotEmpty() && imageUri != null) { // val imageFile = imageToFile(context, imageUri!!) // val nameReq = inputName.toRequestBody("text/plain".toMediaType()) // val categoryReq = selectedCategory.toRequestBody("text/plain".toMediaType()) // val date = dueDateMillis.toString().toRequestBody("text/plain".toMediaType()) // // onSaveApiClick( // nameReq, // imageFile, // categoryReq, // date // ) val product = Product ( name = inputName, image = imageUri.toString(), category = selectedCategory, dueDateMillis = dueDateMillis, ) onSaveDataClick(product) showSnackbar( "Success", SnackbarDuration.Short ) navigateToHome() } else { showSnackbar( "Please fill all the blank", SnackbarDuration.Short ) } }, shape = Shapes.medium, modifier = Modifier .width(120.dp) .height(40.dp), colors = ButtonDefaults.buttonColors(Tacao) ) { Text( text = stringResource(id = R.string.add_save_btn), style = MaterialTheme.typography.labelLarge ) } } } else { CameraCapture( onImageFile = { file -> imageUri = file.toUri() }, onDismiss = { cameraSelect = false } ) } if (showDatePicker) { DatePickerDialog( initialDateMillis = dueDateMillis, onDateSelected = { inputDate = it }, onDateMillisSelected = { dueDateMillis = it }, onDismiss = { showDatePicker = false } ) } } @Preview(showBackground = true) @Composable fun AddContentScreenPreview() { MyProjectTheme { AddContent( onSaveDataClick = {}, navigateToHome = {}, showLoading = {}, showSnackbar = { _, _ -> } ) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/add/AddScreen.kt
1202413550
package com.bangkit.edims.presentation.ui.profile import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.launch class ProfileViewModel (private val repository: ProductRepository) : ViewModel() { private val _result: MutableStateFlow<Result<User>> = MutableStateFlow(Result.Loading) val result: StateFlow<Result<User>> get() = _result fun getUserData() { viewModelScope.launch { repository.getUserData() .catch { _result.value = Result.Error(it.message.toString()) } .collect { _result.value = Result.Success(it) } } } fun logout() { viewModelScope.launch { repository.logout() } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/profile/ProfileViewModel.kt
1241969976
package com.bangkit.edims.presentation.ui.profile import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight import androidx.compose.material3.AlertDialog import androidx.compose.material3.Icon 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.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.bangkit.edims.R import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.presentation.components.shimmer.AnimatedShimmer import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.PaleLeaf import com.bangkit.edims.presentation.theme.Tacao @Composable fun ProfileScreen( modifier: Modifier = Modifier, profileViewModel: ProfileViewModel, navigateToLogOut: () -> Unit, navigateToSettings: () -> Unit, ) { val result by profileViewModel.result.collectAsState() when (result) { Result.Loading -> { profileViewModel.getUserData() } is Result.Success -> { val userData = (result as Result.Success).data ProfileScreenContent( modifier = modifier, userData = userData, navigateToLogOut = navigateToLogOut, navigateToSettings = navigateToSettings ) } is Result.Error -> { val errorMessage = (result as Result.Error).errorMessage Box( modifier = Modifier.fillMaxSize() ) { Text( text = errorMessage, style = MaterialTheme.typography.bodyLarge, modifier = Modifier .align(Alignment.Center) ) } } } } @Composable fun ProfileScreenContent( modifier: Modifier = Modifier, userData: User, navigateToLogOut: () -> Unit, navigateToSettings: () -> Unit, ) { val profileUsername = userData.username Column( modifier = modifier .fillMaxSize() .background(Beige) ) { ProfileBar( username = profileUsername ) ProfileContent( navigateToLogOut = navigateToLogOut, navigateToSettings = navigateToSettings ) } } @Composable private fun ProfileBar( modifier: Modifier = Modifier, username: String? ) { var showShimmer by remember { mutableStateOf(true) } Box( modifier = modifier .fillMaxWidth() .clip(RoundedCornerShape(0.dp, 0.dp, 30.dp, 30.dp)) .background(PaleLeaf) ) { Column( modifier = Modifier .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = R.string.profile_title), style = MaterialTheme.typography.headlineLarge.copy( fontWeight = FontWeight.Normal ), modifier = Modifier .padding(16.dp) ) Box( modifier = Modifier .size(110.dp) ) { Image( painter = painterResource(id = R.drawable.ic_user), contentDescription = "Profile Image", modifier = Modifier .fillMaxSize() .padding(8.dp) .clip(CircleShape) .background(Tacao) .align(Alignment.Center) .background(AnimatedShimmer(showShimmer = showShimmer)), contentScale = ContentScale.Crop, ) } Text( text = username ?: "Guest", style = MaterialTheme.typography.headlineMedium.copy( fontWeight = FontWeight.Normal ), modifier = Modifier.padding(8.dp) ) Spacer(modifier = Modifier.height(20.dp)) } } } @Composable fun ProfileContent( modifier: Modifier = Modifier, navigateToLogOut: () -> Unit, navigateToSettings: () -> Unit, ) { var showDialog by remember { mutableStateOf(false) } val settingsItems = listOf( R.string.profile_settings_items, R.string.profile_logout_items, ) Box( modifier = modifier .fillMaxSize() .background(Beige), ) { Column( modifier = Modifier .fillMaxWidth() .padding(30.dp) ) { settingsItems.map { ProfileItem( name = it, onSettingItemClick = { name -> when (name) { R.string.profile_settings_items -> navigateToSettings() R.string.profile_logout_items -> showDialog = true } }) Spacer(modifier = Modifier.height(4.dp)) } } } if (showDialog) { LogoutDialog( onDismiss = { showDialog = false }, onConfirm = { navigateToLogOut() showDialog = false } ) } } @Composable fun ProfileItem( name: Int, onSettingItemClick: (Int) -> Unit, ) { Row( modifier = Modifier .fillMaxWidth() .clickable { onSettingItemClick(name) }, ) { Text( text = stringResource(id = name), style = MaterialTheme.typography.titleMedium.copy( fontWeight = FontWeight.Bold ) ) Spacer(modifier = Modifier.weight(1f)) Icon( imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = null, modifier = Modifier.size(24.dp) ) } Spacer(modifier = Modifier.height(8.dp)) } @Composable private fun LogoutDialog( onDismiss: () -> Unit, onConfirm: () -> Unit ) { AlertDialog( title = { Text(text = "Log out") }, text = { Text(text = "Are you sure you want to logout?") }, onDismissRequest = { onDismiss() }, confirmButton = { TextButton(onClick = { onConfirm() }) { Text(text = "Yes", color = Color.Black) } }, dismissButton = { TextButton(onClick = { onDismiss() }) { Text(text = "No", color = Color.Black) } } ) }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/profile/ProfileScreen.kt
3632305021
package com.bangkit.edims.presentation.ui.login import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.bangkit.edims.data.Result import com.bangkit.edims.data.User import com.bangkit.edims.data.retrofit.LoginResponse import com.bangkit.edims.database.ProductRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch class LoginViewModel(private val repository: ProductRepository) : ViewModel() { private val _result: MutableStateFlow<Result<LoginResponse>> = MutableStateFlow(Result.Loading) val result: MutableStateFlow<Result<LoginResponse>> get() = _result fun loginUser(email: String, password: String) { viewModelScope.launch { repository.login(email, password) .collect { _result.value = it } } } fun saveLoginData(userId: Int, username: String, email: String, token: String) { val user = User( userId = userId, username = username, email = email, token = token, imageProfile = null ) viewModelScope.launch { repository.saveLoginData(user) } } fun resetResult() { _result.value = Result.Loading } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/login/LoginViewModel.kt
1532108009
package com.bangkit.edims.presentation.ui.login import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.ClickableText import androidx.compose.foundation.verticalScroll import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect 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.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp import com.bangkit.edims.R import com.bangkit.edims.core.utils.Validation import com.bangkit.edims.data.Result import com.bangkit.edims.presentation.components.button.CustomContainedButton import com.bangkit.edims.presentation.components.loading.ShowLoading import com.bangkit.edims.presentation.components.text.CustomTextField import com.bangkit.edims.presentation.theme.PaleLeaf @Composable fun LoginScreen( modifier: Modifier = Modifier, viewModel: LoginViewModel, showSnackbar: (String, SnackbarDuration) -> Unit, navigateToSignUp: () -> Unit, onLoginSuccess: () -> Unit, ) { val result by viewModel.result.collectAsState() var showLoading by remember { mutableStateOf(false) } if (showLoading) { ShowLoading() } LaunchedEffect(result) { when (result) { Result.Loading -> {} is Result.Success -> { val loginResult = (result as Result.Success).data val resultMessage = loginResult.message showSnackbar(resultMessage, SnackbarDuration.Short) showLoading = false val dataUser = loginResult.user val userId = dataUser.id val username = dataUser.username val email = dataUser.email val token = loginResult.token viewModel.saveLoginData(userId, username, email, token) onLoginSuccess() } is Result.Error -> { val errorMessage = (result as Result.Error).errorMessage showSnackbar(errorMessage, SnackbarDuration.Short) showLoading = false viewModel.resetResult() } } } var email by remember { mutableStateOf("") } var emailValid by remember { mutableStateOf(true) } var password by remember { mutableStateOf("") } var passwordValid by remember { mutableStateOf(true) } var isPasswordVisible by remember { mutableStateOf(false) } Column( modifier = modifier .padding(all = 16.dp) .verticalScroll(rememberScrollState()), ) { Image( painterResource(R.drawable.login_logo), "Logo Login", modifier = Modifier .size(250.dp) .align(Alignment.CenterHorizontally) ) Text(text = "Login", style = MaterialTheme.typography.headlineLarge) Spacer(modifier = Modifier.height(16.dp)) CustomTextField( placeholder = "Email", text = email, errorMessage = stringResource(R.string.email_validation), onValueChange = { email = it emailValid = Validation.validateEmail(email) }, isError = !emailValid ) CustomTextField(placeholder = "Password", text = password, errorMessage = stringResource(R.string.password_validation), onValueChange = { password = it passwordValid = Validation.validatePassword(password) }, isError = !passwordValid, isVisible = isPasswordVisible, trailingIcon = { IconButton(onClick = { isPasswordVisible = !isPasswordVisible }) { if (isPasswordVisible) { Image( painterResource(R.drawable.ic_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } else { Image( painterResource(R.drawable.ic_non_visible), "Password Visibility Toggle", modifier = Modifier.size(24.dp) ) } } }) CustomContainedButton( isEnabled = emailValid && passwordValid && (email != "") && (password != ""), text = "Login", onClick = { viewModel.loginUser(email, password) showLoading = true }, ) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier.align(Alignment.CenterHorizontally) ) { Text(text = "Don't have an account? ", style = MaterialTheme.typography.bodyLarge) ClickableText( modifier = Modifier.drawBehind { val strokeWidthPx = 1.dp.toPx() val verticalOffset = size.height - size.height / 3 drawLine( color = PaleLeaf, strokeWidth = strokeWidthPx, start = Offset(0f, verticalOffset), end = Offset(size.width, verticalOffset) ) }, text = AnnotatedString("Sign Up"), onClick = { navigateToSignUp() }, style = MaterialTheme.typography.bodyLarge.copy(color = PaleLeaf) ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/ui/login/LoginScreen.kt
2329472996
package com.bangkit.edims.presentation.components.card import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box 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.width 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.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.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.bangkit.edims.R import com.bangkit.edims.core.utils.DateConverter import com.bangkit.edims.presentation.components.shimmer.AnimatedShimmer import com.bangkit.edims.presentation.theme.Shapes @Composable fun ListItem( name: String, image: String, dueDateMillis: Long, modifier: Modifier = Modifier ) { val remainingTime = DateConverter.remainingDays(dueDateMillis) val remainingHours = DateConverter.remainingHours(dueDateMillis) val labelRemaining by remember { mutableStateOf( when { remainingTime < 0 -> "Expired" remainingHours < 0 -> "Expired" remainingTime < 1 -> { "$remainingHours hours" } remainingTime < 30 -> "$remainingTime days" remainingTime < 90 -> ">1 Month" else -> ">3 Months" } ) } var showShimmer by remember { mutableStateOf(true) } Card( modifier = modifier, elevation = CardDefaults.cardElevation( defaultElevation = 2.dp ), shape = Shapes.medium, ) { Row( modifier = Modifier .fillMaxWidth(), ) { Box( modifier = Modifier .align(Alignment.CenterVertically) .height(60.dp) .width(80.dp) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(image) .crossfade(true) .build(), contentDescription = null, modifier = Modifier .fillMaxSize() .clip(Shapes.medium) .padding(5.dp) .background(AnimatedShimmer(showShimmer = showShimmer)), placeholder = painterResource(R.drawable.ic_placeholder), onSuccess = { showShimmer = false }, onError = { showShimmer = false }, error = painterResource(R.drawable.ic_placeholder), contentScale = ContentScale.Crop ) } Text( text = name, maxLines = 3, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleMedium.copy( fontWeight = FontWeight.Bold ), modifier = Modifier .align(Alignment.CenterVertically) ) Spacer(modifier = Modifier.weight(1f)) Text( text = labelRemaining, maxLines = 2, style = MaterialTheme.typography.labelLarge.copy( fontWeight = FontWeight.Bold ), modifier = Modifier .padding(12.dp) ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/card/ListItem.kt
3458485308
package com.bangkit.edims.presentation.components.card import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable 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.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.bangkit.edims.database.Product import com.bangkit.edims.presentation.theme.Shapes @Composable fun ExpandableCard( modifier: Modifier = Modifier, listItem: List<Product>, icon: Painter, title: String, color: Color, navigateToDetail: (Int) -> Unit, ) { var expandedState by remember { mutableStateOf(false) } val rotationState by animateFloatAsState( targetValue = if (expandedState) 180f else 0f, label = "Drop-down" ) Column( modifier = Modifier .padding(horizontal = 12.dp, vertical = 6.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Card( modifier = Modifier .fillMaxWidth() .animateContentSize( animationSpec = tween( delayMillis = 300, easing = LinearOutSlowInEasing ) ), shape = Shapes.medium, onClick = { expandedState = !expandedState } ) { Row( modifier = Modifier .fillMaxWidth() .background(color = color.copy(alpha = 0.8f)), verticalAlignment = Alignment.CenterVertically ) { Icon( painter = icon, contentDescription = null, modifier = Modifier .size(80.dp) .clip(CircleShape), ) Column(modifier = Modifier.weight(1f)) { Text( text = title, style = MaterialTheme.typography.titleLarge.copy( fontWeight = FontWeight.Bold ), maxLines = 1, overflow = TextOverflow.Ellipsis ) Text( text = "${listItem.size} items", style = MaterialTheme.typography.bodyMedium ) } Icon( imageVector = Icons.Default.KeyboardArrowDown, contentDescription = "More", modifier = modifier .size(60.dp) .padding(end = 12.dp) .clickable { expandedState = !expandedState } .rotate(rotationState), ) } } AnimatedVisibility( visible = expandedState, ) { Column { listItem.map { item -> ListItem( modifier = Modifier.clickable { navigateToDetail(item.id) }, name = item.name, image = item.image, dueDateMillis = item.dueDateMillis, ) } } } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/card/ExpandableCard.kt
4281533214
package com.bangkit.edims.presentation.components.card import androidx.compose.ui.graphics.Color import com.bangkit.edims.database.Product data class CardItem( val id: Int, val title: String, val icon: Int, val color: Color, val listItem: List<Product> )
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/card/CardItem.kt
3388605410
package com.bangkit.edims.presentation.components.loading import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.keyframes import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.bangkit.edims.presentation.theme.Tacao import kotlinx.coroutines.delay @Composable fun ShowLoading( modifier: Modifier = Modifier ) { Box( modifier = modifier .fillMaxSize() .background(Color.Gray.copy(alpha = 0.5f)) .clickable(enabled = false){} .zIndex(2f), contentAlignment = Alignment.Center ) { LoadingIndicator() } } @Composable private fun LoadingIndicator( modifier: Modifier = Modifier, circleSize: Dp = 15.dp, circleColor: Color = Tacao, spaceBetween: Dp = 10.dp, travelDistance: Dp = 15.dp, ) { val circle = listOf( remember { Animatable(initialValue = 0f) }, remember { Animatable(initialValue = 0f) }, remember { Animatable(initialValue = 0f) }, remember { Animatable(initialValue = 0f) } ) circle.forEachIndexed { index, animatable -> LaunchedEffect(key1 = animatable) { delay(index * 100L) animatable.animateTo( targetValue = 1f, animationSpec = infiniteRepeatable( animation = keyframes { durationMillis = 1200 0.0f at 0 using LinearOutSlowInEasing 1.0f at 300 using LinearOutSlowInEasing 0.0f at 600 using LinearOutSlowInEasing 0.0f at 1200 using LinearOutSlowInEasing }, repeatMode = RepeatMode.Restart ) ) } } val circleValues = circle.map { it.value } val distance = with(LocalDensity.current) { travelDistance.toPx() } val lastCircle = circleValues.size - 1 Row( modifier = modifier ) { circleValues.forEachIndexed { index, value -> Box( modifier = Modifier .size(circleSize) .graphicsLayer { translationY = -value * distance } .background( color = circleColor, shape = CircleShape ), ) if (index != lastCircle) { Spacer(modifier = Modifier.width(spaceBetween)) } } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/loading/LoadingIndicator.kt
668584984
package com.bangkit.edims.presentation.components.category import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Fastfood import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.MedicalInformation import androidx.compose.ui.graphics.vector.ImageVector data class Category( val name: String, val icon: ImageVector ) object CategoryItem { val items = listOf( Category( name = "Food and beverages", icon = Icons.Default.Fastfood ), Category( name = "Medicines", icon = Icons.Default.MedicalInformation ), Category( name = "Other", icon = Icons.Default.Folder ), ) }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/category/Category.kt
390464709
package com.bangkit.edims.presentation.components.camera import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Settings import android.util.Log import android.view.ViewGroup import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY import androidx.camera.core.ImageCaptureException import androidx.camera.core.Preview import androidx.camera.core.UseCase import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box 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.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Camera import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope 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.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.core.content.ContextCompat import com.bangkit.edims.core.utils.Permission import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.util.concurrent.Executor import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine suspend fun Context.getCameraProvider(): ProcessCameraProvider = suspendCoroutine { continuation -> ProcessCameraProvider.getInstance(this).also { future -> future.addListener({ continuation.resume(future.get()) }, executor) } } val Context.executor: Executor get() = ContextCompat.getMainExecutor(this) @Composable fun CameraPreview( modifier: Modifier = Modifier, scaleType: PreviewView.ScaleType = PreviewView.ScaleType.FILL_CENTER, onUseCase: (UseCase) -> Unit = {} ) { AndroidView( modifier = modifier, factory = { context -> val previewView = PreviewView(context).apply { this.scaleType = scaleType layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) } onUseCase(Preview.Builder() .build() .also { it.setSurfaceProvider(previewView.surfaceProvider) } ) previewView } ) } @Composable fun CameraCapture( modifier: Modifier = Modifier, cameraSelector: CameraSelector = CameraSelector.DEFAULT_BACK_CAMERA, onImageFile: (File) -> Unit = {}, onDismiss: () -> Unit ) { val context = LocalContext.current Permission( permission = Manifest.permission.CAMERA, rationale = "Please grant the permission.", permissionNotAvailableContent = { Column(modifier) { Text("No Camera") Spacer(modifier = Modifier.height(8.dp)) Button(onClick = { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.fromParts("package", context.packageName, null) }) }) { Text("Open Settings") } } } ) Box(modifier = modifier) { val lifecycleOwner = LocalLifecycleOwner.current var previewUseCase by remember { mutableStateOf<UseCase>(Preview.Builder().build()) } val imageCaptureUseCase by remember { mutableStateOf( ImageCapture.Builder() .setCaptureMode(CAPTURE_MODE_MAXIMIZE_QUALITY) .build() ) } val coroutineScope = rememberCoroutineScope() CameraPreview( modifier = Modifier.fillMaxSize(), onUseCase = { previewUseCase = it } ) Icon( imageVector = Icons.Default.Close, contentDescription = "Close", tint = Color.White, modifier = Modifier .padding(16.dp) .clickable { onDismiss() } ) Button( modifier = Modifier .wrapContentSize() .padding(16.dp) .align(Alignment.BottomCenter), onClick = { coroutineScope.launch { imageCaptureUseCase.takePicture(context.executor).let { onImageFile(it) } onDismiss() } } ) { Icon( imageVector = Icons.Default.Camera, contentDescription = "Take Photo", ) } LaunchedEffect(previewUseCase) { val cameraProvider = context.getCameraProvider() try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle( lifecycleOwner, cameraSelector, previewUseCase, imageCaptureUseCase ) } catch (e: Exception) { Log.e("Camera", "Failed ", e) } } } } suspend fun ImageCapture.takePicture(executor: Executor): File { val photoFile = withContext(Dispatchers.IO) { kotlin.runCatching { File.createTempFile("image", "jpg") }.getOrElse { e -> Log.e("Take Picture", "Failed to create file ", e) File("/dev/null") } } return suspendCoroutine { continuation -> val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build() takePicture(outputOptions, executor, object : ImageCapture.OnImageSavedCallback { override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) { continuation.resume(photoFile) } override fun onError(e: ImageCaptureException) { Log.e("Take Picture", "Failed to capture failed ", e) continuation.resumeWithException(e) } }) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/camera/Camera.kt
2646380638
package com.bangkit.edims.presentation.components.navigation import androidx.compose.ui.graphics.vector.ImageVector data class NavigationItem( val title: String, val icon: ImageVector, val screen: Screen, )
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/navigation/NavigationItem.kt
2001783954
package com.bangkit.edims.presentation.components.navigation sealed class Screen(val route: String) { object Splash : Screen("splash") object Login : Screen("login") object SignUp : Screen("signup") object Home : Screen("home") object Add : Screen("add") object Settings : Screen("settings") object Detail : Screen("home/{id}") { fun createRoute(id: Int) = "home/$id" } object Profile : Screen("profile") }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/navigation/Screen.kt
3831202564
package com.bangkit.edims.presentation.components.button import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import com.bangkit.edims.presentation.theme.Black import com.bangkit.edims.presentation.theme.Tacao @Composable fun CustomContainedButton( isEnabled: Boolean = true, onClick: () -> Unit = {}, text: String, color: Color = Tacao, textColor: Color = Black, height: Int = 52, borderRadius: Int = 8, elevation: Int = 2, ) { Box { Box( modifier = Modifier .fillMaxWidth() .height(height.dp) ) Button( onClick = onClick, shape = RoundedCornerShape(borderRadius.dp), colors = ButtonDefaults.buttonColors( containerColor = color, contentColor = textColor, disabledContainerColor = color.copy(alpha = 0.7f) ), modifier = Modifier .fillMaxWidth() .height(height.dp), enabled = isEnabled, elevation = ButtonDefaults.elevatedButtonElevation( defaultElevation = elevation.dp, pressedElevation = elevation.dp, disabledElevation = 0.dp, ), ) { Text( text = text, style = MaterialTheme.typography.bodyLarge, ) } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/button/CustomContainedButton.kt
2937864800
package com.bangkit.edims.presentation.components.text import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.interaction.MutableInteractionSource 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.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import com.bangkit.edims.presentation.theme.White @Composable fun CustomTextField( placeholder: String, text: String, errorMessage: String?, onValueChange: (String) -> Unit = {}, keyboardType: KeyboardType = KeyboardType.Text, imeAction: ImeAction = ImeAction.Done, isError: Boolean = false, isVisible: Boolean = true, leadingIcon: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, singleLine: Boolean = false, maxLine: Int = 1, ) { Column { BasicTextField( value = text, onValueChange = { onValueChange(it) }, textStyle = MaterialTheme.typography.bodyLarge, maxLines = maxLine, singleLine = singleLine, interactionSource = remember { MutableInteractionSource() }, visualTransformation = if (isVisible) VisualTransformation.None else PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = keyboardType, imeAction = imeAction ), decorationBox = { innerTextField -> Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .background( color = White, shape = RoundedCornerShape(8.dp) ) .border( width = 3.dp, shape = RoundedCornerShape(8.dp), color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.secondary ) ) { if (leadingIcon != null) { leadingIcon() } else { Spacer(modifier = Modifier.padding(8.dp)) } Box( modifier = Modifier .weight(1.0f) .padding(vertical = 12.dp) ) { if (text.isEmpty()) { Text( text = placeholder, style = MaterialTheme.typography.bodyLarge, color = Color.Gray ) } Box(modifier = Modifier.fillMaxWidth()) { innerTextField() } } if (trailingIcon != null) { trailingIcon() } else { Spacer(modifier = Modifier.padding(8.dp)) } } }, ) Text( text = if (isError) errorMessage!! else "", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium, ) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/text/CustomTextField.kt
3894337304
package com.bangkit.edims.presentation.components.shimmer import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.runtime.Composable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color @Composable fun AnimatedShimmer( showShimmer: Boolean = true, targetValue: Float = 1000f ): Brush { return if (showShimmer) { val shimmerColors = listOf( Color.LightGray.copy(alpha = 0.6f), Color.LightGray.copy(alpha = 0.2f), Color.LightGray.copy(alpha = 0.6f), ) val transition = rememberInfiniteTransition(label = "") val translateAnimation = transition.animateFloat( initialValue = 0f, targetValue = targetValue, animationSpec = infiniteRepeatable( animation = tween( durationMillis = 400, ), repeatMode = RepeatMode.Reverse ), label = "" ) Brush.linearGradient( colors = shimmerColors, start = Offset.Zero, end = Offset(x = translateAnimation.value, y = translateAnimation.value) ) } else { Brush.linearGradient( colors = listOf(Color.Transparent, Color.Transparent), start = Offset.Zero, end = Offset.Zero ) } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/components/shimmer/AnimatedShimmer.kt
506227643
package com.bangkit.edims.presentation.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) val Orange1 = Color(0xFFFCF4E7) val Orange2 = Color(0xFFF9B572) val Green1 = Color(0xFFB7C7A6) val Tacao = Color(0xFFF9B572) val PaleLeaf = Color(0xFFB7C7A6) val SurfCrest = Color(0xFFC3D0B4) val Beige = Color(0xFFFAF8ED) val Flamingo = Color(0xFFE55959) val Texas = Color(0xFFEEEA7E) val TurqoiseBlue = Color(0xFF6CD1F1) val Sulu = Color(0xFFB6E783) val Black = Color(0xFF000000) val White = Color(0xFFFFFFFF)
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/theme/Color.kt
2758906998
package com.bangkit.edims.presentation.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/theme/Shapes.kt
1559557015
package com.bangkit.edims.presentation.theme import android.app.Activity import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme 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.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Green1, secondary = Orange1, tertiary = Orange2 ) private val LightColorScheme = lightColorScheme( primary = Green1, secondary = Orange1, tertiary = Orange2 /* 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 MyProjectTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = when { 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 ) }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/theme/Theme.kt
2393686049
package com.bangkit.edims.presentation.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 ) */ )
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/theme/Type.kt
2533241887
package com.bangkit.edims.presentation.main import android.content.pm.ActivityInfo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.bangkit.edims.core.utils.LockScreenOrientation import com.bangkit.edims.presentation.theme.MyProjectTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MyProjectTheme( darkTheme = false ) { LockScreenOrientation(orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) MainScreen() } } } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/main/MainActivity.kt
20060782
package com.bangkit.edims.presentation.main import androidx.compose.animation.AnimatedContentTransitionScope import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.animateIntAsState import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Home import androidx.compose.material3.FabPosition import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationBarItemColors import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.bangkit.edims.database.Product import com.bangkit.edims.database.UserPreference import com.bangkit.edims.presentation.components.navigation.NavigationItem import com.bangkit.edims.presentation.components.navigation.Screen import com.bangkit.edims.presentation.theme.Beige import com.bangkit.edims.presentation.theme.MyProjectTheme import com.bangkit.edims.presentation.theme.PaleLeaf import com.bangkit.edims.presentation.ui.add.AddScreen import com.bangkit.edims.presentation.ui.add.AddViewModel import com.bangkit.edims.presentation.ui.detail.DetailScreen import com.bangkit.edims.presentation.ui.detail.DetailViewModel import com.bangkit.edims.presentation.ui.home.HomeScreen import com.bangkit.edims.presentation.ui.home.HomeViewModel import com.bangkit.edims.presentation.ui.login.LoginScreen import com.bangkit.edims.presentation.ui.login.LoginViewModel import com.bangkit.edims.presentation.ui.profile.ProfileScreen import com.bangkit.edims.presentation.ui.profile.ProfileViewModel import com.bangkit.edims.presentation.ui.settings.SettingsScreen import com.bangkit.edims.presentation.ui.settings.SettingsViewModel import com.bangkit.edims.presentation.ui.signup.SignUpScreen import com.bangkit.edims.presentation.ui.signup.SignUpViewModel import com.bangkit.edims.presentation.ui.splash.SplashScreen import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.koin.androidx.compose.getViewModel import org.koin.compose.koinInject @Composable fun MainScreen( modifier: Modifier = Modifier ) { val context = LocalContext.current val navController: NavHostController = rememberNavController() val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() var isStartPage by remember { mutableStateOf(false) } var isAddPage by remember { mutableStateOf(false) } val fabPosition by animateIntAsState( if (isAddPage) 80 else 50, label = "" ) val snackbarPosition by animateIntAsState( if (isStartPage) 0 else 50, label = "" ) val userPref: UserPreference = koinInject() val token = runBlocking { userPref.token.first() } val isLoggedIn by remember { mutableStateOf( token != "" ) } val navigateNext by remember { mutableStateOf( if (isLoggedIn) Screen.Home.route else Screen.Login.route ) } isStartPage = currentRoute == Screen.Splash.route || currentRoute == Screen.Login.route || currentRoute == Screen.SignUp.route isAddPage = currentRoute == Screen.Add.route Scaffold( snackbarHost = { SnackbarHost( hostState = snackbarHostState, modifier = Modifier.offset(y = snackbarPosition.dp) ) }, bottomBar = { if (!isStartPage) { AnimatedVisibility(visible = !isAddPage) { BottomBar( navController ) } } }, floatingActionButtonPosition = FabPosition.Center, floatingActionButton = { if (!isStartPage) { FloatingActionButton( modifier = modifier .size(60.dp) .offset(y = fabPosition.dp), shape = CircleShape, onClick = { navController.navigate(Screen.Add.route) { restoreState = true launchSingleTop = true } }, containerColor = PaleLeaf, contentColor = Color.Black, ) { Icon(imageVector = Icons.Filled.Add, contentDescription = "Add") } } }, ) { innerPadding -> NavHost( navController = navController, startDestination = Screen.Splash.route, modifier = modifier .padding(innerPadding) .fillMaxSize() ) { composable(route = Screen.Splash.route) { SplashScreen( modifier = Modifier.zIndex(1f), navigateNext = { navController.navigate(navigateNext) { popUpTo(navController.graph.id) { inclusive = true } } } ) } composable(route = Screen.Login.route) { val loginViewModel = getViewModel<LoginViewModel>() LoginScreen( modifier = Modifier.zIndex(1f), viewModel = loginViewModel, showSnackbar = { message, duration -> scope.launch { snackbarHostState.showSnackbar( message = message, duration = duration, actionLabel = "Ok" ) } }, navigateToSignUp = { navController.navigate(Screen.SignUp.route) }, onLoginSuccess = { navController.navigate(Screen.Home.route) { popUpTo(navController.graph.findStartDestination().id) { inclusive = true } } } ) } composable(route = Screen.SignUp.route) { val signUpViewModel = getViewModel<SignUpViewModel>() SignUpScreen( viewModel = signUpViewModel, showSnackbar = { message, duration -> scope.launch { snackbarHostState.showSnackbar( message = message, duration = duration, actionLabel = "Ok" ) } }, navigateToLogin = { navController.navigate(Screen.Login.route) { popUpTo(navController.graph.findStartDestination().id) { inclusive = true } } } ) } composable( route = Screen.Home.route, ) { val homeViewModel = getViewModel<HomeViewModel>() HomeScreen( homeViewModel = homeViewModel, navigateToDetail = { itemId -> navController.navigate(Screen.Detail.createRoute(itemId)) }, ) } composable(Screen.Add.route) { val addViewModel = getViewModel<AddViewModel>() AddScreen( addViewModel = addViewModel, navigateToHome = { navController.navigateUp() }, showSnackbar = { message, duration -> scope.launch { snackbarHostState.showSnackbar( message = message, duration = duration, withDismissAction = true ) } } ) } composable( route = Screen.Profile.route, ) { val profileViewModel = getViewModel<ProfileViewModel>() ProfileScreen( profileViewModel = profileViewModel, navigateToSettings = { navController.navigate(Screen.Settings.route) }, navigateToLogOut = { navController.navigate(Screen.Login.route) { popUpTo(navController.graph.id) { inclusive = true } } profileViewModel.logout() } ) } composable( route = Screen.Detail.route, arguments = listOf(navArgument("id") { type = NavType.IntType }), enterTransition = { slideInVertically( animationSpec = tween( 300, easing = LinearEasing ), initialOffsetY = { it / 2 } ) + slideIntoContainer( animationSpec = tween(300, delayMillis = 90), towards = AnimatedContentTransitionScope.SlideDirection.Start ) }, exitTransition = { slideOutVertically( animationSpec = tween( 300, easing = LinearEasing ), targetOffsetY = { it / 2 } ) + slideOutOfContainer( animationSpec = tween(300, delayMillis = 90), towards = AnimatedContentTransitionScope.SlideDirection.End ) } ) { val id = it.arguments?.getInt("id") ?: 0 var deleteProduct by remember { mutableStateOf<Product?>(null) } val detailViewModel = getViewModel<DetailViewModel>() DetailScreen( detailViewModel = detailViewModel, id = id, showSnackbar = { message, duration -> scope.launch { val snackbarResult = snackbarHostState.showSnackbar( message = message, duration = duration, actionLabel = "Cancel", ) when (snackbarResult) { SnackbarResult.Dismissed -> { deleteProduct?.let { product -> detailViewModel.delete(product) } snackbarHostState.showSnackbar( message = "Deleted", duration = SnackbarDuration.Short ) } SnackbarResult.ActionPerformed -> { deleteProduct = null snackbarHostState.currentSnackbarData?.dismiss() } } } }, navigateBack = { item -> item?.let { product -> deleteProduct = product } navController.navigateUp() } ) } composable( route = Screen.Settings.route, enterTransition = { fadeIn( animationSpec = tween( 300, easing = LinearEasing ) ) + slideIntoContainer( animationSpec = tween(300, delayMillis = 90), towards = AnimatedContentTransitionScope.SlideDirection.Start ) }, exitTransition = { fadeOut( animationSpec = tween( 300, easing = LinearEasing ) ) + slideOutOfContainer( animationSpec = tween(300, delayMillis = 90), towards = AnimatedContentTransitionScope.SlideDirection.End ) } ) { val settingsViewModel = getViewModel<SettingsViewModel>() SettingsScreen( context = context, settingsViewModel = settingsViewModel, navigateBack = { navController.navigateUp() } ) } } } } @Composable private fun BottomBar( navController: NavController, modifier: Modifier = Modifier ) { NavigationBar( containerColor = PaleLeaf, modifier = modifier ) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route val navigationItem = listOf( NavigationItem( title = "Home", icon = Icons.Default.Home, screen = Screen.Home, ), NavigationItem( title = "Profile", icon = Icons.Default.AccountCircle, screen = Screen.Profile ) ) navigationItem.map { item -> val isSelected = currentRoute == item.screen.route val scale by animateFloatAsState(if (isSelected) 1.1f else 1f, label = "scale") val alpha by animateFloatAsState(if (isSelected) 1f else 0.6f, label = "alpha") NavigationBarItem( icon = { Icon( imageVector = item.icon, contentDescription = item.title, ) }, label = { Text(item.title) }, selected = currentRoute == item.screen.route, onClick = { navController.navigate(item.screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } restoreState = true launchSingleTop = true } }, colors = NavigationBarItemColors( selectedIconColor = Color.Black, selectedIndicatorColor = Beige, selectedTextColor = Color.Black, unselectedIconColor = Color.Black, unselectedTextColor = Color.Black, disabledIconColor = Color.Black, disabledTextColor = Color.Black ), alwaysShowLabel = false, modifier = Modifier .scale(scale) .graphicsLayer(alpha = alpha) ) } } } @Preview(showBackground = true) @Composable fun MainScreenPreview() { MyProjectTheme { MainScreen() } }
Edims/EDIMS/src/main/java/com/bangkit/edims/presentation/main/MainScreen.kt
3201431547
package com.example.taskmanagerapp 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.example.taskmanagerapp", appContext.packageName) } }
TaskManagerApp/app/src/androidTest/java/com/example/taskmanagerapp/ExampleInstrumentedTest.kt
1757244902
package com.example.taskmanagerapp 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) } }
TaskManagerApp/app/src/test/java/com/example/taskmanagerapp/ExampleUnitTest.kt
624161969
package com.example.taskmanagerapp.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/ui/theme/Shape.kt
2605079838
package com.example.taskmanagerapp.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val LightPurple = Color(0xFFF1F4FF) val LightGreen = Color(0xFFbbf7d0) val LightRed = Color(0xFFfecaca) val LightBlue = Color(0xFFE6F5FB) val LightOrange = Color(0xFFfed7aa) val LightAmber = Color(0xFFfde68a) val LightLime = Color(0xFFd9f99d) val Orange = Color(0xFFF69A0E) val LightGray = Color(0xFFADADAD)
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/ui/theme/Color.kt
3445198573
package com.example.taskmanagerapp.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun TaskManagerAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/ui/theme/Theme.kt
308073128
package com.example.taskmanagerapp.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.taskmanagerapp.R val Nunito = FontFamily( listOf( Font(R.font.nunito_light, FontWeight.Light), Font(R.font.nunito_regular, FontWeight.Normal), Font(R.font.nunito_medium, FontWeight.Medium), Font(R.font.nunito_semibold, FontWeight.SemiBold), Font(R.font.nunito_bold, FontWeight.Bold), Font(R.font.nunito_extrabold, FontWeight.ExtraBold) ) ) // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/ui/theme/Type.kt
3011192114
package com.example.taskmanagerapp.taskmanager.components import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.border 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.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Divider import androidx.compose.material.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.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.example.taskmanagerapp.taskmanager.data.Task import com.example.taskmanagerapp.R import com.example.taskmanagerapp.ui.theme.* @Composable fun TaskComponent(task: Task) { val taskColor = listOf( LightPurple, LightGreen, LightBlue, LightRed, LightOrange, LightAmber, LightLime).random() Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "${task.startTime}\nAM", color = Color.Black, fontFamily = FontFamily(Font(R.font.nunito_bold)), textAlign = TextAlign.Center ) Row(verticalAlignment = Alignment.CenterVertically) { Box( modifier = Modifier .size(16.dp) .clip(CircleShape) .border( border = BorderStroke(3.dp, Color.Black), shape = CircleShape ) ) Divider(modifier = Modifier.width(6.dp), color = Color.Black) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Column( modifier = Modifier .clip(RoundedCornerShape(14.dp)) .background(taskColor) .weight(0.9f), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Text( text = task.title, color = Color.Black, fontFamily = FontFamily(Font(R.font.nunito_bold)), modifier = Modifier.padding( start = 12.dp, top = 12.dp ) ) if (task.body != null) { Text( text = task.body, fontFamily = FontFamily(Font(R.font.nunito_bold)), modifier = Modifier.padding(start = 12.dp), color = Color.Gray ) } Text( text = "${task.startTime} - ${task.endTime}", color = Color.Black, fontFamily = FontFamily(Font(R.font.nunito_bold)), modifier = Modifier.padding( start = 12.dp, bottom = 12.dp ) ) } Divider( modifier = Modifier .width(6.dp) .weight(0.1f), color = Color.Black ) } } } }
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/taskmanager/components/TaskComponent.kt
1933748165
package com.example.taskmanagerapp.taskmanager.components import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.taskmanagerapp.R import com.example.taskmanagerapp.ui.theme.LightGray @Composable @Preview fun WelcomeMessageComponent() { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( text = "Hi Developers!", color = Color.Black, fontFamily = FontFamily(Font(R.font.nunito_extrabold)), fontSize = 22.sp ) Text( text = "8 tasks for today Monday", fontFamily = FontFamily(Font(R.font.nunito_regular)), fontSize = 18.sp, color = LightGray ) } }
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/taskmanager/components/WelcomeMessageComponent.kt
388346466
package com.example.taskmanagerapp.taskmanager.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Badge import androidx.compose.material.BadgedBox import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Notifications 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.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.taskmanagerapp.R import com.example.taskmanagerapp.ui.theme.Orange @Composable @Preview fun ProfileHeaderComponent() { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(id = R.drawable.profile), contentDescription = "Profile Picture", modifier = Modifier .size(30.dp) .clip(CircleShape) ) BadgedBox( badge = { Badge( backgroundColor = Orange, contentColor = Color.White, modifier = Modifier.offset(y = 7.dp, x = (-6).dp) ) }, modifier = Modifier .padding(end = 16.dp) ) { Icon( imageVector = Icons.Filled.Notifications, contentDescription = "Notifications", tint = Color.Black ) } } }
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/taskmanager/components/ProfileHeaderComponent.kt
618976222
package com.example.taskmanagerapp.taskmanager.data data class Task( val id: Int, val title: String, val body: String? = null, val startTime: String, val endTime: String ) val taskList = listOf( Task( 1, "Do Laundry", "Wash and fold clothes", "10:00", "11:00" ), Task( 2, "Clean Kitchen", "Wash dishes, wipe counters, and mop the floor", "11:30", "12:30" ), Task( 3, "Vacuum Living Room", "Clean carpets and furniture", "13:00", "14:00" ), Task( 4, "Water Plants", "Water indoor and outdoor plants", "15:00", "16:00" ), Task( 5, "Cook Dinner", "Prepare a meal for the family", "18:00", "19:00" ), Task( 6, "Clean Bathrooms", "Clean sinks, toilets, showers, and tubs", "9:00", "10:00" ), Task( 7, "Organize Closet", "Sort and fold clothes and arrange them in the closet", "11:00", "12:00" ), Task( 8, "Dust Furniture", "Dust and polish tables, shelves, and other furniture", "14:00", "15:00" ), Task( 9, "Clean Windows", "Wash and wipe windows and mirrors", "16:30", "17:30" ), Task( 10, "Take Out Trash", "Collect and dispose of garbage and recycling", "20:00", "21:00" ) )
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/taskmanager/data/Task.kt
1890012075
package com.example.taskmanagerapp import android.annotation.SuppressLint import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.BottomNavigation import androidx.compose.material.BottomNavigationItem import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CalendarMonth import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Mail import androidx.compose.material.Icon import androidx.compose.material.Scaffold import androidx.compose.runtime.* 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.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import com.example.taskmanagerapp.taskmanager.components.ProfileHeaderComponent import com.example.taskmanagerapp.taskmanager.components.TaskComponent import com.example.taskmanagerapp.taskmanager.components.WelcomeMessageComponent import com.example.taskmanagerapp.taskmanager.data.taskList import com.example.taskmanagerapp.ui.theme.TaskManagerAppTheme class MainActivity : ComponentActivity() { @SuppressLint("UnusedMaterialScaffoldPaddingParameter") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { var selectedScreen by remember { mutableStateOf(1) } val screens = listOf("Calendar", "Home", "Notifications") TaskManagerAppTheme { // A surface container using the 'background' color from the theme Scaffold(bottomBar = { BottomNavigation( modifier = Modifier.height(90.dp), backgroundColor = Color.White, elevation = 0.dp ) { screens.forEachIndexed { index, _ -> val icon: ImageVector = when (index) { 0 -> Icons.Filled.CalendarMonth 1 -> Icons.Filled.Home 2 -> Icons.Filled.Mail else -> Icons.Filled.Home } BottomNavigationItem( selected = selectedScreen == index, onClick = { selectedScreen = index }, icon = { Box( modifier = Modifier .size(80.dp) .clip(CircleShape) .background(if (selectedScreen == index) Color.Black else Color.White), contentAlignment = Alignment.Center ) { Icon( imageVector = icon, contentDescription = "Calendar", modifier = Modifier .size(50.dp) .padding(12.dp), tint = if (selectedScreen == index) Color.White else Color.Black ) } } ) } } }) { LazyColumn( contentPadding = PaddingValues( start = 16.dp, top = 16.dp, bottom = 100.dp ), modifier = Modifier .background(Color.White) ) { item { ProfileHeaderComponent() } item { Spacer(modifier = Modifier.height(30.dp)) WelcomeMessageComponent() Spacer(modifier = Modifier.height(30.dp)) } items(taskList) { task -> TaskComponent(task = task) Spacer(modifier = Modifier.height(16.dp)) } } } } } } }
TaskManagerApp/app/src/main/java/com/example/taskmanagerapp/MainActivity.kt
4083086803
package com.example.krhandler 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.example.krhandler", appContext.packageName) } }
kenreyskia-handler/app/src/androidTest/java/com/example/krhandler/ExampleInstrumentedTest.kt
3809787424
package com.example.krhandler 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) } }
kenreyskia-handler/app/src/test/java/com/example/krhandler/ExampleUnitTest.kt
3825418607
package com.example.krhandler import java.util.* class PaySummary(_id: String, _createdAt: Date, _updatedAt: Date, _amount: Double, _coins: Double, _month : Months?, _isError : Boolean) : BaseData(_id, _createdAt, _updatedAt) { private var amount : Double = _amount private var coins : Double = _coins private var total : Double = amount-coins private var error : Boolean = _isError private var month : Months? = _month fun getAmount() = amount fun getCoins() = coins fun getTotal() = total fun getMonth() = month fun isError() = error fun setMonth(_month : Months){ month = _month } fun setAmount(_amount : Double) { amount = _amount total = _amount - coins } fun setCoins(_coins : Double) { coins = _coins total = amount - _coins } }
kenreyskia-handler/app/src/main/java/com/example/krhandler/PaySummary.kt
2566781767
package com.example.krhandler import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.google.firebase.firestore.CollectionReference import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FirebaseFirestore class MainActivity : AppCompatActivity() { private val paySummary : MutableList<PaySummary> = mutableListOf() private var adminUser : AdminUser? = null private var srlMainActivity : SwipeRefreshLayout? = null private var clAddPaySummary : ConstraintLayout? = null private var lvPaySummary : ListView? = null private var arrayAdapter: ArrayAdapter<PaySummary>? = null private var firestore : FirebaseFirestore = FirebaseFirestore.getInstance(); private val collectionRef : CollectionReference = firestore.collection("PaySummary") private var documentRef : DocumentReference? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setAdmin() setViews() setAdapters() setEventHandlers() getPaySummaries() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.main_money -> { val intent = Intent(this, MoneyActivity::class.java) intent.putExtra("admin",adminUser) startActivity(intent) finish() } R.id.main_addPaySummary -> { viewAddingPaySummary() } R.id.main_logout -> { val intent = Intent(this, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY startActivity(intent) finish() } } return super.onOptionsItemSelected(item) } private fun setAdmin(){ adminUser = intent.getSerializableExtra("admin") as AdminUser } private fun setViews(){ srlMainActivity = findViewById(R.id.srlMain) lvPaySummary = findViewById(R.id.lvPaySummary) clAddPaySummary = findViewById(R.id.clAddPaySummary) btnAddPaySummary = findViewById(R.id.btnAddPaySummary) btnCancelPaySummary = findViewById(R.id.btnCancelPaySummary) btnDeletePaySummary = findViewById(R.id.btnDeletePaySummary) tvAddPaySummaryAmountLabel = findViewById(R.id.tvAddPaySummaryAmountLabel) tvAddPaySummaryCoinsLabel = findViewById(R.id.tvAddPaySummaryCoinsLabel) tvAddPaySummaryTotalLabel = findViewById(R.id.tvAddPaySummaryTotalLabel) tvAddPaySummaryMonthLabel = findViewById(R.id.tvAddPaySummaryMonthLabel) etAddPaySummaryAmount = findViewById(R.id.etAddPaySummaryAmount) etAddPaySummaryCoins = findViewById(R.id.etAddPaySummaryCoins) etAddPaySummaryTotal = findViewById(R.id.etAddPaySummaryTotal) sAddPaySummaryMonth = findViewById(R.id.sAddPaySummaryMonth) } private var selectedPaySummary : PaySummary? = null private fun setEventHandlers(){ srlMainActivity?.setOnRefreshListener { getPaySummaries() srlMainActivity?.isRefreshing = false } lvPaySummary?.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l -> selectedPaySummary = adapterView.getItemAtPosition(i) as PaySummary if (selectedPaySummary!=null) setSelectedPaySummary(selectedPaySummary!!) else Toast.makeText(this,"MA-SEH-SPSIN-001", Toast.LENGTH_SHORT).show() } btnAddPaySummary?.setOnClickListener {startAddingPaySummary()} btnCancelPaySummary?.setOnClickListener {stopAddingPaySummary()} btnDeletePaySummary?.setOnClickListener {startDeletingPaySummary()} } private fun setSelectedPaySummary(_paySummary : PaySummary){ btnAddPaySummary?.text = "UPDATE" etAddPaySummaryAmount?.setText(_paySummary.getAmount().toString()) etAddPaySummaryCoins?.setText(_paySummary.getCoins().toString()) etAddPaySummaryTotal?.setText(_paySummary.getTotal().toString()) sAddPaySummaryMonth?.setSelection(psHandler.indexOfMonth(_paySummary.getMonth())) btnDeletePaySummary?.visibility=View.VISIBLE viewAddingPaySummary() } private fun setAdapters(){ arrayAdapter = PaySummaryAdapter(this, paySummary) lvPaySummary?.adapter = arrayAdapter sAddPaySummaryMonth?.adapter = MonthAdapter(this) } private val psHandler = PaySummaryHandler() private fun getPaySummaries(){ srlMainActivity?.isRefreshing = true collectionRef .orderBy("created_at") .get() .addOnCompleteListener { task -> srlMainActivity?.isRefreshing = false if(task.isSuccessful){ paySummary.clear() for (data in task.result){ val temp = psHandler.toPaySummary(data) paySummary += temp } paySummary.reverse() arrayAdapter?.notifyDataSetChanged() } } } private var tvAddPaySummaryAmountLabel : TextView? = null private var tvAddPaySummaryCoinsLabel : TextView? = null private var tvAddPaySummaryTotalLabel : TextView? = null private var tvAddPaySummaryMonthLabel : TextView? = null private var etAddPaySummaryAmount : EditText? = null private var etAddPaySummaryCoins : EditText? = null private var etAddPaySummaryTotal : EditText? = null private var sAddPaySummaryMonth : Spinner? = null private var btnAddPaySummary : Button? = null private var btnCancelPaySummary : Button? = null private var btnDeletePaySummary : Button? = null private fun viewAddingPaySummary(){ clAddPaySummary?.visibility = View.VISIBLE srlMainActivity?.visibility = View.GONE } @SuppressLint("ResourceAsColor") private fun startAddingPaySummary(){ if(btnAddPaySummary?.isEnabled == false){ return } val amount = etAddPaySummaryAmount?.text?.toString()?.toDoubleOrNull() val coins = etAddPaySummaryCoins?.text?.toString()?.toDoubleOrNull() if ((amount == null) || amount.isNaN()){ tvAddPaySummaryAmountLabel?.setTextColor(ContextCompat.getColor(this,R.color.danger)) return } if ((coins == null) || coins.isNaN() || amount<coins){ tvAddPaySummaryCoinsLabel?.setTextColor(ContextCompat.getColor(this,R.color.danger)) return } tvAddPaySummaryAmountLabel?.setTextColor(ContextCompat.getColor(this,R.color.black)) tvAddPaySummaryCoinsLabel?.setTextColor(ContextCompat.getColor(this,R.color.black)) val month = sAddPaySummaryMonth?.selectedItem.toString() var entry: HashMap<String, Any>? if (selectedPaySummary == null){ documentRef = collectionRef.document(psHandler.newPaySummaryId()) entry = psHandler.paySummaryToHashmap(amount,coins, Months.valueOf(month), null) } else{ documentRef = collectionRef.document(selectedPaySummary!!.getId()) entry = psHandler.paySummaryToHashmap(amount,coins, Months.valueOf(month), selectedPaySummary!!.getCreatedAt()) } setButtonEnabled(false) documentRef?.set(entry)?.addOnCompleteListener { task -> if (task.isSuccessful){ if (selectedPaySummary!=null) Toast.makeText(this, "Pay Summary Updated!", Toast.LENGTH_SHORT).show() else Toast.makeText(this, "Pay Summary Added!", Toast.LENGTH_SHORT).show() getPaySummaries() stopAddingPaySummary() return@addOnCompleteListener } Toast.makeText(this, "Adding Pay Summary Failed!", Toast.LENGTH_SHORT).show() } } private fun stopAddingPaySummary(){ selectedPaySummary = null btnAddPaySummary?.text = "ADD" btnDeletePaySummary?.visibility = View.GONE setButtonEnabled(true) etAddPaySummaryAmount?.setText("0.0") etAddPaySummaryCoins?.setText("0.0") etAddPaySummaryTotal?.setText("0.0") sAddPaySummaryMonth?.setSelection(0) clAddPaySummary?.visibility = View.GONE srlMainActivity?.visibility = View.VISIBLE } private fun setButtonEnabled(_isEnabled : Boolean){ btnAddPaySummary?.isEnabled = _isEnabled btnCancelPaySummary?.isEnabled = _isEnabled btnDeletePaySummary?.isEnabled = _isEnabled } private fun startDeletingPaySummary(){ if (selectedPaySummary == null){ Toast.makeText(this, "ERROR : MA-SDPS-SPIN-001", Toast.LENGTH_SHORT).show() return } setButtonEnabled(false) documentRef = collectionRef.document(selectedPaySummary!!.getId()) documentRef?.delete()?.addOnCompleteListener { task -> if (task.isSuccessful){ Toast.makeText(this, "Pay Summary Deleted!", Toast.LENGTH_SHORT).show() getPaySummaries() stopAddingPaySummary() return@addOnCompleteListener } Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show() } } }
kenreyskia-handler/app/src/main/java/com/example/krhandler/MainActivity.kt
2274151801
package com.example.krhandler import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.util.Log class Utils { fun isOnline(context: Context): Boolean { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (connectivityManager != null) { val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) if (capabilities != null) { if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) { Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR") return true } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI") return true } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) { Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET") return true } } } return false } }
kenreyskia-handler/app/src/main/java/com/example/krhandler/Utils.kt
1440366406
package com.example.krhandler import java.util.Date abstract class BaseData (_id : String, _createAt : Date, _updatedAt : Date){ private val id : String = _id private val createdAt : Date = _createAt private var updatedAt : Date = _updatedAt fun getId() : String = id fun getCreatedAt() : Date = createdAt fun getUpdatedAt() : Date = updatedAt fun setUpdatedAt(_updatedAt: Date){ updatedAt = _updatedAt } }
kenreyskia-handler/app/src/main/java/com/example/krhandler/BaseData.kt
252027707
package com.example.krhandler import android.util.Log import com.google.firebase.firestore.QueryDocumentSnapshot import java.text.SimpleDateFormat import java.util.* import kotlin.collections.HashMap class PaySummaryHandler { private val monthDate = SimpleDateFormat("MMMM") fun paySummaryToHashmap(_amount : Double, _coins : Double, _month : Months, _createdAt : Date?): HashMap<String, Any> { val newEntry: HashMap<String, Any> = HashMap() val cal = Calendar.getInstance() newEntry["amount"] = _amount newEntry["coins"] = _coins newEntry["created_at"] = _createdAt ?: cal.time newEntry["updated_at"] = cal.time newEntry["month"] = _month return newEntry } fun toPaySummary(data : QueryDocumentSnapshot) : PaySummary{ val id = data.id val amount = data.getDouble("amount") val coins = data.getDouble("coins") val createdAt = data.getDate("created_at") val updatedAt = data.getDate("updated_at") var month = data.getString("month") var newMonth : Months? = parseStringToMonth(month) if (createdAt != null && updatedAt != null && amount != null && coins !=null ){ return PaySummary(id, createdAt, updatedAt, amount, coins, newMonth, false) } val cal = Calendar.getInstance() return PaySummary(id, cal.time, cal.time, 0.0, 0.0, null, true) } fun newPaySummaryId() : String { val cal = Calendar.getInstance() val year = cal.get(Calendar.YEAR) val month = cal.get(Calendar.MONTH) val day = cal.get(Calendar.DATE) return "$year-$month-$day" } private fun parseStringToMonth(str : String?) : Months? { return try { if (str != null) Months.valueOf(str.uppercase()) else null } catch (e : Exception) { null } } fun indexOfMonth(_month : Months?) : Int { val monthList = Months.values().map { it.toString() } return monthList.indexOf(_month.toString()) } }
kenreyskia-handler/app/src/main/java/com/example/krhandler/PaySummaryHandler.kt
742705424