Skip to content

Commit

Permalink
done order
Browse files Browse the repository at this point in the history
  • Loading branch information
nqmgaming committed May 29, 2024
1 parent 61e344e commit 4a62f01
Show file tree
Hide file tree
Showing 8 changed files with 391 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.nqmgaming.shoseshop.data.model.order

import com.google.gson.annotations.SerializedName

data class Order(
@SerializedName("_id")
val id: String,
@SerializedName("user")
val userId: String,
@SerializedName("address")
val address: String,
@SerializedName("email")
val email: String,
@SerializedName("phoneNumber")
val phoneNumber: String,
@SerializedName("paymentMethod")
val paymentMethod: String,
@SerializedName("status")
val status: String,
@SerializedName("total")
val total: Int,
@SerializedName("products")
val products: List<OrderProduct>,
@SerializedName("createdAt")
val createdAt: String,
@SerializedName("updatedAt")
val updatedAt: String,
)

data class OrderProduct(
@SerializedName("_id")
val id: String,
@SerializedName("product")
val productId: String,
@SerializedName("quantity")
val quantity: Int,
)
37 changes: 37 additions & 0 deletions app/src/main/java/com/nqmgaming/shoseshop/data/remote/ShoesApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.nqmgaming.shoseshop.data.model.cart.Cart
import com.nqmgaming.shoseshop.data.model.cart.CartRequest
import com.nqmgaming.shoseshop.data.model.cart.CartResponse
import com.nqmgaming.shoseshop.data.model.category.CategoryResponse
import com.nqmgaming.shoseshop.data.model.order.Order
import com.nqmgaming.shoseshop.data.model.product.Product
import com.nqmgaming.shoseshop.data.model.signIn.SignInRequest
import com.nqmgaming.shoseshop.data.model.signIn.SignInResponse
Expand Down Expand Up @@ -123,7 +124,43 @@ interface ShoesApi {
@Path("id") id: String
)

// DELETE request to delete all cart items by user id
@DELETE("/carts/user/{userId}")
suspend fun deleteAllCartItemsByUserId(
@Header("Authorization") token: String,
@Path("userId") id: String
)

/**
* This part is for order
*/

// GET request to get all orders by user id
@GET("/orders/user/{userId}")
suspend fun getOrdersByUserId(
@Header("Authorization") token: String,
@Path("userId") userId: String
): List<Order>

// POST request to create order
@POST("/orders")
suspend fun createOrder(
@Header("Authorization") token: String,
@Body order: Order
): Order

// PATCH request to update order status
@PATCH("/orders/{id}")
suspend fun updateOrderStatus(
@Header("Authorization") token: String,
@Path("id") id: String,
@Body status: String
): Order

// DELETE request to delete order
@DELETE("/orders/{id}")
suspend fun deleteOrder(
@Header("Authorization") token: String,
@Path("id") id: String
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.nqmgaming.shoseshop.data.repository
import com.nqmgaming.shoseshop.data.model.cart.CartRequest
import com.nqmgaming.shoseshop.data.model.cart.CartResponse
import com.nqmgaming.shoseshop.data.model.category.CategoryResponse
import com.nqmgaming.shoseshop.data.model.order.Order
import com.nqmgaming.shoseshop.data.model.signIn.SignInRequest
import com.nqmgaming.shoseshop.data.model.signUp.SignUpRequest
import com.nqmgaming.shoseshop.data.remote.ShoesApi
Expand Down Expand Up @@ -40,4 +41,11 @@ class ShoesRepository @Inject constructor(
shoesApi.updateCartItemQuantity(token, id, map)

suspend fun deleteCart(token: String, id: String) = shoesApi.deleteCartItem(token, id)

suspend fun deleteAllCart(token: String, userId: String) =
shoesApi.deleteAllCartItemsByUserId(token, userId)

suspend fun createOrder(token: String, order: Order) = shoesApi.createOrder(token, order)

suspend fun getOrders(token: String, userId: String) = shoesApi.getOrdersByUserId(token, userId)
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.nqmgaming.shoseshop.ui.activities.checkout

import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.widget.Toast
Expand All @@ -13,14 +14,13 @@ import com.maxkeppeler.sheets.input.ValidationResult
import com.maxkeppeler.sheets.input.type.InputEditText
import com.nqmgaming.shoseshop.R
import com.nqmgaming.shoseshop.databinding.ActivityCheckoutBinding
import com.nqmgaming.shoseshop.ui.activities.order.OrderActivity
import com.nqmgaming.shoseshop.util.SharedPrefUtils
import com.wajahatkarim3.easyvalidation.core.view_ktx.validEmail
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class CheckoutActivity : AppCompatActivity() {
private lateinit var binding: ActivityCheckoutBinding
private val viewModel: CheckoutViewModel by viewModels()
private lateinit var email: String
private lateinit var phoneNumber: String
private lateinit var address: String
Expand All @@ -40,6 +40,7 @@ class CheckoutActivity : AppCompatActivity() {
address = SharedPrefUtils.getString(this, "address") ?: ""
val total = intent.getStringExtra("total") ?: ""
val shippingFee = total.toDouble() * 0.1
val token = intent.getStringExtra("token")
binding.tvShippingFeeValue.text = "$ $shippingFee"
binding.tvTotalQuantityValue.text = "$ $total"
binding.tvTotalValue.text = "$ ${total.toDouble() + shippingFee}"
Expand Down Expand Up @@ -159,6 +160,17 @@ class CheckoutActivity : AppCompatActivity() {
})
}
}
btnCheckout.setOnClickListener {
val totalIntent = total.toDouble() + shippingFee
Intent(this@CheckoutActivity, OrderActivity::class.java).also {
it.putExtra("total", totalIntent.toString())
it.putExtra("email", email)
it.putExtra("phoneNumber", phoneNumber)
it.putExtra("address", address)
it.putExtra("token", token)
startActivity(it)
}
}
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,21 +1,145 @@
package com.nqmgaming.shoseshop.ui.activities.order

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.nqmgaming.shoseshop.R
import com.nqmgaming.shoseshop.data.model.order.Order
import com.nqmgaming.shoseshop.data.model.order.OrderProduct
import com.nqmgaming.shoseshop.databinding.ActivityOrderBinding
import com.nqmgaming.shoseshop.ui.activities.MainActivity
import com.nqmgaming.shoseshop.ui.fragments.cart.CartViewModel
import com.nqmgaming.shoseshop.util.SharedPrefUtils
import com.saadahmedsoft.popupdialog.PopupDialog
import com.saadahmedsoft.popupdialog.Styles
import com.saadahmedsoft.popupdialog.listener.OnDialogButtonClickListener
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@AndroidEntryPoint
class OrderActivity : AppCompatActivity() {
private lateinit var binding: ActivityOrderBinding
private val viewModel by viewModels<OrderViewModel>()
private val cartViewModel by viewModels<CartViewModel>()
private var paymentMethod: String = "Cash"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_order)
binding = ActivityOrderBinding.inflate(layoutInflater)
setContentView(binding.root)
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
}

