refactor: move lesson 7 checkout orchestration into viewmodel
This commit is contained in:
1 parent
a773ac7867
commit
0e5eff673b
3 files changed
+62
-152
No files matched your search
@@ -6,7 +6,6 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.lifecycle.ViewModel
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.cart.CartRepository
|
||||
import com.example.minishop.checkout.CheckoutService
|
||||
import com.example.minishop.db.createShopDatabase
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.network.ProductApi
|
||||
@@ -55,7 +54,6 @@ class ShopViewModel : ViewModel() {
|
||||
private val database = createShopDatabase()
|
||||
private val cartRepository = CartRepository(database)
|
||||
private val orderRepository = OrderRepository(database)
|
||||
private val checkoutService = CheckoutService(cartRepository, orderRepository)
|
||||
|
||||
var uiState by mutableStateOf(ShopUiState())
|
||||
private set
|
||||
@@ -167,13 +165,19 @@ class ShopViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
fun checkout(): String {
|
||||
val result = checkoutService.checkout()
|
||||
val cartItems = cartRepository.items()
|
||||
if (cartItems.isEmpty()) {
|
||||
return "购物车为空"
|
||||
}
|
||||
|
||||
val order = orderRepository.createOrder(cartItems)
|
||||
?: return "创建订单失败"
|
||||
|
||||
cartRepository.clear()
|
||||
syncCart()
|
||||
syncOrders()
|
||||
if (result.success) {
|
||||
uiState = uiState.copy(currentTab = Tab.Orders)
|
||||
}
|
||||
return result.message
|
||||
uiState = uiState.copy(currentTab = Tab.Orders)
|
||||
return "下单成功,订单号:${order.orderId}"
|
||||
}
|
||||
|
||||
private fun syncCart() {
|
||||
@@ -181,7 +185,7 @@ class ShopViewModel : ViewModel() {
|
||||
uiState = uiState.copy(
|
||||
cartItems = items,
|
||||
totalCount = items.sumOf { it.quantity },
|
||||
totalPrice = checkoutService.totalPrice()
|
||||
totalPrice = items.sumOf { it.price * it.quantity }
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user