Лаб 3: проблема с соответствием версий, коммит - подушка безопасности

This commit is contained in:
Safgerd 2023-12-06 03:40:09 +04:00
parent ee514f4b1e
commit 270e1fdcf8
31 changed files with 790 additions and 314 deletions

View File

@ -1,6 +1,7 @@
plugins { plugins {
id("com.android.application") id("com.android.application")
id("org.jetbrains.kotlin.android") id("org.jetbrains.kotlin.android")
id ("kotlin-kapt")
} }
android { android {
@ -18,6 +19,9 @@ android {
vectorDrawables { vectorDrawables {
useSupportLibrary = true useSupportLibrary = true
} }
kapt {
arguments {arg("room.schemaLocation", "$projectDir/schemas")}
}
} }
buildTypes { buildTypes {
@ -68,4 +72,8 @@ dependencies {
debugImplementation("androidx.compose.ui:ui-test-manifest") debugImplementation("androidx.compose.ui:ui-test-manifest")
implementation("androidx.navigation:navigation-compose:2.7.3") implementation("androidx.navigation:navigation-compose:2.7.3")
implementation ("androidx.room:room-runtime:2.5.0") // Библиотека "Room"
kapt ("androidx.room:room-compiler:2.5.0") // Кодогенератор
implementation ("androidx.room:room-ktx:2.5.0")
} }

View File

@ -0,0 +1,24 @@
package com.example.mobileapp.dao
import androidx.room.*
import com.example.mobileapp.models.*
import kotlinx.coroutines.flow.Flow
@Dao
interface CategoryDao {
@Insert
suspend fun insert(category: Category)
@Update
suspend fun update(category: Category)
@Delete
suspend fun delete(category: Category)
@Query("select * from category")
fun getAll() : Flow<List<Category>>
@Query("select * from category where category.id = :id")
fun getById(id: Int) : Flow<Category>
@Query("select * from category where category.name = :name")
fun getByName(name: String) : Flow<CategoryWithProducts>
@Query("select * from category")
fun getCatgoryWithProducts() : Flow<List<CategoryWithProducts>>
}

View File

@ -0,0 +1,27 @@
package com.example.mobileapp.dao
import androidx.room.*
import com.example.mobileapp.models.*
import kotlinx.coroutines.flow.Flow
@Dao
interface OrderDao {
@Insert
suspend fun insert(order: Order)
@Update
suspend fun update(order: Order)
@Delete
suspend fun delete(order: Order)
@Query("select * from 'order'")
fun getAll() : Flow<List<OrderWithProducts>>
@Query("select * from 'order' where 'order.id' =:id")
fun getById(id: Int): Flow<List<OrderWithProducts>>
@Query("select * from 'order' where ('order.user_id' =:userId and 'order.status_id' != 1 and 'order.status_id' != 4)")
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>>
@Query("select * from 'order' where ('order.user_id' =:userId and 'order.status_id' = 1)")
fun getCartByUserId(userId: Int): Flow<OrderWithProducts>
@Query("select * from 'order' where ('order.status_id' != 1 and 'order.status_id' != 4)")
fun getOrdersToWork(): Flow<List<OrderWithProducts>>
}

View File

@ -0,0 +1,9 @@
package com.example.mobileapp.dao
import androidx.room.*
import com.example.mobileapp.models.OrderProduct
@Dao
interface OrderProductDao {
@Insert
suspend fun insert(order: OrderProduct)
}

View File

@ -0,0 +1,19 @@
package com.example.mobileapp.dao
import androidx.room.*
import com.example.mobileapp.models.Product
import kotlinx.coroutines.flow.Flow
@Dao
interface ProductDao {
@Insert
suspend fun insert(product: Product)
@Update
suspend fun update(product: Product)
@Delete
suspend fun delete(product: Product)
@Query("select * from product")
fun getAll() : Flow<List<Product>>
@Query("select * from product where product.id = :id")
fun getById(id: Int): Flow<Product>
}

View File

@ -0,0 +1,26 @@
package com.example.mobileapp.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.mobileapp.models.*
import kotlinx.coroutines.flow.Flow
@Dao
interface RoleDao {
@Insert
suspend fun insert(role: Role)
@Update
suspend fun update(role: Role)
@Delete
suspend fun delete(role: Role)
@Query("select * from role")
fun getAll() : Flow<List<Role>>
@Query("select * from role where role.id = :id")
fun getById(id: Int) : Flow<Role>
@Query("select * from role where role.name = :name")
fun getByName(name: String) : Flow<Role>
}

View File

@ -0,0 +1,25 @@
package com.example.mobileapp.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.mobileapp.models.Role
import com.example.mobileapp.models.Status
import kotlinx.coroutines.flow.Flow
@Dao
interface StatusDao {
@Insert
suspend fun insert(status: Status)
@Update
suspend fun update(status: Status)
@Delete
suspend fun delete(status: Status)
@Query("select * from status")
fun getAll() : Flow<List<Status>>
@Query("select * from status where status.id = :id")
fun getById(id: Int) : Flow<Status>
}

View File

@ -0,0 +1,20 @@
package com.example.mobileapp.dao
import androidx.room.*
import com.example.mobileapp.models.User
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Insert
suspend fun insert(user: User)
@Update
suspend fun update(user: User)
@Delete
suspend fun delete(user: User)
@Query("select * from user order by login collate nocase asc")
fun getAll() : Flow<List<User>>
@Query("select * from user where user.id = :id")
fun getById(id: Int): User
}

View File

@ -0,0 +1,158 @@
package com.example.mobileapp.db
import android.content.Context
import androidx.room.*
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.mobileapp.dao.*
import com.example.mobileapp.models.*
import kotlinx.coroutines.*
@Database(
entities =
[
Role::class,
Status::class,
Category::class,
User::class,
Order::class,
Product::class,
OrderProduct::class,
],
version = 1,
exportSchema = false
)
abstract class AppDatabase : RoomDatabase() {
abstract fun roleDao() : RoleDao
abstract fun statusDao() : StatusDao
abstract fun categoryDao() : CategoryDao
abstract fun userDao() : UserDao
abstract fun productDao() : ProductDao
abstract fun orderDao() : OrderDao
abstract fun orderProductDao() : OrderProductDao
companion object {
private const val DB_NAME: String = "mobileapp-db"
@Volatile
private var INSTANCE: AppDatabase? = null
private suspend fun populateDatabase() {
INSTANCE?.let { database ->
//region Roles
val roleDao = database.roleDao()
roleDao.insert(Role(1, "admin"))
roleDao.insert(Role(2, "worker"))
roleDao.insert(Role(3, "user"))
//endregion
//region Statuses
val statusDao = database.statusDao()
statusDao.insert(Status(1, "Корзина"))
statusDao.insert(Status(2, "Принят"))
statusDao.insert(Status(3, "Готов"))
statusDao.insert(Status(4, "Выдан"))
//endregion
//region Categories
val categoryDao = database.categoryDao()
categoryDao.insert(Category(1, "Бургеры"))
categoryDao.insert(Category(2, "Картошка"))
categoryDao.insert(Category(3, "Напитки"))
//endregion
//region Users
val userDao = database.userDao()
userDao.insert(User(1, "admin", "admin", 1))
userDao.insert(User(2, "worker", "worker", 2))
userDao.insert(User(3, "user", "user", 3))
//endregion
//region Products
val productDao = database.productDao()
//Бургеры
productDao.insert(Product(1, "Бургер1", 1, 150))
productDao.insert(Product(2, "Бургер2", 1, 300))
productDao.insert(Product(3, "Бургер3", 1, 450))
//Картошка
productDao.insert(Product(4, "Картошка1", 2, 50))
productDao.insert(Product(5, "Картошка2", 2, 100))
productDao.insert(Product(6, "Картошка3", 2, 150))
//Напитки
productDao.insert(Product(7, "Напиток1", 3, 100))
productDao.insert(Product(8, "Напиток2", 3, 200))
productDao.insert(Product(9, "Напиток3", 3, 300))
//endregion
//region Orders
val orderDao = database.orderDao()
//Корзины
orderDao.insert(Order(1,1,400,1))
orderDao.insert(Order(2,2,600,1))
orderDao.insert(Order(3,3,1800,1))
//Заказы
orderDao.insert(Order(4,1,250,3))
orderDao.insert(Order(5,1,400,2))
orderDao.insert(Order(6,2,750,3))
orderDao.insert(Order(7,2,550,2))
orderDao.insert(Order(8,3,400,3))
orderDao.insert(Order(9,3,250,2))
//endregion
//region OrderProducts
val orderProductDao = database.orderProductDao()
//Корзины
//1
orderProductDao.insert(OrderProduct(1,1,2))
orderProductDao.insert(OrderProduct(1,7,1))
//2
orderProductDao.insert(OrderProduct(2,2,1))
orderProductDao.insert(OrderProduct(2,5,1))
orderProductDao.insert(OrderProduct(2,8,1))
//3
orderProductDao.insert(OrderProduct(3,3,2))
orderProductDao.insert(OrderProduct(3,6,2))
orderProductDao.insert(OrderProduct(3,9,2))
//Заказы
//1
orderProductDao.insert(OrderProduct(4,1,1))
orderProductDao.insert(OrderProduct(4,7,1))
//2
orderProductDao.insert(OrderProduct(5,2,1))
orderProductDao.insert(OrderProduct(5,5,1))
//3
orderProductDao.insert(OrderProduct(6,2,1))
orderProductDao.insert(OrderProduct(6,3,1))
//4
orderProductDao.insert(OrderProduct(7,3,1))
orderProductDao.insert(OrderProduct(7,7,1))
//5
orderProductDao.insert(OrderProduct(8,2,1))
orderProductDao.insert(OrderProduct(8,7,1))
//6
orderProductDao.insert(OrderProduct(9,4,1))
orderProductDao.insert(OrderProduct(9,8,1))
//endregion
}
}
fun getInstance(appContext: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
Room.databaseBuilder(
appContext,
AppDatabase::class.java,
DB_NAME
)
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
CoroutineScope(Dispatchers.IO).launch {
populateDatabase()
}
}
})
.build()
.also { INSTANCE = it }
}
}
}
}

