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

[둘리] 3, 4단계 쇼핑 장바구니 제출합니다. #33

Merged
merged 47 commits into from
May 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
6f04e7e
refactor: 함수 간소화
hyemdooly May 15, 2023
e7af72c
refactor: supportActionBar Label 설정 삭제, manifest 이용
hyemdooly May 15, 2023
6977e5f
refactor: test 코드 수정
hyemdooly May 15, 2023
8c85cf2
feat: ProductList 상품 장바구니 추가 뷰 수정
hyemdooly May 16, 2023
723c091
docs: 3단계 요구사항 정리
hyemdooly May 16, 2023
b528d57
feat: 장바구니 버튼 생성
hyemdooly May 16, 2023
fd660c5
feat: ProductDetail 수량 선택 Dialog 구현
hyemdooly May 16, 2023
e9a1b6c
feat: CartActivity 하단 뷰 구현
hyemdooly May 16, 2023
7181e9b
feat: CartActivity Item layout 변경사항 수정
hyemdooly May 16, 2023
27b2a1b
feat: cart badge 생성
hyemdooly May 17, 2023
dd70d3b
feat: ProductListActivity List Count 구현
hyemdooly May 17, 2023
e230169
feat: ProductListActivity AppBar Cart Badge 구현
hyemdooly May 17, 2023
15dc571
feat: ProductDetailActivity 마지막으로 본 상품 startActivity
hyemdooly May 17, 2023
588a1ee
feat: ProductDetailActivity 다른 액티비티 실행 시 Stack 조절
hyemdooly May 17, 2023
dc79515
feat: Cart 아이콘 장바구니 비었으면 Gone으로 수정
hyemdooly May 17, 2023
7d0a2e3
feat: Cart 아이콘 장바구니 비었으면 Gone으로 수정
hyemdooly May 17, 2023
8f145f4
Merge remote-tracking branch 'origin/step4' into step4
hyemdooly May 17, 2023
9370658
feat: ProductListPresenter에서 삭제했던 최근 본 상품 복구
hyemdooly May 18, 2023
0337194
refactor: domain 코드 이동, ktlintformat
hyemdooly May 18, 2023
3e7fc30
feat: CartActivity 상품 개수 업데이트 구현
hyemdooly May 18, 2023
1c419ad
feat: CartActivity, CartSystem 선택 구현 (리팩토링 필수)
hyemdooly May 18, 2023
49e6293
feat: ProductListActivity <-> CartActivity 데이터 동일하게 연동
hyemdooly May 18, 2023
3200e3a
refactor: CartActivity LiveData 활용 리팩터링
hyemdooly May 19, 2023
cbcd2f4
refactor: DataBinding format 수정
hyemdooly May 19, 2023
01b5db9
fix: CartActivity 버그 수정
hyemdooly May 20, 2023
57a2b4d
refactor: ProductListActivity Presenter 리팩터링
hyemdooly May 20, 2023
f6d3645
fix: ProductListActivity Presenter 리팩터링 및 버그 수정
hyemdooly May 20, 2023
b5e1269
refactor: CartPresenterTest 코드 수정에 맞게 리팩터링 및 수정
hyemdooly May 20, 2023
dc3106f
refactor: ProductDetailPresenterTest 리팩터링 및 수정
hyemdooly May 20, 2023
47cb4a5
refactor: ProductListPresenterTest 수정, CartPresenterTest 테스트 통과 안되는 …
hyemdooly May 20, 2023
e23cdba
refactor: formatting
hyemdooly May 20, 2023
65cade1
feat: 4단계 MockServer 구현 및 적용
hyemdooly May 21, 2023
b3e732f
refactor: 강제종료 버그 수정, 패키지 정리
hyemdooly May 21, 2023
6869b1f
fix: 최근 본 상품 반대로 나오는 버그 수정, ProductDetialActivity 다이얼로그 dismiss 추가
hyemdooly May 21, 2023
ebdc9bd
docs: README 업데이트
hyemdooly May 21, 2023
ba1d77f
fix: 갯수 제한 걸리는 버그 수정
hyemdooly May 23, 2023
2797d74
Merge remote-tracking branch 'origin/step4' into step4
hyemdooly May 23, 2023
5cf4f06
refactor: CartProductModel의 isChecked, count variable -> valuable로 변경
hyemdooly May 27, 2023
c291ea5
refactor: ProductModel variable -> valuable로 수정
hyemdooly May 27, 2023
508e204
refactor: backing property 변수 위치 수정
hyemdooly May 27, 2023
b04a4af
refactor: lateinit var -> by lazy로 최대한 수정
hyemdooly May 27, 2023
8d09837
refactor: presenter에서 데이터를 내려주도록 수정
hyemdooly May 27, 2023
a9268da
refactor: AppCompatButton -> Button으로 수정
hyemdooly May 27, 2023
9bac38d
refactor: 요구사항에 없는 내용 삭제
hyemdooly May 27, 2023
261e924
refactor: 테스트코드 로직 최대한 삭제
hyemdooly May 27, 2023
9ec4930
refactor: ProductViewHolder 생성자에서 onClick 등록
hyemdooly May 27, 2023
1227d57
refactor: plus, minus 한계치 수정
hyemdooly May 27, 2023
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
Prev Previous commit
Next Next commit
fix: CartActivity 버그 수정
  • Loading branch information
