diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a86b285..6d30417 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -76,4 +76,7 @@ dependencies { androidTestImplementation("androidx.compose.ui:ui-test-junit4") debugImplementation("androidx.compose.ui:ui-tooling") debugImplementation("androidx.compose.ui:ui-test-manifest") + + implementation ("androidx.paging:paging-compose:3.2.1") + implementation ("androidx.paging:paging-runtime:3.2.1") } \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e013846..55b6581 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,6 +3,7 @@ xmlns:tools="http://schemas.android.com/tools"> () } val sumPrice = remember { mutableStateOf(0.0) } LaunchedEffect(Unit) { - withContext(Dispatchers.IO) { - products.clear() - sumPrice.value = 0.0; - AppDb.getInstance(context).userDao().getUserProductCartById(1).products.forEach { - sumPrice.value += it.price - products.add(it) + if (userViewModel.getUserId() == 0) { + navController.navigate("authorization") + } else { + userViewModel.getUserProductCartById(userViewModel.getUserId()).collect {data -> + products.clear() + sumPrice.value = 0.0; + data.products.forEach { + sumPrice.value += it.price + products.add(it) + } } } } diff --git a/app/src/main/java/com/example/myapplication/components/Main.kt b/app/src/main/java/com/example/myapplication/components/Main.kt index 58e6853..4680ec6 100644 --- a/app/src/main/java/com/example/myapplication/components/Main.kt +++ b/app/src/main/java/com/example/myapplication/components/Main.kt @@ -1,62 +1,71 @@ package com.example.myapplication.components + +import android.widget.Toast +import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.paging.compose.collectAsLazyPagingItems +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn - +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController -import com.example.myapplication.database.entities.Product - -import androidx.compose.runtime.LaunchedEffect +import androidx.paging.compose.itemKey import com.example.myapplication.components.funs.createProductCard -import com.example.myapplication.database.AppDb -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext +import com.example.myapplication.database.entities.UserProductCart +import com.example.myapplication.viewModels.ProductViewModel +import com.example.myapplication.viewModels.UserViewModel +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext @OptIn(ExperimentalMaterial3Api::class) @Composable -fun Main(navController: NavController, categoryId: Int) { +fun Main( + navController: NavController, + catalogId: Int, + productViewModel: ProductViewModel = viewModel(factory = ProductViewModel.factory), + userViewModel: UserViewModel = viewModel(factory = UserViewModel.factory) +) { val context = LocalContext.current - val products = remember { mutableStateListOf() } + val coroutineScope = rememberCoroutineScope() + val products = when (catalogId) { + 0 -> productViewModel.getAll().collectAsLazyPagingItems() + else -> productViewModel.getByCategory(catalogId).collectAsLazyPagingItems() + } - if (categoryId == 0){ - LaunchedEffect(Unit) { - withContext(Dispatchers.IO) { - AppDb.getInstance(context).productDao().getAll().collect { data -> - products.clear() - data.forEach{ - products.add(it) - } - } - } - } - } else { - LaunchedEffect(Unit) { - withContext(Dispatchers.IO) { - AppDb.getInstance(context).categoryDao().getProductsByCategory(categoryId).collect { data -> - products.clear() - - data.forEach { - products.add(it) - } - } - } + LaunchedEffect(Unit) { + if (userViewModel.getUserId() == 0) { + navController.navigate("authorization") } } @@ -65,25 +74,60 @@ fun Main(navController: NavController, categoryId: Int) { .fillMaxSize() .padding(8.dp) ) { -// item { OutlinedTextField( -// value = "", -// onValueChange = { }, -// placeholder = { Text("Поиск товара") }, -// modifier = Modifier -// .fillMaxWidth() -// .padding(8.dp) -// ) } - item {Text( - text = "Товары:", - fontSize = 28.sp, - color = Color.Black, - modifier = Modifier.padding(8.dp) - )} - item{products.forEach { - createProductCard(it.name, it.price, it.img, { navController.navigate("product/" + it.productId) } ) + item { + Text( + text = "Товары:", + fontSize = 28.sp, + color = Color.Black, + modifier = Modifier.padding(8.dp) + ) } + +// item { +// products.forEach { +// createProductCard( +// it.name, +// it.price, +// it.img, +// { navController.navigate("product/" + it.productId) }) +// } +// } + items ( + count = products.itemCount, + key = products.itemKey { product -> product.productId!! } + ) { index -> + val it = products[index]!! + createProductCard( it.name, it.price, it.img, { navController.navigate("product/" + it.productId)}){ + coroutineScope.launch { + kotlin.runCatching { + userViewModel.addProductCart( + UserProductCart( + userViewModel.getUserId(), + it.productId!! + ) + ) + } + .onSuccess { + val toast = + Toast.makeText(context, "Добавлено", Toast.LENGTH_SHORT) + toast.show() + delay(500) + toast.cancel() + } + .onFailure { + val toast = Toast.makeText( + context, + "Уже есть в корзине", + Toast.LENGTH_SHORT + ) + toast.show() + delay(500) + toast.cancel() + } + } + } } } -} +} diff --git a/app/src/main/java/com/example/myapplication/components/Registration.kt b/app/src/main/java/com/example/myapplication/components/Registration.kt index a53b630..214eb7b 100644 --- a/app/src/main/java/com/example/myapplication/components/Registration.kt +++ b/app/src/main/java/com/example/myapplication/components/Registration.kt @@ -2,6 +2,7 @@ package com.example.myapplication.components import Input import TextNice +import android.widget.Toast import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -12,38 +13,64 @@ import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import androidx.compose.ui.tooling.preview.Preview +import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.rememberNavController - +import com.example.myapplication.components.common.myInput +import com.example.myapplication.database.entities.User +import com.example.myapplication.viewModels.UserViewModel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch @Composable -fun Registration (navController: NavController){ - Column( - modifier = Modifier - .fillMaxSize() - .padding(start = 10.dp, end = 10.dp), - verticalArrangement = Arrangement.Center, - horizontalAlignment = Alignment.CenterHorizontally - ){ - Input("Имя") - Input("Эл.почта") - Input("Пароль") - Input("Повторите пароль") +fun Registration( + navController: NavController, + userViewModel: UserViewModel = viewModel(factory = UserViewModel.factory) +) { + val coroutineScope = rememberCoroutineScope() + val context = LocalContext.current + + val mailState = remember { mutableStateOf("") } + val loginState = remember { mutableStateOf("") } + val passState = remember { mutableStateOf("") } + val repeatPassState = remember { mutableStateOf("") } + + Column(modifier = Modifier.padding(start=30.dp, end=30.dp, top=100.dp)) { + myInput("Email", mailState) + myInput("Логин", loginState) + myInput("Пароль", passState) + myInput("Повторите Пароль", repeatPassState) Button( - onClick = { /*TODO*/ }, - modifier = Modifier.fillMaxWidth(), - ) - { - TextNice("Создать аккаунт") - } + onClick = { + coroutineScope.launch { + if(passState.value != repeatPassState.value) { + val toast = Toast.makeText(context, "Пароли не совпадают", Toast.LENGTH_SHORT) + toast.show() + delay(500) + toast.cancel() + return@launch + } + userViewModel.insert(User(null, mailState.value, loginState.value, passState.value)) + navController.navigate("authorization") + } + }, + modifier = Modifier + .fillMaxWidth() + .padding(top = 10.dp)) { + Text("Регистрация", fontSize = 20.sp) + } Button( onClick = {navController.navigate("authorization")}, modifier = Modifier.fillMaxWidth(), @@ -51,18 +78,8 @@ fun Registration (navController: NavController){ colors= ButtonDefaults.buttonColors( containerColor= Color.White, contentColor = Color.Gray - )) - { - TextNice("Авторизация") - + )) { + Text("Авторизация", fontSize = 20.sp, color= Color.Black) } } -} - -@Preview(showBackground = true) -@Composable -fun RegistrationPreview() { - val navController = rememberNavController() - - Registration(navController = navController) } \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/components/common/myInput.kt b/app/src/main/java/com/example/myapplication/components/common/myInput.kt new file mode 100644 index 0000000..5cadd62 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/components/common/myInput.kt @@ -0,0 +1,40 @@ +package com.example.myapplication.components.common + +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.MutableState +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp + + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun myInput(label: String, text: MutableState, height: Dp = 50.dp, modifier: Modifier = Modifier) { + Column(modifier=modifier) { + Text(label) + TextField( + value = text.value, + onValueChange = {newText -> text.value = newText}, + colors= TextFieldDefaults.outlinedTextFieldColors( + focusedBorderColor = Color.Transparent, + disabledBorderColor = Color.Transparent, + unfocusedBorderColor = Color.Transparent, + errorBorderColor = Color.Transparent + ), + modifier = Modifier + .border(1.dp, Color.Black, RoundedCornerShape(10.dp)) + .fillMaxWidth() + .height(height), + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/components/fun/funs.kt b/app/src/main/java/com/example/myapplication/components/fun/funs.kt index c46a361..5fd9478 100644 --- a/app/src/main/java/com/example/myapplication/components/fun/funs.kt +++ b/app/src/main/java/com/example/myapplication/components/fun/funs.kt @@ -32,7 +32,7 @@ import myColor3 import myColor4 @Composable -fun createProductCard(name: String, price: Double, img: Bitmap, onClickAction: () -> Unit){ +fun createProductCard(name: String, price: Double, img: Bitmap, onClickAction: () -> Unit, onClickAction2: () -> Unit){ Column () { Row { Image( @@ -47,7 +47,7 @@ fun createProductCard(name: String, price: Double, img: Bitmap, onClickAction: ( ButtonNice("Инфо: " , Color.White, onClickAction) } } - ButtonNice("Добавить в корзину" , myColor1, onClickAction) + ButtonNice("Добавить в корзину" , myColor1, onClickAction2) } } @Composable diff --git a/app/src/main/java/com/example/myapplication/components/templates/CatalogItems.kt b/app/src/main/java/com/example/myapplication/components/templates/CatalogItems.kt index bbe3cb9..c47e6ae 100644 --- a/app/src/main/java/com/example/myapplication/components/templates/CatalogItems.kt +++ b/app/src/main/java/com/example/myapplication/components/templates/CatalogItems.kt @@ -31,7 +31,7 @@ fun CatalogItems (navController: NavController, title: String, products: Mutable } item{ for (product in products){ - createProductCard(product.name, product.price, product.img, { }) + createProductCard(product.name, product.price, product.img, { }, { }) } } item { diff --git a/app/src/main/java/com/example/myapplication/components/Сategory.kt b/app/src/main/java/com/example/myapplication/components/Сategory.kt index 8f3d5bc..e0b61c2 100644 --- a/app/src/main/java/com/example/myapplication/components/Сategory.kt +++ b/app/src/main/java/com/example/myapplication/components/Сategory.kt @@ -43,33 +43,9 @@ fun Сategory(navController: NavController) { } } } - categories.forEach{ CategoryItem(it.name, { navController.navigate("main/" + it.id)}) } - } } -@Composable -fun myFun(categoryId: Int, title: String){ - - val navController = rememberNavController() - val context = LocalContext.current - val products = remember { mutableStateListOf() } - - LaunchedEffect(Unit) { - withContext(Dispatchers.IO) { - AppDb.getInstance(context).categoryDao().getProductsByCategory(categoryId).collect { data -> - products.clear() - - data.forEach { - products.add(it) - } - } - } - } - - CatalogItems(navController, title, products ) -} - diff --git a/app/src/main/java/com/example/myapplication/database/AppContainer.kt b/app/src/main/java/com/example/myapplication/database/AppContainer.kt new file mode 100644 index 0000000..b0b0d88 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/database/AppContainer.kt @@ -0,0 +1,32 @@ +package com.example.myapplication.database + +import android.content.Context +import com.example.myapplication.database.repository.CategoryRepository +import com.example.myapplication.database.repository.OfflineCategoryRepository +import com.example.myapplication.database.repository.OfflineProductRepository +import com.example.myapplication.database.repository.OfflineUserRepository +import com.example.myapplication.database.repository.ProductRepository +import com.example.myapplication.database.repository.UserRepository + +interface AppContainer { + val userRepository: UserRepository + val productRepository: ProductRepository + val categoryRepository: CategoryRepository +} + +class AppDataContainer(private val context: Context) : AppContainer { + override val userRepository: UserRepository by lazy { + OfflineUserRepository(AppDb.getInstance(context).userDao()) + } + override val productRepository: ProductRepository by lazy { + OfflineProductRepository(AppDb.getInstance(context).productDao()) + } + + override val categoryRepository: CategoryRepository by lazy { + OfflineCategoryRepository(AppDb.getInstance(context).categoryDao()) + } + + companion object { + const val TIMEOUT = 5000L + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/AppDb.kt b/app/src/main/java/com/example/myapplication/database/AppDb.kt index 8345ada..e68afaa 100644 --- a/app/src/main/java/com/example/myapplication/database/AppDb.kt +++ b/app/src/main/java/com/example/myapplication/database/AppDb.kt @@ -96,7 +96,7 @@ abstract class AppDb: RoomDatabase(){ )) val userDao = database.userDao() - userDao.insert(User(1, "Иванов И.И", "ivanov")) + userDao.insert(User(1, "Иванов И.И", "ivanov","ivanov")) database.userDao().addProductCart(UserProductCart(1, 1)) database.userDao().addProductCart(UserProductCart(1, 3)) //database.userDao().addProductCart(UserProductCart(1, 2)) diff --git a/app/src/main/java/com/example/myapplication/database/dao/CategoryDao.kt b/app/src/main/java/com/example/myapplication/database/dao/CategoryDao.kt index a901463..2f55688 100644 --- a/app/src/main/java/com/example/myapplication/database/dao/CategoryDao.kt +++ b/app/src/main/java/com/example/myapplication/database/dao/CategoryDao.kt @@ -11,9 +11,7 @@ import kotlinx.coroutines.flow.Flow interface CategoryDao { @Query("select * from categories") fun getAll(): Flow> + @Insert suspend fun insert(category: Category) - - @Query("select * from products where category_id = :categoryId") - fun getProductsByCategory(categoryId: Int): Flow> } \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/dao/UserDao.kt b/app/src/main/java/com/example/myapplication/database/dao/UserDao.kt index 952fe09..0ee04f5 100644 --- a/app/src/main/java/com/example/myapplication/database/dao/UserDao.kt +++ b/app/src/main/java/com/example/myapplication/database/dao/UserDao.kt @@ -14,13 +14,18 @@ interface UserDao { fun getAll(): Flow> @Query("select * from users where users.userId = :id") - fun getById(id: Int): User + fun getById(id: Int): Flow + @Query("select * from users where users.login = :login and users.password = :password") + fun getByAuth(login: String, password: String): Flow + + @Query("delete from userproductcart where userproductcart.userId == :userId and userproductcart.productId == :productId") + suspend fun deleteCartProduct(userId: Int, productId: Int) @Insert suspend fun insert(user: User) @Query("select * from users where users.userId = :id") - fun getUserProductCartById(id: Int): UserWithCartProduct + fun getUserProductCartById(id: Int): Flow @Insert suspend fun addProductCart(userProduct: UserProductCart) diff --git a/app/src/main/java/com/example/myapplication/database/entities/User.kt b/app/src/main/java/com/example/myapplication/database/entities/User.kt index abbd79e..6814592 100644 --- a/app/src/main/java/com/example/myapplication/database/entities/User.kt +++ b/app/src/main/java/com/example/myapplication/database/entities/User.kt @@ -11,7 +11,9 @@ data class User( @ColumnInfo(name="name") val name: String, @ColumnInfo(name="login") - val login: String + val login: String, + @ColumnInfo(name="password") + val password: String ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/app/src/main/java/com/example/myapplication/database/repository/OfflineCategoryRepository.kt b/app/src/main/java/com/example/myapplication/database/repository/OfflineCategoryRepository.kt new file mode 100644 index 0000000..1dc3108 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/database/repository/OfflineCategoryRepository.kt @@ -0,0 +1,10 @@ +package com.example.myapplication.database.repository + +import com.example.myapplication.database.dao.CategoryDao +import com.example.myapplication.database.entities.Category +import kotlinx.coroutines.flow.Flow + +class OfflineCategoryRepository(private val categoryDao: CategoryDao) : CategoryRepository { + override fun getAll(): Flow> = categoryDao.getAll() + override suspend fun insert(category: Category) = categoryDao.insert(category) +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/repository/OfflineProductRepository.kt b/app/src/main/java/com/example/myapplication/database/repository/OfflineProductRepository.kt new file mode 100644 index 0000000..857fdb6 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/database/repository/OfflineProductRepository.kt @@ -0,0 +1,41 @@ +package com.example.myapplication.database.repository + +import androidx.paging.Pager +import androidx.paging.PagingConfig +import androidx.paging.PagingData +import com.example.myapplication.database.dao.ProductDao +import com.example.myapplication.database.entities.Product +import kotlinx.coroutines.flow.Flow + +class OfflineProductRepository(private val productDao: ProductDao) : ProductRepository { + override fun getAll(): Flow> { + return Pager( + config = PagingConfig( + pageSize = 8, + prefetchDistance = 2, + enablePlaceholders = true, + initialLoadSize = 12, + maxSize = 24 + ), + pagingSourceFactory = { + productDao.getAll() + } + ).flow + } + override fun getById(id: Int): Flow = productDao.getById(id) + override fun getByCategory(category_id: Int): Flow> { + return Pager( + config = PagingConfig( + pageSize = 8, + prefetchDistance = 2, + enablePlaceholders = true, + initialLoadSize = 12, + maxSize = 24 + ), + pagingSourceFactory = { + productDao.getByCategory(category_id) + } + ).flow + } + override suspend fun insert(product: Product) = productDao.insert(product) +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/repository/OfflineUserRepository.kt b/app/src/main/java/com/example/myapplication/database/repository/OfflineUserRepository.kt new file mode 100644 index 0000000..1081416 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/database/repository/OfflineUserRepository.kt @@ -0,0 +1,17 @@ +package com.example.myapplication.database.repository + +import com.example.myapplication.database.dao.UserDao +import com.example.myapplication.database.entities.User +import com.example.myapplication.database.entities.UserProductCart +import com.example.myapplication.database.entities.UserWithCartProduct +import kotlinx.coroutines.flow.Flow + +class OfflineUserRepository(private val userDao: UserDao) : UserRepository { + override fun getAll(): Flow> = userDao.getAll() + override fun getById(id: Int): Flow = userDao.getById(id) + override fun getByAuth(login: String, password: String): Flow = userDao.getByAuth(login, password) + override fun getUserProductCartById(id: Int): Flow = userDao.getUserProductCartById(id) + override suspend fun deleteCartProduct(userId: Int, productId: Int) = userDao.deleteCartProduct(userId, productId) + override suspend fun insert(user: User) = userDao.insert(user) + override suspend fun addProductCart(userItem: UserProductCart) = userDao.addProductCart(userItem) +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/repository/ProductRepository.kt b/app/src/main/java/com/example/myapplication/database/repository/ProductRepository.kt index 0b81544..dbf49ac 100644 --- a/app/src/main/java/com/example/myapplication/database/repository/ProductRepository.kt +++ b/app/src/main/java/com/example/myapplication/database/repository/ProductRepository.kt @@ -1,4 +1,12 @@ package com.example.myapplication.database.repository +import androidx.paging.PagingData +import com.example.myapplication.database.entities.Product +import kotlinx.coroutines.flow.Flow + interface ProductRepository { + fun getAll(): Flow> + fun getById(id: Int): Flow + fun getByCategory(category_id: Int): Flow> + suspend fun insert(product: Product) } \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/database/repository/UserRepository.kt b/app/src/main/java/com/example/myapplication/database/repository/UserRepository.kt index 03a3452..b056e43 100644 --- a/app/src/main/java/com/example/myapplication/database/repository/UserRepository.kt +++ b/app/src/main/java/com/example/myapplication/database/repository/UserRepository.kt @@ -1,16 +1,17 @@ package com.example.myapplication.database.repository import com.example.myapplication.database.entities.User +import com.example.myapplication.database.entities.UserProductCart +import com.example.myapplication.database.entities.UserWithCartProduct import kotlinx.coroutines.flow.Flow interface UserRepository { fun getAll(): Flow> fun getById(id: Int): Flow fun getByAuth(login: String, password: String): Flow - fun getUserItemsCartById(id: Int): Flow - suspend fun deleteCartItem(userId: Int, itemId: Int) - suspend fun deleteFavoriteItem(userId: Int, itemId: Int) + fun getUserProductCartById(id: Int): Flow + suspend fun deleteCartProduct(userId: Int, productId: Int) suspend fun insert(user: User) - suspend fun addItemCart(userItem: UserItemCart) + suspend fun addProductCart(userItem: UserProductCart) } \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/navigation/Navbar.kt b/app/src/main/java/com/example/myapplication/navigation/Navbar.kt index f0dcd17..f621da6 100644 --- a/app/src/main/java/com/example/myapplication/navigation/Navbar.kt +++ b/app/src/main/java/com/example/myapplication/navigation/Navbar.kt @@ -26,7 +26,6 @@ import com.example.myapplication.components.Authorization import com.example.myapplication.components.Cart import com.example.myapplication.components.Main import com.example.myapplication.components.Registration -import com.example.myapplication.components.myFun import com.example.myapplication.components.templates.ProductForPage import com.example.myapplication.components.Сategory import com.example.myapplication.ui.theme.MyApplicationTheme diff --git a/app/src/main/java/com/example/myapplication/viewModels/CategoryViewModel.kt b/app/src/main/java/com/example/myapplication/viewModels/CategoryViewModel.kt new file mode 100644 index 0000000..0716976 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/viewModels/CategoryViewModel.kt @@ -0,0 +1,32 @@ +package com.example.myapplication.viewModels + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewmodel.CreationExtras +import com.example.myapplication.MyApp +import com.example.myapplication.database.entities.Category +import com.example.myapplication.database.repository.CategoryRepository +import com.example.myapplication.database.repository.OfflineCategoryRepository +import kotlinx.coroutines.flow.Flow + +class CategoryViewModel ( + private val categoryRepository: CategoryRepository +): ViewModel() { + companion object { + val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { + override fun create( + modelClass: Class, + extras: CreationExtras + ): T { + + val db = + (checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) as MyApp).db + return CategoryViewModel(OfflineCategoryRepository(db.categoryDao())) as T + } + } + } + + fun getAll(): Flow> { + return categoryRepository.getAll() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/viewModels/ProductViewModel.kt b/app/src/main/java/com/example/myapplication/viewModels/ProductViewModel.kt new file mode 100644 index 0000000..1720436 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/viewModels/ProductViewModel.kt @@ -0,0 +1,46 @@ +package com.example.myapplication.viewModels + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.CreationExtras +import androidx.paging.PagingData +import androidx.paging.cachedIn +import com.example.myapplication.MyApp +import com.example.myapplication.database.entities.Product +import com.example.myapplication.database.repository.OfflineProductRepository +import com.example.myapplication.database.repository.ProductRepository +import kotlinx.coroutines.flow.Flow + +class ProductViewModel( + private val productRepository: ProductRepository +) : ViewModel() { + companion object { + val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory{ + override fun create( + modelClass: Class, + extras: CreationExtras + ) : T { + val db = (checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) as MyApp).db + return ProductViewModel(OfflineProductRepository(db.productDao())) as T + } + } + } + + fun getAll() : Flow> { + return productRepository.getAll().cachedIn(viewModelScope) + } + + fun getById(id: Int) : Flow { + return productRepository.getById(id) + } + + fun getByCategory(cId: Int): Flow> { + return productRepository.getByCategory(cId).cachedIn(viewModelScope) + } + + suspend fun insert(product: Product) { + productRepository.insert(product) + } +} \ No newline at end of file diff --git a/app/src/main/java/com/example/myapplication/viewModels/UserViewModel.kt b/app/src/main/java/com/example/myapplication/viewModels/UserViewModel.kt new file mode 100644 index 0000000..74c9083 --- /dev/null +++ b/app/src/main/java/com/example/myapplication/viewModels/UserViewModel.kt @@ -0,0 +1,62 @@ +package com.example.myapplication.viewModels + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewmodel.CreationExtras +import com.example.myapplication.GlobalUser +import com.example.myapplication.MyApp +import com.example.myapplication.database.entities.User +import com.example.myapplication.database.entities.UserProductCart +import com.example.myapplication.database.entities.UserWithCartProduct +import com.example.myapplication.database.repository.OfflineUserRepository +import com.example.myapplication.database.repository.UserRepository +import kotlinx.coroutines.flow.Flow + +class UserViewModel( + private val userRepository: UserRepository +) : ViewModel() { + companion object { + val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory{ + override fun create( + modelClass: Class, + extras: CreationExtras + ) : T { + + val db = (checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) as MyApp).db + return UserViewModel(OfflineUserRepository(db.userDao())) as T + } + } + } + + fun getUserId(): Int { + return GlobalUser.getInstance().userId + } + + fun setUserId(id: Int) { + GlobalUser.getInstance().userId = id + } + + fun getAll(): Flow> { + return userRepository.getAll() + } + fun getById(id: Int): Flow { + return userRepository.getById(id) + } + fun getByAuth(login: String, password: String): Flow { + return userRepository.getByAuth(login, password) + } + suspend fun deleteCartProduct(userId: Int, productId: Int) { + userRepository.deleteCartProduct(userId, productId) + } + fun getUserProductCartById(id: Int): Flow { + return userRepository.getUserProductCartById(id) + } + + suspend fun insert(user: User) { + userRepository.insert(user) + } + suspend fun addProductCart(userItem: UserProductCart) { + userRepository.addProductCart(userItem) + } + +} \ No newline at end of file