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

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}")
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")
suspend fun insertOrder(@Body order: OrderModelRemote, @Header("Authorization") token: String) : OrderModelRemote?
@PUT("order")
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
//

View File

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

View File

@ -18,4 +18,8 @@ class RestOrderRepository@Inject constructor(
suspend fun updateOrder(token: String, order: OrderModelRemote): OrderModelRemote? {
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.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query
import androidx.room.Update
import com.example.shawarma.data.models.OrderModel
@ -11,7 +12,7 @@ import com.example.shawarma.data.models.OrderWithProducts
import kotlinx.coroutines.flow.Flow
@Dao
interface OrderDao {
@Insert
@Insert(onConflict = REPLACE)
suspend fun insert(order: OrderModel) : Long
@Update
suspend fun update(order: OrderModel)
@ -20,7 +21,7 @@ interface OrderDao {
@Query("select * from orders")
fun getAll(): Flow<List<OrderWithProducts>>
@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")
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>>
@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>
@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 = 'Готовится'")
fun deleteAllPaid()
@ -46,13 +56,13 @@ interface OrderDao {
fun deleteAllServed()
fun deleteByQuery(query: String) {
if (query == "paid") {
if (query == "paid" || query == "all_paid") {
deleteAllPaid()
}
if (query == "ready") {
if (query == "all_ready") {
deleteAllReady()
}
if (query == "served") {
if (query == "all_served") {
deleteAllServed()
}
}

View File

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

View File

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

View File

@ -7,6 +7,6 @@ data class OrderProductModelWithProduct(
@Embedded
val orderProductModel: OrderProductModel,
@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)
restRepository.updateOrder(token, order.toOrderModelRemote())
}
suspend fun delete(order: OrderModel) {
return orderDao.delete(order)
suspend fun delete(token: String, order: OrderModel) {
orderProductDao.deleteByOrderId(order.id!!)
orderDao.delete(order)
restRepository.deleteOrder(token, order.id!!)
}
fun getAll(): Flow<List<OrderWithProducts>> {
return orderDao.getAll()
}
fun getById(id: Int): Flow<OrderWithProducts>{
fun getById(id: Int): Flow<OrderWithProducts?>{
return orderDao.getById(id)
}
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>> {
return orderDao.getByUserId(userId)
}
suspend fun getUnpaidByUser(token: String) : OrderWithProducts? {
val order = restRepository.getUnpaidOrder(token)
if (order!!.id == null) {
return null
}
if (orderDao.getById(order.id!!).first() != null) {
orderDao.delete(order.toOrderModel())
}
if (order!!.id != null) {
orderDao.insert(order.toOrderModel())
for (product in order.order_products) {
@ -68,9 +61,6 @@ class OrderRepository @Inject constructor(
}
return null
}
fun getPaidByUser(userId: Int) : Flow<List<OrderWithProducts>> {
return orderDao.getPaidByUser(userId)
}
@OptIn(ExperimentalPagingApi::class)
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)
).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)
) {
items(order.orderWithProducts.size) { index ->
if (order.orderWithProducts[index].product != null) {
if (order.orderWithProducts.isNotEmpty()) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
@ -187,7 +188,7 @@ fun PaidItem(order : OrderWithProducts) {
.padding(horizontal = 20.dp)
) {
Text(
text = order.orderWithProducts[index].product.title,
text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
@ -201,7 +202,7 @@ fun PaidItem(order : OrderWithProducts) {
fontWeight = FontWeight.Bold
)
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,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
@ -210,6 +211,8 @@ fun PaidItem(order : OrderWithProducts) {
}
}
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
@ -231,6 +234,8 @@ fun CartItem(order : OrderWithProducts) {
horizontalAlignment = Alignment.CenterHorizontally
) {
items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
var count = remember { mutableStateOf(0)}
count.value = order.orderWithProducts[index].orderProductModel.quantity
Row(
@ -248,13 +253,13 @@ fun CartItem(order : OrderWithProducts) {
modifier = Modifier.fillMaxWidth()
) {
Text(
text = order.orderWithProducts[index].product.title,
text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
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,
fontSize = 18.sp,
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.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.shawarma.R
import com.example.shawarma.data.models.OrderStatus
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.MyLightRed
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.viewmodels.OrdersViewModel
import com.example.shawarma.widgets.ShawarmaLogo2
import java.text.SimpleDateFormat
@Composable
fun OrdersScreen() {
@ -60,10 +61,12 @@ fun OrdersScreen() {
@Composable
fun OrdersList(){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
val preparingOrders = ordersViewModel.preparingOrders.observeAsState().value
val preparedOrders = ordersViewModel.preparedOrders.observeAsState().value
val processedOrders = ordersViewModel.processedOrders.observeAsState().value
val preparingOrders = ordersViewModel.getAllPaidList(searchToken).collectAsLazyPagingItems()
val preparedOrders = ordersViewModel.getAllReadyList(searchToken).collectAsLazyPagingItems()
val processedOrders = ordersViewModel.getAllServedList(searchToken).collectAsLazyPagingItems()
Box(
modifier = Modifier
@ -102,9 +105,9 @@ fun OrdersList(){
.height(250.dp)
) {
if (preparingOrders != null) {
if (preparingOrders.isNotEmpty()) {
items(preparingOrders.size) { index ->
PreparingItem(preparingOrders[index])
if (preparingOrders.itemCount > 0) {
items(preparingOrders.itemCount) { index ->
PreparingItem(preparingOrders[index]!!)
}
}
}
@ -122,9 +125,9 @@ fun OrdersList(){
.height(250.dp)
) {
if (preparedOrders != null) {
if (preparedOrders.isNotEmpty()) {
items(preparedOrders.size) { index ->
PreparedItem(preparedOrders[index])
if (preparedOrders.itemCount > 0) {
items(preparedOrders.itemCount) { index ->
PreparedItem(preparedOrders[index]!!)
}
}
}
@ -142,9 +145,9 @@ fun OrdersList(){
.height(250.dp)
) {
if (processedOrders != null) {
if (processedOrders.isNotEmpty()) {
items(processedOrders.size) {index ->
ProcessedItem(processedOrders[index])
if (processedOrders.itemCount > 0) {
items(processedOrders.itemCount) {index ->
ProcessedItem(processedOrders[index]!!)
}
}
}
@ -159,6 +162,8 @@ fun OrdersList(){
@Composable
fun PreparingItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
@ -179,10 +184,8 @@ fun PreparingItem(order : OrderWithProducts){
Column(
modifier = Modifier.fillMaxWidth(0.5f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
text = order.order.date,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -198,7 +201,7 @@ fun PreparingItem(order : OrderWithProducts){
.size(170.dp, 80.dp)
.fillMaxSize(),
onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Готово.name)
ordersViewModel.changeOrderStatus(searchToken, order, OrderStatus.Готово.name)
}
) {
Text(
@ -217,13 +220,14 @@ fun PreparingItem(order : OrderWithProducts){
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -236,6 +240,8 @@ fun PreparingItem(order : OrderWithProducts){
)
}
}
}
}
}
}
@ -246,6 +252,8 @@ fun PreparingItem(order : OrderWithProducts){
@Composable
fun PreparedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
@ -266,10 +274,8 @@ fun PreparedItem(order : OrderWithProducts){
Column(
modifier = Modifier.fillMaxWidth(0.5f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
text = order.order.date,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -285,7 +291,7 @@ fun PreparedItem(order : OrderWithProducts){
.size(170.dp, 80.dp)
.fillMaxSize(),
onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Выдано.name)
ordersViewModel.changeOrderStatus(searchToken, order, OrderStatus.Выдано.name)
}
) {
Text(
@ -304,13 +310,14 @@ fun PreparedItem(order : OrderWithProducts){
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -326,6 +333,7 @@ fun PreparedItem(order : OrderWithProducts){
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
}
@ -333,6 +341,8 @@ fun PreparedItem(order : OrderWithProducts){
@Composable
fun ProcessedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
val searchToken = preferencesManager.getData("token", "")
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
@ -353,10 +363,8 @@ fun ProcessedItem(order : OrderWithProducts){
Column(
modifier = Modifier.fillMaxWidth(0.3f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
text = order.order.date,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -380,7 +388,7 @@ fun ProcessedItem(order : OrderWithProducts){
colors = ButtonDefaults.buttonColors(MyLightRed),
shape = RoundedCornerShape(20.dp),
onClick = {
ordersViewModel.deleteOrder(order)
ordersViewModel.deleteOrder(searchToken, order)
}
) {
Icon(
@ -398,13 +406,14 @@ fun ProcessedItem(order : OrderWithProducts){
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
if (order.orderWithProducts[index].product != null) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
text = order.orderWithProducts[index].product!!.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
@ -417,6 +426,8 @@ fun ProcessedItem(order : OrderWithProducts){
)
}
}
}
}
}
}

View File

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

View File

@ -1,13 +1,12 @@
package com.example.shawarma.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
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.repos.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import javax.inject.Inject
@ -15,39 +14,31 @@ import javax.inject.Inject
class OrdersViewModel @Inject constructor(
private val orderRepository: OrderRepository
) : ViewModel() {
private val _preparingOrders = MutableLiveData<List<OrderWithProducts>>()
private val _preparedOrders = MutableLiveData<List<OrderWithProducts>>()
private val _processedOrders = MutableLiveData<List<OrderWithProducts>>()
val preparingOrders: LiveData<List<OrderWithProducts>>
get() = _preparingOrders
val preparedOrders: LiveData<List<OrderWithProducts>>
get() = _preparedOrders
val processedOrders: LiveData<List<OrderWithProducts>>
get() = _processedOrders
fun getAllPaidList(token: String) : Flow<PagingData<OrderWithProducts>> {
return orderRepository.getAllPaidPaged(token)
}
fun getAllReadyList(token: String) : Flow<PagingData<OrderWithProducts>> {
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{
orderRepository.getAll().collect { allOrders ->
_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 })
}
orderRepository.update(token, model)
}
}
fun changeOrderStatus(order: OrderWithProducts, newStatus: String) {
// val model = order.order
// model.status = newStatus
//
// viewModelScope.launch{
// orderRepository.update(model)
// }
}
fun deleteOrder(order: OrderWithProducts) {
fun deleteOrder(token: String, order: OrderWithProducts) {
viewModelScope.launch{
orderRepository.delete(order.order)
orderRepository.delete(token, order.order)
}
}