hyemdooly committed May 20, 2023
commit 01b5db96cd32ce597d7fa1b2282843041f411690
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@ class CartActivity : AppCompatActivity(), CartContract.View {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setUpPresenter()
setUpBinding()
setContentView(binding.root)
setUpActionBar()
setUpPresenter()
binding.presenter = presenter
binding.lifecycleOwner = this
presenter.fetchProducts()
}

private fun setUpBinding() {
binding = ActivityCartBinding.inflate(layoutInflater)
binding.lifecycleOwner = this
binding.presenter = presenter
}

private fun setUpActionBar() {
Expand Down Expand Up @@ -86,7 +86,6 @@ class CartActivity : AppCompatActivity(), CartContract.View {
}

companion object {
private const val TITLE = "Cart"
fun newIntent(context: Context): Intent = Intent(context, CartActivity::class.java)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ interface CartContract {
fun fetchPrevPage()
fun updateCartProductCount(id: Int, count: Int)
fun selectProduct(product: CartProductModel)
fun selectAll(isChecked: Boolean)
fun selectAll()
}
}
35 changes: 24 additions & 11 deletions app/src/main/java/woowacourse/shopping/view/cart/CartPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package woowacourse.shopping.view.cart

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import woowacourse.shopping.domain.*
Expand Down Expand Up @@ -62,10 +63,11 @@ class CartPresenter(
cartItems.add(CartViewItem.CartProductItem(it))
}
cartItems.add(CartViewItem.PaginationItem(cartPagination.status))
_isCheckedAll.value = getIsCheckedAll()
}

private fun getIsCheckedAll() =
cartSystem.selectedProducts.containsAll(convertItemsToCartProduct(cartItems))
cartSystem.selectedProducts.containsAll(convertItemsToCartProducts(cartItems))

private fun getNextCartProductModel(): CartProductModel? {
val product = cartPagination.currentLastItem() ?: return null
Expand All @@ -75,29 +77,40 @@ class CartPresenter(
)
}

