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.OutlinedButton
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Scaffold
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.SnackbarHost
|
||||||
|
import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.example.minishop.cart.CartState
|
import com.example.minishop.cart.CartItem
|
||||||
import com.example.minishop.cart.CartStore
|
import com.example.minishop.cart.CartRepository
|
||||||
import com.example.minishop.data.FakeProductRepository
|
import com.example.minishop.checkout.CheckoutService
|
||||||
import com.example.minishop.data.FavoriteStore
|
|
||||||
import com.example.minishop.model.Product
|
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)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun App() {
|
fun App() {
|
||||||
MaterialTheme {
|
MaterialTheme {
|
||||||
val repo = remember { FakeProductRepository() }
|
val scope = rememberCoroutineScope()
|
||||||
val cartStore = remember { CartStore() }
|
val snackbarHostState = remember { SnackbarHostState() }
|
||||||
val favoriteStore = remember { FavoriteStore() }
|
|
||||||
|
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 currentTab by remember { mutableStateOf(Tab.Home) }
|
||||||
var selected by remember { mutableStateOf<Product?>(null) }
|
var selected by remember { mutableStateOf<Product?>(null) }
|
||||||
var inDetail by remember { mutableStateOf(false) }
|
var inDetail by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
var tick by remember { mutableStateOf(0) }
|
|
||||||
var query by remember { mutableStateOf("") }
|
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() }
|
var tick by remember { mutableStateOf(0) }
|
||||||
val products = remember(query, tick) {
|
|
||||||
allProducts.filter {
|
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.title.contains(query, ignoreCase = true) ||
|
||||||
it.description.contains(query, ignoreCase = true)
|
it.description.contains(query, ignoreCase = true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val favorites = remember(tick) { favoriteStore.all() }
|
val cartItems = remember(tick) { cartRepository.items() }
|
||||||
val cartState = remember(tick) { cartStore.state() }
|
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(
|
Scaffold(
|
||||||
|
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||||
topBar = {
|
topBar = {
|
||||||
TopAppBar(
|
TopAppBar(
|
||||||
title = {
|
title = {
|
||||||
@@ -71,7 +107,6 @@ fun App() {
|
|||||||
when {
|
when {
|
||||||
inDetail -> "商品详情"
|
inDetail -> "商品详情"
|
||||||
currentTab == Tab.Home -> "Mini Shopping"
|
currentTab == Tab.Home -> "Mini Shopping"
|
||||||
currentTab == Tab.Favorites -> "收藏夹"
|
|
||||||
else -> "购物车"
|
else -> "购物车"
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -90,19 +125,13 @@ fun App() {
|
|||||||
selected = currentTab == Tab.Home,
|
selected = currentTab == Tab.Home,
|
||||||
onClick = { currentTab = Tab.Home },
|
onClick = { currentTab = Tab.Home },
|
||||||
icon = { Text("🏠") },
|
icon = { Text("🏠") },
|
||||||
label = { Text("首页") }
|
label = { Text("商品") }
|
||||||
)
|
|
||||||
NavigationBarItem(
|
|
||||||
selected = currentTab == Tab.Favorites,
|
|
||||||
onClick = { currentTab = Tab.Favorites },
|
|
||||||
icon = { Text("❤️") },
|
|
||||||
label = { Text("收藏(${favorites.size})") }
|
|
||||||
)
|
)
|
||||||
NavigationBarItem(
|
NavigationBarItem(
|
||||||
selected = currentTab == Tab.Cart,
|
selected = currentTab == Tab.Cart,
|
||||||
onClick = { currentTab = Tab.Cart },
|
onClick = { currentTab = Tab.Cart },
|
||||||
icon = { Text("🛒") },
|
icon = { Text("🛒") },
|
||||||
label = { Text("购物车(${cartState.totalCount})") }
|
label = { Text("购物车($totalCount)") }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -112,28 +141,24 @@ fun App() {
|
|||||||
when {
|
when {
|
||||||
inDetail -> ProductDetailScreen(
|
inDetail -> ProductDetailScreen(
|
||||||
product = selected,
|
product = selected,
|
||||||
isFavorite = selected?.let { favoriteStore.isFavorite(it.id) } == true,
|
quantity = selected?.let { id -> cartItems.firstOrNull { it.productId == id.id }?.quantity } ?: 0,
|
||||||
onBack = { inDetail = false },
|
|
||||||
onToggleFavorite = {
|
|
||||||
selected?.let {
|
|
||||||
favoriteStore.toggle(it.id)
|
|
||||||
tick++
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onAdd = {
|
onAdd = {
|
||||||
cartStore.add(it)
|
cartRepository.add(it.id)
|
||||||
tick++
|
tick++
|
||||||
|
scope.launch { snackbarHostState.showSnackbar("已加入购物车") }
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
currentTab == Tab.Home -> ProductListScreen(
|
currentTab == Tab.Home -> ProductListScreen(
|
||||||
products = products,
|
loading = loading,
|
||||||
|
error = loadError,
|
||||||
|
products = filteredProducts,
|
||||||
query = query,
|
query = query,
|
||||||
|
quantityOf = { id -> cartItems.firstOrNull { it.productId == id }?.quantity ?: 0 },
|
||||||
onQueryChange = { query = it },
|
onQueryChange = { query = it },
|
||||||
isFavorite = { favoriteStore.isFavorite(it) },
|
onRetry = { loadProducts() },
|
||||||
quantityOf = { cartState.quantityOf(it) },
|
onAdd = {
|
||||||
onToggleFavorite = { id ->
|
cartRepository.add(it.id)
|
||||||
favoriteStore.toggle(id)
|
|
||||||
tick++
|
tick++
|
||||||
},
|
},
|
||||||
onClick = {
|
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(
|
else -> CartScreen(
|
||||||
cartState = cartState,
|
items = cartItems,
|
||||||
onInc = { id -> cartStore.increase(id); tick++ },
|
productMap = productMap,
|
||||||
onDec = { id -> cartStore.decrease(id); tick++ },
|
totalPrice = totalPrice,
|
||||||
onRemove = { id -> cartStore.remove(id); tick++ },
|
onInc = { id -> cartRepository.increase(id); tick++ },
|
||||||
onClear = { cartStore.clear(); 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
|
@Composable
|
||||||
private fun ProductListScreen(
|
private fun ProductListScreen(
|
||||||
|
loading: Boolean,
|
||||||
|
error: String?,
|
||||||
products: List<Product>,
|
products: List<Product>,
|
||||||
query: String,
|
query: String,
|
||||||
onQueryChange: (String) -> Unit,
|
|
||||||
isFavorite: (String) -> Boolean,
|
|
||||||
quantityOf: (String) -> Int,
|
quantityOf: (String) -> Int,
|
||||||
onToggleFavorite: (String) -> Unit,
|
onQueryChange: (String) -> Unit,
|
||||||
|
onRetry: () -> Unit,
|
||||||
|
onAdd: (Product) -> Unit,
|
||||||
onClick: (Product) -> Unit
|
onClick: (Product) -> Unit
|
||||||
) {
|
) {
|
||||||
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
@@ -188,25 +209,31 @@ private fun ProductListScreen(
|
|||||||
placeholder = { Text("输入标题或描述") }
|
placeholder = { Text("输入标题或描述") }
|
||||||
)
|
)
|
||||||
|
|
||||||
if (products.isEmpty()) {
|
when {
|
||||||
EmptyState("没有匹配的商品")
|
loading -> EmptyState("加载中...")
|
||||||
} else {
|
error != null -> {
|
||||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
items(products) { p ->
|
Text("加载失败:$error")
|
||||||
ElevatedCard(onClick = { onClick(p) }, modifier = Modifier.fillMaxWidth()) {
|
Button(onClick = onRetry) { Text("重试") }
|
||||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
}
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
}
|
||||||
Text(p.title, style = MaterialTheme.typography.titleMedium)
|
products.isEmpty() -> EmptyState("没有匹配的商品")
|
||||||
Text("¥${formatPrice(p.price)}")
|
else -> {
|
||||||
}
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Text(p.description, style = MaterialTheme.typography.bodySmall)
|
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)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
OutlinedButton(onClick = { onToggleFavorite(p.id) }) {
|
Button(onClick = { onAdd(p) }) { Text("加入购物车") }
|
||||||
Text(if (isFavorite(p.id)) "已收藏" else "收藏")
|
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
|
@Composable
|
||||||
private fun ProductDetailScreen(
|
private fun ProductDetailScreen(
|
||||||
product: Product?,
|
product: Product?,
|
||||||
isFavorite: Boolean,
|
quantity: Int,
|
||||||
onBack: () -> Unit,
|
|
||||||
onToggleFavorite: () -> Unit,
|
|
||||||
onAdd: (Product) -> Unit
|
onAdd: (Product) -> Unit
|
||||||
) {
|
) {
|
||||||
if (product == null) {
|
if (product == null) {
|
||||||
@@ -233,81 +258,57 @@ private fun ProductDetailScreen(
|
|||||||
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
Text(product.title, style = MaterialTheme.typography.headlineSmall)
|
||||||
Text("价格:¥${formatPrice(product.price)}")
|
Text("价格:¥${formatPrice(product.price)}")
|
||||||
Text(product.description)
|
Text(product.description)
|
||||||
|
if (quantity > 0) Text("当前已加购:$quantity")
|
||||||
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
||||||
Button(onClick = onBack) { Text("返回") }
|
|
||||||
Button(onClick = { onAdd(product) }) { Text("加入购物车") }
|
|
||||||
OutlinedButton(onClick = onToggleFavorite) {
|
|
||||||
Text(if (isFavorite) "取消收藏" else "收藏")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun CartScreen(
|
private fun CartScreen(
|
||||||
cartState: CartState,
|
items: List<CartItem>,
|
||||||
|
productMap: Map<String, Product>,
|
||||||
|
totalPrice: Double,
|
||||||
onInc: (String) -> Unit,
|
onInc: (String) -> Unit,
|
||||||
onDec: (String) -> Unit,
|
onDec: (String) -> Unit,
|
||||||
onRemove: (String) -> Unit,
|
onRemove: (String) -> Unit,
|
||||||
onClear: () -> Unit
|
onClear: () -> Unit,
|
||||||
|
onCheckout: () -> Unit
|
||||||
) {
|
) {
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
if (cartState.items.isNotEmpty()) {
|
if (items.isNotEmpty()) {
|
||||||
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedButton(onClick = onClear) { Text("清空购物车") }
|
||||||
|
Button(onClick = onCheckout) { Text("结算") }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cartState.items.isEmpty()) {
|
if (items.isEmpty()) {
|
||||||
EmptyState("购物车为空")
|
EmptyState("购物车为空")
|
||||||
} else {
|
} else {
|
||||||
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
items(cartState.items) { item ->
|
items(items) { item ->
|
||||||
Card(Modifier.fillMaxWidth()) {
|
val product = productMap[item.productId]
|
||||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
if (product != null) {
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
Card(Modifier.fillMaxWidth()) {
|
||||||
Text(item.product.title)
|
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Text("¥${formatPrice(item.product.price * item.quantity)}")
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
}
|
Text(product.title)
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
Text("¥${formatPrice(product.price * item.quantity)}")
|
||||||
OutlinedButton(onClick = { onDec(item.product.id) }) { Text("-") }
|
}
|
||||||
Text("数量 ${item.quantity}")
|
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||||
OutlinedButton(onClick = { onInc(item.product.id) }) { Text("+") }
|
OutlinedButton(onClick = { onDec(product.id) }) { Text("-") }
|
||||||
OutlinedButton(onClick = { onRemove(item.product.id) }) { Text("移除") }
|
Text("数量 ${item.quantity}")
|
||||||
|
OutlinedButton(onClick = { onInc(product.id) }) { Text("+") }
|
||||||
|
OutlinedButton(onClick = { onRemove(product.id) }) { Text("移除") }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Text("总件数:${cartState.totalCount}")
|
Text("总件数:${items.sumOf { it.quantity }}")
|
||||||
Text("合计:¥${formatPrice(cartState.totalPrice)}", style = MaterialTheme.typography.titleMedium)
|
Text("合计:¥${formatPrice(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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ kotlin = "2.2.0"
|
|||||||
kotlinx-serialization = "1.8.1"
|
kotlinx-serialization = "1.8.1"
|
||||||
ksp = "2.2.0-2.0.2"
|
ksp = "2.2.0-2.0.2"
|
||||||
ktor = "3.1.3"
|
ktor = "3.1.3"
|
||||||
|
multiplatform-settings = "1.1.1"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
|
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-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
|
||||||
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", 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" }
|
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]
|
[plugins]
|
||||||
androidApplication = { id = "com.android.application", version.ref = "agp" }
|
androidApplication = { id = "com.android.application", version.ref = "agp" }
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ kotlin {
|
|||||||
implementation(libs.ktor.client.core)
|
implementation(libs.ktor.client.core)
|
||||||
implementation(libs.ktor.client.content.negotiation)
|
implementation(libs.ktor.client.content.negotiation)
|
||||||
implementation(libs.ktor.serialization.kotlinx.json)
|
implementation(libs.ktor.serialization.kotlinx.json)
|
||||||
|
implementation(libs.multiplatform.settings.no.arg)
|
||||||
implementation(libs.koin.core)
|
implementation(libs.koin.core)
|
||||||
api(libs.kmp.observable.viewmodel)
|
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
|
package com.example.minishop.model
|
||||||
|
|
||||||
|
import kotlinx.serialization.SerialName
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
data class Product(
|
data class Product(
|
||||||
|
@SerialName("id")
|
||||||
val id: String,
|
val id: String,
|
||||||
|
@SerialName("title")
|
||||||
val title: String,
|
val title: String,
|
||||||
|
@SerialName("price")
|
||||||
val price: Double,
|
val price: Double,
|
||||||
|
@SerialName("description")
|
||||||
val description: String
|
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