Compare commits

...

No commits in common. "main" and "Lab4" have entirely different histories.
main ... Lab4

101 changed files with 4208 additions and 36 deletions

48
.gitignore vendored
View File

@ -1,35 +1,15 @@
# ---> Android
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Log/OS Files
*.log
# Android Studio generated files and folders
captures/
.externalNativeBuild/
.cxx/
*.apk
output.json
# IntelliJ
*.iml
.idea/
misc.xml
deploymentTargetDropDown.xml
render.experimental.xml
# Keystore files
*.jks
*.keystore
# Google Services (e.g. APIs or Firebase)
google-services.json
# Android Profiling
*.hprof
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties

3
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

1
.idea/.name Normal file
View File

@ -0,0 +1 @@
Shawarma

6
.idea/compiler.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="17" />
</component>
</project>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="deploymentTargetDropDown">
<targetSelectedWithDropDown>
<Target>
<type value="QUICK_BOOT_TARGET" />
<deviceKey>
<Key>
<type value="VIRTUAL_DEVICE_PATH" />
<value value="C:\Users\Danya\.android\avd\Pixel_2_API_34_2.avd" />
</Key>
</deviceKey>
</Target>
</targetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2023-10-09T12:44:34.176701300Z" />
</component>
</project>

20
.idea/gradle.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="GRADLE" />
<option name="distributionType" value="DEFAULT_WRAPPED" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="jbr-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$" />
<option value="$PROJECT_DIR$/app" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

View File

@ -0,0 +1,32 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PreviewAnnotationInFunctionWithParameters" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewApiLevelMustBeValid" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewDimensionRespectsLimit" enabled="true" level="WARNING" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewFontScaleMustBeGreaterThanZero" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewMultipleParameterProviders" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewMustBeTopLevelFunction" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewNeedsComposableAnnotation" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewNotSupportedInUnitTestFiles" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
<inspection_tool class="PreviewPickerAnnotation" enabled="true" level="ERROR" enabled_by_default="true">
<option name="composableFile" value="true" />
</inspection_tool>
</profile>
</component>

6
.idea/kotlinc.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.7.0" />
</component>
</project>

6
.idea/misc.xml Normal file
View File

@ -0,0 +1,6 @@
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="jbr-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@ -1,2 +0,0 @@
# PIbd-33_Mochalov_D.V._Mobile

1
app/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build

90
app/build.gradle Normal file
View File

@ -0,0 +1,90 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
//lab 3
id 'kotlin-kapt'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.dagger.hilt.android'
android {
namespace 'com.example.shawarma'
compileSdk 34
defaultConfig {
applicationId "com.example.shawarma"
minSdk 23
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
kapt {
arguments {arg("room.schemaLocation", "$projectDir/schemas")}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.2.0'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.20"
def nav_version = "2.7.0"
implementation "androidx.navigation:navigation-compose:$nav_version"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'
implementation "androidx.compose.ui:ui:$compose_ui_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
implementation 'androidx.compose.material:material:1.2.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_ui_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version"
// lab 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' // Дополнительно для Kotlin Coroutines, Kotlin Flows
// lab4
implementation "com.google.dagger:hilt-android:2.42"
kapt "com.google.dagger:hilt-android-compiler:2.42"
implementation("androidx.hilt:hilt-navigation-compose:1.0.0")
implementation 'androidx.compose.runtime:runtime-livedata:1.0.0-beta01'
implementation "androidx.datastore:datastore-preferences:1.0.0"
implementation("androidx.room:room-paging:2.5.0")
implementation("androidx.paging:paging-compose:3.2.1")
}

21
app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@ -0,0 +1,24 @@
package com.example.shawarma
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.shawarma", appContext.packageName)
}
}

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".ShawarmaApp"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Shawarma"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:windowSoftInputMode="adjustResize"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.Shawarma">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

View File

@ -0,0 +1,52 @@
package com.example.shawarma
import android.app.Application
import androidx.room.Room
import com.example.shawarma.data.db.AppDatabase
import com.example.shawarma.data.repos.OrderProductRepository
import com.example.shawarma.data.repos.OrderRepository
import com.example.shawarma.data.repos.ProductRepository
import com.example.shawarma.data.repos.UserRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideDatabase(app: Application) : AppDatabase {
return Room.databaseBuilder(
app,
AppDatabase::class.java,
AppDatabase.DB_NAME
).build()
}
@Provides
@Singleton
fun provideUserRepository(db: AppDatabase) : UserRepository {
return UserRepository(db.userDao())
}
@Provides
@Singleton
fun provideProductRepository(db: AppDatabase) : ProductRepository {
return ProductRepository(db.productDao(), db.orderProductDao())
}
@Provides
@Singleton
fun provideOrderRepository(db: AppDatabase) : OrderRepository {
return OrderRepository(db.orderDao())
}
@Provides
@Singleton
fun provideOrderProductRepository(db: AppDatabase) : OrderProductRepository {
return OrderProductRepository(db.orderProductDao())
}
}

View File

@ -0,0 +1,29 @@
package com.example.shawarma
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Surface
import androidx.compose.ui.Modifier
import com.example.shawarma.screens.MainNavBar
import com.example.shawarma.screens.authorization.AuthorizationScreen
import com.example.shawarma.screens.registration.RegistrationScreen
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.ShawarmaTheme
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.HiltAndroidApp
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MainNavBar()
}
}
}

View File

@ -0,0 +1,11 @@
package com.example.shawarma
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class ShawarmaApp : Application() {
override fun onCreate() {
super.onCreate()
}
}

View File

