feat: implement lesson6-7 project changes from Feishu outline
This commit is contained in:
1 parent
f6005e4772
commit
7334f326a3
16 files changed
+333
-132
No files matched your search
@@ -19,51 +19,87 @@ import androidx.compose.material3.NavigationBarItem
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.example.minishop.cart.CartState
|
||||
import com.example.minishop.cart.CartStore
|
||||
import com.example.minishop.data.FakeProductRepository
|
||||
import com.example.minishop.data.FavoriteStore
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.cart.CartRepository
|
||||
import com.example.minishop.checkout.CheckoutService
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.network.ProductApi
|
||||
import com.example.minishop.repository.ProductRepository
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private enum class Tab { Home, Favorites, Cart }
|
||||
private enum class Tab { Home, Cart }
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun App() {
|
||||
MaterialTheme {
|
||||
val repo = remember { FakeProductRepository() }
|
||||
val cartStore = remember { CartStore() }
|
||||
val favoriteStore = remember { FavoriteStore() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
val productRepository = remember {
|
||||
ProductRepository(
|
||||
api = ProductApi(
|
||||
baseUrl = "https://example.com",
|
||||
useMock = true
|
||||
)
|
||||
)
|
||||
}
|
||||
val cartRepository = remember { CartRepository() }
|
||||
val checkoutService = remember { CheckoutService(cartRepository) }
|
||||
|
||||
var currentTab by remember { mutableStateOf(Tab.Home) }
|
||||
var selected by remember { mutableStateOf<Product?>(null) }
|
||||
var inDetail by remember { mutableStateOf(false) }
|
||||
|
||||
var tick by remember { mutableStateOf(0) }
|
||||
var query by remember { mutableStateOf("") }
|
||||
var products by remember { mutableStateOf<List<Product>>(emptyList()) }
|
||||
var loading by remember { mutableStateOf(false) }
|
||||
var loadError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
val allProducts = remember { repo.getProducts() }
|
||||
val products = remember(query, tick) {
|
||||
allProducts.filter {
|
||||
var tick by remember { mutableStateOf(0) }
|
||||
|
||||
fun loadProducts() {
|
||||
scope.launch {
|
||||
loading = true
|
||||
loadError = null
|
||||
val list = runCatching { productRepository.getProducts() }
|
||||
.onFailure { loadError = it.message ?: "加载失败" }
|
||||
.getOrDefault(emptyList())
|
||||
products = list
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { loadProducts() }
|
||||
|
||||
val filteredProducts = remember(products, query) {
|
||||
products.filter {
|
||||
it.title.contains(query, ignoreCase = true) ||
|
||||
it.description.contains(query, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
val favorites = remember(tick) { favoriteStore.all() }
|
||||
val cartState = remember(tick) { cartStore.state() }
|
||||
val cartItems = remember(tick) { cartRepository.items() }
|
||||
val productMap = remember(products) { products.associateBy { it.id } }
|
||||
val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } }
|
||||
val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(productMap) }
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = {
|
||||
@@ -71,7 +107,6 @@ fun App() {
|
||||
when {
|
||||
inDetail -> "商品详情"
|
||||
currentTab == Tab.Home -> "Mini Shopping"
|
||||
currentTab == Tab.Favorites -> "收藏夹"
|
||||
else -> "购物车"
|
||||
}
|
||||
)
|
||||
@@ -90,19 +125,13 @@ fun App() {
|
||||
selected = currentTab == Tab.Home,
|
||||
onClick = { currentTab = Tab.Home },
|
||||
icon = { Text("🏠") },
|
||||
label = { Text("首页") }
|
||||
)
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Favorites,
|
||||
onClick = { currentTab = Tab.Favorites },
|
||||
icon = { Text("❤️") },
|
||||
label = { Text("收藏(${favorites.size})") }
|
||||
label = { Text("商品") }
|
||||
)
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Cart,
|
||||
onClick = { currentTab = Tab.Cart },
|
||||
icon = { Text("🛒") },
|
||||
label = { Text("购物车(${cartState.totalCount})") }
|
||||
label = { Text("购物车($totalCount)") }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -112,28 +141,24 @@ fun App() {
|
||||
when {
|
||||
inDetail -> ProductDetailScreen(
|
||||
product = selected,
|
||||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
||||
onBack = { inDetail = false },
|
||||
onToggleFavorite = {
|
||||
selected?.let {
|
||||
favoriteStore.toggle(it.id)
|
||||
tick++
|
||||
}
|
||||
},
|
||||
quantity = selected?.let { id -> cartItems.firstOrNull { it.productId == id.id }?.quantity } ?: 0,
|
||||
onAdd = {
|
||||
cartStore.add(it)
|
||||
cartRepository.add(it.id)
|
||||
tick++
|
||||
scope.launch { snackbarHostState.showSnackbar("已加入购物车") }
|
||||
}
|
||||
)
|
||||
|
||||
currentTab == Tab.Home -> ProductListScreen(
|
||||
products = products,
|
||||
loading = loading,
|
||||
error = loadError,
|
||||
products = filteredProducts,
|
||||
query = query,
|
||||
quantityOf = { id -> cartItems.firstOrNull { it.productId == id }?.quantity ?: 0 },
|
||||
onQueryChange = { query = it },
|
||||
isFavorite = { favoriteStore.isFavorite(it) },
|
||||
quantityOf = { cartState.quantityOf(it) },
|
||||
onToggleFavorite = { id ->
|
||||
favoriteStore.toggle(id)
|
||||
onRetry = { loadProducts() },
|
||||
onAdd = {
|
||||
cartRepository.add(it.id)
|
||||
tick++
|
||||
},
|
||||
onClick = {
|
||||
@@ -142,25 +167,19 @@ fun App() {
|
||||
}
|
||||
)
|
||||
|
||||
currentTab == Tab.Favorites -> FavoriteScreen(
|
||||
products = allProducts.filter { favoriteStore.isFavorite(it.id) },
|
||||
quantityOf = { cartState.quantityOf(it) },
|
||||
onOpen = {
|
||||
selected = it
|
||||
inDetail = true
|
||||
},
|
||||
onAdd = {
|
||||
cartStore.add(it)
|
||||
tick++
|
||||
}
|
||||
)
|
||||
|
||||
else -> CartScreen(
|
||||
cartState = cartState,
|
||||
onInc = { id -> cartStore.increase(id); tick++ },
|
||||
onDec = { id -> cartStore.decrease(id); tick++ },
|
||||
onRemove = { id -> cartStore.remove(id); tick++ },
|
||||
onClear = { cartStore.clear(); tick++ }
|
||||
items = cartItems,
|
||||
productMap = productMap,
|
||||
totalPrice = totalPrice,
|
||||
onInc = { id -> cartRepository.increase(id); tick++ },
|
||||
onDec = { id -> cartRepository.decrease(id); tick++ },
|
||||
onRemove = { id -> cartRepository.remove(id); tick++ },
|
||||
onClear = { cartRepository.clear(); tick++ },
|
||||
onCheckout = {
|
||||
val result = checkoutService.checkout(productMap)
|
||||
tick++
|
||||
scope.launch { snackbarHostState.showSnackbar(result.message) }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -170,12 +189,14 @@ fun App() {
|
||||
|
||||
@Composable
|
||||
private fun ProductListScreen(
|
||||
loading: Boolean,
|
||||
error: String?,
|
||||
products: List<Product>,
|
||||
query: String,
|
||||
onQueryChange: (String) -> Unit,
|
||||
isFavorite: (String) -> Boolean,
|
||||
quantityOf: (String) -> Int,
|
||||
onToggleFavorite: (String) -> Unit,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onRetry: () -> Unit,
|
||||
onAdd: (Product) -> Unit,
|
||||
onClick: (Product) -> Unit
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
@@ -188,25 +209,31 @@ private fun ProductListScreen(
|
||||
placeholder = { Text("输入标题或描述") }
|
||||
)
|
||||
|
||||
if (products.isEmpty()) {
|
||||
EmptyState("没有匹配的商品")
|
||||
} else {
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(products) { p ->
|
||||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
||||
Text("¥${formatPrice(p.price)}")
|
||||
}
|
||||
Text(p.description, style = MaterialTheme.typography.bodySmall)
|
||||
when {
|
||||
loading -> EmptyState("加载中...")
|
||||
error != null -> {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("加载失败:$error")
|
||||
Button(onClick = onRetry) { Text("重试") }
|
||||
}
|
||||
}
|
||||
products.isEmpty() -> EmptyState("没有匹配的商品")
|
||||
else -> {
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(products) { p ->
|
||||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
||||
Text("¥${formatPrice(p.price)}")
|
||||
}
|
||||
Text(p.description, style = MaterialTheme.typography.bodySmall)
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { onToggleFavorite(p.id) }) {
|
||||
Text(if (isFavorite(p.id)) "已收藏" else "收藏")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAdd(p) }) { Text("加入购物车") }
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) Text("已加购 x$q", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) Text("已加购 x$q", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,9 +246,7 @@ private fun ProductListScreen(
|
||||
@Composable
|
||||
private fun ProductDetailScreen(
|
||||
product: Product?,
|
||||
isFavorite: Boolean,
|
||||
onBack: () -> Unit,
|
||||
onToggleFavorite: () -> Unit,
|
||||
quantity: Int,
|
||||
onAdd: (Product) -> Unit
|
||||
) {
|
||||
if (product == null) {
|
||||
@@ -233,81 +258,57 @@ private fun ProductDetailScreen(
|
||||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
||||
Text("价格:¥${formatPrice(product.price)}")
|
||||
Text(product.description)
|
||||
if (quantity > 0) Text("当前已加购:$quantity")
|
||||
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = onBack) { Text("返回") }
|
||||
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
||||
OutlinedButton(onClick = onToggleFavorite) {
|
||||
Text(if (isFavorite) "取消收藏" else "收藏")
|
||||
}
|
||||
}
|
||||
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CartScreen(
|
||||
cartState: CartState,
|
||||
items: List<CartItem>,
|
||||
productMap: Map<String, Product>,
|
||||
totalPrice: Double,
|
||||
onInc: (String) -> Unit,
|
||||
onDec: (String) -> Unit,
|
||||
onRemove: (String) -> Unit,
|
||||
onClear: () -> Unit
|
||||
onClear: () -> Unit,
|
||||
onCheckout: () -> Unit
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (cartState.items.isNotEmpty()) {
|
||||
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
||||
if (items.isNotEmpty()) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
||||
Button(onClick = onCheckout) { Text("结算") }
|
||||
}
|
||||
}
|
||||
|
||||
if (cartState.items.isEmpty()) {
|
||||
if (items.isEmpty()) {
|
||||
EmptyState("购物车为空")
|
||||
} else {
|
||||
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(cartState.items) { item ->
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
Text(item.product.title)
|
||||
Text("¥${formatPrice(item.product.price * item.quantity)}")
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
OutlinedButton(onClick = { onDec(item.product.id) }) { Text("-") }
|
||||
Text("数量 ${item.quantity}")
|
||||
OutlinedButton(onClick = { onInc(item.product.id) }) { Text("+") }
|
||||
OutlinedButton(onClick = { onRemove(item.product.id) }) { Text("移除") }
|
||||
items(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)
|
||||
Text("¥${formatPrice(product.price * item.quantity)}")
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
OutlinedButton(onClick = { onDec(product.id) }) { Text("-") }
|
||||
Text("数量 ${item.quantity}")
|
||||
OutlinedButton(onClick = { onInc(product.id) }) { Text("+") }
|
||||
OutlinedButton(onClick = { onRemove(product.id) }) { Text("移除") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("总件数:${cartState.totalCount}")
|
||||
Text("合计:¥${formatPrice(cartState.totalPrice)}", style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FavoriteScreen(
|
||||
products: List<Product>,
|
||||
quantityOf: (String) -> Int,
|
||||
onOpen: (Product) -> Unit,
|
||||
onAdd: (Product) -> Unit
|
||||
) {
|
||||
if (products.isEmpty()) {
|
||||
EmptyState("你还没有收藏课程")
|
||||
} else {
|
||||
LazyColumn(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
items(products) { p ->
|
||||
ElevatedCard(onClick = { onOpen(p) }, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
||||
Text("¥${formatPrice(p.price)}")
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Button(onClick = { onAdd(p) }) { Text("加入购物车") }
|
||||
val q = quantityOf(p.id)
|
||||
if (q > 0) Text("已加购 x$q")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text("总件数:${items.sumOf { it.quantity }}")
|
||||
Text("合计:¥${formatPrice(totalPrice)}", style = MaterialTheme.typography.titleMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ kotlin = "2.2.0"
|
||||
kotlinx-serialization = "1.8.1"
|
||||
ksp = "2.2.0-2.0.2"
|
||||
ktor = "3.1.3"
|
||||
multiplatform-settings = "1.1.1"
|
||||
|
||||
[libraries]
|
||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
|
||||
@@ -31,6 +32,7 @@ ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
|
||||
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
|
||||
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
|
||||
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
|
||||
multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatform-settings" }
|
||||
|
||||
[plugins]
|
||||
androidApplication = { id = "com.android.application", version.ref = "agp" }
|
||||
|
||||
@@ -39,6 +39,7 @@ kotlin {
|
||||
implementation(libs.ktor.client.core)
|
||||
implementation(libs.ktor.client.content.negotiation)
|
||||
implementation(libs.ktor.serialization.kotlinx.json)
|
||||
implementation(libs.multiplatform.settings.no.arg)
|
||||
implementation(libs.koin.core)
|
||||
api(libs.kmp.observable.viewmodel)
|
||||
}
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.okhttp.OkHttp
|
||||
|
||||
actual fun provideHttpEngine(): HttpClientEngine = OkHttp.create()
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
actual fun platformName(): String = "Android"
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.example.minishop.cart
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class CartItem(
|
||||
val productId: String,
|
||||
val quantity: Int
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.minishop.cart
|
||||
|
||||
class CartRepository(
|
||||
private val storage: CartStorage = CartStorage()
|
||||
) {
|
||||
private val map = storage.load().associateBy { it.productId }.toMutableMap()
|
||||
|
||||
fun items(): List<CartItem> = map.values.sortedBy { it.productId }
|
||||
|
||||
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 increase(productId: String) {
|
||||
val old = map[productId] ?: return
|
||||
map[productId] = old.copy(quantity = old.quantity + 1)
|
||||
persist()
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
fun remove(productId: String) {
|
||||
map.remove(productId)
|
||||
persist()
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
map.clear()
|
||||
persist()
|
||||
}
|
||||
|
||||
private fun persist() {
|
||||
storage.save(items())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.example.minishop.checkout
|
||||
|
||||
import com.example.minishop.cart.CartRepository
|
||||
import com.example.minishop.model.Product
|
||||
import kotlin.random.Random
|
||||
|
||||
data class CheckoutResult(
|
||||
val success: Boolean,
|
||||
val message: String
|
||||
)
|
||||
|
||||
class CheckoutService(
|
||||
private val cartRepository: CartRepository
|
||||
) {
|
||||
fun totalPrice(productMap: Map<String, Product>): Double {
|
||||
return cartRepository.items().sumOf { item ->
|
||||
val product = productMap[item.productId] ?: return@sumOf 0.0
|
||||
product.price * item.quantity
|
||||
}
|
||||
}
|
||||
|
||||
fun checkout(productMap: Map<String, Product>): CheckoutResult {
|
||||
val total = totalPrice(productMap)
|
||||
if (total <= 0.0) return CheckoutResult(false, "购物车为空")
|
||||
|
||||
val success = Random.nextBoolean()
|
||||
return if (success) {
|
||||
cartRepository.clear()
|
||||
CheckoutResult(true, "结算成功(模拟),金额:¥${"%.2f".format(total)}")
|
||||
} else {
|
||||
CheckoutResult(false, "结算失败(模拟),请重试")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
package com.example.minishop.model
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class Product(
|
||||
@SerialName("id")
|
||||
val id: String,
|
||||
@SerialName("title")
|
||||
val title: String,
|
||||
@SerialName("price")
|
||||
val price: Double,
|
||||
@SerialName("description")
|
||||
val description: String
|
||||
)
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
|
||||
import io.ktor.serialization.kotlinx.json.json
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
expect fun provideHttpEngine(): HttpClientEngine
|
||||
|
||||
fun createHttpClient(): HttpClient = HttpClient(provideHttpEngine()) {
|
||||
install(ContentNegotiation) {
|
||||
json(
|
||||
Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.call.body
|
||||
import io.ktor.client.request.get
|
||||
|
||||
class ProductApi(
|
||||
private val baseUrl: String,
|
||||
private val useMock: Boolean = true,
|
||||
private val client: HttpClient = createHttpClient()
|
||||
) {
|
||||
suspend fun fetchProducts(): List<Product> {
|
||||
if (useMock) return mockProducts()
|
||||
return client.get("$baseUrl/products").body()
|
||||
}
|
||||
|
||||
private fun mockProducts(): List<Product> = listOf(
|
||||
Product("1", "KMP 入门课", 99.0, "跨平台开发基础课程"),
|
||||
Product("2", "Compose 实战课", 149.0, "Compose 多端 UI 实战"),
|
||||
Product("3", "Kotlin 协程训练营", 129.0, "协程与 Flow 进阶"),
|
||||
Product("4", "Clean 架构速成", 199.0, "从0构建可维护架构"),
|
||||
Product("5", "SQLDelight 实战", 119.0, "KMP 本地数据库方案"),
|
||||
Product("6", "Ktor API 实战", 159.0, "跨平台网络层搭建")
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
expect fun platformName(): String
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.example.minishop.repository
|
||||
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.network.ProductApi
|
||||
|
||||
class ProductRepository(
|
||||
private val api: ProductApi,
|
||||
private val fallback: List<Product> = emptyList()
|
||||
) {
|
||||
suspend fun getProducts(): List<Product> {
|
||||
return runCatching { api.fetchProducts() }.getOrDefault(fallback)
|
||||
}
|
||||
|
||||
suspend fun getProductDetail(id: String): Product? {
|
||||
return getProducts().firstOrNull { it.id == id }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.example.minishop.network
|
||||
|
||||
import io.ktor.client.engine.HttpClientEngine
|
||||
import io.ktor.client.engine.darwin.Darwin
|
||||
|
||||
actual fun provideHttpEngine(): HttpClientEngine = Darwin.create()
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.example.minishop.platform
|
||||
|
||||
actual fun platformName(): String = "iOS"
|
||||
Reference in new issue
Block a user