Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sneh/points page #558

Merged
merged 21 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,9 @@ dependencies {

// Swipe-to-refresh
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

//Json Parsing
implementation 'com.google.code.gson:gson:2.8.9'
}

apply plugin: 'com.google.gms.google-services'
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/java/org/hackillinois/android/API.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.hackillinois.android

import okhttp3.ResponseBody
import org.hackillinois.android.database.entity.*
import org.hackillinois.android.model.event.EventsList
import org.hackillinois.android.model.event.ShiftsList
Expand All @@ -16,6 +17,7 @@ import org.hackillinois.android.model.user.FavoritesResponse
import org.hackillinois.android.model.version.Version
import org.hackillinois.android.notifications.DeviceToken
import retrofit2.Call
import retrofit2.Response
import retrofit2.http.*

interface API {
Expand Down Expand Up @@ -69,6 +71,18 @@ interface API {
@POST("shop/item/buy/")
suspend fun buyShopItem(@Body body: ItemInstance): ShopItem

@POST("shop/cart/{itemId}")
suspend fun addItemCart(@Path("itemId") itemId: String): Response<ResponseBody>

@GET("shop/cart/")
suspend fun getCart(): Cart

@GET("shop/cart/qr/")
suspend fun getCartQRCode(): QRResponse

@DELETE("shop/cart/{itemId}")
suspend fun removeItemCart(@Path("itemId") itemId: String): Response<ResponseBody>

@POST("shop/cart/redeem/")
suspend fun redeemCart(@Body body: QRCode): Cart

Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/org/hackillinois/android/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,12 @@ class App : Application() {
return if (apiInitialized) apiInternal else getAPI("")
}

Log.d("TOKEN", token)
Log.d("APPTOKEN", token)

val interceptor = { chain: Interceptor.Chain ->
val newRequest = chain.request().newBuilder()
.addHeader("Authorization", token)
.addHeader("Authorization", "Bearer $token")
.addHeader("Accept", "application/json")
.build()
chain.proceed(newRequest)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package org.hackillinois.android.database.entity

data class QRResponse(val QRCode: String)
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package org.hackillinois.android.view.shop

import android.content.Context
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import org.hackillinois.android.R
import org.hackillinois.android.database.entity.ShopItem

class CartAdapter(
private var cartItems: List<Pair<ShopItem, Int>>,
private val listener: OnQuantityChangeListener
) : RecyclerView.Adapter<CartAdapter.ViewHolder>() {

private lateinit var context: Context

inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val textViewSticker: TextView = view.findViewById(R.id.text_view_sticker)
val quantityTextView: TextView = view.findViewById(R.id.number_text)
val shopItemImageView: ImageView = view.findViewById(R.id.image_view_sticker_symbol)
val plusButton: TextView = view.findViewById(R.id.button_plus)
val minusButton: TextView = view.findViewById(R.id.button_minus)
}

private fun expandTouchArea(targetView: View, extraPadding: Int) {
val parentView = targetView.parent as? ViewGroup ?: return
parentView.post {
val rect = Rect()
targetView.getHitRect(rect)
rect.top -= extraPadding
rect.left -= extraPadding
rect.bottom += extraPadding
rect.right += extraPadding
parentView.touchDelegate = TouchDelegate(rect, targetView)
parentView.requestLayout() // Refresh layout so it applies
}
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.point_shop_cart_tile, parent, false)
context = parent.context
return ViewHolder(view)
}

override fun getItemCount() = cartItems.size

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val (item, quantity) = cartItems[position]
holder.textViewSticker.text = item.name
holder.quantityTextView.text = quantity.toString()
Glide.with(context).load(item.imageURL).into(holder.shopItemImageView)

// Increase quantity using plus button
holder.plusButton.setOnClickListener {
val newQuantity = quantity + 1
listener.onIncreaseQuantity(item, newQuantity)
}

expandTouchArea(holder.plusButton, 100)

// Decrease quantity using minus button (allowing 0)
holder.minusButton.setOnClickListener {
val newQuantity = quantity - 1
listener.onDecreaseQuantity(item, newQuantity)
}

expandTouchArea(holder.minusButton, 100)
}

fun updateCart(newCartItems: List<Pair<ShopItem, Int>>) {
this.cartItems = newCartItems
notifyDataSetChanged()
}

interface OnQuantityChangeListener {
fun onIncreaseQuantity(item: ShopItem, newQuantity: Int)
fun onDecreaseQuantity(item: ShopItem, newQuantity: Int)
}
}
120 changes: 120 additions & 0 deletions app/src/main/java/org/hackillinois/android/view/shop/CartFragment.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package org.hackillinois.android.view.shop

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.launch
import org.hackillinois.android.App
import org.hackillinois.android.R
import org.hackillinois.android.database.entity.Cart
import org.hackillinois.android.database.entity.ShopItem

class CartFragment : Fragment(), CartAdapter.OnQuantityChangeListener {

private lateinit var recyclerView: RecyclerView
private lateinit var cartAdapter: CartAdapter
private var cartItems: List<Pair<ShopItem, Int>> = listOf()

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_point_shop_cart, container, false)