@ -0,0 +1,121 @@
package com.example.shawarma.data.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.shawarma.data.interfaces.dao.OrderDao
import com.example.shawarma.data.interfaces.dao.OrderProductDao
import com.example.shawarma.data.interfaces.dao.ProductDao
import com.example.shawarma.data.interfaces.dao.UserDao
import com.example.shawarma.data.models.OrderModel
import com.example.shawarma.data.models.OrderProductModel
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.models.UserModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Database(
entities =
[
UserModel::class,
OrderModel::class,
ProductModel::class,
OrderProductModel::class,
],
version = 1,
exportSchema = false
)
@TypeConverters(Converter::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao() : UserDao
abstract fun productDao() : ProductDao
abstract fun orderDao() : OrderDao
abstract fun orderProductDao() : OrderProductDao
companion object {
const val DB_NAME: String = "shawarma-db"
@Volatile
private var INSTANCE: AppDatabase? = null
private suspend fun populateDatabase() {
INSTANCE?.let { database ->
// Users
val userDao = database.userDao()
val user1 = UserModel(1, "danya", "password", "ADMIN")
userDao.insert(user1)
// // Products
// val productDao = database.productDao()
// val product1 = ProductModel(1, "Классик", 100, null)
// val product2 = ProductModel(2, "Сырная", 120, null)
// val discount1 = ProductModel(3, "Выгода", 80, 100)
// val discount2 = ProductModel(4, "Кола", 50, 75)
// productDao.insert(product1)
// productDao.insert(product2)
// productDao.insert(discount1)
// productDao.insert(discount2)
// // Orders
// val orderDao = database.orderDao()
// val order1 = OrderModel(1, OrderStatus.Готовится.toString(), 1, Date())
// val order2 = OrderModel(2, OrderStatus.Неоплачено.toString(), 1, Date())
// val order3 = OrderModel(3, OrderStatus.Готово.toString(), 1, Date())
// val order4 = OrderModel(4, OrderStatus.Выдано.toString(), 1, Date())
// orderDao.insert(order1)
// orderDao.insert(order2)
// orderDao.insert(order3)
// orderDao.insert(order4)
// // OrderProducts
// val orderProductDao = database.orderProductDao()
// val op1 = OrderProductModel(1, 1, 2, 200)
// val op2 = OrderProductModel(1, 4, 3, 150)
// val op3 = OrderProductModel(1, 3, 1, 80)
// val op4 = OrderProductModel(2, 1, 2, 200)
// val op5 = OrderProductModel(2, 4, 3, 150)
// val op6 = OrderProductModel(2, 3, 1, 80)
// val op7 = OrderProductModel(3, 1, 2, 200)
// val op8 = OrderProductModel(3, 4, 3, 150)
// val op9 = OrderProductModel(3, 3, 1, 80)
// val op10 = OrderProductModel(4, 1, 2, 200)
// val op11 = OrderProductModel(4, 4, 3, 150)
// val op12 = OrderProductModel(4, 3, 1, 80)
// orderProductDao.insert(op1)
// orderProductDao.insert(op2)
// orderProductDao.insert(op3)
// orderProductDao.insert(op4)
// orderProductDao.insert(op5)
// orderProductDao.insert(op6)
// orderProductDao.insert(op7)
// orderProductDao.insert(op8)
// orderProductDao.insert(op9)
// orderProductDao.insert(op10)
// orderProductDao.insert(op11)
// orderProductDao.insert(op12)
}
}
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

@ -0,0 +1,16 @@
package com.example.shawarma.data.db
import androidx.room.TypeConverter
import java.util.Date
class Converter {
@TypeConverter
fun fromTimestamp(value: Long?): Date? {
return value?.let { Date(it) }
}
@TypeConverter
fun dateToTimestamp(date: Date?): Long? {
return date?.time?.toLong()
}
}

View File

@ -0,0 +1,29 @@
package com.example.shawarma.data.interfaces.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.shawarma.data.models.OrderModel
import com.example.shawarma.data.models.OrderWithProducts
import kotlinx.coroutines.flow.Flow
@Dao
interface OrderDao {
@Insert
suspend fun insert(order: OrderModel) : Long
@Update
suspend fun update(order: OrderModel)
@Delete
suspend fun delete(order: OrderModel)
@Query("select * from orders")
fun getAll(): Flow<List<OrderWithProducts>>
@Query("select * from orders where orders.id =:id")
fun getById(id: Int): Flow<List<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 = 'Неоплачено'")
fun getUnpaidByUser(userId: Int) : Flow<OrderWithProducts>
@Query("select * from orders where orders.user_id =:userId and (orders.order_status = 'Готовится' or orders.order_status = 'Готово')")
fun getPaidByUser(userId: Int) : Flow<List<OrderWithProducts>>
}

View File

@ -0,0 +1,19 @@
package com.example.shawarma.data.interfaces.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.shawarma.data.models.OrderProductModel
@Dao
interface OrderProductDao {
@Insert
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);
@Delete
suspend fun delete(order: OrderProductModel)
}

View File

@ -0,0 +1,42 @@
package com.example.shawarma.data.interfaces.dao
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.shawarma.data.models.ProductModel
import kotlinx.coroutines.flow.Flow
@Dao
interface ProductDao {
@Insert
suspend fun insert(product: ProductModel)
@Update
suspend fun update(product: ProductModel)
@Delete()
suspend fun delete(product: ProductModel)
@Query("select * from products where products.product_old_price is null")
fun getAll() : Flow<List<ProductModel>>
@Query("select * from products where products.product_old_price is not null")
fun getDiscounts() : Flow<List<ProductModel>>
@Query("select * from products")
fun getItems() : Flow<List<ProductModel>>
@Query("select * from products where products.id = :id")
fun getById(id: Int): Flow<ProductModel>
@Query("select * from products where products.product_old_price is null")
fun getPaged(): PagingSource<Int, ProductModel>
@Query("select * from products where products.product_old_price is not null")
fun getPagedDiscounts(): PagingSource<Int, ProductModel>
@Query("select * from products")
fun getPagedItems(): PagingSource<Int, ProductModel>
}

View File

@ -0,0 +1,26 @@
package com.example.shawarma.data.interfaces.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.ABORT
import androidx.room.Query
import androidx.room.Update
import com.example.shawarma.data.models.UserModel
import kotlinx.coroutines.flow.Flow
@Dao
interface UserDao {
@Insert(onConflict = ABORT)
suspend fun insert(user: UserModel)
@Update
suspend fun update(user: UserModel)
@Delete
suspend fun delete(user: UserModel)
@Query("select * from users order by user_login collate nocase asc")
fun getAll(): Flow<List<UserModel>>
@Query("select * from users where id = :id")
fun getById(id: Int): Flow<UserModel>
@Query("select * from users where user_login = :login and user_password = :password limit 1")
fun login(login: String, password: String) : Flow<UserModel?>
}

View File

@ -0,0 +1,39 @@
package com.example.shawarma.data.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import java.util.Date
@Entity(
tableName = "orders",
foreignKeys = [
ForeignKey(
entity = UserModel::class,
parentColumns = ["id"],
childColumns = ["user_id"],
)
]
)
data class OrderModel(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "order_status")
var status: String,
@ColumnInfo(name = "user_id", index = true)
val userId: Int?,
@ColumnInfo(name = "date")
val date: Date
)
fun getOrdersByUserId() : List<OrderModel> {
return listOf(
)
}
fun getAllOrders() : List<OrderModel> {
return listOf(
)
}

View File

@ -0,0 +1,16 @@
package com.example.shawarma.data.models
import androidx.room.ColumnInfo
import androidx.room.Entity
@Entity(tableName = "order_product", primaryKeys = ["order_id", "product_id"])
data class OrderProductModel(
@ColumnInfo(name = "order_id", index = true)
var orderId: Int,
@ColumnInfo(name = "product_id", index = true)
var productId: Int,
@ColumnInfo(name = "quantity")
var quantity: Int,
@ColumnInfo(name = "total_price")
var totalPrice: Int
)

View File

@ -0,0 +1,12 @@
package com.example.shawarma.data.models
import androidx.room.Embedded
import androidx.room.Relation
data class OrderProductModelWithProduct(
@Embedded
val orderProductModel: OrderProductModel,
@Relation(entity = ProductModel::class, parentColumn = "product_id", entityColumn = "id")
val product: ProductModel,
)

View File

@ -0,0 +1,11 @@
package com.example.shawarma.data.models
import androidx.room.Embedded
import androidx.room.Relation
data class OrderWithProducts(
@Embedded
val order: OrderModel,
@Relation(entity = OrderProductModel::class, parentColumn = "id", entityColumn = "order_id")
val orderWithProducts: List<OrderProductModelWithProduct>
)

View File

@ -0,0 +1,36 @@
package com.example.shawarma.data.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "products")
data class ProductModel(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "product_title")
val title: String,
@ColumnInfo(name = "product_price")
val price: Int,
@ColumnInfo(name = "product_old_price")
val oldPrice: Int?,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ProductModel
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id ?: -1
}
}
fun getProducts() :List<ProductModel> {
return listOf(
)
}

View File

@ -0,0 +1,5 @@
package com.example.shawarma.data.models
enum class OrderStatus {
Неоплачено, Готовится, Готово, Выдано
}

View File

@ -0,0 +1,30 @@
package com.example.shawarma.data.models
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "users")
data class UserModel(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int?,
@ColumnInfo(name = "user_login")
val login: String,
@ColumnInfo(name = "user_password")
val password: String,
@ColumnInfo(name = "user_role")
val role: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UserModel
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id ?: -1
}
}

View File

@ -0,0 +1,20 @@
package com.example.shawarma.data.repos
import com.example.shawarma.data.interfaces.dao.OrderProductDao
import com.example.shawarma.data.models.OrderProductModel
import javax.inject.Inject
class OrderProductRepository @Inject constructor(
private val orderProductDao: OrderProductDao
) {
suspend fun insert(order: OrderProductModel) {
return orderProductDao.insert(order)
}
suspend fun update(order: OrderProductModel) {
return orderProductDao.update(order)
}
suspend fun delete(order: OrderProductModel) {
return orderProductDao.delete(order)
}
}

