feat: migrate lesson 7 cart flow from settings to sql
This commit is contained in:
1 parent
a5120b3e8a
commit
4f32be7077
12 files changed
+811
-80
No files matched your search
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user