View File

@ -1,17 +0,0 @@
package com.example.mobileapp.models
data class Cart(
val id: Int,
val userId: Int,
val price: Int?,
)
fun getCarts(): List<Cart> {
return listOf(
Cart(1,1, getCartProductsByCartId(1).sumOf { getProductById(it.productId).price * it.amount }),
)
}
fun getCartByUserId(id: Int): Cart{
return getCarts().find { it.userId == id }!!
}

View File

@ -1,19 +0,0 @@
package com.example.mobileapp.models
data class CartProduct(
val cartId: Int,
val productId: Int,
val amount: Int,
)
fun getAllCartProducts(): List<CartProduct> {
return listOf(
CartProduct(1, 1, 2),
CartProduct(1, 4, 1),
CartProduct(1, 7, 1),
)
}
fun getCartProductsByCartId(id: Int): List<CartProduct> {
return getAllCartProducts().filter { it.cartId == id }
}

View File

@ -1,18 +1,22 @@
package com.example.mobileapp.models package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "category")
data class Category( data class Category(
val id: Int, @PrimaryKey(autoGenerate = true)
val title: String, @ColumnInfo(name = "id")
) val id: Int?,
@ColumnInfo(name = "name")
val name: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Category
return id == other.id
}
fun getCategories():List<Category>{ override fun hashCode(): Int {
return listOf( return id ?: -1
Category(1, "Бургеры"), }
Category(2, "Картошка"),
Category(3, "Напитки"),
)
}
fun getCategoryById(id: Int):String{
return getCategories().find{ it.id == id }!!.title
} }