View File

@ -0,0 +1,36 @@
package com.example.shawarma.data.repos
import com.example.shawarma.data.interfaces.dao.OrderDao
import com.example.shawarma.data.models.OrderModel
import com.example.shawarma.data.models.OrderWithProducts
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class OrderRepository @Inject constructor(
private val orderDao: OrderDao
){
suspend fun insert(order: OrderModel): Long {
return orderDao.insert(order)
}
suspend fun update(order:OrderModel) {
return orderDao.update(order)
}
suspend fun delete(order: OrderModel) {
return orderDao.delete(order)
}
fun getAll(): Flow<List<OrderWithProducts>> {
return orderDao.getAll()
}
fun getById(id: Int): Flow<List<OrderWithProducts>> {
return orderDao.getById(id)
}
fun getByUserId(userId: Int): Flow<List<OrderWithProducts>> {
return orderDao.getByUserId(userId)
}
fun getUnpaidByUser(userId: Int) : Flow<OrderWithProducts?> {
return orderDao.getUnpaidByUser(userId)
}
fun getPaidByUser(userId: Int) : Flow<List<OrderWithProducts>> {
return orderDao.getPaidByUser(userId)
}
}

View File

@ -0,0 +1,62 @@
package com.example.shawarma.data.repos
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.shawarma.data.interfaces.dao.OrderProductDao
import com.example.shawarma.data.interfaces.dao.ProductDao
import com.example.shawarma.data.models.ProductModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class ProductRepository @Inject constructor(
private val productDao: ProductDao,
private val orderProductDao: OrderProductDao
) {
suspend fun insert(product: ProductModel) {
return productDao.insert(product)
}
suspend fun update(product: ProductModel) {
return productDao.update(product)
}
suspend fun delete(product: ProductModel) {
orderProductDao.deleteByProductId(product.id!!)
return productDao.delete(product)
}
/*fun getAll(): Flow<List<ProductModel>> {
return productDao.getAll()
}
fun getDiscounts(): Flow<List<ProductModel>> {
return productDao.getDiscounts()
}
fun getItems(): Flow<List<ProductModel>> {
return productDao.getItems()
}*/
fun getById(id: Int): Flow<ProductModel> {
return productDao.getById(id)
}
fun getAllProductsPaged(): Flow<PagingData<ProductModel>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = productDao::getPaged
).flow
fun getAllDiscountsPaged(): Flow<PagingData<ProductModel>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = productDao::getPagedDiscounts
).flow
fun getAllItemsPaged(): Flow<PagingData<ProductModel>> = Pager(
config = PagingConfig(
pageSize = 6,
enablePlaceholders = false
),
pagingSourceFactory = productDao::getPagedItems
).flow
}

View File

@ -0,0 +1,29 @@
package com.example.shawarma.data.repos
import com.example.shawarma.data.interfaces.dao.UserDao
import com.example.shawarma.data.models.UserModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class UserRepository @Inject constructor(
private val userDao: UserDao
) {
suspend fun insert(user: UserModel) {
return userDao.insert(user)
}
suspend fun update (user: UserModel) {
return userDao.update(user)
}
suspend fun delete (user: UserModel) {
return userDao.delete(user)
}
fun getAll(): Flow<List<UserModel>> {
return userDao.getAll()
}
fun getById(id: Int): Flow<UserModel> {
return userDao.getById(id)
}
fun login(login: String, password: String): Flow<UserModel?> {
return userDao.login(login, password)
}
}

View File

@ -0,0 +1,19 @@
package com.example.shawarma.data.sharedpref
import android.content.Context
import android.content.SharedPreferences
class PreferencesManager(context: Context) {
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
fun saveData(key: String, value: String) {
val editor = sharedPreferences.edit()
editor.putString(key, value)
editor.apply()
}
fun getData(key: String, defaultValue: String): String {
return sharedPreferences.getString(key, defaultValue) ?: defaultValue
}
}

View File

@ -0,0 +1,82 @@
package com.example.shawarma.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.shawarma.screens.authorization.AuthorizationScreen
import com.example.shawarma.screens.cart.CartScreen
import com.example.shawarma.screens.discount.DiscountScreen
import com.example.shawarma.screens.home.HomeScreen
import com.example.shawarma.screens.orders.OrdersScreen
import com.example.shawarma.screens.products.ProductScreen
import com.example.shawarma.screens.products.ProductsScreen
import com.example.shawarma.screens.registration.RegistrationScreen
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.widgets.BottomNavBar
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainNavBar() {
val navController = rememberNavController()
Scaffold(
backgroundColor = MyLightYellow,
modifier = Modifier.fillMaxSize(),
bottomBar = {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
if ( currentRoute != ScreenPaths.authorization.name && currentRoute != ScreenPaths.registration.name) {
BottomNavBar(navController = navController)
}
}
) {
NavHost(navController = navController, startDestination = ScreenPaths.authorization.name) {
composable(ScreenPaths.authorization.name) {
AuthorizationScreen(navController)
}
composable(ScreenPaths.registration.name) {
RegistrationScreen(navController)
}
composable(ScreenPaths.home.name) {
HomeScreen()
}
composable(ScreenPaths.discount.name) {
DiscountScreen()
}
composable(ScreenPaths.cart.name) {
CartScreen()
}
composable(ScreenPaths.orders.name) {
OrdersScreen()
}
composable(ScreenPaths.products.name) {
ProductsScreen(navController)
}
composable(
route = ScreenPaths.product.name + "?productId={productId}",
arguments = listOf(
navArgument("productId") {
defaultValue = 0
type = NavType.IntType
}
)
) { navBackStackEntry ->
/* Extracting the id from the route */
val productId = navBackStackEntry.arguments?.getInt("productId")
ProductScreen(navController, productId)
}
}
}
}

View File

@ -0,0 +1,197 @@
package com.example.shawarma.screens.authorization
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextDecoration
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.navigation.NavHostController
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.ui.theme.JejuFamily
import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.viewmodels.UserViewModel
import com.example.shawarma.widgets.MyTextField
import com.example.shawarma.widgets.ShawarmaLogo1
@Composable
fun AuthorizationScreen(navHostController: NavHostController) {
Box(contentAlignment = Alignment.TopCenter){
ShawarmaLogo1()
AuthorizationCard(navHostController)
}
}
@Composable
fun AuthorizationCard(navHostController: NavHostController) {
val login = remember { mutableStateOf(TextFieldValue("")) }
val password = remember { mutableStateOf(TextFieldValue("")) }
val userViewModel: UserViewModel = hiltViewModel<UserViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
if (userViewModel.userModel.observeAsState().value != null) {
preferencesManager.saveData("user_id", userViewModel.userModel.value?.id.toString())
preferencesManager.saveData("user_role", userViewModel.userModel.value?.role.toString())
navHostController.navigate(ScreenPaths.home.name) {
popUpTo(ScreenPaths.authorization.name) {
inclusive = true
}
}
}
if (userViewModel.authorizationState.observeAsState().value == false) {
AlertDialog(
title = {
Text(
text = "Ошибка входа в аккаунт",
fontFamily = NunitoFamily,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
},
text = {
Text(
text = "Проверьте корректность введенных данных",
fontFamily = NunitoFamily,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
},
onDismissRequest = {
userViewModel.calmAuthorizationState()
},
buttons = {
TextButton(
onClick = {
userViewModel.calmAuthorizationState()
}
) {
Text("ОК")
}
}
)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.zIndex(2f)
.verticalScroll(rememberScrollState())
.imePadding()
.padding(10.dp)
.fillMaxHeight()
) {
Card(
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.size(275.dp, 290.dp + 72.dp)
.padding(top = 72.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Авторизация",
fontSize = 20.sp,
modifier = Modifier.padding(
top = 20.dp
),
style = TextStyle(
fontFamily = JejuFamily
)
)
MyTextField(
text = login,
onTextChanged = {login.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp),
placeholder = "Логин",
singleLine = true
)
MyTextField(
text = password,
onTextChanged = {password.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp),
placeholder = "Пароль",
singleLine = true
)
Button(
onClick = {
userViewModel.login(login.value.text, password.value.text)
},
colors = ButtonDefaults.buttonColors(MyLightRed, Color.White),
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp)
) {
Text(
text = "Войти",
style = TextStyle(
fontFamily = JejuFamily,
fontSize = 16.sp
)
)
}
Button(
onClick = {
navHostController.navigate(ScreenPaths.registration.name) {
popUpTo(ScreenPaths.registration.name) {
inclusive = true
}
}
},
colors = ButtonDefaults.buttonColors(Color.White),
elevation = ButtonDefaults.elevation(0.dp)
) {
Text(
text = "У меня нет аккаунта!",
textDecoration = TextDecoration.Underline,
style = TextStyle(
fontFamily = JejuFamily,
fontSize = 12.sp
)
)
}
}
}
}
}

