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
feat: CartActivity, CartSystem 선택 구현 (리팩토링 필수)
  • Loading branch information
hyemdooly committed May 18, 2023
commit 1c419ad0015d8d90225718434bf38b83adc3958b
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ package woowacourse.shopping.model
import woowacourse.shopping.domain.CartProduct
import woowacourse.shopping.domain.Product

fun CartProduct.toUiModel(product: Product): CartProductModel =
CartProductModel(id, product.name, product.imageUrl, count, product.price.price * count)
fun CartProduct.toUiModel(isChecked: Boolean = false, product: Product): CartProductModel =
CartProductModel(isChecked, id, product.name, product.imageUrl, count, product.price.price * count)

fun CartProductModel.toDomain(): CartProduct = CartProduct(id, count)
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package woowacourse.shopping.model

data class CartProductModel(val id: Int, val name: String, val imageUrl: String, val count: Int, val totalPrice: Int)
data class CartProductModel(var isChecked: Boolean, val id: Int, val name: String, val imageUrl: String, val count: Int, val totalPrice: Int)
16 changes: 16 additions & 0 deletions app/src/main/java/woowacourse/shopping/view/cart/CartActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@ import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import woowacourse.shopping.R
import woowacourse.shopping.data.CartDbRepository
import woowacourse.shopping.data.ProductMockRepository
import woowacourse.shopping.databinding.ActivityCartBinding
import woowacourse.shopping.model.CartProductModel
import woowacourse.shopping.util.PriceFormatter

class CartActivity : AppCompatActivity(), CartContract.View {
private lateinit var binding: ActivityCartBinding
Expand All @@ -20,6 +23,9 @@ class CartActivity : AppCompatActivity(), CartContract.View {
setUpActionBar()
setUpPresenter()
presenter.fetchProducts()
binding.checkboxTotal.setOnClickListener {
presenter.selectAll(binding.checkboxTotal.isChecked)
}
}

private fun setUpBinding() {
Expand Down Expand Up @@ -53,6 +59,10 @@ class CartActivity : AppCompatActivity(), CartContract.View {
override fun onUpdateCount(id: Int, count: Int) {
presenter.updateCartProductCount(id, count)
}

override fun onSelectProduct(product: CartProductModel) {
presenter.selectProduct(product)
}
}
)
}
Expand All @@ -65,6 +75,12 @@ class CartActivity : AppCompatActivity(), CartContract.View {
binding.recyclerCart.adapter?.notifyItemChanged(position)
}

