Add variants selecting

This commit is contained in:
Grigorii 2023-01-09 16:34:06 +04:00
parent 33a745e5e0
commit 724c2ca3b8
3 changed files with 21 additions and 1 deletions

View File

@ -20,7 +20,9 @@ abstract class CartModel<TProductModel : ProductModel> {
fun getPriceWithPromocode(): Int = promocodeList
.sortedByDescending { it.discount is PromocodeDiscount.ByPercent }
.fold(initial = totalPrice) { price, promo -> promo.discount.applyTo(price) }
.fold(initial = totalPrice) { price, promo ->
promo.discount.applyTo(price)
}
abstract fun <TCart> copyWith(
products: List<TProductModel> = this.products,

View File

@ -8,11 +8,16 @@ abstract class ProductModel {
abstract val isDeleted: Boolean
open val bonuses: Int? = null
open val variants: List<ProductModel> = emptyList()
open val selectedVariantId: Int? = null
val selectedVariant get() = variants.find { it.id == selectedVariantId }
abstract fun <TProduct> copyWith(
countInCart: Int = this.countInCart,
isDeleted: Boolean = this.isDeleted,
selectedVariantId: Int? = this.selectedVariantId
): TProduct
@Suppress("UNCHECKED_CAST")

View File

@ -64,6 +64,19 @@ class LocalCartRepository<TCart : CartModel<TProduct>, TProduct : ProductModel>(
_currentCart.update { it.copyWith(usedBonuses = bonuses) }
}
fun chooseVariant(productId: Int, variantId: Int?) {
updateCartProducts {
updateProduct(productId) {
if (variantId != null) {
check(variants.any { it.id == variantId }) {
"Product with id=$productId doesn't have variant with id=$variantId"
}
}
copyWith(selectedVariantId = variantId)
}
}
}
private fun updateCartProducts(updateAction: MutableList<TProduct>.() -> Unit) {
_currentCart.update { cart ->
cart.copyWith(products = cart.products.toMutableList().apply(updateAction))