View File

@ -0,0 +1,319 @@
package com.example.shawarma.screens.cart
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.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 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.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.viewmodels.CartViewModel
import com.example.shawarma.widgets.ShawarmaLogo2
@Composable
fun CartScreen() {
Box(
contentAlignment = Alignment.TopCenter
) {
CartWidget()
ShawarmaLogo2()
}
}
@Composable
fun CartWidget(){
val preferencesManager = PreferencesManager(LocalContext.current)
val cartViewModel: CartViewModel = hiltViewModel<CartViewModel>()
cartViewModel.getOrders(preferencesManager.getData("user_id", "null"))
var unpaidOrder: OrderWithProducts? = cartViewModel.unpaidOrder.observeAsState().value
val preparingOrders = cartViewModel.paidOrders.observeAsState().value
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
) {
Text(
text = "Корзина",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.padding(top = 55.dp)
.verticalScroll(rememberScrollState())
) {
Text(
text = "Оплачено:",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
LazyColumn(
modifier = Modifier
.width(340.dp)
.height(200.dp)
) {
if (preparingOrders != null) {
items(preparingOrders.size) { index ->
PaidItem(preparingOrders[index])
}
}
}
Text(
text = "Ожидает оплаты:",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
if (unpaidOrder != null) {
CartItem(order = unpaidOrder)
}
Spacer(modifier = Modifier.height(20.dp))
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = Color(0xFF91FF87)
),
shape = RoundedCornerShape(20.dp),
border = BorderStroke(2.dp, Color(0x66000000)),
modifier = Modifier.size(240.dp, 60.dp),
onClick = {
if (unpaidOrder != null) {
cartViewModel.payForOrder(unpaidOrder)
}
}
) {
Text(
"Оплатить",
fontSize = 20.sp,
fontFamily = NunitoFamily,
fontWeight = FontWeight(700),
)
}
Spacer(modifier = Modifier.height(70.dp))
}
}
}
@Composable
fun PaidItem(order : OrderWithProducts) {
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 150.dp)
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(start = 20.dp, end = 20.dp)
){
Text(
text = "Статус: ",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold,
color = Color.Gray
)
Text(
text = order.order.status,
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold,
color = Color.Gray
)
}
LazyColumn(
modifier = Modifier.padding(top = 40.dp)
) {
items(order.orderWithProducts.size) { index ->
if (order.orderWithProducts.isNotEmpty()) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
) {
Text(
text = order.orderWithProducts[index].product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
Text(
text = "x" + order.orderWithProducts[index].orderProductModel.quantity,
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
Text(
text = (order.orderWithProducts[index].orderProductModel.quantity * order.orderWithProducts[index].product.price).toString() + " руб.",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
}
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
}
@Composable
fun CartItem(order : OrderWithProducts) {
val cartViewModel: CartViewModel = hiltViewModel<CartViewModel>()
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 180.dp)
) {
LazyColumn (
horizontalAlignment = Alignment.CenterHorizontally
) {
items(order.orderWithProducts.size) {index ->
var count = remember { mutableStateOf(0)}
count.value = order.orderWithProducts[index].orderProductModel.quantity
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(20.dp)
.size(340.dp, 80.dp)
) {
Column(
modifier = Modifier.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Text(
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() + " руб.",
fontFamily = NunitoFamily,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
) {
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
shape = RoundedCornerShape(size = 20.dp),
modifier = Modifier
.fillMaxHeight()
.weight(1f)
.fillMaxSize(0.5f),
onClick = {
cartViewModel.removeProductFromOrder(order, index)
count.value -= 1
}
) {
Text(
text = "-",
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
Spacer(modifier = Modifier.fillMaxWidth(0.2f))
Text(
text = "x" + count.value + " ",
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.fillMaxWidth(0.2f))
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
shape = RoundedCornerShape(size = 20.dp),
modifier = Modifier
.fillMaxHeight()
.weight(1f)
.fillMaxSize(0.5f),
onClick = {
cartViewModel.addProductToOrder(order, index)
count.value += 1
}
) {
Text(
text = "+",
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
}
}
}

View File

@ -0,0 +1,195 @@
package com.example.shawarma.screens.discount
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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.text.style.TextDecoration
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.ProductModel
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.MyPriceBackground
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.viewmodels.HomeViewModel
import com.example.shawarma.widgets.ShawarmaLogo2
@Composable
fun DiscountScreen() {
Box(
contentAlignment = Alignment.TopCenter
) {
DiscountList()
ShawarmaLogo2()
}
}
@Composable
fun DiscountList(){
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
val productsListUiState = homeViewModel.discountListUiState.collectAsLazyPagingItems()
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
){
Text(
text = "Акции",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
LazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(top = 80.dp)
)
{
items(productsListUiState.itemCount) { index ->
if (index % 2 == 0 && index == productsListUiState.itemCount - 1) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp)
) {
DiscountCard(productsListUiState[index]!!)
}
} else {
if (index % 2 != 1) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp)
) {
DiscountCard(productsListUiState[index]!!)
DiscountCard(productsListUiState[index+1]!!)
}
}
}
if (index == productsListUiState.itemCount - 1) {
Spacer(modifier = Modifier.height(70.dp))
}
}
}
}
}
@Composable
fun DiscountCard(product : ProductModel){
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
Card(
shape = RoundedCornerShape(20.dp),
backgroundColor = Color.White,
border = BorderStroke(2.dp, MyOrange),
modifier = Modifier
.size(160.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 10.dp)
)
Image(
painter = painterResource(id = R.drawable.shawarma2),
contentDescription = "Shawarma",
Modifier.size(135.dp, 70.dp)
)
Spacer(modifier = Modifier.height(16.dp))
Card(
shape = RoundedCornerShape(20.dp),
backgroundColor = MyPriceBackground,
border = BorderStroke(2.dp, MyOrange),
modifier = Modifier
.size(160.dp, 36.dp)
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween
){
Box(
modifier = Modifier.padding(start = 12.dp)
) {
Text(
text = product.oldPrice.toString() + "руб. ",
fontFamily = NunitoFamily,
fontSize = 10.sp,
fontWeight = FontWeight.Bold,
textDecoration = TextDecoration.LineThrough
)
Text(
text = product.price.toString() + "руб. ",
fontFamily = NunitoFamily,
fontSize = 16.sp,
fontWeight = FontWeight.ExtraBold,
color = Color.Red,
modifier = Modifier.padding(top = 8.dp)
)
}
Button(
onClick = {
product.id?.let { homeViewModel.addProductToCart(it, preferencesManager.getData("user_id", "null")) }
},
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow,
contentColor = Color.Black
),
shape = RoundedCornerShape(20.dp),
) {
Text(
text = "Купить",
fontSize = 14.sp,
fontWeight = FontWeight.ExtraBold,
fontFamily = NunitoFamily,
)
}
}
}
}
}
}