override fun showTotalResult(isSelectAll: Boolean, totalPrice: Int, totalCount: Int) {
binding.checkboxTotal.isChecked = isSelectAll
binding.textTotalPrice.text = getString(R.string.korean_won, PriceFormatter.format(totalPrice))
binding.btnOrder.text = getString(R.string.order_count, totalCount)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package woowacourse.shopping.view.cart

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import woowacourse.shopping.model.CartProductModel

class CartAdapter(
private val items: List<CartViewItem>,
Expand All @@ -13,6 +14,7 @@ class CartAdapter(
fun onNextClick()
fun onPrevClick()
fun onUpdateCount(id: Int, count: Int)
fun onSelectProduct(product: CartProductModel)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartItemViewHolder {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package woowacourse.shopping.view.cart

import woowacourse.shopping.model.CartProductModel

interface CartContract {
interface View {
fun showProducts(items: List<CartViewItem>)
fun showChangedItems()

fun showChangedItem(position: Int)
fun showTotalResult(selectAll: Boolean, totalPrice: Int, totalCount: Int)
}

interface Presenter {
Expand All @@ -14,5 +16,7 @@ interface CartContract {
fun fetchNextPage()
fun fetchPrevPage()
fun updateCartProductCount(id: Int, count: Int)
fun selectProduct(product: CartProductModel)
fun selectAll(isChecked: Boolean)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ sealed class CartItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
binding.btnPlus.setOnClickListener {
onItemClick.onUpdateCount(item.product.id, item.product.count + 1)
}
binding.checkboxSelect.setOnClickListener {
onItemClick.onSelectProduct(item.product)
}
}
}

Expand Down
83 changes: 73 additions & 10 deletions app/src/main/java/woowacourse/shopping/view/cart/CartPresenter.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package woowacourse.shopping.view.cart

import woowacourse.shopping.domain.CartPagination
import woowacourse.shopping.domain.CartProduct
import woowacourse.shopping.domain.CartRepository
import woowacourse.shopping.domain.ProductRepository
import woowacourse.shopping.domain.*
import woowacourse.shopping.model.CartProductModel
import woowacourse.shopping.model.toDomain
import woowacourse.shopping.model.toUiModel

class CartPresenter(
Expand All @@ -13,17 +11,19 @@ class CartPresenter(
private val productRepository: ProductRepository
) : CartContract.Presenter {
private val cartPagination = CartPagination(PAGINATION_SIZE, cartRepository)
private val cartSystem = CartSystem(productRepository)

private val currentCartProducts =
convertToCartProductModels(cartPagination.nextItems()).toMutableList()
private val cartItems =
(
currentCartProducts.map { CartViewItem.CartProductItem(it) } +
CartViewItem.PaginationItem(cartPagination.status)
).toMutableList()
currentCartProducts.map { CartViewItem.CartProductItem(it) } +
CartViewItem.PaginationItem(cartPagination.status)
).toMutableList()

override fun fetchProducts() {
view.showProducts(cartItems)
view.showTotalResult(false, 0, 0)
}

override fun removeProduct(id: Int) {
Expand All @@ -32,22 +32,63 @@ class CartPresenter(
cartRepository.remove(id)
cartItems.removeAt(currentCartProducts.indexOf(removedItem))
currentCartProducts.remove(removedItem)
val result = cartSystem.removeProduct(id)
view.showTotalResult(
cartSystem.selectedProducts.containsAll(currentCartProducts.map { product -> product.toDomain() }),
result.totalPrice,
result.totalCount
)

// 남은 자리 페이지 뒷 상품으로 다시 채우기
if (nextItemExist) {
cartItems.removeLast()
fillProductInBlank()
cartItems.add(CartViewItem.PaginationItem(cartPagination.status))
view.showChangedItems()
return
}
view.showChangedItems()
}

override fun selectAll(isChecked: Boolean) {
val products = if (isChecked) {
cartItems.filterIsInstance<CartViewItem.CartProductItem>().forEachIndexed { index, it ->
it.product.isChecked = true
view.showChangedItem(index)
}

currentCartProducts.map { it.toDomain() } - cartSystem.selectedProducts.toSet()
} else {
cartItems.filterIsInstance<CartViewItem.CartProductItem>().forEachIndexed { index, it ->
it.product.isChecked = false
view.showChangedItem(index)
}
currentCartProducts.map { it.toDomain() }.intersect(cartSystem.selectedProducts.toSet())
}

var result: CartSystemResult? = null
products.forEach {
result = cartSystem.selectProduct(it)
}
result?.let {
view.showTotalResult(
isChecked,
it.totalPrice,
it.totalCount
)
}

return
}

private fun fillProductInBlank() {
val product = cartPagination.currentLastItem() ?: return
val productModel = product.toUiModel(productRepository.find(product.id))
val productModel = product.toUiModel(cartSystem.isSelectedProduct(product), productRepository.find(product.id))
currentCartProducts.add(productModel)
cartItems.add(CartViewItem.CartProductItem(productModel))
}


override fun fetchNextPage() {
val items = cartPagination.nextItems()
if (items.isNotEmpty()) {
Expand All @@ -68,14 +109,36 @@ class CartPresenter(
cartRepository.update(id, count)
currentCartProducts.find { it.id == id }?.let {
val index = currentCartProducts.indexOf(it)
currentCartProducts[index] = CartProductModel(it.id, it.name, it.imageUrl, count, it.totalPrice / it.count * count)
currentCartProducts[index] = CartProductModel(
it.isChecked,
it.id,
it.name,
it.imageUrl,
count,
it.totalPrice / it.count * count
)
cartItems[index] = CartViewItem.CartProductItem(currentCartProducts[index])
view.showChangedItem(index)
val systemResult = cartSystem.updateProduct(id, count)
view.showTotalResult(
cartSystem.selectedProducts.containsAll(currentCartProducts.map { product -> product.toDomain() }),
systemResult.totalPrice,
systemResult.totalCount
)
}
}

override fun selectProduct(product: CartProductModel) {
val result = cartSystem.selectProduct(product.toDomain()) ?: return
view.showTotalResult(
cartSystem.selectedProducts.containsAll(currentCartProducts.map { product -> product.toDomain() }),
result.totalPrice,
result.totalCount
)
}

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

private fun changeListItems(items: List<CartProduct>) {
currentCartProducts.clear()
Expand Down
4 changes: 2 additions & 2 deletions app/src/main/res/layout/activity_cart.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
app:layout_constraintTop_toTopOf="parent">

<CheckBox
android:id="@+id/checkbox_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="0dp"
Expand All @@ -61,10 +62,10 @@
</LinearLayout>

<TextView
android:id="@+id/text_total_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="12dp"
android:text="@string/korean_won"
android:textColor="@color/white"
android:textSize="18sp"
android:textStyle="bold"
Expand All @@ -80,7 +81,6 @@
android:layout_height="0dp"
android:background="@drawable/back_rectangle"
android:paddingHorizontal="14dp"
android:text="@string/order_count"
android:textColor="@color/white"
android:textSize="18sp"
android:textStyle="bold"
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/layout/item_cart.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

<CheckBox
android:id="@+id/checkbox_select"
android:checked="@{cartProduct.checked}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
Expand Down
54 changes: 54 additions & 0 deletions domain/src/main/java/woowacourse/shopping/domain/CartSystem.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package woowacourse.shopping.domain

class CartSystem(
private val productRepository: ProductRepository
) {
private val _selectedProducts = mutableListOf<CartSystemProduct>()
val selectedProducts: List<CartProduct>
get() = _selectedProducts.map { it.cartProduct }.toList()
private var totalPrice: Price = Price(0)

fun isSelectedProduct(product: CartProduct): Boolean {
return _selectedProducts.find { it.cartProduct.id == product.id } != null
}

fun selectProduct(product: CartProduct): CartSystemResult {
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
println("Add : $_selectedProducts | total: $totalPrice")
return CartSystemResult(totalPrice.price, _selectedProducts.size)
}
return deselectProduct(product.id)
}

private fun deselectProduct(id: Int): CartSystemResult {
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")
return CartSystemResult(totalPrice.price, _selectedProducts.size)
}

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]}")
}
return CartSystemResult(totalPrice.price, _selectedProducts.size)
}

fun removeProduct(id: Int): CartSystemResult {
val item = _selectedProducts.find { it.cartProduct.id == id }
if (item != null) {
totalPrice -= item.price * item.cartProduct.count
_selectedProducts.remove(item)
}
return CartSystemResult(totalPrice.price, _selectedProducts.size)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package woowacourse.shopping.domain

data class CartSystemProduct(val cartProduct: CartProduct, val price: Price)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package woowacourse.shopping.domain

data class CartSystemResult(val totalPrice: Int, val totalCount: Int)
7 changes: 7 additions & 0 deletions domain/src/main/java/woowacourse/shopping/domain/Price.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ value class Price(val price: Int) {
require(price >= 0) { PRICE_RANGE_ERROR }
}

operator fun plus(operand: Price): Price = Price(price + operand.price)

operator fun minus(operand: Price): Price = Price(price - operand.price)

operator fun times(count: Int): Price = Price(price * count)


companion object {
private const val PRICE_RANGE_ERROR = "가격은 0 이상의 숫자이어야합니다."
}
Expand Down