/
Stalnodg
/
RandomCoffee
Обзор
Документация
Войти
/
Stalnodg
/
RandomCoffee
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop
app/src/main/java/com/topit/randomcoffee/presentation/viewmodel/CartViewModel.kt
165 строк
6 KB
Max
presentation: pagination moved from data to presentation, bug with broken reload fixed, ViewModel for shopping cart created
05 май 2026, 18:21
05 май 2026, 18:21
1c6961d
Код
Авторство
О чём код?
package com.topit.randomcoffee.presentation.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.topit.randomcoffee.domain.models.Cart import com.topit.randomcoffee.domain.models.DomainError import com.topit.randomcoffee.domain.models.OperationResult import com.topit.randomcoffee.domain.usecase.AddProductUseCase import com.topit.randomcoffee.domain.usecase.ClearCartUseCase import com.topit.randomcoffee.domain.usecase.GetCartUseCase import com.topit.randomcoffee.domain.usecase.PlaceOrderUseCase import com.topit.randomcoffee.domain.usecase.RemoveCartItemQuantityUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CartViewModel @Inject constructor( private val addProductUseCase: AddProductUseCase, private val removeCartItemQuantityUseCase: RemoveCartItemQuantityUseCase, private val getCartUseCase: GetCartUseCase, private val clearCartUseCase: ClearCartUseCase, private val placeOrderUseCase: PlaceOrderUseCase ) : ViewModel() { private val _uiState = MutableStateFlow(CartUiState()) val uiState = _uiState.asStateFlow() init { loadCart() } private fun loadCart() { viewModelScope.launch { try { when (val result = getCartUseCase()) { is OperationResult.Success -> { _uiState.update { it.copy(cart = result.data, cartError = null) } } is OperationResult.Failure -> { _uiState.update { it.copy(cartError = result.error.toUiMessage()) } } } } catch (e: CancellationException) { throw e } catch (e: Exception) { _uiState.update { it.copy(cartError = e.message ?: "Не удалось загрузить корзину") } } } } fun addToCart(productId: Int) { viewModelScope.launch { try { when (val result = addProductUseCase(productId, 1)) { is OperationResult.Success -> loadCart() is OperationResult.Failure -> { _uiState.update { it.copy(cartError = result.error.toUiMessage()) } } } } catch (e: CancellationException) { throw e } catch (e: Exception) { _uiState.update { it.copy(cartError = e.message ?: "Не удалось обновить корзину.") } } } } fun clearCart() { viewModelScope.launch { try { when (val result = clearCartUseCase()) { is OperationResult.Success -> { _uiState.update { it.copy(cart = result.data, cartError = null) } } is OperationResult.Failure -> { _uiState.update { it.copy(cartError = result.error.toUiMessage()) } } } } catch (e: CancellationException) { throw e } catch (e: Exception) { _uiState.update { it.copy(cartError = e.message ?: "Не удалось очистить корзину") } } } } fun placeOrder() { viewModelScope.launch { try { when (val orderResult = placeOrderUseCase()) { is OperationResult.Success -> { when (val cartResult = getCartUseCase()) { is OperationResult.Success -> { _uiState.update { it.copy( cart = cartResult.data, orderMessage = orderResult.data.message, cartError = null ) } } is OperationResult.Failure -> { _uiState.update { it.copy(cartError = cartResult.error.toUiMessage()) } } } } is OperationResult.Failure -> { _uiState.update { it.copy(cartError = orderResult.error.toUiMessage()) } } } } catch (e: CancellationException) { throw e } catch (e: Exception) { _uiState.update { it.copy(cartError = e.message ?: "Не удалось отправить заказ.") } } } } fun removeFromCart(productId: Int, quantity: Int) { viewModelScope.launch { try { when (val result = removeCartItemQuantityUseCase(productId, quantity)) { is OperationResult.Success -> { _uiState.update { it.copy(cart = result.data, cartError = null) } } is OperationResult.Failure -> { _uiState.update { it.copy(cartError = result.error.toUiMessage()) } } } } catch (e: CancellationException) { throw e } catch (e: Exception) { _uiState.update { it.copy(cartError = e.message ?: "Не удалось изменить количество в корзине.") } } } } fun dismissCartError() { _uiState.update { it.copy(cartError = null) } } fun dismissOrderMessage() { _uiState.update { it.copy(orderMessage = null) } } } private fun DomainError.toUiMessage(): String { return when (this) { is DomainError.Network -> "Проблема с сетью. Проверьте подключение." is DomainError.Http -> "Ошибка сервера${code?.let { " ($it)" } ?: ""}." is DomainError.Validation -> message is DomainError.Unexpected -> "Что-то пошло не так. Попробуйте снова." } } data class CartUiState( val cart: Cart? = null, val cartError: String? = null, val orderMessage: String? = null )