Нестабильная, но рабочая версия

This commit is contained in:
Данила Мочалов 2023-12-22 06:51:10 +04:00
parent caaebc7587
commit c3b83018a9
12 changed files with 301 additions and 237 deletions

View File

@ -81,12 +81,24 @@ interface MyServerService {
@GET("order/paid/{after}") @GET("order/paid/{after}")
suspend fun getPaidOrdersList(@Path("after") after: Int, @Header("Authorization") token: String) : OrderListResponse suspend fun getPaidOrdersList(@Path("after") after: Int, @Header("Authorization") token: String) : OrderListResponse
@GET("order/all_paid/{after}")
suspend fun getAllPaidOrdersList(@Path("after") after: Int, @Header("Authorization") token: String) : OrderListResponse
@GET("order/all_ready/{after}")
suspend fun getAllReadyOrdersList(@Path("after") after: Int, @Header("Authorization") token: String) : OrderListResponse
@GET("order/all_served/{after}")
suspend fun getAllServedOrdersList(@Path("after") after: Int, @Header("Authorization") token: String) : OrderListResponse
@POST("order") @POST("order")
suspend fun insertOrder(@Body order: OrderModelRemote, @Header("Authorization") token: String) : OrderModelRemote? suspend fun insertOrder(@Body order: OrderModelRemote, @Header("Authorization") token: String) : OrderModelRemote?
@PUT("order") @PUT("order")
suspend fun updateOrder(@Body order: OrderModelRemote, @Header("Authorization") token: String) : OrderModelRemote? suspend fun updateOrder(@Body order: OrderModelRemote, @Header("Authorization") token: String) : OrderModelRemote?
@DELETE("order/{id}")
suspend fun deleteOrder(@Path("id") id: Int, @Header("Authorization") token: String)
// //
// ORDER PRODUCTS // ORDER PRODUCTS
// //

View File

@ -45,12 +45,15 @@ class OrderRemoteMediator (
"paid" -> { "paid" -> {
serverService.getPaidOrdersList(after = loadKey, token = token) serverService.getPaidOrdersList(after = loadKey, token = token)
} }
// "ready" -> { "all_paid" -> {
// serverService.getDiscountsList(after = loadKey, token = token) serverService.getAllPaidOrdersList(after = loadKey, token = token)
// } }
// "served" -> { "all_ready" -> {
// serverService.getItemsList(after = loadKey, token = token) serverService.getAllReadyOrdersList(after = loadKey, token = token)
// } }
"all_served" -> {
serverService.getAllServedOrdersList(after = loadKey, token = token)
}
else -> { else -> {
OrderListResponse() OrderListResponse()

View File

@ -18,4 +18,8 @@ class RestOrderRepository@Inject constructor(
suspend fun updateOrder(token: String, order: OrderModelRemote): OrderModelRemote? { suspend fun updateOrder(token: String, order: OrderModelRemote): OrderModelRemote? {
return service.updateOrder(order, token) return service.updateOrder(order, token)
} }
suspend fun deleteOrder(token: String, orderId: Int) {
service.deleteOrder(orderId, token)
}
} }

View File

@ -4,6 +4,7 @@ import androidx.paging.PagingSource
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query import androidx.room.Query
import androidx.room.Update import androidx.room.Update
import com.example.shawarma.data.models.OrderModel import com.example.shawarma.data.models.OrderModel
@ -11,7 +12,7 @@ import com.example.shawarma.data.models.OrderWithProducts
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface OrderDao { interface OrderDao {
@Insert @Insert(onConflict = REPLACE)
suspend fun insert(order: OrderModel) : Long suspend fun insert(order: OrderModel) : Long
@Update @Update
suspend fun update(order: OrderModel) suspend fun update(order: OrderModel)
@ -20,7 +21,7 @@ interface OrderDao {
@Query("select * from orders") @Query("select * from orders")
fun getAll(): Flow<List<OrderWithProducts>> fun getAll(): Flow<List<OrderWithProducts>>
@Query("select * from orders where orders.id =:id") @Query("select * from orders where orders.id =:id")
fun getById(id: Int): Flow<OrderWithProducts> fun getById(id: Int): Flow<OrderWithProducts?>
@Query("select * from orders where orders.user_id =:userId") @Query("select * from orders where orders.user_id =:userId")
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>> fun getByUserId(userId: Int): Flow<List<OrderWithProducts>>
@Query("select * from orders where orders.user_id =:userId and orders.order_status = 'Неоплачено'") @Query("select * from orders where orders.user_id =:userId and orders.order_status = 'Неоплачено'")
@ -34,9 +35,18 @@ interface OrderDao {
} }
} }
@Query("select * from orders where orders.order_status != 'Неоплачено'") @Query("select * from orders where orders.order_status = 'Готовится' or orders.order_status = 'Готово'")
fun getPaidPaged(): PagingSource<Int, OrderWithProducts> fun getPaidPaged(): PagingSource<Int, OrderWithProducts>
@Query("select * from orders where orders.order_status = 'Готовится'")
fun getAllPaid(): PagingSource<Int, OrderWithProducts>
@Query("select * from orders where orders.order_status = 'Готово'")
fun getAllReady(): PagingSource<Int, OrderWithProducts>
@Query("select * from orders where orders.order_status = 'Выдано'")
fun getAllServed(): PagingSource<Int, OrderWithProducts>
@Query("delete from orders where orders.order_status = 'Готовится'") @Query("delete from orders where orders.order_status = 'Готовится'")
fun deleteAllPaid() fun deleteAllPaid()
@ -46,13 +56,13 @@ interface OrderDao {
fun deleteAllServed() fun deleteAllServed()
fun deleteByQuery(query: String) { fun deleteByQuery(query: String) {
if (query == "paid") { if (query == "paid" || query == "all_paid") {
deleteAllPaid() deleteAllPaid()
} }
if (query == "ready") { if (query == "all_ready") {
deleteAllReady() deleteAllReady()
} }
if (query == "served") { if (query == "all_served") {
deleteAllServed() deleteAllServed()
} }
} }

View File

@ -3,17 +3,20 @@ package com.example.shawarma.data.interfaces.dao
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query import androidx.room.Query
import androidx.room.Update import androidx.room.Update
import com.example.shawarma.data.models.OrderProductModel import com.example.shawarma.data.models.OrderProductModel
@Dao @Dao
interface OrderProductDao { interface OrderProductDao {
@Insert @Insert(onConflict = REPLACE)
suspend fun insert(order: OrderProductModel) suspend fun insert(order: OrderProductModel)
@Update @Update
suspend fun update(order: OrderProductModel) suspend fun update(order: OrderProductModel)
@Query("delete from order_product WHERE product_id = :productId") @Query("delete from order_product WHERE product_id = :productId")
suspend fun deleteByProductId(productId: Int); suspend fun deleteByProductId(productId: Int);
@Query("delete from order_product WHERE order_id = :orderId")
suspend fun deleteByOrderId(orderId: Int);
@Delete @Delete
suspend fun delete(order: OrderProductModel) suspend fun delete(order: OrderProductModel)
} }

View File

@ -4,13 +4,14 @@ import androidx.paging.PagingSource
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query import androidx.room.Query
import androidx.room.Update import androidx.room.Update
import com.example.shawarma.data.models.ProductModel import com.example.shawarma.data.models.ProductModel
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface ProductDao { interface ProductDao {
@Insert @Insert(onConflict = REPLACE)
suspend fun insert(product: ProductModel) suspend fun insert(product: ProductModel)
suspend fun insertAll(products: List<ProductModel>) { suspend fun insertAll(products: List<ProductModel>) {

View File

@ -7,6 +7,6 @@ data class OrderProductModelWithProduct(
@Embedded @Embedded
val orderProductModel: OrderProductModel, val orderProductModel: OrderProductModel,
@Relation(entity = ProductModel::class, parentColumn = "product_id", entityColumn = "id") @Relation(entity = ProductModel::class, parentColumn = "product_id", entityColumn = "id")
val product: ProductModel, val product: ProductModel?,
) )

View File

@ -39,26 +39,19 @@ class OrderRepository @Inject constructor(
orderDao.update(order) orderDao.update(order)
restRepository.updateOrder(token, order.toOrderModelRemote()) restRepository.updateOrder(token, order.toOrderModelRemote())
} }
suspend fun delete(order: OrderModel) { suspend fun delete(token: String, order: OrderModel) {
return orderDao.delete(order) orderProductDao.deleteByOrderId(order.id!!)
orderDao.delete(order)
restRepository.deleteOrder(token, order.id!!)
} }
fun getAll(): Flow<List<OrderWithProducts>> { fun getById(id: Int): Flow<OrderWithProducts?>{
return orderDao.getAll()
}
fun getById(id: Int): Flow<OrderWithProducts>{
return orderDao.getById(id) return orderDao.getById(id)
} }
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>> {
return orderDao.getByUserId(userId)
}
suspend fun getUnpaidByUser(token: String) : OrderWithProducts? { suspend fun getUnpaidByUser(token: String) : OrderWithProducts? {
val order = restRepository.getUnpaidOrder(token) val order = restRepository.getUnpaidOrder(token)
if (order!!.id == null) { if (order!!.id == null) {
return null return null
} }
if (orderDao.getById(order.id!!).first() != null) {
orderDao.delete(order.toOrderModel())
}
if (order!!.id != null) { if (order!!.id != null) {
orderDao.insert(order.toOrderModel()) orderDao.insert(order.toOrderModel())
for (product in order.order_products) { for (product in order.order_products) {
@ -68,9 +61,6 @@ class OrderRepository @Inject constructor(
} }
return null return null
} }
fun getPaidByUser(userId: Int) : Flow<List<OrderWithProducts>> {
return orderDao.getPaidByUser(userId)
}
@OptIn(ExperimentalPagingApi::class) @OptIn(ExperimentalPagingApi::class)
fun getPaidPaged(token: String): Flow<PagingData<OrderWithProducts>> = Pager( fun getPaidPaged(token: String): Flow<PagingData<OrderWithProducts>> = Pager(
@ -82,4 +72,35 @@ class OrderRepository @Inject constructor(
remoteMediator = OrderRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "paid", token = token) remoteMediator = OrderRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "paid", token = token)
).flow ).flow
@OptIn(ExperimentalPagingApi::class)
fun getAllPaidPaged(token: String): Flow<PagingData<OrderWithProducts>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = orderDao::getAllPaid,
remoteMediator = OrderRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "all_paid", token = token)
).flow
@OptIn(ExperimentalPagingApi::class)
fun getAllReadyPaged(token: String): Flow<PagingData<OrderWithProducts>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = orderDao::getAllReady,
remoteMediator = OrderRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "all_ready", token = token)
).flow
@OptIn(ExperimentalPagingApi::class)
fun getAllServedPaged(token: String): Flow<PagingData<OrderWithProducts>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = orderDao::getAllServed,
remoteMediator = OrderRemoteMediator(database = database, serverService = MyServerService.getInstance(), query = "all_served", token = token)
).flow
} }

View File

@ -179,6 +179,7 @@ fun PaidItem(order : OrderWithProducts) {
modifier = Modifier.padding(top = 40.dp) modifier = Modifier.padding(top = 40.dp)
) { ) {
items(order.orderWithProducts.size) { index -> items(order.orderWithProducts.size) { index ->
if (order.orderWithProducts[index].product != null) {
if (order.orderWithProducts.isNotEmpty()) { if (order.orderWithProducts.isNotEmpty()) {
Row( Row(
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
@ -187,7 +188,7 @@ fun PaidItem(order : OrderWithProducts) {
.padding(horizontal = 20.dp) .padding(horizontal = 20.dp)
) { ) {
Text( Text(
text = order.orderWithProducts[index].product.title, text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp), modifier = Modifier.padding(top = 15.dp),
@ -201,7 +202,7 @@ fun PaidItem(order : OrderWithProducts) {
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = (order.orderWithProducts[index].orderProductModel.quantity * order.orderWithProducts[index].product.price).toString() + " руб.", text = (order.orderWithProducts[index].orderProductModel.quantity * order.orderWithProducts[index].product!!.price).toString() + " руб.",
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp), modifier = Modifier.padding(top = 15.dp),
@ -210,6 +211,8 @@ fun PaidItem(order : OrderWithProducts) {
} }
} }
} }
}
} }
} }
Spacer(modifier = Modifier.height(20.dp)) Spacer(modifier = Modifier.height(20.dp))
@ -231,6 +234,8 @@ fun CartItem(order : OrderWithProducts) {
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
items(order.orderWithProducts.size) {index -> items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
var count = remember { mutableStateOf(0)} var count = remember { mutableStateOf(0)}
count.value = order.orderWithProducts[index].orderProductModel.quantity count.value = order.orderWithProducts[index].orderProductModel.quantity
Row( Row(
@ -248,13 +253,13 @@ fun CartItem(order : OrderWithProducts) {
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
Text( Text(
text = order.orderWithProducts[index].product.title, text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
) )
Text( Text(
text = (order.orderWithProducts[index].orderProductModel.quantity * order.orderWithProducts[index].product.price).toString() + " руб.", text = (order.orderWithProducts[index].orderProductModel.quantity * order.orderWithProducts[index].product!!.price).toString() + " руб.",
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 18.sp, fontSize = 18.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -321,3 +326,4 @@ fun CartItem(order : OrderWithProducts) {
} }
} }
} }
}

View File

@ -23,20 +23,22 @@ import androidx.compose.material.Card
import androidx.compose.material.Icon import androidx.compose.material.Icon
import androidx.compose.material.Text import androidx.compose.material.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
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.FontWeight import androidx.compose.ui.text.font.FontWeight
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 androidx.compose.ui.zIndex import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.shawarma.R import com.example.shawarma.R
import com.example.shawarma.data.models.OrderStatus import com.example.shawarma.data.models.OrderStatus
import com.example.shawarma.data.models.OrderWithProducts import com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.ui.theme.MarckFamily import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightRed import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.MyLightYellow import com.example.shawarma.ui.theme.MyLightYellow
@ -45,7 +47,6 @@ import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.NunitoFamily import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.viewmodels.OrdersViewModel import com.example.shawarma.viewmodels.OrdersViewModel
import com.example.shawarma.widgets.ShawarmaLogo2 import com.example.shawarma.widgets.ShawarmaLogo2
import java.text.SimpleDateFormat
@Composable @Composable
fun OrdersScreen() { fun OrdersScreen() {
@ -60,10 +61,12 @@ fun OrdersScreen() {
@Composable @Composable
fun OrdersList(){ fun OrdersList(){
val ordersViewModel = hiltViewModel<OrdersViewModel>() val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
val preparingOrders = ordersViewModel.preparingOrders.observeAsState().value val preparingOrders = ordersViewModel.getAllPaidList(searchToken).collectAsLazyPagingItems()
val preparedOrders = ordersViewModel.preparedOrders.observeAsState().value val preparedOrders = ordersViewModel.getAllReadyList(searchToken).collectAsLazyPagingItems()
val processedOrders = ordersViewModel.processedOrders.observeAsState().value val processedOrders = ordersViewModel.getAllServedList(searchToken).collectAsLazyPagingItems()
Box( Box(
modifier = Modifier modifier = Modifier
@ -102,9 +105,9 @@ fun OrdersList(){
.height(250.dp) .height(250.dp)
) { ) {
if (preparingOrders != null) { if (preparingOrders != null) {
if (preparingOrders.isNotEmpty()) { if (preparingOrders.itemCount > 0) {
items(preparingOrders.size) { index -> items(preparingOrders.itemCount) { index ->
PreparingItem(preparingOrders[index]) PreparingItem(preparingOrders[index]!!)
} }
} }
} }
@ -122,9 +125,9 @@ fun OrdersList(){
.height(250.dp) .height(250.dp)
) { ) {
if (preparedOrders != null) { if (preparedOrders != null) {
if (preparedOrders.isNotEmpty()) { if (preparedOrders.itemCount > 0) {
items(preparedOrders.size) { index -> items(preparedOrders.itemCount) { index ->
PreparedItem(preparedOrders[index]) PreparedItem(preparedOrders[index]!!)
} }
} }
} }
@ -142,9 +145,9 @@ fun OrdersList(){
.height(250.dp) .height(250.dp)
) { ) {
if (processedOrders != null) { if (processedOrders != null) {
if (processedOrders.isNotEmpty()) { if (processedOrders.itemCount > 0) {
items(processedOrders.size) {index -> items(processedOrders.itemCount) {index ->
ProcessedItem(processedOrders[index]) ProcessedItem(processedOrders[index]!!)
} }
} }
} }
@ -159,6 +162,8 @@ fun OrdersList(){
@Composable @Composable
fun PreparingItem(order : OrderWithProducts){ fun PreparingItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>() val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card( Card(
border = BorderStroke(width = 2.dp, color = MyOrange), border = BorderStroke(width = 2.dp, color = MyOrange),
@ -179,10 +184,8 @@ fun PreparingItem(order : OrderWithProducts){
Column( Column(
modifier = Modifier.fillMaxWidth(0.5f) modifier = Modifier.fillMaxWidth(0.5f)
){ ){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text( Text(
text = time, text = order.order.date,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -198,7 +201,7 @@ fun PreparingItem(order : OrderWithProducts){
.size(170.dp, 80.dp) .size(170.dp, 80.dp)
.fillMaxSize(), .fillMaxSize(),
onClick = { onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Готово.name) ordersViewModel.changeOrderStatus(searchToken, order, OrderStatus.Готово.name)
} }
) { ) {
Text( Text(
@ -217,13 +220,14 @@ fun PreparingItem(order : OrderWithProducts){
.padding(horizontal = 20.dp) .padding(horizontal = 20.dp)
){ ){
items(order.orderWithProducts.size) {index -> items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
) { ) {
Text( Text(
text = order.orderWithProducts[index].product.title, text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -236,6 +240,8 @@ fun PreparingItem(order : OrderWithProducts){
) )
} }
} }
}
} }
} }
} }
@ -246,6 +252,8 @@ fun PreparingItem(order : OrderWithProducts){
@Composable @Composable
fun PreparedItem(order : OrderWithProducts){ fun PreparedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>() val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card( Card(
border = BorderStroke(width = 2.dp, color = MyOrange), border = BorderStroke(width = 2.dp, color = MyOrange),
@ -266,10 +274,8 @@ fun PreparedItem(order : OrderWithProducts){
Column( Column(
modifier = Modifier.fillMaxWidth(0.5f) modifier = Modifier.fillMaxWidth(0.5f)
){ ){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text( Text(
text = time, text = order.order.date,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -285,7 +291,7 @@ fun PreparedItem(order : OrderWithProducts){
.size(170.dp, 80.dp) .size(170.dp, 80.dp)
.fillMaxSize(), .fillMaxSize(),
onClick = { onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Выдано.name) ordersViewModel.changeOrderStatus(searchToken, order, OrderStatus.Выдано.name)
} }
) { ) {
Text( Text(
@ -304,13 +310,14 @@ fun PreparedItem(order : OrderWithProducts){
.padding(horizontal = 20.dp) .padding(horizontal = 20.dp)
){ ){
items(order.orderWithProducts.size) {index -> items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
) { ) {
Text( Text(
text = order.orderWithProducts[index].product.title, text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -326,6 +333,7 @@ fun PreparedItem(order : OrderWithProducts){
} }
} }
} }
}
Spacer(modifier = Modifier.height(20.dp)) Spacer(modifier = Modifier.height(20.dp))
} }
@ -333,6 +341,8 @@ fun PreparedItem(order : OrderWithProducts){
@Composable @Composable
fun ProcessedItem(order : OrderWithProducts){ fun ProcessedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>() val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card( Card(
border = BorderStroke(width = 2.dp, color = MyOrange), border = BorderStroke(width = 2.dp, color = MyOrange),
@ -353,10 +363,8 @@ fun ProcessedItem(order : OrderWithProducts){
Column( Column(
modifier = Modifier.fillMaxWidth(0.3f) modifier = Modifier.fillMaxWidth(0.3f)
){ ){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text( Text(
text = time, text = order.order.date,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -380,7 +388,7 @@ fun ProcessedItem(order : OrderWithProducts){
colors = ButtonDefaults.buttonColors(MyLightRed), colors = ButtonDefaults.buttonColors(MyLightRed),
shape = RoundedCornerShape(20.dp), shape = RoundedCornerShape(20.dp),
onClick = { onClick = {
ordersViewModel.deleteOrder(order) ordersViewModel.deleteOrder(searchToken, order)
} }
) { ) {
Icon( Icon(
@ -398,13 +406,14 @@ fun ProcessedItem(order : OrderWithProducts){
.padding(horizontal = 20.dp) .padding(horizontal = 20.dp)
){ ){
items(order.orderWithProducts.size) {index -> items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
) { ) {
Text( Text(
text = order.orderWithProducts[index].product.title, text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily, fontFamily = NunitoFamily,
fontSize = 20.sp, fontSize = 20.sp,
fontWeight = FontWeight.Bold fontWeight = FontWeight.Bold
@ -417,6 +426,8 @@ fun ProcessedItem(order : OrderWithProducts){
) )
} }
} }
}
} }
} }
} }

View File

@ -50,14 +50,16 @@ class HomeViewModel @Inject constructor(
else { else {
var isAlreadyAdded = false var isAlreadyAdded = false
for (prod in order.orderWithProducts) { for (prod in order.orderWithProducts) {
if (prod.product.id == productId) { if (prod.product != null) {
if (prod.product!!.id == productId) {
val model = prod.orderProductModel val model = prod.orderProductModel
model.quantity += 1 model.quantity += 1
model.totalPrice += prod.product.price model.totalPrice += prod.product!!.price
orderProductRepository.update(token, model) orderProductRepository.update(token, model)
isAlreadyAdded = true isAlreadyAdded = true
} }
} }
}
if (!isAlreadyAdded) { if (!isAlreadyAdded) {
orderProductRepository.insert(token, OrderProductModel(order.order.id!!, productId, 1, product.price)) orderProductRepository.insert(token, OrderProductModel(order.order.id!!, productId, 1, product.price))
} }

View File

@ -1,13 +1,12 @@
package com.example.shawarma.viewmodels package com.example.shawarma.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.example.shawarma.data.models.OrderStatus import androidx.paging.PagingData
import com.example.shawarma.data.models.OrderWithProducts import com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.data.repos.OrderRepository import com.example.shawarma.data.repos.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import javax.inject.Inject import javax.inject.Inject
@ -15,39 +14,31 @@ import javax.inject.Inject
class OrdersViewModel @Inject constructor( class OrdersViewModel @Inject constructor(
private val orderRepository: OrderRepository private val orderRepository: OrderRepository
) : ViewModel() { ) : ViewModel() {
private val _preparingOrders = MutableLiveData<List<OrderWithProducts>>()
private val _preparedOrders = MutableLiveData<List<OrderWithProducts>>()
private val _processedOrders = MutableLiveData<List<OrderWithProducts>>()
val preparingOrders: LiveData<List<OrderWithProducts>> fun getAllPaidList(token: String) : Flow<PagingData<OrderWithProducts>> {
get() = _preparingOrders return orderRepository.getAllPaidPaged(token)
val preparedOrders: LiveData<List<OrderWithProducts>> }
get() = _preparedOrders
val processedOrders: LiveData<List<OrderWithProducts>> fun getAllReadyList(token: String) : Flow<PagingData<OrderWithProducts>> {
get() = _processedOrders return orderRepository.getAllReadyPaged(token)
}
fun getAllServedList(token: String) : Flow<PagingData<OrderWithProducts>> {
return orderRepository.getAllServedPaged(token)
}
fun changeOrderStatus(token: String, order: OrderWithProducts, newStatus: String) {
val model = order.order
model.status = newStatus
init {
viewModelScope.launch{ viewModelScope.launch{
orderRepository.getAll().collect { allOrders -> orderRepository.update(token, model)
_preparingOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Готовится.name })
_preparedOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Готово.name })
_processedOrders.postValue(allOrders.filter { it.order.status == OrderStatus.Выдано.name })
}
} }
} }
fun changeOrderStatus(order: OrderWithProducts, newStatus: String) { fun deleteOrder(token: String, order: OrderWithProducts) {
// val model = order.order
// model.status = newStatus
//
// viewModelScope.launch{
// orderRepository.update(model)
// }
}
fun deleteOrder(order: OrderWithProducts) {
viewModelScope.launch{ viewModelScope.launch{
orderRepository.delete(order.order) orderRepository.delete(token, order.order)
} }
} }