Compare commits
No commits in common. "5c2284ff793c2564bc411ba6fbacf0c133d6f393" and "cbda2271f84b7c654f9ee7f38f3e831aebbb6992" have entirely different histories.
5c2284ff79
...
cbda2271f8
@ -3,7 +3,6 @@ package com.example.shawarma
|
||||
import android.app.Application
|
||||
import androidx.room.Room
|
||||
import com.example.shawarma.data.api.MyServerService
|
||||
import com.example.shawarma.data.api.repos.RestProductRepository
|
||||
import com.example.shawarma.data.api.repos.RestUserRepository
|
||||
import com.example.shawarma.data.db.AppDatabase
|
||||
import com.example.shawarma.data.repos.OrderProductRepository
|
||||
@ -50,13 +49,7 @@ object AppModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideProductRepository(db: AppDatabase) : ProductRepository {
|
||||
return ProductRepository(database = db, db.productDao(), db.orderProductDao())
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideRestProductRepository(service: MyServerService) : RestProductRepository {
|
||||
return RestProductRepository(service)
|
||||
return ProductRepository(db.productDao(), db.orderProductDao())
|
||||
}
|
||||
|
||||
@Provides
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.example.shawarma.data.api
|
||||
|
||||
import com.example.shawarma.data.api.models.ProductListResponse
|
||||
import com.example.shawarma.data.api.models.TokenModelRemote
|
||||
import com.example.shawarma.data.api.models.UserModelRemote
|
||||
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
|
||||
@ -9,10 +8,7 @@ import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.Header
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.Path
|
||||
|
||||
|
||||
interface MyServerService {
|
||||
@ -26,20 +22,6 @@ interface MyServerService {
|
||||
@Body user: UserModelRemote
|
||||
) : TokenModelRemote
|
||||
|
||||
@POST("check/login")
|
||||
suspend fun checkLogin(
|
||||
@Body user: UserModelRemote
|
||||
) :UserModelRemote?
|
||||
|
||||
@GET("user/products/{after}")
|
||||
suspend fun getProductsList(@Path("after") after: Int, @Header("Authorization") token: String) : ProductListResponse
|
||||
|
||||
@GET("user/discounts/{after}")
|
||||
suspend fun getDiscountsList(@Path("after") after: Int, @Header("Authorization") token: String) : ProductListResponse
|
||||
|
||||
@GET("user/items/{after}")
|
||||
suspend fun getItemsList(@Path("after") after: Int, @Header("Authorization") token: String) : ProductListResponse
|
||||
|
||||
|
||||
companion object {
|
||||
private const val BASE_URL = "https://10.0.2.2:80/api/"
|
||||
|
@ -1,91 +0,0 @@
|
||||
package com.example.shawarma.data.api.mediators
|
||||
|
||||
import androidx.paging.ExperimentalPagingApi
|
||||
import androidx.paging.LoadType
|
||||
import androidx.paging.PagingState
|
||||
import androidx.paging.RemoteMediator
|
||||
import androidx.room.withTransaction
|
||||
import com.example.shawarma.data.api.MyServerService
|
||||
import com.example.shawarma.data.api.models.ProductListResponse
|
||||
import com.example.shawarma.data.api.models.toProductModel
|
||||
import com.example.shawarma.data.db.AppDatabase
|
||||
import com.example.shawarma.data.models.ProductModel
|
||||
import java.io.IOException
|
||||
|
||||
@OptIn(ExperimentalPagingApi::class)
|
||||
class ProductRemoteMediator (
|
||||
private val database: AppDatabase,
|
||||
private val serverService: MyServerService,
|
||||
private val query: String,
|
||||
private val token: String
|
||||
) : RemoteMediator<Int, ProductModel>(){
|
||||
|
||||
private val productDao = database.productDao()
|
||||
|
||||
override suspend fun load(
|
||||
loadType: LoadType,
|
||||
state: PagingState<Int, ProductModel>
|
||||
): MediatorResult {
|
||||
return try {
|
||||
// The network load method takes an optional `after=<user.id>` parameter. For every
|
||||
// page after the first, we pass the last user ID to let it continue from where it
|
||||
// left off. For REFRESH, pass `null` to load the first page.
|
||||
var loadKey = when (loadType) {
|
||||
LoadType.REFRESH -> null
|
||||
// In this example, we never need to prepend, since REFRESH will always load the
|
||||
// first page in the list. Immediately return, reporting end of pagination.
|
||||
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
|
||||
LoadType.APPEND -> {
|
||||
val lastItem = state.lastItemOrNull()
|
||||
?: return MediatorResult.Success(endOfPaginationReached = true)
|
||||
|
||||
// We must explicitly check if the last item is `null` when appending,
|
||||
// since passing `null` to networkService is only valid for initial load.
|
||||
// If lastItem is `null` it means no items were loaded after the initial
|
||||
// REFRESH and there are no more items to load.
|
||||
|
||||
lastItem.id
|
||||
}
|
||||
}
|
||||
|
||||
// Suspending network load via Retrofit. This doesn't need to be wrapped in a
|
||||
// withContext(Dispatcher.IO) { ... } block since Retrofit's Coroutine CallAdapter
|
||||
// dispatches on a worker thread.
|
||||
if (loadKey == null) {
|
||||
loadKey = 0
|
||||
}
|
||||
val response: ProductListResponse = when (query) {
|
||||
"home" -> {
|
||||
serverService.getProductsList(after = loadKey, token = token)
|
||||
}
|
||||
"discounts" -> {
|
||||
serverService.getDiscountsList(after = loadKey, token = token)
|
||||
}
|
||||
"items" -> {
|
||||
serverService.getItemsList(after = loadKey, token = token)
|
||||
}
|
||||
|
||||
else -> {ProductListResponse()}
|
||||
}
|
||||
|
||||
|
||||
database.withTransaction {
|
||||
if (loadType == LoadType.REFRESH) {
|
||||
productDao.deleteByQuery(query)
|
||||
}
|
||||
|
||||
// Insert new users into database, which invalidates the current
|
||||
// PagingData, allowing Paging to present the updates in the DB.
|
||||
val products = mutableListOf<ProductModel>()
|
||||
for (prod in response.products) {
|
||||
products.add(prod.toProductModel())
|
||||
}
|
||||
productDao.insertAll(products)
|
||||
}
|
||||
|
||||
MediatorResult.Success(endOfPaginationReached = response.nextKey == -1)
|
||||
} catch (e: IOException) {
|
||||
MediatorResult.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
package com.example.shawarma.data.api.models
|
||||
|
||||
import com.example.shawarma.data.models.ProductModel
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ProductModelRemote(
|
||||
val id: Int = 0,
|
||||
val title: String = "",
|
||||
val price: Int = 0,
|
||||
val old_price: Int? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ProductListResponse(
|
||||
val products: List<ProductModelRemote> = listOf(),
|
||||
val nextKey: Int? = null
|
||||
)
|
||||
|
||||
fun ProductModelRemote.toProductModel(): ProductModel = ProductModel(
|
||||
id, title, price, old_price
|
||||
)
|
||||
|
||||
fun ProductModel.toProductModelRemote(): ProductModelRemote = ProductModelRemote(
|
||||
title = title, price = price, old_price = oldPrice
|
||||
)
|
@ -5,17 +5,16 @@ import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class TokenModelRemote(
|
||||
val access_token: String = "",
|
||||
val message: String = ""
|
||||
val access_token: String = ""
|
||||
)
|
||||
|
||||
|
||||
@Serializable
|
||||
data class UserModelRemote(
|
||||
val id: Int = 0,
|
||||
val login: String = "",
|
||||
val password:String = "",
|
||||
val role:String = "",
|
||||
val message: String = ""
|
||||
val role:String = ""
|
||||
)
|
||||
|
||||
fun UserModelRemote.toUserModel(): UserModel = UserModel(
|
||||
|
@ -1,10 +0,0 @@
|
||||
package com.example.shawarma.data.api.repos
|
||||
|
||||
import com.example.shawarma.data.api.MyServerService
|
||||
import javax.inject.Inject
|
||||
|
||||
class RestProductRepository @Inject constructor(
|
||||
private val service: MyServerService
|
||||
) {
|
||||
|
||||
}
|
@ -2,7 +2,6 @@ package com.example.shawarma.data.api.repos
|
||||
|
||||
import com.example.shawarma.data.api.MyServerService
|
||||
import com.example.shawarma.data.api.models.TokenModelRemote
|
||||
import com.example.shawarma.data.api.models.UserModelRemote
|
||||
import com.example.shawarma.data.api.models.toUserModelRemote
|
||||
import com.example.shawarma.data.models.UserModel
|
||||
import javax.inject.Inject
|
||||
@ -17,8 +16,4 @@ class RestUserRepository @Inject constructor(
|
||||
suspend fun getToken(user: UserModel): TokenModelRemote {
|
||||
return service.getToken(user.toUserModelRemote())
|
||||
}
|
||||
|
||||
suspend fun checkLogin(user: UserModel): UserModelRemote? {
|
||||
return service.checkLogin(user.toUserModelRemote())
|
||||
}
|
||||
}
|
@ -13,12 +13,6 @@ interface ProductDao {
|
||||
@Insert
|
||||
suspend fun insert(product: ProductModel)
|
||||
|
||||
suspend fun insertAll(products: List<ProductModel>) {
|
||||
for (product in products) {
|
||||
insert(product)
|
||||
}
|
||||
}
|
||||
|
||||
@Update
|
||||
suspend fun update(product: ProductModel)
|
||||
|
||||
@ -45,25 +39,4 @@ interface ProductDao {
|
||||
|
||||
@Query("select * from products")
|
||||
fun getPagedItems(): PagingSource<Int, ProductModel>
|
||||
|
||||
@Query("delete from products where products.product_old_price is null")
|
||||
fun deleteAllProducts()
|
||||
|
||||
@Query("delete from products where products.product_old_price is not null")
|
||||
fun deleteAllDiscountProducts()
|
||||
|
||||
@Query("delete from products")
|
||||
fun deleteAllItems()
|
||||
|
||||
fun deleteByQuery(query: String) {
|
||||
if (query == "home") {
|
||||
deleteAllProducts()
|
||||
}
|
||||
if (query == "discounts") {
|
||||
deleteAllDiscountProducts()
|
||||
}
|
||||
if (query == "items") {
|
||||
deleteAllItems()
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +1,8 @@
|
||||
package com.example.shawarma.data.repos
|
||||
|
||||
import androidx.paging.ExperimentalPagingApi
|
||||
import androidx.paging.Pager
|
||||
import androidx.paging.PagingConfig
|
||||
import androidx.paging.PagingData
|
||||
import com.example.shawarma.data.api.MyServerService
|
||||
import com.example.shawarma.data.api.mediators.ProductRemoteMediator
|
||||
import com.example.shawarma.data.db.AppDatabase
|
||||
import com.example.shawarma.data.interfaces.dao.OrderProductDao
|
||||
import com.example.shawarma.data.interfaces.dao.ProductDao
|
||||
import com.example.shawarma.data.models.ProductModel
|
||||
@ -14,7 +10,6 @@ import kotlinx.coroutines.flow.Flow
|
||||
import javax.inject.Inject
|
||||
|
||||
class ProductRepository @Inject constructor(
|
||||
private val database: AppDatabase,
|
||||
private val productDao: ProductDao,
|
||||
private val orderProductDao: OrderProductDao
|
||||
) {
|
||||
@ -28,27 +23,32 @@ class ProductRepository @Inject constructor(
|
||||
orderProductDao.deleteByProductId(product.id!!)
|
||||
return productDao.delete(product)
|
||||
}
|
||||
/*fun getAll(): Flow<List<ProductModel>> {
|
||||
return productDao.getAll()
|
||||
}
|
||||
fun getDiscounts(): Flow<List<ProductModel>> {
|
||||
return productDao.getDiscounts()
|
||||
}
|
||||
fun getItems(): Flow<List<ProductModel>> {
|
||||
return productDao.getItems()
|
||||
}*/
|
||||
fun getById(id: Int): Flow<ProductModel> {
|
||||
return productDao.getById(id)
|
||||
}
|
||||
@OptIn(ExperimentalPagingApi::class)
|
||||
fun getAllProductsPaged(token: String): Flow<PagingData<ProductModel>> = Pager(
|
||||
fun getAllProductsPaged(): Flow<PagingData<ProductModel>> = Pager(
|
||||
config = PagingConfig(
|
||||
pageSize = 6,
|
||||
enablePlaceholders = false
|
||||
),
|
||||
pagingSourceFactory = productDao::getPaged,
|
||||
remoteMediator = ProductRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "home", token = token)
|
||||
pagingSourceFactory = productDao::getPaged
|
||||
).flow
|
||||
|
||||
@OptIn(ExperimentalPagingApi::class)
|
||||
fun getAllDiscountsPaged(token: String): Flow<PagingData<ProductModel>> = Pager(
|
||||
fun getAllDiscountsPaged(): Flow<PagingData<ProductModel>> = Pager(
|
||||
config = PagingConfig(
|
||||
pageSize = 6,
|
||||
enablePlaceholders = false
|
||||
),
|
||||
pagingSourceFactory = productDao::getPagedDiscounts,
|
||||
remoteMediator = ProductRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "discounts", token = token)
|
||||
pagingSourceFactory = productDao::getPagedDiscounts
|
||||
).flow
|
||||
|
||||
fun getAllItemsPaged(): Flow<PagingData<ProductModel>> = Pager(
|
||||
|
@ -59,13 +59,6 @@ fun AuthorizationCard(navHostController: NavHostController) {
|
||||
if (userViewModel.token.observeAsState().value != null) {
|
||||
preferencesManager.saveData("token", userViewModel.token.value.toString())
|
||||
|
||||
if (login.value.text == "admin") {
|
||||
preferencesManager.saveData("user_role", "ADMIN")
|
||||
}
|
||||
else {
|
||||
preferencesManager.saveData("user_role", "USER")
|
||||
}
|
||||
|
||||
navHostController.navigate(ScreenPaths.home.name) {
|
||||
popUpTo(ScreenPaths.authorization.name) {
|
||||
inclusive = true
|
||||
|
@ -58,13 +58,9 @@ fun DiscountScreen() {
|
||||
|
||||
@Composable
|
||||
fun DiscountList(){
|
||||
val preferencesManager = PreferencesManager(LocalContext.current)
|
||||
val searchToken = preferencesManager.getData("token", "")
|
||||
|
||||
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
|
||||
|
||||
|
||||
val productsListUiState = homeViewModel.getDiscountList(searchToken).collectAsLazyPagingItems()
|
||||
val productsListUiState = homeViewModel.discountListUiState.collectAsLazyPagingItems()
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
|
@ -57,13 +57,9 @@ fun HomeScreen() {
|
||||
|
||||
@Composable
|
||||
fun HomeList(){
|
||||
val preferencesManager = PreferencesManager(LocalContext.current)
|
||||
val searchToken = preferencesManager.getData("token", "")
|
||||
|
||||
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
|
||||
|
||||
|
||||
val productsListUiState = homeViewModel.getProductList(searchToken).collectAsLazyPagingItems()
|
||||
val productsListUiState = homeViewModel.productListUiState.collectAsLazyPagingItems()
|
||||
|
||||
|
||||
Box(
|
||||
|
@ -14,7 +14,6 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import javax.inject.Inject
|
||||
|
||||
@ -25,13 +24,9 @@ class HomeViewModel @Inject constructor(
|
||||
private val orderProductRepository: OrderProductRepository
|
||||
) : ViewModel() {
|
||||
|
||||
fun getProductList(token:String): Flow<PagingData<ProductModel>> {
|
||||
return productRepository.getAllProductsPaged(token)
|
||||
}
|
||||
val productListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllProductsPaged()
|
||||
|
||||
fun getDiscountList(token: String): Flow<PagingData<ProductModel>> {
|
||||
return productRepository.getAllDiscountsPaged(token)
|
||||
}
|
||||
val discountListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllDiscountsPaged()
|
||||
|
||||
|
||||
fun addProductToCart(productId: Int, userId: String) {
|
||||
@ -41,10 +36,7 @@ class HomeViewModel @Inject constructor(
|
||||
val product = productRepository.getById(productId).first()
|
||||
val order = orderRepository.getUnpaidByUser(userId.toInt()).first()
|
||||
if (order == null) {
|
||||
val calendar: Calendar = Calendar.getInstance()
|
||||
calendar.time = Date()
|
||||
calendar.add(Calendar.HOUR_OF_DAY, 4)
|
||||
val newOrderId = orderRepository.insert(OrderModel(null, OrderStatus.Неоплачено.name, userId.toInt(),calendar.time))
|
||||
val newOrderId = orderRepository.insert(OrderModel(null, OrderStatus.Неоплачено.name, userId.toInt(), Date()))
|
||||
orderProductRepository.insert(OrderProductModel(newOrderId.toInt(), productId, 1, product.price))
|
||||
}
|
||||
else {
|
||||
|
@ -6,6 +6,7 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.shawarma.data.models.OrderStatus
|
||||
import com.example.shawarma.data.models.OrderWithProducts
|
||||
import com.example.shawarma.data.repos.OrderProductRepository
|
||||
import com.example.shawarma.data.repos.OrderRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
@ -13,7 +14,8 @@ import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class OrdersViewModel @Inject constructor(
|
||||
private val orderRepository: OrderRepository
|
||||
private val orderRepository: OrderRepository,
|
||||
private val orderProductRepository: OrderProductRepository
|
||||
) : ViewModel() {
|
||||
private val _preparingOrders = MutableLiveData<List<OrderWithProducts>>()
|
||||
private val _preparedOrders = MutableLiveData<List<OrderWithProducts>>()
|
||||
|
@ -6,6 +6,7 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.example.shawarma.data.api.repos.RestUserRepository
|
||||
import com.example.shawarma.data.models.UserModel
|
||||
import com.example.shawarma.data.repos.UserRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@ -14,8 +15,13 @@ import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class UserViewModel @Inject constructor(
|
||||
private val userRepository: UserRepository,
|
||||
private val restUserRepository: RestUserRepository
|
||||
) : ViewModel() {
|
||||
private val _userModel = MutableLiveData<UserModel?>()
|
||||
val userModel: LiveData<UserModel?>
|
||||
get() = _userModel
|
||||
|
||||
private val _token = MutableLiveData<String?>()
|
||||
val token: LiveData<String?>
|
||||
get() = _token
|
||||
@ -27,7 +33,7 @@ class UserViewModel @Inject constructor(
|
||||
fun login(login: String, password: String){
|
||||
viewModelScope.launch {
|
||||
withContext(Dispatchers.Main) {
|
||||
val token_response = restUserRepository.getToken(UserModel(id = null, login = login, password = password, role = ""))
|
||||
val token_response = restUserRepository.getToken(UserModel(id = null, login = login, password = password, role = "USER"))
|
||||
if (token_response.access_token.isNotEmpty()) {
|
||||
_token.postValue(token_response.access_token)
|
||||
_authorizationState.postValue(true)
|
||||
@ -40,12 +46,14 @@ class UserViewModel @Inject constructor(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun calmAuthorizationState() {
|
||||
_authorizationState.postValue(null)
|
||||
}
|
||||
|
||||
private val _registrationState = MutableLiveData<Boolean>()
|
||||
val registrationState: LiveData<Boolean>
|
||||
private val _registrationState = MutableLiveData<Boolean?>()
|
||||
val registrationState: LiveData<Boolean?>
|
||||
get() = _registrationState
|
||||
|
||||
fun register(login: String, password: String, passwordRepeat: String) {
|
||||
@ -64,25 +72,25 @@ class UserViewModel @Inject constructor(
|
||||
}
|
||||
viewModelScope.launch {
|
||||
withContext(Dispatchers.Main) {
|
||||
val user_response = restUserRepository.checkLogin(UserModel(null, login, password, ""))
|
||||
if (user_response != null) {
|
||||
if (user_response.login.isNullOrEmpty()) {
|
||||
userRepository.login(login, password).collect() { user ->
|
||||
if (user == null) {
|
||||
if (login == "admin" && password == "admin") {
|
||||
restUserRepository.insert(UserModel(null, login, password, "ADMIN"))
|
||||
_registrationState.postValue(true)
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
restUserRepository.insert(UserModel(null, login, password, "USER"))
|
||||
_registrationState.postValue(true)
|
||||
}
|
||||
} else {
|
||||
if (registrationState.value != true) {
|
||||
_registrationState.postValue(false)
|
||||
}
|
||||
}
|
||||
else {
|
||||
_registrationState.postValue(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun calmRegistrationState() {
|
||||
_registrationState.postValue(null)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user