feat: add lesson 7 order flow and orders screen
This commit is contained in:
1 parent
fc8ea48ea1
commit
e42597b8b7
6 files changed
+647
-25
No files matched your search
+486
-9
@@ -1465,7 +1465,486 @@ private fun CartScreen(
|
||||
|
||||
---
|
||||
|
||||
# 十、本节整体顺序(重新整理后的主线)
|
||||
# 十、Step 5:增加 OrderRepository,打通“下单 → 订单列表”闭环
|
||||
|
||||
## 本步目标
|
||||
到这一步,第7节终于开始进入“像真实商城一点”的阶段。
|
||||
|
||||
完成后,学生应该能看到:
|
||||
- 点击结算不再只是随机弹一句提示
|
||||
- 购物车可以真正生成订单
|
||||
- 下单后购物车被清空
|
||||
- 订单列表页能看到刚刚生成的订单
|
||||
|
||||
也就是说,本步的目标不是“理论上支持订单”,
|
||||
而是把最小订单闭环真正跑通。
|
||||
|
||||
---
|
||||
|
||||
## Step 5.1:先补订单模型
|
||||
|
||||
### 为什么还要单独建 Kotlin 模型
|
||||
虽然 SQLDelight 已经能生成查询结果类型,
|
||||
但课堂里还是建议再封装一层:
|
||||
- `ShopOrder`
|
||||
- `OrderItem`
|
||||
|
||||
这样做有两个好处:
|
||||
1. UI 层读起来更直观
|
||||
2. 后面如果数据库字段变了,页面层不一定跟着一起乱
|
||||
|
||||
### 文件路径
|
||||
`shared/src/commonMain/kotlin/com/example/minishop/order/OrderModels.kt`
|
||||
|
||||
### 完整代码
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.order
|
||||
|
||||
data class OrderItem(
|
||||
val productId: String,
|
||||
val title: String,
|
||||
val price: Double,
|
||||
val imageUrl: String,
|
||||
val quantity: Int
|
||||
)
|
||||
|
||||
data class ShopOrder(
|
||||
val orderId: String,
|
||||
val totalPrice: Double,
|
||||
val status: String,
|
||||
val createdAt: Long,
|
||||
val items: List<OrderItem>
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 5.2:增加 `OrderRepository`
|
||||
|
||||
### 为什么这一步不能省
|
||||
很多学生会觉得:
|
||||
“下单的时候直接在 ViewModel 里调用 `ordersQueries.insertOrder()` 不就行了?”
|
||||
|
||||
这节课一定要强调:
|
||||
- 不能让 ViewModel 直接操作数据库细节
|
||||
- 订单的创建过程有多步:
|
||||
- 写订单主表
|
||||
- 写订单明细表
|
||||
- 这种逻辑应该收进 Repository
|
||||
|
||||
### 文件路径
|
||||
`shared/src/commonMain/kotlin/com/example/minishop/order/OrderRepository.kt`
|
||||
|
||||
### 完整代码
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.order
|
||||
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.db.ShopDatabase
|
||||
import com.example.minishop.platform.currentTimeMillis
|
||||
import kotlin.random.Random
|
||||
|
||||
class OrderRepository(
|
||||
private val database: ShopDatabase
|
||||
) {
|
||||
private val queries = database.ordersQueries
|
||||
|
||||
fun createOrder(cartItems: List<CartItem>): ShopOrder? {
|
||||
if (cartItems.isEmpty()) return null
|
||||
|
||||
val orderId = buildOrderId()
|
||||
val createdAt = currentTimeMillis()
|
||||
val totalPrice = cartItems.sumOf { it.price * it.quantity }
|
||||
val items = cartItems.map {
|
||||
OrderItem(
|
||||
productId = it.productId,
|
||||
title = it.title,
|
||||
price = it.price,
|
||||
imageUrl = it.imageUrl,
|
||||
quantity = it.quantity
|
||||
)
|
||||
}
|
||||
|
||||
queries.insertOrder(
|
||||
order_id = orderId,
|
||||
total_price = totalPrice,
|
||||
status = "CREATED",
|
||||
created_at = createdAt
|
||||
)
|
||||
|
||||
items.forEach { item ->
|
||||
queries.insertOrderItem(
|
||||
order_id = orderId,
|
||||
product_id = item.productId,
|
||||
title = item.title,
|
||||
price = item.price,
|
||||
image_url = item.imageUrl,
|
||||
quantity = item.quantity.toLong()
|
||||
)
|
||||
}
|
||||
|
||||
return ShopOrder(
|
||||
orderId = orderId,
|
||||
totalPrice = totalPrice,
|
||||
status = "CREATED",
|
||||
createdAt = createdAt,
|
||||
items = items
|
||||
)
|
||||
}
|
||||
|
||||
fun getOrders(): List<ShopOrder> {
|
||||
return queries.selectOrders().executeAsList().map { order ->
|
||||
val items = queries.selectItemsByOrderId(order.order_id).executeAsList().map { item ->
|
||||
OrderItem(
|
||||
productId = item.product_id,
|
||||
title = item.title,
|
||||
price = item.price,
|
||||
imageUrl = item.image_url,
|
||||
quantity = item.quantity.toInt()
|
||||
)
|
||||
}
|
||||
ShopOrder(
|
||||
orderId = order.order_id,
|
||||
totalPrice = order.total_price,
|
||||
status = order.status,
|
||||
createdAt = order.created_at,
|
||||
items = items
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildOrderId(): String = "ORD-${currentTimeMillis()}-${Random.nextInt(100, 999)}"
|
||||
}
|
||||
```
|
||||
|
||||
### 这一段课堂要强调什么
|
||||
1. `createOrder()` 不只是返回一个对象,而是真的把订单写进数据库
|
||||
2. 订单主表和订单明细表要一起写
|
||||
3. `getOrders()` 负责把数据库查询结果重新组装成适合 UI 使用的结构
|
||||
|
||||
---
|
||||
|
||||
## Step 5.3:`CheckoutService` 从“模拟结算”升级成“生成订单”
|
||||
|
||||
### 为什么这里要改
|
||||
第6节/Step4 的 `CheckoutService` 还停留在:
|
||||
- 随机成功
|
||||
- 随机失败
|
||||
- 成功就清购物车
|
||||
|
||||
这一步要改成更像真实业务的最小流程:
|
||||
- 读取购物车
|
||||
- 创建订单
|
||||
- 清空购物车
|
||||
- 返回订单号
|
||||
|
||||
### 文件路径
|
||||
`shared/src/commonMain/kotlin/com/example/minishop/checkout/CheckoutService.kt`
|
||||
|
||||
### 完整代码
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop.checkout
|
||||
|
||||
import com.example.minishop.cart.CartRepository
|
||||
import com.example.minishop.order.OrderRepository
|
||||
|
||||
data class CheckoutResult(
|
||||
val success: Boolean,
|
||||
val message: String
|
||||
)
|
||||
|
||||
class CheckoutService(
|
||||
private val cartRepository: CartRepository,
|
||||
private val orderRepository: OrderRepository
|
||||
) {
|
||||
fun totalPrice(): Double {
|
||||
return cartRepository.items().sumOf { item ->
|
||||
item.price * item.quantity
|
||||
}
|
||||
}
|
||||
|
||||
fun checkout(): CheckoutResult {
|
||||
val cartItems = cartRepository.items()
|
||||
if (cartItems.isEmpty()) return CheckoutResult(false, "购物车为空")
|
||||
|
||||
val order = orderRepository.createOrder(cartItems)
|
||||
?: return CheckoutResult(false, "创建订单失败")
|
||||
|
||||
cartRepository.clear()
|
||||
return CheckoutResult(true, "下单成功,订单号:${order.orderId}")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 5.4:让 ViewModel 同时管理购物车和订单
|
||||
|
||||
### 为什么 ViewModel 这里要扩一下
|
||||
因为这一步之后,页面上不只要展示:
|
||||
- 商品列表
|
||||
- 购物车
|
||||
|
||||
还要展示:
|
||||
- 订单列表
|
||||
|
||||
所以 `ShopUiState` 里也要加订单状态。
|
||||
|
||||
### 文件路径
|
||||
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
|
||||
|
||||
### 本步关键改动
|
||||
1. 增加 `orders: List<ShopOrder>`
|
||||
2. 增加 `orderRepository`
|
||||
3. `checkout()` 成功后刷新订单列表
|
||||
4. 下单成功后切到订单页
|
||||
|
||||
### 完整代码
|
||||
|
||||
```kotlin
|
||||
package com.example.minishop
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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
|
||||
import com.example.minishop.order.OrderRepository
|
||||
import com.example.minishop.order.ShopOrder
|
||||
import com.example.minishop.repository.ProductRepository
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ShopUiState(
|
||||
val currentTab: Tab = Tab.Home,
|
||||
val inDetail: Boolean = false,
|
||||
val selectedProductId: String? = null,
|
||||
val query: String = "",
|
||||
val products: List<Product> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val loadError: String? = null,
|
||||
val cartItems: List<CartItem> = emptyList(),
|
||||
val totalCount: Int = 0,
|
||||
val totalPrice: Double = 0.0,
|
||||
val orders: List<ShopOrder> = emptyList()
|
||||
)
|
||||
|
||||
class ShopViewModel : ViewModel() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
private val productRepository = ProductRepository(
|
||||
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
|
||||
)
|
||||
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
|
||||
|
||||
val filteredProducts: List<Product>
|
||||
get() {
|
||||
val normalized = uiState.query.trim()
|
||||
return if (normalized.isBlank()) {
|
||||
uiState.products
|
||||
} else {
|
||||
uiState.products.filter {
|
||||
it.title.contains(normalized, ignoreCase = true) ||
|
||||
it.description.contains(normalized, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val selectedProduct: Product?
|
||||
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
|
||||
|
||||
init {
|
||||
refreshProducts()
|
||||
syncCart()
|
||||
syncOrders()
|
||||
}
|
||||
|
||||
fun refreshProducts() {
|
||||
scope.launch {
|
||||
uiState = uiState.copy(loading = true, loadError = null)
|
||||
val list = runCatching { productRepository.getProducts() }
|
||||
.onFailure { uiState = uiState.copy(loadError = it.message ?: "加载失败") }
|
||||
.getOrDefault(emptyList())
|
||||
|
||||
uiState = uiState.copy(products = list, loading = false)
|
||||
syncCart()
|
||||
}
|
||||
}
|
||||
|
||||
fun onQueryChange(value: String) {
|
||||
uiState = uiState.copy(query = value)
|
||||
}
|
||||
|
||||
fun selectTab(tab: Tab) {
|
||||
uiState = uiState.copy(currentTab = tab)
|
||||
}
|
||||
|
||||
fun openDetail(product: Product) {
|
||||
uiState = uiState.copy(inDetail = true, selectedProductId = product.id)
|
||||
}
|
||||
|
||||
fun closeDetail() {
|
||||
uiState = uiState.copy(inDetail = false)
|
||||
}
|
||||
|
||||
fun quantityOf(productId: String): Int =
|
||||
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
|
||||
|
||||
fun addToCart(product: Product): String {
|
||||
cartRepository.add(product)
|
||||
syncCart()
|
||||
return "已加入购物车"
|
||||
}
|
||||
|
||||
fun increase(productId: String) {
|
||||
cartRepository.increase(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun decrease(productId: String) {
|
||||
cartRepository.decrease(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun remove(productId: String) {
|
||||
cartRepository.remove(productId)
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
cartRepository.clear()
|
||||
syncCart()
|
||||
}
|
||||
|
||||
fun checkout(): String {
|
||||
val result = checkoutService.checkout()
|
||||
syncCart()
|
||||
syncOrders()
|
||||
if (result.success) {
|
||||
uiState = uiState.copy(currentTab = Tab.Orders)
|
||||
}
|
||||
return result.message
|
||||
}
|
||||
|
||||
private fun syncCart() {
|
||||
val items = cartRepository.items()
|
||||
uiState = uiState.copy(
|
||||
cartItems = items,
|
||||
totalCount = items.sumOf { it.quantity },
|
||||
totalPrice = checkoutService.totalPrice()
|
||||
)
|
||||
}
|
||||
|
||||
private fun syncOrders() {
|
||||
uiState = uiState.copy(orders = orderRepository.getOrders())
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
scope.cancel()
|
||||
super.onCleared()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 5.5:新增订单列表页
|
||||
|
||||
### 为什么要加这个页面
|
||||
如果这一步只做到“数据库里有订单”,学生是没有感知的。
|
||||
|
||||
课堂一定要让结果可见:
|
||||
- 下单后切到订单页
|
||||
- 页面里能直接看到订单号、总价、商品明细
|
||||
|
||||
这样学生才会真正感觉“订单闭环”做成了。
|
||||
|
||||
### 这一步最小改动思路
|
||||
1. `Tab` 增加 `Orders`
|
||||
2. 底部导航增加“订单”
|
||||
3. 新增 `OrderScreen`
|
||||
4. checkout 成功后自动切过去
|
||||
|
||||
### 推荐的 `OrderScreen`
|
||||
|
||||
```kotlin
|
||||
@Composable
|
||||
private fun OrderScreen(orders: List<ShopOrder>) {
|
||||
if (orders.isEmpty()) {
|
||||
EmptyState("还没有订单")
|
||||
return
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
items(orders) { order ->
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("订单号:${order.orderId}", fontWeight = FontWeight.Bold)
|
||||
Text("状态:${order.status}")
|
||||
Text("总价:¥${formatPrice(order.totalPrice)}")
|
||||
Text("商品数:${order.items.sumOf { it.quantity }}")
|
||||
order.items.forEach { item ->
|
||||
Text("- ${item.title} x${item.quantity}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 5.6:本步验收
|
||||
这一步课堂上至少要看到这些现象:
|
||||
|
||||
1. 商品加购后,购物车里有内容
|
||||
2. 点击“结算”后,不再只是随机提示
|
||||
3. 成功下单后:
|
||||
- 购物车被清空
|
||||
- 订单页能看到新订单
|
||||
4. 订单里能看到商品明细
|
||||
|
||||
如果学生做到这一步,其实第7节最重要的“订单闭环”就已经成立了。
|
||||
|
||||
---
|
||||
|
||||
## Step 5.7:本步小结
|
||||
到这里,第7节最关键的业务成果已经出来了:
|
||||
|
||||
- SQL 不只是替换了 Settings
|
||||
- 它已经真正承载了订单业务
|
||||
- 购物车 → 下单 → 订单列表 形成了完整链路
|
||||
|
||||
接下来就可以进入第7节剩下的两块:
|
||||
- 最小 MVI
|
||||
- 统一错误呈现
|
||||
|
||||
---
|
||||
|
||||
# 十一、本节整体顺序(重新整理后的主线)
|
||||
去掉“离线优先”后,第7节建议严格按下面顺序推进:
|
||||
|
||||
1. **为什么从 Settings 升级到 SQL**
|
||||
@@ -1485,16 +1964,14 @@ private fun CartScreen(
|
||||
|
||||
---
|
||||
|
||||
# 十一、下一步预告(Step 5)
|
||||
下一步开始真正补齐订单闭环:
|
||||
# 十二、下一步预告(Step 6)
|
||||
下一步开始改造商品列表页,把它收成第7节要求的最小 MVI:
|
||||
|
||||
1. 增加 `OrderRepository`
|
||||
2. 下单后写入 `shop_order` 和 `order_item`
|
||||
3. 清空购物车
|
||||
4. 新增订单列表页展示结果
|
||||
1. Intent:加载 / 重试 / 加购
|
||||
2. State:Loading / Success / Error / Empty
|
||||
3. Reducer:状态统一收敛
|
||||
|
||||
并且继续保持本节文档风格:
|
||||
- 先讲为什么
|
||||
- 再贴官方文档
|
||||
- 再给完整代码
|
||||
- 再贴完整代码
|
||||
- 再给验收方式
|
||||
Reference in new issue
Block a user