View File

@ -0,0 +1,9 @@
package com.example.mobileapp.models
import androidx.room.*
data class CategoryWithProducts(
@Embedded
val category: Category,
@Relation(parentColumn = "id", entityColumn = "category_id")
val products: List<Product>
)

View File

@ -1,21 +1,31 @@
package com.example.mobileapp.models package com.example.mobileapp.models
import androidx.room.*
data class Order( @Entity(
val id: Int, tableName = "order",
val userId: Int, foreignKeys = [
val price: Int, ForeignKey(User::class, ["id"], ["user_id"])
val status: String ]
) )
data class Order(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "user_id")
val userId: Int,
@ColumnInfo(name = "price")
val price: Int,
@ColumnInfo(name = "status_id")
val statusId: Int,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Order
return id == other.id
}
fun getOrders(): List<Order> { override fun hashCode(): Int {
return listOf( return id ?: -1
Order(1,1, getOrderProductsByOrderId(1).sumOf { getProductById(it.productId).price * it.amount }, "Принят"), }
Order(2,1, getOrderProductsByOrderId(2).sumOf { getProductById(it.productId).price * it.amount }, "Принят"),
)
} }
fun getOrdersByUserId(id: Int): List<Order>{
return getOrders().filter { it.userId == id }
}

View File

@ -1,22 +1,12 @@
package com.example.mobileapp.models package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "order_product", primaryKeys = ["order_id", "product_id"])
data class OrderProduct( data class OrderProduct(
val orderId: Int, @ColumnInfo(name = "order_id", index = true)
val productId: Int, var orderId: Int,
val amount: Int, @ColumnInfo(name = "product_id", index = true)
var productId: Int,
@ColumnInfo(name = "amount")
val amount: Int
) )
fun getAllOrderProducts(): List<OrderProduct> {
return listOf(
OrderProduct(1, 1, 2),
OrderProduct(1, 4, 1),
OrderProduct(1, 7, 1),
OrderProduct(2, 1, 2),
OrderProduct(2, 4, 1),
OrderProduct(2, 7, 1),
)
}
fun getOrderProductsByOrderId(id: Int): List<OrderProduct> {
return getAllOrderProducts().filter { it.orderId == id }
}

View File

@ -0,0 +1,9 @@
package com.example.mobileapp.models
import androidx.room.*
data class OrderProductWithProduct(
@Embedded
val orderProduct: OrderProduct,
@Relation(entity = Product::class, parentColumn = "product_id", entityColumn = "id")
val product: Product
)

View File

@ -0,0 +1,9 @@
package com.example.mobileapp.models
import androidx.room.*
data class OrderWithProducts(
@Embedded
val order: Order,
@Relation(entity = OrderProduct::class, parentColumn = "id", entityColumn = "order_id")
val orderWithProducts: List<OrderProductWithProduct>
)

View File

@ -1,32 +1,26 @@
package com.example.mobileapp.models package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "product")
data class Product( data class Product(
val id: Int, @PrimaryKey(autoGenerate = true)
val picture: String, @ColumnInfo(name = "id")
val title: String, val id: Int?,
val category: Int, @ColumnInfo(name = "name")
val price: Int, val name: String,
) @ColumnInfo(name = "category_id")
val categoryId: Int,
@ColumnInfo(name = "price")
val price: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Product
return id == other.id
}
override fun hashCode(): Int {
fun getProducts() :List<Product> { return id ?: -1
return listOf( }
Product(1, "Бургер", "Бургер1", 1,150),
Product(2, "Бургер", "Бургер2", 1,300),
Product(3, "Бургер", "Бургер3", 1,450),
Product(4, "Картошка", "Картошка1", 2,100),
Product(5, "Картошка", "Картошка2", 2,200),
Product(6, "Картошка", "Картошка3", 2,300),
Product(7, "Пепси", "Пепси1", 3,50),
Product(8, "Пепси", "Пепси2", 3,100),
Product(9, "Пепси", "Пепси3", 3,150),
)
} }
fun getProductsByCategoryId(id: Int) :List<Product> {
return getProducts().filter { it.category == id }
}
fun getProductById(id: Int) : Product {
return getProducts().find{ it.id == id }!!
}

View File

@ -0,0 +1,22 @@
package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "role")
data class Role(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "name")
val name: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Role
return id == other.id
}
override fun hashCode(): Int {
return id ?: -1
}
}

View File

@ -1,30 +0,0 @@
package com.example.mobileapp.models
enum class Roles(val roleId: Int) {
admin(0),
worker(1),
user(2);
companion object{
fun fromId(id: Int): Roles? {
return values().find { it.roleId == id }
}
}
}
data class Role(
val id: Int,
val title: String,
)
fun getRoles():List<Role>{
return listOf(
Role(1, "admin"),
Role(2, "worker"),
Role(3, "user"),
)
}
fun getRoleById(id: Int):String{
return getRoles().find{ it.id == id }!!.title
}

View File

@ -0,0 +1,22 @@
package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "status")
data class Status(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "name")
val name: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Status
return id == other.id
}
override fun hashCode(): Int {
return id ?: -1
}
}

View File

@ -1,20 +1,26 @@
package com.example.mobileapp.models package com.example.mobileapp.models
import androidx.room.*
@Entity(tableName = "user")
data class User( data class User(
val id: Int, @PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "login")
val login: String, val login: String,
@ColumnInfo(name = "password")
val password: String, val password: String,
val role: Roles @ColumnInfo(name = "role_id")
) val roleId: Int
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as User
return id == other.id
}
fun getAllUsers():List<User>{ override fun hashCode(): Int {
return listOf( return id ?: -1
User(1, "admin", "admin", Roles.admin), }
User(2, "worker", "worker", Roles.worker),
User(3, "user", "user", Roles.user),
)
}
fun currentUser():User{
return getAllUsers()[0]
} }