View File

@ -0,0 +1,185 @@
package com.example.shawarma.screens.home
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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 androidx.paging.compose.itemKey
import com.example.shawarma.R
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.MyPriceBackground
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.viewmodels.HomeViewModel
import com.example.shawarma.widgets.ShawarmaLogo2
@Composable
fun HomeScreen() {
Box(
contentAlignment = Alignment.TopCenter
) {
HomeList()
ShawarmaLogo2()
}
}
@Composable
fun HomeList(){
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
val productsListUiState = homeViewModel.productListUiState.collectAsLazyPagingItems()
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
){
Text(
text = "Шавармашка",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
LazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(top = 80.dp)
)
{
items(
count = productsListUiState.itemCount,
key = productsListUiState.itemKey()
) { index ->
if (index % 2 == 0 && index == productsListUiState.itemCount - 1) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp)
) {
ProductCard(productsListUiState[index]!!)
}
} else {
if (index % 2 != 1) {
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier
.fillMaxWidth()
.padding(top = 10.dp)
) {
ProductCard(productsListUiState[index]!!)
ProductCard(productsListUiState[index + 1]!!)
}
}
}
if (index == productsListUiState.itemCount - 1) {
Spacer(modifier = Modifier.height(70.dp))
}
}
}
}
}
@Composable
fun ProductCard(product: ProductModel){
val homeViewModel: HomeViewModel = hiltViewModel<HomeViewModel>()
val preferencesManager = PreferencesManager(LocalContext.current)
Card(
shape = RoundedCornerShape(20.dp),
backgroundColor = Color.White,
border = BorderStroke(2.dp, MyOrange),
modifier = Modifier
.size(160.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 10.dp)
)
Image(
painter = painterResource(id = R.drawable.shawarma2),
contentDescription = "Shawarma",
Modifier.size(135.dp, 70.dp)
)
Spacer(modifier = Modifier.height(16.dp))
Card(
shape = RoundedCornerShape(20.dp),
backgroundColor = MyPriceBackground,
border = BorderStroke(2.dp, MyOrange),
modifier = Modifier
.size(160.dp, 36.dp)
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween
){
Text(
text = product.price.toString() + " руб.",
fontFamily = NunitoFamily,
fontSize = 16.sp,
fontWeight = FontWeight.ExtraBold,
modifier = Modifier.padding(start = 12.dp, top = 6.dp)
)
Button(
onClick = {
product.id?.let { homeViewModel.addProductToCart(it, preferencesManager.getData("user_id", "null")) }
},
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow,
contentColor = Color.Black
),
shape = RoundedCornerShape(20.dp),
) {
Text(
text = "Купить",
fontSize = 14.sp,
fontWeight = FontWeight.ExtraBold,
fontFamily = NunitoFamily,
)
}
}
}
}
}
}

View File