recyclerView = view.findViewById(R.id.recyclerview_point_shop)
recyclerView.layoutManager = GridLayoutManager(context, 2)

cartAdapter = CartAdapter(cartItems, this)
recyclerView.adapter = cartAdapter

fetchCartData()

val backButton: View = view.findViewById(R.id.backButton)
backButton.bringToFront()
backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack() // Go back to previous fragment
}

val redeemButton: View = view.findViewById(R.id.redeemButton)
redeemButton.setOnClickListener {
val redeemFragment = RedeemFragment()
requireActivity().supportFragmentManager.beginTransaction()
.replace(R.id.contentFrame, redeemFragment)
.addToBackStack(null)
.commit()
}

return view
}

private fun fetchCartData() {
lifecycleScope.launch {
try {
val shopItems: List<ShopItem> = App.getAPI().shop()
val cart: Cart = App.getAPI().getCart()
val items = mutableListOf<Pair<ShopItem, Int>>()

for ((itemId, quantity) in cart.items) {
val shopItem = shopItems.find { it.itemId == itemId }
if (shopItem != null) {
items.add(Pair(shopItem, quantity))
} else {
Log.e("CartFragment", "ShopItem not found for itemId: $itemId")
}
}
cartItems = items
cartAdapter.updateCart(cartItems)
} catch (e: Exception) {
Log.e("CartFragment", "Error fetching cart items", e)
}
}
}

override fun onIncreaseQuantity(item: ShopItem, newQuantity: Int) {
lifecycleScope.launch {
try {
val response = App.getAPI().addItemCart(item.itemId)
if (response.isSuccessful) {
Log.d("CartDebug", "Item added: ${response.body()}")
fetchCartData() // Refresh cart
} else {
Log.e("CartDebug", "Failed to add item: ${response.code()}")
}
} catch (e: Exception) {
Log.e("CartDebug", "Error adding item to cart", e)
}
}
}

override fun onDecreaseQuantity(item: ShopItem, newQuantity: Int) {
lifecycleScope.launch {
try {
val response = App.getAPI().removeItemCart(item.itemId)
if (response.isSuccessful) {
Log.d("CartDebug", "Item removed: ${response.body()}")
if (newQuantity == 0) {
// If quantity is zero, remove the item from UI
fetchCartData()
} else {
// Just update the UI without full fetch
cartItems = cartItems.map {
if (it.first.itemId == item.itemId) Pair(it.first, newQuantity) else it
}
cartAdapter.updateCart(cartItems)
}
} else {
Log.e("CartDebug", "Failed to remove item: ${response.code()}")
}
} catch (e: Exception) {
Log.e("CartDebug", "Error removing item from cart", e)
}
}
}
}
102 changes: 102 additions & 0 deletions app/src/main/java/org/hackillinois/android/view/shop/RedeemFragment.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package org.hackillinois.android.view.shop

import RedeemViewModel
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import org.hackillinois.android.R
import java.util.EnumMap

class RedeemFragment : Fragment() {

private lateinit var qrCodeImage: ImageView
private lateinit var redeemViewModel: RedeemViewModel

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_point_shop_redeem, container, false)

// Handle Back Button Click
val backButton: View = view.findViewById(R.id.title_textview_back)
backButton.bringToFront()
backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack() // Go back to previous fragment
}

qrCodeImage = view.findViewById(R.id.qr_code_placeholder)

// Initialize and observe the ViewModel
redeemViewModel = ViewModelProvider(this).get(RedeemViewModel::class.java)
redeemViewModel.qrCodeLiveData.observe(
viewLifecycleOwner,
Observer { qrString ->
Log.d("RedeemFragment", "Updated QR Code: $qrString")
updateQRView(qrString)
}
)

redeemViewModel.errorLiveData.observe(viewLifecycleOwner) { errorMessage ->
Toast.makeText(requireContext(), errorMessage, Toast.LENGTH_SHORT).show()
}

return view
}

private fun updateQRView(qrString: String) {
if (qrCodeImage.width > 0 && qrCodeImage.height > 0) {
Log.d("RedeemFragment", "Generating QR with text: $qrString")
val bitmap = generateQR(qrString)
qrCodeImage.setImageBitmap(bitmap)
}
}

private fun generateQR(text: String): Bitmap {
val width = qrCodeImage.width
val height = qrCodeImage.height

val pixels = IntArray(width * height)
val multiFormatWriter = MultiFormatWriter()
val hints = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java)
hints[EncodeHintType.MARGIN] = 0

try {
val bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints)
val clear = Color.TRANSPARENT
val solid = Color.BLACK
for (x in 0 until width) {
for (y in 0 until height) {
pixels[y * width + x] = if (bitMatrix.get(x, y)) solid else clear
}
}
} catch (e: WriterException) {
e.printStackTrace()
}
return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
}

override fun onResume() {
super.onResume()
redeemViewModel.startAutoRefresh() // Resume QR refresh when fragment is visible
}

override fun onPause() {
super.onPause()
redeemViewModel.stopAutoRefresh() // Pause QR refresh when fragment is hidden
}
}
Loading
Loading