Ver Fonte

Merge remote-tracking branch 'origin/master'

# Conflicts:
#	app/src/main/java/com/example/fitmarcetplacekuzminiv/MainViewModel.kt
#	app/src/main/java/com/example/fitmarcetplacekuzminiv/Screens/authScreen.kt
x1tosi há 1 mês atrás
pai
commit
364c9964c4

+ 19 - 31
app/src/main/java/com/example/fitmarcetplacekuzminiv/MainViewModel.kt

@@ -1,26 +1,30 @@
 package com.example.fitmarcetplacekuzminiv
 
-import androidx.compose.runtime.mutableStateOf
 import androidx.lifecycle.ViewModel
 import androidx.lifecycle.viewModelScope
 import com.example.fitmarcetplacekuzminiv.domain.Constants
-import com.example.fitmarcetplacekuzminiv.domain.Constants.supabase
-import com.google.android.gms.analytics.ecommerce.Product
 import io.github.jan.supabase.gotrue.auth
 import io.github.jan.supabase.gotrue.providers.builtin.Email
-import io.github.jan.supabase.postgrest.from
-import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
+import io.github.jan.supabase.gotrue.providers.builtin.OTP
 import kotlinx.coroutines.launch
 
-data class Product(val id: Int, val name: String, val price: Double)
+class MainViewModel():ViewModel() {
 
-class MainViewModel : ViewModel() {
+    fun onSignInEmailCode(emailUser: String) {
+        viewModelScope.launch {
+            try {
+                Constants.supabase.auth.signInWith(OTP) {
+                    email = emailUser
+                    createUser = false
+                }
+
+            } catch (e: Exception) {
+                println(e.message.toString())
 
-    private val _products = MutableStateFlow<List<Product>>(emptyList())
-    val products: StateFlow<List<Product>> = _products
-    // Состояние для хранения результата авторизации
-    var authResult = mutableStateOf("")
+            }
+
+        }
+    }
 
     fun onSignInEmailPassword(emailUser: String, passwordUser: String) {
         viewModelScope.launch {
@@ -29,29 +33,13 @@ class MainViewModel : ViewModel() {
                     email = emailUser
                     password = passwordUser
                 }
+                println(user.toString())
+                println(Constants.supabase.auth.currentUserOrNull()!!.id)
                 println("Success")
-                authResult.value = "Success" // Устанавливаем успешный результат
             } catch (e: Exception) {
                 println("Error")
-                authResult.value = "Error" // Устанавливаем ошибочный результат
                 println(e.message.toString())
             }
         }
     }
-    //Обновление для извлечения данных
-    fun fetchProducts() {
-        viewModelScope.launch {
-            try {
-                // Fetch data from Supabase or other data source
-                val productList = supabase.from("products").select().decodeList<Product>()
-                _products.value = productList
-            } catch (e: Exception) {
-                // Handle the error
-                println("Error fetching products: ${e.message}")
-            }
-        }
-    }
-}
-
-
-
+}

+ 48 - 23
app/src/main/java/com/example/fitmarcetplacekuzminiv/Screens/authScreen.kt

@@ -1,31 +1,40 @@
 package com.example.fitmarcetplacekuzminiv.Screens
 
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.viewModels
 import androidx.compose.foundation.layout.*
 import androidx.compose.material3.*
 import androidx.compose.runtime.*
 import androidx.compose.ui.Alignment
 import androidx.compose.ui.Modifier
-import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.tooling.preview.Preview
 import androidx.compose.ui.unit.dp
-import androidx.navigation.NavController
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.TextFieldValue
+import androidx.lifecycle.viewmodel.compose.viewModel
 import com.example.fitmarcetplacekuzminiv.MainViewModel
-//страница авторизацииd
-@Composable
-fun AuthScreen(navController: NavController, mainViewModel: MainViewModel) {
-    val email = remember { mutableStateOf("") }
-    val password = remember { mutableStateOf("") }
 
-    // Слушаем результат авторизации
-    val authResult by mainViewModel.authResult
+class AuthScreenActivity : ComponentActivity() {
 
-    // Если авторизация прошла успешно, переходим на main_screen
-    LaunchedEffect(authResult) {
-        if (authResult == "Success") {
-            navController.navigate("main_screen") {
-                popUpTo("auth_screen") { inclusive = true }
-            }
+    // Инициализируем ViewModel
+    private val mainViewModel: MainViewModel by viewModels()
+
+    override fun onCreate(savedInstanceState: Bundle?) {
+        super.onCreate(savedInstanceState)
+        setContent {
+            AuthScreen(mainViewModel)
         }
     }
+}
+
+@Composable
+fun AuthScreen(mainViewModel: MainViewModel = viewModel()) {
+    var email by remember { mutableStateOf(TextFieldValue("")) }
+    var password by remember { mutableStateOf(TextFieldValue("")) }
+    var errorMessage by remember { mutableStateOf("") }
+    var successMessage by remember { mutableStateOf("") }
 
     Box(
         modifier = Modifier.fillMaxSize(),
@@ -39,31 +48,47 @@ fun AuthScreen(navController: NavController, mainViewModel: MainViewModel) {
                 .padding(16.dp)
         ) {
             OutlinedTextField(
-                value = email.value,
-                onValueChange = { newText -> email.value = newText },
+                value = email,
+                onValueChange = { email = it },
                 label = { Text("Email") },
                 modifier = Modifier.fillMaxWidth()
             )
             Spacer(modifier = Modifier.height(16.dp))
             OutlinedTextField(
-                value = password.value,
-                onValueChange = { newText -> password.value = newText },
+                value = password,
+                onValueChange = { password = it },
                 label = { Text("Password") },
                 visualTransformation = PasswordVisualTransformation(),
                 modifier = Modifier.fillMaxWidth()
             )
             Spacer(modifier = Modifier.height(24.dp))
             Button(onClick = {
-                mainViewModel.onSignInEmailPassword(email.value, password.value)
+                // Вызов авторизации через email и пароль
+                if (email.text.isNotEmpty() && password.text.isNotEmpty()) {
+                    mainViewModel.onSignInEmailPassword(email.text, password.text)
+                } else {
+                    errorMessage = "Заполните все поля"
+                }
             }) {
                 Text("Login")
             }
 
-            // Отображаем сообщение об ошибке, если авторизация не удалась
-            if (authResult == "Error") {
+            // Отображение ошибок или успешного входа
+            if (errorMessage.isNotEmpty()) {
+                Spacer(modifier = Modifier.height(16.dp))
+                Text(text = errorMessage, color = MaterialTheme.colorScheme.error)
+            }
+
+            if (successMessage.isNotEmpty()) {
                 Spacer(modifier = Modifier.height(16.dp))
-                Text(text = "Ошибка: неверный email или пароль", color = MaterialTheme.colorScheme.error)
+                Text(text = successMessage, color = MaterialTheme.colorScheme.primary)
             }
         }
     }
 }
+
+@Preview(showBackground = true)
+@Composable
+fun PreviewAuthScreen() {
+    AuthScreen()
+}