View File

@ -13,9 +13,13 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.navigation.NavController import androidx.navigation.NavController
@ -23,8 +27,8 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.rememberNavController
import com.example.mobileapp.models.Roles import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.currentUser import com.example.mobileapp.models.User
import com.example.mobileapp.screens.AuthorizationScreen import com.example.mobileapp.screens.AuthorizationScreen
import com.example.mobileapp.screens.CartScreen import com.example.mobileapp.screens.CartScreen
import com.example.mobileapp.screens.CreateProductScreen import com.example.mobileapp.screens.CreateProductScreen
@ -36,6 +40,9 @@ import com.example.mobileapp.screens.OrderScreen
import com.example.mobileapp.screens.ProfileScreen import com.example.mobileapp.screens.ProfileScreen
import com.example.mobileapp.screens.RegistrationScreen import com.example.mobileapp.screens.RegistrationScreen
import com.example.mobileapp.screens.UsersScreen import com.example.mobileapp.screens.UsersScreen
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.withContext
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@ -84,13 +91,24 @@ fun CustomNavigationBar(navController: NavController) {
.background(Color(212, 206, 203)) .background(Color(212, 206, 203))
) { ) {
var listOfNavItems : List<NavItem>? = null var listOfNavItems : List<NavItem>? = null
val user = remember { mutableStateOf(User(-1, "", "", -1)) }
when (currentUser().role.name) { val context = LocalContext.current
Roles.admin.name -> listOfNavItems = listOfAdminNavItems LaunchedEffect(Unit) {
Roles.worker.name -> listOfNavItems = listOfWorkerNavItems withContext(Dispatchers.IO) {
Roles.user.name -> listOfNavItems = listOfUserNavItems user.value = AppDatabase.getInstance(context).userDao().getById(1)
(AppDatabase.getInstance(context).roleDao().getByName("admin")).collect{
if (it.id == user.value.roleId) { listOfNavItems = listOfAdminNavItems }
}
(AppDatabase.getInstance(context).roleDao().getByName("worker")).collect{
if (it.id == user.value.roleId) { listOfNavItems = listOfWorkerNavItems }
}
(AppDatabase.getInstance(context).roleDao().getByName("user")).collect{
if (it.id == user.value.roleId) { listOfNavItems = listOfUserNavItems }
}
}
} }
listOfNavItems?.forEachIndexed { index, navItem -> listOfNavItems?.forEachIndexed { index, navItem ->
OutlinedButton( OutlinedButton(
modifier = Modifier modifier = Modifier
@ -105,7 +123,7 @@ fun CustomNavigationBar(navController: NavController) {
border = BorderStroke(4.dp, Color(222,161,69)), border = BorderStroke(4.dp, Color(222,161,69)),
shape = RoundedCornerShape( shape = RoundedCornerShape(
topStart = if (index == 0) 30.dp else 0.dp, topStart = if (index == 0) 30.dp else 0.dp,
topEnd = if (index == listOfNavItems.size - 1) 30.dp else 0.dp topEnd = if (index == listOfNavItems!!.size - 1) 30.dp else 0.dp
), ),
colors = ButtonDefaults.outlinedButtonColors(Color(255,186,83)), colors = ButtonDefaults.outlinedButtonColors(Color(255,186,83)),

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.screens package com.example.mobileapp.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
@ -19,11 +20,14 @@ import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
@ -32,11 +36,14 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.currentUser import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getCartByUserId import com.example.mobileapp.models.CategoryWithProducts
import com.example.mobileapp.models.getCartProductsByCartId import com.example.mobileapp.models.Order
import com.example.mobileapp.models.getProductById import com.example.mobileapp.models.OrderWithProducts
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable @Composable
fun CartScreen(){ fun CartScreen(){
@ -49,6 +56,7 @@ fun CartScreen(){
} }
} }
@SuppressLint("CoroutineCreationDuringComposition")
@Composable @Composable
fun CartCard(){ fun CartCard(){
Column( Column(
@ -76,15 +84,24 @@ fun CartCard(){
.padding(top = 10.dp), .padding(top = 10.dp),
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val cart = getCartByUserId(currentUser().id) val cartWithProducts = remember { mutableStateOf(OrderWithProducts(Order(-1, -1, -1, -1), listOf())) }
val cartProducts = getCartProductsByCartId(cart.id) val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).orderDao().getCartByUserId(1).collect { data ->
cartWithProducts.value = data
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
) { ) {
items(cartProducts){ cartProduct -> items(cartWithProducts.value.orderWithProducts){ cartProduct ->
val amount = remember { mutableStateOf(TextFieldValue(cartProduct.amount.toString())) } val amount = remember { mutableStateOf(TextFieldValue(cartProduct.orderProduct.amount.toString())) }
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -99,7 +116,13 @@ fun CartCard(){
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
){ ){
if (getProductById(cartProduct.productId).picture == "Бургер"){ val category = remember { mutableStateOf("")}
scope.launch {
AppDatabase.getInstance(context).categoryDao().getById(cartProduct.product.categoryId).collect { data ->
category.value = data.name
}
}
if (category.value == "Бургер"){
Image( Image(
painterResource( painterResource(
id = R.drawable.burger id = R.drawable.burger
@ -110,7 +133,7 @@ fun CartCard(){
.padding(5.dp), .padding(5.dp),
) )
} }
if (getProductById(cartProduct.productId).picture == "Картошка"){ if (category.value == "Картошка"){
Image( Image(
painterResource( painterResource(
id = R.drawable.potato id = R.drawable.potato
@ -121,7 +144,7 @@ fun CartCard(){
.padding(5.dp), .padding(5.dp),
) )
} }
if (getProductById(cartProduct.productId).picture == "Пепси"){ if (category.value == "Напитки"){
Image( Image(
painterResource( painterResource(
id = R.drawable.pepsi id = R.drawable.pepsi
@ -138,14 +161,14 @@ fun CartCard(){
verticalArrangement = Arrangement.SpaceAround verticalArrangement = Arrangement.SpaceAround
) { ) {
Text( Text(
text = getProductById(cartProduct.productId).title, text = cartProduct.product.name,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 17.sp, fontSize = 17.sp,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
Text( Text(
text = getProductById(cartProduct.productId).price.toString() + " р.", text = cartProduct.product.price.toString() + " р.",
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 17.sp, fontSize = 17.sp,
@ -221,7 +244,7 @@ fun CartCard(){
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
){ ){
Text( Text(
text = "Итого: " + cart.price.toString() + " р.", text = "Итого: " + cartWithProducts.value.order.price.toString() + " р.",
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 20.sp, fontSize = 20.sp,

View File

@ -2,10 +2,7 @@ package com.example.mobileapp.screens
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@ -25,24 +22,28 @@ import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.lightColorScheme import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.getCategories import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable @Composable
fun CreateProductScreen(){ fun CreateProductScreen(){
@ -83,9 +84,20 @@ fun CreateProductCard(){
.padding(top = 10.dp), .padding(top = 10.dp),
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val picture = remember { mutableStateOf(TextFieldValue("")) } val categoryList = remember { mutableStateListOf<String>() }
var expanded by remember { mutableStateOf(false) }
val title = remember { mutableStateOf(TextFieldValue("")) } val title = remember { mutableStateOf(TextFieldValue("")) }
val price = remember { mutableStateOf(TextFieldValue("")) } val price = remember { mutableStateOf(TextFieldValue("")) }
val context = LocalContext.current
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).categoryDao().getAll().collect { data ->
categoryList.clear()
categoryList.addAll(data.map { it.name })
}
}
}
var selectedCategory by remember { mutableStateOf(categoryList[0]) }
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
@ -96,25 +108,6 @@ fun CreateProductCard(){
Column ( Column (
modifier = Modifier.background(Color.White) modifier = Modifier.background(Color.White)
) { ) {
OutlinedTextField(
value = picture.value,
onValueChange = {picture.value = it},
placeholder = { Text(text = "Фото", fontSize = 20.sp, color = Color.LightGray) },
singleLine = true,
shape = RoundedCornerShape(20.dp),
textStyle = TextStyle(fontSize = 20.sp),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = Color.Black,
disabledTextColor = Color.Transparent,
containerColor = Color.White,
focusedBorderColor = Color(222,161,69),
unfocusedBorderColor = Color(222,161,69),
),
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp, start = 20.dp, end = 20.dp),
)
OutlinedTextField( OutlinedTextField(
value = title.value, value = title.value,
onValueChange = {title.value = it}, onValueChange = {title.value = it},
@ -139,9 +132,6 @@ fun CreateProductCard(){
border = BorderStroke(1.dp, Color(222,161,69)), border = BorderStroke(1.dp, Color(222,161,69)),
modifier = Modifier.fillMaxWidth().padding(top = 20.dp, start = 20.dp, end = 20.dp), modifier = Modifier.fillMaxWidth().padding(top = 20.dp, start = 20.dp, end = 20.dp),
){ ){
val dataList = getCategories().map { it.title }
var expanded by remember { mutableStateOf(false) }
var selectedItem by remember { mutableStateOf(dataList[0]) }
MaterialTheme( MaterialTheme(
colorScheme = lightColorScheme( colorScheme = lightColorScheme(
surfaceVariant= Color.White, surfaceVariant= Color.White,
@ -159,7 +149,7 @@ fun CreateProductCard(){
modifier = Modifier modifier = Modifier
.menuAnchor().fillMaxWidth(), .menuAnchor().fillMaxWidth(),
readOnly = true, readOnly = true,
value = selectedItem, value = selectedCategory,
onValueChange = {}, onValueChange = {},
label = { Text("Категория") }, label = { Text("Категория") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
@ -171,11 +161,11 @@ fun CreateProductCard(){
expanded = false expanded = false
}, },
) { ) {
dataList.forEach { selectionOption -> categoryList.forEach { selectionOption ->
DropdownMenuItem( DropdownMenuItem(
text = { Text(selectionOption) }, text = { Text(selectionOption) },
onClick = { onClick = {
selectedItem = selectionOption selectedCategory = selectionOption
expanded = false expanded = false
}, },
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding, contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,

View File

@ -20,9 +20,13 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
@ -31,10 +35,12 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.getCategories import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getProductsByCategoryId import com.example.mobileapp.models.CategoryWithProducts
import com.example.mobileapp.navigation.Screens import com.example.mobileapp.navigation.Screens
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable @Composable
fun EditMenuScreen(navController: NavController){ fun EditMenuScreen(navController: NavController){
@ -64,14 +70,25 @@ fun EditMenuCard(navController: NavController){
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
val categories = getCategories() val categoryWithProducts = remember { mutableListOf<CategoryWithProducts>()}
val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).categoryDao().getCatgoryWithProducts().collect { data ->
categoryWithProducts.addAll(data)
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
) { ) {
items(categories){ category -> items(categoryWithProducts){ item ->
Text( Text(
text = category.title, text = item.category.name,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 34.sp, fontSize = 34.sp,
@ -81,9 +98,7 @@ fun EditMenuCard(navController: NavController){
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val products = getProductsByCategoryId(category.id) item.products.forEach{ product ->
products.forEach{ product ->
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -98,7 +113,7 @@ fun EditMenuCard(navController: NavController){
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
){ ){
if (product.picture == "Бургер"){ if (item.category.name == "Бургеры"){
Image( Image(
painterResource( painterResource(
id = R.drawable.burger id = R.drawable.burger
@ -109,7 +124,7 @@ fun EditMenuCard(navController: NavController){
.padding(5.dp), .padding(5.dp),
) )
} }
if (product.picture == "Картошка"){ if (item.category.name == "Картошка"){
Image( Image(
painterResource( painterResource(
id = R.drawable.potato id = R.drawable.potato
@ -120,7 +135,7 @@ fun EditMenuCard(navController: NavController){
.padding(5.dp), .padding(5.dp),
) )
} }
if (product.picture == "Пепси"){ if (item.category.name == "Напитки"){
Image( Image(
painterResource( painterResource(
id = R.drawable.pepsi id = R.drawable.pepsi
@ -137,7 +152,7 @@ fun EditMenuCard(navController: NavController){
verticalArrangement = Arrangement.SpaceAround verticalArrangement = Arrangement.SpaceAround
) { ) {
Text( Text(
text = product.title, text = product.name,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 17.sp, fontSize = 17.sp,

View File

@ -22,13 +22,16 @@ import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.lightColorScheme import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
@ -37,10 +40,10 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.getCategories import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getCategoryById
import com.example.mobileapp.models.getProductById
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable @Composable
fun EditProductScreen(id: Int){ fun EditProductScreen(id: Int){
@ -81,12 +84,28 @@ fun EditProductCard(id: Int){
.padding(top = 10.dp), .padding(top = 10.dp),
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val product = getProductById(id) val context = LocalContext.current
val categoryList = remember { mutableStateListOf<String>() }
val picture = remember { mutableStateOf(TextFieldValue(product.picture)) } var selectedCategory by remember { mutableStateOf("") }
val title = remember { mutableStateOf(TextFieldValue(product.title)) } var expanded by remember { mutableStateOf(false) }
val price = remember { mutableStateOf(TextFieldValue(product.price.toString())) } val title = remember { mutableStateOf(TextFieldValue("")) }
val price = remember { mutableStateOf(TextFieldValue("")) }
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).productDao().getById(id).collect {data ->
title.value = TextFieldValue(data.name)
price.value = TextFieldValue(data.price.toString())
AppDatabase.getInstance(context).categoryDao().getById(data.categoryId).collect {
selectedCategory = it.name
}
}
AppDatabase.getInstance(context).categoryDao().getAll().collect { data ->
categoryList.clear()
categoryList.addAll(data.map { it.name })
}
}
}
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -96,25 +115,6 @@ fun EditProductCard(id: Int){
Column ( Column (
modifier = Modifier.background(Color.White) modifier = Modifier.background(Color.White)
) { ) {
OutlinedTextField(
value = picture.value,
onValueChange = {picture.value = it},
placeholder = { Text(text = "Фото", fontSize = 20.sp, color = Color.LightGray) },
singleLine = true,
shape = RoundedCornerShape(20.dp),
textStyle = TextStyle(fontSize = 20.sp),
colors = TextFieldDefaults.outlinedTextFieldColors(
textColor = Color.Black,
disabledTextColor = Color.Transparent,
containerColor = Color.White,
focusedBorderColor = Color(222,161,69),
unfocusedBorderColor = Color(222,161,69),
),
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp, start = 20.dp, end = 20.dp),
)
OutlinedTextField( OutlinedTextField(
value = title.value, value = title.value,
onValueChange = {title.value = it}, onValueChange = {title.value = it},
@ -139,9 +139,6 @@ fun EditProductCard(id: Int){
border = BorderStroke(1.dp, Color(222,161,69)), border = BorderStroke(1.dp, Color(222,161,69)),
modifier = Modifier.fillMaxWidth().padding(top = 20.dp, start = 20.dp, end = 20.dp), modifier = Modifier.fillMaxWidth().padding(top = 20.dp, start = 20.dp, end = 20.dp),
){ ){
val dataList = getCategories().map { it.title }
var expanded by remember { mutableStateOf(false) }
var selectedItem by remember { mutableStateOf(getCategoryById(product.category)) }
MaterialTheme( MaterialTheme(
colorScheme = lightColorScheme( colorScheme = lightColorScheme(
surfaceVariant= Color.White, surfaceVariant= Color.White,
@ -159,7 +156,7 @@ fun EditProductCard(id: Int){
modifier = Modifier modifier = Modifier
.menuAnchor().fillMaxWidth(), .menuAnchor().fillMaxWidth(),
readOnly = true, readOnly = true,
value = selectedItem, value = selectedCategory,
onValueChange = {}, onValueChange = {},
label = { Text("Категория") }, label = { Text("Категория") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
@ -171,11 +168,11 @@ fun EditProductCard(id: Int){
expanded = false expanded = false
}, },
) { ) {
dataList.forEach { selectionOption -> categoryList.forEach { selectionOption ->
DropdownMenuItem( DropdownMenuItem(
text = { Text(selectionOption) }, text = { Text(selectionOption) },
onClick = { onClick = {
selectedItem = selectionOption selectedCategory = selectionOption
expanded = false expanded = false
}, },
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding, contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,

View File

@ -19,9 +19,14 @@ import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
@ -29,9 +34,12 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.getCategories import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getProductsByCategoryId import com.example.mobileapp.models.Category
import com.example.mobileapp.models.CategoryWithProducts
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@Composable @Composable
fun MenuScreen(){ fun MenuScreen(){
@ -61,14 +69,27 @@ fun MenuCard(){
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
) { ) {
val categories = getCategories() val categoryWithProducts = remember { mutableListOf<CategoryWithProducts>()}
val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).categoryDao().getCatgoryWithProducts().collect { data ->
categoryWithProducts.addAll(data)
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
) { ) {
items(categories){ category -> items(categoryWithProducts){ item ->
Text( Text(
text = category.title, text = item.category.name,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 34.sp, fontSize = 34.sp,
@ -78,9 +99,7 @@ fun MenuCard(){
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val products = getProductsByCategoryId(category.id) item.products.forEach{ product ->
products.forEach{ product ->
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -95,7 +114,7 @@ fun MenuCard(){
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
){ ){
if (product.picture == "Бургер"){ if (item.category.name == "Бургеры"){
Image( Image(
painterResource( painterResource(
id = R.drawable.burger id = R.drawable.burger
@ -106,7 +125,7 @@ fun MenuCard(){
.padding(5.dp), .padding(5.dp),
) )
} }
if (product.picture == "Картошка"){ if (item.category.name == "Картошка"){
Image( Image(
painterResource( painterResource(
id = R.drawable.potato id = R.drawable.potato
@ -117,7 +136,7 @@ fun MenuCard(){
.padding(5.dp), .padding(5.dp),
) )
} }
if (product.picture == "Пепси"){ if (item.category.name == "Напитки"){
Image( Image(
painterResource( painterResource(
id = R.drawable.pepsi id = R.drawable.pepsi
@ -134,7 +153,7 @@ fun MenuCard(){
verticalArrangement = Arrangement.SpaceAround verticalArrangement = Arrangement.SpaceAround
) { ) {
Text( Text(
text = product.title, text = product.name,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 17.sp, fontSize = 17.sp,

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.screens package com.example.mobileapp.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@ -17,20 +18,27 @@ import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.currentUser import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getOrderProductsByOrderId import com.example.mobileapp.models.Order
import com.example.mobileapp.models.getOrdersByUserId import com.example.mobileapp.models.OrderWithProducts
import com.example.mobileapp.models.getProductById
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable @Composable
fun OrderScreen(){ fun OrderScreen(){
@ -43,6 +51,7 @@ fun OrderScreen(){
} }
} }
@SuppressLint("CoroutineCreationDuringComposition")
@Composable @Composable
fun OrderCard(){ fun OrderCard(){
Column( Column(
@ -71,14 +80,29 @@ fun OrderCard(){
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val orders = getOrdersByUserId(currentUser().id) val ordersWithProducts = remember { mutableListOf<OrderWithProducts> () }
val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).orderDao().getOrdersToWork().collect { data ->
ordersWithProducts.addAll(data)
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
) { ) {
items(orders){ order -> items(ordersWithProducts){ order ->
val orderProducts = getOrderProductsByOrderId(order.id) val status = remember { mutableStateOf("")}
scope.launch {
AppDatabase.getInstance(context).statusDao().getById(order.order.statusId).collect { data ->
status.value = data.name
}
}
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -93,7 +117,7 @@ fun OrderCard(){
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
){ ){
Text( Text(
text = "" + order.id.toString(), text = "" + order.order.id,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 34.sp, fontSize = 34.sp,
@ -101,7 +125,7 @@ fun OrderCard(){
) )
Text( Text(
text = "Статус: " + order.status, text = "Статус: " + status,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 20.sp, fontSize = 20.sp,
@ -117,7 +141,7 @@ fun OrderCard(){
horizontalArrangement = Arrangement.SpaceAround, horizontalArrangement = Arrangement.SpaceAround,
){ ){
Column { Column {
orderProducts.forEach{ orderProduct -> order.orderWithProducts.forEach{ orderProduct ->
Row( Row(
modifier = Modifier modifier = Modifier
.background(Color.White), .background(Color.White),
@ -125,7 +149,7 @@ fun OrderCard(){
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
){ ){
Text( Text(
text = getProductById(orderProduct.productId).title + " x" + orderProduct.amount.toString(), text = orderProduct.product.name + " x" + orderProduct.orderProduct.amount.toString(),
color = Color.Gray, color = Color.Gray,
fontFamily = FontFamily(Font(R.font.nunito_bold)), fontFamily = FontFamily(Font(R.font.nunito_bold)),
fontSize = 20.sp, fontSize = 20.sp,
@ -134,21 +158,39 @@ fun OrderCard(){
} }
} }
} }
if (order.order.statusId == 2){
OutlinedButton( OutlinedButton(
onClick = { onClick = {
/*TODO*/ /*TODO*/
}, },
border = BorderStroke(4.dp, Color(222,161,69)), border = BorderStroke(4.dp, Color(222,161,69)),
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults.outlinedButtonColors(Color(255,186,83)), colors = ButtonDefaults.outlinedButtonColors(Color(255,186,83)),
) { ) {
Text( Text(
text = "Готов", text = "Готов",
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 30.sp, fontSize = 30.sp,
color = Color.White color = Color.White
) )
}
}
if (order.order.statusId == 3){
OutlinedButton(
onClick = {
/*TODO*/
},
border = BorderStroke(4.dp, Color(222,161,69)),
shape = RoundedCornerShape(20.dp),
colors = ButtonDefaults.outlinedButtonColors(Color(255,186,83)),
) {
Text(
text = "Выдать",
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 30.sp,
color = Color.White
)
}
} }
} }
} }

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.screens package com.example.mobileapp.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@ -17,9 +18,14 @@ import androidx.compose.material3.Card
import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
@ -27,12 +33,13 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.navigation.NavController import androidx.navigation.NavController
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.currentUser import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getOrderProductsByOrderId import com.example.mobileapp.models.OrderWithProducts
import com.example.mobileapp.models.getOrdersByUserId
import com.example.mobileapp.models.getProductById
import com.example.mobileapp.navigation.Screens import com.example.mobileapp.navigation.Screens
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable @Composable
fun ProfileScreen(navController: NavController){ fun ProfileScreen(navController: NavController){
@ -45,6 +52,7 @@ fun ProfileScreen(navController: NavController){
} }
} }
@SuppressLint("CoroutineCreationDuringComposition")
@Composable @Composable
fun ProfileCard(navController: NavController){ fun ProfileCard(navController: NavController){
Column( Column(
@ -95,14 +103,23 @@ fun ProfileCard(navController: NavController){
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val orders = getOrdersByUserId(currentUser().id) val ordersWithProducts = remember { mutableListOf<OrderWithProducts> () }
val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).orderDao().getByUserId(1).collect { data ->
ordersWithProducts.addAll(data)
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
) { ) {
items(orders){ order -> items(ordersWithProducts){ order ->
val orderProducts = getOrderProductsByOrderId(order.id)
Card( Card(
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
border = BorderStroke(3.dp, Color(222,161,69)), border = BorderStroke(3.dp, Color(222,161,69)),
@ -117,22 +134,27 @@ fun ProfileCard(navController: NavController){
horizontalArrangement = Arrangement.SpaceEvenly, horizontalArrangement = Arrangement.SpaceEvenly,
){ ){
Text( Text(
text = "" + order.id.toString(), text = "" + order.order.id.toString(),
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 34.sp, fontSize = 34.sp,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val status = remember { mutableStateOf("")}
scope.launch {
AppDatabase.getInstance(context).statusDao().getById(order.order.statusId).collect { data ->
status.value = data.name
}
}
Text( Text(
text = "Статус: " + order.status, text = "Статус: " + status.value,
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),
fontSize = 20.sp, fontSize = 20.sp,
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
} }
orderProducts.forEach{ orderProduct -> order.orderWithProducts.forEach{ orderProduct ->
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@ -141,7 +163,7 @@ fun ProfileCard(navController: NavController){
horizontalArrangement = Arrangement.Center, horizontalArrangement = Arrangement.Center,
){ ){
Text( Text(
text = getProductById(orderProduct.productId).title + " " + getProductById(orderProduct.productId).price.toString() + "р. x" + orderProduct.amount.toString(), text = orderProduct.product.name + " " + orderProduct.product.price.toString() + "р. x" + orderProduct.orderProduct.amount.toString(),
color = Color.Gray, color = Color.Gray,
fontFamily = FontFamily(Font(R.font.nunito_bold)), fontFamily = FontFamily(Font(R.font.nunito_bold)),
fontSize = 20.sp, fontSize = 20.sp,
@ -157,7 +179,7 @@ fun ProfileCard(navController: NavController){
horizontalArrangement = Arrangement.Start, horizontalArrangement = Arrangement.Start,
){ ){
Text( Text(
text = "К оплате: " + order.price.toString() + " р.", text = "К оплате: " + order.order.price.toString() + " р.",
modifier = Modifier.padding(start = 20.dp), modifier = Modifier.padding(start = 20.dp),
color = Color.Black, color = Color.Black,
fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)), fontFamily = FontFamily(Font(R.font.nunito_extrabold_italic)),

View File

@ -1,5 +1,6 @@
package com.example.mobileapp.screens package com.example.mobileapp.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
@ -28,13 +29,17 @@ import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material3.lightColorScheme import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.Font
@ -45,12 +50,12 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import com.example.mobileapp.R import com.example.mobileapp.R
import com.example.mobileapp.models.currentUser import com.example.mobileapp.db.AppDatabase
import com.example.mobileapp.models.getAllUsers import com.example.mobileapp.models.User
import com.example.mobileapp.models.getCategories
import com.example.mobileapp.models.getRoleById
import com.example.mobileapp.models.getRoles
import com.example.mobileapp.widgets.Header import com.example.mobileapp.widgets.Header
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable @Composable
fun UsersScreen() { fun UsersScreen() {
@ -63,7 +68,7 @@ fun UsersScreen() {
} }
} }
@Preview @SuppressLint("CoroutineCreationDuringComposition")
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun UsersCard(){ fun UsersCard(){
@ -92,7 +97,18 @@ fun UsersCard(){
.padding(top = 10.dp), .padding(top = 10.dp),
textAlign = TextAlign.Center, textAlign = TextAlign.Center,
) )
val users = getAllUsers() val users = remember { mutableListOf<User> () }
val context = LocalContext.current
val scope = rememberCoroutineScope()
LaunchedEffect(Unit) {
withContext(Dispatchers.IO) {
AppDatabase.getInstance(context).userDao().getAll().collect { data ->
users.addAll(data)
}
}
}
LazyColumn( LazyColumn(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@ -130,9 +146,18 @@ fun UsersCard(){
border = BorderStroke(1.dp, Color(222,161,69)), border = BorderStroke(1.dp, Color(222,161,69)),
modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 10.dp),
){ ){
val dataList = getRoles().map { it.title } val roleList = remember { mutableStateListOf<String>() }
var expanded by remember { mutableStateOf(false) } var expanded by remember { mutableStateOf(false) }
var selectedItem by remember { mutableStateOf (dataList[0]) } var selectedRole by remember { mutableStateOf("") }
scope.launch {
AppDatabase.getInstance(context).roleDao().getAll().collect { data ->
roleList.addAll(data.map {it.name})
}
AppDatabase.getInstance(context).roleDao().getById(user.roleId).collect { data ->
selectedRole = data.name
}
}
MaterialTheme( MaterialTheme(
colorScheme = lightColorScheme( colorScheme = lightColorScheme(
surfaceVariant= Color.White, surfaceVariant= Color.White,
@ -150,7 +175,7 @@ fun UsersCard(){
modifier = Modifier modifier = Modifier
.menuAnchor().fillMaxWidth(), .menuAnchor().fillMaxWidth(),
readOnly = true, readOnly = true,
value = selectedItem, value = selectedRole,
onValueChange = {}, onValueChange = {},
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) }, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
) )
@ -161,11 +186,11 @@ fun UsersCard(){
expanded = false expanded = false
}, },
) { ) {
dataList.forEach { selectionOption -> roleList.forEach { selectionOption ->
DropdownMenuItem( DropdownMenuItem(
text = { Text(selectionOption) }, text = { Text(selectionOption) },
onClick = { onClick = {
selectedItem = selectionOption selectedRole = selectionOption
expanded = false expanded = false
}, },
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding, contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,