feat: migrate lesson 7 cart flow from settings to sql
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 00:44:57 +08:00
1 parent a5120b3e8a
commit 4f32be7077
12 files changed
+811 -80

No files matched your search

@@ -119,7 +119,7 @@ fun App() {
product = vm.selectedProduct,
quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
onAdd = {
val msg = vm.addToCart(it.id)
val msg = vm.addToCart(it)
scope.launch {
snackbarHostState.showSnackbar(msg)
}
@@ -136,14 +136,13 @@ fun App() {
onQueryChange = vm::onQueryChange,
onRetry = vm::refreshProducts,
onAdd = {
vm.addToCart(it.id)
vm.addToCart(it)
},
onClick = vm::openDetail
)
else -> CartScreen(
items = ui.cartItems,
productMap = ui.products.associateBy { it.id },
totalPrice = ui.totalPrice,
onInc = vm::increase,
onDec = vm::decrease,
@@ -294,7 +293,6 @@ private fun ProductDetailScreen(
@Composable
private fun CartScreen(
items: List<CartItem>,
productMap: Map<String, Product>,
totalPrice: Double,
onInc: (String) -> Unit,
onDec: (String) -> Unit,
@@ -315,21 +313,18 @@ private fun CartScreen(
contentPadding = PaddingValues(bottom = 96.dp)
) {
lazyListItems(items) { item ->
val product = productMap[item.productId]
if (product != null) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(product.title, fontWeight = FontWeight.Medium)
Text("¥${formatPrice(product.price * item.quantity)}")
}
Row(verticalAlignment = Alignment.CenterVertically) {
SmallOpButton("-") { onDec(product.id) }
Text(" ${item.quantity} ")
SmallOpButton("+") { onInc(product.id) }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(product.id) }) { Text("移除") }
}
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(item.title, fontWeight = FontWeight.Medium)
Text("¥${formatPrice(item.price * item.quantity)}")
}
Row(verticalAlignment = Alignment.CenterVertically) {
SmallOpButton("-") { onDec(item.productId) }
Text(" ${item.quantity} ")
SmallOpButton("+") { onInc(item.productId) }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
}
}
}
@@ -3,10 +3,12 @@ package com.example.minishop
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.minishop.db.initAppContext
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initAppContext(applicationContext)
setContent {
App()
}
@@ -7,6 +7,7 @@ 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.repository.ProductRepository
@@ -35,7 +36,8 @@ class ShopViewModel : ViewModel() {
private val productRepository = ProductRepository(
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
private val cartRepository = CartRepository()
private val database = createShopDatabase()
private val cartRepository = CartRepository(database)
private val checkoutService = CheckoutService(cartRepository)
var uiState by mutableStateOf(ShopUiState())
@@ -93,8 +95,8 @@ class ShopViewModel : ViewModel() {
fun quantityOf(productId: String): Int =
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
fun addToCart(productId: String): String {
cartRepository.add(productId)
fun addToCart(product: Product): String {
cartRepository.add(product)
syncCart()
return "已加入购物车"
}
@@ -120,19 +122,17 @@ class ShopViewModel : ViewModel() {
}
fun checkout(): String {
val productMap = uiState.products.associateBy { it.id }
val result = checkoutService.checkout(productMap)
val result = checkoutService.checkout()
syncCart()
return result.message
}
private fun syncCart() {
val items = cartRepository.items()
val productMap = uiState.products.associateBy { it.id }
uiState = uiState.copy(
cartItems = items,
totalCount = items.sumOf { it.quantity },
totalPrice = checkoutService.totalPrice(productMap)
totalPrice = checkoutService.totalPrice()
)
}
+680 -6
View File
@@ -757,7 +757,680 @@ ordersQueries
---
# 九、本节整体顺序(重新整理后的主线)
# 九、Step 4:把 CartRepository 从 Settings 改成 SQL
## 本步目标
这一部分是第7节真正开始“把业务接到 SQL 上”。
完成后,学生应该能理解:
1. 为什么 Repository 仍然要保留
2. 为什么不是 UI 直接调用 SQLDelight 生成的 Queries
3. 购物车从 Settings 切到 SQL 时,哪些代码要一起调整
本步会改到这些文件:
1. `shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.kt`
2. `shared/src/androidMain/kotlin/com/example/minishop/db/AppContext.kt`
3. `shared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.kt`
4. `shared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.kt`
5. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
6. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.kt`
7. `shared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.kt`
8. `shared/src/commonMain/kotlin/com/example/minishop/checkout/CheckoutService.kt`
9. `composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
10. `composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
11. `composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
---
## Step 4.1:先补数据库入口(DatabaseFactory)
### 为什么这一步必须先做
前面虽然已经写好了 `.sq` 文件,
但如果没有数据库 driver 和数据库实例入口,`CartRepository` 根本没法拿到:
```kotlin
ShopDatabase
```
所以这一小步不是“附属工作”,而是 SQL 版 Repository 的前置条件。
### 文件1:`shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.kt`
```kotlin
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
expect class DatabaseFactory {
fun createDriver(): SqlDriver
}
fun createShopDatabase(factory: DatabaseFactory = DatabaseFactory()): ShopDatabase {
return ShopDatabase(factory.createDriver())
}
```
### 文件2:`shared/src/androidMain/kotlin/com/example/minishop/db/AppContext.kt`
```kotlin
package com.example.minishop.db
import android.content.Context
lateinit var appContext: Context
private set
fun initAppContext(context: Context) {
appContext = context.applicationContext
}
```
### 文件3:`shared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.kt`
```kotlin
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
actual class DatabaseFactory {
actual fun createDriver(): SqlDriver {
return AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
}
}
```
### 文件4:`shared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.kt`
```kotlin
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
actual class DatabaseFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(ShopDatabase.Schema, "shop.db")
}
}
```
### 这一段课堂要强调什么
- `expect / actual` 是 KMP 平台实现差异的典型用法
- 公共层只关心“我要一个 driver”
- Android / iOS 各自决定 driver 怎么创建
---
## Step 4.2:把 `CartItem` 从“极简数量模型”升级成“可展示购物车模型”
### 为什么要改 `CartItem`
第6节的 `CartItem` 只需要:
- `productId`
- `quantity`
因为当时只是把购物车用 Settings 存起来。
但第7节切到 SQL 后,购物车表里已经存了:
- 标题
- 单价
- 图片
所以 `CartItem` 也应该升级成更适合 UI 和业务层使用的结构。
### 文件路径
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt`
### 完整代码
```kotlin
package com.example.minishop.cart
data class CartItem(
val productId: String,
val quantity: Int,
val title: String,
val price: Double,
val imageUrl: String
)
```
### 课堂要点
这里可以顺手提醒学生:
- SQL 层字段是下划线命名
- Kotlin 层模型还是 camelCase 更顺手
- Repository 的职责之一,就是做这种映射
---
## Step 4.3:把 `CartRepository` 改成 SQL 版
### 为什么 Repository 不能删掉
很多学生会问:
既然 SQLDelight 已经生成 `cartQueries` 了,为什么不直接在页面里调用?
这里要明确讲:
- UI 不应该直接碰数据库
- Repository 是数据访问的统一入口
- 后面如果 SQL 再变、规则再变,上层不用大改
### 文件路径
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.kt`
### 完整代码
```kotlin
package com.example.minishop.cart
import com.example.minishop.db.ShopDatabase
import com.example.minishop.model.Product
import kotlinx.datetime.Clock
class CartRepository(
private val database: ShopDatabase
) {
private val queries = database.cartQueries
fun items(): List<CartItem> {
return queries.selectAll().executeAsList().map {
CartItem(
productId = it.product_id,
quantity = it.quantity.toInt(),
title = it.title,
price = it.price,
imageUrl = it.image_url
)
}
}
fun add(product: Product) {
val current = queries.selectById(product.id).executeAsOneOrNull()
val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
upsert(product, nextQuantity)
}
fun increase(productId: String) {
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
queries.insertOrReplace(
product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = current.quantity + 1,
updated_at = nowMillis()
)
}
fun decrease(productId: String) {
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
val next = current.quantity.toInt() - 1
if (next <= 0) {
queries.deleteById(productId)
} else {
queries.insertOrReplace(
product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = next.toLong(),
updated_at = nowMillis()
)
}
}
fun remove(productId: String) {
queries.deleteById(productId)
}
fun clear() {
queries.deleteAll()
}
private fun upsert(product: Product, quantity: Int) {
queries.insertOrReplace(
product_id = product.id,
title = product.title,
price = product.price,
image_url = product.imageUrl,
quantity = quantity.toLong(),
updated_at = nowMillis()
)
}
private fun nowMillis(): Long = Clock.System.now().toEpochMilliseconds()
}
```
### 这一段课堂要强调什么
1. `items()` 负责把 SQL 行映射成 `CartItem`
2. `add(product: Product)` 改成接收整个商品,而不是只传 `productId`
3. 因为现在购物车表要把展示字段一起存下来
---
## Step 4.4:旧的 `CartStorage` 怎么处理
### 为什么要处理这个文件
如果这个文件继续保留第6节的序列化实现,
它会和新的 `CartItem` 结构不一致。
所以这一步建议直接改成“保留文件名,但不再承担实际功能”,
既能让学生知道第6节方案已经退场,
也不会让项目因为旧代码报错。
### 文件路径
`shared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.kt`
### 完整代码
```kotlin
package com.example.minishop.cart
@Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
class CartStorage
```
### 课堂说明
你可以直接告诉学生:
- 第6节它是真的在用
- 第7节开始它只是“历史痕迹”
- 这节课的真实购物车持久化已经交给 SQLDelight 了
---
## Step 4.5:把 `CheckoutService` 改成适配 SQL 版购物车
### 为什么这里也要改
第6节 `CheckoutService` 的总价计算,是通过:
- `productMap[productId]`
- 再去拿商品价格
但现在 `CartItem` 本身已经有:
- `price`
- `title`
- `imageUrl`
所以总价计算就没必要再绕回商品列表。
### 文件路径
`shared/src/commonMain/kotlin/com/example/minishop/checkout/CheckoutService.kt`
### 完整代码
```kotlin
package com.example.minishop.checkout
import com.example.minishop.cart.CartRepository
import kotlin.random.Random
data class CheckoutResult(
val success: Boolean,
val message: String
)
class CheckoutService(
private val cartRepository: CartRepository
) {
fun totalPrice(): Double {
return cartRepository.items().sumOf { item ->
item.price * item.quantity
}
}
fun checkout(): CheckoutResult {
val total = totalPrice()
if (total <= 0.0) return CheckoutResult(false, "购物车为空")
val success = Random.nextBoolean()
return if (success) {
cartRepository.clear()
CheckoutResult(true, "结算成功(模拟),金额:¥${"%.2f".format(total)}")
} else {
CheckoutResult(false, "结算失败(模拟),请重试")
}
}
}
```
---
## Step 4.6:Android 入口补上 `appContext`
### 为什么这一步不能漏
因为 Android 版 `DatabaseFactory` 用到了:
```kotlin
AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
```
所以应用启动时必须先初始化 `appContext`。
### 文件路径
`composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
### 完整代码
```kotlin
package com.example.minishop
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.minishop.db.initAppContext
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initAppContext(applicationContext)
setContent {
App()
}
}
}
```
---
## Step 4.7:让 `ShopViewModel` 接 SQL 版购物车
### 为什么 ViewModel 也得改
因为 `CartRepository` 的构造方式已经变了:
- 以前:`CartRepository()`
- 现在:`CartRepository(database)`
并且加购方法也变了:
- 以前:`add(productId)`
- 现在:`add(product)`
### 文件路径
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
### 完整代码
```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.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
)
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 checkoutService = CheckoutService(cartRepository)
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()
}
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()
return result.message
}
private fun syncCart() {
val items = cartRepository.items()
uiState = uiState.copy(
cartItems = items,
totalCount = items.sumOf { it.quantity },
totalPrice = checkoutService.totalPrice()
)
}
override fun onCleared() {
scope.cancel()
super.onCleared()
}
}
```
---
## Step 4.8:让 `App.kt` 使用 SQL 版 `CartItem`
### 为什么 UI 这里也要微调
因为现在购物车项里已经带了:
- `title`
- `price`
所以购物车页没必要再依赖 `productMap` 才能展示标题和金额。
### 这一步课堂建议
这一段不要整文件重贴,学生太容易淹死。
你可以只告诉学生改这两处:
#### 改动1:商品列表和详情页的加购回调
把:
```kotlin
vm.addToCart(it.id)
```
改成:
```kotlin
vm.addToCart(it)
```
#### 改动2:购物车页直接使用 `CartItem` 自带字段
把 `CartScreen` 的参数从:
```kotlin
productMap: Map<String, Product>
```
收掉,改为直接使用:
- `item.title`
- `item.price`
### 推荐替换后的 `CartScreen`
```kotlin
@Composable
private fun CartScreen(
items: List<CartItem>,
totalPrice: Double,
onInc: (String) -> Unit,
onDec: (String) -> Unit,
onRemove: (String) -> Unit,
onClear: () -> Unit,
onCheckout: () -> Unit
) {
Box(
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
if (items.isEmpty()) {
EmptyState("购物车为空")
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(bottom = 96.dp)
) {
items(items) { item ->
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(item.title, fontWeight = FontWeight.Medium)
Text("¥${formatPrice(item.price * item.quantity)}")
}
Row(verticalAlignment = Alignment.CenterVertically) {
SmallOpButton("-") { onDec(item.productId) }
Text(" ${item.quantity} ")
SmallOpButton("+") { onInc(item.productId) }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
}
}
}
}
}
Card(
modifier = Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text("总件数:${items.sumOf { it.quantity }}")
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = onClear) { Text("清空") }
Button(onClick = onCheckout) { Text("结算") }
}
}
}
}
}
}
```
---
## Step 4.9:本步验收
到这一步,课堂上至少要看到这些结果:
- 加购之后,购物车记录来自 SQL 表,而不是 Settings
- 重启 App 后,购物车数据还能恢复
- 购物车页能直接显示标题、数量、金额
- `CartRepository` 已经不再依赖第6节的 `CartStorage`
---
## Step 4.10:本步小结
到这里,学生已经完成第7节里第一个真正的数据层升级动作:
- SQL 表不是只写着摆设
- 购物车已经真正切到 SQL
- UI 仍然通过 Repository 拿数据
- ViewModel 和页面只是做最小适配
接下来下一步,就可以开始新增 `OrderRepository`,把“下单 → 订单列表”闭环接起来。
---
# 十、本节整体顺序(重新整理后的主线)
去掉“离线优先”后,第7节建议严格按下面顺序推进:
1. **为什么从 Settings 升级到 SQL**
@@ -777,12 +1450,13 @@ ordersQueries
---
# 十、下一步预告(Step 4)
下一步开始真正把业务代码接上:
# 十一、下一步预告(Step 5)
下一步开始真正补齐订单闭环:
1. 把 `CartRepository` 从 Settings 改成 SQL
2. 增加 `OrderRepository`
3. 让“购物车 → 下单 → 订单列表”开始跑通
1. 增加 `OrderRepository`
2. 下单后写入 `shop_order` 和 `order_item`
3. 清空购物车
4. 新增订单列表页展示结果
并且继续保持本节文档风格:
- 先讲为什么
@@ -0,0 +1,10 @@
package com.example.minishop.db
import android.content.Context
lateinit var appContext: Context
private set
fun initAppContext(context: Context) {
appContext = context.applicationContext
}
@@ -0,0 +1,10 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
actual class DatabaseFactory {
actual fun createDriver(): SqlDriver {
return AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
}
}
@@ -1,9 +1,9 @@
package com.example.minishop.cart
import kotlinx.serialization.Serializable
@Serializable
data class CartItem(
val productId: String,
val quantity: Int
val quantity: Int,
val title: String,
val price: Double,
val imageUrl: String
)
@@ -1,41 +1,79 @@
package com.example.minishop.cart
import com.example.minishop.db.ShopDatabase
import com.example.minishop.model.Product
import kotlinx.datetime.Clock
class CartRepository(
private val storage: CartStorage = CartStorage()
private val database: ShopDatabase
) {
private val map = storage.load().associateBy { it.productId }.toMutableMap()
private val queries = database.cartQueries
fun items(): List<CartItem> = map.values.sortedBy { it.productId }
fun items(): List<CartItem> {
return queries.selectAll().executeAsList().map {
CartItem(
productId = it.product_id,
quantity = it.quantity.toInt(),
title = it.title,
price = it.price,
imageUrl = it.image_url
)
}
}
fun add(productId: String) {
val old = map[productId]
map[productId] = if (old == null) CartItem(productId, 1) else old.copy(quantity = old.quantity + 1)
persist()
fun add(product: Product) {
val current = queries.selectById(product.id).executeAsOneOrNull()
val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
upsert(product, nextQuantity)
}
fun increase(productId: String) {
val old = map[productId] ?: return
map[productId] = old.copy(quantity = old.quantity + 1)
persist()
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
queries.insertOrReplace(
product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = current.quantity + 1,
updated_at = nowMillis()
)
}
fun decrease(productId: String) {
val old = map[productId] ?: return
if (old.quantity <= 1) map.remove(productId) else map[productId] = old.copy(quantity = old.quantity - 1)
persist()
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
val next = current.quantity.toInt() - 1
if (next <= 0) {
queries.deleteById(productId)
} else {
queries.insertOrReplace(
product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = next.toLong(),
updated_at = nowMillis()
)
}
}
fun remove(productId: String) {
map.remove(productId)
persist()
queries.deleteById(productId)
}
fun clear() {
map.clear()
persist()
queries.deleteAll()
}
private fun persist() {
storage.save(items())
private fun upsert(product: Product, quantity: Int) {
queries.insertOrReplace(
product_id = product.id,
title = product.title,
price = product.price,
image_url = product.imageUrl,
quantity = quantity.toLong(),
updated_at = nowMillis()
)
}
private fun nowMillis(): Long = Clock.System.now().toEpochMilliseconds()
}
@@ -1,21 +1,4 @@
package com.example.minishop.cart
import com.russhwolf.settings.Settings
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class CartStorage(
private val settings: Settings = Settings(),
private val json: Json = Json { ignoreUnknownKeys = true }
) {
private val key = "cart_items"
fun load(): List<CartItem> {
val raw = settings.getStringOrNull(key) ?: return emptyList()
return runCatching { json.decodeFromString<List<CartItem>>(raw) }.getOrElse { emptyList() }
}
fun save(items: List<CartItem>) {
settings.putString(key, json.encodeToString(items))
}
}
@Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
class CartStorage
@@ -1,7 +1,6 @@
package com.example.minishop.checkout
import com.example.minishop.cart.CartRepository
import com.example.minishop.model.Product
import kotlin.random.Random
data class CheckoutResult(
@@ -12,15 +11,14 @@ data class CheckoutResult(
class CheckoutService(
private val cartRepository: CartRepository
) {
fun totalPrice(productMap: Map<String, Product>): Double {
fun totalPrice(): Double {
return cartRepository.items().sumOf { item ->
val product = productMap[item.productId] ?: return@sumOf 0.0
product.price * item.quantity
item.price * item.quantity
}
}
fun checkout(productMap: Map<String, Product>): CheckoutResult {
val total = totalPrice(productMap)
fun checkout(): CheckoutResult {
val total = totalPrice()
if (total <= 0.0) return CheckoutResult(false, "购物车为空")
val success = Random.nextBoolean()
@@ -0,0 +1,11 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
expect class DatabaseFactory {
fun createDriver(): SqlDriver
}
fun createShopDatabase(factory: DatabaseFactory = DatabaseFactory()): ShopDatabase {
return ShopDatabase(factory.createDriver())
}
@@ -0,0 +1,10 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
actual class DatabaseFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(ShopDatabase.Schema, "shop.db")
}
}