feat: add lesson 7 order flow and orders screen
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled

This commit is contained in:
OpenClaw committed 2026-03-09 02:25:41 +08:00
1 parent fc8ea48ea1
commit e42597b8b7
6 files changed
+647 -25

No files matched your search

@@ -52,7 +52,7 @@ import com.example.minishop.cart.CartItem
import com.example.minishop.model.Product import com.example.minishop.model.Product
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
enum class Tab { Home, Cart } enum class Tab { Home, Cart, Orders }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -72,7 +72,8 @@ fun App() {
when { when {
ui.inDetail -> "商品详情" ui.inDetail -> "商品详情"
ui.currentTab == Tab.Home -> "KMP Mini Shopping" ui.currentTab == Tab.Home -> "KMP Mini Shopping"
else -> "购物车" ui.currentTab == Tab.Cart -> "购物车"
else -> "订单列表"
} }
) )
}, },
@@ -104,6 +105,12 @@ fun App() {
icon = { Text("🛒") }, icon = { Text("🛒") },
label = { Text("购物车(${ui.totalCount})") } label = { Text("购物车(${ui.totalCount})") }
) )
NavigationBarItem(
selected = ui.currentTab == Tab.Orders,
onClick = { vm.selectTab(Tab.Orders) },
icon = { Text("📦") },
label = { Text("订单") }
)
} }
} }
} }
@@ -141,7 +148,7 @@ fun App() {
onClick = vm::openDetail onClick = vm::openDetail
) )
else -> CartScreen( ui.currentTab == Tab.Cart -> CartScreen(
items = ui.cartItems, items = ui.cartItems,
totalPrice = ui.totalPrice, totalPrice = ui.totalPrice,
onInc = vm::increase, onInc = vm::increase,
@@ -155,6 +162,8 @@ fun App() {
} }
} }
) )
else -> OrderScreen(ui.orders)
} }
} }
} }
@@ -358,6 +367,35 @@ private fun CartScreen(
} }
} }
@Composable
private fun OrderScreen(orders: List<com.example.minishop.order.ShopOrder>) {
if (orders.isEmpty()) {
EmptyState("还没有订单")
return
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
lazyListItems(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}")
}
}
}
}
}
}
@Composable @Composable
private fun ProductCover(url: String) { private fun ProductCover(url: String) {
val coverModifier = Modifier val coverModifier = Modifier
@@ -10,6 +10,8 @@ import com.example.minishop.checkout.CheckoutService
import com.example.minishop.db.createShopDatabase import com.example.minishop.db.createShopDatabase
import com.example.minishop.model.Product import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi 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 com.example.minishop.repository.ProductRepository
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -27,7 +29,8 @@ data class ShopUiState(
val loadError: String? = null, val loadError: String? = null,
val cartItems: List<CartItem> = emptyList(), val cartItems: List<CartItem> = emptyList(),
val totalCount: Int = 0, val totalCount: Int = 0,
val totalPrice: Double = 0.0 val totalPrice: Double = 0.0,
val orders: List<ShopOrder> = emptyList()
) )
class ShopViewModel : ViewModel() { class ShopViewModel : ViewModel() {
@@ -38,7 +41,8 @@ class ShopViewModel : ViewModel() {
) )
private val database = createShopDatabase() private val database = createShopDatabase()
private val cartRepository = CartRepository(database) private val cartRepository = CartRepository(database)
private val checkoutService = CheckoutService(cartRepository) private val orderRepository = OrderRepository(database)
private val checkoutService = CheckoutService(cartRepository, orderRepository)
var uiState by mutableStateOf(ShopUiState()) var uiState by mutableStateOf(ShopUiState())
private set private set
@@ -62,6 +66,7 @@ class ShopViewModel : ViewModel() {
init { init {
refreshProducts() refreshProducts()
syncCart() syncCart()
syncOrders()
} }
fun refreshProducts() { fun refreshProducts() {
@@ -124,6 +129,10 @@ class ShopViewModel : ViewModel() {
fun checkout(): String { fun checkout(): String {
val result = checkoutService.checkout() val result = checkoutService.checkout()
syncCart() syncCart()
syncOrders()
if (result.success) {
uiState = uiState.copy(currentTab = Tab.Orders)
}
return result.message return result.message
} }
@@ -136,6 +145,10 @@ class ShopViewModel : ViewModel() {
) )
} }
private fun syncOrders() {
uiState = uiState.copy(orders = orderRepository.getOrders())
}
override fun onCleared() { override fun onCleared() {
scope.cancel() scope.cancel()
super.onCleared() super.onCleared()
+486 -9
View File
@@ -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节建议严格按下面顺序推进: 去掉“离线优先”后,第7节建议严格按下面顺序推进:
1. **为什么从 Settings 升级到 SQL** 1. **为什么从 Settings 升级到 SQL**
@@ -1485,16 +1964,14 @@ private fun CartScreen(
--- ---
# 十一、下一步预告(Step 5) # 十二、下一步预告(Step 6)
下一步开始真正补齐订单闭环: 下一步开始改造商品列表页,把它收成第7节要求的最小 MVI:
1. 增加 `OrderRepository` 1. Intent:加载 / 重试 / 加购
2. 下单后写入 `shop_order` 和 `order_item` 2. State:Loading / Success / Error / Empty
3. 清空购物车 3. Reducer:状态统一收敛
4. 新增订单列表页展示结果
并且继续保持本节文档风格: 并且继续保持本节文档风格:
- 先讲为什么 - 先讲为什么
- 再贴官方文档 - 再贴完整代码
- 再给完整代码
- 再给验收方式 - 再给验收方式
@@ -1,7 +1,7 @@
package com.example.minishop.checkout package com.example.minishop.checkout
import com.example.minishop.cart.CartRepository import com.example.minishop.cart.CartRepository
import kotlin.random.Random import com.example.minishop.order.OrderRepository
data class CheckoutResult( data class CheckoutResult(
val success: Boolean, val success: Boolean,
@@ -9,7 +9,8 @@ data class CheckoutResult(
) )
class CheckoutService( class CheckoutService(
private val cartRepository: CartRepository private val cartRepository: CartRepository,
private val orderRepository: OrderRepository
) { ) {
fun totalPrice(): Double { fun totalPrice(): Double {
return cartRepository.items().sumOf { item -> return cartRepository.items().sumOf { item ->
@@ -18,15 +19,13 @@ class CheckoutService(
} }
fun checkout(): CheckoutResult { fun checkout(): CheckoutResult {
val total = totalPrice() val cartItems = cartRepository.items()
if (total <= 0.0) return CheckoutResult(false, "购物车为空") if (cartItems.isEmpty()) return CheckoutResult(false, "购物车为空")
val success = Random.nextBoolean() val order = orderRepository.createOrder(cartItems)
return if (success) { ?: return CheckoutResult(false, "创建订单失败")
cartRepository.clear()
CheckoutResult(true, "结算成功(模拟),金额:¥${"%.2f".format(total)}") cartRepository.clear()
} else { return CheckoutResult(true, "下单成功,订单号:${order.orderId}")
CheckoutResult(false, "结算失败(模拟),请重试")
}
} }
} }
@@ -0,0 +1,17 @@
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>
)
@@ -0,0 +1,78 @@
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)}"
}