val totalPrice = intent.getStringExtra("total") ?: ""
val email = intent.getStringExtra("email") ?: ""
val phoneNumber = intent.getStringExtra("phoneNumber") ?: ""
val token = intent.getStringExtra("token") ?: ""
val address = intent.getStringExtra("address") ?: ""
val userId = SharedPrefUtils.getString(this, "id") ?: ""


//get date
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val date = LocalDate.parse(LocalDate.now().toString(), formatter)

binding.rdCash.isChecked = true

binding.cardCash.setOnClickListener {
paymentMethod = "Cash"
binding.rdCash.isChecked = true
binding.rdCc.isChecked = false
binding.rdPaypal.isChecked = false
}

binding.cardCredit.setOnClickListener {
paymentMethod = "CC"
binding.rdCash.isChecked = false
binding.rdCc.isChecked = true
binding.rdPaypal.isChecked = false
}

binding.cardPaypal.setOnClickListener {
paymentMethod = "Paypal"
binding.rdCash.isChecked = false
binding.rdCc.isChecked = false
binding.rdPaypal.isChecked = true
}

binding.btnNext.setOnClickListener {
// Get all carts from the server by userId and create an order
cartViewModel.getAllCartsMain(token, userId) { carts ->
if (carts != null) {
val order = Order(
id = "",
userId = userId,
email = email,
phoneNumber = phoneNumber,
address = address,
createdAt = date.toString(),
updatedAt = date.toString(),
status = "Pending",
paymentMethod = paymentMethod,
total = totalPrice.toDouble().toInt(),
products = carts.map { cart ->
OrderProduct(
id = cart.id,
productId = cart.items.product,
quantity = cart.items.quantity
)
}
)
Log.d("OrderActivity", "onCreate: $order")
viewModel.createOrderOrder(token, order) { isOrderCreated ->
if (isOrderCreated) {
// Order created successfully
// Clear the cart
viewModel.deleteAllCartOrder(token, userId) { done ->
if (done) {
PopupDialog.getInstance(this@OrderActivity)
.setStyle(Styles.SUCCESS)
.setHeading("Order created successfully!")
.setDescription("Thanks for your purchase")
.setDismissButtonText("OK")
.setCancelable(false)
.showDialog(object : OnDialogButtonClickListener() {
override fun onDismissClicked(dialog: Dialog) {
super.onDismissClicked(dialog)
dialog.dismiss()
Intent(
this@OrderActivity,
MainActivity::class.java
).also { intent ->
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
finish()
}
}
})
} else {
Toast.makeText(this, "Error deleting cart", Toast.LENGTH_SHORT)
.show()
}
}
} else {
Toast.makeText(this, "Error creating order", Toast.LENGTH_SHORT).show()
}
}
} else {
Toast.makeText(this, "Cart is empty", Toast.LENGTH_SHORT).show()
}
}
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.nqmgaming.shoseshop.ui.activities.order

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.nqmgaming.shoseshop.data.model.order.Order
import com.nqmgaming.shoseshop.data.repository.ShoesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class OrderViewModel @Inject constructor(
private val shoesRepository: ShoesRepository
) : ViewModel() {
private suspend fun createOrder(token: String, order: Order) =
shoesRepository.createOrder(token, order)

private suspend fun deleteAllCart(token: String, userId: String) =
shoesRepository.deleteAllCart(token, userId)

fun createOrderOrder(token: String, order: Order, callback: (Boolean) -> Unit) {
viewModelScope.launch {
try {
val isOrderCreated = createOrder(token, order)
callback(true)
} catch (e: Exception) {
Log.e("OrderViewModel", "Error creating order: ${e.message}")
callback(false)
}
}
}

fun deleteAllCartOrder(token: String, userId: String, callback: (Boolean) -> Unit) {
viewModelScope.launch {
try {
val isCartDeleted = deleteAllCart(token, userId)
callback(true)
} catch (e: Exception) {
Log.e("OrderViewModel", "Error deleting all cart: ${e.message}")
callback(false)
}
}
}
}
Loading

0 comments on commit 4a62f01

Please sign in to comment.