override fun selectAll(isChecked: Boolean) {
override fun selectAll() {
val isChecked = _isCheckedAll.value?.not() ?: true

cartItems.filterIsInstance<CartViewItem.CartProductItem>().forEachIndexed { index, it ->
it.product.isChecked = isChecked
view.showChangedItem(index)
}

val products = if (isChecked) { // 전체 선택
convertItemsToCartProduct(cartItems) - cartSystem.selectedProducts.toSet()
convertItemsToCartProducts(cartItems) - cartSystem.selectedProducts.toSet()
} else { // 전체 해제
convertItemsToCartProduct(cartItems).intersect(cartSystem.selectedProducts.toSet())
convertItemsToCartProducts(cartItems).intersect(cartSystem.selectedProducts.toSet())
}
Log.d("PRODUCTS", products.toString())
var result: CartSystemResult? = _cartSystemResult.value
products.forEach {
_cartSystemResult.value = cartSystem.selectProduct(it)
result = cartSystem.selectProduct(it)
}
_cartSystemResult.value = result
_isCheckedAll.value = isChecked
}

override fun selectProduct(product: CartProductModel) {
_cartSystemResult.value = cartSystem.selectProduct(product.toDomain())
_isCheckedAll.value = getIsCheckedAll()
}

override fun fetchNextPage() {
val items = cartPagination.nextItems()
if (items.isNotEmpty()) {
changeListItems(items)
view.showChangedItems()
}
_isCheckedAll.value = getIsCheckedAll()
}

override fun fetchPrevPage() {
Expand All @@ -106,6 +119,7 @@ class CartPresenter(
changeListItems(items)
view.showChangedItems()
}
_isCheckedAll.value = getIsCheckedAll()
}

private fun changeListItems(items: List<CartProduct>) {
Expand All @@ -116,8 +130,9 @@ class CartPresenter(
}

override fun updateCartProductCount(id: Int, count: Int) {
if (count !in COUNT_MIN..COUNT_MAX) return
cartRepository.update(id, count)
val cartProducts = convertItemsToCartProduct(cartItems)
val cartProducts = convertItemsToCartProducts(cartItems)
cartProducts.find { it.id == id }?.let {
val index = cartProducts.indexOf(it)
(cartItems[index] as CartViewItem.CartProductItem).product.count = count
Expand All @@ -126,20 +141,18 @@ class CartPresenter(
}
}

override fun selectProduct(product: CartProductModel) {
_cartSystemResult.value = cartSystem.selectProduct(product.toDomain())
_isCheckedAll.value = getIsCheckedAll()
}

private fun convertCartProductToModels(cartProducts: List<CartProduct>) =
cartProducts.map {
it.toUiModel(cartSystem.isSelectedProduct(it), productRepository.find(it.id))
}.toMutableList()

private fun convertItemsToCartProduct(items: List<CartViewItem>): List<CartProduct> =
private fun convertItemsToCartProducts(items: List<CartViewItem>): List<CartProduct> =
items.filterIsInstance<CartViewItem.CartProductItem>().map { it.product.toDomain() }

companion object {
private const val PAGINATION_SIZE = 5
private const val COUNT_MIN = 1
private const val COUNT_MAX = 100
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ class ProductDetailActivity : AppCompatActivity(), ProductDetailContract.View {
startLastViewedDetailActivity(lastViewedProduct)
}
}
productDetailBinding.presenter = presenter
Glide.with(productDetailBinding.root.context).load(product.imageUrl).into(productDetailBinding.imgProduct)
productDetailBinding.btnPutInCart.setOnClickListener {
dialog.show()
Expand All @@ -81,14 +80,11 @@ class ProductDetailActivity : AppCompatActivity(), ProductDetailContract.View {
}

private fun setUpDialogBinding(product: ProductModel) {
dialogBinding.lifecycleOwner = this
dialogBinding.presenter = presenter
dialogBinding.product = product
}

override fun updateCount(count: Int) {
dialogBinding.textCount.text = count.toString()
}

private fun setUpResult(isAdd: Boolean) {
if (isAdd) {
setResult(RESULT_ADDED, intent)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package woowacourse.shopping.view.productdetail

import androidx.lifecycle.LiveData
import woowacourse.shopping.model.ProductModel

interface ProductDetailContract {
interface View {
fun finishActivity(isAdd: Boolean)
fun updateCount(count: Int)
}

interface Presenter {
val count: LiveData<Int>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

count를 LiveData 타입으로 정의하셨네요. 👍
count를 Presenter 인터페이스에 꼭 정의할 필요가 있을까요?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

액티비티에서는 추상화된 presenter를 타입으로 받고 있는데 인터페이스에 정의하지 않더라도 count를 사용할 수 있나요?
xml에 LiveData type의 count variable을 선언해주고 프레젠터에서 LiveData타입의 count를 넘기도록 한 후, TextView에서 쓰도록 수정했는데, error: cannot find symbol 에러가 나왔습니다.ㅠㅠ

    override fun setUpDialogBinding(product: ProductModel, count: LiveData<Int>) {
        dialogBinding.lifecycleOwner = this
        dialogBinding.presenter = presenter
        dialogBinding.product = product
        dialogBinding.count = count
    }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지금 구조에서는 Presenter에서 LiveData를 쓰다보니 인터페이스에 꼭 정의를 해야겠군요. 😅
Presenter에서의 LiveData는 익숙지 않네요.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MVVM 구조를 배운다면 이런 경우가 발생하지 않을까요?
LiveData를 사용하면서 어쩔 수 없이 구조가 이렇게 되는데, 이 구조는 MVP가 아닌 것 같다는 생각이 들면서도 방법이 영 떠오르지 않았습니다...
아키텍처란 어렵네요🥲

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MVVM 구조에서는 Contract를 사용하지 않습니다. 😄

fun putInCart(product: ProductModel)
fun updateRecentViewedProducts(id: Int)
fun plusCount()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package woowacourse.shopping.view.productdetail

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import woowacourse.shopping.domain.CartRepository
import woowacourse.shopping.domain.RecentViewedRepository
import woowacourse.shopping.model.ProductModel
Expand All @@ -9,9 +11,12 @@ class ProductDetailPresenter(
private val cartRepository: CartRepository,
private val recentViewedRepository: RecentViewedRepository,
) : ProductDetailContract.Presenter {
private var count = 1
private val _count: MutableLiveData<Int> = MutableLiveData<Int>(1)
override val count: LiveData<Int>
get() = _count

override fun putInCart(product: ProductModel) {
cartRepository.add(product.id, count)
if (_count.value != null) cartRepository.add(product.id, _count.value ?: 0)
view.finishActivity(true)
}

Expand All @@ -20,13 +25,11 @@ class ProductDetailPresenter(
}

override fun plusCount() {
if (count < COUNT_MAX) count++
view.updateCount(count)
if (_count.value in COUNT_MIN until COUNT_MAX) _count.value = _count.value?.plus(1)
}

override fun minusCount() {
if (count > COUNT_MIN) count--
view.updateCount(count)
if (_count.value in COUNT_MIN + 1..COUNT_MAX) _count.value = _count.value?.minus(1)
}

companion object {
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/layout/activity_cart.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="@{presenter.isCheckedAll()}"
android:onCheckedChanged="@{(view, checked) -> presenter.selectAll(checked)}"
android:onClick="@{() -> presenter.selectAll()}"
android:minWidth="0dp"
android:minHeight="0dp" />

Expand Down
8 changes: 2 additions & 6 deletions app/src/main/res/layout/activity_product_detail.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
name="product"
type="woowacourse.shopping.model.ProductModel" />

<variable
name="presenter"
type="woowacourse.shopping.view.productdetail.ProductDetailContract.Presenter" />

<variable
name="last_viewed_product"
type="woowacourse.shopping.model.ProductModel" />
Expand Down Expand Up @@ -77,7 +73,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="18dp"
android:text="@{String.format(@string/korean_won, PriceFormatter.INSTANCE.format(product.price))}"
android:text="@{@string/korean_won2(product.price)}"
android:textColor="@color/black"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
Expand Down Expand Up @@ -124,7 +120,7 @@
android:id="@+id/text_price_viewed_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.format(@string/korean_won, PriceFormatter.INSTANCE.format(last_viewed_product.price))}"
android:text="@{@string/korean_won2(last_viewed_product.price)}"
android:textColor="@color/black"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="@id/text_product_name_viewed_last"
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/res/layout/dialog_count.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
<variable
name="product"
type="woowacourse.shopping.model.ProductModel" />
<import type="woowacourse.shopping.util.PriceFormatter" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http:https://schemas.android.com/apk/res/android"
Expand Down Expand Up @@ -41,7 +40,7 @@
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/text_product_name_selected"
android:text="@{String.format(@string/korean_won, PriceFormatter.INSTANCE.format(product.price))}"
android:text="@{@string/korean_won2(product.price)}"
tools:text="99,900원" />

<androidx.appcompat.widget.AppCompatButton
Expand All @@ -62,7 +61,7 @@
android:layout_width="42dp"
android:layout_height="0dp"
android:gravity="center"
android:text="1"
android:text="@{presenter.count.toString()}"
android:textColor="@color/gray"
android:textSize="22sp"
app:layout_constraintBottom_toBottomOf="@id/btn_plus"
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/res/layout/item_cart.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
android:checked="@{cartProduct.checked}"
android:minWidth="0dp"
android:minHeight="0dp"
android:onCheckedChanged="@{() -> onItemClick.onSelectProduct(cartProduct)}"
android:onClick="@{() -> onItemClick.onSelectProduct(cartProduct)}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Expand Down
46 changes: 23 additions & 23 deletions app/src/test/java/woowacourse/shopping/ProductListPresenterTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -72,32 +72,32 @@ class ProductListPresenterTest {
val itemsExpected = listOf<ProductListViewItem>(
ProductListViewItem.RecentViewedItem(
listOf(
ProductModel(2, "헛개차", "", 10000),
ProductModel(1, "현미밥", "", 10000),
ProductModel(0, "락토핏", "", 10000)
ProductModel(2, "헛개차", "", 10000, 0),
ProductModel(1, "현미밥", "", 10000, 0),
ProductModel(0, "락토핏", "", 10000, 0)
)
)
) + listOf<ProductListViewItem>(
ProductListViewItem.ProductItem(ProductModel(0, "락토핏", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(1, "현미밥", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(2, "헛개차", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(3, "키", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(4, "닭가슴살", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(5, "enffl", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(6, "뽀또", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(7, "둘리", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(8, "안녕", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(9, "9", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(10, "10", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(11, "11", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(12, "12", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(13, "13", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(14, "14", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(15, "15", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(16, "16", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(17, "17", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(18, "18", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(19, "19", "", 10000)),
ProductListViewItem.ProductItem(ProductModel(0, "락토핏", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(1, "현미밥", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(2, "헛개차", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(3, "키", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(4, "닭가슴살", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(5, "enffl", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(6, "뽀또", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(7, "둘리", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(8, "안녕", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(9, "9", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(10, "10", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(11, "11", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(12, "12", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(13, "13", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(14, "14", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(15, "15", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(16, "16", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(17, "17", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(18, "18", "", 10000, 0)),
ProductListViewItem.ProductItem(ProductModel(19, "19", "", 10000, 0)),
) + ProductListViewItem.ShowMoreItem()
assertEquals(itemsExpected.subList(0, 21), items.captured.subList(0, 21))
assertEquals(itemsExpected[itemsExpected.lastIndex].javaClass, items.captured[items.captured.lastIndex].javaClass)
Expand Down
20 changes: 11 additions & 9 deletions domain/src/main/java/woowacourse/shopping/domain/CartSystem.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class CartSystem(
}

fun selectProduct(product: CartProduct): CartSystemResult {
if (_selectedProducts.find { it.cartProduct.id == product.id } == null){
if (_selectedProducts.find { it.cartProduct.id == product.id } == null) {
val price = productRepository.find(product.id).price
_selectedProducts.add(CartSystemProduct(product, price))
totalPrice += price * product.count
Expand All @@ -24,7 +24,8 @@ class CartSystem(
}

private fun deselectProduct(id: Int): CartSystemResult {
val product = _selectedProducts.find { it.cartProduct.id == id } ?: throw java.lang.IllegalArgumentException()
val product = _selectedProducts.find { it.cartProduct.id == id }
?: throw java.lang.IllegalArgumentException()
totalPrice -= product.price * product.cartProduct.count
_selectedProducts.remove(product)
println("Delete : $product | total: $totalPrice")
Expand All @@ -33,13 +34,14 @@ class CartSystem(

fun updateProduct(id: Int, count: Int): CartSystemResult {
val index = _selectedProducts.indexOfFirst { it.cartProduct.id == id }
if (index != -1) {
println("Before : ${_selectedProducts[index]}")
val diff = count - _selectedProducts[index].cartProduct.count
totalPrice += _selectedProducts[index].price * diff
_selectedProducts[index] = CartSystemProduct(CartProduct(id, count), _selectedProducts[index].price)
println("After : ${_selectedProducts[index]}")
}
if (index == -1) return CartSystemResult(totalPrice.price, _selectedProducts.size)

println("Before : ${_selectedProducts[index]}")
val diff = count - _selectedProducts[index].cartProduct.count
totalPrice += _selectedProducts[index].price.price * diff
_selectedProducts[index] = CartSystemProduct(CartProduct(id, count), _selectedProducts[index].price)
println("After : ${_selectedProducts[index]}")

return CartSystemResult(totalPrice.price, _selectedProducts.size)
}

Expand Down
Loading