content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package hr.jedvaj.demo.obms.repository import hr.jedvaj.demo.obms.model.entity.Book import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface BookRepository: JpaRepository<Book, Long> { }
obms/src/main/kotlin/hr/jedvaj/demo/obms/repository/BookRepository.kt
3340833830
package hr.jedvaj.demo.obms.repository import hr.jedvaj.demo.obms.model.entity.Authority import hr.jedvaj.demo.obms.model.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface AuthorityRepository: JpaRepository<Authority, Long> { }
obms/src/main/kotlin/hr/jedvaj/demo/obms/repository/AuthorityRepository.kt
1049154728
package hr.jedvaj.demo.obms.repository import hr.jedvaj.demo.obms.model.entity.User import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository @Repository interface UserRepository: JpaRepository<User, Long> { fun findByUsername(username: String): User }
obms/src/main/kotlin/hr/jedvaj/demo/obms/repository/UserRepository.kt
4049617021
package hr.jedvaj.demo.obms.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.domain.AuditorAware import org.springframework.data.jpa.repository.config.EnableJpaAuditing import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.User import java.util.* @Configuration @EnableJpaAuditing(auditorAwareRef = "auditorProvider") class JpaAuditConfig { @Bean fun auditorProvider(): AuditorAware<String> { return AuditorAware { Optional.ofNullable(SecurityContextHolder.getContext()) .map { obj -> obj.authentication } .filter { obj -> obj.isAuthenticated } .map { obj -> obj.principal } .map { obj -> User::class.java.cast(obj) } .map { obj -> obj.username } } } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/config/JpaAuditConfig.kt
4078154493
package hr.jedvaj.demo.obms.config enum class SecurityRoles { ROLE_ADMIN, ROLE_USER }
obms/src/main/kotlin/hr/jedvaj/demo/obms/config/SecurityRoles.kt
3606398191
package hr.jedvaj.demo.obms.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.Customizer import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.builders.WebSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.provisioning.JdbcUserDetailsManager import org.springframework.security.provisioning.UserDetailsManager import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.util.matcher.AntPathRequestMatcher import javax.sql.DataSource @Configuration @EnableWebSecurity @EnableMethodSecurity class SecurityConfig { @Bean fun passwordEncoder(): PasswordEncoder { val encoder: PasswordEncoder = BCryptPasswordEncoder() return encoder } @Bean fun usersManager(dataSource: DataSource): UserDetailsManager { return JdbcUserDetailsManager(dataSource) } @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { return http .authorizeHttpRequests { auth -> auth.anyRequest().authenticated() } .sessionManagement { s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } .httpBasic(Customizer.withDefaults()) .csrf { it.disable() } .build() } @Bean fun webSecurityCustomizer(): WebSecurityCustomizer { return WebSecurityCustomizer { web: WebSecurity -> web.ignoring() .requestMatchers(AntPathRequestMatcher("/h2-console/**")) } } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/config/SecurityConfig.kt
2577962999
package hr.jedvaj.demo.obms.controller import hr.jedvaj.demo.obms.model.request.UserCreateRequest import hr.jedvaj.demo.obms.model.request.UserUpdateRequest import hr.jedvaj.demo.obms.model.response.UserResponse import hr.jedvaj.demo.obms.service.UserService import io.github.oshai.kotlinlogging.KotlinLogging import jakarta.validation.Valid import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PostAuthorize import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* import java.net.URI @RestController @RequestMapping("/api/users") @PreAuthorize("hasAuthority('ROLE_ADMIN')") class UserController(val userService: UserService) { val logger = KotlinLogging.logger {} @GetMapping fun getAll(): ResponseEntity<List<UserResponse>> { logger.debug { "Received call to ${UserController::class.simpleName}.getAll()" } val users = userService.getAll() return ResponseEntity.ok().body(users) } @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @PostMapping fun create(@Valid @RequestBody user: UserCreateRequest): ResponseEntity<Void> { logger.debug { "Received call to ${UserController::class.simpleName}.create()" } val userResponse = userService.create(user) return ResponseEntity.created(URI.create("/api/users/${userResponse?.id}")).build() } @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @GetMapping("/{id}") fun getOne(@PathVariable id: Long): ResponseEntity<UserResponse> { logger.debug { "Received call to ${UserController::class.simpleName}.getOne() with path param $id" } val user = userService.getOne(id) user ?: return ResponseEntity.notFound().build() return ResponseEntity.ok().body(user) } @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @PutMapping("/{id}") fun update(@PathVariable id: Long, @Valid @RequestBody userRequest: UserUpdateRequest): ResponseEntity<Void> { logger.debug { "Received call to ${UserController::class.simpleName}.update() with path param: $id" } val user = userService.update(id, userRequest) user ?: return ResponseEntity.notFound().build() return ResponseEntity.ok().build() } @DeleteMapping("/{id}") fun delete(@PathVariable id: Long): ResponseEntity<Void> { logger.debug { "Received call to ${UserController::class.simpleName}.delete() with path param: $id" } val success = userService.delete(id) return if(success) { ResponseEntity.ok().build() } else { ResponseEntity.notFound().build() } } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/controller/UserController.kt
2690159833
package hr.jedvaj.demo.obms.controller import hr.jedvaj.demo.obms.model.request.BookRequest import hr.jedvaj.demo.obms.model.response.BookResponse import hr.jedvaj.demo.obms.service.BookService import io.github.oshai.kotlinlogging.KotlinLogging import jakarta.validation.Valid import org.springframework.http.ResponseEntity import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.* import java.net.URI @RestController @RequestMapping("/api/books") @PreAuthorize("hasAuthority('ROLE_ADMIN')") class BookController(val bookService: BookService) { val logger = KotlinLogging.logger {} @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @GetMapping fun getAll(): ResponseEntity<List<BookResponse>> { logger.debug { "Received call to ${BookController::class.simpleName}.getAll()" } val books = bookService.getAll() return ResponseEntity.ok().body(books) } @PostMapping fun create(@Valid @RequestBody book: BookRequest): ResponseEntity<Void> { logger.debug { "Received call to ${BookController::class.simpleName}.create() with input object: $book" } val bookResponse = bookService.create(book) return ResponseEntity.created(URI.create("/api/books/${bookResponse?.id}")).build() } @PreAuthorize("hasAnyAuthority('ROLE_ADMIN','ROLE_USER')") @GetMapping("/{id}") fun getOne(@PathVariable id: Long): ResponseEntity<BookResponse> { logger.debug { "Received call to ${BookController::class.simpleName}.getOne() with path param: $id" } val book = bookService.getOne(id) book ?: return ResponseEntity.notFound().build() return ResponseEntity.ok().body(book) } @PutMapping("/{id}") fun update(@PathVariable id: Long, @Valid @RequestBody bookRequest: BookRequest): ResponseEntity<Void> { logger.debug { "Received call to ${BookController::class.simpleName}.update() with path param: $id and input object $bookRequest" } val book = bookService.update(id, bookRequest) book ?: return ResponseEntity.notFound().build() return ResponseEntity.ok().build() } @DeleteMapping("/{id}") fun delete(@PathVariable id: Long): ResponseEntity<Void> { logger.debug { "Received call to ${BookController::class.simpleName}.delete() with path param: $id" } val success = bookService.delete(id) return if (success) { ResponseEntity.ok().build() } else { ResponseEntity.notFound().build() } } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/controller/BookController.kt
451448832
package hr.jedvaj.demo.obms.model.response import java.math.BigDecimal data class BookResponse( val id: Long, val title: String, val author: String, val genre: String?, val price: BigDecimal?, val availability: Boolean )
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/response/BookResponse.kt
819032333
package hr.jedvaj.demo.obms.model.response data class UserResponse (val id: Long, val username: String, val enabled: Boolean) { }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/response/UserResponse.kt
4242594731
package hr.jedvaj.demo.obms.model.entity import jakarta.persistence.* @Entity @Table(name = "authorities") data class Authority( @Column(nullable = false) val username: String, @Column(nullable = false) var authority: String, ) { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/entity/Authority.kt
477225199
package hr.jedvaj.demo.obms.model.entity import jakarta.persistence.* import org.springframework.data.annotation.CreatedBy import org.springframework.data.annotation.CreatedDate import org.springframework.data.annotation.LastModifiedBy import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.jpa.domain.support.AuditingEntityListener import java.math.BigDecimal import java.time.LocalDateTime @Entity @EntityListeners(AuditingEntityListener::class) @Table(name = "book_catalogue") data class Book( @Column(nullable = false) val title: String, @Column(nullable = false) val author: String, @Column val genre: String? = null, @Column val price: BigDecimal? = null, @Column(nullable = false) val availability: Boolean ) { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null @CreatedDate @Column(name = "created_at", nullable = false, updatable = false) var createdAt: LocalDateTime? = null @LastModifiedDate @Column(name = "modified_at", nullable = false) var modifiedAt: LocalDateTime? = null @CreatedBy @Column(name = "created_by", nullable = false, updatable = false) var createdBy: String? = null @LastModifiedBy @Column(name = "modified_by", nullable = false) var modifiedBy: String? = null }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/entity/Book.kt
846485696
package hr.jedvaj.demo.obms.model.entity import jakarta.persistence.* @Entity @Table(name = "users") data class User( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long?, @Column(nullable = false) val username: String, @Column(nullable = false) var password: String, @Column(nullable = false) var enabled: Boolean = true ) { constructor(username: String, password: String) : this(null, username, password, true) }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/entity/User.kt
2228638634
package hr.jedvaj.demo.obms.model.mapper import hr.jedvaj.demo.obms.model.entity.User import hr.jedvaj.demo.obms.model.response.UserResponse import org.mapstruct.Mapper @Mapper(componentModel = "spring") interface UserMapper { fun toDto(user: User?): UserResponse? fun toDtoList(userList: List<User>): List<UserResponse> }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/mapper/UserMapper.kt
2891398637
package hr.jedvaj.demo.obms.model.mapper import hr.jedvaj.demo.obms.model.entity.Book import hr.jedvaj.demo.obms.model.request.BookRequest import hr.jedvaj.demo.obms.model.response.BookResponse import org.mapstruct.BeanMapping import org.mapstruct.Mapper import org.mapstruct.MappingTarget import org.mapstruct.NullValuePropertyMappingStrategy @Mapper(componentModel = "spring") interface BookMapper { fun toDto(book: Book?): BookResponse? fun toDtoList(bookList: List<Book>): List<BookResponse> fun toEntity(book: BookRequest): Book }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/mapper/BookMapper.kt
1084336698
package hr.jedvaj.demo.obms.model.request import jakarta.validation.constraints.Pattern data class UserUpdateRequest( @field:Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{6}\$") var password: String?, var enabled: Boolean? ){ }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/request/UserUpdateRequest.kt
2123315681
package hr.jedvaj.demo.obms.model.request import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.NotNull import java.math.BigDecimal data class BookRequest( @field:NotBlank val title: String?, @field:NotBlank val author: String?, val genre: String?, val price: BigDecimal?, @field:NotNull val availability: Boolean? )
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/request/BookRequest.kt
4280761451
package hr.jedvaj.demo.obms.model.request import jakarta.validation.constraints.Pattern data class UserCreateRequest( @field:Pattern(regexp = "^[a-zA-Z]+\$") var username: String, @field:Pattern(regexp = "^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{6}\$") var password: String?) { }
obms/src/main/kotlin/hr/jedvaj/demo/obms/model/request/UserCreateRequest.kt
659551250
package hr.jedvaj.demo.obms.service import hr.jedvaj.demo.obms.model.mapper.BookMapper import hr.jedvaj.demo.obms.model.request.BookRequest import hr.jedvaj.demo.obms.model.response.BookResponse import hr.jedvaj.demo.obms.repository.BookRepository import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service @Service class BookService(val bookRepository: BookRepository, val bookMapper: BookMapper) { val logger = KotlinLogging.logger {} fun getAll(): List<BookResponse> { logger.debug { "Received call to ${BookService::class.simpleName}.getAll()" } val books = bookRepository.findAll() return bookMapper.toDtoList(books) } fun getOne(id: Long): BookResponse? { logger.debug { "Received call to ${BookService::class.simpleName}.getOne() with param id: $id" } val book = bookRepository.findByIdOrNull(id) ?: return null return bookMapper.toDto(book) } fun create(bookReq: BookRequest): BookResponse? { logger.debug { "Received call to ${BookService::class.simpleName}.create() with param bookReq: $bookReq" } val book = bookMapper.toEntity(bookReq) val entity = bookRepository.save(book) return bookMapper.toDto(entity) } fun update(id: Long, bookReq: BookRequest): BookResponse? { logger.debug { "Received call to ${BookService::class.simpleName}.update() with params id: $id , bookReq: $bookReq" } val entity = bookRepository.findByIdOrNull(id) ?: return null val updatedEntity = bookMapper.toEntity(bookReq) updatedEntity.id = entity.id val result = bookRepository.save(updatedEntity) return bookMapper.toDto(result) } fun delete(id: Long): Boolean { logger.debug { "Received call to ${BookService::class.simpleName}.delete() with param id: $id" } val exists = bookRepository.existsById(id) if(!exists) { return false } bookRepository.deleteById(id) return true } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/service/BookService.kt
3372237486
package hr.jedvaj.demo.obms.service import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import java.util.concurrent.CompletableFuture @Service class EmailService { val logger = KotlinLogging.logger {} @Async fun sendEmail(username: String): CompletableFuture<Boolean> { logger.info { "This is me pretending to send email for @Async example" } return CompletableFuture.completedFuture(true) } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/service/EmailService.kt
1496930925
package hr.jedvaj.demo.obms.service import hr.jedvaj.demo.obms.config.SecurityRoles import hr.jedvaj.demo.obms.model.entity.Authority import hr.jedvaj.demo.obms.repository.AuthorityRepository import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Service import java.util.concurrent.CompletableFuture @Service class AuthorityService(val authorityRepository: AuthorityRepository) { val logger = KotlinLogging.logger {} fun createForUser(username: String): Authority { logger.debug { "Received call to ${AuthorityService::class.simpleName} with param username: $username" } val authority = Authority(username, SecurityRoles.ROLE_USER.name) val entity = authorityRepository.save(authority) return entity } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/service/AuthorityService.kt
1017233673
package hr.jedvaj.demo.obms.service import hr.jedvaj.demo.obms.model.entity.User import hr.jedvaj.demo.obms.model.mapper.UserMapper import hr.jedvaj.demo.obms.model.request.UserCreateRequest import hr.jedvaj.demo.obms.model.request.UserUpdateRequest import hr.jedvaj.demo.obms.model.response.UserResponse import hr.jedvaj.demo.obms.repository.UserRepository import io.github.oshai.kotlinlogging.KotlinLogging import org.springframework.data.repository.findByIdOrNull import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.provisioning.UserDetailsManager import org.springframework.stereotype.Service @Service class UserService( val userRepository: UserRepository, val userMapper: UserMapper, val userDetailsManager: UserDetailsManager, val passwordEncoder: PasswordEncoder, val authorityService: AuthorityService, val emailService: EmailService ) { val logger = KotlinLogging.logger {} fun getAll(): List<UserResponse> { logger.debug { "Received call to ${UserService::class.simpleName}.getAll()" } val users = userRepository.findAll() return userMapper.toDtoList(users) } fun getOne(id: Long): UserResponse? { logger.debug { "Received call to ${UserService::class.simpleName}.getOne() with path param $id" } val user = userRepository.findByIdOrNull(id) ?: return null return userMapper.toDto(user) } fun create(userCreateRequest: UserCreateRequest): UserResponse? { logger.debug { "Received call to ${UserService::class.simpleName}.create()" } val password = passwordEncoder.encode(userCreateRequest.password?.trim()) val user = User(userCreateRequest.username, password) val entity = userRepository.save(user) authorityService.createForUser(user.username) val future = emailService.sendEmail(entity.username) future.thenAccept { logger.info { "For demo purpose example of processing async result" } } logger.info { "User creation done" } return userMapper.toDto(entity) } fun update(id: Long, userReq: UserUpdateRequest): UserResponse? { logger.debug { "Received call to ${UserService::class.simpleName}.update() with path param: $id" } val user = userRepository.findByIdOrNull(id) ?: return null userReq.password?.let { user.password = passwordEncoder.encode(userReq.password?.trim()) } userReq.enabled?.let { user.enabled = userReq.enabled!! } val result = userRepository.save(user) return userMapper.toDto(result) } fun delete(id: Long): Boolean { logger.debug { "Received call to ${UserService::class.simpleName}.delete() with path param: $id" } val user = userRepository.findByIdOrNull(id) ?: return false userDetailsManager.deleteUser(user.username) return true } }
obms/src/main/kotlin/hr/jedvaj/demo/obms/service/UserService.kt
2129286422
package hr.jedvaj.demo.obms import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.scheduling.annotation.EnableAsync @EnableAsync @SpringBootApplication class OnlineBookstoreManagementSystemApplication fun main(args: Array<String>) { runApplication<OnlineBookstoreManagementSystemApplication>(*args) }
obms/src/main/kotlin/hr/jedvaj/demo/obms/OnlineBookstoreManagementSystemApplication.kt
952735597
package com.rcrud import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "rcrud" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
NativeApp/rcrud/android/app/src/main/java/com/rcrud/MainActivity.kt
1419586506
package com.rcrud import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.flipper.ReactNativeFlipper import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List<ReactPackage> = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(this.applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, false) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager) } }
NativeApp/rcrud/android/app/src/main/java/com/rcrud/MainApplication.kt
1579721619
package com.example.terms import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.terms", appContext.packageName) } }
compumovil/app/src/androidTest/java/com/example/terms/ExampleInstrumentedTest.kt
3812419470
package com.example.terms 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) } }
compumovil/app/src/test/java/com/example/terms/ExampleUnitTest.kt
1536978505
package com.example.terms.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
compumovil/app/src/main/java/com/example/terms/ui/theme/Color.kt
2784481566
package com.example.terms.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun TermsTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
compumovil/app/src/main/java/com/example/terms/ui/theme/Theme.kt
735495357
package com.example.terms.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
compumovil/app/src/main/java/com/example/terms/ui/theme/Type.kt
2401187093
package com.example.terms import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.terms.ui.theme.TermsTheme import androidx.appcompat.app.AppCompatActivity class TermsAndConditionsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_terms_and_conditions) val textViewTerms: TextView = findViewById<TextView>(R.id.textViewTerms) textViewTerms.text = getString(R.string.terms_and_conditions) val acceptButton: Button = findViewById<Button>(R.id.acceptButton) val rejectButton: Button = findViewById<Button>(R.id.rejectButton) acceptButton.setOnClickListener { val intent = Intent(this, RegistrationActivity::class.java) startActivity(intent) } rejectButton.setOnClickListener { // Aquí iría el código que quieres ejecutar cuando el usuario rechace los términos } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { TermsTheme { Greeting("Android") } }
compumovil/app/src/main/java/com/example/terms/TermsAndConditionsActivity.kt
3087961878
package com.example.terms import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class AdditionalInfoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_additional_info) val buttonNext: Button = findViewById<Button>(R.id.buttonNext) buttonNext.setOnClickListener { val intent = Intent(this, FinancialInfoActivity::class.java) startActivity(intent) } } }
compumovil/app/src/main/java/com/example/terms/AdditionalInfoActivity.kt
3273681498
package com.example.terms import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.google.android.gms.common.SignInButton class GoogleSignInActivity : AppCompatActivity() { @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_google_sign_in) val signInButton = findViewById<SignInButton>(R.id.sign_in_button) signInButton.setSize(SignInButton.SIZE_WIDE) signInButton.setOnClickListener { val intent = Intent(this, AdditionalInfoActivity::class.java) startActivity(intent) } } }
compumovil/app/src/main/java/com/example/terms/GoogleSignInActivity.kt
299757508
package com.example.terms import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class FinancialInfoActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_financial_info) val buttonFinalize: Button = findViewById<Button>(R.id.buttonFinalize) buttonFinalize.setOnClickListener { val intent = Intent(this, Sign_inActivity::class.java) startActivity(intent) } } }
compumovil/app/src/main/java/com/example/terms/FinancialInfoActivity.kt
989807964
package com.example.terms import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Sign_inActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_in) } }
compumovil/app/src/main/java/com/example/terms/Sign_inActivity.kt
1351602407
package com.example.terms import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import org.w3c.dom.Text class RegistrationActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registration) // Encuentra el botón por su ID val buttonRegister: Button = findViewById<Button>(R.id.buttonRegister) // Establece un OnClickListener en el botón buttonRegister.setOnClickListener { // Crea un Intent para iniciar AdditionalInfoActivity val intent = Intent(this, AdditionalInfoActivity::class.java) startActivity(intent) } val textViewRegisterWithGoogle: TextView = findViewById(R.id.textViewRegisterWithGoogle) // Establece un OnClickListener en el TextView textViewRegisterWithGoogle.setOnClickListener { // Crea un Intent para iniciar GoogleSignInActivity val intent = Intent(this, GoogleSignInActivity::class.java) startActivity(intent) } } }
compumovil/app/src/main/java/com/example/terms/RegistrationActivity.kt
2818461534
package com.example.lisbonplaces import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.lisbonplaces", appContext.packageName) } }
dam-lab-2/client/app/src/androidTest/java/com/example/lisbonplaces/ExampleInstrumentedTest.kt
3997819846
package com.example.lisbonplaces 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) } }
dam-lab-2/client/app/src/test/java/com/example/lisbonplaces/ExampleUnitTest.kt
4167294257
package com.example.lisbonplaces import android.os.Bundle import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.bumptech.glide.Glide import org.json.JSONException class DetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail) val id = intent.getIntExtra("id", 1) getDetail(id) } private fun getDetail(id: Int) { val url = resources.getString(R.string.url) + id + "/" val queue = Volley.newRequestQueue(this) val jsonObjectRequest = JsonArrayRequest( Request.Method.GET, url, null, { response -> try { val jresponse = response.getJSONObject(0) val name = jresponse.getString("name") val address = jresponse.getString("address") val description = jresponse.getString("description") val image = jresponse.getString("image") val latitude = jresponse.getDouble("latitude") val longitude = jresponse.getDouble("longitude") val coordinates = "$latitude, $longitude" val name_tv = findViewById<TextView>(R.id.name_tv) name_tv.text = name val address_tv = findViewById<TextView>(R.id.address_tv) address_tv.text = address val description_tv = findViewById<TextView>(R.id.description_tv) description_tv.text = description val coordinates_tv = findViewById<TextView>(R.id.coordinates_tv) coordinates_tv.text = coordinates val image_iv = findViewById<ImageView>(R.id.image_iv) Glide.with(this@DetailActivity) .load(image) .into(image_iv) msg(response.toString()) } catch (je: JSONException) { // } }, { msg("That didn't work!") }) queue.add(jsonObjectRequest) } override fun onSupportNavigateUp(): Boolean { finish() return true } private fun msg(txt: String) { Toast.makeText(this, txt, Toast.LENGTH_LONG).show() } }
dam-lab-2/client/app/src/main/java/com/example/lisbonplaces/DetailActivity.kt
2628151749
package com.example.lisbonplaces import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Button import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // add on click listener to open map activity val btn = findViewById<View>(R.id.openMapButton) as Button btn.setOnClickListener { startActivity( Intent( this@MainActivity, MapsActivity::class.java ) ) } } }
dam-lab-2/client/app/src/main/java/com/example/lisbonplaces/MainActivity.kt
152192890
package com.example.lisbonplaces import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import com.android.volley.Request import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.Volley import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.example.lisbonplaces.databinding.ActivityMapsBinding import org.json.JSONException class MapsActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var binding: ActivityMapsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMapsBinding.inflate(layoutInflater) setContentView(binding.root) // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val point = LatLng(38.73240225798916, -9.160349629389367) // mMap.addMarker(MarkerOptions().position(point).title("NovaIms")) mMap.moveCamera(CameraUpdateFactory.newLatLng(point)) getPlaces() mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 11f)) mMap.setOnInfoWindowClickListener { marker -> val i = Intent(this@MapsActivity, DetailActivity::class.java) val id = marker.tag as Int i.putExtra("id", id) startActivity(i) } } private fun getPlaces() { val url = resources.getString(R.string.url) val queue = Volley.newRequestQueue(this) val jsonObjectRequest = JsonArrayRequest( Request.Method.GET, url, null, { response -> try { for (i in 0 until response.length()) { val jresponse = response.getJSONObject(i) val id = jresponse.getInt("id") val name = jresponse.getString("name") val address = jresponse.getString("address") val latitude = jresponse.getDouble("latitude") val longitude = jresponse.getDouble("longitude") val marker = mMap.addMarker( MarkerOptions() .position(LatLng(latitude, longitude)) .title(name) .snippet(address) ) marker?.tag = id } msg(response.toString()) } catch (je: JSONException) { // } }, { error -> // TODO: Handle error msg("That didn't work! \n$error") } ) queue.add(jsonObjectRequest) } private fun msg(txt: String) { Toast.makeText(this, txt, Toast.LENGTH_LONG).show() } }
dam-lab-2/client/app/src/main/java/com/example/lisbonplaces/MapsActivity.kt
1696862258
package com.appdev.posheesh 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.appdev.posheesh", appContext.packageName) } }
POSheesh/app/src/androidTest/java/com/appdev/posheesh/ExampleInstrumentedTest.kt
3728220325
package com.appdev.posheesh 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) } }
POSheesh/app/src/test/java/com/appdev/posheesh/ExampleUnitTest.kt
1286174940
package com.appdev.posheesh.ui.sales import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.content.Intent import android.database.Cursor import android.net.Uri import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.view.LayoutInflater import android.view.View import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.Toast import androidx.core.content.FileProvider import androidx.fragment.app.DialogFragment import com.appdev.posheesh.BarcodeScan import com.appdev.posheesh.Classes.Products import com.appdev.posheesh.DatabaseHandler import com.appdev.posheesh.R import java.io.File import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.Date import java.util.Locale class AddItemFragment : DialogFragment() { interface OnItemAddedListener { fun onItemAdded() } private var listener: OnItemAddedListener? = null private lateinit var barcodeEditText: EditText private lateinit var dbHelper: DatabaseHandler private var selectedImageUri: String? = null // URI to store the selected image private var capturedPhotoUri: Uri? = null // URI to store the captured image private var currentPhotoPath: String? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(requireContext()) val inflater = LayoutInflater.from(requireContext()) val view: View = inflater.inflate(R.layout.dialog_additem, null) // Initialize database helper dbHelper = DatabaseHandler(requireContext()) val itemNameEditText: EditText = view.findViewById(R.id.editTextItemName) val descriptionEditText: EditText = view.findViewById(R.id.editTextDescription) val sellingPriceEditText: EditText = view.findViewById(R.id.editTextSellingPrice) val addItemButton: Button = view.findViewById(R.id.buttonAddItem) barcodeEditText = view.findViewById(R.id.editTextBarcode) val uploadImageButton: Button = view.findViewById(R.id.buttonFilePicker) val captureImageButton: Button = view.findViewById(R.id.buttonCameraPicker) val scannerIcon: ImageView = view.findViewById(R.id.imageViewScannerIcon) // Add item to database when the "Add Item" button is clicked addItemButton.setOnClickListener { val itemName = itemNameEditText.text.toString().trim() val description = descriptionEditText.text.toString().trim() val sellingPrice = sellingPriceEditText.text.toString().toDoubleOrNull() val barcode = barcodeEditText.text.toString().trim() if (itemName.isNotEmpty() && sellingPrice != null && barcode.isNotEmpty()) { val product = selectedImageUri?.let { it1 -> Products( name = itemName, description = description, categoryId = 1, // You need to replace this with the actual category ID sellingPrice = sellingPrice, imageUri = it1, code = barcode ) } // Send the Product object to the Database Handler for insertion if (product != null) { dbHelper.addProduct(product) listener?.onItemAdded() // Notify the listener } dismiss() // Close the dialog after adding the item } else { Toast.makeText(requireContext(), "Please check inputs", Toast.LENGTH_SHORT).show() } } // Handle image upload button click uploadImageButton.setOnClickListener { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE) } captureImageButton.setOnClickListener { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val photoFile: File? = try { createImageFile() // You need to implement createImageFile() method to create a file to store the image } catch (ex: IOException) { null } photoFile?.also { val photoURI: Uri = FileProvider.getUriForFile( requireContext(), "com.appdev.posheesh.fileprovider", it ) capturedPhotoUri = photoURI // Save the URI to the member variable intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI) } startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE) } scannerIcon.setOnClickListener { val intent = Intent(requireContext(), BarcodeScan::class.java) startActivityForResult(intent, QRCODESCANNED_REQUEST_CODE) } builder.setView(view) return builder.create() } fun setOnItemAddedListener(listener: OnItemAddedListener) { this.listener = listener } @Throws(IOException::class) private fun createImageFile(): File { // Create an image file name val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date()) val storageDir: File? = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( "JPEG_${timeStamp}_", /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ).apply { // Save a file: path for use with ACTION_VIEW intents currentPhotoPath = absolutePath } } private fun copyImageToInternalStorage(originalImageUri: Uri): Uri? { val inputStream = context?.contentResolver?.openInputStream(originalImageUri) val fileName = "copied_image_${System.currentTimeMillis()}.jpg" val outputFile = context?.filesDir?.let { File(it, fileName) } val outputStream = FileOutputStream(outputFile) inputStream?.use { input -> outputStream.use { output -> input.copyTo(output) } } return Uri.fromFile(outputFile) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) { val originalImageUri: Uri? = data.data val copiedImageUri: Uri? = originalImageUri?.let { copyImageToInternalStorage(it) } selectedImageUri = copiedImageUri?.let { getFilePathFromUri(it) } } else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { // Check if the captured image URI is not null if(capturedPhotoUri != null) { // Save the captured image to internal storage val filePath = copyImageToInternalStorage(capturedPhotoUri!!) // Update selectedImageUri with the file path selectedImageUri = getFilePathFromUri(filePath!!) } } else if (requestCode == QRCODESCANNED_REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) { val scannedValue = data?.getStringExtra("scannedValue") // Check if the scannedValue is not null and barcodeEditText is initialized if (scannedValue != null && barcodeEditText != null) { // Set the scanned value to the barcodeEditText barcodeEditText.setText(scannedValue) } else { // Handle case where scanned value is null or barcodeEditText is not initialized Toast.makeText(requireContext(), "Failed to get scanned value", Toast.LENGTH_SHORT).show() } } } fun getFilePathFromUri(uri: Uri): String? { var filePath: String? = null val context = context // Replace applicationContext with your actual context reference // Using ContentResolver to query MediaStore for file path val cursor: Cursor? = context?.contentResolver?.query(uri, null, null, null, null) cursor?.use { if (it.moveToFirst()) { val columnIndex: Int = it.getColumnIndex(MediaStore.Images.ImageColumns.DATA) filePath = it.getString(columnIndex) } } cursor?.close() // If file path is still null, try using FileProvider if (filePath == null) { filePath = uri.path // Fallback to URI path if cursor is null } return filePath } companion object { // Define request codes for image selection and capture private const val PICK_IMAGE_REQUEST_CODE = 1 private const val CAPTURE_IMAGE_REQUEST_CODE = 2 private const val QRCODESCANNED_REQUEST_CODE = 3 } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/AddItemFragment.kt
2683079362
import android.content.Context import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AlphaAnimation import android.view.animation.Animation import android.view.animation.AnimationSet import android.view.animation.ScaleAnimation import android.view.animation.TranslateAnimation import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.appdev.posheesh.Classes.Products import com.appdev.posheesh.R import com.appdev.posheesh.ui.sales.SalesFragment import com.squareup.picasso.Picasso import java.io.File class ItemListAdapter(private val context: Context, private val items: Array<Products>, private val itemClickListener: ItemClickListener) : RecyclerView.Adapter<ItemListAdapter.ViewHolder>() { interface ItemClickListener { fun onItemClick(item: Products) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currentItem = items[position] // Set item data to views holder.bind(currentItem) holder.itemView.setOnClickListener { highlightContainer(holder.itemView, holder, currentItem) } } private fun highlightContainer(view: View, holder: ViewHolder, currentItem: Products) { val highlightScale = 1.1f // Increase the scale slightly for highlighting effect // Highlighting animation val scaleAnimation = ScaleAnimation(1.0f, highlightScale, 1.0f, highlightScale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) scaleAnimation.duration = 200 // Adjust duration as needed // Set up animation set val animationSet = AnimationSet(true) animationSet.addAnimation(scaleAnimation) animationSet.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { // You can add any action needed when animation starts Toast.makeText(context, currentItem.name+" added to cart", Toast.LENGTH_SHORT).show() val borderColor = Color.parseColor("#DAA06D") val backgroundColor = Color.parseColor("#E1C16E") // Create a GradientDrawable for the background val backgroundDrawable = GradientDrawable() backgroundDrawable.shape = GradientDrawable.RECTANGLE backgroundDrawable.cornerRadius = 50f // Adjust the corner radius as needed backgroundDrawable.setColor(backgroundColor) // Set the border color and width backgroundDrawable.setStroke(2, borderColor) // Adjust the width as needed // Set the background drawable to the view view.background = backgroundDrawable SalesFragment.addToCart(currentItem.code, 1) } override fun onAnimationEnd(animation: Animation) { // Perform any action needed after the animation ends } override fun onAnimationRepeat(animation: Animation) {} }) // Start the animation on the provided view view.startAnimation(animationSet) // If you want to trigger any other action when the container is clicked, add it here } override fun getItemCount(): Int { return items.size } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { init { itemView.setOnClickListener(this) } private val imageItemImageView: ImageView = itemView.findViewById(R.id.imageItem) private val itemNameTextView: TextView = itemView.findViewById(R.id.textItemName) private val itemPriceTextView: TextView = itemView.findViewById(R.id.textPrice) override fun onClick(v: View?) { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { val item = items[position] itemClickListener.onItemClick(item) } } fun bind(item: Products) { // Bind item data to views Picasso.get().load(File(item.imageUri)).into(imageItemImageView) itemNameTextView.text = item.name itemPriceTextView.text = "Price: ${item.sellingPrice}" // You can set other item details here if needed } } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/ItemListAdapter.kt
2251554612
import android.content.Context import android.os.Bundle import android.os.CancellationSignal import android.os.ParcelFileDescriptor import android.print.PageRange import android.print.PrintAttributes import android.print.PrintDocumentAdapter import android.print.PrintDocumentInfo import android.print.PrintManager import androidx.appcompat.app.AppCompatActivity import com.appdev.posheesh.R import com.itextpdf.kernel.pdf.PdfWriter import com.itextpdf.layout.Document import com.itextpdf.layout.element.Table import org.apache.poi.ss.usermodel.CellType import org.apache.poi.ss.usermodel.WorkbookFactory import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException class PrintActivity : AppCompatActivity() { fun printExcelFile(context: Context, file: File) { try { val inputStream = FileInputStream(file) val workbook = WorkbookFactory.create(inputStream) // Create PDF document val output = FileOutputStream(context.cacheDir.absolutePath + "/excel_data.pdf") val writer = PdfWriter(output) val pdf = com.itextpdf.kernel.pdf.PdfDocument(writer) val document = Document(pdf) // Add data from Excel to a table in the PDF val table = Table(10) // Adjust the number of columns as per your Excel structure val sheet = workbook.getSheetAt(0) // Assuming you want to print the first sheet for (row in sheet) { for (cell in row) { val cellContent = when (cell.cellType) { CellType.STRING -> cell.stringCellValue CellType.NUMERIC -> cell.numericCellValue.toString() else -> "" } table.addCell(cellContent) } } document.add(table) document.close() // Print the PDF document val printManager = context.getSystemService(Context.PRINT_SERVICE) as PrintManager val jobName = context.getString(R.string.app_name) + " Document" printManager.print(jobName, object : PrintDocumentAdapter() { override fun onLayout( oldAttributes: PrintAttributes?, newAttributes: PrintAttributes?, cancellationSignal: CancellationSignal?, callback: LayoutResultCallback?, extras: Bundle? ) { val info = PrintDocumentInfo.Builder(jobName) .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .build() callback?.onLayoutFinished(info, true) } override fun onWrite( pages: Array<PageRange>, destination: ParcelFileDescriptor, cancellationSignal: CancellationSignal, callback: WriteResultCallback ) { val input = FileInputStream(context.cacheDir.absolutePath + "/excel_data.pdf") val output = FileOutputStream(destination.fileDescriptor) try { input.copyTo(output) callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES)) } catch (e: Exception) { callback.onWriteFailed(e.message) } finally { input.close() output.close() } } }, null) workbook.close() inputStream.close() } catch (e: IOException) { e.printStackTrace() } } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/PrintActivity.kt
1438484210
package com.appdev.posheesh.ui.sales import android.content.Context import android.net.Uri import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.appdev.posheesh.Classes.Products import com.appdev.posheesh.DatabaseHandler import com.appdev.posheesh.R import java.io.File class CartListAdapter( context: Context, private val cartItems: MutableList<Map<String, Any>>, private val totalPriceListener: TotalPriceListener ) : ArrayAdapter<Map<String, Any>>(context, R.layout.list_item_cart, cartItems) { interface TotalPriceListener { fun onTotalPriceChanged(totalPrice: Double) } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var itemView = convertView if (itemView == null) { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater itemView = inflater.inflate(R.layout.list_item_cart, parent, false) } // Get the current cart item val currentCartItem = cartItems[position].toMutableMap() // Set data to views val itemNameTextView = itemView!!.findViewById<TextView>(R.id.itemNameTextView) val quantityTextView = itemView.findViewById<TextView>(R.id.quantityTextView) val itemImageView = itemView.findViewById<ImageView>(R.id.itemImageView) // Set the item id and quantity itemNameTextView.text = getProductByCode(currentCartItem.get("code") as String).name quantityTextView.text = currentCartItem["quantity"].toString() currentCartItem["code"]?.let { getProductByCode(it as String).imageUri } ?.let { itemImageView.setImageURI(Uri.fromFile(File(it))) } // Calculate total price and notify the listener val totalPrice = calculateTotalPrice() totalPriceListener.onTotalPriceChanged(totalPrice) val minusButton = itemView.findViewById<ImageView>(R.id.minusButton) val plusButton = itemView.findViewById<ImageView>(R.id.plusButton) // Click listener for minus button minusButton.setOnClickListener { SalesFragment.removeToCart(currentCartItem["code"] as String) notifyDataSetChanged() // Update the ListView notifyTotalPriceChanged() // Notify the total price change } // Click listener for plus button plusButton.setOnClickListener { SalesFragment.addToCart(currentCartItem["code"] as String, 1) notifyDataSetChanged() // Update the ListView notifyTotalPriceChanged() // Notify the total price change } return itemView } private fun notifyTotalPriceChanged() { val totalPrice = calculateTotalPrice() totalPriceListener.onTotalPriceChanged(totalPrice) } private fun calculateTotalPrice(): Double { var totalPrice = 0.0 for (cartItem in cartItems) { val product = getProductByCode(cartItem["code"] as String) totalPrice += product.sellingPrice * cartItem["quantity"] as Int } return totalPrice } fun getProductByCode(itemCode: String): Products { // Initialize DatabaseHandler val dbHelper = DatabaseHandler(context) // Query the database to get the product by ID return dbHelper.getProductByCode(itemCode)!! } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/CartListAdapter.kt
4284469748
package com.appdev.posheesh.ui.sales import CartFragment import ItemDialogFragment import ItemListAdapter import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.os.Bundle import android.speech.RecognizerIntent import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.appdev.posheesh.BarcodeScan import com.appdev.posheesh.Classes.FragmentChangeListener import com.appdev.posheesh.Classes.Products import com.appdev.posheesh.DatabaseHandler import com.appdev.posheesh.R import com.appdev.posheesh.databinding.FragmentSalesBinding import com.google.android.material.floatingactionbutton.FloatingActionButton import java.util.Locale import java.util.Objects class SalesFragment : Fragment(), ItemListAdapter.ItemClickListener, AddItemFragment.OnItemAddedListener{ companion object { val cart: MutableList<Map<String, Any>> = mutableListOf() // Change to MutableList fun addToCart(itemCode: String, itemQuantity: Int) { // Check if the itemCode is already present in the cart val existingItem = cart.find { it["code"] == itemCode } if (existingItem != null) { // If the item is already in the cart, update its quantity by adding 1 val currentQuantity = existingItem["quantity"] as Int val updatedQuantity = currentQuantity + 1 val indexOfExistingItem = cart.indexOf(existingItem) cart[indexOfExistingItem] = mapOf("code" to itemCode, "quantity" to updatedQuantity) } else { // If the item is not in the cart, add it to the cart val newItem = mapOf("code" to itemCode, "quantity" to itemQuantity) cart.add(newItem) } } fun removeToCart(itemCode: String) { // Check if the itemCode is already present in the cart val existingItem = cart.find { it["code"] == itemCode } // If the item is already in the cart, update its quantity by subtracting 1 val currentQuantity = existingItem?.get("quantity") as Int val updatedQuantity = currentQuantity - 1 if(updatedQuantity == 0){ cart.remove(existingItem) }else { val indexOfExistingItem = cart.indexOf(existingItem) cart[indexOfExistingItem] = mapOf("code" to itemCode, "quantity" to updatedQuantity) } } } private var _binding: FragmentSalesBinding? = null private lateinit var recyclerView: RecyclerView private lateinit var etSearch: TextView private lateinit var dbHelper: DatabaseHandler lateinit var fabShowCart: FloatingActionButton private lateinit var fabAddItem: FloatingActionButton private lateinit var micImg: ImageView private val binding get() = _binding!! private var spinnerIndex: Int = 0 private var fragmentChangeListener: FragmentChangeListener? = null private val REQUEST_CODE_SPEECH_INPUT = 1 private val requestCodeBarcodeScan = 101 // define a request code override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSalesBinding.inflate(inflater, container, false) val view = binding.root dbHelper = DatabaseHandler(requireContext()) fabShowCart = view.findViewById(R.id.fabShowCart) fabShowCart.setOnClickListener { // Add your logic here to show the cart's contents // For example, you can navigate to the cart fragment showCart() } fabAddItem = view.findViewById(R.id.fabAddItem) fabAddItem.setOnClickListener { // Add your logic here to show the cart's contents // For example, you can navigate to the cart fragment addItem() } // Find the ListView recyclerView = view.findViewById(R.id.recyclerViewSalesItems) recyclerView.layoutManager = GridLayoutManager(requireContext(), 2) // Set up GridLayoutManager with 2 columns val scanBarcodeImg: ImageView = view.findViewById(R.id.cameraIcon) scanBarcodeImg.setOnClickListener { val intent = Intent(requireActivity(), BarcodeScan::class.java) startActivityForResult(intent, requestCodeBarcodeScan) } micImg = view.findViewById(R.id.microphoneIcon) micImg.setOnClickListener{ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM ) intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault() ) intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to text") try { startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT) } catch (e: Exception) { // on below line we are displaying error message in toast Toast .makeText( [email protected], " " + e.message, Toast.LENGTH_SHORT ) .show() } } // Display items based on the category ID displayItemsByCategoryId(0) etSearch = view.findViewById(R.id.etSearch) etSearch.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // Not needed } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // Filter the items list based on the search text displayItemsByNameSearch(s.toString(), spinnerIndex) } override fun afterTextChanged(s: Editable?) { // Not needed } }) return view } //All about Barcode Scanning// override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // in this method we are checking request // code with our result code. if (requestCode == REQUEST_CODE_SPEECH_INPUT) { // on below line we are checking if result code is ok if (resultCode == RESULT_OK && data != null) { // in that case we are extracting the // data from our array list val res: ArrayList<String> = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS) as ArrayList<String> // on below line we are setting data // to our output text view\ etSearch.setText( Objects.requireNonNull(res)[0] ) } } else if (requestCode == requestCodeBarcodeScan) { if (resultCode == RESULT_OK && data != null) { val scannedValue = data.getStringExtra("scannedValue") etSearch.setText( scannedValue?.let { dbHelper.getProductByCode(it)?.name } ?: "No product found" ) } } } //End Barcode Scanning Function// override fun onAttach(context: Context) { super.onAttach(context) if (context is FragmentChangeListener) { fragmentChangeListener = context } else { throw RuntimeException("$context must implement FragmentChangeListener") } } override fun onStart() { super.onStart() fragmentChangeListener?.onFragmentChanged("Sales") } override fun onStop() { super.onStop() // Clear fragmentChangeListener reference to avoid memory leaks fragmentChangeListener = null } private fun displayItemsByCategoryId(categoryId: Int) { val items = dbHelper.getProductsByCategoryId(categoryId).toTypedArray() // Create and set the custom adapter with item click listener val adapter = ItemListAdapter(requireContext(), items, this) recyclerView.adapter = adapter } private fun displayItemsByNameSearch(nameString :String, categoryId: Int) { val items = dbHelper.getProductsByNameSearch(nameString, categoryId).toTypedArray() // Create and set the custom adapter // Create and set the custom adapter with item click listener val adapter = ItemListAdapter(requireContext(), items, this) recyclerView.adapter = adapter } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dbHelper = DatabaseHandler(requireContext()) // Initialize the Spinner and setup filter options val spinner: Spinner = view.findViewById(R.id.spinnerFilter) val categories = dbHelper.getAllCategory().toTypedArray() val categoryList = mutableListOf<String>() categoryList.add("All Items") categories.forEach { item -> categoryList.add(item.name) } // Create an ArrayAdapter using the string array and a default spinner layout val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, categoryList) // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner spinner.adapter = adapter // Set an item selection listener for the spinner spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { // Handle item selection displayItemsByCategoryId(position) spinnerIndex = position } override fun onNothingSelected(parent: AdapterView<*>?) { // Do nothing } } } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun showItemDialog(item: Products) { val dialog = ItemDialogFragment.newInstance(item) dialog.show(parentFragmentManager, "ItemDialogFragment") } private fun showCart(){ val dialog = CartFragment(cart) dialog.show(parentFragmentManager, "CartFragment") } private fun addItem(){ val dialog = AddItemFragment() dialog.setOnItemAddedListener(this) dialog.show(childFragmentManager, "com.appdev.posheesh.ui.sales.AddItemFragment") } override fun onItemClick(item: Products) { showItemDialog(item) } override fun onItemAdded() { displayItemsByCategoryId(spinnerIndex) } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/SalesFragment.kt
1850202652
import android.app.Activity import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.ImageButton import android.widget.ImageView import android.widget.ListView import android.widget.TextView import android.widget.Toast import androidx.fragment.app.DialogFragment import com.appdev.posheesh.R import com.appdev.posheesh.ui.sales.CartListAdapter import java.io.FileNotFoundException import java.io.IOException class CartFragment(private val items: MutableList<Map<String, Any>>) : DialogFragment(), CartListAdapter.TotalPriceListener { private lateinit var totalPriceTextView: TextView private lateinit var contentDesc: String override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(requireContext()) val inflater = requireActivity().layoutInflater val view = inflater.inflate(R.layout.dialog_cart, null) // Find the ListView val listViewCartItems: ListView = view.findViewById(R.id.listViewCartItems) // Create and set the custom adapter with items from SalesFragment.cart val adapter = CartListAdapter(requireContext(), items, this) listViewCartItems.adapter = adapter // Set the view for the dialog builder.setView(view) // Add other configurations like title, buttons, etc. totalPriceTextView = view.findViewById(R.id.textViewTotalPrice) val btnPayWithCash: Button = view.findViewById(R.id.btn_paywithcash) btnPayWithCash.setOnClickListener { showPaymentDialogCash() } // Set click listener for the QR button val btnPayWithQR: Button = view.findViewById(R.id.btn_paywithqr) btnPayWithQR.setOnClickListener { showPaymentDialogQR() } return builder.create() } private fun showPaymentDialogCash() { val dialogView = layoutInflater.inflate(R.layout.dialog_paywithcash, null) val builder = AlertDialog.Builder(requireContext()) .setView(dialogView) .setTitle("Select Payment Method") val dialog = builder.create() // Find buttons in the dialog layout val btnPayWithCash = dialogView.findViewById<Button>(R.id.btnPayWithCash) // Set click listeners for the buttons btnPayWithCash.setOnClickListener { // Handle payment with Cash dialog.dismiss() // Add your logic here } dialog.show() } private fun showPaymentDialogQR() { val dialogView = layoutInflater.inflate(R.layout.dialog_paywithqr, null) val builder = AlertDialog.Builder(requireContext()) .setView(dialogView) .setTitle("Select Payment Method") val dialog = builder.create() // Find buttons in the dialog layout val btnPayWithGCash = dialogView.findViewById<Button>(R.id.btnPayWithGCash) val btnPayWithMaya = dialogView.findViewById<Button>(R.id.btnPayWithMaya) val btnSet = dialogView.findViewById<ImageButton>(R.id.btn_set) // Find the ImageView and buttons val imageViewQRCode: ImageView = dialogView.findViewById(R.id.imageViewQRCode) // Calculate the maxHeight for the ImageView // Set click listeners for the buttons btnPayWithGCash.setOnClickListener { contentDesc = "GCash" val displayMetrics = resources.displayMetrics val screenHeight = displayMetrics.heightPixels val buttonHeight = btnPayWithMaya.measuredHeight + btnPayWithGCash.measuredHeight + (8 * 2) // total button heights + margins val maxHeight = screenHeight - buttonHeight // Set the maxHeight for the ImageView imageViewQRCode.maxHeight = maxHeight imageViewQRCode.setImageBitmap(getbitmap("gcash_qr_image.jpg")) } btnPayWithMaya.setOnClickListener { contentDesc = "Maya" val displayMetrics = resources.displayMetrics val screenHeight = displayMetrics.heightPixels val buttonHeight = btnPayWithMaya.measuredHeight + btnPayWithGCash.measuredHeight + (8 * 2) // total button heights + margins val maxHeight = screenHeight - buttonHeight // Set the maxHeight for the ImageView imageViewQRCode.maxHeight = maxHeight imageViewQRCode.setImageBitmap(getbitmap("maya_qr_image.jpg")) } btnSet.setOnClickListener { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = "image/*" //contentDesc = imageViewQRCode.contentDescription.toString() startActivityForResult(intent, PICK_IMAGE_REQUEST) } dialog.show() } override fun onTotalPriceChanged(totalPrice: Double) { totalPriceTextView.text = "Total Price: $${String.format("%.2f", totalPrice)}" } private val PICK_IMAGE_REQUEST = 1 // Override onActivityResult to handle the result of the image picker private fun getbitmap(fileName: String): Bitmap? { try { val fileInputStream = requireContext().openFileInput(fileName) val bitmap = BitmapFactory.decodeStream(fileInputStream) fileInputStream.close() // Display the image using an ImageView or any other appropriate view return bitmap } catch (e: FileNotFoundException) { // Handle the case where the file is not found e.printStackTrace() Toast.makeText(requireContext(), "Image not found", Toast.LENGTH_SHORT).show() return null } catch (e: IOException) { // Handle other I/O exceptions e.printStackTrace() Toast.makeText(requireContext(), "Failed to open image", Toast.LENGTH_SHORT).show() return null } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { // Get the URI of the selected image val imageUri: Uri? = data?.data // Check the contentDescription of imageViewQRCode when (contentDesc) { "GCash" -> saveImageToInternalStorage(imageUri, "gcash_qr_image.jpg") "Maya" -> saveImageToInternalStorage(imageUri, "maya_qr_image.jpg") } } } // Function to save the image to internal storage private fun saveImageToInternalStorage(imageUri: Uri?, fileName: String) { imageUri?.let { try { val inputStream = requireContext().contentResolver.openInputStream(it) val outputStream = requireContext().openFileOutput(fileName, Context.MODE_PRIVATE) inputStream?.copyTo(outputStream) inputStream?.close() outputStream.close() // Notify the user that the image has been saved Toast.makeText(requireContext(), "Image saved successfully", Toast.LENGTH_SHORT).show() } catch (e: Exception) { e.printStackTrace() // Notify the user if there was an error saving the image Toast.makeText(requireContext(), "Failed to save image", Toast.LENGTH_SHORT).show() } } } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/CartFragment.kt
3842883314
package com.appdev.posheesh.ui.sales import android.content.Context import android.database.sqlite.SQLiteDatabase import org.apache.poi.ss.usermodel.Sheet import org.apache.poi.xssf.usermodel.XSSFWorkbook import java.io.File import java.io.FileOutputStream import java.io.IOException public class ExcelHandler { fun exportToExcel(context: Context, database: SQLiteDatabase): File { // Create a workbook val workbook = XSSFWorkbook() // Create a sheet val sheet: Sheet = workbook.createSheet("Data") // Query your SQLite database to get the data you want to export val cursor = database.rawQuery("SELECT * FROM products", null) var rowNum = 0 while (cursor.moveToNext()) { val row = sheet.createRow(rowNum++) val columnCount = cursor.columnCount for (i in 0 until columnCount) { val cell = row.createCell(i) cell.setCellValue(cursor.getString(i)) } } cursor.close() // Save the workbook to a file in internal storage val fileName = "data.xlsx" val file = File(context.filesDir, fileName) try { val outputStream = FileOutputStream(file) workbook.write(outputStream) outputStream.close() } catch (e: IOException) { e.printStackTrace() } return file } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/ExcelHandler.kt
3852729651
import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.widget.Button import android.widget.EditText import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.DialogFragment import com.appdev.posheesh.Classes.Products import com.appdev.posheesh.R class ItemDialogFragment : DialogFragment() { companion object { private const val ITEM_NAME_KEY = "itemName" private const val ITEM_DESCRIPTION_KEY = "itemDescription" private const val ITEM_SELLING_PRICE_KEY = "itemSellingPrice" private const val ITEM_ID_KEY = "0" fun newInstance(item: Products): ItemDialogFragment { val fragment = ItemDialogFragment() val args = Bundle() args.putString(ITEM_NAME_KEY, item.name) args.putString(ITEM_DESCRIPTION_KEY, item.description) args.putDouble(ITEM_SELLING_PRICE_KEY, item.sellingPrice) fragment.arguments = args return fragment } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val builder = AlertDialog.Builder(requireContext()) val inflater = requireActivity().layoutInflater val view = inflater.inflate(R.layout.dialog_item_options, null) // Find views val itemNameTextView: TextView = view.findViewById(R.id.itemNameTextView) val itemDescriptionTextView: TextView = view.findViewById(R.id.itemDescriptionTextView) val quantityEditText: EditText = view.findViewById(R.id.quantityEditText) val totalPriceTextView: TextView = view.findViewById(R.id.totalPriceTextView) val plusButton: ImageView = view.findViewById(R.id.plusButton) val minusButton: ImageView = view.findViewById(R.id.minusButton) val addToCartButton: Button = view.findViewById(R.id.addToCartButton) val cancelButton: Button = view.findViewById(R.id.cancelButton) // Retrieve item details from arguments val itemName = arguments?.getString(ITEM_NAME_KEY) val itemDescription = arguments?.getString(ITEM_DESCRIPTION_KEY) val itemSellingPrice = arguments?.getDouble(ITEM_SELLING_PRICE_KEY) // Set the item name and description itemNameTextView.text = itemName itemDescriptionTextView.text = itemDescription // Set initial total price totalPriceTextView.text = getString(R.string.total_price, itemSellingPrice) // Set click listeners for plus and minus buttons var quantity = 1 // Initial quantity plusButton.setOnClickListener { quantity++ quantityEditText.setText(quantity.toString()) } minusButton.setOnClickListener { if (quantity > 1) { quantity-- quantityEditText.setText(quantity.toString()) } } // Update total price when quantity changes quantityEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { // Not used } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { // Not used } override fun afterTextChanged(s: Editable?) { val quantityValue = s.toString().toIntOrNull() ?: 0 val totalPrice = quantityValue * (itemSellingPrice ?: 0.0) totalPriceTextView.text = getString(R.string.total_price, totalPrice) } }) // Set click listener for Add to Cart button addToCartButton.setOnClickListener { // Add your logic here to handle adding the item to the cart // You can access the quantity using quantityEditText.text.toString().toInt() // You can access other item details using itemName, itemDescription, and itemSellingPrice val itemId = arguments?.getInt(ITEM_ID_KEY) if (itemId != null) { // SalesFragment.addToCart(itemId, quantityEditText.text.toString().toInt()) // Show a modal popup indicating the item has been added to the cart val alertDialog = AlertDialog.Builder(requireContext()) .setTitle("Item Added to Cart") .setMessage("The item has been successfully added to your cart.") .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() // Dismiss the dialog when OK is clicked } .create() alertDialog.show() } dismiss() } // Set click listener for Cancel button cancelButton.setOnClickListener { // Add your logic here to handle canceling the operation // Dismiss the dialog when the cancel button is clicked dismiss() } // Set the view for the dialog builder.setView(view) // Add other configurations like title, buttons, etc. return builder.create() } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/sales/ItemDialogFragment.kt
4002137118
package com.appdev.posheesh.ui import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.appdev.posheesh.R // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [LogoutFragment.newInstance] factory method to * create an instance of this fragment. */ class LogoutFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_logout, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val intent = Intent(activity, LoginActivity::class.java) startActivity(intent) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LogoutFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = LogoutFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/LogoutFragment.kt
1634407383
package com.appdev.posheesh.ui.about import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.appdev.posheesh.databinding.FragmentAboutBinding class AboutFragment : Fragment() { private var _binding: FragmentAboutBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentAboutBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/about/AboutFragment.kt
1876889000
package com.appdev.posheesh.ui.dashboard import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.appdev.posheesh.databinding.FragmentDashboardBinding class DashboardFragment : Fragment() { private var _binding: FragmentDashboardBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDashboardBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/dashboard/DashboardFragment.kt
995050447
package com.appdev.posheesh.ui.inventory import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.appdev.posheesh.databinding.FragmentInventoryBinding class InventoryFragment : Fragment() { private var _binding: FragmentInventoryBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentInventoryBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/inventory/InventoryFragment.kt
2164119807
package com.appdev.openaitest.ui import android.app.Activity import android.content.Context import android.graphics.Color import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.widget.EditText import android.widget.ImageButton import android.widget.LinearLayout import android.widget.ScrollView import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import com.appdev.posheesh.DatabaseHandler import com.appdev.posheesh.R import com.skydoves.balloon.ArrowPositionRules import com.skydoves.balloon.Balloon import com.skydoves.balloon.BalloonAnimation import okhttp3.Call import okhttp3.Callback import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okio.IOException import org.json.JSONArray import org.json.JSONObject class AIChatBoxBalloon(private val context: Context): Activity() { private val balloon: Balloon private val chatLayout: View private val sendButton: ImageButton private val messageEditText: EditText private val chatMessagesLayout: LinearLayout private val client = OkHttpClient() private var chatScrollView: ScrollView private var dbHandler: DatabaseHandler = DatabaseHandler(context) init { // Inflate the custom chat layout chatLayout = LayoutInflater.from(context).inflate(R.layout.layout_floating_chatbox, null) sendButton = chatLayout.findViewById(R.id.send_message_button) messageEditText = chatLayout.findViewById(R.id.message_input_edittext) chatMessagesLayout = chatLayout.findViewById(R.id.chat_messages_layout) // Assuming chatScrollView is your ScrollView chatScrollView = chatLayout.findViewById<ScrollView>(R.id.chat_messages_container) // Create a Balloon instance and set the custom layout val backgroundDrawable = ContextCompat.getDrawable(context, R.drawable.search_box_background) balloon = Balloon.Builder(context) .setWidthRatio(0.6f) .setHeight(400) .setArrowPositionRules(ArrowPositionRules.ALIGN_ANCHOR) .setArrowSize(10) .setArrowPosition(0.5f) .setPadding(3) .setBackgroundDrawable(backgroundDrawable) .setCornerRadius(8f) .setLayout(chatLayout) .setBalloonAnimation(BalloonAnimation.OVERSHOOT) // Apply the animation here .build() // Initialize chat UI elements and set up listeners initChatUI() } private fun initChatUI() { sendButton.setOnClickListener { // Handle message sending logic val message = messageEditText.text.toString().trim() sendMessage(message, true) val question=message.trim() if(question.isNotEmpty()){ getResponse(question) { response -> runOnUiThread { sendMessage(response, false) } } } } } private fun sendMessage(message: String, isUserMessage: Boolean) { // Handle message sending logic // Get the message text from the EditText val messageText = message if (messageText.isNotEmpty()) { // Create a new LinearLayout to hold the message TextView val messageLayout = LinearLayout(context) val layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) // Set margins based on who sends the message if (isUserMessage) { layoutParams.setMargins(16, 16, 16, 16) // Add right margin for user's message layoutParams.gravity = Gravity.END // Align to the right if user's message } else { layoutParams.gravity = Gravity.START // Align to the left if other's message layoutParams.setMargins(16, 16, 16, 16) // Add left margin for other's message } messageLayout.layoutParams = layoutParams // Create a new TextView to display the message val newMessageTextView = TextView(context) newMessageTextView.text = messageText newMessageTextView.setTextColor(Color.BLACK) newMessageTextView.textSize = 16f newMessageTextView.setPadding(16, 8, 16, 8) if (isUserMessage) { // If the message is from the user, set background to blue and align right newMessageTextView.setBackgroundResource(R.drawable.user_message_background) newMessageTextView.setTextColor(Color.WHITE) // Add icon at the end of the message bubble //newMessageTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_menu_camera, 0) // Align the text to the end (right) newMessageTextView.textAlignment = View.TEXT_ALIGNMENT_TEXT_START } else { // If the message is from the other, set background to gray and align left newMessageTextView.setBackgroundResource(R.drawable.ai_message_background) newMessageTextView.setTextColor(Color.BLACK) // Add icon at the start of the message bubble //newMessageTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_menu_gallery, 0, 0, 0) // Align the text to the start (left) newMessageTextView.textAlignment = View.TEXT_ALIGNMENT_TEXT_START newMessageTextView.gravity = View.TEXT_ALIGNMENT_TEXT_START } // Add the new message TextView to the messageLayout messageLayout.addView(newMessageTextView) // Add the messageLayout to the chat messages layout chatMessagesLayout.addView(messageLayout) // Clear the EditText after sending the message messageEditText.text.clear() //Update the height of the balloon to show the new message } else { // Show a toast or handle empty message case Toast.makeText(context, "Please enter a message", Toast.LENGTH_SHORT).show() } chatScrollView.post { chatScrollView.fullScroll(ScrollView.FOCUS_DOWN) } } fun show(anchorView: View) { balloon.showAlignBottom(anchorView) // Show the balloon at the bottom of an anchor view } fun getResponse(question: String, callback: (String) -> Unit){ val apiKey="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" val url="https://api.openai.com/v1/chat/completions" val refTableString = dbHandler.generateDatabaseDescription() val content = "If my question does not relate to the data that I will be giving, don't reference it and just answer the question, but if it does, reference the data. This is the data "+refTableString + " and this is the question "+question val requestBody=""" { "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "$content"}], "temperature": 0.7 } """.trimIndent() val request = Request.Builder() .url(url) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer $apiKey") .post(requestBody.toRequestBody("application/json".toMediaTypeOrNull())) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("error","API failed",e) } override fun onResponse(call: Call, response: Response) { val body=response.body?.string() if (body != null) { Log.v("data",body) } else{ Log.v("data","empty") } val jsonObject = JSONObject(body) val jsonArray: JSONArray = jsonObject.getJSONArray("choices") val messageObject = jsonArray.getJSONObject(0).getJSONObject("message") val content = messageObject.getString("content") val textResult = content callback(textResult) } }) } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/AIChatBoxBalloon.kt
4118199530
package com.appdev.posheesh.ui import android.annotation.SuppressLint import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.os.Handler import android.view.Gravity import android.view.MotionEvent import android.view.View import android.widget.Button import android.widget.EditText import android.widget.LinearLayout import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.marginLeft import androidx.core.view.marginStart import com.appdev.posheesh.DatabaseHandler import com.appdev.posheesh.MainActivity import com.appdev.posheesh.R import com.appdev.posheesh.databinding.ActivityLogin2Binding class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLogin2Binding private var loginButtonPressCount = 0 @SuppressLint("ClickableViewAccessibility") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLogin2Binding.inflate(layoutInflater) setContentView(binding.root) val loginButton: Button = findViewById(R.id.buttonSubmit) val secretButton: Button = findViewById(R.id.buttonAccessAdmin) val editTextCashierCode: EditText = findViewById(R.id.editTextCashierCode) val handler = Handler() loginButton.setOnTouchListener { view, motionEvent -> when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { // Start a handler to show the secret button after 5 seconds handler.postDelayed({ secretButton.visibility = View.VISIBLE }, 5000) // 5000 milliseconds = 5 seconds } MotionEvent.ACTION_UP -> { // Cancel the handler if the user releases the button before 5 seconds view.performClick() // Ensure the onClick event is triggered handler.removeCallbacksAndMessages(null) } } true } loginButton.setOnClickListener { // Add your existing logic here val enteredCode = editTextCashierCode.text.toString().trim() if (enteredCode.isNotEmpty()) { val db = DatabaseHandler(this) // If the entered code is not empty, check if it exists in the database if (db.isUserCodeExists(enteredCode)) { // If the user code exists, open the main activity val intent = Intent(this, MainActivity::class.java) startActivity(intent) } else { // If the user code does not exist, show a dialog indicating it val builder = AlertDialog.Builder(this) builder.setTitle("Invalid User Code") .setMessage("The entered user code does not exist.") .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() } val dialog = builder.create() dialog.show() } } else { if(secretButton.visibility != View.VISIBLE) { // If the entered code is empty, show a dialog indicating it val builder = AlertDialog.Builder(this) builder.setTitle("Empty User Code") .setMessage("Please enter a user code.") .setPositiveButton("OK") { dialog, _ -> dialog.dismiss() } val dialog = builder.create() dialog.show() } } } secretButton.setOnClickListener { Toast.makeText(this, "You've unlocked the admin access", Toast.LENGTH_SHORT).show() showPasswordDialog() } } private fun showPasswordDialog() { val builder = AlertDialog.Builder(this, R.style.AlertDialogCustom) builder.setTitle("Enter Admin Password") // Create a parent layout to encase the EditText val parentLayout = LinearLayout(this) parentLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) parentLayout.gravity = Gravity.CENTER parentLayout.setPadding(40, 16, 40, 0) // Add margin to the parent layout // Create EditText and add it to the parent layout val input = EditText(this) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) input.layoutParams = lp input.gravity = Gravity.CENTER input.background = resources.getDrawable(R.drawable.edit_text_bg, null) parentLayout.addView(input) builder.setView(parentLayout) builder.setPositiveButton("OK") { dialog: DialogInterface, _: Int -> val password = input.text.toString() if (password == "admin") { showEmployeeIdDialog() } else { Toast.makeText(this, "Invalid password", Toast.LENGTH_SHORT).show() } dialog.dismiss() } builder.setNegativeButton("Cancel") { dialog: DialogInterface, _: Int -> dialog.cancel() } val dialog = builder.create() dialog.show() val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE) positiveButton.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary)) val negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE) negativeButton.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary)) } private fun showEmployeeIdDialog() { val builder = AlertDialog.Builder(this, R.style.AlertDialogCustom) builder.setTitle("Enter the employee id of the user you want to add") // Create a parent layout to encase the EditText val parentLayout = LinearLayout(this) parentLayout.layoutParams = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) parentLayout.gravity = Gravity.CENTER parentLayout.setPadding(40, 16, 40, 0) // Add margin to the parent layout // Create EditText and add it to the parent layout val input = EditText(this) val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) input.layoutParams = lp input.gravity = Gravity.CENTER input.background = resources.getDrawable(R.drawable.edit_text_bg, null) parentLayout.addView(input) builder.setView(parentLayout) builder.setPositiveButton("OK") { dialog: DialogInterface, _: Int -> val employeeId = input.text.toString() val result = addUserToDatabase(employeeId) if (result != null) { showResultDialog(result) } dialog.dismiss() } builder.setNegativeButton("Cancel") { dialog: DialogInterface, _: Int -> dialog.cancel() } val dialog = builder.create() dialog.show() val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE) positiveButton.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary)) val negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE) negativeButton.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary)) } private fun showResultDialog(result: String) { val builder = AlertDialog.Builder(this) builder.setTitle("Add User Result") builder.setMessage("User Code: $result\nPlease save this code to login as the user.") builder.setPositiveButton("OK") { dialog, _ -> dialog.dismiss() } builder.show() } private fun addUserToDatabase(employeeId: String): String? { return DatabaseHandler(this).addUser(role = "user",employeeId = employeeId) } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/LoginActivity.kt
3936549597
package com.appdev.posheesh.ui.reports import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.appdev.posheesh.databinding.FragmentReportsBinding class ReportsFragment : Fragment() { private var _binding: FragmentReportsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentReportsBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } }
POSheesh/app/src/main/java/com/appdev/posheesh/ui/reports/ReportsFragment.kt
963615027
package com.appdev.posheesh import PrintActivity import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Environment import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.Toast import com.google.android.material.navigation.NavigationView 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 androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.appdev.openaitest.ui.AIChatBoxBalloon import com.appdev.posheesh.Classes.FragmentChangeListener import com.appdev.posheesh.databinding.ActivityMainBinding import com.appdev.posheesh.ui.LoginActivity import com.appdev.posheesh.ui.sales.ExcelHandler import com.google.android.material.floatingactionbutton.FloatingActionButton import java.io.File import java.io.IOException class MainActivity : AppCompatActivity(), FragmentChangeListener { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding private lateinit var fab: FloatingActionButton private lateinit var chatBoxBalloon: AIChatBoxBalloon private var currentMenu: Menu? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.appBarMain.toolbar) fab = binding.appBarMain.fab chatBoxBalloon = AIChatBoxBalloon(this) fab.setOnClickListener { view -> chatBoxBalloon.show(view) } val drawerLayout: DrawerLayout = binding.drawerLayout val navView: NavigationView = binding.navView val navController = findNavController(R.id.nav_host_fragment_content_main) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration(setOf( R.id.nav_dashboard, R.id.nav_sales, R.id.nav_inventory, R.id.nav_reports, R.id.nav_about, R.id.nav_logout), drawerLayout) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onFragmentChanged(fragmentTag: String) { if (fragmentTag == "Sales") { currentMenu?.clear() // Clear existing menu items menuInflater.inflate(R.menu.sales_menu, currentMenu) } else { currentMenu?.clear() // Clear existing menu items menuInflater.inflate(R.menu.dashboard_menu, currentMenu) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.dashboard_menu, menu) // Save the reference to the menu object currentMenu = menu return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle menu item selection when (item.itemId) { R.id.sales_menu_export -> { val dbHelper = DatabaseHandler(this) val database = dbHelper.writableDatabase val excelHandler = ExcelHandler() // Export the Excel file to internal storage val file = excelHandler.exportToExcel(this, database) // Copy the file to external storage val externalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) val copiedFile = File(externalDir, "data.xlsx") try { file.copyTo(copiedFile, true) } catch (e: IOException) { e.printStackTrace() Log.println(Log.ERROR, "Error", "Error copying file to external storage"+e.message) Toast.makeText(this, "Error copying file to external storage", Toast.LENGTH_SHORT).show() return true } // Get the URI of the copied file val uri: Uri = FileProvider.getUriForFile(this, "com.appdev.posheesh.fileprovider", copiedFile) // Create an intent to view the Excel file val intent = Intent(Intent.ACTION_VIEW) intent.setDataAndType(uri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // Start the activity to view the Excel file startActivity(intent) } R.id.sales_menu_print -> { val printExcelActivity = PrintActivity() val dbHelper = DatabaseHandler(this) val database = dbHelper.writableDatabase val file = ExcelHandler().exportToExcel(this, database) printExcelActivity.printExcelFile(this, file) } } return super.onOptionsItemSelected(item) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment_content_main) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
POSheesh/app/src/main/java/com/appdev/posheesh/MainActivity.kt
973986124
package com.appdev.posheesh.Classes data class Supplies( val supplyName: String, val supplyDescription: String, val imgUrl: String, val supplyQuantity: Int, val supplyUnit: String, val crticalLevel: Int, val isActive: Int, val creationDate: String )
POSheesh/app/src/main/java/com/appdev/posheesh/Classes/Supplies.kt
4030516828
package com.appdev.posheesh.Classes data class Category ( val id: Int, val name: String )
POSheesh/app/src/main/java/com/appdev/posheesh/Classes/Category.kt
1807810801
package com.appdev.posheesh.Classes interface FragmentChangeListener { fun onFragmentChanged(fragmentTag: String) }
POSheesh/app/src/main/java/com/appdev/posheesh/Classes/FragmentChangeListener.kt
1618766746
package com.appdev.posheesh.Classes import android.net.Uri data class Products ( val name: String, val description: String?, val categoryId: Int, val sellingPrice: Double, val imageUri: String, val code: String )
POSheesh/app/src/main/java/com/appdev/posheesh/Classes/Products.kt
639070599
package com.appdev.posheesh import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2"
POSheesh/app/src/main/java/com/appdev/posheesh/ReportsFragment.kt
3730353895
package com.appdev.posheesh import android.annotation.SuppressLint import android.content.ContentResolver import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.provider.MediaStore import android.util.Log import com.appdev.posheesh.Classes.Category import com.appdev.posheesh.Classes.Products import java.io.File import java.io.FileOutputStream import java.io.IOException class DatabaseHandler(private val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { // Create the categories table db.execSQL( "CREATE TABLE IF NOT EXISTS categories (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL" + ")" ) // Populate the categories table with dummy entries db.execSQL("INSERT INTO categories (name) VALUES ('P39 Coffee')") // Create the products table db.execSQL( "CREATE TABLE IF NOT EXISTS products (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL," + "description TEXT," + "isActive INTEGER DEFAULT 1," + "category_id INTEGER NOT NULL," + "quantity INTEGER DEFAULT 0," + "selling_price REAL DEFAULT 0.0," + "buying_price REAL DEFAULT 0.0," + "image_url TEXT," + "code TEXT," + "required_supplies TEXT," + "FOREIGN KEY (category_id) REFERENCES categories(id)" + ")" ) db.execSQL( "CREATE TABLE IF NOT EXISTS users (" + "userid INTEGER PRIMARY KEY AUTOINCREMENT," + "employeeId TEXT," + "usercode TEXT NOT NULL," + "role TEXT NOT NULL," + "isActive INTEGER DEFAULT 1," + "creationDate TEXT" + ")" ) db.execSQL( "CREATE TABLE IF NOT EXISTS supplies (" + "supplyID INTEGER PRIMARY KEY AUTOINCREMENT," + "supplyName TEXT," + "supplyDescription TEXT NOT NULL," + "img_url TEXT NOT NULL," + "supplyQuantity INTEGER DEFAULT 0," + "supplyUnit TEXT NOT NULL," + "crticalLevel INTEGER DEFAULT 0," + "isActive INTEGER DEFAULT 1," + "creationDate TEXT" + ")" ) // Insert a record for the first user with admin role val firstUserCode = "admin" val currentTime = System.currentTimeMillis() val contentValues = ContentValues().apply { put("usercode", firstUserCode) put("employeeId", "000001") put("role", "admin") put("creationDate", currentTime.toString()) } db.insert("users", null, contentValues) // Insert product entries val products = mutableListOf<Products>() // Add the product entries to the list val icedCaramelUri = saveImageToInternalStorage(R.drawable.iced_caramel) val icedCaramelPath = icedCaramelUri?.let { getFilePathFromUri(context, it) } icedCaramelPath?.let { products.add(Products(name = "Iced Caramel Macchiatos", description = "Wapako katilaw ani, libre pls hehe", categoryId = 1, sellingPrice = 39.0, imageUri = it, code = "P001")) } val donDarkoUri = saveImageToInternalStorage(R.drawable.don_darko) val donDarkoPath = donDarkoUri?.let { getFilePathFromUri(context, it) } donDarkoPath?.let { products.add(Products(name = "Don Darko", description = "tsikolet", categoryId = 1, sellingPrice = 39.0, imageUri = it, code = "P002")) } val donyaBerryUri = saveImageToInternalStorage(R.drawable.donya_berry) val donyaBerryPath = donyaBerryUri?.let { getFilePathFromUri(context, it) } donyaBerryPath?.let { products.add(Products(name = "Donya Berry", description = "Kape nga penkpenk", categoryId = 1, sellingPrice = 39.0, imageUri = it, code = "P003")) } val donMatchattoUri = saveImageToInternalStorage(R.drawable.don_matchato) val donMatchattoPath = donMatchattoUri?.let { getFilePathFromUri(context, it) } donMatchattoPath?.let { products.add(Products(name = "Don Matchatto", description = "Green nga Kape gikan Japan", categoryId = 1, sellingPrice = 39.0, imageUri = it, code = "P004")) } // Insert product entries into the database for (product in products) { val contentValues = ContentValues().apply { put("name", product.name) put("description", product.description) put("category_id", product.categoryId) put("selling_price", product.sellingPrice) put("image_url", product.imageUri.toString()) // Convert Uri to string put("code", product.code) } db.insert("products", null, contentValues) } db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('plastic cups', 'Disposable plastic cups for serving beverages', 'https://example.com/plastic_cups_image.jpg', 500, 'per piece', 50, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('straw', 'Disposable straws for drinking', 'https://example.com/straw_image.jpg', 500, 'per piece', 50, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('chocolate syrup', 'Chocolate-flavored syrup for flavoring beverages', 'https://example.com/chocolate_syrup_image.jpg', 5000, 'ml', 500, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('strawberry jam', 'Strawberry-flavored jam for flavoring beverages', 'https://example.com/strawberry_jam_image.jpg', 5000, 'ml', 500, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('matcha syrup', 'Matcha-flavored syrup for flavoring beverages', 'https://example.com/matcha_syrup_image.jpg', 5000, 'ml', 500, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('ice', 'Ice cubes for chilling beverages', 'https://example.com/ice_image.jpg', 10000, 'ml', 1000, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('coffee', 'Coffee concentrate for making coffee-based beverages', 'https://example.com/coffee_image.jpg', 5000, 'ml', 500, 1, CURRENT_TIMESTAMP);") db.execSQL("INSERT INTO supplies (supplyName, supplyDescription, img_url, supplyQuantity, supplyUnit, crticalLevel, isActive, creationDate) VALUES ('milk', 'Milk for making milk-based beverages', 'https://example.com/milk_image.jpg', 10000, 'ml', 1000, 1, CURRENT_TIMESTAMP);") } fun addUser(role: String, employeeId: String): String? { val userCode = generateUniqueUserCode() return if (userCode != null) { val currentTime = System.currentTimeMillis() val contentValues = ContentValues().apply { put("usercode", userCode) put("role", role) put("employeeId", employeeId) put("creationDate", currentTime.toString()) } val db = writableDatabase val success = db.insert("users", null, contentValues) != -1L db.close() if (success) userCode else null } else { null // Handle case where unique user code could not be generated } } @SuppressLint("Range") private fun generateUniqueUserCode(): String? { val db = readableDatabase val userCodes = mutableListOf<String>() // Query all existing user codes val cursor = db.rawQuery("SELECT usercode FROM users", null) while (cursor.moveToNext()) { val userCode = cursor.getString(cursor.getColumnIndex("usercode")) userCodes.add(userCode) } cursor.close() db.close() // Generate a random 6-digit number string and check if it's unique var randomUserCode: String do { randomUserCode = generateUserCode() } while (userCodes.contains(randomUserCode)) return randomUserCode } private fun generateUserCode(): String { // Generate a random 6-digit number string return (100000..999999).random().toString() } private fun saveImageToInternalStorage(resourceId: Int): Uri? { val bitmap = BitmapFactory.decodeResource(context.resources, resourceId) val imagesDir = context.filesDir val imageFile = File(imagesDir, "image_${System.currentTimeMillis()}.jpg") return try { FileOutputStream(imageFile).use { outputStream -> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream) outputStream.flush() outputStream.close() Uri.fromFile(imageFile) } } catch (e: IOException) { e.printStackTrace() null } } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // Handle database upgrades if necessary } fun getAllCategory(): MutableList<Category> { val categoryList = mutableListOf<Category>() val db = readableDatabase val cursor: Cursor? = db.rawQuery("SELECT * FROM categories", null) cursor?.use { val idColumnIndex = it.getColumnIndex("id") val nameColumnIndex = it.getColumnIndex("name") while(it.moveToNext()) { val id = it.getInt(idColumnIndex) val name = it.getString(nameColumnIndex) val category = Category(id, name) categoryList.add(category) } } cursor?.close() db.close() return categoryList } fun getProductsByCategoryId(categoryId: Int): MutableList<Products> { val productList = mutableListOf<Products>() val db = readableDatabase var cursor: Cursor? = null if (categoryId == 0) { cursor = db.rawQuery("SELECT * FROM products", null) } else { val selectionArgs = arrayOf(categoryId.toString()) cursor = db.rawQuery("SELECT * FROM products WHERE category_id = ?", selectionArgs) } cursor?.use { val idColumnIndex = it.getColumnIndex("id") val nameColumnIndex = it.getColumnIndex("name") val descriptionColumnIndex = it.getColumnIndex("description") val isActiveColumnIndex = it.getColumnIndex("isActive") val categoryIdColumnIndex = it.getColumnIndex("category_id") val sellingPriceColumnIndex = it.getColumnIndex("selling_price") val imageUrlColumnIndex = it.getColumnIndex("image_url") val codeColumnIndex = it.getColumnIndex("code") while (it.moveToNext()) { val id = it.getInt(idColumnIndex) val name = it.getString(nameColumnIndex) val description = it.getString(descriptionColumnIndex) val isActive = it.getInt(isActiveColumnIndex) == 1 // Assuming 1 for true, 0 for false val categoryId = it.getInt(categoryIdColumnIndex) val sellingPrice = it.getDouble(sellingPriceColumnIndex) val imageUrl = it.getString(imageUrlColumnIndex) val code = it.getString(codeColumnIndex) // Log the values of properties before creating the Products object Log.d("ProductProperties", "ID: $id") Log.d("ProductProperties", "Name: $name") Log.d("ProductProperties", "Description: $description") Log.d("ProductProperties", "isActive: $isActive") Log.d("ProductProperties", "Category ID: $categoryId") Log.d("ProductProperties", "Selling Price: $sellingPrice") Log.d("ProductProperties", "Image URL: $imageUrl") Log.d("ProductProperties", "Code: $code") // Create the Products object val product = try { Products(name, description, categoryId, sellingPrice, imageUrl, code) } catch (e: Exception) { // Log the exception if one occurs during object creation Log.e("ProductCreationError", "Error creating product: ${e.message}") null // Return null if product creation fails } // Check if the product is null after creation if (product != null) { // Proceed with using the product Log.d("ProductCreation", "Product created successfully: $product") productList.add(product) } else { // Handle the case where product creation failed Log.w("ProductCreation", "Product creation failed: Product is null") } } } cursor?.close() db.close() return productList } fun getProductsByNameSearch(searchString: String, categoryId: Int): MutableList<Products> { val productList = mutableListOf<Products>() val db = readableDatabase var cursor: Cursor? if (categoryId == 0) { cursor = db.rawQuery("SELECT * FROM products WHERE name LIKE ?", arrayOf("%$searchString%")) } else { val selectionArgs = arrayOf(categoryId.toString(), "%$searchString%") cursor = db.rawQuery("SELECT * FROM products WHERE category_id = ? AND name LIKE ?", selectionArgs) } cursor?.use { val idColumnIndex = it.getColumnIndex("id") val nameColumnIndex = it.getColumnIndex("name") val descriptionColumnIndex = it.getColumnIndex("description") val isActiveColumnIndex = it.getColumnIndex("isActive") val categoryIdColumnIndex = it.getColumnIndex("category_id") val sellingPriceColumnIndex = it.getColumnIndex("selling_price") val imageUrlColumnIndex = it.getColumnIndex("image_url") val codeColumnIndex = it.getColumnIndex("code") while (it.moveToNext()) { val id = it.getInt(idColumnIndex) val name = it.getString(nameColumnIndex) val description = it.getString(descriptionColumnIndex) val isActive = it.getInt(isActiveColumnIndex) == 1 // Assuming 1 for true, 0 for false val categoryId = it.getInt(categoryIdColumnIndex) val sellingPrice = it.getDouble(sellingPriceColumnIndex) val imageUrl = it.getString(imageUrlColumnIndex) val code = it.getString(codeColumnIndex) val product = Products(name, description, categoryId, sellingPrice, imageUrl, code) productList.add(product) } } cursor?.close() db.close() return productList } fun getProductByCode(itemCode: Any): Products? { val db = readableDatabase val cursor: Cursor? = db.rawQuery("SELECT * FROM products WHERE code = ?", arrayOf(itemCode.toString())) var product: Products? = null cursor?.use { val idColumnIndex = it.getColumnIndex("id") val nameColumnIndex = it.getColumnIndex("name") val descriptionColumnIndex = it.getColumnIndex("description") val isActiveColumnIndex = it.getColumnIndex("isActive") val categoryIdColumnIndex = it.getColumnIndex("category_id") val sellingPriceColumnIndex = it.getColumnIndex("selling_price") val imageUrlColumnIndex = it.getColumnIndex("image_url") val codeColumnIndex = it.getColumnIndex("code") if (it.moveToFirst()) { val id = it.getInt(idColumnIndex) val name = it.getString(nameColumnIndex) val description = it.getString(descriptionColumnIndex) val isActive = it.getInt(isActiveColumnIndex) == 1 // Assuming 1 for true, 0 for false val categoryId = it.getInt(categoryIdColumnIndex) val sellingPrice = it.getDouble(sellingPriceColumnIndex) val imageUri = it.getString(imageUrlColumnIndex) val code = it.getString(codeColumnIndex) product = Products(name, description, categoryId, sellingPrice, imageUri, code) } } cursor?.close() db.close() return product } private fun getFilePathFromUri(context: Context, uri: Uri): String? { val filePath: String? val cursor = context.contentResolver.query(uri, null, null, null, null) if (cursor != null) { cursor.moveToFirst() val columnIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA) filePath = cursor.getString(columnIndex) cursor.close() } else { filePath = uri.path // Fallback to URI path if cursor is null } return filePath } fun addProduct(product: Products) { val sql = "INSERT INTO products (name, description, category_id, selling_price, image_url, code) VALUES (?, ?, ?, ?, ?, ?)" val database = writableDatabase database.execSQL(sql, arrayOf(product.name, product.description, product.categoryId, product.sellingPrice, product.imageUri, product.code)) database.close() } @SuppressLint("Range") fun generateDatabaseDescription(): String { val databaseDescription = StringBuilder() // Get readable database val db = readableDatabase // Get all table names val cursor: Cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null) // Iterate through table names while (cursor.moveToNext()) { val tableName = cursor.getString(0) val tableDescription = StringBuilder() tableDescription.append("On table $tableName with fields ") // Get column names for the current table val columnsCursor: Cursor = db.rawQuery("PRAGMA table_info($tableName)", null) val fieldList = mutableListOf<String>() // Iterate through column names while (columnsCursor.moveToNext()) { val columnName = columnsCursor.getString(columnsCursor.getColumnIndex("name")) fieldList.add(columnName) } columnsCursor.close() tableDescription.append(fieldList.joinToString(", ")) // Get data from the current table val dataCursor: Cursor = db.rawQuery("SELECT * FROM $tableName", null) // Iterate through rows var rowNumber = 1 while (dataCursor.moveToNext()) { tableDescription.append(" $rowNumber${getOrdinalSuffix(rowNumber)} entry has ") for (i in 0 until dataCursor.columnCount) { val fieldName = dataCursor.getColumnName(i) val fieldValue = dataCursor.getString(i) tableDescription.append("$fieldName value of $fieldValue") if (i < dataCursor.columnCount - 1) { tableDescription.append(", ") } } tableDescription.append(". ") rowNumber++ } dataCursor.close() databaseDescription.append(tableDescription.toString()) } cursor.close() db.close() return databaseDescription.toString() } private fun getOrdinalSuffix(number: Int): String { return when (number % 100) { 11, 12, 13 -> "th" else -> when (number % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" } } } fun isUserCodeExists(userCode: String): Boolean { val db = readableDatabase val selection = "usercode = ?" val selectionArgs = arrayOf(userCode) val cursor = db.query("users", null, selection, selectionArgs, null, null, null) val count = cursor.count cursor.close() db.close() return count > 0 } companion object { const val DATABASE_VERSION = 1 const val DATABASE_NAME = "posheesh.db" } }
POSheesh/app/src/main/java/com/appdev/posheesh/DatabaseHandler.kt
3582235659
package com.appdev.posheesh import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.SurfaceHolder import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.appdev.posheesh.databinding.BarcodeScanBinding import java.io.IOException import com.google.android.gms.vision.CameraSource import com.google.android.gms.vision.Detector import com.google.android.gms.vision.barcode.Barcode import com.google.android.gms.vision.barcode.BarcodeDetector import com.google.android.gms.vision.Detector.Detections class BarcodeScan : AppCompatActivity() { private val requestCodeCameraPermission = 1001 private lateinit var cameraSource: CameraSource private lateinit var barcodeDetector: BarcodeDetector private var scannedValue = "" private lateinit var binding: BarcodeScanBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = BarcodeScanBinding.inflate(layoutInflater) val view = binding.root setContentView(view) if (ContextCompat.checkSelfPermission( this@BarcodeScan, Manifest.permission.CAMERA ) != PackageManager.PERMISSION_GRANTED ) { askForCameraPermission() } else { setupControls() } val aniSlide: Animation = AnimationUtils.loadAnimation(this@BarcodeScan, R.anim.scanner_animation) binding.barcodeLine.startAnimation(aniSlide) } private fun setupControls() { barcodeDetector = BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.ALL_FORMATS).build() cameraSource = CameraSource.Builder(this, barcodeDetector) .setRequestedPreviewSize(1920, 1080) .setAutoFocusEnabled(true) //you should add this feature .build() binding.cameraSurfaceView.getHolder().addCallback(object : SurfaceHolder.Callback { @SuppressLint("MissingPermission") override fun surfaceCreated(holder: SurfaceHolder) { try { //Start preview after 1s delay cameraSource.start(holder) } catch (e: IOException) { e.printStackTrace() } } @SuppressLint("MissingPermission") override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { try { cameraSource.start(holder) } catch (e: IOException) { e.printStackTrace() } } override fun surfaceDestroyed(holder: SurfaceHolder) { cameraSource.stop() } }) barcodeDetector.setProcessor(object : Detector.Processor<Barcode> { override fun release() { Toast.makeText(applicationContext, "Scanner has been closed", Toast.LENGTH_SHORT) .show() } override fun receiveDetections(detections: Detections<Barcode>) { val barcodes = detections.detectedItems if (barcodes.size() == 1) { scannedValue = barcodes.valueAt(0).rawValue runOnUiThread { val intent = Intent() intent.putExtra("scannedValue", scannedValue) setResult(Activity.RESULT_OK, intent) cameraSource.stop() finish() } } } }) } private fun askForCameraPermission() { ActivityCompat.requestPermissions( this@BarcodeScan, arrayOf(android.Manifest.permission.CAMERA), requestCodeCameraPermission ) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == requestCodeCameraPermission && grantResults.isNotEmpty()) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { setupControls() } else { Toast.makeText(applicationContext, "Permission Denied", Toast.LENGTH_SHORT).show() } } } override fun onDestroy() { super.onDestroy() cameraSource.stop() } }
POSheesh/app/src/main/java/com/appdev/posheesh/BarcodeScan.kt
48151082
package lc_101 class Solution { private val leftFirstVisits: ArrayList<Int> = arrayListOf() private val rightFirstVisits: ArrayList<Int> = arrayListOf() fun isSymmetric(root: TreeNode?): Boolean { visitLeftFirst(root?.left) visitRightFirst(root?.right) return leftFirstVisits == rightFirstVisits } private fun visitLeftFirst(node: TreeNode?) { leftFirstVisits.add(Int.MIN_VALUE) node ?: return leftFirstVisits.add(node.`val`) visitLeftFirst(node.left) visitLeftFirst(node.right) } private fun visitRightFirst(node: TreeNode?) { rightFirstVisits.add(Int.MIN_VALUE) node ?: return rightFirstVisits.add(node.`val`) visitRightFirst(node.right) visitRightFirst(node.left) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
LC-PS/src/lc_101/Solution.kt
2048980496
package lc_334 class Solution { fun increasingTriplet(nums: IntArray): Boolean { val smallest = IntArray(size = 2) { Int.MAX_VALUE } nums.forEach { when { it <= smallest[0] -> smallest[0] = it it <= smallest[1] -> smallest[1] = it else -> return true } } return false } }
LC-PS/src/lc_334/Solution.kt
2506503485
package lc_933 import java.util.LinkedList import java.util.Queue class RecentCounter() { private val queue: Queue<Int> = LinkedList() fun ping(t: Int): Int { val diff = t - TIMEOUT while (queue.isNotEmpty() && queue.peek() < diff) queue.poll() queue.offer(t) return queue.size } private companion object { const val TIMEOUT: Int = 3_000 } }
LC-PS/src/lc_933/RecentCounter.kt
1409188457
package lc_2300 class Solution { fun successfulPairs(spells: IntArray, potions: IntArray, success: Long): IntArray { potions.sort() return IntArray(spells.size) { var low = 0 var high = potions.size while (low < high) { val mid = low + high shr 1 val pair = spells[it].toLong() * potions[mid] if (pair < success) low = mid + 1 else high = mid } potions.size - high } } }
LC-PS/src/lc_2300/Solution.kt
2020877893
package lc_735 import java.util.Stack class Solution { fun asteroidCollision(asteroids: IntArray): IntArray { val stack = Stack<Int>() asteroids.forEach { stack.handleCollision(it) } return stack.toIntArray() } private fun Stack<Int>.handleCollision(asteroid: Int) { val peekAsteroid = if (isNotEmpty()) peek() else 0 if (0 < peekAsteroid && asteroid < 0) { when { peekAsteroid + asteroid < 0 -> pop().also { handleCollision(asteroid) } peekAsteroid + asteroid == 0 -> pop() else -> Unit } return } push(asteroid) } }
LC-PS/src/lc_735/Solution.kt
2549945491
package lc_994 import java.util.LinkedList class Solution { private val dirs: Sequence<Pair<Int, Int>> = sequenceOf(1 to 0, -1 to 0, 0 to 1, 0 to -1) fun orangesRotting(grid: Array<IntArray>): Int { val coords = LinkedList<Triple<Int, Int, Int>>() for (row in grid.indices) { for (col in grid[row].indices) { if (grid[row][col] == 2) { grid[row][col] = 0 coords.offer(Triple(row, col, third = 0)) } } } var maxDay = 0 while (coords.isNotEmpty()) { val (row, col, day) = coords.poll() maxDay = maxOf(maxDay, day) dirs.map { row + it.first to col + it.second } .filter { it.first in grid.indices } .filter { it.second in grid[it.first].indices } .filter { grid[it.first][it.second] == 1 } .forEach { grid[it.first][it.second] = 0 coords.offer(Triple(it.first, it.second, third = day + 1)) } } if (grid.any { cols -> cols.any { 0 < it } }) maxDay = -1 return maxDay } }
LC-PS/src/lc_994/Solution.kt
2655099606
package lc_394 import java.util.Stack class Solution { fun decodeString(s: String): String { val countStack = Stack<Int>() val strStack = Stack<String>() val countSb = StringBuilder() for (c in s) { if (c in '0'..'9') { countSb.append(c - '0') continue } if (countSb.isNotEmpty()) { countStack.push(countSb.toString().toInt()) countSb.clear() } if (c != ']') { strStack.push(c.toString()) continue } val strSb = StringBuilder() var peek: String while (strStack.pop().also { peek = it } != "[") strSb.append(peek.reversed()) repeat(countStack.pop()) { strStack.push(strSb.toString().reversed()) } } return strStack.joinToString(separator = "") } }
LC-PS/src/lc_394/Solution.kt
2218693252
package lc_199 class Solution { private val visitedValues: ArrayList<Int> = arrayListOf() fun rightSideView(root: TreeNode?): List<Int> { dfs(root) return visitedValues } private fun dfs(node: TreeNode?, depth: Int = 0) { node ?: return if (visitedValues.size == depth) visitedValues.add(node.`val`) dfs(node.right, depth = depth + 1) dfs(node.left, depth = depth + 1) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null } fun main() { val root = TreeNode(1).apply { left = TreeNode(2).apply { left = TreeNode(4) } right = TreeNode(3) } println(Solution().rightSideView(root)) }
LC-PS/src/lc_199/Solution.kt
569080719
package lc_2336 import java.util.PriorityQueue class SmallestInfiniteSet() { private var last: Int = 1 private val pq: PriorityQueue<Int> = PriorityQueue() fun popSmallest(): Int = if (pq.isEmpty()) ++last else pq.poll() fun addBack(num: Int) { if (num < last && num !in pq) pq.offer(num) } }
LC-PS/src/lc_2336/Solution.kt
2222017144
package lc_1372 class Solution { fun longestZigZag(root: TreeNode?): Int = maxOf(dfs(root, shouldGoLeft = true), dfs(root, shouldGoLeft = false)) private fun dfs(node: TreeNode?, shouldGoLeft: Boolean, level: Int = 0): Int = if (shouldGoLeft) { node?.left?.let { maxOf( dfs(it, shouldGoLeft = false, level = level + 1), dfs(it, shouldGoLeft = true) ) } ?: level } else { node?.right?.let { maxOf( dfs(it, shouldGoLeft = true, level = level + 1), dfs(it, shouldGoLeft = false) ) } ?: level } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
LC-PS/src/lc_1372/Solution.kt
736125898
package lc_136 class Solution { fun singleNumber(nums: IntArray): Int = nums.fold(initial = 0) { acc, num -> acc xor num } }
LC-PS/src/lc_136/Solution.kt
1556539527
package lc_2352 class Solution { fun equalPairs(grid: Array<IntArray>): Int { var count = 0 for (rowIdx in grid.indices) { val col = IntArray(grid.size) { grid[it][rowIdx] } grid.forEach { if (it contentEquals col) ++count } } return count } }
LC-PS/src/lc_2352/Solution.kt
3973344789
package lc_2390 import java.util.Stack class Solution { fun removeStars(s: String): String { val stack = Stack<Char>() s.forEach { if (it == '*') { while (stack.isNotEmpty()) if (stack.pop() != '*') break } else { stack.push(it) } } return stack.joinToString(separator = "") } }
LC-PS/src/lc_2390/Solution.kt
4181579263
package lc_100 class Solution { fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean { if (p == null && q == null) return true if (p?.`val` != q?.`val`) return false return isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right) } } class TreeNode(var `val`: Int) { var left: TreeNode? = null var right: TreeNode? = null }
LC-PS/src/lc_100/Solution.kt
545568446
package lc_392 class Solution { fun isSubsequence(s: String, t: String): Boolean { var i = 0 for (c in t) { if (s.lastIndex < i) break if (c == s[i]) ++i } return i == s.length } }
LC-PS/src/lc_392/Solution.kt
701481187
package lc_198 class Solution { fun rob(nums: IntArray): Int { if (nums.size == 1) return nums[0] val maxMoney = IntArray(nums.size).apply { this[0] = nums[0] this[1] = maxOf(nums[0], nums[1]) } for (i in 2 until nums.size) { maxMoney[i] = maxOf(maxMoney[i - 1], b = maxMoney[i - 2] + nums[i]) } return maxMoney[nums.lastIndex] } }
LC-PS/src/lc_198/Solution.kt
45224201
package lc_1926 import java.util.LinkedList class Solution { private val dirs: Sequence<Pair<Int, Int>> = sequenceOf(1 to 0, -1 to 0, 0 to 1, 0 to -1) fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int { val coords = LinkedList<Triple<Int, Int, Int>>() .apply { maze[entrance[0]][entrance[1]] = '+' offer(Triple(entrance[0], entrance[1], third = 0)) } while (coords.isNotEmpty()) { val (row, col, dist) = coords.poll() val isEntrance = row == entrance[0] && col == entrance[1] if (!isEntrance) { val isExit = dirs.map { row + it.first to col + it.second } .any { it.first !in maze.indices || it.second !in maze[it.first].indices } if (isExit) return dist } dirs.map { row + it.first to col + it.second } .filter { it.first in maze.indices } .filter { it.second in maze[it.first].indices } .filter { maze[it.first][it.second] == '.' } .forEach { (row, col) -> maze[row][col] = '+' coords.offer(Triple(row, col, third = dist + 1)) } } return -1 } }
LC-PS/src/lc_1926/Solution.kt
2817433573
package lc_162 class Solution { fun findPeakElement(nums: IntArray): Int { var low = 0 var high = nums.lastIndex while (low < high) { val mid = low + (low + high shr 1) if (nums[mid + 1] < nums[mid]) high = mid else low = mid + 1 } return low } }
LC-PS/src/lc_162/Solution.kt
3689239356
package lc_20 import java.util.Stack class Solution { fun isValid(s: String): Boolean { val stack = Stack<Char>() s.forEach { when (it) { ')' -> if (stack.isNotEmpty() && stack.peek() == '(') stack.pop() else stack.push(it) ']' -> if (stack.isNotEmpty() && stack.peek() == '[') stack.pop() else stack.push(it) '}' -> if (stack.isNotEmpty() && stack.peek() == '{') stack.pop() else stack.push(it) else -> stack.push(it) } } return stack.isEmpty() } }
LC-PS/src/lc_20/Solution.kt
499575873
package lc_27 class Solution { fun removeElement(nums: IntArray, `val`: Int): Int { var j = 0 for (i in nums.indices) if (nums[i] != `val`) nums[j++] = nums[i] return j } }
LC-PS/src/lc_27/Solution.kt
2694216026
package lc_11 class Solution { fun maxArea(height: IntArray): Int { var left = 0 var right = height.lastIndex var maxArea = 0 while (left < right) { val width = right - left val area = width * if (height[left] < height[right]) height[left++] else height[right--] if (maxArea < area) maxArea = area } return maxArea } }
LC-PS/src/lc_11/Solution.kt
814323532
package lc_42 import java.util.Stack class Solution { fun trap(height: IntArray): Int { var maxHeight = 0 val stack = Stack<Pair<Int, Int>>() height.forEach { stack.push(it to maxHeight) maxHeight = maxOf(maxHeight, it) } maxHeight = 0 var water = 0 while (stack.isNotEmpty()) { val pair = stack.pop() water += (minOf(pair.second, maxHeight) - pair.first).coerceAtLeast(minimumValue = 0) maxHeight = maxOf(maxHeight, pair.first) } return water } }
LC-PS/src/lc_42/Solution.kt
4126913746
package lc_1004 class Solution { fun longestOnes(nums: IntArray, k: Int): Int { var left = 0 var flippableCount = k for (right in nums.indices) { if (nums[right] < 1) --flippableCount if (flippableCount < 0) { if (nums[left] < 1) ++flippableCount ++left } } return nums.size - left } }
LC-PS/src/lc_1004/Solution.kt
849271133
package lc_1493 class Solution { fun longestSubarray(nums: IntArray): Int { var left = 0 var zeroCount = 0 nums.forEach { if (it < 1) ++zeroCount if (1 < zeroCount && nums[left++] < 1) --zeroCount } return nums.lastIndex - left } }
LC-PS/src/lc_1493/Solution.kt
3707311695
package lc_1207 class Solution { fun uniqueOccurrences(arr: IntArray): Boolean { val map = HashMap<Int, Int>() arr.forEach { map[it] = map.getOrDefault(it, 0) + 1 } val set = HashSet<Int>() map.values.forEach { if (!set.add(it)) return false } return true } }
LC-PS/src/lc_1207/Solution.kt
4243535547
package lc_80 class Solution { fun removeDuplicates(nums: IntArray): Int { var prev = Int.MIN_VALUE var times = 0 var k = 0 for (i in nums.indices) { if (prev != nums[i]) { prev = nums[i] times = 1 nums[k++] = nums[i] } else if (++times < 3) { nums[k++] = nums[i] } } return k } }
LC-PS/src/lc_80/Solution.kt
1070956483
package lc_1456 class Solution { fun maxVowels(s: String, k: Int): Int { val vowels = setOf('a', 'e', 'i', 'o', 'u') var count = 0 repeat(k) { if (s[it] in vowels) ++count } var maxCount = count for (i in k..<s.length) { if (s[i] in vowels) ++count if (s[i - k] in vowels) --count if (maxCount < count) maxCount = count } return maxCount } }
LC-PS/src/lc_1456/Solution.kt
3194388823
package lc_28 class Solution { fun strStr(haystack: String, needle: String): Int { var i = 0 while (i in haystack.indices) { if (haystack[i] != needle.first()) { ++i continue } val range = i until i + needle.length if (haystack.lastIndex < range.last) return -1 var j = range.first var k = i var isMatched = true while (j in range) { if (haystack[j] == needle.first() && k == i) k = j if (haystack[j] != needle[j - i]) { isMatched = false break } ++j } if (isMatched) { return i } else { i = if (i < k) k else j + 1 } } return -1 } }
LC-PS/src/lc_28/Solution.kt
3032801589
package lc_215 class Solution { fun findKthLargest(nums: IntArray, k: Int): Int { val counts = IntArray(size = 20_001) nums.forEach { ++counts[it + 10_000] } var i = 0 for (num in counts.lastIndex downTo 0) { if (i + counts[num] < k) { i += counts[num] } else { return num - 10_000 } } return Int.MIN_VALUE } }
LC-PS/src/lc_215/Solution.kt
1108218874
package lc_443 class Solution { fun compress(chars: CharArray): Int { val result = buildString { var count = 0 for (i in chars.indices) { ++count if (i == chars.lastIndex || chars[i] != chars[i + 1]) { append(chars[i]) if (1 < count) append(count) count = 0 } } } for (i in result.indices) chars[i] = result[i] return result.length } }
LC-PS/src/lc_443/Solution.kt
2350890000
package lc_1 class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { buildMap<Int, Int> { nums.forEachIndexed { i, num -> this[num]?.let { return intArrayOf(it, i) } this[target - num] = i } } return intArrayOf() } }
LC-PS/src/lc_1/Solution.kt
3153102243
package lc_6 class Solution { fun convert(s: String, numRows: Int): String { if (numRows == 1) return s val canvas = Array(numRows) { CharArray(size = 1_001) { ' ' } } var row = 0 var col = 0 var i = 0 while (i < s.length) { while (i < s.length && row < numRows) canvas[row++][col] = s[i++] row -= 2 ++col while (i < s.length && 0 < row) canvas[row--][col++] = s[i++] } val sb = StringBuilder() for (row in 0 until numRows) { for (col in 0 until 1_001) { if (canvas[row][col] != ' ') sb.append(canvas[row][col]) } } return sb.toString() } }
LC-PS/src/lc_6/Solution.kt
3348554145
package lc_26 class Solution { fun removeDuplicates(nums: IntArray): Int { var i = 0 nums.forEach { if (it != nums[i]) nums[++i] = it } return i + 1 } }
LC-PS/src/lc_26/Solution.kt
31211632
package lc_21 class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { var l1 = list1 var l2 = list2 val merged: ListNode? when { l1 == null && l2 == null -> return null l1 == null -> return l2 l2 == null -> return l1 l1.`val` < l2.`val` -> { merged = l1 l1 = l1.next } else -> { merged = l2 l2 = l2.next } } merged.next = merge(l1, l2) return merged } private fun merge(l1: ListNode?, l2: ListNode?): ListNode? = when { l1 == null -> l2 l2 == null -> l1 l1.`val` < l2.`val` -> { l1.next = merge(l1.next, l2) l1 } else -> { l2.next = merge(l1, l2.next) l2 } } } class ListNode(var `val`: Int) { var next: ListNode? = null }
LC-PS/src/lc_21/Solution.kt
3073314784