content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package org.example.mypotrfolio.models import org.example.mypotrfolio.util.Res enum class Achievement( val icon: String, val number: Int, val description: String ) { Completed( icon = Res.Icon.checkmark, number = 12, description = "Completed Projects" ), Active( icon = Res.Icon.shield, number = 2, description = "Active Projects" ), Satisfied( icon = Res.Icon.happy, number = 2, description = "Satisfied Clients" ), Team( icon = Res.Icon.user, number = 2, description = "Team Members" ) }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/models/Achievement.kt
3841166379
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.color import com.varabyte.kobweb.compose.ui.modifiers.transform import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.compose.ui.modifiers.width import com.varabyte.kobweb.compose.ui.styleModifier import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.anyLink import com.varabyte.kobweb.silk.components.style.hover import org.example.mypotrfolio.models.Theme import org.jetbrains.compose.web.ExperimentalComposeWebApi import org.jetbrains.compose.web.css.* val NavigationItemStyle by ComponentStyle { base { Modifier .color(Theme.Secondary.rgb) .transition(CSSTransition(property = "color", duration = 200.ms)) } anyLink { Modifier .color(Theme.Secondary.rgb) } hover { Modifier .color(Theme.Primary.rgb) } } @OptIn(ExperimentalComposeWebApi::class) val LogoStyle by ComponentStyle { base { Modifier .transform { rotate(0.deg) } .transition(CSSTransition(property = "transform", duration = 200.ms)) } hover { Modifier .transform { rotate((-10).deg) } } } val SocialLinkStyle by ComponentStyle { base { Modifier .color(Theme.Gray.rgb) .transition(CSSTransition(property = "color", duration = 200.ms)) } hover { Modifier .color(Theme.Primary.rgb) } } val MainButtonStyle by ComponentStyle { base { Modifier .width(100.px) .transition(CSSTransition(property = "width", duration = 200.ms)) } hover { Modifier .width(120.px) } } @OptIn(ExperimentalComposeWebApi::class) val MainImageStyle by ComponentStyle { base { Modifier .styleModifier { // filter { grayscale(100.percent) } } .transition(CSSTransition(property = "filter", duration = 200.ms)) } hover { Modifier.styleModifier { filter { grayscale(0.percent) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/MainSectionStyle.kt
740265203
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.TransitionProperty import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.borderRadius import com.varabyte.kobweb.compose.ui.modifiers.opacity import com.varabyte.kobweb.compose.ui.modifiers.rotate import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.compose.ui.styleModifier import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.hover import org.jetbrains.compose.web.ExperimentalComposeWebApi import org.jetbrains.compose.web.css.* @OptIn(ExperimentalComposeWebApi::class) val AboutImageStyle by ComponentStyle { base { Modifier .styleModifier { filter { grayscale(100.percent) } } .borderRadius(r = 0.px) .rotate(0.deg) .transition(CSSTransition(property = TransitionProperty.All, duration = 200.ms)) } hover { Modifier .styleModifier { filter { grayscale(0.percent) } } .borderRadius(r = 100.px) .rotate(10.deg) } } val AboutTextStyle by ComponentStyle { base { Modifier .opacity(50.percent) .transition(CSSTransition(property = "opacity", duration = 200.ms)) } hover { Modifier.opacity(100.percent) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/AboutSectionStyle.kt
3769033623
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.rotate import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.hover import org.jetbrains.compose.web.css.deg import org.jetbrains.compose.web.css.ms val BackToTopButtonStyle by ComponentStyle { base { Modifier.rotate(a = 180.deg) .transition(CSSTransition(property = "rotate", duration = 200.ms)) } hover { Modifier.rotate(a = 0.deg) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/BackToTopButtonStyle.kt
2724240081
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.backgroundColor import com.varabyte.kobweb.compose.ui.modifiers.border import com.varabyte.kobweb.compose.ui.modifiers.color import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.hover import org.example.mypotrfolio.models.Theme import org.jetbrains.compose.web.css.LineStyle import org.jetbrains.compose.web.css.ms import org.jetbrains.compose.web.css.px val ServiceCardStyle by ComponentStyle { base { Modifier .border( width = 2.px, style = LineStyle.Solid, color = Theme.LighterGray.rgb ) .backgroundColor(Colors.White) .transition( CSSTransition(property = "border", duration = 200.ms), CSSTransition(property = "background", duration = 200.ms) ) } hover { Modifier .border( width = 2.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) .backgroundColor(Theme.Primary.rgb) } cssRule(" > #iconBox") { Modifier .backgroundColor(Colors.Transparent) .transition(CSSTransition(property = "background", duration = 200.ms)) } cssRule(":hover > #iconBox") { Modifier.backgroundColor(Colors.White) } cssRule(" > p") { Modifier .color(Theme.Secondary.rgb) .transition(CSSTransition(property = "color", duration = 200.ms)) } cssRule(":hover > p") { Modifier.color(Colors.White) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/ServiceSectionStyle.kt
457437110
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.Visibility import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.hover import org.example.mypotrfolio.models.Theme import org.jetbrains.compose.web.css.ms import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px val PortfolioSectionStyle by ComponentStyle { cssRule(" > #columnParent > #boxParent > #greenOverlay") { Modifier .width(0.px) .transition(CSSTransition(property = "width", duration = 500.ms)) } cssRule(":hover > #columnParent > #boxParent > #greenOverlay") { Modifier.width(300.px) } cssRule(" > #columnParent > #boxParent > #greenOverlay > #linkIcon") { Modifier.visibility(Visibility.Hidden) } cssRule(":hover > #columnParent > #boxParent > #greenOverlay > #linkIcon") { Modifier.visibility(Visibility.Visible) } cssRule(" > #columnParent > #portfolioTitle") { Modifier .color(Theme.Secondary.rgb) .translateX(0.percent) .transition( CSSTransition(property = "color", duration = 200.ms), CSSTransition(property = "translate", duration = 200.ms) ) } cssRule(":hover > #columnParent > #portfolioTitle") { Modifier .color(Theme.Primary.rgb) .translateX(5.percent) } cssRule(" > #columnParent > #portfolioDesc") { Modifier .translateX(0.percent) .transition(CSSTransition(property = "translate", duration = 200.ms)) } cssRule(":hover > #columnParent > #portfolioDesc") { Modifier.translateX(5.percent) } } val PortfolioArrowIconStyle by ComponentStyle { base { Modifier .color(Theme.Gray.rgb) .transition(CSSTransition(property = "color", duration = 200.ms)) } hover { Modifier.color(Theme.Primary.rgb) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/PortfolioSectionStyle.kt
1186307363
package org.example.mypotrfolio.styles import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.border import com.varabyte.kobweb.compose.ui.modifiers.transition import com.varabyte.kobweb.silk.components.style.ComponentStyle import com.varabyte.kobweb.silk.components.style.focus import com.varabyte.kobweb.silk.components.style.hover import org.example.mypotrfolio.models.Theme import org.jetbrains.compose.web.css.LineStyle import org.jetbrains.compose.web.css.ms import org.jetbrains.compose.web.css.px val InputStyle by ComponentStyle { base { Modifier .border( width = 2.px, style = LineStyle.Solid, color = Theme.LightGray.rgb ) .transition(CSSTransition(property = "border", duration = 200.ms)) } focus { Modifier .border( width = 2.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) } hover { Modifier .border( width = 1.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/styles/ContactSectionStyle.kt
2888765737
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.util.Res import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.margin import com.varabyte.kobweb.compose.ui.modifiers.size import com.varabyte.kobweb.silk.components.graphics.Image import org.jetbrains.compose.web.css.px @Composable fun RatingBar( modifier: Modifier = Modifier ) { Row(modifier = modifier) { repeat(5) { Image( modifier = Modifier .margin(right = if (it != 4) 2.px else 0.px) .size(16.px), src = Res.Icon.star, description = "Star icon" ) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/RatingBar.kt
1535808979
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Achievement import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.util.Constants.FONT_FAMILY import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.graphics.Image import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun AchievementCard( modifier: Modifier = Modifier, animatedNumber: Int, achievement: Achievement ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { Image( modifier = Modifier .size(70.px) .margin(right = 20.px), src = achievement.icon, description = "Achievement Icon" ) Column { P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(30.px) .fontWeight(FontWeight.Bolder) .color(Theme.Primary.rgb) .toAttrs() ) { Text( if (achievement == Achievement.Completed) "${animatedNumber}+" else "$animatedNumber" ) } P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(16.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .opacity(50.percent) .toAttrs() ) { Text(achievement.description) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/AchievementCard.kt
1087700264
package org.example.mypotrfolio.components import androidx.compose.runtime.* import org.example.mypotrfolio.models.Section import org.example.mypotrfolio.styles.NavigationItemStyle import org.example.mypotrfolio.util.Constants.FONT_FAMILY import org.example.mypotrfolio.util.Res import com.varabyte.kobweb.compose.css.* import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Color.Companion.argb import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.navigation.OpenLinkStrategy import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.icons.fa.FaXmark import com.varabyte.kobweb.silk.components.icons.fa.IconSize import com.varabyte.kobweb.silk.components.navigation.Link import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.components.style.toModifier import com.varabyte.kobweb.silk.theme.breakpoint.rememberBreakpoint import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.jetbrains.compose.web.css.* @Composable fun OverflowMenu(onMenuClosed: () -> Unit) { val scope = rememberCoroutineScope() val breakpoint = rememberBreakpoint() var translateX by remember { mutableStateOf((-100).percent) } var opacity by remember { mutableStateOf(0.percent) } LaunchedEffect(breakpoint) { translateX = 0.percent opacity = 100.percent if (breakpoint > Breakpoint.MD) { scope.launch { translateX = (-100).percent opacity = 0.percent delay(500) onMenuClosed() } } } Column( modifier = Modifier .fillMaxWidth() .height(100.vh) .position(Position.Fixed) .zIndex(2) .opacity(opacity) .backgroundColor(argb(a = 0.5f, r = 0.0f, g = 0.0f, b = 0.0f)) .transition(CSSTransition(property = "opacity", duration = 500.ms)) ) { Column( modifier = Modifier .fillMaxHeight() .padding(all = 25.px) .width(if (breakpoint < Breakpoint.MD) 50.percent else 25.percent) .overflow(Overflow.Auto) .scrollBehavior(ScrollBehavior.Smooth) .backgroundColor(Colors.White) .translateX(tx = translateX) .transition(CSSTransition(property = "translate", duration = 500.ms)) ) { Row( modifier = Modifier .margin(bottom = 25.px), verticalAlignment = Alignment.CenterVertically ) { FaXmark( modifier = Modifier .cursor(Cursor.Pointer) .margin(right = 20.px, bottom = 3.px) .onClick { scope.launch { translateX = (-100).percent opacity = 0.percent delay(500) onMenuClosed() } }, size = IconSize.LG ) Image( modifier = Modifier.size(80.px), src = Res.Image.Logo, description = "Logo image" ) } Section.values().take(6).forEach { section -> Link( modifier = NavigationItemStyle.toModifier() .margin(bottom = 10.px) .fontFamily(FONT_FAMILY) .fontSize(16.px) .fontWeight(FontWeight.Normal) .textDecorationLine(TextDecorationLine.None) .onClick { scope.launch { translateX = (-100).percent opacity = 0.percent delay(500) onMenuClosed() } }, path = section.path, openInternalLinksStrategy = OpenLinkStrategy.IN_PLACE, text = section.title ) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/OverflowMenu.kt
735988485
package org.example.mypotrfolio.components import androidx.compose.runtime.* import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.css.TextAlign import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.example.mypotrfolio.models.Section import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.util.Constants import org.example.mypotrfolio.util.ObserveViewPortEntered import org.jetbrains.compose.web.css.ms import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun SectionTitle( modifier: Modifier = Modifier, section: Section, alignment: Alignment.Horizontal = Alignment.Start, ) { val scope = rememberCoroutineScope() var titleMargin by remember { mutableStateOf(50.px) } var subtitleMargin by remember { mutableStateOf(50.px) } ObserveViewPortEntered( sectionId = section.id, distanceFromTop = 700.0, onViewPortEntered = { scope.launch { subtitleMargin = 0.px if (alignment == Alignment.Start) { delay(25) } titleMargin = 0.px } } ) Column( modifier = modifier, horizontalAlignment = alignment ) { P( attrs = Modifier .fillMaxWidth() .textAlign( when (alignment) { Alignment.CenterHorizontally -> TextAlign.Center Alignment.End -> TextAlign.End else -> TextAlign.Start } ) .margin( top = 0.px, bottom = 0.px, left = titleMargin ) .fontFamily(Constants.FONT_FAMILY) .fontSize(25.px) .fontWeight(FontWeight.Normal) .color(Theme.Primary.rgb) .transition(CSSTransition(property = "margin", duration = 300.ms)) .toAttrs() ) { Text(section.title) } P( attrs = Modifier .fillMaxWidth() .textAlign( when (alignment) { Alignment.CenterHorizontally -> TextAlign.Center Alignment.End -> TextAlign.End else -> TextAlign.Start } ) .margin( bottom = 10.px, top = 0.px, left = if (alignment == Alignment.Start) subtitleMargin else 0.px, right = if (alignment == Alignment.CenterHorizontally) subtitleMargin else 0.px ) .fontFamily(Constants.FONT_FAMILY) .fontSize(40.px) .fontWeight(FontWeight.Bold) .color(Theme.Secondary.rgb) .transition(CSSTransition(property = "margin", duration = 300.ms)) .toAttrs() ) { Text(section.subtitle) } Box( modifier = Modifier .height(2.px) .width(80.px) .backgroundColor(Theme.Primary.rgb) .borderRadius(r = 50.px) ) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/SectionTitle.kt
3890164293
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Experience import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.util.Constants import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.layout.SimpleGrid import com.varabyte.kobweb.silk.components.layout.numColumns import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import org.jetbrains.compose.web.css.* import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun ExperienceCard( active: Boolean = false, breakpoint: Breakpoint, experience: Experience, animatedMargin: CSSSizeValue<CSSUnit.px> ) { SimpleGrid( modifier = Modifier.fillMaxWidth() .maxWidth( if (breakpoint >= Breakpoint.MD) 60.percent else 90.percent ), numColumns = numColumns(base = 1, md = 2) ) { ExperienceDescription( active = active, description = experience.description ) ExperienceDetails( breakpoint = breakpoint, active = active, experience = experience, animatedMargin = animatedMargin ) } } @Composable fun ExperienceDescription( active: Boolean, description: String ) { Box( modifier = Modifier .fillMaxWidth() .margin(topBottom = 14.px) .padding(all = 14.px) .backgroundColor(if (active) Theme.Primary.rgb else Theme.LighterGray.rgb) ) { P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(14.px) .lineHeight(1.6) .fontWeight(FontWeight.Normal) .color(if (active) Colors.White else Theme.Secondary.rgb) .toAttrs() ) { Text(description) } } } @Composable fun ExperienceDetails( active: Boolean, breakpoint: Breakpoint, experience: Experience, animatedMargin: CSSSizeValue<CSSUnit.px> ) { Row( modifier = Modifier .fillMaxWidth() .margin(left = if (breakpoint >= Breakpoint.MD) 14.px else 0.px), verticalAlignment = Alignment.CenterVertically ) { if (breakpoint >= Breakpoint.MD) { ExperienceNumber( active = active, experience = experience ) } Column( modifier = Modifier .fillMaxSize() .margin(left = if (breakpoint <= Breakpoint.SM) 0.px else animatedMargin) .transition( CSSTransition( property = "margin", duration = 500.ms, delay = experience.ordinal * 100.ms ) ), verticalArrangement = Arrangement.Center ) { P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(20.px) .fontWeight(FontWeight.Bold) .color(Theme.Secondary.rgb) .toAttrs() ) { Text(experience.jobPosition) } P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(14.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .toAttrs() ) { Text("${experience.from} - ${experience.to}") } P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(14.px) .fontWeight(FontWeight.Normal) .color(Theme.Primary.rgb) .toAttrs() ) { Text(experience.company) } } } } @Composable fun ExperienceNumber( active: Boolean, experience: Experience ) { Box( modifier = Modifier .margin(right = 14.px) .fillMaxHeight(), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .fillMaxHeight() .width(3.px) .backgroundColor(Theme.Primary.rgb) ) Box( modifier = Modifier .size(40.px) .border( width = 3.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) .backgroundColor(if (active) Theme.Primary.rgb else Colors.White) .borderRadius(50.percent), contentAlignment = Alignment.Center ) { P( attrs = Modifier .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(16.px) .fontWeight(FontWeight.Bold) .color(if (active) Colors.White else Theme.Primary.rgb) .toAttrs() ) { Text(experience.number) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/ExperienceCard.kt
3934042381
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import com.varabyte.kobweb.compose.css.Cursor import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.attrsModifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.components.style.toModifier import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.styles.InputStyle import org.example.mypotrfolio.styles.MainButtonStyle import org.example.mypotrfolio.util.Constants import org.jetbrains.compose.web.attributes.InputType import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.* @Composable fun ContactForm(breakpoint: Breakpoint) { Column(modifier = Modifier.width(500.px), horizontalAlignment = Alignment.CenterHorizontally ) { Form( action = "https://formspree.io/f/xbjnpnvj", attrs = Modifier .attrsModifier { attr("method","POST") } .toAttrs() ) { Label( attrs = Modifier .classNames("form-label") .fontFamily(Constants.FONT_FAMILY) .fontSize(15.px) .fontWeight(FontWeight.Normal) .margin(bottom = 2.px) .toAttrs(), forId = "inputName" ) { Text("Name") } Input( type = InputType.Text, attrs = InputStyle.toModifier() .id("inputName") .classNames("form-control") .margin(bottom = 12.px) .width( if (breakpoint >= Breakpoint.MD) 500.px else 250.px ) .boxShadow(0.px, 0.px, 0.px, 0.px, null) .backgroundColor(Theme.LighterGray.rgb) .attrsModifier { attr("placeholder", "Full name") attr("name", "name") attr("required", "true") } .toAttrs() ) Label( attrs = Modifier .classNames("form-label") .fontFamily(Constants.FONT_FAMILY) .fontSize(15.px) .fontWeight(FontWeight.Normal) .margin(bottom = 2.px) .toAttrs(), forId = "inputEmail" ) { Text("Email") } Input( type = InputType.Email, attrs = InputStyle.toModifier() .id("inputEmail") .classNames("form-control") .margin(bottom = 10.px) .width( if (breakpoint >= Breakpoint.MD) 500.px else 250.px ) .boxShadow(0.px, 0.px, 0.px, 0.px, null) .backgroundColor(Theme.LighterGray.rgb) .attrsModifier { attr("placeholder", "Email address") attr("name", "email") attr("required", "true") } .toAttrs() ) Label( attrs = Modifier .classNames("form-label") .fontFamily(Constants.FONT_FAMILY) .fontSize(15.px) .fontWeight(FontWeight.Normal) .margin(bottom = 2.px) .toAttrs(), forId = "inputMessage" ) { Text("Message") } TextArea( attrs = InputStyle.toModifier() .id("inputMessage") .classNames("form-control") .height(150.px) .margin(bottom = 20.px) .width( if (breakpoint >= Breakpoint.MD) 500.px else 250.px ) .boxShadow(0.px, 0.px, 0.px, 0.px, null) .backgroundColor(Theme.LighterGray.rgb) .attrsModifier { attr("placeholder", "Your message") attr("name", "message") attr("required", "true") } .toAttrs() ) Box( modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center ) { Button( attrs = MainButtonStyle.toModifier() .height(40.px) .border(width = 0.px) .borderRadius(r = 5.px) .backgroundColor(Theme.Primary.rgb) .color(Colors.White) .cursor(Cursor.Pointer) .toAttrs() ) { Text("Submit") } } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/ContactForm.kt
4238623567
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Service import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.styles.ServiceCardStyle import org.example.mypotrfolio.util.Constants.FONT_FAMILY import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.style.toModifier import org.jetbrains.compose.web.css.LineStyle import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun ServiceCard( service: Service ) { Column( modifier = ServiceCardStyle.toModifier() .maxWidth(300.px) .margin(all = 20.px) .padding(all = 20.px) ) { Box( modifier = Modifier .id("iconBox") .padding(all = 10.px) .margin(bottom = 20.px) .border( width = 2.px, style = LineStyle.Solid, color = Theme.Primary.rgb ) .borderRadius( topLeft = 20.px, topRight = 20.px, bottomLeft = 20.px, bottomRight = 0.px ) ) { Image( modifier = Modifier.size(40.px), src = service.icon, description = service.imageDesc ) } P( attrs = Modifier .fillMaxWidth() .margin(top = 0.px, bottom = 10.px) .fontFamily(FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Bold) .toAttrs() ) { Text(service.title) } P( attrs = Modifier .fillMaxWidth() .margin(top = 0.px, bottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(14.px) .fontWeight(FontWeight.Normal) .toAttrs() ) { Text(service.description) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/ServiceCard.kt
1069591089
package org.example.mypotrfolio.components import androidx.compose.runtime.* import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.styles.BackToTopButtonStyle import com.varabyte.kobweb.compose.css.Cursor import com.varabyte.kobweb.compose.css.Visibility import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.styleModifier import com.varabyte.kobweb.silk.components.icons.fa.FaArrowUp import com.varabyte.kobweb.silk.components.icons.fa.IconSize import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.components.style.toModifier import com.varabyte.kobweb.silk.theme.breakpoint.rememberBreakpoint import kotlinx.browser.document import kotlinx.browser.window import org.jetbrains.compose.web.css.Position import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px @Composable fun BackToTopButton() { val breakpoint = rememberBreakpoint() var scroll: Double? by remember { mutableStateOf(null) } LaunchedEffect(Unit) { window.addEventListener(type = "scroll", callback = { scroll = document.documentElement?.scrollTop }) } Column( modifier = Modifier .fillMaxSize() .position(Position.Fixed) .zIndex(1) .styleModifier { property("pointer-events", "none") }, verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.End ) { Box( modifier = BackToTopButtonStyle.toModifier() .size(50.px) .visibility( if (scroll != null && scroll!! > 400.0) Visibility.Visible else Visibility.Hidden ) .borderRadius(20.percent) .margin( right = if (breakpoint <= Breakpoint.SM) 30.px else 40.px, bottom = if (breakpoint <= Breakpoint.SM) 30.px else 40.px ) .backgroundColor(Theme.Primary.rgb) .cursor(Cursor.Pointer) .onClick { document.documentElement?.scrollTo(x = 0.0, y = 0.0) } .styleModifier { property("pointer-events", "auto") }, contentAlignment = Alignment.Center ) { FaArrowUp( modifier = Modifier.color(Colors.White), size = IconSize.LG ) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/BackToTopButton.kt
626379218
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.util.Constants.FONT_FAMILY import com.varabyte.kobweb.compose.css.CSSTransition import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import org.jetbrains.compose.web.css.* import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun SkillBar( name: String, progressBarHeight: CSSSizeValue<CSSUnit.px> = 5.px, percentage: CSSSizeValue<CSSUnit.percent> = 50.percent, index: Int, animatedPercentage: Int ) { Column( modifier = Modifier .fillMaxWidth() .margin(bottom = 10.px) .maxWidth(500.px) .padding(topBottom = 5.px) ) { Row( modifier = Modifier .fillMaxWidth() .margin(bottom = 5.px), horizontalArrangement = Arrangement.SpaceBetween ) { P( attrs = Modifier .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .toAttrs() ) { Text(name) } P( attrs = Modifier .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .toAttrs() ) { Text("$animatedPercentage%") } } Box( modifier = Modifier.fillMaxWidth() ) { Box( modifier = Modifier .fillMaxWidth() .height(progressBarHeight) .backgroundColor(Theme.LightGray.rgb) ) Box( modifier = Modifier .fillMaxWidth(percentage) .height(progressBarHeight) .backgroundColor(Theme.Primary.rgb) .transition( CSSTransition( property = "width", duration = 1000.ms, delay = 100.ms * index ) ) ) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/SkillBar.kt
1927788355
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.css.TextDecorationLine import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.icons.fa.FaBars import com.varabyte.kobweb.silk.components.icons.fa.IconSize import com.varabyte.kobweb.silk.components.navigation.Link import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import com.varabyte.kobweb.silk.components.style.toModifier import com.varabyte.kobweb.silk.theme.breakpoint.rememberBreakpoint import org.example.mypotrfolio.models.Section import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.styles.LogoStyle import org.example.mypotrfolio.styles.NavigationItemStyle import org.example.mypotrfolio.util.Constants.FONT_FAMILY import org.example.mypotrfolio.util.Res import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px @Composable fun Header( onMenuClick: () -> Unit ) { val breakpoint = rememberBreakpoint() Row( modifier = Modifier .fillMaxWidth( if (breakpoint > Breakpoint.MD) 80.percent else 90.percent ) .margin(bottom = 50.px), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { LeftSide( breakpoint = breakpoint, onMenuClick = onMenuClick ) if (breakpoint > Breakpoint.MD) { RightSide() } } } @Composable fun LeftSide( breakpoint: Breakpoint, onMenuClick: () -> Unit ) { Row( verticalAlignment = Alignment.CenterVertically ) { if (breakpoint <= Breakpoint.MD) { FaBars( modifier = Modifier .margin(right = 15.px) .onClick { onMenuClick() }, size = IconSize.XL ) } Image( modifier = LogoStyle.toModifier() .height(120.px) .width(180.px), src = Res.Image.Logo, description = "Logo image" ) } } @Composable fun RightSide() { Row( modifier = Modifier .fillMaxWidth() .borderRadius(r = 50.px) .backgroundColor(Theme.LighterGray.rgb) .padding(20.px), horizontalArrangement = Arrangement.End ) { Section.entries.toTypedArray().take(6).forEach { section -> Link( modifier = NavigationItemStyle.toModifier() .padding(right = 30.px) .fontFamily(FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Normal) .textDecorationLine(TextDecorationLine.None), path = section.path, text = section.title ) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/Header.kt
526487676
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Portfolio import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.styles.PortfolioSectionStyle import org.example.mypotrfolio.util.Constants.FONT_FAMILY import org.example.mypotrfolio.util.Res import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.css.ObjectFit import com.varabyte.kobweb.compose.css.TextDecorationLine import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Color.Companion.argb import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.navigation.OpenLinkStrategy import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.navigation.Link import com.varabyte.kobweb.silk.components.style.toModifier import org.jetbrains.compose.web.css.percent import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun PortfolioCard( modifier: Modifier = Modifier, portfolio: Portfolio ) { Link( modifier = PortfolioSectionStyle.toModifier() .textDecorationLine(TextDecorationLine.None), path = portfolio.link, openExternalLinksStrategy = OpenLinkStrategy.IN_NEW_TAB ) { Column(modifier = modifier.id("columnParent")) { Box( modifier = Modifier .id("boxParent") .width(300.px) .margin(bottom = 20.px) ) { Image( modifier = Modifier .size(300.px) .objectFit(ObjectFit.Cover), src = portfolio.image, description = "Portfolio Image" ) Box( modifier = Modifier .id("greenOverlay") .fillMaxHeight() .backgroundColor(argb(a = 0.5f, r = 0, g = 167, b = 142)), contentAlignment = Alignment.Center ) { Image( modifier = Modifier .id("linkIcon") .size(32.px), src = Res.Icon.link, description = "Link Icon" ) } } P( attrs = Modifier .id("portfolioTitle") .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Bold) .toAttrs() ) { Text(portfolio.title) } P( attrs = Modifier .id("portfolioDesc") .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(FONT_FAMILY) .fontSize(14.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .opacity(50.percent) .toAttrs() ) { Text(portfolio.description) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/PortfolioCard.kt
579088321
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.graphics.Colors import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.navigation.OpenLinkStrategy import com.varabyte.kobweb.silk.components.icons.fa.FaGithub import com.varabyte.kobweb.silk.components.icons.fa.FaLinkedin import com.varabyte.kobweb.silk.components.icons.fa.IconSize import com.varabyte.kobweb.silk.components.navigation.Link import com.varabyte.kobweb.silk.components.style.toModifier import org.example.mypotrfolio.styles.SocialLinkStyle import org.jetbrains.compose.web.css.px @Composable fun SocialBar(row: Boolean = false) { if (row) { Row ( modifier = Modifier .margin(top = 25.px) .padding(leftRight = 25.px) .minHeight(40.px) .borderRadius(r = 20.px) .backgroundColor(Colors.White), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { SocialLinks(row = true) } } else { Column( modifier = Modifier .margin(right = 25.px) .padding(topBottom = 25.px) .minWidth(40.px) .borderRadius(r = 20.px) .backgroundColor(Colors.White), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { SocialLinks() } } } @Composable private fun SocialLinks(row: Boolean = false) { Link( path = "https://github.com/MohamedElgohary88", openExternalLinksStrategy = OpenLinkStrategy.IN_NEW_TAB ) { FaGithub( modifier = SocialLinkStyle.toModifier().margin( bottom = if (row) 0.px else 40.px, right =if (row) 40.px else 0.px ), size = IconSize.LG ) } Link( path = "https://www.linkedin.com/in/mohamed-elgohary8", openExternalLinksStrategy = OpenLinkStrategy.IN_NEW_TAB ) { FaLinkedin( modifier = SocialLinkStyle.toModifier(), size = IconSize.LG ) } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/SocialBar.kt
3780281927
package org.example.mypotrfolio.components import androidx.compose.runtime.Composable import org.example.mypotrfolio.models.Testimonial import org.example.mypotrfolio.models.Theme import org.example.mypotrfolio.util.Constants import com.varabyte.kobweb.compose.css.FontWeight import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.foundation.layout.Row import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.compose.ui.toAttrs import com.varabyte.kobweb.silk.components.graphics.Image import com.varabyte.kobweb.silk.components.style.breakpoint.Breakpoint import org.jetbrains.compose.web.css.px import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Text @Composable fun TestimonialCard( modifier: Modifier = Modifier, testimonial: Testimonial, breakpoint: Breakpoint ) { Row( modifier = modifier.maxWidth(500.px) ) { Image( modifier = Modifier .margin(20.px) .maxWidth(if (breakpoint >= Breakpoint.MD) 160.px else 80.px) .borderRadius( topLeft = 60.px, topRight = 60.px, bottomLeft = 60.px, bottomRight = 0.px ), src = testimonial.image, description = "Avatar image" ) Column( ) { Row( modifier = Modifier .fillMaxWidth() .margin(bottom = 10.px) ) { Column { P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(18.px) .fontWeight(FontWeight.Bold) .color(Theme.Secondary.rgb) .toAttrs() ) { Text(testimonial.fullName) } P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(12.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .toAttrs() ) { Text(testimonial.profession) } RatingBar( modifier = Modifier.margin(top = 5.px) ) } } P( attrs = Modifier .fillMaxWidth() .margin(topBottom = 0.px) .fontFamily(Constants.FONT_FAMILY) .fontSize(12.px) .fontWeight(FontWeight.Normal) .color(Theme.Secondary.rgb) .toAttrs() ) { Text(testimonial.review) } } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/components/TestimonialCard.kt
65152722
package org.example.mypotrfolio import androidx.compose.runtime.* import com.varabyte.kobweb.compose.ui.modifiers.* import com.varabyte.kobweb.core.App import com.varabyte.kobweb.silk.SilkApp import com.varabyte.kobweb.silk.components.layout.Surface import com.varabyte.kobweb.silk.components.style.common.SmoothColorStyle import com.varabyte.kobweb.silk.components.style.toModifier import org.jetbrains.compose.web.css.* @App @Composable fun AppEntry(content: @Composable () -> Unit) { SilkApp { Surface(SmoothColorStyle.toModifier().minHeight(100.vh)) { content() } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/AppEntry.kt
3640789351
package org.example.mypotrfolio.pages import androidx.compose.runtime.* import com.varabyte.kobweb.compose.foundation.layout.Arrangement import com.varabyte.kobweb.compose.foundation.layout.Box import com.varabyte.kobweb.compose.foundation.layout.Column import com.varabyte.kobweb.compose.ui.Alignment import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.modifiers.fillMaxSize import com.varabyte.kobweb.core.Page import org.example.mypotrfolio.components.BackToTopButton import org.example.mypotrfolio.components.OverflowMenu import org.example.mypotrfolio.sections.* @Page @Composable fun HomePage() { var menuOpened by remember { mutableStateOf(false) } Box( modifier = Modifier.fillMaxSize() ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { MainSection(onMenuClick = { menuOpened = true }) AboutSection() ServiceSection() PortfolioSection() AchievementsSection() // TestimonialSection() ExperienceSection() ContactSection() FooterSection() } BackToTopButton() if (menuOpened) { OverflowMenu(onMenuClosed = { menuOpened = false }) } } }
my-potrfolio/site/src/jsMain/kotlin/org/example/mypotrfolio/pages/Index.kt
2536329002
package org.example.mypotrfolio.worker import com.varabyte.kobweb.worker.OutputDispatcher import com.varabyte.kobweb.worker.WorkerFactory import com.varabyte.kobweb.worker.WorkerStrategy import com.varabyte.kobweb.worker.createPassThroughSerializer // TODO: Worker checklist // - Review https://github.com/varabyte/kobweb#worker // - Rename this class to a more appropriate worker for your project // - Choose appropriate input/output generic types for WorkerFactory<I, O> // - Consider using Kotlinx serialization for rich I/O types // - Write strategy implementation logic // - Update IO serialization override if I/O types changed // - Delete this checklist! internal class EchoWorkerFactory : WorkerFactory<String, String> { override fun createStrategy(postOutput: OutputDispatcher<String>) = WorkerStrategy<String> { input -> postOutput(input) // Add real worker logic here } override fun createIOSerializer() = createPassThroughSerializer() }
my-potrfolio/worker/src/jsMain/kotlin/org/example/mypotrfolio/worker/EchoWorkerFactory.kt
1671441516
package com.np.calculatorapp 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.np.calculatorapp", appContext.packageName) } }
viewBinding-kotlin/app/src/androidTest/java/com/np/calculatorapp/ExampleInstrumentedTest.kt
2272966533
package com.np.calculatorapp 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) } }
viewBinding-kotlin/app/src/test/java/com/np/calculatorapp/ExampleUnitTest.kt
2009757689
package com.np.calculatorapp import android.os.Bundle import android.view.View import android.view.View.OnClickListener import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.np.calculatorapp.databinding.ActivityMainBinding class MainActivity : AppCompatActivity(), View.OnClickListener { lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btnAdd.setOnClickListener(this) binding.btnSub.setOnClickListener(this) binding.btnMultiply.setOnClickListener(this) binding.btnDivision.setOnClickListener(this) } override fun onClick(v: View?) { val a = binding.inputA.text.toString().toDouble() val b = binding.inputB.text.toString().toDouble() var result=0.0 when(v?.id){ R.id.btn_add ->{ result = a+b } R.id.btn_sub ->{ result = a-b } R.id.btn_multiply ->{ result = a*b } R.id.btn_division ->{ result = a/b } } binding.resultTv.text = "Result is $result" } }
viewBinding-kotlin/app/src/main/java/com/np/calculatorapp/MainActivity.kt
2799130880
class Tablero() { var contenido = listOf<MutableList<String>>( mutableListOf<String>(" ", " ", " "), mutableListOf<String>(" ", " ", " "), mutableListOf<String>(" ", " ", " ") ) fun imprimirTablero() { for (columna in contenido) { for (espacio in columna) { print("| ") print("$espacio | ") } println() } } fun colocarFicha(ficha: Ficha): Boolean{ if (ficha.posx < 0||ficha.posx > 3 || ficha.posy < 0 || ficha.posy > 3){ println("Creo que las fichas se colocan en el tablero, no fuera") return false } else if (contenido[ficha.posx-1][ficha.posy-1] == " "){ contenido[ficha.posx-1][ficha.posy-1] = ficha.tipo return true } else{ println("No se puede colocar una ficha ahí") return false } } fun reset(tablero: Tablero){ tablero.contenido = listOf<MutableList<String>>( mutableListOf<String>(" ", " ", " "), mutableListOf<String>(" ", " ", " "), mutableListOf<String>(" ", " ", " ") ) } }
EjerciciosBasicos10/src/Tablero.kt
1408843412
fun main() { try { val tablero = Tablero() val partida = Juego() partida.juego(tablero) } catch (e:Exception) { print(e.message) } }
EjerciciosBasicos10/src/Main.kt
1039876304
class Juego { fun juego(tablero: Tablero) { var win: Boolean? = null var ronda = 0 val tipos = mutableListOf<String>("Cara", "Cruz") val jugadores = elegirTipo(tipos) var jugar = true while (jugar) { ronda += 1 turnoJ1(tablero, ronda, jugadores) win = comprobarGanador(tablero, ronda, jugadores[0]) if (win == true) { tablero.imprimirTablero() print("J1 GANA") break } turnoJ2(tablero, ronda, jugadores) win = comprobarGanador(tablero, ronda, jugadores[1]) if (win == true) { tablero.imprimirTablero() print("J2 GANA") break } if (ronda >= 5) { println("¿Quereís seguir jugando? (s/n)") val respuesta = readln().lowercase() if (respuesta == "s") { tablero.reset(tablero) } else if (respuesta == "n") { jugar = false } } } } //------------------------------------------------------------------------------------------------------------------ /** * elegirTipo se encarga unicamente de asignar Cara o Cruz a J1 en la primera ronda, puesto que J2 será el que J1 no quiera. * @param tipos -> Lista sencilla con "Cara" y "Cruz" dentro. * @return J1 -> La opción que ha seleccionado J1. */ private fun elegirTipo(tipos: MutableList<String>): MutableList<String> { val jugadores = mutableListOf<String>() var elegido = false while (!elegido) { print("J1, ¿Quieres ser cara o cruz? ") val tipo = readln().lowercase().replaceFirstChar { it -> it.uppercase() } when (tipo) { "Cara" -> { val J1 = TiposFicha.CARA.simbolo val J2 = TiposFicha.CRUZ.simbolo jugadores.add(J1) jugadores.add(J2) elegido = true } "Cruz" -> { val J1 = TiposFicha.CRUZ.simbolo val J2 = TiposFicha.CARA.simbolo jugadores.add(J1) jugadores.add(J2) elegido = true } else -> { println("No existe esa ficha") } } } return jugadores } //------------------------------------------------------------------------------------------------------------------ /** * turnoJ1 recoge el flujo de acciones que el J1 realiza en su turno * @param tablero -> Tablero de juego. * @param ronda -> Entero que representa la ronda actual * @param jugadores -> Lista con el tipo de ficha de J1 y J2. */ private fun turnoJ1(tablero: Tablero, ronda:Int, jugadores: MutableList<String>): Tablero { var win: Boolean? = null val movimiento = false println(" --Turno J1-- ") while (!movimiento) { tablero.imprimirTablero() print("¿Dónde quieres colocar la ficha? ") val posiciones = readln().split("-") val ficha = Ficha(posiciones[0].toInt(), posiciones[1].toInt(), jugadores[0]) val mov = tablero.colocarFicha(ficha) if (ronda == 3) win = comprobarGanador(tablero, ronda, jugadores[0]) if (mov) break } return tablero } //------------------------------------------------------------------------------------------------------------------ /** * turnoJ2 recoge el flujo de acciones que el J2 realiza en su turno * @param tablero -> Tablero de juego. * @param ronda -> Entero que representa la ronda actual * @param jugadores -> Lista con el tipo de ficha de J1 y J2. */ private fun turnoJ2(tablero: Tablero, ronda: Int, jugadores: MutableList<String>): Tablero { var win: Boolean? = null val movimiento = false println(" --Turno J2-- ") while (!movimiento) { tablero.imprimirTablero() print("¿Dónde quieres colocar la ficha? ") val posiciones = readln().split("-") val ficha = Ficha(posiciones[0].toInt(), posiciones[1].toInt(), jugadores[1]) val mov = tablero.colocarFicha(ficha) if (ronda == 3) win = comprobarGanador(tablero, ronda, jugadores[1]) if (mov) break } return tablero } //------------------------------------------------------------------------------------------------------------------ private fun comprobarGanador(tablero: Tablero, ronda: Int, tipo :String): Boolean? { var win = false if (ronda >= 3) { for (i in 1..3) { if (tablero.contenido[i][0] == tipo && tablero.contenido[i][1] == tipo && tablero.contenido[i][2] == tipo) { win = true return win } else if (tablero.contenido[0][i]== tipo && tablero.contenido[1][i]== tipo && tablero.contenido[2][i]== tipo) { win = true return win } else if (tablero.contenido[0][0]== tipo && tablero.contenido[1][1]== tipo && tablero.contenido[2][2]== tipo) { win = true return win } else if (tablero.contenido[0][2]== tipo && tablero.contenido[1][1] == tipo && tablero.contenido[2][0]== tipo) { win = true return win } else { win = false return win } } } return null } }
EjerciciosBasicos10/src/Juego.kt
1727526667
enum class TiposFicha(val simbolo: String) { CARA ("O"), CRUZ("X") }
EjerciciosBasicos10/src/TiposFicha.kt
1067858924
class Ficha (var posx: Int, var posy: Int, var tipo: String){ init { require(posx > 0) {"La fila seleccionada no está dentro del tablero"} require(posy > 0) {"La columna seleccionada no está dentro del tablero"} if (tipo == TiposFicha.CARA.simbolo){ tipo = "0" } else { tipo = "X" } } }
EjerciciosBasicos10/src/Ficha.kt
627753108
package com.score.vact 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.score.vact", appContext.packageName) } }
vact/app/src/androidTest/java/com/score/vact/ExampleInstrumentedTest.kt
2968866633
package com.score.vact 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) } }
vact/app/src/test/java/com/score/vact/ExampleUnitTest.kt
154031479
package com.score.vact.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider class ViewModelProviderFactory @Inject constructor(private val creators: Map<Class<out ViewModel?>?, @JvmSuppressWildcards Provider<ViewModel>?>) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { var creator: Provider<out ViewModel>? = creators[modelClass] if (creator == null) { // if the viewmodel has not been created // loop through the allowable keys (aka allowed classes with the @ViewModelKey) for ((key, value) in creators) { // if it's allowed, set the Provider<ViewModel> if (modelClass.isAssignableFrom(key!!)) { creator = value break } } } // if this is not one of the allowed keys, throw exception requireNotNull(creator) { "unknown model class $modelClass" } // return the Provider return try { creator.get() as T } catch (e: Exception) { throw RuntimeException(e) } } companion object { private const val TAG = "ViewModelProviderFactor" } }
vact/app/src/main/java/com/score/vact/viewmodel/ViewModelProviderFactory.kt
3622969919
package com.score.vact.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.score.vact.repository.HomeRepository import com.score.vact.vo.Resource import com.score.vact.vo.Status import kotlinx.coroutines.async import kotlinx.coroutines.launch import javax.inject.Inject class HomeViewModel @Inject constructor(val homeRepository: HomeRepository) : ViewModel() { //Just a dummy Int data type. Not used anywhere private val _phoneNumberVerificationResponse = MutableLiveData<Resource<Int>>() val phoneNumberVerificationResponse: LiveData<Resource<Int>> get() = _phoneNumberVerificationResponse //Int is the userId coming from API. //0 if not exists else there will be a visitorId private val _otpVerificationResponse = MutableLiveData<Resource<Int>>() val otpVerificationResponse: LiveData<Resource<Int>> get() = _otpVerificationResponse fun verifyPhoneNumber(number: String) = viewModelScope.launch { _phoneNumberVerificationResponse.postValue( Resource( status = Status.LOADING, data = null, message = null ) ) val response = async { homeRepository.verifyPhoneNumber(number) }.await() _phoneNumberVerificationResponse.postValue(response) } fun verifyOtp(number: String, otp: String) = viewModelScope.launch { _otpVerificationResponse.postValue( Resource( status = Status.LOADING, data = null, message = null ) ) val response = async { homeRepository.verifyOtp(number,otp) }.await() _otpVerificationResponse.postValue(response) } fun clear(){ _phoneNumberVerificationResponse.postValue(null) _otpVerificationResponse.postValue(null) } }
vact/app/src/main/java/com/score/vact/ui/home/HomeViewModel.kt
2306784151
package com.score.vact.ui.home import android.Manifest import android.content.DialogInterface import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Handler import android.text.TextUtils import android.util.Log import android.util.SparseArray import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.google.android.material.bottomsheet.BottomSheetBehavior import com.score.vact.R import com.score.vact.databinding.HomeFragmentBinding import com.score.vact.di.Injectable import com.score.vact.ui.MainActivity import com.score.vact.ui.afterTextChanged import com.score.vact.vo.Status import kotlinx.android.synthetic.main.home_fragment.* import kotlinx.android.synthetic.main.number_layout.* import kotlinx.android.synthetic.main.otp_layout.* import kotlinx.android.synthetic.main.otp_layout.otpLayout import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import java.lang.Exception import javax.inject.Inject import kotlin.coroutines.CoroutineContext class HomeFragment : Fragment(), Injectable, CoroutineScope, View.OnClickListener { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: HomeViewModel private val TAG = javaClass.simpleName private val keyValues = SparseArray<String>() private var otpInputConnection: InputConnection? = null private var mobileInputConnection: InputConnection? = null private lateinit var otpBottomSheetBehavior: BottomSheetBehavior<*> private lateinit var numberBottomSheetBehavior: BottomSheetBehavior<*> private val CAMERA_REQUEST_CODE = 1024 private lateinit var binding: HomeFragmentBinding private lateinit var job: Job private var verifiedNumber = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<HomeFragmentBinding>( inflater, R.layout.home_fragment, container, false ) this.binding = binding return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Log.d(TAG,"onActivityCreated called") observePhoneVerification() observerOtpVerification() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(HomeViewModel::class.java) binding.viewmodel = viewModel binding.lifecycleOwner = viewLifecycleOwner otpBottomSheetBehavior = BottomSheetBehavior.from(otpLayout) numberBottomSheetBehavior = BottomSheetBehavior.from(mobileLayout) otpBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN numberBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN otpInputConnection = etPinView.onCreateInputConnection(EditorInfo()) mobileInputConnection = etNumber.onCreateInputConnection(EditorInfo()) assignClickEvent() assignKeyValues() btnAppointment.setOnClickListener { // numberBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED val action = HomeFragmentDirections.actionHomeFragmentToAppointmentBookingFragment(12,accompaniedPerson = null) this.findNavController().navigate(action) } etNumber.afterTextChanged { if (it.length == 10) { val act = activity as MainActivity act.showAlert("An OTP will be sent to ${etNumber.text.toString().trim()}", DialogInterface.OnClickListener { p0, p1 -> viewModel.verifyPhoneNumber(it) }) } } etPinView.afterTextChanged { if (it.length == 4) { viewModel.verifyOtp(verifiedNumber,it) } } scanView.setOnClickListener(this) numberBottomSheetBehavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(p0: View, p1: Float) { } override fun onStateChanged(p0: View, p1: Int) { if(p1 == BottomSheetBehavior.STATE_HIDDEN){ etNumber.setText("") } } }) otpBottomSheetBehavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(p0: View, p1: Float) { } override fun onStateChanged(p0: View, p1: Int) { if(p1 == BottomSheetBehavior.STATE_HIDDEN){ etPinView.setText("") } } }) } private fun observePhoneVerification() { viewModel.phoneNumberVerificationResponse.observe(viewLifecycleOwner, Observer { if(it==null){ return@Observer } Log.d(TAG,"observePhoneVerification called with value ${it.status}") if(it.status==Status.LOADING){ progressBar.visibility = View.VISIBLE }else{ progressBar.visibility = View.GONE } if(it.status==Status.SUCCESS){ verifiedNumber = etNumber.text.toString() numberBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN Handler().postDelayed({ otpBottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED },500) }else if(it.status == Status.ERROR){ Toast.makeText(this.requireContext(),it.message!!,Toast.LENGTH_LONG).show() } }) } private fun observerOtpVerification() { viewModel.otpVerificationResponse.observe(viewLifecycleOwner, Observer { if(it==null){ return@Observer } Log.d(TAG,"observerOtpVerification called with value ${it.status}") if(it.status==Status.LOADING){ otpProgressBar.visibility = View.VISIBLE }else{ otpProgressBar.visibility = View.GONE } if(it.status==Status.SUCCESS){ otpBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN Handler().postDelayed({ when (it.data) { 0 -> { val action = HomeFragmentDirections.actionHomeFragmentToRegistrationFragment(verifiedNumber) this.findNavController().navigate(action) } 1 -> { val action = HomeFragmentDirections.actionHomeFragmentToSurveyFragment(it.data) this.findNavController().navigate(action) } else -> { Toast.makeText(this.requireContext(),"Something went wrong",Toast.LENGTH_LONG).show() } } },500) }else if(it.status == Status.ERROR){ Toast.makeText(this.requireContext(),it.message!!,Toast.LENGTH_LONG).show() } }) } private fun assignClickEvent() { btn1!!.setOnClickListener(this) btn2!!.setOnClickListener(this) btn3!!.setOnClickListener(this) btn4!!.setOnClickListener(this) btn5!!.setOnClickListener(this) btn6!!.setOnClickListener(this) btn7!!.setOnClickListener(this) btn8!!.setOnClickListener(this) btn9!!.setOnClickListener(this) btn0!!.setOnClickListener(this) btnDelete!!.setOnClickListener(this) btn1a!!.setOnClickListener(this) btn2a!!.setOnClickListener(this) btn3a!!.setOnClickListener(this) btn4a!!.setOnClickListener(this) btn5a!!.setOnClickListener(this) btn6a!!.setOnClickListener(this) btn7a!!.setOnClickListener(this) btn8a!!.setOnClickListener(this) btn9a!!.setOnClickListener(this) btn0a!!.setOnClickListener(this) btnDeletea!!.setOnClickListener(this) } private fun assignKeyValues() { keyValues.put(R.id.btn1, "1") keyValues.put(R.id.btn2, "2") keyValues.put(R.id.btn3, "3") keyValues.put(R.id.btn4, "4") keyValues.put(R.id.btn5, "5") keyValues.put(R.id.btn6, "6") keyValues.put(R.id.btn7, "7") keyValues.put(R.id.btn8, "8") keyValues.put(R.id.btn9, "9") keyValues.put(R.id.btn0, "0") keyValues.put(R.id.btn1a, "1") keyValues.put(R.id.btn2a, "2") keyValues.put(R.id.btn3a, "3") keyValues.put(R.id.btn4a, "4") keyValues.put(R.id.btn5a, "5") keyValues.put(R.id.btn6a, "6") keyValues.put(R.id.btn7a, "7") keyValues.put(R.id.btn8a, "8") keyValues.put(R.id.btn9a, "9") keyValues.put(R.id.btn0a, "0") } private fun navigateToSurveyPage() { val navController = this.findNavController() etPinView.setText("") navController.navigate(R.id.action_homeFragment_to_surveyFragment) } private fun navigateToRegistrationPage() { etPinView.setText("") this.findNavController().navigate(R.id.action_homeFragment_to_registrationFragment) } override fun onDestroyView() { super.onDestroyView() viewModel.clear() } private fun scanBarCode() { //TODO navigate for scanner fragment in production // val navController = this.findNavController() // navController.navigate(R.id.action_homeFragment_to_scannerFragment) //For navigating to surveyFragment for development purpose val action = HomeFragmentDirections.actionHomeFragmentToSurveyFragment(12) this.findNavController().navigate(action) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) Log.d(TAG, "permission result") if (requestCode == CAMERA_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { scanBarCode() } } } override fun onResume() { super.onResume() (activity as AppCompatActivity?)!!.supportActionBar!!.hide() } override fun onStop() { super.onStop() (activity as AppCompatActivity?)!!.supportActionBar!!.show() } override fun onClick(view: View) { if(view.id == binding.scanView.id){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission( this.requireContext(), Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED ) { requestPermissions(arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE) return } } scanBarCode() } if (view.id == R.id.btnDelete) { val selectedText = otpInputConnection!!.getSelectedText(0) if (TextUtils.isEmpty(selectedText)) { otpInputConnection!!.deleteSurroundingText(1, 0) } else { otpInputConnection!!.commitText("", 1) } } else if (view.id == R.id.btnDeletea) { val selectedText = mobileInputConnection!!.getSelectedText(0) if (TextUtils.isEmpty(selectedText)) { mobileInputConnection!!.deleteSurroundingText(1, 0) } else { mobileInputConnection!!.commitText("", 1) } } else { try { val value = keyValues[view.id] Log.d(TAG, "value is $value") if (otpBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) { otpInputConnection!!.commitText(value, 1) } else if (numberBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) { mobileInputConnection!!.commitText(value, 1) } } catch (ex: Exception) { ex.printStackTrace() } } } private fun hideOtpSheet() { if (otpBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) { otpBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN } } private fun hideMobileSheet() { if (numberBottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) { numberBottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN } } override fun onDestroy() { super.onDestroy() job.cancel() } }
vact/app/src/main/java/com/score/vact/ui/home/HomeFragment.kt
363830337
package com.score.vact.ui.splash import androidx.lifecycle.ViewModel import com.score.vact.repository.SplashRepo import javax.inject.Inject class SplashViewModel @Inject constructor(private val splashRepo: SplashRepo): ViewModel() { val isLoggedIn = splashRepo.isLoggedIn }
vact/app/src/main/java/com/score/vact/ui/splash/SplashViewModel.kt
848616682
package com.score.vact.ui.splash import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import androidx.lifecycle.ViewModelProvider import com.score.vact.R import com.score.vact.ui.MainActivity import com.score.vact.ui.login.LoginActivity import javax.inject.Inject class SplashActivity : AppCompatActivity() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: SplashViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) viewModel = ViewModelProvider(this, viewModelFactory).get(SplashViewModel::class.java) Handler().postDelayed({ if (viewModel.isLoggedIn) { startActivity(Intent(this,MainActivity::class.java)) this.finish() } else { startActivity(Intent(this, LoginActivity::class.java)) this.finish() } }, 3000) } }
vact/app/src/main/java/com/score/vact/ui/splash/SplashActivity.kt
4105805482
package com.score.vact.ui import android.content.Context import android.content.DialogInterface import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.MotionEvent import android.view.inputmethod.InputMethodManager import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.navigation.NavigationView import com.score.vact.R import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import javax.inject.Inject class MainActivity : AppCompatActivity(),HasSupportFragmentInjector { private val TAG = javaClass.simpleName private lateinit var appBarConfiguration: AppBarConfiguration @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration(navController.graph, null) setupActionBarWithNavController(navController) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) Log.d(TAG, "permission result") } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } fun showAlert(message:String,onclick:DialogInterface.OnClickListener){ val builder = AlertDialog.Builder(this) builder.setMessage(message) builder.setCancelable(false) builder.setPositiveButton("OK",onclick) builder.setNegativeButton("CANCEL"){_,_-> } builder.create().show() } override fun supportFragmentInjector() = dispatchingAndroidInjector override fun dispatchTouchEvent(ev: MotionEvent): Boolean { val view = currentFocus if (view != null && (ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE) && view is EditText && !view.javaClass.name.startsWith( "android.webkit." ) ) { val scrcoords = IntArray(2) view.getLocationOnScreen(scrcoords) val x = ev.rawX + view.left - scrcoords[0] val y = ev.rawY + view.top - scrcoords[1] if (x < view.left || x > view.right || y < view.top || y > view.bottom) (this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow( this.window.decorView.applicationWindowToken, 0 ) } return super.dispatchTouchEvent(ev) } } fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) { this.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(editable: Editable?) { afterTextChanged.invoke(editable.toString()) } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {} }) }
vact/app/src/main/java/com/score/vact/ui/MainActivity.kt
187075282
package com.score.vact.ui.visitor_registration import android.Manifest import android.app.Activity.RESULT_OK import android.app.DatePickerDialog import android.content.ClipData import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import androidx.core.content.ContextCompat import androidx.core.content.FileProvider import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.google.android.material.snackbar.Snackbar import com.score.vact.R import com.score.vact.databinding.VisitorRegistrationFragmentBinding import com.score.vact.di.Injectable import com.score.vact.model.* import com.score.vact.ui.afterTextChanged import com.score.vact.util.autoCleared import com.score.vact.vo.Status import kotlinx.android.synthetic.main.visitor_registration_fragment.* import kotlinx.coroutines.* import java.io.File import java.io.IOException import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject import kotlin.coroutines.CoroutineContext class VisitorRegistrationFragment : Fragment(), Injectable, CoroutineScope, View.OnClickListener { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private val TAG = javaClass.simpleName private lateinit var viewModel: VisitorRegistrationViewModel private lateinit var job: Job private var binding by autoCleared<VisitorRegistrationFragmentBinding>() lateinit var countryAdapter: ArrayAdapter<String> private var mCountryList: List<CountryData> = listOf() private var mStateList: List<StateData> = listOf() private var mDistrictList: List<DistrictData> = listOf() private var mCityList: List<CityData> = listOf() private var mIdProofList: List<IDProofData> = listOf() private val ADD_PROFILE_IMAGE_REQUEST = 1231 private val ADD_DOCUMENT_IMAGE_REQUEST = 1232 private var profileImageFilePath: String = "" private var docImageFilePath: String = "" private val args by navArgs<VisitorRegistrationFragmentArgs>() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dataBinding = DataBindingUtil.inflate<VisitorRegistrationFragmentBinding>( inflater, R.layout.visitor_registration_fragment, container, false ) binding = dataBinding return dataBinding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeCountryList() observeIdProofList() observeStateList() observeDistrictList() observeCityList() observeGenderSelection() observeRegistrationResponse() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(VisitorRegistrationViewModel::class.java) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner viewModel.checkedGender.postValue(R.id.rbMale) getCountries() getIdProofList() viewModel.primaryNumber.postValue(args.phoneNumber) binding.btnRegister.setOnClickListener(this) binding.spinnerCountry.setOnClickListener(this) binding.spinnerState.setOnClickListener(this) binding.spinnerDistrict.setOnClickListener(this) binding.spinnerCity.setOnClickListener(this) binding.spinnerIdProof.setOnClickListener(this) binding.spinnerCountry.afterTextChanged { text -> updateSelectedCountry(text.trim()) } binding.spinnerState.afterTextChanged { updateSelectedState(it.trim()) } binding.spinnerDistrict.afterTextChanged { updateSelectedDistrict(it.trim()) } binding.spinnerCity.afterTextChanged { updateSelectedCity(it.trim()) } binding.spinnerIdProof.afterTextChanged { updateSelectedIdProof(it.trim()) } binding.imgProfile.setOnClickListener(this) binding.imgDoc.setOnClickListener(this) } private fun getCountries() = launch { viewModel.getCountries() } private fun getIdProofList() = launch { viewModel.getIdProofList() } private fun observeCountryList() = launch { viewModel.countries.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } mCountryList = it setSpinner(it, spinnerCountry) }) } private fun observeIdProofList() = launch { viewModel.idProofDocuments.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } mIdProofList = it setSpinner(it, spinnerIdProof) }) } private fun observeStateList() = launch { viewModel.states.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } Log.d(TAG, "state list found ${it.size}") mStateList = it setSpinner(it, spinnerState) }) } private fun observeDistrictList() = launch { viewModel.district.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } Log.d(TAG, "districtList list found ${it.size}") mDistrictList = it setSpinner(it, spinnerDistrict) }) } private fun observeCityList() = launch { viewModel.cities.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } Log.d(TAG, "city list found ${it.size}") mCityList = it setSpinner(it, spinnerCity) }) } private fun observeGenderSelection() = launch { viewModel.checkedGender.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } when (it) { binding.rbMale.id -> viewModel.selectedGenderText.postValue("Male") binding.rbFemale.id -> viewModel.selectedGenderText.postValue("Female") binding.rbTrans.id -> viewModel.selectedGenderText.postValue("Transgender") } }) } private fun setSpinner(it: List<Any>, view: AutoCompleteTextView) { if (it.isEmpty()) { view.setText("") } val adapter: ArrayAdapter<Any> = ArrayAdapter<Any>( [email protected](), android.R.layout.select_dialog_item, it ) view.threshold = 0 view.setAdapter(adapter) } private fun updateSelectedCountry(text: String) = launch(Dispatchers.Default) { for (i in mCountryList.indices) { if (mCountryList[i].toString().equals(text, true)) { viewModel.setCountry(mCountryList[i]) break } else { viewModel.setCountry(null) } } } private fun updateSelectedState(text: String) = launch(Dispatchers.Default) { for (i in mStateList.indices) { if (mStateList[i].toString().equals(text, true)) { viewModel.setState(mStateList[i]) break } else { viewModel.setState(null) } } } private fun updateSelectedDistrict(text: String) = launch(Dispatchers.Default) { for (i in mDistrictList.indices) { if (mDistrictList[i].toString().equals(text, true)) { viewModel.setDistrict(mDistrictList[i]) break } else { viewModel.setDistrict(null) } } } private fun updateSelectedCity(text: String) = launch(Dispatchers.Default) { for (i in mCityList.indices) { if (mCityList[i].toString().equals(text, true)) { viewModel.setCity(mCityList[i]) break } else { viewModel.setCity(null) } } } private fun updateSelectedIdProof(text: String) = launch(Dispatchers.Default) { for (i in mIdProofList.indices) { if (mIdProofList[i].toString().equals(text, true)) { viewModel.setIdProof(mIdProofList[i]) break } else { viewModel.setIdProof(null) } } } override fun onDestroy() { super.onDestroy() job.cancel() } override fun onClick(v: View?) { if (v is AutoCompleteTextView) { v.showDropDown() } when (v!!.id) { binding.btnRegister.id -> { viewModel.registerVisitor() } binding.imgProfile.id -> selectImage(ADD_PROFILE_IMAGE_REQUEST) binding.imgDoc.id -> selectImage(ADD_DOCUMENT_IMAGE_REQUEST) } } private fun selectImage(selectionMode: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (permissionGranted()) { addImage(selectionMode) } else { requestPermissions( arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ), selectionMode ) } return } addImage(selectionMode) } private fun permissionGranted(): Boolean { return (ContextCompat.checkSelfPermission( this.requireContext(), Manifest.permission.CAMERA ) == PackageManager.PERMISSION_GRANTED && (ContextCompat.checkSelfPermission( this.requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission( this.requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED)) } private fun addImage(selectionMode: Int) = launch { try { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) if (intent.resolveActivity(requireActivity().packageManager) != null) { var photoFile: File? = null try { photoFile = async { createImageFile(selectionMode) }.await() photoFile?.let { val photoURI: Uri = FileProvider.getUriForFile( [email protected](), "com.score.vact.fileprovider", it ) if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) { intent.clipData = ClipData.newRawUri("", photoURI); intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) } intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) [email protected]( intent, selectionMode ) } } catch (ex: IOException) { ex.printStackTrace() } } } catch (ex: Exception) { ex.printStackTrace() } } private suspend fun createImageFile(selectionMode: Int): File? { val timeStamp: String = SimpleDateFormat( "yyyyMMdd_HHmmss", Locale.getDefault() ).format(Date()); var imageFileName: String = if (selectionMode == ADD_PROFILE_IMAGE_REQUEST) "IMG_" else "DOC_" + timeStamp + "_"; var storageDir: File? = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES); var image: File = File.createTempFile( imageFileName, ".jpg", storageDir ) if (selectionMode == ADD_PROFILE_IMAGE_REQUEST) { profileImageFilePath = image.absolutePath } else { docImageFilePath = image.absolutePath } return image } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == ADD_PROFILE_IMAGE_REQUEST || requestCode == ADD_DOCUMENT_IMAGE_REQUEST) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED ) { addImage(requestCode) } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK) { if (requestCode == ADD_PROFILE_IMAGE_REQUEST) { if (File(profileImageFilePath).length() >= 0) { if (profileImageFilePath.isNotEmpty() && File(profileImageFilePath).exists()) { viewModel.profileImagePath.postValue(profileImageFilePath) } } } else if (requestCode == ADD_DOCUMENT_IMAGE_REQUEST) { if (File(docImageFilePath).length() >= 0) { if (docImageFilePath.isNotEmpty() && File(docImageFilePath).exists()) { viewModel.documentImagePath.postValue(docImageFilePath) } } } } } private fun observeRegistrationResponse() = launch { viewModel.registrationResponse.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } if (it.status == Status.SUCCESS) { val action = VisitorRegistrationFragmentDirections.actionRegistrationFragmentToAppointmentBookingFragment(it.data!!,accompaniedPerson = null) [email protected]().navigate(action) } else if (it.status == Status.ERROR) { Snackbar.make(binding.coordinateLayout,it.message!!,Snackbar.LENGTH_LONG).show() } }) } }
vact/app/src/main/java/com/score/vact/ui/visitor_registration/VisitorRegistrationFragment.kt
2108187458
package com.score.vact.ui.visitor_registration import android.util.Log import androidx.lifecycle.* import com.score.vact.model.* import com.score.vact.repository.VisitorRegistrationRepo import com.score.vact.vo.Resource import com.score.vact.vo.Status import kotlinx.coroutines.launch import javax.inject.Inject class VisitorRegistrationViewModel @Inject constructor(private val visitorRegistrationRepo: VisitorRegistrationRepo) : ViewModel() { private val TAG = javaClass.simpleName val checkedGender = MutableLiveData<Int>() val selectedGenderText = MutableLiveData<String>() val firstName = MutableLiveData<String>("") val lastName = MutableLiveData<String>("") val dob = MutableLiveData<String>("") val primaryNumber = MutableLiveData<String>("") val alternativeNumber = MutableLiveData<String>("") val address = MutableLiveData<String>("") val pincode = MutableLiveData<String>("") val email = MutableLiveData<String>("") val alternateEmail = MutableLiveData<String>("") val idNo = MutableLiveData<String>("") val profileImagePath = MutableLiveData<String>("") val documentImagePath = MutableLiveData<String>("") val errorMessage = MutableLiveData<String>("") private val _countries = MutableLiveData<List<CountryData>>() val countries: LiveData<List<CountryData>> get() = _countries private var _selectedCountryData = MutableLiveData<CountryData>(null) val selectedCountryData: LiveData<CountryData> get() = _selectedCountryData private val _idProofDocuments = MutableLiveData<List<IDProofData>>() val idProofDocuments: LiveData<List<IDProofData>> get() = _idProofDocuments private var _selectedIdProof = MutableLiveData<IDProofData>(null) val selectedIdProof: LiveData<IDProofData> get() = _selectedIdProof private val _states = MutableLiveData<List<StateData>>() val states: LiveData<List<StateData>> get() = _states private var _selectedStateData = MutableLiveData<StateData>(null) val selectedStateData: LiveData<StateData> get() = _selectedStateData private val _district = MutableLiveData<List<DistrictData>>() val district: LiveData<List<DistrictData>> get() = _district private var _selectedDistrictData = MutableLiveData<DistrictData>(null) val selectedDistrictData: LiveData<DistrictData> get() = _selectedDistrictData private val _cities = MutableLiveData<List<CityData>>() val cities: LiveData<List<CityData>> get() = _cities private var _selectedCityData = MutableLiveData<CityData>(null) val selectedCityData: LiveData<CityData> get() = _selectedCityData suspend fun getCountries() { val countries = visitorRegistrationRepo.getCountries() _countries.postValue(countries) } suspend fun getIdProofList() { val ids = visitorRegistrationRepo.getIdProofList() _idProofDocuments.postValue(ids) } suspend fun setCountry(countryData: CountryData?) { _selectedCountryData.postValue(countryData) if (countryData != null) { val stateList = visitorRegistrationRepo.getStates(countryData.id) _states.postValue(stateList) } else { _states.postValue(emptyList()) _district.postValue(emptyList()) _cities.postValue(emptyList()) } } suspend fun setState(stateData: StateData?) { _selectedStateData.postValue(stateData) if (stateData != null) { val districtList = visitorRegistrationRepo.getDistricts(stateData.id) _district.postValue(districtList) } else { _district.postValue(emptyList()) _cities.postValue(emptyList()) } } suspend fun setDistrict(districtData: DistrictData?) { _selectedDistrictData.postValue(districtData) if (districtData != null) { val cityList = visitorRegistrationRepo.getCities(districtData.id) Log.d( TAG, "stateListCount for $districtData id is ${districtData.id} is ${cityList.size}" ) _cities.postValue(cityList) } else { _cities.postValue(emptyList()) } } suspend fun setCity(cityData: CityData?) { _selectedCityData.postValue(cityData) } suspend fun setIdProof(idProofData: IDProofData?) { _selectedIdProof.postValue(idProofData) } private val _registrationResponse = MutableLiveData<Resource<Int>>() val registrationResponse get() = _registrationResponse val validate = MediatorLiveData<Boolean>().apply { /* addSource(documentImagePath){ value = isFormValid() }*/ addSource(idNo) { value = isFormValid() } addSource(selectedIdProof) { value = isFormValid() } addSource(email) { value = isFormValid() } addSource(pincode) { value = isFormValid() } addSource(selectedCityData) { value = isFormValid() } addSource(selectedDistrictData) { value = isFormValid() } addSource(selectedStateData) { value = isFormValid() } addSource(selectedCountryData) { value = isFormValid() } addSource(address) { value = isFormValid() } addSource(checkedGender) { value = isFormValid() } addSource(dob) { value = isFormValid() } addSource(lastName) { value = isFormValid() } addSource(firstName) { value = isFormValid() } /* addSource(profileImagePath){ value = isFormValid() }*/ } private fun isFormValid(): Boolean { errorMessage.postValue("") /* if(profileImagePath.value.isNullOrEmpty()){ errorMessage.postValue("Please select profile image") return false }*/ if (selectedCountryData.value == null) { errorMessage.postValue("Please select country") return false } if (selectedStateData.value == null) { errorMessage.postValue("Please select state") return false } if (selectedDistrictData.value == null) { errorMessage.postValue("Please select district") return false } if (selectedCityData.value == null) { errorMessage.postValue("Please select city") return false } if (selectedIdProof.value == null) { errorMessage.postValue("Please select ID proof") return false } /* if(documentImagePath.value.isNullOrEmpty()){ errorMessage.postValue("Please select document image") return false }*/ if (firstName.value.isNullOrEmpty()) { return false } if (lastName.value.isNullOrEmpty()) { return false } if (dob.value.isNullOrEmpty()) { return false } if (address.value.isNullOrEmpty()) { return false } if (idNo.value.isNullOrEmpty()) { return false } if (pincode.value.isNullOrEmpty()) { return false } return true } fun registerVisitor() = viewModelScope.launch { _registrationResponse.postValue( Resource( status = Status.LOADING, data = null, message = null ) ) try { val visitorRegistrationResponse = visitorRegistrationRepo.registerVisitor( firstName = firstName.value?:"", lastName = lastName.value?:"", birthYear = dob.value?:"", gender = selectedGenderText.value?:"", contactNumber = primaryNumber.value?:"", address = address.value?:"", pincode = pincode.value?:"", countryId = selectedCountryData.value!!.id, stateId = selectedStateData.value!!.id, districtId = selectedDistrictData.value!!.id, cityId = selectedCityData.value!!.id, email = email.value?:"", identityId = selectedIdProof.value!!.id, idNo = idNo.value?:"" ) _registrationResponse.postValue(visitorRegistrationResponse) } catch (ex: Exception) { _registrationResponse.postValue( Resource( status = Status.ERROR, data = null, message = ex.message ) ) } } }
vact/app/src/main/java/com/score/vact/ui/visitor_registration/VisitorRegistrationViewModel.kt
2348686997
package com.score.vact.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import com.score.vact.R import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import javax.inject.Inject class AppointmentListActivity : AppCompatActivity(),HasSupportFragmentInjector { private val TAG = javaClass.simpleName private lateinit var appBarConfiguration: AppBarConfiguration @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_appointment_list) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration(navController.graph, null) setupActionBarWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } override fun supportFragmentInjector() = dispatchingAndroidInjector }
vact/app/src/main/java/com/score/vact/ui/AppointmentListActivity.kt
4011865625
package com.score.vact.ui.appointment_modify import androidx.lifecycle.ViewModel import javax.inject.Inject class AppointmentModifyViewModel @Inject constructor() : ViewModel() { }
vact/app/src/main/java/com/score/vact/ui/appointment_modify/AppointmentModifyViewModel.kt
3181159422
package com.score.vact.ui.appointment_modify import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.score.vact.R import com.score.vact.databinding.AppointmentModifyFragmentBinding import com.score.vact.di.Injectable import com.score.vact.util.autoCleared import javax.inject.Inject class AppointmentModifyFragment : Fragment(), Injectable { @Inject lateinit var viewmodelFactory: ViewModelProvider.Factory private lateinit var viewModel: AppointmentModifyViewModel private var binding by autoCleared<AppointmentModifyFragmentBinding>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<AppointmentModifyFragmentBinding>( inflater, R.layout.appointment_modify_fragment, container, false ) this.binding = binding return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewmodelFactory).get(AppointmentModifyViewModel::class.java) binding.viewmodel = viewModel binding.lifecycleOwner = viewLifecycleOwner } }
vact/app/src/main/java/com/score/vact/ui/appointment_modify/AppointmentModifyFragment.kt
1903955790
package com.score.vact.ui import androidx.lifecycle.ViewModel class VisitorDetailsViewModel : ViewModel() { // TODO: Implement the ViewModel }
vact/app/src/main/java/com/score/vact/ui/VisitorDetailsViewModel.kt
3548099491
package com.score.vact.ui.appointment_list import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.score.vact.model.appointment.AppointmentData import com.score.vact.repository.AppointmentRepo import com.score.vact.vo.Resource import com.score.vact.vo.Status import com.score.vact.vo.lazyDeferred import java.io.IOException import javax.inject.Inject class AppointmentsViewModel @Inject constructor(private val mAppointmentRepo: AppointmentRepo) : ViewModel() { private val _appointments = MutableLiveData<Resource<List<AppointmentData>>>() val appointments: LiveData<Resource<List<AppointmentData>>> get() = _appointments suspend fun getAppointments(date: String) { _appointments.postValue(Resource(status = Status.LOADING, data = null, message = null)) try { val appointments = mAppointmentRepo.getAppointments(date) appointments.observeForever { if (it == null) { return@observeForever } _appointments.postValue( Resource( status = Status.SUCCESS, data = it, message = null ) ) } } catch (ex: Exception) { ex.printStackTrace() _appointments.postValue( Resource( status = Status.ERROR, data = null, message = ex.message ) ) } } }
vact/app/src/main/java/com/score/vact/ui/appointment_list/AppointmentsViewModel.kt
754167363
package com.score.vact.ui.appointment_list import android.app.DatePickerDialog import androidx.lifecycle.ViewModelProviders import android.os.Bundle import android.util.Log import android.view.* import androidx.fragment.app.Fragment import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.NavOptions import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.adapter.AppointmentListAdapter import com.score.vact.databinding.AppointmentBookingFragmentBinding import com.score.vact.databinding.AppointmentsFragmentBinding import com.score.vact.databinding.VisitorRegistrationFragmentBinding import com.score.vact.di.Injectable import com.score.vact.util.autoCleared import com.score.vact.vo.Status import kotlinx.android.synthetic.main.appointments_fragment.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject import kotlin.coroutines.CoroutineContext class AppointmentsFragment : Fragment(), Injectable, CoroutineScope { private val TAG = javaClass.simpleName @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var job: Job private lateinit var viewModel: AppointmentsViewModel private var binding by autoCleared<AppointmentsFragmentBinding>() private var mAppointmentAdapter by autoCleared<AppointmentListAdapter>() private val dateFormatter = SimpleDateFormat("MMM dd yyyy", Locale.getDefault()) @Inject lateinit var appExecutors: AppExecutors override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) job = Job() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<AppointmentsFragmentBinding>( inflater, R.layout.appointments_fragment, container, false ) this.binding = binding return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(AppointmentsViewModel::class.java) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner val adapter = AppointmentListAdapter(appExecutors = appExecutors, onClick = { val action = AppointmentsFragmentDirections.actionAppointmentsFragment2ToAppointmentDetailsFragment2( it.id ) this.findNavController().navigate(action) }, onActionClick = { id, action -> when(action){ Action.MODIFY->{ this.findNavController().navigate(R.id.action_appointmentsFragment2_to_appointmentModifyFragment) } } }) binding.recyclerView.adapter = adapter this.mAppointmentAdapter = adapter getAppointments(dateFormatter.format(Calendar.getInstance().timeInMillis)) observerAppointments() } private fun getAppointments(date: String) = launch { viewModel.getAppointments(date) } private fun observerAppointments() { viewModel.appointments.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } if (it.status == Status.SUCCESS) { mAppointmentAdapter.submitList(it.data) } else if (it.status == Status.ERROR) { Snackbar.make(binding.coordinateLayout, it.message!!, Snackbar.LENGTH_LONG).show() } }) } override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onDestroy() { super.onDestroy() job.cancel() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.appointments_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_date -> { showCalendar() return true } } return super.onOptionsItemSelected(item) } private fun showCalendar() { val calender = Calendar.getInstance() val dialog = DatePickerDialog( this.requireContext(), DatePickerDialog.OnDateSetListener { _, p1, p2, p3 -> val selectedCalendar = Calendar.getInstance() selectedCalendar.set(p1, p2, p3) val date = dateFormatter.format(selectedCalendar.timeInMillis).toString() getAppointments(date) }, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH), calender.get(Calendar.DAY_OF_YEAR) ) dialog.datePicker.maxDate = System.currentTimeMillis() dialog.show() } }
vact/app/src/main/java/com/score/vact/ui/appointment_list/AppointmentsFragment.kt
2336040257
package com.score.vact.ui.appointment_list //Enum class for Reject, Modify, Approve options in appointment list enum class Action {REJECT, MODIFY, APPROVE }
vact/app/src/main/java/com/score/vact/ui/appointment_list/Action.kt
1400006141
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.ui.common import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.RecyclerView /** * A generic ViewHolder that works with a [ViewDataBinding]. * @param <T> The type of the ViewDataBinding. </T> */ class DataBoundViewHolder<out T : ViewDataBinding> constructor(val binding: T) : RecyclerView.ViewHolder(binding.root)
vact/app/src/main/java/com/score/vact/ui/common/DataBoundViewHolder.kt
2937917395
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.ui.common import androidx.databinding.ViewDataBinding import androidx.recyclerview.widget.AsyncDifferConfig import androidx.recyclerview.widget.ListAdapter import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import com.score.vact.AppExecutors /** * A generic RecyclerView adapter that uses Data Binding & DiffUtil. * * @param <T> Type of the items in the list * @param <V> The type of the ViewDataBinding </V></T> */ abstract class DataBoundListAdapter<T, V : ViewDataBinding>( appExecutors: AppExecutors, diffCallback: Any ) : ListAdapter<T, DataBoundViewHolder<V>>( AsyncDifferConfig.Builder<T>(diffCallback as DiffUtil.ItemCallback<T>) .setBackgroundThreadExecutor(appExecutors.diskIO()) .build() ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBoundViewHolder<V> { val binding = createBinding(parent) return DataBoundViewHolder(binding) } protected abstract fun createBinding(parent: ViewGroup): V override fun onBindViewHolder(holder: DataBoundViewHolder<V>, position: Int) { bind(holder.binding, getItem(position)) holder.binding.executePendingBindings() } protected abstract fun bind(binding: V, item: T) }
vact/app/src/main/java/com/score/vact/ui/common/DataBoundListAdapter.kt
1140798453
package com.score.vact.ui import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import com.score.vact.R import kotlinx.android.synthetic.main.visitor_details_fragment.* class VisitorDetailsFragment : Fragment() { companion object { fun newInstance() = VisitorDetailsFragment() } private lateinit var viewModel: VisitorDetailsViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.visitor_details_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProviders.of(this).get(VisitorDetailsViewModel::class.java) // TODO: Use the ViewModel } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btnConfirm.setOnClickListener { // this.findNavController().navigate(R.id.action_visitorDetailsFragment_to_surveyFragment) } } }
vact/app/src/main/java/com/score/vact/ui/VisitorDetailsFragment.kt
3203537776
package com.score.vact.ui import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.google.zxing.Result import me.dm7.barcodescanner.zxing.ZXingScannerView class ScannerFragment : Fragment(), ZXingScannerView.ResultHandler { private lateinit var mScannerView: ZXingScannerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment mScannerView = ZXingScannerView(activity); return mScannerView; } override fun onResume() { super.onResume() mScannerView.setResultHandler(this) mScannerView.startCamera() } override fun handleResult(rawResult: Result?) { Toast.makeText( activity, "Contents = " + rawResult?.text.toString() + ", Format = " + rawResult?.barcodeFormat.toString(), Toast.LENGTH_SHORT ).show() rawResult?.let { val navController = this.findNavController() val bundle = Bundle() bundle.putString("id", rawResult.text) val id = rawResult.text val action = ScannerFragmentDirections.actionScannerFragmentToHomeFragment() navController.navigate(action) /* val handler = Handler() handler.postDelayed( Runnable { mScannerView.resumeCameraPreview(this) }, 2000 )*/ } } override fun onPause() { super.onPause() mScannerView.stopCamera() } }
vact/app/src/main/java/com/score/vact/ui/ScannerFragment.kt
2270534068
package com.score.vact.ui.appointment_details import androidx.lifecycle.ViewModelProviders import android.os.Bundle import android.text.TextUtils import android.util.Log import android.util.SparseArray import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.navArgs import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.android.material.snackbar.Snackbar import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.adapter.appointment_booking.AccompaniedDetailsListAdapter import com.score.vact.databinding.AppointmentDetailsFragmentBinding import com.score.vact.di.Injectable import com.score.vact.vo.Status import kotlinx.android.synthetic.main.appointment_details_fragment.* import kotlinx.android.synthetic.main.otp_layout.* import kotlinx.coroutines.* import java.lang.Exception import javax.inject.Inject import kotlin.coroutines.CoroutineContext class AppointmentDetailsFragment : Fragment(), Injectable, CoroutineScope, View.OnClickListener { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: AppointmentDetailsViewModel private val TAG = javaClass.simpleName private val args: AppointmentDetailsFragmentArgs by navArgs() private var appointmentId = 0 private lateinit var job: Job private lateinit var binding:AppointmentDetailsFragmentBinding private lateinit var mAdapter:AccompaniedDetailsListAdapter @Inject lateinit var appExecutors:AppExecutors override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) appointmentId = args.id job = Job() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<AppointmentDetailsFragmentBinding>(inflater, R.layout.appointment_details_fragment, container, false) this.binding = binding return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(AppointmentDetailsViewModel::class.java) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner val adapter = AccompaniedDetailsListAdapter(appExecutors = appExecutors) mAdapter = adapter binding.recyclerView.adapter = mAdapter getAppointments() observeAppointmentDetails() } private fun observeAppointmentDetails() { viewModel.appointmentDetails.observe(viewLifecycleOwner, Observer { if(it==null){ return@Observer } if (it.status == Status.ERROR) { Snackbar.make( coordinateLayout, it.message ?: "Something went wrong", Snackbar.LENGTH_LONG ).show() }else{ mAdapter.submitList(it.data?.detailsData?.accompaniedBy) } }) } private fun getAppointments() = launch { viewModel.getAppointmentDetails(appointmentId) } override fun onClick(view: View) { } override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onDestroy() { super.onDestroy() job.cancel() } }
vact/app/src/main/java/com/score/vact/ui/appointment_details/AppointmentDetailsFragment.kt
3897967872
package com.score.vact.ui.appointment_details import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.score.vact.model.appointment.AppointmentDetailsData import com.score.vact.repository.AppointmentRepo import com.score.vact.vo.Resource import com.score.vact.vo.Status import com.score.vact.vo.lazyDeferred import java.io.IOException import java.lang.Exception import javax.inject.Inject class AppointmentDetailsViewModel @Inject constructor(private val mAppointmentRepo: AppointmentRepo) : ViewModel() { private val _appointmentDetails = MutableLiveData<Resource<AppointmentDetailsData>>() val appointmentDetails: LiveData<Resource<AppointmentDetailsData>> get() = _appointmentDetails suspend fun getAppointmentDetails(appointmentId: Int) { _appointmentDetails.postValue( Resource( status = Status.LOADING, data = null, message = null ) ) try { val details = mAppointmentRepo.getAppointmentDetails(appointmentId) details.observeForever { if(it==null){ return@observeForever }else if(it.detailsData==null){ _appointmentDetails.postValue( Resource( status = Status.ERROR, data = null, message ="No details found" ) ) return@observeForever } _appointmentDetails.postValue( Resource( status = Status.SUCCESS, data = it, message = null ) ) } } catch (ex: IOException) { _appointmentDetails.postValue( Resource( status = Status.ERROR, data = null, message = ex.message ) ) }catch (ex: Exception){ _appointmentDetails.postValue( Resource( status = Status.ERROR, data = null, message ="Something went wrong" ) ) } } }
vact/app/src/main/java/com/score/vact/ui/appointment_details/AppointmentDetailsViewModel.kt
4289835108
package com.score.vact.ui.survey import android.annotation.SuppressLint import android.content.pm.ActivityInfo import android.os.Bundle import android.os.Handler import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.viewpager.widget.ViewPager import com.score.vact.R import com.score.vact.adapter.SurveyAdapter import com.score.vact.databinding.SurveyFragmentBinding import com.score.vact.di.Injectable import com.score.vact.model.QuestionData import com.score.vact.vo.Answer import kotlinx.android.synthetic.main.survey_fragment.* import kotlinx.coroutines.* import javax.inject.Inject import kotlin.coroutines.CoroutineContext class SurveyFragment : Fragment(), Injectable, CoroutineScope, ViewPager.OnPageChangeListener { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var job: Job private lateinit var viewModel: SurveyViewModel private lateinit var questions: MutableList<QuestionData> private lateinit var adapter: SurveyAdapter private val TAG = javaClass.simpleName private val args by navArgs<SurveyFragmentArgs>() private lateinit var binding: SurveyFragmentBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<SurveyFragmentBinding>( inflater, R.layout.survey_fragment, container, false ) this.binding = binding return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeSurveyQuestions() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(SurveyViewModel::class.java) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner // viewModel.getSurveyQuestions() questions = mutableListOf() viewPager.addOnPageChangeListener(this) adapter = SurveyAdapter(this.requireContext(), questions) { questionId, answer -> showNextQuestion(questionId,answer) } viewPager.adapter = adapter viewPager.clipToPadding = false viewPager.pageMargin = 20 btnPrevious.setOnClickListener { viewPager.setCurrentItem(viewPager.currentItem - 1, true) } btnDone.setOnClickListener { this.findNavController() .navigate(R.id.action_surveyFragment_to_visitorDetailsFragment) } } private fun observeSurveyQuestions() = launch { viewModel.question.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } [email protected]() [email protected](it) [email protected]() updateProgress(it.size) }) } private fun showNextQuestion(questionId: Int, answer: Answer) = launch{ viewModel.submitAnswer(questionId, answer) //Keeping some delay to make the page answer update and showing //next page with smooth animation Handler().postDelayed({ viewPager.setCurrentItem(viewPager.currentItem + 1, true) try{ if (viewPager.currentItem == viewModel.question.value!!.size-1 && viewModel.question.value!![ viewModel.question.value!!.size-1].answer!=Answer.NA) { binding.btnDone.visibility = View.VISIBLE } }catch (ex:Exception){ ex.printStackTrace() } },500) } private fun updateProgress(size: Int) { tvQuestionIndex.text = "${viewPager.currentItem + 1}/${size}" val progress = ((viewPager.currentItem + 1).toDouble() / size.toDouble()) * 100 progress_bar_1.progress = progress.toInt() } override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { Log.d(TAG,"viewPager position $position") if(position>0){ binding.btnPrevious.visibility = View.VISIBLE }else{ binding.btnPrevious.visibility = View.INVISIBLE } updateProgress(questions.size) } @SuppressLint("SourceLockedOrientationActivity") override fun onResume() { super.onResume() activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } override fun onPause() { super.onPause() activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR; } override fun onDestroy() { job.cancel() super.onDestroy() } }
vact/app/src/main/java/com/score/vact/ui/survey/SurveyFragment.kt
1637799035
package com.score.vact.ui.survey import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.score.vact.model.QuestionData import com.score.vact.repository.SurveyRepository import com.score.vact.vo.Answer import com.score.vact.vo.Resource import com.score.vact.vo.Status import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject class SurveyViewModel @Inject constructor(private val surveyRepository: SurveyRepository) : ViewModel() { private val _questionsResponse = MutableLiveData<Resource<Int>>() val questionsResponse: LiveData<Resource<Int>> get() = _questionsResponse private val _questions = MutableLiveData<List<QuestionData>>() val question: LiveData<List<QuestionData>> get() = _questions init { getSurveyQuestions() } fun getSurveyQuestions() = viewModelScope.launch { _questionsResponse.postValue(Resource(status = Status.LOADING, data = null, message = null)) val questions = surveyRepository.getSurveyQuestions() questions.observeForever { if (it == null) { return@observeForever } _questions.postValue(it) _questionsResponse.postValue( Resource( status = Status.SUCCESS, data = 1,//Just a dummy int value message = null ) ) } } suspend fun submitAnswer(questionId: Int, answer: Answer) = viewModelScope.launch { _questions.value!!.forEach { if (questionId == it.id) { it.answer = answer } } _questions.postValue(_questions.value) } }
vact/app/src/main/java/com/score/vact/ui/survey/SurveyViewModel.kt
1772914194
package com.score.vact.ui.login import android.util.Log import androidx.lifecycle.* import com.score.vact.vo.Resource import com.score.vact.model.UserData import com.score.vact.repository.SharedPrefs import com.score.vact.repository.UserRepository import com.score.vact.vo.Status import kotlinx.coroutines.* import javax.inject.Inject class LoginViewModel @Inject constructor( private val userRepository: UserRepository, private val sharedPrefs: SharedPrefs ) : ViewModel() { private val TAG = javaClass.simpleName // TODO: Implement the ViewModel val username = MutableLiveData("") val password = MutableLiveData("") val _userResponse =MutableLiveData<Resource<UserData>>() val userResponse:LiveData<Resource<UserData>> get() = _userResponse fun login() = viewModelScope.launch { Log.d(TAG, "login called") _userResponse.postValue(Resource(status = Status.LOADING,data = null,message = null)) val userData = userRepository.login(username.value.toString(), password = password.value.toString()) _userResponse.postValue(userData) } val validate = MediatorLiveData<Boolean>().apply { addSource(username) { value = (isFormValid(username.value.toString(), password.value.toString())) } addSource(password) { value = (isFormValid(username.value.toString(), password.value.toString())) } } private fun isFormValid(username: String, password: String): Boolean { Log.d(TAG, "isFormValid called $username and $password values") return username.isNotEmpty() && password.isNotEmpty() } }
vact/app/src/main/java/com/score/vact/ui/login/LoginViewModel.kt
3945370359
package com.score.vact.ui.login import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.score.vact.R import com.score.vact.databinding.ActivityLoginBinding import com.score.vact.repository.SharedPrefs import com.score.vact.ui.AppointmentListActivity import com.score.vact.ui.MainActivity import com.score.vact.vo.Status import kotlinx.android.synthetic.main.activity_login.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.coroutines.CoroutineContext class LoginActivity : AppCompatActivity(), CoroutineScope { private val TAG = javaClass.simpleName lateinit var job: Job @Inject lateinit var viewModelFactory: ViewModelProvider.Factory @Inject lateinit var sharedPrefs: SharedPrefs private lateinit var loginViewModel: LoginViewModel lateinit var binding:ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_login) job = Job() loginViewModel = ViewModelProvider(this, viewModelFactory).get(LoginViewModel::class.java) val savedDummy = sharedPrefs.userName loginViewModel.userResponse.observe(this, Observer { if(it==null){ return@Observer } if(it.status==Status.SUCCESS){ if(it.data!!.isAdmin==1){ startActivity(Intent(this,AppointmentListActivity::class.java)) this.finish() }else { startActivity(Intent(this, MainActivity::class.java)) this.finish() } }else if(it.status == Status.ERROR){ Toast.makeText(this@LoginActivity,it.message,Toast.LENGTH_LONG).show() } }) binding.viewmodel = loginViewModel binding.lifecycleOwner = this } override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun dispatchTouchEvent(ev: MotionEvent): Boolean { val view = currentFocus if (view != null && (ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE) && view is EditText && !view.javaClass.name.startsWith( "android.webkit." ) ) { val scrcoords = IntArray(2) view.getLocationOnScreen(scrcoords) val x = ev.rawX + view.left - scrcoords[0] val y = ev.rawY + view.top - scrcoords[1] if (x < view.left || x > view.right || y < view.top || y > view.bottom) (this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow( this.window.decorView.applicationWindowToken, 0 ) } return super.dispatchTouchEvent(ev) } override fun onDestroy() { job.cancel() super.onDestroy() } }
vact/app/src/main/java/com/score/vact/ui/login/LoginActivity.kt
1377008783
package com.score.vact.ui.appointment_booking import androidx.lifecycle.* import com.score.vact.R import com.score.vact.model.IDProofData import com.score.vact.model.appointment_booking.AccompaniedPersonData import com.score.vact.repository.AppointmentRepo import com.score.vact.repository.VisitorRegistrationRepo import com.score.vact.vo.lazyDeferred import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import java.lang.Exception import javax.inject.Inject class AccompaniedPersonViewModel @Inject constructor(val userRegistrationRepo: VisitorRegistrationRepo) : ViewModel() { val fullname = MutableLiveData<String>("") val year = MutableLiveData<String>("") val selectedGenderId = MutableLiveData<Int>(R.id.rbMale) val contactNumber = MutableLiveData<String>("") val email = MutableLiveData<String>("") val address = MutableLiveData<String>("") val idNo = MutableLiveData<String>("") val selectedGenderText = MutableLiveData<String>() val isValidForm = MediatorLiveData<Boolean>().apply { addSource(fullname) { value = isValid() } addSource(year) { value = isValid() } addSource(selectedGenderId) { value = isValid() } addSource(contactNumber) { value = isValid() } addSource(email) { value = isValid() } addSource(address) { value = isValid() } /*addSource(selectedIdProof){ value = isValid() }*/ addSource(idNo) { value = isValid() } } val errorMessage = MutableLiveData<String>() val documentList = MutableLiveData<List<IDProofData>>() private var _selectedIdProof = MutableLiveData<IDProofData>(null) val selectedIdProof: LiveData<IDProofData> get() = _selectedIdProof suspend fun setIdProof(idProofData: IDProofData?) { _selectedIdProof.postValue(idProofData) } private val _addedPerson = MutableLiveData<AccompaniedPersonData>() val addedPerson: LiveData<AccompaniedPersonData> get() = _addedPerson init { getDocumentList() } private fun getDocumentList() = viewModelScope.launch { val docList = userRegistrationRepo.getIdProofList() documentList.postValue(docList) } override fun onCleared() { super.onCleared() try { viewModelScope.cancel() } catch (ex: Exception) { ex.printStackTrace() } } private fun isValid(): Boolean { errorMessage.postValue("") if (selectedIdProof.value == null) { errorMessage.postValue("Please select ID proof") return false } if (fullname.value.isNullOrEmpty()) { return false } if (year.value.isNullOrEmpty()) { return false } if (contactNumber.value.isNullOrEmpty()) { return false } if (email.value.isNullOrEmpty()) { return false } if (address.value.isNullOrEmpty()) { return false } if (idNo.value.isNullOrEmpty()) { return false } return true } fun addPerson() { val name = fullname.value!! val doy = year.value!! val gender = selectedGenderText.value!! val number = contactNumber.value!! val email = email.value!! val address = address.value!! val docTypeId = selectedIdProof.value!!.id val docId = idNo.value!! val accompaniedPersonData = AccompaniedPersonData(name, doy, gender, number, email, address, docTypeId, docId) _addedPerson.postValue(accompaniedPersonData) } }
vact/app/src/main/java/com/score/vact/ui/appointment_booking/AccompaniedPersonViewModel.kt
545902244
package com.score.vact.ui.appointment_booking import android.app.DatePickerDialog import android.app.TimePickerDialog import android.os.Bundle import android.os.Handler import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.setFragmentResultListener import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.score.vact.AppExecutors import com.score.vact.R import com.score.vact.adapter.appointment_booking.AccompaniedPersonListAdapter import com.score.vact.adapter.appointment_booking.BelongingsAdapter import com.score.vact.databinding.AppointmentBookingFragmentBinding import com.score.vact.di.Injectable import com.score.vact.model.appointment_booking.AccompaniedPersonData import com.score.vact.model.appointment_booking.CompanyData import com.score.vact.model.appointment_booking.DepartmentData import com.score.vact.model.appointment_booking.EmployeeData import com.score.vact.ui.afterTextChanged import com.score.vact.util.autoCleared import kotlinx.android.synthetic.main.appointment_booking_fragment.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject import kotlin.coroutines.CoroutineContext class AppointmentBookingFragment : Fragment(), CoroutineScope, Injectable, View.OnClickListener { private val TAG = javaClass.simpleName @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: AppointmentBookingViewModel private lateinit var job: Job private var binding by autoCleared<AppointmentBookingFragmentBinding>() private var mAccompaniedAdapter by autoCleared<AccompaniedPersonListAdapter>() private var mBelongingsAdapter by autoCleared<BelongingsAdapter>() private lateinit var mCurrentCalendar: Calendar private var mCompanies: List<CompanyData> = listOf() private var mDepartments: List<DepartmentData> = listOf() private var mEmployees: List<EmployeeData> = listOf() private val args by navArgs<AppointmentBookingFragmentArgs>() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job @Inject lateinit var appExecutors: AppExecutors override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mCurrentCalendar = Calendar.getInstance() job = Job() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeCompaniesData() observeDepartment() observeEmployees() observeAccompaniedPerson() //This observation is create to automatically check availability //for the appointment after selecting tim and validating condition observeTimeSelection() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val dataBinding = DataBindingUtil.inflate<AppointmentBookingFragmentBinding>( inflater, R.layout.appointment_booking_fragment, container, false ) binding = dataBinding return dataBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(AppointmentBookingViewModel::class.java) binding.viewmodel = viewModel binding.lifecycleOwner = viewLifecycleOwner binding.etDate.setOnClickListener(this) binding.etTime.setOnClickListener(this) // viewModel.selectedTransportationId.postValue(binding.rdPersonal.id) viewModel.selectedVehicleTypeId.postValue(binding.rdTwoWhealer.id) binding.spnCompany.setOnClickListener(this) binding.spnDepartment.setOnClickListener(this) binding.spnPerson.setOnClickListener(this) args.accompaniedPerson?.let { addAccompaniedPerson(args.accompaniedPerson!!) } getCompanies() // getBelongings() // observeBelongingsData() binding.spnCompany.afterTextChanged { updateSelection(it, binding.spnCompany.id) } binding.spnDepartment.afterTextChanged { updateSelection(it, binding.spnDepartment.id) } binding.spnPerson.afterTextChanged { updateSelection(it, spnPerson.id) } val adapter = AccompaniedPersonListAdapter( appExecutors = appExecutors ) { accompaniedPersonData -> viewModel.remove(accompaniedPersonData) } binding.recyclerView.adapter = adapter this.mAccompaniedAdapter = adapter //Belongings selection is not required. it shows belongings checkbox list in grid view /* val belongingAdapter = BelongingsAdapter(appExecutors = appExecutors) { viewModel.updateBelongingsItem(it) } val layoutManager = FlexboxLayoutManager(this.requireContext()) layoutManager.flexWrap = FlexWrap.WRAP layoutManager.justifyContent = JustifyContent.FLEX_START binding.belongingsGrid.layoutManager = layoutManager binding.belongingsGrid.adapter = belongingAdapter this.mBelongingsAdapter = belongingAdapter */ viewModel.validate.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) { return@Observer } else { Log.d(TAG, "isFormValid $it") } }) binding.btnAdd?.setOnClickListener(this) setFragmentResultListener(AccompaniedPersonFragment.REQUEST_KEY) { key, bundle -> // read from the bundle addAccompaniedPerson(bundle.getSerializable("person") as AccompaniedPersonData) } } private fun getCompanies() = launch { viewModel.getCompanies() } /*private fun getBelongings() = launch { viewModel.getBelongings() }*/ private fun observeCompaniesData() { viewModel.companies.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) { return@Observer } mCompanies = it setSpinner(it, binding.spnCompany) }) } /* private fun observeBelongingsData() { viewModel.belongigns.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) { return@Observer } mBelongingsAdapter.submitList(it) }) }*/ private fun observeDepartment() { viewModel.departments.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) { return@Observer } mDepartments = it setSpinner(it, binding.spnDepartment) }) } private fun observeEmployees() { viewModel.employess.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) { return@Observer } mEmployees = it setSpinner(it, binding.spnPerson) }) } private fun observeAccompaniedPerson() { viewModel.accompaniedPersons.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if (it == null) return@Observer mAccompaniedAdapter.submitList(it) }) } private fun setSpinner(it: List<Any>, view: AutoCompleteTextView) { if (it.isEmpty()) { view.setText("") } val adapter: ArrayAdapter<Any> = ArrayAdapter<Any>( this.requireContext(), android.R.layout.select_dialog_item, it ) view.threshold = 0 view.setAdapter(adapter) } private fun updateSelection(text: String, viewId: Int) = launch(Dispatchers.Default) { when (viewId) { binding.spnCompany.id -> { for (i in mCompanies.indices) { if (mCompanies[i].toString().equals(text, true)) { viewModel.setCompany(mCompanies[i]) break } else { viewModel.setCompany(null) } } } binding.spnDepartment.id -> { for (i in mDepartments.indices) { if (mDepartments[i].toString().equals(text, true)) { viewModel.setDepartment(mDepartments[i]) break } else { viewModel.setDepartment(null) } } } binding.spnPerson.id -> { for (i in mEmployees.indices) { if (mEmployees[i].toString().equals(text, true)) { viewModel.setEmployee(mEmployees[i]) break } else { viewModel.setEmployee(null) } } } } } override fun onDestroy() { super.onDestroy() job.cancel() } override fun onClick(view: View?) { when (view?.id) { binding.etDate.id -> selectDate() binding.etTime.id -> selectTime() binding.spnCompany.id -> spnCompany.showDropDown() binding.spnDepartment.id -> spnDepartment.showDropDown() binding.spnPerson.id -> spnPerson.showDropDown() binding.btnAdd?.id -> { this.findNavController().navigate(R.id.action_appointmentBookingFragment_to_accompaniedPersonFragment) } } } private fun selectDate() { val datePicker = DatePickerDialog( this.requireContext(), DatePickerDialog.OnDateSetListener { p0, p1, p2, p3 -> val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) val selectedCalendar = Calendar.getInstance() selectedCalendar.set(p1, p2, p3) viewModel.date.postValue(formatter.format(selectedCalendar.timeInMillis)) }, mCurrentCalendar.get(Calendar.YEAR), mCurrentCalendar.get(Calendar.MONTH), mCurrentCalendar.get(Calendar.DAY_OF_YEAR) ) datePicker.datePicker.minDate = System.currentTimeMillis() datePicker.show() } private fun selectTime() { val timePicker = TimePickerDialog( this.requireContext(), TimePickerDialog.OnTimeSetListener { p0, p1, p2 -> val formatter = SimpleDateFormat("HH:mm", Locale.getDefault()) val selectedCalendar = Calendar.getInstance() selectedCalendar.set(Calendar.HOUR_OF_DAY, p1) selectedCalendar.set(Calendar.MINUTE, p2) if (selectedCalendar.timeInMillis < System.currentTimeMillis()) { return@OnTimeSetListener } viewModel.time.postValue(formatter.format(selectedCalendar.timeInMillis)) }, mCurrentCalendar.get(Calendar.HOUR_OF_DAY), mCurrentCalendar.get(Calendar.MINUTE), true ) //datePicker.time.minDate = mCurrentCalendar.timeInMillis timePicker.show() } private fun observeTimeSelection() = launch{ viewModel.canCheckAvailability.observe(viewLifecycleOwner, androidx.lifecycle.Observer { if(it==null) return@Observer if(it){ checkForAvailability() } }) } private fun checkForAvailability() = launch{ viewModel.checkAvailability() } private fun addAccompaniedPerson(accompaniedPerson: AccompaniedPersonData) { Handler().postDelayed({ viewModel.onAccompaniedAdd(accompaniedPerson) },200) } }
vact/app/src/main/java/com/score/vact/ui/appointment_booking/AppointmentBookingFragment.kt
1505029611
package com.score.vact.ui.appointment_booking import android.os.Bundle import android.os.Handler import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.AutoCompleteTextView import androidx.core.os.bundleOf import androidx.databinding.DataBindingUtil import androidx.fragment.app.setFragmentResult import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import com.google.android.material.snackbar.Snackbar import com.score.vact.R import com.score.vact.databinding.FragmentAccompaniedFormBinding import com.score.vact.di.Injectable import com.score.vact.di.ViewModelFactoryModule import com.score.vact.model.IDProofData import com.score.vact.ui.afterTextChanged import kotlinx.android.synthetic.main.visitor_registration_fragment.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.coroutines.CoroutineContext /** * A simple [Fragment] subclass. */ class AccompaniedPersonFragment : Fragment(), Injectable, CoroutineScope, View.OnClickListener { companion object { val REQUEST_KEY = "REQUEST_KEY" } @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: AccompaniedPersonViewModel private lateinit var binding: FragmentAccompaniedFormBinding private lateinit var job: Job private var mIdProofList: List<IDProofData> = listOf() override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) observeIdProofList() observeGenderSelection() observePersonAdd() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<FragmentAccompaniedFormBinding>( inflater, R.layout.fragment_accompanied_form, container, false ) this.binding = binding return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel = ViewModelProvider(this, viewModelFactory).get(AccompaniedPersonViewModel::class.java) binding.viewModel = viewModel binding.lifecycleOwner = viewLifecycleOwner binding.spinnerIdProof.afterTextChanged { text -> updateSelectedIdProof(text.trim()) } binding.spinnerIdProof.setOnClickListener(this) } private fun observeIdProofList() = launch { viewModel.documentList.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } mIdProofList = it setSpinner(it, spinnerIdProof) }) } private fun setSpinner(it: List<Any>, view: AutoCompleteTextView) { if (it.isEmpty()) { view.setText("") } val adapter: ArrayAdapter<Any> = ArrayAdapter<Any>( this.requireContext(), android.R.layout.select_dialog_item, it ) view.threshold = 0 view.setAdapter(adapter) } private fun updateSelectedIdProof(text: String) = launch(Dispatchers.Default) { for (i in mIdProofList.indices) { if (mIdProofList[i].toString().equals(text, true)) { viewModel.setIdProof(mIdProofList[i]) break } else { viewModel.setIdProof(null) } } } override fun onDestroy() { super.onDestroy() job.cancel() } override fun onClick(p0: View?) { p0?.let { when (it.id) { binding.spinnerIdProof.id -> binding.spinnerIdProof.showDropDown() } } } private fun observeGenderSelection() = launch { viewModel.selectedGenderId.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } when (it) { binding.rbMale.id -> viewModel.selectedGenderText.postValue("Male") binding.rbFemale.id -> viewModel.selectedGenderText.postValue("Female") binding.rbTrans.id -> viewModel.selectedGenderText.postValue("Transgender") } }) } private fun observePersonAdd() = launch { viewModel.addedPerson.observe(viewLifecycleOwner, Observer { if (it == null) { return@Observer } Snackbar.make(coordinateLayout, "Person added", Snackbar.LENGTH_LONG).show() Handler().postDelayed({ val action = AccompaniedPersonFragmentDirections.actionAccompaniedPersonFragmentToAppointmentBookingFragment( -1,//dummy value because is required param avoided this by checking BookingFragment accompaniedPerson = it ) // [email protected]().navigate(action) val bundle = Bundle() bundle.putSerializable("person",it) setFragmentResult(REQUEST_KEY, bundle) // Step 4. Go back to Fragment A findNavController().navigateUp() }, 500) }) } }
vact/app/src/main/java/com/score/vact/ui/appointment_booking/AccompaniedPersonFragment.kt
183638025
package com.score.vact.ui.appointment_booking import android.util.Log import androidx.lifecycle.* import com.score.vact.model.appointment_booking.* import com.score.vact.repository.AppointmentRepo import com.score.vact.vo.Resource import com.score.vact.vo.Status import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject class AppointmentBookingViewModel @Inject constructor( private val mAppointmentRepo: AppointmentRepo ) : ViewModel() { private val TAG = javaClass.simpleName private val mBelongingList = mutableListOf<String>() val date = MutableLiveData<String>("") val time = MutableLiveData<String>("") val purpose = MutableLiveData<String>("") val selectedTransportationId = MutableLiveData<Int>() val selectedVehicleTypeId = MutableLiveData<Int>() val vehicleNumber = MutableLiveData("") val accompaniedByName = MutableLiveData("") val accompaniedByNumber = MutableLiveData("") val errorMessage = MutableLiveData<String>("") private val _belongings = MutableLiveData<List<BelongingsData>>() val belongigns: LiveData<List<BelongingsData>> get() = _belongings private var _companies = MutableLiveData<List<CompanyData>>() val companies: LiveData<List<CompanyData>> get() = _companies private val selectedCompany = MutableLiveData<CompanyData>(null) private var _departments = MutableLiveData<List<DepartmentData>>() val departments: LiveData<List<DepartmentData>> get() = _departments private val selectedDepartment = MutableLiveData<DepartmentData>(null) private var _emplyoees = MutableLiveData<List<EmployeeData>>() val employess: LiveData<List<EmployeeData>> get() = _emplyoees private val selectedEmployee = MutableLiveData<EmployeeData>(null) private val _appointmentAvailabilityResponse = MutableLiveData<Resource<Boolean>>() val appointmentAvailabilityResponse: LiveData<Resource<Boolean>> get() = _appointmentAvailabilityResponse val canCheckAvailability = MediatorLiveData<Boolean>().apply { addSource(selectedCompany){ value = performAvailabilityCheck() } addSource(selectedDepartment){ value = performAvailabilityCheck() } addSource(selectedEmployee){ value = performAvailabilityCheck() } addSource(date){ value = performAvailabilityCheck() } addSource(time) { value = performAvailabilityCheck() } } private val _accompaniedPersons = MutableLiveData<List<AccompaniedPersonData>>() val accompaniedPersons: LiveData<List<AccompaniedPersonData>> get() = _accompaniedPersons private fun updateSelectedList(it: Boolean, date: String): List<String> { if (it) { mBelongingList.add(date) } else { mBelongingList.remove(date) } return mBelongingList } fun onAccompaniedAdd(accompaniedPerson: AccompaniedPersonData) { val existingList = mutableListOf<AccompaniedPersonData>() existingList.addAll(if (_accompaniedPersons.value == null) emptyList() else _accompaniedPersons.value!!) existingList.add(accompaniedPerson) _accompaniedPersons.postValue(existingList) } suspend fun getCompanies() { val companies = mAppointmentRepo.getCompanies() _companies.postValue(companies) } suspend fun getBelongings() { val belongings = mAppointmentRepo.getBelongings() belongings.observeForever { if (it == null) { return@observeForever } _belongings.postValue(it) } } suspend fun setCompany(companyData: CompanyData?) { selectedDepartment.postValue(null) selectedEmployee.postValue(null) selectedCompany.postValue(companyData) if (companyData != null) { getDepartments(companyData) } else { _departments.postValue(emptyList()) _emplyoees.postValue(emptyList()) } } private suspend fun getDepartments(companyData: CompanyData) { val departments = mAppointmentRepo.getDepartment(companyId = companyData.id) _departments.postValue(departments) } suspend fun setDepartment(departmentData: DepartmentData?) { selectedEmployee.postValue(null) selectedDepartment.postValue(departmentData) if (departmentData != null) { getEmployees(departmentData.id) } else { _emplyoees.postValue(emptyList()) } } private suspend fun getEmployees(departmentId: String) { val employees = mAppointmentRepo.getEmployees(selectedCompany.value!!.id, departmentId) _emplyoees.postValue(employees) } fun setEmployee(employeeData: EmployeeData?) { selectedEmployee.postValue(employeeData) } fun remove(accompaniedPersonData: AccompaniedPersonData) { val existingList = mutableListOf<AccompaniedPersonData>() existingList.addAll(_accompaniedPersons.value!!) existingList.remove(accompaniedPersonData) _accompaniedPersons.postValue(existingList) } val validate = MediatorLiveData<Boolean>().apply { /* addSource(selectedTransportationId) { value = isValid() } addSource(vehicleNumber) { value = isValid() }*/ addSource(selectedEmployee) { value = isValid() } addSource(selectedDepartment) { value = isValid() } addSource(selectedCompany) { value = isValid() } addSource(date) { value = isValid() } addSource(time) { value = isValid() } addSource(appointmentAvailabilityResponse){ value = isValid() } addSource(purpose) { value = isValid() } } private fun isValid(): Boolean { errorMessage.postValue("") if (selectedCompany.value == null) { errorMessage.postValue("Please select company") return false } if (selectedDepartment.value == null) { errorMessage.postValue("Please select department") return false } if (selectedEmployee.value == null) { errorMessage.postValue("Please select person to meet") } if (date.value.isNullOrEmpty()) { return false } if (time.value.isNullOrEmpty()) { return false } if (appointmentAvailabilityResponse.value == null || appointmentAvailabilityResponse.value!!.status == Status.ERROR) { errorMessage.postValue("Appointment not available at selected date and time") return false } if (purpose.value.isNullOrEmpty()) { return false } /* if (selectedTransportationId.value == R.id.rdPersonal) { if (vehicleNumber.value.isNullOrEmpty()) { return false } }*/ return true } fun updateBelongingsItem(updatedBelonging: BelongingsData) { viewModelScope.launch(Dispatchers.Default) { _belongings.value?.let { it.forEach { data -> if (updatedBelonging.id == data.id) { val updatedData = data.copy(isSelected = updatedBelonging.isSelected) it as MutableList it[it.indexOf(data)] = updatedData _belongings.postValue(it) } } } } } private fun performAvailabilityCheck(): Boolean { return (selectedCompany.value != null && selectedDepartment.value != null && selectedEmployee.value != null && !date.value.isNullOrEmpty() && !time.value.isNullOrEmpty()) } suspend fun checkAvailability() { _appointmentAvailabilityResponse.postValue( Resource( status = Status.LOADING, data = null, message = null ) ) val date = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).parse(date.value!!)!! val formattedData = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(date.time) val time = SimpleDateFormat("HH:mm", Locale.getDefault()).parse(time.value!!)!! val formattedTime = SimpleDateFormat("HH:mm:ss",Locale.getDefault()).format(time) Log.d(TAG,"formatted date and time $formattedData and $formattedTime") val isAvailable = mAppointmentRepo.checkAppointmentAvailability( companyId = selectedCompany.value!!.id, departmentId = selectedDepartment.value!!.id, employeeId = selectedEmployee.value!!.id, date = formattedData, time = formattedTime!! ) _appointmentAvailabilityResponse.postValue(isAvailable) } }
vact/app/src/main/java/com/score/vact/ui/appointment_booking/AppointmentBookingViewModel.kt
3362584813
package com.score.vact.datasource import android.accounts.NetworkErrorException import android.util.Log import com.google.gson.Gson import com.score.vact.api.AppService import com.score.vact.model.* import com.score.vact.vo.Resource import com.score.vact.vo.ResponseException import com.score.vact.vo.Status import org.json.JSONArray import org.json.JSONObject import java.lang.Exception import java.net.UnknownHostException import javax.inject.Inject class VisitorRegistrationDataSource @Inject constructor(private val appService: AppService) { private val TAG = javaClass.simpleName suspend fun getCountries():List<CountryData>{ var countryList:List<CountryData> = listOf() try { val countriesResponse = appService.getCountries().await() val responseObj = JSONObject(countriesResponse) if (responseObj.getInt("Output") == 1) { countryList = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<CountryData>::class.java ).toList() Log.d(TAG, "api countryList ${countryList.size}") // registrationFormDao.insertCountries(countries = countryList) } } catch (ex: Exception) { ex.printStackTrace() } finally { Log.d(TAG, "returning countryList ") return countryList // return registrationFormDao.getCountries() } } suspend fun getStates(countryId:String):List<StateData>{ var stateList:List<StateData> = listOf() try{ val apiResponse = appService.getStates(countryId).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { stateList = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<StateData>::class.java ).toList() Log.d(TAG, "api countryList ${stateList.size}") } }catch (ex:Exception){ ex.printStackTrace() }finally { return stateList } } suspend fun getDistricts(stateId:String):List<DistrictData>{ var districtList:List<DistrictData> = listOf() try{ val apiResponse = appService.getDistricts(stateId).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { districtList = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<DistrictData>::class.java ).toList() Log.d(TAG, "api countryList ${districtList.size}") } }catch (ex:Exception){ ex.printStackTrace() }finally { return districtList } } suspend fun getCities(districtId:String):List<CityData>{ var cityList:List<CityData> = listOf() try{ val apiResponse = appService.getCities(districtId).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { cityList = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<CityData>::class.java ).toList() Log.d(TAG, "api countryList ${cityList.size}") } }catch (ex:Exception){ ex.printStackTrace() }finally { return cityList } } suspend fun getIdProofList():List<IDProofData>{ var idList:List<IDProofData> = listOf() try{ val apiResponse = appService.getIdProofList().await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { idList = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<IDProofData>::class.java ).toList() Log.d(TAG, "api countryList ${idList.size}") } }catch (ex:Exception){ ex.printStackTrace() }finally { return idList } } suspend fun registerVisitor( firstName: String, lastName: String, birthYear: String, gender: String, contactNumber: String, address: String, pincode: String, countryId: String, stateId: String, districtId: String, cityId: String, email: String, identityId: String, idNo: String, userId:Int ): Resource<Int> { try{ val requestArray =JSONArray() val requestJSON = JSONObject() requestJSON.put("VISITOR_ID",0) requestJSON.put("FIRST_NAME",firstName) requestJSON.put("LAST_NAME",lastName) requestJSON.put("DOB_YEAR",birthYear) requestJSON.put("GENDER",gender) requestJSON.put("CONTACT_NO",contactNumber) requestJSON.put("ADDRESS",address) requestJSON.put("PIN_CODE",pincode) requestJSON.put("STATE_ID",stateId) requestJSON.put("DISTRICT_ID",districtId) requestJSON.put("CITY_ID",cityId) requestJSON.put("EMAIL_ID",email) requestJSON.put("IDENTITY_ID",identityId) requestJSON.put("IDENTITY_NO",idNo) requestJSON.put("LOGIN_USER_ID",userId) requestArray.put(requestJSON) val apiResponse = appService.registerVisitor( requestParam = requestArray.toString() ).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("OUTPUT") == 1) { return Resource(status = Status.SUCCESS,data = responseObj.getInt("USER_ID"),message = null) }else{ return Resource(status = Status.ERROR,data = null,message = responseObj.getString("MESSAGE")) } }catch (ex: NetworkErrorException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: UnknownHostException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: ResponseException) { ex.errorMessage return postError(message = ex.errorMessage) } catch (ex: Exception) { ex.printStackTrace() return postError(message = "Something went wrong") } } private fun postError(message: String): Resource<Int> { return Resource(status = Status.ERROR, data = null, message = message) } }
vact/app/src/main/java/com/score/vact/datasource/VisitorRegistrationDataSource.kt
528897720
package com.score.vact.datasource import android.accounts.NetworkErrorException import android.os.Handler import com.score.vact.api.AppService import com.score.vact.model.QuestionData import com.score.vact.vo.Resource import com.score.vact.vo.ResponseException import com.score.vact.vo.Status import java.lang.Exception import java.net.UnknownHostException import javax.inject.Inject class SurveyDataSource @Inject constructor(private val appService: AppService) { suspend fun getSurveyQuestions():List<QuestionData> { try { //val apiResponse = appService.getSurveyQuestions().await() return getDummyQuestions() } catch (ex: Exception) { ex.printStackTrace() return emptyList() } } private fun postError(message: String): Resource<List<QuestionData>> { return Resource(status = Status.ERROR, data = null, message = message) } private fun getDummyQuestions(): MutableList<QuestionData> { val questions: MutableList<QuestionData> = mutableListOf<QuestionData>() questions.add(QuestionData(1, "What are symptoms of coronavirus (COVID-19)?")) questions.add( QuestionData( 2, "What are some other symptoms coronavirus patients might experience?" ) ) questions.add( QuestionData( 3, "How long does it take to develop symptoms after you have been exposed to COVID-19?" ) ) questions.add( QuestionData( 4, "Is it possible to have other coronavirus symptoms without the fever?" ) ) return questions } }
vact/app/src/main/java/com/score/vact/datasource/SurveyDataSource.kt
962605696
package com.score.vact.datasource import android.accounts.NetworkErrorException import com.google.gson.Gson import com.score.vact.api.AppService import com.score.vact.model.appointment.AppointmentData import com.score.vact.model.appointment.DetailsData import com.score.vact.model.appointment_booking.BelongingsData import com.score.vact.model.appointment_booking.CompanyData import com.score.vact.model.appointment_booking.DepartmentData import com.score.vact.model.appointment_booking.EmployeeData import com.score.vact.vo.Resource import com.score.vact.vo.ResponseException import com.score.vact.vo.Status import org.json.JSONObject import java.io.IOException import java.net.UnknownHostException import javax.inject.Inject class AppointmentDataSource @Inject constructor(private val appService: AppService) { suspend fun getCompanies(): List<CompanyData> { var companies = listOf<CompanyData>() try { val apiResponse = appService.getCompanies().await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { companies = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<CompanyData>::class.java ).toList() } } catch (ex: Exception) { ex.printStackTrace() } finally { return companies } } suspend fun getDepartments(companyId: String): List<DepartmentData> { var departments = listOf<DepartmentData>() try { val apiResponse = appService.getDepartments(companyId).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { departments = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<DepartmentData>::class.java ).toList() } } catch (ex: Exception) { ex.printStackTrace() } finally { return departments } } suspend fun getEmployess(companyId: String, departmentId: String): List<EmployeeData> { var employees = listOf<EmployeeData>() try { val apiResponse = appService.getEmployees(companyId, departmentId).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { employees = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<EmployeeData>::class.java ).toList() } } catch (ex: Exception) { ex.printStackTrace() } finally { return employees } } suspend fun getBelongings(): List<BelongingsData> { var belongings = listOf<BelongingsData>() try { val apiResponse = appService.getBelongings().await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("Output") == 1) { belongings = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<BelongingsData>::class.java ).toList() } } catch (ex: Exception) { ex.printStackTrace() } finally { return belongings } } suspend fun getAppointments(date: String): List<AppointmentData> { var appointments = listOf<AppointmentData>() try { //TODO get appointments from API // val apiResponse = appService.getAppointments().await() val responseObj = JSONObject(getDummyAppointments()) if (responseObj.getInt("Output") == 1) { appointments = Gson().fromJson( responseObj.getJSONArray("Data").toString(), Array<AppointmentData>::class.java ).toList() } } catch (ex: Exception) { ex.printStackTrace() } finally { return appointments } } private fun getDummyAppointments(): String { /* { "Output": 1, "Data": [ { "id": 1, "image_url": "", "name": "Ajit Jaiswal", "number": "9876543210", "email": "[email protected]", "address": "Kolkata", "date": "May 25 2020", "time": "04:30 PM", "status": 1 }, { "id": 2, "image_url": "", "name": "Debjit maity", "number": "9876543210", "email": "[email protected]", "address": "Kolkata", "date": "May 25 2020", "time": "05:30 PM", "status": 2 } ] } */ return "{\n" + " \"Output\": 1,\n" + " \"Data\": [\n" + " {\n" + " \"id\": 1,\n" + " \"image_url\": \"\",\n" + " \"name\": \"Ajit Jaiswal\",\n" + " \"number\": \"9876543210\",\n" + " \"email\": \"[email protected]\",\n" + " \"address\": \"Kolkata\",\n" + " \"date\": \"May 25 2020\",\n" + " \"time\": \"04:30 PM\",\n" + " \"status\": 1\n" + " },\n" + " {\n" + " \"id\": 2,\n" + " \"image_url\": \"\",\n" + " \"name\": \"Debjit maity\",\n" + " \"number\": \"9876543210\",\n" + " \"email\": \"[email protected]\",\n" + " \"address\": \"Kolkata\",\n" + " \"date\": \"May 25 2020\",\n" + " \"time\": \"05:30 PM\",\n" + " \"status\": 2\n" + " }\n" + " ]\n" + "}" } fun getAppointmentDetails(appointmentId: Int): DetailsData { try { //TODO get appointments from API // val apiResponse = appService.getAppointments().await() val responseObj = JSONObject(getDummyAppointmentDetails()) if (responseObj.getInt("Output") == 1) { val details = Gson().fromJson( responseObj.getJSONObject("Data").toString(), DetailsData::class.java ) return details } else { throw IOException("Something went wrong") } } catch (ex: Exception) { ex.printStackTrace() throw IOException("Something went wrong") } } private fun getDummyAppointmentDetails(): String { return "{\n" + " \"Output\": 1,\n" + " \"Data\": {\n" + " \"id\":1,\n" + " \"accompanied_by\": [\n" + " {\n" + " \"name\": \"Ajit Jaiswal\",\n" + " \"number\": \"9876543210\"\n" + " },\n" + " {\n" + " \"name\": \"Debjit Maity\",\n" + " \"number\": \"9876543210\"\n" + " }\n" + " ],\n" + " \"report_to\": \"Subhajit Sarkar\",\n" + " \"designation\": \"HOD\",\n" + " \"department\": \"IT Department\",\n" + " \"purpose\": \"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\",\n" + " \"belongings\": [\n" + " \"Mobile\",\n" + " \"Bag\",\n" + " \"Laptop\"\n" + " ]\n" + " }\n" + "}" /* { "Output": 1, "Data": { "id":1, "accompanied_by": [ { "name": "Ajit Jaiswal", "number": "9876543210" }, { "name": "Debjit Maity", "number": "9876543210" } ], "report_to": "Subhajit Sarkar", "designation": "HOD", "department": "IT Department", "purpose": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", "belongings": [ "Mobile", "Bag", "Laptop" ] } } */ } suspend fun checkAppointmentAvailability( companyId: String, departmentId: String, employeeId: String, date: String, time: String ): Resource<Boolean> { try { val apiResponse = appService.checkAppointmentAvailability( companyId, employeeId, date, time ).await() val responseObj = JSONObject(apiResponse) if (responseObj.getInt("OUTPUT") == 1) { return Resource( status = Status.SUCCESS, data = true, message = null ) } else { return Resource( status = Status.ERROR, data = false, message = responseObj.getString("MESSAGE") ) } } catch (ex: NetworkErrorException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: UnknownHostException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: ResponseException) { ex.errorMessage return postError(message = ex.errorMessage) } catch (ex: java.lang.Exception) { ex.printStackTrace() return postError(message = "Something went wrong") } } private fun postError(message: String): Resource<Boolean> { return Resource(status = Status.ERROR, data = null, message = message) } }
vact/app/src/main/java/com/score/vact/datasource/AppointmentDataSource.kt
3340942520
package com.score.vact.datasource import com.score.vact.api.AppService import com.score.vact.vo.Resource import com.score.vact.vo.Status import org.json.JSONObject import java.lang.Exception import javax.inject.Inject class HomeDataSource @Inject constructor(val appService: AppService) { suspend fun verifyPhoneNumber(number: String): Resource<Int> { try { val apiResponse = appService.verifyPhoneNumber(number).await() val responseOBJ = JSONObject(apiResponse) if (responseOBJ.getInt("Output") == 1) { return Resource(status = Status.SUCCESS, data = 1, message = null) } else { return Resource( status = Status.ERROR, data = null, message = responseOBJ.getString("Message") ) } } catch (ex: Exception) { return Resource( status = Status.ERROR, data = null, message = ex.message ?: "Something went wrong" ) } } suspend fun verifyOtpNumber(number: String, otp: String): Resource<Int> { try { val apiResponse = appService.verifyOTP(number, otp).await() val responseOBJ = JSONObject(apiResponse) if (responseOBJ.getInt("Output") == 1) { return Resource( status = Status.SUCCESS, data = responseOBJ.getInt("IsExist"), message = null ) } else { return Resource( status = Status.ERROR, data = null, message = responseOBJ.getString("Status") ) } } catch (ex: Exception) { return Resource( status = Status.ERROR, data = null, message = ex.message ?: "Something went wrong" ) } } }
vact/app/src/main/java/com/score/vact/datasource/HomeDataSource.kt
1607234365
package com.score.vact.vo import kotlinx.coroutines.* fun <T> lazyDeferred(block: suspend CoroutineScope.() -> T): Lazy<Deferred<T>> { return lazy { GlobalScope.async(start = CoroutineStart.LAZY) { block.invoke(this) } } }
vact/app/src/main/java/com/score/vact/vo/Delegates.kt
1207961991
package com.score.vact.vo import java.io.IOException class NoConnectivityException : IOException() class AuthFailureException : IOException()
vact/app/src/main/java/com/score/vact/vo/Exceptions.kt
442522249
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.vo /** * Status of a resource that is provided to the UI. * * * These are usually created by the Repository classes where they return * `LiveData<Resource<T>>` to pass back the latest data to the UI with its fetch status. */ enum class Status { SUCCESS, ERROR, LOADING }
vact/app/src/main/java/com/score/vact/vo/Status.kt
3942257715
package com.score.vact.vo enum class Answer {Yes,No,NOT_AWARE,NA}
vact/app/src/main/java/com/score/vact/vo/Answer.kt
1541192148
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.vo import com.score.vact.vo.Status.ERROR import com.score.vact.vo.Status.LOADING import com.score.vact.vo.Status.SUCCESS /** * A generic class that holds a value with its loading status. * @param <T> </T> */ data class Resource<out T>(val status: Status, val data: T?, val message: String?) { companion object { fun <T> success(data: T?): Resource<T> { return Resource(SUCCESS, data, null) } fun <T> error(msg: String, data: T?): Resource<T> { return Resource(ERROR, data, msg) } fun <T> loading(data: T?): Resource<T> { return Resource(LOADING, data, null) } } }
vact/app/src/main/java/com/score/vact/vo/Resource.kt
1734387929
package com.score.vact.vo import java.io.IOException data class ResponseException(val errorCode: Int, val errorMessage: String) : IOException()
vact/app/src/main/java/com/score/vact/vo/ResponseException.kt
570627315
package com.score.vact.repository import android.content.SharedPreferences import javax.inject.Inject import javax.inject.Singleton @Singleton class SharedPrefs @Inject constructor(private val sharedPreferences: SharedPreferences) { var userName: String set(value) { val editor = sharedPreferences.edit() editor.putString("name", value) editor.apply() } get() = sharedPreferences.getString("name", "")!! var userId:Int set(value) { val editor = sharedPreferences.edit() editor.putInt("userId",value) editor.apply() } get() = sharedPreferences.getInt("userId",0) }
vact/app/src/main/java/com/score/vact/repository/SharedPrefs.kt
775969419
package com.score.vact.repository import com.score.vact.datasource.VisitorRegistrationDataSource import com.score.vact.db.RegistrationFormDao import com.score.vact.model.* import com.score.vact.vo.Resource import javax.inject.Inject class VisitorRegistrationRepo @Inject constructor( private val viewRegistrationDataSource: VisitorRegistrationDataSource, private val registrationFormDao: RegistrationFormDao, private val sharedPrefs: SharedPrefs ) { private val TAG = javaClass.simpleName suspend fun getCountries(): List<CountryData> =viewRegistrationDataSource.getCountries() suspend fun getStates(countryId: String):List<StateData> = viewRegistrationDataSource.getStates(countryId = countryId) suspend fun getDistricts(stateId: String):List<DistrictData> = viewRegistrationDataSource.getDistricts(stateId = stateId) suspend fun getCities(districtId: String):List<CityData> = viewRegistrationDataSource.getCities(districtId = districtId) suspend fun getIdProofList():List<IDProofData> = viewRegistrationDataSource.getIdProofList() suspend fun registerVisitor(firstName: String, lastName: String, birthYear: String, gender: String, contactNumber: String, address: String, pincode: String, countryId: String, stateId: String, districtId: String, cityId: String, email: String, identityId: String, idNo: String ): Resource<Int>{ return viewRegistrationDataSource.registerVisitor( firstName = firstName, lastName = lastName, birthYear = birthYear, gender = gender, contactNumber = contactNumber, address = address, pincode = pincode, countryId = countryId, stateId = stateId, districtId = districtId, cityId = cityId, email = email, identityId = identityId, idNo = idNo,userId = sharedPrefs.userId) } }
vact/app/src/main/java/com/score/vact/repository/VisitorRegistrationRepo.kt
1315507437
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.repository import android.accounts.NetworkErrorException import android.util.Log import com.score.vact.vo.Resource import com.score.vact.vo.Status import com.score.vact.api.AppService import com.score.vact.model.UserData import com.score.vact.vo.ResponseException import org.json.JSONObject import java.lang.Exception import java.net.UnknownHostException import javax.inject.Inject import javax.inject.Singleton /** * Repository that handles User objects. */ @Singleton class UserRepository @Inject constructor( private val appSe: AppService, private val sharedPrefs: SharedPrefs ) { private val TAG = javaClass.simpleName suspend fun login(userName: String, password: String): Resource<UserData> { Log.d("Repo ", "api called"); try { val loginResponse = appSe.loginAsync(userName, password).await() Log.d(TAG, "response $loginResponse") val dataObj = JSONObject(loginResponse) if (dataObj.getInt("Output") == 1) { val id: Int = dataObj.getInt("Id") val name = dataObj.getString("Name") val image = dataObj.getString("Image") val type = dataObj.getString("Type") val isAdmin = dataObj.getInt("IsAdmin") val userData = UserData(id = id, name = name, image = image, type = type,isAdmin = isAdmin) sharedPrefs.userId = userData.id return Resource( status = Status.SUCCESS, data = userData, message = "" ) } else { return Resource( status = Status.ERROR, data = null, message = dataObj.getString("Message") ) } } catch (ex: NetworkErrorException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: UnknownHostException) { ex.printStackTrace() return postError("Connectivity exception") } catch (ex: ResponseException) { ex.errorMessage return postError(message = ex.errorMessage) } catch (ex: Exception) { ex.printStackTrace() return postError(message = "Something went wrong") } } private fun postError(message: String): Resource<UserData> { return Resource(status = Status.ERROR, data = null, message = message) } }
vact/app/src/main/java/com/score/vact/repository/UserRepository.kt
45708856
package com.score.vact.repository import com.score.vact.datasource.HomeDataSource import javax.inject.Inject class HomeRepository @Inject constructor(val homeDataSource: HomeDataSource) { suspend fun verifyPhoneNumber(number:String) = homeDataSource.verifyPhoneNumber(number) suspend fun verifyOtp(number: String, otp: String) = homeDataSource.verifyOtpNumber(number,otp) }
vact/app/src/main/java/com/score/vact/repository/HomeRepository.kt
1234366155
package com.score.vact.repository import javax.inject.Inject class SplashRepo @Inject constructor(private val sharedPrefs: SharedPrefs){ val isLoggedIn = sharedPrefs.userId!=0 }
vact/app/src/main/java/com/score/vact/repository/SplashRepo.kt
4280297653
package com.score.vact.repository import androidx.lifecycle.LiveData import com.score.vact.datasource.SurveyDataSource import com.score.vact.db.SurveyDao import com.score.vact.model.QuestionData import com.score.vact.vo.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.inject.Inject class SurveyRepository @Inject constructor( private val surveyDataSource: SurveyDataSource, private val surveyDao: SurveyDao ) { suspend fun getSurveyQuestions(): LiveData<List<QuestionData>> { val questions = surveyDataSource.getSurveyQuestions() surveyDao.insertQuestions(questions) return surveyDao.getSurveyQuestions() } }
vact/app/src/main/java/com/score/vact/repository/SurveyRepository.kt
1186814015
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.repository import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.annotation.MainThread import androidx.annotation.WorkerThread import com.score.vact.AppExecutors import com.score.vact.vo.Resource import com.score.vact.api.ApiEmptyResponse import com.score.vact.api.ApiErrorResponse import com.score.vact.api.ApiResponse import com.score.vact.api.ApiSuccessResponse /** * A generic class that can provide a resource backed by both the sqlite database and the network. * * * You can read more about it in the [Architecture * Guide](https://developer.android.com/arch). * @param <ResultType> * @param <RequestType> </RequestType></ResultType> */ abstract class NetworkBoundResource<ResultType, RequestType> @MainThread constructor(private val appExecutors: AppExecutors) { private val result = MediatorLiveData<Resource<ResultType>>() init { result.value = Resource.loading(null) @Suppress("LeakingThis") val dbSource = loadFromDb() result.addSource(dbSource) { data -> result.removeSource(dbSource) if (shouldFetch(data)) { fetchFromNetwork(dbSource) } else { result.addSource(dbSource) { newData -> setValue(Resource.success(newData)) } } } } @MainThread private fun setValue(newValue: Resource<ResultType>) { if (result.value != newValue) { result.value = newValue } } private fun fetchFromNetwork(dbSource: LiveData<ResultType>) { val apiResponse = createCall() // we re-attach dbSource as a new source, it will dispatch its latest value quickly result.addSource(dbSource) { newData -> setValue(Resource.loading(newData)) } result.addSource(apiResponse) { response -> result.removeSource(apiResponse) result.removeSource(dbSource) when (response) { is ApiSuccessResponse -> { appExecutors.diskIO().execute { saveCallResult(processResponse(response)) appExecutors.mainThread().execute { // we specially request a new live data, // otherwise we will get immediately last cached value, // which may not be updated with latest results received from network. result.addSource(loadFromDb()) { newData -> setValue(Resource.success(newData)) } } } } is ApiEmptyResponse -> { appExecutors.mainThread().execute { // reload from disk whatever we had result.addSource(loadFromDb()) { newData -> setValue(Resource.success(newData)) } } } is ApiErrorResponse -> { onFetchFailed() result.addSource(dbSource) { newData -> setValue(Resource.error(response.errorMessage, newData)) } } } } } protected open fun onFetchFailed() {} fun asLiveData() = result as LiveData<Resource<ResultType>> @WorkerThread protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body @WorkerThread protected abstract fun saveCallResult(item: RequestType) @MainThread protected abstract fun shouldFetch(data: ResultType?): Boolean @MainThread protected abstract fun loadFromDb(): LiveData<ResultType> @MainThread protected abstract fun createCall(): LiveData<ApiResponse<RequestType>> }
vact/app/src/main/java/com/score/vact/repository/NetworkBoundResource.kt
1674029754
package com.score.vact.repository import androidx.lifecycle.LiveData import com.score.vact.datasource.AppointmentDataSource import com.score.vact.db.AppointmentDao import com.score.vact.model.appointment.AppointmentData import com.score.vact.model.appointment.AppointmentDetailsData import com.score.vact.model.appointment_booking.BelongingsData import com.score.vact.model.appointment_booking.CompanyData import com.score.vact.model.appointment_booking.DepartmentData import com.score.vact.model.appointment_booking.EmployeeData import com.score.vact.vo.Resource import java.io.IOException import java.lang.Exception import javax.inject.Inject class AppointmentRepo @Inject constructor( private val mAppointmentDataSource: AppointmentDataSource, private val appointmentDao: AppointmentDao ) { //Appointment booking fragment suspend fun getCompanies(): List<CompanyData> = mAppointmentDataSource.getCompanies() suspend fun getDepartment(companyId: String): List<DepartmentData> = mAppointmentDataSource.getDepartments(companyId = companyId) suspend fun getEmployees(companyId: String, departmentId: String): List<EmployeeData> = mAppointmentDataSource.getEmployess(companyId, departmentId) suspend fun getBelongings(): LiveData<List<BelongingsData>> { val belongings = mAppointmentDataSource.getBelongings() appointmentDao.insertBelongings(belongings) return appointmentDao.getBelongings() } //AppointmentFragment suspend fun getAppointments(date:String): LiveData<List<AppointmentData>> { val appointments = mAppointmentDataSource.getAppointments(date) appointmentDao.insertAppointments(appointments) return appointmentDao.getAppointments(date) } suspend fun getAppointmentDetails(appointmentId: Int): LiveData<AppointmentDetailsData> { try { val details = mAppointmentDataSource.getAppointmentDetails(appointmentId) appointmentDao.insertDetails(details) return appointmentDao.getAppointmentDetails(appointmentId) } catch (ex: Exception) { ex.printStackTrace() throw IOException(ex.message) } } suspend fun checkAppointmentAvailability( companyId: String, departmentId: String, employeeId: String, date: String, time: String ): Resource<Boolean> = mAppointmentDataSource.checkAppointmentAvailability( companyId = companyId, departmentId = departmentId, employeeId = employeeId, date = date, time = time ) }
vact/app/src/main/java/com/score/vact/repository/AppointmentRepo.kt
1185200644
package com.score.vact.di.home import java.lang.annotation.RetentionPolicy import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class HomeScope
vact/app/src/main/java/com/score/vact/di/home/HomeScope.kt
521264124
package com.score.vact.di.home import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.home.HomeViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class HomeViewModelModule { @Binds @IntoMap @ViewModelKey(HomeViewModel::class) abstract fun bindHomeViewModelModule(homeViewModel: HomeViewModel):ViewModel }
vact/app/src/main/java/com/score/vact/di/home/HomeViewModelModule.kt
4181102774
package com.score.vact.di.splash import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.splash.SplashViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class SplashViewModelModule { @Binds @IntoMap @ViewModelKey(SplashViewModel::class) abstract fun bindViewModelModule(splashViewModel: SplashViewModel):ViewModel }
vact/app/src/main/java/com/score/vact/di/splash/SplashViewModelModule.kt
909612987
package com.score.vact.di.splash import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class SplashScope
vact/app/src/main/java/com/score/vact/di/splash/SplashScope.kt
604402917
package com.score.vact.di import android.app.Application import android.content.Context.MODE_PRIVATE import android.content.SharedPreferences import android.util.Log import androidx.room.Room import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.score.vact.api.AppService import com.score.vact.db.AppDb import com.score.vact.db.AppointmentDao import com.score.vact.db.RegistrationFormDao import com.score.vact.db.SurveyDao import com.score.vact.vo.ResponseException import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactory import javax.inject.Singleton @Module class AppModule { private val BASE_URL = "http://192.168.0.208/vactservice/api/" @Singleton @Provides fun provideAppService(): AppService { val requestInterceptor = Interceptor { chain -> val url = chain.request() .url() .newBuilder() .build() val request = chain.request() .newBuilder() .url(url) .build() Log.d(javaClass.simpleName, "url is $url") return@Interceptor chain.proceed(request) } val responseInterceptor = Interceptor { chain -> return@Interceptor getResponseInteceptor(chain) } val okHttpClient = OkHttpClient.Builder() .addInterceptor(requestInterceptor) .addInterceptor(responseInterceptor) .build() return Retrofit.Builder() .client(okHttpClient) .baseUrl(BASE_URL) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() .create(AppService::class.java) } private fun getResponseInteceptor(chain: Interceptor.Chain): Response? { val response = chain.proceed(chain.request()) when { response.code() == 400 -> throw ResponseException(response.code(), "Bad Request") response.code() == 401 -> throw ResponseException( response.code(), "Invalid username or password" ) response.code() == 403 -> throw ResponseException(response.code(), "Forbidden") response.code() == 404 -> throw ResponseException(response.code(), "Not Found") response.code() == 405 -> throw ResponseException(response.code(), "Method Not Allowed") response.code() == 406 -> throw ResponseException(response.code(), "Not Acceptable") response.code() == 408 -> throw ResponseException(response.code(), "Request timeout") response.code() == 500 -> throw ResponseException(response.code(), "Server Error") response.code() == 204 -> throw ResponseException( response.code(), "No Content exception" ) response.code() != 200 -> throw ResponseException( response.code(), "Something went wrong" ) else -> return response } } @Singleton @Provides fun getSharedPreference(application: Application?): SharedPreferences { return application!!.applicationContext.getSharedPreferences("MyPrefs", MODE_PRIVATE) } @Provides fun provideDb(app: Application): AppDb { return Room .databaseBuilder(app, AppDb::class.java, "app.db") .fallbackToDestructiveMigration() .build() } @Provides fun provideUserDao(db: AppDb): RegistrationFormDao { return db.registrationFormData() } @Provides fun provideAppointmentsDao(db: AppDb): AppointmentDao { return db.appointmentDao() } @Provides fun provideSurveyDao(db: AppDb):SurveyDao{ return db.surveyDao() } }
vact/app/src/main/java/com/score/vact/di/AppModule.kt
3171795142
package com.score.vact.di.visitor_registration import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class VisitorRegistrationScope
vact/app/src/main/java/com/score/vact/di/visitor_registration/VisitorRegistrationScope.kt
2345895084
package com.score.vact.di.visitor_registration import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.visitor_registration.VisitorRegistrationViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class VisitorRegistrationViewModelModule { @Binds @IntoMap @ViewModelKey(VisitorRegistrationViewModel::class) abstract fun bindVisitorRegistrationModule(registrationViewModel: VisitorRegistrationViewModel): ViewModel }
vact/app/src/main/java/com/score/vact/di/visitor_registration/VisitorRegistrationViewModelModule.kt
433829537
package com.score.vact.di import com.score.vact.di.appointment_details.AppointmentDetailsScope import com.score.vact.di.appointment_details.AppointmentDetailsViewModelModule import com.score.vact.di.appointment_list.AppointmentListScope import com.score.vact.di.appointment_list.AppointmentListViewModelModule import com.score.vact.di.appointment_modify.AppointmentModifyScope import com.score.vact.di.appointment_modify.AppointmentModifyViewModelModule import com.score.vact.ui.appointment_details.AppointmentDetailsFragment import com.score.vact.ui.appointment_list.AppointmentsFragment import com.score.vact.ui.appointment_modify.AppointmentModifyFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class AppointmentFragmentBuilderModule { @AppointmentListScope @ContributesAndroidInjector(modules = [AppointmentListViewModelModule::class]) abstract fun contributeAppointmentListFragment(): AppointmentsFragment @AppointmentDetailsScope @ContributesAndroidInjector(modules = [AppointmentDetailsViewModelModule::class]) abstract fun contributeAppointmentDetailsFragment(): AppointmentDetailsFragment @AppointmentModifyScope @ContributesAndroidInjector(modules = [AppointmentModifyViewModelModule::class]) abstract fun contributeAppointmentModifyFragment(): AppointmentModifyFragment }
vact/app/src/main/java/com/score/vact/di/AppointmentFragmentBuilderModule.kt
236098670
package com.score.vact.di.appointment_modify import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class AppointmentModifyScope
vact/app/src/main/java/com/score/vact/di/appointment_modify/AppointmentModifyScope.kt
3554490141
package com.score.vact.di.appointment_modify import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.appointment_modify.AppointmentModifyViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class AppointmentModifyViewModelModule { @Binds @IntoMap @ViewModelKey(AppointmentModifyViewModel::class) abstract fun bindAppointmentModifyViewModel(appointmentModifyViewModel: AppointmentModifyViewModel): ViewModel }
vact/app/src/main/java/com/score/vact/di/appointment_modify/AppointmentModifyViewModelModule.kt
2915301089
package com.score.vact.di.scope import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class AppointmentScope
vact/app/src/main/java/com/score/vact/di/scope/AppointmentScope.kt
1290273480
package com.score.vact.di.scope import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class MainScope
vact/app/src/main/java/com/score/vact/di/scope/MainScope.kt
3969859809
package com.score.vact.di.appointment_list import androidx.lifecycle.ViewModel import com.score.vact.di.ViewModelKey import com.score.vact.ui.appointment_list.AppointmentsViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class AppointmentListViewModelModule { @Binds @IntoMap @ViewModelKey(AppointmentsViewModel::class) abstract fun bindAppointmentsModule(registrationViewModel: AppointmentsViewModel): ViewModel }
vact/app/src/main/java/com/score/vact/di/appointment_list/AppointmentListViewModelModule.kt
2312740058
package com.score.vact.di.appointment_list import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class AppointmentListScope
vact/app/src/main/java/com/score/vact/di/appointment_list/AppointmentListScope.kt
2630580173
package com.score.vact.di import com.score.vact.di.appointment_booking.AccompaniedPersonViewModelModule import com.score.vact.di.appointment_booking.AppointmentBookingScope import com.score.vact.di.appointment_booking.AppointmentBookingViewModelModule import com.score.vact.di.home.HomeScope import com.score.vact.di.home.HomeViewModelModule import com.score.vact.di.survey.SurveyScope import com.score.vact.di.survey.SurveyViewModelModule import com.score.vact.di.visitor_registration.VisitorRegistrationScope import com.score.vact.di.visitor_registration.VisitorRegistrationViewModelModule import com.score.vact.ui.appointment_booking.AccompaniedPersonFragment import com.score.vact.ui.survey.SurveyFragment import com.score.vact.ui.appointment_booking.AppointmentBookingFragment import com.score.vact.ui.home.HomeFragment import com.score.vact.ui.visitor_registration.VisitorRegistrationFragment import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class MainFragmentBuildersModule { @HomeScope @ContributesAndroidInjector(modules = [HomeViewModelModule::class]) abstract fun contributeHomeFragment(): HomeFragment @VisitorRegistrationScope @ContributesAndroidInjector(modules = [VisitorRegistrationViewModelModule::class]) abstract fun contributeVisitorRegistrationFragment(): VisitorRegistrationFragment @AppointmentBookingScope @ContributesAndroidInjector(modules = [AppointmentBookingViewModelModule::class]) abstract fun contributeAppointmentBookingFragment(): AppointmentBookingFragment @AppointmentBookingScope @ContributesAndroidInjector(modules = [AccompaniedPersonViewModelModule::class]) abstract fun contributeAccompaniedPersonFragment():AccompaniedPersonFragment @SurveyScope @ContributesAndroidInjector(modules = [SurveyViewModelModule::class]) abstract fun contributeSurveyFragment(): SurveyFragment }
vact/app/src/main/java/com/score/vact/di/MainFragmentBuildersModule.kt
1507134584
package com.score.vact.di import androidx.lifecycle.ViewModelProvider import com.score.vact.viewmodel.ViewModelProviderFactory import dagger.Binds import dagger.Module @Module abstract class ViewModelFactoryModule { /* @Binds public abstract ViewModelProvider.Factory bindViewModelFactory(ViewModelProviderFactory viewModelFactory); */ /*@Binds abstract fun bindViewModelFactory(factory: VACTViewModelFactory): ViewModelProvider.Factory*/ @Binds abstract fun bindViewModelFactory(factory: ViewModelProviderFactory): ViewModelProvider.Factory }
vact/app/src/main/java/com/score/vact/di/ViewModelFactoryModule.kt
3561489547
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.di /** * Marks an activity / fragment injectable. */ interface Injectable
vact/app/src/main/java/com/score/vact/di/Injectable.kt
1390317828
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.score.vact.di import android.app.Activity import android.app.Application import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.score.vact.VACTApp import dagger.android.AndroidInjection import dagger.android.support.AndroidSupportInjection import dagger.android.support.HasSupportFragmentInjector /** * Helper class to automatically inject fragments if they implement [Injectable]. */ object AppInjector { fun init(vactApp: VACTApp) { DaggerAppComponent.builder().application(vactApp) .build().inject(vactApp) vactApp .registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { handleActivity(activity) } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) { } override fun onActivityDestroyed(activity: Activity) { } }) } private fun handleActivity(activity: Activity) { if(activity is AppCompatActivity){ AndroidInjection.inject(activity) } if (activity is HasSupportFragmentInjector) { AndroidInjection.inject(activity) } if (activity is FragmentActivity) { activity.supportFragmentManager .registerFragmentLifecycleCallbacks( object : FragmentManager.FragmentLifecycleCallbacks() { override fun onFragmentCreated( fm: FragmentManager, f: Fragment, savedInstanceState: Bundle? ) { if (f is Injectable) { AndroidSupportInjection.inject(f) } } }, true ) } } }
vact/app/src/main/java/com/score/vact/di/AppInjector.kt
375167418
package com.score.vact.di import com.score.vact.di.login.LoginScope import com.score.vact.di.login.LoginViewModelModule import com.score.vact.di.scope.AppointmentScope import com.score.vact.di.scope.MainScope import com.score.vact.di.splash.SplashScope import com.score.vact.di.splash.SplashViewModelModule import com.score.vact.ui.AppointmentListActivity import com.score.vact.ui.login.LoginActivity import com.score.vact.ui.MainActivity import com.score.vact.ui.splash.SplashActivity import com.score.vact.ui.splash.SplashViewModel import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class ActivityBuildersModule { @SplashScope @ContributesAndroidInjector(modules = [SplashViewModelModule::class]) abstract fun contributeSplashActivity(): SplashActivity @LoginScope @ContributesAndroidInjector(modules = [LoginViewModelModule::class]) abstract fun contributeLoginActivity(): LoginActivity @MainScope @ContributesAndroidInjector(modules = [MainFragmentBuildersModule::class]) abstract fun contributeMainActivity(): MainActivity @AppointmentScope @ContributesAndroidInjector(modules = [AppointmentFragmentBuilderModule::class]) abstract fun contributeAppointmentListActivity():AppointmentListActivity }
vact/app/src/main/java/com/score/vact/di/ActivityBuildersModule.kt
4191564932
package com.score.vact.di.appointment_details import java.lang.annotation.RetentionPolicy import javax.inject.Scope @Scope @MustBeDocumented @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) annotation class AppointmentDetailsScope
vact/app/src/main/java/com/score/vact/di/appointment_details/AppointmentDetailsScope.kt
1709800116