@ -0,0 +1,425 @@
package com.example.shawarma.screens.orders
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
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.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 com.example.shawarma.R
import com.example.shawarma.data.models.OrderStatus
import com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
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() {
Box(
contentAlignment = Alignment.Center
) {
ShawarmaLogo2()
OrdersList()
}
}
@Composable
fun OrdersList(){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
val preparingOrders = ordersViewModel.preparingOrders.observeAsState().value
val preparedOrders = ordersViewModel.preparedOrders.observeAsState().value
val processedOrders = ordersViewModel.processedOrders.observeAsState().value
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
) {
Text(
text = "Заказы",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.padding(top = 55.dp)
.verticalScroll(rememberScrollState())
){
Text(
text = "Готовится:",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
LazyColumn(
modifier = Modifier
.width(340.dp)
.height(250.dp)
) {
if (preparingOrders != null) {
if (preparingOrders.isNotEmpty()) {
items(preparingOrders.size) { index ->
PreparingItem(preparingOrders[index])
}
}
}
}
Text(
text = "Готово:",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
LazyColumn(
modifier = Modifier
.width(340.dp)
.height(250.dp)
) {
if (preparedOrders != null) {
if (preparedOrders.isNotEmpty()) {
items(preparedOrders.size) { index ->
PreparedItem(preparedOrders[index])
}
}
}
}
Text(
text = "Выдано:",
fontFamily = NunitoFamily,
fontSize = 20.sp,
modifier = Modifier.padding(top = 15.dp),
fontWeight = FontWeight.Bold
)
LazyColumn(
modifier = Modifier
.width(340.dp)
.height(250.dp)
) {
if (processedOrders != null) {
if (processedOrders.isNotEmpty()) {
items(processedOrders.size) {index ->
ProcessedItem(processedOrders[index])
}
}
}
}
Spacer(modifier = Modifier.height(70.dp))
}
}
}
@Composable
fun PreparingItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 200.dp)
){
Column(
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(20.dp)
.size(340.dp, 60.dp)
){
Column(
modifier = Modifier.fillMaxWidth(0.5f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
shape = RoundedCornerShape(size = 10.dp),
modifier = Modifier
.size(170.dp, 80.dp)
.fillMaxSize(),
onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Готово.name)
}
) {
Text(
text = "Готово!",
fontFamily = NunitoFamily,
fontSize = 14.sp,
fontWeight = FontWeight.Bold
)
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Text(
text = "x" + order.orderWithProducts[index].orderProductModel.quantity,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
}
@Composable
fun PreparedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 200.dp)
){
Column(
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(20.dp)
.size(340.dp, 60.dp)
){
Column(
modifier = Modifier.fillMaxWidth(0.5f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
Button(
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
shape = RoundedCornerShape(size = 10.dp),
modifier = Modifier
.size(170.dp, 80.dp)
.fillMaxSize(),
onClick = {
ordersViewModel.changeOrderStatus(order, OrderStatus.Выдано.name)
}
) {
Text(
text = "Выдано!",
fontFamily = NunitoFamily,
fontSize = 14.sp,
fontWeight = FontWeight.Bold
)
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Text(
text = "x" + order.orderWithProducts[index].orderProductModel.quantity,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
}
@Composable
fun ProcessedItem(order : OrderWithProducts){
val ordersViewModel = hiltViewModel<OrdersViewModel>()
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 200.dp)
){
Column(
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(20.dp)
.size(340.dp, 60.dp)
){
Column(
modifier = Modifier.fillMaxWidth(0.3f)
){
val localDateFormat = SimpleDateFormat("HH:mm")
val time = localDateFormat.format(order.order.date)
Text(
text = time,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
Column(
modifier = Modifier.fillMaxWidth(0.3f)
){
Text(
text = order.order.date.toString(),
fontFamily = NunitoFamily,
fontSize = 16.sp,
fontWeight = FontWeight.Bold
)
}
Button(
modifier = Modifier
.size(80.dp)
,
colors = ButtonDefaults.buttonColors(MyLightRed),
shape = RoundedCornerShape(20.dp),
onClick = {
ordersViewModel.deleteOrder(order)
}
) {
Icon(
painter = painterResource(id = R.drawable.trash),
contentDescription = "trash",
modifier = Modifier.size(80.dp)
)
}
}
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
){
items(order.orderWithProducts.size) {index ->
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = order.orderWithProducts[index].product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Text(
text = "x" + order.orderWithProducts[index].orderProductModel.quantity,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}
}
Spacer(modifier = Modifier.height(20.dp))
}

View File

@ -0,0 +1,158 @@
package com.example.shawarma.screens.products
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
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.navigation.NavHostController
import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.viewmodels.ProductViewModel
import com.example.shawarma.widgets.MyTextField
import com.example.shawarma.widgets.ShawarmaLogo2
@Composable
fun ProductScreen(navHostController: NavHostController, productId: Int?) {
Box(
contentAlignment = Alignment.TopCenter
) {
ProductWidget(navHostController, productId)
ShawarmaLogo2()
}
}
@Composable
fun ProductWidget(navHostController: NavHostController, productId: Int?) {
val title = remember { mutableStateOf(TextFieldValue(""))}
val price = remember { mutableStateOf(TextFieldValue(""))}
val oldPrice = remember { mutableStateOf(TextFieldValue(""))}
val productViewModel: ProductViewModel = hiltViewModel<ProductViewModel>()
val product = productViewModel.product.observeAsState().value
if (productViewModel.addingProductState.observeAsState().value == true) {
navHostController.navigate(ScreenPaths.products.name) {
popUpTo(ScreenPaths.product.name) {
inclusive = true
}
}
}
if (productId != null) {
productViewModel.getProduct(productId)
}
if (product != null) {
title.value = TextFieldValue(text = product.title)
price.value = TextFieldValue(text = product.price.toString())
oldPrice.value = TextFieldValue(text = product.oldPrice.toString())
}
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
){
Text(
text = "Товар",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
Column(
modifier = Modifier
.padding(top = 60.dp)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally
) {
MyTextField(
text = title,
onTextChanged = {title.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(300.dp, (60).dp),
placeholder = "Наименование",
singleLine = true
)
MyTextField(
text = price,
onTextChanged = {price.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(300.dp, (60).dp),
placeholder = "Цена",
singleLine = true
)
MyTextField(
text = oldPrice,
onTextChanged = {oldPrice.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(300.dp, (60).dp),
placeholder = "Старая цена",
singleLine = true
)
Button(
modifier = Modifier
.padding(top = 80.dp)
.size(300.dp, 50.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
border = BorderStroke(2.dp, color = MyOrange),
shape = RoundedCornerShape(20.dp),
onClick = {
if (product == null)
productViewModel.addProduct(title.value.text, price.value.text.toInt(), if (!oldPrice.value.text.isNullOrEmpty()) oldPrice.value.text.toInt() else null)
else
productViewModel.updateProduct(title.value.text, price.value.text.toInt(), if (!oldPrice.value.text.isNullOrEmpty()) oldPrice.value.text.toInt() else null)
}
) {
Text(
text = if (product != null) "Изменить" else "Добавить",
fontFamily = NunitoFamily,
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
}
}
}

View File

@ -0,0 +1,203 @@
package com.example.shawarma.screens.products
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
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.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.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.example.shawarma.R
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.ui.theme.MarckFamily
import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.MyLightYellow
import com.example.shawarma.ui.theme.MyMainBackground
import com.example.shawarma.ui.theme.MyOrange
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.viewmodels.ProductsViewModel
import com.example.shawarma.widgets.ShawarmaLogo2
@Composable
fun ProductsScreen(navHostController: NavHostController) {
Box(
contentAlignment = Alignment.TopCenter
) {
ProductsList(navHostController)
ShawarmaLogo2()
}
}
@Composable
fun ProductsList(navHostController: NavHostController){
val productsViewModel: ProductsViewModel = hiltViewModel<ProductsViewModel>()
val products = productsViewModel.productListUiState.collectAsLazyPagingItems()
Box(
modifier = Modifier
.clip(shape = RoundedCornerShape(30.dp))
.padding(top = 100.dp)
.fillMaxSize()
.background(color = MyMainBackground)
.zIndex(2f),
contentAlignment = Alignment.TopCenter
){
Text(
text = "Товары",
fontFamily = MarckFamily,
fontSize = 40.sp,
modifier = Modifier.padding(top = 15.dp)
)
Button(
modifier = Modifier
.padding(top = 80.dp)
.size(340.dp, 60.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
border = BorderStroke(2.dp, color = MyOrange),
shape = RoundedCornerShape(20.dp),
onClick = {
navHostController.navigate(ScreenPaths.product.name)
}
) {
Text(
text = "Добавить товар",
fontFamily = NunitoFamily,
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
LazyColumn(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(top = 160.dp)
)
{
items(
products.itemCount,
key = products.itemKey()
) { index ->
ProductItem(products[index]!!, navHostController)
Spacer(modifier = Modifier.height(20.dp))
if (index == products.itemCount - 1) {
Spacer(modifier = Modifier.height(70.dp))
}
}
}
}
}
@Composable
fun ProductItem(product: ProductModel, navHostController: NavHostController){
val productsViewModel: ProductsViewModel = hiltViewModel<ProductsViewModel>()
Card(
border = BorderStroke(width = 2.dp, color = MyOrange),
shape = RoundedCornerShape(size = 20.dp),
backgroundColor = Color.White,
modifier = Modifier.size(340.dp, 100.dp)
) {
Row(
modifier = Modifier
.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
Column(
modifier = Modifier.fillMaxWidth(0.5f)
) {
Text(
text = product.title,
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
if (product.oldPrice != null) {
Text(
text = product.price.toString() + " руб.",
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
color = Color.Red
)
}
else {
Text(
text = product.price.toString() + " руб.",
fontFamily = NunitoFamily,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
}
Button(
modifier = Modifier.size(60.dp),
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightYellow
),
onClick = {
navHostController.navigate(
route = ScreenPaths.product.name + "?productId=" + product.id.toString()
)
}
) {
Icon(
painter = painterResource(id = R.drawable.pen_icon),
contentDescription = "pen",
modifier = Modifier.fillMaxSize()
)
}
Button(
modifier = Modifier.size(60.dp),
shape = RoundedCornerShape(10.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = MyLightRed
),
onClick = {
productsViewModel.deleteProduct(product)
}
) {
Icon(
painter = painterResource(id = R.drawable.trash),
contentDescription = "trash",
modifier = Modifier.fillMaxSize()
)
}
}
}
}

View File

@ -0,0 +1,204 @@
package com.example.shawarma.screens.registration
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextDecoration
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.navigation.NavHostController
import com.example.shawarma.ui.theme.JejuFamily
import com.example.shawarma.ui.theme.MyLightRed
import com.example.shawarma.ui.theme.NunitoFamily
import com.example.shawarma.utils.ScreenPaths
import com.example.shawarma.viewmodels.UserViewModel
import com.example.shawarma.widgets.MyTextField
import com.example.shawarma.widgets.ShawarmaLogo1
@Composable
fun RegistrationScreen(navHostController: NavHostController) {
Box(contentAlignment = Alignment.TopCenter){
ShawarmaLogo1()
RegistrationCard(navHostController)
}
}
@Composable
fun RegistrationCard(navHostController: NavHostController){
val login = remember { mutableStateOf(TextFieldValue("")) }
val password = remember { mutableStateOf(TextFieldValue("")) }
val passwordRepeat = remember { mutableStateOf(TextFieldValue("")) }
val userViewModel: UserViewModel = hiltViewModel<UserViewModel>()
if (userViewModel.registrationState.observeAsState().value == true) {
navHostController.navigate(ScreenPaths.authorization.name) {
popUpTo(ScreenPaths.authorization.name) {
inclusive = true
}
}
}
if (userViewModel.registrationState.observeAsState().value == false) {
AlertDialog(
title = {
Text(
text = "Ошибка регистрации",
fontFamily = NunitoFamily,
fontWeight = FontWeight.Bold,
fontSize = 20.sp
)
},
text = {
Text(
text = "Проверьте корректность введенных данных",
fontFamily = NunitoFamily,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
},
onDismissRequest = {
userViewModel.calmRegistrationState()
},
buttons = {
TextButton(
onClick = {
userViewModel.calmRegistrationState()
}
) {
Text("ОК")
}
}
)
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.zIndex(2f)
.verticalScroll(rememberScrollState())
.imePadding()
.padding(10.dp)
.fillMaxHeight()
) {
Card(
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.size(275.dp, 380.dp + 72.dp)
.padding(top = 72.dp)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "Регистрация",
fontSize = 20.sp,
modifier = Modifier.padding(
top = 20.dp
),
style = TextStyle(
fontFamily = JejuFamily
)
)
MyTextField(
text = login,
onTextChanged = {login.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp),
placeholder = "Логин",
singleLine = true
)
MyTextField(
text = password,
onTextChanged = {password.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp),
placeholder = "Пароль",
singleLine = true
)
MyTextField(
text = passwordRepeat,
onTextChanged = {passwordRepeat.value = it},
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp),
placeholder = "Повторите пароль",
singleLine = true
)
Button(
onClick = {
userViewModel.register(login.value.text, password.value.text, passwordRepeat.value.text)
},
colors = ButtonDefaults.buttonColors(MyLightRed, Color.White),
shape = RoundedCornerShape(20.dp),
modifier = Modifier
.padding(
top = (20).dp
)
.size(208.dp, (50).dp)
) {
Text(
text = "Зарегистрироваться",
style = TextStyle(
fontFamily = JejuFamily,
fontSize = 16.sp
)
)
}
Button(
onClick = {
navHostController.navigate(ScreenPaths.authorization.name) {
popUpTo(ScreenPaths.authorization.name) {
inclusive = true
}
}
},
colors = ButtonDefaults.buttonColors(Color.White),
elevation = ButtonDefaults.elevation(0.dp)
) {
Text(
text = "У меня уже есть аккаунт!",
textDecoration = TextDecoration.Underline,
style = TextStyle(
fontFamily = JejuFamily,
fontSize = 12.sp
)
)
}
}
}
}
}

View File

@ -0,0 +1,10 @@
package com.example.shawarma.ui.theme
import androidx.compose.ui.graphics.Color
val MyLightYellow = Color(255,225,120,255)
val MyLightRed = Color(255,100,100,255)
val MyTextFieldBackground = Color(232,232,232,255)
val MyPriceBackground = Color(0xFFE8E8E8)
val MyMainBackground = Color(0x80FFFFFF)
val MyOrange = Color(0xFFFF9600)

View File

@ -0,0 +1,11 @@
package com.example.shawarma.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(4.dp),
large = RoundedCornerShape(0.dp)
)

View File

@ -0,0 +1,38 @@
package com.example.shawarma.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
private val DarkColorPalette = darkColors(
)
private val LightColorPalette = lightColors(
/* Other default colors to override
background = Color.White,
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun ShawarmaTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}

View File

@ -0,0 +1,41 @@
package com.example.shawarma.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.shawarma.R
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
val JejuFamily = FontFamily(
Font(R.font.jejugothic_regular, FontWeight.Normal)
)
val MarckFamily = FontFamily(
Font(R.font.marckscript_regular, FontWeight.Normal)
)
val NunitoFamily = FontFamily(
Font(R.font.nunito_wght, FontWeight.Normal)
)

View File

@ -0,0 +1,12 @@
package com.example.shawarma.utils
import com.example.shawarma.R
sealed class BottomNavItem(var title:String, var icon:Int, var screen_route:String) {
object Home : BottomNavItem("Home", R.drawable.home_icon,ScreenPaths.home.name)
object Discount : BottomNavItem("Discount", R.drawable.discount_icon,ScreenPaths.discount.name)
object Cart : BottomNavItem("Cart", R.drawable.cart_icon,ScreenPaths.cart.name)
object Orders: BottomNavItem("Orders", R.drawable.orders_icon,ScreenPaths.orders.name)
object Products: BottomNavItem("Products", R.drawable.pen_icon, ScreenPaths.products.name)
}

View File

@ -0,0 +1,5 @@
package com.example.shawarma.utils
enum class ScreenPaths {
authorization, registration, home, discount, cart, orders, products, product
}

View File

@ -0,0 +1,73 @@
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 com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.data.repos.OrderProductRepository
import com.example.shawarma.data.repos.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class CartViewModel @Inject constructor(
private val orderRepository: OrderRepository,
private val orderProductRepository: OrderProductRepository
) : ViewModel(){
private val _unpaidOrder = MutableLiveData<OrderWithProducts>()
val unpaidOrder: LiveData<OrderWithProducts>
get() = _unpaidOrder
private val _paidOrders = MutableLiveData<List<OrderWithProducts>>()
val paidOrders: LiveData<List<OrderWithProducts>>
get() = _paidOrders
fun getOrders(userId: String) {
if (userId == "null") return
viewModelScope.launch {
orderRepository.getUnpaidByUser(userId.toInt()).collect {
_unpaidOrder.postValue(it)
}
}
viewModelScope.launch {
orderRepository.getPaidByUser(userId.toInt()).collect {
_paidOrders.postValue(it)
}
}
}
fun payForOrder(order: OrderWithProducts) {
val model = order.order
model.status = OrderStatus.Готовится.name
viewModelScope.launch {
orderRepository.update(model)
}
}
fun removeProductFromOrder(order: OrderWithProducts, productId: Int) {
val model = order.orderWithProducts[productId].orderProductModel
if(model.quantity == 1) {
// delete
viewModelScope.launch {
orderProductRepository.delete(model)
}
}
else{
// update
model.quantity -= 1
viewModelScope.launch {
orderProductRepository.update(model)
}
}
}
fun addProductToOrder(order: OrderWithProducts, productId: Int) {
val model = order.orderWithProducts[productId].orderProductModel
// update
model.quantity += 1
viewModelScope.launch {
orderProductRepository.update(model)
}
}
}

View File

@ -0,0 +1,63 @@
package com.example.shawarma.viewmodels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import com.example.shawarma.data.models.OrderModel
import com.example.shawarma.data.models.OrderProductModel
import com.example.shawarma.data.models.OrderStatus
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.repos.OrderProductRepository
import com.example.shawarma.data.repos.OrderRepository
import com.example.shawarma.data.repos.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val productRepository: ProductRepository,
private val orderRepository: OrderRepository,
private val orderProductRepository: OrderProductRepository
) : ViewModel() {
val productListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllProductsPaged()
val discountListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllDiscountsPaged()
fun addProductToCart(productId: Int, userId: String) {
if (userId == "null") return
viewModelScope.launch {
val product = productRepository.getById(productId).first()
val order = orderRepository.getUnpaidByUser(userId.toInt()).first()
if (order == null) {
val calendar: Calendar = Calendar.getInstance()
calendar.time = Date()
calendar.add(Calendar.HOUR_OF_DAY, 4)
val newOrderId = orderRepository.insert(OrderModel(null, OrderStatus.Неоплачено.name, userId.toInt(),calendar.time))
orderProductRepository.insert(OrderProductModel(newOrderId.toInt(), productId, 1, product.price))
}
else {
var isAlreadyAdded = false
for (prod in order.orderWithProducts) {
if (prod.product.id == productId) {
val model = prod.orderProductModel
model.quantity += 1
model.totalPrice += prod.product.price
orderProductRepository.update(model)
isAlreadyAdded = true
}
}
if (!isAlreadyAdded) {
orderProductRepository.insert(OrderProductModel(order.order.id!!, productId, 1, product.price))
}
}
}
}
}

View File

@ -0,0 +1,55 @@
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 com.example.shawarma.data.models.OrderWithProducts
import com.example.shawarma.data.repos.OrderRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
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
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 })
}
}
}
fun changeOrderStatus(order: OrderWithProducts, newStatus: String) {
val model = order.order
model.status = newStatus
viewModelScope.launch{
orderRepository.update(model)
}
}
fun deleteOrder(order: OrderWithProducts) {
viewModelScope.launch{
orderRepository.delete(order.order)
}
}
}

View File

@ -0,0 +1,46 @@
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.ProductModel
import com.example.shawarma.data.repos.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProductViewModel @Inject constructor(
private val productRepository: ProductRepository
) : ViewModel() {
private val _addingProductState = MutableLiveData<Boolean>(false)
val addingProductState: LiveData<Boolean?>
get() = _addingProductState
private val _product = MutableLiveData<ProductModel>()
val product: LiveData<ProductModel>
get() = _product
fun addProduct(name: String, price: Int, oldPrice: Int? = null) {
viewModelScope.launch {
productRepository.insert(ProductModel(null, name, price, oldPrice))
_addingProductState.postValue(true)
}
}
fun getProduct(productId: Int) {
viewModelScope.launch {
productRepository.getById(productId).collect {
_product.postValue(it)
}
}
}
fun updateProduct(name: String, price: Int, oldPrice: Int? = null) {
viewModelScope.launch {
productRepository.update(ProductModel(product.value?.id, name, price, oldPrice))
_addingProductState.postValue(true)
}
}
}

View File

@ -0,0 +1,32 @@
package com.example.shawarma.viewmodels
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingData
import com.example.shawarma.data.models.ProductModel
import com.example.shawarma.data.repos.ProductRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class ProductsViewModel @Inject constructor(
private val productRepository: ProductRepository
) : ViewModel() {
private val _products = MutableLiveData<List<ProductModel>>()
val products: LiveData<List<ProductModel>>
get() = _products
val productListUiState: Flow<PagingData<ProductModel>> = productRepository.getAllItemsPaged()
fun deleteProduct(product: ProductModel) {
viewModelScope.launch {
productRepository.delete(product)
}
}
}

View File

@ -0,0 +1,92 @@
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.UserModel
import com.example.shawarma.data.repos.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class UserViewModel @Inject constructor(
private val userRepository: UserRepository
) : ViewModel() {
private val _userModel = MutableLiveData<UserModel?>()
val userModel: LiveData<UserModel?>
get() = _userModel
private val _authorizationState = MutableLiveData<Boolean?>()
val authorizationState: LiveData<Boolean?>
get() = _authorizationState
fun login(login: String, password: String){
viewModelScope.launch {
withContext(Dispatchers.Main) {
userRepository.login(login, password).collect() { user ->
if (user != null) {
_userModel.postValue(user)
_authorizationState.postValue(true)
}
else {
_userModel.postValue(null)
_authorizationState.postValue(false)
}
}
}
}
}
fun calmAuthorizationState() {
_authorizationState.postValue(null)
}
private val _registrationState = MutableLiveData<Boolean>()
val registrationState: LiveData<Boolean>
get() = _registrationState
fun register(login: String, password: String, passwordRepeat: String) {
_registrationState.postValue(null)
if (password != passwordRepeat) {
_registrationState.postValue(false)
return
}
if (login.length < 5 || login.length > 20) {
_registrationState.postValue(false)
return
}
if (password.length < 5 || password.length > 20) {
_registrationState.postValue(false)
return
}
viewModelScope.launch {
withContext(Dispatchers.Main) {
userRepository.login(login, password).collect() { user ->
if (user == null) {
if (login == "admin" && password == "admin") {
userRepository.insert(UserModel(null, login, password, "ADMIN"))
_registrationState.postValue(true)
}
else {
userRepository.insert(UserModel(null, login, password, "USER"))
_registrationState.postValue(true)
}
}
else {
if (registrationState.value != true) {
_registrationState.postValue(false)
}
}
}
}
}
}
fun calmRegistrationState() {
_registrationState.postValue(null)
}
}

View File

@ -0,0 +1,71 @@
package com.example.shawarma.widgets
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.shawarma.data.sharedpref.PreferencesManager
import com.example.shawarma.utils.BottomNavItem
@Composable
fun BottomNavBar(navController: NavController) {
val preferencesManager = PreferencesManager(LocalContext.current)
val user_role = preferencesManager.getData("user_role", "USER")
val adminItems = listOf(
BottomNavItem.Discount,
BottomNavItem.Home,
BottomNavItem.Cart,
BottomNavItem.Orders,
BottomNavItem.Products
)
val userItems = listOf(
BottomNavItem.Discount,
BottomNavItem.Home,
BottomNavItem.Cart
)
BottomNavigation(
backgroundColor = Color.White,
contentColor = Color.Black,
modifier = Modifier.height(60.dp)
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
val items = if (user_role == "ADMIN") adminItems else userItems
items.forEach { item ->
BottomNavigationItem(
icon = {
Icon(
painterResource(id = item.icon),
contentDescription = item.title,
modifier = Modifier.size(42.dp)
) },
selectedContentColor = Color.Black,
unselectedContentColor = Color.Black.copy(0.4f),
alwaysShowLabel = true,
selected = currentRoute == item.screen_route,
onClick = {
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
},
)
}
}
}

View File

@ -0,0 +1,57 @@
package com.example.shawarma.widgets
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.shawarma.ui.theme.JejuFamily
import com.example.shawarma.ui.theme.MyTextFieldBackground
@Composable
fun MyTextField(
text: MutableState<TextFieldValue>,
onTextChanged: (TextFieldValue) -> Unit,
modifier: Modifier,
placeholder: String,
singleLine: Boolean
) {
return TextField(
value = text.value,
onValueChange = onTextChanged,
placeholder = {
Text(
text = placeholder,
fontSize = 16.sp,
style = TextStyle(
fontFamily = JejuFamily
)
)
},
singleLine = singleLine,
shape = RoundedCornerShape(20.dp),
textStyle = TextStyle(
fontSize = 16.sp,
fontFamily = JejuFamily
),
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
disabledTextColor = Color.Transparent,
backgroundColor = MyTextFieldBackground,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
modifier = modifier
)
}

View File

@ -0,0 +1,45 @@
package com.example.shawarma.widgets
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.example.shawarma.R
@Composable
fun ShawarmaLogo1(){
Column(modifier = Modifier
.zIndex(-1f)
.fillMaxSize()
) {
Image(
painterResource(
id = R.drawable.shawarma1
),
contentDescription = "Logo",
modifier = Modifier
.size(256.dp, 256.dp)
.rotate(degrees = 19.25f)
.offset((-70).dp, (-5).dp),
)
Image(
painterResource(
id = R.drawable.shawarma1
),
contentDescription = "Logo",
modifier = Modifier
.size(256.dp, 256.dp)
.offset((200).dp, (100).dp)
.rotate(degrees = -136f)
)
}
}

View File

@ -0,0 +1,30 @@
package com.example.shawarma.widgets
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import com.example.shawarma.R
@Composable
fun ShawarmaLogo2() {
Column(
modifier = Modifier
.zIndex(-1f)
.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(id = R.drawable.shawarma1),
contentDescription = null,
modifier = Modifier
.size(256.dp, 256.dp)
)
}
}

View File

@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

Binary file not shown.

After

Width:  |  Height:  |  Size: 937 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 514 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="purple_200">#FFBB86FC</color>
<color name="purple_500">#FF6200EE</color>
<color name="purple_700">#FF3700B3</color>
<color name="teal_200">#FF03DAC5</color>
<color name="teal_700">#FF018786</color>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
</resources>

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">Shawarma</string>
</resources>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Shawarma" parent="android:Theme.Material.Light.NoActionBar">
<item name="android:statusBarColor">@color/purple_700</item>
</style>
</resources>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older that API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

View File

@ -0,0 +1,17 @@
package com.example.shawarma
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}

17
build.gradle Normal file
View File

@ -0,0 +1,17 @@
buildscript {
ext {
compose_ui_version = '1.2.0'
}
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.0'
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.42'
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.4.2' apply false
id 'com.android.library' version '7.4.2' apply false
id 'org.jetbrains.kotlin.android' version '1.7.0' apply false
}

26
gradle.properties Normal file
View File

@ -0,0 +1,26 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.defaults.buildfeatures.buildconfig=true
android.nonFinalResIds=false
android.suppressUnsupportedCompileSdk=34

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Fri Oct 06 03:21:29 GMT+04:00 2023
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

185
gradlew vendored Normal file
View File

@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Some files were not shown because too many files have changed in this diff Show More